@supabase/lite 0.6.1 → 0.6.2-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LIMITATIONS.md +1 -1
- package/README.md +15 -6
- package/STATUS.md +5 -3
- package/dist/cli/index.js +105 -105
- package/dist/cli/lib.js +35 -35
- package/dist/db/postgres/pglite/PgliteConnection.js +23 -23
- package/dist/index.d.ts +1 -0
- package/dist/index.js +36 -36
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {jsonStringify,Connection,RelationNotFoundError,invariant,DataLossError,PlanStepType}from'@supabase/lite';import {Kysely,PostgresQueryCompiler,PostgresIntrospector,DummyDriver,PostgresAdapter,SqliteQueryCompiler,SqliteIntrospector,SqliteAdapter,sql,OperationNodeTransformer,SchemableIdentifierNode,JoinNode,TableNode,AliasNode,ListNode,UsingNode}from'kysely';import {jsonObjectFrom as jsonObjectFrom$1,jsonArrayFrom as jsonArrayFrom$1}from'kysely/helpers/postgres';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/sqlite';import
|
|
1
|
+
import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {jsonStringify,Connection,RelationNotFoundError,invariant,DataLossError,PlanStepType}from'@supabase/lite';import {Kysely,PostgresQueryCompiler,PostgresIntrospector,DummyDriver,PostgresAdapter,SqliteQueryCompiler,SqliteIntrospector,SqliteAdapter,sql,OperationNodeTransformer,SchemableIdentifierNode,JoinNode,TableNode,AliasNode,ListNode,UsingNode}from'kysely';import {jsonObjectFrom as jsonObjectFrom$1,jsonArrayFrom as jsonArrayFrom$1}from'kysely/helpers/postgres';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/sqlite';import Qh from'bcryptjs';import {v7}from'uuid';import {createClient}from'@supabase/supabase-js';try {
|
|
2
2
|
/**
|
|
3
3
|
* Adding this to avoid warnings from node:sqlite being experimental
|
|
4
4
|
*/
|
|
@@ -9,37 +9,37 @@ import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pg
|
|
|
9
9
|
};
|
|
10
10
|
} catch {}
|
|
11
11
|
|
|
12
|
-
var Vy=Object.create;var Aa=Object.defineProperty;var Qy=Object.getOwnPropertyDescriptor;var Yy=Object.getOwnPropertyNames;var Xy=Object.getPrototypeOf,Zy=Object.prototype.hasOwnProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var of=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ir=(t,e)=>{for(var n in e)Aa(t,n,{get:e[n],enumerable:true});},eb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yy(e))!Zy.call(t,s)&&s!==n&&Aa(t,s,{get:()=>e[s],enumerable:!(r=Qy(e,s))||r.enumerable});return t};var ka=(t,e,n)=>(n=t!=null?Vy(Xy(t)):{},eb(Aa(n,"default",{value:t,enumerable:true}),t));function tb(t,e,n=void 0){let r=typeof e=="string"?uf(e):Pa(e);return bi(t,r,n)}function bi(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.\[\]\"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:bi(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function sb(t){return t===null}function fe(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null}function ib(t){return Object.prototype.toString.call(t)==="[object Object]"}function nt(t){return typeof t=="string"}function yt(t){return typeof t=="number"}function ob(t){return typeof t=="number"&&Number.isInteger(t)}function Da(t){return typeof t=="boolean"}function Lt(t){return Array.isArray(t)}function ab(t){return typeof t!="boolean"}function lb(t){return t!==void 0&&ab(t)&&"type"in t}function ve(t){return t!==void 0&&fe(t)&&Te in t}function cb(t){return ve(t)&&typeof t.toJSON()=="boolean"}function ub(t,e,n){if(!t)throw new rb(e,n)}function ff(t){return nt(t)?t.normalize("NFC"):t}function Dr(t,e){let n=typeof t;if(n!==typeof e)return false;if(Array.isArray(t)){if(!Array.isArray(e))return false;let r=t.length;if(r!==e.length)return false;for(let s=0;s<r;s++)if(!Dr(t[s],e[s]))return false;return true}if(n==="object"){if(!t||!e)return t===e;let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Dr(t[i],e[i]))return false;return true}return t===e}function fb(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function pf(t){try{return structuredClone(t)}catch{return t}}function pb(t,e,n={}){let r=e;try{r=structuredClone(e);}catch{r=JSON.parse(JSON.stringify(e));}let s={resolver:n.resolver||new ja(t),depth:n.depth||0,dropUnknown:n.dropUnknown??false};return s.resolver.hasRef(t,r)?s.resolver.resolve(t.$ref).coerce(r,{...s,depth:s.depth+1}):r}function wi(t,e,n={}){return t.map(r=>r.validate(e,yi(n)).valid?r:void 0).filter(Boolean)}function Kb(t,e,n={}){let r={keywordPath:n.keywordPath||[],instancePath:n.instancePath||[],coerce:n.coerce||false,errors:n.errors||[],shortCircuit:n.shortCircuit||false,ignoreUnsupported:n.ignoreUnsupported||false,resolver:n.resolver||t.getResolver?.()||new ja(t),depth:n.depth?n.depth+1:0,skipClone:n.skipClone||false},s;if(n?.coerce&&t.coerce){let i=t.coerce(e,{resolver:r.resolver,depth:r.depth});s=r.skipClone?i:structuredClone(i);}else s=r.skipClone?e:structuredClone(e);if(n.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(t[o])throw new Error(`${o} not implemented`)}if(r.resolver.hasRef(t,s)){let i=r.resolver.resolve(t.$ref).validate(s,{...r,errors:[]});i.valid||r.errors.push(...i.errors);}else {let i={keywordPath:r.keywordPath,instancePath:r.instancePath,coerce:r.coerce,errors:[],shortCircuit:r.shortCircuit,ignoreUnsupported:r.ignoreUnsupported,resolver:r.resolver,depth:r.depth};for(let o in t)if(o==="type"&&t.type!==void 0){if(s!==void 0){let a=$a[o];if(a){i.errors=[];let l=a(t,s,i);if(!l.valid){if(n.shortCircuit)return l;r.errors.push(...l.errors);}}}}else if(o in $a&&t[o]!==void 0){if(s===void 0)continue;let a=$a[o];if(a){i.errors=[];let l=a(t,s,i);if(!l.valid){if(n.shortCircuit)return l;r.errors.push(...l.errors);}}}}return {valid:r.errors.length===0,errors:r.errors}}function Si(t,e,n){return new class extends bt{type=t}(e,n)}function Na(t){return new Jb(t)}function lf(t,e){return Array.isArray(t)?t.map(e):t!==void 0?[e(t)]:[]}function cf(t,e,n=r=>r){return Object.fromEntries(Object.entries(t).map(([r,s])=>[r,n(e(s,r),r)]))}function jt(t){if(Da(t))return Na(t);let e=structuredClone(t);if(!fe(e))throw new nb("non-object schemas cannot be converted to a schema",e);"properties"in e&&e.properties&&(e.properties=cf(e.properties,(i,o)=>{try{return jt(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in e&&Array.isArray(e.required)&&e.required.includes(o)?i:i.optional()));let n=["patternProperties","dependentSchemas","$defs"];for(let i of n)i in e&&e[i]&&(e[i]=cf(e[i],jt));let r=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of r)i in e&&typeof e[i]<"u"&&(Lt(e[i])?e[i]=lf(e[i],jt):e[i]=jt(e[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in e){let{[i]:o}=e;e[i]=lf(o,jt);}if(lb(e))switch(e.type){case "string":return on(e);case "number":return hf(e);case "integer":return gf(e);case "boolean":return Lr(e);case "object":{let{properties:i,...o}=e;return _i(i,o)}case "array":{let{items:i,...o}=e;return yf(i,o)}}return df(e)}function rw(){return {type(t){let e=t.map(n=>Array.isArray(n)?new Set(n):new Set([n])).reduce((n,r)=>n?new Set([...n].filter(s=>r.has(s))):new Set(r));if(!e.size)throw new Error('Incompatible "type" in allOf');return e.size===1?[...e][0]:[...e]},enum(t){let e=t.map(n=>new Set(n)).reduce((n,r)=>new Set([...n].filter(s=>r.has(s))));if(!e.size)throw new Error('Incompatible "enum" in allOf');return [...e]},required(t){return [...new Set(t.flat())]},properties(t,e,n){return t.reduce((r,s)=>n(r,s),{})},patternProperties(t,e,n){return t.reduce((r,s)=>n(r,s),{})},$defs(t,e,n){return t.reduce((r,s)=>n(r,s),{})},definitions(t,e,n){return t.reduce((r,s)=>n(r,s),{})},...Object.fromEntries(tw.map(t=>[t,e=>Math.min(...e)])),...Object.fromEntries(nw.map(t=>[t,e=>Math.max(...e)]))}}function sw(t){let e={...rw(),...t.resolvers};function n(r,s){if(Array.isArray(r)&&Array.isArray(s))return [...new Set([...r,...s])];if(Ia(r)&&Ia(s)){let i={...r};for(let[o,a]of Object.entries(s))if(o in i){let l=e[o];i[o]=l?l([i[o],a],o,n):Oa(a);}else i[o]=Oa(a);return i}return Oa(s)}return n}function ow(t,e={}){let n=e.deep!==false,r=sw(e);function s(i){if(Array.isArray(i))return i.map(s);if(!Ia(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(d=>d===false))return false;let l=a.filter(d=>d!==true);if(!l.length)return true;let c=l.reduce((d,y)=>r(d,y),{}),u=iw(c);if(u!==null)return u;let f={...i};delete f.allOf;let p=r(c,n?s(f):f);return n?s(p):p}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(t)}var Pa,uf,te,$,Mn,yi,sn,nb,rb,Te,ja,db,mb,hb,gb,yb,bb,wb,Sb,_b,Eb,xb,Rb,Cb,Tb,vb,Ab,kb,$b,Ob,Pb,Nb,Ib,Db,jb,Lb,Fb,Mb,Ub,Bb,qb,Hb,af,Wb,$a,bt,jr,Jb,df,zb,Gb,_i,Un,Vb,Qb,Yb,La,on,mf,hf,gf,Xb,yf,Lr,gi,bf,Zb,ew,Ia,Oa,tw,nw,iw,aw,wf,lw,cw,uw,b,ie=N(()=>{Pa=(t=[],e="")=>"/"+[e,...t.map(n=>String(n).replace(/\./g,"/"))].filter(Boolean).join("/"),uf=t=>t.split("/").slice(1);te=(t={},e,n,r)=>({valid:false,errors:[...t.errors??[],{keywordLocation:Pa([...t.keywordPath??[],e]),instanceLocation:Pa(t.instancePath),error:typeof n=="string"?n:`Invalid value for ${e}`,data:r}]}),$=()=>({valid:true,errors:[]}),Mn=(t,e,n)=>{let r=Array.isArray(e)?e:[e],s=n?Array.isArray(n)?n:[n]:[];return {...t,keywordPath:[...t.keywordPath??[],...r],instancePath:s?[...t.instancePath??[],...s]:t.instancePath}},yi=(t={})=>({...t,errors:[]}),sn=class extends Error{constructor(t){super(`Expected ${t}`);}},nb=class extends Error{constructor(t,e){super(`${t??"Invalid raw schema"}: ${JSON.stringify(e)}`),this.schema=e;}},rb=class extends Error{constructor(t,e){super(`${t}, got: 'type "${typeof e}": ${JSON.stringify(e)}'`),this.value=e;}},Te=Symbol.for("jsonv-ts:schema");ja=class{constructor(t){this.root=t,this.cache=new Map;}cache;hasRef(t,e){return e!==void 0&&"$ref"in t&&nt(t.$ref)}resolve(t){let e=this.cache.get(t);if(!e){if(e=tb(this.root,t),!ve(e))throw new Error(`ref not found: ${t}`);if("$ref"in e&&e.$ref===t)throw new Error(`ref loop: ${t}`);this.cache.set(t,e);}return e}};db=({type:t},e,n={})=>{if(t===void 0||e===void 0)return $();let r,s={string:nt,number:yt,integer:ob,object:fe,array:Lt,boolean:Da,null:sb};if(Array.isArray(t)){for(let i of t){if(!(i in s))throw new sn(`Unknown type: ${i}`);if(s[i](e))return $()}r=`Expected one of: ${t.join(", ")}`;}else {if(!(t in s))throw new sn(`Unknown type: ${t}`);s[t](e)||(r=`Expected ${t}`);}return r?te(n,"type",r,e):$()},mb=({const:t},e,n={})=>Dr(t,e)?$():te(n,"const",`Expected const: ${t}`,e),hb=({enum:t=[]},e,n={})=>t.some(r=>Dr(r,e))?$():te(n,"enum",`Expected enum: ${JSON.stringify(t)}`,e);gb=({anyOf:t=[]},e,n={})=>wi(t,e,n).length>0?$():te(n,"anyOf","Expected at least one to match",e),yb=({oneOf:t=[]},e,n={})=>wi(t,e).length===1?$():te(n,"oneOf","Expected exactly one to match",e),bb=({allOf:t=[]},e,n={})=>wi(t,e,n).length===t.length?$():te(n,"allOf","Expected all to match",e),wb=({not:t},e,n={})=>e===void 0?$():ve(t)&&t.validate(e,n).valid?te(n,"not","Expected not to match",e):$(),Sb=({if:t,then:e,else:n},r,s={})=>{if(t&&(e||n)){if(t.validate(r,yi(s)).valid)return e?e.validate(r,yi(s)):$();if(n)return n.validate(r,yi(s))}return $()},_b=({pattern:t=""},e,n={})=>{if(!nt(e))return $();if(t instanceof RegExp){if(t.test(e))return $()}else if(new RegExp(t,"u").test(e))return $();return te(n,"pattern",`Expected string matching pattern ${t}`,e)},Eb=({minLength:t=0},e,n={})=>nt(e)?[...ff(e)].length>=t?$():te(n,"minLength",`Expected string with minimum length of ${t}`,e):$(),xb=({maxLength:t=0},e,n={})=>nt(e)?[...ff(e)].length<=t?$():te(n,"maxLength",`Expected string with maximum length of ${t}`,e):$(),Rb=({multipleOf:t=0},e,n={})=>{if(!yt(e))return $();if(!(Number.isFinite(e)&&Number.isFinite(t))||t<=0)throw new sn("number");let r=e/t,s=Number.EPSILON*Math.max(1,Math.abs(r));return Math.abs(r-Math.round(r))<=s?$():te(n,"multipleOf",`Expected number being a multiple of ${t}`,e)},Cb=({maximum:t=0},e,n={})=>!yt(e)||e<=t?$():te(n,"maximum",`Expected number less than or equal to ${t}`,e),Tb=({exclusiveMaximum:t=0},e,n={})=>!yt(e)||e<t?$():te(n,"exclusiveMaximum",`Expected number less than ${t}`,e),vb=({minimum:t=0},e,n={})=>!yt(e)||e>=t?$():te(n,"minimum",`Expected number greater than or equal to ${t}`,e),Ab=({exclusiveMinimum:t=0},e,n={})=>!yt(e)||e>t?$():te(n,"exclusiveMinimum",`Expected number greater than ${t}`,e),kb=({properties:t={}},e,n={})=>{if(!fe(e))return $();for(let[r,s]of Object.entries(e)){let i=t[r];if(!ve(i))continue;let o=i.validate(s,Mn(n,["properties",r],r));if(!o.valid)return o}return $()},$b=({properties:t={},additionalProperties:e,patternProperties:n},r,s={})=>{if(!fe(r))return $();if(!ve(e))throw new sn("additionalProperties must be a boolean or a managed schema");let i=Object.keys(t),o=fe(n)?Object.keys(r).filter(l=>Object.keys(n).some(c=>new RegExp(c).test(l))):[],a=Object.keys(r).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(cb(e)){if(e.toJSON()===true)return $();let l=a.reduce((c,u)=>(c[u]=r[u],c),{});return te(s,"additionalProperties","Additional properties are not allowed",l)}else if(ve(e))for(let l of a){let c=e.validate(r[l],Mn(s,["additionalProperties"],l));if(!c.valid)return c}}return $()},Ob=({dependentRequired:t},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");if(fe(t)){for(let[s,i]of Object.entries(t))if(r.includes(s)){for(let o of i)if(!r.includes(o))return te(n,"dependentRequired",`Expected dependent required property ${o}`,e)}}return $()},Pb=({required:t=[]},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");return t.every(s=>r.includes(s))?$():te(n,"required",`Expected object with required properties ${t.join(", ")}`,e)},Nb=({dependentSchemas:t},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");if(fe(t)){for(let[s,i]of Object.entries(t))if(r.includes(s)){let o=i.validate(e,n);if(!o.valid)return o}}return $()},Ib=({minProperties:t=0},e,n={})=>fe(e)?Object.keys(e).length>=t?$():te(n,"minProperties",`Expected object with at least ${t} properties`,e):$(),Db=({maxProperties:t=0},e,n={})=>!fe(e)||Object.keys(e).length<=t?$():te(n,"maxProperties",`Expected object with at most ${t} properties`,e),jb=({patternProperties:t={}},e,n={})=>{if(!fe(e))return $();if(!fe(t))throw new sn("patternProperties must be an object");for(let[r,s]of Object.entries(e))for(let[i,o]of Object.entries(t))if(new RegExp(i,"u").test(r)){let a=o.validate(s,Mn(n,["patternProperties"],r));if(!a.valid)return a}return $()},Lb=({propertyNames:t},e,n={})=>{if(!fe(e)||t===void 0)return $();if(!ve(t))throw new sn("propertyNames must be a managed schema");for(let r of Object.keys(e)){let s=t.validate(r,Mn(n,["propertyNames"],r));if(!s.valid)return s}return $()},Fb=({items:t,prefixItems:e=[]},n,r={})=>{if(!Lt(n)||t===void 0)return $();if(!ve(t))throw new sn("items must be a managed schema");for(let[s,i]of n.slice(e.length).entries()){let o=t.validate(i,Mn(r,["items"],String(s)));if(!o.valid)return o}return $()},Mb=({minItems:t=0},e,n={})=>!Lt(e)||e.length>=t?$():te(n,"minItems",`Expected array with at least ${t} items`,e),Ub=({maxItems:t=0},e,n={})=>!Lt(e)||e.length<=t?$():te(n,"maxItems",`Expected array with at most ${t} items`,e),Bb=({uniqueItems:t=false},e,n={})=>{if(!Lt(e)||!t)return $();for(let r=0;r<e.length;r++){let s=e[r];for(let i=0;i<e.length;i++){if(r===i)continue;let o=e[i];if(Dr(s,o))return te(n,"uniqueItems",`Duplicated items at index ${r} and ${i}`,e)}}return $()},qb=({contains:t,minContains:e,maxContains:n},r,s={})=>{if(!ve(t))throw new Error("contains must be a managed schema");if(!Lt(r))return $();let i=r.filter(o=>t.validate(o).valid).length;return i<(e??1)?te(s,e?"minContains":"contains",`Expected array to contain at least ${e??1}, but found ${i}`,r):n!==void 0&&i>n?te(s,"maxContains",`Expected array to contain at most ${n}, but found ${i}`,r):$()},Hb=({prefixItems:t=[]},e,n={})=>{if(!Lt(e))return $();for(let r=0;r<e.length;r++){let s=t[r]?.validate(e[r],Mn(n,String(r),String(r)));if(s&&s?.valid!==true)return s}return $()},af={email:t=>{if(t.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(t))return true;if(!t.includes("@")||/(^\.|^"|\.@|\.\.)/.test(t))return false;let[e,n,...r]=t.split("@");return !e||!n||r.length!==0||e.length>64||n.length>253||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?false:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:t=>t.length>(t.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(t),date:t=>{if(t.length!==10)return false;if(t[5]==="0"&&t[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(t))return true;let e=t.match(/^(\d\d\d\d)-02-29$/);if(!e)return false;let n=Number(e[1]);return n%16===0||n%4===0&&n%25!==0}return t.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(t)},time:t=>{if(t.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(t))return false;if(!/:60/.test(t))return true;let e=t.match(/([0-9.]+|[^0-9.])/g);if(!e)return false;let n=Number(e[0])*60+Number(e[2]);return e[5]==="+"?n+=1440-Number(e[6]||0)*60-Number(e[8]||0):e[5]==="-"&&(n+=Number(e[6]||0)*60+Number(e[8]||0)),n%1440===1439},"date-time":t=>{if(t.length>38)return false;let e=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,n=t[5]==="0"&&t[6]==="2";if(n&&t[8]==="3"||!e.test(t))return false;if(t[17]==="6"){let r=t.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!r)return false;let s=Number(r[0])*60+Number(r[2]);if(r[5]==="+"?s+=1440-Number(r[6]||0)*60-Number(r[8]||0):r[5]==="-"&&(s+=Number(r[6]||0)*60+Number(r[8]||0)),s%1440!==1439)return false}if(n){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(t))return true;let r=t.match(/^(\d\d\d\d)-02-29/);if(!r)return false;let s=Number(r[1]??0);return s%16===0||s%4===0&&s%25!==0}return t[8]==="3"&&t[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(t)},ipv4:t=>t.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(t),ipv6:t=>{if(t.length>45||t.length<2)return false;let e=0,n=0,r=0,s=false,i=false,o=0,a=true;for(let c=0;c<t.length;c++){let u=t.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++r>4)return false}else if(u===46){if(e>6||n>=3||r===0||i)return false;n++,r=0;}else if(u===58){if(n>0||e>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);e++,r=0,i=false;}else if(u>=97&&u<=102||u>=65&&u<=70){if(n>0||++r>4)return false;i=true;}else return false;o=u;}if(e<2||n>0&&(n!==3||r===0))return false;if(s&&t.length===2)return true;if(n>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(t))return false;let l=n>0?6:7;return s?(a||r>0)&&e<l:e===l&&a&&r>0},uri:t=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(t),"uri-reference":t=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(t),"uri-template":t=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(t),"json-pointer":t=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(t),"relative-json-pointer":t=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(t),uuid:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),duration:t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),regex:t=>{if(/[^\\]\\Z/.test(t))return false;try{return new RegExp(t,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},Wb=({format:t},e,n={})=>!nt(e)||!t?$():af[t]?af[t](e)?$():te(n,"format",`Expected format: ${t}`,e):$(),$a={type:db,const:mb,enum:hb,allOf:bb,anyOf:gb,oneOf:yb,not:wb,minLength:Eb,maxLength:xb,pattern:_b,format:Wb,minimum:vb,exclusiveMinimum:Ab,maximum:Cb,exclusiveMaximum:Tb,multipleOf:Rb,required:Pb,dependentRequired:Ob,dependentSchemas:Nb,minProperties:Ib,maxProperties:Db,propertyNames:Lb,properties:kb,patternProperties:jb,additionalProperties:$b,minItems:Mb,maxItems:Ub,uniqueItems:Bb,contains:qb,prefixItems:Hb,items:Fb,if:Sb};bt=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(t,e){let{type:n,validate:r,coerce:s,template:i,...o}=t||{};Object.assign(this,{type:n},o),this[Te]={raw:t,optional:false,overrides:e},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:uf(c.instanceLocation)}))}}};}template(t,e){let n=this,r=t;if(n.const!==void 0?r=n.const:r===void 0&&(n.default!==void 0&&(r=n.default),e?.withExtendedOptional&&n.enum!==void 0&&(r=n.enum[0])),e?.withOptional!==true&&r===void 0&&this.isOptional())return r;if(this[Te].raw?.template){let i=this[Te].raw.template(r,e);i!==void 0&&(r=i);}let s=this[Te].overrides?.template?.(r,e);return s!==void 0&&(r=s),r}validate(t,e){let n={keywordPath:e?.keywordPath||[],instancePath:e?.instancePath||[],coerce:e?.coerce||false,errors:e?.errors||[],shortCircuit:e?.shortCircuit||false,ignoreUnsupported:e?.ignoreUnsupported||false,resolver:e?.resolver||this.getResolver(),depth:e?.depth?e.depth+1:0,skipClone:e?.skipClone??true},r=this[Te].raw?.validate;if(r!==void 0){let s=r(t,n);if(!s.valid)return s}return Kb(this,t,n)}coerce(t,e){let n={...e,resolver:e?.resolver||this.getResolver(),depth:e?.depth?e.depth+1:0,dropUnknown:e?.dropUnknown??false},r=this[Te].raw?.coerce;if(r!==void 0)return r(t,n);let s=this[Te].overrides?.coerce?.(t,n)??t;return pb(this,s,n)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new ja(this)),this._resolver}children(t){return []}*walk({instancePath:t=[],keywordPath:e=[],data:n,maxDepth:r=Number.POSITIVE_INFINITY,...s}={}){let i=t.length===0&&n?pf(n):n;if(s.includeSelf!==false&&(yield new jr(this,{instancePath:t,keywordPath:e,data:i,...s})),!(t.length>=r))for(let o of this.children(s)){let a=[...t,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:r,instancePath:a,keywordPath:[...e,...o.keywordPath]});}}*[Symbol.iterator](t){for(let e of this.walk(t))yield e;}toJSON(){let{toJSON:t,"~standard":e,_resolver:n,...r}=this;return JSON.parse(JSON.stringify(r))}},jr=class{constructor(t,e={}){this.schema=t,this.instancePath=e.instancePath||[],this.keywordPath=e.keywordPath||[],this.depth=this.instancePath.length;try{if(e.data!==void 0){let n=bi(e.data,this.instancePath);t.validate(n).valid&&(this.data=n);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(t){return this.instancePath=[...this.instancePath,...t],this}appendKeywordPath(t){return this.keywordPath=[...this.keywordPath,...t],this}setData(t){return this.data=t,this}};Jb=class extends bt{constructor(t){super(),this.bool=t;}toJSON(){return this.bool}validate(t,e){return this.bool?$():te(e,"","Always fails",t)}};df=t=>Si(t?.type,t),zb=(t,e)=>Si(void 0,{...e,const:t}),Gb=class extends bt{type="object";properties;required;constructor(t,e){let n=[];for(let[s,i]of Object.entries(t||{}))ub(ve(i),"properties must be managed schemas",i),i[Te].optional||n.push(s);let r=e?.additionalProperties===false?Na(false):e?.additionalProperties;n=n.length>0?n:void 0,super({...e,additionalProperties:r,properties:t,required:n},{template:(s,i)=>{let o=structuredClone(fe(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=bi(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let f=c.template(u,i);f!==void 0&&(a[l]=f);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=pf(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[Te].optional);if(ib(a)&&(i?.dropUnknown===true||l)&&(a=fb(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,f]of Object.entries(this.properties)){let p=a[u];p!==void 0&&(a[u]=f.coerce(p,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=fe(s)?s:{},f=Object.keys(u).filter(p=>!o.includes(p));for(let p of f)a[p]=c?c.coerce(u[p],i):u[p];}return a}}),this.properties=t,this.required=n;}strict(){return this.additionalProperties=Na(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,t]of Object.entries(this.properties))t[Te].optional=true;return this.required=void 0,this}children(t){let e=[];for(let[n,r]of Object.entries(this.properties)){let s=new jr(r,t);s.appendInstancePath([n]),s.appendKeywordPath(["properties",n]),e.push(s);}return e}},_i=(t,e)=>new Gb(t,e),Un=(t,e)=>_i(t,e).strict(),Vb=(t,e)=>_i(t,e).partial(),Qb=class extends bt{type="object";additionalProperties;constructor(t,e){super({...e,additionalProperties:t},{template:(n,r)=>r?.withExtendedOptional&&(n===void 0||!fe(n))?{}:n}),this.additionalProperties=t;}children(t){let e=[],n=new jr(this.additionalProperties,t);return n.appendKeywordPath(["additionalProperties"]),e.push(n),e}},Yb=(t,e)=>new Qb(t,e),La=class extends bt{type="string";constructor(t){super(t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!nt(e))?"":e,coerce:e=>yt(e)?String(e):e});}toJSON(){let{pattern:t,"~standard":e,_resolver:n,...r}=this;return JSON.parse(JSON.stringify({...r,pattern:t instanceof RegExp?t.source:t}))}},on=t=>new La(t),mf=(t,e,n)=>Si(t,n,{template:(r,s)=>s?.withExtendedOptional&&(r===void 0||!yt(r))?n?.minimum??0:r,coerce:r=>{if(nt(r)){let s=e.parseFn(r);if(!Number.isNaN(s))return s}return r}}),hf=t=>mf("number",{parseFn:Number},t),gf=t=>mf("integer",{parseFn:Number.parseInt},t),Xb=class extends bt{constructor(t,e={}){super({...e,items:t},{template:n=>n===void 0||!Array.isArray(n)?[]:n,coerce:(n,r)=>{try{let s=typeof n=="string"?JSON.parse(n):n;if(!Array.isArray(s))return;if(ve(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,r);return s}catch{}return n}}),this.items=t,this.items=t;}type="array";children(t){let e=[];if(this.items){let n=new jr(this.items,t);n.appendKeywordPath(["items"]),e.push(n);}return e}},yf=(t,e)=>new Xb(t,e),Lr=t=>Si("boolean",t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!Da(e))?false:e,coerce:e=>{if(nt(e)&&["true","false","1","0"].includes(e))return e==="true"||e==="1";if(yt(e)){if(e===1)return true;if(e===0)return false}return e}}),gi=Symbol.for("unionType"),bf=class extends bt{[gi];constructor(t,e,n){super({...n,[e]:t},{coerce:(r,s)=>{let i=n?.coerce;if(i!==void 0)return i.bind(this)(r,s);let o=wi(t,r,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(r,s):r}}),this[gi]=e;}get schemas(){return this[this[gi]]}children(t){let e=[];for(let[n,r]of this.schemas.entries()){let s=new jr(r,t);s.appendKeywordPath([this[gi],n]),e.push(s);}return e}},Zb=(t,e)=>new bf(t,"anyOf",e),ew=(t,e)=>new bf(t,"oneOf",e);Ia=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Oa=t=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):JSON.parse(JSON.stringify(t)),tw=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],nw=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];iw=t=>t===true||t===false?t:null;aw=(t,e)=>{let n=JSON.parse(JSON.stringify({...e,allOf:t}));return jt(ow(n))},wf=class extends bt{$ref;constructor(t,e){if(!e&&!ve(t))throw new Error("Ref not set");if(ve(t)&&!t.$id)throw new Error("Ref must have an $id");let n=e??t?.$id;super({$ref:n},{coerce:(r,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!ve(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(r,s)}}),this.$ref=n;}},lw=(t,e)=>new wf(t,e),cw=t=>new wf(void 0,t),uw=t=>t(new bt({$ref:"#",coerce:(e,n)=>{let r=n?.resolver?.resolve("#");if(!ve(r))throw new Error("Ref not found: #");return r.coerce(e,n)}})),b={boolean:Lr,any:df,literal:zb,object:_i,strictObject:Un,partialObject:Vb,record:Yb,string:on,number:hf,integer:gf,array:yf,anyOf:Zb,oneOf:ew,allOf:aw,ref:lw,refId:cw,recursive:uw};});var gn,Ki=N(()=>{gn=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ae,it=N(()=>{Ki();ae=class{context;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(e,n){return new gn(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function y$(t=10,e={}){let o="abcdefghijklmnopqrstuvwxyz"+(e.uppercase?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":"")+(e.numbers?"0123456789":"")+(e.special?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),a="";for(let l=0;l<t;l++)a+=o[Math.floor(Math.random()*o.length)];return a}function b$(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!b.string({format:"email"}).validate(t).valid){if(e?.panic)throw new Error("Invalid email");return false}if(e?.domains?.length&&!e.domains.includes(t.split("@")[1])){if(e?.panic)throw new Error("Email domain not allowed");return false}return true}function w$(t,{panic:e=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof t!="string"){if(e)throw new Error("Password must be a string");return !1}if(t.length<n){if(e)throw new Error(`Password must be at least ${n} characters long`);return !1}if((t.match(/[0-9]/g)?.length??0)<r){if(e)throw new Error(`Password must contain at least ${r} numbers`);return !1}if((t.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(e)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(e)throw i;return false}}function S$(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function _$(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function E$(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function x_(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function x$(t){return x_(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function R$(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function I(t,e='"'){return `${e}${t}${e}`}function co(t,e,n){if(e instanceof RegExp)return e.test(t);if(typeof e=="string")switch(!n&&e.startsWith("/")&&(n="regex"),n){case "regex":return new RegExp(e).test(t);case "sql":return new RegExp(e.replace("%",".*").replace("_",".")).test(t);case "wildcard":return new RegExp(e.replace("*",".*")).test(t);default:return t.includes(e)}return false}function C$(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function ps(t,e,n=.33){if(e.length===0)return null;let r=Cd(t),s=[];for(let l of e){let c=R_(r,Cd(l));c>.1&&s.push([l,c]);}s.sort((l,c)=>c[1]-l[1]);let i=s.slice(0,50),o=null,a=n;for(let[l]of i){let c=Math.max(t.length,l.length),u=c===0?1:1-C_(t.toLowerCase(),l.toLowerCase())/c;u>a&&(a=u,o=l);}return o}function Cd(t,e=2){let n=new Map,r=`-${t.toLowerCase()}-`;for(let s=0;s<=r.length-e;s++){let i=r.slice(s,s+e);n.set(i,(n.get(i)||0)+1);}return n}function R_(t,e){let n=0,r=0,s=0;for(let[i,o]of t){r+=o*o;let a=e.get(i);a!==void 0&&(n+=o*a);}for(let[,i]of e)s+=i*i;return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function C_(t,e){let n=t.length,r=e.length,s=Array.from({length:r+1},(i,o)=>o);for(let i=1;i<=n;i++){let o=s[0];s[0]=i;for(let a=1;a<=r;a++){let l=s[a];s[a]=t[i-1]===e[a-1]?o:1+Math.min(o,s[a],s[a-1]),o=l;}}return s[r]}var er=N(()=>{ie();});var Xl=of((_O,Yl)=>{var wo=process||{},Gd=wo.argv||[],bo=wo.env||{},EE=!(bo.NO_COLOR||Gd.includes("--no-color"))&&(!!bo.FORCE_COLOR||Gd.includes("--color")||wo.platform==="win32"||(wo.stdout||{}).isTTY&&bo.TERM!=="dumb"||!!bo.CI),xE=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+RE(s,e,n,i)+e:t+s+e},RE=(t,e,n,r)=>{let s="",i=0;do s+=t.substring(i,r)+n,i=r+e.length,r=t.indexOf(e,i);while(~r);return s+t.substring(i)},Vd=(t=EE)=>{let e=t?xE:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Yl.exports=Vd();Yl.exports.createColors=Vd;});function EO(t){return ["string","number","boolean"].includes(typeof t)}function xO(t){return [true,false,0,1].includes(t)}function RO(t){return typeof t=="string"}var Qd=N(()=>{});function TO(...t){return e=>t.reduce((n,r)=>r(n),e)}function vO(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Yd=N(()=>{});function Xd(t){return Object.prototype.toString.call(t)==="[object Object]"}function Zd(t){return t!==null&&typeof t=="object"}function kO(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function Gt(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.[\]"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:Gt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function CE(t,e,n){let r=e;if(typeof r=="string"){let o=a=>a[0]==='"'&&a.at(-1)==='"';r=r.split(/[.[\]]+/).filter(a=>a).map(a=>Number.isNaN(Number(a))?a:Number(a)).map(a=>typeof a=="string"&&o(a)?a.slice(1,-1):a);}if(r.length===0)throw new Error("The path must have at least one entry in it");let[s,...i]=r;return i.length===0?(t[s]=n,t):(s in t||(t[s]=typeof i[0]=="number"?[]:{}),CE(t[s],i,n),t)}function $O(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function OO(t,e){let n=new Set(e),r={};for(let[s,i]of Object.entries(t))n.has(s)||(r[s]=i);return r}function ec(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!Xd(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Zd(t[r])?ec(t[r],s):t[r]=s);return t}function TE(t,e,n){for(let[r,s]of Object.entries(e)){let i=n(t[r],s,r,t,e);if(i!==void 0){t[r]=i;continue}s!==void 0&&(!Xd(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Zd(t[r])?TE(t[r],s,n):t[r]=s);}return t}function Zl(t,e){let n=s=>{if(s!==Object(s))return "primitive";if(Array.isArray(s))return "array";if(s instanceof Map)return "map";if(s!=null&&[null,Object.prototype].includes(Object.getPrototypeOf(s)))return "plainObject";if(s instanceof Function)return "function";throw new Error(`deeply comparing an instance of type ${t.constructor?.name} is not supported.`)},r=n(t);if(r!==n(e))return false;if(r==="primitive")return t===e||Number.isNaN(t)&&Number.isNaN(e);if(r==="array")return t.length===e.length&&t.every((s,i)=>Zl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&Zl(i,e.get(s)));if(r==="plainObject"){let s=new Map(Object.entries(t)),i=new Map(Object.entries(e));return s.size===i.size&&[...s].every(([o,a])=>i.has(o)&&Zl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function PO(...t){let[e,n,r]=t;return JSON.stringify(e,(s,i)=>typeof i=="bigint"?Number.parseInt(i.toString(),10):i instanceof Map?Object.fromEntries(i.entries()):i instanceof Set?Array.from(i):n&&typeof n=="function"?n(s,i):i,r)}var hs=N(()=>{});function IO(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function DO(t,e){let n=t instanceof Request?new URL(t.url).searchParams:t,r={};for(let[s,i]of n.entries())e(s,i)&&(r[s]=i);return r}var em=N(()=>{});function LO(){try{return !vE()&&global?.process?.release?.name==="node"}catch{return false}}function vE(){try{return typeof Bun<"u"}catch{return false}}function tm(t,e){if(!t)throw new Error(e)}function FO(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function MO(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function UO(t,e){try{return t()}catch{return e}}async function BO(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var qO,nm=N(()=>{qO={Map:t=>t instanceof Map?t:new Map(typeof t=="object"&&t!==null?Object.entries(t):[]),Set:t=>t instanceof Set?t:new Set(Array.isArray(t)?t:[]),Array:t=>Array.isArray(t)?t:["string","number","boolean"].includes(typeof t)?[t]:[]};});function gs(t,e={}){return t.split(`
|
|
12
|
+
var Zy=Object.create;var Aa=Object.defineProperty;var eb=Object.getOwnPropertyDescriptor;var tb=Object.getOwnPropertyNames;var nb=Object.getPrototypeOf,rb=Object.prototype.hasOwnProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var lf=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ir=(t,e)=>{for(var n in e)Aa(t,n,{get:e[n],enumerable:true});},sb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tb(e))!rb.call(t,s)&&s!==n&&Aa(t,s,{get:()=>e[s],enumerable:!(r=eb(e,s))||r.enumerable});return t};var ka=(t,e,n)=>(n=t!=null?Zy(nb(t)):{},sb(Aa(n,"default",{value:t,enumerable:true}),t));function ib(t,e,n=void 0){let r=typeof e=="string"?pf(e):Pa(e);return bi(t,r,n)}function bi(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.\[\]\"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:bi(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function lb(t){return t===null}function fe(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null}function cb(t){return Object.prototype.toString.call(t)==="[object Object]"}function nt(t){return typeof t=="string"}function bt(t){return typeof t=="number"}function ub(t){return typeof t=="number"&&Number.isInteger(t)}function Da(t){return typeof t=="boolean"}function Ft(t){return Array.isArray(t)}function fb(t){return typeof t!="boolean"}function pb(t){return t!==void 0&&fb(t)&&"type"in t}function ve(t){return t!==void 0&&fe(t)&&Te in t}function db(t){return ve(t)&&typeof t.toJSON()=="boolean"}function mb(t,e,n){if(!t)throw new ab(e,n)}function df(t){return nt(t)?t.normalize("NFC"):t}function Dr(t,e){let n=typeof t;if(n!==typeof e)return false;if(Array.isArray(t)){if(!Array.isArray(e))return false;let r=t.length;if(r!==e.length)return false;for(let s=0;s<r;s++)if(!Dr(t[s],e[s]))return false;return true}if(n==="object"){if(!t||!e)return t===e;let r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return false;for(let i of r)if(!Dr(t[i],e[i]))return false;return true}return t===e}function hb(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function mf(t){try{return structuredClone(t)}catch{return t}}function gb(t,e,n={}){let r=e;try{r=structuredClone(e);}catch{r=JSON.parse(JSON.stringify(e));}let s={resolver:n.resolver||new ja(t),depth:n.depth||0,dropUnknown:n.dropUnknown??false};return s.resolver.hasRef(t,r)?s.resolver.resolve(t.$ref).coerce(r,{...s,depth:s.depth+1}):r}function wi(t,e,n={}){return t.map(r=>r.validate(e,yi(n)).valid?r:void 0).filter(Boolean)}function Vb(t,e,n={}){let r={keywordPath:n.keywordPath||[],instancePath:n.instancePath||[],coerce:n.coerce||false,errors:n.errors||[],shortCircuit:n.shortCircuit||false,ignoreUnsupported:n.ignoreUnsupported||false,resolver:n.resolver||t.getResolver?.()||new ja(t),depth:n.depth?n.depth+1:0,skipClone:n.skipClone||false},s;if(n?.coerce&&t.coerce){let i=t.coerce(e,{resolver:r.resolver,depth:r.depth});s=r.skipClone?i:structuredClone(i);}else s=r.skipClone?e:structuredClone(e);if(n.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(t[o])throw new Error(`${o} not implemented`)}if(r.resolver.hasRef(t,s)){let i=r.resolver.resolve(t.$ref).validate(s,{...r,errors:[]});i.valid||r.errors.push(...i.errors);}else {let i={keywordPath:r.keywordPath,instancePath:r.instancePath,coerce:r.coerce,errors:[],shortCircuit:r.shortCircuit,ignoreUnsupported:r.ignoreUnsupported,resolver:r.resolver,depth:r.depth};for(let o in t)if(o==="type"&&t.type!==void 0){if(s!==void 0){let a=$a[o];if(a){i.errors=[];let l=a(t,s,i);if(!l.valid){if(n.shortCircuit)return l;r.errors.push(...l.errors);}}}}else if(o in $a&&t[o]!==void 0){if(s===void 0)continue;let a=$a[o];if(a){i.errors=[];let l=a(t,s,i);if(!l.valid){if(n.shortCircuit)return l;r.errors.push(...l.errors);}}}}return {valid:r.errors.length===0,errors:r.errors}}function Si(t,e,n){return new class extends wt{type=t}(e,n)}function Na(t){return new Qb(t)}function uf(t,e){return Array.isArray(t)?t.map(e):t!==void 0?[e(t)]:[]}function ff(t,e,n=r=>r){return Object.fromEntries(Object.entries(t).map(([r,s])=>[r,n(e(s,r),r)]))}function Lt(t){if(Da(t))return Na(t);let e=structuredClone(t);if(!fe(e))throw new ob("non-object schemas cannot be converted to a schema",e);"properties"in e&&e.properties&&(e.properties=ff(e.properties,(i,o)=>{try{return Lt(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in e&&Array.isArray(e.required)&&e.required.includes(o)?i:i.optional()));let n=["patternProperties","dependentSchemas","$defs"];for(let i of n)i in e&&e[i]&&(e[i]=ff(e[i],Lt));let r=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of r)i in e&&typeof e[i]<"u"&&(Ft(e[i])?e[i]=uf(e[i],Lt):e[i]=Lt(e[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in e){let{[i]:o}=e;e[i]=uf(o,Lt);}if(pb(e))switch(e.type){case "string":return an(e);case "number":return yf(e);case "integer":return bf(e);case "boolean":return Lr(e);case "object":{let{properties:i,...o}=e;return _i(i,o)}case "array":{let{items:i,...o}=e;return wf(i,o)}}return hf(e)}function aw(){return {type(t){let e=t.map(n=>Array.isArray(n)?new Set(n):new Set([n])).reduce((n,r)=>n?new Set([...n].filter(s=>r.has(s))):new Set(r));if(!e.size)throw new Error('Incompatible "type" in allOf');return e.size===1?[...e][0]:[...e]},enum(t){let e=t.map(n=>new Set(n)).reduce((n,r)=>new Set([...n].filter(s=>r.has(s))));if(!e.size)throw new Error('Incompatible "enum" in allOf');return [...e]},required(t){return [...new Set(t.flat())]},properties(t,e,n){return t.reduce((r,s)=>n(r,s),{})},patternProperties(t,e,n){return t.reduce((r,s)=>n(r,s),{})},$defs(t,e,n){return t.reduce((r,s)=>n(r,s),{})},definitions(t,e,n){return t.reduce((r,s)=>n(r,s),{})},...Object.fromEntries(iw.map(t=>[t,e=>Math.min(...e)])),...Object.fromEntries(ow.map(t=>[t,e=>Math.max(...e)]))}}function lw(t){let e={...aw(),...t.resolvers};function n(r,s){if(Array.isArray(r)&&Array.isArray(s))return [...new Set([...r,...s])];if(Ia(r)&&Ia(s)){let i={...r};for(let[o,a]of Object.entries(s))if(o in i){let l=e[o];i[o]=l?l([i[o],a],o,n):Oa(a);}else i[o]=Oa(a);return i}return Oa(s)}return n}function uw(t,e={}){let n=e.deep!==false,r=lw(e);function s(i){if(Array.isArray(i))return i.map(s);if(!Ia(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(d=>d===false))return false;let l=a.filter(d=>d!==true);if(!l.length)return true;let c=l.reduce((d,g)=>r(d,g),{}),u=cw(c);if(u!==null)return u;let f={...i};delete f.allOf;let p=r(c,n?s(f):f);return n?s(p):p}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(t)}var Pa,pf,te,$,Mn,yi,on,ob,ab,Te,ja,yb,bb,wb,Sb,_b,Eb,xb,Rb,Cb,Tb,vb,Ab,kb,$b,Ob,Pb,Nb,Ib,Db,jb,Lb,Fb,Mb,Ub,Bb,qb,Hb,Wb,Kb,Jb,zb,cf,Gb,$a,wt,jr,Qb,hf,Yb,Xb,_i,Un,Zb,ew,tw,La,an,gf,yf,bf,nw,wf,Lr,gi,Sf,rw,sw,Ia,Oa,iw,ow,cw,fw,_f,pw,dw,mw,b,ie=N(()=>{Pa=(t=[],e="")=>"/"+[e,...t.map(n=>String(n).replace(/\./g,"/"))].filter(Boolean).join("/"),pf=t=>t.split("/").slice(1);te=(t={},e,n,r)=>({valid:false,errors:[...t.errors??[],{keywordLocation:Pa([...t.keywordPath??[],e]),instanceLocation:Pa(t.instancePath),error:typeof n=="string"?n:`Invalid value for ${e}`,data:r}]}),$=()=>({valid:true,errors:[]}),Mn=(t,e,n)=>{let r=Array.isArray(e)?e:[e],s=n?Array.isArray(n)?n:[n]:[];return {...t,keywordPath:[...t.keywordPath??[],...r],instancePath:s?[...t.instancePath??[],...s]:t.instancePath}},yi=(t={})=>({...t,errors:[]}),on=class extends Error{constructor(t){super(`Expected ${t}`);}},ob=class extends Error{constructor(t,e){super(`${t??"Invalid raw schema"}: ${JSON.stringify(e)}`),this.schema=e;}},ab=class extends Error{constructor(t,e){super(`${t}, got: 'type "${typeof e}": ${JSON.stringify(e)}'`),this.value=e;}},Te=Symbol.for("jsonv-ts:schema");ja=class{constructor(t){this.root=t,this.cache=new Map;}cache;hasRef(t,e){return e!==void 0&&"$ref"in t&&nt(t.$ref)}resolve(t){let e=this.cache.get(t);if(!e){if(e=ib(this.root,t),!ve(e))throw new Error(`ref not found: ${t}`);if("$ref"in e&&e.$ref===t)throw new Error(`ref loop: ${t}`);this.cache.set(t,e);}return e}};yb=({type:t},e,n={})=>{if(t===void 0||e===void 0)return $();let r,s={string:nt,number:bt,integer:ub,object:fe,array:Ft,boolean:Da,null:lb};if(Array.isArray(t)){for(let i of t){if(!(i in s))throw new on(`Unknown type: ${i}`);if(s[i](e))return $()}r=`Expected one of: ${t.join(", ")}`;}else {if(!(t in s))throw new on(`Unknown type: ${t}`);s[t](e)||(r=`Expected ${t}`);}return r?te(n,"type",r,e):$()},bb=({const:t},e,n={})=>Dr(t,e)?$():te(n,"const",`Expected const: ${t}`,e),wb=({enum:t=[]},e,n={})=>t.some(r=>Dr(r,e))?$():te(n,"enum",`Expected enum: ${JSON.stringify(t)}`,e);Sb=({anyOf:t=[]},e,n={})=>wi(t,e,n).length>0?$():te(n,"anyOf","Expected at least one to match",e),_b=({oneOf:t=[]},e,n={})=>wi(t,e).length===1?$():te(n,"oneOf","Expected exactly one to match",e),Eb=({allOf:t=[]},e,n={})=>wi(t,e,n).length===t.length?$():te(n,"allOf","Expected all to match",e),xb=({not:t},e,n={})=>e===void 0?$():ve(t)&&t.validate(e,n).valid?te(n,"not","Expected not to match",e):$(),Rb=({if:t,then:e,else:n},r,s={})=>{if(t&&(e||n)){if(t.validate(r,yi(s)).valid)return e?e.validate(r,yi(s)):$();if(n)return n.validate(r,yi(s))}return $()},Cb=({pattern:t=""},e,n={})=>{if(!nt(e))return $();if(t instanceof RegExp){if(t.test(e))return $()}else if(new RegExp(t,"u").test(e))return $();return te(n,"pattern",`Expected string matching pattern ${t}`,e)},Tb=({minLength:t=0},e,n={})=>nt(e)?[...df(e)].length>=t?$():te(n,"minLength",`Expected string with minimum length of ${t}`,e):$(),vb=({maxLength:t=0},e,n={})=>nt(e)?[...df(e)].length<=t?$():te(n,"maxLength",`Expected string with maximum length of ${t}`,e):$(),Ab=({multipleOf:t=0},e,n={})=>{if(!bt(e))return $();if(!(Number.isFinite(e)&&Number.isFinite(t))||t<=0)throw new on("number");let r=e/t,s=Number.EPSILON*Math.max(1,Math.abs(r));return Math.abs(r-Math.round(r))<=s?$():te(n,"multipleOf",`Expected number being a multiple of ${t}`,e)},kb=({maximum:t=0},e,n={})=>!bt(e)||e<=t?$():te(n,"maximum",`Expected number less than or equal to ${t}`,e),$b=({exclusiveMaximum:t=0},e,n={})=>!bt(e)||e<t?$():te(n,"exclusiveMaximum",`Expected number less than ${t}`,e),Ob=({minimum:t=0},e,n={})=>!bt(e)||e>=t?$():te(n,"minimum",`Expected number greater than or equal to ${t}`,e),Pb=({exclusiveMinimum:t=0},e,n={})=>!bt(e)||e>t?$():te(n,"exclusiveMinimum",`Expected number greater than ${t}`,e),Nb=({properties:t={}},e,n={})=>{if(!fe(e))return $();for(let[r,s]of Object.entries(e)){let i=t[r];if(!ve(i))continue;let o=i.validate(s,Mn(n,["properties",r],r));if(!o.valid)return o}return $()},Ib=({properties:t={},additionalProperties:e,patternProperties:n},r,s={})=>{if(!fe(r))return $();if(!ve(e))throw new on("additionalProperties must be a boolean or a managed schema");let i=Object.keys(t),o=fe(n)?Object.keys(r).filter(l=>Object.keys(n).some(c=>new RegExp(c).test(l))):[],a=Object.keys(r).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(db(e)){if(e.toJSON()===true)return $();let l=a.reduce((c,u)=>(c[u]=r[u],c),{});return te(s,"additionalProperties","Additional properties are not allowed",l)}else if(ve(e))for(let l of a){let c=e.validate(r[l],Mn(s,["additionalProperties"],l));if(!c.valid)return c}}return $()},Db=({dependentRequired:t},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");if(fe(t)){for(let[s,i]of Object.entries(t))if(r.includes(s)){for(let o of i)if(!r.includes(o))return te(n,"dependentRequired",`Expected dependent required property ${o}`,e)}}return $()},jb=({required:t=[]},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");return t.every(s=>r.includes(s))?$():te(n,"required",`Expected object with required properties ${t.join(", ")}`,e)},Lb=({dependentSchemas:t},e,n={})=>{if(!fe(e))return $();let r=Object.keys(e).filter(s=>typeof e[s]!="function");if(fe(t)){for(let[s,i]of Object.entries(t))if(r.includes(s)){let o=i.validate(e,n);if(!o.valid)return o}}return $()},Fb=({minProperties:t=0},e,n={})=>fe(e)?Object.keys(e).length>=t?$():te(n,"minProperties",`Expected object with at least ${t} properties`,e):$(),Mb=({maxProperties:t=0},e,n={})=>!fe(e)||Object.keys(e).length<=t?$():te(n,"maxProperties",`Expected object with at most ${t} properties`,e),Ub=({patternProperties:t={}},e,n={})=>{if(!fe(e))return $();if(!fe(t))throw new on("patternProperties must be an object");for(let[r,s]of Object.entries(e))for(let[i,o]of Object.entries(t))if(new RegExp(i,"u").test(r)){let a=o.validate(s,Mn(n,["patternProperties"],r));if(!a.valid)return a}return $()},Bb=({propertyNames:t},e,n={})=>{if(!fe(e)||t===void 0)return $();if(!ve(t))throw new on("propertyNames must be a managed schema");for(let r of Object.keys(e)){let s=t.validate(r,Mn(n,["propertyNames"],r));if(!s.valid)return s}return $()},qb=({items:t,prefixItems:e=[]},n,r={})=>{if(!Ft(n)||t===void 0)return $();if(!ve(t))throw new on("items must be a managed schema");for(let[s,i]of n.slice(e.length).entries()){let o=t.validate(i,Mn(r,["items"],String(s)));if(!o.valid)return o}return $()},Hb=({minItems:t=0},e,n={})=>!Ft(e)||e.length>=t?$():te(n,"minItems",`Expected array with at least ${t} items`,e),Wb=({maxItems:t=0},e,n={})=>!Ft(e)||e.length<=t?$():te(n,"maxItems",`Expected array with at most ${t} items`,e),Kb=({uniqueItems:t=false},e,n={})=>{if(!Ft(e)||!t)return $();for(let r=0;r<e.length;r++){let s=e[r];for(let i=0;i<e.length;i++){if(r===i)continue;let o=e[i];if(Dr(s,o))return te(n,"uniqueItems",`Duplicated items at index ${r} and ${i}`,e)}}return $()},Jb=({contains:t,minContains:e,maxContains:n},r,s={})=>{if(!ve(t))throw new Error("contains must be a managed schema");if(!Ft(r))return $();let i=r.filter(o=>t.validate(o).valid).length;return i<(e??1)?te(s,e?"minContains":"contains",`Expected array to contain at least ${e??1}, but found ${i}`,r):n!==void 0&&i>n?te(s,"maxContains",`Expected array to contain at most ${n}, but found ${i}`,r):$()},zb=({prefixItems:t=[]},e,n={})=>{if(!Ft(e))return $();for(let r=0;r<e.length;r++){let s=t[r]?.validate(e[r],Mn(n,String(r),String(r)));if(s&&s?.valid!==true)return s}return $()},cf={email:t=>{if(t.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(t))return true;if(!t.includes("@")||/(^\.|^"|\.@|\.\.)/.test(t))return false;let[e,n,...r]=t.split("@");return !e||!n||r.length!==0||e.length>64||n.length>253||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?false:n.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:t=>t.length>(t.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(t),date:t=>{if(t.length!==10)return false;if(t[5]==="0"&&t[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(t))return true;let e=t.match(/^(\d\d\d\d)-02-29$/);if(!e)return false;let n=Number(e[1]);return n%16===0||n%4===0&&n%25!==0}return t.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(t)},time:t=>{if(t.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(t))return false;if(!/:60/.test(t))return true;let e=t.match(/([0-9.]+|[^0-9.])/g);if(!e)return false;let n=Number(e[0])*60+Number(e[2]);return e[5]==="+"?n+=1440-Number(e[6]||0)*60-Number(e[8]||0):e[5]==="-"&&(n+=Number(e[6]||0)*60+Number(e[8]||0)),n%1440===1439},"date-time":t=>{if(t.length>38)return false;let e=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,n=t[5]==="0"&&t[6]==="2";if(n&&t[8]==="3"||!e.test(t))return false;if(t[17]==="6"){let r=t.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!r)return false;let s=Number(r[0])*60+Number(r[2]);if(r[5]==="+"?s+=1440-Number(r[6]||0)*60-Number(r[8]||0):r[5]==="-"&&(s+=Number(r[6]||0)*60+Number(r[8]||0)),s%1440!==1439)return false}if(n){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(t))return true;let r=t.match(/^(\d\d\d\d)-02-29/);if(!r)return false;let s=Number(r[1]??0);return s%16===0||s%4===0&&s%25!==0}return t[8]==="3"&&t[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(t)},ipv4:t=>t.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(t),ipv6:t=>{if(t.length>45||t.length<2)return false;let e=0,n=0,r=0,s=false,i=false,o=0,a=true;for(let c=0;c<t.length;c++){let u=t.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++r>4)return false}else if(u===46){if(e>6||n>=3||r===0||i)return false;n++,r=0;}else if(u===58){if(n>0||e>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);e++,r=0,i=false;}else if(u>=97&&u<=102||u>=65&&u<=70){if(n>0||++r>4)return false;i=true;}else return false;o=u;}if(e<2||n>0&&(n!==3||r===0))return false;if(s&&t.length===2)return true;if(n>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(t))return false;let l=n>0?6:7;return s?(a||r>0)&&e<l:e===l&&a&&r>0},uri:t=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(t),"uri-reference":t=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(t),"uri-template":t=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(t),"json-pointer":t=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(t),"relative-json-pointer":t=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(t),uuid:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),duration:t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),regex:t=>{if(/[^\\]\\Z/.test(t))return false;try{return new RegExp(t,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},Gb=({format:t},e,n={})=>!nt(e)||!t?$():cf[t]?cf[t](e)?$():te(n,"format",`Expected format: ${t}`,e):$(),$a={type:yb,const:bb,enum:wb,allOf:Eb,anyOf:Sb,oneOf:_b,not:xb,minLength:Tb,maxLength:vb,pattern:Cb,format:Gb,minimum:Ob,exclusiveMinimum:Pb,maximum:kb,exclusiveMaximum:$b,multipleOf:Ab,required:jb,dependentRequired:Db,dependentSchemas:Lb,minProperties:Fb,maxProperties:Mb,propertyNames:Bb,properties:Nb,patternProperties:Ub,additionalProperties:Ib,minItems:Hb,maxItems:Wb,uniqueItems:Kb,contains:Jb,prefixItems:zb,items:qb,if:Rb};wt=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(t,e){let{type:n,validate:r,coerce:s,template:i,...o}=t||{};Object.assign(this,{type:n},o),this[Te]={raw:t,optional:false,overrides:e},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:pf(c.instanceLocation)}))}}};}template(t,e){let n=this,r=t;if(n.const!==void 0?r=n.const:r===void 0&&(n.default!==void 0&&(r=n.default),e?.withExtendedOptional&&n.enum!==void 0&&(r=n.enum[0])),e?.withOptional!==true&&r===void 0&&this.isOptional())return r;if(this[Te].raw?.template){let i=this[Te].raw.template(r,e);i!==void 0&&(r=i);}let s=this[Te].overrides?.template?.(r,e);return s!==void 0&&(r=s),r}validate(t,e){let n={keywordPath:e?.keywordPath||[],instancePath:e?.instancePath||[],coerce:e?.coerce||false,errors:e?.errors||[],shortCircuit:e?.shortCircuit||false,ignoreUnsupported:e?.ignoreUnsupported||false,resolver:e?.resolver||this.getResolver(),depth:e?.depth?e.depth+1:0,skipClone:e?.skipClone??true},r=this[Te].raw?.validate;if(r!==void 0){let s=r(t,n);if(!s.valid)return s}return Vb(this,t,n)}coerce(t,e){let n={...e,resolver:e?.resolver||this.getResolver(),depth:e?.depth?e.depth+1:0,dropUnknown:e?.dropUnknown??false},r=this[Te].raw?.coerce;if(r!==void 0)return r(t,n);let s=this[Te].overrides?.coerce?.(t,n)??t;return gb(this,s,n)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new ja(this)),this._resolver}children(t){return []}*walk({instancePath:t=[],keywordPath:e=[],data:n,maxDepth:r=Number.POSITIVE_INFINITY,...s}={}){let i=t.length===0&&n?mf(n):n;if(s.includeSelf!==false&&(yield new jr(this,{instancePath:t,keywordPath:e,data:i,...s})),!(t.length>=r))for(let o of this.children(s)){let a=[...t,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:r,instancePath:a,keywordPath:[...e,...o.keywordPath]});}}*[Symbol.iterator](t){for(let e of this.walk(t))yield e;}toJSON(){let{toJSON:t,"~standard":e,_resolver:n,...r}=this;return JSON.parse(JSON.stringify(r))}},jr=class{constructor(t,e={}){this.schema=t,this.instancePath=e.instancePath||[],this.keywordPath=e.keywordPath||[],this.depth=this.instancePath.length;try{if(e.data!==void 0){let n=bi(e.data,this.instancePath);t.validate(n).valid&&(this.data=n);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(t){return this.instancePath=[...this.instancePath,...t],this}appendKeywordPath(t){return this.keywordPath=[...this.keywordPath,...t],this}setData(t){return this.data=t,this}};Qb=class extends wt{constructor(t){super(),this.bool=t;}toJSON(){return this.bool}validate(t,e){return this.bool?$():te(e,"","Always fails",t)}};hf=t=>Si(t?.type,t),Yb=(t,e)=>Si(void 0,{...e,const:t}),Xb=class extends wt{type="object";properties;required;constructor(t,e){let n=[];for(let[s,i]of Object.entries(t||{}))mb(ve(i),"properties must be managed schemas",i),i[Te].optional||n.push(s);let r=e?.additionalProperties===false?Na(false):e?.additionalProperties;n=n.length>0?n:void 0,super({...e,additionalProperties:r,properties:t,required:n},{template:(s,i)=>{let o=structuredClone(fe(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=bi(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let f=c.template(u,i);f!==void 0&&(a[l]=f);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=mf(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[Te].optional);if(cb(a)&&(i?.dropUnknown===true||l)&&(a=hb(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,f]of Object.entries(this.properties)){let p=a[u];p!==void 0&&(a[u]=f.coerce(p,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=fe(s)?s:{},f=Object.keys(u).filter(p=>!o.includes(p));for(let p of f)a[p]=c?c.coerce(u[p],i):u[p];}return a}}),this.properties=t,this.required=n;}strict(){return this.additionalProperties=Na(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,t]of Object.entries(this.properties))t[Te].optional=true;return this.required=void 0,this}children(t){let e=[];for(let[n,r]of Object.entries(this.properties)){let s=new jr(r,t);s.appendInstancePath([n]),s.appendKeywordPath(["properties",n]),e.push(s);}return e}},_i=(t,e)=>new Xb(t,e),Un=(t,e)=>_i(t,e).strict(),Zb=(t,e)=>_i(t,e).partial(),ew=class extends wt{type="object";additionalProperties;constructor(t,e){super({...e,additionalProperties:t},{template:(n,r)=>r?.withExtendedOptional&&(n===void 0||!fe(n))?{}:n}),this.additionalProperties=t;}children(t){let e=[],n=new jr(this.additionalProperties,t);return n.appendKeywordPath(["additionalProperties"]),e.push(n),e}},tw=(t,e)=>new ew(t,e),La=class extends wt{type="string";constructor(t){super(t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!nt(e))?"":e,coerce:e=>bt(e)?String(e):e});}toJSON(){let{pattern:t,"~standard":e,_resolver:n,...r}=this;return JSON.parse(JSON.stringify({...r,pattern:t instanceof RegExp?t.source:t}))}},an=t=>new La(t),gf=(t,e,n)=>Si(t,n,{template:(r,s)=>s?.withExtendedOptional&&(r===void 0||!bt(r))?n?.minimum??0:r,coerce:r=>{if(nt(r)){let s=e.parseFn(r);if(!Number.isNaN(s))return s}return r}}),yf=t=>gf("number",{parseFn:Number},t),bf=t=>gf("integer",{parseFn:Number.parseInt},t),nw=class extends wt{constructor(t,e={}){super({...e,items:t},{template:n=>n===void 0||!Array.isArray(n)?[]:n,coerce:(n,r)=>{try{let s=typeof n=="string"?JSON.parse(n):n;if(!Array.isArray(s))return;if(ve(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,r);return s}catch{}return n}}),this.items=t,this.items=t;}type="array";children(t){let e=[];if(this.items){let n=new jr(this.items,t);n.appendKeywordPath(["items"]),e.push(n);}return e}},wf=(t,e)=>new nw(t,e),Lr=t=>Si("boolean",t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!Da(e))?false:e,coerce:e=>{if(nt(e)&&["true","false","1","0"].includes(e))return e==="true"||e==="1";if(bt(e)){if(e===1)return true;if(e===0)return false}return e}}),gi=Symbol.for("unionType"),Sf=class extends wt{[gi];constructor(t,e,n){super({...n,[e]:t},{coerce:(r,s)=>{let i=n?.coerce;if(i!==void 0)return i.bind(this)(r,s);let o=wi(t,r,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(r,s):r}}),this[gi]=e;}get schemas(){return this[this[gi]]}children(t){let e=[];for(let[n,r]of this.schemas.entries()){let s=new jr(r,t);s.appendKeywordPath([this[gi],n]),e.push(s);}return e}},rw=(t,e)=>new Sf(t,"anyOf",e),sw=(t,e)=>new Sf(t,"oneOf",e);Ia=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Oa=t=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):JSON.parse(JSON.stringify(t)),iw=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],ow=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];cw=t=>t===true||t===false?t:null;fw=(t,e)=>{let n=JSON.parse(JSON.stringify({...e,allOf:t}));return Lt(uw(n))},_f=class extends wt{$ref;constructor(t,e){if(!e&&!ve(t))throw new Error("Ref not set");if(ve(t)&&!t.$id)throw new Error("Ref must have an $id");let n=e??t?.$id;super({$ref:n},{coerce:(r,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!ve(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(r,s)}}),this.$ref=n;}},pw=(t,e)=>new _f(t,e),dw=t=>new _f(void 0,t),mw=t=>t(new wt({$ref:"#",coerce:(e,n)=>{let r=n?.resolver?.resolve("#");if(!ve(r))throw new Error("Ref not found: #");return r.coerce(e,n)}})),b={boolean:Lr,any:hf,literal:Yb,object:_i,strictObject:Un,partialObject:Zb,record:tw,string:an,number:yf,integer:bf,array:wf,anyOf:rw,oneOf:sw,allOf:fw,ref:pw,refId:dw,recursive:mw};});var yn,Ki=N(()=>{yn=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ae,it=N(()=>{Ki();ae=class{context;constructor(e){this.context=e;}get isShimBacked(){return false}checkConstraint(){return null}serialize(e){return e}deserialize(e){return e}validateStorage(e){return {status:"pass",message:null}}validationFail(e,n){return {status:"fail",message:e,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(e){return e==null}toColumnDDL(e){let{includeNullable:n=true}=e??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(e,n){return new yn(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function _$(t=10,e={}){let o="abcdefghijklmnopqrstuvwxyz"+(e.uppercase?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":"")+(e.numbers?"0123456789":"")+(e.special?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),a="";for(let l=0;l<t;l++)a+=o[Math.floor(Math.random()*o.length)];return a}function E$(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!b.string({format:"email"}).validate(t).valid){if(e?.panic)throw new Error("Invalid email");return false}if(e?.domains?.length&&!e.domains.includes(t.split("@")[1])){if(e?.panic)throw new Error("Email domain not allowed");return false}return true}function x$(t,{panic:e=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof t!="string"){if(e)throw new Error("Password must be a string");return !1}if(t.length<n){if(e)throw new Error(`Password must be at least ${n} characters long`);return !1}if((t.match(/[0-9]/g)?.length??0)<r){if(e)throw new Error(`Password must contain at least ${r} numbers`);return !1}if((t.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(e)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(e)throw i;return false}}function R$(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function C$(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function T$(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function v_(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function v$(t){return v_(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function A$(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function I(t,e='"'){return `${e}${t}${e}`}function co(t,e,n){if(e instanceof RegExp)return e.test(t);if(typeof e=="string")switch(!n&&e.startsWith("/")&&(n="regex"),n){case "regex":return new RegExp(e).test(t);case "sql":return new RegExp(e.replace("%",".*").replace("_",".")).test(t);case "wildcard":return new RegExp(e.replace("*",".*")).test(t);default:return t.includes(e)}return false}function k$(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function ps(t,e,n=.33){if(e.length===0)return null;let r=vd(t),s=[];for(let l of e){let c=A_(r,vd(l));c>.1&&s.push([l,c]);}s.sort((l,c)=>c[1]-l[1]);let i=s.slice(0,50),o=null,a=n;for(let[l]of i){let c=Math.max(t.length,l.length),u=c===0?1:1-k_(t.toLowerCase(),l.toLowerCase())/c;u>a&&(a=u,o=l);}return o}function vd(t,e=2){let n=new Map,r=`-${t.toLowerCase()}-`;for(let s=0;s<=r.length-e;s++){let i=r.slice(s,s+e);n.set(i,(n.get(i)||0)+1);}return n}function A_(t,e){let n=0,r=0,s=0;for(let[i,o]of t){r+=o*o;let a=e.get(i);a!==void 0&&(n+=o*a);}for(let[,i]of e)s+=i*i;return r===0||s===0?0:n/(Math.sqrt(r)*Math.sqrt(s))}function k_(t,e){let n=t.length,r=e.length,s=Array.from({length:r+1},(i,o)=>o);for(let i=1;i<=n;i++){let o=s[0];s[0]=i;for(let a=1;a<=r;a++){let l=s[a];s[a]=t[i-1]===e[a-1]?o:1+Math.min(o,s[a],s[a-1]),o=l;}}return s[r]}var er=N(()=>{ie();});var Xl=lf((CO,Yl)=>{var wo=process||{},Qd=wo.argv||[],bo=wo.env||{},TE=!(bo.NO_COLOR||Qd.includes("--no-color"))&&(!!bo.FORCE_COLOR||Qd.includes("--color")||wo.platform==="win32"||(wo.stdout||{}).isTTY&&bo.TERM!=="dumb"||!!bo.CI),vE=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+AE(s,e,n,i)+e:t+s+e},AE=(t,e,n,r)=>{let s="",i=0;do s+=t.substring(i,r)+n,i=r+e.length,r=t.indexOf(e,i);while(~r);return s+t.substring(i)},Yd=(t=TE)=>{let e=t?vE:()=>String;return {isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Yl.exports=Yd();Yl.exports.createColors=Yd;});function TO(t){return ["string","number","boolean"].includes(typeof t)}function vO(t){return [true,false,0,1].includes(t)}function AO(t){return typeof t=="string"}var Xd=N(()=>{});function $O(...t){return e=>t.reduce((n,r)=>r(n),e)}function OO(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Zd=N(()=>{});function em(t){return Object.prototype.toString.call(t)==="[object Object]"}function tm(t){return t!==null&&typeof t=="object"}function NO(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function Vt(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.[\]"]+/).filter(s=>s):e;if(r.length===0)return t;try{let[s,...i]=r;return !s||!(s in t)?n:Vt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function kE(t,e,n){let r=e;if(typeof r=="string"){let o=a=>a[0]==='"'&&a.at(-1)==='"';r=r.split(/[.[\]]+/).filter(a=>a).map(a=>Number.isNaN(Number(a))?a:Number(a)).map(a=>typeof a=="string"&&o(a)?a.slice(1,-1):a);}if(r.length===0)throw new Error("The path must have at least one entry in it");let[s,...i]=r;return i.length===0?(t[s]=n,t):(s in t||(t[s]=typeof i[0]=="number"?[]:{}),kE(t[s],i,n),t)}function IO(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function DO(t,e){let n=new Set(e),r={};for(let[s,i]of Object.entries(t))n.has(s)||(r[s]=i);return r}function ec(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!em(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:tm(t[r])?ec(t[r],s):t[r]=s);return t}function $E(t,e,n){for(let[r,s]of Object.entries(e)){let i=n(t[r],s,r,t,e);if(i!==void 0){t[r]=i;continue}s!==void 0&&(!em(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:tm(t[r])?$E(t[r],s,n):t[r]=s);}return t}function Zl(t,e){let n=s=>{if(s!==Object(s))return "primitive";if(Array.isArray(s))return "array";if(s instanceof Map)return "map";if(s!=null&&[null,Object.prototype].includes(Object.getPrototypeOf(s)))return "plainObject";if(s instanceof Function)return "function";throw new Error(`deeply comparing an instance of type ${t.constructor?.name} is not supported.`)},r=n(t);if(r!==n(e))return false;if(r==="primitive")return t===e||Number.isNaN(t)&&Number.isNaN(e);if(r==="array")return t.length===e.length&&t.every((s,i)=>Zl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&Zl(i,e.get(s)));if(r==="plainObject"){let s=new Map(Object.entries(t)),i=new Map(Object.entries(e));return s.size===i.size&&[...s].every(([o,a])=>i.has(o)&&Zl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function jO(...t){let[e,n,r]=t;return JSON.stringify(e,(s,i)=>typeof i=="bigint"?Number.parseInt(i.toString(),10):i instanceof Map?Object.fromEntries(i.entries()):i instanceof Set?Array.from(i):n&&typeof n=="function"?n(s,i):i,r)}var hs=N(()=>{});function FO(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function MO(t,e){let n=t instanceof Request?new URL(t.url).searchParams:t,r={};for(let[s,i]of n.entries())e(s,i)&&(r[s]=i);return r}var nm=N(()=>{});function BO(){try{return !OE()&&global?.process?.release?.name==="node"}catch{return false}}function OE(){try{return typeof Bun<"u"}catch{return false}}function rm(t,e){if(!t)throw new Error(e)}function qO(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function HO(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function WO(t,e){try{return t()}catch{return e}}async function KO(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var JO,sm=N(()=>{JO={Map:t=>t instanceof Map?t:new Map(typeof t=="object"&&t!==null?Object.entries(t):[]),Set:t=>t instanceof Set?t:new Set(Array.isArray(t)?t:[]),Array:t=>Array.isArray(t)?t:["string","number","boolean"].includes(typeof t)?[t]:[]};});function gs(t,e={}){return t.split(`
|
|
13
13
|
`).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!n.startsWith(e.comments??"--")).join(`
|
|
14
|
-
`)}function
|
|
15
|
-
`;)n+=t[r],r++;continue}if(f==="/"&&p==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(f==="'"){for(n+=f,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(f==='"'){for(n+=f,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(f==="$"){let d=t.indexOf("$",r+1);if(d!==-1){let
|
|
16
|
-
`;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=s,n++;}return e.trim()}function tc(t){return (t??"").trim().toLowerCase()}function nc(t){return (t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function rc(t){if(t==null)return null;let e=t.trim();for(;e.startsWith("(")&&e.endsWith(")");)e=e.slice(1,-1).trim();return (e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))&&(e=e.slice(1,-1)),e}var ys=N(()=>{});function zO(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var sm=N(()=>{});function VO(){return crypto.randomUUID()}var im=N(()=>{});var bs=N(()=>{Qd();Yd();hs();em();nm();ys();er();sm();im();});var Tn,Po=N(()=>{it();Tn=class extends ae{get sqliteType(){return "INTEGER"}};});var xs,bc=N(()=>{Po();xs=class extends Tn{constructor(e){super({...e,isSerial:true});}};});function UE(t,e){let{precision:n,scale:r}=e,s=10**r,i=10**(n-r);return Math.abs(Math.round(t*s)-t*s)<1e-4&&Math.abs(t)<i}var Rs,wc=N(()=>{it();Rs=class extends ae{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(e-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${i}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!UE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ue,Ze=N(()=>{it();ue=class extends ae{lengthConstraint;constructor(e,n){super(e),this.lengthConstraint=n;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Cs,Sc=N(()=>{it();Cs=class extends ae{get sqliteType(){return "BLOB"}};});var Ts,_c=N(()=>{it();Ts=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Tm(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var vs,Ec=N(()=>{it();vs=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Tm(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Tm(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function BE(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var As,xc=N(()=>{Ze();As=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!BE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function qE(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=e[3]===void 0?0:Number(e[3]),i=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[6]),a=i===null||o!==null&&i<=15&&o<=59;return n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var ks,Rc=N(()=>{Ze();ks=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!qE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function HE(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=Number(e[3]),i=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),u=new Date(Date.UTC(n,r-1,s)),f=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===s,p=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),d=l===null||c!==null&&l<=15&&c<=59;return f&&p&&d}var $s,Cc=N(()=>{Ze();$s=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!HE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Os,Tc=N(()=>{Ze();Os=class extends ue{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var Ps,vc=N(()=>{Ze();Ps=class extends ue{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function vm(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var or,Ac=N(()=>{it();or=class extends ae{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=vm(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=vm(e);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Am(t){return KE.test(t.toLowerCase())}var WE,KE,Ns,kc=N(()=>{Ze();WE="????????-????-????-????-????????????",KE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Ns=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${WE}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!Am(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Am(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function JE(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function zE(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function GE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function km(t){let e=JE(t);return e?zE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:GE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var Is,$c=N(()=>{Ze();Is=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!km(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!km(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var Ds,Oc=N(()=>{Ze();Ds=class extends ue{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function ct(t,e){if(e?.isArray){let r=ct(t,{...e,isArray:false});return new or(t,r)}if(e?.enumValues)return new Ps(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...t,pgTypeName:r},i=ct(s);return new or(t,i)}return QE.has(n)?new xs(t):VE.has(n)?new Tn(t):ex.has(n)?new Ts(t):tx.has(n)?new vs(t):ix.has(n)?new As(t):ox.has(n)?new ks(t):ax.has(n)?new $s(t):lx.has(n)?new Os(t):ZE.has(n)?new Cs(t):YE.has(n)?new Rs(t,e?.numericPrecision):nx.has(n)?new Ns(t):rx.has(n)?new ue(t,63):sx.has(n)?new Is(t):XE.has(n)?new ue(t,e?.lengthConstraint):new Ds(t)}var VE,QE,YE,XE,ZE,ex,tx,nx,rx,sx,ix,ox,ax,lx,Pc=N(()=>{Po();bc();wc();Ze();Sc();_c();Ec();xc();Rc();Cc();Tc();vc();Ac();kc();$c();Oc();VE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),QE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),YE=new Set(["float4","real","float8","double precision","numeric","decimal"]),XE=new Set(["text","varchar","character varying","char","character","bpchar"]),ZE=new Set(["bytea"]),ex=new Set(["bool","boolean"]),tx=new Set(["json","jsonb"]),nx=new Set(["uuid"]),rx=new Set(["name"]),sx=new Set(["inet"]),ix=new Set(["date"]),ox=new Set(["time","timetz","time without time zone","time with time zone"]),ax=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),lx=new Set(["interval"]);});function Nc(t,e="auto"){let n=t.toLowerCase(),r=No[n];if(!r)return null;switch(e){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${t}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${t}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var $m,No,Ic=N(()=>{$m="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",No={gen_random_uuid:{sqlite:()=>$m,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>$m,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var Xt,Om=N(()=>{Xt=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(e){let n={...e};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var Dc=N(()=>{it();Ki();Po();bc();wc();Ze();Sc();_c();Ec();xc();Rc();Cc();Tc();vc();Ac();kc();$c();Oc();Pc();Ic();Om();});var kh={};Ir(kh,{AwsClient:()=>Vc,AwsV4Signer:()=>Bo});async function Us(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Gc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Gc.encode(e))}async function Th(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Gc.encode(t):t)}function zc(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=vh[s>>>4&15],n+=vh[s&15];}return n}function Ah(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function lR(t,e){let{hostname:n,pathname:r}=t;if(n.endsWith(".on.aws")){let a=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return a!=null?["lambda",a[1]||""]:["",""]}if(n.endsWith(".r2.cloudflarestorage.com"))return ["s3","auto"];if(n.endsWith(".backblazeb2.com")){let a=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return a!=null?["s3",a[1]||""]:["",""]}let s=n.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),i=s&&s[1]||"",o=s&&s[2];if(o==="us-gov")o="us-gov-west-1";else if(o==="s3"||o==="s3-accelerate")o="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let a=(e.get("X-Amz-Target")||"").split(".")[0];a==="AnyScaleFrontendService"?i="application-autoscaling":a==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans");}else o==null&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return [oR[i]||i,o||""]}var Gc,oR,aR,Vc,Bo,vh,$h=N(()=>{Gc=new TextEncoder,oR={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},aR=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Vc=class{constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:s,region:i,cache:o,retries:a,initRetryMs:l}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=s,this.region=i,this.cache=o||new Map,this.retries=a??10,this.initRetryMs=l||50;}async sign(e,n){if(e instanceof Request){let{method:i,url:o,headers:a,body:l}=e;n=Object.assign({method:i,url:o,headers:a},n),n.body==null&&a.has("Content-Type")&&(n.body=l!=null&&a.has("X-Amz-Content-Sha256")?l:await e.clone().arrayBuffer()),e=o;}let r=new Bo(Object.assign({url:e.toString()},n,this,n&&n.aws)),s=Object.assign({},n,await r.sign());delete s.aws;try{return new Request(s.url.toString(),s)}catch(i){if(i instanceof TypeError)return new Request(s.url.toString(),Object.assign({duplex:"half"},s));throw i}}async fetch(e,n){for(let r=0;r<=this.retries;r++){let s=fetch(await this.sign(e,n));if(r===this.retries)return s;let i=await s;if(i.status<500&&i.status!==429)return i;await new Promise(o=>setTimeout(o,Math.random()*this.initRetryMs*Math.pow(2,r)));}throw new Error("An unknown error occurred, ensure retries is not negative")}},Bo=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:u,datetime:f,signQuery:p,appendSessionToken:d,allHeaders:y,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let h,g;(!l||!c)&&([h,g]=lR(this.url,this.headers)),this.service=l||h||"",this.region=c||g||"us-east-1",this.cache=u||new Map,this.datetime=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=p,this.appendSessionToken=d||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let S=this.signQuery?this.url.searchParams:this.headers;if(S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(w=>y||!aR.has(w)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(w=>w+":"+(w==="host"?this.url.host:(this.headers.get(w)||"").replace(/\s+/g," "))).join(`
|
|
17
|
-
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "));}catch{this.encodedPath=this.url.pathname;}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath
|
|
14
|
+
`)}function GO(t,e=true){return (e?gs(t):t).split(";").filter(Boolean)}function VO(t){let e=[],n="",r=0,s=t.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=f=>{im(f).length>0&&e.push(f.trim());},u=()=>{i=false,o=false,a=0;};for(;r<s;){let f=t[r],p=t[r+1];if(f==="-"&&p==="-"){for(;r<s&&t[r]!==`
|
|
15
|
+
`;)n+=t[r],r++;continue}if(f==="/"&&p==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(f==="'"){for(n+=f,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(f==='"'){for(n+=f,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(f==="$"){let d=t.indexOf("$",r+1);if(d!==-1){let g=t.slice(r,d+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=d+1;let h=t.indexOf(g,r);h===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,h+g.length),r=h+g.length);continue}}}if(/[A-Za-z_]/.test(f)){let d=r;for(;d<s&&/[A-Za-z0-9_]/.test(t[d]);)d++;let g=t.slice(r,d),m=g.toLowerCase();if(m==="trigger"&&l.test(im(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=g,r=d,i&&o&&a===0){let h=r;for(;h<s&&/\s/.test(t[h]);)h++;t[h]===";"&&(r=h+1),c(n),n="",u();}continue}if(f===";"){if(i&&o&&a>0){n+=f,r++;continue}c(n),n="",u(),r++;continue}n+=f,r++;}return c(n),e}function im(t){let e="",n=0,r=t.length;for(;n<r;){let s=t[n],i=t[n+1];if(s==="-"&&i==="-"){for(;n<r&&t[n]!==`
|
|
16
|
+
`;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(t[n]==="*"&&t[n+1]==="/");)n++;n+=2;continue}e+=s,n++;}return e.trim()}function tc(t){return (t??"").trim().toLowerCase()}function nc(t){return (t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function rc(t){if(t==null)return null;let e=t.trim();for(;e.startsWith("(")&&e.endsWith(")");)e=e.slice(1,-1).trim();return (e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))&&(e=e.slice(1,-1)),e}var ys=N(()=>{});function YO(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var om=N(()=>{});function ZO(){return crypto.randomUUID()}var am=N(()=>{});var bs=N(()=>{Xd();Zd();hs();nm();sm();ys();er();om();am();});var vn,Po=N(()=>{it();vn=class extends ae{get sqliteType(){return "INTEGER"}};});var xs,bc=N(()=>{Po();xs=class extends vn{constructor(e){super({...e,isSerial:true});}};});function WE(t,e){let{precision:n,scale:r}=e,s=10**r,i=10**(n-r);return Math.abs(Math.round(t*s)-t*s)<1e-4&&Math.abs(t)<i}var Rs,wc=N(()=>{it();Rs=class extends ae{numericPrecision;constructor(e,n){super(e),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:e,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(e-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${i}`}return null}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="number"||!Number.isFinite(e))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:n,scale:r}=this.numericPrecision;if(!WE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ue,Ze=N(()=>{it();ue=class extends ae{lengthConstraint;constructor(e,n){super(e),this.lengthConstraint=n;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(e).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Cs,Sc=N(()=>{it();Cs=class extends ae{get sqliteType(){return "BLOB"}};});var Ts,_c=N(()=>{it();Ts=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Am(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var vs,Ec=N(()=>{it();vs=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR json_valid(${e})`}serialize(e){if(this.isNullish(e))return e;try{return JSON.stringify(e)}catch{throw this.checkError("json_valid",e)}}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=Am(e);return n.ok?n.value:e}return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Am(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function KE(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return false;let e=new Date(`${t}T00:00:00.000Z`);return !Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===t}var As,xc=N(()=>{Ze();As=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!KE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function JE(t){let e=t.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=e[3]===void 0?0:Number(e[3]),i=e[5]===void 0?null:Number(e[5]),o=e[6]===void 0?null:Number(e[6]),a=i===null||o!==null&&i<=15&&o<=59;return n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var ks,Rc=N(()=>{Ze();ks=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!JE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function zE(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=Number(e[3]),i=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),u=new Date(Date.UTC(n,r-1,s)),f=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===s,p=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),d=l===null||c!==null&&l<=15&&c<=59;return f&&p&&d}var $s,Cc=N(()=>{Ze();$s=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!zE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Os,Tc=N(()=>{Ze();Os=class extends ue{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var Ps,vc=N(()=>{Ze();Ps=class extends ue{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function km(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var or,Ac=N(()=>{it();or=class extends ae{elementField;constructor(e,n){super(e),this.elementField=n;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR (json_valid(${e}) AND json_type(${e}) = 'array')`}serialize(e){if(this.isNullish(e))return e;if(!Array.isArray(e))throw this.checkError("array_type",e);return this.elementField?JSON.stringify(e.map(n=>this.elementField.serialize(n))):JSON.stringify(e)}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="string"){let n=km(e);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.value}return e}validateStorage(e){if(this.isNullish(e))return this.validationPass();if(typeof e!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let n=km(e);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function $m(t){return VE.test(t.toLowerCase())}var GE,VE,Ns,kc=N(()=>{Ze();GE="????????-????-????-????-????????????",VE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Ns=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${GE}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!$m(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!$m(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function QE(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function YE(t){let e=t.split(".");return e.length!==4?false:e.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function XE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function Om(t){let e=QE(t);return e?YE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:XE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var Is,$c=N(()=>{Ze();Is=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!Om(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Om(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var Ds,Oc=N(()=>{Ze();Ds=class extends ue{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function ct(t,e){if(e?.isArray){let r=ct(t,{...e,isArray:false});return new or(t,r)}if(e?.enumValues)return new Ps(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...t,pgTypeName:r},i=ct(s);return new or(t,i)}return ex.has(n)?new xs(t):ZE.has(n)?new vn(t):sx.has(n)?new Ts(t):ix.has(n)?new vs(t):cx.has(n)?new As(t):ux.has(n)?new ks(t):fx.has(n)?new $s(t):px.has(n)?new Os(t):rx.has(n)?new Cs(t):tx.has(n)?new Rs(t,e?.numericPrecision):ox.has(n)?new Ns(t):ax.has(n)?new ue(t,63):lx.has(n)?new Is(t):nx.has(n)?new ue(t,e?.lengthConstraint):new Ds(t)}var ZE,ex,tx,nx,rx,sx,ix,ox,ax,lx,cx,ux,fx,px,Pc=N(()=>{Po();bc();wc();Ze();Sc();_c();Ec();xc();Rc();Cc();Tc();vc();Ac();kc();$c();Oc();ZE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),ex=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),tx=new Set(["float4","real","float8","double precision","numeric","decimal"]),nx=new Set(["text","varchar","character varying","char","character","bpchar"]),rx=new Set(["bytea"]),sx=new Set(["bool","boolean"]),ix=new Set(["json","jsonb"]),ox=new Set(["uuid"]),ax=new Set(["name"]),lx=new Set(["inet"]),cx=new Set(["date"]),ux=new Set(["time","timetz","time without time zone","time with time zone"]),fx=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),px=new Set(["interval"]);});function Nc(t,e="auto"){let n=t.toLowerCase(),r=No[n];if(!r)return null;switch(e){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${t}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${t}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var Pm,No,Ic=N(()=>{Pm="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",No={gen_random_uuid:{sqlite:()=>Pm,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Pm,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var Zt,Nm=N(()=>{Zt=class{table;schema;fields;constructor(e,n="public",r=new Map){this.table=e,this.schema=n,this.fields=r;}get(e){return this.fields.get(e)}has(e){return this.fields.has(e)}set(e,n){this.fields.set(e,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(e){let n={};for(let[r,s]of Object.entries(e)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(e){let n={...e};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var Dc=N(()=>{it();Ki();Po();bc();wc();Ze();Sc();_c();Ec();xc();Rc();Cc();Tc();vc();Ac();kc();$c();Oc();Pc();Ic();Nm();});var Oh={};Ir(Oh,{AwsClient:()=>Vc,AwsV4Signer:()=>Bo});async function Us(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Gc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Gc.encode(e))}async function Ah(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Gc.encode(t):t)}function zc(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=kh[s>>>4&15],n+=kh[s&15];}return n}function $h(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function pR(t,e){let{hostname:n,pathname:r}=t;if(n.endsWith(".on.aws")){let a=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return a!=null?["lambda",a[1]||""]:["",""]}if(n.endsWith(".r2.cloudflarestorage.com"))return ["s3","auto"];if(n.endsWith(".backblazeb2.com")){let a=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return a!=null?["s3",a[1]||""]:["",""]}let s=n.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),i=s&&s[1]||"",o=s&&s[2];if(o==="us-gov")o="us-gov-west-1";else if(o==="s3"||o==="s3-accelerate")o="us-east-1",i="s3";else if(i==="iot")n.startsWith("iot.")?i="execute-api":n.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let a=(e.get("X-Amz-Target")||"").split(".")[0];a==="AnyScaleFrontendService"?i="application-autoscaling":a==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans");}else o==null&&i.startsWith("s3-")?(o=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):o&&/-\d$/.test(i)&&!/-\d$/.test(o)&&([i,o]=[o,i]);return [uR[i]||i,o||""]}var Gc,uR,fR,Vc,Bo,kh,Ph=N(()=>{Gc=new TextEncoder,uR={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},fR=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Vc=class{constructor({accessKeyId:e,secretAccessKey:n,sessionToken:r,service:s,region:i,cache:o,retries:a,initRetryMs:l}){if(e==null)throw new TypeError("accessKeyId is a required option");if(n==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=n,this.sessionToken=r,this.service=s,this.region=i,this.cache=o||new Map,this.retries=a??10,this.initRetryMs=l||50;}async sign(e,n){if(e instanceof Request){let{method:i,url:o,headers:a,body:l}=e;n=Object.assign({method:i,url:o,headers:a},n),n.body==null&&a.has("Content-Type")&&(n.body=l!=null&&a.has("X-Amz-Content-Sha256")?l:await e.clone().arrayBuffer()),e=o;}let r=new Bo(Object.assign({url:e.toString()},n,this,n&&n.aws)),s=Object.assign({},n,await r.sign());delete s.aws;try{return new Request(s.url.toString(),s)}catch(i){if(i instanceof TypeError)return new Request(s.url.toString(),Object.assign({duplex:"half"},s));throw i}}async fetch(e,n){for(let r=0;r<=this.retries;r++){let s=fetch(await this.sign(e,n));if(r===this.retries)return s;let i=await s;if(i.status<500&&i.status!==429)return i;await new Promise(o=>setTimeout(o,Math.random()*this.initRetryMs*Math.pow(2,r)));}throw new Error("An unknown error occurred, ensure retries is not negative")}},Bo=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:u,datetime:f,signQuery:p,appendSessionToken:d,allHeaders:g,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let h,y;(!l||!c)&&([h,y]=pR(this.url,this.headers)),this.service=l||h||"",this.region=c||y||"us-east-1",this.cache=u||new Map,this.datetime=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=p,this.appendSessionToken=d||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let S=this.signQuery?this.url.searchParams:this.headers;if(S.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&S.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(w=>g||!fR.has(w)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(w=>w+":"+(w==="host"?this.url.host:(this.headers.get(w)||"").replace(/\s+/g," "))).join(`
|
|
17
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!S.has("X-Amz-Expires")&&S.set("X-Amz-Expires","86400"),S.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),S.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),S.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "));}catch{this.encodedPath=this.url.pathname;}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=$h(this.encodedPath);let _=new Set;this.encodedSearch=[...this.url.searchParams].filter(([w])=>{if(!w)return false;if(this.service==="s3"){if(_.has(w))return false;_.add(w);}return true}).map(w=>w.map(x=>$h(encodeURIComponent(x)))).sort(([w,x],[E,R])=>w<E?-1:w>E?1:x<R?-1:x>R?1:0).map(w=>w.join("=")).join("&");}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return ["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),n=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(n);if(!r){let s=await Us("AWS4"+this.secretAccessKey,e),i=await Us(s,this.region),o=await Us(i,this.service);r=await Us(o,"aws4_request"),this.cache.set(n,r);}return zc(await Us(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,zc(await Ah(await this.canonicalString()))].join(`
|
|
18
18
|
`)}async canonicalString(){return [this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
19
19
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
20
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=zc(await
|
|
20
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=zc(await Ah(this.body||""));}return e}};kh=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var ny=lf((WU,MC)=>{MC.exports={"dev/vite/main.tsx":{file:"assets/main-DO_xnvTw.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-BITGMylP.css"]}};});var Qu,uy,fy,ca=N(()=>{Qu=(d=>(d.DISABLE_FOREIGN_KEYS="disable_foreign_keys",d.ENABLE_FOREIGN_KEYS="enable_foreign_keys",d.BEGIN_TRANSACTION="begin_transaction",d.COMMIT_TRANSACTION="commit_transaction",d.CREATE_TABLE="create_table",d.ADD_COLUMN="add_column",d.DROP_COLUMN="drop_column",d.ADD_INDEX="add_index",d.DROP_INDEX="drop_index",d.DROP_TABLE="drop_table",d.RENAME_TABLE="rename_table",d.COPY_DATA="copy_data",d.CREATE_TRIGGER="create_trigger",d))(Qu||{}),uy=class extends Error{constructor(n){super(`Migration would cause data loss:
|
|
21
21
|
${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
|
|
22
|
-
`)}`);this.warnings=n;this.name="DataLossError";}},
|
|
23
|
-
SQL: ${r}`);this.stepIndex=n;this.sql=r;this.cause=s;this.name="MigrationError";}};});var
|
|
24
|
-
SELECT ${
|
|
25
|
-
FROM ${I(e)};`,description:`Copy data from ${I(e)} to ${I(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${I(e)};`,description:`Drop old table ${I(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${I(l)} RENAME TO ${I(e)};`,description:`Rename ${I(l)} to ${I(e)}`,type:"rename_table"});let d=r.indexes.filter(g=>g.table===e);for(let g of d){let S=g.unique?"UNIQUE ":"",_=g.columns.map(w=>I(w)).join(", ");i.push({sql:`CREATE ${S}INDEX ${I(g.name)} ON ${I(e)} (${_});`,description:`Recreate index ${I(g.name)} on ${I(e)}`,type:"add_index"});}let y=r.triggers?.filter(g=>g.table===e)??[];for(let g of y)i.push({sql:`${g.sql};`,description:`Recreate trigger ${I(g.name)} on ${I(e)}`,type:"create_trigger"});let m=s.columns.filter(g=>g.table===e&&g.type==="removed");for(let g of m)o.push({table:e,reason:`column "${g.name}" will be dropped`});let h=s.columns.filter(g=>g.table===e&&g.type==="modified");for(let g of h)g.changes?.type&&o.push({table:e,reason:`column "${g.name}" type changes from ${g.changes.type.from} to ${g.changes.type.to}`}),g.changes?.nullable&&!g.changes.nullable.to&&o.push({table:e,reason:`column "${g.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(f=>f.table===e),i=s.filter(f=>f.type==="added"),o=s.filter(f=>f.type==="removed"),a=s.filter(f=>f.type==="modified"),l=n.foreign_keys.some(f=>f.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(f=>f.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(f=>{let p=f.column;return this.hasNonConstantDefault(p.default_value)?false:p.nullable||p.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return fT.includes(n)}columnDef(e){let n=e.column,r=`${I(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function kr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var Ty=N(()=>{});function pi(t){if("String"in t)return t.String.sval}function Nn(t){return t.map(pi).filter(e=>e!=null)}function In(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function ya(t){return QuoteUtils.quoteIdentifier(t)}function $r(t){return Object.keys(t)[0]}function vy(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var Dn=N(()=>{});function ky(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=ET[e];if(!n)throw new jn(`Unsupported PostgreSQL type: "${t}"`);return n}function ba(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function wa(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Sa(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var jn,F,ET,Ay,xT,_a,Or=N(()=>{Dn();jn=class extends Error{},F=class extends jn{constructor(n,r){super(r??`Unsupported node type: ${$r(n)}`);this.node=n;}},ET={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},Ay=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];xT={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},_a=new Map(Object.entries(xT));});var Ea,$y=N(()=>{Or();Dn();Ea=class{constructor(e){this.ast=e;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(e=this.ast,n=[],r={}){if(!e||typeof e!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(e)){for(let o=0;o<e.length;o++)yield*this.walk(e[o],n,r);return}let i=Object.keys(e);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:e,path:n},yield*this.walk(e[o],[...n,o],r);}else for(let[o,a]of Object.entries(e))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:e}of this.result){let n=$r(e),r=_a.get(n);if(r&&r.react==="error")return true}}hasFuncCall(){for(let{node:e}of this.result)if("FuncCall"in e)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"FuncCall"in e).map(e=>e.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(e=>e.funcname?.map(n=>n.String?.sval||n.String?.str))}hasSqlValueFunction(){for(let{node:e}of this.result)if("SQLValueFunction"in e)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"SQLValueFunction"in e).map(e=>e.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(e=>e.op)}hasUnsafeStar(){let e=this.result.filter(({node:n})=>"A_Star"in n);if(e.length===0)return false;for(let{path:n}of e)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(e=>e.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(e=>e.columns?.map(n=>n.type))))}}};});var RT,CT,TT,vT,Pr,xa,Oy=N(()=>{Or();RT=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],CT=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,TT=/^RETURN\s+(NEW|OLD)$/i,vT=/^(INSERT|UPDATE|DELETE)\b/i,Pr=class extends jn{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},xa=class{parse(e){let n=this.extractBlock(e),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(TT);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(CT);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(vT.test(a)){s.push({type:"dml",sql:a});continue}throw new Pr(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new jn("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(e){let n=e.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new Pr('"DECLARE" is not translatable to SQLite',e);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new Pr("Expected BEGIN ... END block in trigger function body",e);return n.slice(s+5,i).trim()}splitStatements(e){let n=[],r="",s=0,i=false,o="";for(let l=0;l<e.length;l++){let c=e[l];if(i){r+=c,c===o&&(l+1<e.length&&e[l+1]===o?r+=e[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(e){let n=e.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&RT.includes(n))throw new Pr(`"${n}" is not translatable to SQLite`,e)}};});function PT(t){let e=t?.GrantStmt??t;return e?.is_grant!==true?false:e.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?e.objtype==="OBJECT_TABLE"||e.objtype==="OBJECT_SEQUENCE":e.targtype==="ACL_TARGET_OBJECT"&&OT.has(e.objtype)}var OT,Ra,Py=N(()=>{Or();Dn();Dn();$y();bs();Oy();ca();ef();tf();er();Pc();Ic();OT=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);Ra=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new xa;introspection;functionResolution;serialColumns;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new Ea(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=$r(e);if(r==="GrantStmt"&&PT(e))return "";let s=_a.get(r);if(s){if(s.react==="error")throw new F({[r]:e},`Unsupported node type: ${r}`);return s.react==="warn"&&this.warnings.push({type:r,node:e}),""}return super.visit(e,n)}deparse(e,n){if(e==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof e=="number"||e instanceof Number?e.toString():this.visit(e,n)}RawStmt(e,n){if(!e.stmt||e.stmt.CommentStmt)return "";let r=this.deparse(e.stmt,n);return !r||r.length===0?"":e.stmt_len?r+";":r}RangeVar(e,n){this.ensureRelation(e);let r=this.effectiveSchema(e.schemaname),s=e.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=e.alias?" "+this.Alias(e.alias,n):"";return i+o}getRelationName(e){this.ensureRelation(e);let n=this.effectiveSchema(e.schemaname),r=e.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}quoteBareIfNeeded(e){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}effectiveSchema(e){if(e){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return e;if(e!=="public")return e}}ensureRelation(e){let n=this.config.forceDefaultSchema;n&&(!e||typeof e!="object"||n.length===0||e.schemaname||(e.schemaname=n));}CreateStmt(e,n){if(e.inhRelations&&e.inhRelations.length>0)throw new F({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new F({CreateStmt:e},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(e.options&&e.options.length>0&&(e.options=void 0),!e.tableElts||e.tableElts.length===0)throw new F({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");return e.accessMethod&&(e.accessMethod=void 0),super.CreateStmt(e,n)+" STRICT"}TableLikeClause(e,n){throw new F({TableLikeClause:e},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(e,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>co(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new F({DefElem:e},`DefElem "${e.defname}" (${s}) not supported`)}TypeName(e,n){if(!e.names)return "";let r=e.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return e.arrayBounds&&e.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":ky(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,u=false;if(e.typeName){let f=e.typeName.names?.map(y=>y.String?.sval||y.String?.str).filter(Boolean);c=f&&(f.length===2&&f[0]==="pg_catalog"?f[1]:f[0]),i=!!(c&&ba(c))||this.serialColumns.has(e),u=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let p=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],d=y=>p[y]?.A_Const?.ival?.ival??p[y]?.A_Const?.val?.ival?.ival;if(c&&wa(c)&&p.length>0){let y=d(0);typeof y=="number"&&y>0&&(a={maxLen:y});}if(c&&Sa(c)&&p.length>=2){let y=d(0),m=d(1);typeof y=="number"&&typeof m=="number"&&y>0&&m>=0&&(l={precision:y,scale:m});}if(e.constraints){let y=Array.isArray(e.constraints)?e.constraints:[];o=y.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),y.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let f=Array.isArray(e.constraints)?e.constraints:[],p=f.map(y=>this.visit(y,n));r.push(...p.filter(Boolean));let d=f.some(y=>y.Constraint?.contype==="CONSTR_CHECK");i&&o&&!d?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let f={isArray:u};a&&(f.lengthConstraint=a.maxLen),l&&(f.numericPrecision=l);let p=this.enums.get(c.toLowerCase());p&&(f.enumValues=p);let m=ct({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},f).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.visit(e.raw_expr,n);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",ya(e.conname)),s.push("CHECK");let i=this.visit(e.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return e.keys&&e.keys.length>0?`PRIMARY KEY (${In(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${In(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(e,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&e.raw_expr)return `GENERATED ALWAYS AS (${this.visit(e.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new F({Constraint:e},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(e,n){let s=(e.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&e.args&&e.args.length>=2){let c=e.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(e.args[1],n)})`}let a=(e.args??[]).map(c=>this.visit(c,n));if(e.agg_star)return `${i}(*)`;if(e.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Nc(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=No[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${a.join(", ")})`}}}throw new F({FuncCall:e},`Function call "${i}" not supported`)}SQLValueFunction(e,n){switch(e.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new F({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new F({ResTarget:e},"Indirections are not supported in SQLite");let r=[];return n.update&&e.name?(r.push(this.quoteIfNeeded(e.name)),r.push("="),e.val&&r.push(this.deparse(e.val,n))):n.insertColumns&&e.name?r.push(this.quoteIfNeeded(e.name)):(e.val&&r.push(this.deparse(e.val,n)),e.name&&r.push(this.Alias({aliasname:e.name},n))),r.join(" ")}A_Expr(e,n){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new F({A_Expr:e},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(e.name&&e.name.length>0){if(e.name.length>1)throw new F({A_Expr:e},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=e.name[0]?.String?.sval||e.name[0]?.String?.str;if(r){if(!e.lexpr||!e.rexpr)throw new F({A_Expr:e},"A_Expr missing left or right expression");if(!Ay.includes(r.toUpperCase()))throw new F({A_Expr:e},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(e,n)}IndexStmt(e,n){let r=["CREATE"];e.unique&&r.push("UNIQUE"),r.push("INDEX"),e.if_not_exists&&r.push("IF NOT EXISTS"),e.idxname&&r.push(ya(e.idxname)),r.push("ON"),e.relation&&r.push(this.RangeVar(e.relation,n));let s=(e.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(e,n){let r=[];return e.name?r.push(ya(e.name)):e.expr&&r.push(`(${this.visit(e.expr,n)})`),e.ordering==="SORTBY_ASC"&&r.push("ASC"),e.ordering==="SORTBY_DESC"&&r.push("DESC"),e.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),e.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}TypeCast(e,n){if(!e.arg||!e.typeName)return super.TypeCast(e,n);if([...this.helper.walk(e)].filter(({node:o})=>"A_Star"in o).length>0)throw new F({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(f=>f.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let f=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(f).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,n)}let s=this.visit(e.arg,n),i=this.TypeName(e.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(e,n){let r=In(e.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(e){let n=[];for(let r of e)if("A_ArrayExpr"in r){let s=In(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(e,n){if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("Not a PG array literal");let r=e.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(e,n){return super.A_Expr(e,n)}AlterTableStmt(e,n){let r=e.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=r.filter(u=>"AlterTableCmd"in u&&!s.includes(u.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new F({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let u of i){let f=u.AlterTableCmd.subtype;if(o.includes(f)){let p={...e,cmds:[u]};l.push(super.AlterTableStmt(p,n));}else if(a.includes(f))c.push(u.AlterTableCmd);else throw new F({AlterTableStmt:e},`AlterTableCmd with subtype ${f} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(e.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
22
|
+
`)}`);this.warnings=n;this.name="DataLossError";}},fy=class extends Error{constructor(n,r,s){super(`Migration failed at step ${n}: ${s.message}
|
|
23
|
+
SQL: ${r}`);this.stepIndex=n;this.sql=r;this.cause=s;this.name="MigrationError";}};});var gt,fa=N(()=>{gt=class t{constructor(e){this.data=e;}appliesTo(e){return this.data.command==="ALL"||this.data.command===e}appliesToRole(e){return this.data.roles.length===0||this.data.roles.includes(e)}toJSON(){return this.data}static fromJSON(e){return new t(e)}};});var vr,ef=N(()=>{ys();vr=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}`}diff(e,n){let r=[],s=[],i=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of e.tables){let h=n.tables.find(_=>_.name===m.name);if(!h)continue;let y=nc(m.sql),S=nc(h.sql);y!==S&&r.push({type:"modified",name:m.name,sql:h.sql});}let c=e.tables.filter(m=>l.has(m.name));for(let m of c){let h=e.columns.filter(w=>w.table===m.name),y=n.columns.filter(w=>w.table===m.name),S=new Map(h.map(w=>[w.name,w])),_=new Map(y.map(w=>[w.name,w]));for(let[w,x]of _)S.has(w)||s.push({type:"added",table:m.name,name:w,column:x});for(let[w]of S)_.has(w)||s.push({type:"removed",table:m.name,name:w});for(let[w,x]of S){let E=_.get(w);if(!E)continue;let R={};tc(x.type)!==tc(E.type)&&(R.type={from:x.type,to:E.type}),x.nullable!==E.nullable&&(R.nullable={from:x.nullable,to:E.nullable}),rc(x.default_value)!==rc(E.default_value)&&(R.default_value={from:x.default_value,to:E.default_value}),Object.keys(R).length>0&&s.push({type:"modified",table:m.name,name:w,changes:R});}}let u=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),f=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,h]of f)u.has(m)||i.push({type:"added",...h});for(let[m,h]of u)f.has(m)||i.push({type:"removed",...h});let p=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),d=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,h]of d)p.has(m)||o.push({type:"added",...h});for(let[m,h]of p)d.has(m)||o.push({type:"removed",...h});let g=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:g}}};});var hT,Ar,tf=N(()=>{ca();er();hT=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],Ar=class{plan(e,n,r,s){if(!e.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let f of e.tables.filter(p=>p.type==="added")){i.push({sql:`${f.sql};`,description:`CREATE TABLE ${I(f.name)}`,type:"create_table"});let p=r.indexes.filter(d=>d.table===f.name);for(let d of p){let g=d.unique?"UNIQUE ":"",m=d.columns.map(h=>I(h)).join(", ");i.push({sql:`CREATE ${g}INDEX ${I(d.name)} ON ${I(f.name)} (${m});`,description:`Create index ${I(d.name)} on ${I(f.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(f=>f.name)),l=new Set(r.tables.map(f=>f.name)),c=new Set(e.tables.filter(f=>f.type==="modified").map(f=>f.name)),u=[...a].filter(f=>l.has(f));for(let f of u){if(!(c.has(f)||e.columns.some(m=>m.table===f)||e.indexes.some(m=>m.table===f)||e.foreign_keys.some(m=>m.table===f)))continue;let{canAlter:d,addedCols:g}=this.canSimpleAlter(f,e,r);if(d){for(let y of g)i.push({sql:`ALTER TABLE ${I(f)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${I(y.name)} to ${I(f)}`,type:"add_column"});let m=e.indexes.filter(y=>y.table===f&&y.type==="added"),h=e.indexes.filter(y=>y.table===f&&y.type==="removed");for(let y of h)i.push({sql:`DROP INDEX IF EXISTS ${I(y.name)};`,description:`Drop index ${I(y.name)}`,type:"drop_index"});for(let y of m){let S=y.unique?"UNIQUE ":"",_=y.columns.map(w=>I(w)).join(", ");i.push({sql:`CREATE ${S}INDEX ${I(y.name)} ON ${I(f)} (${_});`,description:`Create index ${I(y.name)} on ${I(f)}`,type:"add_index"});}}else {let m=this.rebuildTable(f,n,r,e);i.push(...m.steps),o.push(...m.warnings);}}for(let f of e.tables.filter(p=>p.type==="removed"))i.push({sql:`DROP TABLE ${I(f.name)};`,description:`Drop table ${I(f.name)}`,type:"drop_table"}),o.push({table:f.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(e,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===e);if(!a)return {steps:i,warnings:o};let l=`_${e}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${I(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${I(l)}`,type:"create_table"});let u=n.columns.filter(y=>y.table===e).map(y=>y.name),f=r.columns.filter(y=>y.table===e).map(y=>y.name),p=u.filter(y=>f.includes(y));if(p.length>0){let y=p.map(S=>I(S)).join(", ");i.push({sql:`INSERT INTO ${I(l)} (${y})
|
|
24
|
+
SELECT ${y}
|
|
25
|
+
FROM ${I(e)};`,description:`Copy data from ${I(e)} to ${I(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${I(e)};`,description:`Drop old table ${I(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${I(l)} RENAME TO ${I(e)};`,description:`Rename ${I(l)} to ${I(e)}`,type:"rename_table"});let d=r.indexes.filter(y=>y.table===e);for(let y of d){let S=y.unique?"UNIQUE ":"",_=y.columns.map(w=>I(w)).join(", ");i.push({sql:`CREATE ${S}INDEX ${I(y.name)} ON ${I(e)} (${_});`,description:`Recreate index ${I(y.name)} on ${I(e)}`,type:"add_index"});}let g=r.triggers?.filter(y=>y.table===e)??[];for(let y of g)i.push({sql:`${y.sql};`,description:`Recreate trigger ${I(y.name)} on ${I(e)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===e&&y.type==="removed");for(let y of m)o.push({table:e,reason:`column "${y.name}" will be dropped`});let h=s.columns.filter(y=>y.table===e&&y.type==="modified");for(let y of h)y.changes?.type&&o.push({table:e,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:e,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(f=>f.table===e),i=s.filter(f=>f.type==="added"),o=s.filter(f=>f.type==="removed"),a=s.filter(f=>f.type==="modified"),l=n.foreign_keys.some(f=>f.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(f=>f.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(f=>{let p=f.column;return this.hasNonConstantDefault(p.default_value)?false:p.nullable||p.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return hT.includes(n)}columnDef(e){let n=e.column,r=`${I(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function kr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var Ay=N(()=>{});function pi(t){if("String"in t)return t.String.sval}function sn(t){return t.map(pi).filter(e=>e!=null)}function In(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function ya(t){return QuoteUtils.quoteIdentifier(t)}function $r(t){return Object.keys(t)[0]}function ky(t){if("A_Const"in t){if(t.A_Const.ival)return t.A_Const.ival.ival;if(t.A_Const.fval)return t.A_Const.fval.fval;if(t.A_Const.sval)return t.A_Const.sval.sval;if(t.A_Const.boolval)return t.A_Const.boolval.boolval;if(t.A_Const.isnull)return null}}var Dn=N(()=>{});function Oy(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=TT[e];if(!n)throw new jn(`Unsupported PostgreSQL type: "${t}"`);return n}function ba(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function wa(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Sa(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var jn,F,TT,$y,vT,_a,Or=N(()=>{Dn();jn=class extends Error{},F=class extends jn{constructor(n,r){super(r??`Unsupported node type: ${$r(n)}`);this.node=n;}},TT={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},$y=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];vT={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},_a=new Map(Object.entries(vT));});var Ea,Py=N(()=>{Or();Dn();Ea=class{constructor(e){this.ast=e;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(e=this.ast,n=[],r={}){if(!e||typeof e!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(e)){for(let o=0;o<e.length;o++)yield*this.walk(e[o],n,r);return}let i=Object.keys(e);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:e,path:n},yield*this.walk(e[o],[...n,o],r);}else for(let[o,a]of Object.entries(e))if(a&&typeof a=="object"){let l=s.includes(o)?[...n,o]:n;yield*this.walk(a,l,r);}}containsUnsupportedNode(){for(let{node:e}of this.result){let n=$r(e),r=_a.get(n);if(r&&r.react==="error")return true}}hasFuncCall(){for(let{node:e}of this.result)if("FuncCall"in e)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"FuncCall"in e).map(e=>e.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(e=>e.funcname?.map(n=>n.String?.sval||n.String?.str))}hasSqlValueFunction(){for(let{node:e}of this.result)if("SQLValueFunction"in e)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:e})=>e).filter(e=>"SQLValueFunction"in e).map(e=>e.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(e=>e.op)}hasUnsafeStar(){let e=this.result.filter(({node:n})=>"A_Star"in n);if(e.length===0)return false;for(let{path:n}of e)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(e=>e.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(e=>e.columns?.map(n=>n.type))))}}};});var AT,kT,$T,OT,Pr,xa,Ny=N(()=>{Or();AT=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],kT=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,$T=/^RETURN\s+(NEW|OLD)$/i,OT=/^(INSERT|UPDATE|DELETE)\b/i,Pr=class extends jn{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},xa=class{parse(e){let n=this.extractBlock(e),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match($T);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(kT);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(OT.test(a)){s.push({type:"dml",sql:a});continue}throw new Pr(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new jn("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(e){let n=e.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new Pr('"DECLARE" is not translatable to SQLite',e);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new Pr("Expected BEGIN ... END block in trigger function body",e);return n.slice(s+5,i).trim()}splitStatements(e){let n=[],r="",s=0,i=false,o="";for(let l=0;l<e.length;l++){let c=e[l];if(i){r+=c,c===o&&(l+1<e.length&&e[l+1]===o?r+=e[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,r+=c;continue}if(c==="("){s++,r+=c;continue}if(c===")"){s--,r+=c;continue}if(c===";"&&s===0){n.push(r.trim()),r="";continue}r+=c;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(e){let n=e.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&AT.includes(n))throw new Pr(`"${n}" is not translatable to SQLite`,e)}};});function jT(t){let e=t?.GrantStmt??t;return e?.is_grant!==true?false:e.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?e.objtype==="OBJECT_TABLE"||e.objtype==="OBJECT_SEQUENCE":e.targtype==="ACL_TARGET_OBJECT"&&DT.has(e.objtype)}var DT,Ra,Iy=N(()=>{Or();Dn();Dn();Py();bs();Ny();ca();ef();tf();er();Pc();Ic();DT=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);Ra=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new xa;introspection;functionResolution;serialColumns;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new Ea(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=$r(e);if(r==="GrantStmt"&&jT(e))return "";let s=_a.get(r);if(s){if(s.react==="error")throw new F({[r]:e},`Unsupported node type: ${r}`);return s.react==="warn"&&this.warnings.push({type:r,node:e}),""}return super.visit(e,n)}deparse(e,n){if(e==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof e=="number"||e instanceof Number?e.toString():this.visit(e,n)}RawStmt(e,n){if(!e.stmt||e.stmt.CommentStmt)return "";let r=this.deparse(e.stmt,n);return !r||r.length===0?"":e.stmt_len?r+";":r}RangeVar(e,n){this.ensureRelation(e);let r=this.effectiveSchema(e.schemaname),s=e.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=e.alias?" "+this.Alias(e.alias,n):"";return i+o}getRelationName(e){this.ensureRelation(e);let n=this.effectiveSchema(e.schemaname),r=e.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}quoteBareIfNeeded(e){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}effectiveSchema(e){if(e){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return e;if(e!=="public")return e}}ensureRelation(e){let n=this.config.forceDefaultSchema;n&&(!e||typeof e!="object"||n.length===0||e.schemaname||(e.schemaname=n));}CreateStmt(e,n){if(e.inhRelations&&e.inhRelations.length>0)throw new F({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new F({CreateStmt:e},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(e.options&&e.options.length>0&&(e.options=void 0),!e.tableElts||e.tableElts.length===0)throw new F({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");return e.accessMethod&&(e.accessMethod=void 0),super.CreateStmt(e,n)+" STRICT"}TableLikeClause(e,n){throw new F({TableLikeClause:e},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(e,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>co(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new F({DefElem:e},`DefElem "${e.defname}" (${s}) not supported`)}TypeName(e,n){if(!e.names)return "";let r=e.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return e.arrayBounds&&e.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":Oy(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,u=false;if(e.typeName){let f=e.typeName.names?.map(g=>g.String?.sval||g.String?.str).filter(Boolean);c=f&&(f.length===2&&f[0]==="pg_catalog"?f[1]:f[0]),i=!!(c&&ba(c))||this.serialColumns.has(e),u=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let p=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],d=g=>p[g]?.A_Const?.ival?.ival??p[g]?.A_Const?.val?.ival?.ival;if(c&&wa(c)&&p.length>0){let g=d(0);typeof g=="number"&&g>0&&(a={maxLen:g});}if(c&&Sa(c)&&p.length>=2){let g=d(0),m=d(1);typeof g=="number"&&typeof m=="number"&&g>0&&m>=0&&(l={precision:g,scale:m});}if(e.constraints){let g=Array.isArray(e.constraints)?e.constraints:[];o=g.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),g.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let f=Array.isArray(e.constraints)?e.constraints:[],p=f.map(g=>this.visit(g,n));r.push(...p.filter(Boolean));let d=f.some(g=>g.Constraint?.contype==="CONSTR_CHECK");i&&o&&!d?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let f={isArray:u};a&&(f.lengthConstraint=a.maxLen),l&&(f.numericPrecision=l);let p=this.enums.get(c.toLowerCase());p&&(f.enumValues=p);let m=ct({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},f).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.visit(e.raw_expr,n);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",ya(e.conname)),s.push("CHECK");let i=this.visit(e.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return e.keys&&e.keys.length>0?`PRIMARY KEY (${In(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${In(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(e,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&e.raw_expr)return `GENERATED ALWAYS AS (${this.visit(e.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new F({Constraint:e},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(e,n){let s=(e.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&e.args&&e.args.length>=2){let c=e.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(e.args[1],n)})`}let a=(e.args??[]).map(c=>this.visit(c,n));if(e.agg_star)return `${i}(*)`;if(e.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Nc(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=No[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${a.join(", ")})`}}}throw new F({FuncCall:e},`Function call "${i}" not supported`)}SQLValueFunction(e,n){switch(e.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new F({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new F({ResTarget:e},"Indirections are not supported in SQLite");let r=[];return n.update&&e.name?(r.push(this.quoteIfNeeded(e.name)),r.push("="),e.val&&r.push(this.deparse(e.val,n))):n.insertColumns&&e.name?r.push(this.quoteIfNeeded(e.name)):(e.val&&r.push(this.deparse(e.val,n)),e.name&&r.push(this.Alias({aliasname:e.name},n))),r.join(" ")}A_Expr(e,n){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new F({A_Expr:e},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(e.name&&e.name.length>0){if(e.name.length>1)throw new F({A_Expr:e},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=e.name[0]?.String?.sval||e.name[0]?.String?.str;if(r){if(!e.lexpr||!e.rexpr)throw new F({A_Expr:e},"A_Expr missing left or right expression");if(!$y.includes(r.toUpperCase()))throw new F({A_Expr:e},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(e.lexpr,n),i=this.visit(e.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(e,n)}IndexStmt(e,n){let r=["CREATE"];e.unique&&r.push("UNIQUE"),r.push("INDEX"),e.if_not_exists&&r.push("IF NOT EXISTS"),e.idxname&&r.push(ya(e.idxname)),r.push("ON"),e.relation&&r.push(this.RangeVar(e.relation,n));let s=(e.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(e,n){let r=[];return e.name?r.push(ya(e.name)):e.expr&&r.push(`(${this.visit(e.expr,n)})`),e.ordering==="SORTBY_ASC"&&r.push("ASC"),e.ordering==="SORTBY_DESC"&&r.push("DESC"),e.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),e.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}TypeCast(e,n){if(!e.arg||!e.typeName)return super.TypeCast(e,n);if([...this.helper.walk(e)].filter(({node:o})=>"A_Star"in o).length>0)throw new F({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(f=>f.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let f=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(f).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,n)}let s=this.visit(e.arg,n),i=this.TypeName(e.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(e,n){let r=In(e.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(e){let n=[];for(let r of e)if("A_ArrayExpr"in r){let s=In(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(e,n){if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("Not a PG array literal");let r=e.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,r[i]===","&&i++;}return s}BetweenExpr(e,n){return super.A_Expr(e,n)}AlterTableStmt(e,n){let r=e.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=r.filter(u=>"AlterTableCmd"in u&&!s.includes(u.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new F({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let u of i){let f=u.AlterTableCmd.subtype;if(o.includes(f)){let p={...e,cmds:[u]};l.push(super.AlterTableStmt(p,n));}else if(a.includes(f))c.push(u.AlterTableCmd);else throw new F({AlterTableStmt:e},`AlterTableCmd with subtype ${f} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(e.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
26
26
|
`)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new F({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);return e.subtype==="AT_DropColumn"&&e.behavior?super.AlterTableCmd({...e,behavior:void 0},n):super.AlterTableCmd(e,n)}DefineStmt(e,n){if(e.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(e,n)}InsertStmt(e,n){if("selectStmt"in e){let s=(e.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...e,selectStmt:void 0,cols:void 0},n);if(s.some(i=>i.some(o=>o===true)))throw new F({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new F({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new F({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=In(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new F({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new F({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new F({SelectStmt:e},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(e,n){return e.alias&&this.Alias(e.alias,n),super.JoinExpr(e,n)}A_Const(e,n){if(e.bsval!==void 0)throw new F({A_Const:e},"Bit string literals are not supported in SQLite");let r=super.A_Const(e,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(e,n){if(e.sortby_dir==="SORTBY_USING"){let r=In(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new F({SortBy:e},"Only `USING <` or `USING >` are supported.");e.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",e.useOp=void 0;}return super.SortBy(e,n)}RangeSubselect(e,n){if(e.lateral)throw new F({RangeSubselect:e},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(e,n)}SubLink(e,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(e.subLinkType))throw new F({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new F({SubLink:e},"ARRAY subqueries are not supported in SQLite");return super.SubLink(e,n)}LockingClause(e,n){return ""}UpdateStmt(e,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new F({UpdateStmt:e},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(e,n)}Alias(e,n){if(e.colnames&&e.colnames.length>0)throw new F({Alias:e},"Aliasing with column names is not supported in SQLite");return `AS "${e.aliasname}"`}CreateFunctionStmt(e,n){let r=e.options??[],s=e.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=r.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new F({CreateFunctionStmt:e},"Only trigger functions with LANGUAGE plpgsql are supported");let o=e.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=r.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(e,n){let r=e.trigname,s=this.RangeVar(e.relation,n),i=e.funcname?.map(f=>f.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new F({CreateTrigStmt:e},`Trigger "${r}" references unknown function "${i}"`);let a=e.timing===2?"BEFORE":e.timing===64?"INSTEAD OF":"AFTER",l=[];if(e.events&4&&l.push("INSERT"),e.events&8&&l.push("DELETE"),e.events&16)if(e.columns?.length){let f=e.columns.map(p=>p.String?.sval).filter(Boolean);l.push(`UPDATE OF ${f.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),u=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...u.map(f=>` ${f};`),"END"].join(`
|
|
27
|
-
`)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,u)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??u)}`),e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(e,n){if(e.arg?.ColumnRef?.fields?.length>1)throw new F({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new F({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new F({RenameStmt:e},`RenameStmt with renameType ${e.renameType} is not supported in SQLite`);return super.RenameStmt(e,n)}DropStmt(e,n){let r=e.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new F({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}generateRebuildSql(e,n){if(!this.introspection)throw new Error(`ALTER TABLE on "${e}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let r=this.buildDesiredSchema(this.introspection,e,n),s=new vr,i=new Ar,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
|
|
28
|
-
`):""}buildDesiredSchema(e,n,r){let s={...e,tables:e.tables.map(i=>({...i})),columns:e.columns.map(i=>({...i})),indexes:e.indexes.map(i=>({...i})),foreign_keys:e.foreign_keys.map(i=>({...i})),primary_keys:e.primary_keys.map(i=>({...i})),views:e.views.map(i=>({...i})),triggers:(e.triggers??[]).map(i=>({...i})),check_constraints:e.check_constraints.map(i=>({...i})),unique_constraints:(e.unique_constraints??[]).map(i=>({...i})),comments:(e.comments??[]).map(i=>({...i})),custom_types:e.custom_types.map(i=>({...i}))};for(let i of r){let o=s.columns.findIndex(a=>a.table===n&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(e,n){let r=e.tables.findIndex(f=>f.name===n);if(r===-1)return;let s=e.columns.filter(f=>f.table===n),i=e.foreign_keys.filter(f=>f.table===n),o=e.check_constraints.filter(f=>f.table===n),a=s.map(f=>{let p=`${I(f.name)} ${f.type||"TEXT"}`;return f.is_primary_key&&(p+=" PRIMARY KEY"),f.nullable||(p+=" NOT NULL"),f.default_value!=null&&(p+=` DEFAULT ${f.default_value}`),p}),l=i.map(f=>`FOREIGN KEY (${I(f.column)}) REFERENCES ${I(f.ref_table)}(${I(f.ref_column)}) ON UPDATE ${f.on_update} ON DELETE ${f.on_delete}`),c=o.map(f=>`CHECK (${f.expression})`),u=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${I(n)} (${u.join(", ")}) STRICT`};}extractTypeName(e){let n=e.def?.ColumnDef;return n?.typeName?.TypeName?(n.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){return e.def?"Integer"in e.def?String(e.def.Integer.ival):"Float"in e.def?e.def.Float.fval:"String"in e.def?`'${e.def.String.sval}'`:null:null}};});function Ny(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function NT(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function IT(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function Iy(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!NT(s));r.length!==n.length?(t.constraints=r,e.add(t)):IT(t)&&e.add(t);}function DT(t,e,n){let r=e?.Constraint;if(!r)return false;let s=r.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=t.tableElts??[];if(s==="CONSTR_PRIMARY"){let o=(r.keys??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length===1){let a=i.find(l=>"ColumnDef"in l&&l.ColumnDef.colname===o[0]);if(a&&n.has(a.ColumnDef)){let l=Array.isArray(a.ColumnDef.constraints)?a.ColumnDef.constraints:[];return l.push({Constraint:{contype:"CONSTR_PRIMARY"}}),a.ColumnDef.constraints=l,true}}}return i.push(e),t.tableElts=i,true}function Dy(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(Ny(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&Iy(o.ColumnDef,e);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(Ny(i.relation)),a=i.cmds??[],l=[];for(let c of a){let u=c.AlterTableCmd;u?.subtype==="AT_AddColumn"&&u.def&&"ColumnDef"in u.def&&Iy(u.def.ColumnDef,e),!(o&&u?.subtype==="AT_AddConstraint"&&u.def&&DT(o,u.def,e))&&l.push(c);}i.cmds=l;}return e}var jy=N(()=>{});var Ve,Ln,nf=N(()=>{Dn();Or();Ve=class extends F{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},Ln=class{deparse(e){if("A_Const"in e){let s=e.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let n=Object.keys(e)[0],r=this[n];if(!r)throw new Ve({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new Ve({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?pi(n):void 0;if(!r)throw new Ve({A_Expr:e},"A_Expr missing operator");let s=this.isJwtAccessor(e);if(s)return {[s]:{}};let i=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new Ve({A_Expr:e},`Unsupported operator: ${r}`);let l=e.rexpr!=null&&"ColumnRef"in e.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,i=(e.name?.[0]?pi(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new Ve({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new Ve({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new Ve({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let p of e.targetList??[]){let d="ResTarget"in p?p.ResTarget:void 0;if(d?.val){let y=this.deparseValue(d.val);Array.isArray(y)?i.push(...y.map(String)):y!=null&&y!==""&&i.push(String(y));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),u=this.deparseGroupClause(e.groupClause),f={type:"query",from:n,select:i};return r&&(f.schema=r),Object.keys(s).length>0&&(f.join=s),o&&(f.where=o),a.length>0&&(f.order=a),l!==void 0&&(f.limit=l),c!==void 0&&(f.offset=c),u.length>0&&(f.group=u),f}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new Ve({FuncCall:e},`FuncCall: ${Nn(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=Nn(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new Ve({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new Ve({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let s=e.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let s=e.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};e.quals&&(l.on=this.deparse(e.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){if(!("SortBy"in r))continue;let s=r.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),n.push(a);}return n}deparseLimit(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=Nn(e);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?pi(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function Fy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=Nn(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=Nn(r.vals);e.set(s.toLowerCase(),i);}return e}function My(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=vy(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function Uy(t){let e=new Ln,n=new Set,r=[];for(let s of t.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,f=[],p=false;for(let h of i.roles??[])if("RoleSpec"in h){let g=h.RoleSpec;g.roletype==="ROLESPEC_PUBLIC"?g.location===-1&&(p=true):g.roletype==="ROLESPEC_CSTRING"&&g.rolename&&f.push(g.rolename);}let d=i.qual?e.deparse(i.qual):void 0,y=i.with_check?e.deparse(i.with_check):void 0;if(p){let h=a?`${a}.${o}`:o,g=i.policy_name??"",S=`${h}::${g}`;if(!Ly.has(S)){Ly.add(S);let _=JSON.stringify(d)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(_)||console.warn(`[supalite] policy "${g}" on "${h}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let m=new rn({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:f,using:d,withCheck:y});r.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";n.add(l);}}}return {policies:r,tables:n}}function By(t,e){let n=new Map;for(let r of t.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new Xt(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let f=c.typeName?.names?.map(C=>C.String?.sval||C.String?.str).filter(Boolean),p=f&&(f.length===2&&f[0]==="pg_catalog"?f[1]:f[0]);if(!p)continue;let d=!!c.typeName?.arrayBounds?.length,y=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=C=>y[C]?.A_Const?.ival?.ival??y[C]?.A_Const?.val?.ival?.ival,h={isArray:d};if(wa(p)&&y.length>0){let C=m(0);typeof C=="number"&&C>0&&(h.lengthConstraint=C);}if(Sa(p)&&y.length>=2){let C=m(0),q=m(1);typeof C=="number"&&typeof q=="number"&&C>0&&q>=0&&(h.numericPrecision={precision:C,scale:q});}let g=e.get(p.toLowerCase());g&&(h.enumValues=g);let S=Array.isArray(c.constraints)?c.constraints:[],_=S.some(C=>C.Constraint?.contype==="CONSTR_PRIMARY"),w=ba(p)||S.some(C=>C.Constraint?.contype==="CONSTR_IDENTITY"),x=S.some(C=>C.Constraint?.contype==="CONSTR_NOTNULL"),E=S.find(C=>C.Constraint?.contype==="CONSTR_UNIQUE"),R=S.find(C=>C.Constraint?.contype==="CONSTR_GENERATED"),O=S.find(C=>C.Constraint?.contype==="CONSTR_FOREIGN"),P=S.find(C=>C.Constraint?.contype==="CONSTR_CHECK"),D;if(O){let C=O.Constraint,q=C.pktable?.relname,K=C.pktable?.schemaname,M=C.pk_attrs?.[0]?.String?.sval;q&&M&&(D={refSchema:K,refTable:q,refColumn:M,constraintName:C.conname||void 0});}let v={schema:o,table:i,column:u,pgTypeName:p,nullable:!x&&!_,defaultValue:null,defaultFn:null,isPrimaryKey:_,isUnique:!!E,isSerial:w,isGenerated:!!R,fkRef:D,hasCheck:!!P,checkConstraintName:P?.Constraint?.conname||void 0,uniqueConstraintName:E?.Constraint?.conname||void 0};a.set(u,ct(v,h));}n.set(`${o}.${i}`,a);}return n}function qy(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(f=>f.String?.sval??f.String?.str).filter(Boolean);if(u.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")e.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(d=>d.String?.sval??d.String?.str).filter(Boolean),f=(l.pk_attrs??[]).map(d=>d.String?.sval??d.String?.str).filter(Boolean),p=l.pktable?.relname;if(!p)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:p,refColumns:f});}}}return e}function Hy(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];e.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,e.push({schema:a,table:l,column:c,text:s});}}}return e}var Ly,Wy=N(()=>{nf();Dn();fa();Dc();Or();Ly=new Set;});var zy={};Ir(zy,{Policy:()=>rn,deparseDdl:()=>rf,deparseExpression:()=>FT,deparsePostgresDdl:()=>LT,deparseSelect:()=>MT,parse:()=>kr,parseExpression:()=>Jy,translatePostgresDdl:()=>Ky});async function Ky(t,e={}){let n=await kr(t);return rf(n,e).ddl}async function LT(t,e={}){let n=await kr(t);return {ast:n,...rf(n,e)}}function rf(t,e={}){let n=Dy(t),r=Fy(t),s=By(t,r),i=My(t),o=qy(t),a=Hy(t),l=new Ra(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:u}=Uy(t);if(e.strict)for(let f of c){if(!s.get(`${f.data.schema??"public"}.${f.data.table}`))throw new Error(`Policy "${f.data.name}" references unknown table "${f.data.table}"`);if(!u.has(f.data.table))throw new Error(`RLS is not enabled on table "${f.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:u,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function Jy(t){let n=(await kr(`SELECT 1 WHERE ${t}`)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");let r=n.SelectStmt.whereClause;if(!r)throw new Error("no whereClause");return r}async function FT(t){let e=await Jy(t);return new Ln().deparse(e)}async function MT(t){let n=(await kr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new Ln().deparse(n)}var sf=N(()=>{Ty();Py();jy();nf();Wy();fa();});ie();function Sf(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r);}return n}function _f(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Sf(Object(n),true).forEach(function(r){fw(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Sf(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function fw(t,e,n){return e=pw(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function pw(t){var e=dw(t,"string");return typeof e=="symbol"?e:String(e)}function dw(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}var mw=Ef({}),Le=mw;function Ef(t){return e.withOptions=n=>Ef(_f(_f({},t),n)),e;function e(n,...r){let s=typeof n=="string"?[n]:n.raw,{alignValues:i=false,escapeSpecialCharacters:o=Array.isArray(n),trimWhitespace:a=true}=t,l="";for(let f=0;f<s.length;f++){let p=s[f];if(o&&(p=p.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=p,f<r.length){let d=i?hw(r[f],l):r[f];l+=d;}}let c=l.split(`
|
|
27
|
+
`)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,u)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??u)}`),e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(e,n){if(e.arg?.ColumnRef?.fields?.length>1)throw new F({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");if(e.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new F({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new F({RenameStmt:e},`RenameStmt with renameType ${e.renameType} is not supported in SQLite`);return super.RenameStmt(e,n)}DropStmt(e,n){let r=e.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new F({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}generateRebuildSql(e,n){if(!this.introspection)throw new Error(`ALTER TABLE on "${e}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let r=this.buildDesiredSchema(this.introspection,e,n),s=new vr,i=new Ar,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
|
|
28
|
+
`):""}buildDesiredSchema(e,n,r){let s={...e,tables:e.tables.map(i=>({...i})),columns:e.columns.map(i=>({...i})),indexes:e.indexes.map(i=>({...i})),foreign_keys:e.foreign_keys.map(i=>({...i})),primary_keys:e.primary_keys.map(i=>({...i})),views:e.views.map(i=>({...i})),triggers:(e.triggers??[]).map(i=>({...i})),check_constraints:e.check_constraints.map(i=>({...i})),unique_constraints:(e.unique_constraints??[]).map(i=>({...i})),comments:(e.comments??[]).map(i=>({...i})),custom_types:e.custom_types.map(i=>({...i}))};for(let i of r){let o=s.columns.findIndex(a=>a.table===n&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(e,n){let r=e.tables.findIndex(f=>f.name===n);if(r===-1)return;let s=e.columns.filter(f=>f.table===n),i=e.foreign_keys.filter(f=>f.table===n),o=e.check_constraints.filter(f=>f.table===n),a=s.map(f=>{let p=`${I(f.name)} ${f.type||"TEXT"}`;return f.is_primary_key&&(p+=" PRIMARY KEY"),f.nullable||(p+=" NOT NULL"),f.default_value!=null&&(p+=` DEFAULT ${f.default_value}`),p}),l=i.map(f=>`FOREIGN KEY (${I(f.column)}) REFERENCES ${I(f.ref_table)}(${I(f.ref_column)}) ON UPDATE ${f.on_update} ON DELETE ${f.on_delete}`),c=o.map(f=>`CHECK (${f.expression})`),u=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${I(n)} (${u.join(", ")}) STRICT`};}extractTypeName(e){let n=e.def?.ColumnDef;return n?.typeName?.TypeName?(n.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){return e.def?"Integer"in e.def?String(e.def.Integer.ival):"Float"in e.def?e.def.Float.fval:"String"in e.def?`'${e.def.String.sval}'`:null:null}};});function Dy(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function LT(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function FT(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function jy(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!LT(s));r.length!==n.length?(t.constraints=r,e.add(t)):FT(t)&&e.add(t);}function MT(t,e,n){let r=e?.Constraint;if(!r)return false;let s=r.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=t.tableElts??[];if(s==="CONSTR_PRIMARY"){let o=(r.keys??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length===1){let a=i.find(l=>"ColumnDef"in l&&l.ColumnDef.colname===o[0]);if(a&&n.has(a.ColumnDef)){let l=Array.isArray(a.ColumnDef.constraints)?a.ColumnDef.constraints:[];return l.push({Constraint:{contype:"CONSTR_PRIMARY"}}),a.ColumnDef.constraints=l,true}}}return i.push(e),t.tableElts=i,true}function Ly(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(Dy(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&jy(o.ColumnDef,e);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(Dy(i.relation)),a=i.cmds??[],l=[];for(let c of a){let u=c.AlterTableCmd;u?.subtype==="AT_AddColumn"&&u.def&&"ColumnDef"in u.def&&jy(u.def.ColumnDef,e),!(o&&u?.subtype==="AT_AddConstraint"&&u.def&&MT(o,u.def,e))&&l.push(c);}i.cmds=l;}return e}var Fy=N(()=>{});var Ve,Ln,nf=N(()=>{Dn();Or();Ve=class extends F{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},Ln=class{deparse(e){if("A_Const"in e){let s=e.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let n=Object.keys(e)[0],r=this[n];if(!r)throw new Ve({[n]:e},`Unsupported expression: ${n}`);return r.call(this,e[n])}deparseValue(e){if("A_Const"in e)return this.A_Const(e.A_Const);if("ColumnRef"in e)return this.ColumnRef(e.ColumnRef);if("FuncCall"in e)return this.FuncCall(e.FuncCall);if("SubLink"in e)return this.SubLink(e.SubLink);if("TypeCast"in e)return this.TypeCast(e.TypeCast);if("A_Expr"in e){let r=this.isJwtAccessor(e.A_Expr);return r||this.A_Expr(e.A_Expr)}if("BoolExpr"in e)return this.BoolExpr(e.BoolExpr);let n=Object.keys(e)[0];throw new Ve({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?pi(n):void 0;if(!r)throw new Ve({A_Expr:e},"A_Expr missing operator");let s=this.isJwtAccessor(e);if(s)return {[s]:{}};let i=e.lexpr?this.deparseValue(e.lexpr):void 0,o=e.rexpr?this.deparseValue(e.rexpr):void 0,a=this.mapOperator(r);if(!a)throw new Ve({A_Expr:e},`Unsupported operator: ${r}`);let l=e.rexpr!=null&&"ColumnRef"in e.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(e.kind==="AEXPR_LIKE"||e.kind==="AEXPR_ILIKE"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr?this.deparseValue(e.rexpr):void 0,i=(e.name?.[0]?pi(e.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,r=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new Ve({A_Expr:e},`A_Expr kind: ${e.kind}`)}BoolExpr(e){let n=e.args??[];switch(e.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new Ve({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(e){if(e.subLinkType==="ANY_SUBLINK"){let n=e.testexpr?this.deparseValue(e.testexpr):void 0,r=e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(e.subLinkType==="EXISTS_SUBLINK")return {$exists:e.subselect?this.SelectStmt(e.subselect.SelectStmt):void 0};if(e.subLinkType==="EXPR_SUBLINK"){let n=e.subselect?e.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new Ve({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let p of e.targetList??[]){let d="ResTarget"in p?p.ResTarget:void 0;if(d?.val){let g=this.deparseValue(d.val);Array.isArray(g)?i.push(...g.map(String)):g!=null&&g!==""&&i.push(String(g));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),u=this.deparseGroupClause(e.groupClause),f={type:"query",from:n,select:i};return r&&(f.schema=r),Object.keys(s).length>0&&(f.join=s),o&&(f.where=o),a.length>0&&(f.order=a),l!==void 0&&(f.limit=l),c!==void 0&&(f.offset=c),u.length>0&&(f.group=u),f}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new Ve({FuncCall:e},`FuncCall: ${sn(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=sn(e.fields??[]);return n.length===1?n[0]:n.join(".")}A_Const(e){if(e.boolval!==void 0)return e.boolval.boolval;if(e.ival!==void 0)return e.ival.ival??0;if(e.fval!==void 0)return parseFloat(e.fval.fval??"0");if(e.sval!==void 0)return e.sval.sval??"";if(e.isnull)return null;throw new Ve({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new Ve({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let s=e.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let s=e.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};e.quals&&(l.on=this.deparse(e.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){if(!("SortBy"in r))continue;let s=r.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),n.push(a);}return n}deparseLimit(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=sn(e);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(e){if(e.kind!=="AEXPR_OP")return null;let n=e.name?.[0]?pi(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function qy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=sn(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=sn(r.vals);e.set(s.toLowerCase(),i);}return e}function Hy(t){let e=new Map;for(let n of t.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=ky(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function Uy(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&e.push(s.rolename);}return {roles:e,implicitPublic:n}}function By(t,e){return t&&t.length>0?t:e}function rf(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&By(r.data.schema,n)===By(e.schema,n))}function sf(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function Wy(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,s=new Ln,i=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",u=l.table?.schemaname,f={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},p=l.cmd_name?f[l.cmd_name]??"ALL":"ALL",d=l.permissive===true,{roles:g,implicitPublic:m}=Uy(l.roles),h=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let _=u?`${u}.${c}`:c,w=l.policy_name??"",x=`${_}::${w}`;if(!My.has(x)){My.add(x);let E=JSON.stringify(h)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(E)||console.warn(`[supalite] policy "${w}" on "${_}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let S=new gt({name:l.policy_name??"",table:c,schema:u,command:p,permissive:d,roles:g,using:h,withCheck:y});o.push(S);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let u=sn(c.List.items??[]),f=u[u.length-1],p=u[u.length-2],d=u.length>=3?u[u.length-3]:void 0;if(f&&p){let g=rf(o,{name:f,table:p,schema:d},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw sf(f,p)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",f=l.table?.schemaname,p=rf(o,{name:c,table:u,schema:f},n);if(p===-1){if(r)throw sf(c,u);continue}let d=o[p].data,g=l.roles?Uy(l.roles).roles:d.roles,m=l.qual?s.deparse(l.qual):d.using,h=l.with_check?s.deparse(l.with_check):d.withCheck;o[p]=new gt({...d,roles:g,using:m,withCheck:h});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",f=l.relation?.schemaname,p=rf(o,{name:c,table:u,schema:f},n);if(p===-1){if(r)throw sf(c,u);continue}l.newname&&(o[p]=new gt({...o[p].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(f=>"AlterTableCmd"in f&&(f.AlterTableCmd.subtype==="AT_EnableRowSecurity"||f.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let f=l.relation?.relname??"";i.add(f);}}}return {policies:o,tables:i}}function Ky(t,e){let n=new Map;for(let r of t.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new Zt(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let f=c.typeName?.names?.map(C=>C.String?.sval||C.String?.str).filter(Boolean),p=f&&(f.length===2&&f[0]==="pg_catalog"?f[1]:f[0]);if(!p)continue;let d=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=C=>g[C]?.A_Const?.ival?.ival??g[C]?.A_Const?.val?.ival?.ival,h={isArray:d};if(wa(p)&&g.length>0){let C=m(0);typeof C=="number"&&C>0&&(h.lengthConstraint=C);}if(Sa(p)&&g.length>=2){let C=m(0),q=m(1);typeof C=="number"&&typeof q=="number"&&C>0&&q>=0&&(h.numericPrecision={precision:C,scale:q});}let y=e.get(p.toLowerCase());y&&(h.enumValues=y);let S=Array.isArray(c.constraints)?c.constraints:[],_=S.some(C=>C.Constraint?.contype==="CONSTR_PRIMARY"),w=ba(p)||S.some(C=>C.Constraint?.contype==="CONSTR_IDENTITY"),x=S.some(C=>C.Constraint?.contype==="CONSTR_NOTNULL"),E=S.find(C=>C.Constraint?.contype==="CONSTR_UNIQUE"),R=S.find(C=>C.Constraint?.contype==="CONSTR_GENERATED"),O=S.find(C=>C.Constraint?.contype==="CONSTR_FOREIGN"),P=S.find(C=>C.Constraint?.contype==="CONSTR_CHECK"),D;if(O){let C=O.Constraint,q=C.pktable?.relname,K=C.pktable?.schemaname,M=C.pk_attrs?.[0]?.String?.sval;q&&M&&(D={refSchema:K,refTable:q,refColumn:M,constraintName:C.conname||void 0});}let v={schema:o,table:i,column:u,pgTypeName:p,nullable:!x&&!_,defaultValue:null,defaultFn:null,isPrimaryKey:_,isUnique:!!E,isSerial:w,isGenerated:!!R,fkRef:D,hasCheck:!!P,checkConstraintName:P?.Constraint?.conname||void 0,uniqueConstraintName:E?.Constraint?.conname||void 0};a.set(u,ct(v,h));}n.set(`${o}.${i}`,a);}return n}function Jy(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(f=>f.String?.sval??f.String?.str).filter(Boolean);if(u.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")e.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(d=>d.String?.sval??d.String?.str).filter(Boolean),f=(l.pk_attrs??[]).map(d=>d.String?.sval??d.String?.str).filter(Boolean),p=l.pktable?.relname;if(!p)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:p,refColumns:f});}}}return e}function zy(t){let e=[];for(let n of t.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];e.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,e.push({schema:a,table:l,column:c,text:s});}}}return e}var My,Gy=N(()=>{nf();Dn();fa();Dc();Or();My=new Set;});var Yy={};Ir(Yy,{Policy:()=>gt,deparseDdl:()=>of,deparseExpression:()=>qT,deparsePostgresDdl:()=>BT,deparseSelect:()=>HT,parse:()=>kr,parseExpression:()=>Qy,translatePostgresDdl:()=>Vy});async function Vy(t,e={}){let n=await kr(t);return of(n,e).ddl}async function BT(t,e={}){let n=await kr(t);return {ast:n,...of(n,e)}}function of(t,e={}){let n=Ly(t),r=qy(t),s=Ky(t,r),i=Hy(t),o=Jy(t),a=zy(t),l=new Ra(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:u}=Wy(t,{defaultSchema:e.defaultSchema,validateMutations:e.strict});if(e.strict)for(let f of c){if(!s.get(`${f.data.schema??"public"}.${f.data.table}`))throw new Error(`Policy "${f.data.name}" references unknown table "${f.data.table}"`);if(!u.has(f.data.table))throw new Error(`RLS is not enabled on table "${f.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:u,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function Qy(t){let n=(await kr(`SELECT 1 WHERE ${t}`)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");let r=n.SelectStmt.whereClause;if(!r)throw new Error("no whereClause");return r}async function qT(t){let e=await Qy(t);return new Ln().deparse(e)}async function HT(t){let n=(await kr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new Ln().deparse(n)}var af=N(()=>{Ay();Iy();Fy();nf();Gy();fa();});ie();function Ef(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r);}return n}function xf(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Ef(Object(n),true).forEach(function(r){hw(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Ef(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function hw(t,e,n){return e=gw(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function gw(t){var e=yw(t,"string");return typeof e=="symbol"?e:String(e)}function yw(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}var bw=Rf({}),Le=bw;function Rf(t){return e.withOptions=n=>Rf(xf(xf({},t),n)),e;function e(n,...r){let s=typeof n=="string"?[n]:n.raw,{alignValues:i=false,escapeSpecialCharacters:o=Array.isArray(n),trimWhitespace:a=true}=t,l="";for(let f=0;f<s.length;f++){let p=s[f];if(o&&(p=p.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=p,f<r.length){let d=i?ww(r[f],l):r[f];l+=d;}}let c=l.split(`
|
|
29
29
|
`),u=null;for(let f of c){let p=f.match(/^(\s+)\S+/);if(p){let d=p[1].length;u?u=Math.min(u,d):u=d;}}if(u!==null){let f=u;l=c.map(p=>p[0]===" "||p[0]===" "?p.slice(f):p).join(`
|
|
30
30
|
`);}return a&&(l=l.trim()),o&&(l=l.replace(/\\n/g,`
|
|
31
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(f,p)=>String.fromCharCode(parseInt(p,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(f,p)=>String.fromCodePoint(parseInt(p,16))).replace(/\\u([\da-fA-F]{4})/g,(f,p)=>String.fromCharCode(parseInt(p,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(f,p,d)=>{var
|
|
31
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(f,p)=>String.fromCharCode(parseInt(p,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(f,p)=>String.fromCodePoint(parseInt(p,16))).replace(/\\u([\da-fA-F]{4})/g,(f,p)=>String.fromCharCode(parseInt(p,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(f,p,d)=>{var g;let m=(g=p??d)!==null&&g!==void 0?g:"";return String.fromCodePoint(parseInt(m,16))})),l}}function ww(t,e){if(typeof t!="string"||!t.includes(`
|
|
32
32
|
`))return t;let r=e.slice(e.lastIndexOf(`
|
|
33
33
|
`)+1).match(/^(\s+)/);if(r){let s=r[1];return t.replace(/\n/g,`
|
|
34
|
-
${s}`)}return t}ie();var
|
|
34
|
+
${s}`)}return t}ie();var Cf=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],xi=["analytics"],Tf=b.strictObject({enabled:b.boolean({default:false,description:"Enable the local Logflare service.",tags:xi,links:Cf}),port:b.number({default:54327,description:"Port to the local Logflare service.",tags:xi}),vector_port:b.number({default:54328,description:"Port to the local syslog ingest service.",tags:xi}),backend:b.string({enum:["postgres","bigquery"],default:"postgres",description:Le`
|
|
35
35
|
Configure one of the supported backends:
|
|
36
36
|
|
|
37
37
|
- \`postgres\`
|
|
38
|
-
- \`bigquery\``,tags:xi,links:
|
|
38
|
+
- \`bigquery\``,tags:xi,links:Cf})}).partial();ie();var Sw=Symbol.for("lite-only"),Mt=t=>(Object.defineProperty(t,Sw,{value:true,enumerable:false,writable:false,configurable:false}),t);var rt=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],We=["api"],vf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local PostgREST service.",tags:We,links:rt}),port:b.number({default:54321,description:"Port to use for the API URL.",tags:We,links:rt}),schemas:b.array(b.string({description:"Schemas to expose in your API. Tables, views and functions in this schema will get API endpoints. `public` and `storage` are always included.",tags:We,links:rt}),{default:["public","storage","graphql_public"]}),extra_search_path:b.array(b.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:We,links:rt}),{default:["public","extensions"]}),max_rows:b.number({default:1e3,description:"The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.",tags:We,links:rt}),pg_safe_update:b.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:We,links:rt}),plan_enabled:Mt(b.boolean({default:false,description:"Enable the EXPLAIN plan feature via `Accept: application/vnd.pgrst.plan`. Disabled by default to match PostgREST's `db-plan-enabled` setting.",tags:We,links:rt})),aggregates_enabled:Mt(b.boolean({default:false,description:"Enable aggregate functions (count(), sum(), avg(), min(), max()) in select. Disabled by default to match PostgREST's `db-aggregates-enabled` setting.",tags:We,links:rt})),limited_mutations_enabled:Mt(b.boolean({default:false,description:"Honor `?limit`, `?offset`, and `?order` on UPDATE/DELETE via subquery. Disabled by default to match PostgREST's silent-ignore behavior.",tags:We,links:rt})),anonymous_enabled:Mt(b.boolean({default:true,description:"Allow requests without an Authorization header. When false, unauthenticated requests receive 401 PGRST302 'Anonymous access is disabled'. Mirrors PostgREST's `db-anon-role`.",tags:We,links:rt})),tls:b.strictObject({enabled:b.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:We})}).partial(),external_url:b.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:We})}).partial();ie();ie();var ln=["auth"],cn={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Fr=(t,e)=>b.strictObject({subject:b.string({default:e,description:`The subject of the ${t} email.`}),content_path:b.string({description:`The path to the content of the ${t} email.`})}).partial(),Af=b.strictObject({enable_signup:b.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:ln,links:[cn.auth]}),double_confirm_changes:b.boolean({default:true,description:"If enabled, a user will be required to confirm any email change on both the old, and new email addresses. If disabled, only the new email is required to confirm.",tags:ln,links:[cn.auth]}),enable_confirmations:b.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:ln,links:[cn.auth]}),secure_password_change:b.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:ln,links:[cn.auth]}),max_frequency:b.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:ln,links:[cn.auth]}),smtp:b.strictObject({host:b.string({default:"inbucket",description:"Hostname or IP address of the SMTP server."}),port:b.number({default:2500,description:"Port number of the SMTP server."}),user:b.string({description:"Username for authenticating with the SMTP server."}),pass:b.string({description:"Password for authenticating with the SMTP server."}),admin_email:b.string({default:"admin@email.com",description:"Email used as the sender for emails sent from the application."}),sender_name:b.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:b.strictObject({invite:Fr("invite","You have been invited"),confirmation:Fr("confirmation","Confirm Your Signup"),recovery:Fr("recovery","Reset Your Password"),magic_link:Fr("magic link","Your Magic Link"),email_change:Fr("email change","Confirm Email Change")}).partial(),otp_length:b.number({default:6,description:"Number of characters used in the email OTP.",tags:ln,links:[cn.auth]}),otp_expiry:b.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:ln,links:[cn.auth]})}).partial();ie();var Ri=["auth"],Fa=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),Mr=(t,e)=>b.strictObject({enabled:b.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:Ri,links:[Fa(t,e)]}),uri:b.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:Ri,links:[Fa(t,e)]}),secrets:b.array(b.string({description:"A secret to pass to the function or endpoint.",tags:Ri}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:Ri,links:[Fa(t,e)]})}).partial(),kf=b.strictObject({mfa_verification_attempt:Mr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:Mr("Password Verification Hook","password-verification-hook"),custom_access_token:Mr("Custom Access Token Hook","custom-access-token-hook"),send_sms:Mr("Send SMS Hook","send-sms-hook"),send_email:Mr("Send Email Hook","send-email-hook")}).partial();ie();var Ut=["auth"],Bt={mfa:{name:"Multi-Factor Authentication",link:"https://supabase.com/docs/guides/auth/auth-mfa"},totp:{name:"Multi-Factor Authentication (TOTP)",link:"https://supabase.com/docs/guides/auth/auth-mfa/totp"},phone:{name:"Multi-Factor Authentication (Phone)",link:"https://supabase.com/docs/guides/auth/auth-mfa/phone"}},$f=b.strictObject({totp:b.strictObject({enroll_enabled:b.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:Ut,links:[Bt.totp]}),verify_enabled:b.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:Ut,links:[Bt.totp]})}).partial(),phone:b.strictObject({enroll_enabled:b.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:Ut,links:[Bt.phone]}),verify_enabled:b.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:Ut,links:[Bt.phone]}),otp_length:b.number({default:6,description:"The length of the OTP code.",tags:Ut,links:[Bt.phone]}),template:b.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:Ut,links:[Bt.phone]}),max_frequency:b.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:Ut,links:[Bt.phone]})}).partial(),max_enrolled_factors:b.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:Ut,links:[Bt.mfa]})}).partial();ie();ie();var Ma=class extends La{},St=t=>new Ma(t);var Bn=["auth"],he=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return b.strictObject({enabled:b.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Bn,links:e}),client_id:b.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Bn,links:e}),secret:St({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:Le`
|
|
39
39
|
Client secret for the ${t.name} OAuth provider.
|
|
40
40
|
|
|
41
41
|
DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead.
|
|
42
|
-
`,tags:Bn,links:e}),url:b.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Bn,links:e}),redirect_uri:b.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:Bn,links:e}),skip_nonce_check:b.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Bn,links:e})}).partial()},kf=b.strictObject({apple:he({id:"apple",name:"Apple"}),azure:he({id:"azure",name:"Azure"}),bitbucket:he({id:"bitbucket",name:"Bitbucket"}),discord:he({id:"discord",name:"Discord"}),facebook:he({id:"facebook",name:"Facebook"}),github:he({id:"github",name:"GitHub"}),gitlab:he({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:he({id:"google",name:"Google"}),kakao:he({id:"kakao",name:"Kakao"}),keycloak:he({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:he({id:"linkedin",name:"LinkedIn"}),notion:he({id:"notion",name:"Notion"}),twitch:he({id:"twitch",name:"Twitch"}),twitter:he({id:"twitter",name:"Twitter"}),slack:he({id:"slack",name:"Slack"}),spotify:he({id:"spotify",name:"Spotify"}),workos:he({id:"workos",name:"WorkOS"}),zoom:he({id:"zoom",name:"Zoom"})}).partial();ie();var Ua=["auth"],Ba=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],$f=b.strictObject({timebox:b.string({description:"The timebox for the user session.",tags:Ua,links:Ba}),inactivity_timeout:b.string({description:"The inactivity timeout for the user session.",tags:Ua,links:Ba}),single_per_user:b.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:Ua,links:Ba})}).partial();ie();var oe=["auth"],ce={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},Of=b.strictObject({enable_signup:b.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:oe,links:[ce.auth]}),enable_confirmations:b.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:oe,links:[ce.auth]}),template:b.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:oe,links:[ce.auth]}),max_frequency:b.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:oe}),twilio:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:oe,links:[ce.phoneLogin("Twilio")]}),account_sid:b.string({description:"The account SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),message_service_sid:b.string({description:"The message service SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),auth_token:b.string({description:"The auth token for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]})}).partial(),twilio_verify:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:oe,links:[ce.phoneLogin("Twilio")]}),account_sid:b.string({description:"The account SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),message_service_sid:b.string({description:"The message service SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),auth_token:b.string({description:"The auth token for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]})}).partial(),messagebird:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:oe,links:[ce.phoneLogin("MessageBird")]}),originator:b.string({description:"The originator of the SMS message.",tags:oe,links:[ce.phoneLogin("MessageBird")]}),api_key:b.string({description:"The API key for the MessageBird API.",tags:oe,links:[ce.phoneLogin("MessageBird")]})}).partial(),textlocal:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:b.string({description:"The sender of the SMS message.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:b.string({description:"The API key for the Textlocal API.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:oe,links:[ce.phoneLogin("Vonage")]}),from:b.string({description:"The sender of the SMS message.",tags:oe,links:[ce.phoneLogin("Vonage")]}),api_key:b.string({description:"The API key for the Vonage API.",tags:oe,links:[ce.phoneLogin("Vonage")]}),api_secret:b.string({description:"The API secret for the Vonage API.",tags:oe,links:[ce.phoneLogin("Vonage")]})}).partial(),test_otp:b.record(b.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:oe,links:[ce.auth]})}).partial();var Fe=["auth"],Ke={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Pf=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],Nf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local GoTrue service.",tags:Fe,links:[Ke.auth]}),jwt_secret:b.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Fe,links:[Ke.auth]}),site_url:b.string({default:"http://localhost:3000",description:"The base URL of your website. Used as an allow-list for redirects and for constructing URLs used in emails.",tags:Fe,links:[Ke.auth]}),additional_redirect_urls:b.array(b.string({description:"A URL that auth providers are permitted to redirect to.",tags:Fe}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Fe,links:[Ke.auth]}),jwt_expiry:b.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Fe,links:[Ke.auth]}),enable_refresh_token_rotation:b.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Fe,links:[Ke.auth]}),refresh_token_reuse_interval:b.number({default:10,description:"Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. Requires enable_refresh_token_rotation = true.",tags:Fe,links:[Ke.auth]}),enable_manual_linking:b.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Fe,links:[Ke.auth]}),enable_signup:b.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Fe,links:[Ke.auth]}),enable_anonymous_sign_ins:b.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Fe,links:[Ke.auth]}),minimum_password_length:b.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Fe,links:[Ke.auth]}),password_requirements:b.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${Pf.join(", ")}`,enum:["",...Pf],tags:Fe,links:[Ke.auth]}),hook:vf,mfa:Af,sessions:$f,email:Tf,sms:Of,external:kf}).partial();ie();var cn={postgres:{name:"PostgreSQL configuration",link:"https://postgrest.org/en/stable/configuration.html"},pgbouncer:t=>({name:"PgBouncer Configuration",link:`https://www.pgbouncer.org/config.html${t?`#${t}`:""}`})},Ae=["database"],If=b.object({driver:Ft(b.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite",description:"The database driver to use.",tags:Ae})),url:Ft(b.string({description:"Path to the database file/directory (Supalite only).",tags:Ae})),port:b.number({default:54322,description:"Port to use for the local database URL.",tags:Ae,links:[cn.postgres]}),shadow_port:b.number({default:54320,description:"Port to use for the local shadow database.",tags:Ae}),major_version:b.number({default:15,description:"The database major version to use. This has to be the same as your remote database's. Run `SHOW server_version;` on the remote database to check.",tags:Ae,links:[cn.postgres]}),pooler:b.object({enabled:b.boolean({default:false,description:"Enable the local PgBouncer service.",tags:Ae,links:[cn.pgbouncer()]}),port:b.number({default:54329,description:"Port to use for the local connection pooler.",tags:Ae,links:[cn.pgbouncer("listen_port")]}),pool_mode:b.string({enum:["transaction","session"],default:"transaction",description:"Specifies when a server connection can be reused by other clients. Configure one of the supported pooler modes: `transaction`, `session`.",tags:Ae,links:[cn.pgbouncer("pool_mode")]}),default_pool_size:b.number({default:20,description:"How many server connections to allow per user/database pair.",tags:Ae,links:[cn.pgbouncer("default_pool_size")]}),max_client_conn:b.number({default:100,description:"Maximum number of client connections allowed.",tags:Ae,links:[cn.pgbouncer("max_client_conn")]})}).partial(),seed:b.strictObject({enabled:b.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:Ae}),sql_paths:b.array(b.string({description:"Path to a SQL file to seed the database with.",tags:Ae}),{default:["./seed.sql"],description:"Paths to SQL files to seed the database with. Supports glob patterns relative to supabase directory.",examples:[["./seeds/*.sql","../project-src/seeds/*-load-testing.sql"]],tags:Ae})}).partial(),migrations:b.strictObject({enabled:b.boolean({default:true,description:"Enable migrations.",tags:Ae}),schema_paths:b.array(b.string({description:"Path to a SQL file to seed the database with.",tags:Ae}),{default:["./schemas/schema.sql"]})}).partial()}).partial();ie();var qa=["edge-functions"],Df=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:qa}),policy:b.string({enum:["oneshot","per_worker"],default:"oneshot",description:"Configure the supported request policy. Use `oneshot` for hot reload, or `per_worker` for load testing.",tags:qa}),inspector_port:b.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:qa})}).partial();ie();var Ur=["experimental"],jf=b.strictObject({orioledb_version:b.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Ur}),s3_host:wt({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Ur}),s3_region:wt({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Ur}),s3_access_key:wt({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Ur}),s3_secret_key:wt({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Ur})}).partial();ie();var Ci=["functions"],Ti=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],yw=Un({enabled:Lr({default:true,description:Le`
|
|
42
|
+
`,tags:Bn,links:e}),url:b.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Bn,links:e}),redirect_uri:b.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:Bn,links:e}),skip_nonce_check:b.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Bn,links:e})}).partial()},Of=b.strictObject({apple:he({id:"apple",name:"Apple"}),azure:he({id:"azure",name:"Azure"}),bitbucket:he({id:"bitbucket",name:"Bitbucket"}),discord:he({id:"discord",name:"Discord"}),facebook:he({id:"facebook",name:"Facebook"}),github:he({id:"github",name:"GitHub"}),gitlab:he({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:he({id:"google",name:"Google"}),kakao:he({id:"kakao",name:"Kakao"}),keycloak:he({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:he({id:"linkedin",name:"LinkedIn"}),notion:he({id:"notion",name:"Notion"}),twitch:he({id:"twitch",name:"Twitch"}),twitter:he({id:"twitter",name:"Twitter"}),slack:he({id:"slack",name:"Slack"}),spotify:he({id:"spotify",name:"Spotify"}),workos:he({id:"workos",name:"WorkOS"}),zoom:he({id:"zoom",name:"Zoom"})}).partial();ie();var Ua=["auth"],Ba=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],Pf=b.strictObject({timebox:b.string({description:"The timebox for the user session.",tags:Ua,links:Ba}),inactivity_timeout:b.string({description:"The inactivity timeout for the user session.",tags:Ua,links:Ba}),single_per_user:b.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:Ua,links:Ba})}).partial();ie();var oe=["auth"],ce={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},Nf=b.strictObject({enable_signup:b.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:oe,links:[ce.auth]}),enable_confirmations:b.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:oe,links:[ce.auth]}),template:b.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:oe,links:[ce.auth]}),max_frequency:b.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:oe}),twilio:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:oe,links:[ce.phoneLogin("Twilio")]}),account_sid:b.string({description:"The account SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),message_service_sid:b.string({description:"The message service SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),auth_token:b.string({description:"The auth token for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]})}).partial(),twilio_verify:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:oe,links:[ce.phoneLogin("Twilio")]}),account_sid:b.string({description:"The account SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),message_service_sid:b.string({description:"The message service SID for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]}),auth_token:b.string({description:"The auth token for the Twilio API.",tags:oe,links:[ce.phoneLogin("Twilio")]})}).partial(),messagebird:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:oe,links:[ce.phoneLogin("MessageBird")]}),originator:b.string({description:"The originator of the SMS message.",tags:oe,links:[ce.phoneLogin("MessageBird")]}),api_key:b.string({description:"The API key for the MessageBird API.",tags:oe,links:[ce.phoneLogin("MessageBird")]})}).partial(),textlocal:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:b.string({description:"The sender of the SMS message.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:b.string({description:"The API key for the Textlocal API.",tags:oe,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:b.strictObject({enabled:b.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:oe,links:[ce.phoneLogin("Vonage")]}),from:b.string({description:"The sender of the SMS message.",tags:oe,links:[ce.phoneLogin("Vonage")]}),api_key:b.string({description:"The API key for the Vonage API.",tags:oe,links:[ce.phoneLogin("Vonage")]}),api_secret:b.string({description:"The API secret for the Vonage API.",tags:oe,links:[ce.phoneLogin("Vonage")]})}).partial(),test_otp:b.record(b.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:oe,links:[ce.auth]})}).partial();var Fe=["auth"],Ke={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},If=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],Df=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local GoTrue service.",tags:Fe,links:[Ke.auth]}),jwt_secret:b.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Fe,links:[Ke.auth]}),site_url:b.string({default:"http://localhost:3000",description:"The base URL of your website. Used as an allow-list for redirects and for constructing URLs used in emails.",tags:Fe,links:[Ke.auth]}),additional_redirect_urls:b.array(b.string({description:"A URL that auth providers are permitted to redirect to.",tags:Fe}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Fe,links:[Ke.auth]}),jwt_expiry:b.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Fe,links:[Ke.auth]}),enable_refresh_token_rotation:b.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Fe,links:[Ke.auth]}),refresh_token_reuse_interval:b.number({default:10,description:"Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. Requires enable_refresh_token_rotation = true.",tags:Fe,links:[Ke.auth]}),enable_manual_linking:b.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Fe,links:[Ke.auth]}),enable_signup:b.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Fe,links:[Ke.auth]}),enable_anonymous_sign_ins:b.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Fe,links:[Ke.auth]}),minimum_password_length:b.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Fe,links:[Ke.auth]}),password_requirements:b.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${If.join(", ")}`,enum:["",...If],tags:Fe,links:[Ke.auth]}),hook:kf,mfa:$f,sessions:Pf,email:Af,sms:Nf,external:Of}).partial();ie();var un={postgres:{name:"PostgreSQL configuration",link:"https://postgrest.org/en/stable/configuration.html"},pgbouncer:t=>({name:"PgBouncer Configuration",link:`https://www.pgbouncer.org/config.html${t?`#${t}`:""}`})},Ae=["database"],jf=b.object({driver:Mt(b.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite-postgres",description:"The database driver to use.",tags:Ae})),url:Mt(b.string({description:"Path to the database file/directory (Supalite only).",tags:Ae})),port:b.number({default:54322,description:"Port to use for the local database URL.",tags:Ae,links:[un.postgres]}),shadow_port:b.number({default:54320,description:"Port to use for the local shadow database.",tags:Ae}),major_version:b.number({default:15,description:"The database major version to use. This has to be the same as your remote database's. Run `SHOW server_version;` on the remote database to check.",tags:Ae,links:[un.postgres]}),pooler:b.object({enabled:b.boolean({default:false,description:"Enable the local PgBouncer service.",tags:Ae,links:[un.pgbouncer()]}),port:b.number({default:54329,description:"Port to use for the local connection pooler.",tags:Ae,links:[un.pgbouncer("listen_port")]}),pool_mode:b.string({enum:["transaction","session"],default:"transaction",description:"Specifies when a server connection can be reused by other clients. Configure one of the supported pooler modes: `transaction`, `session`.",tags:Ae,links:[un.pgbouncer("pool_mode")]}),default_pool_size:b.number({default:20,description:"How many server connections to allow per user/database pair.",tags:Ae,links:[un.pgbouncer("default_pool_size")]}),max_client_conn:b.number({default:100,description:"Maximum number of client connections allowed.",tags:Ae,links:[un.pgbouncer("max_client_conn")]})}).partial(),seed:b.strictObject({enabled:b.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:Ae}),sql_paths:b.array(b.string({description:"Path to a SQL file to seed the database with.",tags:Ae}),{default:["./seed.sql"],description:"Paths to SQL files to seed the database with. Supports glob patterns relative to supabase directory.",examples:[["./seeds/*.sql","../project-src/seeds/*-load-testing.sql"]],tags:Ae})}).partial(),migrations:b.strictObject({enabled:b.boolean({default:true,description:"Enable migrations.",tags:Ae}),schema_paths:b.array(b.string({description:"Path to a SQL file to seed the database with.",tags:Ae}),{default:["./schemas/schema.sql"]})}).partial()}).partial();ie();var qa=["edge-functions"],Lf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:qa}),policy:b.string({enum:["oneshot","per_worker"],default:"oneshot",description:"Configure the supported request policy. Use `oneshot` for hot reload, or `per_worker` for load testing.",tags:qa}),inspector_port:b.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:qa})}).partial();ie();var Ur=["experimental"],Ff=b.strictObject({orioledb_version:b.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Ur}),s3_host:St({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Ur}),s3_region:St({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Ur}),s3_access_key:St({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Ur}),s3_secret_key:St({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Ur})}).partial();ie();var Ci=["functions"],Ti=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],_w=Un({enabled:Lr({default:true,description:Le`
|
|
43
43
|
Controls whether a function is deployed or served. When set to false,
|
|
44
44
|
the function will be skipped during deployment and won't be served locally.
|
|
45
45
|
This is useful for disabling demo functions or temporarily disabling a function
|
|
@@ -48,15 +48,15 @@ ${s}`)}return t}ie();var xf=[{name:"Self-hosted Logflare Configuration",link:"ht
|
|
|
48
48
|
By default, when you deploy your Edge Functions or serve them locally, it
|
|
49
49
|
will reject requests without a valid JWT in the Authorization header.
|
|
50
50
|
Setting this configuration changes the default behavior.
|
|
51
|
-
`,tags:Ci,links:Ti}),import_map:
|
|
51
|
+
`,tags:Ci,links:Ti}),import_map:an({description:Le`
|
|
52
52
|
Specify the Deno import map file to use for the Function.
|
|
53
53
|
|
|
54
54
|
Note that the \`--import-map\` flag overrides this configuration.
|
|
55
|
-
`,tags:Ci,links:Ti}),entrypoint:
|
|
55
|
+
`,tags:Ci,links:Ti}),entrypoint:an({description:Le`
|
|
56
56
|
Specify the entrypoint path to the Function (defaults to "functions/slug/index.ts").
|
|
57
57
|
|
|
58
58
|
Both \`.js\` and \`.ts\` file extensions are supported.
|
|
59
|
-
`,tags:Ci,links:Ti})}).partial(),
|
|
59
|
+
`,tags:Ci,links:Ti})}).partial(),Mf=Un({},{patternProperties:{"^[a-zA-Z0-9_-]+$":_w}});ie();var vi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],Ai=["local"],Uf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local InBucket service.",tags:Ai,links:vi}),port:b.number({default:54324,description:Le`
|
|
60
60
|
Port to use for the email testing server web interface.
|
|
61
61
|
|
|
62
62
|
Emails sent with the local dev setup are not actually sent - rather, they are monitored, and you can view the emails that would have been sent from the web interface.
|
|
@@ -72,21 +72,21 @@ ${s}`)}return t}ie();var xf=[{name:"Self-hosted Logflare Configuration",link:"ht
|
|
|
72
72
|
Emails sent with the local dev setup are not actually sent - rather, they are monitored, and you can view the emails that would have been sent from the web interface.
|
|
73
73
|
|
|
74
74
|
If set, you can access the POP3 server from this port.
|
|
75
|
-
`,tags:Ai,links:vi})}).partial();ie();var bw=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],Ha=["realtime"],Mf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Realtime service.",tags:Ha,links:bw}),ip_version:b.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:Ha,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:b.number({default:4096,description:"Maximum length of the HTTP header.",tags:Ha})}).partial();ie();var ki=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Bt=["storage"],ww=b.strictObject({public:b.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:b.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Bt,links:ki}),allowed_mime_types:b.array(b.string({description:"A MIME type allowed for the bucket.",tags:Bt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Bt}),objects_path:b.string({description:"The path to the objects in the bucket.",tags:Bt})}).partial(),Uf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Storage service.",tags:Bt,links:ki}),file_size_limit:b.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Bt,links:ki}),image_transformation:b.strictObject({enabled:b.boolean({default:true,description:"Enable image transformation.",tags:Bt,links:ki})}).partial(),buckets:b.record(ww,{description:"Storage buckets configuration.",tags:Bt})}).partial();ie();var Wa={studio:{name:"Supabase Studio",link:"https://supabase.com/docs/guides/studio"},config:{name:"Supabase Studio Configuration",link:"https://supabase.com/docs/guides/self-hosting/studio"}},$i=["studio"],Bf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:$i,links:[Wa.studio]}),port:b.number({default:54323,description:"Port to use for Supabase Studio.",tags:$i}),api_url:b.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:$i,links:[Wa.config]}),openai_api_key:wt({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:$i,links:[Wa.config]})}).partial();var Oi=Un({project_id:on({description:"A string used to distinguish different Supabase projects on the same host. Defaults to the working directory name when running `supabase init`.",tags:["general"]}),analytics:Rf,api:Cf,auth:Nf,db:If,edge_runtime:Df,functions:Lf,inbucket:Ff,realtime:Mf,storage:Uf,studio:Bf,experimental:jf}).partial();var Ka=(t,e,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(t[a]?(u=t[a][0][0],r.req.routeIndex=a):u=a===t.length&&s||void 0,u)try{l=await u(r,()=>o(a+1));}catch(f){if(f instanceof Error&&e)r.error=f,l=await e(f,r),c=true;else throw f}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var Pi=class extends Error{res;status;constructor(t=500,e){super(e?.message,{cause:e?.cause}),this.res=e?.res,this.status=t;}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};var qf=Symbol();var Hf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof Ni?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Sw(t,{all:n,dot:r}):{}};async function Sw(t,e){let n=await t.formData();return n?_w(n,e):{}}function _w(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?Ew(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(xw(n,r,s),delete n[r]);}),n}var Ew=(t,e,n)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:e.endsWith("[]")?t[e]=[n]:t[e]=n;},xw=(t,e,n)=>{let r=t,s=e.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};var za=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Wf=t=>{let{groups:e,path:n}=Rw(t),r=za(n);return Cw(r,e)},Rw=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},Cw=(t,e)=>{for(let n=e.length-1;n>=0;n--){let[r]=e[n];for(let s=t.length-1;s>=0;s--)if(t[s].includes(r)){t[s]=t[s].replace(r,e[n][1]);break}}return t},Ii={},Kf=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return Ii[r]||(n[2]?Ii[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:Ii[r]=[t,n[1],true]),Ii[r]}return null},qn=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},Tw=t=>qn(t,decodeURI),Ga=t=>{let e=t.url,n=e.indexOf("/",e.indexOf(":")+4),r=n;for(;r<e.length;r++){let s=e.charCodeAt(r);if(s===37){let i=e.indexOf("?",r),o=e.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=e.slice(n,a);return Tw(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var Jf=t=>{let e=Ga(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},un=(t,e,...n)=>(n.length&&(e=un(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Di=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),n=[],r="";return e.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},Ja=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?qn(t,Br):t):t,zf=(t,e,n)=>{let r;if(!n&&e&&!/[%+]/.test(e)){let o=t.indexOf("?",8);if(o===-1)return;for(t.startsWith(e,o+1)||(o=t.indexOf(`&${e}`,o+1));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let l=o+e.length+2,c=t.indexOf("&",l);return Ja(t.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=t.indexOf(`&${e}`,o+1);}if(r=/[%+]/.test(t),!r)return}let s={};r??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let o=t.indexOf("&",i+1),a=t.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=t.slice(i+1,a===-1?o===-1?void 0:o:a);if(r&&(l=Ja(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=Ja(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},Gf=zf,Vf=(t,e)=>zf(t,e,true),Br=decodeURIComponent;var Qf=t=>qn(t,Br),Ni=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#t=n,this.#e={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#t[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?Qf(n):n}#i(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?Qf(r):r);}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Gf(this.url,t)}queries(t){return Vf(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((n,r)=>{e[r]=n;}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Hf(this,t)}#s=t=>{let{bodyCache:e,raw:n}=this,r=e[t];if(r)return r;let s=Object.keys(e)[0];return s?e[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[t]())):e[t]=n[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#e[t]=e;}valid(t){return this.#e[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[qf](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,t]])=>t)}get routePath(){return this.#t[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ye={Stringify:1},Y=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},vw=/[&<>'"]/,ji=async(t,e)=>{let n="";e||=[];let r=await Promise.all(t);for(let s=r.length-1;n+=r[s],s--,!(s<0);s--){let i=r[s];typeof i=="object"&&e.push(...i.callbacks||[]);let o=i.isEscaped;if(i=await(typeof i=="object"?i.toString():i),typeof i=="object"&&e.push(...i.callbacks||[]),i.isEscaped??o)n+=i;else {let a=[n];St(i,a),n=a[0];}}return Y(n,e)},St=(t,e)=>{let n=t.search(vw);if(n===-1){e[0]+=t;return}let r,s,i=0;for(s=n;s<t.length;s++){switch(t.charCodeAt(s)){case 34:r=""";break;case 39:r="'";break;case 38:r="&";break;case 60:r="<";break;case 62:r=">";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},Va=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:Ye.Stringify,buffer:n,context:r})),n[0]},fn=async(t,e,n,r,s)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let i=t.callbacks;if(!i?.length)return Promise.resolve(t);s?s[0]+=t:s=[t];let o=Promise.all(i.map(a=>a({phase:e,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>fn(l,e,false,r,s))).then(()=>s[0]));return n?Y(await o,i):o};var Aw="text/plain; charset=UTF-8",Qa=(t,e)=>({"Content-Type":t,...e}),qr=(t,e)=>new Response(t,e),Yf=class{#e;#t;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#p;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#p=e.path,this.#f=e.matchResult);}get req(){return this.#t??=new Ni(this.#e,this.#p,this.#f),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=qr(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=qr(t.body,t);for(let[e,n]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let s of r)t.headers.append("set-cookie",s);}else t.headers.set(e,n);}this.#s=t,this.finalized=true;}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#l=t;};header=(t,e,n)=>{this.finalized&&(this.#s=qr(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):n?.append?r.append(t,e):r.set(t,e);};status=t=>{this.#i=t;};set=(t,e)=>{this.#n??=new Map,this.#n.set(t,e);};get=t=>this.#n?this.#n.get(t):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(t,e,n){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof e=="number"?e:e?.status??this.#i;return qr(t,{status:s,headers:r})}newResponse=(...t)=>this.#o(...t);body=(t,e,n)=>this.#o(t,e,n);text=(t,e,n)=>!this.#a&&!this.#i&&!e&&!n&&!this.finalized?new Response(t):this.#o(t,e,Qa(Aw,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,Qa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,Qa("text/html; charset=UTF-8",n));return typeof t=="object"?fn(t,Ye.Stringify,false,{}).then(r):r(t)};redirect=(t,e)=>{let n=String(t);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,e??302)};notFound=()=>(this.#c??=()=>qr(),this.#c(this))};var re="ALL",Xf="all",Zf=["get","post","put","delete","options","patch"],Li="Can not add a route since the matcher is already built.",Fi=class extends Error{};var ep="__COMPOSED_HANDLER";var kw=t=>t.text("404 Not Found",404),tp=(t,e)=>{if("getResponse"in t){let n=t.getResponse();return e.newResponse(n.body,n)}return console.error(t),e.text("Internal Server Error",500)},np=class rp{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...Zf,Xf].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(re,this.#e,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??Ga:Jf;}#t(){let e=new rp({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=kw;errorHandler=tp;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===tp?i=s.handler:(i=async(o,a)=>(await Ka([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[ep]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#t();return n._basePath=un(this._basePath,e),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=un(this._basePath,e),c=l==="/"?0:l.length;return u=>{let f=new URL(u.url);return f.pathname=f.pathname.slice(c)||"/",new Request(f,u)}})();let a=async(l,c)=>{let u=await n(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(re,un(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=un(this._basePath,n);let s={basePath:this._basePath,path:n,method:e,handler:r};this.router.add(e,n,[r,s]),this.routes.push(s);}#r(e,n){if(e instanceof Error)return this.errorHandler(e,n);throw e}#s(e,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#s(e,n,r,"GET")))();let i=this.getPath(e,{env:r}),o=this.router.match(s,i),a=new Yf(e,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(u){return this.#r(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#n(a))).catch(u=>this.#r(u,a)):c??this.#n(a)}let l=Ka(o[0],this.errorHandler,this.#n);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#r(c,a)}})()}fetch=(e,...n)=>this.#s(e,n[1],n[0],e.method);request=(e,n,r,s)=>e instanceof Request?this.fetch(n?new Request(e,n):e,r,s):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${un("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var Mi=[];function Ya(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[re],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],Mi];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ui="[^/]+",Hr=".*",Wr="(?:|/.*)",pn=Symbol(),$w=new Set(".\\+*[^]$()");function Ow(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Hr||t===Wr?1:e===Hr||e===Wr?-1:t===Ui?1:e===Ui?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var sp=class Xa{#e;#t;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#e!==void 0)throw pn;if(i)return;this.#e=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",Hr]:["","",Ui]:o==="/*"?["","",Wr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],f=l[2]||Ui;if(u&&l[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))))throw pn;if(c=this.#n[f],!c){if(Object.keys(this.#n).some(p=>p!==Hr&&p!==Wr))throw pn;if(i)return;c=this.#n[f]=new Xa,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&r.push([u,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(u=>u.length>1&&u!==Hr&&u!==Wr))throw pn;if(i)return;c=this.#n[o]=new Xa;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Ow).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:$w.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#e=="number"&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var ip=class{#e={varIndex:0};#t=new sp;insert(t,e,n){let r=[],s=[];for(let o=0;;){let a=false;if(t=t.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,e,r,this.#e,n),r}buildRegExp(){let t=this.#t.buildRegExpStr();if(t==="")return [/^$/,[],[]];let e=0,n=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++e]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++e),"")),[new RegExp(`^${t}`),n,r]}};var Pw=[/^$/,[],Object.create(null)],op=Object.create(null);function ap(t){return op[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Nw(){op=Object.create(null);}function Iw(t){let e=new ip,n=[];if(t.length===0)return Pw;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[f,p])=>c?1:f?-1:u.length-p.length),s=Object.create(null);for(let c=0,u=-1,f=r.length;c<f;c++){let[p,d,y]=r[c];p?s[d]=[y.map(([h])=>[h,Object.create(null)]),Mi]:u++;let m;try{m=e.insert(d,u,p);}catch(h){throw h===pn?new Fi(d):h}p||(n[u]=y.map(([h,g])=>{let S=Object.create(null);for(g-=1;g>=0;g--){let[_,w]=m[g];S[_]=w;}return [h,S]}));}let[i,o,a]=e.buildRegExp();for(let c=0,u=n.length;c<u;c++)for(let f=0,p=n[c].length;f<p;f++){let d=n[c][f]?.[1];if(!d)continue;let y=Object.keys(d);for(let m=0,h=y.length;m<h;m++)d[y[m]]=a[d[y[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Hn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(ap(n).test(e))return [...t[n]]}}var Bi=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[re]:Object.create(null)},this.#t={[re]:Object.create(null)};}add(t,e,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(Li);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[re]).forEach(l=>{a[t][l]=[...a[re][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=ap(e);t===re?Object.keys(r).forEach(l=>{r[l][e]||=Hn(r[l],e)||Hn(r[re],e)||[];}):r[t][e]||=Hn(r[t],e)||Hn(r[re],e)||[],Object.keys(r).forEach(l=>{(t===re||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===re||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=Di(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(t===re||t===u)&&(s[u][c]||=[...Hn(r[u],c)||Hn(r[re],c)||[]],s[u][c].push([n,i-l+a+1]));});}}match=Ya;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#n(e);}),this.#e=this.#t=void 0,Nw(),t}#n(t){let e=[],n=t===re;return [this.#e,this.#t].forEach(r=>{let s=r[t]?Object.keys(r[t]).map(i=>[i,r[t][i]]):[];s.length!==0?(n||=true,e.push(...s)):t!==re&&e.push(...Object.keys(r[re]).map(i=>[i,r[re][i]]));}),n?Iw(e):null}};var Za=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers;}add(t,e,n){if(!this.#t)throw new Error(Li);this.#t.push([t,e,n]);}match(t,e){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(t,e);}catch(l){if(l instanceof Fi)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var Kr=Object.create(null),Dw=t=>{for(let e in t)return true;return false},lp=class cp{#e;#t;#n;#i=0;#r=Kr;constructor(e,n,r){if(this.#t=r||Object.create(null),this.#e=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#e=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=Wf(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],f=Kf(c,u),p=Array.isArray(f)?f[0]:c;if(p in s.#t){s=s.#t[p],f&&o.push(f[1]);continue}s.#t[p]=new cp,f&&(s.#n.push(f),o.push(f[1])),s=s.#t[p];}return s.#e.push({[e]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#s(e,n,r,s,i){for(let o=0,a=n.#e.length;o<a;o++){let l=n.#e[o],c=l[r]||l[re],u={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Kr||i&&i!==Kr))for(let f=0,p=c.possibleKeys.length;f<p;f++){let d=c.possibleKeys[f],y=u[c.score];c.params[d]=i?.[d]&&!y?i[d]:s[d]??i?.[d],u[c.score]=true;}}}search(e,n){let r=[];this.#r=Kr;let i=[this],o=za(n),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let f=o[u],p=u===l-1,d=[];for(let m=0,h=i.length;m<h;m++){let g=i[m],S=g.#t[f];S&&(S.#r=g.#r,p?(S.#t["*"]&&this.#s(r,S.#t["*"],e,g.#r),this.#s(r,S,e,g.#r)):d.push(S));for(let _=0,w=g.#n.length;_<w;_++){let x=g.#n[_],E=g.#r===Kr?{}:{...g.#r};if(x==="*"){let v=g.#t["*"];v&&(this.#s(r,v,e,g.#r),v.#r=E,d.push(v));continue}let[R,O,P]=x;if(!f&&!(P instanceof RegExp))continue;let D=g.#t[R];if(P instanceof RegExp){if(c===null){c=new Array(l);let q=n[0]==="/"?1:0;for(let K=0;K<l;K++)c[K]=q,q+=o[K].length+1;}let v=n.substring(c[u]),C=P.exec(v);if(C){if(E[O]=C[0],this.#s(r,D,e,g.#r,E),Dw(D.#t)){D.#r=E;let q=C[0].match(/\//)?.length??0;(a[q]||=[]).push(D);}continue}}(P===true||P.test(f))&&(E[O]=f,p?(this.#s(r,D,e,E,g.#r),D.#t["*"]&&this.#s(r,D.#t["*"],e,E,g.#r)):(D.#r=E,d.push(D)));}}let y=a.shift();i=y?d.concat(y):d;}return r.length>1&&r.sort((u,f)=>u.score-f.score),[r.map(({handler:u,params:f})=>[u,f])]}};var el=class{name="TrieRouter";#e;constructor(){this.#e=new lp;}add(t,e,n){let r=Di(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#e.insert(t,r[s],n);return}this.#e.insert(t,e,n);}match(t,e){return this.#e.search(t,e)}};var _e=class extends np{constructor(t={}){super(t),this.router=t.router??new Za({routers:[new Bi,new el]});}};var up=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(u,f){o.res.headers.set(u,f);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let u=await s(o.req.header("origin")||"",o);u.length&&l("Access-Control-Allow-Methods",u.join(","));let f=n.allowHeaders;if(!f?.length){let p=o.req.header("Access-Control-Request-Headers");p&&(f=p.split(/\s*,\s*/));}return f?.length&&(l("Access-Control-Allow-Headers",f.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};var Lw=t=>JSON.parse(jsonStringify(t)),fp=new _e().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(t.var.app.config)).get("/info",t=>t.json(Lw({connection:t.var.app.connection.config,config:t.var.app.config}))).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var ke=class extends Error{code;details;hint;httpStatus;constructor(e){super(e.message),this.name="EmbedError",this.code=e.code,this.details=e.details,this.hint=e.hint,this.httpStatus=e.httpStatus;}},Je=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},qt=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},Wn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},Kn=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},pe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var Fw="/rest/v1";function tl(t,e=Fw){let n=new URL(t.url),r=decodeURIComponent(n.pathname);r.startsWith(e)&&(r=r.slice(e.length)),r=r.replace(/^\/+|\/+$/g,"");let s=r.split("/");if(s[0]==="rpc"&&s[1])return {function:s[1],isRpc:true};if(s.length>1)throw new Wn;return {from:s[0]||void 0,isRpc:false}}function nl(t){let e=t.method.toUpperCase(),n;e==="GET"||e==="HEAD"?n=t.headers.get("Accept-Profile")??void 0:n=t.headers.get("Content-Profile")??void 0;let r=[],s=[],i=t.headers.get("Prefer");i&&s.push(i);for(let a of s){let l=a.split(",").map(c=>c.trim()).filter(Boolean);for(let c of l){let u=c.indexOf("=");if(u===-1)continue;let f=c.slice(0,u).trim(),p=c.slice(u+1).trim();f==="max-affected"?r.push({key:"max-affected",value:Number(p)}):r.push({key:f,value:p});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var pp=new Set(["count","sum","avg","min","max"]);function W(t){return t.input[t.pos]??""}function H(t,e=1){t.pos+=e;}function Oe(t){return t.pos>=t.input.length}function $e(t,e){return t.input.startsWith(e,t.pos)}function sl(t){return /^[a-zA-Z0-9_]$/.test(t)}function z(t){for(;!Oe(t)&&/\s/.test(W(t));)H(t);}function ol(t){let n=new URL(t.url).searchParams.get("select");if(n==null)return {select:[],join:{},embeddedAliases:new Set};if(n==="")return {select:[],join:{},embeddedAliases:new Set};if(n.trim()==="")throw new Je("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=gp(i,r,s);if(z(i),Mw(i),!Oe(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(Uw(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function Mw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;W(t)==="'";)H(t);t.pos!==n&&z(t);}function Uw(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(Bw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function Bw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function gp(t,e,n){let r=[];if(z(t),Oe(t)||W(t)===")"||W(t)===","&&(H(t),z(t),Oe(t)||W(t)===")"))return r;for(r.push(dp(t,e,n));!Oe(t)&&(z(t),W(t)===",");)H(t),z(t),r.push(dp(t,e,n));return r}function dp(t,e,n){if(z(t),W(t)==="*")return H(t),Kw(t),$e(t,".count()")&&H(t,8),"*";if($e(t,"..."))return H(t,3),z(t),qw(t,e,n);let r=Xe(t,{allowSpaces:true,allowDollar:true});return z(t),$e(t,"::")?il(r,void 0,t,e,n):W(t)===":"?(H(t),z(t),Hw(r,t,e,n)):il(r,void 0,t,e,n)}function qw(t,e,n){let r=Xe(t);z(t);let{hint:s,innerJoin:i}=yp(t);if(z(t),W(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=bp(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let u={spread:true,select:o};return Object.keys(a).length>0&&(u.join=a),{[l]:u}}function Hw(t,e,n,r){let s=Xe(e,{allowSpaces:true,allowDollar:true});return z(e),il(s,t,e,n,r)}function il(t,e,n,r,s){return z(n),t==="count"&&(Oe(n)||W(n)===","||W(n)===")"||W(n)==="("||$e(n,"::"))?zw(e,n):W(n)==="!"||W(n)==="("?Ww(t,e,n,r,s):Gw(t,e,n)}function Ww(t,e,n,r,s){let{hint:i,innerJoin:o}=yp(n);if(z(n),W(n)!=="(")throw new Je("failed to parse select parameter");let{subSelect:a,subJoin:l}=bp(n),c=e??t,u={};e&&(u.from=t),o&&(u.type="inner"),i&&(u.hint=i),r[c]=u,s.add(c),e&&t!==c&&s.add(t);let f={select:a};return Object.keys(l).length>0&&(f.join=l),{[c]:f}}function yp(t){if(z(t),W(t)!=="!")return {};H(t);let e=Xe(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(z(t),W(t)==="!"){H(t);let r=Xe(t);if(r==="inner")return {hint:n,innerJoin:true};if(r==="left")return {hint:n};throw new Error(`Expected "inner" or "left" after hint, got "${r}" at position ${t.pos}`)}return {hint:n}}function Kw(t){for(;W(t)==="*";)H(t);for(;W(t)==="!";){let e=t.pos;if(H(t),!Jw(t)){t.pos=e;return}}}function Jw(t){let e=t.pos;try{return Xe(t),!0}catch{return t.pos=e,false}}function bp(t,e,n){if(W(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);H(t),z(t);let r={},s=new Set;if(W(t)===")")return H(t),{subSelect:[],subJoin:r};let i=gp(t,r,s);if(z(t),W(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return H(t),{subSelect:i,subJoin:r}}function zw(t,e){z(e);let n=true;if(W(e)==="("){n=false,H(e);let o=e.pos;for(;!Oe(e)&&W(e)!==")";)H(e);if(Oe(e))throw new Je("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(H(e),a!=="")throw new Je("expected null arg for count()")}z(e);let r;$e(e,"::")&&(H(e,2),r=zr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function Gw(t,e,n){z(n);let r,s,i=false,o;if($e(n,"->")){let{path:u,lastProp:f,lastIsText:p,invalidTextTraversalKey:d}=Vw(n);r=u,s=f||void 0,i=p,o=d;}z(n);let a,l;if($e(n,"::")){H(n,2);let u=zr(n);if(z(n),W(n)==="."&&!Oe(n)){let f=n.input[n.pos+1]??"";if(sl(f)){let p=n.pos;H(n);let d=Xe(n);if(pp.has(d)&&$e(n,"()"))return a=u,H(n,2),z(n),$e(n,"::")&&(H(n,2),l=zr(n),rl(n)),mp(t,e,r,s,i,o,a,d,l);n.pos=p;}}l=u,rl(n);}let c;if(W(n)==="."&&!Oe(n)){let u=n.input[n.pos+1]??"";if(sl(u)){let f=n.pos;H(n);let p=Xe(n);pp.has(p)&&$e(n,"()")?(c=p,H(n,2),z(n),$e(n,"::")&&(H(n,2),l=zr(n),rl(n))):n.pos=f;}}return mp(t,e,r,s,i,o,a,c,l)}function rl(t){for(z(t);$e(t,"::");)H(t,2),zr(t),z(t);}function zr(t){z(t);let e=[Xe(t)];for(;!Oe(t);){let n=t.pos;if(z(t),t.pos===n)break;let r=W(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(Xe(t));}return e.join(" ")}function mp(t,e,n,r,s,i,o,a,l){let c=e??(a||void 0)??r;if(!c&&!o&&!l&&!a&&!n)return t;let u=c??t,f={};return t!==u&&(f.column=t),a&&!f.column&&t===u&&(f.column=t),n&&(f.column||(f.column=t),f.path=n,s&&(f.pathText=true),i&&(f.invalidJsonTextTraversalKey=i)),o&&(f.preCast=o),a&&(f.aggregate=a),l&&(f.cast=l),{[u]:f}}function Vw(t){let e=[],n="",r=false,s;for(;$e(t,"->");){let o=r;H(t,2);let a=false;W(t)===">"&&(H(t),a=true);let l=Qw(t);e.push(l),o&&s===void 0&&(s=l),/^-?\d+$/.test(l)||(n=l),r=a;}return {path:"$."+e.join("."),lastProp:n,lastIsText:r,invalidTextTraversalKey:s}}function Qw(t){return Yw(t)}var hp=new Set(["(",".",">","<"]);function Jr(t,e,n){throw new Je(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function Yw(t){z(t);let e=t.pos;if(W(t)==='"')return Xe(t);let n="";for(;!Oe(t)&&!($e(t,"->")||$e(t,"::"));){let s=W(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,H(t);}n===""&&Jr(t,e+1,"unexpected end of input");let r=n[0]??"";hp.has(r)&&Jr(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];hp.has(i)&&Jr(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;Jr(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&Jr(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new Je("failed to parse select parameter");return n}function Xe(t,e={}){if(z(t),W(t)==='"'){H(t);let r="";for(;!Oe(t)&&W(t)!=='"';)r+=W(t),H(t);if(Oe(t))throw new Error(`Missing closing quote at position ${t.pos}`);return H(t),r}let n="";for(;!Oe(t);){let r=W(t);if(sl(r))n+=r,H(t);else if(e.allowDollar&&r==="$")n+=r,H(t);else if(e.allowSpaces&&r===" ")n+=r,H(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,H(t);}else break}if(e.allowSpaces&&(n=n.trimEnd()),n==="")throw new Error(`Expected identifier at position ${t.pos}`);if(n.includes("--")||n.endsWith("-"))throw new Je("failed to parse select parameter");return n}var Xw=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function Zw(t){return t.split(";")[0]?.trim().toLowerCase()??""}var Gr=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function al(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=Zw(r);if(!n&&r.includes("text/csv"))throw new Jn('parse error (not enough input) at ""');if(!n)return {};if(s&&!Xw.has(s))throw new Gr(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:eS(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function eS(t){let e=t.replace(/\r\n/g,`
|
|
75
|
+
`,tags:Ai,links:vi})}).partial();ie();var Ew=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],Ha=["realtime"],Bf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Realtime service.",tags:Ha,links:Ew}),ip_version:b.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:Ha,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:b.number({default:4096,description:"Maximum length of the HTTP header.",tags:Ha})}).partial();ie();var ki=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],qt=["storage"],xw=b.strictObject({public:b.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:b.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:qt,links:ki}),allowed_mime_types:b.array(b.string({description:"A MIME type allowed for the bucket.",tags:qt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:qt}),objects_path:b.string({description:"The path to the objects in the bucket.",tags:qt})}).partial(),qf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Storage service.",tags:qt,links:ki}),file_size_limit:b.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:qt,links:ki}),image_transformation:b.strictObject({enabled:b.boolean({default:true,description:"Enable image transformation.",tags:qt,links:ki})}).partial(),buckets:b.record(xw,{description:"Storage buckets configuration.",tags:qt})}).partial();ie();var Wa={studio:{name:"Supabase Studio",link:"https://supabase.com/docs/guides/studio"},config:{name:"Supabase Studio Configuration",link:"https://supabase.com/docs/guides/self-hosting/studio"}},$i=["studio"],Hf=b.strictObject({enabled:b.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:$i,links:[Wa.studio]}),port:b.number({default:54323,description:"Port to use for Supabase Studio.",tags:$i}),api_url:b.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:$i,links:[Wa.config]}),openai_api_key:St({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:$i,links:[Wa.config]})}).partial();var Oi=Un({project_id:an({description:"A string used to distinguish different Supabase projects on the same host. Defaults to the working directory name when running `supabase init`.",tags:["general"]}),analytics:Tf,api:vf,auth:Df,db:jf,edge_runtime:Lf,functions:Mf,inbucket:Uf,realtime:Bf,storage:qf,studio:Hf,experimental:Ff}).partial();var Ka=(t,e,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(t[a]?(u=t[a][0][0],r.req.routeIndex=a):u=a===t.length&&s||void 0,u)try{l=await u(r,()=>o(a+1));}catch(f){if(f instanceof Error&&e)r.error=f,l=await e(f,r),c=true;else throw f}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var Pi=class extends Error{res;status;constructor(t=500,e){super(e?.message,{cause:e?.cause}),this.res=e?.res,this.status=t;}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};var Wf=Symbol();var Kf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof Ni?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Rw(t,{all:n,dot:r}):{}};async function Rw(t,e){let n=await t.formData();return n?Cw(n,e):{}}function Cw(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?Tw(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(vw(n,r,s),delete n[r]);}),n}var Tw=(t,e,n)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:e.endsWith("[]")?t[e]=[n]:t[e]=n;},vw=(t,e,n)=>{let r=t,s=e.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};var za=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Jf=t=>{let{groups:e,path:n}=Aw(t),r=za(n);return kw(r,e)},Aw=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},kw=(t,e)=>{for(let n=e.length-1;n>=0;n--){let[r]=e[n];for(let s=t.length-1;s>=0;s--)if(t[s].includes(r)){t[s]=t[s].replace(r,e[n][1]);break}}return t},Ii={},zf=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return Ii[r]||(n[2]?Ii[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:Ii[r]=[t,n[1],true]),Ii[r]}return null},qn=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},$w=t=>qn(t,decodeURI),Ga=t=>{let e=t.url,n=e.indexOf("/",e.indexOf(":")+4),r=n;for(;r<e.length;r++){let s=e.charCodeAt(r);if(s===37){let i=e.indexOf("?",r),o=e.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=e.slice(n,a);return $w(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var Gf=t=>{let e=Ga(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},fn=(t,e,...n)=>(n.length&&(e=fn(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Di=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),n=[],r="";return e.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},Ja=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?qn(t,Br):t):t,Vf=(t,e,n)=>{let r;if(!n&&e&&!/[%+]/.test(e)){let o=t.indexOf("?",8);if(o===-1)return;for(t.startsWith(e,o+1)||(o=t.indexOf(`&${e}`,o+1));o!==-1;){let a=t.charCodeAt(o+e.length+1);if(a===61){let l=o+e.length+2,c=t.indexOf("&",l);return Ja(t.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=t.indexOf(`&${e}`,o+1);}if(r=/[%+]/.test(t),!r)return}let s={};r??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let o=t.indexOf("&",i+1),a=t.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=t.slice(i+1,a===-1?o===-1?void 0:o:a);if(r&&(l=Ja(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=Ja(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},Qf=Vf,Yf=(t,e)=>Vf(t,e,true),Br=decodeURIComponent;var Xf=t=>qn(t,Br),Ni=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#t=n,this.#e={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#t[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?Xf(n):n}#i(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?Xf(r):r);}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Qf(this.url,t)}queries(t){return Yf(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((n,r)=>{e[r]=n;}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Kf(this,t)}#s=t=>{let{bodyCache:e,raw:n}=this,r=e[t];if(r)return r;let s=Object.keys(e)[0];return s?e[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[t]())):e[t]=n[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#e[t]=e;}valid(t){return this.#e[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Wf](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,t]])=>t)}get routePath(){return this.#t[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ye={Stringify:1},Y=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},Ow=/[&<>'"]/,ji=async(t,e)=>{let n="";e||=[];let r=await Promise.all(t);for(let s=r.length-1;n+=r[s],s--,!(s<0);s--){let i=r[s];typeof i=="object"&&e.push(...i.callbacks||[]);let o=i.isEscaped;if(i=await(typeof i=="object"?i.toString():i),typeof i=="object"&&e.push(...i.callbacks||[]),i.isEscaped??o)n+=i;else {let a=[n];_t(i,a),n=a[0];}}return Y(n,e)},_t=(t,e)=>{let n=t.search(Ow);if(n===-1){e[0]+=t;return}let r,s,i=0;for(s=n;s<t.length;s++){switch(t.charCodeAt(s)){case 34:r=""";break;case 39:r="'";break;case 38:r="&";break;case 60:r="<";break;case 62:r=">";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},Va=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:Ye.Stringify,buffer:n,context:r})),n[0]},pn=async(t,e,n,r,s)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let i=t.callbacks;if(!i?.length)return Promise.resolve(t);s?s[0]+=t:s=[t];let o=Promise.all(i.map(a=>a({phase:e,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(l=>pn(l,e,false,r,s))).then(()=>s[0]));return n?Y(await o,i):o};var Pw="text/plain; charset=UTF-8",Qa=(t,e)=>({"Content-Type":t,...e}),qr=(t,e)=>new Response(t,e),Zf=class{#e;#t;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#p;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#p=e.path,this.#f=e.matchResult);}get req(){return this.#t??=new Ni(this.#e,this.#p,this.#f),this.#t}get event(){if(this.#r&&"respondWith"in this.#r)return this.#r;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#r)return this.#r;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=qr(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=qr(t.body,t);for(let[e,n]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let s of r)t.headers.append("set-cookie",s);}else t.headers.set(e,n);}this.#s=t,this.finalized=true;}render=(...t)=>(this.#l??=e=>this.html(e),this.#l(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#l=t;};header=(t,e,n)=>{this.finalized&&(this.#s=qr(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):n?.append?r.append(t,e):r.set(t,e);};status=t=>{this.#i=t;};set=(t,e)=>{this.#n??=new Map,this.#n.set(t,e);};get=t=>this.#n?this.#n.get(t):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(t,e,n){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let i=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof e=="number"?e:e?.status??this.#i;return qr(t,{status:s,headers:r})}newResponse=(...t)=>this.#o(...t);body=(t,e,n)=>this.#o(t,e,n);text=(t,e,n)=>!this.#a&&!this.#i&&!e&&!n&&!this.finalized?new Response(t):this.#o(t,e,Qa(Pw,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,Qa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,Qa("text/html; charset=UTF-8",n));return typeof t=="object"?pn(t,Ye.Stringify,false,{}).then(r):r(t)};redirect=(t,e)=>{let n=String(t);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,e??302)};notFound=()=>(this.#c??=()=>qr(),this.#c(this))};var re="ALL",ep="all",tp=["get","post","put","delete","options","patch"],Li="Can not add a route since the matcher is already built.",Fi=class extends Error{};var np="__COMPOSED_HANDLER";var Nw=t=>t.text("404 Not Found",404),rp=(t,e)=>{if("getResponse"in t){let n=t.getResponse();return e.newResponse(n.body,n)}return console.error(t),e.text("Internal Server Error",500)},sp=class ip{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...tp,ep].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(re,this.#e,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??Ga:Gf;}#t(){let e=new ip({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=Nw;errorHandler=rp;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===rp?i=s.handler:(i=async(o,a)=>(await Ka([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[np]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#t();return n._basePath=fn(this._basePath,e),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=l=>l:s=r.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=fn(this._basePath,e),c=l==="/"?0:l.length;return u=>{let f=new URL(u.url);return f.pathname=f.pathname.slice(c)||"/",new Request(f,u)}})();let a=async(l,c)=>{let u=await n(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(re,fn(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=fn(this._basePath,n);let s={basePath:this._basePath,path:n,method:e,handler:r};this.router.add(e,n,[r,s]),this.routes.push(s);}#r(e,n){if(e instanceof Error)return this.errorHandler(e,n);throw e}#s(e,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#s(e,n,r,"GET")))();let i=this.getPath(e,{env:r}),o=this.router.match(s,i),a=new Zf(e,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(u){return this.#r(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#n(a))).catch(u=>this.#r(u,a)):c??this.#n(a)}let l=Ka(o[0],this.errorHandler,this.#n);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#r(c,a)}})()}fetch=(e,...n)=>this.#s(e,n[1],n[0],e.method);request=(e,n,r,s)=>e instanceof Request?this.fetch(n?new Request(e,n):e,r,s):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${fn("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var Mi=[];function Ya(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[re],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],Mi];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ui="[^/]+",Hr=".*",Wr="(?:|/.*)",dn=Symbol(),Iw=new Set(".\\+*[^]$()");function Dw(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Hr||t===Wr?1:e===Hr||e===Wr?-1:t===Ui?1:e===Ui?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var op=class Xa{#e;#t;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#e!==void 0)throw dn;if(i)return;this.#e=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",Hr]:["","",Ui]:o==="/*"?["","",Wr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],f=l[2]||Ui;if(u&&l[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))))throw dn;if(c=this.#n[f],!c){if(Object.keys(this.#n).some(p=>p!==Hr&&p!==Wr))throw dn;if(i)return;c=this.#n[f]=new Xa,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&r.push([u,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(u=>u.length>1&&u!==Hr&&u!==Wr))throw dn;if(i)return;c=this.#n[o]=new Xa;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Dw).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:Iw.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#e=="number"&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var ap=class{#e={varIndex:0};#t=new op;insert(t,e,n){let r=[],s=[];for(let o=0;;){let a=false;if(t=t.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,e,r,this.#e,n),r}buildRegExp(){let t=this.#t.buildRegExpStr();if(t==="")return [/^$/,[],[]];let e=0,n=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++e]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++e),"")),[new RegExp(`^${t}`),n,r]}};var jw=[/^$/,[],Object.create(null)],lp=Object.create(null);function cp(t){return lp[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Lw(){lp=Object.create(null);}function Fw(t){let e=new ap,n=[];if(t.length===0)return jw;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[f,p])=>c?1:f?-1:u.length-p.length),s=Object.create(null);for(let c=0,u=-1,f=r.length;c<f;c++){let[p,d,g]=r[c];p?s[d]=[g.map(([h])=>[h,Object.create(null)]),Mi]:u++;let m;try{m=e.insert(d,u,p);}catch(h){throw h===dn?new Fi(d):h}p||(n[u]=g.map(([h,y])=>{let S=Object.create(null);for(y-=1;y>=0;y--){let[_,w]=m[y];S[_]=w;}return [h,S]}));}let[i,o,a]=e.buildRegExp();for(let c=0,u=n.length;c<u;c++)for(let f=0,p=n[c].length;f<p;f++){let d=n[c][f]?.[1];if(!d)continue;let g=Object.keys(d);for(let m=0,h=g.length;m<h;m++)d[g[m]]=a[d[g[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Hn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(cp(n).test(e))return [...t[n]]}}var Bi=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[re]:Object.create(null)},this.#t={[re]:Object.create(null)};}add(t,e,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(Li);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[re]).forEach(l=>{a[t][l]=[...a[re][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=cp(e);t===re?Object.keys(r).forEach(l=>{r[l][e]||=Hn(r[l],e)||Hn(r[re],e)||[];}):r[t][e]||=Hn(r[t],e)||Hn(r[re],e)||[],Object.keys(r).forEach(l=>{(t===re||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===re||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=Di(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(t===re||t===u)&&(s[u][c]||=[...Hn(r[u],c)||Hn(r[re],c)||[]],s[u][c].push([n,i-l+a+1]));});}}match=Ya;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#n(e);}),this.#e=this.#t=void 0,Lw(),t}#n(t){let e=[],n=t===re;return [this.#e,this.#t].forEach(r=>{let s=r[t]?Object.keys(r[t]).map(i=>[i,r[t][i]]):[];s.length!==0?(n||=true,e.push(...s)):t!==re&&e.push(...Object.keys(r[re]).map(i=>[i,r[re][i]]));}),n?Fw(e):null}};var Za=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers;}add(t,e,n){if(!this.#t)throw new Error(Li);this.#t.push([t,e,n]);}match(t,e){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let l=0,c=r.length;l<c;l++)a.add(...r[l]);o=a.match(t,e);}catch(l){if(l instanceof Fi)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var Kr=Object.create(null),Mw=t=>{for(let e in t)return true;return false},up=class fp{#e;#t;#n;#i=0;#r=Kr;constructor(e,n,r){if(this.#t=r||Object.create(null),this.#e=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#e=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=Jf(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],f=zf(c,u),p=Array.isArray(f)?f[0]:c;if(p in s.#t){s=s.#t[p],f&&o.push(f[1]);continue}s.#t[p]=new fp,f&&(s.#n.push(f),o.push(f[1])),s=s.#t[p];}return s.#e.push({[e]:{handler:r,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#s(e,n,r,s,i){for(let o=0,a=n.#e.length;o<a;o++){let l=n.#e[o],c=l[r]||l[re],u={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Kr||i&&i!==Kr))for(let f=0,p=c.possibleKeys.length;f<p;f++){let d=c.possibleKeys[f],g=u[c.score];c.params[d]=i?.[d]&&!g?i[d]:s[d]??i?.[d],u[c.score]=true;}}}search(e,n){let r=[];this.#r=Kr;let i=[this],o=za(n),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let f=o[u],p=u===l-1,d=[];for(let m=0,h=i.length;m<h;m++){let y=i[m],S=y.#t[f];S&&(S.#r=y.#r,p?(S.#t["*"]&&this.#s(r,S.#t["*"],e,y.#r),this.#s(r,S,e,y.#r)):d.push(S));for(let _=0,w=y.#n.length;_<w;_++){let x=y.#n[_],E=y.#r===Kr?{}:{...y.#r};if(x==="*"){let v=y.#t["*"];v&&(this.#s(r,v,e,y.#r),v.#r=E,d.push(v));continue}let[R,O,P]=x;if(!f&&!(P instanceof RegExp))continue;let D=y.#t[R];if(P instanceof RegExp){if(c===null){c=new Array(l);let q=n[0]==="/"?1:0;for(let K=0;K<l;K++)c[K]=q,q+=o[K].length+1;}let v=n.substring(c[u]),C=P.exec(v);if(C){if(E[O]=C[0],this.#s(r,D,e,y.#r,E),Mw(D.#t)){D.#r=E;let q=C[0].match(/\//)?.length??0;(a[q]||=[]).push(D);}continue}}(P===true||P.test(f))&&(E[O]=f,p?(this.#s(r,D,e,E,y.#r),D.#t["*"]&&this.#s(r,D.#t["*"],e,E,y.#r)):(D.#r=E,d.push(D)));}}let g=a.shift();i=g?d.concat(g):d;}return r.length>1&&r.sort((u,f)=>u.score-f.score),[r.map(({handler:u,params:f})=>[u,f])]}};var el=class{name="TrieRouter";#e;constructor(){this.#e=new up;}add(t,e,n){let r=Di(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#e.insert(t,r[s],n);return}this.#e.insert(t,e,n);}match(t,e){return this.#e.search(t,e)}};var _e=class extends sp{constructor(t={}){super(t),this.router=t.router??new Za({routers:[new Bi,new el]});}};var pp=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(u,f){o.res.headers.set(u,f);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let u=await s(o.req.header("origin")||"",o);u.length&&l("Access-Control-Allow-Methods",u.join(","));let f=n.allowHeaders;if(!f?.length){let p=o.req.header("Access-Control-Request-Headers");p&&(f=p.split(/\s*,\s*/));}return f?.length&&(l("Access-Control-Allow-Headers",f.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};var Bw=t=>JSON.parse(jsonStringify(t)),dp=new _e().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(t.var.app.config)).get("/info",t=>t.json(Bw({connection:t.var.app.connection.config,config:t.var.app.config}))).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var ke=class extends Error{code;details;hint;httpStatus;constructor(e){super(e.message),this.name="EmbedError",this.code=e.code,this.details=e.details,this.hint=e.hint,this.httpStatus=e.httpStatus;}},Je=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},Ht=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},Wn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},Kn=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},pe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var qw="/rest/v1";function tl(t,e=qw){let n=new URL(t.url),r=decodeURIComponent(n.pathname);r.startsWith(e)&&(r=r.slice(e.length)),r=r.replace(/^\/+|\/+$/g,"");let s=r.split("/");if(s[0]==="rpc"&&s[1])return {function:s[1],isRpc:true};if(s.length>1)throw new Wn;return {from:s[0]||void 0,isRpc:false}}function nl(t){let e=t.method.toUpperCase(),n;e==="GET"||e==="HEAD"?n=t.headers.get("Accept-Profile")??void 0:n=t.headers.get("Content-Profile")??void 0;let r=[],s=[],i=t.headers.get("Prefer");i&&s.push(i);for(let a of s){let l=a.split(",").map(c=>c.trim()).filter(Boolean);for(let c of l){let u=c.indexOf("=");if(u===-1)continue;let f=c.slice(0,u).trim(),p=c.slice(u+1).trim();f==="max-affected"?r.push({key:"max-affected",value:Number(p)}):r.push({key:f,value:p});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var mp=new Set(["count","sum","avg","min","max"]);function W(t){return t.input[t.pos]??""}function H(t,e=1){t.pos+=e;}function Oe(t){return t.pos>=t.input.length}function $e(t,e){return t.input.startsWith(e,t.pos)}function sl(t){return /^[a-zA-Z0-9_]$/.test(t)}function z(t){for(;!Oe(t)&&/\s/.test(W(t));)H(t);}function ol(t){let n=new URL(t.url).searchParams.get("select");if(n==null)return {select:[],join:{},embeddedAliases:new Set};if(n==="")return {select:[],join:{},embeddedAliases:new Set};if(n.trim()==="")throw new Je("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=bp(i,r,s);if(z(i),Hw(i),!Oe(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(Ww(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function Hw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;W(t)==="'";)H(t);t.pos!==n&&z(t);}function Ww(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(Kw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function Kw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function bp(t,e,n){let r=[];if(z(t),Oe(t)||W(t)===")"||W(t)===","&&(H(t),z(t),Oe(t)||W(t)===")"))return r;for(r.push(hp(t,e,n));!Oe(t)&&(z(t),W(t)===",");)H(t),z(t),r.push(hp(t,e,n));return r}function hp(t,e,n){if(z(t),W(t)==="*")return H(t),Vw(t),$e(t,".count()")&&H(t,8),"*";if($e(t,"..."))return H(t,3),z(t),Jw(t,e,n);let r=Xe(t,{allowSpaces:true,allowDollar:true});return z(t),$e(t,"::")?il(r,void 0,t,e,n):W(t)===":"?(H(t),z(t),zw(r,t,e,n)):il(r,void 0,t,e,n)}function Jw(t,e,n){let r=Xe(t);z(t);let{hint:s,innerJoin:i}=wp(t);if(z(t),W(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=Sp(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let u={spread:true,select:o};return Object.keys(a).length>0&&(u.join=a),{[l]:u}}function zw(t,e,n,r){let s=Xe(e,{allowSpaces:true,allowDollar:true});return z(e),il(s,t,e,n,r)}function il(t,e,n,r,s){return z(n),t==="count"&&(Oe(n)||W(n)===","||W(n)===")"||W(n)==="("||$e(n,"::"))?Yw(e,n):W(n)==="!"||W(n)==="("?Gw(t,e,n,r,s):Xw(t,e,n)}function Gw(t,e,n,r,s){let{hint:i,innerJoin:o}=wp(n);if(z(n),W(n)!=="(")throw new Je("failed to parse select parameter");let{subSelect:a,subJoin:l}=Sp(n),c=e??t,u={};e&&(u.from=t),o&&(u.type="inner"),i&&(u.hint=i),r[c]=u,s.add(c),e&&t!==c&&s.add(t);let f={select:a};return Object.keys(l).length>0&&(f.join=l),{[c]:f}}function wp(t){if(z(t),W(t)!=="!")return {};H(t);let e=Xe(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(z(t),W(t)==="!"){H(t);let r=Xe(t);if(r==="inner")return {hint:n,innerJoin:true};if(r==="left")return {hint:n};throw new Error(`Expected "inner" or "left" after hint, got "${r}" at position ${t.pos}`)}return {hint:n}}function Vw(t){for(;W(t)==="*";)H(t);for(;W(t)==="!";){let e=t.pos;if(H(t),!Qw(t)){t.pos=e;return}}}function Qw(t){let e=t.pos;try{return Xe(t),!0}catch{return t.pos=e,false}}function Sp(t,e,n){if(W(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);H(t),z(t);let r={},s=new Set;if(W(t)===")")return H(t),{subSelect:[],subJoin:r};let i=bp(t,r,s);if(z(t),W(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return H(t),{subSelect:i,subJoin:r}}function Yw(t,e){z(e);let n=true;if(W(e)==="("){n=false,H(e);let o=e.pos;for(;!Oe(e)&&W(e)!==")";)H(e);if(Oe(e))throw new Je("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(H(e),a!=="")throw new Je("expected null arg for count()")}z(e);let r;$e(e,"::")&&(H(e,2),r=zr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function Xw(t,e,n){z(n);let r,s,i=false,o;if($e(n,"->")){let{path:u,lastProp:f,lastIsText:p,invalidTextTraversalKey:d}=Zw(n);r=u,s=f||void 0,i=p,o=d;}z(n);let a,l;if($e(n,"::")){H(n,2);let u=zr(n);if(z(n),W(n)==="."&&!Oe(n)){let f=n.input[n.pos+1]??"";if(sl(f)){let p=n.pos;H(n);let d=Xe(n);if(mp.has(d)&&$e(n,"()"))return a=u,H(n,2),z(n),$e(n,"::")&&(H(n,2),l=zr(n),rl(n)),gp(t,e,r,s,i,o,a,d,l);n.pos=p;}}l=u,rl(n);}let c;if(W(n)==="."&&!Oe(n)){let u=n.input[n.pos+1]??"";if(sl(u)){let f=n.pos;H(n);let p=Xe(n);mp.has(p)&&$e(n,"()")?(c=p,H(n,2),z(n),$e(n,"::")&&(H(n,2),l=zr(n),rl(n))):n.pos=f;}}return gp(t,e,r,s,i,o,a,c,l)}function rl(t){for(z(t);$e(t,"::");)H(t,2),zr(t),z(t);}function zr(t){z(t);let e=[Xe(t)];for(;!Oe(t);){let n=t.pos;if(z(t),t.pos===n)break;let r=W(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(Xe(t));}return e.join(" ")}function gp(t,e,n,r,s,i,o,a,l){let c=e??(a||void 0)??r;if(!c&&!o&&!l&&!a&&!n)return t;let u=c??t,f={};return t!==u&&(f.column=t),a&&!f.column&&t===u&&(f.column=t),n&&(f.column||(f.column=t),f.path=n,s&&(f.pathText=true),i&&(f.invalidJsonTextTraversalKey=i)),o&&(f.preCast=o),a&&(f.aggregate=a),l&&(f.cast=l),{[u]:f}}function Zw(t){let e=[],n="",r=false,s;for(;$e(t,"->");){let o=r;H(t,2);let a=false;W(t)===">"&&(H(t),a=true);let l=eS(t);e.push(l),o&&s===void 0&&(s=l),/^-?\d+$/.test(l)||(n=l),r=a;}return {path:"$."+e.join("."),lastProp:n,lastIsText:r,invalidTextTraversalKey:s}}function eS(t){return tS(t)}var yp=new Set(["(",".",">","<"]);function Jr(t,e,n){throw new Je(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function tS(t){z(t);let e=t.pos;if(W(t)==='"')return Xe(t);let n="";for(;!Oe(t)&&!($e(t,"->")||$e(t,"::"));){let s=W(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,H(t);}n===""&&Jr(t,e+1,"unexpected end of input");let r=n[0]??"";yp.has(r)&&Jr(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];yp.has(i)&&Jr(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;Jr(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&Jr(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new Je("failed to parse select parameter");return n}function Xe(t,e={}){if(z(t),W(t)==='"'){H(t);let r="";for(;!Oe(t)&&W(t)!=='"';)r+=W(t),H(t);if(Oe(t))throw new Error(`Missing closing quote at position ${t.pos}`);return H(t),r}let n="";for(;!Oe(t);){let r=W(t);if(sl(r))n+=r,H(t);else if(e.allowDollar&&r==="$")n+=r,H(t);else if(e.allowSpaces&&r===" ")n+=r,H(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,H(t);}else break}if(e.allowSpaces&&(n=n.trimEnd()),n==="")throw new Error(`Expected identifier at position ${t.pos}`);if(n.includes("--")||n.endsWith("-"))throw new Je("failed to parse select parameter");return n}var nS=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function rS(t){return t.split(";")[0]?.trim().toLowerCase()??""}var Gr=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function al(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=rS(r);if(!n&&r.includes("text/csv"))throw new Jn('parse error (not enough input) at ""');if(!n)return {};if(s&&!nS.has(s))throw new Gr(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:sS(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function sS(t){let e=t.replace(/\r\n/g,`
|
|
76
76
|
`).replace(/\r/g,`
|
|
77
|
-
`),n=
|
|
78
|
-
`);){let{row:s,nextPos:i}=
|
|
77
|
+
`),n=iS(e);if(n.length===0)throw new Jn("parse error (not enough input)");let r=n[0];if(n.length===1)return [];let s=[];for(let i=1;i<n.length;i++){let o=n[i],a={};for(let l=0;l<r.length;l++){let c=l<o.length?o[l]:"";a[r[l]]=c===""?null:c;}s.push(a);}return s}function iS(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
|
|
78
|
+
`);){let{row:s,nextPos:i}=oS(t,n);e.push(s),n=i;}return e}function oS(t,e){let n=[],r=e,s=t.length;for(;r<=s;){if(r===s||t[r]===`
|
|
79
79
|
`)return n.length,{row:n,nextPos:r+1};if(t[r]==='"'){let i="";for(r++;r<s;)if(t[r]==='"')if(r+1<s&&t[r+1]==='"')i+='"',r+=2;else {r++;break}else i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}else {let i="";for(;r<s&&t[r]!==","&&t[r]!==`
|
|
80
|
-
`;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var Jn=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function ll(t){let e=new URL(t.url),n=new Map;for(let[r,s]of e.searchParams.entries()){let i=n.get(r)??[];i.push(s),n.set(r,i);}return n}function cl(t,e,n){let r=e.toUpperCase();if(t.isRpc)return "rpc";switch(r){case "GET":case "HEAD":return "query";case "POST":return n.preferTokens.find(i=>i.key==="resolution"&&(i.value==="merge-duplicates"||i.value==="ignore-duplicates"))?"upsert":"insert";case "PATCH":return "update";case "PUT":return "put";case "DELETE":return "delete";default:return "query"}}var Sp=new Set(["eq","neq","gt","gte","lt","lte","like","ilike","match","imatch","is","isdistinct","in","cs","cd","ov","sl","sr","nxl","nxr","adj","fts","plfts","phfts","wfts","not"]),wp={eq:"$eq",neq:"$neq",gt:"$gt",gte:"$gte",lt:"$lt",lte:"$lte",like:"$like",ilike:"$ilike",match:"$regex",imatch:"$iregex",is:"$is",isdistinct:"$isDistinct",in:"$in",cs:"$contains",cd:"$containedBy",ov:"$overlaps",sl:"$rangeLt",sr:"$rangeGt",nxl:"$rangeGte",nxr:"$rangeLte",adj:"$rangeAdjacent"},rS={any:"Any",all:"All"},sS=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),iS={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function qi(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!sS.has(s))return null;let o=wp[s];return o?{astOp:o+rS[i]}:null}let n=t.match(/^(p[lh]fts|wfts|fts)(?:\(([^)]+)\))?$/);if(n){let[,s,i]=n;return i!==void 0&&!/^[A-Za-z_][A-Za-z0-9_ ]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(i)?null:{astOp:"$textSearch",ftsType:iS[s],ftsConfig:i}}let r=wp[t];return r?{astOp:r}:null}function Vr(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return Sp.has(r)}var dn=new Set(["select","order","limit","offset","on_conflict","columns"]);function Qr(t){if(t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,-1)),t.trim()==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(st(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function mn(t){if(t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),t==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(st(r));}n<t.length&&t[n]===","&&n++;}return e}var zn=Symbol.for("postgrest:not_null"),hn=Symbol.for("postgrest:unknown");function st(t,e){let n=e?.preserveWhitespace===true,r=t.trim();if(r.startsWith('"')&&r.endsWith('"')&&r.length>=2)return r.slice(1,-1);let s=r.toLowerCase();if(s==="null")return null;if(s==="not_null")return zn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Zr(t,e,n,r){let s={},i={};for(let[o,a]of t){if(dn.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let u=o.slice(0,c),f=o.slice(c+1);if(e.has(u)){if(f==="order"||f==="limit"||f==="offset")continue;if(f.includes(".")){let p=f.lastIndexOf("."),d=f.slice(p+1);if(d==="order"||d==="limit"||d==="offset")continue}i[u]||(i[u]={}),cS(f,a,i[u]);continue}if(o!=="not.or"&&o!=="not.and")throw aS(u)}if(e.has(o)&&!a.every(oS)&&!r?.has(o)){let u=n?`${n}.${o}`:o,f=new Error(`column ${u} does not exist`);throw f.code="42703",f}fl(o,a,s);}return {where:s,embeddedWheres:i}}function oS(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function aS(t){return new ke({httpStatus:400,code:"PGRST108",message:`'${t}' is not an embedded resource in this request`,details:null,hint:`Verify that '${t}' is included in the 'select' query parameter.`})}function fl(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)lS(t,o,n);return}let s=e.map(o=>Ep(o)),i=s.length===1?s[0]:s.flat();n[`$${t}`]=i;return}if(t==="not.or"||t==="not.and"){let s=t.slice(4),i=e.map(a=>Ep(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=xp(mS(t),{stopAtSpace:false});Rp(r);for(let s of e){let i=pl(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function lS(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=pl(o);n[i]?Object.assign(n[i],a):n[i]=a;}function cS(t,e,n){let r=uS(t);if(!r){fl(t,e,n);return}let s={};fl(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function uS(t){for(let e of ["not.or","not.and","or","and"]){let n=`.${e}`;if(t.endsWith(n)){let r=t.slice(0,-n.length);if((e==="or"||e==="and")&&r==="not")continue;if(r)return {path:r,filterKey:e}}}}function pl(t){let e=t,n=false;e.startsWith("not.")&&(n=true,e=e.slice(4));let r=e.indexOf("."),s,i;r===-1?(s=e,i=""):(s=e.slice(0,r),i=e.slice(r+1));let o=qi(s);if(!o){let f=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw f?new Error(`"failed to parse filter (${t})" (line 1, column ${f[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:ul(a,i)};if(n&&a==="$is")return {$isNot:ul(a,i)};let u=a==="$textSearch"?pS(i,l,c):ul(a,i);return n?{$not:{[a]:u}}:{[a]:u}}function ul(t,e){if(t==="$in"||t==="$notIn"){if(!e.startsWith("(")||!e.endsWith(")")){let n=t==="$in"?"in":"not.in";throw new Error(`"failed to parse filter (${n}.${e})" (line 1, column ${n.length+e.length+2})`)}return Qr(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return mn(e);if(!fS(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Qr(e)}if(t==="$contains"||t==="$containedBy"||t==="$overlaps"){if(e.startsWith("{")){try{let n=JSON.parse(e);if(typeof n=="object"&&!Array.isArray(n))return n}catch{}return mn(e)}return e.startsWith("[")||e.startsWith("(")?e:st(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?hn:s==="not_null"?zn:s==="null"?null:s==="true"?true:s==="false"?false:st(e)}if(t==="$like"||t==="$ilike"||t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"){let n=e.replace(/\*/g,"%");return t.endsWith("Any")||t.endsWith("All")?n.startsWith("{")?mn(n):Qr(n):n}if(t==="$isDistinct")return e.startsWith("{")?mn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return mn(e)}return st(e)}function fS(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function pS(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function dS(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function _p(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${dS(t)})`)}function Ep(t){if(!t.startsWith("(")||!t.endsWith(")"))throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+3})`);let e=t.slice(1,-1);for(;e.endsWith(")");){let n=0;for(let r of e)r==="("?n++:r===")"&&n--;if(n<0)e=e.slice(0,e.length+n);else break}if(e.trim()==="")throw _p(t);try{return Yr(e).map(r=>Xr(r))}catch{throw _p(t)}}function Yr(t){let e=[],n=0,r=0,s=false,i="";for(let o of t)if(o==='"'&&!s?s=true:o==='"'&&s&&(s=false),s||(o==="("?n++:o===")"?n--:o==="{"?r++:o==="}"&&r--),o===","&&n===0&&r===0&&!s){if(i.trim()==="")throw new Error("empty logical expression");e.push(i.trim()),i="";}else i+=o;if(i.trim())e.push(i.trim());else if(t.trim().endsWith(","))throw new Error("empty logical expression");return e}function Xr(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Yr(n[1]).map(p=>Xr(p))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Yr(r[1]).map(p=>Xr(p))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Yr(s[1]).map(p=>Xr(p))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Yr(i[1]).map(p=>Xr(p))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let d=o.slice(4).split(".")[0];if(!(d.length>0&&qi(d)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=xp(o.slice(0,l),{stopAtSpace:true});Rp(c);let u=o.slice(l+1),f=pl(u);return {[c]:f}}function xp(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function mS(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function Rp(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function hS(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function Cp(t){if(t===void 0)return;let e=t.trim();if(!/^[+-]?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function dl(t,e){let n=Cp(t),r=Cp(e);return r!==void 0&&r<0&&(n!==void 0&&n>=0&&(n=Math.max(0,n+r)),r=void 0),{limit:n,offset:r}}function hl(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[p,d]of t){let y=d[0],m=p.indexOf(".");if(m>0){let h=p.slice(0,m),g=p.slice(m+1);if(e.has(h)){if(g==="order"||g==="limit"||g==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={}),g==="order"?n.embeddedTransforms[h].order=ml(y):g==="limit"?i[h]=y:g==="offset"&&(o[h]=y);continue}if(g.includes(".")){let S=g.lastIndexOf("."),_=g.slice(S+1);if(_==="order"||_==="limit"||_==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={});let w=n.embeddedTransforms[h],x=g.slice(0,S);w._nested||(w._nested={});let E=w._nested;E[x]||(E[x]={});let R=E[x];_==="order"?R.order=ml(y):_==="limit"?(a[h]||(a[h]={}),a[h][x]=y):_==="offset"&&(l[h]||(l[h]={}),l[h][x]=y);continue}}}}p==="order"?n.order=ml(y):p==="limit"?r=y:p==="offset"&&(s=y);}if(n.order){for(let p of n.order)if(p.embed&&!e.has(p.embed))throw new ke({httpStatus:400,code:"PGRST108",message:`'${p.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${p.embed}' is included in the 'select' query parameter.`})}let c=dl(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let u=new Set([...Object.keys(i),...Object.keys(o)]);for(let p of u){let d=dl(i[p],o[p]);n.embeddedTransforms[p]||(n.embeddedTransforms[p]={}),d.limit!==void 0&&(n.embeddedTransforms[p].limit=d.limit),d.offset!==void 0&&(n.embeddedTransforms[p].offset=d.offset);}let f=new Set([...Object.keys(a),...Object.keys(l)]);for(let p of f){let d=new Set([...Object.keys(a[p]??{}),...Object.keys(l[p]??{})]);for(let y of d){let m=dl(a[p]?.[y],l[p]?.[y]),h=n.embeddedTransforms[p]?._nested?.[y];h&&(m.limit!==void 0&&(h.limit=m.limit),m.offset!==void 0&&(h.offset=m.offset));}}return n}function ml(t){return gS(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return yS(s,t,i)})}function gS(t){let e=[],n=0,r=0;for(let s=0;s<t.length;s++){let i=t[s];i==="("?n++:i===")"?n=Math.max(0,n-1):i===","&&n===0&&(e.push({entry:t.slice(r,s),start:r}),r=s+1);}return e.push({entry:t.slice(r),start:r}),e}function yS(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new pe(`failed to parse order (${e})`,'unexpected end of input expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input',1);let o=i.indexOf("::");if(o!==-1)throw new pe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+o+1);let a=i.indexOf("--");if(a!==-1)throw new pe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+a+2);let l=i.search(/[@#%]/);if(l!==-1)throw new pe(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new pe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.length);let c=i.indexOf(":");if(c!==-1)throw new pe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let u=hS(i);if(u){if(u.column.includes(","))throw new pe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",u.embed.length)+1);s.column=u.column,s.embed=u.embed;}else if(i.includes("(")||i.includes(")")){let y=i.search(/[()]/);throw new pe(`failed to parse order (${e})`,`unexpected '${i[y]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+y+1)}let f=n+i.length+1,p=false,d=false;for(let y=1;y<r.length;y++){let m=r[y];if(m==="asc"||m==="desc"){if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.direction=m,p=true,f+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.nullsFirst=m==="nullsfirst",d=true,f+=m.length+1;}else {let h=["asc","desc","nullsfirst","nullslast"],g=null;for(let S of h)if(m.startsWith(S)&&m.length>S.length){g=S;break}if(g){let S=m[g.length],_=f+g.length;throw new pe(`failed to parse order (${e})`,`unexpected '${S}' expecting "," or end of input`,_+1)}throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1)}}return s}function gl(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=SS(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=bS("columns",i);}return r}function bS(t,e){let n=e.split(",").map(r=>wS(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new qt(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function wS(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function SS(t){let e={},n=t.match(/options=([^;]+)/);if(n){let r=n[1].split("|").map(s=>s.trim());e.analyze=r.includes("analyze"),e.verbose=r.includes("verbose"),e.settings=r.includes("settings"),e.buffers=r.includes("buffers"),e.wal=r.includes("wal");}return e}function yl(t,e,n,r){if(!t.isRpc)return {};if(e.toUpperCase()==="POST"){let a={httpMethod:"POST"};return r.values?(Array.isArray(r.values)?(a.args=r.values,a.paramsType="positional"):(a.args=r.values,a.paramsType="named"),a.inputType="json"):r.raw!==void 0&&(a.args={_raw:r.raw},a.inputType="text"),a}let i={};for(let[a,l]of n){if(dn.has(a))continue;let c=l.filter(u=>!Vr(u));c.length!==0&&(c.length>1?i[a]=c.map(u=>st(u)):i[a]=st(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function bl(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:_S(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function _S(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new qt(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function Hi(t,e){let n=e?.basePath,r=e?.parseRoute??(v=>tl(v,n)),s=e?.parseHeaders??nl,i=e?.parseSelect??ol,o=e?.parseBody??al,a=e?.parseQueryParams??ll,l=e?.resolveType??cl,c=e?.resolveFilters??Zr,u=e?.resolveTransforms??hl,f=e?.resolveMeta??gl,p=e?.resolveRpcParams??yl,d=e?.resolveUpsertParams??bl,[y,m,h,g,S]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),_=t.method,w=l(y,_,m),x=S;if(y.isRpc&&_.toUpperCase()==="GET"){x=new Map;for(let[v,C]of S){if(dn.has(v)){x.set(v,C);continue}let q=C.filter(K=>Vr(K));q.length>0&&x.set(v,q);}}let E=c(x,h.embeddedAliases,y.isRpc?void 0:y.from,e?.parentColumns),R=u(S,h.embeddedAliases),O=f(m,S,_),P=p(y,_,S,g),D=w==="upsert"||w==="put"?d(S,m):void 0;return ES(w,y,m,h,g,E,R,O,P,D)}function ES(t,e,n,r,s,i,o,a,l,c){let u={type:t};return e.isRpc?u.function=e.function:u.from=e.from,n.schema&&(u.schema=n.schema),Object.keys(r.join).length>0&&(u.join=r.join),r.select.length>0&&(u.select=Tp(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(u.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(u.values=s.values),t==="rpc"&&(l.args!==void 0&&(u.args=l.args),l.httpMethod&&(u.httpMethod=l.httpMethod),l.paramsType&&(u.paramsType=l.paramsType),l.inputType&&(u.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(u.onConflict=c.onConflict),u.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!u.select||u.select.length===0)&&(u.select=["*"]),o.order&&(u.order=o.order),o.limit!==void 0&&(u.limit=o.limit),o.offset!==void 0&&(u.offset=o.offset),Object.keys(a).length>0&&(u.$meta=a),u}function xS(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function Tp(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,u=e[o]||c&&e[c],f=n[o]||c&&n[c];if(u&&s!==o){let p={},d={};for(let[y,m]of Object.entries(u)){let h=y.indexOf(".");if(h>0){let g=y.slice(0,h),S=y.slice(h+1);if(l.join?.[g]||l.select?.some(x=>typeof x=="object"&&g in x&&"select"in(x[g]??{}))){d[g]||(d[g]={}),d[g][S]=m;continue}}p[y]=m;}Object.keys(p).length>0&&(l.where=p);for(let[y,m]of Object.entries(d))l.select=xS(l.select??[],y,m);}if(f){let p=f;if(p.order&&(l.order=p.order),p.limit!==void 0&&(l.limit=p.limit),p.offset!==void 0&&(l.offset=p.offset),p._nested)for(let[d,y]of Object.entries(p._nested))n[d]=y;}return l.select&&(l.select=Tp(l.select,e,n,l.join,o)),{[o]:l}})}function Wi(t){return t!=null&&typeof t=="object"&&"$ref"in t}it();var wl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return Gn(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return vp(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return vp(n)}return e}},Sl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},_l=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},El=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},xl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function Gn(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function vp(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function kp(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var RS=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),CS=new Set(["bool","boolean"]),$p=new Map;function Me(t){if(!t)return false;let e=t.toLowerCase().trim();return RS.has(e)||$p.has(e)}function Ie(t,e){return (t??e).toLowerCase().trim()}function Rl(t,e){let n=Ie(t.pg_type,t.type);return Me(n)||!e?n:TS(t.table,t.name,e)??n}function TS(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(Me(a)||CS.has(a))return a}}function Cl(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function Op(t){return Array.isArray(t)?t.map(e=>Ap(e)):Ap(t)}function Ap(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return Gn(e.startsWith("#")?e:`#${e}`)}return t}function Ji(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function Pp(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function es(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ie(a.pg_type,a.type);return Me(l)?Ji(t,l)??t:t}function Np(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?Me(Ie(i.pg_type,i.type)):false}function ts(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:Me(Ie(s.pg_type,s.type)))}function Tl(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ie(s.pg_type,s.type),o=Me(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function Ip(t){let e=t.pgTypeName.toLowerCase().trim(),n=$p.get(e);if(n)return n(t);switch(e){case "color":return new wl(t);case "isodate":case "isodatetext":return new Sl(t);case "unixtz":return new _l(t);case "monetary":case "monetarytext":return new El(t);case "bytea_b64":return new xl(t);default:return null}}var vS=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,AS=/[;'"\\/*\-#]/,kS=/['\\;(]/,_t=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Pe(t,e){if(!vS.test(t))throw new _t(t,e)}function bn(t,e){if(AS.test(t))throw new _t(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new _t(t,e);if(n!==0)throw new _t(t,e)}function Vn(t,e){if(kS.test(t))throw new _t(t,e)}function wn(t){let e=t.indexOf("->");if(e===-1)return {col:t,parts:[]};let n=t.slice(0,e),r=t.slice(e),s=[];for(;r.length>0;){let i;if(r.startsWith("->>"))i="->>",r=r.slice(3);else if(r.startsWith("->"))i="->",r=r.slice(2);else break;let o=r.indexOf("->"),a=o===-1?r:r.slice(0,o);s.push({op:i,key:a}),r=o===-1?"":r.slice(o);}return {col:n,parts:s}}function ns(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||Vn(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function A(t){return typeof t=="string"?sql.ref(t):t}function $S(t){return `"${t.replace(/"/g,'""')}"`}function vl(t){return sql.raw($S(t))}function Al(t,e,n=e.currentTable,r=e.currentSchema){if(!n||!e.introspection?.columns)return;let s=e.introspection.columns.filter(i=>i.table===n&&i.name===t);if(s.length!==0)return s.find(i=>!r||i.schema===r)??s.find(i=>["","public"].includes(i.schema??""))??s[0]}function zi(t,e,n=e.currentTable,r=e.currentSchema){return Al(t,e,n,r)!==void 0}function de(t,e,n=e.currentTable){return zi(t,e,n)?vl(t):sql.ref(t)}function Et(t,e,n,r=n.currentTable){let s=zi(e,n,r)?vl(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function OS(t){return (t?.pg_type??t?.type??"").toLowerCase()}function Dp(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=OS(Al(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function jp(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Ht(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=Al(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function Lp(t,e){let n=t;for(let r of e)n=sql`(${n}).${vl(r)}`;return n}function Fp(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return de(t,n,r);if(Dp(t,n,r)){let l=jp(i);if(l)return sql`${de(t,n,r)}${sql.raw(l)}`}if(Ht(t,n,r))return Lp(de(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=ns(o,"JSON path key");return sql`${de(t,n,r)}${sql.raw(a)}`}function rs(t,e,n=e.currentTable,r){let{col:s,parts:i}=wn(t),o=r?Et(r,s,e,n):de(s,e,n);if(i.length===0)return o;if(Dp(s,e,n)){let c=jp(i.map(u=>u.key));if(c)return sql`${o}${sql.raw(c)}`}if(Ht(s,e,n))return Lp(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,u)=>u===i.length-1?{...c,op:"->>"}:c):i,l=ns(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Gi={$eq:(t,e,n)=>sql`${A(e)} = ${n}`,$neq:(t,e,n)=>sql`${A(e)} != ${n}`,$gt:(t,e,n)=>sql`${A(e)} > ${n}`,$gte:(t,e,n)=>sql`${A(e)} >= ${n}`,$lt:(t,e,n)=>sql`${A(e)} < ${n}`,$lte:(t,e,n)=>sql`${A(e)} <= ${n}`,$like:(t,e,n)=>sql`${A(e)} like ${n}`,$is:(t,e,n)=>{let r=A(e);return n===zn?sql`${r} IS NOT NULL`:n===hn?sql`${r} IS UNKNOWN`:n===null?sql`${r} IS NULL`:n===true?sql`${r} IS TRUE`:n===false?sql`${r} IS FALSE`:sql`${r} IS NULL`},$isNot:(t,e,n)=>{let r=A(e);return n===zn?sql`${r} IS NULL`:n===hn?sql`${r} IS NOT UNKNOWN`:n===null?sql`${r} IS NOT NULL`:n===true?sql`${r} IS NOT TRUE`:n===false?sql`${r} IS NOT FALSE`:sql`${r} IS NOT NULL`},$in:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`false`;let r=A(e);return Array.isArray(n)?sql`${r} in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} in ${n}`},$notIn:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`true`;let r=A(e);return Array.isArray(n)?sql`${r} not in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} not in ${n}`},$isDistinct:(t,e,n)=>sql`${A(e)} is distinct from ${n}`},Vi={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function Mp(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function kl(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function Yi(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function Qi(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Wt(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!kl(a.arg_types[0],e,a.schema)||!Qi(t,e,a.schema)||a.return_typtype!=="c")continue;let l=Mp(a.return_type);if(kl(a.return_type,l,a.schema)&&Qi(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function ss(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Xi(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&kl(a.arg_types[0],e,a.schema)&&Qi(t,e,a.schema)&&!(a.return_typtype==="c"&&Qi(t,Mp(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Zi(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var PS=new Set(["$like","$ilike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function $l(t){return t!=null&&typeof t=="object"&&t.type==="query"}function Sn(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!Yi(e.introspection,e.currentTable,t,e.currentSchema)){let r=Xi(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Zi(r,e.currentTableAlias??e.currentTable)}return de(t,e)}function eo(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),Pl(t,e,n)}function NS(t){return t.includes("->")}function Wp(t,e){let{col:n,parts:r}=wn(t);return r.length===0?de(t,e):rs(t,e)}function Ee(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Ee(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Ee(t,a,n))));}else if(s==="$not")r.push(t.not(Ee(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(eo(o,n)));}else {let o=i,a=NS(s);for(let[l,c]of Object.entries(o)){if(Wi(c)){let u=Vi[l];if(!u)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Wp(s,n):Sn(s,n)} ${sql.raw(u)} ${de(c.$ref,n)}`);continue}if(l==="$not"){let u=c;for(let[f,p]of Object.entries(u))if(a)r.push(t.not(Hp(s,f,p,n)));else {let d=Up(s,f,p,n);if(d){r.push(t.not(d));continue}let y=qp(s,f,p,n);if(y){r.push(t.not(y));continue}let m=Bp(s,f,p,n);if(m){r.push(t.not(m));continue}let h=n.operators[f];if(!h)throw new Error(`Unsupported operator: ${f}`);r.push(t.not(h(t,Sn(s,n),p)));}}else if($l(c)){let u=eo(c,n),f=n.operators[l];if(!f)throw new Error(`Unsupported operator: ${l}`);r.push(f(t,Sn(s,n),u));}else if(a)r.push(Hp(s,l,c,n));else {let u=Up(s,l,c,n);if(u){r.push(u);continue}let f=DS(s,l,c,n);if(f){r.push(f);continue}LS(s,l,n);let p=Ol(s,c,n),d=qp(s,l,p,n);if(d){r.push(d);continue}let y=Bp(s,l,p,n);if(y){r.push(y);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,Sn(s,n),p));}}}}return r.length===1?r[0]:t.and(r)}function Up(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==hn)return null;let s=Yn(t,r);if(!s)return null;let i=Kp(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${de(t,r)} IS NULL`:sql`${de(t,r)} IS NOT NULL`;throw Object.assign(new Error(`argument of IS UNKNOWN must be type boolean, not type ${i}`),{code:"42804",detail:null})}function Yn(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?wn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var IS={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function Bp(t,e,n,r){if(r.dialect!=="postgres")return null;let s=IS[e];if(!s)return null;let i=Yn(t,r);if(!i||Ie(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${Sn(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function qp(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Yn(t,r);if(!s||Ie(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${Sn(t,r)})`:sql`to_tsvector(${Sn(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function Kp(t){switch(t.toLowerCase()){case "bool":return "boolean";case "int8":case "bigserial":case "serial8":return "bigint";case "int4":case "serial":case "serial4":return "integer";case "int2":return "smallint";default:return t.toLowerCase()}}function DS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Yn(t,r),i=Kp(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=de(t,r),a=sql`cast(${sql.raw(jS(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function jS(t){return `'${t.replace(/'/g,"''")}'`}function LS(t,e,n){if(!PS.has(e))return;let r=Yn(t,n);if(!r||Ie(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function Ol(t,e,n){if(!n?.currentTable)return e;let r=Yn(t,n);if(!r)return e;let s=Ie(r.pg_type,r.type);if(s==="color")return Op(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)Cl(i);else Cl(e);return e}function Hp(t,e,n,r){let s=r?Wp(t,r):A(t),o={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<=",$like:"like",$ilike:"ilike"}[e];if(o)return sql`${s} ${sql.raw(o)} ${n}`;if(e==="$is")return n===null?sql`${s} IS NULL`:n===true?sql`${s} IS TRUE`:n===false?sql`${s} IS FALSE`:sql`${s} IS NULL`;if(e==="$isNot")return n===null?sql`${s} IS NOT NULL`:n===true?sql`${s} IS NOT TRUE`:n===false?sql`${s} IS NOT FALSE`:sql`${s} IS NOT NULL`;if(e==="$in"){if(r&&$l(n))return sql`${s} in ${eo(n,r)}`;let a=Ol(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&$l(n))return sql`${s} not in ${eo(n,r)}`;let a=Ol(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function is(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>is(i,e)):r==="$not"?n[r]=is(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function ot(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function Nl(t,e){return `${t}_${e}_fkey`}function to(t,e){return e===Nl(t.table,t.column)}function Jp(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function zp(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function Gp(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function FS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?zp(e,n,t.fk):Gp(e,n,t.fk);case "parent_column":return zp(e,n,t.fk);case "target_column":return Gp(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function Vp(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function Qp(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&to(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&to(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Yp(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function Xp(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function Zp(t,e,n,r){let s=r.filter(a=>a.table===t),i=Jp(s.filter(a=>a.ref_table===e)),o=Jp(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function ed(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function td(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var MS=[Vp,Qp,Yp,Xp,Zp,ed,td];function nd(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[Vp,Qp,Xp,Yp,Zp,ed,td]:MS;for(let o of i){let a=o(t,e,n,r);if(a)return FS(a,e,n)}return null}function no(t,e,n,r){t=t.innerJoin(e.junctionTable,s=>{let i=s;for(let o=0;o<e.junctionToTargetCols.length;o++)i=i.onRef(`${e.junctionTable}.${e.junctionToTargetCols[o]}`,"=",`${n}.${e.targetCols[o]}`);return i});for(let s=0;s<e.junctionToParentCols.length;s++)t=t.whereRef(`${e.junctionTable}.${e.junctionToParentCols[s]}`,"=",`${r}.${e.parentCols[s]}`);return t}function os(t,e,n,r){if(e.type==="m2m")return no(t,e,n,r);for(let{leftCol:s,rightCol:i}of ot(e))t=t.whereRef(s,"=",i);return t}function as(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:Nl(t.table,t.column)}function Xn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!id(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=rd(a,e,n,r,s,i);return o=l.remainingWhere,l.expression??sql`1 = 1`}),Object.keys(o).length===Object.keys(e).length?{qb:t,remainingWhere:e}:{qb:t,remainingWhere:o}}function rd(t,e,n,r,s,i){let o=[],a={};for(let[c,u]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(u)){let p=u.map(d=>rd(t,d,n,r,s,i));if(p.length>0&&p.every(d=>d.fullyHandled&&d.expression)){o.push(c==="$or"?t.or(p.map(d=>d.expression)):t.and(p.map(d=>d.expression)));continue}a[c]=u;continue}let f=US(t,c,u,n,r,s,i);f?o.push(f):a[c]=u;}let l=o.length===0?null:o.length===1?o[0]:t.and(o);return {expression:l,remainingWhere:a,fullyHandled:l!==null&&Object.keys(a).length===0}}function US(t,e,n,r,s,i,o){let a=n;if(!a||typeof a!="object")return null;let l="$is"in a&&a.$is===null,c="$isNot"in a&&a.$isNot===null;if(!l&&!c)return null;let u=sd(r,e);if(!u)return null;let f=s?.[e],p=Wt(o.introspection,i,f?.from||e,o.dialect,o.currentSchema);if(p){let S=t.selectFrom(ss(p,i,p.targetTable)).select(sql`1`.as("_"));if(u.where&&Object.keys(u.where).length>0){let w=Xn(S,u.where,u.select,u.join,p.targetTable,o);if(S=w.qb,Object.keys(w.remainingWhere).length>0){let x=is(w.remainingWhere,p.targetTable);S=S.where(E=>Ee(E,x,o));}}let _=t.exists(S);return c?_:t.not(_)}let d=xe(i,e,f,o.introspection),{targetTable:y,fkRel:m}=d;if(!m)return null;let h=t.selectFrom(y).select(sql`1`.as("_"));if(f?.on?h=h.where(S=>Ee(S,f.on,o)):h=os(h,m,y,i),u.where&&Object.keys(u.where).length>0){let S=Xn(h,u.where,u.select,u.join,y,o);if(h=S.qb,Object.keys(S.remainingWhere).length>0){let _=is(S.remainingWhere,y);h=h.where(w=>Ee(w,_,o));}}let g=t.exists(h);return c?g:t.not(g)}function sd(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&se(r))return r}return null}function id(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>id(a,e)))return true;continue}let s=r;if(!s||typeof s!="object")continue;let i="$is"in s&&s.$is===null,o="$isNot"in s&&s.$isNot===null;if((i||o)&&sd(e,n))return true}return false}function se(t){return "select"in t||"spread"in t||"join"in t}function Fl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function cs(t){return Fl(t)?.def??null}function BS(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function od(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function oo(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(ts(l,n.introspection,Ue(n))||so(l,n))?ad(t,l,n,new Set,false,s):t.selectAll();for(let u of e)if(typeof u=="string")if(u==="*")if(c&&l&&(ts(l,n.introspection,Ue(n))||so(l,n))){let f=new Set;for(let p of e){if(p===u)break;if(typeof p=="string"&&p!=="*")f.add(p.includes(".")?p.split(".").pop():p);else if(typeof p!="string")for(let[d]of Object.entries(p))f.add(d);}t=ad(t,l,n,f,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(u))t=t.select(sql.lit(Number(u)).as("_lit"));else if(ZS(u,n,s)){let f=i&&s?Et(s,u,n,s):de(u,n,s);t=t.select(sql`json(${f})`.as(u));}else if(c&&l&&s&&!u.includes(".")&&!Yi(n.introspection,l,u,n.currentSchema)){let f=Xi(n.introspection,l,u,n.dialect,n.currentSchema);t=f?t.select(Zi(f,s).as(u)):t.select(u);}else if(c&&s&&l&&Np(l,od(u),n.introspection,Ue(n))){let f=od(u),p=u.includes(".")?sql.ref(u):i?Et(s,u,n,s):sql.ref(u);t=t.select(es(p,l,f,n.dialect,n.introspection,Ue(n)).as(f));}else t=i&&s&&!u.includes(".")?t.select(Et(s,u,n,s).as(u)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&zi(u,n,s)?t.select(de(u,n,s).as(u)):t.select(u);else for(let[f,p]of Object.entries(u))se(p)?t=E_(t,f,p,n,r,l,a):t=zS(t,f,p,n,s,i,l);return t}function Ue(t){return t.currentSchema??t.introspection?.default_schema??"public"}function so(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=Ue(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Ht(r.name,e,t))}function ad(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=Tl(e,n.introspection,Ue(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let u=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let f=Ji(u,c);t=t.select((f??u).as(a));}else Ht(a,n,e)?t=t.select(sql`to_jsonb(${u})`.as(a)):t=s?t.select(u.as(a)):t.select(a);}return t}function us(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(ts(s,n.introspection,Ue(n))||so(s,n))?ld(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(ts(s,n.introspection,Ue(n))||so(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=ld(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Ht(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=es(o,s,i,n.dialect,n.introspection,Ue(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(se(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Ht(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),u=es(c,s,l,n.dialect,n.introspection,Ue(n));t=u!==c?t.returning(u.as(o)):t.returning(l);}else t=t.returning(l);}return t}function ld(t,e,n,r){if(!n.introspection)return t.returningAll();let s=Tl(e,n.introspection,Ue(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=Ji(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Ht(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function fs(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${HS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=Fp(l,n.path,r,s,n.pathText===true);else {let c=s&&i?Et(s,l,r,s):de(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?es(c,o??s??r.currentTable,l,r.dialect,r.introspection,Ue(r)):c;}n.preCast&&(bn(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(bn(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&qS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&JS(r,s,n.column)?a=kp(a,r.dialect):a=r.dialect==="sqlite"&&(WS(n.cast)||KS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function qS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function HS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function WS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function KS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function JS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===Ue(t))??s.find(o=>o.schema==="public")??s[0];return Ie(i.pg_type,i.type)==="color"}function zS(t,e,n,r,s,i=false,o){return t.select(a=>fs(a,e,n,r,s,i,o).as(e))}function GS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!se(n)&&n.aggregate)return true}return false}function VS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(se(n)&&n.spread&&Ml(n.select))return true}return false}function cd(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(se(n)&&n.spread)return true}return false}function QS(t){return GS(t)||VS(t)}function Ml(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(se(n)){if(Ml(n.select))return true;continue}if(n.aggregate)return true}return false}function Ul(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(se(n)){if(n.spread)continue;if(Ul(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function Bl(t,e,n,r,s,i=false,o){if(!QS(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(de(l,n,r));continue}for(let[c,u]of Object.entries(l))se(u)||u.aggregate||a.push(f=>fs(f,c,u,n,r,i,o));}return YS(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function YS(t,e,n,r,s){if(!(!e||!r||!n.introspection?.foreign_keys)){for(let i of e)if(typeof i!="string")for(let[o,a]of Object.entries(i)){if(!se(a)||!a.spread)continue;let l=a,c=s?.[o],u=xe(r,o,c,n.introspection);if(!u.fkRel||!xt(u))continue;let f=u.targetTable;u.fkRel;let d=lo(l.select,f,n.introspection)??l.select??[],y=`_spread_${o}`;for(let m of d){if(typeof m=="string"){m!=="*"&&t.push(`${y}.${m}`);continue}let[h,g]=Object.entries(m)[0];se(g)||g.aggregate||t.push(S=>fs(S,h,g,n,y,true));}}}}function md(t,e,n,r,s){if(!t||!e||!r||!s.introspection?.foreign_keys)return t;let i=new Set;for(let o of e)if(typeof o!="string")for(let[a,l]of Object.entries(o)){if(!se(l)||!l.spread)continue;let c=n?.[a],u=xe(r,a,c,s.introspection);u.fkRel&&xt(u)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function hd(t,e,n,r){if(!t||!n||!r.introspection?.foreign_keys)return false;for(let s of t)if(typeof s!="string")for(let[i,o]of Object.entries(s)){if(!se(o)||!o.spread)continue;let a=e?.[i],l=xe(n,i,a,r.introspection);if(l.fkRel&&xt(l))return true}return false}function Zn(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function ls(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function ql(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ot(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ot(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a})}function ao(t,e,n,r,s){let i=new Set;if(!e||!r.introspection?.foreign_keys)return {sub:t,joined:i};for(let o of e){if(!o.embed||i.has(o.embed))continue;Pe(o.embed,"order embed alias");let a=s?.[o.embed],l=xe(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&Pe(l.targetTable,"order embed target"),!l.fkRel||!xt(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:u}=l;t=ql(t,u,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function XS(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function io(t,e,n){let r=n.includes(".")?n.split(".").pop():n,s=t.introspection?.columns?.find(o=>o.table===e&&o.name===r),i=(s?.pg_type||s?.type||"").toLowerCase();return i==="json"||i==="jsonb"}function ZS(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&io(e,n,t)}function e_(t,e){if(!t)return false;let n=e.includes(".")?e.split(".").pop():e;return t.some(r=>r.column.includes("->")?r.column.slice(0,r.column.indexOf("->"))===n:false)}function gd(t,e,n,r){return io(t,e,n)||e_(r,n)}function t_(t,e,n){if(!t)return null;let r=[];for(let s of t){if(typeof s=="string"){if(s==="*")return null;let l=s.includes(".")?s.split(".").pop():s;r.push({alias:l,asJson:io(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(se(o))return null;let a=io(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function n_(t,e,n,r){let s=t_(e,n,r);if(!s||s.length===0)return r.jsonObjectFrom(t);let i=s.flatMap(o=>[sql.lit(o.alias),o.asJson?sql`json(${sql.ref(`obj.${o.alias}`)})`:sql.ref(`obj.${o.alias}`)]);return sql`(select json_object(${sql.join(i)}) from ${t} as obj)`}function yd(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=Fl(e);if(n&&(!se(n.def)||yd(n.def.select)))return true}return false}function bd(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function r_(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return bd(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(Ed(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function s_(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&i_(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function i_(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function o_(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of s_(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function a_(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function ud(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function l_(t){let e=[],n=new Map;for(let r of t){let s=a_(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}ud(r)<ud(e[i])&&(e[i]=r);}return e}function Dl(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return as(t.fk)}function jl(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${as(a)}(${a.column}) and ${as(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=as(t.fk);if(t.type==="o2m"){let a=ro(t.rightCols??[t.rightCol]),l=ro(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=ro(t.leftCols??[t.leftCol]),o=ro(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function ro(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function c_(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function Hl(t,e,n,r){let s=t?.foreign_keys?.find(o=>o.table===e||o.ref_table===e)?.schema||"test",i=r?` using the hint '${r}'`:"";throw new ke({httpStatus:400,code:"PGRST200",message:`Could not find a relationship between '${e}' and '${n}' in the schema cache`,details:`Searched for a foreign key relationship between '${e}' and '${n}'${i} in the schema '${s}', but no matches were found.`,hint:c_(t,n,s)})}function u_(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(h=>h.is_visible!==false);if(r){let h=nd(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(h)return h;Hl(t,e,n,r);}if(e===n){let h=Zn(i.filter(g=>g.table===n&&g.ref_table===e))[0];if(h)return ls(e,n,h,"o2m")}let o=i.filter(h=>h.table===e&&h.ref_table===n),a=Zn(o),l=i.filter(h=>h.table===n&&h.ref_table===e),c=Zn(l),u=[],f=Zn(i.filter(h=>h.ref_table===e));for(let h of f){let g=h[0].table;if(g===e||g===n)continue;let S=i.filter(_=>_.table===g&&_.ref_table===n);if(S.length!==0)for(let _ of Zn(S))u.push({type:"m2m",junctionTable:g,junctionToParentCols:h.map(w=>w.column),parentCols:h.map(w=>w.ref_column),junctionToTargetCols:_.map(w=>w.column),targetCols:_.map(w=>w.ref_column),fk:h[0],parentFkGroup:h,targetFkGroup:_});}if(a.length+c.length+u.length===0)return null;let d=[...u];o_(d,t),d=l_(d);let y=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&d.length>1||y||a.length>0&&d.length>1){let h=[...a.map(E=>ls(e,n,E,"m2o")),...c.map(E=>ls(e,n,E,"o2m")),...d],g={o2m:0,m2o:1,m2m:2},S=[...h].sort((E,R)=>{let O=g[E.type]??3,P=g[R.type]??3;if(O!==P)return O-P;let D=Dl(E)??"",v=Dl(R)??"",C=D.localeCompare(v);return C!==0?C:jl(E,e,n).localeCompare(jl(R,e,n))}),_=S.map(E=>({cardinality:r_(E,e,n,t),embedding:`${e} with ${n}`,relationship:jl(E,e,n)})),x=S.map(E=>Dl(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new ke({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:_,hint:x?`Try changing '${n}' to one of the following: ${x}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?ls(e,n,a[0],"m2o"):c.length===1?ls(e,n,c[0],"o2m"):u.length===1?u[0]:null}function f_(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||to(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function p_(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return bd(e,i,s)?"o2o":"m2o"}return Ed(s,e,n,r,t)?"o2o":"o2m"}function xe(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=f_(s,t,r),a=BS(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?u_(r,t,i,a,l):null,u=p_(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:u,displayHint:a}}function xt(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function wd(t,e,n,r){if(!(!t||!n||!r.introspection?.foreign_keys))for(let s of t){if(!s.embed)continue;let i=e?.[s.embed],o=xe(n,s.embed,i,r.introspection);if(o.fkRel&&!xt(o))throw new ke({httpStatus:400,code:"PGRST118",message:`A related order on '${s.embed}' is not possible`,details:`'${n}' and '${s.embed}' do not form a many-to-one or one-to-one relationship`,hint:null})}}function fd(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!se(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let u=Wt(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),f=u?u.targetTable:xe(n,a,c,s.introspection).targetTable;t=t.where(p=>Sd(p,l,f,n,c,l.join??i,s));}return t}function Sd(t,e,n,r,s,i,o){let a=r?Wt(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let f=t.selectFrom(ss(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(f=f.where(p=>Ee(p,e.where,{...o,currentTable:a.targetTable}))),r&&(f=fd(f,e,a.targetTable,i,o)),t.exists(f)}let c=(r?xe(r,s?.from??n,s,o.introspection):null)?.fkRel??null,u=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)u=u.where(f=>Ee(f,s.on,o));else if(c&&c.type==="m2m")u=no(u,c,n,r);else if(c)for(let{leftCol:f,rightCol:p}of ot(c))u=u.whereRef(f,"=",p);else r&&(u=u.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(u=u.where(f=>Ee(f,e.where,{...o,currentTable:n}))),r&&(u=fd(u,e,n,i,o)),t.exists(u)}function pd(t,e,n,r,s,i){let o=s?.[e],a=i?Wt(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?xe(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>Sd(c,n,l,i,o,s,r))}function _d(t,e,n){if(!n||t.type!=="o2m")return false;let r=t.leftCol.split(".")[1];return n.indexes?.some(o=>o.table===e&&o.unique&&o.columns.length===1&&o.columns[0]===r)||n.unique_constraints?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)?true:n.primary_keys?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)??false}function Ed(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(_d(s,n,t))return true;let o=t.foreign_keys.filter(f=>f.is_visible!==false).filter(f=>f.table===n&&f.ref_table===e);if(r){let f=o.filter(p=>p.foreign_key_name===r);f.length>0&&(o=f);}let a=Zn(o);if(a.length!==1)return false;let l=[...a[0].map(f=>f.column)].sort(),c=t.primary_keys?.find(f=>f.table===n);if(!c?.columns?.length)return false;let u=[...c.columns].sort();return l.length===u.length&&l.every((f,p)=>f===u[p])}function d_(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Jt(t){if(typeof t=="string")return {colAlias:t,colName:t};let e=Object.keys(t)[0],n=t[e];return {colAlias:e,colName:n?.column||e}}function m_(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=xe(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,u=lo(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return __(t,u,l,i,c);if(!c)throw new ke({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});if(!xt(a)){if(Ml(n.select))throw new ke({httpStatus:400,code:"PGRST127",message:"Feature not implemented",details:"Aggregates are not implemented for one-to-many or many-to-many spreads.",hint:null});return S_(t,u,n,c,l,i,r)}let f=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new ke({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let p=ot(c).map(({leftCol:m,rightCol:h},g)=>{let[S,_]=m.split("."),[,w]=h.split(".");return {targetSideCol:S===l?_:w,parentSideCol:S===i?_:w,joinKey:`__spread_join_key_${g}`}}),d=[],y=new Set;for(let m of u){if(typeof m=="string"&&m==="*")continue;let h;if(typeof m!="string"){let _=cs(m);if(!_||se(_))continue;h=_;}let{colAlias:g,colName:S}=Jt(m);d.push({src:S,out:g,def:h}),y.add(S);}t=t.leftJoin(m=>{let h=m.selectFrom(l);for(let{targetSideCol:g,joinKey:S}of p)h=h.select(`${l}.${g} as ${S}`);for(let g of y)h=h.select(`${l}.${g} as ${g}`);return h.as(f)},m=>{let h=m;for(let{joinKey:g,parentSideCol:S}of p)h=h.onRef(`${f}.${g}`,"=",`${i}.${S}`);return h});for(let{out:m,def:h}of d)h?t=t.select(g=>fs(g,m,h,r,f,true).as(m)):t=t.select(`${f}.${m}`);return t}function h_(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=cs(s);if(!i||!se(i))continue;let{colAlias:o}=Jt(s),a=e.join?.[o],l=xe(n,o,a,r.introspection),c=l.targetTable,u=l.fkRel;if(!u||u.type!=="o2m"||!_d(u,c,r.introspection))continue;let f=r.introspection?.primary_keys?.find(p=>p.table===c);if(f?.columns?.length)return {nestedTargetTable:c,fkRel:u,pkColumns:f.columns}}return null}function g_(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=os(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(u=>Ee(u,o.where,c));}let l=ao(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Kt(a,XS(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=ql(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Kt(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function y_(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Kt(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function b_(t,e,n){if(n&&se(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!xt(s))return true;let{colName:i}=Jt(e);return gd(t.config,r.fromTable,i,t.frames[0].embed.order)}function w_(t,e,n,r){let s=cs(n),{colAlias:i,colName:o}=Jt(n),l=e.frames[r].fromTable;if(r===0&&s&&se(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(u=>xd(u,i,s,e.config,c,l).as("value"))}if(s&&!se(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,u=r>0?i:o;return t.select(f=>fs(f,u,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function Ll(t,e,n,r,s){if(r===e.frames.length-1)return w_(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(xt(l))return s.has(a.fromTable)||(t=ql(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=y_(t,e,a),Ll(t,e,n,r+1,s);let{colName:c}=Jt(n);return t.select(u=>{let f=u.selectFrom(a.fromTable);return f=os(f,a.fkRel,a.fromTable,o.fromTable),f=Ll(f,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(f,"value",gd(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function dd(t,e,n){let{colAlias:r}=Jt(n),s=cs(n);return t.select(i=>{let{inner:o,joinedToOne:a}=g_(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let u=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(u).as(r)}let c=Ll(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",b_(e,n,s)).as(r)})}function S_(t,e,n,r,s,i,o){let a=n.order?null:h_(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let u=cs(c),f=u!==null&&se(u)&&u.spread,{colAlias:p}=Jt(c);if(f){let d=u,y=n.join?.[p],m=xe(s,p,y,o.introspection),h=lo(d.select,m.targetTable,o.introspection)??d.select??[],g={...l,frames:[...l.frames,{embed:d,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let S of h)typeof S=="string"&&S==="*"||(t=dd(t,g,S));continue}t=dd(t,l,c);}return t}function __(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Jt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:u,rightCol:f}of ot(s))c=c.whereRef(u,"=",f);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function lo(t,e,n){if(!t||!n?.columns||!t.some(i=>i==="*"))return t;let r=n.columns.filter(i=>i.table===e).sort((i,o)=>i.ordinal_position-o.ordinal_position).map(i=>i.name);if(r.length===0)return t;let s=[];for(let i of t)if(i==="*")for(let o of r)s.push(o);else s.push(i);return s}function E_(t,e,n,r,s,i,o){let a=s?.[e];if(!yd(n.select)){if(a?.type==="inner"&&i)return pd(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Wt(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=xe(i,e,a,r.introspection);l.fkRel||Hl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=pd(t,e,n,r,s,i)),n.spread&&i?m_(t,e,n,r,s,i):t.select(l=>xd(l,e,n,r,a,i,o).as(e))}function xd(t,e,n,r,s,i,o){let a=i?Wt(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:xe(i,e,s,r.introspection),c=l.targetTable,{displayHint:u,fkRel:f}=l,p=i===c,d=p?o?`${c}_nested`:`${c}_self`:c,y=p?`${c} as ${d}`:c,m=a?t.selectFrom(ss(a,o??i,d)):t.selectFrom(y),h=i&&!s?.on&&!a?f:null,g=h?.type==="m2m",S=lo(n.select,c,r.introspection),_=g?d_(S,d):S;if(m=oo(m,_,r,n.join,d,g||cd(_),p?c:d,p?d:void 0),n.where&&Object.keys(n.where).length>0){let R=Xn(m,n.where,n.select,n.join,c,r);m=R.qb,Object.keys(R.remainingWhere).length>0&&(m=m.where(O=>Ee(O,R.remainingWhere,{...r,currentTable:c,currentTableAlias:d})));}let w=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(R=>Ee(R,s.on,r));else if(i&&!a){let R=h;if(R&&R.type==="m2m")w="m2m",m=no(m,R,d,i);else if(R?.type==="m2o"){for(let{leftCol:O,rightCol:P}of ot(R)){let[,D]=O.split("."),[,v]=P.split("."),C=o?`${o}.${D}`:`${i}.${D}`;m=m.whereRef(`${d}.${v}`,"=",C);}w="m2o";}else if(R){for(let{leftCol:O,rightCol:P}of ot(R)){let[,D]=O.split("."),[,v]=P.split("."),C=p?`${d}.${D}`:O,q=o?`${o}.${v}`:p?P.replace(`${c}.`,`${i}.`):P;m=m.whereRef(C,"=",q);}w=R.type;}else r.introspection?.foreign_keys?Hl(r.introspection,i,c,u):m=m.whereRef(`${d}.${i}_id`,"=",`${i}.id`);}m=Bl(m,_,r,d,void 0,g||cd(_),p?c:d),n.order?.some(R=>R.embed)&&(m=ao(m,n.order,c,r,n.join).sub),m=Kt(m,n.order,void 0,r,c),w==="m2m"&&!n.order&&h?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${h.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let x=n.spread?true:a?a.toOne:w==="m2o"||l.cardinality==="o2o";return x&&r.dialect==="sqlite"?n_(m,_,c,r):(x?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function Rd(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=Fl(s);if(!i||!se(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=xe(n,o,l,r.introspection);if(c.fkRel&&!xt(c))return true}return false}er();function Wl(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function T_(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${Wl(s)}`);return `${t}.${e}(${r.join(", ")})`}function v_(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(Wl).join(","),i=n.arg_types.map(Wl).join(",");return s<i?-1:s>i?1:0})}function Td(t,e,n){return {message:`Could not choose the best candidate function between: ${v_(n).map(i=>T_(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function Ad(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(f=>f.schema===r&&f.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let f=zt(n,{schema:r,fnName:s,providedNames:o});if(f.length>1)return Td(r,s,c);if(f.length===1)return null}if(i==="POST"&&a!=="text"){let f=c.filter(p=>!p.has_variadic&&p.arg_types.length===1&&p.arg_names.length===0&&(p.arg_types[0]==="json"||p.arg_types[0]==="jsonb"));if(f.length>1)return Td(r,s,f)}return null}function _n(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function kd(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function A_(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function zt(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&A_(i,s))}function uo(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=zt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function fo(t,e){let n=uo(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function $d(t,e){let n=uo(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function k_(t){return [...t].sort().join(", ")}function $_(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:k_(e)}}function O_(t,e,n,r){let s=r.filter(p=>p.schema===t),i=()=>{let p=[...new Set(s.map(d=>d.name))].filter(d=>d!==e);return ps(e,p)},o=p=>`Perhaps you meant to call the function ${t}.${p}`,a=p=>`Perhaps you meant to call the function ${t}.${e}(${p})`,l=s.filter(p=>p.name===e).map($_).filter(p=>p!==null);if(l.length===0){let p=i();return p?o(p):null}if(s.filter(p=>p.name===e).length>1){let p=l.filter(d=>d.arity===n.length);return p.length===1?a(p[0].sig):null}return l[0].sig.split(", ").every(p=>n.includes(p)||ps(p,n)!==null)?a(l[0].sig):null}function vd(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",u=c&&o==="text",f;u?f=`with a single unnamed ${a??"text"} parameter`:c?f=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:f=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let p=`Searched for the function ${n}.${r} ${f}, but no matches were found in the schema cache.`,d;l.length>0?d=`${n}.${r}(${l.join(", ")})`:u?d=`${n}.${r}`:d=`${n}.${r} without parameters`;let y=`Could not find the function ${d} in the schema cache`,m=O_(n,r,i,e);return {message:y,details:p,hint:m}}function Kl(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?vd(e,n):e.paramsType==="positional"&&e.providedNames.length===0||zt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:vd(e,n)}function P_(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function zl(t,e,n,r,s={}){if(!t)return t;let i=P_(e,n,r),o=a=>{let l=N_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):I_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function N_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??Dd(n,r,s,o)??void 0;i[o]=D_(a,l,n.dialect);}return i}function I_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=Dd(e,n,r,i);s[i]=j_(a)?mo(o):o;}return s}function Dd(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ie(a.pg_type,a.type)}function D_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&Me(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return Gn(i.startsWith("#")?i:`#${i}`)}return t}return Pp(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return Gn(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=ds(e);return i==="boolean"?Od(t):i==="integer"?po(t,true):i==="number"?po(t,false):i==="json"?Jl(t):i==="array"?Pd(t):t}if(r==="color")return Gn(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=ds(e);return s==="boolean"?Od(t):s==="integer"?po(t,true):s==="number"?po(t,false):s==="json"?Jl(t):s==="array"?Pd(t):t}function ds(t){if(!t)return;let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "array";if(e==="bool"||e==="boolean")return "boolean";if(["int2","smallint","int4","integer","int","int8","bigint"].includes(e))return "integer";if(["float4","real","float8","double precision","numeric","decimal"].includes(e))return "number";if(e==="json"||e==="jsonb")return "json"}function Od(t){let e=t.trim().toLowerCase();return ["true","t","1","yes","y","on"].includes(e)?true:["false","f","0","no","n","off"].includes(e)?false:t}function po(t,e){let n=t.trim();if(n==="")return t;let r=Number(n);return !Number.isFinite(r)||e&&!Number.isInteger(r)?t:r}function Jl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function Pd(t){let e=Jl(t);return Array.isArray(e)?e:t}function j_(t){let e=ds(t);return e==="json"||e==="array"}var L_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function Nd(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !L_.has(n)}function mo(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function jd(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return Pl(t,e,n);case "insert":return M_(t,e,n);case "update":return U_(t,e,n);case "delete":return B_(t,e,n);case "upsert":case "put":return q_(t,e,n);case "rpc":return W_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Kt(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Pe(i.embed,"order embed alias"),i.column.includes("->")?r?rs(i.column,r,s,i.embed):Id(i.column,i.embed):(Pe(i.column,"order embed column"),r?Et(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?rs(i.column,r,s,n):Id(i.column,void 0,n):n?r?Et(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?de(i.column,r,s):i.column,a=i.nullsFirst!==void 0?i.nullsFirst:r?.dialect==="sqlite"?i.direction==="desc":void 0;a!==void 0?t=t.orderBy(o,l=>{let c=i.direction==="desc"?l.desc():l.asc();return a?c.nullsFirst():c.nullsLast()}):t=t.orderBy(o,i.direction||"asc");}return t}function Id(t,e,n){let{col:r,parts:s}=wn(t);if(s.length===0)return sql.ref(t);e&&Pe(r,"order embed column");let i=ns(s,"ORDER BY JSON path key");return e?sql`${sql.ref(e)}.${sql.ref(r)}${sql.raw(i)}`:n?sql`${sql.ref(n)}.${sql.ref(r)}${sql.raw(i)}`:sql`${sql.ref(r)}${sql.raw(i)}`}function ms(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Ee(i,e,{...n,currentTable:r,currentSchema:s}))}function Pl(t,e,n){let r=n.selectFrom(t.from);return Ld(r,t,e,t.from)}function Ld(t,e,n,r){t=F_(t,e.join,e.select);let s=e.order?.some(u=>u.embed)===true;t=oo(t,e.select,n,e.join,r,s||hd(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=Xn(t,i,e.select,e.join,r,n);t=o,t=ms(t,a,n,r,e.schema),t=Bl(t,e.select,n,r,e.join),wd(e.order,e.join,r,n),s&&(t=ao(t,e.order,r,n,e.join).sub);let l=Rd(e.select,e.join,r,n)?r:void 0,c=md(e.order,e.select,e.join,r,n);return t=Kt(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function F_(t,e,n){if(!e)return t;let r=new Set;if(n){for(let s of n)if(typeof s!="string")for(let i of Object.keys(s))r.add(i);}for(let[s,i]of Object.entries(e)){if(!i.on||r.has(s))continue;let o=i.from||s,a=i.type==="left"?"leftJoin":"innerJoin";t=t[a](`${o} as ${s}`,l=>Fd(l,i.on));}return t}function Fd(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=Fd(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Vi[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Wi(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function M_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=zl(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function U_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=zl(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=Md(r,t,e,n):r=ms(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function B_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=Md(r,t,e,n):r=ms(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function Md(t,e,n,r){let i=n.introspection?.primary_keys.find(l=>l.table===e.from)?.columns??[],o=r.selectFrom(e.from),a=n.rowIdColumn;if(i.length>0)for(let l of i)o=o.select(l);else o=o.select(sql.ref(a).as("__rowid"));if(o=ms(o,e.where??{},n,e.from,e.schema),o=Kt(o,e.order,void 0,n,e.from),e.limit!==void 0&&(o=o.limit(e.limit)),e.offset!==void 0&&(o=o.offset(e.offset)),i.length===1)return t.where(i[0],"in",o);if(i.length>1){let l="__ltd_target",c=r.selectFrom(o.as(l)).select(sql`1`.as("_"));for(let u of i)c=c.whereRef(`${l}.${u}`,"=",`${e.from}.${u}`);return t.where(u=>u.exists(c))}else return t.where(sql.ref(a),"in",o)}function q_(t,e,n){let r=t.values,s=zl(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,u=Object.keys(c).filter(f=>!t.onConflict.includes(f));return u.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(f=>{let p={};for(let d of u)p[d]=f.ref(`excluded.${d}`);return p})}));let o=t.from?{...e,currentTable:t.from}:e;return i=us(i,t.select,o),i}function H_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?_n(t):Object.keys(t.args);if(zt(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function W_(t,e,n){let r=t.function;Pe(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(Pe(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,Pe(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?H_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${mo(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let f=Object.entries(t.args),p=null,d=null,y=null;if(e.dialect==="postgres"&&e.introspection?.functions){let g=f.map(([_])=>_),S=zt(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:g});if(S.length===1){let _=S[0];p=new Map;for(let w=0;w<_.arg_names.length;w++)p.set(_.arg_names[w],_.arg_types[w]);if(_.has_variadic&&_.arg_names.length>0){d=_.arg_names[_.arg_names.length-1];let w=_.arg_types[_.arg_types.length-1];y=w.endsWith("[]")?w.slice(0,-2):w;}}}let m=t.httpMethod==="GET",h=f.map(([g,S])=>{if(Pe(g,"RPC param key"),p){let w=p.get(g);if(w){if(g===d&&y){bn(y,"RPC variadic elem type"),Pe(g,"RPC variadic param key");let x=Array.isArray(S)?S:[S];return sql`VARIADIC ${sql.raw(g)} := ${x}::${sql.raw(y+"[]")}`}if(Nd(w)){bn(w,"RPC arg type");let x=m&&Array.isArray(S)?S[S.length-1]:S,E=ds(w),R=E==="json"||E==="array"&&!Array.isArray(x)?mo(x):x;return sql`${sql.raw(g)} := ${R}::${sql.raw(w)}`}}}let _=m&&Array.isArray(S)?S[S.length-1]:S;return sql`${sql.raw(g)} := ${_}`});o=sql`${sql.raw(i)}(${sql.join(h)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let f=null;if(e.dialect==="postgres"&&e.introspection?.functions){let d=e.introspection.functions,y=t.schema??e.introspection?.default_schema??"public",h=t.args.length,g=d.filter(S=>S.schema===y&&S.name===r&&S.arg_types.length===h);g.length===1&&(f=g[0].arg_types);}let p=t.args.map((d,y)=>{if(f){let m=f[y];if(m&&Nd(m)){bn(m,"RPC positional arg type");let h=ds(m),g=h==="json"||h==="array"&&!Array.isArray(d)?mo(d):d;return sql`${g}::${sql.raw(m)}`}}return sql`${d}`});o=sql`${sql.raw(i)}(${sql.join(p)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let f=$d(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:_n(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(f)return Ld(n.selectFrom(o.as(f)),t,e,f)}let u=n.selectFrom(o.as(r));return u=oo(u,t.select,e),u=ms(u,t.where??{},e,t.from,t.schema),u=Kt(u,t.order,void 0,e,t.from),t.limit!==void 0&&(u=u.limit(t.limit)),t.offset!==void 0&&(u=u.offset(t.offset)),u}var X_=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),Z_={$ilike:(t,e,n)=>sql`${A(e)} ilike ${n}`,$regex:(t,e,n)=>sql`${A(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${A(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${A(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${A(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${A(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${A(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${A(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${A(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${A(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${A(e)} -|- ${n}`,$textSearch:(t,e,n)=>{let r=n,s=r.config||"english",i="to_tsquery";return r.type==="plain"?i="plainto_tsquery":r.type==="phrase"?i="phraseto_tsquery":r.type==="websearch"&&(i="websearch_to_tsquery"),sql`${A(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${A(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${A(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${A(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${A(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${A(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${A(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${A(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${A(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${A(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${A(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${A(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${A(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${A(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${A(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${A(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${A(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${A(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${A(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${A(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${A(e)} ~* all(${n})`};function eE(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||Vn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function tE(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var Ud={db:X_,operators:{...Gi,...Z_},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:tE,jsonPath:eE,rowIdColumn:"ctid"};var nE=/[.*+?[\]{}()|]/;function ho(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function Bd(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function Gl(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=Bd(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=Bd(r),n+=1;}return e}function go(t){return t?nE.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function qd(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return go(e)?{mode:"exact",text:ho(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return go(e)?{mode:"prefix",text:ho(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return go(e)?{mode:"suffix",text:ho(e)}:null}return go(t)?{mode:"contains",text:ho(t)}:null}function Hd(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Wd(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var uE=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function fE(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||Vn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function pE(t,e){let n=A(t);if(e.length===0)return sql`(${n} is not null)`;let r=sql.join(e.map(s=>sql`${s}`));return sql`(${n} is not null and (select count(distinct value) from json_each(${n}) where value in (${r})) = ${sql.lit(e.length)})`}function dE(t,e){let n=A(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(Vn(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var mE=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function hE(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function Kd(t,e,n){let r=hE(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function gE(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function Vl(t,e){let n=A(t),r=gE(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>Vl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>Vl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>Kd(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!mE.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>Kd(n,o,e.config)),i)})`}function Ql(t,e){return sql`${A(t)} GLOB ${e}`}function yE(t,e){let n=A(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function bE(t,e){let n=A(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Jd(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=qd(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Wd(r.mode,r.text),o=A(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=Hd(r.mode,r.text);return Ql(t,s)}function yo(t,e,n,r){if(!Array.isArray(e))throw new Error(`$${n}${r} on sqlite requires an array value`);if(e.length===0)return r==="any"?sql`false`:sql`true`;let s=A(t),i=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:Ql(t,typeof o=="string"?Gl(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var wE={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?yE(e,n):sql`${A(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${A(e)}) != json(${JSON.stringify(n)})`:sql`${A(e)} != ${n}`,$textSearch:(t,e,n)=>Vl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return Ql(e,Gl(n))},$regex:(t,e,n)=>Jd(e,n,false),$iregex:(t,e,n)=>Jd(e,n,true),$ilike:(t,e,n)=>sql`lower(${A(e)}) like lower(${n})`,$likeAny:(t,e,n)=>yo(e,n,"like","any"),$ilikeAny:(t,e,n)=>yo(e,n,"ilike","any"),$likeAll:(t,e,n)=>yo(e,n,"like","all"),$ilikeAll:(t,e,n)=>yo(e,n,"ilike","all"),$isDistinct:(t,e,n)=>bE(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return pE(e,n);if(n!==null&&typeof n=="object")return dE(e,n);throw new Error("$contains on sqlite requires an array or object value")},$containedBy:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$containedBy on sqlite requires an array value");let r=A(e),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=A(e);if(n.length===0)return sql`1 = 0`;let s=sql.join(n.map(i=>sql`${i}`));return sql`(${r} is not null and exists (select 1 from json_each(${r}) where value in (${s})))`}};function SE(t,e="value",n=false){let r=sql.ref(e),s=n?sql`json_group_array(json(${r}))`:sql`json_group_array(${r})`;return sql`(select coalesce(${s}, json('[]')) from ${t} as _agg)`}var zd={db:uE,operators:{...Gi,...wE},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:SE,jsonPath:fE,rowIdColumn:"rowid"};function _E(t){switch(t){case "postgres":return Ud;case "sqlite":return zd;default:throw new Error(`Unsupported dialect: ${t}`)}}function ne(t,e="postgres",n){let r=_E(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return jd(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var Jc=ka(Xl());bs();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function at(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}var En=new TextEncoder,Rt=new TextDecoder;function So(...t){let e=t.reduce((s,{length:i})=>s+i,0),n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.length;return n}function Vt(t){let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");e[n]=r;}return e}function om(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,n=[];for(let r=0;r<t.length;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(""))}function am(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function tr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Rt.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Rt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return am(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function _o(t){let e=t;return typeof e=="string"&&(e=En.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:true}):om(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Tt={};Ir(Tt,{JOSEAlgNotAllowed:()=>ws,JOSEError:()=>ye,JOSENotSupported:()=>Be,JWEDecryptionFailed:()=>sc,JWEInvalid:()=>ic,JWKInvalid:()=>oc,JWKSInvalid:()=>ac,JWKSMultipleMatchingKeys:()=>cc,JWKSNoMatchingKey:()=>lc,JWKSTimeout:()=>uc,JWSInvalid:()=>Z,JWSSignatureVerificationFailed:()=>Ss,JWTClaimValidationFailed:()=>De,JWTExpired:()=>nr,JWTInvalid:()=>Ct});var ye=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,n){super(e,n),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor);}},De=class extends ye{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,n,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:n}}),this.claim=r,this.reason=s,this.payload=n;}},nr=class extends ye{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,n,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:n}}),this.claim=r,this.reason=s,this.payload=n;}},ws=class extends ye{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Be=class extends ye{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},sc=class extends ye{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",n){super(e,n);}},ic=class extends ye{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Z=class extends ye{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Ct=class extends ye{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},oc=class extends ye{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},ac=class extends ye{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},lc=class extends ye{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",n){super(e,n);}},cc=class extends ye{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",n){super(e,n);}},uc=class extends ye{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",n){super(e,n);}},Ss=class extends ye{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",n){super(e,n);}};var lt=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),rr=(t,e)=>t.name===e;function fc(t){return parseInt(t.name.slice(4),10)}function AE(t){switch(t){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}function kE(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function lm(t,e,n){switch(e){case "HS256":case "HS384":case "HS512":{if(!rr(t.algorithm,"HMAC"))throw lt("HMAC");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!rr(t.algorithm,"RSASSA-PKCS1-v1_5"))throw lt("RSASSA-PKCS1-v1_5");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!rr(t.algorithm,"RSA-PSS"))throw lt("RSA-PSS");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "Ed25519":case "EdDSA":{if(!rr(t.algorithm,"Ed25519"))throw lt("Ed25519");break}case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":{if(!rr(t.algorithm,e))throw lt(e);break}case "ES256":case "ES384":case "ES512":{if(!rr(t.algorithm,"ECDSA"))throw lt("ECDSA");let r=AE(e);if(t.algorithm.namedCurve!==r)throw lt(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}kE(t,n);}function cm(t,e,...n){if(n=n.filter(Boolean),n.length>2){let r=n.pop();t+=`one of type ${n.join(", ")}, or ${r}.`;}else n.length===2?t+=`one of type ${n[0]} or ${n[1]}.`:t+=`of type ${n[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var um=(t,...e)=>cm("Key must be ",t,...e),pc=(t,e,...n)=>cm(`Key for the ${t} algorithm must be `,e,...n);var dc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return true;try{return t instanceof CryptoKey}catch{return false}},mc=t=>t?.[Symbol.toStringTag]==="KeyObject",hc=t=>dc(t)||mc(t);function Eo(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return true;let n;for(let r of e){let s=Object.keys(r);if(!n||n.size===0){n=new Set(s);continue}for(let i of s){if(n.has(i))return false;n.add(i);}}return true}var $E=t=>typeof t=="object"&&t!==null;function Qt(t){if(!$E(t)||Object.prototype.toString.call(t)!=="[object Object]")return false;if(Object.getPrototypeOf(t)===null)return true;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function xo(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:n}=e.algorithm;if(typeof n!="number"||n<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function OE(t){let e,n;switch(t.kty){case "AKP":{switch(t.alg){case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":e={name:t.alg},n=t.priv?["sign"]:["verify"];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "RSA":{switch(t.alg){case "PS256":case "PS384":case "PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},n=t.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},n=t.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},n=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "EC":{switch(t.alg){case "ES256":e={name:"ECDSA",namedCurve:"P-256"},n=t.d?["sign"]:["verify"];break;case "ES384":e={name:"ECDSA",namedCurve:"P-384"},n=t.d?["sign"]:["verify"];break;case "ES512":e={name:"ECDSA",namedCurve:"P-521"},n=t.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},n=t.d?["deriveBits"]:[];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "OKP":{switch(t.alg){case "Ed25519":case "EdDSA":e={name:"Ed25519"},n=t.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":e={name:t.crv},n=t.d?["deriveBits"]:[];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Be('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:e,keyUsages:n}}async function fm(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:n}=OE(t),r={...t};return r.kty!=="AKP"&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,e,t.ext??!(t.d||t.priv),t.key_ops??n)}function Ro(t,e,n,r,s){if(s.crit!==void 0&&r?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;n!==void 0?i=new Map([...Object.entries(n),...e.entries()]):i=e;for(let o of r.crit){if(!i.has(o))throw new Be(`Extension Header Parameter "${o}" is not recognized`);if(s[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&r[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(r.crit)}function pm(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(n=>typeof n!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var _s=t=>Qt(t)&&typeof t.kty=="string",dm=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),mm=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,hm=t=>t.kty==="oct"&&typeof t.k=="string";var sr,gm=async(t,e,n,r=false)=>{sr||=new WeakMap;let s=sr.get(t);if(s?.[n])return s[n];let i=await fm({...e,alg:n});return r&&Object.freeze(t),s?s[n]=i:sr.set(t,{[n]:i}),i},NE=(t,e)=>{sr||=new WeakMap;let n=sr.get(t);if(n?.[e])return n[e];let r=t.type==="public",s=!!r,i;if(t.asymmetricKeyType==="x25519"){switch(e){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=t.toCryptoKey(t.asymmetricKeyType,s,r?[]:["deriveBits"]);}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[r?"verify":"sign"]);}switch(t.asymmetricKeyType){case "ml-dsa-44":case "ml-dsa-65":case "ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[r?"verify":"sign"]);}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case "RSA-OAEP":o="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":o="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":o="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},s,r?["encrypt"]:["decrypt"]);i=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},s,[r?"verify":"sign"]);}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&a==="P-256"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e==="ES384"&&a==="P-384"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e==="ES512"&&a==="P-521"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e.startsWith("ECDH-ES")&&(i=t.toCryptoKey({name:"ECDH",namedCurve:a},s,r?[]:["deriveBits"]));}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[e]=i:sr.set(t,{[e]:i}),i};async function Co(t,e){if(t instanceof Uint8Array||dc(t))return t;if(mc(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return NE(t,e)}catch(r){if(r instanceof TypeError)throw r}let n=t.export({format:"jwk"});return gm(t,n,e)}if(_s(t))return t.k?tr(t.k):gm(t,t,e,true);throw new Error("unreachable")}var ir=t=>t?.[Symbol.toStringTag],gc=(t,e,n)=>{if(e.use!==void 0){let r;switch(n){case "sign":case "verify":r="sig";break;case "encrypt":case "decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let r;switch(true){case(n==="sign"||n==="verify"):case t==="dir":case t.includes("CBC-HS"):r=n;break;case t.startsWith("PBES2"):r="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?r=n==="encrypt"?"wrapKey":"unwrapKey":r=n;break;case(n==="encrypt"&&t.startsWith("RSA")):r="wrapKey";break;case n==="decrypt":r=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===false)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return true},IE=(t,e,n)=>{if(!(e instanceof Uint8Array)){if(_s(e)){if(hm(e)&&gc(t,e,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!hc(e))throw new TypeError(pc(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ir(e)} instances for symmetric algorithms must be of type "secret"`)}},DE=(t,e,n)=>{if(_s(e))switch(n){case "decrypt":case "sign":if(dm(e)&&gc(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if(mm(e)&&gc(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!hc(e))throw new TypeError(pc(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${ir(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(n){case "sign":throw new TypeError(`${ir(e)} instances for asymmetric algorithm signing must be of type "private"`);case "decrypt":throw new TypeError(`${ir(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(n){case "verify":throw new TypeError(`${ir(e)} instances for asymmetric algorithm verifying must be of type "public"`);case "encrypt":throw new TypeError(`${ir(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function To(t,e,n){switch(t.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":IE(t,e,n);break;default:DE(t,e,n);}}function vo(t,e){let n=`SHA-${t.slice(-3)}`;switch(t){case "HS256":case "HS384":case "HS512":return {hash:n,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:n,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:n,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:n,name:"ECDSA",namedCurve:e.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return {name:t};default:throw new Be(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ao(t,e,n){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(um(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},false,[n])}return lm(e,t,n),e}async function ym(t,e,n,r){let s=await Ao(t,e,"verify");xo(t,s);let i=vo(t,s.algorithm);try{return await crypto.subtle.verify(i,s,n,r)}catch{return false}}async function bm(t,e,n){if(!Qt(t))throw new Z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new Z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new Z("JWS Payload missing");if(typeof t.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Qt(t.header))throw new Z("JWS Unprotected Header incorrect type");let r={};if(t.protected)try{let h=tr(t.protected);r=JSON.parse(Rt.decode(h));}catch{throw new Z("JWS Protected Header is invalid")}if(!Eo(r,t.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...r,...t.header},i=Ro(Z,new Map([["b64",true]]),n?.crit,r,s),o=true;if(i.has("b64")&&(o=r.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=s;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=n&&pm("algorithms",n.algorithms);if(l&&!l.has(a))throw new ws('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let c=false;typeof e=="function"&&(e=await e(r,t),c=true),To(a,e,"verify");let u=So(t.protected!==void 0?Vt(t.protected):new Uint8Array,Vt("."),typeof t.payload=="string"?o?Vt(t.payload):En.encode(t.payload):t.payload),f;try{f=tr(t.signature);}catch{throw new Z("Failed to base64url decode the signature")}let p=await Co(e,a);if(!await ym(a,p,f,u))throw new Ss;let y;if(o)try{y=tr(t.payload);}catch{throw new Z("Failed to base64url decode the payload")}else typeof t.payload=="string"?y=En.encode(t.payload):y=t.payload;let m={payload:y};return t.protected!==void 0&&(m.protectedHeader=r),t.header!==void 0&&(m.unprotectedHeader=t.header),c?{...m,key:p}:m}async function wm(t,e,n){if(t instanceof Uint8Array&&(t=Rt.decode(t)),typeof t!="string")throw new Z("Compact JWS must be a string or Uint8Array");let{0:r,1:s,2:i,length:o}=t.split(".");if(o!==3)throw new Z("Invalid Compact JWS");let a=await bm({payload:s,protected:r,signature:i},e,n),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...l,key:a.key}:l}var Yt=t=>Math.floor(t.getTime()/1e3),_m=60,Em=_m*60,yc=Em*24,jE=yc*7,LE=yc*365.25,FE=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Es(t){let e=FE.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let n=parseFloat(e[2]),r=e[3].toLowerCase(),s;switch(r){case "sec":case "secs":case "second":case "seconds":case "s":s=Math.round(n);break;case "minute":case "minutes":case "min":case "mins":case "m":s=Math.round(n*_m);break;case "hour":case "hours":case "hr":case "hrs":case "h":s=Math.round(n*Em);break;case "day":case "days":case "d":s=Math.round(n*yc);break;case "week":case "weeks":case "w":s=Math.round(n*jE);break;default:s=Math.round(n*LE);break}return e[1]==="-"||e[4]==="ago"?-s:s}function xn(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Sm=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,ME=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):false;function xm(t,e,n={}){let r;try{r=JSON.parse(Rt.decode(e));}catch{}if(!Qt(r))throw new Ct("JWT Claims Set must be a top-level JSON object");let{typ:s}=n;if(s&&(typeof t.typ!="string"||Sm(t.typ)!==Sm(s)))throw new De('unexpected "typ" JWT header value',r,"typ","check_failed");let{requiredClaims:i=[],issuer:o,subject:a,audience:l,maxTokenAge:c}=n,u=[...i];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let y of new Set(u.reverse()))if(!(y in r))throw new De(`missing required "${y}" claim`,r,y,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new De('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new De('unexpected "sub" claim value',r,"sub","check_failed");if(l&&!ME(r.aud,typeof l=="string"?[l]:l))throw new De('unexpected "aud" claim value',r,"aud","check_failed");let f;switch(typeof n.clockTolerance){case "string":f=Es(n.clockTolerance);break;case "number":f=n.clockTolerance;break;case "undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=n,d=Yt(p||new Date);if((r.iat!==void 0||c)&&typeof r.iat!="number")throw new De('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new De('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>d+f)throw new De('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new De('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=d-f)throw new nr('"exp" claim timestamp check failed',r,"exp","check_failed")}if(c){let y=d-r.iat,m=typeof c=="number"?c:Es(c);if(y-f>m)throw new nr('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(y<0-f)throw new De('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}var ko=class{#e;constructor(e){if(!Qt(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e);}data(){return En.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e;}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e;}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e;}set jti(e){this.#e.jti=e;}set nbf(e){typeof e=="number"?this.#e.nbf=xn("setNotBefore",e):e instanceof Date?this.#e.nbf=xn("setNotBefore",Yt(e)):this.#e.nbf=Yt(new Date)+Es(e);}set exp(e){typeof e=="number"?this.#e.exp=xn("setExpirationTime",e):e instanceof Date?this.#e.exp=xn("setExpirationTime",Yt(e)):this.#e.exp=Yt(new Date)+Es(e);}set iat(e){e===void 0?this.#e.iat=Yt(new Date):e instanceof Date?this.#e.iat=xn("setIssuedAt",Yt(e)):typeof e=="string"?this.#e.iat=xn("setIssuedAt",Yt(new Date)+Es(e)):this.#e.iat=xn("setIssuedAt",e);}};async function Rn(t,e,n){let r=await wm(t,e,n);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===false)throw new Ct("JWTs MUST NOT use unencoded payload");let i={payload:xm(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}async function Rm(t,e,n){let r=await Ao(t,e,"sign");xo(t,r);let s=await crypto.subtle.sign(vo(t,r.algorithm),r,n);return new Uint8Array(s)}var $o=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e;}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setUnprotectedHeader(e){if(this.#n)throw new TypeError("setUnprotectedHeader can only be called once");return this.#n=e,this}async sign(e,n){if(!this.#t&&!this.#n)throw new Z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Eo(this.#t,this.#n))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#n},s=Ro(Z,new Map([["b64",true]]),n?.crit,this.#t,r),i=true;if(s.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=r;if(typeof o!="string"||!o)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');To(o,e,"sign");let a,l;i?(a=_o(this.#e),l=Vt(a)):(l=this.#e,a="");let c,u;this.#t?(c=_o(JSON.stringify(this.#t)),u=Vt(c)):(c="",u=new Uint8Array);let f=So(u,Vt("."),l),p=await Co(e,o),d=await Rm(o,p,f),y={signature:_o(d),payload:a};return this.#n&&(y.header=this.#n),this.#t&&(y.protected=c),y}};var Oo=class{#e;constructor(e){this.#e=new $o(e);}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,n){let r=await this.#e.sign(e,n);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return `${r.protected}.${r.payload}.${r.signature}`}};var Cn=class{#e;#t;constructor(e={}){this.#t=new ko(e);}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,n){let r=new Oo(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===false)throw new Ct("JWTs MUST NOT use unencoded payload");return r.sign(e,n)}};async function Cm(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:at({status:401,code:"PGRST302",message:"Anonymous access is disabled"})};let n=t.slice(7).trim(),r=n.split(".");if(r.length!==3||r.some(s=>s.length===0))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:at({status:401,code:"PGRST301",message:`Expected 3 parts in JWT; got ${Math.max(1,r.filter(s=>s.length>0).length)}`})};if(!e.jwtSecret)return {kind:"error",response:at({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await Rn(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:at({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof Tt.JWTExpired?{kind:"error",response:at({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:at({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}Dc();function cx(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function ux(t,e){let n=t.schema||"public",r=Rl(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function Pm(t,e){let n=ux(t,e);return Me(n.pgTypeName)?Ip(n)??ct(n):ct(n)}function fx(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new Xt(r.table,s),n.set(i,o)),o.set(r.name,Pm(r,t));}return n}function px(t,e){for(let n of e.columns){if(!Me(Rl(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new Xt(n.table,r),t.set(s,i)),i.set(n.name,Pm(n,e));}return t}function Nm(t,e,n){if(n==="sqlite")return fx(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return px(new Map(r),e)}return t&&t.size>0?t:new Map}function Im(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function Dm(t,e,n,r){return !n||!e?.from?t:t.map(s=>jc(s,e.select,e.from,e.schema,e.join,n,r))}function jc(t,e,n,r,s,i,o){let a=cx(i,n,r,o),l=mx(e,s),c={};for(let[u,f]of Object.entries(t)){let p=l.get(u);if(p&&"embed"in p){let m=p.embed;c[u]=dx(f,m,r,i,o);continue}let d=p?.sourceColumn??u,y=a?.get(d);c[u]=y?.isShimBacked?y.deserialize(f):f;}return c}function dx(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?jc(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?jc(t,e.select,e.table,n,e.join,r,s):t}function mx(t,e){let n=new Map;if(!t)return n;for(let r of t){if(typeof r=="string"){if(r==="*")continue;n.set(r,{sourceColumn:r});continue}if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))if(hx(i)){let o=e?.[s]?.from??s;n.set(s,{embed:{table:o,select:i.select,join:i.join}});}else {let o=i;if(o.cast||o.path||o.aggregate)continue;n.set(s,{sourceColumn:o.column??s});}}return n}function hx(t){return t!=null&&typeof t=="object"&&("select"in t||"where"in t||"order"in t||"limit"in t||"offset"in t||"spread"in t||"join"in t)}var ar=class extends Error{constructor(n,r){super(`Could not find the table '${[n,r].filter(Boolean).join(".")}' in the schema cache`);this.schema=n;this.relation=r;}},Lc=class{constructor(e){this.config=e;}kysely;introspection;async translateDdl(e){return e}async clearSchemaCache(){this.introspection=void 0,await this.deleteCachedIntrospection();}async readCachedIntrospection(e){if(typeof this.introspection=="object"&&e?.useCache===true)return this.introspection;if(e?.useCache!==true||!this.config.schemaCache)return;let n=await this.config.schemaCache.get(this.schemaCacheKey());if(n)try{return this.introspection=JSON.parse(n),this.introspection}catch{await this.deleteCachedIntrospection();return}}async writeCachedIntrospection(e,n){this.introspection=e,n?.useDriver===true&&await this.config.schemaCache?.set(this.schemaCacheKey(),JSON.stringify(e));}async deleteCachedIntrospection(){await this.config.schemaCache?.delete(this.schemaCacheKey());}schemaCacheKey(){return ["@supabase/lite","schema-cache",this.dialect,this.config.introspection?.name??"",this.config.url??""].join(":")}async exec(e,...n){try{return sql(e,...n??[]).execute(this.kysely)}catch(r){throw console.error(r),new Error(`Failed to execute query: ${e}`)}}async ping(){try{let e=await this.exec("SELECT 1");return e&&Array.isArray(e.rows)&&e.rows.length===1}catch{return false}}async transaction(e,n){throw new Error("This Connection does not support transactions")}createMigrator(e){throw new Error("This Connection does not support migrations")}async onPostgrestAST(e,n){return e}deserializeRow(e){return e}normalizeDbError(e){return e}async withContext(e,n,r){return n(this.kysely)}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function vt(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var jm=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function Lm(t){let e=t.match(jm);if(!e)return null;let n=e[1]?.toLowerCase()==="json"?"json":"text",r=t.match(/;\s*options=([^;]+)/i),s=r?`; options=${r[1].trim()}`:"";return {format:n,optionsSegment:s}}function Fm(t){return jm.test(t)}function Mm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function vn(t){if(Array.isArray(t))return t.map(e=>vn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=vn(r));return e}return t}function Io(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let u;if(typeof o=="number"&&typeof a=="number"?u=o-a:u=String(o).localeCompare(String(a)),u!==0)return i.direction==="desc"?-u:u}return 0};return [...t].sort(n)}function yx(t,e){return !e||e.length===0?t:t.map(n=>qc(n,e))}function Um(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=yx(t,e);return r=wx(r,e),r=Sx(r,e),r=_x(r,e),n==="sqlite"&&(r=Ex(r,e),r=bx(r,e)),r}function bx(t,e){if(!e||e.length===0)return t;let n=xx(e);return n.size===0?t:t.map(r=>{if(!cr(r))return r;let s={...r};for(let i of n){let o=s[i];o!==null&&typeof o=="object"&&(s[i]=JSON.stringify(o));}return s})}function wx(t,e){return !e||e.length===0?t:t.map(n=>Mc(n,e))}function Sx(t,e){return !e||e.length===0?t:t.map(n=>Uc(n,e))}function _x(t,e){return !e||e.length===0?t:t.map(n=>Bc(n,e))}function Ex(t,e){return !e||e.length===0?t:t.map(n=>Fc(n,e))}function xx(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];if(!r||!s)continue;let i=s;i.path&&i.pathText&&!Bm(i.cast)&&e.add(r);}return e}function Bm(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function Rx(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function Fc(t,e){if(Array.isArray(t))return t.map(r=>Fc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Fc(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!Rx(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new Kn(l);n[s]=Number.parseInt(l,10);}return n}function qc(t,e){if(Array.isArray(t))return t.map(r=>qc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];!s||!i||!js(i)||s in n&&(n[s]=Tx(n[s],i.select));}return n}function Mc(t,e){if(Array.isArray(t))return t.map(r=>Mc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Mc(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=Cx(n[s]));}return n}function Uc(t,e){if(Array.isArray(t))return t.map(r=>Uc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Uc(n[s],i.select));continue}Bm(i.cast)&&s in n&&(n[s]=qm(n[s]));}return n}function Bc(t,e){if(Array.isArray(t))return t.map(r=>Bc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Bc(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=qm(n[s]));}return n}function Cx(t){if(typeof t!="string")return t;let e=t.trim();if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(e))return t;let n=Number(e);return !Number.isFinite(n)||e.replace(/^[+-]/,"").replace(/e[+-]?\d+$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length>15?t:n}function Tx(t,e){let n=vx(t);return !e||e.length===0?n:qc(n,e)}function vx(t){if(typeof t!="string")return t;let e=t[0];if(e!=="["&&e!=="{")return t;try{return JSON.parse(t)}catch{return t}}function qm(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function cr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function js(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var Ax=new Set(["*/*","application/*","application/json","application/vnd.pgrst.object","application/vnd.pgrst.object+json","application/vnd.pgrst.array","application/vnd.pgrst.array+json","application/octet-stream","text/csv"]);function Hm(t){let e=Lm(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function Wm(t,e){let n=t.split(",").map(r=>r.split(";")[0].trim().toLowerCase()).filter(Boolean);if(n.length===0)return true;for(let r of n)if(Ax.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function Km(t,e){let n=Lm(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?vt({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function ut(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function Jm(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function lr(t,e,n,r){if(e.type==="rpc"){let u={...e,order:void 0,limit:void 0,offset:void 0},f=ne(u,n,{db:t,introspection:r}),{sql:p,parameters:d}=f.compile(),y=`SELECT count(*) as __count FROM (${p}) AS __inner_count`,m=await t.executeQuery({sql:y,parameters:d,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(u=>u.type==="inner"),i=kx(e);if(s||i){let u={...e,type:"query",order:void 0,limit:void 0,offset:void 0},f=ne(u,n,{db:t,introspection:r}),{sql:p,parameters:d}=f.compile(),y=`SELECT count(*) as __count FROM (${p}) AS __inner_count`,h=(await t.executeQuery({sql:y,parameters:d,query:{kind:"RawNode"}})).rows?.[0];return Number(h?.__count??0)}let o={...e,type:"query",select:[{__count:{aggregate:"count"}}],order:void 0,limit:void 0,offset:void 0,join:void 0},l=await ne(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function Hc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return lr(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=ne(s,n,{db:t,introspection:r}).compile(),c=(await t.executeQuery({sql:`EXPLAIN (FORMAT JSON) ${o.sql}`,parameters:o.parameters,query:{kind:"RawNode"}})).rows?.[0]?.["QUERY PLAN"],u=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,f=u&&typeof u=="object"?Number(u["Plan Rows"]):Number.NaN;return Number.isFinite(f)?f:lr(t,e,n,r)}function kx(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=$x(t.select);return e.size===0?false:zm(t.where,e)}function zm(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(i=>i&&typeof i=="object"&&zm(i,e)))return true;continue}if(!e.has(n)||!r||typeof r!="object")continue;let s=r;if(s.$is===null||s.$isNot===null)return true}return false}function $x(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function Wc(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function Zt(t,e,n){return Wc(e)?`*/${n??0}`:t.type==="update"&&n!==0?ut(0,n??1,void 0):"*/*"}function Gm(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":ut(n,1,r)}var Ox=/[",\n\r ]/;function Vm(t){if(t==null)return "";let e;return typeof t=="string"?e=t:typeof t=="number"||typeof t=="boolean"?e=String(t):typeof t=="bigint"?e=t.toString():e=JSON.stringify(t),Ox.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Do(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>Vm(s)).join(",")];for(let s of t)r.push(n.map(i=>Vm(s[i])).join(","));return r.join(`
|
|
81
|
-
`)}function Qm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function Zm(t){return t==null?[]:Array.isArray(t)?t.map(e=>Ls(e)?new Set(Object.keys(e)):new Set):Ls(t)?[new Set(Object.keys(t))]:[]}function eh(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function th(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=Ym(t,e),s=Px(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!Ls(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!Ix(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:Ym(t,e);return n.length===0?(t.onConflict=void 0,{ast:t}):(t.onConflict=n,{ast:t,appliedResolution:t.ignoreDuplicates?"ignore-duplicates":"merge-duplicates",preflight:t.ignoreDuplicates?void 0:{mode:"merge-duplicates",conflictColumns:n}})}function nh(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=Fs(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:et(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function Ym(t,e){if(!t.from)return [];let n=t.schema??"public",r=e.primary_keys.find(s=>s.table===t.from&&s.schema===n);return r?r.columns:e.primary_keys.find(s=>s.table===t.from)?.columns??[]}function Px(t,e){if(!t||e.length===0)return null;let n=Object.keys(t);if(n.length!==e.length)return null;let r={};for(let s of n){if(s.startsWith("$")||!e.includes(s))return null;let i=Nx(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function Nx(t){if(!Ls(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function Ix(t,e){return Object.is(t,e)?true:t!==null&&e!==null&&t!==void 0&&e!==void 0&&typeof t!="object"&&typeof e!="object"?String(t)===String(e):vt(t)===vt(e)}function Fs(t,e){let n=[];return e&&n.push(`resolution=${e}`),t?.missing&&n.push(`missing=${t.missing}`),t?.return&&n.push(`return=${t.return}`),t?.count&&t.count!=="none"&&n.push(`count=${t.count}`),t?.tx&&n.push(`tx=${t.tx}`),n.length>0?n.join(", "):void 0}function et(t,e,n,r){switch(t.type){case "insert":return 201;case "upsert":return !n||n==="ignore-duplicates"?201:r===false?200:201;case "put":return e==="representation"?r?201:200:204;case "update":case "delete":return e==="representation"?200:204;default:return 200}}async function rh(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await Xm(t,e.from,e.schema,e.where??{},n,r);let i=Array.isArray(e.values)?e.values:e.values?[e.values]:[];for(let o of i){if(!Ls(o))continue;let a=Dx(s.preflight.conflictColumns,o);if(!a||!await Xm(t,e.from,e.schema,a,n,r))return true}return false}function Dx(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function Xm(t,e,n,r,s,i){return await lr(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function Ls(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jx(t){return "select"in t||"spread"in t||"join"in t}function sh(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))jx(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),sh(r.select,e));}}var Lx={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function Fx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!Mx(i,s))}function Mx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=Lx[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function Ux(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function ih(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&Ul(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let u=c?.plan_enabled===true;if(!t.allowRawMedia&&!Wm(i,u))return T(406,"PGRST107",`None of these media types are available: ${Hm(i)}`,null,null);let f=Mm(i),p=Qm(i),d=Fx(o,r.timezones);if(d.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${d.join(", ")}`,null);let y=Ux(e);if(y)return y;if(n==="sqlite"&&e.from){let w=e.schema??"",x=r.tables.some(R=>R.name===e.from&&(R.schema??"")===w),E=r.views.some(R=>R.name===e.from&&(R.schema??"")===w);if(!x&&!E)throw new ar(e.schema,e.from)}let m=e.$meta,h=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",g={ast:e};if(h&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&h){let w=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!w)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!w)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(h&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let w=m?.return==="representation"?200:204,x=Fs(m,g.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":Zt(e,m,0)};if(x&&(E["Preference-Applied"]=x),m?.return==="representation"){let R=new TextEncoder().encode("[]");return E["Content-Length"]=String(R.byteLength),new Response(R,{status:w,headers:E})}return new Response(null,{status:w,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?g.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(w=>typeof w!="object"||w===null||Array.isArray(w)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let w=Object.keys(e.values[0]).sort().join(",");for(let x=1;x<e.values.length;x++)if(Object.keys(e.values[x]).sort().join(",")!==w)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){g.bodyKeySets=Zm(e.values);let w=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!w.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let x=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let R={};for(let O of x)O in E&&(R[O]=E[O]);return R});else {let E={};for(let R of x)R in e.values&&(E[R]=e.values[R]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let w=r.columns.filter(x=>x.table===e.from).map(x=>x.name);if(w.length>0){let x=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of x)if(!w.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let w=e.schema??"public",x=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===w&&E.is_generated===true).map(E=>E.name));if(x.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let R of E)if(!(!R||typeof R!="object")){for(let O of Object.keys(R))if(x.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let S=th(e,r);if(S instanceof Response)return S;let _=g.bodyKeySets;if(g=S,g.bodyKeySets=_,e=g.ast,h&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||g.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):nh(e,g);if(l&&(a==="GET"||a==="HEAD")){let w=l.match(/^(\d+)-(\d*)$/);if(w){let x=parseInt(w[1],10);if(w[2]!==""){let E=parseInt(w[2],10);if(x>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=x,e.limit=E-x+1;}else e.offset=x;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!h){let w=c?.max_rows;w!==void 0&&w>0&&((e.limit===void 0||e.limit>w)&&(e.limit=w),sh(e.select,w));}return {ast:e,meta:m,mutationPlan:g,isMutation:h,stripNullsResponse:f,csvResponse:p,planEnabled:u}}var ur=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Ki();hs();er();function oh(t){if(t.from)return t.from}function ch(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof pe){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof Je)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof Kn)return T(400,t.code,t.message,null,null);if(t instanceof qt)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof Wn)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof ke)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof Jn)return T(400,"PGRST102",t.message,null,null);if(t instanceof Gr)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof _t)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof gn)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof ur){let l=Gt(s,"auth.role","anon")==="anon"?401:403;return at({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof ar){let a=o.schema||"public",l=[...r.tables.filter(p=>(p.schema||"public")===a).map(p=>p.name),...r.views.filter(p=>(p.schema||"public")===a).map(p=>p.name)],c=l.length>0?l:[...r.tables.map(p=>p.name),...r.views.map(p=>p.name)],u=ps(o.relation,c),f=u?`Perhaps you meant the table '${a}.${u}'`:null;return at({status:404,code:"PGRST205",message:o.message,hint:f})}if(typeof o?.code=="string"){if(o.code==="PGRST")return qx(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=Gt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?oh(i):void 0;if(o.code==="42703"&&c){let u=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(f,p)=>u?.includes(p)?f:`column ${c}.${p} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var Kc=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,Bx="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",ah="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function lh(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function qx(t){let e=typeof t.message=="string"?t.message:"",n=lh(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",Kc,`Invalid JSON value for MESSAGE: '${e}'`,Bx);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",Kc,"DETAIL is missing in the RAISE statement",ah);let s=lh(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",Kc,`Invalid JSON value for DETAIL: '${r}'`,ah);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[f,p]of Object.entries(i))typeof p=="string"&&(c[f]=p);let u={status:s.status,headers:c};typeof s.status_text=="string"&&(u.statusText=s.status_text);try{return new Response(l,u)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var Wx="response.status guc must be a valid status code",fr="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function uh(t,e){let n=(await sql`
|
|
80
|
+
`;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var Jn=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function ll(t){let e=new URL(t.url),n=new Map;for(let[r,s]of e.searchParams.entries()){let i=n.get(r)??[];i.push(s),n.set(r,i);}return n}function cl(t,e,n){let r=e.toUpperCase();if(t.isRpc)return "rpc";switch(r){case "GET":case "HEAD":return "query";case "POST":return n.preferTokens.find(i=>i.key==="resolution"&&(i.value==="merge-duplicates"||i.value==="ignore-duplicates"))?"upsert":"insert";case "PATCH":return "update";case "PUT":return "put";case "DELETE":return "delete";default:return "query"}}var Ep=new Set(["eq","neq","gt","gte","lt","lte","like","ilike","match","imatch","is","isdistinct","in","cs","cd","ov","sl","sr","nxl","nxr","adj","fts","plfts","phfts","wfts","not"]),_p={eq:"$eq",neq:"$neq",gt:"$gt",gte:"$gte",lt:"$lt",lte:"$lte",like:"$like",ilike:"$ilike",match:"$regex",imatch:"$iregex",is:"$is",isdistinct:"$isDistinct",in:"$in",cs:"$contains",cd:"$containedBy",ov:"$overlaps",sl:"$rangeLt",sr:"$rangeGt",nxl:"$rangeGte",nxr:"$rangeLte",adj:"$rangeAdjacent"},aS={any:"Any",all:"All"},lS=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),cS={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function qi(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!lS.has(s))return null;let o=_p[s];return o?{astOp:o+aS[i]}:null}let n=t.match(/^(p[lh]fts|wfts|fts)(?:\(([^)]+)\))?$/);if(n){let[,s,i]=n;return i!==void 0&&!/^[A-Za-z_][A-Za-z0-9_ ]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/.test(i)?null:{astOp:"$textSearch",ftsType:cS[s],ftsConfig:i}}let r=_p[t];return r?{astOp:r}:null}function Vr(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return Ep.has(r)}var mn=new Set(["select","order","limit","offset","on_conflict","columns"]);function Qr(t){if(t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,-1)),t.trim()==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(st(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function hn(t){if(t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),t==="")return [];let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){n++;let r="";for(;n<t.length&&t[n]!=='"';)t[n]==="\\"&&n+1<t.length&&n++,r+=t[n],n++;n<t.length&&n++,e.push(r);}else {let r="";for(;n<t.length&&t[n]!==",";)r+=t[n],n++;e.push(st(r));}n<t.length&&t[n]===","&&n++;}return e}var zn=Symbol.for("postgrest:not_null"),gn=Symbol.for("postgrest:unknown");function st(t,e){let n=e?.preserveWhitespace===true,r=t.trim();if(r.startsWith('"')&&r.endsWith('"')&&r.length>=2)return r.slice(1,-1);let s=r.toLowerCase();if(s==="null")return null;if(s==="not_null")return zn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Zr(t,e,n,r){let s={},i={};for(let[o,a]of t){if(mn.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let u=o.slice(0,c),f=o.slice(c+1);if(e.has(u)){if(f==="order"||f==="limit"||f==="offset")continue;if(f.includes(".")){let p=f.lastIndexOf("."),d=f.slice(p+1);if(d==="order"||d==="limit"||d==="offset")continue}i[u]||(i[u]={}),dS(f,a,i[u]);continue}if(o!=="not.or"&&o!=="not.and")throw fS(u)}if(e.has(o)&&!a.every(uS)&&!r?.has(o)){let u=n?`${n}.${o}`:o,f=new Error(`column ${u} does not exist`);throw f.code="42703",f}fl(o,a,s);}return {where:s,embeddedWheres:i}}function uS(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function fS(t){return new ke({httpStatus:400,code:"PGRST108",message:`'${t}' is not an embedded resource in this request`,details:null,hint:`Verify that '${t}' is included in the 'select' query parameter.`})}function fl(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)pS(t,o,n);return}let s=e.map(o=>Rp(o)),i=s.length===1?s[0]:s.flat();n[`$${t}`]=i;return}if(t==="not.or"||t==="not.and"){let s=t.slice(4),i=e.map(a=>Rp(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=Cp(bS(t),{stopAtSpace:false});Tp(r);for(let s of e){let i=pl(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function pS(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=pl(o);n[i]?Object.assign(n[i],a):n[i]=a;}function dS(t,e,n){let r=mS(t);if(!r){fl(t,e,n);return}let s={};fl(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function mS(t){for(let e of ["not.or","not.and","or","and"]){let n=`.${e}`;if(t.endsWith(n)){let r=t.slice(0,-n.length);if((e==="or"||e==="and")&&r==="not")continue;if(r)return {path:r,filterKey:e}}}}function pl(t){let e=t,n=false;e.startsWith("not.")&&(n=true,e=e.slice(4));let r=e.indexOf("."),s,i;r===-1?(s=e,i=""):(s=e.slice(0,r),i=e.slice(r+1));let o=qi(s);if(!o){let f=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw f?new Error(`"failed to parse filter (${t})" (line 1, column ${f[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:ul(a,i)};if(n&&a==="$is")return {$isNot:ul(a,i)};let u=a==="$textSearch"?gS(i,l,c):ul(a,i);return n?{$not:{[a]:u}}:{[a]:u}}function ul(t,e){if(t==="$in"||t==="$notIn"){if(!e.startsWith("(")||!e.endsWith(")")){let n=t==="$in"?"in":"not.in";throw new Error(`"failed to parse filter (${n}.${e})" (line 1, column ${n.length+e.length+2})`)}return Qr(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return hn(e);if(!hS(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Qr(e)}if(t==="$contains"||t==="$containedBy"||t==="$overlaps"){if(e.startsWith("{")){try{let n=JSON.parse(e);if(typeof n=="object"&&!Array.isArray(n))return n}catch{}return hn(e)}return e.startsWith("[")||e.startsWith("(")?e:st(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?gn:s==="not_null"?zn:s==="null"?null:s==="true"?true:s==="false"?false:st(e)}if(t==="$like"||t==="$ilike"||t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"){let n=e.replace(/\*/g,"%");return t.endsWith("Any")||t.endsWith("All")?n.startsWith("{")?hn(n):Qr(n):n}if(t==="$isDistinct")return e.startsWith("{")?hn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return hn(e)}return st(e)}function hS(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function gS(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function yS(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function xp(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${yS(t)})`)}function Rp(t){if(!t.startsWith("(")||!t.endsWith(")"))throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+3})`);let e=t.slice(1,-1);for(;e.endsWith(")");){let n=0;for(let r of e)r==="("?n++:r===")"&&n--;if(n<0)e=e.slice(0,e.length+n);else break}if(e.trim()==="")throw xp(t);try{return Yr(e).map(r=>Xr(r))}catch{throw xp(t)}}function Yr(t){let e=[],n=0,r=0,s=false,i="";for(let o of t)if(o==='"'&&!s?s=true:o==='"'&&s&&(s=false),s||(o==="("?n++:o===")"?n--:o==="{"?r++:o==="}"&&r--),o===","&&n===0&&r===0&&!s){if(i.trim()==="")throw new Error("empty logical expression");e.push(i.trim()),i="";}else i+=o;if(i.trim())e.push(i.trim());else if(t.trim().endsWith(","))throw new Error("empty logical expression");return e}function Xr(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Yr(n[1]).map(p=>Xr(p))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Yr(r[1]).map(p=>Xr(p))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Yr(s[1]).map(p=>Xr(p))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Yr(i[1]).map(p=>Xr(p))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let d=o.slice(4).split(".")[0];if(!(d.length>0&&qi(d)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=Cp(o.slice(0,l),{stopAtSpace:true});Tp(c);let u=o.slice(l+1),f=pl(u);return {[c]:f}}function Cp(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function bS(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function Tp(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function wS(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function vp(t){if(t===void 0)return;let e=t.trim();if(!/^[+-]?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function dl(t,e){let n=vp(t),r=vp(e);return r!==void 0&&r<0&&(n!==void 0&&n>=0&&(n=Math.max(0,n+r)),r=void 0),{limit:n,offset:r}}function hl(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[p,d]of t){let g=d[0],m=p.indexOf(".");if(m>0){let h=p.slice(0,m),y=p.slice(m+1);if(e.has(h)){if(y==="order"||y==="limit"||y==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={}),y==="order"?n.embeddedTransforms[h].order=ml(g):y==="limit"?i[h]=g:y==="offset"&&(o[h]=g);continue}if(y.includes(".")){let S=y.lastIndexOf("."),_=y.slice(S+1);if(_==="order"||_==="limit"||_==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={});let w=n.embeddedTransforms[h],x=y.slice(0,S);w._nested||(w._nested={});let E=w._nested;E[x]||(E[x]={});let R=E[x];_==="order"?R.order=ml(g):_==="limit"?(a[h]||(a[h]={}),a[h][x]=g):_==="offset"&&(l[h]||(l[h]={}),l[h][x]=g);continue}}}}p==="order"?n.order=ml(g):p==="limit"?r=g:p==="offset"&&(s=g);}if(n.order){for(let p of n.order)if(p.embed&&!e.has(p.embed))throw new ke({httpStatus:400,code:"PGRST108",message:`'${p.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${p.embed}' is included in the 'select' query parameter.`})}let c=dl(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let u=new Set([...Object.keys(i),...Object.keys(o)]);for(let p of u){let d=dl(i[p],o[p]);n.embeddedTransforms[p]||(n.embeddedTransforms[p]={}),d.limit!==void 0&&(n.embeddedTransforms[p].limit=d.limit),d.offset!==void 0&&(n.embeddedTransforms[p].offset=d.offset);}let f=new Set([...Object.keys(a),...Object.keys(l)]);for(let p of f){let d=new Set([...Object.keys(a[p]??{}),...Object.keys(l[p]??{})]);for(let g of d){let m=dl(a[p]?.[g],l[p]?.[g]),h=n.embeddedTransforms[p]?._nested?.[g];h&&(m.limit!==void 0&&(h.limit=m.limit),m.offset!==void 0&&(h.offset=m.offset));}}return n}function ml(t){return SS(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return _S(s,t,i)})}function SS(t){let e=[],n=0,r=0;for(let s=0;s<t.length;s++){let i=t[s];i==="("?n++:i===")"?n=Math.max(0,n-1):i===","&&n===0&&(e.push({entry:t.slice(r,s),start:r}),r=s+1);}return e.push({entry:t.slice(r),start:r}),e}function _S(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new pe(`failed to parse order (${e})`,'unexpected end of input expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input',1);let o=i.indexOf("::");if(o!==-1)throw new pe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+o+1);let a=i.indexOf("--");if(a!==-1)throw new pe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+a+2);let l=i.search(/[@#%]/);if(l!==-1)throw new pe(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new pe(`failed to parse order (${e})`,`unexpected '-' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.length);let c=i.indexOf(":");if(c!==-1)throw new pe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let u=wS(i);if(u){if(u.column.includes(","))throw new pe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",u.embed.length)+1);s.column=u.column,s.embed=u.embed;}else if(i.includes("(")||i.includes(")")){let g=i.search(/[()]/);throw new pe(`failed to parse order (${e})`,`unexpected '${i[g]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+g+1)}let f=n+i.length+1,p=false,d=false;for(let g=1;g<r.length;g++){let m=r[g];if(m==="asc"||m==="desc"){if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.direction=m,p=true,f+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.nullsFirst=m==="nullsfirst",d=true,f+=m.length+1;}else {let h=["asc","desc","nullsfirst","nullslast"],y=null;for(let S of h)if(m.startsWith(S)&&m.length>S.length){y=S;break}if(y){let S=m[y.length],_=f+y.length;throw new pe(`failed to parse order (${e})`,`unexpected '${S}' expecting "," or end of input`,_+1)}throw new pe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1)}}return s}function gl(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=RS(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=ES("columns",i);}return r}function ES(t,e){let n=e.split(",").map(r=>xS(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new Ht(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function xS(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function RS(t){let e={},n=t.match(/options=([^;]+)/);if(n){let r=n[1].split("|").map(s=>s.trim());e.analyze=r.includes("analyze"),e.verbose=r.includes("verbose"),e.settings=r.includes("settings"),e.buffers=r.includes("buffers"),e.wal=r.includes("wal");}return e}function yl(t,e,n,r){if(!t.isRpc)return {};if(e.toUpperCase()==="POST"){let a={httpMethod:"POST"};return r.values?(Array.isArray(r.values)?(a.args=r.values,a.paramsType="positional"):(a.args=r.values,a.paramsType="named"),a.inputType="json"):r.raw!==void 0&&(a.args={_raw:r.raw},a.inputType="text"),a}let i={};for(let[a,l]of n){if(mn.has(a))continue;let c=l.filter(u=>!Vr(u));c.length!==0&&(c.length>1?i[a]=c.map(u=>st(u)):i[a]=st(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function bl(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:CS(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function CS(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new Ht(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function Hi(t,e){let n=e?.basePath,r=e?.parseRoute??(v=>tl(v,n)),s=e?.parseHeaders??nl,i=e?.parseSelect??ol,o=e?.parseBody??al,a=e?.parseQueryParams??ll,l=e?.resolveType??cl,c=e?.resolveFilters??Zr,u=e?.resolveTransforms??hl,f=e?.resolveMeta??gl,p=e?.resolveRpcParams??yl,d=e?.resolveUpsertParams??bl,[g,m,h,y,S]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),_=t.method,w=l(g,_,m),x=S;if(g.isRpc&&_.toUpperCase()==="GET"){x=new Map;for(let[v,C]of S){if(mn.has(v)){x.set(v,C);continue}let q=C.filter(K=>Vr(K));q.length>0&&x.set(v,q);}}let E=c(x,h.embeddedAliases,g.isRpc?void 0:g.from,e?.parentColumns),R=u(S,h.embeddedAliases),O=f(m,S,_),P=p(g,_,S,y),D=w==="upsert"||w==="put"?d(S,m):void 0;return TS(w,g,m,h,y,E,R,O,P,D)}function TS(t,e,n,r,s,i,o,a,l,c){let u={type:t};return e.isRpc?u.function=e.function:u.from=e.from,n.schema&&(u.schema=n.schema),Object.keys(r.join).length>0&&(u.join=r.join),r.select.length>0&&(u.select=Ap(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(u.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(u.values=s.values),t==="rpc"&&(l.args!==void 0&&(u.args=l.args),l.httpMethod&&(u.httpMethod=l.httpMethod),l.paramsType&&(u.paramsType=l.paramsType),l.inputType&&(u.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(u.onConflict=c.onConflict),u.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!u.select||u.select.length===0)&&(u.select=["*"]),o.order&&(u.order=o.order),o.limit!==void 0&&(u.limit=o.limit),o.offset!==void 0&&(u.offset=o.offset),Object.keys(a).length>0&&(u.$meta=a),u}function vS(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function Ap(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,u=e[o]||c&&e[c],f=n[o]||c&&n[c];if(u&&s!==o){let p={},d={};for(let[g,m]of Object.entries(u)){let h=g.indexOf(".");if(h>0){let y=g.slice(0,h),S=g.slice(h+1);if(l.join?.[y]||l.select?.some(x=>typeof x=="object"&&y in x&&"select"in(x[y]??{}))){d[y]||(d[y]={}),d[y][S]=m;continue}}p[g]=m;}Object.keys(p).length>0&&(l.where=p);for(let[g,m]of Object.entries(d))l.select=vS(l.select??[],g,m);}if(f){let p=f;if(p.order&&(l.order=p.order),p.limit!==void 0&&(l.limit=p.limit),p.offset!==void 0&&(l.offset=p.offset),p._nested)for(let[d,g]of Object.entries(p._nested))n[d]=g;}return l.select&&(l.select=Ap(l.select,e,n,l.join,o)),{[o]:l}})}function Wi(t){return t!=null&&typeof t=="object"&&"$ref"in t}it();var wl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return Gn(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return kp(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return kp(n)}return e}},Sl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},_l=class extends ae{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},El=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},xl=class extends ae{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function Gn(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function kp(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function Op(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var AS=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),kS=new Set(["bool","boolean"]),Pp=new Map;function Me(t){if(!t)return false;let e=t.toLowerCase().trim();return AS.has(e)||Pp.has(e)}function Ie(t,e){return (t??e).toLowerCase().trim()}function Rl(t,e){let n=Ie(t.pg_type,t.type);return Me(n)||!e?n:$S(t.table,t.name,e)??n}function $S(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(Me(a)||kS.has(a))return a}}function Cl(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function Np(t){return Array.isArray(t)?t.map(e=>$p(e)):$p(t)}function $p(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return Gn(e.startsWith("#")?e:`#${e}`)}return t}function Ji(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function Ip(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function es(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ie(a.pg_type,a.type);return Me(l)?Ji(t,l)??t:t}function Dp(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?Me(Ie(i.pg_type,i.type)):false}function ts(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:Me(Ie(s.pg_type,s.type)))}function Tl(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ie(s.pg_type,s.type),o=Me(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function jp(t){let e=t.pgTypeName.toLowerCase().trim(),n=Pp.get(e);if(n)return n(t);switch(e){case "color":return new wl(t);case "isodate":case "isodatetext":return new Sl(t);case "unixtz":return new _l(t);case "monetary":case "monetarytext":return new El(t);case "bytea_b64":return new xl(t);default:return null}}var OS=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,PS=/[;'"\\/*\-#]/,NS=/['\\;(]/,Et=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Pe(t,e){if(!OS.test(t))throw new Et(t,e)}function wn(t,e){if(PS.test(t))throw new Et(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new Et(t,e);if(n!==0)throw new Et(t,e)}function Vn(t,e){if(NS.test(t))throw new Et(t,e)}function Sn(t){let e=t.indexOf("->");if(e===-1)return {col:t,parts:[]};let n=t.slice(0,e),r=t.slice(e),s=[];for(;r.length>0;){let i;if(r.startsWith("->>"))i="->>",r=r.slice(3);else if(r.startsWith("->"))i="->",r=r.slice(2);else break;let o=r.indexOf("->"),a=o===-1?r:r.slice(0,o);s.push({op:i,key:a}),r=o===-1?"":r.slice(o);}return {col:n,parts:s}}function ns(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||Vn(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function A(t){return typeof t=="string"?sql.ref(t):t}function IS(t){return `"${t.replace(/"/g,'""')}"`}function vl(t){return sql.raw(IS(t))}function Al(t,e,n=e.currentTable,r=e.currentSchema){if(!n||!e.introspection?.columns)return;let s=e.introspection.columns.filter(i=>i.table===n&&i.name===t);if(s.length!==0)return s.find(i=>!r||i.schema===r)??s.find(i=>["","public"].includes(i.schema??""))??s[0]}function zi(t,e,n=e.currentTable,r=e.currentSchema){return Al(t,e,n,r)!==void 0}function de(t,e,n=e.currentTable){return zi(t,e,n)?vl(t):sql.ref(t)}function xt(t,e,n,r=n.currentTable){let s=zi(e,n,r)?vl(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function DS(t){return (t?.pg_type??t?.type??"").toLowerCase()}function Lp(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=DS(Al(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function Fp(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Wt(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=Al(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function Mp(t,e){let n=t;for(let r of e)n=sql`(${n}).${vl(r)}`;return n}function Up(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return de(t,n,r);if(Lp(t,n,r)){let l=Fp(i);if(l)return sql`${de(t,n,r)}${sql.raw(l)}`}if(Wt(t,n,r))return Mp(de(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=ns(o,"JSON path key");return sql`${de(t,n,r)}${sql.raw(a)}`}function rs(t,e,n=e.currentTable,r){let{col:s,parts:i}=Sn(t),o=r?xt(r,s,e,n):de(s,e,n);if(i.length===0)return o;if(Lp(s,e,n)){let c=Fp(i.map(u=>u.key));if(c)return sql`${o}${sql.raw(c)}`}if(Wt(s,e,n))return Mp(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,u)=>u===i.length-1?{...c,op:"->>"}:c):i,l=ns(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Gi={$eq:(t,e,n)=>sql`${A(e)} = ${n}`,$neq:(t,e,n)=>sql`${A(e)} != ${n}`,$gt:(t,e,n)=>sql`${A(e)} > ${n}`,$gte:(t,e,n)=>sql`${A(e)} >= ${n}`,$lt:(t,e,n)=>sql`${A(e)} < ${n}`,$lte:(t,e,n)=>sql`${A(e)} <= ${n}`,$like:(t,e,n)=>sql`${A(e)} like ${n}`,$is:(t,e,n)=>{let r=A(e);return n===zn?sql`${r} IS NOT NULL`:n===gn?sql`${r} IS UNKNOWN`:n===null?sql`${r} IS NULL`:n===true?sql`${r} IS TRUE`:n===false?sql`${r} IS FALSE`:sql`${r} IS NULL`},$isNot:(t,e,n)=>{let r=A(e);return n===zn?sql`${r} IS NULL`:n===gn?sql`${r} IS NOT UNKNOWN`:n===null?sql`${r} IS NOT NULL`:n===true?sql`${r} IS NOT TRUE`:n===false?sql`${r} IS NOT FALSE`:sql`${r} IS NOT NULL`},$in:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`false`;let r=A(e);return Array.isArray(n)?sql`${r} in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} in ${n}`},$notIn:(t,e,n)=>{if(Array.isArray(n)&&n.length===0)return sql`true`;let r=A(e);return Array.isArray(n)?sql`${r} not in (${sql.join(n.map(s=>sql`${s}`))})`:sql`${r} not in ${n}`},$isDistinct:(t,e,n)=>sql`${A(e)} is distinct from ${n}`},Vi={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function Bp(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function kl(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function Yi(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function Qi(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Kt(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!kl(a.arg_types[0],e,a.schema)||!Qi(t,e,a.schema)||a.return_typtype!=="c")continue;let l=Bp(a.return_type);if(kl(a.return_type,l,a.schema)&&Qi(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function ss(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Xi(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&kl(a.arg_types[0],e,a.schema)&&Qi(t,e,a.schema)&&!(a.return_typtype==="c"&&Qi(t,Bp(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Zi(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var jS=new Set(["$like","$ilike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function $l(t){return t!=null&&typeof t=="object"&&t.type==="query"}function _n(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!Yi(e.introspection,e.currentTable,t,e.currentSchema)){let r=Xi(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Zi(r,e.currentTableAlias??e.currentTable)}return de(t,e)}function eo(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),Pl(t,e,n)}function LS(t){return t.includes("->")}function Jp(t,e){let{col:n,parts:r}=Sn(t);return r.length===0?de(t,e):rs(t,e)}function Ee(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Ee(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Ee(t,a,n))));}else if(s==="$not")r.push(t.not(Ee(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(eo(o,n)));}else {let o=i,a=LS(s);for(let[l,c]of Object.entries(o)){if(Wi(c)){let u=Vi[l];if(!u)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Jp(s,n):_n(s,n)} ${sql.raw(u)} ${de(c.$ref,n)}`);continue}if(l==="$not"){let u=c;for(let[f,p]of Object.entries(u))if(a)r.push(t.not(Kp(s,f,p,n)));else {let d=qp(s,f,p,n);if(d){r.push(t.not(d));continue}let g=Wp(s,f,p,n);if(g){r.push(t.not(g));continue}let m=Hp(s,f,p,n);if(m){r.push(t.not(m));continue}let h=n.operators[f];if(!h)throw new Error(`Unsupported operator: ${f}`);r.push(t.not(h(t,_n(s,n),p)));}}else if($l(c)){let u=eo(c,n),f=n.operators[l];if(!f)throw new Error(`Unsupported operator: ${l}`);r.push(f(t,_n(s,n),u));}else if(a)r.push(Kp(s,l,c,n));else {let u=qp(s,l,c,n);if(u){r.push(u);continue}let f=MS(s,l,c,n);if(f){r.push(f);continue}BS(s,l,n);let p=Ol(s,c,n),d=Wp(s,l,p,n);if(d){r.push(d);continue}let g=Hp(s,l,p,n);if(g){r.push(g);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,_n(s,n),p));}}}}return r.length===1?r[0]:t.and(r)}function qp(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==gn)return null;let s=Yn(t,r);if(!s)return null;let i=zp(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${de(t,r)} IS NULL`:sql`${de(t,r)} IS NOT NULL`;throw Object.assign(new Error(`argument of IS UNKNOWN must be type boolean, not type ${i}`),{code:"42804",detail:null})}function Yn(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?Sn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var FS={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function Hp(t,e,n,r){if(r.dialect!=="postgres")return null;let s=FS[e];if(!s)return null;let i=Yn(t,r);if(!i||Ie(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${_n(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function Wp(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Yn(t,r);if(!s||Ie(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${_n(t,r)})`:sql`to_tsvector(${_n(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function zp(t){switch(t.toLowerCase()){case "bool":return "boolean";case "int8":case "bigserial":case "serial8":return "bigint";case "int4":case "serial":case "serial4":return "integer";case "int2":return "smallint";default:return t.toLowerCase()}}function MS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Yn(t,r),i=zp(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=de(t,r),a=sql`cast(${sql.raw(US(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function US(t){return `'${t.replace(/'/g,"''")}'`}function BS(t,e,n){if(!jS.has(e))return;let r=Yn(t,n);if(!r||Ie(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function Ol(t,e,n){if(!n?.currentTable)return e;let r=Yn(t,n);if(!r)return e;let s=Ie(r.pg_type,r.type);if(s==="color")return Np(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)Cl(i);else Cl(e);return e}function Kp(t,e,n,r){let s=r?Jp(t,r):A(t),o={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<=",$like:"like",$ilike:"ilike"}[e];if(o)return sql`${s} ${sql.raw(o)} ${n}`;if(e==="$is")return n===null?sql`${s} IS NULL`:n===true?sql`${s} IS TRUE`:n===false?sql`${s} IS FALSE`:sql`${s} IS NULL`;if(e==="$isNot")return n===null?sql`${s} IS NOT NULL`:n===true?sql`${s} IS NOT TRUE`:n===false?sql`${s} IS NOT FALSE`:sql`${s} IS NOT NULL`;if(e==="$in"){if(r&&$l(n))return sql`${s} in ${eo(n,r)}`;let a=Ol(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&$l(n))return sql`${s} not in ${eo(n,r)}`;let a=Ol(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function is(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>is(i,e)):r==="$not"?n[r]=is(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function ot(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function Nl(t,e){return `${t}_${e}_fkey`}function to(t,e){return e===Nl(t.table,t.column)}function Gp(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Vp(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function Qp(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function qS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?Vp(e,n,t.fk):Qp(e,n,t.fk);case "parent_column":return Vp(e,n,t.fk);case "target_column":return Qp(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function Yp(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function Xp(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&to(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&to(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Zp(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function ed(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function td(t,e,n,r){let s=r.filter(a=>a.table===t),i=Gp(s.filter(a=>a.ref_table===e)),o=Gp(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function nd(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function rd(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var HS=[Yp,Xp,Zp,ed,td,nd,rd];function sd(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[Yp,Xp,ed,Zp,td,nd,rd]:HS;for(let o of i){let a=o(t,e,n,r);if(a)return qS(a,e,n)}return null}function no(t,e,n,r){t=t.innerJoin(e.junctionTable,s=>{let i=s;for(let o=0;o<e.junctionToTargetCols.length;o++)i=i.onRef(`${e.junctionTable}.${e.junctionToTargetCols[o]}`,"=",`${n}.${e.targetCols[o]}`);return i});for(let s=0;s<e.junctionToParentCols.length;s++)t=t.whereRef(`${e.junctionTable}.${e.junctionToParentCols[s]}`,"=",`${r}.${e.parentCols[s]}`);return t}function os(t,e,n,r){if(e.type==="m2m")return no(t,e,n,r);for(let{leftCol:s,rightCol:i}of ot(e))t=t.whereRef(s,"=",i);return t}function as(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:Nl(t.table,t.column)}function Xn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!ad(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=id(a,e,n,r,s,i);return o=l.remainingWhere,l.expression??sql`1 = 1`}),Object.keys(o).length===Object.keys(e).length?{qb:t,remainingWhere:e}:{qb:t,remainingWhere:o}}function id(t,e,n,r,s,i){let o=[],a={};for(let[c,u]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(u)){let p=u.map(d=>id(t,d,n,r,s,i));if(p.length>0&&p.every(d=>d.fullyHandled&&d.expression)){o.push(c==="$or"?t.or(p.map(d=>d.expression)):t.and(p.map(d=>d.expression)));continue}a[c]=u;continue}let f=WS(t,c,u,n,r,s,i);f?o.push(f):a[c]=u;}let l=o.length===0?null:o.length===1?o[0]:t.and(o);return {expression:l,remainingWhere:a,fullyHandled:l!==null&&Object.keys(a).length===0}}function WS(t,e,n,r,s,i,o){let a=n;if(!a||typeof a!="object")return null;let l="$is"in a&&a.$is===null,c="$isNot"in a&&a.$isNot===null;if(!l&&!c)return null;let u=od(r,e);if(!u)return null;let f=s?.[e],p=Kt(o.introspection,i,f?.from||e,o.dialect,o.currentSchema);if(p){let S=t.selectFrom(ss(p,i,p.targetTable)).select(sql`1`.as("_"));if(u.where&&Object.keys(u.where).length>0){let w=Xn(S,u.where,u.select,u.join,p.targetTable,o);if(S=w.qb,Object.keys(w.remainingWhere).length>0){let x=is(w.remainingWhere,p.targetTable);S=S.where(E=>Ee(E,x,o));}}let _=t.exists(S);return c?_:t.not(_)}let d=xe(i,e,f,o.introspection),{targetTable:g,fkRel:m}=d;if(!m)return null;let h=t.selectFrom(g).select(sql`1`.as("_"));if(f?.on?h=h.where(S=>Ee(S,f.on,o)):h=os(h,m,g,i),u.where&&Object.keys(u.where).length>0){let S=Xn(h,u.where,u.select,u.join,g,o);if(h=S.qb,Object.keys(S.remainingWhere).length>0){let _=is(S.remainingWhere,g);h=h.where(w=>Ee(w,_,o));}}let y=t.exists(h);return c?y:t.not(y)}function od(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&se(r))return r}return null}function ad(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>ad(a,e)))return true;continue}let s=r;if(!s||typeof s!="object")continue;let i="$is"in s&&s.$is===null,o="$isNot"in s&&s.$isNot===null;if((i||o)&&od(e,n))return true}return false}function se(t){return "select"in t||"spread"in t||"join"in t}function Fl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function cs(t){return Fl(t)?.def??null}function KS(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function ld(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function oo(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(ts(l,n.introspection,Ue(n))||so(l,n))?cd(t,l,n,new Set,false,s):t.selectAll();for(let u of e)if(typeof u=="string")if(u==="*")if(c&&l&&(ts(l,n.introspection,Ue(n))||so(l,n))){let f=new Set;for(let p of e){if(p===u)break;if(typeof p=="string"&&p!=="*")f.add(p.includes(".")?p.split(".").pop():p);else if(typeof p!="string")for(let[d]of Object.entries(p))f.add(d);}t=cd(t,l,n,f,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(u))t=t.select(sql.lit(Number(u)).as("_lit"));else if(r_(u,n,s)){let f=i&&s?xt(s,u,n,s):de(u,n,s);t=t.select(sql`json(${f})`.as(u));}else if(c&&l&&s&&!u.includes(".")&&!Yi(n.introspection,l,u,n.currentSchema)){let f=Xi(n.introspection,l,u,n.dialect,n.currentSchema);t=f?t.select(Zi(f,s).as(u)):t.select(u);}else if(c&&s&&l&&Dp(l,ld(u),n.introspection,Ue(n))){let f=ld(u),p=u.includes(".")?sql.ref(u):i?xt(s,u,n,s):sql.ref(u);t=t.select(es(p,l,f,n.dialect,n.introspection,Ue(n)).as(f));}else t=i&&s&&!u.includes(".")?t.select(xt(s,u,n,s).as(u)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&zi(u,n,s)?t.select(de(u,n,s).as(u)):t.select(u);else for(let[f,p]of Object.entries(u))se(p)?t=T_(t,f,p,n,r,l,a):t=YS(t,f,p,n,s,i,l);return t}function Ue(t){return t.currentSchema??t.introspection?.default_schema??"public"}function so(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=Ue(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Wt(r.name,e,t))}function cd(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=Tl(e,n.introspection,Ue(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let u=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let f=Ji(u,c);t=t.select((f??u).as(a));}else Wt(a,n,e)?t=t.select(sql`to_jsonb(${u})`.as(a)):t=s?t.select(u.as(a)):t.select(a);}return t}function us(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(ts(s,n.introspection,Ue(n))||so(s,n))?ud(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(ts(s,n.introspection,Ue(n))||so(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=ud(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Wt(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=es(o,s,i,n.dialect,n.introspection,Ue(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(se(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Wt(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),u=es(c,s,l,n.dialect,n.introspection,Ue(n));t=u!==c?t.returning(u.as(o)):t.returning(l);}else t=t.returning(l);}return t}function ud(t,e,n,r){if(!n.introspection)return t.returningAll();let s=Tl(e,n.introspection,Ue(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=Ji(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Wt(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function fs(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${zS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=Up(l,n.path,r,s,n.pathText===true);else {let c=s&&i?xt(s,l,r,s):de(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?es(c,o??s??r.currentTable,l,r.dialect,r.introspection,Ue(r)):c;}n.preCast&&(wn(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(wn(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&JS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&QS(r,s,n.column)?a=Op(a,r.dialect):a=r.dialect==="sqlite"&&(GS(n.cast)||VS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function JS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function zS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function GS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function VS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function QS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===Ue(t))??s.find(o=>o.schema==="public")??s[0];return Ie(i.pg_type,i.type)==="color"}function YS(t,e,n,r,s,i=false,o){return t.select(a=>fs(a,e,n,r,s,i,o).as(e))}function XS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!se(n)&&n.aggregate)return true}return false}function ZS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(se(n)&&n.spread&&Ml(n.select))return true}return false}function fd(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(se(n)&&n.spread)return true}return false}function e_(t){return XS(t)||ZS(t)}function Ml(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(se(n)){if(Ml(n.select))return true;continue}if(n.aggregate)return true}return false}function Ul(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(se(n)){if(n.spread)continue;if(Ul(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function Bl(t,e,n,r,s,i=false,o){if(!e_(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(de(l,n,r));continue}for(let[c,u]of Object.entries(l))se(u)||u.aggregate||a.push(f=>fs(f,c,u,n,r,i,o));}return t_(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function t_(t,e,n,r,s){if(!(!e||!r||!n.introspection?.foreign_keys)){for(let i of e)if(typeof i!="string")for(let[o,a]of Object.entries(i)){if(!se(a)||!a.spread)continue;let l=a,c=s?.[o],u=xe(r,o,c,n.introspection);if(!u.fkRel||!Rt(u))continue;let f=u.targetTable;u.fkRel;let d=lo(l.select,f,n.introspection)??l.select??[],g=`_spread_${o}`;for(let m of d){if(typeof m=="string"){m!=="*"&&t.push(`${g}.${m}`);continue}let[h,y]=Object.entries(m)[0];se(y)||y.aggregate||t.push(S=>fs(S,h,y,n,g,true));}}}}function gd(t,e,n,r,s){if(!t||!e||!r||!s.introspection?.foreign_keys)return t;let i=new Set;for(let o of e)if(typeof o!="string")for(let[a,l]of Object.entries(o)){if(!se(l)||!l.spread)continue;let c=n?.[a],u=xe(r,a,c,s.introspection);u.fkRel&&Rt(u)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function yd(t,e,n,r){if(!t||!n||!r.introspection?.foreign_keys)return false;for(let s of t)if(typeof s!="string")for(let[i,o]of Object.entries(s)){if(!se(o)||!o.spread)continue;let a=e?.[i],l=xe(n,i,a,r.introspection);if(l.fkRel&&Rt(l))return true}return false}function Zn(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function ls(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function ql(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ot(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ot(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a})}function ao(t,e,n,r,s){let i=new Set;if(!e||!r.introspection?.foreign_keys)return {sub:t,joined:i};for(let o of e){if(!o.embed||i.has(o.embed))continue;Pe(o.embed,"order embed alias");let a=s?.[o.embed],l=xe(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&Pe(l.targetTable,"order embed target"),!l.fkRel||!Rt(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:u}=l;t=ql(t,u,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function n_(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function io(t,e,n){let r=n.includes(".")?n.split(".").pop():n,s=t.introspection?.columns?.find(o=>o.table===e&&o.name===r),i=(s?.pg_type||s?.type||"").toLowerCase();return i==="json"||i==="jsonb"}function r_(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&io(e,n,t)}function s_(t,e){if(!t)return false;let n=e.includes(".")?e.split(".").pop():e;return t.some(r=>r.column.includes("->")?r.column.slice(0,r.column.indexOf("->"))===n:false)}function bd(t,e,n,r){return io(t,e,n)||s_(r,n)}function i_(t,e,n){if(!t)return null;let r=[];for(let s of t){if(typeof s=="string"){if(s==="*")return null;let l=s.includes(".")?s.split(".").pop():s;r.push({alias:l,asJson:io(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(se(o))return null;let a=io(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function o_(t,e,n,r){let s=i_(e,n,r);if(!s||s.length===0)return r.jsonObjectFrom(t);let i=s.flatMap(o=>[sql.lit(o.alias),o.asJson?sql`json(${sql.ref(`obj.${o.alias}`)})`:sql.ref(`obj.${o.alias}`)]);return sql`(select json_object(${sql.join(i)}) from ${t} as obj)`}function wd(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=Fl(e);if(n&&(!se(n.def)||wd(n.def.select)))return true}return false}function Sd(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function a_(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return Sd(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(Rd(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function l_(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&c_(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function c_(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function u_(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of l_(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function f_(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function pd(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function p_(t){let e=[],n=new Map;for(let r of t){let s=f_(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}pd(r)<pd(e[i])&&(e[i]=r);}return e}function Dl(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return as(t.fk)}function jl(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${as(a)}(${a.column}) and ${as(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=as(t.fk);if(t.type==="o2m"){let a=ro(t.rightCols??[t.rightCol]),l=ro(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=ro(t.leftCols??[t.leftCol]),o=ro(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function ro(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function d_(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function Hl(t,e,n,r){let s=t?.foreign_keys?.find(o=>o.table===e||o.ref_table===e)?.schema||"test",i=r?` using the hint '${r}'`:"";throw new ke({httpStatus:400,code:"PGRST200",message:`Could not find a relationship between '${e}' and '${n}' in the schema cache`,details:`Searched for a foreign key relationship between '${e}' and '${n}'${i} in the schema '${s}', but no matches were found.`,hint:d_(t,n,s)})}function m_(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(h=>h.is_visible!==false);if(r){let h=sd(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(h)return h;Hl(t,e,n,r);}if(e===n){let h=Zn(i.filter(y=>y.table===n&&y.ref_table===e))[0];if(h)return ls(e,n,h,"o2m")}let o=i.filter(h=>h.table===e&&h.ref_table===n),a=Zn(o),l=i.filter(h=>h.table===n&&h.ref_table===e),c=Zn(l),u=[],f=Zn(i.filter(h=>h.ref_table===e));for(let h of f){let y=h[0].table;if(y===e||y===n)continue;let S=i.filter(_=>_.table===y&&_.ref_table===n);if(S.length!==0)for(let _ of Zn(S))u.push({type:"m2m",junctionTable:y,junctionToParentCols:h.map(w=>w.column),parentCols:h.map(w=>w.ref_column),junctionToTargetCols:_.map(w=>w.column),targetCols:_.map(w=>w.ref_column),fk:h[0],parentFkGroup:h,targetFkGroup:_});}if(a.length+c.length+u.length===0)return null;let d=[...u];u_(d,t),d=p_(d);let g=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&d.length>1||g||a.length>0&&d.length>1){let h=[...a.map(E=>ls(e,n,E,"m2o")),...c.map(E=>ls(e,n,E,"o2m")),...d],y={o2m:0,m2o:1,m2m:2},S=[...h].sort((E,R)=>{let O=y[E.type]??3,P=y[R.type]??3;if(O!==P)return O-P;let D=Dl(E)??"",v=Dl(R)??"",C=D.localeCompare(v);return C!==0?C:jl(E,e,n).localeCompare(jl(R,e,n))}),_=S.map(E=>({cardinality:a_(E,e,n,t),embedding:`${e} with ${n}`,relationship:jl(E,e,n)})),x=S.map(E=>Dl(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new ke({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:_,hint:x?`Try changing '${n}' to one of the following: ${x}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?ls(e,n,a[0],"m2o"):c.length===1?ls(e,n,c[0],"o2m"):u.length===1?u[0]:null}function h_(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||to(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function g_(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return Sd(e,i,s)?"o2o":"m2o"}return Rd(s,e,n,r,t)?"o2o":"o2m"}function xe(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=h_(s,t,r),a=KS(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?m_(r,t,i,a,l):null,u=g_(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:u,displayHint:a}}function Rt(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function _d(t,e,n,r){if(!(!t||!n||!r.introspection?.foreign_keys))for(let s of t){if(!s.embed)continue;let i=e?.[s.embed],o=xe(n,s.embed,i,r.introspection);if(o.fkRel&&!Rt(o))throw new ke({httpStatus:400,code:"PGRST118",message:`A related order on '${s.embed}' is not possible`,details:`'${n}' and '${s.embed}' do not form a many-to-one or one-to-one relationship`,hint:null})}}function dd(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!se(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let u=Kt(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),f=u?u.targetTable:xe(n,a,c,s.introspection).targetTable;t=t.where(p=>Ed(p,l,f,n,c,l.join??i,s));}return t}function Ed(t,e,n,r,s,i,o){let a=r?Kt(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let f=t.selectFrom(ss(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(f=f.where(p=>Ee(p,e.where,{...o,currentTable:a.targetTable}))),r&&(f=dd(f,e,a.targetTable,i,o)),t.exists(f)}let c=(r?xe(r,s?.from??n,s,o.introspection):null)?.fkRel??null,u=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)u=u.where(f=>Ee(f,s.on,o));else if(c&&c.type==="m2m")u=no(u,c,n,r);else if(c)for(let{leftCol:f,rightCol:p}of ot(c))u=u.whereRef(f,"=",p);else r&&(u=u.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(u=u.where(f=>Ee(f,e.where,{...o,currentTable:n}))),r&&(u=dd(u,e,n,i,o)),t.exists(u)}function md(t,e,n,r,s,i){let o=s?.[e],a=i?Kt(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?xe(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>Ed(c,n,l,i,o,s,r))}function xd(t,e,n){if(!n||t.type!=="o2m")return false;let r=t.leftCol.split(".")[1];return n.indexes?.some(o=>o.table===e&&o.unique&&o.columns.length===1&&o.columns[0]===r)||n.unique_constraints?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)?true:n.primary_keys?.some(o=>o.table===e&&o.columns.length===1&&o.columns[0]===r)??false}function Rd(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(xd(s,n,t))return true;let o=t.foreign_keys.filter(f=>f.is_visible!==false).filter(f=>f.table===n&&f.ref_table===e);if(r){let f=o.filter(p=>p.foreign_key_name===r);f.length>0&&(o=f);}let a=Zn(o);if(a.length!==1)return false;let l=[...a[0].map(f=>f.column)].sort(),c=t.primary_keys?.find(f=>f.table===n);if(!c?.columns?.length)return false;let u=[...c.columns].sort();return l.length===u.length&&l.every((f,p)=>f===u[p])}function y_(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function zt(t){if(typeof t=="string")return {colAlias:t,colName:t};let e=Object.keys(t)[0],n=t[e];return {colAlias:e,colName:n?.column||e}}function b_(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=xe(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,u=lo(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return C_(t,u,l,i,c);if(!c)throw new ke({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});if(!Rt(a)){if(Ml(n.select))throw new ke({httpStatus:400,code:"PGRST127",message:"Feature not implemented",details:"Aggregates are not implemented for one-to-many or many-to-many spreads.",hint:null});return R_(t,u,n,c,l,i,r)}let f=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new ke({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let p=ot(c).map(({leftCol:m,rightCol:h},y)=>{let[S,_]=m.split("."),[,w]=h.split(".");return {targetSideCol:S===l?_:w,parentSideCol:S===i?_:w,joinKey:`__spread_join_key_${y}`}}),d=[],g=new Set;for(let m of u){if(typeof m=="string"&&m==="*")continue;let h;if(typeof m!="string"){let _=cs(m);if(!_||se(_))continue;h=_;}let{colAlias:y,colName:S}=zt(m);d.push({src:S,out:y,def:h}),g.add(S);}t=t.leftJoin(m=>{let h=m.selectFrom(l);for(let{targetSideCol:y,joinKey:S}of p)h=h.select(`${l}.${y} as ${S}`);for(let y of g)h=h.select(`${l}.${y} as ${y}`);return h.as(f)},m=>{let h=m;for(let{joinKey:y,parentSideCol:S}of p)h=h.onRef(`${f}.${y}`,"=",`${i}.${S}`);return h});for(let{out:m,def:h}of d)h?t=t.select(y=>fs(y,m,h,r,f,true).as(m)):t=t.select(`${f}.${m}`);return t}function w_(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=cs(s);if(!i||!se(i))continue;let{colAlias:o}=zt(s),a=e.join?.[o],l=xe(n,o,a,r.introspection),c=l.targetTable,u=l.fkRel;if(!u||u.type!=="o2m"||!xd(u,c,r.introspection))continue;let f=r.introspection?.primary_keys?.find(p=>p.table===c);if(f?.columns?.length)return {nestedTargetTable:c,fkRel:u,pkColumns:f.columns}}return null}function S_(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=os(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(u=>Ee(u,o.where,c));}let l=ao(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Jt(a,n_(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=ql(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Jt(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function __(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Jt(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function E_(t,e,n){if(n&&se(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!Rt(s))return true;let{colName:i}=zt(e);return bd(t.config,r.fromTable,i,t.frames[0].embed.order)}function x_(t,e,n,r){let s=cs(n),{colAlias:i,colName:o}=zt(n),l=e.frames[r].fromTable;if(r===0&&s&&se(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(u=>Cd(u,i,s,e.config,c,l).as("value"))}if(s&&!se(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,u=r>0?i:o;return t.select(f=>fs(f,u,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function Ll(t,e,n,r,s){if(r===e.frames.length-1)return x_(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(Rt(l))return s.has(a.fromTable)||(t=ql(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=__(t,e,a),Ll(t,e,n,r+1,s);let{colName:c}=zt(n);return t.select(u=>{let f=u.selectFrom(a.fromTable);return f=os(f,a.fkRel,a.fromTable,o.fromTable),f=Ll(f,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(f,"value",bd(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function hd(t,e,n){let{colAlias:r}=zt(n),s=cs(n);return t.select(i=>{let{inner:o,joinedToOne:a}=S_(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let u=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(u).as(r)}let c=Ll(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",E_(e,n,s)).as(r)})}function R_(t,e,n,r,s,i,o){let a=n.order?null:w_(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let u=cs(c),f=u!==null&&se(u)&&u.spread,{colAlias:p}=zt(c);if(f){let d=u,g=n.join?.[p],m=xe(s,p,g,o.introspection),h=lo(d.select,m.targetTable,o.introspection)??d.select??[],y={...l,frames:[...l.frames,{embed:d,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let S of h)typeof S=="string"&&S==="*"||(t=hd(t,y,S));continue}t=hd(t,l,c);}return t}function C_(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=zt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:u,rightCol:f}of ot(s))c=c.whereRef(u,"=",f);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function lo(t,e,n){if(!t||!n?.columns||!t.some(i=>i==="*"))return t;let r=n.columns.filter(i=>i.table===e).sort((i,o)=>i.ordinal_position-o.ordinal_position).map(i=>i.name);if(r.length===0)return t;let s=[];for(let i of t)if(i==="*")for(let o of r)s.push(o);else s.push(i);return s}function T_(t,e,n,r,s,i,o){let a=s?.[e];if(!wd(n.select)){if(a?.type==="inner"&&i)return md(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Kt(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=xe(i,e,a,r.introspection);l.fkRel||Hl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=md(t,e,n,r,s,i)),n.spread&&i?b_(t,e,n,r,s,i):t.select(l=>Cd(l,e,n,r,a,i,o).as(e))}function Cd(t,e,n,r,s,i,o){let a=i?Kt(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:xe(i,e,s,r.introspection),c=l.targetTable,{displayHint:u,fkRel:f}=l,p=i===c,d=p?o?`${c}_nested`:`${c}_self`:c,g=p?`${c} as ${d}`:c,m=a?t.selectFrom(ss(a,o??i,d)):t.selectFrom(g),h=i&&!s?.on&&!a?f:null,y=h?.type==="m2m",S=lo(n.select,c,r.introspection),_=y?y_(S,d):S;if(m=oo(m,_,r,n.join,d,y||fd(_),p?c:d,p?d:void 0),n.where&&Object.keys(n.where).length>0){let R=Xn(m,n.where,n.select,n.join,c,r);m=R.qb,Object.keys(R.remainingWhere).length>0&&(m=m.where(O=>Ee(O,R.remainingWhere,{...r,currentTable:c,currentTableAlias:d})));}let w=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(R=>Ee(R,s.on,r));else if(i&&!a){let R=h;if(R&&R.type==="m2m")w="m2m",m=no(m,R,d,i);else if(R?.type==="m2o"){for(let{leftCol:O,rightCol:P}of ot(R)){let[,D]=O.split("."),[,v]=P.split("."),C=o?`${o}.${D}`:`${i}.${D}`;m=m.whereRef(`${d}.${v}`,"=",C);}w="m2o";}else if(R){for(let{leftCol:O,rightCol:P}of ot(R)){let[,D]=O.split("."),[,v]=P.split("."),C=p?`${d}.${D}`:O,q=o?`${o}.${v}`:p?P.replace(`${c}.`,`${i}.`):P;m=m.whereRef(C,"=",q);}w=R.type;}else r.introspection?.foreign_keys?Hl(r.introspection,i,c,u):m=m.whereRef(`${d}.${i}_id`,"=",`${i}.id`);}m=Bl(m,_,r,d,void 0,y||fd(_),p?c:d),n.order?.some(R=>R.embed)&&(m=ao(m,n.order,c,r,n.join).sub),m=Jt(m,n.order,void 0,r,c),w==="m2m"&&!n.order&&h?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${h.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let x=n.spread?true:a?a.toOne:w==="m2o"||l.cardinality==="o2o";return x&&r.dialect==="sqlite"?o_(m,_,c,r):(x?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function Td(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=Fl(s);if(!i||!se(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=xe(n,o,l,r.introspection);if(c.fkRel&&!Rt(c))return true}return false}er();function Wl(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function $_(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${Wl(s)}`);return `${t}.${e}(${r.join(", ")})`}function O_(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(Wl).join(","),i=n.arg_types.map(Wl).join(",");return s<i?-1:s>i?1:0})}function Ad(t,e,n){return {message:`Could not choose the best candidate function between: ${O_(n).map(i=>$_(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function $d(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(f=>f.schema===r&&f.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let f=Gt(n,{schema:r,fnName:s,providedNames:o});if(f.length>1)return Ad(r,s,c);if(f.length===1)return null}if(i==="POST"&&a!=="text"){let f=c.filter(p=>!p.has_variadic&&p.arg_types.length===1&&p.arg_names.length===0&&(p.arg_types[0]==="json"||p.arg_types[0]==="jsonb"));if(f.length>1)return Ad(r,s,f)}return null}function En(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function Od(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function P_(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function Gt(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&P_(i,s))}function uo(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=Gt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function fo(t,e){let n=uo(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function Pd(t,e){let n=uo(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function N_(t){return [...t].sort().join(", ")}function I_(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:N_(e)}}function D_(t,e,n,r){let s=r.filter(p=>p.schema===t),i=()=>{let p=[...new Set(s.map(d=>d.name))].filter(d=>d!==e);return ps(e,p)},o=p=>`Perhaps you meant to call the function ${t}.${p}`,a=p=>`Perhaps you meant to call the function ${t}.${e}(${p})`,l=s.filter(p=>p.name===e).map(I_).filter(p=>p!==null);if(l.length===0){let p=i();return p?o(p):null}if(s.filter(p=>p.name===e).length>1){let p=l.filter(d=>d.arity===n.length);return p.length===1?a(p[0].sig):null}return l[0].sig.split(", ").every(p=>n.includes(p)||ps(p,n)!==null)?a(l[0].sig):null}function kd(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",u=c&&o==="text",f;u?f=`with a single unnamed ${a??"text"} parameter`:c?f=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:f=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let p=`Searched for the function ${n}.${r} ${f}, but no matches were found in the schema cache.`,d;l.length>0?d=`${n}.${r}(${l.join(", ")})`:u?d=`${n}.${r}`:d=`${n}.${r} without parameters`;let g=`Could not find the function ${d} in the schema cache`,m=D_(n,r,i,e);return {message:g,details:p,hint:m}}function Kl(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?kd(e,n):e.paramsType==="positional"&&e.providedNames.length===0||Gt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:kd(e,n)}function j_(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function zl(t,e,n,r,s={}){if(!t)return t;let i=j_(e,n,r),o=a=>{let l=L_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):F_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function L_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??Ld(n,r,s,o)??void 0;i[o]=M_(a,l,n.dialect);}return i}function F_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=Ld(e,n,r,i);s[i]=U_(a)?mo(o):o;}return s}function Ld(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ie(a.pg_type,a.type)}function M_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&Me(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return Gn(i.startsWith("#")?i:`#${i}`)}return t}return Ip(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return Gn(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=ds(e);return i==="boolean"?Nd(t):i==="integer"?po(t,true):i==="number"?po(t,false):i==="json"?Jl(t):i==="array"?Id(t):t}if(r==="color")return Gn(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=ds(e);return s==="boolean"?Nd(t):s==="integer"?po(t,true):s==="number"?po(t,false):s==="json"?Jl(t):s==="array"?Id(t):t}function ds(t){if(!t)return;let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "array";if(e==="bool"||e==="boolean")return "boolean";if(["int2","smallint","int4","integer","int","int8","bigint"].includes(e))return "integer";if(["float4","real","float8","double precision","numeric","decimal"].includes(e))return "number";if(e==="json"||e==="jsonb")return "json"}function Nd(t){let e=t.trim().toLowerCase();return ["true","t","1","yes","y","on"].includes(e)?true:["false","f","0","no","n","off"].includes(e)?false:t}function po(t,e){let n=t.trim();if(n==="")return t;let r=Number(n);return !Number.isFinite(r)||e&&!Number.isInteger(r)?t:r}function Jl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function Id(t){let e=Jl(t);return Array.isArray(e)?e:t}function U_(t){let e=ds(t);return e==="json"||e==="array"}var B_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function Dd(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !B_.has(n)}function mo(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function Fd(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return Pl(t,e,n);case "insert":return H_(t,e,n);case "update":return W_(t,e,n);case "delete":return K_(t,e,n);case "upsert":case "put":return J_(t,e,n);case "rpc":return G_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Jt(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Pe(i.embed,"order embed alias"),i.column.includes("->")?r?rs(i.column,r,s,i.embed):jd(i.column,i.embed):(Pe(i.column,"order embed column"),r?xt(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?rs(i.column,r,s,n):jd(i.column,void 0,n):n?r?xt(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?de(i.column,r,s):i.column,a=i.nullsFirst!==void 0?i.nullsFirst:r?.dialect==="sqlite"?i.direction==="desc":void 0;a!==void 0?t=t.orderBy(o,l=>{let c=i.direction==="desc"?l.desc():l.asc();return a?c.nullsFirst():c.nullsLast()}):t=t.orderBy(o,i.direction||"asc");}return t}function jd(t,e,n){let{col:r,parts:s}=Sn(t);if(s.length===0)return sql.ref(t);e&&Pe(r,"order embed column");let i=ns(s,"ORDER BY JSON path key");return e?sql`${sql.ref(e)}.${sql.ref(r)}${sql.raw(i)}`:n?sql`${sql.ref(n)}.${sql.ref(r)}${sql.raw(i)}`:sql`${sql.ref(r)}${sql.raw(i)}`}function ms(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Ee(i,e,{...n,currentTable:r,currentSchema:s}))}function Pl(t,e,n){let r=n.selectFrom(t.from);return Md(r,t,e,t.from)}function Md(t,e,n,r){t=q_(t,e.join,e.select);let s=e.order?.some(u=>u.embed)===true;t=oo(t,e.select,n,e.join,r,s||yd(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=Xn(t,i,e.select,e.join,r,n);t=o,t=ms(t,a,n,r,e.schema),t=Bl(t,e.select,n,r,e.join),_d(e.order,e.join,r,n),s&&(t=ao(t,e.order,r,n,e.join).sub);let l=Td(e.select,e.join,r,n)?r:void 0,c=gd(e.order,e.select,e.join,r,n);return t=Jt(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function q_(t,e,n){if(!e)return t;let r=new Set;if(n){for(let s of n)if(typeof s!="string")for(let i of Object.keys(s))r.add(i);}for(let[s,i]of Object.entries(e)){if(!i.on||r.has(s))continue;let o=i.from||s,a=i.type==="left"?"leftJoin":"innerJoin";t=t[a](`${o} as ${s}`,l=>Ud(l,i.on));}return t}function Ud(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=Ud(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Vi[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Wi(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function H_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=zl(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function W_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=zl(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=Bd(r,t,e,n):r=ms(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function K_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=Bd(r,t,e,n):r=ms(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=us(r,t.select,s),r}function Bd(t,e,n,r){let i=n.introspection?.primary_keys.find(l=>l.table===e.from)?.columns??[],o=r.selectFrom(e.from),a=n.rowIdColumn;if(i.length>0)for(let l of i)o=o.select(l);else o=o.select(sql.ref(a).as("__rowid"));if(o=ms(o,e.where??{},n,e.from,e.schema),o=Jt(o,e.order,void 0,n,e.from),e.limit!==void 0&&(o=o.limit(e.limit)),e.offset!==void 0&&(o=o.offset(e.offset)),i.length===1)return t.where(i[0],"in",o);if(i.length>1){let l="__ltd_target",c=r.selectFrom(o.as(l)).select(sql`1`.as("_"));for(let u of i)c=c.whereRef(`${l}.${u}`,"=",`${e.from}.${u}`);return t.where(u=>u.exists(c))}else return t.where(sql.ref(a),"in",o)}function J_(t,e,n){let r=t.values,s=zl(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,u=Object.keys(c).filter(f=>!t.onConflict.includes(f));return u.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(f=>{let p={};for(let d of u)p[d]=f.ref(`excluded.${d}`);return p})}));let o=t.from?{...e,currentTable:t.from}:e;return i=us(i,t.select,o),i}function z_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?En(t):Object.keys(t.args);if(Gt(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function G_(t,e,n){let r=t.function;Pe(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(Pe(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,Pe(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?z_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${mo(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let f=Object.entries(t.args),p=null,d=null,g=null;if(e.dialect==="postgres"&&e.introspection?.functions){let y=f.map(([_])=>_),S=Gt(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:y});if(S.length===1){let _=S[0];p=new Map;for(let w=0;w<_.arg_names.length;w++)p.set(_.arg_names[w],_.arg_types[w]);if(_.has_variadic&&_.arg_names.length>0){d=_.arg_names[_.arg_names.length-1];let w=_.arg_types[_.arg_types.length-1];g=w.endsWith("[]")?w.slice(0,-2):w;}}}let m=t.httpMethod==="GET",h=f.map(([y,S])=>{if(Pe(y,"RPC param key"),p){let w=p.get(y);if(w){if(y===d&&g){wn(g,"RPC variadic elem type"),Pe(y,"RPC variadic param key");let x=Array.isArray(S)?S:[S];return sql`VARIADIC ${sql.raw(y)} := ${x}::${sql.raw(g+"[]")}`}if(Dd(w)){wn(w,"RPC arg type");let x=m&&Array.isArray(S)?S[S.length-1]:S,E=ds(w),R=E==="json"||E==="array"&&!Array.isArray(x)?mo(x):x;return sql`${sql.raw(y)} := ${R}::${sql.raw(w)}`}}}let _=m&&Array.isArray(S)?S[S.length-1]:S;return sql`${sql.raw(y)} := ${_}`});o=sql`${sql.raw(i)}(${sql.join(h)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let f=null;if(e.dialect==="postgres"&&e.introspection?.functions){let d=e.introspection.functions,g=t.schema??e.introspection?.default_schema??"public",h=t.args.length,y=d.filter(S=>S.schema===g&&S.name===r&&S.arg_types.length===h);y.length===1&&(f=y[0].arg_types);}let p=t.args.map((d,g)=>{if(f){let m=f[g];if(m&&Dd(m)){wn(m,"RPC positional arg type");let h=ds(m),y=h==="json"||h==="array"&&!Array.isArray(d)?mo(d):d;return sql`${y}::${sql.raw(m)}`}}return sql`${d}`});o=sql`${sql.raw(i)}(${sql.join(p)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let f=Pd(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:En(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(f)return Md(n.selectFrom(o.as(f)),t,e,f)}let u=n.selectFrom(o.as(r));return u=oo(u,t.select,e),u=ms(u,t.where??{},e,t.from,t.schema),u=Jt(u,t.order,void 0,e,t.from),t.limit!==void 0&&(u=u.limit(t.limit)),t.offset!==void 0&&(u=u.offset(t.offset)),u}var nE=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),rE={$ilike:(t,e,n)=>sql`${A(e)} ilike ${n}`,$regex:(t,e,n)=>sql`${A(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${A(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${A(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${A(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${A(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${A(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${A(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${A(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${A(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${A(e)} -|- ${n}`,$textSearch:(t,e,n)=>{let r=n,s=r.config||"english",i="to_tsquery";return r.type==="plain"?i="plainto_tsquery":r.type==="phrase"?i="phraseto_tsquery":r.type==="websearch"&&(i="websearch_to_tsquery"),sql`${A(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${A(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${A(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${A(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${A(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${A(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${A(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${A(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${A(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${A(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${A(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${A(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${A(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${A(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${A(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${A(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${A(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${A(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${A(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${A(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${A(e)} ~* all(${n})`};function sE(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||Vn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function iE(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var qd={db:nE,operators:{...Gi,...rE},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:iE,jsonPath:sE,rowIdColumn:"ctid"};var oE=/[.*+?[\]{}()|]/;function ho(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function Hd(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function Gl(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=Hd(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=Hd(r),n+=1;}return e}function go(t){return t?oE.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function Wd(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return go(e)?{mode:"exact",text:ho(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return go(e)?{mode:"prefix",text:ho(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return go(e)?{mode:"suffix",text:ho(e)}:null}return go(t)?{mode:"contains",text:ho(t)}:null}function Kd(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Jd(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var mE=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function hE(t,e){let n=e.replace(/^\$\./,"").split(".");if(n.length===0)return sql.ref(t);let r=n.map((s,i)=>{let o=i===n.length-1?"->>":"->",a=/^-?\d+$/.test(s);return a||Vn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function gE(t,e){let n=A(t);if(e.length===0)return sql`(${n} is not null)`;let r=sql.join(e.map(s=>sql`${s}`));return sql`(${n} is not null and (select count(distinct value) from json_each(${n}) where value in (${r})) = ${sql.lit(e.length)})`}function yE(t,e){let n=A(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(Vn(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var bE=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function wE(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function zd(t,e,n){let r=wE(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function SE(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function Vl(t,e){let n=A(t),r=SE(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>Vl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>Vl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>zd(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!bE.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>zd(n,o,e.config)),i)})`}function Ql(t,e){return sql`${A(t)} GLOB ${e}`}function _E(t,e){let n=A(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function EE(t,e){let n=A(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Gd(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=Wd(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Jd(r.mode,r.text),o=A(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=Kd(r.mode,r.text);return Ql(t,s)}function yo(t,e,n,r){if(!Array.isArray(e))throw new Error(`$${n}${r} on sqlite requires an array value`);if(e.length===0)return r==="any"?sql`false`:sql`true`;let s=A(t),i=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:Ql(t,typeof o=="string"?Gl(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var xE={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?_E(e,n):sql`${A(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${A(e)}) != json(${JSON.stringify(n)})`:sql`${A(e)} != ${n}`,$textSearch:(t,e,n)=>Vl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return Ql(e,Gl(n))},$regex:(t,e,n)=>Gd(e,n,false),$iregex:(t,e,n)=>Gd(e,n,true),$ilike:(t,e,n)=>sql`lower(${A(e)}) like lower(${n})`,$likeAny:(t,e,n)=>yo(e,n,"like","any"),$ilikeAny:(t,e,n)=>yo(e,n,"ilike","any"),$likeAll:(t,e,n)=>yo(e,n,"like","all"),$ilikeAll:(t,e,n)=>yo(e,n,"ilike","all"),$isDistinct:(t,e,n)=>EE(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return gE(e,n);if(n!==null&&typeof n=="object")return yE(e,n);throw new Error("$contains on sqlite requires an array or object value")},$containedBy:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$containedBy on sqlite requires an array value");let r=A(e),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=A(e);if(n.length===0)return sql`1 = 0`;let s=sql.join(n.map(i=>sql`${i}`));return sql`(${r} is not null and exists (select 1 from json_each(${r}) where value in (${s})))`}};function RE(t,e="value",n=false){let r=sql.ref(e),s=n?sql`json_group_array(json(${r}))`:sql`json_group_array(${r})`;return sql`(select coalesce(${s}, json('[]')) from ${t} as _agg)`}var Vd={db:mE,operators:{...Gi,...xE},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:RE,jsonPath:hE,rowIdColumn:"rowid"};function CE(t){switch(t){case "postgres":return qd;case "sqlite":return Vd;default:throw new Error(`Unsupported dialect: ${t}`)}}function ne(t,e="postgres",n){let r=CE(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return Fd(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var Jc=ka(Xl());bs();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function at(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}var xn=new TextEncoder,Ct=new TextDecoder;function So(...t){let e=t.reduce((s,{length:i})=>s+i,0),n=new Uint8Array(e),r=0;for(let s of t)n.set(s,r),r+=s.length;return n}function Qt(t){let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r>127)throw new TypeError("non-ASCII string encountered in encode()");e[n]=r;}return e}function lm(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,n=[];for(let r=0;r<t.length;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(""))}function cm(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function tr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:Ct.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=Ct.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return cm(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function _o(t){let e=t;return typeof e=="string"&&(e=xn.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:true}):lm(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var vt={};Ir(vt,{JOSEAlgNotAllowed:()=>ws,JOSEError:()=>ye,JOSENotSupported:()=>Be,JWEDecryptionFailed:()=>sc,JWEInvalid:()=>ic,JWKInvalid:()=>oc,JWKSInvalid:()=>ac,JWKSMultipleMatchingKeys:()=>cc,JWKSNoMatchingKey:()=>lc,JWKSTimeout:()=>uc,JWSInvalid:()=>Z,JWSSignatureVerificationFailed:()=>Ss,JWTClaimValidationFailed:()=>De,JWTExpired:()=>nr,JWTInvalid:()=>Tt});var ye=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,n){super(e,n),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor);}},De=class extends ye{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,n,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:n}}),this.claim=r,this.reason=s,this.payload=n;}},nr=class extends ye{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,n,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:n}}),this.claim=r,this.reason=s,this.payload=n;}},ws=class extends ye{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Be=class extends ye{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},sc=class extends ye{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",n){super(e,n);}},ic=class extends ye{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Z=class extends ye{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Tt=class extends ye{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},oc=class extends ye{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},ac=class extends ye{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},lc=class extends ye{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",n){super(e,n);}},cc=class extends ye{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",n){super(e,n);}},uc=class extends ye{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",n){super(e,n);}},Ss=class extends ye{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",n){super(e,n);}};var lt=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),rr=(t,e)=>t.name===e;function fc(t){return parseInt(t.name.slice(4),10)}function PE(t){switch(t){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}function NE(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function um(t,e,n){switch(e){case "HS256":case "HS384":case "HS512":{if(!rr(t.algorithm,"HMAC"))throw lt("HMAC");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!rr(t.algorithm,"RSASSA-PKCS1-v1_5"))throw lt("RSASSA-PKCS1-v1_5");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!rr(t.algorithm,"RSA-PSS"))throw lt("RSA-PSS");let r=parseInt(e.slice(2),10);if(fc(t.algorithm.hash)!==r)throw lt(`SHA-${r}`,"algorithm.hash");break}case "Ed25519":case "EdDSA":{if(!rr(t.algorithm,"Ed25519"))throw lt("Ed25519");break}case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":{if(!rr(t.algorithm,e))throw lt(e);break}case "ES256":case "ES384":case "ES512":{if(!rr(t.algorithm,"ECDSA"))throw lt("ECDSA");let r=PE(e);if(t.algorithm.namedCurve!==r)throw lt(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}NE(t,n);}function fm(t,e,...n){if(n=n.filter(Boolean),n.length>2){let r=n.pop();t+=`one of type ${n.join(", ")}, or ${r}.`;}else n.length===2?t+=`one of type ${n[0]} or ${n[1]}.`:t+=`of type ${n[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var pm=(t,...e)=>fm("Key must be ",t,...e),pc=(t,e,...n)=>fm(`Key for the ${t} algorithm must be `,e,...n);var dc=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return true;try{return t instanceof CryptoKey}catch{return false}},mc=t=>t?.[Symbol.toStringTag]==="KeyObject",hc=t=>dc(t)||mc(t);function Eo(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return true;let n;for(let r of e){let s=Object.keys(r);if(!n||n.size===0){n=new Set(s);continue}for(let i of s){if(n.has(i))return false;n.add(i);}}return true}var IE=t=>typeof t=="object"&&t!==null;function Yt(t){if(!IE(t)||Object.prototype.toString.call(t)!=="[object Object]")return false;if(Object.getPrototypeOf(t)===null)return true;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function xo(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:n}=e.algorithm;if(typeof n!="number"||n<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function DE(t){let e,n;switch(t.kty){case "AKP":{switch(t.alg){case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":e={name:t.alg},n=t.priv?["sign"]:["verify"];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "RSA":{switch(t.alg){case "PS256":case "PS384":case "PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},n=t.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},n=t.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},n=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "EC":{switch(t.alg){case "ES256":e={name:"ECDSA",namedCurve:"P-256"},n=t.d?["sign"]:["verify"];break;case "ES384":e={name:"ECDSA",namedCurve:"P-384"},n=t.d?["sign"]:["verify"];break;case "ES512":e={name:"ECDSA",namedCurve:"P-521"},n=t.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},n=t.d?["deriveBits"]:[];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "OKP":{switch(t.alg){case "Ed25519":case "EdDSA":e={name:"Ed25519"},n=t.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":e={name:t.crv},n=t.d?["deriveBits"]:[];break;default:throw new Be('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Be('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:e,keyUsages:n}}async function dm(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:n}=DE(t),r={...t};return r.kty!=="AKP"&&delete r.alg,delete r.use,crypto.subtle.importKey("jwk",r,e,t.ext??!(t.d||t.priv),t.key_ops??n)}function Ro(t,e,n,r,s){if(s.crit!==void 0&&r?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;n!==void 0?i=new Map([...Object.entries(n),...e.entries()]):i=e;for(let o of r.crit){if(!i.has(o))throw new Be(`Extension Header Parameter "${o}" is not recognized`);if(s[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&r[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(r.crit)}function mm(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(n=>typeof n!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var _s=t=>Yt(t)&&typeof t.kty=="string",hm=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),gm=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,ym=t=>t.kty==="oct"&&typeof t.k=="string";var sr,bm=async(t,e,n,r=false)=>{sr||=new WeakMap;let s=sr.get(t);if(s?.[n])return s[n];let i=await dm({...e,alg:n});return r&&Object.freeze(t),s?s[n]=i:sr.set(t,{[n]:i}),i},LE=(t,e)=>{sr||=new WeakMap;let n=sr.get(t);if(n?.[e])return n[e];let r=t.type==="public",s=!!r,i;if(t.asymmetricKeyType==="x25519"){switch(e){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}i=t.toCryptoKey(t.asymmetricKeyType,s,r?[]:["deriveBits"]);}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[r?"verify":"sign"]);}switch(t.asymmetricKeyType){case "ml-dsa-44":case "ml-dsa-65":case "ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");i=t.toCryptoKey(t.asymmetricKeyType,s,[r?"verify":"sign"]);}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case "RSA-OAEP":o="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":o="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":o="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},s,r?["encrypt"]:["decrypt"]);i=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},s,[r?"verify":"sign"]);}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&a==="P-256"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e==="ES384"&&a==="P-384"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e==="ES512"&&a==="P-521"&&(i=t.toCryptoKey({name:"ECDSA",namedCurve:a},s,[r?"verify":"sign"])),e.startsWith("ECDH-ES")&&(i=t.toCryptoKey({name:"ECDH",namedCurve:a},s,r?[]:["deriveBits"]));}if(!i)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return n?n[e]=i:sr.set(t,{[e]:i}),i};async function Co(t,e){if(t instanceof Uint8Array||dc(t))return t;if(mc(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return LE(t,e)}catch(r){if(r instanceof TypeError)throw r}let n=t.export({format:"jwk"});return bm(t,n,e)}if(_s(t))return t.k?tr(t.k):bm(t,t,e,true);throw new Error("unreachable")}var ir=t=>t?.[Symbol.toStringTag],gc=(t,e,n)=>{if(e.use!==void 0){let r;switch(n){case "sign":case "verify":r="sig";break;case "encrypt":case "decrypt":r="enc";break}if(e.use!==r)throw new TypeError(`Invalid key for this operation, its "use" must be "${r}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let r;switch(true){case(n==="sign"||n==="verify"):case t==="dir":case t.includes("CBC-HS"):r=n;break;case t.startsWith("PBES2"):r="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?r=n==="encrypt"?"wrapKey":"unwrapKey":r=n;break;case(n==="encrypt"&&t.startsWith("RSA")):r="wrapKey";break;case n==="decrypt":r=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(r&&e.key_ops?.includes?.(r)===false)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return true},FE=(t,e,n)=>{if(!(e instanceof Uint8Array)){if(_s(e)){if(ym(e)&&gc(t,e,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!hc(e))throw new TypeError(pc(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ir(e)} instances for symmetric algorithms must be of type "secret"`)}},ME=(t,e,n)=>{if(_s(e))switch(n){case "decrypt":case "sign":if(hm(e)&&gc(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if(gm(e)&&gc(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!hc(e))throw new TypeError(pc(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${ir(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(n){case "sign":throw new TypeError(`${ir(e)} instances for asymmetric algorithm signing must be of type "private"`);case "decrypt":throw new TypeError(`${ir(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(n){case "verify":throw new TypeError(`${ir(e)} instances for asymmetric algorithm verifying must be of type "public"`);case "encrypt":throw new TypeError(`${ir(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function To(t,e,n){switch(t.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":FE(t,e,n);break;default:ME(t,e,n);}}function vo(t,e){let n=`SHA-${t.slice(-3)}`;switch(t){case "HS256":case "HS384":case "HS512":return {hash:n,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:n,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:n,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:n,name:"ECDSA",namedCurve:e.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":return {name:t};default:throw new Be(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ao(t,e,n){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(pm(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},false,[n])}return um(e,t,n),e}async function wm(t,e,n,r){let s=await Ao(t,e,"verify");xo(t,s);let i=vo(t,s.algorithm);try{return await crypto.subtle.verify(i,s,n,r)}catch{return false}}async function Sm(t,e,n){if(!Yt(t))throw new Z("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new Z("JWS Protected Header incorrect type");if(t.payload===void 0)throw new Z("JWS Payload missing");if(typeof t.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Yt(t.header))throw new Z("JWS Unprotected Header incorrect type");let r={};if(t.protected)try{let h=tr(t.protected);r=JSON.parse(Ct.decode(h));}catch{throw new Z("JWS Protected Header is invalid")}if(!Eo(r,t.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...r,...t.header},i=Ro(Z,new Map([["b64",true]]),n?.crit,r,s),o=true;if(i.has("b64")&&(o=r.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=s;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=n&&mm("algorithms",n.algorithms);if(l&&!l.has(a))throw new ws('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let c=false;typeof e=="function"&&(e=await e(r,t),c=true),To(a,e,"verify");let u=So(t.protected!==void 0?Qt(t.protected):new Uint8Array,Qt("."),typeof t.payload=="string"?o?Qt(t.payload):xn.encode(t.payload):t.payload),f;try{f=tr(t.signature);}catch{throw new Z("Failed to base64url decode the signature")}let p=await Co(e,a);if(!await wm(a,p,f,u))throw new Ss;let g;if(o)try{g=tr(t.payload);}catch{throw new Z("Failed to base64url decode the payload")}else typeof t.payload=="string"?g=xn.encode(t.payload):g=t.payload;let m={payload:g};return t.protected!==void 0&&(m.protectedHeader=r),t.header!==void 0&&(m.unprotectedHeader=t.header),c?{...m,key:p}:m}async function _m(t,e,n){if(t instanceof Uint8Array&&(t=Ct.decode(t)),typeof t!="string")throw new Z("Compact JWS must be a string or Uint8Array");let{0:r,1:s,2:i,length:o}=t.split(".");if(o!==3)throw new Z("Invalid Compact JWS");let a=await Sm({payload:s,protected:r,signature:i},e,n),l={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...l,key:a.key}:l}var Xt=t=>Math.floor(t.getTime()/1e3),xm=60,Rm=xm*60,yc=Rm*24,UE=yc*7,BE=yc*365.25,qE=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Es(t){let e=qE.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let n=parseFloat(e[2]),r=e[3].toLowerCase(),s;switch(r){case "sec":case "secs":case "second":case "seconds":case "s":s=Math.round(n);break;case "minute":case "minutes":case "min":case "mins":case "m":s=Math.round(n*xm);break;case "hour":case "hours":case "hr":case "hrs":case "h":s=Math.round(n*Rm);break;case "day":case "days":case "d":s=Math.round(n*yc);break;case "week":case "weeks":case "w":s=Math.round(n*UE);break;default:s=Math.round(n*BE);break}return e[1]==="-"||e[4]==="ago"?-s:s}function Rn(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Em=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,HE=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):false;function Cm(t,e,n={}){let r;try{r=JSON.parse(Ct.decode(e));}catch{}if(!Yt(r))throw new Tt("JWT Claims Set must be a top-level JSON object");let{typ:s}=n;if(s&&(typeof t.typ!="string"||Em(t.typ)!==Em(s)))throw new De('unexpected "typ" JWT header value',r,"typ","check_failed");let{requiredClaims:i=[],issuer:o,subject:a,audience:l,maxTokenAge:c}=n,u=[...i];c!==void 0&&u.push("iat"),l!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let g of new Set(u.reverse()))if(!(g in r))throw new De(`missing required "${g}" claim`,r,g,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new De('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new De('unexpected "sub" claim value',r,"sub","check_failed");if(l&&!HE(r.aud,typeof l=="string"?[l]:l))throw new De('unexpected "aud" claim value',r,"aud","check_failed");let f;switch(typeof n.clockTolerance){case "string":f=Es(n.clockTolerance);break;case "number":f=n.clockTolerance;break;case "undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=n,d=Xt(p||new Date);if((r.iat!==void 0||c)&&typeof r.iat!="number")throw new De('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new De('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>d+f)throw new De('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new De('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=d-f)throw new nr('"exp" claim timestamp check failed',r,"exp","check_failed")}if(c){let g=d-r.iat,m=typeof c=="number"?c:Es(c);if(g-f>m)throw new nr('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(g<0-f)throw new De('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}var ko=class{#e;constructor(e){if(!Yt(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e);}data(){return xn.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e;}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e;}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e;}set jti(e){this.#e.jti=e;}set nbf(e){typeof e=="number"?this.#e.nbf=Rn("setNotBefore",e):e instanceof Date?this.#e.nbf=Rn("setNotBefore",Xt(e)):this.#e.nbf=Xt(new Date)+Es(e);}set exp(e){typeof e=="number"?this.#e.exp=Rn("setExpirationTime",e):e instanceof Date?this.#e.exp=Rn("setExpirationTime",Xt(e)):this.#e.exp=Xt(new Date)+Es(e);}set iat(e){e===void 0?this.#e.iat=Xt(new Date):e instanceof Date?this.#e.iat=Rn("setIssuedAt",Xt(e)):typeof e=="string"?this.#e.iat=Rn("setIssuedAt",Xt(new Date)+Es(e)):this.#e.iat=Rn("setIssuedAt",e);}};async function Cn(t,e,n){let r=await _m(t,e,n);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===false)throw new Tt("JWTs MUST NOT use unencoded payload");let i={payload:Cm(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}async function Tm(t,e,n){let r=await Ao(t,e,"sign");xo(t,r);let s=await crypto.subtle.sign(vo(t,r.algorithm),r,n);return new Uint8Array(s)}var $o=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e;}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setUnprotectedHeader(e){if(this.#n)throw new TypeError("setUnprotectedHeader can only be called once");return this.#n=e,this}async sign(e,n){if(!this.#t&&!this.#n)throw new Z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Eo(this.#t,this.#n))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#n},s=Ro(Z,new Map([["b64",true]]),n?.crit,this.#t,r),i=true;if(s.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=r;if(typeof o!="string"||!o)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');To(o,e,"sign");let a,l;i?(a=_o(this.#e),l=Qt(a)):(l=this.#e,a="");let c,u;this.#t?(c=_o(JSON.stringify(this.#t)),u=Qt(c)):(c="",u=new Uint8Array);let f=So(u,Qt("."),l),p=await Co(e,o),d=await Tm(o,p,f),g={signature:_o(d),payload:a};return this.#n&&(g.header=this.#n),this.#t&&(g.protected=c),g}};var Oo=class{#e;constructor(e){this.#e=new $o(e);}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,n){let r=await this.#e.sign(e,n);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return `${r.protected}.${r.payload}.${r.signature}`}};var Tn=class{#e;#t;constructor(e={}){this.#t=new ko(e);}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,n){let r=new Oo(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===false)throw new Tt("JWTs MUST NOT use unencoded payload");return r.sign(e,n)}};async function vm(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:at({status:401,code:"PGRST302",message:"Anonymous access is disabled"})};let n=t.slice(7).trim(),r=n.split(".");if(r.length!==3||r.some(s=>s.length===0))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:at({status:401,code:"PGRST301",message:`Expected 3 parts in JWT; got ${Math.max(1,r.filter(s=>s.length>0).length)}`})};if(!e.jwtSecret)return {kind:"error",response:at({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await Cn(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:at({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof vt.JWTExpired?{kind:"error",response:at({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:at({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}Dc();function dx(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function mx(t,e){let n=t.schema||"public",r=Rl(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function Im(t,e){let n=mx(t,e);return Me(n.pgTypeName)?jp(n)??ct(n):ct(n)}function hx(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new Zt(r.table,s),n.set(i,o)),o.set(r.name,Im(r,t));}return n}function gx(t,e){for(let n of e.columns){if(!Me(Rl(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new Zt(n.table,r),t.set(s,i)),i.set(n.name,Im(n,e));}return t}function Dm(t,e,n){if(n==="sqlite")return hx(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return gx(new Map(r),e)}return t&&t.size>0?t:new Map}function jm(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function Lm(t,e,n,r){return !n||!e?.from?t:t.map(s=>jc(s,e.select,e.from,e.schema,e.join,n,r))}function jc(t,e,n,r,s,i,o){let a=dx(i,n,r,o),l=bx(e,s),c={};for(let[u,f]of Object.entries(t)){let p=l.get(u);if(p&&"embed"in p){let m=p.embed;c[u]=yx(f,m,r,i,o);continue}let d=p?.sourceColumn??u,g=a?.get(d);c[u]=g?.isShimBacked?g.deserialize(f):f;}return c}function yx(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?jc(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?jc(t,e.select,e.table,n,e.join,r,s):t}function bx(t,e){let n=new Map;if(!t)return n;for(let r of t){if(typeof r=="string"){if(r==="*")continue;n.set(r,{sourceColumn:r});continue}if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))if(wx(i)){let o=e?.[s]?.from??s;n.set(s,{embed:{table:o,select:i.select,join:i.join}});}else {let o=i;if(o.cast||o.path||o.aggregate)continue;n.set(s,{sourceColumn:o.column??s});}}return n}function wx(t){return t!=null&&typeof t=="object"&&("select"in t||"where"in t||"order"in t||"limit"in t||"offset"in t||"spread"in t||"join"in t)}var ar=class extends Error{constructor(n,r){super(`Could not find the table '${[n,r].filter(Boolean).join(".")}' in the schema cache`);this.schema=n;this.relation=r;}},Lc=class{constructor(e){this.config=e;}kysely;introspection;async translateDdl(e){return e}async clearSchemaCache(){this.introspection=void 0,await this.deleteCachedIntrospection();}async readCachedIntrospection(e){if(typeof this.introspection=="object"&&e?.useCache===true)return this.introspection;if(e?.useCache!==true||!this.config.schemaCache)return;let n=await this.config.schemaCache.get(this.schemaCacheKey());if(n)try{return this.introspection=JSON.parse(n),this.introspection}catch{await this.deleteCachedIntrospection();return}}async writeCachedIntrospection(e,n){this.introspection=e,n?.useDriver===true&&await this.config.schemaCache?.set(this.schemaCacheKey(),JSON.stringify(e));}async deleteCachedIntrospection(){await this.config.schemaCache?.delete(this.schemaCacheKey());}schemaCacheKey(){return ["@supabase/lite","schema-cache",this.dialect,this.config.introspection?.name??"",this.config.url??""].join(":")}async exec(e,...n){try{return sql(e,...n??[]).execute(this.kysely)}catch(r){throw console.error(r),new Error(`Failed to execute query: ${e}`)}}async ping(){try{let e=await this.exec("SELECT 1");return e&&Array.isArray(e.rows)&&e.rows.length===1}catch{return false}}async transaction(e,n){throw new Error("This Connection does not support transactions")}createMigrator(e){throw new Error("This Connection does not support migrations")}async onPostgrestAST(e,n){return e}deserializeRow(e){return e}normalizeDbError(e){return e}async withContext(e,n,r){return n(this.kysely)}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function At(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var Fm=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function Mm(t){let e=t.match(Fm);if(!e)return null;let n=e[1]?.toLowerCase()==="json"?"json":"text",r=t.match(/;\s*options=([^;]+)/i),s=r?`; options=${r[1].trim()}`:"";return {format:n,optionsSegment:s}}function Um(t){return Fm.test(t)}function Bm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function An(t){if(Array.isArray(t))return t.map(e=>An(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=An(r));return e}return t}function Io(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let u;if(typeof o=="number"&&typeof a=="number"?u=o-a:u=String(o).localeCompare(String(a)),u!==0)return i.direction==="desc"?-u:u}return 0};return [...t].sort(n)}function _x(t,e){return !e||e.length===0?t:t.map(n=>qc(n,e))}function qm(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=_x(t,e);return r=xx(r,e),r=Rx(r,e),r=Cx(r,e),n==="sqlite"&&(r=Tx(r,e),r=Ex(r,e)),r}function Ex(t,e){if(!e||e.length===0)return t;let n=vx(e);return n.size===0?t:t.map(r=>{if(!cr(r))return r;let s={...r};for(let i of n){let o=s[i];o!==null&&typeof o=="object"&&(s[i]=JSON.stringify(o));}return s})}function xx(t,e){return !e||e.length===0?t:t.map(n=>Mc(n,e))}function Rx(t,e){return !e||e.length===0?t:t.map(n=>Uc(n,e))}function Cx(t,e){return !e||e.length===0?t:t.map(n=>Bc(n,e))}function Tx(t,e){return !e||e.length===0?t:t.map(n=>Fc(n,e))}function vx(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];if(!r||!s)continue;let i=s;i.path&&i.pathText&&!Hm(i.cast)&&e.add(r);}return e}function Hm(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function Ax(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function Fc(t,e){if(Array.isArray(t))return t.map(r=>Fc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Fc(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!Ax(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new Kn(l);n[s]=Number.parseInt(l,10);}return n}function qc(t,e){if(Array.isArray(t))return t.map(r=>qc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];!s||!i||!js(i)||s in n&&(n[s]=$x(n[s],i.select));}return n}function Mc(t,e){if(Array.isArray(t))return t.map(r=>Mc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Mc(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=kx(n[s]));}return n}function Uc(t,e){if(Array.isArray(t))return t.map(r=>Uc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Uc(n[s],i.select));continue}Hm(i.cast)&&s in n&&(n[s]=Wm(n[s]));}return n}function Bc(t,e){if(Array.isArray(t))return t.map(r=>Bc(r,e));if(!cr(t))return t;let n={...t};for(let r of e){if(typeof r=="string")continue;let[s,i]=Object.entries(r)[0]??[];if(!s||!i)continue;if(js(i)){s in n&&i.select&&(n[s]=Bc(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=Wm(n[s]));}return n}function kx(t){if(typeof t!="string")return t;let e=t.trim();if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(e))return t;let n=Number(e);return !Number.isFinite(n)||e.replace(/^[+-]/,"").replace(/e[+-]?\d+$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length>15?t:n}function $x(t,e){let n=Ox(t);return !e||e.length===0?n:qc(n,e)}function Ox(t){if(typeof t!="string")return t;let e=t[0];if(e!=="["&&e!=="{")return t;try{return JSON.parse(t)}catch{return t}}function Wm(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function cr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function js(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var Px=new Set(["*/*","application/*","application/json","application/vnd.pgrst.object","application/vnd.pgrst.object+json","application/vnd.pgrst.array","application/vnd.pgrst.array+json","application/octet-stream","text/csv"]);function Km(t){let e=Mm(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function Jm(t,e){let n=t.split(",").map(r=>r.split(";")[0].trim().toLowerCase()).filter(Boolean);if(n.length===0)return true;for(let r of n)if(Px.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function zm(t,e){let n=Mm(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?At({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function ut(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function Gm(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function lr(t,e,n,r){if(e.type==="rpc"){let u={...e,order:void 0,limit:void 0,offset:void 0},f=ne(u,n,{db:t,introspection:r}),{sql:p,parameters:d}=f.compile(),g=`SELECT count(*) as __count FROM (${p}) AS __inner_count`,m=await t.executeQuery({sql:g,parameters:d,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(u=>u.type==="inner"),i=Nx(e);if(s||i){let u={...e,type:"query",order:void 0,limit:void 0,offset:void 0},f=ne(u,n,{db:t,introspection:r}),{sql:p,parameters:d}=f.compile(),g=`SELECT count(*) as __count FROM (${p}) AS __inner_count`,h=(await t.executeQuery({sql:g,parameters:d,query:{kind:"RawNode"}})).rows?.[0];return Number(h?.__count??0)}let o={...e,type:"query",select:[{__count:{aggregate:"count"}}],order:void 0,limit:void 0,offset:void 0,join:void 0},l=await ne(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function Hc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return lr(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=ne(s,n,{db:t,introspection:r}).compile(),c=(await t.executeQuery({sql:`EXPLAIN (FORMAT JSON) ${o.sql}`,parameters:o.parameters,query:{kind:"RawNode"}})).rows?.[0]?.["QUERY PLAN"],u=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,f=u&&typeof u=="object"?Number(u["Plan Rows"]):Number.NaN;return Number.isFinite(f)?f:lr(t,e,n,r)}function Nx(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=Ix(t.select);return e.size===0?false:Vm(t.where,e)}function Vm(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(i=>i&&typeof i=="object"&&Vm(i,e)))return true;continue}if(!e.has(n)||!r||typeof r!="object")continue;let s=r;if(s.$is===null||s.$isNot===null)return true}return false}function Ix(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function Wc(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function en(t,e,n){return Wc(e)?`*/${n??0}`:t.type==="update"&&n!==0?ut(0,n??1,void 0):"*/*"}function Qm(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":ut(n,1,r)}var Dx=/[",\n\r ]/;function Ym(t){if(t==null)return "";let e;return typeof t=="string"?e=t:typeof t=="number"||typeof t=="boolean"?e=String(t):typeof t=="bigint"?e=t.toString():e=JSON.stringify(t),Dx.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Do(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>Ym(s)).join(",")];for(let s of t)r.push(n.map(i=>Ym(s[i])).join(","));return r.join(`
|
|
81
|
+
`)}function Xm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function th(t){return t==null?[]:Array.isArray(t)?t.map(e=>Ls(e)?new Set(Object.keys(e)):new Set):Ls(t)?[new Set(Object.keys(t))]:[]}function nh(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function rh(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=Zm(t,e),s=jx(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!Ls(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!Fx(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:Zm(t,e);return n.length===0?(t.onConflict=void 0,{ast:t}):(t.onConflict=n,{ast:t,appliedResolution:t.ignoreDuplicates?"ignore-duplicates":"merge-duplicates",preflight:t.ignoreDuplicates?void 0:{mode:"merge-duplicates",conflictColumns:n}})}function sh(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=Fs(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:et(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function Zm(t,e){if(!t.from)return [];let n=t.schema??"public",r=e.primary_keys.find(s=>s.table===t.from&&s.schema===n);return r?r.columns:e.primary_keys.find(s=>s.table===t.from)?.columns??[]}function jx(t,e){if(!t||e.length===0)return null;let n=Object.keys(t);if(n.length!==e.length)return null;let r={};for(let s of n){if(s.startsWith("$")||!e.includes(s))return null;let i=Lx(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function Lx(t){if(!Ls(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function Fx(t,e){return Object.is(t,e)?true:t!==null&&e!==null&&t!==void 0&&e!==void 0&&typeof t!="object"&&typeof e!="object"?String(t)===String(e):At(t)===At(e)}function Fs(t,e){let n=[];return e&&n.push(`resolution=${e}`),t?.missing&&n.push(`missing=${t.missing}`),t?.return&&n.push(`return=${t.return}`),t?.count&&t.count!=="none"&&n.push(`count=${t.count}`),t?.tx&&n.push(`tx=${t.tx}`),n.length>0?n.join(", "):void 0}function et(t,e,n,r){switch(t.type){case "insert":return 201;case "upsert":return !n||n==="ignore-duplicates"?201:r===false?200:201;case "put":return e==="representation"?r?201:200:204;case "update":case "delete":return e==="representation"?200:204;default:return 200}}async function ih(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await eh(t,e.from,e.schema,e.where??{},n,r);let i=Array.isArray(e.values)?e.values:e.values?[e.values]:[];for(let o of i){if(!Ls(o))continue;let a=Mx(s.preflight.conflictColumns,o);if(!a||!await eh(t,e.from,e.schema,a,n,r))return true}return false}function Mx(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function eh(t,e,n,r,s,i){return await lr(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function Ls(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ux(t){return "select"in t||"spread"in t||"join"in t}function oh(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))Ux(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),oh(r.select,e));}}var Bx={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function qx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!Hx(i,s))}function Hx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=Bx[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function Wx(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function ah(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&Ul(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let u=c?.plan_enabled===true;if(!t.allowRawMedia&&!Jm(i,u))return T(406,"PGRST107",`None of these media types are available: ${Km(i)}`,null,null);let f=Bm(i),p=Xm(i),d=qx(o,r.timezones);if(d.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${d.join(", ")}`,null);let g=Wx(e);if(g)return g;if(n==="sqlite"&&e.from){let w=e.schema??"",x=r.tables.some(R=>R.name===e.from&&(R.schema??"")===w),E=r.views.some(R=>R.name===e.from&&(R.schema??"")===w);if(!x&&!E)throw new ar(e.schema,e.from)}let m=e.$meta,h=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",y={ast:e};if(h&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&h){let w=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!w)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!w)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(h&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let w=m?.return==="representation"?200:204,x=Fs(m,y.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":en(e,m,0)};if(x&&(E["Preference-Applied"]=x),m?.return==="representation"){let R=new TextEncoder().encode("[]");return E["Content-Length"]=String(R.byteLength),new Response(R,{status:w,headers:E})}return new Response(null,{status:w,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?y.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(w=>typeof w!="object"||w===null||Array.isArray(w)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let w=Object.keys(e.values[0]).sort().join(",");for(let x=1;x<e.values.length;x++)if(Object.keys(e.values[x]).sort().join(",")!==w)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){y.bodyKeySets=th(e.values);let w=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!w.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let x=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let R={};for(let O of x)O in E&&(R[O]=E[O]);return R});else {let E={};for(let R of x)R in e.values&&(E[R]=e.values[R]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let w=r.columns.filter(x=>x.table===e.from).map(x=>x.name);if(w.length>0){let x=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of x)if(!w.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let w=e.schema??"public",x=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===w&&E.is_generated===true).map(E=>E.name));if(x.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let R of E)if(!(!R||typeof R!="object")){for(let O of Object.keys(R))if(x.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let S=rh(e,r);if(S instanceof Response)return S;let _=y.bodyKeySets;if(y=S,y.bodyKeySets=_,e=y.ast,h&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||y.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):sh(e,y);if(l&&(a==="GET"||a==="HEAD")){let w=l.match(/^(\d+)-(\d*)$/);if(w){let x=parseInt(w[1],10);if(w[2]!==""){let E=parseInt(w[2],10);if(x>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=x,e.limit=E-x+1;}else e.offset=x;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!h){let w=c?.max_rows;w!==void 0&&w>0&&((e.limit===void 0||e.limit>w)&&(e.limit=w),oh(e.select,w));}return {ast:e,meta:m,mutationPlan:y,isMutation:h,stripNullsResponse:f,csvResponse:p,planEnabled:u}}var ur=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Ki();hs();er();function lh(t){if(t.from)return t.from}function fh(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof pe){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof Je)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof Kn)return T(400,t.code,t.message,null,null);if(t instanceof Ht)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof Wn)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof ke)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof Jn)return T(400,"PGRST102",t.message,null,null);if(t instanceof Gr)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof Et)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof yn)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof ur){let l=Vt(s,"auth.role","anon")==="anon"?401:403;return at({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof ar){let a=o.schema||"public",l=[...r.tables.filter(p=>(p.schema||"public")===a).map(p=>p.name),...r.views.filter(p=>(p.schema||"public")===a).map(p=>p.name)],c=l.length>0?l:[...r.tables.map(p=>p.name),...r.views.map(p=>p.name)],u=ps(o.relation,c),f=u?`Perhaps you meant the table '${a}.${u}'`:null;return at({status:404,code:"PGRST205",message:o.message,hint:f})}if(typeof o?.code=="string"){if(o.code==="PGRST")return Jx(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=Vt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?lh(i):void 0;if(o.code==="42703"&&c){let u=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(f,p)=>u?.includes(p)?f:`column ${c}.${p} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var Kc=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,Kx="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",ch="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function uh(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Jx(t){let e=typeof t.message=="string"?t.message:"",n=uh(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",Kc,`Invalid JSON value for MESSAGE: '${e}'`,Kx);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",Kc,"DETAIL is missing in the RAISE statement",ch);let s=uh(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",Kc,`Invalid JSON value for DETAIL: '${r}'`,ch);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[f,p]of Object.entries(i))typeof p=="string"&&(c[f]=p);let u={status:s.status,headers:c};typeof s.status_text=="string"&&(u.statusText=s.status_text);try{return new Response(l,u)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var Gx="response.status guc must be a valid status code",fr="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function ph(t,e){let n=(await sql`
|
|
82
82
|
SELECT current_setting('response.status', true) AS status,
|
|
83
83
|
current_setting('response.headers', true) AS headers
|
|
84
|
-
`.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let u=Number(r);if(!Number.isInteger(u)||u<200||u>599)return T(500,"PGRST112",
|
|
85
|
-
- ${JSON.stringify([...s])}`));}async function hh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},u=ne(c,s,{db:r,introspection:i,schema:o});Re("",u,t.debug);let f=await u.execute(),p=Array.isArray(f)&&f.length>0&&f[0]&&typeof f[0]=="object"&&("numUpdatedRows"in f[0]||"numInsertedOrUpdatedRows"in f[0]||"numDeletedRows"in f[0])?f[0]:void 0,d=p===void 0?void 0:Number(p.numUpdatedRows??p.numInsertedOrUpdatedRows??p.numDeletedRows??0),y=et(e,"no-return",a.appliedResolution,l),m={"Content-Range":Zt(e,n,d)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:y,headers:m})}async function gh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let f=i.primary_keys.find(S=>S.table===e.from)?.columns??[],p={...e,select:f.length>0?f:void 0},d=ne(p,s,{db:r,introspection:i,schema:o});Re("",d,t.debug);let y=await d.execute(),m=Array.isArray(y)?y.length:0,h=et(e,"no-return",a.appliedResolution,l),g={"Content-Range":Zt(e,n,m)};if(c&&(g["Preference-Applied"]=c),f.length>0&&Array.isArray(y)&&y.length>0){let S=y[0],_=f.map(w=>`${w}=eq.${S[w]}`).join("&");g.Location=`/${e.from}?${_}`;}return new Response(null,{status:h,headers:g})}function pr({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=Dm(i,e,r,Im(n,e)),i=Um(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=eh(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function Lo(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?vn(e):e,u=r?Do(Array.isArray(c)?c:[c]):vt(c),f=new TextEncoder().encode(u),p={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(f.byteLength)};return o&&(p["Preference-Applied"]=o),a&&(p.Location=a),new Response(f,{status:i,headers:p})}async function yh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let u={...e,select:void 0},f=ne(u,s,{db:r,introspection:i,schema:o});if(Re("LTD",f,t.debug),await f.execute(),n?.return==="representation"){let _={...e,type:"query",values:void 0,limit:void 0,offset:void 0},w=ne(_,s,{db:r,introspection:i,schema:o});Re("LTD-SEL",w,t.debug);let x=await w.execute(),E=Array.isArray(x)?x:[],R=pr({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=R.length,P=[];n.return==="representation"&&P.push("return=representation"),n.count&&P.push(`count=${n.count}`),n.tx&&P.push(`tx=${n.tx}`);let D=e.type==="delete"?"*/*":O>0?ut(0,O,void 0):"*/*";return Lo({rows:R,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:D,preferenceApplied:P.length>0?P.join(", "):void 0})}let p={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},y=await ne(p,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(y)?y[0]:y)?.__count??0),g={"Content-Range":m>0?ut(0,m,void 0):"*/*"},S=[];return n?.count&&S.push(`count=${n.count}`),n?.tx&&S.push(`tx=${n.tx}`),S.length>0&&(g["Preference-Applied"]=S.join(", ")),new Response(null,{status:204,headers:g})}function Zx(t){return "select"in t||"spread"in t||"join"in t}function bh(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(Zx(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function wh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u}=t;if(!(t.isMutation&&n?.return==="representation"&&bh(e.select)))return null;let d=i.primary_keys.find(x=>x.table===e.from)?.columns??[],y=[];if(e.type==="delete"){let x={...e,type:"query",values:void 0},E=ne(x,s,{db:r,introspection:i,schema:o});Re("EMB-PRE",E,t.debug),y=await E.execute();let R={...e,select:void 0},O=ne(R,s,{db:r,introspection:i,schema:o});Re("EMB-DEL",O,t.debug),await O.execute();}else {if(d.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let x={...e,select:d},E=ne(x,s,{db:r,introspection:i,schema:o});Re("EMB-MUT",E,t.debug);let R=await E.execute(),O=Array.isArray(R)?R:[];if(O.length>0){let P;if(d.length===1){let q=d[0];P={[q]:{$in:O.map(K=>K[q])}};}else P={$or:O.map(q=>{let K={};for(let M of d)K[M]={$eq:q[M]};return K})};let D=e.where?{$and:[e.where,P]}:P,v={...e,type:"query",values:void 0,where:D},C=ne(v,s,{db:r,introspection:i,schema:o});Re("EMB-SEL",C,t.debug),y=await C.execute();}}let m=pr({rows:y,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=Io(m,e.order));let h=et(e,"representation",c.appliedResolution,u),g=m.length,S=["return=representation"];n?.count&&S.push(`count=${n.count}`),n?.tx&&S.push(`tx=${n.tx}`);let _=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":g>0?ut(0,g,void 0):"*/*",w;if((e.type==="insert"||e.type==="upsert")&&d.length>0&&m.length>0){let x=m[0],E=d.map(R=>`${R}=eq.${x[R]}`).join("&");w=`/${e.from}?${E}`;}return Lo({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:_,status:h,preferenceApplied:S.join(", "),location:w})}function eR(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function Sh(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function tR(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function _h(t){if(!t.isMutation)return null;let e=eR(t.meta);if(e===null)return null;let n=tR(t.ast);if(n!==null)return n>e?Sh(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=ne(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});Re("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?Sh(o):null}function An(t){return t||"public"}function nR(t,e,n){let r=An(e);return n.views.some(s=>s.name===t&&An(s.schema)===r)}function rR(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function sR(t,e,n){let r=An(e);for(let s of n.triggers){if(s.table!==t||An(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=rR(s.sql);if(i)return i}}async function Eh(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!nR(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=An(e.schema),l=n.primary_keys.find(h=>h.table===e.from&&An(h.schema)===a)?.columns??[];if(l.length===0){let h=sR(e.from,e.schema,n);h&&(l=n.primary_keys.find(g=>g.table===h&&An(g.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],u=t.map(h=>h[c]).filter(h=>h!=null);if(u.length===0)return t;let f={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:u}}},d=await ne(f,r,{db:s,introspection:n,schema:i}).execute(),y=h=>String(h[c]),m=new Map(d.map(h=>[y(h),h]));return t.map(h=>m.get(y(h))??h)}async function xh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u,prefApplied:f,isMutation:p,stripNullsResponse:d,csvResponse:y,requestUrl:m,acceptHeader:h}=t,g=ne(e,s,{db:r,introspection:i,schema:o});Re("",g,t.debug);let S=await g.execute(),_,w=false,x=0;if(p&&Array.isArray(S)&&S.length>0&&S[0]&&typeof S[0]=="object"&&("numUpdatedRows"in S[0]||"numInsertedOrUpdatedRows"in S[0]||"numDeletedRows"in S[0])){w=true;let J=S[0];x=Number(J.numUpdatedRows??J.numInsertedOrUpdatedRows??J.numDeletedRows??0),_=[];}else _=S;p&&Array.isArray(_)&&_.length>0&&(_=await Eh(_,e,i,s,r,o));let E=false,R,O=false,P=false,D=false,v=null;if(e.type==="rpc"&&Array.isArray(_)){let J={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:_n(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};v=jo(i.functions,J,h);let me=fo(i.functions,J);if(me){let He=e.function??"",gt=_;E=!me.returns_object&>.length>0&>.every(hi=>{let Nr=Object.keys(hi);return Nr.length===1&&Nr[0]===He}),E&&(R=He,_=gt.map(hi=>hi[He])),O=!me.return_is_setof,D=me.volatility!=="v",P=me.returns_void;}}if(P){let J={"Content-Range":"0-0/*"};return f&&(J["Preference-Applied"]=f),new Response(null,{status:204,headers:J})}if(v&&Array.isArray(_)&&_.length===1){let J=_[0];if(!E&&J&&typeof J=="object"&&!Array.isArray(J)&&!(J instanceof Uint8Array)){let gt=Object.keys(J);gt.length===1&&(J=J[gt[0]]);}let me=dh(J,v.isBinary),He={"Content-Type":ph(v.mediaType),"Content-Range":"0-0/*","Content-Length":String(me.byteLength)};return f&&(He["Preference-Applied"]=f),n?.head?new Response(null,{status:200,headers:He}):new Response(me,{status:200,headers:He})}let C=Array.isArray(_);C&&!E&&(_=pr({rows:_,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),p&&C&&e.order&&e.order.length>0&&(_=Io(_,e.order));let q=C?_:[],K=q.length,M=e.offset??0;if(p&&w){if(n?.cardinality==="one"){if(x===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(x>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${x} rows`,null)}let J=et(e,"no-return",c.appliedResolution,u),me={"Content-Type":"application/json; charset=utf-8","Content-Range":Zt(e,n,x)};return f&&(me["Preference-Applied"]=f),new Response(null,{status:J,headers:me})}let V;if(Wc(n)&&(p?V=K:e.type==="rpc"?M===0&&K<(e.limit??Number.POSITIVE_INFINITY)?V=K:D&&(V=await Hc(r,e,s,i)):V=await Hc(r,e,s,i)),n?.cardinality==="one"||O){if(K===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(K>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${K} rows`,null);let J=200;p&&(J=et(e,"representation",c.appliedResolution,u));let me=d?vn(q[0]):q[0],He=vt(me),gt=new TextEncoder().encode(He),Nr=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",va={"Content-Type":d?`${Nr};nulls=stripped; charset=utf-8`:`${Nr}; charset=utf-8`,"Content-Range":Gm(e,p,M,V),"Content-Length":String(gt.byteLength)};return f&&(va["Preference-Applied"]=f),n?.head?new Response(null,{status:J,headers:va}):new Response(gt,{status:J,headers:va})}if(V!==void 0&&M>0&&K===0&&M>=V){let J=JSON.stringify({code:"PGRST103",details:`An offset of ${M} was requested, but there are only ${V} rows.`,hint:null,message:"Requested range not satisfiable"}),me=new TextEncoder().encode(J),He={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${V}`,"Content-Length":String(me.byteLength)};return f&&(He["Preference-Applied"]=f),new Response(me,{status:416,headers:He})}let Se;p&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?Se=V!==void 0?`*/${V}`:"*/*":p&&n?.return!=="representation"?Se=V!==void 0?`*/${V}`:"*/*":K>0?Se=ut(M,K,V):Se=V!==void 0?`*/${V}`:"*/*";let ge=200;p?ge=et(e,"representation",c.appliedResolution,u):V!==void 0&&(M+K<V||M>0)&&(ge=206);let Qe=d?vn(_):_,Fn=Array.isArray(Qe)?Qe:[Qe];if(y&&E&&R!==void 0){let J=R;Fn=Fn.map(me=>({[J]:me}));}let mi=y?Do(Fn):vt(Qe),Ta=new TextEncoder().encode(mi),Dt={"Content-Type":y?"text/csv; charset=utf-8":d?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Se,"Content-Length":String(Ta.byteLength)};if(!p&&e.from&&m){let J=Jm(`/${e.from}`,new URL(m).search);J&&(Dt["Content-Location"]=J);}return f&&(Dt["Preference-Applied"]=f),n?.head?new Response(null,{status:ge,headers:Dt}):new Response(Ta,{status:ge,headers:Dt})}var Ms=Symbol.for("lite-internal-request");var iR={swagger:"2.0",info:{description:"",title:"standard public schema",version:"14.1"},basePath:"/",schemes:["https"],consumes:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"],produces:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"]},Rh=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let h=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(h))return T(405,"PGRST101",`Cannot use the ${h} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(h=>co(o,h,"sql")))return n.notFound();if(!(Ms in n.req.raw)&&n.req.method!=="OPTIONS"){let h=await Cm(n.req.header("Authorization"),{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(h.kind==="error")return h.response;h.payload&&(n.set("userId",h.payload.sub),n.set("sessionId",h.payload.session_id),n.set("jwt",h.payload));}if(a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",g=Kl(l.functions,{schema:h,fnName:o,method:"OPTIONS",providedNames:[]});if(g)return T(404,"PGRST202",g.message,g.details,g.hint);let S=zt(l.functions??[],{schema:h,fnName:o,providedNames:[]}),_=S.length>0&&S.every(w=>w.volatility!=="v");return n.header("Allow",_?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",g=w=>{let x=w||"public";return i.dialect==="sqlite"?x===h||x==="public"||x==="":x===h},S=l.views.find(w=>w.name===o&&g(w.schema)),_=!S&&l.tables.find(w=>w.name===o&&w.type!=="view"&&g(w.schema));if(_||S){let w=new Set(["OPTIONS","GET","HEAD"]);if(_)w.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,R=false,O=false,P=(M,V)=>`${M||"public"}\0${V}`,D=new Set,v=S.schema||"public",C=await i.viewOptionsMetadata(o,v).catch(()=>null);if(C){E=C.canInsert,R=C.canUpdate,O=C.canDelete;for(let M of C.baseTables)D.add(P(M.schema,M.name));}else {let M=l.triggers.filter(ge=>ge.table===o&&g(ge.schema)),V=ge=>M.some(Qe=>new RegExp(`instead\\s+of\\s+${ge}`,"i").test(Qe.sql));E=V("insert"),R=V("update"),O=V("delete");let Se=S?.sql??"";for(let ge of l.tables){if(ge.type==="view")continue;let Qe=ge.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Qe}\\b`,"i").test(Se)&&D.add(P(ge.schema,ge.name));}}let q=new Set(l.columns.filter(M=>M.table===o&&g(M.schema)).map(M=>M.name)),K=l.tables.some(M=>{if(M.type==="view"||!D.has(P(M.schema,M.name)))return false;let V=l.columns.filter(Se=>Se.table===M.name&&(Se.schema||"public")===(M.schema||"public")&&Se.is_primary_key);return V.length>0&&V.every(Se=>q.has(Se.name))});E&&w.add("POST"),R&&w.add("PATCH"),O&&w.add("DELETE"),E&&R&&K&&w.add("PUT");}let x=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>w.has(E));return n.header("Allow",x.join(",")),n.body(null,200)}}let{dialect:u}=i,f=i.config.translation?.deparse?.schema,p=Nm(f,l,u),d=n.var.jwt,y={auth:{uid:n.var.userId??null,role:d?.role||"anon",jwt:d??null}},m;try{let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",g=new Set(l.columns.filter(v=>{if(v.table!==o)return !1;let C=v.schema||"public";return u==="sqlite"?C===h||C==="public"||C==="":C===h}).map(v=>v.name));if(m=await Hi(n.req.raw,{basePath:"/rest/v1",parentColumns:g,resolveFilters:(v,C,q)=>Zr(v,C,q,g)}),m.schema){let v=new Set;for(let C of l.tables)C.schema&&v.add(C.schema);for(let C of l.views)C.schema&&v.add(C.schema);if(v.size>0&&v.add("public"),v.size>0&&!v.has(m.schema)){let C=[...v].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${m.schema}`,null,`Only the following schemas are exposed: ${C}`)}}m=await i.onPostgrestAST(m,y);let S=m.function,_=!1;if(a&&S){let v={schema:m.schema??l.default_schema??"public",fnName:S,method:n.req.method.toUpperCase(),providedNames:_n(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:kd(n.req.header("Content-Type"))},C=Kl(l.functions,v);if(C)return T(404,"PGRST202",C.message,C.details,C.hint);let q=Ad(l.functions,v);if(q)return T(300,"PGRST203",q.message,q.details,q.hint);if(v.method==="OPTIONS"){let K=fo(l.functions,{schema:v.schema,fnName:v.fnName,providedNames:v.providedNames,paramsType:v.paramsType}),M=K&&K.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:M,"Access-Control-Allow-Origin":"*"}})}_=jo(l.functions,{schema:v.schema,fnName:v.fnName,providedNames:v.providedNames,paramsType:v.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:v.method,inputType:v.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(Jc.default.dim("[POSTGREST:AST]"),m);let w=ih({ast:m,dialect:u,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:_,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(w instanceof Response)return w;m=w.ast;let{meta:x,mutationPlan:E,isMutation:R,stripNullsResponse:O,csvResponse:P,planEnabled:D}=w;return await i.withContext(y,async v=>{let C=n.req.header("Accept")??"application/json";if(D&&Fm(C)){let Dt=ne(m,u,{db:v,introspection:l,schema:f}).compile();return t?.debug&&console.info(Jc.default.dim(`[POSTGREST:PLAN] ${Dt.sql}
|
|
86
|
-
- ${JSON.stringify([...
|
|
84
|
+
`.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let u=Number(r);if(!Number.isInteger(u)||u<200||u>599)return T(500,"PGRST112",Gx,null,null);i=u;}let o;if(s&&s.length>0){let u;try{u=JSON.parse(s);}catch{return T(500,"PGRST111",fr,null,null)}if(!Array.isArray(u))return T(500,"PGRST111",fr,null,null);let f=[];for(let p of u){if(!p||typeof p!="object"||Array.isArray(p))return T(500,"PGRST111",fr,null,null);let d=Object.keys(p);if(d.length!==1)return T(500,"PGRST111",fr,null,null);let g=p[d[0]];if(typeof g!="string")return T(500,"PGRST111",fr,null,null);f.push([d[0],g]);}o=f;}if(i===void 0&&!o)return e;let a=i??e.status,l=new Headers(e.headers);if(o)try{for(let[u,f]of o)l.set(u,f);}catch{return T(500,"PGRST111",fr,null,null)}let c;return Vx.has(a)?(c=null,l.delete("Content-Length"),l.delete("Content-Type")):c=e.body?await e.arrayBuffer():null,new Response(c,{status:a,statusText:e.statusText,headers:l})}var Vx=new Set([101,204,205,304]);var Qx=/^[\w.+*-]+\/[\w.+*-]+$/,Yx=new Set(["text/plain","text/xml","text/csv","application/json","application/geo+json","application/openapi+json"]);function Xx(t){return t.replace(/^"([\s\S]*)"$/,"$1")}function Zx(t){let e=t.match(/^(?:"(?:[^"]|"")*"|[^."]+)\.([\s\S]+)$/);return e?e[1]:t}function eR(t){if(t.return_typtype!=="d"||t.return_is_setof)return null;let e=Xx(Zx(t.return_type));return Qx.test(e)?e:null}function dh(t){if(!t)return [];let e=[];for(let n of t.split(",")){let r=n.split(";"),s=r[0].trim().toLowerCase();if(!s)continue;let i=1;for(let o of r.slice(1)){let a=o.trim().match(/^q=(.+)$/i);if(a){let l=Number.parseFloat(a[1]);Number.isFinite(l)&&(i=l);}}e.push({media:s,q:i});}return e}function mh(t){return Yx.has(t)?`${t}; charset=utf-8`:t}function tR(t,e){let n=e.indexOf("/"),r=n>0?e.slice(0,n):e,s=-1,i=0;for(let o of t){let a=o.media===e?2:o.media===`${r}/*`?1:o.media==="*/*"?0:-1;a<0||(a>s?(s=a,i=o.q):a===s&&(i=Math.max(i,o.q)));}return s<0?0:i}function nR(t,e){let n=eR(t);if(!n)return null;if(n==="*/*"){let r=dh(e);return r.some(s=>s.media==="*/*"&&s.q<=0)?null:!e||r.some(s=>s.q>0)?{mediaType:"application/octet-stream",isBinary:true}:null}return tR(dh(e),n)>0?{mediaType:n,isBinary:(t.return_base_type??"").toLowerCase()==="bytea"}:null}function jo(t,e,n){let r=uo(t,e);return r?nR(r,n):null}function hh(t,e){if(t instanceof Uint8Array){let s=new Uint8Array(t.byteLength);return s.set(t),s}if(e&&typeof t=="string"&&t.startsWith("\\x")){let s=t.slice(2),i=new Uint8Array(Math.floor(s.length/2));for(let o=0;o<i.length;o++)i[o]=parseInt(s.substr(o*2,2),16);return i}let n=new TextEncoder().encode(t==null?"":String(t)),r=new Uint8Array(n.byteLength);return r.set(n),r}var gh=ka(Xl());function Re(t,e,n){if(!n)return;let{sql:r,parameters:s}=e.compile();console.info(gh.default.dim(`[POSTGREST:SQL:${t}] ${r}
|
|
85
|
+
- ${JSON.stringify([...s])}`));}async function yh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},u=ne(c,s,{db:r,introspection:i,schema:o});Re("",u,t.debug);let f=await u.execute(),p=Array.isArray(f)&&f.length>0&&f[0]&&typeof f[0]=="object"&&("numUpdatedRows"in f[0]||"numInsertedOrUpdatedRows"in f[0]||"numDeletedRows"in f[0])?f[0]:void 0,d=p===void 0?void 0:Number(p.numUpdatedRows??p.numInsertedOrUpdatedRows??p.numDeletedRows??0),g=et(e,"no-return",a.appliedResolution,l),m={"Content-Range":en(e,n,d)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:g,headers:m})}async function bh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let f=i.primary_keys.find(S=>S.table===e.from)?.columns??[],p={...e,select:f.length>0?f:void 0},d=ne(p,s,{db:r,introspection:i,schema:o});Re("",d,t.debug);let g=await d.execute(),m=Array.isArray(g)?g.length:0,h=et(e,"no-return",a.appliedResolution,l),y={"Content-Range":en(e,n,m)};if(c&&(y["Preference-Applied"]=c),f.length>0&&Array.isArray(g)&&g.length>0){let S=g[0],_=f.map(w=>`${w}=eq.${S[w]}`).join("&");y.Location=`/${e.from}?${_}`;}return new Response(null,{status:h,headers:y})}function pr({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=Lm(i,e,r,jm(n,e)),i=qm(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=nh(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function Lo(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?An(e):e,u=r?Do(Array.isArray(c)?c:[c]):At(c),f=new TextEncoder().encode(u),p={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(f.byteLength)};return o&&(p["Preference-Applied"]=o),a&&(p.Location=a),new Response(f,{status:i,headers:p})}async function wh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let u={...e,select:void 0},f=ne(u,s,{db:r,introspection:i,schema:o});if(Re("LTD",f,t.debug),await f.execute(),n?.return==="representation"){let _={...e,type:"query",values:void 0,limit:void 0,offset:void 0},w=ne(_,s,{db:r,introspection:i,schema:o});Re("LTD-SEL",w,t.debug);let x=await w.execute(),E=Array.isArray(x)?x:[],R=pr({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=R.length,P=[];n.return==="representation"&&P.push("return=representation"),n.count&&P.push(`count=${n.count}`),n.tx&&P.push(`tx=${n.tx}`);let D=e.type==="delete"?"*/*":O>0?ut(0,O,void 0):"*/*";return Lo({rows:R,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:D,preferenceApplied:P.length>0?P.join(", "):void 0})}let p={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},g=await ne(p,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(g)?g[0]:g)?.__count??0),y={"Content-Range":m>0?ut(0,m,void 0):"*/*"},S=[];return n?.count&&S.push(`count=${n.count}`),n?.tx&&S.push(`tx=${n.tx}`),S.length>0&&(y["Preference-Applied"]=S.join(", ")),new Response(null,{status:204,headers:y})}function rR(t){return "select"in t||"spread"in t||"join"in t}function Sh(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(rR(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function _h(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u}=t;if(!(t.isMutation&&n?.return==="representation"&&Sh(e.select)))return null;let d=i.primary_keys.find(x=>x.table===e.from)?.columns??[],g=[];if(e.type==="delete"){let x={...e,type:"query",values:void 0},E=ne(x,s,{db:r,introspection:i,schema:o});Re("EMB-PRE",E,t.debug),g=await E.execute();let R={...e,select:void 0},O=ne(R,s,{db:r,introspection:i,schema:o});Re("EMB-DEL",O,t.debug),await O.execute();}else {if(d.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let x={...e,select:d},E=ne(x,s,{db:r,introspection:i,schema:o});Re("EMB-MUT",E,t.debug);let R=await E.execute(),O=Array.isArray(R)?R:[];if(O.length>0){let P;if(d.length===1){let q=d[0];P={[q]:{$in:O.map(K=>K[q])}};}else P={$or:O.map(q=>{let K={};for(let M of d)K[M]={$eq:q[M]};return K})};let D=e.where?{$and:[e.where,P]}:P,v={...e,type:"query",values:void 0,where:D},C=ne(v,s,{db:r,introspection:i,schema:o});Re("EMB-SEL",C,t.debug),g=await C.execute();}}let m=pr({rows:g,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=Io(m,e.order));let h=et(e,"representation",c.appliedResolution,u),y=m.length,S=["return=representation"];n?.count&&S.push(`count=${n.count}`),n?.tx&&S.push(`tx=${n.tx}`);let _=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":y>0?ut(0,y,void 0):"*/*",w;if((e.type==="insert"||e.type==="upsert")&&d.length>0&&m.length>0){let x=m[0],E=d.map(R=>`${R}=eq.${x[R]}`).join("&");w=`/${e.from}?${E}`;}return Lo({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:_,status:h,preferenceApplied:S.join(", "),location:w})}function sR(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function Eh(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function iR(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function xh(t){if(!t.isMutation)return null;let e=sR(t.meta);if(e===null)return null;let n=iR(t.ast);if(n!==null)return n>e?Eh(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=ne(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});Re("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?Eh(o):null}function kn(t){return t||"public"}function oR(t,e,n){let r=kn(e);return n.views.some(s=>s.name===t&&kn(s.schema)===r)}function aR(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function lR(t,e,n){let r=kn(e);for(let s of n.triggers){if(s.table!==t||kn(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=aR(s.sql);if(i)return i}}async function Rh(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!oR(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=kn(e.schema),l=n.primary_keys.find(h=>h.table===e.from&&kn(h.schema)===a)?.columns??[];if(l.length===0){let h=lR(e.from,e.schema,n);h&&(l=n.primary_keys.find(y=>y.table===h&&kn(y.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],u=t.map(h=>h[c]).filter(h=>h!=null);if(u.length===0)return t;let f={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:u}}},d=await ne(f,r,{db:s,introspection:n,schema:i}).execute(),g=h=>String(h[c]),m=new Map(d.map(h=>[g(h),h]));return t.map(h=>m.get(g(h))??h)}async function Ch(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u,prefApplied:f,isMutation:p,stripNullsResponse:d,csvResponse:g,requestUrl:m,acceptHeader:h}=t,y=ne(e,s,{db:r,introspection:i,schema:o});Re("",y,t.debug);let S=await y.execute(),_,w=false,x=0;if(p&&Array.isArray(S)&&S.length>0&&S[0]&&typeof S[0]=="object"&&("numUpdatedRows"in S[0]||"numInsertedOrUpdatedRows"in S[0]||"numDeletedRows"in S[0])){w=true;let J=S[0];x=Number(J.numUpdatedRows??J.numInsertedOrUpdatedRows??J.numDeletedRows??0),_=[];}else _=S;p&&Array.isArray(_)&&_.length>0&&(_=await Rh(_,e,i,s,r,o));let E=false,R,O=false,P=false,D=false,v=null;if(e.type==="rpc"&&Array.isArray(_)){let J={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:En(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};v=jo(i.functions,J,h);let me=fo(i.functions,J);if(me){let He=e.function??"",yt=_;E=!me.returns_object&&yt.length>0&&yt.every(hi=>{let Nr=Object.keys(hi);return Nr.length===1&&Nr[0]===He}),E&&(R=He,_=yt.map(hi=>hi[He])),O=!me.return_is_setof,D=me.volatility!=="v",P=me.returns_void;}}if(P){let J={"Content-Range":"0-0/*"};return f&&(J["Preference-Applied"]=f),new Response(null,{status:204,headers:J})}if(v&&Array.isArray(_)&&_.length===1){let J=_[0];if(!E&&J&&typeof J=="object"&&!Array.isArray(J)&&!(J instanceof Uint8Array)){let yt=Object.keys(J);yt.length===1&&(J=J[yt[0]]);}let me=hh(J,v.isBinary),He={"Content-Type":mh(v.mediaType),"Content-Range":"0-0/*","Content-Length":String(me.byteLength)};return f&&(He["Preference-Applied"]=f),n?.head?new Response(null,{status:200,headers:He}):new Response(me,{status:200,headers:He})}let C=Array.isArray(_);C&&!E&&(_=pr({rows:_,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),p&&C&&e.order&&e.order.length>0&&(_=Io(_,e.order));let q=C?_:[],K=q.length,M=e.offset??0;if(p&&w){if(n?.cardinality==="one"){if(x===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(x>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${x} rows`,null)}let J=et(e,"no-return",c.appliedResolution,u),me={"Content-Type":"application/json; charset=utf-8","Content-Range":en(e,n,x)};return f&&(me["Preference-Applied"]=f),new Response(null,{status:J,headers:me})}let V;if(Wc(n)&&(p?V=K:e.type==="rpc"?M===0&&K<(e.limit??Number.POSITIVE_INFINITY)?V=K:D&&(V=await Hc(r,e,s,i)):V=await Hc(r,e,s,i)),n?.cardinality==="one"||O){if(K===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(K>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${K} rows`,null);let J=200;p&&(J=et(e,"representation",c.appliedResolution,u));let me=d?An(q[0]):q[0],He=At(me),yt=new TextEncoder().encode(He),Nr=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",va={"Content-Type":d?`${Nr};nulls=stripped; charset=utf-8`:`${Nr}; charset=utf-8`,"Content-Range":Qm(e,p,M,V),"Content-Length":String(yt.byteLength)};return f&&(va["Preference-Applied"]=f),n?.head?new Response(null,{status:J,headers:va}):new Response(yt,{status:J,headers:va})}if(V!==void 0&&M>0&&K===0&&M>=V){let J=JSON.stringify({code:"PGRST103",details:`An offset of ${M} was requested, but there are only ${V} rows.`,hint:null,message:"Requested range not satisfiable"}),me=new TextEncoder().encode(J),He={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${V}`,"Content-Length":String(me.byteLength)};return f&&(He["Preference-Applied"]=f),new Response(me,{status:416,headers:He})}let Se;p&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?Se=V!==void 0?`*/${V}`:"*/*":p&&n?.return!=="representation"?Se=V!==void 0?`*/${V}`:"*/*":K>0?Se=ut(M,K,V):Se=V!==void 0?`*/${V}`:"*/*";let ge=200;p?ge=et(e,"representation",c.appliedResolution,u):V!==void 0&&(M+K<V||M>0)&&(ge=206);let Qe=d?An(_):_,Fn=Array.isArray(Qe)?Qe:[Qe];if(g&&E&&R!==void 0){let J=R;Fn=Fn.map(me=>({[J]:me}));}let mi=g?Do(Fn):At(Qe),Ta=new TextEncoder().encode(mi),jt={"Content-Type":g?"text/csv; charset=utf-8":d?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Se,"Content-Length":String(Ta.byteLength)};if(!p&&e.from&&m){let J=Gm(`/${e.from}`,new URL(m).search);J&&(jt["Content-Location"]=J);}return f&&(jt["Preference-Applied"]=f),n?.head?new Response(null,{status:ge,headers:jt}):new Response(Ta,{status:ge,headers:jt})}var Ms=Symbol.for("lite-internal-request");var cR={swagger:"2.0",info:{description:"",title:"standard public schema",version:"14.1"},basePath:"/",schemes:["https"],consumes:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"],produces:["application/json","application/vnd.pgrst.object+json;nulls=stripped","application/vnd.pgrst.object+json","text/csv"]},Th=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let h=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(h))return T(405,"PGRST101",`Cannot use the ${h} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(h=>co(o,h,"sql")))return n.notFound();if(!(Ms in n.req.raw)&&n.req.method!=="OPTIONS"){let h=await vm(n.req.header("Authorization"),{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(h.kind==="error")return h.response;h.payload&&(n.set("userId",h.payload.sub),n.set("sessionId",h.payload.session_id),n.set("jwt",h.payload));}if(a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",y=Kl(l.functions,{schema:h,fnName:o,method:"OPTIONS",providedNames:[]});if(y)return T(404,"PGRST202",y.message,y.details,y.hint);let S=Gt(l.functions??[],{schema:h,fnName:o,providedNames:[]}),_=S.length>0&&S.every(w=>w.volatility!=="v");return n.header("Allow",_?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=w=>{let x=w||"public";return i.dialect==="sqlite"?x===h||x==="public"||x==="":x===h},S=l.views.find(w=>w.name===o&&y(w.schema)),_=!S&&l.tables.find(w=>w.name===o&&w.type!=="view"&&y(w.schema));if(_||S){let w=new Set(["OPTIONS","GET","HEAD"]);if(_)w.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,R=false,O=false,P=(M,V)=>`${M||"public"}\0${V}`,D=new Set,v=S.schema||"public",C=await i.viewOptionsMetadata(o,v).catch(()=>null);if(C){E=C.canInsert,R=C.canUpdate,O=C.canDelete;for(let M of C.baseTables)D.add(P(M.schema,M.name));}else {let M=l.triggers.filter(ge=>ge.table===o&&y(ge.schema)),V=ge=>M.some(Qe=>new RegExp(`instead\\s+of\\s+${ge}`,"i").test(Qe.sql));E=V("insert"),R=V("update"),O=V("delete");let Se=S?.sql??"";for(let ge of l.tables){if(ge.type==="view")continue;let Qe=ge.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Qe}\\b`,"i").test(Se)&&D.add(P(ge.schema,ge.name));}}let q=new Set(l.columns.filter(M=>M.table===o&&y(M.schema)).map(M=>M.name)),K=l.tables.some(M=>{if(M.type==="view"||!D.has(P(M.schema,M.name)))return false;let V=l.columns.filter(Se=>Se.table===M.name&&(Se.schema||"public")===(M.schema||"public")&&Se.is_primary_key);return V.length>0&&V.every(Se=>q.has(Se.name))});E&&w.add("POST"),R&&w.add("PATCH"),O&&w.add("DELETE"),E&&R&&K&&w.add("PUT");}let x=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>w.has(E));return n.header("Allow",x.join(",")),n.body(null,200)}}let{dialect:u}=i,f=i.config.translation?.deparse?.schema,p=Dm(f,l,u),d=n.var.jwt,g={auth:{uid:n.var.userId??null,role:d?.role||"anon",jwt:d??null}},m;try{let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=new Set(l.columns.filter(v=>{if(v.table!==o)return !1;let C=v.schema||"public";return u==="sqlite"?C===h||C==="public"||C==="":C===h}).map(v=>v.name));if(m=await Hi(n.req.raw,{basePath:"/rest/v1",parentColumns:y,resolveFilters:(v,C,q)=>Zr(v,C,q,y)}),m.schema){let v=new Set;for(let C of l.tables)C.schema&&v.add(C.schema);for(let C of l.views)C.schema&&v.add(C.schema);if(v.size>0&&v.add("public"),v.size>0&&!v.has(m.schema)){let C=[...v].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${m.schema}`,null,`Only the following schemas are exposed: ${C}`)}}m=await i.onPostgrestAST(m,g);let S=m.function,_=!1;if(a&&S){let v={schema:m.schema??l.default_schema??"public",fnName:S,method:n.req.method.toUpperCase(),providedNames:En(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:Od(n.req.header("Content-Type"))},C=Kl(l.functions,v);if(C)return T(404,"PGRST202",C.message,C.details,C.hint);let q=$d(l.functions,v);if(q)return T(300,"PGRST203",q.message,q.details,q.hint);if(v.method==="OPTIONS"){let K=fo(l.functions,{schema:v.schema,fnName:v.fnName,providedNames:v.providedNames,paramsType:v.paramsType}),M=K&&K.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:M,"Access-Control-Allow-Origin":"*"}})}_=jo(l.functions,{schema:v.schema,fnName:v.fnName,providedNames:v.providedNames,paramsType:v.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:v.method,inputType:v.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(Jc.default.dim("[POSTGREST:AST]"),m);let w=ah({ast:m,dialect:u,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:_,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(w instanceof Response)return w;m=w.ast;let{meta:x,mutationPlan:E,isMutation:R,stripNullsResponse:O,csvResponse:P,planEnabled:D}=w;return await i.withContext(g,async v=>{let C=n.req.header("Accept")??"application/json";if(D&&Um(C)){let jt=ne(m,u,{db:v,introspection:l,schema:f}).compile();return t?.debug&&console.info(Jc.default.dim(`[POSTGREST:PLAN] ${jt.sql}
|
|
86
|
+
- ${JSON.stringify([...jt.parameters])}`)),zm(C,jt)}let q=R?await ih(v,m,u,l,E):void 0,K=Fs(x,E.appliedResolution),M={ast:m,meta:x,db:v,dialect:u,introspection:l,deparseSchema:f,connection:i,responseSchemaMap:p,mutationPlan:E,mutationCreated:q,prefApplied:K,isMutation:R,stripNullsResponse:O,csvResponse:P,acceptHeader:C,requestUrl:n.req.url,debug:t?.debug},V=await xh(M);if(V)return V;let Se=await yh(M);if(Se)return Se;let ge=await bh(M);if(ge)return ge;let Qe=await wh(M);if(Qe)return Qe;let Fn=await _h(M);if(Fn)return Fn;let mi=await Ch(M);return a&&u==="postgres"?await ph(v,mi):mi},{forceRollback:t?.forceRollback===!0,rpc:a&&u==="postgres"?{method:n.req.method.toUpperCase(),path:`/rpc/${o}`,readOnly:["GET","HEAD"].includes(n.req.method.toUpperCase()),requestHeaders:Object.fromEntries(n.req.raw.headers)}:void 0})}catch(h){return fh(h,{connection:i,introspection:l,vars:g,ast:m})}};return new _e().all("/rpc/:function",n=>e(n,{relation:n.req.param("function"),isRpc:true})).all("/:relation",n=>e(n,{relation:n.req.param("relation"),isRpc:false})).use(async(n,r)=>{if(n.req.method==="GET"&&n.req.path.endsWith("/")){let{app:s}=n.var,i=n.req.header("Accept-Profile")??n.req.header("Content-Profile")??null;if(i){let o=new Set(s.config.api?.schemas??["public"]);if(o.size>0&&!o.has(i)){let a=[...o].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${i}`,null,`Only the following schemas are exposed: ${a}`)}}return n.json(cR)}await r();}).all("*",n=>T(404,"PGRST125","Invalid path specified in request URL",null,null))};var dr=class{maxSizeBytes;now;entries=new Map;sizeBytes=0;constructor(e={}){this.maxSizeBytes=e.maxSizeBytes??1024*1024,this.now=e.now??Date.now;}async get(e){let n=this.entries.get(e);if(n){if(this.isExpired(n)){this.deleteEntry(e,n);return}return this.entries.delete(e),this.entries.set(e,n),n.value}}async set(e,n,r){let s=this.entries.get(e);s&&this.deleteEntry(e,s);let i={value:n,size:vh(e)+vh(n),expiresAt:r?.ttl&&r.ttl>0?this.now()+r.ttl*1e3:void 0};this.entries.set(e,i),this.sizeBytes+=i.size,this.evictToSize();}async delete(e){let n=this.entries.get(e);n&&this.deleteEntry(e,n);}isExpired(e){return typeof e.expiresAt=="number"&&e.expiresAt<=this.now()}evictToSize(){for(;this.sizeBytes>this.maxSizeBytes;){let e=this.entries.keys().next().value;if(typeof e!="string")break;let n=this.entries.get(e);if(!n)break;this.deleteEntry(e,n);}}deleteEntry(e,n){this.entries.delete(e),this.sizeBytes-=n.size;}};function vh(t){return new TextEncoder().encode(t).byteLength}var Fo=class{constructor(e){this.options=e;}async get(e){return await this.options.namespace.get(e)??void 0}async set(e,n,r){await this.options.namespace.put(e,n,{...r?.ttl&&r.ttl>0?{expirationTtl:r.ttl}:{}});}async delete(e){await this.options.namespace.delete(e);}};var Mo=class{constructor(e){this.options=e;}async get(e){return await this.options.client.get(e)??void 0}async set(e,n,r){if(r?.ttl&&r.ttl>0){await this.options.client.set(e,n,"EX",r.ttl);return}await this.options.client.set(e,n);}async delete(e){if(this.options.client.del){await this.options.client.del(e);return}if(this.options.client.delete){await this.options.client.delete(e);return}throw new Error("RedisCacheDriver client must provide del() or delete()")}};var Uo=class{constructor(e){this.options=e;this.endpoint=e.endpoint??"https://api.resend.com/emails",this.fetchFn=e.fetch??fetch;}endpoint;fetchFn;async send(e){let n=await this.fetchFn(this.endpoint,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.apiKey}`},body:JSON.stringify({from:this.options.from,to:e.to,subject:e.subject,...e.text?{text:e.text}:{},...e.html?{html:e.html}:{}})});if(!n.ok)throw new Error(`Resend email failed (${n.status}): ${await n.text()}`)}};var qo=class{constructor(e){this.options=e;this.endpoint=`https://email.${e.region}.amazonaws.com/v2/email/outbound-emails`,this.client=e.client;}endpoint;client;async send(e){let n=await this.getClient(),r={FromEmailAddress:this.options.from,Destination:{ToAddresses:[e.to]},Content:{Simple:{Subject:{Data:e.subject,Charset:"UTF-8"},Body:{...e.text?{Text:{Data:e.text,Charset:"UTF-8"}}:{},...e.html?{Html:{Data:e.html,Charset:"UTF-8"}}:{}}}}},s=await n.fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`AWS SES email failed (${s.status}): ${await s.text()}`)}async getClient(){if(this.client)return this.client;let{AwsClient:e}=await Promise.resolve().then(()=>(Ph(),Oh));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var Ho=class{constructor(e){this.options=e;this.sendmailPath=e.sendmailPath??"/usr/sbin/sendmail";}sendmailPath;async send(e){let{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("SendmailEmailDriver requires a Node-compatible runtime")}),r=Qc(this.options.from,e);await new Promise((s,i)=>{let o=n(this.sendmailPath,["-t","-i"],{stdio:["pipe","ignore","pipe"]}),a=[];o.on("error",l=>{i(new Error(`SendmailEmailDriver failed to start ${this.sendmailPath}: ${l.message}`));}),o.stderr?.on("data",l=>a.push(Buffer.from(l))),o.on("close",l=>{if(l===0){s();return}i(new Error(`SendmailEmailDriver exited with code ${l}: ${Buffer.concat(a).toString("utf8")}`));}),o.stdin.end(r);});}};function Qc(t,e){let n=e.html?"text/html; charset=UTF-8":"text/plain; charset=UTF-8";return [`From: ${t}`,`To: ${e.to}`,`Subject: ${e.subject}`,"MIME-Version: 1.0",`Content-Type: ${n}`,"",e.html??e.text??""].join(`
|
|
87
87
|
`)}var Bs=class{messages=new Map;maxKeepCount;order=[];constructor(e={}){this.maxKeepCount=e.maxKeepCount??100;}async send(e){if(this.maxKeepCount<=0)return;let n=e.to.toLowerCase(),r={...e,sentAt:new Date().toISOString()},s=this.messages.get(n)??[];s.push(r),this.messages.set(n,s),this.order.push({key:n,message:r}),this.trim();}clear(){this.messages.clear(),this.order.length=0;}trim(){for(;this.order.length>this.maxKeepCount;){let e=this.order.shift();if(!e)return;let n=this.messages.get(e.key);if(!n)continue;let r=n.indexOf(e.message);r>=0&&n.splice(r,1),n.length===0&&this.messages.delete(e.key);}}},mr=class extends Bs{silent;logger;constructor(e={}){super({maxKeepCount:0}),this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){await super.send(e),this.silent||this.logger.info(["[@supabase/lite] Email driver noop send",`To: ${e.to}`,`Subject: ${e.subject}`,e.text?`Text: ${e.text}`:void 0,e.html?`HTML: ${e.html}`:void 0].filter(Boolean).join(`
|
|
88
88
|
`));}};var qs=class{silent;logger;constructor(e={}){this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){this.silent||this.logger.info(["[@supabase/lite] SMS driver noop send",`To: ${e.to}`,`Body: ${e.body}`].join(`
|
|
89
|
-
`));}};function Oh(t={}){return {email:t.email??new mr,sms:t.sms??new qs,cache:t.cache??new dr}}var Yc=new Map,Hs=class{constructor(e){this.driver=e;}async sendConfirmation(e,n,r,s){await this.send(cR(e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(uR(e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(fR(e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(pR(e,n,r,s));}async sendReauthentication(e,n,r){await this.send(dR(e,n,r));}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};function cR(t,e,n,r){return {to:t,subject:"Confirm Your Signup",body:{text:`Your confirmation code is: ${n}`,html:`<p>Your confirmation code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=signup">Confirm</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"signup"}}}function uR(t,e,n,r){return {to:t,subject:"Reset Your Password",body:{text:`Your recovery code is: ${n}`,html:`<p>Your recovery code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=recovery">Reset</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"recovery"}}}function fR(t,e,n,r){return {to:t,subject:"Your Magic Link",body:{text:`Your login code is: ${n}`,html:`<p>Your login code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=magiclink">Login</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"magiclink"}}}function pR(t,e,n,r){return {to:t,subject:"Confirm Email Change",body:{text:`Your email change code is: ${n}`,html:`<p>Your email change code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=email_change">Confirm</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"email_change"}}}function dR(t,e,n){return {to:t,subject:"Reauthentication",body:{text:`Your reauthentication code is: ${e}`,html:`<p>Your reauthentication code is: <strong>${e}</strong></p>`},otp:e,tokenHash:n?.tokenHash,meta:{...n,emailActionType:n?.emailActionType??"reauthentication"}}}var G=class extends Error{constructor(n,r,s,i,o){super(s);this.status=n;this.code=r;this.details=i;this.headers=o;this.name="AuthError";}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},ft=()=>new G(400,"invalid_credentials","Invalid login credentials"),Ph=()=>new G(400,"email_not_confirmed","Email not confirmed"),Nh=(t,e=[],n=["length"])=>{let r=[];return n.includes("length")&&r.push(`Password should be at least ${t} characters.`),n.includes("characters")&&r.push(`Password should contain at least one character of each: ${e.join(", ")}.`),new G(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},Ih=(t="Access token is required")=>new G(401,"no_authorization",t),hr=()=>new G(401,"no_authorization","This endpoint requires a valid Bearer token"),Ws=t=>new G(403,"bad_jwt",t),Xc=()=>Ws("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),Zc=t=>Ws(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),Dh=()=>Ws("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),jh=()=>Ws("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),eu=()=>Ws("invalid claim: missing sub claim"),tu=()=>new G(400,"bad_jwt","invalid claim: sub claim must be a UUID");var Lh=()=>new G(403,"user_not_found","User from sub claim in JWT does not exist"),Fh=()=>new G(403,"session_not_found","Session from session_id claim in JWT does not exist"),Mh=()=>new G(422,"user_already_exists","User already registered"),Uh=()=>new G(422,"email_exists","A user with this email address has already been registered"),nu=()=>new G(422,"signup_disabled","Signups not allowed for this instance"),Bh=()=>new G(400,"email_provider_disabled","Email signups are disabled"),qh=()=>new G(422,"otp_disabled","Signups not allowed for otp"),Hh=()=>new G(422,"same_password","New password should be different from the old password."),gr=()=>new G(403,"otp_expired","Email link is invalid or has expired"),le=(t,e=422)=>new G(e,"validation_failed",t);var Ks=t=>new G(400,"bad_json",t),ru=()=>new G(400,"validation_failed","Refresh token is not valid"),yr=()=>new G(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),Wo=(t,e)=>new G(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),Wh=()=>new G(401,"session_not_found","Invalid Refresh Token: Already Used"),su=(t,e,n)=>new G(400,"session_expired",t==="inactivity"?"Invalid Refresh Token: Session Expired (Inactivity)":"Invalid Refresh Token: Session Expired",void 0,{...e?{"Sb-Auth-Session-Id":e}:{},...n?{"Sb-Auth-User-Id":n}:{}}),Kh=()=>new G(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),Jh=()=>new G(400,"invalid_credentials","unsupported_grant_type"),Ko=()=>new G(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds.");async function ou(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new Cn({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function zh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw Xc();let r=mR(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await Rn(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof Tt.JWTExpired?jh():i instanceof Tt.JWSSignatureVerificationFailed?Dh():i instanceof Tt.JWSInvalid||i instanceof Tt.JWTInvalid?Xc():i}}function mR(t){let e=hR(t);if(!e)return Zc("unexpected end of JSON input");let n=gR(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return Zc(au(n))}}function hR(t){try{let e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}catch{return null}}function gR(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var yR={n:"null",t:"true",f:"false"};function au(t){let e=0;for(;e<t.length;){let i=t.charCodeAt(e);if(i===32||i===9||i===10||i===13)e++;else break}let n=t.slice(e);if(!n)return "unexpected end of JSON input";let r=n[0],s=yR[r];if(s){for(let i=1;i<s.length;i++){if(i>=n.length)return "unexpected end of JSON input";if(n[i]!==s[i])return `invalid character ${iu(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${iu(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${iu(r)} looking for beginning of value`}function iu(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var bR=10,wR=4,SR=4,_R=31;function ER(t=process.env){let e=t.LITE_AUTH_BCRYPT_COST;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return Math.min(_R,Math.max(SR,Math.trunc(n)))}return t.RUN_SPEC==="1"?wR:bR}async function Js(t){return Gh.hash(t,ER())}async function lu(t,e){return Gh.compare(t,e)}function Vh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!xR(t,s))&&r.push("characters"),r}function xR(t,e){for(let n of t)if(e.includes(n))return true;return false}function At(t=6){let e=crypto.getRandomValues(new Uint8Array(t)),n="";for(let r=0;r<t;r++)n+=(e[r]%10).toString();return n}function tt(){let t=crypto.getRandomValues(new Uint8Array(32));return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function cu(){return v7()}function ze(){return v7()}function Jo(t){if(!t.jwt_secret)throw new Error('[auth] is enabled but `auth.jwt_secret` is empty. Add `jwt_secret = "<secret>"` under [auth] in your config.toml.')}var zs=class{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;Jo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??CR(n.password_requirements),this.sessionTimeboxSeconds=Yh(n.sessions?.timebox),this.sessionInactivitySeconds=Yh(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;async signUp(e,n,r){if(this.config.enable_signup===false)throw nu();if(!e)throw Kh();if(this.config.email?.enable_signup===false)throw Bh();if(n==null||n===void 0||n==="")throw le("Signup requires a valid password",400);if(!br(e))throw le("Unable to validate email address: invalid format",400);if(n.length>72)throw le("Password cannot be longer than 72 characters",400);this.assertPasswordStrong(n);let i=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false);e=e.toLowerCase();let o=await this.repo.findUserByEmail(e);if(o)throw i?(await this.createAuditLog(o.id,e,"user_repeated_signup","user"),Mh()):Ko();let a=ze(),l=await Js(n),c=new Date().toISOString(),u=null,f=null,p=null;i||(u=At(),f=tt(),p=c);let d={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},y={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:d,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:f,confirmation_sent_at:p});await this.repo.createIdentity({id:ze(),provider:"email",provider_id:a,user_id:a,identity_data:y}),!i&&u&&f&&await this.mailer.sendConfirmation(e,f,u,{userId:a,redirectTo:this.config.site_url});let h=await this.repo.findIdentitiesByUserId(a),g=this.repo.parseUserJson(m),S=this.mapUserToResponse(g,h,"signup");if(i){let _=await this.createSessionForUser(g,h);return await this.createAuditLog(a,e,"user_signedup","team"),{user:S,session:_}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:S}}async signInWithPassword(e,n){if(!e)throw le("missing email or phone",400);if(!n)throw ft();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw ft();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw Ph();if(!await lu(n,s.encrypted_password))throw ft();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw ru();let n=await this.repo.findRefreshToken(e);if(!n)throw TR(e)?yr():ru();if(Xh(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw yr();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw yr();this.assertSessionRefreshable(s);}let i=uu(s?.updated_at,s?.refreshed_at,r.updated_at);await this.repo.revokeRefreshToken(n.id);let o=cu(),a=n.session_id??ze();return n.session_id?await this.repo.updateSessionRefreshedAt(n.session_id,i):await this.repo.createSession({id:a,user_id:r.id}),await this.repo.createRefreshToken({token:o,user_id:r.id,session_id:a,parent:n.token}),await this.createAuditLog(r.id,r.email??"","token_refreshed","token",false),await this.createAuditLog(r.id,r.email??"","token_revoked","token",false),this.createRefreshResponse(r,a,o,i)}async refreshWithRevokedToken(e){if(this.config.sessions?.single_per_user)throw Wh();if(!e.session_id)throw Wo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=vR(n,e.token),s=r.filter(c=>!Xh(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),Wo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw Wo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw yr();let a=await this.repo.findSessionById(e.session_id);if(!a)throw yr();this.assertSessionRefreshable(a);let l=uu(a.updated_at,a.refreshed_at,o.updated_at);return await this.repo.updateSessionRefreshedAt(e.session_id,l),await this.createAuditLog(o.id,o.email??"","token_refreshed","token",false),this.createRefreshResponse(o,e.session_id,i.token,l)}async createRefreshResponse(e,n,r,s){let i=await this.repo.updateUser(e.id,{last_sign_in_at:s}),o=this.repo.parseUserJson(i??e),a=await this.repo.findIdentitiesByUserId(e.id),l=await ou({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:n},this.config.jwt_secret,this.jwtExpiry),c=Math.floor(Date.now()/1e3);return Zh({access_token:l,refresh_token:r,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:c+this.jwtExpiry,user:this.mapUserToResponse(o,a,"user")},n,e.id)}assertSessionRefreshable(e){let n=Date.now();if(this.sessionTimeboxSeconds!==void 0&&n-Date.parse(e.created_at)>this.sessionTimeboxSeconds*1e3)throw su(void 0,e.id,e.user_id);let r=e.refreshed_at??e.created_at;if(this.sessionInactivitySeconds!==void 0&&n-Date.parse(r)>this.sessionInactivitySeconds*1e3)throw su("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw ft();let r=this.repo.parseUserJson(n),s=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(r,s,"user")}async updateUser(e,n){let r=await this.repo.findUserById(e);if(!r)throw ft();let s=this.repo.parseUserJson(r),i={},o=false,a=false,l=n.data!==void 0||n.password!==void 0||n.email!==void 0;if(n.data!==void 0){let f=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=RR(f,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await lu(n.password,s.encrypted_password))throw Hh();i.encrypted_password=await Js(n.password),i.recovery_token=null,i.recovery_sent_at=null,o=true,a=true;}if(n.email!==void 0)if(n.email==="")o=true;else {let f=n.email.toLowerCase();if(!br(f))throw le("Unable to validate email address: invalid format",400);if(o=true,f!==s.email?.toLowerCase()){let p=await this.repo.findUserByEmail(f);if(p&&p.id!==e)throw Uh();let d=new Date().toISOString(),y=At(),m=tt(),h=At(),g=tt(),S=this.config.email?.double_confirm_changes??true;i.email_change=f,i.email_change_token_current=S?m:null,i.email_change_token_new=g,i.email_change_sent_at=d,S?await this.mailer.sendEmailChange(f,m,y,{userId:e,tokenNew:h,tokenHashNew:g,redirectTo:this.config.site_url}):await this.mailer.sendEmailChange(f,g,h,{userId:e,redirectTo:this.config.site_url});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let f=await this.repo.updateUser(e,i);if(!f)throw ft();c=this.repo.parseUserJson(f);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let u=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,u,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw le(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw ft();let o=this.repo.parseUserJson(i);s==="global"?(await this.repo.deleteRefreshTokensForUser(r),await this.repo.deleteUserSessions(r)):s==="others"&&e?(await this.repo.deleteRefreshTokensForUser(r,e),await this.repo.deleteUserSessions(r,e)):e&&(await this.repo.deleteRefreshTokensForSession(e),await this.repo.deleteSession(e)),await this.createAuditLog(r,o.email??"","logout","account",false);}async signInWithOtp(e,n){if(!e)throw le("One of email or phone must be set",400);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=ze(),c=await Js(tt()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ze(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw qh();let i=At(),o=tt(),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ft();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw le("Password recovery requires an email",422);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r){if(this.config.enable_signup===false)throw nu();let l=ze(),c=await Js(tt()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ze(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=At(),o=tt(),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ft();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async verifyOtp(e){let n=null,r=null;if(e.token_hash){let c=await this.findUserByTokenAndType(e.token_hash,e.type);n=c?.user??null,r=c?.tokenColumn??null;}else if(e.email&&e.token)if(n=await this.repo.findUserByEmail(e.email.toLowerCase()),n){for(let c of this.getTokenColumnsForType(e.type)){let u=n[c];if(u===e.token||this.otpMatchesStoredTokenHash(e.email,e.token,u)){r=c;break}}if(!r)throw gr()}else throw gr();else throw gr();if(!n)throw gr();let s=this.repo.parseUserJson(n),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),e.type==="email_change"&&s.email_change){o.email=s.email_change,o.email_change=null,o.email_change_token_current=null,o.email_change_token_new=null;let c=await this.repo.findIdentitiesByUserId(n.id);for(let u of c){let f=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...f,email:s.email_change,email_verified:true}});}await this.createAuditLog(n.id,s.email??"","user_modified","user",false);}else if(e.type==="signup"){let c=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};o.raw_user_meta_data={...c,email_verified:true};let u=await this.repo.findIdentitiesByUserId(n.id);for(let f of u){let p=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...p,email_verified:true}});}r&&(o[r]=null);}else r&&(o[r]=null);o.last_sign_in_at=i,await this.repo.updateUser(n.id,o);let a=await this.repo.findUserById(n.id);if(!a)throw gr();let l=await this.repo.findIdentitiesByUserId(n.id);return e.type==="signup"&&await this.createAuditLog(n.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(e.type),includeLoginProviderTrait:!["magiclink","recovery"].includes(e.type),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(e.type)?"otp":"password"})}async recover(e){if(!e)throw le("Password recovery requires an email",400);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=At(),s=tt(),i=new Date().toISOString();await this.repo.updateUser(n.id,{recovery_token:s,recovery_sent_at:i}),await this.createAuditLog(n.id,e,"user_recovery_requested","user",false),await this.mailer.sendRecovery(e,s,r,{userId:n.id,redirectTo:this.config.site_url});}async resend(e,n){if(!["signup","email_change","sms","phone_change"].includes(e))throw le("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw le("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!br(n))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=At(),i=tt(),o=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw Ko()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw Ko();await this.repo.updateUser(r.id,{email_change_token_new:i,email_change_sent_at:o}),await this.mailer.sendEmailChange(r.email_change,i,s,{userId:r.id,redirectTo:this.config.site_url});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw Ih();let r=At(),s=tt(),i=new Date().toISOString();await this.repo.updateUser(n.id,{reauthentication_token:s,reauthentication_sent_at:i}),await this.mailer.sendReauthentication(n.email,r,{userId:n.id,tokenHash:s,redirectTo:this.config.site_url}),await this.createAuditLog(n.id,n.email??"","user_reauthenticate_requested","",false);}async createSessionForUser(e,n,r="session",s={}){let i=uu(e.last_sign_in_at,e.updated_at),o=await this.repo.updateUser(e.id,{last_sign_in_at:i}),a=o?this.repo.parseUserJson(o):e;this.config.sessions?.single_per_user&&await this.repo.revokeUserRefreshTokens(e.id);let l=ze();await this.repo.createSession({id:l,user_id:e.id});let c=cu();await this.repo.createRefreshToken({token:c,user_id:e.id,session_id:l}),(s.createLoginAudit??true)&&await this.createAuditLog(e.id,e.email??"","login","account",s.includeLoginProviderTrait??true);let u=await ou({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:l},this.config.jwt_secret,this.jwtExpiry),f=Math.floor(Date.now()/1e3);return Zh({access_token:u,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:f+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=Vh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw Nh(this.minPasswordLength,this.passwordRequiredCharacters,n)}mapUserToResponse(e,n,r){let s=typeof e.raw_app_meta_data=="string"?JSON.parse(e.raw_app_meta_data):e.raw_app_meta_data??{},i=typeof e.raw_user_meta_data=="string"?JSON.parse(e.raw_user_meta_data):e.raw_user_meta_data??{},o={id:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??"",phone:e.phone??"",app_metadata:s,user_metadata:i,identities:n.map(a=>this.mapIdentityToResponse(a,r,e)),created_at:e.created_at,updated_at:e.updated_at,is_anonymous:false};return e.confirmed_at&&(o.email_confirmed_at=e.confirmed_at,(r==="user"||r==="verify")&&(o.confirmed_at=e.confirmed_at)),e.last_sign_in_at&&(o.last_sign_in_at=e.last_sign_in_at),e.confirmation_sent_at&&(o.confirmation_sent_at=e.confirmation_sent_at),e.email_change&&(o.new_email=e.email_change),e.email_change_sent_at&&(o.email_change_sent_at=e.email_change_sent_at),r==="verify"&&e.recovery_sent_at&&(o.recovery_sent_at=e.recovery_sent_at),o}mapIdentityToResponse(e,n,r){let s=typeof e.identity_data=="string"?JSON.parse(e.identity_data):e.identity_data??{},i=n==="session"&&r.confirmed_at?{...s,email_verified:true}:s,o=e.email??(typeof i.email=="string"?i.email:r.email??void 0);return {identity_id:e.id,id:e.provider_id,user_id:e.user_id,identity_data:i,provider:"email",last_sign_in_at:e.last_sign_in_at??e.created_at,created_at:e.created_at,updated_at:e.updated_at,...o?{email:o}:{}}}async findUserByTokenAndType(e,n){if(n==="email_change"){let r=await this.repo.findUserByToken("email_change_token_current",e);if(r)return {user:r,tokenColumn:"email_change_token_current"};let s=await this.repo.findUserByToken("email_change_token_new",e);return s?{user:s,tokenColumn:"email_change_token_new"}:null}for(let r of this.getTokenColumnsForType(n)){let s=await this.repo.findUserByToken(r,e);if(s)return {user:s,tokenColumn:r}}return null}otpMatchesStoredTokenHash(e,n,r){return !n||typeof r!="string"?false:(Yc.get(e.toLowerCase())??[]).some(i=>i.otp===n&&i.tokenHash===r)}getTokenColumnsForType(e){switch(e){case "signup":return ["confirmation_token"];case "magiclink":return ["recovery_token","confirmation_token"];case "recovery":return ["recovery_token"];case "email_change":return ["email_change_token_new"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true){let o={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(o.traits={provider:"email"}),await this.repo.createAuditLogEntry({id:ze(),payload:o});}};function RR(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function CR(t){switch(t){case "letters_digits":return ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits_symbols":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789","!@#$%^&*"];default:return []}}function Yh(t){if(!t)return;let e=t.match(/^(\d+)(ms|s|m|h)?$/);if(!e)return;let n=Number(e[1]);switch(e[2]??"s"){case "ms":return n/1e3;case "m":return n*60;case "h":return n*3600;default:return n}}function br(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function TR(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function Xh(t){return t.revoked===true||t.revoked===1}function vR(t,e){let n=[],r=[e];for(;r.length>0;){let s=r.shift();for(let i of t)i.parent!==s||n.some(o=>o.id===i.id)||(n.push(i),r.push(i.token));}return n}function uu(...t){let e=Math.max(0,...t.map(r=>r?Date.parse(r):0)),n=Date.now();return new Date(Math.max(n,e+1)).toISOString()}function Zh(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}function fu(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function kn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Gs=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async findUserByEmail(e){return await this.table("users").selectAll().where("email","=",e.toLowerCase()).executeTakeFirst()??null}async findUserById(e){return await this.table("users").selectAll().where("id","=",e).executeTakeFirst()??null}async findUserByToken(e,n){return await this.table("users").selectAll().where(e,"=",n).executeTakeFirst()??null}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email.toLowerCase(),encrypted_password:e.encrypted_password??null,phone:e.phone??null,email_confirmed_at:e.email_confirmed_at??e.confirmed_at??null,confirmation_token:e.confirmation_token??null,confirmation_sent_at:e.confirmation_sent_at??null,recovery_token:e.recovery_token??null,recovery_sent_at:e.recovery_sent_at??null,email_change:e.email_change??null,email_change_token_new:e.email_change_token_new??null,email_change_token_current:e.email_change_token_current??null,email_change_sent_at:e.email_change_sent_at??null,email_change_confirm_status:e.email_change_confirm_status??0,reauthentication_token:e.reauthentication_token??null,reauthentication_sent_at:e.reauthentication_sent_at??null,raw_app_meta_data:kn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:kn(e.raw_user_meta_data??{}),is_sso_user:this.bool(e.is_sso_user??false),is_anonymous:this.bool(e.is_anonymous??false),last_sign_in_at:e.last_sign_in_at??null,created_at:n,updated_at:n};return await this.insertInto("users").values(r).execute(),await this.findUserById(e.id)}async updateUser(e,n){let r={...n,updated_at:new Date().toISOString()};return r.confirmed_at!=null&&r.email_confirmed_at==null&&(r.email_confirmed_at=r.confirmed_at),delete r.confirmed_at,r.raw_app_meta_data!=null&&(r.raw_app_meta_data=kn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=kn(r.raw_user_meta_data)),r.is_sso_user!=null&&(r.is_sso_user=this.bool(!!r.is_sso_user)),r.is_anonymous!=null&&(r.is_anonymous=this.bool(!!r.is_anonymous)),await this.update("users").set(r).where("id","=",e).execute(),this.findUserById(e)}async createSession(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id,aal:e.aal??"aal1",not_after:null,refreshed_at:null,user_agent:null,ip:null,tag:null,refresh_token_hmac_key:null,refresh_token_counter:null,scopes:null,factor_id:null,created_at:n,updated_at:n};return await this.insertInto("sessions").values(r).execute(),r}async findSessionById(e){return await this.table("sessions").selectAll().where("id","=",e).executeTakeFirst()??null}async updateSessionRefreshedAt(e,n){return await this.update("sessions").set({refreshed_at:n,updated_at:n}).where("id","=",e).execute(),this.findSessionById(e)}async deleteSession(e){await this.deleteFrom("sessions").where("id","=",e).execute();}async deleteUserSessions(e,n){let r=this.deleteFrom("sessions").where("user_id","=",e);n&&(r=r.where("id","!=",n)),await r.execute();}async deleteRefreshTokensForSession(e){await this.deleteFrom("refresh_tokens").where("session_id","=",e).execute();}async deleteRefreshTokensForUser(e,n){let r=this.deleteFrom("refresh_tokens").where("user_id","=",e);n&&(r=r.where("session_id","!=",n)),await r.execute();}async createRefreshToken(e){let n=new Date().toISOString(),r={id:ze(),token:e.token,user_id:e.user_id,session_id:e.session_id,revoked:this.bool(false),parent:e.parent??null,created_at:n,updated_at:n};return await this.insertInto("refresh_tokens").values(r).execute(),r}async findRefreshToken(e){return await this.table("refresh_tokens").selectAll().where("token","=",e).executeTakeFirst()??null}async findRefreshTokensBySession(e){return await this.table("refresh_tokens").selectAll().where("session_id","=",e).execute()}async revokeRefreshToken(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","=",e).execute();}async revokeSessionRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("session_id","=",e).execute();}async revokeRefreshTokensByIds(e){e.length!==0&&await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","in",e).execute();}async revokeUserRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("user_id","=",e).execute();}async createIdentity(e){let n=new Date().toISOString(),r={id:e.id,provider:e.provider,provider_id:e.provider_id,user_id:e.user_id,identity_data:kn(e.identity_data),last_sign_in_at:e.last_sign_in_at??n,created_at:n,updated_at:n};return await this.insertInto("identities").values(r).execute(),{...r,identity_data:e.identity_data}}async findIdentitiesByUserId(e){return (await this.table("identities").selectAll().where("user_id","=",e).execute()).map(r=>({...r,identity_data:fu(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=kn(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async createAuditLogEntry(e){let n={id:e.id,payload:kn(e.payload??{}),ip_address:e.ip_address??"",created_at:new Date().toISOString()};await this.insertInto("audit_log_entries").values(n).execute();}parseUserJson(e){return {...e,raw_app_meta_data:fu(e.raw_app_meta_data),raw_user_meta_data:fu(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};function eg(){return {version:AR(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function tg(t){return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,apple:false,azure:false,bitbucket:false,discord:false,facebook:false,snapchat:false,figma:false,fly:false,github:false,gitlab:false,google:false,keycloak:false,kakao:false,linkedin:false,linkedin_oidc:false,notion:false,spotify:false,slack:false,slack_oidc:false,workos:false,twitch:false,twitter:false,email:t.email?.enable_signup??true,phone:false,zoom:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function ng(){return {keys:[]}}function rg(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function AR(){return [pu(JSON.stringify({alg:"HS256",typ:"JWT"})),pu(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),pu("metadata")].join(".")}function pu(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64url");let e=new TextEncoder().encode(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var du=t=>t;var kR="00000000-0000-0000-0000-000000000000",$R=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,mu=({onError:t}={})=>du(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await ig(e);if(r&&t)return t(r,e)}await n();}),Vs=()=>du(async(t,e)=>{if(!t.var.userId){let n=await ig(t);if(n)return sg(t,n);if(!t.var.userId)return sg(t,hr())}await e();});async function ig(t){let e=t.req.header("Authorization");if(!e)return hr();if(!e.startsWith("Bearer "))return hr();let n=e.slice(7);if(!n||/^\s/.test(n))return hr();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await zh(n,r);}catch(c){return c instanceof G?c:hr()}let i=OR(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return Lh();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Fh();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function OR(t){let e=t.sub,n=t.role;return e==null||e===""?eu():typeof e!="string"?tu():$R.test(e)?e===kR&&n==="service_role"?eu():null:tu()}function sg(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var hu=new _e().onError((t,e)=>{if(t instanceof G){e.header("X-Sb-Error-Code",t.code);for(let[n,r]of Object.entries(t.headers??{}))e.header(n,r);return e.json(t.toJSON(),t.status)}return console.error("Auth error:",t),e.json({error:"server_error",error_description:"Internal server error"},500)}).options("*",t=>{let e=t.req.header("Access-Control-Request-Method");return e&&t.header("Access-Control-Allow-Methods",e),t.header("Access-Control-Allow-Credentials","true"),t.header("Access-Control-Allow-Origin","*"),t.body(null,204)}).post("/signup",async t=>{let e=await kt(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(zo(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",$n("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await kt(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return zo(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return zo(t,s),t.json(s,200)}throw Jh()}).all("/token",$n("POST")).post("/otp",async t=>{let e=await kt(t),{authService:n}=t.var;return await n.signInWithOtp(e.email,{shouldCreateUser:e.create_user??e.options?.shouldCreateUser}),t.json({},200)}).post("/magiclink",async t=>{let e=await kt(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",$n("POST")).post("/verify",async t=>{let e=await kt(t),{authService:n}=t.var;NR(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return zo(t,r),t.json(r,200)}).get("/verify",t=>{let e=t.req.query("type");throw e?og.has(e)?le("Verify requires a token or a token hash",400):le("Invalid email verification type",400):le("Verify requires a verification type",400)}).post("/recover",async t=>{let e=await kt(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await kt(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(eg(),200)).all("/health",$n("GET")).get("/settings",t=>t.json(tg(t.var.app.config.auth??{}),200)).all("/settings",$n("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(ng(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(rg(),200))).all("/nonexistent",PR).use(Vs()).post("/logout",async t=>{let e=await kt(t),{authService:n}=t.var;return await n.signOut(t.get("sessionId"),t.req.query("scope")??e.scope,t.get("userId")),t.body(null,204)}).get("/user",async t=>{let{authService:e}=t.var,n=await e.getUser(t.get("userId"));return t.json(n,200)}).put("/user",async t=>{let e=await kt(t),{authService:n}=t.var,r=await n.updateUser(t.get("userId"),{data:e.data,password:e.password,email:e.email});return t.json(r,200)}).all("/user",$n("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",$n("GET"));function $n(t){return e=>(e.header("Allow",t),e.body(null,405))}function PR(t){return t.header("Content-Type","text/plain; charset=utf-8"),t.header("X-Content-Type-Options","nosniff"),t.body("404 page not found",404)}var og=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function NR(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw le("Verify requires a verification type",400);if(!og.has(e))throw le("Invalid email verification type",400);let n=typeof t.token_hash=="string"?t.token_hash:"",r=typeof t.token=="string"?t.token:"",s=typeof t.email=="string"?t.email:"";if(e==="signup"&&!n&&!(s&&r))throw le("Verify requires either a token or a token hash",400)}async function kt(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw Ks("Could not parse request body as JSON: unexpected end of JSON input");return {}}let n=await t.req.text();if(n===""){if(e.requireBody)throw Ks("Could not parse request body as JSON: unexpected end of JSON input");return {}}try{return JSON.parse(n)}catch{if(t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim()==="application/x-www-form-urlencoded")throw Ks("Could not parse request body as JSON: unexpected end of JSON input");let s=au(n)||"invalid character ' ' looking for beginning of value";throw Ks(`Could not parse request body as JSON: ${s}`)}}function zo(t,e){e.session_id&&t.header("Sb-Auth-Session-Id",e.session_id),e.user_id&&t.header("Sb-Auth-User-Id",e.user_id),e.refresh_token&&t.header("Sb-Auth-Refresh-Token-Prefix",String(e.refresh_token).slice(0,8));}function ag(t){let e=t.connection.dialect,n=new Gs(t.connection.kysely,e);return new zs(n,t.config.auth,t._mailer??new Hs(t.drivers.email))}function lg(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function cg(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function en(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Qs=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="storage";}schema;table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async createBucket(e){let n=new Date().toISOString(),r={id:e.id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,public:e.public??false,file_size_limit:e.file_size_limit??null,allowed_mime_types:this.dialect==="postgres"?e.allowed_mime_types??null:en(e.allowed_mime_types??[]),created_at:n,updated_at:n};return await this.insertInto("buckets").values(r).execute(),await this.findBucketById(e.id)}async findBucketById(e){let n=await this.table("buckets").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async findBucketByName(e){let n=await this.table("buckets").selectAll().where("name","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async listBuckets(){return (await this.table("buckets").selectAll().execute()).map(n=>this.parseBucketRow(n))}async updateBucket(e,n){let r={updated_at:new Date().toISOString()};return n.public!==void 0&&(r.public=n.public),n.file_size_limit!==void 0&&(r.file_size_limit=n.file_size_limit),n.allowed_mime_types!==void 0&&(r.allowed_mime_types=this.dialect==="postgres"?n.allowed_mime_types??null:en(n.allowed_mime_types)),await this.update("buckets").set(r).where("id","=",e).execute(),this.findBucketById(e)}async deleteBucket(e){await this.deleteFrom("buckets").where("id","=",e).execute();}async isBucketEmpty(e){let n=await this.table("objects").select(this.db.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();return Number(n?.count??0)===0}async createObject(e){let n=new Date().toISOString(),r={id:e.id,bucket_id:e.bucket_id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,metadata:en(e.metadata??{}),user_metadata:en(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=en(e.name.split("/"))),await this.insertInto("objects").values(r).execute(),await this.findObjectById(e.id)}async findObjectById(e){let n=await this.table("objects").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseObjectRow(n):null}async findObjectByPath(e,n){let r=await this.table("objects").selectAll().where("bucket_id","=",e).where("name","=",n).executeTakeFirst();return r?this.parseObjectRow(r):null}async listObjects(e,n,r){let s=this.table("objects").selectAll().where("bucket_id","=",e);return n&&(s=s.where("name","like",`${n}%`)),r?.search&&(s=s.where("name","like",`%${r.search}%`)),r?.sortBy?s=s.orderBy(r.sortBy.column,r.sortBy.order):s=s.orderBy("name","asc"),r?.limit&&(s=s.limit(r.limit)),r?.offset&&(s=s.offset(r.offset)),(await s.execute()).map(o=>this.parseObjectRow(o))}async updateObject(e,n){let r={updated_at:new Date().toISOString()};return n.name!==void 0&&(r.name=n.name,this.dialect!=="postgres"&&(r.path_tokens=en(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=en(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=en(n.user_metadata)),n.version!==void 0&&(r.version=n.version),n.owner!==void 0&&(r.owner=n.owner),n.owner_id!==void 0&&(r.owner_id=n.owner_id),await this.update("objects").set(r).where("id","=",e).execute(),this.findObjectById(e)}async deleteObject(e){await this.deleteFrom("objects").where("id","=",e).execute();}async deleteObjectsByBucket(e){let r=(await this.table("objects").select("name").where("bucket_id","=",e).execute()).map(s=>s.name);return r.length>0&&await this.deleteFrom("objects").where("bucket_id","=",e).execute(),r}async objectExists(e,n){return !!await this.table("objects").select("id").where("bucket_id","=",e).where("name","=",n).executeTakeFirst()}async touchObject(e){await this.update("objects").set({last_accessed_at:new Date().toISOString()}).where("id","=",e).execute();}parseBucketRow(e){return {...e,owner:e.owner??"",owner_id:e.owner_id??"",public:!!e.public,allowed_mime_types:e.allowed_mime_types==null?null:cg(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:lg(e.metadata),user_metadata:lg(e.user_metadata),path_tokens:cg(e.path_tokens)}}};var X=class t extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;}name="StorageError";static bucketNotFound(n){return new t(404,"Bucket not found",`Bucket not found: ${n}`)}static bucketAlreadyExists(n){return new t(409,"Duplicate","The resource already exists")}static bucketNotEmpty(n){return new t(409,"ResourceNotEmpty","The bucket you tried to delete is not empty")}static objectNotFound(n){return new t(404,"Object not found",`Object not found: ${n}`)}static invalidMimeType(n,r){return new t(415,"invalid_mime_type",`mime type ${n} is not supported. Supported: ${r.join(", ")}`)}static fileTooLarge(n){return new t(413,"Payload too large",`The object exceeded the maximum allowed size of ${n} bytes`)}static invalidKey(n){return new t(400,"Invalid key",`Invalid object key: ${n}`)}static storageNotConfigured(){return new t(500,"Storage not configured","Storage is enabled but no storage adapter has been set. Set app._storageAdapter before making storage requests.")}toJSON(){return {statusCode:String(this.status),error:this.code,message:this.message}}};var Ys=class{constructor(e,n,r,s={},i){this.repo=e;this.adapter=n;this.config=r;this.options=s;this.transformationAdapter=i;}initialized=false;async init(){if(!this.initialized&&(this.initialized=true,this.options.autoCreateBuckets!==false&&this.config.buckets))for(let[e,n]of Object.entries(this.config.buckets))await this.repo.findBucketById(e)||await this.repo.createBucket({id:e,name:e,public:n.public??false,file_size_limit:n.file_size_limit?DR(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw X.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw X.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw X.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){gu(n);let i=await this.repo.findBucketById(e);if(!i)throw X.bucketNotFound(e);let o=s?.contentType??"application/octet-stream",a=s?.cacheControl??"no-cache";if(i.allowed_mime_types&&i.allowed_mime_types.length>0&&!i.allowed_mime_types.includes(o))throw X.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw X.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw X.bucketAlreadyExists(n);return await this.adapter.uploadObject(e,n,void 0,r,o,a),c&&s?.upsert?await this.repo.updateObject(c.id,{metadata:s?.metadata??c.metadata,version:crypto.randomUUID()}):this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:n,owner:s?.owner??null,owner_id:s?.owner??null,metadata:s?.metadata??{},version:crypto.randomUUID()})}async download(e,n,r){let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);if(await this.repo.touchObject(s.id),r?.transform&&this.transformationAdapter&&!this.transformationAdapter.requiresBuffer&&this.transformationAdapter.transformFromUrl){let o=await this.adapter.privateAssetUrl(e,n,s.version??void 0),a=await this.transformationAdapter.transformFromUrl(o,r.transform);return {body:a.body,metadata:{cacheControl:"public, max-age=3600",contentLength:a.contentLength??0,size:a.contentLength??0,mimetype:a.contentType,eTag:""}}}let i=await this.adapter.getObject(e,n,s.version??void 0);if(!i.body)throw X.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await IR(i.body),a=await this.transformationAdapter.transform(o,r.transform);return {body:a.body,metadata:{...i.metadata,mimetype:a.contentType,size:a.contentLength??0,contentLength:a.contentLength??0}}}return {body:i.body,metadata:i.metadata}}async update(e,n,r,s){return this.upload(e,n,r,{...s,upsert:s?.upsert??true})}async remove(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let s=[];for(let i of n){let o=await this.repo.findObjectByPath(e,i);o&&(await this.adapter.deleteObject(e,i,o.version??void 0),await this.repo.deleteObject(o.id),s.push(o));}return s}async list(e,n,r){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){gu(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.adapter.deleteObject(e,n,s.version??void 0),await this.repo.updateObject(s.id,{name:r,version:crypto.randomUUID()});}async copy(e,n,r){gu(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);return await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:r,owner:s.owner,owner_id:s.owner_id,metadata:s.metadata,version:crypto.randomUUID()}),{key:r}}async info(e,n){let r=await this.repo.findObjectByPath(e,n);if(!r)throw X.objectNotFound(n);let s=await this.adapter.headObject(e,n,r.version??void 0);return {...r,httpMetadata:s}}async exists(e,n){return this.repo.objectExists(e,n)}async createSignedUrl(e,n,r){if(!await this.repo.findObjectByPath(e,n))throw X.objectNotFound(n);let i=await this.signStorageToken({sub:n,bucket:e,intent:"download"},r);return {signedUrl:`/storage/v1/object/sign/${e}/${n}?token=${i}`}}async createSignedUrls(e,n,r){let s=[];for(let i of n)try{let{signedUrl:o}=await this.createSignedUrl(e,i,r);s.push({path:i,signedUrl:o,error:null});}catch(o){s.push({path:i,signedUrl:"",error:o.message});}return s}async createSignedUploadUrl(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let s=await this.signStorageToken({sub:n,bucket:e,intent:"upload"},7200);return {signedUrl:`/storage/v1/object/upload/sign/${e}/${n}?token=${s}`,token:s,path:n}}async verifySignedUrl(e){let n=new TextEncoder().encode(this.config.jwtSecret),{payload:r}=await Rn(e,n,{algorithms:["HS256"]});return {bucket:r.bucket,path:r.sub,intent:r.intent}}async signStorageToken(e,n){let r=new TextEncoder().encode(this.config.jwtSecret),s=Math.floor(Date.now()/1e3);return new Cn({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function IR(t){if(t instanceof Uint8Array||Buffer.isBuffer(t))return t;if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());let e=[],n=t.getReader();for(;;){let{done:r,value:s}=await n.read();if(r)break;e.push(s);}return Buffer.concat(e)}function gu(t){if(!t||t.includes("..")||t.startsWith("/"))throw X.invalidKey(t)}function DR(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var jR=/^[\w!#$%&'*.^`|~+-]+$/,LR=/^[ !#-:<-[\]-~]*$/,yu=(t,e)=>{let n=t.trim().split(";"),r={};for(let s of n){s=s.trim();let i=s.indexOf("=");if(i===-1)continue;let o=s.substring(0,i).trim();if(!jR.test(o))continue;let a=s.substring(i+1).trim();if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),LR.test(a)&&(r[o]=a.indexOf("%")!==-1?qn(a,Br):a,e));}return r};var ug=(t,e,n)=>{let r=t.req.raw.headers.get("Cookie");return r?yu(r):{}};var fg=(t,e)=>new Response(t,{headers:{"Content-Type":e}}).formData();var FR=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,MR=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,UR=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,bu=(t,e)=>async(n,r)=>{let s={},i=n.req.header("Content-Type");switch(t){case "json":if(!i||!FR.test(i))break;try{s=await n.req.json();}catch{let a="Malformed JSON in request body";throw new Pi(400,{message:a})}break;case "form":{if(!i||!(MR.test(i)||UR.test(i)))break;let a;if(n.req.bodyCache.formData)a=await n.req.bodyCache.formData;else try{let c=await n.req.arrayBuffer();a=await fg(c,i),n.req.bodyCache.formData=a;}catch(c){let u="Malformed FormData request.";throw u+=c instanceof Error?` ${c.message}`:` ${String(c)}`,new Pi(400,{message:u})}let l={};a.forEach((c,u)=>{u.endsWith("[]")?(l[u]??=[]).push(c):Array.isArray(l[u])?l[u].push(c):u in l?l[u]=[l[u],c]:l[u]=c;}),s=l;break}case "query":s=Object.fromEntries(Object.entries(n.req.queries()).map(([a,l])=>l.length===1?[a,l[0]]:[a,l]));break;case "param":s=n.req.param();break;case "header":s=n.req.header();break;case "cookie":s=ug(n);break}let o=await e(s,n);return o instanceof Response?o:(n.req.addValidatedData(t,o),await r())};var BR=Symbol.for("jsonv"),qR=(t,e)=>Object.assign(t,{[BR]:e}),$t=(t,e,n,r)=>{let s=bu(t,async(i,o)=>{let a=e.coerce(i,{dropUnknown:n?.dropUnknown}),l=e.validate(a);if(!l.valid)return o.json({...l,schema:e},400);return a});return qR(s,{type:"parameters",skip:n?.skipOpenAPI,value:{target:t,schema:e}})};ie();var HR=b.object({id:b.string(),name:b.string(),public:b.boolean({default:false}).optional(),file_size_limit:b.number().optional(),allowed_mime_types:b.array(b.string()).optional()}),WR=b.object({public:b.boolean().optional(),file_size_limit:b.number().optional(),allowed_mime_types:b.array(b.string()).optional()}),KR=b.object({prefix:b.string().optional(),limit:b.number().optional(),offset:b.number().optional(),sortBy:b.object({column:b.string(),order:b.string()}).optional(),search:b.string().optional()}),pg=b.object({bucketId:b.string(),sourceKey:b.string(),destinationKey:b.string()}),JR=b.object({expiresIn:b.number()}),zR=b.object({expiresIn:b.number(),paths:b.array(b.string())}),GR=b.object({prefixes:b.array(b.string())}),VR=new _e().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/public/${e}/`),{storageService:r}=t.var;if(!(await r.getBucket(e)).public)return t.json({error:"Bucket is not public"},400);let i=wu(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:Su(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n)return t.json({error:"Invalid token"},403);let o=wu(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:Su(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/upload/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n||i.intent!=="upload")return t.json({error:"Invalid token"},403);let o=t.req.header("content-type")??"application/octet-stream",a=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,l=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),c=await s.upload(e,n,l,{contentType:o,contentLength:a,upsert:true});return t.json({Key:c.name},200)}),QR=new _e().use(Vs()).post("/bucket",$t("json",HR),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.createBucket({id:e.id,name:e.name??e.id,public:e.public,file_size_limit:e.file_size_limit,allowed_mime_types:e.allowed_mime_types});return t.json({name:r.name},200)}).get("/bucket",async t=>{let{storageService:e}=t.var,n=await e.listBuckets();return t.json(n,200)}).get("/bucket/:id",async t=>{let{storageService:e}=t.var,n=await e.getBucket(t.req.param("id"));return t.json(n,200)}).put("/bucket/:id",$t("json",WR),async t=>{let{storageService:e}=t.var;return await e.updateBucket(t.req.param("id"),t.req.valid("json")),t.json({message:"Successfully updated"},200)}).delete("/bucket/:id",async t=>{let{storageService:e}=t.var;return await e.deleteBucket(t.req.param("id")),t.json({message:"Successfully deleted"},200)}).post("/bucket/:id/empty",async t=>{let{storageService:e}=t.var;return await e.emptyBucket(t.req.param("id")),t.json({message:"Empty bucket has been queued. Completion may take up to an hour."},200)}).post("/object/list/:bucketId",$t("json",KR),async t=>{let e=t.req.param("bucketId"),n=t.req.valid("json"),{storageService:r}=t.var,s=await r.list(e,n.prefix,{limit:n.limit,offset:n.offset,sortBy:n.sortBy,search:n.search});return t.json(s,200)}).post("/object/move",$t("json",pg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var;return await n.move(e.bucketId,e.sourceKey,e.destinationKey),t.json({message:"Successfully moved"},200)}).post("/object/copy",$t("json",pg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.copy(e.bucketId,e.sourceKey,e.destinationKey);return t.json({key:r.key},200)}).get("/object/info/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/info/${e}/`),{storageService:r}=t.var,s=await r.info(e,n);return t.json(s,200)}).post("/object/sign/:bucketId/*",$t("json",JR),async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/sign/${e}/`),{expiresIn:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrl(e,n,r);return t.json(i,200)}).post("/object/sign/:bucketId",$t("json",zR),async t=>{let e=t.req.param("bucketId"),{expiresIn:n,paths:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrls(e,r,n);return t.json(i,200)}).post("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/upload/sign/${e}/`),{storageService:r}=t.var,s=await r.createSignedUploadUrl(e,n);return t.json(s,200)}).delete("/object/:bucketId",$t("json",GR),async t=>{let e=t.req.param("bucketId"),{prefixes:n}=t.req.valid("json"),{storageService:r}=t.var,s=await r.remove(e,n);return t.json(s,200)}).post("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("x-upsert")==="true",a,l,c;if(s.startsWith("multipart/form-data")){let p=(await t.req.formData()).get("file");if(!p)throw new X(400,"InvalidRequest","Missing file in multipart upload");let d=new Uint8Array(await p.arrayBuffer());a=d,l=p.type||"application/octet-stream",c=d.length;}else a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=s,c=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0;let u=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${u.name}`,Id:u.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=await r.update(e,n,a,{contentType:s,cacheControl:i,contentLength:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${l.name}`,Id:l.id},200)}).get("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=wu(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:Su(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),_u=new _e().onError((t,e)=>t instanceof X?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",VR).route("/",QR);function pt(t,e){let n=t.replace(/^\/storage\/v1/,""),r=n.indexOf(e);return r===-1?n.split("/").slice(3).join("/"):n.slice(r+e.length)}function wu(t){let{width:e,height:n,resize:r,format:s,quality:i}=t;return !e&&!n&&!r&&!s&&!i?null:{width:e?Number.parseInt(e,10):void 0,height:n?Number.parseInt(n,10):void 0,resize:r,format:s,quality:i?Number.parseInt(i,10):void 0}}function Su(t){let e={"Content-Type":t.mimetype,"Cache-Control":t.cacheControl,ETag:t.eTag};return t.contentLength&&(e["Content-Length"]=String(t.contentLength)),t.lastModified&&(e["Last-Modified"]=t.lastModified.toUTCString()),t.contentRange&&(e["Content-Range"]=t.contentRange),e}ys();var Eu=`-- supabase/storage core schema (Postgres)
|
|
89
|
+
`));}};function Nh(t={}){return {email:t.email??new mr,sms:t.sms??new qs,cache:t.cache??new dr}}var Yc=new Map,Hs=class{constructor(e){this.driver=e;}async sendConfirmation(e,n,r,s){await this.send(dR(e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(mR(e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(hR(e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(gR(e,n,r,s));}async sendReauthentication(e,n,r){await this.send(yR(e,n,r));}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};function dR(t,e,n,r){return {to:t,subject:"Confirm Your Signup",body:{text:`Your confirmation code is: ${n}`,html:`<p>Your confirmation code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=signup">Confirm</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"signup"}}}function mR(t,e,n,r){return {to:t,subject:"Reset Your Password",body:{text:`Your recovery code is: ${n}`,html:`<p>Your recovery code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=recovery">Reset</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"recovery"}}}function hR(t,e,n,r){return {to:t,subject:"Your Magic Link",body:{text:`Your login code is: ${n}`,html:`<p>Your login code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=magiclink">Login</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"magiclink"}}}function gR(t,e,n,r){return {to:t,subject:"Confirm Email Change",body:{text:`Your email change code is: ${n}`,html:`<p>Your email change code is: <strong>${n}</strong></p><p><a href="http://localhost:3000/verify?token_hash=${e}&type=email_change">Confirm</a></p>`},otp:n,tokenHash:e,meta:{...r,emailActionType:r?.emailActionType??"email_change"}}}function yR(t,e,n){return {to:t,subject:"Reauthentication",body:{text:`Your reauthentication code is: ${e}`,html:`<p>Your reauthentication code is: <strong>${e}</strong></p>`},otp:e,tokenHash:n?.tokenHash,meta:{...n,emailActionType:n?.emailActionType??"reauthentication"}}}var G=class extends Error{constructor(n,r,s,i,o){super(s);this.status=n;this.code=r;this.details=i;this.headers=o;this.name="AuthError";}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},ft=()=>new G(400,"invalid_credentials","Invalid login credentials"),Ih=()=>new G(400,"email_not_confirmed","Email not confirmed"),Dh=(t,e=[],n=["length"])=>{let r=[];return n.includes("length")&&r.push(`Password should be at least ${t} characters.`),n.includes("characters")&&r.push(`Password should contain at least one character of each: ${e.join(", ")}.`),new G(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},jh=(t="Access token is required")=>new G(401,"no_authorization",t),hr=()=>new G(401,"no_authorization","This endpoint requires a valid Bearer token"),Ws=t=>new G(403,"bad_jwt",t),Xc=()=>Ws("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),Zc=t=>Ws(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),Lh=()=>Ws("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),Fh=()=>Ws("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),eu=()=>Ws("invalid claim: missing sub claim"),tu=()=>new G(400,"bad_jwt","invalid claim: sub claim must be a UUID");var Mh=()=>new G(403,"user_not_found","User from sub claim in JWT does not exist"),Uh=()=>new G(403,"session_not_found","Session from session_id claim in JWT does not exist"),Bh=()=>new G(422,"user_already_exists","User already registered"),qh=()=>new G(422,"email_exists","A user with this email address has already been registered"),nu=()=>new G(422,"signup_disabled","Signups not allowed for this instance"),Hh=()=>new G(400,"email_provider_disabled","Email signups are disabled"),Wh=()=>new G(422,"otp_disabled","Signups not allowed for otp"),Kh=()=>new G(422,"same_password","New password should be different from the old password."),gr=()=>new G(403,"otp_expired","Email link is invalid or has expired"),le=(t,e=422)=>new G(e,"validation_failed",t);var Ks=t=>new G(400,"bad_json",t),ru=()=>new G(400,"validation_failed","Refresh token is not valid"),yr=()=>new G(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),Wo=(t,e)=>new G(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),Jh=()=>new G(401,"session_not_found","Invalid Refresh Token: Already Used"),su=(t,e,n)=>new G(400,"session_expired",t==="inactivity"?"Invalid Refresh Token: Session Expired (Inactivity)":"Invalid Refresh Token: Session Expired",void 0,{...e?{"Sb-Auth-Session-Id":e}:{},...n?{"Sb-Auth-User-Id":n}:{}}),zh=()=>new G(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),Gh=()=>new G(400,"invalid_credentials","unsupported_grant_type"),Ko=()=>new G(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds.");async function ou(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new Tn({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function Vh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw Xc();let r=bR(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await Cn(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof vt.JWTExpired?Fh():i instanceof vt.JWSSignatureVerificationFailed?Lh():i instanceof vt.JWSInvalid||i instanceof vt.JWTInvalid?Xc():i}}function bR(t){let e=wR(t);if(!e)return Zc("unexpected end of JSON input");let n=SR(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return Zc(au(n))}}function wR(t){try{let e=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}catch{return null}}function SR(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var _R={n:"null",t:"true",f:"false"};function au(t){let e=0;for(;e<t.length;){let i=t.charCodeAt(e);if(i===32||i===9||i===10||i===13)e++;else break}let n=t.slice(e);if(!n)return "unexpected end of JSON input";let r=n[0],s=_R[r];if(s){for(let i=1;i<s.length;i++){if(i>=n.length)return "unexpected end of JSON input";if(n[i]!==s[i])return `invalid character ${iu(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${iu(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${iu(r)} looking for beginning of value`}function iu(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var ER=10,xR=4,RR=4,CR=31;function TR(t=process.env){let e=t.LITE_AUTH_BCRYPT_COST;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return Math.min(CR,Math.max(RR,Math.trunc(n)))}return t.RUN_SPEC==="1"?xR:ER}async function Js(t){return Qh.hash(t,TR())}async function lu(t,e){return Qh.compare(t,e)}function Yh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!vR(t,s))&&r.push("characters"),r}function vR(t,e){for(let n of t)if(e.includes(n))return true;return false}function kt(t=6){let e=crypto.getRandomValues(new Uint8Array(t)),n="";for(let r=0;r<t;r++)n+=(e[r]%10).toString();return n}function tt(){let t=crypto.getRandomValues(new Uint8Array(32));return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function cu(){return v7()}function ze(){return v7()}function Jo(t){if(!t.jwt_secret)throw new Error('[auth] is enabled but `auth.jwt_secret` is empty. Add `jwt_secret = "<secret>"` under [auth] in your config.toml.')}var zs=class{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;Jo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??kR(n.password_requirements),this.sessionTimeboxSeconds=Zh(n.sessions?.timebox),this.sessionInactivitySeconds=Zh(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;async signUp(e,n,r){if(this.config.enable_signup===false)throw nu();if(!e)throw zh();if(this.config.email?.enable_signup===false)throw Hh();if(n==null||n===void 0||n==="")throw le("Signup requires a valid password",400);if(!br(e))throw le("Unable to validate email address: invalid format",400);if(n.length>72)throw le("Password cannot be longer than 72 characters",400);this.assertPasswordStrong(n);let i=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false);e=e.toLowerCase();let o=await this.repo.findUserByEmail(e);if(o)throw i?(await this.createAuditLog(o.id,e,"user_repeated_signup","user"),Bh()):Ko();let a=ze(),l=await Js(n),c=new Date().toISOString(),u=null,f=null,p=null;i||(u=kt(),f=tt(),p=c);let d={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},g={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:d,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:f,confirmation_sent_at:p});await this.repo.createIdentity({id:ze(),provider:"email",provider_id:a,user_id:a,identity_data:g}),!i&&u&&f&&await this.mailer.sendConfirmation(e,f,u,{userId:a,redirectTo:this.config.site_url});let h=await this.repo.findIdentitiesByUserId(a),y=this.repo.parseUserJson(m),S=this.mapUserToResponse(y,h,"signup");if(i){let _=await this.createSessionForUser(y,h);return await this.createAuditLog(a,e,"user_signedup","team"),{user:S,session:_}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:S}}async signInWithPassword(e,n){if(!e)throw le("missing email or phone",400);if(!n)throw ft();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw ft();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw Ih();if(!await lu(n,s.encrypted_password))throw ft();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw ru();let n=await this.repo.findRefreshToken(e);if(!n)throw $R(e)?yr():ru();if(eg(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw yr();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw yr();this.assertSessionRefreshable(s);}let i=uu(s?.updated_at,s?.refreshed_at,r.updated_at);await this.repo.revokeRefreshToken(n.id);let o=cu(),a=n.session_id??ze();return n.session_id?await this.repo.updateSessionRefreshedAt(n.session_id,i):await this.repo.createSession({id:a,user_id:r.id}),await this.repo.createRefreshToken({token:o,user_id:r.id,session_id:a,parent:n.token}),await this.createAuditLog(r.id,r.email??"","token_refreshed","token",false),await this.createAuditLog(r.id,r.email??"","token_revoked","token",false),this.createRefreshResponse(r,a,o,i)}async refreshWithRevokedToken(e){if(this.config.sessions?.single_per_user)throw Jh();if(!e.session_id)throw Wo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=OR(n,e.token),s=r.filter(c=>!eg(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),Wo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw Wo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw yr();let a=await this.repo.findSessionById(e.session_id);if(!a)throw yr();this.assertSessionRefreshable(a);let l=uu(a.updated_at,a.refreshed_at,o.updated_at);return await this.repo.updateSessionRefreshedAt(e.session_id,l),await this.createAuditLog(o.id,o.email??"","token_refreshed","token",false),this.createRefreshResponse(o,e.session_id,i.token,l)}async createRefreshResponse(e,n,r,s){let i=await this.repo.updateUser(e.id,{last_sign_in_at:s}),o=this.repo.parseUserJson(i??e),a=await this.repo.findIdentitiesByUserId(e.id),l=await ou({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:n},this.config.jwt_secret,this.jwtExpiry),c=Math.floor(Date.now()/1e3);return tg({access_token:l,refresh_token:r,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:c+this.jwtExpiry,user:this.mapUserToResponse(o,a,"user")},n,e.id)}assertSessionRefreshable(e){let n=Date.now();if(this.sessionTimeboxSeconds!==void 0&&n-Date.parse(e.created_at)>this.sessionTimeboxSeconds*1e3)throw su(void 0,e.id,e.user_id);let r=e.refreshed_at??e.created_at;if(this.sessionInactivitySeconds!==void 0&&n-Date.parse(r)>this.sessionInactivitySeconds*1e3)throw su("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw ft();let r=this.repo.parseUserJson(n),s=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(r,s,"user")}async updateUser(e,n){let r=await this.repo.findUserById(e);if(!r)throw ft();let s=this.repo.parseUserJson(r),i={},o=false,a=false,l=n.data!==void 0||n.password!==void 0||n.email!==void 0;if(n.data!==void 0){let f=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=AR(f,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await lu(n.password,s.encrypted_password))throw Kh();i.encrypted_password=await Js(n.password),i.recovery_token=null,i.recovery_sent_at=null,o=true,a=true;}if(n.email!==void 0)if(n.email==="")o=true;else {let f=n.email.toLowerCase();if(!br(f))throw le("Unable to validate email address: invalid format",400);if(o=true,f!==s.email?.toLowerCase()){let p=await this.repo.findUserByEmail(f);if(p&&p.id!==e)throw qh();let d=new Date().toISOString(),g=kt(),m=tt(),h=kt(),y=tt(),S=this.config.email?.double_confirm_changes??true;i.email_change=f,i.email_change_token_current=S?m:null,i.email_change_token_new=y,i.email_change_sent_at=d,S?await this.mailer.sendEmailChange(f,m,g,{userId:e,tokenNew:h,tokenHashNew:y,redirectTo:this.config.site_url}):await this.mailer.sendEmailChange(f,y,h,{userId:e,redirectTo:this.config.site_url});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let f=await this.repo.updateUser(e,i);if(!f)throw ft();c=this.repo.parseUserJson(f);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let u=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,u,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw le(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw ft();let o=this.repo.parseUserJson(i);s==="global"?(await this.repo.deleteRefreshTokensForUser(r),await this.repo.deleteUserSessions(r)):s==="others"&&e?(await this.repo.deleteRefreshTokensForUser(r,e),await this.repo.deleteUserSessions(r,e)):e&&(await this.repo.deleteRefreshTokensForSession(e),await this.repo.deleteSession(e)),await this.createAuditLog(r,o.email??"","logout","account",false);}async signInWithOtp(e,n){if(!e)throw le("One of email or phone must be set",400);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=ze(),c=await Js(tt()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ze(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw Wh();let i=kt(),o=tt(),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ft();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw le("Password recovery requires an email",422);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r){if(this.config.enable_signup===false)throw nu();let l=ze(),c=await Js(tt()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:ze(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=kt(),o=tt(),a=new Date().toISOString();if(await this.repo.updateUser(r.id,{recovery_token:o,recovery_sent_at:a}),await this.createAuditLog(r.id,e,"user_recovery_requested","user",false),await this.mailer.sendMagicLink(e,o,i,{userId:r.id,redirectTo:this.config.site_url}),s){let l=await this.repo.findUserById(r.id);if(!l)throw ft();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async verifyOtp(e){let n=null,r=null;if(e.token_hash){let c=await this.findUserByTokenAndType(e.token_hash,e.type);n=c?.user??null,r=c?.tokenColumn??null;}else if(e.email&&e.token)if(n=await this.repo.findUserByEmail(e.email.toLowerCase()),n){for(let c of this.getTokenColumnsForType(e.type)){let u=n[c];if(u===e.token||this.otpMatchesStoredTokenHash(e.email,e.token,u)){r=c;break}}if(!r)throw gr()}else throw gr();else throw gr();if(!n)throw gr();let s=this.repo.parseUserJson(n),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),e.type==="email_change"&&s.email_change){o.email=s.email_change,o.email_change=null,o.email_change_token_current=null,o.email_change_token_new=null;let c=await this.repo.findIdentitiesByUserId(n.id);for(let u of c){let f=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...f,email:s.email_change,email_verified:true}});}await this.createAuditLog(n.id,s.email??"","user_modified","user",false);}else if(e.type==="signup"){let c=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};o.raw_user_meta_data={...c,email_verified:true};let u=await this.repo.findIdentitiesByUserId(n.id);for(let f of u){let p=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...p,email_verified:true}});}r&&(o[r]=null);}else r&&(o[r]=null);o.last_sign_in_at=i,await this.repo.updateUser(n.id,o);let a=await this.repo.findUserById(n.id);if(!a)throw gr();let l=await this.repo.findIdentitiesByUserId(n.id);return e.type==="signup"&&await this.createAuditLog(n.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(e.type),includeLoginProviderTrait:!["magiclink","recovery"].includes(e.type),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(e.type)?"otp":"password"})}async recover(e){if(!e)throw le("Password recovery requires an email",400);if(e=e.toLowerCase(),!br(e))throw le("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=kt(),s=tt(),i=new Date().toISOString();await this.repo.updateUser(n.id,{recovery_token:s,recovery_sent_at:i}),await this.createAuditLog(n.id,e,"user_recovery_requested","user",false),await this.mailer.sendRecovery(e,s,r,{userId:n.id,redirectTo:this.config.site_url});}async resend(e,n){if(!["signup","email_change","sms","phone_change"].includes(e))throw le("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw le("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!br(n))throw le("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=kt(),i=tt(),o=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw Ko()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw Ko();await this.repo.updateUser(r.id,{email_change_token_new:i,email_change_sent_at:o}),await this.mailer.sendEmailChange(r.email_change,i,s,{userId:r.id,redirectTo:this.config.site_url});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw jh();let r=kt(),s=tt(),i=new Date().toISOString();await this.repo.updateUser(n.id,{reauthentication_token:s,reauthentication_sent_at:i}),await this.mailer.sendReauthentication(n.email,r,{userId:n.id,tokenHash:s,redirectTo:this.config.site_url}),await this.createAuditLog(n.id,n.email??"","user_reauthenticate_requested","",false);}async createSessionForUser(e,n,r="session",s={}){let i=uu(e.last_sign_in_at,e.updated_at),o=await this.repo.updateUser(e.id,{last_sign_in_at:i}),a=o?this.repo.parseUserJson(o):e;this.config.sessions?.single_per_user&&await this.repo.revokeUserRefreshTokens(e.id);let l=ze();await this.repo.createSession({id:l,user_id:e.id});let c=cu();await this.repo.createRefreshToken({token:c,user_id:e.id,session_id:l}),(s.createLoginAudit??true)&&await this.createAuditLog(e.id,e.email??"","login","account",s.includeLoginProviderTrait??true);let u=await ou({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:l},this.config.jwt_secret,this.jwtExpiry),f=Math.floor(Date.now()/1e3);return tg({access_token:u,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:f+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=Yh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw Dh(this.minPasswordLength,this.passwordRequiredCharacters,n)}mapUserToResponse(e,n,r){let s=typeof e.raw_app_meta_data=="string"?JSON.parse(e.raw_app_meta_data):e.raw_app_meta_data??{},i=typeof e.raw_user_meta_data=="string"?JSON.parse(e.raw_user_meta_data):e.raw_user_meta_data??{},o={id:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??"",phone:e.phone??"",app_metadata:s,user_metadata:i,identities:n.map(a=>this.mapIdentityToResponse(a,r,e)),created_at:e.created_at,updated_at:e.updated_at,is_anonymous:false};return e.confirmed_at&&(o.email_confirmed_at=e.confirmed_at,(r==="user"||r==="verify")&&(o.confirmed_at=e.confirmed_at)),e.last_sign_in_at&&(o.last_sign_in_at=e.last_sign_in_at),e.confirmation_sent_at&&(o.confirmation_sent_at=e.confirmation_sent_at),e.email_change&&(o.new_email=e.email_change),e.email_change_sent_at&&(o.email_change_sent_at=e.email_change_sent_at),r==="verify"&&e.recovery_sent_at&&(o.recovery_sent_at=e.recovery_sent_at),o}mapIdentityToResponse(e,n,r){let s=typeof e.identity_data=="string"?JSON.parse(e.identity_data):e.identity_data??{},i=n==="session"&&r.confirmed_at?{...s,email_verified:true}:s,o=e.email??(typeof i.email=="string"?i.email:r.email??void 0);return {identity_id:e.id,id:e.provider_id,user_id:e.user_id,identity_data:i,provider:"email",last_sign_in_at:e.last_sign_in_at??e.created_at,created_at:e.created_at,updated_at:e.updated_at,...o?{email:o}:{}}}async findUserByTokenAndType(e,n){if(n==="email_change"){let r=await this.repo.findUserByToken("email_change_token_current",e);if(r)return {user:r,tokenColumn:"email_change_token_current"};let s=await this.repo.findUserByToken("email_change_token_new",e);return s?{user:s,tokenColumn:"email_change_token_new"}:null}for(let r of this.getTokenColumnsForType(n)){let s=await this.repo.findUserByToken(r,e);if(s)return {user:s,tokenColumn:r}}return null}otpMatchesStoredTokenHash(e,n,r){return !n||typeof r!="string"?false:(Yc.get(e.toLowerCase())??[]).some(i=>i.otp===n&&i.tokenHash===r)}getTokenColumnsForType(e){switch(e){case "signup":return ["confirmation_token"];case "magiclink":return ["recovery_token","confirmation_token"];case "recovery":return ["recovery_token"];case "email_change":return ["email_change_token_new"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true){let o={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(o.traits={provider:"email"}),await this.repo.createAuditLogEntry({id:ze(),payload:o});}};function AR(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function kR(t){switch(t){case "letters_digits":return ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789"];case "lower_upper_letters_digits_symbols":return ["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789","!@#$%^&*"];default:return []}}function Zh(t){if(!t)return;let e=t.match(/^(\d+)(ms|s|m|h)?$/);if(!e)return;let n=Number(e[1]);switch(e[2]??"s"){case "ms":return n/1e3;case "m":return n*60;case "h":return n*3600;default:return n}}function br(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function $R(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function eg(t){return t.revoked===true||t.revoked===1}function OR(t,e){let n=[],r=[e];for(;r.length>0;){let s=r.shift();for(let i of t)i.parent!==s||n.some(o=>o.id===i.id)||(n.push(i),r.push(i.token));}return n}function uu(...t){let e=Math.max(0,...t.map(r=>r?Date.parse(r):0)),n=Date.now();return new Date(Math.max(n,e+1)).toISOString()}function tg(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}function fu(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function $n(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Gs=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async findUserByEmail(e){return await this.table("users").selectAll().where("email","=",e.toLowerCase()).executeTakeFirst()??null}async findUserById(e){return await this.table("users").selectAll().where("id","=",e).executeTakeFirst()??null}async findUserByToken(e,n){return await this.table("users").selectAll().where(e,"=",n).executeTakeFirst()??null}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email.toLowerCase(),encrypted_password:e.encrypted_password??null,phone:e.phone??null,email_confirmed_at:e.email_confirmed_at??e.confirmed_at??null,confirmation_token:e.confirmation_token??null,confirmation_sent_at:e.confirmation_sent_at??null,recovery_token:e.recovery_token??null,recovery_sent_at:e.recovery_sent_at??null,email_change:e.email_change??null,email_change_token_new:e.email_change_token_new??null,email_change_token_current:e.email_change_token_current??null,email_change_sent_at:e.email_change_sent_at??null,email_change_confirm_status:e.email_change_confirm_status??0,reauthentication_token:e.reauthentication_token??null,reauthentication_sent_at:e.reauthentication_sent_at??null,raw_app_meta_data:$n(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:$n(e.raw_user_meta_data??{}),is_sso_user:this.bool(e.is_sso_user??false),is_anonymous:this.bool(e.is_anonymous??false),last_sign_in_at:e.last_sign_in_at??null,created_at:n,updated_at:n};return await this.insertInto("users").values(r).execute(),await this.findUserById(e.id)}async updateUser(e,n){let r={...n,updated_at:new Date().toISOString()};return r.confirmed_at!=null&&r.email_confirmed_at==null&&(r.email_confirmed_at=r.confirmed_at),delete r.confirmed_at,r.raw_app_meta_data!=null&&(r.raw_app_meta_data=$n(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=$n(r.raw_user_meta_data)),r.is_sso_user!=null&&(r.is_sso_user=this.bool(!!r.is_sso_user)),r.is_anonymous!=null&&(r.is_anonymous=this.bool(!!r.is_anonymous)),await this.update("users").set(r).where("id","=",e).execute(),this.findUserById(e)}async createSession(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id,aal:e.aal??"aal1",not_after:null,refreshed_at:null,user_agent:null,ip:null,tag:null,refresh_token_hmac_key:null,refresh_token_counter:null,scopes:null,factor_id:null,created_at:n,updated_at:n};return await this.insertInto("sessions").values(r).execute(),r}async findSessionById(e){return await this.table("sessions").selectAll().where("id","=",e).executeTakeFirst()??null}async updateSessionRefreshedAt(e,n){return await this.update("sessions").set({refreshed_at:n,updated_at:n}).where("id","=",e).execute(),this.findSessionById(e)}async deleteSession(e){await this.deleteFrom("sessions").where("id","=",e).execute();}async deleteUserSessions(e,n){let r=this.deleteFrom("sessions").where("user_id","=",e);n&&(r=r.where("id","!=",n)),await r.execute();}async deleteRefreshTokensForSession(e){await this.deleteFrom("refresh_tokens").where("session_id","=",e).execute();}async deleteRefreshTokensForUser(e,n){let r=this.deleteFrom("refresh_tokens").where("user_id","=",e);n&&(r=r.where("session_id","!=",n)),await r.execute();}async createRefreshToken(e){let n=new Date().toISOString(),r={id:ze(),token:e.token,user_id:e.user_id,session_id:e.session_id,revoked:this.bool(false),parent:e.parent??null,created_at:n,updated_at:n};return await this.insertInto("refresh_tokens").values(r).execute(),r}async findRefreshToken(e){return await this.table("refresh_tokens").selectAll().where("token","=",e).executeTakeFirst()??null}async findRefreshTokensBySession(e){return await this.table("refresh_tokens").selectAll().where("session_id","=",e).execute()}async revokeRefreshToken(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","=",e).execute();}async revokeSessionRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("session_id","=",e).execute();}async revokeRefreshTokensByIds(e){e.length!==0&&await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("id","in",e).execute();}async revokeUserRefreshTokens(e){await this.update("refresh_tokens").set({revoked:this.bool(true),updated_at:new Date().toISOString()}).where("user_id","=",e).execute();}async createIdentity(e){let n=new Date().toISOString(),r={id:e.id,provider:e.provider,provider_id:e.provider_id,user_id:e.user_id,identity_data:$n(e.identity_data),last_sign_in_at:e.last_sign_in_at??n,created_at:n,updated_at:n};return await this.insertInto("identities").values(r).execute(),{...r,identity_data:e.identity_data}}async findIdentitiesByUserId(e){return (await this.table("identities").selectAll().where("user_id","=",e).execute()).map(r=>({...r,identity_data:fu(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=$n(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async createAuditLogEntry(e){let n={id:e.id,payload:$n(e.payload??{}),ip_address:e.ip_address??"",created_at:new Date().toISOString()};await this.insertInto("audit_log_entries").values(n).execute();}parseUserJson(e){return {...e,raw_app_meta_data:fu(e.raw_app_meta_data),raw_user_meta_data:fu(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};function ng(){return {version:PR(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function rg(t){return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,apple:false,azure:false,bitbucket:false,discord:false,facebook:false,snapchat:false,figma:false,fly:false,github:false,gitlab:false,google:false,keycloak:false,kakao:false,linkedin:false,linkedin_oidc:false,notion:false,spotify:false,slack:false,slack_oidc:false,workos:false,twitch:false,twitter:false,email:t.email?.enable_signup??true,phone:false,zoom:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function sg(){return {keys:[]}}function ig(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function PR(){return [pu(JSON.stringify({alg:"HS256",typ:"JWT"})),pu(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),pu("metadata")].join(".")}function pu(t){if(typeof Buffer<"u")return Buffer.from(t,"utf-8").toString("base64url");let e=new TextEncoder().encode(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var du=t=>t;var NR="00000000-0000-0000-0000-000000000000",IR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,mu=({onError:t}={})=>du(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await ag(e);if(r&&t)return t(r,e)}await n();}),Vs=()=>du(async(t,e)=>{if(!t.var.userId){let n=await ag(t);if(n)return og(t,n);if(!t.var.userId)return og(t,hr())}await e();});async function ag(t){let e=t.req.header("Authorization");if(!e)return hr();if(!e.startsWith("Bearer "))return hr();let n=e.slice(7);if(!n||/^\s/.test(n))return hr();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await Vh(n,r);}catch(c){return c instanceof G?c:hr()}let i=DR(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return Mh();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Uh();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function DR(t){let e=t.sub,n=t.role;return e==null||e===""?eu():typeof e!="string"?tu():IR.test(e)?e===NR&&n==="service_role"?eu():null:tu()}function og(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var hu=new _e().onError((t,e)=>{if(t instanceof G){e.header("X-Sb-Error-Code",t.code);for(let[n,r]of Object.entries(t.headers??{}))e.header(n,r);return e.json(t.toJSON(),t.status)}return console.error("Auth error:",t),e.json({error:"server_error",error_description:"Internal server error"},500)}).options("*",t=>{let e=t.req.header("Access-Control-Request-Method");return e&&t.header("Access-Control-Allow-Methods",e),t.header("Access-Control-Allow-Credentials","true"),t.header("Access-Control-Allow-Origin","*"),t.body(null,204)}).post("/signup",async t=>{let e=await $t(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(zo(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",On("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await $t(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return zo(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return zo(t,s),t.json(s,200)}throw Gh()}).all("/token",On("POST")).post("/otp",async t=>{let e=await $t(t),{authService:n}=t.var;return await n.signInWithOtp(e.email,{shouldCreateUser:e.create_user??e.options?.shouldCreateUser}),t.json({},200)}).post("/magiclink",async t=>{let e=await $t(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",On("POST")).post("/verify",async t=>{let e=await $t(t),{authService:n}=t.var;LR(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return zo(t,r),t.json(r,200)}).get("/verify",t=>{let e=t.req.query("type");throw e?lg.has(e)?le("Verify requires a token or a token hash",400):le("Invalid email verification type",400):le("Verify requires a verification type",400)}).post("/recover",async t=>{let e=await $t(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await $t(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(ng(),200)).all("/health",On("GET")).get("/settings",t=>t.json(rg(t.var.app.config.auth??{}),200)).all("/settings",On("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(sg(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(ig(),200))).all("/nonexistent",jR).use(Vs()).post("/logout",async t=>{let e=await $t(t),{authService:n}=t.var;return await n.signOut(t.get("sessionId"),t.req.query("scope")??e.scope,t.get("userId")),t.body(null,204)}).get("/user",async t=>{let{authService:e}=t.var,n=await e.getUser(t.get("userId"));return t.json(n,200)}).put("/user",async t=>{let e=await $t(t),{authService:n}=t.var,r=await n.updateUser(t.get("userId"),{data:e.data,password:e.password,email:e.email});return t.json(r,200)}).all("/user",On("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",On("GET"));function On(t){return e=>(e.header("Allow",t),e.body(null,405))}function jR(t){return t.header("Content-Type","text/plain; charset=utf-8"),t.header("X-Content-Type-Options","nosniff"),t.body("404 page not found",404)}var lg=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function LR(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw le("Verify requires a verification type",400);if(!lg.has(e))throw le("Invalid email verification type",400);let n=typeof t.token_hash=="string"?t.token_hash:"",r=typeof t.token=="string"?t.token:"",s=typeof t.email=="string"?t.email:"";if(e==="signup"&&!n&&!(s&&r))throw le("Verify requires either a token or a token hash",400)}async function $t(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw Ks("Could not parse request body as JSON: unexpected end of JSON input");return {}}let n=await t.req.text();if(n===""){if(e.requireBody)throw Ks("Could not parse request body as JSON: unexpected end of JSON input");return {}}try{return JSON.parse(n)}catch{if(t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim()==="application/x-www-form-urlencoded")throw Ks("Could not parse request body as JSON: unexpected end of JSON input");let s=au(n)||"invalid character ' ' looking for beginning of value";throw Ks(`Could not parse request body as JSON: ${s}`)}}function zo(t,e){e.session_id&&t.header("Sb-Auth-Session-Id",e.session_id),e.user_id&&t.header("Sb-Auth-User-Id",e.user_id),e.refresh_token&&t.header("Sb-Auth-Refresh-Token-Prefix",String(e.refresh_token).slice(0,8));}function cg(t){let e=t.connection.dialect,n=new Gs(t.connection.kysely,e);return new zs(n,t.config.auth,t._mailer??new Hs(t.drivers.email))}function ug(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function fg(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function tn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Qs=class{constructor(e,n){this.db=e;this.dialect=n;this.schema="storage";}schema;table(e){return this.db.withSchema(this.schema).selectFrom(e)}insertInto(e){return this.db.withSchema(this.schema).insertInto(e)}update(e){return this.db.withSchema(this.schema).updateTable(e)}deleteFrom(e){return this.db.withSchema(this.schema).deleteFrom(e)}async createBucket(e){let n=new Date().toISOString(),r={id:e.id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,public:e.public??false,file_size_limit:e.file_size_limit??null,allowed_mime_types:this.dialect==="postgres"?e.allowed_mime_types??null:tn(e.allowed_mime_types??[]),created_at:n,updated_at:n};return await this.insertInto("buckets").values(r).execute(),await this.findBucketById(e.id)}async findBucketById(e){let n=await this.table("buckets").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async findBucketByName(e){let n=await this.table("buckets").selectAll().where("name","=",e).executeTakeFirst();return n?this.parseBucketRow(n):null}async listBuckets(){return (await this.table("buckets").selectAll().execute()).map(n=>this.parseBucketRow(n))}async updateBucket(e,n){let r={updated_at:new Date().toISOString()};return n.public!==void 0&&(r.public=n.public),n.file_size_limit!==void 0&&(r.file_size_limit=n.file_size_limit),n.allowed_mime_types!==void 0&&(r.allowed_mime_types=this.dialect==="postgres"?n.allowed_mime_types??null:tn(n.allowed_mime_types)),await this.update("buckets").set(r).where("id","=",e).execute(),this.findBucketById(e)}async deleteBucket(e){await this.deleteFrom("buckets").where("id","=",e).execute();}async isBucketEmpty(e){let n=await this.table("objects").select(this.db.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();return Number(n?.count??0)===0}async createObject(e){let n=new Date().toISOString(),r={id:e.id,bucket_id:e.bucket_id,name:e.name,owner:e.owner??null,owner_id:e.owner_id??null,metadata:tn(e.metadata??{}),user_metadata:tn(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=tn(e.name.split("/"))),await this.insertInto("objects").values(r).execute(),await this.findObjectById(e.id)}async findObjectById(e){let n=await this.table("objects").selectAll().where("id","=",e).executeTakeFirst();return n?this.parseObjectRow(n):null}async findObjectByPath(e,n){let r=await this.table("objects").selectAll().where("bucket_id","=",e).where("name","=",n).executeTakeFirst();return r?this.parseObjectRow(r):null}async listObjects(e,n,r){let s=this.table("objects").selectAll().where("bucket_id","=",e);return n&&(s=s.where("name","like",`${n}%`)),r?.search&&(s=s.where("name","like",`%${r.search}%`)),r?.sortBy?s=s.orderBy(r.sortBy.column,r.sortBy.order):s=s.orderBy("name","asc"),r?.limit&&(s=s.limit(r.limit)),r?.offset&&(s=s.offset(r.offset)),(await s.execute()).map(o=>this.parseObjectRow(o))}async updateObject(e,n){let r={updated_at:new Date().toISOString()};return n.name!==void 0&&(r.name=n.name,this.dialect!=="postgres"&&(r.path_tokens=tn(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=tn(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=tn(n.user_metadata)),n.version!==void 0&&(r.version=n.version),n.owner!==void 0&&(r.owner=n.owner),n.owner_id!==void 0&&(r.owner_id=n.owner_id),await this.update("objects").set(r).where("id","=",e).execute(),this.findObjectById(e)}async deleteObject(e){await this.deleteFrom("objects").where("id","=",e).execute();}async deleteObjectsByBucket(e){let r=(await this.table("objects").select("name").where("bucket_id","=",e).execute()).map(s=>s.name);return r.length>0&&await this.deleteFrom("objects").where("bucket_id","=",e).execute(),r}async objectExists(e,n){return !!await this.table("objects").select("id").where("bucket_id","=",e).where("name","=",n).executeTakeFirst()}async touchObject(e){await this.update("objects").set({last_accessed_at:new Date().toISOString()}).where("id","=",e).execute();}parseBucketRow(e){return {...e,owner:e.owner??"",owner_id:e.owner_id??"",public:!!e.public,allowed_mime_types:e.allowed_mime_types==null?null:fg(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:ug(e.metadata),user_metadata:ug(e.user_metadata),path_tokens:fg(e.path_tokens)}}};var X=class t extends Error{constructor(n,r,s){super(s);this.status=n;this.code=r;}name="StorageError";static bucketNotFound(n){return new t(404,"Bucket not found",`Bucket not found: ${n}`)}static bucketAlreadyExists(n){return new t(409,"Duplicate","The resource already exists")}static bucketNotEmpty(n){return new t(409,"ResourceNotEmpty","The bucket you tried to delete is not empty")}static objectNotFound(n){return new t(404,"Object not found",`Object not found: ${n}`)}static invalidMimeType(n,r){return new t(415,"invalid_mime_type",`mime type ${n} is not supported. Supported: ${r.join(", ")}`)}static fileTooLarge(n){return new t(413,"Payload too large",`The object exceeded the maximum allowed size of ${n} bytes`)}static invalidKey(n){return new t(400,"Invalid key",`Invalid object key: ${n}`)}static storageNotConfigured(){return new t(500,"Storage not configured","Storage is enabled but no storage adapter has been set. Set app._storageAdapter before making storage requests.")}toJSON(){return {statusCode:String(this.status),error:this.code,message:this.message}}};var Ys=class{constructor(e,n,r,s={},i){this.repo=e;this.adapter=n;this.config=r;this.options=s;this.transformationAdapter=i;}initialized=false;async init(){if(!this.initialized&&(this.initialized=true,this.options.autoCreateBuckets!==false&&this.config.buckets))for(let[e,n]of Object.entries(this.config.buckets))await this.repo.findBucketById(e)||await this.repo.createBucket({id:e,name:e,public:n.public??false,file_size_limit:n.file_size_limit?MR(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw X.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw X.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw X.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){gu(n);let i=await this.repo.findBucketById(e);if(!i)throw X.bucketNotFound(e);let o=s?.contentType??"application/octet-stream",a=s?.cacheControl??"no-cache";if(i.allowed_mime_types&&i.allowed_mime_types.length>0&&!i.allowed_mime_types.includes(o))throw X.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw X.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw X.bucketAlreadyExists(n);return await this.adapter.uploadObject(e,n,void 0,r,o,a),c&&s?.upsert?await this.repo.updateObject(c.id,{metadata:s?.metadata??c.metadata,version:crypto.randomUUID()}):this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:n,owner:s?.owner??null,owner_id:s?.owner??null,metadata:s?.metadata??{},version:crypto.randomUUID()})}async download(e,n,r){let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);if(await this.repo.touchObject(s.id),r?.transform&&this.transformationAdapter&&!this.transformationAdapter.requiresBuffer&&this.transformationAdapter.transformFromUrl){let o=await this.adapter.privateAssetUrl(e,n,s.version??void 0),a=await this.transformationAdapter.transformFromUrl(o,r.transform);return {body:a.body,metadata:{cacheControl:"public, max-age=3600",contentLength:a.contentLength??0,size:a.contentLength??0,mimetype:a.contentType,eTag:""}}}let i=await this.adapter.getObject(e,n,s.version??void 0);if(!i.body)throw X.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await FR(i.body),a=await this.transformationAdapter.transform(o,r.transform);return {body:a.body,metadata:{...i.metadata,mimetype:a.contentType,size:a.contentLength??0,contentLength:a.contentLength??0}}}return {body:i.body,metadata:i.metadata}}async update(e,n,r,s){return this.upload(e,n,r,{...s,upsert:s?.upsert??true})}async remove(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let s=[];for(let i of n){let o=await this.repo.findObjectByPath(e,i);o&&(await this.adapter.deleteObject(e,i,o.version??void 0),await this.repo.deleteObject(o.id),s.push(o));}return s}async list(e,n,r){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){gu(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.adapter.deleteObject(e,n,s.version??void 0),await this.repo.updateObject(s.id,{name:r,version:crypto.randomUUID()});}async copy(e,n,r){gu(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw X.objectNotFound(n);return await this.adapter.copyObject(e,n,s.version??void 0,r,void 0),await this.repo.createObject({id:crypto.randomUUID(),bucket_id:e,name:r,owner:s.owner,owner_id:s.owner_id,metadata:s.metadata,version:crypto.randomUUID()}),{key:r}}async info(e,n){let r=await this.repo.findObjectByPath(e,n);if(!r)throw X.objectNotFound(n);let s=await this.adapter.headObject(e,n,r.version??void 0);return {...r,httpMetadata:s}}async exists(e,n){return this.repo.objectExists(e,n)}async createSignedUrl(e,n,r){if(!await this.repo.findObjectByPath(e,n))throw X.objectNotFound(n);let i=await this.signStorageToken({sub:n,bucket:e,intent:"download"},r);return {signedUrl:`/storage/v1/object/sign/${e}/${n}?token=${i}`}}async createSignedUrls(e,n,r){let s=[];for(let i of n)try{let{signedUrl:o}=await this.createSignedUrl(e,i,r);s.push({path:i,signedUrl:o,error:null});}catch(o){s.push({path:i,signedUrl:"",error:o.message});}return s}async createSignedUploadUrl(e,n){if(!await this.repo.findBucketById(e))throw X.bucketNotFound(e);let s=await this.signStorageToken({sub:n,bucket:e,intent:"upload"},7200);return {signedUrl:`/storage/v1/object/upload/sign/${e}/${n}?token=${s}`,token:s,path:n}}async verifySignedUrl(e){let n=new TextEncoder().encode(this.config.jwtSecret),{payload:r}=await Cn(e,n,{algorithms:["HS256"]});return {bucket:r.bucket,path:r.sub,intent:r.intent}}async signStorageToken(e,n){let r=new TextEncoder().encode(this.config.jwtSecret),s=Math.floor(Date.now()/1e3);return new Tn({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function FR(t){if(t instanceof Uint8Array||Buffer.isBuffer(t))return t;if(t instanceof Blob)return new Uint8Array(await t.arrayBuffer());let e=[],n=t.getReader();for(;;){let{done:r,value:s}=await n.read();if(r)break;e.push(s);}return Buffer.concat(e)}function gu(t){if(!t||t.includes("..")||t.startsWith("/"))throw X.invalidKey(t)}function MR(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var UR=/^[\w!#$%&'*.^`|~+-]+$/,BR=/^[ !#-:<-[\]-~]*$/,yu=(t,e)=>{let n=t.trim().split(";"),r={};for(let s of n){s=s.trim();let i=s.indexOf("=");if(i===-1)continue;let o=s.substring(0,i).trim();if(!UR.test(o))continue;let a=s.substring(i+1).trim();if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),BR.test(a)&&(r[o]=a.indexOf("%")!==-1?qn(a,Br):a,e));}return r};var pg=(t,e,n)=>{let r=t.req.raw.headers.get("Cookie");return r?yu(r):{}};var dg=(t,e)=>new Response(t,{headers:{"Content-Type":e}}).formData();var qR=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,HR=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,WR=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,bu=(t,e)=>async(n,r)=>{let s={},i=n.req.header("Content-Type");switch(t){case "json":if(!i||!qR.test(i))break;try{s=await n.req.json();}catch{let a="Malformed JSON in request body";throw new Pi(400,{message:a})}break;case "form":{if(!i||!(HR.test(i)||WR.test(i)))break;let a;if(n.req.bodyCache.formData)a=await n.req.bodyCache.formData;else try{let c=await n.req.arrayBuffer();a=await dg(c,i),n.req.bodyCache.formData=a;}catch(c){let u="Malformed FormData request.";throw u+=c instanceof Error?` ${c.message}`:` ${String(c)}`,new Pi(400,{message:u})}let l={};a.forEach((c,u)=>{u.endsWith("[]")?(l[u]??=[]).push(c):Array.isArray(l[u])?l[u].push(c):u in l?l[u]=[l[u],c]:l[u]=c;}),s=l;break}case "query":s=Object.fromEntries(Object.entries(n.req.queries()).map(([a,l])=>l.length===1?[a,l[0]]:[a,l]));break;case "param":s=n.req.param();break;case "header":s=n.req.header();break;case "cookie":s=pg(n);break}let o=await e(s,n);return o instanceof Response?o:(n.req.addValidatedData(t,o),await r())};var KR=Symbol.for("jsonv"),JR=(t,e)=>Object.assign(t,{[KR]:e}),Ot=(t,e,n,r)=>{let s=bu(t,async(i,o)=>{let a=e.coerce(i,{dropUnknown:n?.dropUnknown}),l=e.validate(a);if(!l.valid)return o.json({...l,schema:e},400);return a});return JR(s,{type:"parameters",skip:n?.skipOpenAPI,value:{target:t,schema:e}})};ie();var zR=b.object({id:b.string(),name:b.string(),public:b.boolean({default:false}).optional(),file_size_limit:b.number().optional(),allowed_mime_types:b.array(b.string()).optional()}),GR=b.object({public:b.boolean().optional(),file_size_limit:b.number().optional(),allowed_mime_types:b.array(b.string()).optional()}),VR=b.object({prefix:b.string().optional(),limit:b.number().optional(),offset:b.number().optional(),sortBy:b.object({column:b.string(),order:b.string()}).optional(),search:b.string().optional()}),mg=b.object({bucketId:b.string(),sourceKey:b.string(),destinationKey:b.string()}),QR=b.object({expiresIn:b.number()}),YR=b.object({expiresIn:b.number(),paths:b.array(b.string())}),XR=b.object({prefixes:b.array(b.string())}),ZR=new _e().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/public/${e}/`),{storageService:r}=t.var;if(!(await r.getBucket(e)).public)return t.json({error:"Bucket is not public"},400);let i=wu(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:Su(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n)return t.json({error:"Invalid token"},403);let o=wu(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:Su(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/upload/sign/${e}/`),r=t.req.query("token"),{storageService:s}=t.var;if(!r)return t.json({error:"Missing token"},400);let i=await s.verifySignedUrl(r);if(i.bucket!==e||i.path!==n||i.intent!=="upload")return t.json({error:"Invalid token"},403);let o=t.req.header("content-type")??"application/octet-stream",a=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,l=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),c=await s.upload(e,n,l,{contentType:o,contentLength:a,upsert:true});return t.json({Key:c.name},200)}),eC=new _e().use(Vs()).post("/bucket",Ot("json",zR),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.createBucket({id:e.id,name:e.name??e.id,public:e.public,file_size_limit:e.file_size_limit,allowed_mime_types:e.allowed_mime_types});return t.json({name:r.name},200)}).get("/bucket",async t=>{let{storageService:e}=t.var,n=await e.listBuckets();return t.json(n,200)}).get("/bucket/:id",async t=>{let{storageService:e}=t.var,n=await e.getBucket(t.req.param("id"));return t.json(n,200)}).put("/bucket/:id",Ot("json",GR),async t=>{let{storageService:e}=t.var;return await e.updateBucket(t.req.param("id"),t.req.valid("json")),t.json({message:"Successfully updated"},200)}).delete("/bucket/:id",async t=>{let{storageService:e}=t.var;return await e.deleteBucket(t.req.param("id")),t.json({message:"Successfully deleted"},200)}).post("/bucket/:id/empty",async t=>{let{storageService:e}=t.var;return await e.emptyBucket(t.req.param("id")),t.json({message:"Empty bucket has been queued. Completion may take up to an hour."},200)}).post("/object/list/:bucketId",Ot("json",VR),async t=>{let e=t.req.param("bucketId"),n=t.req.valid("json"),{storageService:r}=t.var,s=await r.list(e,n.prefix,{limit:n.limit,offset:n.offset,sortBy:n.sortBy,search:n.search});return t.json(s,200)}).post("/object/move",Ot("json",mg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var;return await n.move(e.bucketId,e.sourceKey,e.destinationKey),t.json({message:"Successfully moved"},200)}).post("/object/copy",Ot("json",mg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.copy(e.bucketId,e.sourceKey,e.destinationKey);return t.json({key:r.key},200)}).get("/object/info/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/info/${e}/`),{storageService:r}=t.var,s=await r.info(e,n);return t.json(s,200)}).post("/object/sign/:bucketId/*",Ot("json",QR),async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/sign/${e}/`),{expiresIn:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrl(e,n,r);return t.json(i,200)}).post("/object/sign/:bucketId",Ot("json",YR),async t=>{let e=t.req.param("bucketId"),{expiresIn:n,paths:r}=t.req.valid("json"),{storageService:s}=t.var,i=await s.createSignedUrls(e,r,n);return t.json(i,200)}).post("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/upload/sign/${e}/`),{storageService:r}=t.var,s=await r.createSignedUploadUrl(e,n);return t.json(s,200)}).delete("/object/:bucketId",Ot("json",XR),async t=>{let e=t.req.param("bucketId"),{prefixes:n}=t.req.valid("json"),{storageService:r}=t.var,s=await r.remove(e,n);return t.json(s,200)}).post("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("x-upsert")==="true",a,l,c;if(s.startsWith("multipart/form-data")){let p=(await t.req.formData()).get("file");if(!p)throw new X(400,"InvalidRequest","Missing file in multipart upload");let d=new Uint8Array(await p.arrayBuffer());a=d,l=p.type||"application/octet-stream",c=d.length;}else a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=s,c=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0;let u=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${u.name}`,Id:u.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type")??"application/octet-stream",i=t.req.header("cache-control")??"no-cache",o=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0,a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=await r.update(e,n,a,{contentType:s,cacheControl:i,contentLength:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${l.name}`,Id:l.id},200)}).get("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=wu(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:Su(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=pt(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),_u=new _e().onError((t,e)=>t instanceof X?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",ZR).route("/",eC);function pt(t,e){let n=t.replace(/^\/storage\/v1/,""),r=n.indexOf(e);return r===-1?n.split("/").slice(3).join("/"):n.slice(r+e.length)}function wu(t){let{width:e,height:n,resize:r,format:s,quality:i}=t;return !e&&!n&&!r&&!s&&!i?null:{width:e?Number.parseInt(e,10):void 0,height:n?Number.parseInt(n,10):void 0,resize:r,format:s,quality:i?Number.parseInt(i,10):void 0}}function Su(t){let e={"Content-Type":t.mimetype,"Cache-Control":t.cacheControl,ETag:t.eTag};return t.contentLength&&(e["Content-Length"]=String(t.contentLength)),t.lastModified&&(e["Last-Modified"]=t.lastModified.toUTCString()),t.contentRange&&(e["Content-Range"]=t.contentRange),e}ys();var Eu=`-- supabase/storage core schema (Postgres)
|
|
90
90
|
-- Source: supabase/storage migrations (consolidated)
|
|
91
91
|
|
|
92
92
|
CREATE SCHEMA IF NOT EXISTS storage;
|
|
@@ -121,11 +121,11 @@ CREATE TABLE IF NOT EXISTS storage.objects (
|
|
|
121
121
|
);
|
|
122
122
|
|
|
123
123
|
CREATE INDEX IF NOT EXISTS storage_objects_name_pattern_search ON storage.objects (name text_pattern_ops);
|
|
124
|
-
`;function xu(t=true){return t?gs(Eu):Eu}var Go=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function dg(t){if(!t._storageAdapter)throw X.storageNotConfigured();let e=t.connection.dialect,n=new Qs(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"secret",s=t._transformationAdapter??new Go;return new Ys(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?XR(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function XR(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var Ge=Symbol("RENDERER"),tn=Symbol("ERROR_HANDLER"),ee=Symbol("STASH"),Vo=Symbol("INTERNAL"),Ru=Symbol("MEMO"),wr=Symbol("PERMALINK");var Cu=t=>(t[Vo]=true,t);var Tu=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:Cu(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Cu(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[tn]=i=>{throw t.pop(),i},s},Qo=t=>{let e=[t],n=Tu(e);return n.values=e,n.Provider=n,Ot.push(n),n};var Ot=[],Xs=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new vu("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>Y(i,i.callbacks)):(e.pop(),Y(s))});return n.values=e,n.Provider=n,n[Ge]=Tu(e),Ot.push(n),n},Ce=t=>t.values.at(-1);var Sr={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Zs={},_r="data-precedence";var ni={};Ir(ni,{button:()=>oC,form:()=>sC,input:()=>iC,link:()=>nC,meta:()=>rC,script:()=>eC,style:()=>tC,title:()=>ZR});var On=t=>Array.isArray(t)?t:[t];var mg=new WeakMap,hg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=mg.get(i)||{};mg.set(i,o);let a=o[t]||=[],l=false,c=Sr[t];if(c.length>0){e:for(let[,u]of a)for(let f of c)if((u?.[f]??null)===n?.[f]){l=true;break e}}if(l?s[0]=s[0].replaceAll(e,""):c.length>0?a.push([e,n,r]):a.unshift([e,n,r]),s[0].indexOf("</head>")!==-1){let u;if(r===void 0)u=a.map(([f])=>f);else {let f=[];u=a.map(([p,,d])=>{let y=f.indexOf(d);return y===-1&&(f.push(d),y=f.length-1),[p,y]}).sort((p,d)=>p[1]-d[1]).map(([p])=>p);}u.forEach(f=>{s[0]=s[0].replaceAll(f,"");}),s[0]=s[0].replace(/(?=<\/head>)/,u.join(""));}},ei=(t,e,n)=>Y(new qe(t,n,On(e??[])).toString()),ti=(t,e,n,r)=>{if("itemProp"in n)return ei(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[_r]=s);let a=new qe(t,o,On(e||[])).toString();return a instanceof Promise?a.then(l=>Y(a,[...l.callbacks||[],hg(t,l,o,s)])):Y(a,[hg(t,a,o,s)])},ZR=({children:t,...e})=>{let n=Yo();if(n){let r=Ce(n);if(r==="svg"||r==="head")return new qe("title",e,On(t??[]))}return ti("title",t,e,false)},eC=({children:t,...e})=>{let n=Yo();return ["src","async"].some(r=>!e[r])||n&&Ce(n)==="head"?ei("script",t,e):ti("script",t,e,false)},tC=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,ti("style",t,e,true)):ei("style",t,e),nC=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?ei("link",t,e):ti("link",t,e,"precedence"in e),rC=({children:t,...e})=>{let n=Yo();return n&&Ce(n)==="head"?ei("meta",t,e):ti("meta",t,e,false)},gg=(t,{children:e,...n})=>new qe(t,n,On(e??[])),sC=t=>(typeof t.action=="function"&&(t.action=wr in t.action?t.action[wr]:void 0),gg("form",t)),yg=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=wr in e.formAction?e.formAction[wr]:void 0),gg(t,e)),iC=t=>yg("input",t),oC=t=>yg("button",t);var aC=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),Er=t=>aC.get(t)||t,ri=(t,e)=>{for(let[n,r]of Object.entries(t)){let s=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e(s,r==null?null:typeof r=="number"?s.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r);}};var si=void 0,Yo=()=>si,lC=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,cC=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],uC=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],ku=(t,e)=>{for(let n=0,r=t.length;n<r;n++){let s=t[n];if(typeof s=="string")St(s,e);else {if(typeof s=="boolean"||s===null||s===void 0)continue;s instanceof qe?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):ku(s,e);}}},qe=class{tag;props;key;children;isEscaped=true;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n;}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){let t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n);});try{this.toStringToBuffer(t);}finally{this.localContexts?.forEach(([e])=>{e.values.pop();});}return t.length===1?"callbacks"in t?Va(Y(t[0],t.callbacks)).toString():t[0]:ji(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=si&&Ce(si)==="svg"?i=>lC(Er(i)):i=>Er(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";ri(o,(l,c)=>{c!=null&&(a+=`${a?";":""}${l}:${c}`);}),t[0]+=' style="',St(a,t),t[0]+='"';}else if(typeof o=="string")t[0]+=` ${i}="`,St(o,t),t[0]+='"';else if(o!=null)if(typeof o=="number"||o.isEscaped)t[0]+=` ${i}="${o}"`;else if(typeof o=="boolean"&&uC.includes(i))o&&(t[0]+=` ${i}=""`);else if(i==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Y(o.__html)];}else if(o instanceof Promise)t[0]+=` ${i}="`,t.unshift('"',o);else if(typeof o=="function"){if(!i.startsWith("on")&&i!=="ref")throw new Error(`Invalid prop '${i}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${i}="`,St(o.toString(),t),t[0]+='"';}if(cC.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",ku(r,t),t[0]+=`</${e}>`;}},Au=class extends qe{toStringToBuffer(t){let{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);let r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Ot.length===0)t.unshift("",r);else {let s=Ot.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof qe&&(i.localContexts=s),i)));}else r instanceof qe?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):St(r,t);}},vu=class extends qe{toStringToBuffer(t){ku(this.children,t);}},bg=false,ii=(t,e,n)=>{if(!bg){for(let r in Zs)ni[r][Ge]=Zs[r];bg=true;}return typeof t=="function"?new Au(t,e,n):ni[t]?new Au(ni[t],e,n):t==="svg"||t==="head"?(si||=Xs(""),new qe(t,e,[new Au(si,{value:t},n)])):new qe(t,e,n)};var dt=({children:t})=>new vu("",{children:t},Array.isArray(t)?t:t?[t]:[]);var ta={};Ir(ta,{button:()=>Kg,clearCache:()=>EC,composeRef:()=>ea,form:()=>qg,input:()=>Wg,link:()=>Mg,meta:()=>Ug,script:()=>Lg,style:()=>Fg,title:()=>jg});var ai="_hp",fC={Change:"Input",DoubleClick:"DblClick"},pC={svg:"2000/svg",math:"1998/Math/MathML"},mt=[],Pu=new WeakMap,xr=void 0,Cg=()=>xr,Pt=t=>"t"in t,Ou={onClick:["click",false]},wg=t=>{if(!t.startsWith("on"))return;if(Ou[t])return Ou[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return Ou[t]=[(fC[n]||n).toLowerCase(),!!r]}},Sg=(t,e)=>xr&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dC=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=Er(r);let i=wg(r);if(i){if(n?.[r]!==s&&(n&&t.removeEventListener(i[0],n[r],i[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(i[0],s,i[1]);}}else if(r==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(r==="ref"){let o;typeof s=="function"?o=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,o=()=>s.current=null),Pu.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&ri(s,o.setProperty.bind(o)));}else {if(r==="value"){let a=t.nodeName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"){if(t.value=s==null||s===false?null:s,a==="TEXTAREA"){t.textContent=s;continue}else if(a==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else (r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=s);let o=Sg(t,r);s==null||s===false?t.removeAttribute(o):s===true?t.setAttribute(o,""):typeof s=="string"||typeof s=="number"?t.setAttribute(o,s):t.setAttribute(o,s.toString());}}}if(n)for(let r in n){let s=n[r];if(r!=="children"&&!(r in e)){r=Er(r);let i=wg(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?Pu.get(t)?.():t.removeAttribute(Sg(t,r));}}},mC=(t,e)=>{e[ee][0]=0,mt.push([t,e]);let n=e.tag[Ge]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{mt.pop();}},Tg=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ee][1][Iu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Pt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(Tg(i,e,n,r,s),i.s){for(let a=o;a<n.length;a++)n[a].s=true;i.s=false;}}else n.push(i),i.vR?.length&&(r.push(...i.vR),delete i.vR);});},hC=t=>{for(;t&&(t.tag===ai||!t.e);)t=t.tag===ai||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},vg=t=>{Pt(t)||(t[ee]?.[1][Iu]?.forEach(e=>e[2]?.()),Pu.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(vg)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(oi.delete(t),Xo.delete(t),delete t[ee][3],t.a=true);},Ag=(t,e,n)=>{t.c=e,kg(t,e,n);},_g=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Eg=Symbol(),kg=(t,e,n)=>{let r=[],s=[],i=[];Tg(t,e,r,s,i),s.forEach(vg);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=_g(o,hC(t.nN));c!==void 0?(l=o[c],a=c):a=_g(o,r.find(u=>u.tag!==ai&&u.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,u=r.length;c<u;c++,a++){let f=r[c],p;if(f.s&&f.e)p=f.e,f.s=false;else {let d=n||!f.e;Pt(f)?(f.e&&f.d&&(f.e.textContent=f.t),f.d=false,p=f.e||=document.createTextNode(f.t)):(p=f.e||=f.n?document.createElementNS(f.n,f.tag):document.createElement(f.tag),dC(p,f.props,f.pP),kg(f,p,d));}f.tag===ai?a--:n?p.parentNode||e.appendChild(p):o[a]!==p&&o[a-1]!==p&&(o[a+1]===p?e.appendChild(o[a]):e.insertBefore(p,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],u=[];i.forEach(([,f,,p,d])=>{f&&c.push(f),p&&u.push(p),d?.();}),c.forEach(f=>f()),u.length&&requestAnimationFrame(()=>{u.forEach(f=>f());});}},gC=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Xo=new WeakMap,Nu=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?mC(t,e):On(e.props.children),n[0]?.tag===""&&n[0][tn]&&(s=n[0][tn],t[5].push([t,s,e]));let i=r?[...e.pC]:e.vC?[...e.vC]:void 0,o=[],a;for(let l=0;l<n.length;l++){if(Array.isArray(n[l])){n.splice(l,1,...n[l].flat(1/0)),l--;continue}let c=yC(n[l]);if(c){typeof c.tag=="function"&&!c.tag[Vo]&&(Ot.length>0&&(c[ee][2]=Ot.map(f=>[f,f.values.at(-1)])),t[5]?.length&&(c[ee][3]=t[5].at(-1)));let u;if(i&&i.length){let f=i.findIndex(Pt(c)?p=>Pt(p):c.key!==void 0?p=>p.key===c.key&&p.tag===c.tag:p=>p.tag===c.tag);f!==-1&&(u=i[f],i.splice(f,1));}if(u)if(Pt(c))u.t!==c.t&&(u.t=c.t,u.d=!0),c=u;else {let f=u.pP=u.props;if(u.props=c.props,u.f||=c.f||e.f,typeof c.tag=="function"){let p=u[ee][2];u[ee][2]=c[ee][2]||[],u[ee][3]=c[ee][3],!u.f&&((u.o||u)===c.o||u.tag[Ru]?.(f,u.props))&&gC(p,u[ee][2])&&(u.s=!0);}c=u;}else if(!Pt(c)&&xr){let f=Ce(xr);f&&(c.n=f);}if(!Pt(c)&&!c.s&&(Nu(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let f=a;f&&!Pt(f);f=f.vC?.at(-1))f.nN=c;a=c;}}e.vR=r?[...e.vC,...i||[]]:i||[],e.vC=o,r&&delete e.pC;}catch(i){if(e.f=true,i===Eg){if(s)return;throw i}let[o,a,l]=e[ee]?.[3]||[];if(a){let c=()=>li([0,false,t[2]],l),u=Xo.get(l)||[];u.push(c),Xo.set(l,u);let f=a(i,()=>{let p=Xo.get(l);if(p){let d=p.indexOf(c);if(d!==-1)return p.splice(d,1),c()}});if(f){if(t[0]===1)t[1]=true;else if(Nu(t,l,[f]),(a.length===1||t!==o)&&l.c){Ag(l,l.c,false);return}throw Eg}}throw i}finally{s&&t[5].pop();}},yC=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return {t:t.toString(),d:true};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ee]=[0,[]];else {let e=pC[t.tag];e&&(xr||=Qo(""),t.props.children=[{tag:xr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var xg=(t,e)=>{e[ee][2]?.forEach(([n,r])=>{n.values.push(r);});try{Nu(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[ee][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&Ag(e,e.c,false);},oi=new WeakMap,Rg=[],li=async(t,e)=>{t[5]||=[];let n=oi.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(oi.set(e,[r,()=>{t[2]?t[2](t,e,i=>{xg(i,e);}).then(()=>r(e)):(xg(t,e),r(e));}]),Rg.length)Rg.at(-1).add(e);else {await Promise.resolve();let i=oi.get(e);i&&(oi.delete(e),i[1]());}return s};var $g=(t,e,n)=>({tag:ai,props:{children:t},key:n,e,p:1});var bC=0,Iu=1,wC=2,SC=3;var Du=new WeakMap,Pg=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var _C=void 0;var Og=[];var Zo=t=>{let e=()=>typeof t=="function"?t():t,n=mt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[ee][1][bC]||=[],i=r[ee][0]++;return s[i]||=[e(),o=>{let a=_C,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,Og.length){let[c,u]=Og.at(-1);Promise.all([c===3?r:li([c,false,a],r),u]).then(([f])=>{if(!f||!(c===2||c===3))return;let p=f.vC;requestAnimationFrame(()=>{setTimeout(()=>{p===f.vC&&li([c===3?1:0,false,a],f);});});});}else li([0,false,a],r);}]};var Rr=(t,e)=>{let n=mt.at(-1);if(!n)return t;let[,r]=n,s=r[ee][1][wC]||=[],i=r[ee][0]++,o=s[i];return Pg(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var ju=t=>{let e=Du.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>Du.set(t,[n]),n=>Du.set(t,[void 0,n])),t},Lu=(t,e)=>{let n=mt.at(-1);if(!n)return t();let[,r]=n,s=r[ee][1][SC]||=[],i=r[ee][0]++,o=s[i];return Pg(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Ig=Qo({pending:false,data:null,method:null,action:null}),Ng=new Set,Dg=t=>{Ng.add(t),t.finally(()=>Ng.delete(t));};var EC=()=>{Fu=Object.create(null),Mu=Object.create(null);},ea=(t,e)=>Lu(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null);}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null;}));let s=e(n);return ()=>{s?.(),r?.();}},[t]),Fu=Object.create(null),Mu=Object.create(null),ci=(t,e,n,r,s)=>{if(e?.itemProp)return {tag:t,props:e,type:t,ref:e.ref};let i=document.head,{onLoad:o,onError:a,precedence:l,blocking:c,...u}=e,f=null,p=false,d=Sr[t],y;if(d.length>0){let S=i.querySelectorAll(t);e:for(let _ of S)for(let w of Sr[t])if(_.getAttribute(w)===e[w]){f=_;break e}if(!f){let _=d.reduce((w,x)=>e[x]===void 0?w:`${w}-${x}-${e[x]}`,t);p=!Mu[_],f=Mu[_]||=(()=>{let w=document.createElement(t);for(let x of d)e[x]!==void 0&&w.setAttribute(x,e[x]),e.rel&&w.setAttribute("rel",e.rel);return w})();}}else y=i.querySelectorAll(t);l=r?l??"":void 0,r&&(u[_r]=l);let m=Rr(S=>{if(d.length>0){let _=false;for(let w of i.querySelectorAll(t)){if(_&&w.getAttribute(_r)!==l){i.insertBefore(S,w);return}w.getAttribute(_r)===l&&(_=true);}i.appendChild(S);}else if(y){let _=false;for(let w of y)if(w===S){_=true;break}_||i.insertBefore(S,i.contains(y[0])?y[0]:i.querySelector(t)),y=void 0;}},[l]),h=ea(e.ref,S=>{let _=d[0];if(n===2&&(S.innerHTML=""),(p||y)&&m(S),!a&&!o)return;let w=Fu[S.getAttribute(_)]||=new Promise((x,E)=>{S.addEventListener("load",x),S.addEventListener("error",E);});o&&(w=w.then(o)),a&&(w=w.catch(a)),w.catch(()=>{});});if(s&&c==="render"){let S=Sr[t][0];if(e[S]){let _=e[S],w=Fu[_]||=new Promise((x,E)=>{m(f),f.addEventListener("load",x),f.addEventListener("error",E);});ju(w);}}let g={tag:t,type:t,props:{...u,ref:h},ref:h};return g.p=n,f&&(g.e=f),$g(g,i)},jg=t=>{let e=Cg();return (e&&Ce(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:ci("title",t,void 0,false,false)},Lg=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:ci("script",t,1,false,true),Fg=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,ci("style",t,2,true,true)),Mg=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:ci("link",t,1,"precedence"in t,true),Ug=t=>ci("meta",t,void 0,false,false),Bg=Symbol(),qg=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Zo([null,false]),i=Rr(async c=>{let u=c.isTrusted?e:c.detail[Bg];if(typeof u!="function")return;c.preventDefault();let f=new FormData(c.target);s([f,true]);let p=u(f);p instanceof Promise&&(Dg(p),await p),s([null,true]);},[]),o=ea(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Ig,props:{value:{pending:a!==null,data:a,method:a?"post":null,action:a?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},Hg=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=Rr(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Bg]:e}}));},[]);n.ref=ea(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Wg=t=>Hg("input",t),Kg=t=>Hg("button",t);Object.assign(Zs,{title:jg,script:Lg,style:Fg,link:Mg,meta:Ug,form:qg,input:Wg,button:Kg});Xs(null);new TextEncoder;var Pn=":-hono-global",TC=new RegExp(`^${Pn}{(.*)}$`),sa="hono-css",Nt=Symbol(),be=Symbol(),je=Symbol(),ht=Symbol(),ia=Symbol(),Qg=Symbol();var Yg=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},vC=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),AC=new RegExp(["("+vC+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),kC=t=>t.replace(AC,(e,n,r,s,i)=>n||r||s||i||""),Xg=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,u=l.length;c<u;c++){let f=l[c];if(!(typeof f=="boolean"||f===null||f===void 0))if(typeof f=="string")/([\\"'\/])/.test(f)?i+=f.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=f;else if(typeof f=="number")i+=f;else if(f[Qg])i+=f[Qg];else if(f[be].startsWith("@keyframes "))n.push(f),i+=` ${f[be].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(f),f=`.${f[be]}`;else {n.push(...f[ht]),r.push(...f[ia]),f=f[je];let p=f.length;if(p>0){let d=f[p-1];d!==";"&&d!=="}"&&(f+=";");}}i+=`${f||""}`;}}}}return [s,kC(i),n,r]},Cr=(t,e)=>{let[n,r,s,i]=Xg(t,e),o=TC.exec(r);o&&(r=o[1]);let a=(o?Pn:"")+Yg(n+r),l=(o?s.map(c=>c[be]):[a,...i]).join(" ");return {[Nt]:a,[be]:l,[je]:r,[ht]:s,[ia]:i}},oa=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Nt]:"",[be]:"",[je]:"",[ht]:[],[ia]:[r]});}return t},aa=(t,...e)=>{let[n,r]=Xg(t,e);return {[Nt]:"",[be]:`@keyframes ${Yg(n+r)}`,[je]:r,[ht]:[],[ia]:[]}},$C=0,la=((t,e)=>{t||(t=[`/* h-v-t ${$C++} */`]);let n=Array.isArray(t)?Cr(t,e):t,r=n[be],s=Cr(["view-transition-name:",""],[r]);return n[be]=Pn+n[be],n[je]=n[je].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[be]=s[Nt]=r,s[ht]=[...n[ht],n],s});var PC=t=>{let e=[],n=0,r=0;for(let s=0,i=t.length;s<i;s++){let o=t[s];if(o==="'"||o==='"'){let a=o;for(s++;s<i;s++){if(t[s]==="\\"){s++;continue}if(t[s]===a)break}continue}if(o==="{"){r++;continue}if(o==="}"){r--,r===0&&(e.push(t.slice(n,s+1)),n=s+1);continue}}return e},qu=({id:t})=>{let e,n=()=>(e||(e=document.querySelector(`style#${t}`)?.sheet,e&&(e.addedStyles=new Set)),e?[e,e.addedStyles]:[]),r=(o,a)=>{let[l,c]=n();if(!l||!c){Promise.resolve().then(()=>{if(!n()[0])throw new Error("style sheet not found");r(o,a);});return}c.has(o)||(c.add(o),(o.startsWith(Pn)?PC(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(u=>{l.insertRule(u,l.cssRules.length);}));};return [{toString(){let o=this[Nt];return r(o,this[je]),this[ht].forEach(({[be]:a,[je]:l})=>{r(a,l);}),this[be]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[je])}})]};var IC=({id:t})=>{let[e,n]=qu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=p=>{let d=({buffer:g,context:S})=>{let[_,w]=r.get(S),x=Object.keys(_);if(!x.length)return;let E="";if(x.forEach(P=>{w[P]=true,E+=P.startsWith(Pn)?_[P]:`${P[0]==="@"?"":"."}${P}{${_[P]}}`;}),r.set(S,[{},w]),g&&i.test(g[0])){g[0]=g[0].replace(i,(P,D,v)=>`${D}${E}${v}`);return}let R=s.get(S),O=`<script${R?` nonce="${R}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(g){g[0]=`${O}${g[0]}`;return}return Promise.resolve(O)},y=({context:g})=>{r.has(g)||r.set(g,[{},{}]);let[S,_]=r.get(g),w=true;if(_[p[Nt]]||(w=false,S[p[Nt]]=p[je]),p[ht].forEach(({[be]:x,[je]:E})=>{_[x]||(w=false,S[x]=E);}),!w)return Promise.resolve(Y("",[d]))},m=new String(p[be]);Object.assign(m,p),m.isEscaped=true,m.callbacks=[y];let h=Promise.resolve(m);return Object.assign(h,p),h.toString=e.toString,h},a=(p,...d)=>o(Cr(p,d)),l=(...p)=>(p=oa(p),a(Array(p.length).fill(""),...p)),c=aa,u=((p,...d)=>o(la(p,d))),f=({children:p,nonce:d}={})=>Y(`<style id="${t}"${d?` nonce="${d}"`:""}>${p?p[je]:""}</style>`,[({context:y})=>{s.set(y,d);}]);return f[Ge]=n,{css:a,cx:l,keyframes:c,viewTransition:u,Style:f}},fi=IC({id:sa}),Zg=fi.Style;function we(t,e,n){let r;if(!e||!("children"in e))r=ii(t,e,[]);else {let s=e.children;r=Array.isArray(s)?ii(t,e,s):ii(t,e,[s]);}return r.key=n,r}var Hu=new _e().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>ka(ey())).then(s=>s.default);try{let s=Object.values(r).find(i=>i.isEntry);if(!s)throw new Error("No entry found in manifest");e.js=s?.file,e.css=s?.css??[];}catch(s){console.warn("Couldn't find assets in manifest",s);}return t.html(we(dt,{children:we("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[we("head",{children:[we("meta",{charset:"UTF-8"}),we("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),we("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),we("title",{children:"Supalite"}),we(dt,{children:[we("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>we("link",{rel:"stylesheet",href:n+s},i))]}),we(Zg,{})]}),we("body",{children:we("div",{id:"root"})})]})}))});async function jC(t){return Hu.fetch(t)}var LC={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ty=["storage","cloud"],Ku=Object.fromEntries(ty.map(t=>[t,FC(t)]));function FC(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[LC[t]]==="1":false}function Tr(t){return Ku[t]}function MC(t,e){Ku[t]=e;}function ny(){return ty.filter(t=>Ku[t])}function UC(){let t=ny();if(t.length===0)return null;let e=t.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${t.join(", ")} - not supported, do not use in production.${e}`}var Wu=false;function ry(t=e=>console.warn(e)){if(Wu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){Wu=true;return}let e=UC();e&&t(e),Wu=true;}function sy(t,e={}){let n=e.middlewares??[async(l,c)=>{await c();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=up({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),a=async(l,c)=>{await c();let u=l.res.headers;u.has("Access-Control-Allow-Origin")||u.set("Access-Control-Allow-Origin","*"),u.set("Access-Control-Expose-Headers",i.join(", ")),l.req.method==="OPTIONS"&&(u.set("Access-Control-Allow-Methods",r.join(", ")),u.set("Access-Control-Allow-Headers",l.req.header("Access-Control-Request-Headers")??s.join(", ")),u.set("Access-Control-Max-Age","86400"));};return new _e().use("/storage/v1/*",o).use("/rest/v1/*",a).use(async(l,c)=>{l.set("app",t),t.config.auth?.enabled&&l.set("authService",ag(t)),t.config.storage?.enabled&&t._storageAdapter&&Tr("storage")&&l.set("storageService",dg(t)),await c();}).use(...n).use(mu()).route("/auth/v1",hu).route("/rest/v1",Rh({forceRollback:e.forceRollback})).use("/storage/v1/*",async(l,c)=>{if(!Tr("storage"))return l.notFound();await c();}).route("/storage/v1",_u).route("/_system",fp).use(async(l,c)=>{if(!e.disableStudio&&t.config.studio?.enabled)return Hu.fetch(l.req.raw);if(!e.disableFallback)return l.notFound();await c();})}ie();var BC=t=>{let e=t.toJSON();return jt(e)},Ju=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
|
|
124
|
+
`;function xu(t=true){return t?gs(Eu):Eu}var Go=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function hg(t){if(!t._storageAdapter)throw X.storageNotConfigured();let e=t.connection.dialect,n=new Qs(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"secret",s=t._transformationAdapter??new Go;return new Ys(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?nC(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function nC(t){let e=t.match(/^(\d+(?:\.\d+)?)\s*(B|KB|KiB|MB|MiB|GB|GiB)$/i);if(!e)return 0;let n=Number.parseFloat(e[1]),r=e[2].toUpperCase();return Math.floor(n*({B:1,KB:1e3,KIB:1024,MB:1e6,MIB:1048576,GB:1e9,GIB:1073741824}[r]??1))}var Ge=Symbol("RENDERER"),nn=Symbol("ERROR_HANDLER"),ee=Symbol("STASH"),Vo=Symbol("INTERNAL"),Ru=Symbol("MEMO"),wr=Symbol("PERMALINK");var Cu=t=>(t[Vo]=true,t);var Tu=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:Cu(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Cu(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[nn]=i=>{throw t.pop(),i},s},Qo=t=>{let e=[t],n=Tu(e);return n.values=e,n.Provider=n,Pt.push(n),n};var Pt=[],Xs=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new vu("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>Y(i,i.callbacks)):(e.pop(),Y(s))});return n.values=e,n.Provider=n,n[Ge]=Tu(e),Pt.push(n),n},Ce=t=>t.values.at(-1);var Sr={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Zs={},_r="data-precedence";var ni={};Ir(ni,{button:()=>uC,form:()=>lC,input:()=>cC,link:()=>oC,meta:()=>aC,script:()=>sC,style:()=>iC,title:()=>rC});var Pn=t=>Array.isArray(t)?t:[t];var gg=new WeakMap,yg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=gg.get(i)||{};gg.set(i,o);let a=o[t]||=[],l=false,c=Sr[t];if(c.length>0){e:for(let[,u]of a)for(let f of c)if((u?.[f]??null)===n?.[f]){l=true;break e}}if(l?s[0]=s[0].replaceAll(e,""):c.length>0?a.push([e,n,r]):a.unshift([e,n,r]),s[0].indexOf("</head>")!==-1){let u;if(r===void 0)u=a.map(([f])=>f);else {let f=[];u=a.map(([p,,d])=>{let g=f.indexOf(d);return g===-1&&(f.push(d),g=f.length-1),[p,g]}).sort((p,d)=>p[1]-d[1]).map(([p])=>p);}u.forEach(f=>{s[0]=s[0].replaceAll(f,"");}),s[0]=s[0].replace(/(?=<\/head>)/,u.join(""));}},ei=(t,e,n)=>Y(new qe(t,n,Pn(e??[])).toString()),ti=(t,e,n,r)=>{if("itemProp"in n)return ei(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[_r]=s);let a=new qe(t,o,Pn(e||[])).toString();return a instanceof Promise?a.then(l=>Y(a,[...l.callbacks||[],yg(t,l,o,s)])):Y(a,[yg(t,a,o,s)])},rC=({children:t,...e})=>{let n=Yo();if(n){let r=Ce(n);if(r==="svg"||r==="head")return new qe("title",e,Pn(t??[]))}return ti("title",t,e,false)},sC=({children:t,...e})=>{let n=Yo();return ["src","async"].some(r=>!e[r])||n&&Ce(n)==="head"?ei("script",t,e):ti("script",t,e,false)},iC=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,ti("style",t,e,true)):ei("style",t,e),oC=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?ei("link",t,e):ti("link",t,e,"precedence"in e),aC=({children:t,...e})=>{let n=Yo();return n&&Ce(n)==="head"?ei("meta",t,e):ti("meta",t,e,false)},bg=(t,{children:e,...n})=>new qe(t,n,Pn(e??[])),lC=t=>(typeof t.action=="function"&&(t.action=wr in t.action?t.action[wr]:void 0),bg("form",t)),wg=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=wr in e.formAction?e.formAction[wr]:void 0),bg(t,e)),cC=t=>wg("input",t),uC=t=>wg("button",t);var fC=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),Er=t=>fC.get(t)||t,ri=(t,e)=>{for(let[n,r]of Object.entries(t)){let s=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e(s,r==null?null:typeof r=="number"?s.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r);}};var si=void 0,Yo=()=>si,pC=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,dC=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],mC=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],ku=(t,e)=>{for(let n=0,r=t.length;n<r;n++){let s=t[n];if(typeof s=="string")_t(s,e);else {if(typeof s=="boolean"||s===null||s===void 0)continue;s instanceof qe?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):ku(s,e);}}},qe=class{tag;props;key;children;isEscaped=true;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n;}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){let t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n);});try{this.toStringToBuffer(t);}finally{this.localContexts?.forEach(([e])=>{e.values.pop();});}return t.length===1?"callbacks"in t?Va(Y(t[0],t.callbacks)).toString():t[0]:ji(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=si&&Ce(si)==="svg"?i=>pC(Er(i)):i=>Er(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";ri(o,(l,c)=>{c!=null&&(a+=`${a?";":""}${l}:${c}`);}),t[0]+=' style="',_t(a,t),t[0]+='"';}else if(typeof o=="string")t[0]+=` ${i}="`,_t(o,t),t[0]+='"';else if(o!=null)if(typeof o=="number"||o.isEscaped)t[0]+=` ${i}="${o}"`;else if(typeof o=="boolean"&&mC.includes(i))o&&(t[0]+=` ${i}=""`);else if(i==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Y(o.__html)];}else if(o instanceof Promise)t[0]+=` ${i}="`,t.unshift('"',o);else if(typeof o=="function"){if(!i.startsWith("on")&&i!=="ref")throw new Error(`Invalid prop '${i}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${i}="`,_t(o.toString(),t),t[0]+='"';}if(dC.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",ku(r,t),t[0]+=`</${e}>`;}},Au=class extends qe{toStringToBuffer(t){let{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);let r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Pt.length===0)t.unshift("",r);else {let s=Pt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof qe&&(i.localContexts=s),i)));}else r instanceof qe?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):_t(r,t);}},vu=class extends qe{toStringToBuffer(t){ku(this.children,t);}},Sg=false,ii=(t,e,n)=>{if(!Sg){for(let r in Zs)ni[r][Ge]=Zs[r];Sg=true;}return typeof t=="function"?new Au(t,e,n):ni[t]?new Au(ni[t],e,n):t==="svg"||t==="head"?(si||=Xs(""),new qe(t,e,[new Au(si,{value:t},n)])):new qe(t,e,n)};var dt=({children:t})=>new vu("",{children:t},Array.isArray(t)?t:t?[t]:[]);var ta={};Ir(ta,{button:()=>zg,clearCache:()=>TC,composeRef:()=>ea,form:()=>Wg,input:()=>Jg,link:()=>Bg,meta:()=>qg,script:()=>Mg,style:()=>Ug,title:()=>Fg});var ai="_hp",hC={Change:"Input",DoubleClick:"DblClick"},gC={svg:"2000/svg",math:"1998/Math/MathML"},mt=[],Pu=new WeakMap,xr=void 0,vg=()=>xr,Nt=t=>"t"in t,Ou={onClick:["click",false]},_g=t=>{if(!t.startsWith("on"))return;if(Ou[t])return Ou[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return Ou[t]=[(hC[n]||n).toLowerCase(),!!r]}},Eg=(t,e)=>xr&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,yC=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=Er(r);let i=_g(r);if(i){if(n?.[r]!==s&&(n&&t.removeEventListener(i[0],n[r],i[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(i[0],s,i[1]);}}else if(r==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(r==="ref"){let o;typeof s=="function"?o=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,o=()=>s.current=null),Pu.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&ri(s,o.setProperty.bind(o)));}else {if(r==="value"){let a=t.nodeName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"){if(t.value=s==null||s===false?null:s,a==="TEXTAREA"){t.textContent=s;continue}else if(a==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else (r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=s);let o=Eg(t,r);s==null||s===false?t.removeAttribute(o):s===true?t.setAttribute(o,""):typeof s=="string"||typeof s=="number"?t.setAttribute(o,s):t.setAttribute(o,s.toString());}}}if(n)for(let r in n){let s=n[r];if(r!=="children"&&!(r in e)){r=Er(r);let i=_g(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?Pu.get(t)?.():t.removeAttribute(Eg(t,r));}}},bC=(t,e)=>{e[ee][0]=0,mt.push([t,e]);let n=e.tag[Ge]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{mt.pop();}},Ag=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ee][1][Iu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Nt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(Ag(i,e,n,r,s),i.s){for(let a=o;a<n.length;a++)n[a].s=true;i.s=false;}}else n.push(i),i.vR?.length&&(r.push(...i.vR),delete i.vR);});},wC=t=>{for(;t&&(t.tag===ai||!t.e);)t=t.tag===ai||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},kg=t=>{Nt(t)||(t[ee]?.[1][Iu]?.forEach(e=>e[2]?.()),Pu.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(kg)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(oi.delete(t),Xo.delete(t),delete t[ee][3],t.a=true);},$g=(t,e,n)=>{t.c=e,Og(t,e,n);},xg=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Rg=Symbol(),Og=(t,e,n)=>{let r=[],s=[],i=[];Ag(t,e,r,s,i),s.forEach(kg);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=xg(o,wC(t.nN));c!==void 0?(l=o[c],a=c):a=xg(o,r.find(u=>u.tag!==ai&&u.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,u=r.length;c<u;c++,a++){let f=r[c],p;if(f.s&&f.e)p=f.e,f.s=false;else {let d=n||!f.e;Nt(f)?(f.e&&f.d&&(f.e.textContent=f.t),f.d=false,p=f.e||=document.createTextNode(f.t)):(p=f.e||=f.n?document.createElementNS(f.n,f.tag):document.createElement(f.tag),yC(p,f.props,f.pP),Og(f,p,d));}f.tag===ai?a--:n?p.parentNode||e.appendChild(p):o[a]!==p&&o[a-1]!==p&&(o[a+1]===p?e.appendChild(o[a]):e.insertBefore(p,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],u=[];i.forEach(([,f,,p,d])=>{f&&c.push(f),p&&u.push(p),d?.();}),c.forEach(f=>f()),u.length&&requestAnimationFrame(()=>{u.forEach(f=>f());});}},SC=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Xo=new WeakMap,Nu=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?bC(t,e):Pn(e.props.children),n[0]?.tag===""&&n[0][nn]&&(s=n[0][nn],t[5].push([t,s,e]));let i=r?[...e.pC]:e.vC?[...e.vC]:void 0,o=[],a;for(let l=0;l<n.length;l++){if(Array.isArray(n[l])){n.splice(l,1,...n[l].flat(1/0)),l--;continue}let c=_C(n[l]);if(c){typeof c.tag=="function"&&!c.tag[Vo]&&(Pt.length>0&&(c[ee][2]=Pt.map(f=>[f,f.values.at(-1)])),t[5]?.length&&(c[ee][3]=t[5].at(-1)));let u;if(i&&i.length){let f=i.findIndex(Nt(c)?p=>Nt(p):c.key!==void 0?p=>p.key===c.key&&p.tag===c.tag:p=>p.tag===c.tag);f!==-1&&(u=i[f],i.splice(f,1));}if(u)if(Nt(c))u.t!==c.t&&(u.t=c.t,u.d=!0),c=u;else {let f=u.pP=u.props;if(u.props=c.props,u.f||=c.f||e.f,typeof c.tag=="function"){let p=u[ee][2];u[ee][2]=c[ee][2]||[],u[ee][3]=c[ee][3],!u.f&&((u.o||u)===c.o||u.tag[Ru]?.(f,u.props))&&SC(p,u[ee][2])&&(u.s=!0);}c=u;}else if(!Nt(c)&&xr){let f=Ce(xr);f&&(c.n=f);}if(!Nt(c)&&!c.s&&(Nu(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let f=a;f&&!Nt(f);f=f.vC?.at(-1))f.nN=c;a=c;}}e.vR=r?[...e.vC,...i||[]]:i||[],e.vC=o,r&&delete e.pC;}catch(i){if(e.f=true,i===Rg){if(s)return;throw i}let[o,a,l]=e[ee]?.[3]||[];if(a){let c=()=>li([0,false,t[2]],l),u=Xo.get(l)||[];u.push(c),Xo.set(l,u);let f=a(i,()=>{let p=Xo.get(l);if(p){let d=p.indexOf(c);if(d!==-1)return p.splice(d,1),c()}});if(f){if(t[0]===1)t[1]=true;else if(Nu(t,l,[f]),(a.length===1||t!==o)&&l.c){$g(l,l.c,false);return}throw Rg}}throw i}finally{s&&t[5].pop();}},_C=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return {t:t.toString(),d:true};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ee]=[0,[]];else {let e=gC[t.tag];e&&(xr||=Qo(""),t.props.children=[{tag:xr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var Cg=(t,e)=>{e[ee][2]?.forEach(([n,r])=>{n.values.push(r);});try{Nu(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[ee][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&$g(e,e.c,false);},oi=new WeakMap,Tg=[],li=async(t,e)=>{t[5]||=[];let n=oi.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(oi.set(e,[r,()=>{t[2]?t[2](t,e,i=>{Cg(i,e);}).then(()=>r(e)):(Cg(t,e),r(e));}]),Tg.length)Tg.at(-1).add(e);else {await Promise.resolve();let i=oi.get(e);i&&(oi.delete(e),i[1]());}return s};var Pg=(t,e,n)=>({tag:ai,props:{children:t},key:n,e,p:1});var EC=0,Iu=1,xC=2,RC=3;var Du=new WeakMap,Ig=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var CC=void 0;var Ng=[];var Zo=t=>{let e=()=>typeof t=="function"?t():t,n=mt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[ee][1][EC]||=[],i=r[ee][0]++;return s[i]||=[e(),o=>{let a=CC,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,Ng.length){let[c,u]=Ng.at(-1);Promise.all([c===3?r:li([c,false,a],r),u]).then(([f])=>{if(!f||!(c===2||c===3))return;let p=f.vC;requestAnimationFrame(()=>{setTimeout(()=>{p===f.vC&&li([c===3?1:0,false,a],f);});});});}else li([0,false,a],r);}]};var Rr=(t,e)=>{let n=mt.at(-1);if(!n)return t;let[,r]=n,s=r[ee][1][xC]||=[],i=r[ee][0]++,o=s[i];return Ig(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var ju=t=>{let e=Du.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>Du.set(t,[n]),n=>Du.set(t,[void 0,n])),t},Lu=(t,e)=>{let n=mt.at(-1);if(!n)return t();let[,r]=n,s=r[ee][1][RC]||=[],i=r[ee][0]++,o=s[i];return Ig(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var jg=Qo({pending:false,data:null,method:null,action:null}),Dg=new Set,Lg=t=>{Dg.add(t),t.finally(()=>Dg.delete(t));};var TC=()=>{Fu=Object.create(null),Mu=Object.create(null);},ea=(t,e)=>Lu(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null);}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null;}));let s=e(n);return ()=>{s?.(),r?.();}},[t]),Fu=Object.create(null),Mu=Object.create(null),ci=(t,e,n,r,s)=>{if(e?.itemProp)return {tag:t,props:e,type:t,ref:e.ref};let i=document.head,{onLoad:o,onError:a,precedence:l,blocking:c,...u}=e,f=null,p=false,d=Sr[t],g;if(d.length>0){let S=i.querySelectorAll(t);e:for(let _ of S)for(let w of Sr[t])if(_.getAttribute(w)===e[w]){f=_;break e}if(!f){let _=d.reduce((w,x)=>e[x]===void 0?w:`${w}-${x}-${e[x]}`,t);p=!Mu[_],f=Mu[_]||=(()=>{let w=document.createElement(t);for(let x of d)e[x]!==void 0&&w.setAttribute(x,e[x]),e.rel&&w.setAttribute("rel",e.rel);return w})();}}else g=i.querySelectorAll(t);l=r?l??"":void 0,r&&(u[_r]=l);let m=Rr(S=>{if(d.length>0){let _=false;for(let w of i.querySelectorAll(t)){if(_&&w.getAttribute(_r)!==l){i.insertBefore(S,w);return}w.getAttribute(_r)===l&&(_=true);}i.appendChild(S);}else if(g){let _=false;for(let w of g)if(w===S){_=true;break}_||i.insertBefore(S,i.contains(g[0])?g[0]:i.querySelector(t)),g=void 0;}},[l]),h=ea(e.ref,S=>{let _=d[0];if(n===2&&(S.innerHTML=""),(p||g)&&m(S),!a&&!o)return;let w=Fu[S.getAttribute(_)]||=new Promise((x,E)=>{S.addEventListener("load",x),S.addEventListener("error",E);});o&&(w=w.then(o)),a&&(w=w.catch(a)),w.catch(()=>{});});if(s&&c==="render"){let S=Sr[t][0];if(e[S]){let _=e[S],w=Fu[_]||=new Promise((x,E)=>{m(f),f.addEventListener("load",x),f.addEventListener("error",E);});ju(w);}}let y={tag:t,type:t,props:{...u,ref:h},ref:h};return y.p=n,f&&(y.e=f),Pg(y,i)},Fg=t=>{let e=vg();return (e&&Ce(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:ci("title",t,void 0,false,false)},Mg=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:ci("script",t,1,false,true),Ug=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,ci("style",t,2,true,true)),Bg=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:ci("link",t,1,"precedence"in t,true),qg=t=>ci("meta",t,void 0,false,false),Hg=Symbol(),Wg=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Zo([null,false]),i=Rr(async c=>{let u=c.isTrusted?e:c.detail[Hg];if(typeof u!="function")return;c.preventDefault();let f=new FormData(c.target);s([f,true]);let p=u(f);p instanceof Promise&&(Lg(p),await p),s([null,true]);},[]),o=ea(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:jg,props:{value:{pending:a!==null,data:a,method:a?"post":null,action:a?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},Kg=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=Rr(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Hg]:e}}));},[]);n.ref=ea(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Jg=t=>Kg("input",t),zg=t=>Kg("button",t);Object.assign(Zs,{title:Fg,script:Mg,style:Ug,link:Bg,meta:qg,form:Wg,input:Jg,button:zg});Xs(null);new TextEncoder;var Nn=":-hono-global",$C=new RegExp(`^${Nn}{(.*)}$`),sa="hono-css",It=Symbol(),be=Symbol(),je=Symbol(),ht=Symbol(),ia=Symbol(),Xg=Symbol();var Zg=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},OC=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),PC=new RegExp(["("+OC+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),NC=t=>t.replace(PC,(e,n,r,s,i)=>n||r||s||i||""),ey=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,u=l.length;c<u;c++){let f=l[c];if(!(typeof f=="boolean"||f===null||f===void 0))if(typeof f=="string")/([\\"'\/])/.test(f)?i+=f.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=f;else if(typeof f=="number")i+=f;else if(f[Xg])i+=f[Xg];else if(f[be].startsWith("@keyframes "))n.push(f),i+=` ${f[be].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(f),f=`.${f[be]}`;else {n.push(...f[ht]),r.push(...f[ia]),f=f[je];let p=f.length;if(p>0){let d=f[p-1];d!==";"&&d!=="}"&&(f+=";");}}i+=`${f||""}`;}}}}return [s,NC(i),n,r]},Cr=(t,e)=>{let[n,r,s,i]=ey(t,e),o=$C.exec(r);o&&(r=o[1]);let a=(o?Nn:"")+Zg(n+r),l=(o?s.map(c=>c[be]):[a,...i]).join(" ");return {[It]:a,[be]:l,[je]:r,[ht]:s,[ia]:i}},oa=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[It]:"",[be]:"",[je]:"",[ht]:[],[ia]:[r]});}return t},aa=(t,...e)=>{let[n,r]=ey(t,e);return {[It]:"",[be]:`@keyframes ${Zg(n+r)}`,[je]:r,[ht]:[],[ia]:[]}},IC=0,la=((t,e)=>{t||(t=[`/* h-v-t ${IC++} */`]);let n=Array.isArray(t)?Cr(t,e):t,r=n[be],s=Cr(["view-transition-name:",""],[r]);return n[be]=Nn+n[be],n[je]=n[je].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[be]=s[It]=r,s[ht]=[...n[ht],n],s});var jC=t=>{let e=[],n=0,r=0;for(let s=0,i=t.length;s<i;s++){let o=t[s];if(o==="'"||o==='"'){let a=o;for(s++;s<i;s++){if(t[s]==="\\"){s++;continue}if(t[s]===a)break}continue}if(o==="{"){r++;continue}if(o==="}"){r--,r===0&&(e.push(t.slice(n,s+1)),n=s+1);continue}}return e},qu=({id:t})=>{let e,n=()=>(e||(e=document.querySelector(`style#${t}`)?.sheet,e&&(e.addedStyles=new Set)),e?[e,e.addedStyles]:[]),r=(o,a)=>{let[l,c]=n();if(!l||!c){Promise.resolve().then(()=>{if(!n()[0])throw new Error("style sheet not found");r(o,a);});return}c.has(o)||(c.add(o),(o.startsWith(Nn)?jC(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(u=>{l.insertRule(u,l.cssRules.length);}));};return [{toString(){let o=this[It];return r(o,this[je]),this[ht].forEach(({[be]:a,[je]:l})=>{r(a,l);}),this[be]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[je])}})]};var FC=({id:t})=>{let[e,n]=qu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=p=>{let d=({buffer:y,context:S})=>{let[_,w]=r.get(S),x=Object.keys(_);if(!x.length)return;let E="";if(x.forEach(P=>{w[P]=true,E+=P.startsWith(Nn)?_[P]:`${P[0]==="@"?"":"."}${P}{${_[P]}}`;}),r.set(S,[{},w]),y&&i.test(y[0])){y[0]=y[0].replace(i,(P,D,v)=>`${D}${E}${v}`);return}let R=s.get(S),O=`<script${R?` nonce="${R}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(y){y[0]=`${O}${y[0]}`;return}return Promise.resolve(O)},g=({context:y})=>{r.has(y)||r.set(y,[{},{}]);let[S,_]=r.get(y),w=true;if(_[p[It]]||(w=false,S[p[It]]=p[je]),p[ht].forEach(({[be]:x,[je]:E})=>{_[x]||(w=false,S[x]=E);}),!w)return Promise.resolve(Y("",[d]))},m=new String(p[be]);Object.assign(m,p),m.isEscaped=true,m.callbacks=[g];let h=Promise.resolve(m);return Object.assign(h,p),h.toString=e.toString,h},a=(p,...d)=>o(Cr(p,d)),l=(...p)=>(p=oa(p),a(Array(p.length).fill(""),...p)),c=aa,u=((p,...d)=>o(la(p,d))),f=({children:p,nonce:d}={})=>Y(`<style id="${t}"${d?` nonce="${d}"`:""}>${p?p[je]:""}</style>`,[({context:g})=>{s.set(g,d);}]);return f[Ge]=n,{css:a,cx:l,keyframes:c,viewTransition:u,Style:f}},fi=FC({id:sa}),ty=fi.Style;function we(t,e,n){let r;if(!e||!("children"in e))r=ii(t,e,[]);else {let s=e.children;r=Array.isArray(s)?ii(t,e,s):ii(t,e,[s]);}return r.key=n,r}var Hu=new _e().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>ka(ny())).then(s=>s.default);try{let s=Object.values(r).find(i=>i.isEntry);if(!s)throw new Error("No entry found in manifest");e.js=s?.file,e.css=s?.css??[];}catch(s){console.warn("Couldn't find assets in manifest",s);}return t.html(we(dt,{children:we("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[we("head",{children:[we("meta",{charset:"UTF-8"}),we("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),we("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),we("title",{children:"Supalite"}),we(dt,{children:[we("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>we("link",{rel:"stylesheet",href:n+s},i))]}),we(ty,{})]}),we("body",{children:we("div",{id:"root"})})]})}))});async function UC(t){return Hu.fetch(t)}var BC={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ry=["storage","cloud"],Ku=Object.fromEntries(ry.map(t=>[t,qC(t)]));function qC(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[BC[t]]==="1":false}function Tr(t){return Ku[t]}function HC(t,e){Ku[t]=e;}function sy(){return ry.filter(t=>Ku[t])}function WC(){let t=sy();if(t.length===0)return null;let e=t.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${t.join(", ")} - not supported, do not use in production.${e}`}var Wu=false;function iy(t=e=>console.warn(e)){if(Wu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){Wu=true;return}let e=WC();e&&t(e),Wu=true;}function oy(t,e={}){let n=e.middlewares??[async(l,c)=>{await c();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=pp({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),a=async(l,c)=>{await c();let u=l.res.headers;u.has("Access-Control-Allow-Origin")||u.set("Access-Control-Allow-Origin","*"),u.set("Access-Control-Expose-Headers",i.join(", ")),l.req.method==="OPTIONS"&&(u.set("Access-Control-Allow-Methods",r.join(", ")),u.set("Access-Control-Allow-Headers",l.req.header("Access-Control-Request-Headers")??s.join(", ")),u.set("Access-Control-Max-Age","86400"));};return new _e().use("/storage/v1/*",o).use("/rest/v1/*",a).use(async(l,c)=>{l.set("app",t),t.config.auth?.enabled&&l.set("authService",cg(t)),t.config.storage?.enabled&&t._storageAdapter&&Tr("storage")&&l.set("storageService",hg(t)),await c();}).use(...n).use(mu()).route("/auth/v1",hu).route("/rest/v1",Th({forceRollback:e.forceRollback})).use("/storage/v1/*",async(l,c)=>{if(!Tr("storage"))return l.notFound();await c();}).route("/storage/v1",_u).route("/_system",dp).use(async(l,c)=>{if(!e.disableStudio&&t.config.studio?.enabled)return Hu.fetch(l.req.raw);if(!e.disableFallback)return l.notFound();await c();})}ie();var KC=t=>{let e=t.toJSON();return Lt(e)},Ju=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
|
|
125
125
|
|
|
126
126
|
Error: ${JSON.stringify(s[0],null,2)}
|
|
127
127
|
|
|
128
|
-
Schema: ${JSON.stringify(n.toJSON(),null,2)}`);this.schema=n;this.value=r;this.errors=s;}name="InvalidSchemaError";first(){return this.errors[0]}firstToString(){let n=this.first();return `${n.error} at ${n.instanceLocation}`}};function
|
|
128
|
+
Schema: ${JSON.stringify(n.toJSON(),null,2)}`);this.schema=n;this.value=r;this.errors=s;}name="InvalidSchemaError";first(){return this.errors[0]}firstToString(){let n=this.first();return `${n.error} at ${n.instanceLocation}`}};function ay(t,e,n){let r=n?.clone?KC(t):t,s=n?.coerce!==false?r.coerce(e,{dropUnknown:n?.coerceDropUnknown??false}):e;n?.withDefaults!==false&&(s=r.template(s,{withOptional:true,withExtendedOptional:n?.withExtendedDefaults??false}));let i=t.validate(s,{shortCircuit:true,ignoreUnsupported:true});if(!i.valid)if(n?.onError)n.onError(i.errors);else throw new Ju(r,e,i.errors);return s}ys();var zu=`-- supabase/auth core schema (Postgres)
|
|
129
129
|
-- Scope: Core Authentication + User Management
|
|
130
130
|
-- Source: GoTrue migrations + runtime analysis
|
|
131
131
|
|
|
@@ -302,9 +302,9 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
|
|
|
302
302
|
created_at timestamptz DEFAULT now(),
|
|
303
303
|
ip_address varchar(64) DEFAULT ''
|
|
304
304
|
);
|
|
305
|
-
`;function Gu(t=true){return t?gs(zu):zu}var Vu=class{_connection;_rls;config;server;drivers;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.drivers=
|
|
305
|
+
`;function Gu(t=true){return t?gs(zu):zu}var Vu=class{_connection;_rls;config;server;drivers;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.drivers=Nh(n.drivers),this.config=ay(Oi,s,{withDefaults:n.defaults??true}),this.server=oy(this,n.server);}get connection(){if(this._connection instanceof Promise)throw new Error("Connection is not available yet");return this._connection}async init(){if(this.#e)return this;iy(),this.config.auth?.enabled&&Jo(this.config.auth),await this._connection;let e=this.connection;if(e.config.schemaCache??=this.drivers.cache,e.config.baseSchema=[e.config.baseSchema??"",this.config.auth?.enabled&&Gu(),this.config.storage?.enabled&&this._storageAdapter&&Tr("storage")&&xu()].filter(Boolean).join(`
|
|
306
306
|
|
|
307
|
-
`),this._rls){let n=e;if(typeof n.updateDeparseInfo=="function"){let r=n.config.translation?.deparse;n.updateDeparseInfo({enums:r?.enums??new Map,schema:r?.schema??new Map,vars:r?.vars??new Map,...r,rls:{tables:new Set(this._rls.tables),policies:this._rls.policies}});}}return this.#e=true,this}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return Oi.validate(s).valid}return Oi.validate(e).valid}getClient(e){return createClient("http://localhost","<nokey>",{...e,global:{...e?.global,fetch:async(n,r)=>{let s=new Request(n,r);return Object.assign(s,{[Ms]:true}),await this.fetch(s)}}})}isLocalRequest(e){return Ms in e}fetch=async e=>(await this.init(),this.server.fetch(e));getInfoJson(){return JSON.parse(jsonStringify({connection:this.connection?.config??{},config:this.config}))}};var
|
|
307
|
+
`),this._rls){let n=e;if(typeof n.updateDeparseInfo=="function"){let r=n.config.translation?.deparse;n.updateDeparseInfo({enums:r?.enums??new Map,schema:r?.schema??new Map,vars:r?.vars??new Map,...r,rls:{tables:new Set(this._rls.tables),policies:this._rls.policies}});}}return this.#e=true,this}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return Oi.validate(s).valid}return Oi.validate(e).valid}getClient(e){return createClient("http://localhost","<nokey>",{...e,global:{...e?.global,fetch:async(n,r)=>{let s=new Request(n,r);return Object.assign(s,{[Ms]:true}),await this.fetch(s)}}})}isLocalRequest(e){return Ms in e}fetch=async e=>(await this.init(),this.server.fetch(e));getInfoJson(){return JSON.parse(jsonStringify({connection:this.connection?.config??{},config:this.config}))}};var ly=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},cy=class extends Error{constructor(n,r,s){super(`Failed to translate Postgres to SQLite DDL: ${String(s)}`);this.pgSql=n;this.sqliteDdl=r;this.cause=s;}name="InvalidPostgresToSQLiteTranslation"};ca();bs();var VC=(t={})=>{let e=(n="m")=>[...t.exclude_tables??[],"sqlite_%"].map(r=>r.includes("%")?`${n}.name NOT LIKE '${r}'`:`${n}.name != '${r}'`).join(" AND ");return `WITH table_info AS (SELECT
|
|
308
308
|
json_group_array(
|
|
309
309
|
json_object(
|
|
310
310
|
'name', m.name,
|
|
@@ -505,13 +505,13 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
|
|
|
505
505
|
(SELECT data FROM trigger_info) AS triggers,
|
|
506
506
|
(SELECT data FROM unique_info) AS unique_constraints,
|
|
507
507
|
${t.name?`'${t.name}'`:"'sqlite'"} AS database_name,
|
|
508
|
-
${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function nn(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function uy(t,e={}){let r=(await t.exec(KC(e)))?.rows?.[0]||{};return {tables:nn(r.tables),columns:nn(r.columns),indexes:nn(r.indexes),foreign_keys:nn(r.foreign_keys),primary_keys:nn(r.primary_keys),views:nn(r.views),triggers:nn(r.triggers),check_constraints:[],unique_constraints:nn(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function JC(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function fy(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function Yu(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function zC(t){let e=new Map;for(let r of t){if(!fy(r.foreign_key_name))continue;let s=e.get(Yu(r));s?s.push(r):e.set(Yu(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get(Yu(r));return s?{...r,foreign_key_name:s}:r})}function py(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!fy(r.foreign_key_name))return r;let s=e.get(r.table),i=JC(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:zC(n)}}function Xu(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function GC(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function VC(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(Xu);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?Xu(r):i}}function dy(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function QC(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!dy(t[s-1])&&!dy(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function YC(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function my(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function XC(t,e){if(!t)return null;let n=QC(t);if(!n)return null;let r=YC(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(Xu).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of GC(n.selectList)){let u=c.trim();if(u==="*"||u.endsWith(".*")){for(let p of l)my(a,p,p);continue}let f=VC(c);f&&my(a,f.baseColumn,f.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function ZC(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function eT(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(u=>u.name===l.name&&u.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=XC(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let u=new Map;for(let[p,d]of l.columns){let y=d.filter(m=>c.has(m));y.length>0&&u.set(p,y);}if(u.size===0)continue;let f={name:a.name,schema:a.schema,columnByBaseColumn:u,fromRelation:l.baseTable};s.set(a.name,f);}let i=16;function o(a,l,c){if(l>i)return null;let u=a.fromRelation;if(e.has(u))return {physicalBase:u,columnByBaseColumn:a.columnByBaseColumn};let f=s.get(u);if(!f||c.has(u))return null;c.add(u);let p=o(f,l+1,c);if(c.delete(u),!p)return null;let d=ZC(a.columnByBaseColumn,p.columnByBaseColumn);return d.size===0?null:{physicalBase:p.physicalBase,columnByBaseColumn:d}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function hy(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function tT(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function nT(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function rT(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function gy(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=eT(t),n=new Set(t.foreign_keys.map(hy)),r=[];for(let s of tT(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let u=[];for(let f of s){let p=l.columnByBaseColumn.get(f.column)??[],d=c.columnByBaseColumn.get(f.ref_column)??[],y=p.flatMap(m=>d.map(h=>({fk:f,childColumn:m,parentColumn:h})));if(y.length===0){u.length=0;break}u.push(y);}for(let f of nT(u)){let d=l.name===i.table&&c.name===i.ref_table&&f.every(y=>y.childColumn===y.fk.column&&y.parentColumn===y.fk.ref_column)?void 0:rT(l,c,i.foreign_key_name,f);for(let y of f){let m={...y.fk,table:l.name,column:y.childColumn,schema:l.schema,ref_table:c.name,ref_column:y.parentColumn,ref_schema:c.schema,foreign_key_group:d},h=hy(m);n.has(h)||(n.add(h),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var uT=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Zu=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#e=new Set;#t=new Set;transformNodeImpl(n,r){if(!uT.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#t.add(o);let i=this.#n(n);for(let o of i)this.#e.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#e.delete(o);for(let o of s)this.#t.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#t.has(s)&&this.#e.has(s),a=i??(o?this.config.defaultSchema:void 0);if(!a)return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:s}};let l=this.config.approach==="snake_case"?"__":".";return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:`${a}${l}${s}`}}}#n(n){let r=new Set;if(n?.name&&SchemableIdentifierNode.is(n.name)&&this.#r(n.name,r),n?.from?.froms)for(let s of n.from.froms)this.#i(s,r);if(n?.into&&this.#i(n.into,r),n?.table&&this.#i(n.table,r),n?.joins)for(let s of n.joins)this.#i(s.table,r);return n?.using&&(JoinNode.is(n.using)?this.#i(n.using.table,r):this.#i(n.using,r)),r}#i(n,r){if(TableNode.is(n)){this.#r(n.table,r);return}if(AliasNode.is(n)&&TableNode.is(n.node)){this.#r(n.node.table,r);return}if(ListNode.is(n)){for(let s of n.items)this.#i(s,r);return}if(UsingNode.is(n))for(let s of n.tables)this.#i(s,r);}#r(n,r){let s=n.identifier.name;this.#t.has(s)||r.add(s);}#s(n){let r=new Set;if(n?.with?.expressions)for(let s of n.with.expressions){let i=s?.name?.table?.table?.identifier?.name;i&&r.add(i);}return r}},ua=class{#e;constructor(e){this.#e=new Zu(e);}transformQuery(e){return this.#e.transformNode(e.node)}async transformResult(e){return e.result}};fa();ef();tf();function mT(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function by(t,e){let n=r=>mT(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}var da=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new vr,this.planner=new Ar;}differ;planner;translationResult;async getDesiredSchema(){let e=await this.conn.translateDdl(this.desiredSchema);return this.translationResult=e,await this.options.onTranslation?.(e),e.ddl}async diff(){let e=await this.conn.introspect({postprocess:false}),n=await this.getDesiredSchema();if(!n||n.trim().length===0)return {current:e,desired:e,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:r}=await import('@supabase/lite/sqlite'),s=await r({url:":memory:"});try{await s.exec(n);let i=await s.introspect({postprocess:!1}),o=this.conn.config.ddlDialect,a=by(e,o),l=by(i,o),c=this.differ.diff(a,l),u=this.planner.plan(c,a,l);return {current:e,desired:i,diff:c,plan:u}}finally{await s.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff();return await this.migratePlan(n.plan,e),n}};hs();var Sy=/^\{\{(.+)\}\}$/;function _y(t){return typeof t=="string"&&Sy.test(t)}function hT(t){return Sy.exec(t)[1]}var wy=Symbol("unresolved");function Ey(t,e){let n=hT(t),r=Gt(e,n,wy);if(r===wy)throw new Error(`Unresolved variable: {{${n}}}`);return r}function It(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>It(i,e));continue}if(r==="$not"){n[r]=It(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?It(i.where,e):i?.where};continue}if(_y(r)){let i=Ey(r,e),a=yT(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=xy(s,e);continue}n[r]=s;}return n}function xy(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=xy(s,e):gT(s)?n[r]={...s,where:s?.where?It(s?.where,e):void 0}:_y(s)?n[r]=Ey(s,e):n[r]=s;return n}function gT(t){return t!=null&&typeof t=="object"&&t.type==="query"}function yT(t,e){for(let[n,r]of Object.entries(e))switch(n){case "$eq":if(t!==r)return false;break;case "$neq":if(t===r)return false;break;case "$in":if(!Array.isArray(r)||!r.includes(t))return false;break;case "$notIn":if(Array.isArray(r)&&r.includes(t))return false;break;default:throw new Error(`Cannot statically evaluate operator ${n} on placeholder key`)}return true}hs();var ha=class{constructor(e,n,r){this.tables=e;this.policies=n;this.defaultSchema=r;}enforce(e,n){let r=e.from;if(!r||!this.isRlsEnabled(r,e.schema))return e;let s=bT(e.type);if(!s)return e;let i=Gt(n,"auth.role")??"anon",{permissive:o,restrictive:a}=this.resolvePolicies(r,e.schema,s,i);switch(s){case "SELECT":case "DELETE":{let l=this.combineUsing(o,a,n);return {...e,where:Ry(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Ry(e.where,l)};if(l.$always===false)return c;let u=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(u).length>0){let f=new Set(Object.keys(e.values));this.validateWithCheck(u,e.values,o,a,f);}return c}case "INSERT":{let l=this.combineWithCheck(o,a,n,s);if(e.values){let c=Array.isArray(e.values)?e.values:[e.values];for(let u of c)this.validateWithCheck(l,u,o,a);}return e}default:return e}}isRlsEnabled(e,n){return this.tables.has(e)}resolvePolicies(e,n,r,s){let i=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,n)&&o.appliesTo(r)&&o.appliesToRole(s));return {permissive:i.filter(o=>o.data.permissive),restrictive:i.filter(o=>!o.data.permissive)}}schemasMatch(e,n){let r=e||this.defaultSchema,s=n||this.defaultSchema;return r===s}combineUsing(e,n,r){if(e.length===0)return {$always:false};let s=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>It(o,r)),i;s.length===0?i={}:s.length===1?i=s[0]:i={$or:s};for(let o of n)if(o.data.using&&Object.keys(o.data.using).length>0){let a=It(o.data.using,r);i=Object.keys(i).length===0?a:{$and:[i,a]};}return i}combineWithCheck(e,n,r,s){if(e.length===0)return {$always:false};let i=e.map(a=>a.data.withCheck??(s==="UPDATE"?a.data.using:void 0)).filter(a=>a!=null&&Object.keys(a).length>0).map(a=>It(a,r)),o;i.length===0?o={}:i.length===1?o=i[0]:o={$or:i};for(let a of n){let l=a.data.withCheck??(s==="UPDATE"?a.data.using:void 0);if(l&&Object.keys(l).length>0){let c=It(l,r);o=Object.keys(o).length===0?c:{$and:[o,c]};}}return o}validateWithCheck(e,n,r,s,i){if(Object.keys(e).length===0)return;if(!ma(e,n,i)){let a=r[0]??s[0];throw a?new ur(a):new Error("RLS policy violation")}}};function bT(t){switch(t){case "query":return "SELECT";case "insert":case "upsert":case "put":return "INSERT";case "update":return "UPDATE";case "delete":return "DELETE";default:return}}function Ry(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function ma(t,e,n){for(let[r,s]of Object.entries(t)){if(r==="$always"){if(s===false)return false;continue}if(r==="$and"){if(!s.every(l=>ma(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>ma(l,e,n)))return false;continue}if(r==="$not"){if(ma(s,e,n))return false;continue}if(n&&!n.has(r))continue;let i=s,o=e[r];for(let[a,l]of Object.entries(i))if(!wT(o,a,l))return false}return true}function wT(t,e,n){switch(e){case "$eq":return t===n;case "$neq":return t!==n;case "$gt":return t>n;case "$gte":return t>=n;case "$lt":return t<n;case "$lte":return t<=n;case "$in":return Array.isArray(n)&&n.includes(t);case "$notIn":return !Array.isArray(n)||!n.includes(t);case "$is":return t===n;case "$isNot":return t!==n;default:throw new Error(`Cannot evaluate operator "${e}" client-side for WITH CHECK`)}}var ga=class{transformQuery(e){return e.node}transformResult(e){return e.result.rows?Promise.resolve({...e.result,rows:e.result.rows.map(n=>{let r={};for(let s in n){let i=n[s];if(typeof i=="string"&&(i[0]==="{"||i[0]==="["))try{r[s]=JSON.parse(i);}catch{r[s]=i;}else r[s]=i;}return r})}):Promise.resolve(e.result)}};function Cy(t){let e={};for(let n in t){let r=t[n];if(typeof r=="string"&&(r[0]==="["||r[0]==="{"))try{e[n]=JSON.parse(r);}catch{e[n]=r;}else e[n]=r;}return e}var di=class t extends Connection{dialect="sqlite";deserializeRow(e){return this.config.ddlDialect==="postgres"?Cy(e):e}constructor(e={}){super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}});}static parseDeparseInfo(e){try{if(typeof e!="object"||e===null)return {};let n=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),r=e?.rls?.policies.map(i=>new rn(JSON.parse(JSON.stringify(i)))),s=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{}));return {rls:{tables:n,policies:r},vars:s}}catch(n){return console.log("error parsing deparse info",n),{}}}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e};}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new ga),n.push(new ua(ec({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...n,...e]}async translateDdl(e){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let n=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,r=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:s}=await Promise.resolve().then(()=>(sf(),zy));return await s(e,{forceDefaultSchema:n,introspection:r,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){tm(typeof e=="object"||e===void 0,"options must be an object");let n=e?.useCache??false;if(e?.postprocess!==false){let i=await this.readCachedIntrospection({useCache:n});if(i)return i}let r=await uy(this,this.config.introspection),s=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let i=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>c=>{let u=c[l],f=c.schema??i;return !f&&i&&u.includes(s)&&([f,u]=u.split(s)),{...c,[l]:u,schema:f??i}},a=l=>{let c=o()(l),u=c.ref_table,f=c.ref_schema??i;return u?.includes(s)&&([f,u]=u.split(s)),{...c,ref_table:u,ref_schema:f??i}};r={...r,tables:r.tables.map(o("name")),columns:r.columns.map(o()),indexes:r.indexes.map(o()),primary_keys:r.primary_keys.map(o()),foreign_keys:r.foreign_keys.map(a),views:r.views.map(o("name")),check_constraints:r.check_constraints.map(o("table"))};}return r=py(r),r=gy(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&Me(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let u=c.context,f=r.find(p=>p.table===u.table&&p.name===u.column);if(f&&(f.pg_type=u.pgTypeName,u.isGenerated!==void 0&&(f.is_generated=u.isGenerated)),u.fkRef?.constraintName){let p=s.find(d=>d.table===u.table&&d.column===u.column&&d.ref_table===u.fkRef.refTable&&d.ref_column===u.fkRef.refColumn);p&&(p.foreign_key_name=u.fkRef.constraintName);}u.uniqueConstraintName&&i.push({schema:u.schema,table:u.table,name:u.uniqueConstraintName,columns:[u.column]}),u.hasCheck&&o.push({schema:u.schema,table:u.table,expression:"",name:u.checkConstraintName,column:u.column});}for(let l of n.tableConstraints??[])if(l.kind==="unique")i.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let c=l.refTable;for(let u=0;u<l.columns.length;u++){let f=s.find(p=>p.table===l.table&&p.column===l.columns[u]&&p.ref_table===c&&p.ref_column===(l.refColumns?.[u]??""));f&&(f.foreign_key_name=l.name);}}let a=[...e.comments??[],...n.comments??[]];return {...e,columns:r,foreign_keys:s,unique_constraints:i,check_constraints:o,comments:a}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
|
|
508
|
+
${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function rn(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function py(t,e={}){let r=(await t.exec(VC(e)))?.rows?.[0]||{};return {tables:rn(r.tables),columns:rn(r.columns),indexes:rn(r.indexes),foreign_keys:rn(r.foreign_keys),primary_keys:rn(r.primary_keys),views:rn(r.views),triggers:rn(r.triggers),check_constraints:[],unique_constraints:rn(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function QC(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function dy(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function Yu(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function YC(t){let e=new Map;for(let r of t){if(!dy(r.foreign_key_name))continue;let s=e.get(Yu(r));s?s.push(r):e.set(Yu(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get(Yu(r));return s?{...r,foreign_key_name:s}:r})}function my(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!dy(r.foreign_key_name))return r;let s=e.get(r.table),i=QC(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:YC(n)}}function Xu(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function XC(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function ZC(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(Xu);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?Xu(r):i}}function hy(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function eT(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!hy(t[s-1])&&!hy(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function tT(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function gy(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function nT(t,e){if(!t)return null;let n=eT(t);if(!n)return null;let r=tT(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(Xu).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of XC(n.selectList)){let u=c.trim();if(u==="*"||u.endsWith(".*")){for(let p of l)gy(a,p,p);continue}let f=ZC(c);f&&gy(a,f.baseColumn,f.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function rT(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function sT(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(u=>u.name===l.name&&u.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=nT(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let u=new Map;for(let[p,d]of l.columns){let g=d.filter(m=>c.has(m));g.length>0&&u.set(p,g);}if(u.size===0)continue;let f={name:a.name,schema:a.schema,columnByBaseColumn:u,fromRelation:l.baseTable};s.set(a.name,f);}let i=16;function o(a,l,c){if(l>i)return null;let u=a.fromRelation;if(e.has(u))return {physicalBase:u,columnByBaseColumn:a.columnByBaseColumn};let f=s.get(u);if(!f||c.has(u))return null;c.add(u);let p=o(f,l+1,c);if(c.delete(u),!p)return null;let d=rT(a.columnByBaseColumn,p.columnByBaseColumn);return d.size===0?null:{physicalBase:p.physicalBase,columnByBaseColumn:d}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function yy(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function iT(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function oT(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function aT(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function by(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=sT(t),n=new Set(t.foreign_keys.map(yy)),r=[];for(let s of iT(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let u=[];for(let f of s){let p=l.columnByBaseColumn.get(f.column)??[],d=c.columnByBaseColumn.get(f.ref_column)??[],g=p.flatMap(m=>d.map(h=>({fk:f,childColumn:m,parentColumn:h})));if(g.length===0){u.length=0;break}u.push(g);}for(let f of oT(u)){let d=l.name===i.table&&c.name===i.ref_table&&f.every(g=>g.childColumn===g.fk.column&&g.parentColumn===g.fk.ref_column)?void 0:aT(l,c,i.foreign_key_name,f);for(let g of f){let m={...g.fk,table:l.name,column:g.childColumn,schema:l.schema,ref_table:c.name,ref_column:g.parentColumn,ref_schema:c.schema,foreign_key_group:d},h=yy(m);n.has(h)||(n.add(h),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var mT=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Zu=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#e=new Set;#t=new Set;transformNodeImpl(n,r){if(!mT.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#t.add(o);let i=this.#n(n);for(let o of i)this.#e.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#e.delete(o);for(let o of s)this.#t.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#t.has(s)&&this.#e.has(s),a=i??(o?this.config.defaultSchema:void 0);if(!a)return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:s}};let l=this.config.approach==="snake_case"?"__":".";return {kind:"SchemableIdentifierNode",schema:void 0,identifier:{kind:"IdentifierNode",name:`${a}${l}${s}`}}}#n(n){let r=new Set;if(n?.name&&SchemableIdentifierNode.is(n.name)&&this.#r(n.name,r),n?.from?.froms)for(let s of n.from.froms)this.#i(s,r);if(n?.into&&this.#i(n.into,r),n?.table&&this.#i(n.table,r),n?.joins)for(let s of n.joins)this.#i(s.table,r);return n?.using&&(JoinNode.is(n.using)?this.#i(n.using.table,r):this.#i(n.using,r)),r}#i(n,r){if(TableNode.is(n)){this.#r(n.table,r);return}if(AliasNode.is(n)&&TableNode.is(n.node)){this.#r(n.node.table,r);return}if(ListNode.is(n)){for(let s of n.items)this.#i(s,r);return}if(UsingNode.is(n))for(let s of n.tables)this.#i(s,r);}#r(n,r){let s=n.identifier.name;this.#t.has(s)||r.add(s);}#s(n){let r=new Set;if(n?.with?.expressions)for(let s of n.with.expressions){let i=s?.name?.table?.table?.identifier?.name;i&&r.add(i);}return r}},ua=class{#e;constructor(e){this.#e=new Zu(e);}transformQuery(e){return this.#e.transformNode(e.node)}async transformResult(e){return e.result}};fa();ef();tf();function bT(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function Sy(t,e){let n=r=>bT(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}var da=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new vr,this.planner=new Ar;}differ;planner;translationResult;async getDesiredSchema(){let e=await this.conn.translateDdl(this.desiredSchema);return this.translationResult=e,await this.options.onTranslation?.(e),e.ddl}async diff(){let e=await this.conn.introspect({postprocess:false}),n=await this.getDesiredSchema();if(!n||n.trim().length===0)return {current:e,desired:e,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:r}=await import('@supabase/lite/sqlite'),s=await r({url:":memory:"});try{await s.exec(n);let i=await s.introspect({postprocess:!1}),o=this.conn.config.ddlDialect,a=Sy(e,o),l=Sy(i,o),c=this.differ.diff(a,l),u=this.planner.plan(c,a,l);return {current:e,desired:i,diff:c,plan:u}}finally{await s.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff();return await this.migratePlan(n.plan,e),n}};hs();var Ey=/^\{\{(.+)\}\}$/;function xy(t){return typeof t=="string"&&Ey.test(t)}function wT(t){return Ey.exec(t)[1]}var _y=Symbol("unresolved");function Ry(t,e){let n=wT(t),r=Vt(e,n,_y);if(r===_y)throw new Error(`Unresolved variable: {{${n}}}`);return r}function Dt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>Dt(i,e));continue}if(r==="$not"){n[r]=Dt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?Dt(i.where,e):i?.where};continue}if(xy(r)){let i=Ry(r,e),a=_T(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=Cy(s,e);continue}n[r]=s;}return n}function Cy(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=Cy(s,e):ST(s)?n[r]={...s,where:s?.where?Dt(s?.where,e):void 0}:xy(s)?n[r]=Ry(s,e):n[r]=s;return n}function ST(t){return t!=null&&typeof t=="object"&&t.type==="query"}function _T(t,e){for(let[n,r]of Object.entries(e))switch(n){case "$eq":if(t!==r)return false;break;case "$neq":if(t===r)return false;break;case "$in":if(!Array.isArray(r)||!r.includes(t))return false;break;case "$notIn":if(Array.isArray(r)&&r.includes(t))return false;break;default:throw new Error(`Cannot statically evaluate operator ${n} on placeholder key`)}return true}hs();var ha=class{constructor(e,n,r){this.tables=e;this.policies=n;this.defaultSchema=r;}enforce(e,n){let r=e.from;if(!r||!this.isRlsEnabled(r,e.schema))return e;let s=ET(e.type);if(!s)return e;let i=Vt(n,"auth.role")??"anon",{permissive:o,restrictive:a}=this.resolvePolicies(r,e.schema,s,i);switch(s){case "SELECT":case "DELETE":{let l=this.combineUsing(o,a,n);return {...e,where:Ty(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Ty(e.where,l)};if(l.$always===false)return c;let u=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(u).length>0){let f=new Set(Object.keys(e.values));this.validateWithCheck(u,e.values,o,a,f);}return c}case "INSERT":{let l=this.combineWithCheck(o,a,n,s);if(e.values){let c=Array.isArray(e.values)?e.values:[e.values];for(let u of c)this.validateWithCheck(l,u,o,a);}return e}default:return e}}isRlsEnabled(e,n){return this.tables.has(e)}resolvePolicies(e,n,r,s){let i=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,n)&&o.appliesTo(r)&&o.appliesToRole(s));return {permissive:i.filter(o=>o.data.permissive),restrictive:i.filter(o=>!o.data.permissive)}}schemasMatch(e,n){let r=e||this.defaultSchema,s=n||this.defaultSchema;return r===s}combineUsing(e,n,r){if(e.length===0)return {$always:false};let s=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>Dt(o,r)),i;s.length===0?i={}:s.length===1?i=s[0]:i={$or:s};for(let o of n)if(o.data.using&&Object.keys(o.data.using).length>0){let a=Dt(o.data.using,r);i=Object.keys(i).length===0?a:{$and:[i,a]};}return i}combineWithCheck(e,n,r,s){if(e.length===0)return {$always:false};let i=e.map(a=>a.data.withCheck??(s==="UPDATE"?a.data.using:void 0)).filter(a=>a!=null&&Object.keys(a).length>0).map(a=>Dt(a,r)),o;i.length===0?o={}:i.length===1?o=i[0]:o={$or:i};for(let a of n){let l=a.data.withCheck??(s==="UPDATE"?a.data.using:void 0);if(l&&Object.keys(l).length>0){let c=Dt(l,r);o=Object.keys(o).length===0?c:{$and:[o,c]};}}return o}validateWithCheck(e,n,r,s,i){if(Object.keys(e).length===0)return;if(!ma(e,n,i)){let a=r[0]??s[0];throw a?new ur(a):new Error("RLS policy violation")}}};function ET(t){switch(t){case "query":return "SELECT";case "insert":case "upsert":case "put":return "INSERT";case "update":return "UPDATE";case "delete":return "DELETE";default:return}}function Ty(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function ma(t,e,n){for(let[r,s]of Object.entries(t)){if(r==="$always"){if(s===false)return false;continue}if(r==="$and"){if(!s.every(l=>ma(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>ma(l,e,n)))return false;continue}if(r==="$not"){if(ma(s,e,n))return false;continue}if(n&&!n.has(r))continue;let i=s,o=e[r];for(let[a,l]of Object.entries(i))if(!xT(o,a,l))return false}return true}function xT(t,e,n){switch(e){case "$eq":return t===n;case "$neq":return t!==n;case "$gt":return t>n;case "$gte":return t>=n;case "$lt":return t<n;case "$lte":return t<=n;case "$in":return Array.isArray(n)&&n.includes(t);case "$notIn":return !Array.isArray(n)||!n.includes(t);case "$is":return t===n;case "$isNot":return t!==n;default:throw new Error(`Cannot evaluate operator "${e}" client-side for WITH CHECK`)}}var ga=class{transformQuery(e){return e.node}transformResult(e){return e.result.rows?Promise.resolve({...e.result,rows:e.result.rows.map(n=>{let r={};for(let s in n){let i=n[s];if(typeof i=="string"&&(i[0]==="{"||i[0]==="["))try{r[s]=JSON.parse(i);}catch{r[s]=i;}else r[s]=i;}return r})}):Promise.resolve(e.result)}};function vy(t){let e={};for(let n in t){let r=t[n];if(typeof r=="string"&&(r[0]==="["||r[0]==="{"))try{e[n]=JSON.parse(r);}catch{e[n]=r;}else e[n]=r;}return e}var di=class t extends Connection{dialect="sqlite";deserializeRow(e){return this.config.ddlDialect==="postgres"?vy(e):e}constructor(e={}){super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}});}static parseDeparseInfo(e){try{if(typeof e!="object"||e===null)return {};let n=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),r=e?.rls?.policies.map(i=>new gt(JSON.parse(JSON.stringify(i)))),s=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{}));return {rls:{tables:n,policies:r},vars:s}}catch(n){return console.log("error parsing deparse info",n),{}}}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e};}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new ga),n.push(new ua(ec({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...n,...e]}async translateDdl(e){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let n=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,r=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:s}=await Promise.resolve().then(()=>(af(),Yy));return await s(e,{forceDefaultSchema:n,introspection:r,defaultSchema:this.config.translation?.schemas?.defaultSchema||void 0,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){rm(typeof e=="object"||e===void 0,"options must be an object");let n=e?.useCache??false;if(e?.postprocess!==false){let i=await this.readCachedIntrospection({useCache:n});if(i)return i}let r=await py(this,this.config.introspection),s=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let i=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>c=>{let u=c[l],f=c.schema??i;return !f&&i&&u.includes(s)&&([f,u]=u.split(s)),{...c,[l]:u,schema:f??i}},a=l=>{let c=o()(l),u=c.ref_table,f=c.ref_schema??i;return u?.includes(s)&&([f,u]=u.split(s)),{...c,ref_table:u,ref_schema:f??i}};r={...r,tables:r.tables.map(o("name")),columns:r.columns.map(o()),indexes:r.indexes.map(o()),primary_keys:r.primary_keys.map(o()),foreign_keys:r.foreign_keys.map(a),views:r.views.map(o("name")),check_constraints:r.check_constraints.map(o("table"))};}return r=my(r),r=by(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&Me(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let u=c.context,f=r.find(p=>p.table===u.table&&p.name===u.column);if(f&&(f.pg_type=u.pgTypeName,u.isGenerated!==void 0&&(f.is_generated=u.isGenerated)),u.fkRef?.constraintName){let p=s.find(d=>d.table===u.table&&d.column===u.column&&d.ref_table===u.fkRef.refTable&&d.ref_column===u.fkRef.refColumn);p&&(p.foreign_key_name=u.fkRef.constraintName);}u.uniqueConstraintName&&i.push({schema:u.schema,table:u.table,name:u.uniqueConstraintName,columns:[u.column]}),u.hasCheck&&o.push({schema:u.schema,table:u.table,expression:"",name:u.checkConstraintName,column:u.column});}for(let l of n.tableConstraints??[])if(l.kind==="unique")i.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let c=l.refTable;for(let u=0;u<l.columns.length;u++){let f=s.find(p=>p.table===l.table&&p.column===l.columns[u]&&p.ref_table===c&&p.ref_column===(l.refColumns?.[u]??""));f&&(f.foreign_key_name=l.name);}}let a=[...e.comments??[],...n.comments??[]];return {...e,columns:r,foreign_keys:s,unique_constraints:i,check_constraints:o,comments:a}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
|
|
509
509
|
|
|
510
|
-
`);return new da(this,n,{onTranslation:async r=>{if(this.config.translation){let s={enums:r.enums,rls:r.rls,schema:r.schema,vars:r.vars,tableConstraints:r.tableConstraints??[],comments:r.comments??[]};this.config.translation.deparse=s;}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let n=e?.length??0,r=this.maxBoundParameters;if(!(n<=r))throw Object.assign(new Error(`Query exceeds max bound parameters (${n} > ${r}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${r} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s===void 0)continue;if(s===null){n.push(s);continue}let i=typeof s;if(i==="boolean"){n.push(s?1:0);continue}if(i==="number"||i==="bigint"||i==="string"){n.push(s);continue}if(s instanceof Uint8Array||s instanceof ArrayBuffer||s instanceof Date){n.push(s);continue}throw new Error(`Cannot bind value at parameter ${r+1}: unsupported type ${Array.isArray(s)?"array":i}`)}return n}normalizeDbError(e){let n=e,r=n?.cause?.code??n?.code,s=n?.cause?.message??n?.message??String(e);if(r==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(s),{code:"23502",detail:s});if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(s),{code:"23505",detail:s});if(r==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(s),{code:"23503",detail:s});if(typeof s=="string"){if(/too many SQL variables/i.test(s)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:s})}let i=s.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(i){let a=i[1],l=a.lastIndexOf("."),c=l>=0?a.slice(0,l):void 0,u=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,u)}let o=s.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:s})}return e}async onPostgrestAST(e,n){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,this.applyRls(e,n);let r=this.config.translation?.schemas?.appendDefaultSchema,s=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===s&&!r?e.schema=void 0:!e.schema&&s&&r&&(e.schema=s),!e.from)return e;let i=await this.introspect({useCache:true}),o=e.schema??(r&&s?s:""),a=e.from;if(!(i.tables.some(c=>c.name===a&&(c.schema??"")===o)||i.views.some(c=>c.name===a&&(c.schema??"")===o))){if(!(i.tables.some(u=>u.name===a&&["","public",s].includes(u.schema??""))||i.views.some(u=>u.name===a&&["","public",s].includes(u.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return this.applyRls(e,n)}applyRls(e,n){let r=this.config.translation?.deparse?.rls;if(!r||!n)return e;let s=this.config.translation?.schemas?.defaultSchema||void 0;return new ha(r.tables,r.policies,s).enforce(e,n)}};var Ca=class extends di{constructor(n){super({...n,introspection:{...n.introspection,version:"3.47.0"}});this.config=n;}dialect="sqlite";driver=null;kysely=null;fetch(n,r){let s=n instanceof URL?new URL(n.toString(),this.config.host):new URL(n,this.config.host);return fetch(s,{...r,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.token}`,...r?.headers}})}async introspect(n){let r=new URLSearchParams({useCache:n?.useCache?"1":"0",postprocess:n?.postprocess?"1":"0"}),s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/introspect?${r}`),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to get project introspect: ${s.status} ${s.statusText}`);try{let o=JSON.parse(i);if(!o)throw new Error("Failed to get project introspect");return o}catch(o){throw console.error(o),console.log(i),new Error(`Failed to parse introspect response: "${i}"`)}}async transaction(n,r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/transaction?intent=${r?.intent??"migration"}`,{method:"POST",body:JSON.stringify({statements:n})});if(!s.ok)throw new Error(`Failed to execute transaction: ${s.status} ${s.statusText}`)}async exec(n,...r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/exec`,{method:"POST",body:JSON.stringify({statement:n,parameters:r})}),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to execute statement: ${s.status} ${s.statusText}`);try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function
|
|
510
|
+
`);return new da(this,n,{onTranslation:async r=>{if(this.config.translation){let s={enums:r.enums,rls:r.rls,schema:r.schema,vars:r.vars,tableConstraints:r.tableConstraints??[],comments:r.comments??[]};this.config.translation.deparse=s;}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let n=e?.length??0,r=this.maxBoundParameters;if(!(n<=r))throw Object.assign(new Error(`Query exceeds max bound parameters (${n} > ${r}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${r} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s===void 0)continue;if(s===null){n.push(s);continue}let i=typeof s;if(i==="boolean"){n.push(s?1:0);continue}if(i==="number"||i==="bigint"||i==="string"){n.push(s);continue}if(s instanceof Uint8Array||s instanceof ArrayBuffer||s instanceof Date){n.push(s);continue}throw new Error(`Cannot bind value at parameter ${r+1}: unsupported type ${Array.isArray(s)?"array":i}`)}return n}normalizeDbError(e){let n=e,r=n?.cause?.code??n?.code,s=n?.cause?.message??n?.message??String(e);if(r==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(s),{code:"23502",detail:s});if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(s),{code:"23505",detail:s});if(r==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(s),{code:"23503",detail:s});if(typeof s=="string"){if(/too many SQL variables/i.test(s)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:s})}let i=s.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(i){let a=i[1],l=a.lastIndexOf("."),c=l>=0?a.slice(0,l):void 0,u=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,u)}let o=s.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:s})}return e}async onPostgrestAST(e,n){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,this.applyRls(e,n);let r=this.config.translation?.schemas?.appendDefaultSchema,s=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===s&&!r?e.schema=void 0:!e.schema&&s&&r&&(e.schema=s),!e.from)return e;let i=await this.introspect({useCache:true}),o=e.schema??(r&&s?s:""),a=e.from;if(!(i.tables.some(c=>c.name===a&&(c.schema??"")===o)||i.views.some(c=>c.name===a&&(c.schema??"")===o))){if(!(i.tables.some(u=>u.name===a&&["","public",s].includes(u.schema??""))||i.views.some(u=>u.name===a&&["","public",s].includes(u.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return this.applyRls(e,n)}applyRls(e,n){let r=this.config.translation?.deparse?.rls;if(!r||!n)return e;let s=this.config.translation?.schemas?.defaultSchema||void 0;return new ha(r.tables,r.policies,s).enforce(e,n)}};var Ca=class extends di{constructor(n){super({...n,introspection:{...n.introspection,version:"3.47.0"}});this.config=n;}dialect="sqlite";driver=null;kysely=null;fetch(n,r){let s=n instanceof URL?new URL(n.toString(),this.config.host):new URL(n,this.config.host);return fetch(s,{...r,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${this.config.token}`,...r?.headers}})}async introspect(n){let r=new URLSearchParams({useCache:n?.useCache?"1":"0",postprocess:n?.postprocess?"1":"0"}),s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/introspect?${r}`),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to get project introspect: ${s.status} ${s.statusText}`);try{let o=JSON.parse(i);if(!o)throw new Error("Failed to get project introspect");return o}catch(o){throw console.error(o),console.log(i),new Error(`Failed to parse introspect response: "${i}"`)}}async transaction(n,r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/transaction?intent=${r?.intent??"migration"}`,{method:"POST",body:JSON.stringify({statements:n})});if(!s.ok)throw new Error(`Failed to execute transaction: ${s.status} ${s.statusText}`)}async exec(n,...r){let s=await this.fetch(`/v1/projects/${this.config.projectRef}/db/exec`,{method:"POST",body:JSON.stringify({statement:n,parameters:r})}),i=await s.text();if(!s.ok)throw console.error(i),new Error(`Failed to execute statement: ${s.status} ${s.statusText}`);try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function KT(t){return new Ca(t)}af();bs();try{let{emitWarning:t}=process;process.emitWarning=(e,...n)=>{if(!e.includes("SQLite is an experimental feature"))return t(e,...n)};}catch{}/*! Bundled license information:
|
|
511
511
|
|
|
512
512
|
aws4fetch/dist/aws4fetch.esm.mjs:
|
|
513
513
|
(**
|
|
514
514
|
* @license MIT <https://opensource.org/licenses/MIT>
|
|
515
515
|
* @copyright Michael Hart 2024
|
|
516
516
|
*)
|
|
517
|
-
*/export{Vu as App,qo as AwsSesEmailDriver,Ca as CloudConnection,Fo as CloudflareKvCacheDriver,Lc as Connection,
|
|
517
|
+
*/export{Vu as App,qo as AwsSesEmailDriver,Ca as CloudConnection,Fo as CloudflareKvCacheDriver,Lc as Connection,uy as DataLossError,Bs as InMemoryEmailDriver,dr as InMemoryLruCacheDriver,cy as InvalidPostgresToSQLiteTranslation,fy as MigrationError,mr as NoopEmailDriver,qs as NoopSmsDriver,Qu as PlanStepType,Mo as RedisCacheDriver,ar as RelationNotFoundError,Uo as ResendEmailDriver,Ho as SendmailEmailDriver,di as SqliteConnection,ly as UnableToCreateRuntimeConnection,x$ as checkPasswordStrength,gs as cleanSql,KT as cloud,Nh as createAppDrivers,JO as ensureVar,MO as filterSearchParams,Qc as formatSendmailMessage,ps as fuzzyMatch,Gu as getAuthSchemaSql,Vt as getPath,GO as getStatementsArray,rm as invariant,vO as isBooleanLike,OE as isBun,E$ as isEmail,Zl as isEqual,Tr as isExperimentalEnabled,BO as isNode,tm as isObject,em as isPlainObject,TO as isPrimitive,AO as isString,jO as jsonStringify,sy as listEnabledExperimentals,KO as measureTime,ec as mergeObject,$E as mergeObjectWith,rc as normalizeDefault,nc as normalizeSql,v_ as normalizeString,tc as normalizeType,NO as objectDiff,DO as omit,FO as params,YO as parseBigInt,co as patternMatch,IO as pick,$O as pipe,OO as pipeEach,I as quote,_$ as randomString,k$ as replacePlaceholders,Vs as requireAuth,mu as resolveAuth,HC as setExperimental,kE as setPath,v$ as slugify,T$ as snakeToPascalWithSpaces,VO as splitSqlStatements,UC as studioRouteHandler,qO as threw,HO as threwAsync,Vy as translatePostgresDdl,A$ as truncate,WO as trySync,R$ as ucFirst,C$ as ucFirstAll,ZO as uuid};
|