@supabase/lite 0.2.1-next.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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 Np from'bcryptjs';import {v7}from'uuid';import {createClient}from'@supabase/supabase-js';try {
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 Ip 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,42 +9,42 @@ import {Deparser,QuoteUtils}from'pgsql-deparser';import {DeparserContext}from'pg
9
9
  };
10
10
  } catch {}
11
11
 
12
- var Nh=Object.create;var Zo=Object.defineProperty;var Ih=Object.getOwnPropertyDescriptor;var Dh=Object.getOwnPropertyNames;var jh=Object.getPrototypeOf,Lh=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(t&&(e=t(t=0)),e);var iu=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),xr=(t,e)=>{for(var n in e)Zo(t,n,{get:e[n],enumerable:true});},Uh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dh(e))!Lh.call(t,s)&&s!==n&&Zo(t,s,{get:()=>e[s],enumerable:!(r=Ih(e,s))||r.enumerable});return t};var ou=(t,e,n)=>(n=t!=null?Nh(jh(t)):{},Uh(Zo(n,"default",{value:t,enumerable:true}),t));function Mh(t,e,n=void 0){let r=typeof e=="string"?uu(e):na(e);return ni(t,r,n)}function ni(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:ni(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function qh(t){return t===null}function fe(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null}function Wh(t){return Object.prototype.toString.call(t)==="[object Object]"}function ot(t){return typeof t=="string"}function wt(t){return typeof t=="number"}function Jh(t){return typeof t=="number"&&Number.isInteger(t)}function ia(t){return typeof t=="boolean"}function Kt(t){return Array.isArray(t)}function Kh(t){return typeof t!="boolean"}function Hh(t){return t!==void 0&&Kh(t)&&"type"in t}function ve(t){return t!==void 0&&fe(t)&&xe in t}function zh(t){return ve(t)&&typeof t.toJSON()=="boolean"}function Gh(t,e,n){if(!t)throw new Bh(e,n)}function fu(t){return ot(t)?t.normalize("NFC"):t}function vr(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(!vr(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(!vr(t[i],e[i]))return false;return true}return t===e}function Vh(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function du(t){try{return structuredClone(t)}catch{return t}}function Qh(t,e,n={}){let r=e;try{r=structuredClone(e);}catch{r=JSON.parse(JSON.stringify(e));}let s={resolver:n.resolver||new oa(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 ri(t,e,n={}){return t.map(r=>r.validate(e,ti(n)).valid?r:void 0).filter(Boolean)}function Ag(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 oa(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=ea[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 ea&&t[o]!==void 0){if(s===void 0)continue;let a=ea[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 St{type=t}(e,n)}function ra(t){return new Og(t)}function lu(t,e){return Array.isArray(t)?t.map(e):t!==void 0?[e(t)]:[]}function cu(t,e,n=r=>r){return Object.fromEntries(Object.entries(t).map(([r,s])=>[r,n(e(s,r),r)]))}function Jt(t){if(ia(t))return ra(t);let e=structuredClone(t);if(!fe(e))throw new Fh("non-object schemas cannot be converted to a schema",e);"properties"in e&&e.properties&&(e.properties=cu(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]=cu(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"&&(Kt(e[i])?e[i]=lu(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]=lu(o,Jt);}if(Hh(e))switch(e.type){case "string":return cn(e);case "number":return hu(e);case "integer":return gu(e);case "boolean":return Rr(e);case "object":{let{properties:i,...o}=e;return ii(i,o)}case "array":{let{items:i,...o}=e;return yu(i,o)}}return pu(e)}function Bg(){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(Mg.map(t=>[t,e=>Math.min(...e)])),...Object.fromEntries(Fg.map(t=>[t,e=>Math.max(...e)]))}}function qg(t){let e={...Bg(),...t.resolvers};function n(r,s){if(Array.isArray(r)&&Array.isArray(s))return [...new Set([...r,...s])];if(sa(r)&&sa(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):ta(a);}else i[o]=ta(a);return i}return ta(s)}return n}function Jg(t,e={}){let n=e.deep!==false,r=qg(e);function s(i){if(Array.isArray(i))return i.map(s);if(!sa(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(p=>p===false))return false;let l=a.filter(p=>p!==true);if(!l.length)return true;let c=l.reduce((p,y)=>r(p,y),{}),f=Wg(c);if(f!==null)return f;let u={...i};delete u.allOf;let d=r(c,n?s(u):u);return n?s(d):d}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(t)}var na,uu,Q,T,Mn,ti,ln,Fh,Bh,xe,oa,Xh,Yh,Zh,eg,tg,ng,rg,sg,ig,og,ag,lg,cg,ug,fg,dg,pg,mg,hg,gg,yg,bg,wg,Sg,Eg,_g,xg,vg,Cg,Rg,Tg,au,kg,ea,St,Cr,Og,pu,$g,Pg,ii,Fn,Ng,Ig,Dg,aa,cn,mu,hu,gu,jg,yu,Rr,ei,bu,Lg,Ug,sa,ta,Mg,Fg,Wg,Kg,wu,Hg,zg,Gg,g,ee=$(()=>{na=(t=[],e="")=>"/"+[e,...t.map(n=>String(n).replace(/\./g,"/"))].filter(Boolean).join("/"),uu=t=>t.split("/").slice(1);Q=(t={},e,n,r)=>({valid:false,errors:[...t.errors??[],{keywordLocation:na([...t.keywordPath??[],e]),instanceLocation:na(t.instancePath),error:typeof n=="string"?n:`Invalid value for ${e}`,data:r}]}),T=()=>({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}},ti=(t={})=>({...t,errors:[]}),ln=class extends Error{constructor(t){super(`Expected ${t}`);}},Fh=class extends Error{constructor(t,e){super(`${t??"Invalid raw schema"}: ${JSON.stringify(e)}`),this.schema=e;}},Bh=class extends Error{constructor(t,e){super(`${t}, got: 'type "${typeof e}": ${JSON.stringify(e)}'`),this.value=e;}},xe=Symbol.for("jsonv-ts:schema");oa=class{constructor(t){this.root=t,this.cache=new Map;}cache;hasRef(t,e){return e!==void 0&&"$ref"in t&&ot(t.$ref)}resolve(t){let e=this.cache.get(t);if(!e){if(e=Mh(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}};Xh=({type:t},e,n={})=>{if(t===void 0||e===void 0)return T();let r,s={string:ot,number:wt,integer:Jh,object:fe,array:Kt,boolean:ia,null:qh};if(Array.isArray(t)){for(let i of t){if(!(i in s))throw new ln(`Unknown type: ${i}`);if(s[i](e))return T()}r=`Expected one of: ${t.join(", ")}`;}else {if(!(t in s))throw new ln(`Unknown type: ${t}`);s[t](e)||(r=`Expected ${t}`);}return r?Q(n,"type",r,e):T()},Yh=({const:t},e,n={})=>vr(t,e)?T():Q(n,"const",`Expected const: ${t}`,e),Zh=({enum:t=[]},e,n={})=>t.some(r=>vr(r,e))?T():Q(n,"enum",`Expected enum: ${JSON.stringify(t)}`,e);eg=({anyOf:t=[]},e,n={})=>ri(t,e,n).length>0?T():Q(n,"anyOf","Expected at least one to match",e),tg=({oneOf:t=[]},e,n={})=>ri(t,e).length===1?T():Q(n,"oneOf","Expected exactly one to match",e),ng=({allOf:t=[]},e,n={})=>ri(t,e,n).length===t.length?T():Q(n,"allOf","Expected all to match",e),rg=({not:t},e,n={})=>e===void 0?T():ve(t)&&t.validate(e,n).valid?Q(n,"not","Expected not to match",e):T(),sg=({if:t,then:e,else:n},r,s={})=>{if(t&&(e||n)){if(t.validate(r,ti(s)).valid)return e?e.validate(r,ti(s)):T();if(n)return n.validate(r,ti(s))}return T()},ig=({pattern:t=""},e,n={})=>{if(!ot(e))return T();if(t instanceof RegExp){if(t.test(e))return T()}else if(new RegExp(t,"u").test(e))return T();return Q(n,"pattern",`Expected string matching pattern ${t}`,e)},og=({minLength:t=0},e,n={})=>ot(e)?[...fu(e)].length>=t?T():Q(n,"minLength",`Expected string with minimum length of ${t}`,e):T(),ag=({maxLength:t=0},e,n={})=>ot(e)?[...fu(e)].length<=t?T():Q(n,"maxLength",`Expected string with maximum length of ${t}`,e):T(),lg=({multipleOf:t=0},e,n={})=>{if(!wt(e))return T();if(!(Number.isFinite(e)&&Number.isFinite(t))||t<=0)throw new ln("number");let r=e/t,s=Number.EPSILON*Math.max(1,Math.abs(r));return Math.abs(r-Math.round(r))<=s?T():Q(n,"multipleOf",`Expected number being a multiple of ${t}`,e)},cg=({maximum:t=0},e,n={})=>!wt(e)||e<=t?T():Q(n,"maximum",`Expected number less than or equal to ${t}`,e),ug=({exclusiveMaximum:t=0},e,n={})=>!wt(e)||e<t?T():Q(n,"exclusiveMaximum",`Expected number less than ${t}`,e),fg=({minimum:t=0},e,n={})=>!wt(e)||e>=t?T():Q(n,"minimum",`Expected number greater than or equal to ${t}`,e),dg=({exclusiveMinimum:t=0},e,n={})=>!wt(e)||e>t?T():Q(n,"exclusiveMinimum",`Expected number greater than ${t}`,e),pg=({properties:t={}},e,n={})=>{if(!fe(e))return T();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 T()},mg=({properties:t={},additionalProperties:e,patternProperties:n},r,s={})=>{if(!fe(r))return T();if(!ve(e))throw new ln("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(zh(e)){if(e.toJSON()===true)return T();let l=a.reduce((c,f)=>(c[f]=r[f],c),{});return Q(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 T()},hg=({dependentRequired:t},e,n={})=>{if(!fe(e))return T();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 Q(n,"dependentRequired",`Expected dependent required property ${o}`,e)}}return T()},gg=({required:t=[]},e,n={})=>{if(!fe(e))return T();let r=Object.keys(e).filter(s=>typeof e[s]!="function");return t.every(s=>r.includes(s))?T():Q(n,"required",`Expected object with required properties ${t.join(", ")}`,e)},yg=({dependentSchemas:t},e,n={})=>{if(!fe(e))return T();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 T()},bg=({minProperties:t=0},e,n={})=>fe(e)?Object.keys(e).length>=t?T():Q(n,"minProperties",`Expected object with at least ${t} properties`,e):T(),wg=({maxProperties:t=0},e,n={})=>!fe(e)||Object.keys(e).length<=t?T():Q(n,"maxProperties",`Expected object with at most ${t} properties`,e),Sg=({patternProperties:t={}},e,n={})=>{if(!fe(e))return T();if(!fe(t))throw new ln("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 T()},Eg=({propertyNames:t},e,n={})=>{if(!fe(e)||t===void 0)return T();if(!ve(t))throw new ln("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 T()},_g=({items:t,prefixItems:e=[]},n,r={})=>{if(!Kt(n)||t===void 0)return T();if(!ve(t))throw new ln("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 T()},xg=({minItems:t=0},e,n={})=>!Kt(e)||e.length>=t?T():Q(n,"minItems",`Expected array with at least ${t} items`,e),vg=({maxItems:t=0},e,n={})=>!Kt(e)||e.length<=t?T():Q(n,"maxItems",`Expected array with at most ${t} items`,e),Cg=({uniqueItems:t=false},e,n={})=>{if(!Kt(e)||!t)return T();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(vr(s,o))return Q(n,"uniqueItems",`Duplicated items at index ${r} and ${i}`,e)}}return T()},Rg=({contains:t,minContains:e,maxContains:n},r,s={})=>{if(!ve(t))throw new Error("contains must be a managed schema");if(!Kt(r))return T();let i=r.filter(o=>t.validate(o).valid).length;return i<(e??1)?Q(s,e?"minContains":"contains",`Expected array to contain at least ${e??1}, but found ${i}`,r):n!==void 0&&i>n?Q(s,"maxContains",`Expected array to contain at most ${n}, but found ${i}`,r):T()},Tg=({prefixItems:t=[]},e,n={})=>{if(!Kt(e))return T();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 T()},au={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 f=t.charCodeAt(c);if(c===1&&o===58&&f!==58)return false;if(f>=48&&f<=57){if(++r>4)return false}else if(f===46){if(e>6||n>=3||r===0||i)return false;n++,r=0;}else if(f===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(f>=97&&f<=102||f>=65&&f<=70){if(n>0||++r>4)return false;i=true;}else return false;o=f;}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},kg=({format:t},e,n={})=>!ot(e)||!t?T():au[t]?au[t](e)?T():Q(n,"format",`Expected format: ${t}`,e):T(),ea={type:Xh,const:Yh,enum:Zh,allOf:ng,anyOf:eg,oneOf:tg,not:rg,minLength:og,maxLength:ag,pattern:ig,format:kg,minimum:fg,exclusiveMinimum:dg,maximum:cg,exclusiveMaximum:ug,multipleOf:lg,required:gg,dependentRequired:hg,dependentSchemas:yg,minProperties:bg,maxProperties:wg,propertyNames:Eg,properties:pg,patternProperties:Sg,additionalProperties:mg,minItems:xg,maxItems:vg,uniqueItems:Cg,contains:Rg,prefixItems:Tg,items:_g,if:sg};St=class{"~standard";[xe];_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[xe]={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:uu(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[xe].raw?.template){let i=this[xe].raw.template(r,e);i!==void 0&&(r=i);}let s=this[xe].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[xe].raw?.validate;if(r!==void 0){let s=r(t,n);if(!s.valid)return s}return Ag(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[xe].raw?.coerce;if(r!==void 0)return r(t,n);let s=this[xe].overrides?.coerce?.(t,n)??t;return Qh(this,s,n)}optional(){return this[xe].optional=true,this}isOptional(){return this[xe].optional}getResolver(){return this._resolver||(this._resolver=new oa(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?du(n):n;if(s.includeSelf!==false&&(yield new Cr(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))}},Cr=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=ni(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}};Og=class extends St{constructor(t){super(),this.bool=t;}toJSON(){return this.bool}validate(t,e){return this.bool?T():Q(e,"","Always fails",t)}};pu=t=>si(t?.type,t),$g=(t,e)=>si(void 0,{...e,const:t}),Pg=class extends St{type="object";properties;required;constructor(t,e){let n=[];for(let[s,i]of Object.entries(t||{}))Gh(ve(i),"properties must be managed schemas",i),i[xe].optional||n.push(s);let r=e?.additionalProperties===false?ra(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 f=ni(o,l);if(c.isOptional()&&i?.withOptional!==true&&f===void 0&&s===void 0)continue;let u=c.template(f,i);u!==void 0&&(a[l]=u);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=du(s),l=o.length>0&&Object.values(this.properties).every(f=>!f[xe].optional);if(Wh(a)&&(i?.dropUnknown===true||l)&&(a=Vh(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[f,u]of Object.entries(this.properties)){let d=a[f];d!==void 0&&(a[f]=u.coerce(d,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let f=fe(s)?s:{},u=Object.keys(f).filter(d=>!o.includes(d));for(let d of u)a[d]=c?c.coerce(f[d],i):f[d];}return a}}),this.properties=t,this.required=n;}strict(){return this.additionalProperties=ra(false),this[xe].raw.additionalProperties=false,this}partial(){for(let[,t]of Object.entries(this.properties))t[xe].optional=true;return this.required=void 0,this}children(t){let e=[];for(let[n,r]of Object.entries(this.properties)){let s=new Cr(r,t);s.appendInstancePath([n]),s.appendKeywordPath(["properties",n]),e.push(s);}return e}},ii=(t,e)=>new Pg(t,e),Fn=(t,e)=>ii(t,e).strict(),Ng=(t,e)=>ii(t,e).partial(),Ig=class extends St{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 Cr(this.additionalProperties,t);return n.appendKeywordPath(["additionalProperties"]),e.push(n),e}},Dg=(t,e)=>new Ig(t,e),aa=class extends St{type="string";constructor(t){super(t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!ot(e))?"":e,coerce:e=>wt(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}))}},cn=t=>new aa(t),mu=(t,e,n)=>si(t,n,{template:(r,s)=>s?.withExtendedOptional&&(r===void 0||!wt(r))?n?.minimum??0:r,coerce:r=>{if(ot(r)){let s=e.parseFn(r);if(!Number.isNaN(s))return s}return r}}),hu=t=>mu("number",{parseFn:Number},t),gu=t=>mu("integer",{parseFn:Number.parseInt},t),jg=class extends St{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 Cr(this.items,t);n.appendKeywordPath(["items"]),e.push(n);}return e}},yu=(t,e)=>new jg(t,e),Rr=t=>si("boolean",t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!ia(e))?false:e,coerce:e=>{if(ot(e)&&["true","false","1","0"].includes(e))return e==="true"||e==="1";if(wt(e)){if(e===1)return true;if(e===0)return false}return e}}),ei=Symbol.for("unionType"),bu=class extends St{[ei];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=ri(t,r,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(r,s):r}}),this[ei]=e;}get schemas(){return this[this[ei]]}children(t){let e=[];for(let[n,r]of this.schemas.entries()){let s=new Cr(r,t);s.appendKeywordPath([this[ei],n]),e.push(s);}return e}},Lg=(t,e)=>new bu(t,"anyOf",e),Ug=(t,e)=>new bu(t,"oneOf",e);sa=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ta=t=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):JSON.parse(JSON.stringify(t)),Mg=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],Fg=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Wg=t=>t===true||t===false?t:null;Kg=(t,e)=>{let n=JSON.parse(JSON.stringify({...e,allOf:t}));return Jt(Jg(n))},wu=class extends St{$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;}},Hg=(t,e)=>new wu(t,e),zg=t=>new wu(void 0,t),Gg=t=>t(new St({$ref:"#",coerce:(e,n)=>{let r=n?.resolver?.resolve("#");if(!ve(r))throw new Error("Ref not found: #");return r.coerce(e,n)}})),g={boolean:Rr,any:pu,literal:$g,object:ii,strictObject:Fn,partialObject:Ng,record:Dg,string:cn,number:hu,integer:gu,array:yu,anyOf:Lg,oneOf:Ug,allOf:Kg,ref:Hg,refId:zg,recursive:Gg};});var sd=iu((xT,nl)=>{var Bi=process||{},nd=Bi.argv||[],Fi=Bi.env||{},mw=!(Fi.NO_COLOR||nd.includes("--no-color"))&&(!!Fi.FORCE_COLOR||nd.includes("--color")||Bi.platform==="win32"||(Bi.stdout||{}).isTTY&&Fi.TERM!=="dumb"||!!Fi.CI),hw=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+gw(s,e,n,i)+e:t+s+e},gw=(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)},rd=(t=mw)=>{let e=t?hw:()=>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")}};nl.exports=rd();nl.exports.createColors=rd;});function vT(t){return ["string","number","boolean"].includes(typeof t)}function CT(t){return [true,false,0,1].includes(t)}function RT(t){return typeof t=="string"}var id=$(()=>{});function kT(...t){return e=>t.reduce((n,r)=>r(n),e)}function AT(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var od=$(()=>{});function ad(t){return Object.prototype.toString.call(t)==="[object Object]"}function ld(t){return t!==null&&typeof t=="object"}function $T(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function Yt(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:Yt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function yw(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"?[]:{}),yw(t[s],i,n),t)}function PT(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function NT(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 sl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!ad(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:ld(t[r])?sl(t[r],s):t[r]=s);return t}function bw(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&&(!ad(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:ld(t[r])?bw(t[r],s,n):t[r]=s);}return t}function rl(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)=>rl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&rl(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)&&rl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function IT(...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 Gr=$(()=>{});function jT(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function LT(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 cd=$(()=>{});function MT(){try{return !ww()&&global?.process?.release?.name==="node"}catch{return false}}function ww(){try{return typeof Bun<"u"}catch{return false}}function ud(t,e){if(!t)throw new Error(e)}function FT(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function BT(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function qT(t,e){try{return t()}catch{return e}}async function WT(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var JT,fd=$(()=>{JT={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 Vr(t,e={}){return t.split(`
12
+ var Nh=Object.create;var Zo=Object.defineProperty;var Ih=Object.getOwnPropertyDescriptor;var Dh=Object.getOwnPropertyNames;var jh=Object.getPrototypeOf,Lh=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(t&&(e=t(t=0)),e);var ou=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),xr=(t,e)=>{for(var n in e)Zo(t,n,{get:e[n],enumerable:true});},Uh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dh(e))!Lh.call(t,s)&&s!==n&&Zo(t,s,{get:()=>e[s],enumerable:!(r=Ih(e,s))||r.enumerable});return t};var au=(t,e,n)=>(n=t!=null?Nh(jh(t)):{},Uh(Zo(n,"default",{value:t,enumerable:true}),t));function Mh(t,e,n=void 0){let r=typeof e=="string"?fu(e):na(e);return ni(t,r,n)}function ni(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:ni(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function qh(t){return t===null}function fe(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null}function Wh(t){return Object.prototype.toString.call(t)==="[object Object]"}function ot(t){return typeof t=="string"}function wt(t){return typeof t=="number"}function Jh(t){return typeof t=="number"&&Number.isInteger(t)}function ia(t){return typeof t=="boolean"}function Kt(t){return Array.isArray(t)}function Kh(t){return typeof t!="boolean"}function Hh(t){return t!==void 0&&Kh(t)&&"type"in t}function ve(t){return t!==void 0&&fe(t)&&xe in t}function zh(t){return ve(t)&&typeof t.toJSON()=="boolean"}function Gh(t,e,n){if(!t)throw new Bh(e,n)}function du(t){return ot(t)?t.normalize("NFC"):t}function vr(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(!vr(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(!vr(t[i],e[i]))return false;return true}return t===e}function Vh(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function pu(t){try{return structuredClone(t)}catch{return t}}function Qh(t,e,n={}){let r=e;try{r=structuredClone(e);}catch{r=JSON.parse(JSON.stringify(e));}let s={resolver:n.resolver||new oa(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 ri(t,e,n={}){return t.map(r=>r.validate(e,ti(n)).valid?r:void 0).filter(Boolean)}function kg(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 oa(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=ea[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 ea&&t[o]!==void 0){if(s===void 0)continue;let a=ea[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 St{type=t}(e,n)}function ra(t){return new Og(t)}function cu(t,e){return Array.isArray(t)?t.map(e):t!==void 0?[e(t)]:[]}function uu(t,e,n=r=>r){return Object.fromEntries(Object.entries(t).map(([r,s])=>[r,n(e(s,r),r)]))}function Jt(t){if(ia(t))return ra(t);let e=structuredClone(t);if(!fe(e))throw new Fh("non-object schemas cannot be converted to a schema",e);"properties"in e&&e.properties&&(e.properties=uu(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]=uu(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"&&(Kt(e[i])?e[i]=cu(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]=cu(o,Jt);}if(Hh(e))switch(e.type){case "string":return cn(e);case "number":return gu(e);case "integer":return yu(e);case "boolean":return Tr(e);case "object":{let{properties:i,...o}=e;return ii(i,o)}case "array":{let{items:i,...o}=e;return bu(i,o)}}return mu(e)}function Bg(){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(Mg.map(t=>[t,e=>Math.min(...e)])),...Object.fromEntries(Fg.map(t=>[t,e=>Math.max(...e)]))}}function qg(t){let e={...Bg(),...t.resolvers};function n(r,s){if(Array.isArray(r)&&Array.isArray(s))return [...new Set([...r,...s])];if(sa(r)&&sa(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):ta(a);}else i[o]=ta(a);return i}return ta(s)}return n}function Jg(t,e={}){let n=e.deep!==false,r=qg(e);function s(i){if(Array.isArray(i))return i.map(s);if(!sa(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(p=>p===false))return false;let l=a.filter(p=>p!==true);if(!l.length)return true;let c=l.reduce((p,y)=>r(p,y),{}),f=Wg(c);if(f!==null)return f;let u={...i};delete u.allOf;let d=r(c,n?s(u):u);return n?s(d):d}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(t)}var na,fu,Q,R,Mn,ti,ln,Fh,Bh,xe,oa,Yh,Xh,Zh,eg,tg,ng,rg,sg,ig,og,ag,lg,cg,ug,fg,dg,pg,mg,hg,gg,yg,bg,wg,Sg,Eg,_g,xg,vg,Cg,Tg,Rg,lu,Ag,ea,St,Cr,Og,mu,$g,Pg,ii,Fn,Ng,Ig,Dg,aa,cn,hu,gu,yu,jg,bu,Tr,ei,wu,Lg,Ug,sa,ta,Mg,Fg,Wg,Kg,Su,Hg,zg,Gg,g,ee=$(()=>{na=(t=[],e="")=>"/"+[e,...t.map(n=>String(n).replace(/\./g,"/"))].filter(Boolean).join("/"),fu=t=>t.split("/").slice(1);Q=(t={},e,n,r)=>({valid:false,errors:[...t.errors??[],{keywordLocation:na([...t.keywordPath??[],e]),instanceLocation:na(t.instancePath),error:typeof n=="string"?n:`Invalid value for ${e}`,data:r}]}),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}},ti=(t={})=>({...t,errors:[]}),ln=class extends Error{constructor(t){super(`Expected ${t}`);}},Fh=class extends Error{constructor(t,e){super(`${t??"Invalid raw schema"}: ${JSON.stringify(e)}`),this.schema=e;}},Bh=class extends Error{constructor(t,e){super(`${t}, got: 'type "${typeof e}": ${JSON.stringify(e)}'`),this.value=e;}},xe=Symbol.for("jsonv-ts:schema");oa=class{constructor(t){this.root=t,this.cache=new Map;}cache;hasRef(t,e){return e!==void 0&&"$ref"in t&&ot(t.$ref)}resolve(t){let e=this.cache.get(t);if(!e){if(e=Mh(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}};Yh=({type:t},e,n={})=>{if(t===void 0||e===void 0)return R();let r,s={string:ot,number:wt,integer:Jh,object:fe,array:Kt,boolean:ia,null:qh};if(Array.isArray(t)){for(let i of t){if(!(i in s))throw new ln(`Unknown type: ${i}`);if(s[i](e))return R()}r=`Expected one of: ${t.join(", ")}`;}else {if(!(t in s))throw new ln(`Unknown type: ${t}`);s[t](e)||(r=`Expected ${t}`);}return r?Q(n,"type",r,e):R()},Xh=({const:t},e,n={})=>vr(t,e)?R():Q(n,"const",`Expected const: ${t}`,e),Zh=({enum:t=[]},e,n={})=>t.some(r=>vr(r,e))?R():Q(n,"enum",`Expected enum: ${JSON.stringify(t)}`,e);eg=({anyOf:t=[]},e,n={})=>ri(t,e,n).length>0?R():Q(n,"anyOf","Expected at least one to match",e),tg=({oneOf:t=[]},e,n={})=>ri(t,e).length===1?R():Q(n,"oneOf","Expected exactly one to match",e),ng=({allOf:t=[]},e,n={})=>ri(t,e,n).length===t.length?R():Q(n,"allOf","Expected all to match",e),rg=({not:t},e,n={})=>e===void 0?R():ve(t)&&t.validate(e,n).valid?Q(n,"not","Expected not to match",e):R(),sg=({if:t,then:e,else:n},r,s={})=>{if(t&&(e||n)){if(t.validate(r,ti(s)).valid)return e?e.validate(r,ti(s)):R();if(n)return n.validate(r,ti(s))}return R()},ig=({pattern:t=""},e,n={})=>{if(!ot(e))return R();if(t instanceof RegExp){if(t.test(e))return R()}else if(new RegExp(t,"u").test(e))return R();return Q(n,"pattern",`Expected string matching pattern ${t}`,e)},og=({minLength:t=0},e,n={})=>ot(e)?[...du(e)].length>=t?R():Q(n,"minLength",`Expected string with minimum length of ${t}`,e):R(),ag=({maxLength:t=0},e,n={})=>ot(e)?[...du(e)].length<=t?R():Q(n,"maxLength",`Expected string with maximum length of ${t}`,e):R(),lg=({multipleOf:t=0},e,n={})=>{if(!wt(e))return R();if(!(Number.isFinite(e)&&Number.isFinite(t))||t<=0)throw new ln("number");let r=e/t,s=Number.EPSILON*Math.max(1,Math.abs(r));return Math.abs(r-Math.round(r))<=s?R():Q(n,"multipleOf",`Expected number being a multiple of ${t}`,e)},cg=({maximum:t=0},e,n={})=>!wt(e)||e<=t?R():Q(n,"maximum",`Expected number less than or equal to ${t}`,e),ug=({exclusiveMaximum:t=0},e,n={})=>!wt(e)||e<t?R():Q(n,"exclusiveMaximum",`Expected number less than ${t}`,e),fg=({minimum:t=0},e,n={})=>!wt(e)||e>=t?R():Q(n,"minimum",`Expected number greater than or equal to ${t}`,e),dg=({exclusiveMinimum:t=0},e,n={})=>!wt(e)||e>t?R():Q(n,"exclusiveMinimum",`Expected number greater than ${t}`,e),pg=({properties:t={}},e,n={})=>{if(!fe(e))return R();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 R()},mg=({properties:t={},additionalProperties:e,patternProperties:n},r,s={})=>{if(!fe(r))return R();if(!ve(e))throw new ln("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(zh(e)){if(e.toJSON()===true)return R();let l=a.reduce((c,f)=>(c[f]=r[f],c),{});return Q(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 R()},hg=({dependentRequired:t},e,n={})=>{if(!fe(e))return R();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 Q(n,"dependentRequired",`Expected dependent required property ${o}`,e)}}return R()},gg=({required:t=[]},e,n={})=>{if(!fe(e))return R();let r=Object.keys(e).filter(s=>typeof e[s]!="function");return t.every(s=>r.includes(s))?R():Q(n,"required",`Expected object with required properties ${t.join(", ")}`,e)},yg=({dependentSchemas:t},e,n={})=>{if(!fe(e))return R();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 R()},bg=({minProperties:t=0},e,n={})=>fe(e)?Object.keys(e).length>=t?R():Q(n,"minProperties",`Expected object with at least ${t} properties`,e):R(),wg=({maxProperties:t=0},e,n={})=>!fe(e)||Object.keys(e).length<=t?R():Q(n,"maxProperties",`Expected object with at most ${t} properties`,e),Sg=({patternProperties:t={}},e,n={})=>{if(!fe(e))return R();if(!fe(t))throw new ln("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 R()},Eg=({propertyNames:t},e,n={})=>{if(!fe(e)||t===void 0)return R();if(!ve(t))throw new ln("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 R()},_g=({items:t,prefixItems:e=[]},n,r={})=>{if(!Kt(n)||t===void 0)return R();if(!ve(t))throw new ln("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 R()},xg=({minItems:t=0},e,n={})=>!Kt(e)||e.length>=t?R():Q(n,"minItems",`Expected array with at least ${t} items`,e),vg=({maxItems:t=0},e,n={})=>!Kt(e)||e.length<=t?R():Q(n,"maxItems",`Expected array with at most ${t} items`,e),Cg=({uniqueItems:t=false},e,n={})=>{if(!Kt(e)||!t)return R();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(vr(s,o))return Q(n,"uniqueItems",`Duplicated items at index ${r} and ${i}`,e)}}return R()},Tg=({contains:t,minContains:e,maxContains:n},r,s={})=>{if(!ve(t))throw new Error("contains must be a managed schema");if(!Kt(r))return R();let i=r.filter(o=>t.validate(o).valid).length;return i<(e??1)?Q(s,e?"minContains":"contains",`Expected array to contain at least ${e??1}, but found ${i}`,r):n!==void 0&&i>n?Q(s,"maxContains",`Expected array to contain at most ${n}, but found ${i}`,r):R()},Rg=({prefixItems:t=[]},e,n={})=>{if(!Kt(e))return R();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 R()},lu={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 f=t.charCodeAt(c);if(c===1&&o===58&&f!==58)return false;if(f>=48&&f<=57){if(++r>4)return false}else if(f===46){if(e>6||n>=3||r===0||i)return false;n++,r=0;}else if(f===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(f>=97&&f<=102||f>=65&&f<=70){if(n>0||++r>4)return false;i=true;}else return false;o=f;}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},Ag=({format:t},e,n={})=>!ot(e)||!t?R():lu[t]?lu[t](e)?R():Q(n,"format",`Expected format: ${t}`,e):R(),ea={type:Yh,const:Xh,enum:Zh,allOf:ng,anyOf:eg,oneOf:tg,not:rg,minLength:og,maxLength:ag,pattern:ig,format:Ag,minimum:fg,exclusiveMinimum:dg,maximum:cg,exclusiveMaximum:ug,multipleOf:lg,required:gg,dependentRequired:hg,dependentSchemas:yg,minProperties:bg,maxProperties:wg,propertyNames:Eg,properties:pg,patternProperties:Sg,additionalProperties:mg,minItems:xg,maxItems:vg,uniqueItems:Cg,contains:Tg,prefixItems:Rg,items:_g,if:sg};St=class{"~standard";[xe];_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[xe]={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:fu(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[xe].raw?.template){let i=this[xe].raw.template(r,e);i!==void 0&&(r=i);}let s=this[xe].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[xe].raw?.validate;if(r!==void 0){let s=r(t,n);if(!s.valid)return s}return kg(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[xe].raw?.coerce;if(r!==void 0)return r(t,n);let s=this[xe].overrides?.coerce?.(t,n)??t;return Qh(this,s,n)}optional(){return this[xe].optional=true,this}isOptional(){return this[xe].optional}getResolver(){return this._resolver||(this._resolver=new oa(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?pu(n):n;if(s.includeSelf!==false&&(yield new Cr(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))}},Cr=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=ni(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}};Og=class extends St{constructor(t){super(),this.bool=t;}toJSON(){return this.bool}validate(t,e){return this.bool?R():Q(e,"","Always fails",t)}};mu=t=>si(t?.type,t),$g=(t,e)=>si(void 0,{...e,const:t}),Pg=class extends St{type="object";properties;required;constructor(t,e){let n=[];for(let[s,i]of Object.entries(t||{}))Gh(ve(i),"properties must be managed schemas",i),i[xe].optional||n.push(s);let r=e?.additionalProperties===false?ra(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 f=ni(o,l);if(c.isOptional()&&i?.withOptional!==true&&f===void 0&&s===void 0)continue;let u=c.template(f,i);u!==void 0&&(a[l]=u);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=pu(s),l=o.length>0&&Object.values(this.properties).every(f=>!f[xe].optional);if(Wh(a)&&(i?.dropUnknown===true||l)&&(a=Vh(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[f,u]of Object.entries(this.properties)){let d=a[f];d!==void 0&&(a[f]=u.coerce(d,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let f=fe(s)?s:{},u=Object.keys(f).filter(d=>!o.includes(d));for(let d of u)a[d]=c?c.coerce(f[d],i):f[d];}return a}}),this.properties=t,this.required=n;}strict(){return this.additionalProperties=ra(false),this[xe].raw.additionalProperties=false,this}partial(){for(let[,t]of Object.entries(this.properties))t[xe].optional=true;return this.required=void 0,this}children(t){let e=[];for(let[n,r]of Object.entries(this.properties)){let s=new Cr(r,t);s.appendInstancePath([n]),s.appendKeywordPath(["properties",n]),e.push(s);}return e}},ii=(t,e)=>new Pg(t,e),Fn=(t,e)=>ii(t,e).strict(),Ng=(t,e)=>ii(t,e).partial(),Ig=class extends St{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 Cr(this.additionalProperties,t);return n.appendKeywordPath(["additionalProperties"]),e.push(n),e}},Dg=(t,e)=>new Ig(t,e),aa=class extends St{type="string";constructor(t){super(t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!ot(e))?"":e,coerce:e=>wt(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}))}},cn=t=>new aa(t),hu=(t,e,n)=>si(t,n,{template:(r,s)=>s?.withExtendedOptional&&(r===void 0||!wt(r))?n?.minimum??0:r,coerce:r=>{if(ot(r)){let s=e.parseFn(r);if(!Number.isNaN(s))return s}return r}}),gu=t=>hu("number",{parseFn:Number},t),yu=t=>hu("integer",{parseFn:Number.parseInt},t),jg=class extends St{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 Cr(this.items,t);n.appendKeywordPath(["items"]),e.push(n);}return e}},bu=(t,e)=>new jg(t,e),Tr=t=>si("boolean",t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!ia(e))?false:e,coerce:e=>{if(ot(e)&&["true","false","1","0"].includes(e))return e==="true"||e==="1";if(wt(e)){if(e===1)return true;if(e===0)return false}return e}}),ei=Symbol.for("unionType"),wu=class extends St{[ei];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=ri(t,r,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(r,s):r}}),this[ei]=e;}get schemas(){return this[this[ei]]}children(t){let e=[];for(let[n,r]of this.schemas.entries()){let s=new Cr(r,t);s.appendKeywordPath([this[ei],n]),e.push(s);}return e}},Lg=(t,e)=>new wu(t,"anyOf",e),Ug=(t,e)=>new wu(t,"oneOf",e);sa=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ta=t=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):JSON.parse(JSON.stringify(t)),Mg=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],Fg=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Wg=t=>t===true||t===false?t:null;Kg=(t,e)=>{let n=JSON.parse(JSON.stringify({...e,allOf:t}));return Jt(Jg(n))},Su=class extends St{$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;}},Hg=(t,e)=>new Su(t,e),zg=t=>new Su(void 0,t),Gg=t=>t(new St({$ref:"#",coerce:(e,n)=>{let r=n?.resolver?.resolve("#");if(!ve(r))throw new Error("Ref not found: #");return r.coerce(e,n)}})),g={boolean:Tr,any:mu,literal:$g,object:ii,strictObject:Fn,partialObject:Ng,record:Dg,string:cn,number:gu,integer:yu,array:bu,anyOf:Lg,oneOf:Ug,allOf:Kg,ref:Hg,refId:zg,recursive:Gg};});var id=ou((OR,nl)=>{var Bi=process||{},rd=Bi.argv||[],Fi=Bi.env||{},mw=!(Fi.NO_COLOR||rd.includes("--no-color"))&&(!!Fi.FORCE_COLOR||rd.includes("--color")||Bi.platform==="win32"||(Bi.stdout||{}).isTTY&&Fi.TERM!=="dumb"||!!Fi.CI),hw=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+gw(s,e,n,i)+e:t+s+e},gw=(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)},sd=(t=mw)=>{let e=t?hw:()=>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")}};nl.exports=sd();nl.exports.createColors=sd;});function $R(t){return ["string","number","boolean"].includes(typeof t)}function PR(t){return [true,false,0,1].includes(t)}function NR(t){return typeof t=="string"}var od=$(()=>{});function DR(...t){return e=>t.reduce((n,r)=>r(n),e)}function jR(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var ad=$(()=>{});function ld(t){return Object.prototype.toString.call(t)==="[object Object]"}function cd(t){return t!==null&&typeof t=="object"}function UR(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function Xt(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:Xt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function yw(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"?[]:{}),yw(t[s],i,n),t)}function MR(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function FR(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 sl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!ld(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:cd(t[r])?sl(t[r],s):t[r]=s);return t}function bw(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&&(!ld(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:cd(t[r])?bw(t[r],s,n):t[r]=s);}return t}function rl(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)=>rl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&rl(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)&&rl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function BR(...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 Gr=$(()=>{});function WR(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function JR(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 ud=$(()=>{});function HR(){try{return !ww()&&global?.process?.release?.name==="node"}catch{return false}}function ww(){try{return typeof Bun<"u"}catch{return false}}function fd(t,e){if(!t)throw new Error(e)}function zR(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function GR(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function VR(t,e){try{return t()}catch{return e}}async function QR(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var YR,dd=$(()=>{YR={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 Vr(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 HT(t,e=true){return (e?Vr(t):t).split(";").filter(Boolean)}function zT(t){let e=[],n="",r=0,s=t.length,i=o=>{Sw(o).length>0&&e.push(o.trim());};for(;r<s;){let o=t[r],a=t[r+1];if(o==="-"&&a==="-"){for(;r<s&&t[r]!==`
14
+ `)}function ZR(t,e=true){return (e?Vr(t):t).split(";").filter(Boolean)}function eA(t){let e=[],n="",r=0,s=t.length,i=o=>{Sw(o).length>0&&e.push(o.trim());};for(;r<s;){let o=t[r],a=t[r+1];if(o==="-"&&a==="-"){for(;r<s&&t[r]!==`
15
15
  `;)n+=t[r],r++;continue}if(o==="/"&&a==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(o==="'"){for(n+=o,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(o==='"'){for(n+=o,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(o==="$"){let l=t.indexOf("$",r+1);if(l!==-1){let c=t.slice(r,l+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(c)){n+=c,r=l+1;let u=t.indexOf(c,r);u===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,u+c.length),r=u+c.length);continue}}}if(o===";"){i(n),n="",r++;continue}n+=o,r++;}return i(n),e}function Sw(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 il(t){return (t??"").trim().toLowerCase()}function ol(t){return (t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function al(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 Qr=$(()=>{});function QT(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 XT(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!g.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 YT(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 ZT(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function ek(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function tk(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function Ew(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function nk(t){return Ew(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function rk(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function P(t,e='"'){return `${e}${t}${e}`}function qi(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 sk(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function pd(t,e,n=.33){if(e.length===0)return null;let r=dd(t),s=[];for(let l of e){let c=_w(r,dd(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),f=c===0?1:1-xw(t.toLowerCase(),l.toLowerCase())/c;f>a&&(a=f,o=l);}return o}function dd(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 _w(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 xw(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 Xr=$(()=>{ee();});function ok(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var md=$(()=>{});function lk(){return crypto.randomUUID()}var hd=$(()=>{});var Yr=$(()=>{id();od();Gr();cd();fd();Qr();Xr();md();hd();});var Sn,Wi=$(()=>{Sn=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 mp={};xr(mp,{AwsClient:()=>Nl,AwsV4Signer:()=>lo});async function as(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Pl.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Pl.encode(e))}async function fp(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Pl.encode(t):t)}function $l(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=dp[s>>>4&15],n+=dp[s&15];}return n}function pp(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function rS(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 [tS[i]||i,o||""]}var Pl,tS,nS,Nl,lo,dp,hp=$(()=>{Pl=new TextEncoder,tS={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"},nS=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Nl=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 lo(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")}},lo=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:f,datetime:u,signQuery:d,appendSessionToken:p,allHeaders:y,singleEncode:h}){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 b,m;(!l||!c)&&([b,m]=rS(this.url,this.headers)),this.service=l||b||"",this.region=c||m||"us-east-1",this.cache=f||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=d,this.appendSessionToken=p||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 w=this.signQuery?this.url.searchParams:this.headers;if(w.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&w.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>y||!nS.has(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
17
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!w.has("X-Amz-Expires")&&w.set("X-Amz-Expires","86400"),w.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),w.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),w.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,"/");h||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=pp(this.encodedPath);let _=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return false;if(this.service==="s3"){if(_.has(S))return false;_.add(S);}return true}).map(S=>S.map(E=>pp(encodeURIComponent(E)))).sort(([S,E],[C,x])=>S<C?-1:S>C?1:E<x?-1:E>x?1:0).map(S=>S.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 as("AWS4"+this.secretAccessKey,e),i=await as(s,this.region),o=await as(i,this.service);r=await as(o,"aws4_request"),this.cache.set(n,r);}return $l(await as(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,$l(await fp(await this.canonicalString()))].join(`
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 il(t){return (t??"").trim().toLowerCase()}function ol(t){return (t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function al(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 Qr=$(()=>{});function rA(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 sA(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!g.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 iA(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 oA(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function aA(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function lA(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function Ew(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function cA(t){return Ew(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function uA(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function P(t,e='"'){return `${e}${t}${e}`}function qi(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 fA(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function md(t,e,n=.33){if(e.length===0)return null;let r=pd(t),s=[];for(let l of e){let c=_w(r,pd(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),f=c===0?1:1-xw(t.toLowerCase(),l.toLowerCase())/c;f>a&&(a=f,o=l);}return o}function pd(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 _w(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 xw(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 Yr=$(()=>{ee();});function pA(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var hd=$(()=>{});function hA(){return crypto.randomUUID()}var gd=$(()=>{});var Xr=$(()=>{od();ad();Gr();ud();dd();Qr();Yr();hd();gd();});var Sn,Wi=$(()=>{Sn=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 hp={};xr(hp,{AwsClient:()=>Nl,AwsV4Signer:()=>lo});async function as(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Pl.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Pl.encode(e))}async function dp(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Pl.encode(t):t)}function $l(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=pp[s>>>4&15],n+=pp[s&15];}return n}function mp(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function rS(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 [tS[i]||i,o||""]}var Pl,tS,nS,Nl,lo,pp,gp=$(()=>{Pl=new TextEncoder,tS={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"},nS=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Nl=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 lo(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")}},lo=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:f,datetime:u,signQuery:d,appendSessionToken:p,allHeaders:y,singleEncode:h}){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 b,m;(!l||!c)&&([b,m]=rS(this.url,this.headers)),this.service=l||b||"",this.region=c||m||"us-east-1",this.cache=f||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=d,this.appendSessionToken=p||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 w=this.signQuery?this.url.searchParams:this.headers;if(w.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&w.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(S=>y||!nS.has(S)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(S=>S+":"+(S==="host"?this.url.host:(this.headers.get(S)||"").replace(/\s+/g," "))).join(`
17
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!w.has("X-Amz-Expires")&&w.set("X-Amz-Expires","86400"),w.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),w.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),w.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,"/");h||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=mp(this.encodedPath);let _=new Set;this.encodedSearch=[...this.url.searchParams].filter(([S])=>{if(!S)return false;if(this.service==="s3"){if(_.has(S))return false;_.add(S);}return true}).map(S=>S.map(E=>mp(encodeURIComponent(E)))).sort(([S,E],[C,x])=>S<C?-1:S>C?1:E<x?-1:E>x?1:0).map(S=>S.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 as("AWS4"+this.secretAccessKey,e),i=await as(s,this.region),o=await as(i,this.service);r=await as(o,"aws4_request"),this.cache.set(n,r);}return $l(await as(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,$l(await dp(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=$l(await fp(this.body||""));}return e}};dp=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var Fm=iu((oI,CE)=>{CE.exports={"dev/vite/main.tsx":{file:"assets/main-BsWx0q9l.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-DexXgo9R.css"]}};});var Nc,Gm,Vm,$o=$(()=>{Nc=(p=>(p.DISABLE_FOREIGN_KEYS="disable_foreign_keys",p.ENABLE_FOREIGN_KEYS="enable_foreign_keys",p.BEGIN_TRANSACTION="begin_transaction",p.COMMIT_TRANSACTION="commit_transaction",p.CREATE_TABLE="create_table",p.ADD_COLUMN="add_column",p.DROP_COLUMN="drop_column",p.ADD_INDEX="add_index",p.DROP_INDEX="drop_index",p.DROP_TABLE="drop_table",p.RENAME_TABLE="rename_table",p.COPY_DATA="copy_data",p.CREATE_TRIGGER="create_trigger",p))(Nc||{}),Gm=class extends Error{constructor(n){super(`Migration would cause data loss:
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=$l(await dp(this.body||""));}return e}};pp=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var Fm=ou((pI,OE)=>{OE.exports={"dev/vite/main.tsx":{file:"assets/main-BsWx0q9l.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-DexXgo9R.css"]}};});var Ic,Gm,Vm,$o=$(()=>{Ic=(p=>(p.DISABLE_FOREIGN_KEYS="disable_foreign_keys",p.ENABLE_FOREIGN_KEYS="enable_foreign_keys",p.BEGIN_TRANSACTION="begin_transaction",p.COMMIT_TRANSACTION="commit_transaction",p.CREATE_TABLE="create_table",p.ADD_COLUMN="add_column",p.DROP_COLUMN="drop_column",p.ADD_INDEX="add_index",p.DROP_INDEX="drop_index",p.DROP_TABLE="drop_table",p.RENAME_TABLE="rename_table",p.COPY_DATA="copy_data",p.CREATE_TRIGGER="create_trigger",p))(Ic||{}),Gm=class extends Error{constructor(n){super(`Migration would cause data loss:
21
21
  ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
22
22
  `)}`);this.warnings=n;this.name="DataLossError";}},Vm=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 on,No=$(()=>{on=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 pr,Dc=$(()=>{Qr();pr=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(h=>h.name)),l=new Set(n.tables.map(h=>h.name));for(let h of n.tables)a.has(h.name)||r.push({type:"added",name:h.name,sql:h.sql});for(let h of e.tables)l.has(h.name)||r.push({type:"removed",name:h.name});for(let h of e.tables){let b=n.tables.find(_=>_.name===h.name);if(!b)continue;let m=ol(h.sql),w=ol(b.sql);m!==w&&r.push({type:"modified",name:h.name,sql:b.sql});}let c=e.tables.filter(h=>l.has(h.name));for(let h of c){let b=e.columns.filter(S=>S.table===h.name),m=n.columns.filter(S=>S.table===h.name),w=new Map(b.map(S=>[S.name,S])),_=new Map(m.map(S=>[S.name,S]));for(let[S,E]of _)w.has(S)||s.push({type:"added",table:h.name,name:S,column:E});for(let[S]of w)_.has(S)||s.push({type:"removed",table:h.name,name:S});for(let[S,E]of w){let C=_.get(S);if(!C)continue;let x={};il(E.type)!==il(C.type)&&(x.type={from:E.type,to:C.type}),E.nullable!==C.nullable&&(x.nullable={from:E.nullable,to:C.nullable}),al(E.default_value)!==al(C.default_value)&&(x.default_value={from:E.default_value,to:C.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:h.name,name:S,changes:x});}}let f=new Map(e.indexes.map(h=>[this.makeIndexKey(h),h])),u=new Map(n.indexes.map(h=>[this.makeIndexKey(h),h]));for(let[h,b]of u)f.has(h)||i.push({type:"added",...b});for(let[h,b]of f)u.has(h)||i.push({type:"removed",...b});let d=new Map(e.foreign_keys.map(h=>[this.makeForeignKeyKey(h),h])),p=new Map(n.foreign_keys.map(h=>[this.makeForeignKeyKey(h),h]));for(let[h,b]of p)d.has(h)||o.push({type:"added",...b});for(let[h,b]of d)p.has(h)||o.push({type:"removed",...b});let y=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:y}}};});var WE,mr,jc=$(()=>{$o();Xr();WE=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],mr=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 u of e.tables.filter(d=>d.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${P(u.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===u.name);for(let p of d){let y=p.unique?"UNIQUE ":"",h=p.columns.map(b=>P(b)).join(", ");i.push({sql:`CREATE ${y}INDEX ${P(p.name)} ON ${P(u.name)} (${h});`,description:`Create index ${P(p.name)} on ${P(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(e.tables.filter(u=>u.type==="modified").map(u=>u.name)),f=[...a].filter(u=>l.has(u));for(let u of f){if(!(c.has(u)||e.columns.some(h=>h.table===u)||e.indexes.some(h=>h.table===u)||e.foreign_keys.some(h=>h.table===u)))continue;let{canAlter:p,addedCols:y}=this.canSimpleAlter(u,e,r);if(p){for(let m of y)i.push({sql:`ALTER TABLE ${P(u)} ADD COLUMN ${this.columnDef(m)};`,description:`Add column ${P(m.name)} to ${P(u)}`,type:"add_column"});let h=e.indexes.filter(m=>m.table===u&&m.type==="added"),b=e.indexes.filter(m=>m.table===u&&m.type==="removed");for(let m of b)i.push({sql:`DROP INDEX IF EXISTS ${P(m.name)};`,description:`Drop index ${P(m.name)}`,type:"drop_index"});for(let m of h){let w=m.unique?"UNIQUE ":"",_=m.columns.map(S=>P(S)).join(", ");i.push({sql:`CREATE ${w}INDEX ${P(m.name)} ON ${P(u)} (${_});`,description:`Create index ${P(m.name)} on ${P(u)}`,type:"add_index"});}}else {let h=this.rebuildTable(u,n,r,e);i.push(...h.steps),o.push(...h.warnings);}}for(let u of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${P(u.name)};`,description:`Drop table ${P(u.name)}`,type:"drop_table"}),o.push({table:u.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(m=>m.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${P(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${P(l)}`,type:"create_table"});let f=n.columns.filter(m=>m.table===e).map(m=>m.name),u=r.columns.filter(m=>m.table===e).map(m=>m.name),d=f.filter(m=>u.includes(m));if(d.length>0){let m=d.map(w=>P(w)).join(", ");i.push({sql:`INSERT INTO ${P(l)} (${m})
23
+ SQL: ${r}`);this.stepIndex=n;this.sql=r;this.cause=s;this.name="MigrationError";}};});var on,No=$(()=>{on=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 pr,jc=$(()=>{Qr();pr=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(h=>h.name)),l=new Set(n.tables.map(h=>h.name));for(let h of n.tables)a.has(h.name)||r.push({type:"added",name:h.name,sql:h.sql});for(let h of e.tables)l.has(h.name)||r.push({type:"removed",name:h.name});for(let h of e.tables){let b=n.tables.find(_=>_.name===h.name);if(!b)continue;let m=ol(h.sql),w=ol(b.sql);m!==w&&r.push({type:"modified",name:h.name,sql:b.sql});}let c=e.tables.filter(h=>l.has(h.name));for(let h of c){let b=e.columns.filter(S=>S.table===h.name),m=n.columns.filter(S=>S.table===h.name),w=new Map(b.map(S=>[S.name,S])),_=new Map(m.map(S=>[S.name,S]));for(let[S,E]of _)w.has(S)||s.push({type:"added",table:h.name,name:S,column:E});for(let[S]of w)_.has(S)||s.push({type:"removed",table:h.name,name:S});for(let[S,E]of w){let C=_.get(S);if(!C)continue;let x={};il(E.type)!==il(C.type)&&(x.type={from:E.type,to:C.type}),E.nullable!==C.nullable&&(x.nullable={from:E.nullable,to:C.nullable}),al(E.default_value)!==al(C.default_value)&&(x.default_value={from:E.default_value,to:C.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:h.name,name:S,changes:x});}}let f=new Map(e.indexes.map(h=>[this.makeIndexKey(h),h])),u=new Map(n.indexes.map(h=>[this.makeIndexKey(h),h]));for(let[h,b]of u)f.has(h)||i.push({type:"added",...b});for(let[h,b]of f)u.has(h)||i.push({type:"removed",...b});let d=new Map(e.foreign_keys.map(h=>[this.makeForeignKeyKey(h),h])),p=new Map(n.foreign_keys.map(h=>[this.makeForeignKeyKey(h),h]));for(let[h,b]of p)d.has(h)||o.push({type:"added",...b});for(let[h,b]of d)p.has(h)||o.push({type:"removed",...b});let y=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:y}}};});var GE,mr,Lc=$(()=>{$o();Yr();GE=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],mr=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 u of e.tables.filter(d=>d.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${P(u.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===u.name);for(let p of d){let y=p.unique?"UNIQUE ":"",h=p.columns.map(b=>P(b)).join(", ");i.push({sql:`CREATE ${y}INDEX ${P(p.name)} ON ${P(u.name)} (${h});`,description:`Create index ${P(p.name)} on ${P(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),l=new Set(r.tables.map(u=>u.name)),c=new Set(e.tables.filter(u=>u.type==="modified").map(u=>u.name)),f=[...a].filter(u=>l.has(u));for(let u of f){if(!(c.has(u)||e.columns.some(h=>h.table===u)||e.indexes.some(h=>h.table===u)||e.foreign_keys.some(h=>h.table===u)))continue;let{canAlter:p,addedCols:y}=this.canSimpleAlter(u,e,r);if(p){for(let m of y)i.push({sql:`ALTER TABLE ${P(u)} ADD COLUMN ${this.columnDef(m)};`,description:`Add column ${P(m.name)} to ${P(u)}`,type:"add_column"});let h=e.indexes.filter(m=>m.table===u&&m.type==="added"),b=e.indexes.filter(m=>m.table===u&&m.type==="removed");for(let m of b)i.push({sql:`DROP INDEX IF EXISTS ${P(m.name)};`,description:`Drop index ${P(m.name)}`,type:"drop_index"});for(let m of h){let w=m.unique?"UNIQUE ":"",_=m.columns.map(S=>P(S)).join(", ");i.push({sql:`CREATE ${w}INDEX ${P(m.name)} ON ${P(u)} (${_});`,description:`Create index ${P(m.name)} on ${P(u)}`,type:"add_index"});}}else {let h=this.rebuildTable(u,n,r,e);i.push(...h.steps),o.push(...h.warnings);}}for(let u of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${P(u.name)};`,description:`Drop table ${P(u.name)}`,type:"drop_table"}),o.push({table:u.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(m=>m.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${P(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${P(l)}`,type:"create_table"});let f=n.columns.filter(m=>m.table===e).map(m=>m.name),u=r.columns.filter(m=>m.table===e).map(m=>m.name),d=f.filter(m=>u.includes(m));if(d.length>0){let m=d.map(w=>P(w)).join(", ");i.push({sql:`INSERT INTO ${P(l)} (${m})
24
24
  SELECT ${m}
25
- FROM ${P(e)};`,description:`Copy data from ${P(e)} to ${P(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${P(e)};`,description:`Drop old table ${P(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${P(l)} RENAME TO ${P(e)};`,description:`Rename ${P(l)} to ${P(e)}`,type:"rename_table"});let p=r.indexes.filter(m=>m.table===e);for(let m of p){let w=m.unique?"UNIQUE ":"",_=m.columns.map(S=>P(S)).join(", ");i.push({sql:`CREATE ${w}INDEX ${P(m.name)} ON ${P(e)} (${_});`,description:`Recreate index ${P(m.name)} on ${P(e)}`,type:"add_index"});}let y=r.triggers?.filter(m=>m.table===e)??[];for(let m of y)i.push({sql:`${m.sql};`,description:`Recreate trigger ${P(m.name)} on ${P(e)}`,type:"create_trigger"});let h=s.columns.filter(m=>m.table===e&&m.type==="removed");for(let m of h)o.push({table:e,reason:`column "${m.name}" will be dropped`});let b=s.columns.filter(m=>m.table===e&&m.type==="modified");for(let m of b)m.changes?.type&&o.push({table:e,reason:`column "${m.name}" type changes from ${m.changes.type.from} to ${m.changes.type.to}`}),m.changes?.nullable&&!m.changes.nullable.to&&o.push({table:e,reason:`column "${m.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(u=>u.table===e),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let d=u.column;return this.hasNonConstantDefault(d.default_value)?false:d.nullable||d.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return WE.includes(n)}columnDef(e){let n=e.column,r=`${P(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function hr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var oh=$(()=>{});function Is(t){if("String"in t)return t.String.sval}function Pn(t){return t.map(Is).filter(e=>e!=null)}function Nn(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function Uo(t){return QuoteUtils.quoteIdentifier(t)}function gr(t){return Object.keys(t)[0]}function ah(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 In=$(()=>{});function ch(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=ZE[e];if(!n)throw new Dn(`Unsupported PostgreSQL type: "${t}"`);return n}function Mo(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Fo(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Bo(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var Dn,N,ZE,lh,e_,qo,yr=$(()=>{In();Dn=class extends Error{},N=class extends Dn{constructor(n,r){super(r??`Unsupported node type: ${gr(n)}`);this.node=n;}},ZE={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"},lh=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];e_={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},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"}},qo=new Map(Object.entries(e_));});var Wo,uh=$(()=>{yr();In();Wo=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=gr(e),r=qo.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 t_,n_,r_,s_,br,Jo,fh=$(()=>{yr();t_=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],n_=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,r_=/^RETURN\s+(NEW|OLD)$/i,s_=/^(INSERT|UPDATE|DELETE)\b/i,br=class extends Dn{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},Jo=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(r_);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(n_);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(s_.test(a)){s.push({type:"dml",sql:a});continue}throw new br(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new Dn("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 br('"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 br("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&&t_.includes(n))throw new br(`"${n}" is not translatable to SQLite`,e)}};});var be,Ft=$(()=>{Wi();be=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 Sn(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});var jn,Ko=$(()=>{Ft();jn=class extends be{get sqliteType(){return "INTEGER"}};});var Ds,Lc=$(()=>{Ko();Ds=class extends jn{constructor(e){super({...e,isSerial:true});}};});function i_(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 js,Uc=$(()=>{Ft();js=class extends be{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(!i_(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ie,tt=$(()=>{Ft();ie=class extends be{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 Ls,Mc=$(()=>{Ft();Ls=class extends be{get sqliteType(){return "BLOB"}};});var Us,Fc=$(()=>{Ft();Us=class extends be{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){return this.isNullish(e)?e:e===1?true:e===0?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 dh(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Ms,Bc=$(()=>{Ft();Ms=class extends be{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=dh(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."):dh(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function o_(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 Fs,qc=$(()=>{tt();Fs=class extends ie{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"||!o_(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function a_(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 Bs,Wc=$(()=>{tt();Bs=class extends ie{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"||!a_(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function l_(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]),f=new Date(Date.UTC(n,r-1,s)),u=f.getUTCFullYear()===n&&f.getUTCMonth()===r-1&&f.getUTCDate()===s,d=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),p=l===null||c!==null&&l<=15&&c<=59;return u&&d&&p}var qs,Jc=$(()=>{tt();qs=class extends ie{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"||!l_(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Ws,Kc=$(()=>{tt();Ws=class extends ie{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 Js,Hc=$(()=>{tt();Js=class extends ie{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 ph(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var wr,zc=$(()=>{Ft();wr=class extends be{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=ph(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=ph(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 mh(t){return u_.test(t.toLowerCase())}var c_,u_,Ks,Gc=$(()=>{tt();c_="????????-????-????-????-????????????",u_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Ks=class extends ie{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${c_}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!mh(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!mh(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function f_(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 d_(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 p_(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function hh(t){let e=f_(t);return e?d_(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:p_(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var Hs,Vc=$(()=>{tt();Hs=class extends ie{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(!hh(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!hh(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var zs,Qc=$(()=>{tt();zs=class extends ie{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 Ln(t,e){if(e?.isArray){let r=Ln(t,{...e,isArray:false});return new wr(t,r)}if(e?.enumValues)return new Js(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=Ln(s);return new wr(t,i)}return h_.has(n)?new Ds(t):m_.has(n)?new jn(t):w_.has(n)?new Us(t):S_.has(n)?new Ms(t):v_.has(n)?new Fs(t):C_.has(n)?new Bs(t):R_.has(n)?new qs(t):T_.has(n)?new Ws(t):b_.has(n)?new Ls(t):g_.has(n)?new js(t,e?.numericPrecision):E_.has(n)?new Ks(t):__.has(n)?new ie(t,63):x_.has(n)?new Hs(t):y_.has(n)?new ie(t,e?.lengthConstraint):new zs(t)}var m_,h_,g_,y_,b_,w_,S_,E_,__,x_,v_,C_,R_,T_,Xc=$(()=>{Ko();Lc();Uc();tt();Mc();Fc();Bc();qc();Wc();Jc();Kc();Hc();zc();Gc();Vc();Qc();m_=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),h_=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),g_=new Set(["float4","real","float8","double precision","numeric","decimal"]),y_=new Set(["text","varchar","character varying","char","character","bpchar"]),b_=new Set(["bytea"]),w_=new Set(["bool","boolean"]),S_=new Set(["json","jsonb"]),E_=new Set(["uuid"]),__=new Set(["name"]),x_=new Set(["inet"]),v_=new Set(["date"]),C_=new Set(["time","timetz","time without time zone","time with time zone"]),R_=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),T_=new Set(["interval"]);});function Yc(t,e="auto"){let n=t.toLowerCase(),r=Ho[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 gh,Ho,Zc=$(()=>{gh="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)))",Ho={gen_random_uuid:{sqlite:()=>gh,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>gh,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 zo,yh=$(()=>{yr();In();In();uh();Yr();fh();$o();Dc();jc();Xr();Xc();Zc();zo=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Jo;introspection;functionResolution;constructor(e,{enums:n,schemaHandling:r,introspection:s,...i}={}){super(e,i),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new Wo(e),this.config=i,this.introspection=s,this.functionResolution=i?.functionResolution??"translate";}visit(e,n){let r=gr(e),s=qo.get(r);if(s){if(s.react==="error")throw new N({[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 N({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new N({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 N({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 N({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=>qi(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new N({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":ch(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,f=false;if(e.typeName){let u=e.typeName.names?.map(y=>y.String?.sval||y.String?.str).filter(Boolean);c=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(c&&Mo(c)),f=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=y=>d[y]?.A_Const?.ival?.ival??d[y]?.A_Const?.val?.ival?.ival;if(c&&Fo(c)&&d.length>0){let y=p(0);typeof y=="number"&&y>0&&(a={maxLen:y});}if(c&&Bo(c)&&d.length>=2){let y=p(0),h=p(1);typeof y=="number"&&typeof h=="number"&&y>0&&h>=0&&(l={precision:y,scale:h});}if(e.constraints){let y=Array.isArray(e.constraints)?e.constraints:[];o=y.some(h=>h.Constraint?.contype==="CONSTR_PRIMARY"),y.some(h=>h.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let u=Array.isArray(e.constraints)?e.constraints:[],d=u.map(y=>this.visit(y,n));r.push(...d.filter(Boolean));let p=u.some(y=>y.Constraint?.contype==="CONSTR_CHECK");i&&o&&!p&&r.push("AUTOINCREMENT");}if(s&&c){let u={isArray:f};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let d=this.enums.get(c.toLowerCase());d&&(u.enumValues=d);let h=Ln({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();h&&r.push(`CHECK (${h})`);}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",Uo(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 (${Nn(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${Nn(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 N({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=Yc(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=Ho[i];if(c?.sqlite){let f=c.sqlite();return f.includes("(")?f:`${f}(${a.join(", ")})`}}}throw new N({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 N({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new N({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 N({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 N({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 N({A_Expr:e},"A_Expr missing left or right expression");if(!lh.includes(r.toUpperCase()))throw new N({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(Uo(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(Uo(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 N({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(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],f=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,f);return `'${JSON.stringify(u).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=Nn(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=Nn(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(f=>"AlterTableCmd"in f&&!s.includes(f.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new N({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 f of i){let u=f.AlterTableCmd.subtype;if(o.includes(u)){let d={...e,cmds:[f]};l.push(super.AlterTableStmt(d,n));}else if(a.includes(u))c.push(f.AlterTableCmd);else throw new N({AlterTableStmt:e},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let f=this.getRelationName(e.relation);l.push(this.generateRebuildSql(f,c));}return l.join(`;
25
+ FROM ${P(e)};`,description:`Copy data from ${P(e)} to ${P(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${P(e)};`,description:`Drop old table ${P(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${P(l)} RENAME TO ${P(e)};`,description:`Rename ${P(l)} to ${P(e)}`,type:"rename_table"});let p=r.indexes.filter(m=>m.table===e);for(let m of p){let w=m.unique?"UNIQUE ":"",_=m.columns.map(S=>P(S)).join(", ");i.push({sql:`CREATE ${w}INDEX ${P(m.name)} ON ${P(e)} (${_});`,description:`Recreate index ${P(m.name)} on ${P(e)}`,type:"add_index"});}let y=r.triggers?.filter(m=>m.table===e)??[];for(let m of y)i.push({sql:`${m.sql};`,description:`Recreate trigger ${P(m.name)} on ${P(e)}`,type:"create_trigger"});let h=s.columns.filter(m=>m.table===e&&m.type==="removed");for(let m of h)o.push({table:e,reason:`column "${m.name}" will be dropped`});let b=s.columns.filter(m=>m.table===e&&m.type==="modified");for(let m of b)m.changes?.type&&o.push({table:e,reason:`column "${m.name}" type changes from ${m.changes.type.from} to ${m.changes.type.to}`}),m.changes?.nullable&&!m.changes.nullable.to&&o.push({table:e,reason:`column "${m.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(u=>u.table===e),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=n.foreign_keys.some(u=>u.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(u=>u.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let d=u.column;return this.hasNonConstantDefault(d.default_value)?false:d.nullable||d.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(e){if(e==null)return false;let n=e.trim().toUpperCase();return GE.includes(n)}columnDef(e){let n=e.column,r=`${P(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function hr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var oh=$(()=>{});function Is(t){if("String"in t)return t.String.sval}function Pn(t){return t.map(Is).filter(e=>e!=null)}function Nn(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function Uo(t){return QuoteUtils.quoteIdentifier(t)}function gr(t){return Object.keys(t)[0]}function ah(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 In=$(()=>{});function ch(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=s_[e];if(!n)throw new Dn(`Unsupported PostgreSQL type: "${t}"`);return n}function Mo(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Fo(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Bo(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var Dn,N,s_,lh,i_,qo,yr=$(()=>{In();Dn=class extends Error{},N=class extends Dn{constructor(n,r){super(r??`Unsupported node type: ${gr(n)}`);this.node=n;}},s_={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"},lh=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];i_={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},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"}},qo=new Map(Object.entries(i_));});var Wo,uh=$(()=>{yr();In();Wo=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=gr(e),r=qo.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 o_,a_,l_,c_,br,Jo,fh=$(()=>{yr();o_=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],a_=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,l_=/^RETURN\s+(NEW|OLD)$/i,c_=/^(INSERT|UPDATE|DELETE)\b/i,br=class extends Dn{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},Jo=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(l_);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(a_);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(c_.test(a)){s.push({type:"dml",sql:a});continue}throw new br(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new Dn("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 br('"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 br("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&&o_.includes(n))throw new br(`"${n}" is not translatable to SQLite`,e)}};});var be,Ft=$(()=>{Wi();be=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 Sn(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});var jn,Ko=$(()=>{Ft();jn=class extends be{get sqliteType(){return "INTEGER"}};});var Ds,Uc=$(()=>{Ko();Ds=class extends jn{constructor(e){super({...e,isSerial:true});}};});function u_(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 js,Mc=$(()=>{Ft();js=class extends be{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(!u_(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ie,tt=$(()=>{Ft();ie=class extends be{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 Ls,Fc=$(()=>{Ft();Ls=class extends be{get sqliteType(){return "BLOB"}};});var Us,Bc=$(()=>{Ft();Us=class extends be{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){return this.isNullish(e)?e:e===1?true:e===0?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 dh(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Ms,qc=$(()=>{Ft();Ms=class extends be{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=dh(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."):dh(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function f_(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 Fs,Wc=$(()=>{tt();Fs=class extends ie{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"||!f_(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function d_(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 Bs,Jc=$(()=>{tt();Bs=class extends ie{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"||!d_(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function p_(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]),f=new Date(Date.UTC(n,r-1,s)),u=f.getUTCFullYear()===n&&f.getUTCMonth()===r-1&&f.getUTCDate()===s,d=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),p=l===null||c!==null&&l<=15&&c<=59;return u&&d&&p}var qs,Kc=$(()=>{tt();qs=class extends ie{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"||!p_(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var Ws,Hc=$(()=>{tt();Ws=class extends ie{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 Js,zc=$(()=>{tt();Js=class extends ie{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 ph(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var wr,Gc=$(()=>{Ft();wr=class extends be{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=ph(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=ph(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 mh(t){return h_.test(t.toLowerCase())}var m_,h_,Ks,Vc=$(()=>{tt();m_="????????-????-????-????-????????????",h_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Ks=class extends ie{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${m_}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!mh(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!mh(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function g_(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 y_(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 b_(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function hh(t){let e=g_(t);return e?y_(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:b_(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var Hs,Qc=$(()=>{tt();Hs=class extends ie{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(!hh(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!hh(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var zs,Yc=$(()=>{tt();zs=class extends ie{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 Ln(t,e){if(e?.isArray){let r=Ln(t,{...e,isArray:false});return new wr(t,r)}if(e?.enumValues)return new Js(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=Ln(s);return new wr(t,i)}return S_.has(n)?new Ds(t):w_.has(n)?new jn(t):v_.has(n)?new Us(t):C_.has(n)?new Ms(t):k_.has(n)?new Fs(t):O_.has(n)?new Bs(t):$_.has(n)?new qs(t):P_.has(n)?new Ws(t):x_.has(n)?new Ls(t):E_.has(n)?new js(t,e?.numericPrecision):T_.has(n)?new Ks(t):R_.has(n)?new ie(t,63):A_.has(n)?new Hs(t):__.has(n)?new ie(t,e?.lengthConstraint):new zs(t)}var w_,S_,E_,__,x_,v_,C_,T_,R_,A_,k_,O_,$_,P_,Xc=$(()=>{Ko();Uc();Mc();tt();Fc();Bc();qc();Wc();Jc();Kc();Hc();zc();Gc();Vc();Qc();Yc();w_=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),S_=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),E_=new Set(["float4","real","float8","double precision","numeric","decimal"]),__=new Set(["text","varchar","character varying","char","character","bpchar"]),x_=new Set(["bytea"]),v_=new Set(["bool","boolean"]),C_=new Set(["json","jsonb"]),T_=new Set(["uuid"]),R_=new Set(["name"]),A_=new Set(["inet"]),k_=new Set(["date"]),O_=new Set(["time","timetz","time without time zone","time with time zone"]),$_=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),P_=new Set(["interval"]);});function Zc(t,e="auto"){let n=t.toLowerCase(),r=Ho[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 gh,Ho,eu=$(()=>{gh="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)))",Ho={gen_random_uuid:{sqlite:()=>gh,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>gh,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}};});function L_(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"&&j_.has(e.objtype)}var j_,zo,yh=$(()=>{yr();In();In();uh();Xr();fh();$o();jc();Lc();Yr();Xc();eu();j_=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);zo=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Jo;introspection;functionResolution;constructor(e,{enums:n,schemaHandling:r,introspection:s,...i}={}){super(e,i),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new Wo(e),this.config=i,this.introspection=s,this.functionResolution=i?.functionResolution??"translate";}visit(e,n){let r=gr(e);if(r==="GrantStmt"&&L_(e))return "";let s=qo.get(r);if(s){if(s.react==="error")throw new N({[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 N({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new N({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 N({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 N({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=>qi(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new N({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":ch(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,f=false;if(e.typeName){let u=e.typeName.names?.map(y=>y.String?.sval||y.String?.str).filter(Boolean);c=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(c&&Mo(c)),f=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=y=>d[y]?.A_Const?.ival?.ival??d[y]?.A_Const?.val?.ival?.ival;if(c&&Fo(c)&&d.length>0){let y=p(0);typeof y=="number"&&y>0&&(a={maxLen:y});}if(c&&Bo(c)&&d.length>=2){let y=p(0),h=p(1);typeof y=="number"&&typeof h=="number"&&y>0&&h>=0&&(l={precision:y,scale:h});}if(e.constraints){let y=Array.isArray(e.constraints)?e.constraints:[];o=y.some(h=>h.Constraint?.contype==="CONSTR_PRIMARY"),y.some(h=>h.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let u=Array.isArray(e.constraints)?e.constraints:[],d=u.map(y=>this.visit(y,n));r.push(...d.filter(Boolean));let p=u.some(y=>y.Constraint?.contype==="CONSTR_CHECK");i&&o&&!p&&r.push("AUTOINCREMENT");}if(s&&c){let u={isArray:f};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let d=this.enums.get(c.toLowerCase());d&&(u.enumValues=d);let h=Ln({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();h&&r.push(`CHECK (${h})`);}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",Uo(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 (${Nn(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${Nn(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 N({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=Zc(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=Ho[i];if(c?.sqlite){let f=c.sqlite();return f.includes("(")?f:`${f}(${a.join(", ")})`}}}throw new N({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 N({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new N({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 N({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 N({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 N({A_Expr:e},"A_Expr missing left or right expression");if(!lh.includes(r.toUpperCase()))throw new N({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(Uo(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(Uo(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 N({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(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],f=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,f);return `'${JSON.stringify(u).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=Nn(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=Nn(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(f=>"AlterTableCmd"in f&&!s.includes(f.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new N({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 f of i){let u=f.AlterTableCmd.subtype;if(o.includes(u)){let d={...e,cmds:[f]};l.push(super.AlterTableStmt(d,n));}else if(a.includes(u))c.push(f.AlterTableCmd);else throw new N({AlterTableStmt:e},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let f=this.getRelationName(e.relation);l.push(this.generateRebuildSql(f,c));}return l.join(`;
26
26
  `)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new N({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 N({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new N({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new N({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=Nn(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new N({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new N({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new N({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 N({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=Nn(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new N({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 N({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 N({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new N({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 N({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 N({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 N({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(u=>u.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 N({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 u=e.columns.map(d=>d.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),f=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...f.map(u=>` ${u};`),"END"].join(`
27
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}}translateDml(e,n){return 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 N({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 N({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new N({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 N({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 pr,i=new mr,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(u=>u.name===n);if(r===-1)return;let s=e.columns.filter(u=>u.table===n),i=e.foreign_keys.filter(u=>u.table===n),o=e.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let d=`${P(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(d+=" PRIMARY KEY"),u.nullable||(d+=" NOT NULL"),u.default_value!=null&&(d+=` DEFAULT ${u.default_value}`),d}),l=i.map(u=>`FOREIGN KEY (${P(u.column)}) REFERENCES ${P(u.ref_table)}(${P(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),f=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${P(n)} (${f.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}};});var Qe,Un,eu=$(()=>{In();yr();Qe=class extends N{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},Un=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 Qe({[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 Qe({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?Is(n):void 0;if(!r)throw new Qe({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 Qe({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]?Is(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 Qe({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 Qe({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 Qe({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let d of e.targetList??[]){let p="ResTarget"in d?d.ResTarget:void 0;if(p?.val){let y=this.deparseValue(p.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),f=this.deparseGroupClause(e.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),f.length>0&&(u.group=f),u}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new Qe({FuncCall:e},`FuncCall: ${Pn(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=Pn(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 Qe({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new Qe({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 f=2;for(;`${c}_${f}`in n;)f++;c=`${c}_${f}`;}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=Pn(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]?Is(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}}};});var Gs,bh=$(()=>{Gs=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 wh=$(()=>{Ft();Wi();Ko();Lc();Uc();tt();Mc();Fc();Bc();qc();Wc();Jc();Kc();Hc();zc();Gc();Vc();Qc();Xc();Zc();bh();});function Eh(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=Pn(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=Pn(r.vals);e.set(s.toLowerCase(),i);}return e}function _h(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=ah(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function xh(t){let e=new Un,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",f=i.permissive===true,u=[],d=false;for(let b of i.roles??[])if("RoleSpec"in b){let m=b.RoleSpec;m.roletype==="ROLESPEC_PUBLIC"?m.location===-1&&(d=true):m.roletype==="ROLESPEC_CSTRING"&&m.rolename&&u.push(m.rolename);}if(d){let b=a?`${a}.${o}`:o,m=i.policy_name??"",w=`${b}::${m}`;Sh.has(w)||(Sh.add(w),console.warn(`[supalite] policy "${m}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let p=i.qual?e.deparse(i.qual):void 0,y=i.with_check?e.deparse(i.with_check):void 0,h=new on({name:i.policy_name??"",table:o,schema:a,command:c,permissive:f,roles:u,using:p,withCheck:y});r.push(h);}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 vh(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 Gs(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,f=c.colname;if(!f)continue;let u=c.typeName?.names?.map(I=>I.String?.sval||I.String?.str).filter(Boolean),d=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!d)continue;let p=!!c.typeName?.arrayBounds?.length,y=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],h=I=>y[I]?.A_Const?.ival?.ival??y[I]?.A_Const?.val?.ival?.ival,b={isArray:p};if(Fo(d)&&y.length>0){let I=h(0);typeof I=="number"&&I>0&&(b.lengthConstraint=I);}if(Bo(d)&&y.length>=2){let I=h(0),ue=h(1);typeof I=="number"&&typeof ue=="number"&&I>0&&ue>=0&&(b.numericPrecision={precision:I,scale:ue});}let m=e.get(d.toLowerCase());m&&(b.enumValues=m);let w=Array.isArray(c.constraints)?c.constraints:[],_=w.some(I=>I.Constraint?.contype==="CONSTR_PRIMARY"),S=Mo(d)||w.some(I=>I.Constraint?.contype==="CONSTR_IDENTITY"),E=w.some(I=>I.Constraint?.contype==="CONSTR_NOTNULL"),C=w.find(I=>I.Constraint?.contype==="CONSTR_UNIQUE"),x=w.find(I=>I.Constraint?.contype==="CONSTR_GENERATED"),R=w.find(I=>I.Constraint?.contype==="CONSTR_FOREIGN"),v=w.find(I=>I.Constraint?.contype==="CONSTR_CHECK"),k;if(R){let I=R.Constraint,ue=I.pktable?.relname,Xe=I.pktable?.schemaname,Qs=I.pk_attrs?.[0]?.String?.sval;ue&&Qs&&(k={refSchema:Xe,refTable:ue,refColumn:Qs,constraintName:I.conname||void 0});}let z={schema:o,table:i,column:f,pgTypeName:d,nullable:!E&&!_,defaultValue:null,defaultFn:null,isPrimaryKey:_,isUnique:!!C,isSerial:S,isGenerated:!!x,fkRef:k,hasCheck:!!v,checkConstraintName:v?.Constraint?.conname||void 0,uniqueConstraintName:C?.Constraint?.conname||void 0};a.set(f,Ln(z,b));}n.set(`${o}.${i}`,a);}return n}function Ch(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 f=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(f.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:f});}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 f=(l.fk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:f,refSchema:l.pktable?.schemaname,refTable:d,refColumns:u});}}}return e}function Rh(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 Sh,Th=$(()=>{eu();In();No();wh();yr();Sh=new Set;});var Oh={};xr(Oh,{Policy:()=>on,deparseDdl:()=>tu,deparseExpression:()=>N_,deparsePostgresDdl:()=>P_,deparseSelect:()=>I_,parse:()=>hr,parseExpression:()=>Ah,translatePostgresDdl:()=>kh});async function kh(t,e={}){let n=await hr(t);return tu(n,e).ddl}async function P_(t,e={}){let n=await hr(t);return {ast:n,...tu(n,e)}}function tu(t,e={}){let n=Eh(t),r=vh(t,n),s=_h(t),i=Ch(t),o=Rh(t),a=new zo(t,{...e,enums:n}),{policies:l,tables:c}=xh(t);if(e.strict)for(let f of l){if(!r.get(`${f.data.schema??"public"}.${f.data.table}`))throw new Error(`Policy "${f.data.name}" references unknown table "${f.data.table}"`);if(!c.has(f.data.table))throw new Error(`RLS is not enabled on table "${f.data.table}"`)}return {ddl:a.deparseQuery(),enums:n,rls:{tables:c,policies:l},schema:r,vars:s,tableConstraints:i,comments:o}}async function Ah(t){let n=(await hr(`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 N_(t){let e=await Ah(t);return new Un().deparse(e)}async function I_(t){let n=(await hr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new Un().deparse(n)}var nu=$(()=>{oh();yh();eu();Th();No();});ee();function Su(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 Eu(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Su(Object(n),true).forEach(function(r){Vg(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Su(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function Vg(t,e,n){return e=Qg(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function Qg(t){var e=Xg(t,"string");return typeof e=="symbol"?e:String(e)}function Xg(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 Yg=_u({}),Le=Yg;function _u(t){return e.withOptions=n=>_u(Eu(Eu({},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 u=0;u<s.length;u++){let d=s[u];if(o&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=d,u<r.length){let p=i?Zg(r[u],l):r[u];l+=p;}}let c=l.split(`
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(u=>u.name===n);if(r===-1)return;let s=e.columns.filter(u=>u.table===n),i=e.foreign_keys.filter(u=>u.table===n),o=e.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let d=`${P(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(d+=" PRIMARY KEY"),u.nullable||(d+=" NOT NULL"),u.default_value!=null&&(d+=` DEFAULT ${u.default_value}`),d}),l=i.map(u=>`FOREIGN KEY (${P(u.column)}) REFERENCES ${P(u.ref_table)}(${P(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),f=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${P(n)} (${f.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}};});var Qe,Un,tu=$(()=>{In();yr();Qe=class extends N{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},Un=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 Qe({[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 Qe({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?Is(n):void 0;if(!r)throw new Qe({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 Qe({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]?Is(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 Qe({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 Qe({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 Qe({SubLink:e},`SubLink type: ${e.subLinkType}`)}SelectStmt(e){let{from:n,schema:r,join:s}=this.deparseFromClause(e.fromClause??[]),i=[];for(let d of e.targetList??[]){let p="ResTarget"in d?d.ResTarget:void 0;if(p?.val){let y=this.deparseValue(p.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),f=this.deparseGroupClause(e.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),f.length>0&&(u.group=f),u}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;throw new Qe({FuncCall:e},`FuncCall: ${Pn(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=Pn(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 Qe({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new Qe({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 f=2;for(;`${c}_${f}`in n;)f++;c=`${c}_${f}`;}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=Pn(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]?Is(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}}};});var Gs,bh=$(()=>{Gs=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 wh=$(()=>{Ft();Wi();Ko();Uc();Mc();tt();Fc();Bc();qc();Wc();Jc();Kc();Hc();zc();Gc();Vc();Qc();Yc();Xc();eu();bh();});function Eh(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=Pn(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=Pn(r.vals);e.set(s.toLowerCase(),i);}return e}function _h(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=ah(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function xh(t){let e=new Un,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",f=i.permissive===true,u=[],d=false;for(let b of i.roles??[])if("RoleSpec"in b){let m=b.RoleSpec;m.roletype==="ROLESPEC_PUBLIC"?m.location===-1&&(d=true):m.roletype==="ROLESPEC_CSTRING"&&m.rolename&&u.push(m.rolename);}if(d){let b=a?`${a}.${o}`:o,m=i.policy_name??"",w=`${b}::${m}`;Sh.has(w)||(Sh.add(w),console.warn(`[supalite] policy "${m}" on "${b}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`));}let p=i.qual?e.deparse(i.qual):void 0,y=i.with_check?e.deparse(i.with_check):void 0,h=new on({name:i.policy_name??"",table:o,schema:a,command:c,permissive:f,roles:u,using:p,withCheck:y});r.push(h);}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 vh(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 Gs(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,f=c.colname;if(!f)continue;let u=c.typeName?.names?.map(I=>I.String?.sval||I.String?.str).filter(Boolean),d=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!d)continue;let p=!!c.typeName?.arrayBounds?.length,y=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],h=I=>y[I]?.A_Const?.ival?.ival??y[I]?.A_Const?.val?.ival?.ival,b={isArray:p};if(Fo(d)&&y.length>0){let I=h(0);typeof I=="number"&&I>0&&(b.lengthConstraint=I);}if(Bo(d)&&y.length>=2){let I=h(0),ue=h(1);typeof I=="number"&&typeof ue=="number"&&I>0&&ue>=0&&(b.numericPrecision={precision:I,scale:ue});}let m=e.get(d.toLowerCase());m&&(b.enumValues=m);let w=Array.isArray(c.constraints)?c.constraints:[],_=w.some(I=>I.Constraint?.contype==="CONSTR_PRIMARY"),S=Mo(d)||w.some(I=>I.Constraint?.contype==="CONSTR_IDENTITY"),E=w.some(I=>I.Constraint?.contype==="CONSTR_NOTNULL"),C=w.find(I=>I.Constraint?.contype==="CONSTR_UNIQUE"),x=w.find(I=>I.Constraint?.contype==="CONSTR_GENERATED"),T=w.find(I=>I.Constraint?.contype==="CONSTR_FOREIGN"),v=w.find(I=>I.Constraint?.contype==="CONSTR_CHECK"),A;if(T){let I=T.Constraint,ue=I.pktable?.relname,Ye=I.pktable?.schemaname,Qs=I.pk_attrs?.[0]?.String?.sval;ue&&Qs&&(A={refSchema:Ye,refTable:ue,refColumn:Qs,constraintName:I.conname||void 0});}let z={schema:o,table:i,column:f,pgTypeName:d,nullable:!E&&!_,defaultValue:null,defaultFn:null,isPrimaryKey:_,isUnique:!!C,isSerial:S,isGenerated:!!x,fkRef:A,hasCheck:!!v,checkConstraintName:v?.Constraint?.conname||void 0,uniqueConstraintName:C?.Constraint?.conname||void 0};a.set(f,Ln(z,b));}n.set(`${o}.${i}`,a);}return n}function Ch(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 f=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(f.length===0)continue;e.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:f});}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 f=(l.fk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;e.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:f,refSchema:l.pktable?.schemaname,refTable:d,refColumns:u});}}}return e}function Th(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 Sh,Rh=$(()=>{tu();In();No();wh();yr();Sh=new Set;});var Oh={};xr(Oh,{Policy:()=>on,deparseDdl:()=>nu,deparseExpression:()=>F_,deparsePostgresDdl:()=>M_,deparseSelect:()=>B_,parse:()=>hr,parseExpression:()=>kh,translatePostgresDdl:()=>Ah});async function Ah(t,e={}){let n=await hr(t);return nu(n,e).ddl}async function M_(t,e={}){let n=await hr(t);return {ast:n,...nu(n,e)}}function nu(t,e={}){let n=Eh(t),r=vh(t,n),s=_h(t),i=Ch(t),o=Th(t),a=new zo(t,{...e,enums:n}),{policies:l,tables:c}=xh(t);if(e.strict)for(let f of l){if(!r.get(`${f.data.schema??"public"}.${f.data.table}`))throw new Error(`Policy "${f.data.name}" references unknown table "${f.data.table}"`);if(!c.has(f.data.table))throw new Error(`RLS is not enabled on table "${f.data.table}"`)}return {ddl:a.deparseQuery(),enums:n,rls:{tables:c,policies:l},schema:r,vars:s,tableConstraints:i,comments:o}}async function kh(t){let n=(await hr(`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 F_(t){let e=await kh(t);return new Un().deparse(e)}async function B_(t){let n=(await hr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new Un().deparse(n)}var ru=$(()=>{oh();yh();tu();Rh();No();});ee();function Eu(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 _u(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Eu(Object(n),true).forEach(function(r){Vg(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Eu(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function Vg(t,e,n){return e=Qg(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function Qg(t){var e=Yg(t,"string");return typeof e=="symbol"?e:String(e)}function Yg(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 Xg=xu({}),Le=Xg;function xu(t){return e.withOptions=n=>xu(_u(_u({},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 u=0;u<s.length;u++){let d=s[u];if(o&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=d,u<r.length){let p=i?Zg(r[u],l):r[u];l+=p;}}let c=l.split(`
29
29
  `),f=null;for(let u of c){let d=u.match(/^(\s+)\S+/);if(d){let p=d[1].length;f?f=Math.min(f,p):f=p;}}if(f!==null){let u=f;l=c.map(d=>d[0]===" "||d[0]===" "?d.slice(u):d).join(`
30
30
  `);}return a&&(l=l.trim()),o&&(l=l.replace(/\\n/g,`
31
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,(u,d)=>String.fromCharCode(parseInt(d,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(u,d)=>String.fromCodePoint(parseInt(d,16))).replace(/\\u([\da-fA-F]{4})/g,(u,d)=>String.fromCharCode(parseInt(d,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(u,d,p)=>{var y;let h=(y=d??p)!==null&&y!==void 0?y:"";return String.fromCodePoint(parseInt(h,16))})),l}}function Zg(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}ee();var xu=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ai=["analytics"],vu=g.strictObject({enabled:g.boolean({default:false,description:"Enable the local Logflare service.",tags:ai,links:xu}),port:g.number({default:54327,description:"Port to the local Logflare service.",tags:ai}),vector_port:g.number({default:54328,description:"Port to the local syslog ingest service.",tags:ai}),backend:g.string({enum:["postgres","bigquery"],default:"postgres",description:Le`
34
+ ${s}`)}return t}ee();var vu=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ai=["analytics"],Cu=g.strictObject({enabled:g.boolean({default:false,description:"Enable the local Logflare service.",tags:ai,links:vu}),port:g.number({default:54327,description:"Port to the local Logflare service.",tags:ai}),vector_port:g.number({default:54328,description:"Port to the local syslog ingest service.",tags:ai}),backend:g.string({enum:["postgres","bigquery"],default:"postgres",description:Le`
35
35
  Configure one of the supported backends:
36
36
 
37
37
  - \`postgres\`
38
- - \`bigquery\``,tags:ai,links:xu})}).partial();ee();var ey=Symbol.for("lite-only"),Ht=t=>(Object.defineProperty(t,ey,{value:true,enumerable:false,writable:false,configurable:false}),t);var at=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Ke=["api"],Cu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local PostgREST service.",tags:Ke,links:at}),port:g.number({default:54321,description:"Port to use for the API URL.",tags:Ke,links:at}),schemas:g.array(g.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:Ke,links:at}),{default:["public","storage","graphql_public"]}),extra_search_path:g.array(g.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Ke,links:at}),{default:["public","extensions"]}),max_rows:g.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:Ke,links:at}),pg_safe_update:g.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Ke,links:at}),plan_enabled:Ht(g.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:Ke,links:at})),aggregates_enabled:Ht(g.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:Ke,links:at})),limited_mutations_enabled:Ht(g.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:Ke,links:at})),anonymous_enabled:Ht(g.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:Ke,links:at})),tls:g.strictObject({enabled:g.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Ke})}).partial(),external_url:g.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Ke})}).partial();ee();ee();var un=["auth"],fn={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Tr=(t,e)=>g.strictObject({subject:g.string({default:e,description:`The subject of the ${t} email.`}),content_path:g.string({description:`The path to the content of the ${t} email.`})}).partial(),Ru=g.strictObject({enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:un,links:[fn.auth]}),double_confirm_changes:g.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:un,links:[fn.auth]}),enable_confirmations:g.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:un,links:[fn.auth]}),secure_password_change:g.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:un,links:[fn.auth]}),max_frequency:g.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:un,links:[fn.auth]}),smtp:g.strictObject({host:g.string({default:"inbucket",description:"Hostname or IP address of the SMTP server."}),port:g.number({default:2500,description:"Port number of the SMTP server."}),user:g.string({description:"Username for authenticating with the SMTP server."}),pass:g.string({description:"Password for authenticating with the SMTP server."}),admin_email:g.string({default:"admin@email.com",description:"Email used as the sender for emails sent from the application."}),sender_name:g.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:g.strictObject({invite:Tr("invite","You have been invited"),confirmation:Tr("confirmation","Confirm Your Signup"),recovery:Tr("recovery","Reset Your Password"),magic_link:Tr("magic link","Your Magic Link"),email_change:Tr("email change","Confirm Email Change")}).partial(),otp_length:g.number({default:6,description:"Number of characters used in the email OTP.",tags:un,links:[fn.auth]}),otp_expiry:g.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:un,links:[fn.auth]})}).partial();ee();var li=["auth"],la=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),kr=(t,e)=>g.strictObject({enabled:g.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:li,links:[la(t,e)]}),uri:g.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:li,links:[la(t,e)]}),secrets:g.array(g.string({description:"A secret to pass to the function or endpoint.",tags:li}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:li,links:[la(t,e)]})}).partial(),Tu=g.strictObject({mfa_verification_attempt:kr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:kr("Password Verification Hook","password-verification-hook"),custom_access_token:kr("Custom Access Token Hook","custom-access-token-hook"),send_sms:kr("Send SMS Hook","send-sms-hook"),send_email:kr("Send Email Hook","send-email-hook")}).partial();ee();var zt=["auth"],Gt={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"}},ku=g.strictObject({totp:g.strictObject({enroll_enabled:g.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:zt,links:[Gt.totp]}),verify_enabled:g.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:zt,links:[Gt.totp]})}).partial(),phone:g.strictObject({enroll_enabled:g.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:zt,links:[Gt.phone]}),verify_enabled:g.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:zt,links:[Gt.phone]}),otp_length:g.number({default:6,description:"The length of the OTP code.",tags:zt,links:[Gt.phone]}),template:g.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:zt,links:[Gt.phone]}),max_frequency:g.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:zt,links:[Gt.phone]})}).partial(),max_enrolled_factors:g.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:zt,links:[Gt.mfa]})}).partial();ee();ee();var ca=class extends aa{},Et=t=>new ca(t);var Bn=["auth"],de=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return g.strictObject({enabled:g.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Bn,links:e}),client_id:g.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Bn,links:e}),secret:Et({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:Le`
38
+ - \`bigquery\``,tags:ai,links:vu})}).partial();ee();var ey=Symbol.for("lite-only"),Ht=t=>(Object.defineProperty(t,ey,{value:true,enumerable:false,writable:false,configurable:false}),t);var at=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Ke=["api"],Tu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local PostgREST service.",tags:Ke,links:at}),port:g.number({default:54321,description:"Port to use for the API URL.",tags:Ke,links:at}),schemas:g.array(g.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:Ke,links:at}),{default:["public","storage","graphql_public"]}),extra_search_path:g.array(g.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Ke,links:at}),{default:["public","extensions"]}),max_rows:g.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:Ke,links:at}),pg_safe_update:g.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Ke,links:at}),plan_enabled:Ht(g.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:Ke,links:at})),aggregates_enabled:Ht(g.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:Ke,links:at})),limited_mutations_enabled:Ht(g.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:Ke,links:at})),anonymous_enabled:Ht(g.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:Ke,links:at})),tls:g.strictObject({enabled:g.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Ke})}).partial(),external_url:g.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Ke})}).partial();ee();ee();var un=["auth"],fn={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Rr=(t,e)=>g.strictObject({subject:g.string({default:e,description:`The subject of the ${t} email.`}),content_path:g.string({description:`The path to the content of the ${t} email.`})}).partial(),Ru=g.strictObject({enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:un,links:[fn.auth]}),double_confirm_changes:g.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:un,links:[fn.auth]}),enable_confirmations:g.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:un,links:[fn.auth]}),secure_password_change:g.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:un,links:[fn.auth]}),max_frequency:g.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:un,links:[fn.auth]}),smtp:g.strictObject({host:g.string({default:"inbucket",description:"Hostname or IP address of the SMTP server."}),port:g.number({default:2500,description:"Port number of the SMTP server."}),user:g.string({description:"Username for authenticating with the SMTP server."}),pass:g.string({description:"Password for authenticating with the SMTP server."}),admin_email:g.string({default:"admin@email.com",description:"Email used as the sender for emails sent from the application."}),sender_name:g.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:g.strictObject({invite:Rr("invite","You have been invited"),confirmation:Rr("confirmation","Confirm Your Signup"),recovery:Rr("recovery","Reset Your Password"),magic_link:Rr("magic link","Your Magic Link"),email_change:Rr("email change","Confirm Email Change")}).partial(),otp_length:g.number({default:6,description:"Number of characters used in the email OTP.",tags:un,links:[fn.auth]}),otp_expiry:g.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:un,links:[fn.auth]})}).partial();ee();var li=["auth"],la=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),Ar=(t,e)=>g.strictObject({enabled:g.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:li,links:[la(t,e)]}),uri:g.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:li,links:[la(t,e)]}),secrets:g.array(g.string({description:"A secret to pass to the function or endpoint.",tags:li}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:li,links:[la(t,e)]})}).partial(),Au=g.strictObject({mfa_verification_attempt:Ar("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:Ar("Password Verification Hook","password-verification-hook"),custom_access_token:Ar("Custom Access Token Hook","custom-access-token-hook"),send_sms:Ar("Send SMS Hook","send-sms-hook"),send_email:Ar("Send Email Hook","send-email-hook")}).partial();ee();var zt=["auth"],Gt={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"}},ku=g.strictObject({totp:g.strictObject({enroll_enabled:g.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:zt,links:[Gt.totp]}),verify_enabled:g.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:zt,links:[Gt.totp]})}).partial(),phone:g.strictObject({enroll_enabled:g.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:zt,links:[Gt.phone]}),verify_enabled:g.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:zt,links:[Gt.phone]}),otp_length:g.number({default:6,description:"The length of the OTP code.",tags:zt,links:[Gt.phone]}),template:g.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:zt,links:[Gt.phone]}),max_frequency:g.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:zt,links:[Gt.phone]})}).partial(),max_enrolled_factors:g.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:zt,links:[Gt.mfa]})}).partial();ee();ee();var ca=class extends aa{},Et=t=>new ca(t);var Bn=["auth"],de=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return g.strictObject({enabled:g.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Bn,links:e}),client_id:g.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Bn,links:e}),secret:Et({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:g.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Bn,links:e}),redirect_uri:g.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:g.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Bn,links:e})}).partial()},Au=g.strictObject({apple:de({id:"apple",name:"Apple"}),azure:de({id:"azure",name:"Azure"}),bitbucket:de({id:"bitbucket",name:"Bitbucket"}),discord:de({id:"discord",name:"Discord"}),facebook:de({id:"facebook",name:"Facebook"}),github:de({id:"github",name:"GitHub"}),gitlab:de({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:de({id:"google",name:"Google"}),kakao:de({id:"kakao",name:"Kakao"}),keycloak:de({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:de({id:"linkedin",name:"LinkedIn"}),notion:de({id:"notion",name:"Notion"}),twitch:de({id:"twitch",name:"Twitch"}),twitter:de({id:"twitter",name:"Twitter"}),slack:de({id:"slack",name:"Slack"}),spotify:de({id:"spotify",name:"Spotify"}),workos:de({id:"workos",name:"WorkOS"}),zoom:de({id:"zoom",name:"Zoom"})}).partial();ee();var ua=["auth"],fa=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],Ou=g.strictObject({timebox:g.string({description:"The timebox for the user session.",tags:ua,links:fa}),inactivity_timeout:g.string({description:"The inactivity timeout for the user session.",tags:ua,links:fa}),single_per_user:g.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:ua,links:fa})}).partial();ee();var te=["auth"],se={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`})},$u=g.strictObject({enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:te,links:[se.auth]}),enable_confirmations:g.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:te,links:[se.auth]}),template:g.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:te,links:[se.auth]}),max_frequency:g.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:te}),twilio:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:te,links:[se.phoneLogin("Twilio")]}),account_sid:g.string({description:"The account SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),message_service_sid:g.string({description:"The message service SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),auth_token:g.string({description:"The auth token for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]})}).partial(),twilio_verify:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:te,links:[se.phoneLogin("Twilio")]}),account_sid:g.string({description:"The account SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),message_service_sid:g.string({description:"The message service SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),auth_token:g.string({description:"The auth token for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]})}).partial(),messagebird:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:te,links:[se.phoneLogin("MessageBird")]}),originator:g.string({description:"The originator of the SMS message.",tags:te,links:[se.phoneLogin("MessageBird")]}),api_key:g.string({description:"The API key for the MessageBird API.",tags:te,links:[se.phoneLogin("MessageBird")]})}).partial(),textlocal:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:g.string({description:"The sender of the SMS message.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:g.string({description:"The API key for the Textlocal API.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:te,links:[se.phoneLogin("Vonage")]}),from:g.string({description:"The sender of the SMS message.",tags:te,links:[se.phoneLogin("Vonage")]}),api_key:g.string({description:"The API key for the Vonage API.",tags:te,links:[se.phoneLogin("Vonage")]}),api_secret:g.string({description:"The API secret for the Vonage API.",tags:te,links:[se.phoneLogin("Vonage")]})}).partial(),test_otp:g.record(g.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:te,links:[se.auth]})}).partial();var Ue=["auth"],He={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Pu=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],Nu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local GoTrue service.",tags:Ue,links:[He.auth]}),jwt_secret:g.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Ue,links:[He.auth]}),site_url:g.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:Ue,links:[He.auth]}),additional_redirect_urls:g.array(g.string({description:"A URL that auth providers are permitted to redirect to.",tags:Ue}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Ue,links:[He.auth]}),jwt_expiry:g.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Ue,links:[He.auth]}),enable_refresh_token_rotation:g.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Ue,links:[He.auth]}),refresh_token_reuse_interval:g.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:Ue,links:[He.auth]}),enable_manual_linking:g.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Ue,links:[He.auth]}),enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Ue,links:[He.auth]}),enable_anonymous_sign_ins:g.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Ue,links:[He.auth]}),minimum_password_length:g.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Ue,links:[He.auth]}),password_requirements:g.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${Pu.join(", ")}`,enum:["",...Pu],tags:Ue,links:[He.auth]}),hook:Tu,mfa:ku,sessions:Ou,email:Ru,sms:$u,external:Au}).partial();ee();var dn={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}`:""}`})},Ce=["database"],Iu=g.object({driver:Ht(g.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite",description:"The database driver to use.",tags:Ce})),url:Ht(g.string({description:"Path to the database file/directory (Supalite only).",tags:Ce})),port:g.number({default:54322,description:"Port to use for the local database URL.",tags:Ce,links:[dn.postgres]}),shadow_port:g.number({default:54320,description:"Port to use for the local shadow database.",tags:Ce}),major_version:g.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:Ce,links:[dn.postgres]}),pooler:g.object({enabled:g.boolean({default:false,description:"Enable the local PgBouncer service.",tags:Ce,links:[dn.pgbouncer()]}),port:g.number({default:54329,description:"Port to use for the local connection pooler.",tags:Ce,links:[dn.pgbouncer("listen_port")]}),pool_mode:g.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:Ce,links:[dn.pgbouncer("pool_mode")]}),default_pool_size:g.number({default:20,description:"How many server connections to allow per user/database pair.",tags:Ce,links:[dn.pgbouncer("default_pool_size")]}),max_client_conn:g.number({default:100,description:"Maximum number of client connections allowed.",tags:Ce,links:[dn.pgbouncer("max_client_conn")]})}).partial(),seed:g.strictObject({enabled:g.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:Ce}),sql_paths:g.array(g.string({description:"Path to a SQL file to seed the database with.",tags:Ce}),{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:Ce})}).partial(),migrations:g.strictObject({enabled:g.boolean({default:true,description:"Enable migrations.",tags:Ce}),schema_paths:g.array(g.string({description:"Path to a SQL file to seed the database with.",tags:Ce}),{default:["./schemas/schema.sql"]})}).partial()}).partial();ee();var da=["edge-functions"],Du=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:da}),policy:g.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:da}),inspector_port:g.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:da})}).partial();ee();var Ar=["experimental"],ju=g.strictObject({orioledb_version:g.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Ar}),s3_host:Et({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Ar}),s3_region:Et({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Ar}),s3_access_key:Et({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Ar}),s3_secret_key:Et({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Ar})}).partial();ee();var ci=["functions"],ui=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],ty=Fn({enabled:Rr({default:true,description:Le`
42
+ `,tags:Bn,links:e}),url:g.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Bn,links:e}),redirect_uri:g.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:g.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Bn,links:e})}).partial()},Ou=g.strictObject({apple:de({id:"apple",name:"Apple"}),azure:de({id:"azure",name:"Azure"}),bitbucket:de({id:"bitbucket",name:"Bitbucket"}),discord:de({id:"discord",name:"Discord"}),facebook:de({id:"facebook",name:"Facebook"}),github:de({id:"github",name:"GitHub"}),gitlab:de({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:de({id:"google",name:"Google"}),kakao:de({id:"kakao",name:"Kakao"}),keycloak:de({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:de({id:"linkedin",name:"LinkedIn"}),notion:de({id:"notion",name:"Notion"}),twitch:de({id:"twitch",name:"Twitch"}),twitter:de({id:"twitter",name:"Twitter"}),slack:de({id:"slack",name:"Slack"}),spotify:de({id:"spotify",name:"Spotify"}),workos:de({id:"workos",name:"WorkOS"}),zoom:de({id:"zoom",name:"Zoom"})}).partial();ee();var ua=["auth"],fa=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],$u=g.strictObject({timebox:g.string({description:"The timebox for the user session.",tags:ua,links:fa}),inactivity_timeout:g.string({description:"The inactivity timeout for the user session.",tags:ua,links:fa}),single_per_user:g.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:ua,links:fa})}).partial();ee();var te=["auth"],se={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`})},Pu=g.strictObject({enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:te,links:[se.auth]}),enable_confirmations:g.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:te,links:[se.auth]}),template:g.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:te,links:[se.auth]}),max_frequency:g.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:te}),twilio:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:te,links:[se.phoneLogin("Twilio")]}),account_sid:g.string({description:"The account SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),message_service_sid:g.string({description:"The message service SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),auth_token:g.string({description:"The auth token for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]})}).partial(),twilio_verify:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:te,links:[se.phoneLogin("Twilio")]}),account_sid:g.string({description:"The account SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),message_service_sid:g.string({description:"The message service SID for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]}),auth_token:g.string({description:"The auth token for the Twilio API.",tags:te,links:[se.phoneLogin("Twilio")]})}).partial(),messagebird:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:te,links:[se.phoneLogin("MessageBird")]}),originator:g.string({description:"The originator of the SMS message.",tags:te,links:[se.phoneLogin("MessageBird")]}),api_key:g.string({description:"The API key for the MessageBird API.",tags:te,links:[se.phoneLogin("MessageBird")]})}).partial(),textlocal:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:g.string({description:"The sender of the SMS message.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:g.string({description:"The API key for the Textlocal API.",tags:te,links:[se.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:g.strictObject({enabled:g.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:te,links:[se.phoneLogin("Vonage")]}),from:g.string({description:"The sender of the SMS message.",tags:te,links:[se.phoneLogin("Vonage")]}),api_key:g.string({description:"The API key for the Vonage API.",tags:te,links:[se.phoneLogin("Vonage")]}),api_secret:g.string({description:"The API secret for the Vonage API.",tags:te,links:[se.phoneLogin("Vonage")]})}).partial(),test_otp:g.record(g.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:te,links:[se.auth]})}).partial();var Ue=["auth"],He={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Nu=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],Iu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local GoTrue service.",tags:Ue,links:[He.auth]}),jwt_secret:g.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Ue,links:[He.auth]}),site_url:g.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:Ue,links:[He.auth]}),additional_redirect_urls:g.array(g.string({description:"A URL that auth providers are permitted to redirect to.",tags:Ue}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Ue,links:[He.auth]}),jwt_expiry:g.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Ue,links:[He.auth]}),enable_refresh_token_rotation:g.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Ue,links:[He.auth]}),refresh_token_reuse_interval:g.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:Ue,links:[He.auth]}),enable_manual_linking:g.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Ue,links:[He.auth]}),enable_signup:g.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Ue,links:[He.auth]}),enable_anonymous_sign_ins:g.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Ue,links:[He.auth]}),minimum_password_length:g.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Ue,links:[He.auth]}),password_requirements:g.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${Nu.join(", ")}`,enum:["",...Nu],tags:Ue,links:[He.auth]}),hook:Au,mfa:ku,sessions:$u,email:Ru,sms:Pu,external:Ou}).partial();ee();var dn={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}`:""}`})},Ce=["database"],Du=g.object({driver:Ht(g.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite",description:"The database driver to use.",tags:Ce})),url:Ht(g.string({description:"Path to the database file/directory (Supalite only).",tags:Ce})),port:g.number({default:54322,description:"Port to use for the local database URL.",tags:Ce,links:[dn.postgres]}),shadow_port:g.number({default:54320,description:"Port to use for the local shadow database.",tags:Ce}),major_version:g.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:Ce,links:[dn.postgres]}),pooler:g.object({enabled:g.boolean({default:false,description:"Enable the local PgBouncer service.",tags:Ce,links:[dn.pgbouncer()]}),port:g.number({default:54329,description:"Port to use for the local connection pooler.",tags:Ce,links:[dn.pgbouncer("listen_port")]}),pool_mode:g.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:Ce,links:[dn.pgbouncer("pool_mode")]}),default_pool_size:g.number({default:20,description:"How many server connections to allow per user/database pair.",tags:Ce,links:[dn.pgbouncer("default_pool_size")]}),max_client_conn:g.number({default:100,description:"Maximum number of client connections allowed.",tags:Ce,links:[dn.pgbouncer("max_client_conn")]})}).partial(),seed:g.strictObject({enabled:g.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:Ce}),sql_paths:g.array(g.string({description:"Path to a SQL file to seed the database with.",tags:Ce}),{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:Ce})}).partial(),migrations:g.strictObject({enabled:g.boolean({default:true,description:"Enable migrations.",tags:Ce}),schema_paths:g.array(g.string({description:"Path to a SQL file to seed the database with.",tags:Ce}),{default:["./schemas/schema.sql"]})}).partial()}).partial();ee();var da=["edge-functions"],ju=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:da}),policy:g.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:da}),inspector_port:g.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:da})}).partial();ee();var kr=["experimental"],Lu=g.strictObject({orioledb_version:g.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:kr}),s3_host:Et({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:kr}),s3_region:Et({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:kr}),s3_access_key:Et({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:kr}),s3_secret_key:Et({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:kr})}).partial();ee();var ci=["functions"],ui=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],ty=Fn({enabled:Tr({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
46
46
  without removing its code.
47
- `,tags:ci,links:ui}),verify_jwt:Rr({default:true,description:Le`
47
+ `,tags:ci,links:ui}),verify_jwt:Tr({default:true,description:Le`
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.
@@ -56,7 +56,7 @@ ${s}`)}return t}ee();var xu=[{name:"Self-hosted Logflare Configuration",link:"ht
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:ui})}).partial(),Lu=Fn({},{patternProperties:{"^[a-zA-Z0-9_-]+$":ty}});ee();var fi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],di=["local"],Uu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local InBucket service.",tags:di,links:fi}),port:g.number({default:54324,description:Le`
59
+ `,tags:ci,links:ui})}).partial(),Uu=Fn({},{patternProperties:{"^[a-zA-Z0-9_-]+$":ty}});ee();var fi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],di=["local"],Mu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local InBucket service.",tags:di,links:fi}),port:g.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,26 +72,26 @@ ${s}`)}return t}ee();var xu=[{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:di,links:fi})}).partial();ee();var ny=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],pa=["realtime"],Mu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Realtime service.",tags:pa,links:ny}),ip_version:g.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:pa,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:g.number({default:4096,description:"Maximum length of the HTTP header.",tags:pa})}).partial();ee();var pi=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Vt=["storage"],ry=g.strictObject({public:g.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:g.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Vt,links:pi}),allowed_mime_types:g.array(g.string({description:"A MIME type allowed for the bucket.",tags:Vt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Vt}),objects_path:g.string({description:"The path to the objects in the bucket.",tags:Vt})}).partial(),Fu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Storage service.",tags:Vt,links:pi}),file_size_limit:g.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Vt,links:pi}),image_transformation:g.strictObject({enabled:g.boolean({default:true,description:"Enable image transformation.",tags:Vt,links:pi})}).partial(),buckets:g.record(ry,{description:"Storage buckets configuration.",tags:Vt})}).partial();ee();var ma={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"}},mi=["studio"],Bu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:mi,links:[ma.studio]}),port:g.number({default:54323,description:"Port to use for Supabase Studio.",tags:mi}),api_url:g.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:mi,links:[ma.config]}),openai_api_key:Et({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:mi,links:[ma.config]})}).partial();var hi=Fn({project_id:cn({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:vu,api:Cu,auth:Nu,db:Iu,edge_runtime:Du,functions:Lu,inbucket:Uu,realtime:Mu,storage:Fu,studio:Bu,experimental:ju}).partial();var ha=(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,f;if(t[a]?(f=t[a][0][0],r.req.routeIndex=a):f=a===t.length&&s||void 0,f)try{l=await f(r,()=>o(a+1));}catch(u){if(u instanceof Error&&e)r.error=u,l=await e(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var gi=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 qu=Symbol();var Wu=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof yi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?sy(t,{all:n,dot:r}):{}};async function sy(t,e){let n=await t.formData();return n?iy(n,e):{}}function iy(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?oy(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(ay(n,r,s),delete n[r]);}),n}var oy=(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;},ay=(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 ya=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ju=t=>{let{groups:e,path:n}=ly(t),r=ya(n);return cy(r,e)},ly=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},cy=(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},bi={},Ku=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return bi[r]||(n[2]?bi[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:bi[r]=[t,n[1],true]),bi[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}})}},uy=t=>qn(t,decodeURI),ba=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 uy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var Hu=t=>{let e=ba(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},pn=(t,e,...n)=>(n.length&&(e=pn(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),wi=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)},ga=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?qn(t,Or):t):t,zu=(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 ga(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=ga(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=ga(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},Gu=zu,Vu=(t,e)=>zu(t,e,true),Or=decodeURIComponent;var Qu=t=>qn(t,Or),yi=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)?Qu(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)?Qu(r):r);}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Gu(this.url,t)}queries(t){return Vu(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 Wu(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[qu](){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},K=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},fy=/[&<>'"]/,Si=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 K(n,e)},_t=(t,e)=>{let n=t.search(fy);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="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},wa=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]},mn=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=>mn(l,e,false,r,s))).then(()=>s[0]));return n?K(await o,i):o};var dy="text/plain; charset=UTF-8",Sa=(t,e)=>({"Content-Type":t,...e}),$r=(t,e)=>new Response(t,e),Xu=class{#e;#t;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#d=e.path,this.#f=e.matchResult);}get req(){return this.#t??=new yi(this.#e,this.#d,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||=$r(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=$r(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=$r(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 $r(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,Sa(dy,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,Sa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,Sa("text/html; charset=UTF-8",n));return typeof t=="object"?mn(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??=()=>$r(),this.#c(this))};var Y="ALL",Yu="all",Zu=["get","post","put","delete","options","patch"],Ei="Can not add a route since the matcher is already built.",_i=class extends Error{};var ef="__COMPOSED_HANDLER";var py=t=>t.text("404 Not Found",404),tf=(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)},nf=class rf{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...Zu,Yu].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(f=>{this.#i(c.toUpperCase(),this.#e,f);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(Y,this.#e,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??ba:Hu;}#t(){let e=new rf({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=py;errorHandler=tf;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===tf?i=s.handler:(i=async(o,a)=>(await ha([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[ef]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#t();return n._basePath=pn(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=pn(this._basePath,e),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(s(l.req.raw),...o(l));if(f)return f;await c();};return this.#i(Y,pn(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=pn(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 Xu(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(f){return this.#r(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#r(f,a)):c??this.#n(a)}let l=ha(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${pn("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var xi=[];function Ea(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[Y],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],xi];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var vi="[^/]+",Pr=".*",Nr="(?:|/.*)",hn=Symbol(),my=new Set(".\\+*[^]$()");function hy(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Pr||t===Nr?1:e===Pr||e===Nr?-1:t===vi?1:e===vi?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var sf=class _a{#e;#t;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#e!==void 0)throw hn;if(i)return;this.#e=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",Pr]:["","",vi]:o==="/*"?["","",Nr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||vi;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw hn;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(d=>d!==Pr&&d!==Nr))throw hn;if(i)return;c=this.#n[u]=new _a,f!==""&&(c.#t=s.varIndex++);}!i&&f!==""&&r.push([f,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==Pr&&f!==Nr))throw hn;if(i)return;c=this.#n[o]=new _a;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(hy).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:my.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 of=class{#e={varIndex:0};#t=new sf;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 gy=[/^$/,[],Object.create(null)],af=Object.create(null);function lf(t){return af[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function yy(){af=Object.create(null);}function by(t){let e=new of,n=[];if(t.length===0)return gy;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,d])=>c?1:u?-1:f.length-d.length),s=Object.create(null);for(let c=0,f=-1,u=r.length;c<u;c++){let[d,p,y]=r[c];d?s[p]=[y.map(([b])=>[b,Object.create(null)]),xi]:f++;let h;try{h=e.insert(p,f,d);}catch(b){throw b===hn?new _i(p):b}d||(n[f]=y.map(([b,m])=>{let w=Object.create(null);for(m-=1;m>=0;m--){let[_,S]=h[m];w[_]=S;}return [b,w]}));}let[i,o,a]=e.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,d=n[c].length;u<d;u++){let p=n[c][u]?.[1];if(!p)continue;let y=Object.keys(p);for(let h=0,b=y.length;h<b;h++)p[y[h]]=a[p[y[h]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Wn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(lf(n).test(e))return [...t[n]]}}var Ci=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[Y]:Object.create(null)},this.#t={[Y]:Object.create(null)};}add(t,e,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(Ei);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[Y]).forEach(l=>{a[t][l]=[...a[Y][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=lf(e);t===Y?Object.keys(r).forEach(l=>{r[l][e]||=Wn(r[l],e)||Wn(r[Y],e)||[];}):r[t][e]||=Wn(r[t],e)||Wn(r[Y],e)||[],Object.keys(r).forEach(l=>{(t===Y||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===Y||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=wi(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(f=>{(t===Y||t===f)&&(s[f][c]||=[...Wn(r[f],c)||Wn(r[Y],c)||[]],s[f][c].push([n,i-l+a+1]));});}}match=Ea;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,yy(),t}#n(t){let e=[],n=t===Y;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!==Y&&e.push(...Object.keys(r[Y]).map(i=>[i,r[Y][i]]));}),n?by(e):null}};var xa=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers;}add(t,e,n){if(!this.#t)throw new Error(Ei);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 _i)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 Ir=Object.create(null),wy=t=>{for(let e in t)return true;return false},cf=class uf{#e;#t;#n;#i=0;#r=Ir;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=Ju(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],f=i[a+1],u=Ku(c,f),d=Array.isArray(u)?u[0]:c;if(d in s.#t){s=s.#t[d],u&&o.push(u[1]);continue}s.#t[d]=new uf,u&&(s.#n.push(u),o.push(u[1])),s=s.#t[d];}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[Y],f={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Ir||i&&i!==Ir))for(let u=0,d=c.possibleKeys.length;u<d;u++){let p=c.possibleKeys[u],y=f[c.score];c.params[p]=i?.[p]&&!y?i[p]:s[p]??i?.[p],f[c.score]=true;}}}search(e,n){let r=[];this.#r=Ir;let i=[this],o=ya(n),a=[],l=o.length,c=null;for(let f=0;f<l;f++){let u=o[f],d=f===l-1,p=[];for(let h=0,b=i.length;h<b;h++){let m=i[h],w=m.#t[u];w&&(w.#r=m.#r,d?(w.#t["*"]&&this.#s(r,w.#t["*"],e,m.#r),this.#s(r,w,e,m.#r)):p.push(w));for(let _=0,S=m.#n.length;_<S;_++){let E=m.#n[_],C=m.#r===Ir?{}:{...m.#r};if(E==="*"){let z=m.#t["*"];z&&(this.#s(r,z,e,m.#r),z.#r=C,p.push(z));continue}let[x,R,v]=E;if(!u&&!(v instanceof RegExp))continue;let k=m.#t[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let ue=n[0]==="/"?1:0;for(let Xe=0;Xe<l;Xe++)c[Xe]=ue,ue+=o[Xe].length+1;}let z=n.substring(c[f]),I=v.exec(z);if(I){if(C[R]=I[0],this.#s(r,k,e,m.#r,C),wy(k.#t)){k.#r=C;let ue=I[0].match(/\//)?.length??0;(a[ue]||=[]).push(k);}continue}}(v===true||v.test(u))&&(C[R]=u,d?(this.#s(r,k,e,C,m.#r),k.#t["*"]&&this.#s(r,k.#t["*"],e,C,m.#r)):(k.#r=C,p.push(k)));}}let y=a.shift();i=y?p.concat(y):p;}return r.length>1&&r.sort((f,u)=>f.score-u.score),[r.map(({handler:f,params:u})=>[f,u])]}};var va=class{name="TrieRouter";#e;constructor(){this.#e=new cf;}add(t,e,n){let r=wi(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 Se=class extends nf{constructor(t={}){super(t),this.router=t.router??new xa({routers:[new Ci,new va]});}};var Ey=t=>JSON.parse(jsonStringify(t)),ff=new Se().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(t.var.app.config)).get("/info",t=>t.json(Ey({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 Ae=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;}},Me=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";}},Jn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},pe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var _y="/rest/v1";function Ca(t,e=_y){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 Jn;return {from:s[0]||void 0,isRpc:false}}function Ra(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 f=c.indexOf("=");if(f===-1)continue;let u=c.slice(0,f).trim(),d=c.slice(f+1).trim();u==="max-affected"?r.push({key:"max-affected",value:Number(d)}):r.push({key:u,value:d});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var df=new Set(["count","sum","avg","min","max"]);function F(t){return t.input[t.pos]??""}function L(t,e=1){t.pos+=e;}function Re(t){return t.pos>=t.input.length}function Oe(t,e){return t.input.startsWith(e,t.pos)}function ka(t){return /^[a-zA-Z0-9_]$/.test(t)}function B(t){for(;!Re(t)&&/\s/.test(F(t));)L(t);}function Oa(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 Me("failed to parse select parameter");let r={},s=new Set,i={input:n,pos:0},o=hf(i,r,s);if(B(i),!Re(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}function hf(t,e,n){let r=[];if(B(t),Re(t)||F(t)===")"||F(t)===","&&(L(t),B(t),Re(t)||F(t)===")"))return r;for(r.push(pf(t,e,n));!Re(t)&&(B(t),F(t)===",");)L(t),B(t),r.push(pf(t,e,n));return r}function pf(t,e,n){if(B(t),F(t)==="*")return L(t),"*";if(Oe(t,"..."))return L(t,3),B(t),xy(t,e,n);let r=lt(t,{allowSpaces:true,allowDollar:true});return B(t),Oe(t,"::")?Aa(r,void 0,t,e,n):F(t)===":"?(L(t),B(t),vy(r,t,e,n)):Aa(r,void 0,t,e,n)}function xy(t,e,n){let r=lt(t);B(t);let{hint:s,innerJoin:i}=gf(t);if(B(t),F(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=yf(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let f={spread:true,select:o};return Object.keys(a).length>0&&(f.join=a),{[l]:f}}function vy(t,e,n,r){let s=lt(e,{allowSpaces:true,allowDollar:true});return B(e),Aa(s,t,e,n,r)}function Aa(t,e,n,r,s){return B(n),t==="count"&&(Re(n)||F(n)===","||F(n)===")"||F(n)==="("||Oe(n,"::"))?Ry(e,n):F(n)==="!"||F(n)==="("?Cy(t,e,n,r,s):Ty(t,e,n)}function Cy(t,e,n,r,s){let{hint:i,innerJoin:o}=gf(n);if(B(n),F(n)!=="(")throw new Me("failed to parse select parameter");let{subSelect:a,subJoin:l}=yf(n),c=e??t,f={};e&&(f.from=t),o&&(f.type="inner"),i&&(f.hint=i),r[c]=f,s.add(c),e&&t!==c&&s.add(t);let u={select:a};return Object.keys(l).length>0&&(u.join=l),{[c]:u}}function gf(t){if(B(t),F(t)!=="!")return {};L(t);let e=lt(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(B(t),F(t)==="!"){L(t);let r=lt(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 yf(t,e,n){if(F(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);L(t),B(t);let r={},s=new Set;if(F(t)===")")return L(t),{subSelect:[],subJoin:r};let i=hf(t,r,s);if(B(t),F(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return L(t),{subSelect:i,subJoin:r}}function Ry(t,e){B(e);let n=true;if(F(e)==="("){n=false,L(e);let o=e.pos;for(;!Re(e)&&F(e)!==")";)L(e);if(Re(e))throw new Me("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(L(e),a!=="")throw new Me("expected null arg for count()")}B(e);let r;Oe(e,"::")&&(L(e,2),r=Dr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function Ty(t,e,n){B(n);let r,s,i=false,o;if(Oe(n,"->")){let{path:f,lastProp:u,lastIsText:d,invalidTextTraversalKey:p}=ky(n);r=f,s=u||void 0,i=d,o=p;}B(n);let a,l;if(Oe(n,"::")){L(n,2);let f=Dr(n);if(B(n),F(n)==="."&&!Re(n)){let u=n.input[n.pos+1]??"";if(ka(u)){let d=n.pos;L(n);let p=lt(n);if(df.has(p)&&Oe(n,"()"))return a=f,L(n,2),B(n),Oe(n,"::")&&(L(n,2),l=Dr(n),Ta(n)),mf(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=f,Ta(n);}let c;if(F(n)==="."&&!Re(n)){let f=n.input[n.pos+1]??"";if(ka(f)){let u=n.pos;L(n);let d=lt(n);df.has(d)&&Oe(n,"()")?(c=d,L(n,2),B(n),Oe(n,"::")&&(L(n,2),l=Dr(n),Ta(n))):n.pos=u;}}return mf(t,e,r,s,i,o,a,c,l)}function Ta(t){for(B(t);Oe(t,"::");)L(t,2),Dr(t),B(t);}function Dr(t){B(t);let e=[lt(t)];for(;!Re(t);){let n=t.pos;if(B(t),t.pos===n)break;let r=F(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(lt(t));}return e.join(" ")}function mf(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 f=c??t,u={};return t!==f&&(u.column=t),a&&!u.column&&t===f&&(u.column=t),n&&(u.column||(u.column=t),u.path=n,s&&(u.pathText=true),i&&(u.invalidJsonTextTraversalKey=i)),o&&(u.preCast=o),a&&(u.aggregate=a),l&&(u.cast=l),{[f]:u}}function ky(t){let e=[],n="",r=false,s;for(;Oe(t,"->");){let o=r;L(t,2);let a=false;F(t)===">"&&(L(t),a=true);let l=Ay(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 Ay(t){return Oy(t)}function Oy(t){B(t);let e=t.pos;if(F(t)==='"')return lt(t);let n="";for(;!Re(t)&&!(Oe(t,"->")||Oe(t,"::"));){let r=F(t);if(r===","||r==="."||r===":"||/\s/.test(r))break;n+=r,L(t);}if(n==="")throw new Me(`"failed to parse select parameter (${t.input})" (line 1, column ${e+1})`);if(n.includes("--")||n.endsWith("-"))throw new Me("failed to parse select parameter");if(/^-\d+\D/.test(n))throw new Me("failed to parse select parameter");return n}function lt(t,e={}){if(B(t),F(t)==='"'){L(t);let r="";for(;!Re(t)&&F(t)!=='"';)r+=F(t),L(t);if(Re(t))throw new Error(`Missing closing quote at position ${t.pos}`);return L(t),r}let n="";for(;!Re(t);){let r=F(t);if(ka(r))n+=r,L(t);else if(e.allowDollar&&r==="$")n+=r,L(t);else if(e.allowSpaces&&r===" ")n+=r,L(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,L(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 Me("failed to parse select parameter");return n}async function $a(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"";if(!n&&r.includes("text/csv"))throw new Kn('parse error (not enough input) at ""');if(!n)return {};if(r.includes("application/json"))try{let s=JSON.parse(n);return Array.isArray(s)?{values:s}:{values:s}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:$y(n)};if(r.includes("application/x-www-form-urlencoded")){let s=new URLSearchParams(n),i={};for(let[o,a]of s)i[o]=a;return {values:i}}return {raw:n}}function $y(t){let e=t.replace(/\r\n/g,`
75
+ `,tags:di,links:fi})}).partial();ee();var ny=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],pa=["realtime"],Fu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Realtime service.",tags:pa,links:ny}),ip_version:g.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:pa,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:g.number({default:4096,description:"Maximum length of the HTTP header.",tags:pa})}).partial();ee();var pi=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Vt=["storage"],ry=g.strictObject({public:g.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:g.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Vt,links:pi}),allowed_mime_types:g.array(g.string({description:"A MIME type allowed for the bucket.",tags:Vt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Vt}),objects_path:g.string({description:"The path to the objects in the bucket.",tags:Vt})}).partial(),Bu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Storage service.",tags:Vt,links:pi}),file_size_limit:g.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Vt,links:pi}),image_transformation:g.strictObject({enabled:g.boolean({default:true,description:"Enable image transformation.",tags:Vt,links:pi})}).partial(),buckets:g.record(ry,{description:"Storage buckets configuration.",tags:Vt})}).partial();ee();var ma={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"}},mi=["studio"],qu=g.strictObject({enabled:g.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:mi,links:[ma.studio]}),port:g.number({default:54323,description:"Port to use for Supabase Studio.",tags:mi}),api_url:g.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:mi,links:[ma.config]}),openai_api_key:Et({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:mi,links:[ma.config]})}).partial();var hi=Fn({project_id:cn({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:Cu,api:Tu,auth:Iu,db:Du,edge_runtime:ju,functions:Uu,inbucket:Mu,realtime:Fu,storage:Bu,studio:qu,experimental:Lu}).partial();var ha=(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,f;if(t[a]?(f=t[a][0][0],r.req.routeIndex=a):f=a===t.length&&s||void 0,f)try{l=await f(r,()=>o(a+1));}catch(u){if(u instanceof Error&&e)r.error=u,l=await e(u,r),c=true;else throw u}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var gi=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 Wu=Symbol();var Ju=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof yi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?sy(t,{all:n,dot:r}):{}};async function sy(t,e){let n=await t.formData();return n?iy(n,e):{}}function iy(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?oy(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(ay(n,r,s),delete n[r]);}),n}var oy=(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;},ay=(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 ya=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ku=t=>{let{groups:e,path:n}=ly(t),r=ya(n);return cy(r,e)},ly=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},cy=(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},bi={},Hu=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return bi[r]||(n[2]?bi[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:bi[r]=[t,n[1],true]),bi[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}})}},uy=t=>qn(t,decodeURI),ba=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 uy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var zu=t=>{let e=ba(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},pn=(t,e,...n)=>(n.length&&(e=pn(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),wi=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)},ga=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?qn(t,Or):t):t,Gu=(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 ga(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=ga(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=ga(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},Vu=Gu,Qu=(t,e)=>Gu(t,e,true),Or=decodeURIComponent;var Yu=t=>qn(t,Or),yi=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)?Yu(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)?Yu(r):r);}return t}#r(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Vu(this.url,t)}queries(t){return Qu(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 Ju(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[Wu](){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 Xe={Stringify:1},K=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},fy=/[&<>'"]/,Si=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 K(n,e)},_t=(t,e)=>{let n=t.search(fy);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="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(i,s)+r,i=s+1;}e[0]+=t.substring(i,s);},wa=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:Xe.Stringify,buffer:n,context:r})),n[0]},mn=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=>mn(l,e,false,r,s))).then(()=>s[0]));return n?K(await o,i):o};var dy="text/plain; charset=UTF-8",Sa=(t,e)=>({"Content-Type":t,...e}),$r=(t,e)=>new Response(t,e),Xu=class{#e;#t;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#e=t,e&&(this.#r=e.executionCtx,this.env=e.env,this.#c=e.notFoundHandler,this.#d=e.path,this.#f=e.matchResult);}get req(){return this.#t??=new yi(this.#e,this.#d,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||=$r(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=$r(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=$r(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 $r(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,Sa(dy,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,Sa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,Sa("text/html; charset=UTF-8",n));return typeof t=="object"?mn(t,Xe.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??=()=>$r(),this.#c(this))};var X="ALL",Zu="all",ef=["get","post","put","delete","options","patch"],Ei="Can not add a route since the matcher is already built.",_i=class extends Error{};var tf="__COMPOSED_HANDLER";var py=t=>t.text("404 Not Found",404),nf=(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)},rf=class sf{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...ef,Zu].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(f=>{this.#i(c.toUpperCase(),this.#e,f);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(X,this.#e,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??ba:zu;}#t(){let e=new sf({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=py;errorHandler=nf;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===nf?i=s.handler:(i=async(o,a)=>(await ha([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[tf]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#t();return n._basePath=pn(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=pn(this._basePath,e),c=l==="/"?0:l.length;return f=>{let u=new URL(f.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,f)}})();let a=async(l,c)=>{let f=await n(s(l.req.raw),...o(l));if(f)return f;await c();};return this.#i(X,pn(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=pn(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 Xu(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(f){return this.#r(f,a)}return c instanceof Promise?c.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#r(f,a)):c??this.#n(a)}let l=ha(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${pn("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var xi=[];function Ea(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[X],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],xi];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var vi="[^/]+",Pr=".*",Nr="(?:|/.*)",hn=Symbol(),my=new Set(".\\+*[^]$()");function hy(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===Pr||t===Nr?1:e===Pr||e===Nr?-1:t===vi?1:e===vi?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var of=class _a{#e;#t;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#e!==void 0)throw hn;if(i)return;this.#e=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",Pr]:["","",vi]:o==="/*"?["","",Nr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||vi;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw hn;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(d=>d!==Pr&&d!==Nr))throw hn;if(i)return;c=this.#n[u]=new _a,f!==""&&(c.#t=s.varIndex++);}!i&&f!==""&&r.push([f,c.#t]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==Pr&&f!==Nr))throw hn;if(i)return;c=this.#n[o]=new _a;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(hy).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:my.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 af=class{#e={varIndex:0};#t=new of;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 gy=[/^$/,[],Object.create(null)],lf=Object.create(null);function cf(t){return lf[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function yy(){lf=Object.create(null);}function by(t){let e=new af,n=[];if(t.length===0)return gy;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,f],[u,d])=>c?1:u?-1:f.length-d.length),s=Object.create(null);for(let c=0,f=-1,u=r.length;c<u;c++){let[d,p,y]=r[c];d?s[p]=[y.map(([b])=>[b,Object.create(null)]),xi]:f++;let h;try{h=e.insert(p,f,d);}catch(b){throw b===hn?new _i(p):b}d||(n[f]=y.map(([b,m])=>{let w=Object.create(null);for(m-=1;m>=0;m--){let[_,S]=h[m];w[_]=S;}return [b,w]}));}let[i,o,a]=e.buildRegExp();for(let c=0,f=n.length;c<f;c++)for(let u=0,d=n[c].length;u<d;u++){let p=n[c][u]?.[1];if(!p)continue;let y=Object.keys(p);for(let h=0,b=y.length;h<b;h++)p[y[h]]=a[p[y[h]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Wn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(cf(n).test(e))return [...t[n]]}}var Ci=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[X]:Object.create(null)},this.#t={[X]:Object.create(null)};}add(t,e,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(Ei);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[X]).forEach(l=>{a[t][l]=[...a[X][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=cf(e);t===X?Object.keys(r).forEach(l=>{r[l][e]||=Wn(r[l],e)||Wn(r[X],e)||[];}):r[t][e]||=Wn(r[t],e)||Wn(r[X],e)||[],Object.keys(r).forEach(l=>{(t===X||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===X||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=wi(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(f=>{(t===X||t===f)&&(s[f][c]||=[...Wn(r[f],c)||Wn(r[X],c)||[]],s[f][c].push([n,i-l+a+1]));});}}match=Ea;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,yy(),t}#n(t){let e=[],n=t===X;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!==X&&e.push(...Object.keys(r[X]).map(i=>[i,r[X][i]]));}),n?by(e):null}};var xa=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers;}add(t,e,n){if(!this.#t)throw new Error(Ei);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 _i)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 Ir=Object.create(null),wy=t=>{for(let e in t)return true;return false},uf=class ff{#e;#t;#n;#i=0;#r=Ir;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=Ku(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],f=i[a+1],u=Hu(c,f),d=Array.isArray(u)?u[0]:c;if(d in s.#t){s=s.#t[d],u&&o.push(u[1]);continue}s.#t[d]=new ff,u&&(s.#n.push(u),o.push(u[1])),s=s.#t[d];}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[X],f={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Ir||i&&i!==Ir))for(let u=0,d=c.possibleKeys.length;u<d;u++){let p=c.possibleKeys[u],y=f[c.score];c.params[p]=i?.[p]&&!y?i[p]:s[p]??i?.[p],f[c.score]=true;}}}search(e,n){let r=[];this.#r=Ir;let i=[this],o=ya(n),a=[],l=o.length,c=null;for(let f=0;f<l;f++){let u=o[f],d=f===l-1,p=[];for(let h=0,b=i.length;h<b;h++){let m=i[h],w=m.#t[u];w&&(w.#r=m.#r,d?(w.#t["*"]&&this.#s(r,w.#t["*"],e,m.#r),this.#s(r,w,e,m.#r)):p.push(w));for(let _=0,S=m.#n.length;_<S;_++){let E=m.#n[_],C=m.#r===Ir?{}:{...m.#r};if(E==="*"){let z=m.#t["*"];z&&(this.#s(r,z,e,m.#r),z.#r=C,p.push(z));continue}let[x,T,v]=E;if(!u&&!(v instanceof RegExp))continue;let A=m.#t[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let ue=n[0]==="/"?1:0;for(let Ye=0;Ye<l;Ye++)c[Ye]=ue,ue+=o[Ye].length+1;}let z=n.substring(c[f]),I=v.exec(z);if(I){if(C[T]=I[0],this.#s(r,A,e,m.#r,C),wy(A.#t)){A.#r=C;let ue=I[0].match(/\//)?.length??0;(a[ue]||=[]).push(A);}continue}}(v===true||v.test(u))&&(C[T]=u,d?(this.#s(r,A,e,C,m.#r),A.#t["*"]&&this.#s(r,A.#t["*"],e,C,m.#r)):(A.#r=C,p.push(A)));}}let y=a.shift();i=y?p.concat(y):p;}return r.length>1&&r.sort((f,u)=>f.score-u.score),[r.map(({handler:f,params:u})=>[f,u])]}};var va=class{name="TrieRouter";#e;constructor(){this.#e=new uf;}add(t,e,n){let r=wi(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 Se=class extends rf{constructor(t={}){super(t),this.router=t.router??new xa({routers:[new Ci,new va]});}};var Ey=t=>JSON.parse(jsonStringify(t)),df=new Se().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(t.var.app.config)).get("/info",t=>t.json(Ey({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;}},Me=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";}},Jn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},pe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var _y="/rest/v1";function Ca(t,e=_y){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 Jn;return {from:s[0]||void 0,isRpc:false}}function Ta(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 f=c.indexOf("=");if(f===-1)continue;let u=c.slice(0,f).trim(),d=c.slice(f+1).trim();u==="max-affected"?r.push({key:"max-affected",value:Number(d)}):r.push({key:u,value:d});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var pf=new Set(["count","sum","avg","min","max"]);function F(t){return t.input[t.pos]??""}function L(t,e=1){t.pos+=e;}function Te(t){return t.pos>=t.input.length}function Oe(t,e){return t.input.startsWith(e,t.pos)}function Aa(t){return /^[a-zA-Z0-9_]$/.test(t)}function B(t){for(;!Te(t)&&/\s/.test(F(t));)L(t);}function Oa(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 Me("failed to parse select parameter");let r={},s=new Set,i={input:n,pos:0},o=gf(i,r,s);if(B(i),!Te(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}function gf(t,e,n){let r=[];if(B(t),Te(t)||F(t)===")"||F(t)===","&&(L(t),B(t),Te(t)||F(t)===")"))return r;for(r.push(mf(t,e,n));!Te(t)&&(B(t),F(t)===",");)L(t),B(t),r.push(mf(t,e,n));return r}function mf(t,e,n){if(B(t),F(t)==="*")return L(t),"*";if(Oe(t,"..."))return L(t,3),B(t),xy(t,e,n);let r=lt(t,{allowSpaces:true,allowDollar:true});return B(t),Oe(t,"::")?ka(r,void 0,t,e,n):F(t)===":"?(L(t),B(t),vy(r,t,e,n)):ka(r,void 0,t,e,n)}function xy(t,e,n){let r=lt(t);B(t);let{hint:s,innerJoin:i}=yf(t);if(B(t),F(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=bf(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let f={spread:true,select:o};return Object.keys(a).length>0&&(f.join=a),{[l]:f}}function vy(t,e,n,r){let s=lt(e,{allowSpaces:true,allowDollar:true});return B(e),ka(s,t,e,n,r)}function ka(t,e,n,r,s){return B(n),t==="count"&&(Te(n)||F(n)===","||F(n)===")"||F(n)==="("||Oe(n,"::"))?Ty(e,n):F(n)==="!"||F(n)==="("?Cy(t,e,n,r,s):Ry(t,e,n)}function Cy(t,e,n,r,s){let{hint:i,innerJoin:o}=yf(n);if(B(n),F(n)!=="(")throw new Me("failed to parse select parameter");let{subSelect:a,subJoin:l}=bf(n),c=e??t,f={};e&&(f.from=t),o&&(f.type="inner"),i&&(f.hint=i),r[c]=f,s.add(c),e&&t!==c&&s.add(t);let u={select:a};return Object.keys(l).length>0&&(u.join=l),{[c]:u}}function yf(t){if(B(t),F(t)!=="!")return {};L(t);let e=lt(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(B(t),F(t)==="!"){L(t);let r=lt(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 bf(t,e,n){if(F(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);L(t),B(t);let r={},s=new Set;if(F(t)===")")return L(t),{subSelect:[],subJoin:r};let i=gf(t,r,s);if(B(t),F(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return L(t),{subSelect:i,subJoin:r}}function Ty(t,e){B(e);let n=true;if(F(e)==="("){n=false,L(e);let o=e.pos;for(;!Te(e)&&F(e)!==")";)L(e);if(Te(e))throw new Me("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(L(e),a!=="")throw new Me("expected null arg for count()")}B(e);let r;Oe(e,"::")&&(L(e,2),r=Dr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function Ry(t,e,n){B(n);let r,s,i=false,o;if(Oe(n,"->")){let{path:f,lastProp:u,lastIsText:d,invalidTextTraversalKey:p}=Ay(n);r=f,s=u||void 0,i=d,o=p;}B(n);let a,l;if(Oe(n,"::")){L(n,2);let f=Dr(n);if(B(n),F(n)==="."&&!Te(n)){let u=n.input[n.pos+1]??"";if(Aa(u)){let d=n.pos;L(n);let p=lt(n);if(pf.has(p)&&Oe(n,"()"))return a=f,L(n,2),B(n),Oe(n,"::")&&(L(n,2),l=Dr(n),Ra(n)),hf(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=f,Ra(n);}let c;if(F(n)==="."&&!Te(n)){let f=n.input[n.pos+1]??"";if(Aa(f)){let u=n.pos;L(n);let d=lt(n);pf.has(d)&&Oe(n,"()")?(c=d,L(n,2),B(n),Oe(n,"::")&&(L(n,2),l=Dr(n),Ra(n))):n.pos=u;}}return hf(t,e,r,s,i,o,a,c,l)}function Ra(t){for(B(t);Oe(t,"::");)L(t,2),Dr(t),B(t);}function Dr(t){B(t);let e=[lt(t)];for(;!Te(t);){let n=t.pos;if(B(t),t.pos===n)break;let r=F(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(lt(t));}return e.join(" ")}function hf(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 f=c??t,u={};return t!==f&&(u.column=t),a&&!u.column&&t===f&&(u.column=t),n&&(u.column||(u.column=t),u.path=n,s&&(u.pathText=true),i&&(u.invalidJsonTextTraversalKey=i)),o&&(u.preCast=o),a&&(u.aggregate=a),l&&(u.cast=l),{[f]:u}}function Ay(t){let e=[],n="",r=false,s;for(;Oe(t,"->");){let o=r;L(t,2);let a=false;F(t)===">"&&(L(t),a=true);let l=ky(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 ky(t){return Oy(t)}function Oy(t){B(t);let e=t.pos;if(F(t)==='"')return lt(t);let n="";for(;!Te(t)&&!(Oe(t,"->")||Oe(t,"::"));){let r=F(t);if(r===","||r==="."||r===":"||/\s/.test(r))break;n+=r,L(t);}if(n==="")throw new Me(`"failed to parse select parameter (${t.input})" (line 1, column ${e+1})`);if(n.includes("--")||n.endsWith("-"))throw new Me("failed to parse select parameter");if(/^-\d+\D/.test(n))throw new Me("failed to parse select parameter");return n}function lt(t,e={}){if(B(t),F(t)==='"'){L(t);let r="";for(;!Te(t)&&F(t)!=='"';)r+=F(t),L(t);if(Te(t))throw new Error(`Missing closing quote at position ${t.pos}`);return L(t),r}let n="";for(;!Te(t);){let r=F(t);if(Aa(r))n+=r,L(t);else if(e.allowDollar&&r==="$")n+=r,L(t);else if(e.allowSpaces&&r===" ")n+=r,L(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,L(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 Me("failed to parse select parameter");return n}async function $a(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"";if(!n&&r.includes("text/csv"))throw new Kn('parse error (not enough input) at ""');if(!n)return {};if(r.includes("application/json"))try{let s=JSON.parse(n);return Array.isArray(s)?{values:s}:{values:s}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:$y(n)};if(r.includes("application/x-www-form-urlencoded")){let s=new URLSearchParams(n),i={};for(let[o,a]of s)i[o]=a;return {values:i}}return {raw:n}}function $y(t){let e=t.replace(/\r\n/g,`
76
76
  `).replace(/\r/g,`
77
77
  `),n=Py(e);if(n.length===0)throw new Kn("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 Py(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
78
78
  `);){let{row:s,nextPos:i}=Ny(t,n);e.push(s),n=i;}return e}function Ny(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 Kn=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function Pa(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 Na(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 wf=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"]),bf={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"},Iy={any:"Any",all:"All"},Dy=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),jy={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function Ia(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!Dy.has(s))return null;let o=bf[s];return o?{astOp:o+Iy[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:jy[s],ftsConfig:i}}let r=bf[t];return r?{astOp:r}:null}function jr(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"");return wf.has(r)}var gn=new Set(["select","order","limit","offset","on_conflict","columns"]);function Lr(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(xt(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function Ur(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(xt(r));}n<t.length&&t[n]===","&&n++;}return e}var Ri=Symbol.for("postgrest:not_null"),yn=Symbol.for("postgrest:unknown");function xt(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 Ri;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;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 La(t,e){let n={},r={};for(let[s,i]of t){if(gn.has(s))continue;let a=s.startsWith('"')?-1:s.indexOf(".");if(a>0&&!s.slice(0,a).includes("->")){let l=s.slice(0,a),c=s.slice(a+1);if(e.has(l)){if(c==="order"||c==="limit"||c==="offset")continue;if(c.includes(".")){let f=c.lastIndexOf("."),u=c.slice(f+1);if(u==="order"||u==="limit"||u==="offset")continue}r[l]||(r[l]={}),Uy(c,i,r[l]);continue}if(s!=="not.or"&&s!=="not.and")throw Ly(l)}ja(s,i,n);}return {where:n,embeddedWheres:r}}function Ly(t){return new Ae({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 ja(t,e,n){if(t==="or"||t==="and"){let s=e.map(o=>Sf(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=>Sf(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=_f(qy(t),{stopAtSpace:false});xf(r);for(let s of e){let i=Ef(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function Uy(t,e,n){let r=My(t);if(!r){ja(t,e,n);return}let s={};ja(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function My(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 Ef(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=Ia(s);if(!o)throw 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:Da(a,i)};if(n&&a==="$is")return {$isNot:Da(a,i)};let f=a==="$textSearch"?By(i,l,c):Da(a,i);return n?{$not:{[a]:f}}:{[a]:f}}function Da(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 Lr(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return Ur(e);if(!Fy(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Lr(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 Ur(e)}return e.startsWith("[")||e.startsWith("(")?e:xt(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim();if(!["null","true","false","unknown","not_null"].includes(n))throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return n==="unknown"?yn:xt(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("{")?Ur(n):Lr(n):n}return t==="$isDistinct"?e:xt(e)}function Fy(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function By(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function Sf(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 new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+2})`);try{return Mr(e).map(r=>Fr(r))}catch{throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+2})`)}}function Mr(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 Fr(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Mr(n[1]).map(d=>Fr(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Mr(r[1]).map(d=>Fr(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Mr(s[1]).map(d=>Fr(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Mr(i[1]).map(d=>Fr(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not.")||e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t,a=false;o.startsWith("not.")&&(a=true,o=o.slice(4));let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=_f(o.slice(0,l),{stopAtSpace:true});xf(c);let f=o.slice(l+1),u=Ef(a?`not.${f}`:f);return {[c]:u}}function _f(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t);return r?t.slice(0,r.index):t}function qy(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function xf(t){if(t===""||t==="*"||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+\D/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function Wy(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function vf(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 Ua(t,e){let n=vf(t),r=vf(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 Fa(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let y=p[0],h=d.indexOf(".");if(h>0){let b=d.slice(0,h),m=d.slice(h+1);if(e.has(b)){if(m==="order"||m==="limit"||m==="offset"){n.embeddedTransforms[b]||(n.embeddedTransforms[b]={}),m==="order"?n.embeddedTransforms[b].order=Ma(y):m==="limit"?i[b]=y:m==="offset"&&(o[b]=y);continue}if(m.includes(".")){let w=m.lastIndexOf("."),_=m.slice(w+1);if(_==="order"||_==="limit"||_==="offset"){n.embeddedTransforms[b]||(n.embeddedTransforms[b]={});let S=n.embeddedTransforms[b],E=m.slice(0,w);S._nested||(S._nested={});let C=S._nested;C[E]||(C[E]={});let x=C[E];_==="order"?x.order=Ma(y):_==="limit"?(a[b]||(a[b]={}),a[b][E]=y):_==="offset"&&(l[b]||(l[b]={}),l[b][E]=y);continue}}}}d==="order"?n.order=Ma(y):d==="limit"?r=y:d==="offset"&&(s=y);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new Ae({httpStatus:400,code:"PGRST108",message:`'${d.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${d.embed}' is included in the 'select' query parameter.`})}let c=Ua(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let f=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of f){let p=Ua(i[d],o[d]);n.embeddedTransforms[d]||(n.embeddedTransforms[d]={}),p.limit!==void 0&&(n.embeddedTransforms[d].limit=p.limit),p.offset!==void 0&&(n.embeddedTransforms[d].offset=p.offset);}let u=new Set([...Object.keys(a),...Object.keys(l)]);for(let d of u){let p=new Set([...Object.keys(a[d]??{}),...Object.keys(l[d]??{})]);for(let y of p){let h=Ua(a[d]?.[y],l[d]?.[y]),b=n.embeddedTransforms[d]?._nested?.[y];b&&(h.limit!==void 0&&(b.limit=h.limit),h.offset!==void 0&&(b.offset=h.offset));}}return n}function Ma(t){return Jy(t).map(({entry:e,start:n})=>Ky(e.trim(),t,n+e.length-e.trimStart().length))}function Jy(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 Ky(t,e,n){let r=t.split("."),s={column:r[0]},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 f=Wy(i);if(f){if(f.column.includes(","))throw new pe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",f.embed.length)+1);s.column=f.column,s.embed=f.embed;}let u=n+i.length+1,d=false,p=false;for(let y=1;y<r.length;y++){let h=r[y];if(h==="asc"||h==="desc"){if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);s.direction=h,d=true,u+=h.length+1;}else if(h==="nullsfirst"||h==="nullslast"){if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);s.nullsFirst=h==="nullsfirst",p=true,u+=h.length+1;}else {let b=["asc","desc","nullsfirst","nullslast"],m=null;for(let w of b)if(h.startsWith(w)&&h.length>w.length){m=w;break}if(m){let w=h[m.length],_=u+m.length;throw new pe(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,_+1)}throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1)}}return s}function Ba(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count=i.value;break;case "missing":r.missing=i.value;break;case "handling":r.handling=i.value;break;case "tx":r.tx=i.value,i.value==="rollback"&&(r.rollback=true);break;case "max-affected":r.maxAffected=i.value;break;case "timezone":r.timezone=i.value;break;case "return":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=Gy(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=Hy("columns",i);}return r}function Hy(t,e){let n=e.split(",").map(r=>zy(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 zy(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function Gy(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 qa(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(gn.has(a))continue;let c=l[0];jr(c)||(i[a]=xt(c));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function Wa(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:Vy(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function Vy(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}async function Ti(t,e){let n=e?.basePath,r=e?.parseRoute??(z=>Ca(z,n)),s=e?.parseHeaders??Ra,i=e?.parseSelect??Oa,o=e?.parseBody??$a,a=e?.parseQueryParams??Pa,l=e?.resolveType??Na,c=e?.resolveFilters??La,f=e?.resolveTransforms??Fa,u=e?.resolveMeta??Ba,d=e?.resolveRpcParams??qa,p=e?.resolveUpsertParams??Wa,[y,h,b,m,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),_=t.method,S=l(y,_,h),E=w;if(y.isRpc&&_.toUpperCase()==="GET"){E=new Map;for(let[z,I]of w){if(gn.has(z)){E.set(z,I);continue}let ue=I.filter(Xe=>jr(Xe));ue.length>0&&E.set(z,ue);}}let C=c(E,b.embeddedAliases),x=f(w,b.embeddedAliases),R=u(h,w,_),v=d(y,_,w,m),k=S==="upsert"||S==="put"?p(w,h):void 0;return Qy(S,y,h,b,m,C,x,R,v,k)}function Qy(t,e,n,r,s,i,o,a,l,c){let f={type:t};return e.isRpc?f.function=e.function:f.from=e.from,n.schema&&(f.schema=n.schema),Object.keys(r.join).length>0&&(f.join=r.join),r.select.length>0&&(f.select=Cf(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(f.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(f.values=s.values),t==="rpc"&&(l.args!==void 0&&(f.args=l.args),l.httpMethod&&(f.httpMethod=l.httpMethod),l.paramsType&&(f.paramsType=l.paramsType),l.inputType&&(f.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(f.onConflict=c.onConflict),f.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!f.select||f.select.length===0)&&(f.select=["*"]),o.order&&(f.order=o.order),o.limit!==void 0&&(f.limit=o.limit),o.offset!==void 0&&(f.offset=o.offset),Object.keys(a).length>0&&(f.$meta=a),f}function Cf(t,e,n,r){return t.map(s=>{if(typeof s=="string")return s;let i=Object.keys(s)[0],o=s[i];if(!o.select)return s;let a={...o},l=r?.[i]?.from,c=e[i]||l&&e[l],f=n[i]||l&&n[l];if(c){let u={},d={};for(let[p,y]of Object.entries(c)){let h=p.indexOf(".");if(h>0){let b=p.slice(0,h),m=p.slice(h+1);if(a.join?.[b]||a.select?.some(S=>typeof S=="object"&&b in S&&"select"in(S[b]??{}))){d[b]||(d[b]={}),d[b][m]=y;continue}}u[p]=y;}Object.keys(u).length>0&&(a.where=u);for(let[p,y]of Object.entries(d))e[p]={...e[p],...y};}if(f){let u=f;if(u.order&&(a.order=u.order),u.limit!==void 0&&(a.limit=u.limit),u.offset!==void 0&&(a.offset=u.offset),u._nested)for(let[d,p]of Object.entries(u._nested))n[d]=p;}return a.select&&(a.select=Cf(a.select,e,n,a.join)),{[i]:a}})}function ki(t){return t!=null&&typeof t=="object"&&"$ref"in t}var Xy=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,Yy=/[;'"\\/*\-#]/,Zy=/['\\;(]/,vt=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Ct(t,e){if(!Xy.test(t))throw new vt(t,e)}function Ja(t,e){if(Yy.test(t))throw new vt(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new vt(t,e);if(n!==0)throw new vt(t,e)}function Hn(t,e){if(Zy.test(t))throw new vt(t,e)}function bn(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 Br(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||Hn(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 eb(t){return `"${t.replace(/"/g,'""')}"`}function Rf(t){return sql.raw(eb(t))}function Tf(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 Ai(t,e,n=e.currentTable,r=e.currentSchema){return Tf(t,e,n,r)!==void 0}function oe(t,e,n=e.currentTable){return Ai(t,e,n)?Rf(t):sql.ref(t)}function Xt(t,e,n,r=n.currentTable){let s=Ai(e,n,r)?Rf(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function tb(t){return (t?.pg_type??t?.type??"").toLowerCase()}function kf(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=tb(Tf(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function Af(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Of(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return oe(t,n,r);if(kf(t,n,r)){let l=Af(i);if(l)return sql`${oe(t,n,r)}${sql.raw(l)}`}let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=Br(o,"JSON path key");return sql`${oe(t,n,r)}${sql.raw(a)}`}function qr(t,e,n=e.currentTable,r){let{col:s,parts:i}=bn(t),o=r?Xt(r,s,e,n):oe(s,e,n);if(i.length===0)return o;if(kf(s,e,n)){let c=Af(i.map(f=>f.key));if(c)return sql`${o}${sql.raw(c)}`}let a=e.dialect==="sqlite"?i.map((c,f)=>f===i.length-1?{...c,op:"->>"}:c):i,l=Br(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Oi={$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===Ri?sql`${r} IS NOT NULL`:n===yn?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===Ri?sql`${r} IS NULL`:n===yn?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}`},$i={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function Ka(t){return t!=null&&typeof t=="object"&&t.type==="query"}function Pi(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),Ha(t,e,n)}function nb(t){return t.includes("->")}function Nf(t,e){let{col:n,parts:r}=bn(t);return r.length===0?oe(t,e):qr(t,e)}function Pe(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=>Pe(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Pe(t,a,n))));}else if(s==="$not")r.push(t.not(Pe(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(Pi(o,n)));}else {let o=i,a=nb(s);for(let[l,c]of Object.entries(o)){if(ki(c)){let f=$i[l];if(!f)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Nf(s,n):oe(s,n)} ${sql.raw(f)} ${oe(c.$ref,n)}`);continue}if(l==="$not"){let f=c;for(let[u,d]of Object.entries(f))if(a)r.push(t.not(Pf(s,u,d,n)));else {let p=$f(s,u,d,n);if(p){r.push(t.not(p));continue}let y=n.operators[u];if(!y)throw new Error(`Unsupported operator: ${u}`);r.push(t.not(y(t,oe(s,n),d)));}}else if(Ka(c)){let f=Pi(c,n),u=n.operators[l];if(!u)throw new Error(`Unsupported operator: ${l}`);r.push(u(t,oe(s,n),f));}else if(a)r.push(Pf(s,l,c,n));else {let f=$f(s,l,c,n);if(f){r.push(f);continue}let u=rb(s,l,c,n);if(u){r.push(u);continue}let d=n.operators[l];if(!d)throw new Error(`Unsupported operator: ${l}`);r.push(d(t,oe(s,n),c));}}}}return r.length===1?r[0]:t.and(r)}function $f(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==yn)return null;let s=If(t,r);if(!s)return null;let i=Df(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${oe(t,r)} IS NULL`:sql`${oe(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 If(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?bn(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]}function Df(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 rb(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=If(t,r),i=Df(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=oe(t,r),a=sql`cast(${sql.raw(sb(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function sb(t){return `'${t.replace(/'/g,"''")}'`}function Pf(t,e,n,r){let s=r?Nf(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&&Ka(n))return sql`${s} in ${Pi(n,r)}`;let a=n;return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&Ka(n))return sql`${s} not in ${Pi(n,r)}`;let a=n;return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function ce(t){return "select"in t||"spread"in t||"join"in t}function ji(t,e,n,r,s,i=false){if(!e||e.length===0)return t.selectAll();for(let o of e)if(typeof o=="string")if(o==="*")t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(o))t=t.select(sql.lit(Number(o)).as("_lit"));else if(mb(o,n,s)){let a=i&&s?Xt(s,o,n,s):oe(o,n,s);t=t.select(sql`json(${a})`.as(o));}else t=i&&s&&!o.includes(".")?t.select(Xt(s,o,n,s).as(o)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)&&Ai(o,n,s)?t.select(oe(o,n,s).as(o)):t.select(o);else for(let[a,l]of Object.entries(o))ce(l)?t=Tb(t,a,l,n,r,s):t=lb(t,a,l,n,s,i);return t}function Jr(t,e){if(!e||e.length===0)return t;for(let n of e)if(typeof n=="string")t=n==="*"?t.returningAll():t.returning(n);else for(let[r,s]of Object.entries(n)){if(ce(s))continue;let i=s.column||r;t=t.returning(i);}return t}function wn(t,e,n,r,s,i=false){let o;if(n.aggregate==="count"&&!n.column&&!n.path)o=t.fn.countAll();else {let a=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${ib(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});o=n.path?Of(a,n.path,r,s,n.pathText===true):s&&i?Xt(s,a,r,s):oe(a,r,s),n.preCast&&(Ja(n.preCast,"pre-cast type"),o=sql`cast(${o} as ${sql.raw(n.preCast)})`),n.aggregate&&(o=sql`${sql.raw(n.aggregate)}(${o})`);}return n.cast&&(Ja(n.cast,"cast type"),o=r.dialect==="sqlite"&&(ob(n.cast)||ab(n.cast))?sql`json(${o})`:sql`cast(${o} as ${sql.raw(n.cast)})`),o}function ib(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function ob(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function ab(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function lb(t,e,n,r,s,i=false){return t.select(o=>wn(o,e,n,r,s,i).as(e))}function cb(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!ce(n)&&n.aggregate)return true}return false}function ub(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ce(n)&&n.spread&&Ga(n.select))return true}return false}function fb(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ce(n)&&n.spread)return true}return false}function db(t){return cb(t)||ub(t)}function Ga(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ce(n)){if(Ga(n.select))return true;continue}if(n.aggregate)return true}return false}function Va(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ce(n)){if(n.spread)continue;if(Va(n.select))return true;continue}let r=n;if(r.aggregate&&!r.bareCount)return true}return false}function Qa(t,e,n,r,s){if(!db(e))return t;let i=[];for(let o of e){if(typeof o=="string"){if(o==="*")continue;i.push(oe(o,n,r));continue}for(let[a,l]of Object.entries(o)){if(ce(l))continue;let c=l;c.aggregate||i.push(f=>wn(f,a,c,n,r));}}return pb(i,e,n,r,s),i.length===0?t:t.groupBy(i)}function pb(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(!ce(a)||!a.spread)continue;let l=a,c=s?.[o],f=c?.from||o;f=Tt(f,r,n.introspection);let u=Te(n.introspection,r,f,c?.hint),d=u?.type==="m2o"||u?.type==="o2m"&&ct(u,f,n.introspection);if(!u||!d)continue;let p=Li(l.select,f,n.introspection)??l.select??[],y=`_spread_${o}`;for(let h of p){if(typeof h=="string"){h!=="*"&&t.push(`${y}.${h}`);continue}let[b,m]=Object.entries(h)[0];ce(m)||m.aggregate||t.push(w=>wn(w,b,m,n,y,true));}}}}function Lf(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(!ce(l)||!l.spread)continue;let c=n?.[a],f=c?.from||a;f=Tt(f,r,s.introspection);let u=Te(s.introspection,r,f,c?.hint),d=u?.type==="m2o"||u?.type==="o2m"&&ct(u,f,s.introspection);u&&d&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function Uf(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(!ce(o)||!o.spread)continue;let a=e?.[i],l=a?.from||i;l=Tt(l,n,r.introspection);let c=Te(r.introspection,n,l,a?.hint),f=c?.type==="m2o"||c?.type==="o2m"&&ct(c,l,r.introspection);if(c&&f)return true}return false}function Ni(t){let e=new Map;for(let n of t){let r=n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Xa(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 Ya(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;if(e.type==="m2o"){let[,l]=e.leftCol.split("."),[,c]=e.rightCol.split(".");return t.leftJoin(i,f=>f.onRef(`${s}.${c}`,"=",`${r}.${l}`))}let[,o]=e.leftCol.split("."),[,a]=e.rightCol.split(".");return t.leftJoin(i,l=>l.onRef(`${s}.${o}`,"=",`${r}.${a}`))}function Kr(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;Ct(o.embed,"order embed alias");let a=s?.[o.embed],l=el(o.embed,a,n,r.introspection);l!==o.embed&&Ct(l,"order embed target");let c=Te(r.introspection,n,l,a?.hint),f=c?.type==="m2o"||c?.type==="o2m"&&ct(c,l,r.introspection);!c||!f||(t=Ya(t,c,l,n,o.embed),i.add(o.embed),i.add(l));}return {sub:t,joined:i}}function Mf(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function za(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>za(i,e)):r==="$not"?n[r]=za(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function Ii(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 mb(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Ii(e,n,t)}function hb(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 Wr(t,e,n,r){return Ii(t,e,n)||hb(r,n)}function gb(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:Ii(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(ce(o))return null;let a=Ii(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function yb(t,e,n,r){let s=gb(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 bb(t){return t==="m2o"?"many-to-one":t==="o2m"?"one-to-many":"many-to-many"}function wb(t,e,n){return t.fk?t.type==="m2m"?`${t.fk.foreign_key_name} using ${t.junctionTable}(${t.fk.column}) and ${e}(${t.fk.ref_column})`:`${t.fk.foreign_key_name} using ${t.fk.table}(${t.fk.column}) and ${t.fk.ref_table}(${t.fk.ref_column})`:""}function Sb(t,e){if(!t||!e)return null;let n=[];for(let s of t.tables??[])n.push(s.name);for(let s of t.views??[])n.push(s.name);let r=n.find(s=>s.length===e.length+1&&s.startsWith(e));return r?`Perhaps you meant '${r}' instead of '${e}'.`:null}function Za(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 Ae({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:Sb(t,n)})}function Te(t,e,n,r){if(!t||!t.foreign_keys)return null;let s=t.foreign_keys.filter(p=>p.is_visible!==false);if(r){let p=s.find(E=>E.foreign_key_name===r);if(p){if(p.table===e&&p.ref_table===n)return {leftCol:`${e}.${p.column}`,rightCol:`${n}.${p.ref_column}`,type:"m2o"};if(p.table===n&&p.ref_table===e)return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}let y=s.find(E=>E.table===e&&E.column===r&&E.ref_table===n);if(y)return {leftCol:`${e}.${y.column}`,rightCol:`${n}.${y.ref_column}`,type:"m2o"};let h=s.find(E=>E.table===n&&E.column===r&&E.ref_table===e);if(h)return {leftCol:`${n}.${h.column}`,rightCol:`${e}.${h.ref_column}`,type:"o2m"};let b=s.filter(E=>E.table===r),m=Ni(b.filter(E=>E.ref_table===e)),w=Ni(b.filter(E=>E.ref_table===n));if(m.length>0&&w.length>0){let E=m[0],C=w[0];return {type:"m2m",junctionTable:r,junctionToParentCols:E.map(x=>x.column),parentCols:E.map(x=>x.ref_column),junctionToTargetCols:C.map(x=>x.column),targetCols:C.map(x=>x.ref_column)}}let _=s.find(E=>E.table===n&&E.ref_column===r&&E.ref_table===e);if(_)return {leftCol:`${n}.${_.column}`,rightCol:`${e}.${_.ref_column}`,type:"o2m"};let S=s.find(E=>E.table===e&&E.ref_column===r&&E.ref_table===n);if(S)return {leftCol:`${e}.${S.column}`,rightCol:`${n}.${S.ref_column}`,type:"m2o"};Za(t,e,n,r);}if(e===n){let p=s.find(y=>y.table===n&&y.ref_table===e);if(p)return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}let i=s.filter(p=>p.table===e&&p.ref_table===n),o=[...new Map(i.map(p=>[p.foreign_key_name,p])).values()],a=s.filter(p=>p.table===n&&p.ref_table===e),l=[...new Map(a.map(p=>[p.foreign_key_name,p])).values()],c=[],f=Ni(s.filter(p=>p.ref_table===e));for(let p of f){let y=p[0].table;if(y===e||y===n)continue;let h=s.filter(b=>b.table===y&&b.ref_table===n);if(h.length!==0)for(let b of Ni(h))c.push({type:"m2m",junctionTable:y,junctionToParentCols:p.map(m=>m.column),parentCols:p.map(m=>m.ref_column),junctionToTargetCols:b.map(m=>m.column),targetCols:b.map(m=>m.ref_column),fk:p[0]});}if(o.length+l.length+c.length===0)return null;if(o.length>1||l.length>1){let p=[...o.map(m=>({leftCol:`${e}.${m.column}`,rightCol:`${n}.${m.ref_column}`,type:"m2o",fk:m})),...l.map(m=>({leftCol:`${n}.${m.column}`,rightCol:`${e}.${m.ref_column}`,type:"o2m",fk:m})),...c],y=p.map(m=>({cardinality:bb(m.type),embedding:`${e} with ${n}`,relationship:wb(m,e)})),b=p.map(m=>m.fk?.foreign_key_name).filter(Boolean).map(m=>`'${n}!${m}'`).join(", ");throw new Ae({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:y,hint:b?`Try changing '${n}' to one of the following: ${b}. Find the desired relationship in the 'details' key.`:null})}if(o.length===1){let p=o[0];return {leftCol:`${e}.${p.column}`,rightCol:`${n}.${p.ref_column}`,type:"m2o"}}if(l.length===1){let p=l[0];return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}return c.length===1?c[0]:null}function Ff(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=el(s.embed,i,n,r.introspection),a=Te(r.introspection,n,o,i?.hint);if(!a)continue;if(!(a.type==="m2o"||a.type==="o2m"&&ct(a,o,r.introspection)))throw new Ae({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 Tt(t,e,n){if(!n?.foreign_keys||n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t))return t;let s=n.foreign_keys,i=s.find(l=>l.table===e&&l.column===t);if(i)return i.ref_table;let o=s.find(l=>l.foreign_key_name===t&&(l.table===e||l.ref_table===e));if(o)return o.table===e?o.ref_table:o.table;let a=s.find(l=>l.ref_table===e&&l.ref_column===t);return a?a.table:t}function jf(t,e,n,r,s,i){let o=s?.[e],a=o?.from||e;i&&(a=Tt(a,i,r.introspection));let l=i?Te(r.introspection,i,a,o?.hint):null;return t.where(c=>{let f=c.selectFrom(a).select(sql`1`.as("_"));return o?.on?f=f.where(u=>Pe(u,o.on,r)):l&&l.type==="m2m"?f=Xa(f,l,a,i):l?f=f.whereRef(l.leftCol,"=",l.rightCol):i&&(f=f.whereRef(`${a}.${i}_id`,"=",`${i}.id`)),n.where&&Object.keys(n.where).length>0&&(f=f.where(u=>Pe(u,n.where,r))),c.exists(f)})}function ct(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 Eb(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Hr(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=o?.from||e;a=Tt(a,i,r.introspection);let l=Te(r.introspection,i,a,o?.hint),c=Li(n.select,a,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return Rb(t,c,a,i,l);if(!l)throw new Ae({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(!(l.type==="m2o"||l.type==="o2m"&&ct(l,a,r.introspection))){if(Ga(n.select))throw new Ae({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 vb(t,c,n,l,a,i,r)}let u=`_spread_${e}`,[d,p]=l.leftCol.split("."),[,y]=l.rightCol.split("."),h=d===a?p:y,b=d===i?p:y,m="__spread_join_key",w=[],_=new Set;for(let S of c){if(typeof S=="string"&&S==="*")continue;let E;if(typeof S!="string"){let R=Object.values(S)[0];if(ce(R))continue;E=R;}let{colAlias:C,colName:x}=Hr(S);w.push({src:x,out:C,def:E}),_.add(x);}t=t.leftJoin(S=>{let E=S.selectFrom(a);E=E.select(`${a}.${h} as ${m}`);for(let C of _)E=E.select(`${a}.${C} as ${C}`);return E.as(u)},S=>S.onRef(`${u}.${m}`,"=",`${i}.${b}`));for(let{out:S,def:E}of w)E?t=t.select(C=>wn(C,S,E,r,u,true).as(S)):t=t.select(`${u}.${S}`);return t}function xb(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=Object.values(s)[0];if(!ce(i))continue;let{colAlias:o}=Hr(s),a=e.join?.[o],l=Tt(a?.from||o,n,r.introspection),c=Te(r.introspection,n,l,a?.hint);if(!c||c.type!=="o2m"||!ct(c,l,r.introspection))continue;let f=r.introspection?.primary_keys?.find(u=>u.table===l);if(f?.columns?.length)return {nestedTargetTable:l,fkRel:c,pkColumns:f.columns}}return null}function vb(t,e,n,r,s,i,o){let a=n.order?null:xb(e,n,s,o);for(let l of e){if(typeof l=="string"&&l==="*")continue;let c=typeof l=="string"?null:Object.values(l)[0],f=c!==null&&ce(c),u=f&&c.spread,{colAlias:d,colName:p}=Hr(l);if(u){t=Cb(t,d,c,n,r,s,i,o);continue}t=t.select(y=>{let h=y.selectFrom(s);if(h=Di(h,r,s,i),n.where&&Object.keys(n.where).length>0&&(h=h.where(b=>Pe(b,n.where,o))),n.order&&(h=Kr(h,n.order,s,o,n.join).sub,h=Rt(h,Mf(n.order),void 0,o,s)),n.limit!==void 0&&(h=h.limit(n.limit)),n.offset!==void 0&&(h=h.offset(n.offset)),a&&(h=Ya(h,a.fkRel,a.nestedTargetTable,s),h=Rt(h,a.pkColumns.map(b=>({column:b,embed:a.nestedTargetTable})),void 0,o)),f){let b=n.join?.[d];return h=h.select(m=>Bf(m,d,c,o,b,s).as("value")),o.jsonScalarArrayFrom(h,"value",true).as(d)}else return c!==null?(h=h.select(b=>wn(b,p,c,o,s).as("value")),o.jsonScalarArrayFrom(h,"value",Wr(o,s,p,n.order)).as(d)):(h=h.select(`${s}.${p} as value`),o.jsonScalarArrayFrom(h,"value",Wr(o,s,p,n.order)).as(d))});}return t}function Cb(t,e,n,r,s,i,o,a){let l=r.join?.[e],c=Tt(l?.from||e,i,a.introspection),f=Te(a.introspection,i,c,l?.hint),u=Li(n.select,c,a.introspection)??n.select??[],d=f?.type==="m2o"||f?.type==="o2m"&&ct(f,c,a.introspection);for(let p of u){if(typeof p=="string"&&p==="*")continue;let y=typeof p=="string"?null:Object.values(p)[0],{colAlias:h,colName:b}=Hr(p);t=t.select(m=>{let w=m.selectFrom(i);w=Di(w,s,i,o),r.where&&Object.keys(r.where).length>0&&(w=w.where(S=>Pe(S,r.where,a)));let _=Kr(w,r.order,i,a,r.join);if(w=_.sub,r.order&&(w=Rt(w,Mf(r.order),void 0,a,i)),r.limit!==void 0&&(w=w.limit(r.limit)),r.offset!==void 0&&(w=w.offset(r.offset)),!f)return w=w.where(sql`1 = 0`).select(sql`null`.as("value")),a.jsonScalarArrayFrom(w).as(h);if(d){if(_.joined.has(c)||(w=Ya(w,f,c,i)),!r.order&&f.type==="o2m"){let S=a.introspection?.primary_keys?.find(E=>E.table===c);S?.columns?.length&&(w=Rt(w,S.columns.map(E=>({column:E,embed:c})),void 0,a));}if(y!==null&&!ce(y)){let S={...y,column:`${c}.${b}`};w=w.select(E=>wn(E,h,S,a).as("value"));}else w=w.select(`${c}.${b} as value`);return a.jsonScalarArrayFrom(w,"value",Wr(a,c,b,r.order)).as(h)}else return w=w.select(S=>{let E=S.selectFrom(c);return E=Di(E,f,c,i),y!==null&&!ce(y)?(E=E.select(C=>wn(C,b,y,a,c).as("value")),a.jsonScalarArrayFrom(E,"value",Wr(a,c,b,r.order)).as("value")):(E=E.select(`${c}.${b} as value`),a.jsonScalarArrayFrom(E,"value",Wr(a,c,b,r.order)).as("value"))}),a.jsonScalarArrayFrom(w,"value",true).as(h)});}return t}function Di(t,e,n,r){return e.type==="m2m"?Xa(t,e,n,r):t.whereRef(e.leftCol,"=",e.rightCol)}function Rb(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Hr(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);return s&&s.type!=="m2m"?c=c.whereRef(s.leftCol,"=",s.rightCol):c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`),c=c.limit(1),c.as(o)});}return t}function Li(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 el(t,e,n,r){let s=e?.from||t;if(!r?.foreign_keys||r.tables?.some(f=>f.name===s)||r.views?.some(f=>f.name===s))return s;let o=r.foreign_keys,a=o.find(f=>f.table===n&&f.column===s);if(a)return a.ref_table;let l=o.find(f=>f.foreign_key_name===s&&(f.table===n||f.ref_table===n));if(l)return l.table===n?l.ref_table:l.table;let c=o.find(f=>f.ref_table===n&&f.ref_column===s);return c?c.table:s}function Tb(t,e,n,r,s,i){let o=s?.[e];if(!n.select||n.select.length===0){if(o?.type==="inner"&&i)return jf(t,e,n,r,s,i);if(i&&!o?.on&&r.introspection?.foreign_keys){let a=el(e,o,i,r.introspection);Te(r.introspection,i,a,o?.hint)||Za(r.introspection,i,a,o?.hint);}return t}return o?.type==="inner"&&i&&(t=jf(t,e,n,r,s,i)),n.spread&&i?_b(t,e,n,r,s,i):t.select(a=>Bf(a,e,n,r,o,i).as(e))}function Bf(t,e,n,r,s,i){let o=s?.from||e;if(i&&r.introspection?.foreign_keys){let _=r.introspection.foreign_keys.find(S=>S.table===i&&S.column===o);if(_)o=_.ref_table;else {let S=r.introspection.foreign_keys.find(E=>E.foreign_key_name===o&&(E.table===i||E.ref_table===i));if(S)o=S.table===i?S.ref_table:S.table;else {let E=r.introspection.foreign_keys.find(C=>C.ref_table===i&&C.ref_column===o);E&&(o=E.table);}}}let a=i===o,l=a?`${o}_self`:o,c=a?`${o} as ${l}`:o,f=t.selectFrom(c),u=i&&!s?.on?Te(r.introspection,i,o,s?.hint):null,d=u?.type==="m2m",p=Li(n.select,o,r.introspection),y=d?Eb(p,l):p;if(f=ji(f,y,r,n.join,l,fb(y)),n.where&&Object.keys(n.where).length>0){let _=Ui(f,n.where,n.select,n.join,o,r);f=_.qb,Object.keys(_.remainingWhere).length>0&&(f=f.where(S=>Pe(S,_.remainingWhere,r)));}let h="o2m";if(s?.on)f=f.where(_=>Pe(_,s.on,r));else if(i){let _=Te(r.introspection,i,o,s?.hint);if(_&&_.type==="m2m")h="m2m",f=Xa(f,_,l,i);else if(_){let S=a?_.leftCol.replace(`${o}.`,`${l}.`):_.leftCol;f=f.whereRef(S,"=",_.rightCol),h=_.type;}else r.introspection?.foreign_keys?Za(r.introspection,i,o,s?.hint):f=f.whereRef(`${l}.${i}_id`,"=",`${i}.id`);}f=Qa(f,y,r,o),n.order?.some(_=>_.embed)&&(f=Kr(f,n.order,o,r,n.join).sub),f=Rt(f,n.order,void 0,r,o),h==="m2m"&&!n.order&&u?.type==="m2m"&&r.dialect==="sqlite"&&(f=f.orderBy(`${u.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(f=f.limit(n.limit)),n.offset!==void 0&&(f=f.offset(n.offset));let b=false;if(h==="o2m"&&i&&r.introspection){let _=Te(r.introspection,i,o,s?.hint);_&&_.type==="o2m"&&(b=ct(_,o,r.introspection));}let m=n.spread||h==="m2o"||b;return m&&r.dialect==="sqlite"?yb(f,y,o,r):(m?r.jsonObjectFrom:r.jsonArrayFrom)(f)}function qf(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){if(typeof s=="string")continue;let[i,o]=Object.entries(s)[0];if(!ce(o)||!o.spread)continue;let l=e?.[i],c=Tt(l?.from||i,n,r.introspection),f=Te(r.introspection,n,c,l?.hint);if(!f)continue;if(!(f.type==="m2o"||f.type==="o2m"&&ct(f,c,r.introspection)))return true}return false}function Ui(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!Kf(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=Wf(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 Wf(t,e,n,r,s,i){let o=[],a={};for(let[c,f]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(f)){let d=f.map(p=>Wf(t,p,n,r,s,i));if(d.length>0&&d.every(p=>p.fullyHandled&&p.expression)){o.push(c==="$or"?t.or(d.map(p=>p.expression)):t.and(d.map(p=>p.expression)));continue}a[c]=f;continue}let u=kb(t,c,f,n,r,s,i);u?o.push(u):a[c]=f;}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 kb(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 f=Jf(r,e);if(!f)return null;let u=s?.[e],d=Tt(u?.from||e,i,o.introspection),p=Te(o.introspection,i,d,u?.hint);if(!p)return null;let y=t.selectFrom(d).select(sql`1`.as("_"));if(u?.on?y=y.where(b=>Pe(b,u.on,o)):y=Di(y,p,d,i),f.where&&Object.keys(f.where).length>0){let b=Ui(y,f.where,f.select,f.join,d,o);if(y=b.qb,Object.keys(b.remainingWhere).length>0){let m=za(b.remainingWhere,d);y=y.where(w=>Pe(w,m,o));}}let h=t.exists(y);return c?h:t.not(h)}function Jf(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&ce(r))return r}return null}function Kf(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>Kf(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)&&Jf(e,n))return true}return false}function Ab(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function tl(t,e,n,r,s={}){if(!t)return t;let i=Ab(e,n,r),o=a=>{let l=Ob(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):$b(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function Ob(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??Gf(n,r,s,o)??void 0;i[o]=Pb(a,l);}return i}function $b(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=Gf(e,n,r,i);s[i]=Db(a)?jb(o):o;}return s}function Gf(t,e,n,r){let i=(t.introspection?.columns??[]).filter(a=>a.table===n&&a.name===r);if(i.length===0)return;let o=i.find(a=>a.schema===(e??"public"))??i.find(a=>a.schema==="public")??i[0];return o.pg_type??o.type}function Pb(t,e){if(t==null||typeof t!="string")return t;let n=Vf(e);return n==="boolean"?Nb(t):n==="integer"?Hf(t,true):n==="number"?Hf(t,false):n==="json"?Qf(t):n==="array"?Ib(t):t}function Vf(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 Nb(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 Hf(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 Qf(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function Ib(t){let e=Qf(t);return Array.isArray(e)?e:t}function Db(t){let e=Vf(t);return e==="json"||e==="array"}function jb(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function Xf(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema)),t.type){case "query":return Ha(t,e,n);case "insert":return Ub(t,e,n);case "update":return Mb(t,e,n);case "delete":return Fb(t,e,n);case "upsert":case "put":return Bb(t,e,n);case "rpc":return qb(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Rt(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Ct(i.embed,"order embed alias"),i.column.includes("->")?r?qr(i.column,r,s,i.embed):zf(i.column,i.embed):(Ct(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?qr(i.column,r,s,n):zf(i.column,void 0,n):n?r?Xt(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?oe(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 zf(t,e,n){let{col:r,parts:s}=bn(t);if(s.length===0)return sql.ref(t);e&&Ct(r,"order embed column");let i=Br(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 zr(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Pe(i,e,{...n,currentTable:r,currentSchema:s}))}function Ha(t,e,n){let r=n.selectFrom(t.from);r=Lb(r,t.join,t.select);let s=t.order?.some(f=>f.embed)===true;r=ji(r,t.select,e,t.join,t.from,s||Uf(t.select,t.join,t.from,e));let i=t.where??{},{qb:o,remainingWhere:a}=t.from?Ui(r,i,t.select,t.join,t.from,e):{qb:r,remainingWhere:i};r=o,r=zr(r,a,e,t.from,t.schema),r=Qa(r,t.select,e,t.from,t.join),Ff(t.order,t.join,t.from,e),t.from&&s&&(r=Kr(r,t.order,t.from,e,t.join).sub);let l=t.from&&qf(t.select,t.join,t.from,e)?t.from:void 0,c=Lf(t.order,t.select,t.join,t.from,e);return r=Rt(r,c,l,e,t.from),t.limit!==void 0&&(r=r.limit(t.limit)),t.offset!==void 0&&(r=r.offset(t.offset)),r}function Lb(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=>Yf(l,i.on));}return t}function Yf(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=Yf(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=$i[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);ki(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function Ub(t,e,n){let r=n.insertInto(t.from);if(t.values){let s=tl(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(s);}return r=Jr(r,t.select),r}function Mb(t,e,n){let r=n.updateTable(t.from);if(t.values){let s=tl(t.values,e,t.schema,t.from);r=r.set(s);}return t.limit!==void 0||t.offset!==void 0?r=Zf(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema),r=Jr(r,t.select),r}function Fb(t,e,n){let r=n.deleteFrom(t.from);return t.limit!==void 0||t.offset!==void 0?r=Zf(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema),r=Jr(r,t.select),r}function Zf(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=zr(o,e.where??{},n,e.from,e.schema),o=Rt(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 f of i)c=c.whereRef(`${l}.${f}`,"=",`${e.from}.${f}`);return t.where(f=>f.exists(c))}else return t.where(sql.ref(a),"in",o)}function Bb(t,e,n){let r=t.values,s=tl(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);return t.onConflict&&(i=i.onConflict(o=>{let a=t.onConflict.length===1?o.column(t.onConflict[0]):o.columns(t.onConflict);if(t.ignoreDuplicates)return a.doNothing();let l=Array.isArray(s)?s[0]:s,c=Object.keys(l).filter(f=>!t.onConflict.includes(f));return c.length===0?a.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):a.doUpdateSet(f=>{let u={};for(let d of c)u[d]=f.ref(`excluded.${d}`);return u})})),i=Jr(i,t.select),i}function qb(t,e,n){let r=t.function;Ct(r,"RPC function name");let s;if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let a=Object.entries(t.args).map(([l,c])=>(Ct(l,"RPC param key"),sql`${sql.raw(l)} := ${c}`));s=sql`${sql.raw(r)}(${sql.join(a)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let o=t.args.map(a=>sql`${a}`);s=sql`${sql.raw(r)}(${sql.join(o)})`;}else s=sql`${sql.raw(r)}()`;let i=n.selectFrom(s.as(r));return i=ji(i,t.select,e),i=zr(i,t.where??{},e,t.from,t.schema),i=Rt(i,t.order,void 0,e,t.from),t.limit!==void 0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset)),i}var Qb=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),Xb={$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 Yb(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||Hn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function Zb(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var ed={db:Qb,operators:{...Oi,...Xb},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:Zb,jsonPath:Yb,rowIdColumn:"ctid"};var aw=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function lw(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||Hn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function cw(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 uw(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=>(Hn(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 `)}`}function Mi(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=n==="ilike"?sql`lower(${s})`:s,o=e.map(a=>n==="ilike"?sql`${i} like lower(${a})`:sql`${i} like ${a}`);return sql`(${sql.join(o,r==="any"?sql` or `:sql` and `)})`}var fw={$ilike:(t,e,n)=>sql`lower(${A(e)}) like lower(${n})`,$likeAny:(t,e,n)=>Mi(e,n,"like","any"),$ilikeAny:(t,e,n)=>Mi(e,n,"ilike","any"),$likeAll:(t,e,n)=>Mi(e,n,"like","all"),$ilikeAll:(t,e,n)=>Mi(e,n,"ilike","all"),$contains:(t,e,n)=>{if(Array.isArray(n))return cw(e,n);if(n!==null&&typeof n=="object")return uw(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);if(n.length===0)return sql`${r} is not null and not exists (select 1 from json_each(${r}))`;let s=sql.join(n.map(i=>sql`${i}`));return sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${s}))`},$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 dw(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 td={db:aw,operators:{...Oi,...fw},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:dw,jsonPath:lw,rowIdColumn:"rowid"};function pw(t){switch(t){case "postgres":return ed;case "sqlite":return td;default:throw new Error(`Unsupported dialect: ${t}`)}}function me(t,e="postgres",n){let r=pw(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return Xf(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var ze=ou(sd());Yr();Gr();var Zr=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;}},ll=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)}};Xr();var zn=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Wi();function O(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 Ze(t){return O(t.status,t.code,t.message,t.details??null,t.hint??null)}var En=new TextEncoder,kt=new TextDecoder;function Ji(...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 Zt(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 gd(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 yd(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 Gn(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:kt.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=kt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return yd(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Ki(t){let e=t;return typeof e=="string"&&(e=En.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:true}):gd(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ot={};xr(Ot,{JOSEAlgNotAllowed:()=>es,JOSEError:()=>he,JOSENotSupported:()=>Fe,JWEDecryptionFailed:()=>cl,JWEInvalid:()=>ul,JWKInvalid:()=>fl,JWKSInvalid:()=>dl,JWKSMultipleMatchingKeys:()=>ml,JWKSNoMatchingKey:()=>pl,JWKSTimeout:()=>hl,JWSInvalid:()=>G,JWSSignatureVerificationFailed:()=>ts,JWTClaimValidationFailed:()=>Ne,JWTExpired:()=>Vn,JWTInvalid:()=>At});var he=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);}},Ne=class extends he{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;}},Vn=class extends he{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;}},es=class extends he{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Fe=class extends he{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},cl=class extends he{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",n){super(e,n);}},ul=class extends he{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},G=class extends he{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},At=class extends he{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},fl=class extends he{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},dl=class extends he{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},pl=class extends he{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);}},ml=class extends he{[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);}},hl=class extends he{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",n){super(e,n);}},ts=class extends he{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",n){super(e,n);}};var ut=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Qn=(t,e)=>t.name===e;function gl(t){return parseInt(t.name.slice(4),10)}function Cw(t){switch(t){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}function Rw(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function bd(t,e,n){switch(e){case "HS256":case "HS384":case "HS512":{if(!Qn(t.algorithm,"HMAC"))throw ut("HMAC");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!Qn(t.algorithm,"RSASSA-PKCS1-v1_5"))throw ut("RSASSA-PKCS1-v1_5");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!Qn(t.algorithm,"RSA-PSS"))throw ut("RSA-PSS");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "Ed25519":case "EdDSA":{if(!Qn(t.algorithm,"Ed25519"))throw ut("Ed25519");break}case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":{if(!Qn(t.algorithm,e))throw ut(e);break}case "ES256":case "ES384":case "ES512":{if(!Qn(t.algorithm,"ECDSA"))throw ut("ECDSA");let r=Cw(e);if(t.algorithm.namedCurve!==r)throw ut(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Rw(t,n);}function wd(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 Sd=(t,...e)=>wd("Key must be ",t,...e),yl=(t,e,...n)=>wd(`Key for the ${t} algorithm must be `,e,...n);var bl=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return true;try{return t instanceof CryptoKey}catch{return false}},wl=t=>t?.[Symbol.toStringTag]==="KeyObject",Sl=t=>bl(t)||wl(t);function Hi(...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 Tw=t=>typeof t=="object"&&t!==null;function en(t){if(!Tw(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 zi(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 kw(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 Fe('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 Fe('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 Fe('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 Fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Fe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:e,keyUsages:n}}async function Ed(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:n}=kw(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 Gi(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 Fe(`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 _d(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 ns=t=>en(t)&&typeof t.kty=="string",xd=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),vd=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Cd=t=>t.kty==="oct"&&typeof t.k=="string";var Xn,Rd=async(t,e,n,r=false)=>{Xn||=new WeakMap;let s=Xn.get(t);if(s?.[n])return s[n];let i=await Ed({...e,alg:n});return r&&Object.freeze(t),s?s[n]=i:Xn.set(t,{[n]:i}),i},Ow=(t,e)=>{Xn||=new WeakMap;let n=Xn.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:Xn.set(t,{[e]:i}),i};async function Vi(t,e){if(t instanceof Uint8Array||bl(t))return t;if(wl(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Ow(t,e)}catch(r){if(r instanceof TypeError)throw r}let n=t.export({format:"jwk"});return Rd(t,n,e)}if(ns(t))return t.k?Gn(t.k):Rd(t,t,e,true);throw new Error("unreachable")}var Yn=t=>t?.[Symbol.toStringTag],El=(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},$w=(t,e,n)=>{if(!(e instanceof Uint8Array)){if(ns(e)){if(Cd(e)&&El(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(!Sl(e))throw new TypeError(yl(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Yn(e)} instances for symmetric algorithms must be of type "secret"`)}},Pw=(t,e,n)=>{if(ns(e))switch(n){case "decrypt":case "sign":if(xd(e)&&El(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if(vd(e)&&El(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Sl(e))throw new TypeError(yl(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Yn(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(n){case "sign":throw new TypeError(`${Yn(e)} instances for asymmetric algorithm signing must be of type "private"`);case "decrypt":throw new TypeError(`${Yn(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(n){case "verify":throw new TypeError(`${Yn(e)} instances for asymmetric algorithm verifying must be of type "public"`);case "encrypt":throw new TypeError(`${Yn(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Qi(t,e,n){switch(t.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":$w(t,e,n);break;default:Pw(t,e,n);}}function Xi(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 Fe(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Yi(t,e,n){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Sd(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},false,[n])}return bd(e,t,n),e}async function Td(t,e,n,r){let s=await Yi(t,e,"verify");zi(t,s);let i=Xi(t,s.algorithm);try{return await crypto.subtle.verify(i,s,n,r)}catch{return false}}async function kd(t,e,n){if(!en(t))throw new G("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new G('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new G("JWS Protected Header incorrect type");if(t.payload===void 0)throw new G("JWS Payload missing");if(typeof t.signature!="string")throw new G("JWS Signature missing or incorrect type");if(t.header!==void 0&&!en(t.header))throw new G("JWS Unprotected Header incorrect type");let r={};if(t.protected)try{let b=Gn(t.protected);r=JSON.parse(kt.decode(b));}catch{throw new G("JWS Protected Header is invalid")}if(!Hi(r,t.header))throw new G("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...r,...t.header},i=Gi(G,new Map([["b64",true]]),n?.crit,r,s),o=true;if(i.has("b64")&&(o=r.b64,typeof o!="boolean"))throw new G('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=s;if(typeof a!="string"||!a)throw new G('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=n&&_d("algorithms",n.algorithms);if(l&&!l.has(a))throw new es('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new G("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new G("JWS Payload must be a string or an Uint8Array instance");let c=false;typeof e=="function"&&(e=await e(r,t),c=true),Qi(a,e,"verify");let f=Ji(t.protected!==void 0?Zt(t.protected):new Uint8Array,Zt("."),typeof t.payload=="string"?o?Zt(t.payload):En.encode(t.payload):t.payload),u;try{u=Gn(t.signature);}catch{throw new G("Failed to base64url decode the signature")}let d=await Vi(e,a);if(!await Td(a,d,u,f))throw new ts;let y;if(o)try{y=Gn(t.payload);}catch{throw new G("Failed to base64url decode the payload")}else typeof t.payload=="string"?y=En.encode(t.payload):y=t.payload;let h={payload:y};return t.protected!==void 0&&(h.protectedHeader=r),t.header!==void 0&&(h.unprotectedHeader=t.header),c?{...h,key:d}:h}async function Ad(t,e,n){if(t instanceof Uint8Array&&(t=kt.decode(t)),typeof t!="string")throw new G("Compact JWS must be a string or Uint8Array");let{0:r,1:s,2:i,length:o}=t.split(".");if(o!==3)throw new G("Invalid Compact JWS");let a=await kd({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 tn=t=>Math.floor(t.getTime()/1e3),$d=60,Pd=$d*60,_l=Pd*24,Nw=_l*7,Iw=_l*365.25,Dw=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function rs(t){let e=Dw.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*$d);break;case "hour":case "hours":case "hr":case "hrs":case "h":s=Math.round(n*Pd);break;case "day":case "days":case "d":s=Math.round(n*_l);break;case "week":case "weeks":case "w":s=Math.round(n*Nw);break;default:s=Math.round(n*Iw);break}return e[1]==="-"||e[4]==="ago"?-s:s}function _n(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Od=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,jw=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):false;function Nd(t,e,n={}){let r;try{r=JSON.parse(kt.decode(e));}catch{}if(!en(r))throw new At("JWT Claims Set must be a top-level JSON object");let{typ:s}=n;if(s&&(typeof t.typ!="string"||Od(t.typ)!==Od(s)))throw new Ne('unexpected "typ" JWT header value',r,"typ","check_failed");let{requiredClaims:i=[],issuer:o,subject:a,audience:l,maxTokenAge:c}=n,f=[...i];c!==void 0&&f.push("iat"),l!==void 0&&f.push("aud"),a!==void 0&&f.push("sub"),o!==void 0&&f.push("iss");for(let y of new Set(f.reverse()))if(!(y in r))throw new Ne(`missing required "${y}" claim`,r,y,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new Ne('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new Ne('unexpected "sub" claim value',r,"sub","check_failed");if(l&&!jw(r.aud,typeof l=="string"?[l]:l))throw new Ne('unexpected "aud" claim value',r,"aud","check_failed");let u;switch(typeof n.clockTolerance){case "string":u=rs(n.clockTolerance);break;case "number":u=n.clockTolerance;break;case "undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:d}=n,p=tn(d||new Date);if((r.iat!==void 0||c)&&typeof r.iat!="number")throw new Ne('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new Ne('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>p+u)throw new Ne('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new Ne('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=p-u)throw new Vn('"exp" claim timestamp check failed',r,"exp","check_failed")}if(c){let y=p-r.iat,h=typeof c=="number"?c:rs(c);if(y-u>h)throw new Vn('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(y<0-u)throw new Ne('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}var Zi=class{#e;constructor(e){if(!en(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=_n("setNotBefore",e):e instanceof Date?this.#e.nbf=_n("setNotBefore",tn(e)):this.#e.nbf=tn(new Date)+rs(e);}set exp(e){typeof e=="number"?this.#e.exp=_n("setExpirationTime",e):e instanceof Date?this.#e.exp=_n("setExpirationTime",tn(e)):this.#e.exp=tn(new Date)+rs(e);}set iat(e){e===void 0?this.#e.iat=tn(new Date):e instanceof Date?this.#e.iat=_n("setIssuedAt",tn(e)):typeof e=="string"?this.#e.iat=_n("setIssuedAt",tn(new Date)+rs(e)):this.#e.iat=_n("setIssuedAt",e);}};async function xn(t,e,n){let r=await Ad(t,e,n);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===false)throw new At("JWTs MUST NOT use unencoded payload");let i={payload:Nd(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}async function Id(t,e,n){let r=await Yi(t,e,"sign");zi(t,r);let s=await crypto.subtle.sign(Xi(t,r.algorithm),r,n);return new Uint8Array(s)}var eo=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 G("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Hi(this.#t,this.#n))throw new G("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#n},s=Gi(G,new Map([["b64",true]]),n?.crit,this.#t,r),i=true;if(s.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new G('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=r;if(typeof o!="string"||!o)throw new G('JWS "alg" (Algorithm) Header Parameter missing or invalid');Qi(o,e,"sign");let a,l;i?(a=Ki(this.#e),l=Zt(a)):(l=this.#e,a="");let c,f;this.#t?(c=Ki(JSON.stringify(this.#t)),f=Zt(c)):(c="",f=new Uint8Array);let u=Ji(f,Zt("."),l),d=await Vi(e,o),p=await Id(o,d,u),y={signature:Ki(p),payload:a};return this.#n&&(y.header=this.#n),this.#t&&(y.protected=c),y}};var to=class{#e;constructor(e){this.#e=new eo(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 vn=class{#e;#t;constructor(e={}){this.#t=new Zi(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 to(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===false)throw new At("JWTs MUST NOT use unencoded payload");return r.sign(e,n)}};async function Dd(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:Ze({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:Ze({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:Ze({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await xn(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:Ze({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof Ot.JWTExpired?{kind:"error",response:Ze({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:Ze({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}function no(t,e,n,r){return !n||!e?.from?t:t.map(s=>xl(s,e.select,e.from,e.schema,e.join,n,r))}function xl(t,e,n,r,s,i,o){let a=i.get(`${r??o}.${n}`),l=Uw(e,s),c={};for(let[f,u]of Object.entries(t)){let d=l.get(f);if(d&&"embed"in d){let h=d.embed;c[f]=Lw(u,h,r,i,o);continue}let p=d?.sourceColumn??f,y=a?.get(p);c[f]=y?y.deserialize(u):u;}return c}function Lw(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?xl(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?xl(t,e.select,e.table,n,e.join,r,s):t}function Uw(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(Mw(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 Mw(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 ss=Symbol.for("lite-internal-request");function $t(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var jd=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function Ld(t){let e=t.match(jd);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 Ud(t){return jd.test(t)}function Md(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function Cn(t){if(Array.isArray(t))return t.map(e=>Cn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=Cn(r));return e}return t}function Tl(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 f;if(typeof o=="number"&&typeof a=="number"?f=o-a:f=String(o).localeCompare(String(a)),f!==0)return i.direction==="desc"?-f:f}return 0};return [...t].sort(n)}function Fd(t,e){return !e||e.length===0?t:t.map(n=>kl(n,e))}function Bd(t,e){if(!e||e.length===0)return t;let n=Fw(e);return n.size===0?t:t.map(r=>{if(!os(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 qd(t,e){return !e||e.length===0?t:t.map(n=>vl(n,e))}function Wd(t,e){return !e||e.length===0?t:t.map(n=>Cl(n,e))}function Jd(t,e){return !e||e.length===0?t:t.map(n=>Rl(n,e))}function Fw(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&&!Kd(i.cast)&&e.add(r);}return e}function Kd(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function kl(t,e){if(Array.isArray(t))return t.map(r=>kl(r,e));if(!os(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||!ro(i)||s in n&&(n[s]=qw(n[s],i.select));}return n}function vl(t,e){if(Array.isArray(t))return t.map(r=>vl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=vl(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=Bw(n[s]));}return n}function Cl(t,e){if(Array.isArray(t))return t.map(r=>Cl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=Cl(n[s],i.select));continue}Kd(i.cast)&&s in n&&(n[s]=Hd(n[s]));}return n}function Rl(t,e){if(Array.isArray(t))return t.map(r=>Rl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=Rl(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=Hd(n[s]));}return n}function Bw(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 qw(t,e){let n=Ww(t);return !e||e.length===0?n:kl(n,e)}function Ww(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 Hd(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function os(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ro(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var Jw=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 zd(t){let e=Ld(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function Gd(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(Jw.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function Vd(t,e){let n=Ld(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?$t({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function Rn(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}async function is(t,e,n,r){let s=e.join&&Object.values(e.join).some(f=>f.type==="inner"),i=Kw(e);if(s||i){let f={...e,type:"query",order:void 0,limit:void 0,offset:void 0},u=me(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),y=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,b=(await t.executeQuery({sql:y,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(b?.__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 me(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function Qd(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres")return is(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=me(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"],f=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,u=f&&typeof f=="object"?Number(f["Plan Rows"]):Number.NaN;return Number.isFinite(u)?u:is(t,e,n,r)}function Kw(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=Hw(t.select);return e.size===0?false:Xd(t.where,e)}function Xd(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"&&Xd(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 Hw(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}var zw=/[",\n\r ]/;function Yd(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),zw.test(e)?`"${e.replace(/"/g,'""')}"`:e}function so(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>Yd(s)).join(",")];for(let s of t)r.push(n.map(i=>Yd(s[i])).join(","));return r.join(`
81
- `)}function Zd(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function np(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 O(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=ep(t,e),s=Gw(t.where,r);if(!s)return O(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(!Ol(t.values))return O(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!Qw(t.values[i],s[i]))return O(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:ep(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 rp(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=Al(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*";return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:Pt(t,"representation",e.appliedResolution,false),headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:Pt(t,"no-return",e.appliedResolution,false),headers:r}))}function ep(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 Gw(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=Vw(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function Vw(t){if(!Ol(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function Qw(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):$t(t)===$t(e)}function Al(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 Pt(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 sp(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await tp(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(!Ol(o))continue;let a=Xw(s.preflight.conflictColumns,o);if(!a||!await tp(t,e.from,e.schema,a,n,r))return true}return false}function Xw(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function tp(t,e,n,r,s,i){return await is(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function Ol(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function op(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function ip(t,e,n){return op(e)?`*/${n??0}`:t.type==="update"&&n!==0?Rn(0,n??1,void 0):"*/*"}function Yw(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":Rn(n,1,r)}function ap(t){return "select"in t||"spread"in t||"join"in t}function lp(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))ap(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),lp(r.select,e));}}function Zw(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(ap(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}var eS={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"]},cp=t=>new Se().all("/:relation",async e=>{let{app:n}=e.var,r=n.connection;if(!n.config.api?.enabled)return e.notFound();let s=e.req.param("relation"),i=await r.introspect({useCache:true});if(r.config.introspection?.exclude_tables?.some(d=>qi(s,d,"sql")))return e.notFound();if(!(ss in e.req.raw)){let d=await Dd(e.req.header("Authorization"),{jwtSecret:n.config.auth?.jwt_secret,anonymousEnabled:n.config.api?.anonymous_enabled!==false});if(d.kind==="error")return d.response;d.payload&&(e.set("userId",d.payload.sub),e.set("sessionId",d.payload.session_id),e.set("jwt",d.payload));}let{dialect:a}=r,l=r.config.translation?.deparse?.schema,c=e.var.jwt,f={auth:{uid:e.var.userId??null,role:c?.role||"anon",jwt:c??null}},u;try{if(u=await Ti(e.req.raw,{basePath:"/rest/v1"}),u.schema){let x=new Set;for(let R of i.tables)R.schema&&x.add(R.schema);for(let R of i.views)R.schema&&x.add(R.schema);if(x.size>0&&x.add("public"),x.size>0&&!x.has(u.schema)){let R=[...x].sort().join(", ");return O(406,"PGRST106",`Invalid schema: ${u.schema}`,null,`Only the following schemas are exposed: ${R}`)}}if(u=await r.onPostgrestAST(u,f),t?.debug&&console.log(ze.default.dim("[POSTGREST:AST]"),u),n.config.api?.aggregates_enabled!==!0&&Va(u.select))return O(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let d=e.req.header("Accept")??"application/json",p=n.config.api?.plan_enabled===!0;if(!Gd(d,p))return O(406,"PGRST107",`None of these media types are available: ${zd(d)}`,null,null);let y=Md(d),h=Zd(d),b=e.req.header("Prefer");if(b){let x=b.split(",").map(v=>v.trim()).filter(Boolean);if(x.find(v=>v.startsWith("handling="))==="handling=strict"){let v=x.filter(k=>!k.includes("="));if(v.length>0)return O(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${v.join(", ")}`,null)}}if(r.dialect==="sqlite"&&u.from){let x=u.schema??"",R=i.tables.some(k=>k.name===u.from&&(k.schema??"")===x),v=i.views.some(k=>k.name===u.from&&(k.schema??"")===x);if(!R&&!v)throw new Zr(u.schema,u.from)}let m=u.$meta,w=u.type==="update"||u.type==="delete"||u.type==="insert"||u.type==="upsert"||u.type==="put",_={ast:u};if(w&&m?.return!=="representation"&&(u.select=void 0),(u.type==="put"||u.type==="upsert")&&(u.limit!==void 0||u.offset!==void 0))return O(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((u.type==="update"||u.type==="delete"||u.type==="insert")&&n.config.api?.limited_mutations_enabled!==!0&&(u.limit=void 0,u.offset=void 0),n.config.api?.pg_safe_update&&w){let x=u.where&&Object.keys(u.where).length>0;if(u.type==="update"&&!x)return O(400,"21000","UPDATE requires a WHERE clause",null,null);if(u.type==="delete"&&!x)return O(400,"21000","DELETE requires a WHERE clause",null,null)}if(w&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){if((u.type==="update"||u.type==="insert"||u.type==="upsert"||u.type==="put")&&(u.values===void 0||u.values===null))return O(400,"PGRST102","Empty or invalid json",null,null);if(u.type==="update"&&u.values&&typeof u.values=="object"&&!Array.isArray(u.values)&&Object.keys(u.values).length===0){let x=m?.return==="representation"?200:204,R={"Content-Type":"application/json; charset=utf-8","Content-Range":"*/*"};if(m?.return==="representation"){let v=new TextEncoder().encode("[]");return R["Content-Length"]=String(v.byteLength),R["Preference-Applied"]="return=representation",new Response(v,{status:x,headers:R})}return new Response(null,{status:x,headers:R})}if(u.type==="put"&&Array.isArray(u.values)&&(u.values.length===0?_.emptyPayload=!0:u.values=u.values[0]),Array.isArray(u.values)){if(m?.cardinality==="one"&&(u.type==="insert"||u.type==="upsert")&&u.values.length>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${u.values.length} rows`,null);if(u.values.length>0&&u.values.some(x=>typeof x!="object"||x===null||Array.isArray(x)))return m?.columns?O(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):O(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&u.values.length>1){let x=Object.keys(u.values[0]).sort().join(",");for(let R=1;R<u.values.length;R++)if(Object.keys(u.values[R]).sort().join(",")!==x)return O(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&u.from){let x=i.columns.filter(v=>v.table===u.from).map(v=>v.name);for(let v of m.columns){if(v==="")return O(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!x.includes(v))return O(400,"PGRST204",`Could not find the '${v}' column of '${u.from}' in the schema cache`,null,null)}let R=new Set(m.columns);if(u.values)if(Array.isArray(u.values))u.values=u.values.map(v=>{let k={};for(let z of R)z in v&&(k[z]=v[z]);return k});else {let v={};for(let k of R)k in u.values&&(v[k]=u.values[k]);u.values=v;}}if(!m?.columns&&u.values&&u.from&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){let x=i.columns.filter(R=>R.table===u.from).map(R=>R.name);if(x.length>0){let R=Array.isArray(u.values)?u.values.length>0?Object.keys(u.values[0]):[]:Object.keys(u.values);for(let v of R)if(!x.includes(v))return O(400,"PGRST204",`Could not find the '${v}' column of '${u.from}' in the schema cache`,null,null)}}if(u.values&&u.from&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){let x=u.schema??"public",R=new Set(i.columns.filter(v=>v.table===u.from&&(v.schema||"public")===x&&v.is_generated===!0).map(v=>v.name));if(R.size>0){let v=Array.isArray(u.values)?u.values:[u.values];for(let k of v)if(!(!k||typeof k!="object")){for(let z of Object.keys(k))if(R.has(z))return O(400,"428C9",`cannot insert a non-DEFAULT value into column "${z}"`,`Column "${z}" is a generated column.`,null)}}}}let S=np(u,i);if(S instanceof Response)return S;if(_=S,u=_.ast,w&&((u.type==="insert"||u.type==="upsert")&&Array.isArray(u.values)&&u.values.length===0||_.emptyPayload))return m?.cardinality==="one"?O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):rp(u,_);let E=e.req.method.toUpperCase(),C=e.req.header("Range");if(C&&(E==="GET"||E==="HEAD")){let x=C.match(/^(\d+)-(\d*)$/);if(x){let R=parseInt(x[1],10);if(x[2]!==""){let v=parseInt(x[2],10);if(R>v)return O(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);u.offset=R,u.limit=v-R+1;}else u.offset=R;}}if(u.limit!==void 0&&u.limit<0||u.limit===0&&u.offset!==void 0&&u.offset>0)return O(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(u.offset!==void 0&&u.offset<0&&(u.offset=0),!w){let x=n.config.api?.max_rows;x!==void 0&&x>0&&((u.limit===void 0||u.limit>x)&&(u.limit=x),lp(u.select,x));}return await r.withContext(f,async x=>{let R=e.req.header("Accept")??"application/json";if(p&&Ud(R)){let W=me(u,a,{db:x,introspection:i,schema:l}).compile();return t?.debug&&console.info(ze.default.dim(`[POSTGREST:PLAN] ${W.sql}
82
- - ${JSON.stringify([...W.parameters])}`)),Vd(R,W)}let v=w?await sp(x,u,a,i,_):void 0,k=Al(m,_.appliedResolution);if(w&&m?.return==="minimal"){let ae={...u,select:void 0},W=me(ae,a,{db:x,introspection:i,schema:l}),{sql:X,parameters:nt}=W.compile();t?.debug&&console.info(ze.default.dim(`[POSTGREST:SQL] ${X}
83
- - ${JSON.stringify([...nt])}`));let Z=await W.execute(),ke=Array.isArray(Z)&&Z.length>0&&Z[0]&&typeof Z[0]=="object"&&("numUpdatedRows"in Z[0]||"numInsertedOrUpdatedRows"in Z[0]||"numDeletedRows"in Z[0])?Z[0]:void 0,qt=ke===void 0?void 0:Number(ke.numUpdatedRows??ke.numInsertedOrUpdatedRows??ke.numDeletedRows??0),De=Pt(u,"no-return",_.appliedResolution,v),je={"Content-Range":ip(u,m,qt)};return k&&(je["Preference-Applied"]=k),new Response(null,{status:De,headers:je})}if(w&&m?.return==="headers-only"){let W=i.primary_keys.find(De=>De.table===u.from)?.columns??[],X={...u,select:W.length>0?W:void 0},nt=me(X,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:De,parameters:je}=nt.compile();console.info(ze.default.dim(`[POSTGREST:SQL] ${De}
84
- - ${JSON.stringify([...je])}`));}let Z=await nt.execute(),ke=Pt(u,"no-return",_.appliedResolution,v),qt={"Content-Range":"*/*"};if(k&&(qt["Preference-Applied"]=k),W.length>0&&Array.isArray(Z)&&Z.length>0){let De=Z[0],je=W.map(yt=>`${yt}=eq.${De[yt]}`).join("&");qt.Location=`/${u.from}?${je}`;}return new Response(null,{status:ke,headers:qt})}if(w&&(u.type==="update"||u.type==="delete")&&(u.limit!==void 0||u.offset!==void 0)){let ae={...u,select:void 0},W=me(ae,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:yt,parameters:Wt}=W.compile();console.info(ze.default.dim(`[POSTGREST:SQL:LTD] ${yt}
80
+ `;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var Kn=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function Pa(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 Na(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 Sf=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"]),wf={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"},Iy={any:"Any",all:"All"},Dy=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),jy={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function Ia(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!Dy.has(s))return null;let o=wf[s];return o?{astOp:o+Iy[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:jy[s],ftsConfig:i}}let r=wf[t];return r?{astOp:r}:null}function jr(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"");return Sf.has(r)}var gn=new Set(["select","order","limit","offset","on_conflict","columns"]);function Lr(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(xt(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function Ur(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(xt(r));}n<t.length&&t[n]===","&&n++;}return e}var Ti=Symbol.for("postgrest:not_null"),yn=Symbol.for("postgrest:unknown");function xt(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 Ti;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;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 La(t,e){let n={},r={};for(let[s,i]of t){if(gn.has(s))continue;let a=s.startsWith('"')?-1:s.indexOf(".");if(a>0&&!s.slice(0,a).includes("->")){let l=s.slice(0,a),c=s.slice(a+1);if(e.has(l)){if(c==="order"||c==="limit"||c==="offset")continue;if(c.includes(".")){let f=c.lastIndexOf("."),u=c.slice(f+1);if(u==="order"||u==="limit"||u==="offset")continue}r[l]||(r[l]={}),Uy(c,i,r[l]);continue}if(s!=="not.or"&&s!=="not.and")throw Ly(l)}ja(s,i,n);}return {where:n,embeddedWheres:r}}function Ly(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 ja(t,e,n){if(t==="or"||t==="and"){let s=e.map(o=>Ef(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=>Ef(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=xf(qy(t),{stopAtSpace:false});vf(r);for(let s of e){let i=_f(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function Uy(t,e,n){let r=My(t);if(!r){ja(t,e,n);return}let s={};ja(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function My(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 _f(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=Ia(s);if(!o)throw 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:Da(a,i)};if(n&&a==="$is")return {$isNot:Da(a,i)};let f=a==="$textSearch"?By(i,l,c):Da(a,i);return n?{$not:{[a]:f}}:{[a]:f}}function Da(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 Lr(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return Ur(e);if(!Fy(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Lr(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 Ur(e)}return e.startsWith("[")||e.startsWith("(")?e:xt(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim();if(!["null","true","false","unknown","not_null"].includes(n))throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return n==="unknown"?yn:xt(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("{")?Ur(n):Lr(n):n}return t==="$isDistinct"?e:xt(e)}function Fy(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function By(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function Ef(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 new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+2})`);try{return Mr(e).map(r=>Fr(r))}catch{throw new Error(`"failed to parse logic tree (${t})" (line 1, column ${t.length+2})`)}}function Mr(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 Fr(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Mr(n[1]).map(d=>Fr(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Mr(r[1]).map(d=>Fr(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Mr(s[1]).map(d=>Fr(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Mr(i[1]).map(d=>Fr(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not.")||e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t,a=false;o.startsWith("not.")&&(a=true,o=o.slice(4));let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=xf(o.slice(0,l),{stopAtSpace:true});vf(c);let f=o.slice(l+1),u=_f(a?`not.${f}`:f);return {[c]:u}}function xf(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t);return r?t.slice(0,r.index):t}function qy(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function vf(t){if(t===""||t==="*"||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+\D/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function Wy(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function Cf(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 Ua(t,e){let n=Cf(t),r=Cf(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 Fa(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let y=p[0],h=d.indexOf(".");if(h>0){let b=d.slice(0,h),m=d.slice(h+1);if(e.has(b)){if(m==="order"||m==="limit"||m==="offset"){n.embeddedTransforms[b]||(n.embeddedTransforms[b]={}),m==="order"?n.embeddedTransforms[b].order=Ma(y):m==="limit"?i[b]=y:m==="offset"&&(o[b]=y);continue}if(m.includes(".")){let w=m.lastIndexOf("."),_=m.slice(w+1);if(_==="order"||_==="limit"||_==="offset"){n.embeddedTransforms[b]||(n.embeddedTransforms[b]={});let S=n.embeddedTransforms[b],E=m.slice(0,w);S._nested||(S._nested={});let C=S._nested;C[E]||(C[E]={});let x=C[E];_==="order"?x.order=Ma(y):_==="limit"?(a[b]||(a[b]={}),a[b][E]=y):_==="offset"&&(l[b]||(l[b]={}),l[b][E]=y);continue}}}}d==="order"?n.order=Ma(y):d==="limit"?r=y:d==="offset"&&(s=y);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new ke({httpStatus:400,code:"PGRST108",message:`'${d.embed}' is not an embedded resource in this request`,details:null,hint:`Verify that '${d.embed}' is included in the 'select' query parameter.`})}let c=Ua(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let f=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of f){let p=Ua(i[d],o[d]);n.embeddedTransforms[d]||(n.embeddedTransforms[d]={}),p.limit!==void 0&&(n.embeddedTransforms[d].limit=p.limit),p.offset!==void 0&&(n.embeddedTransforms[d].offset=p.offset);}let u=new Set([...Object.keys(a),...Object.keys(l)]);for(let d of u){let p=new Set([...Object.keys(a[d]??{}),...Object.keys(l[d]??{})]);for(let y of p){let h=Ua(a[d]?.[y],l[d]?.[y]),b=n.embeddedTransforms[d]?._nested?.[y];b&&(h.limit!==void 0&&(b.limit=h.limit),h.offset!==void 0&&(b.offset=h.offset));}}return n}function Ma(t){return Jy(t).map(({entry:e,start:n})=>Ky(e.trim(),t,n+e.length-e.trimStart().length))}function Jy(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 Ky(t,e,n){let r=t.split("."),s={column:r[0]},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 f=Wy(i);if(f){if(f.column.includes(","))throw new pe(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",f.embed.length)+1);s.column=f.column,s.embed=f.embed;}let u=n+i.length+1,d=false,p=false;for(let y=1;y<r.length;y++){let h=r[y];if(h==="asc"||h==="desc"){if(d)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);s.direction=h,d=true,u+=h.length+1;}else if(h==="nullsfirst"||h==="nullslast"){if(p)throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1);s.nullsFirst=h==="nullsfirst",p=true,u+=h.length+1;}else {let b=["asc","desc","nullsfirst","nullslast"],m=null;for(let w of b)if(h.startsWith(w)&&h.length>w.length){m=w;break}if(m){let w=h[m.length],_=u+m.length;throw new pe(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,_+1)}throw new pe(`failed to parse order (${e})`,`unexpected '${h[0]}' expecting "," or end of input`,u+1)}}return s}function Ba(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count=i.value;break;case "missing":r.missing=i.value;break;case "handling":r.handling=i.value;break;case "tx":r.tx=i.value,i.value==="rollback"&&(r.rollback=true);break;case "max-affected":r.maxAffected=i.value;break;case "timezone":r.timezone=i.value;break;case "return":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=Gy(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=Hy("columns",i);}return r}function Hy(t,e){let n=e.split(",").map(r=>zy(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 zy(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function Gy(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 qa(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(gn.has(a))continue;let c=l[0];jr(c)||(i[a]=xt(c));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function Wa(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:Vy(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function Vy(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}async function Ri(t,e){let n=e?.basePath,r=e?.parseRoute??(z=>Ca(z,n)),s=e?.parseHeaders??Ta,i=e?.parseSelect??Oa,o=e?.parseBody??$a,a=e?.parseQueryParams??Pa,l=e?.resolveType??Na,c=e?.resolveFilters??La,f=e?.resolveTransforms??Fa,u=e?.resolveMeta??Ba,d=e?.resolveRpcParams??qa,p=e?.resolveUpsertParams??Wa,[y,h,b,m,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),_=t.method,S=l(y,_,h),E=w;if(y.isRpc&&_.toUpperCase()==="GET"){E=new Map;for(let[z,I]of w){if(gn.has(z)){E.set(z,I);continue}let ue=I.filter(Ye=>jr(Ye));ue.length>0&&E.set(z,ue);}}let C=c(E,b.embeddedAliases),x=f(w,b.embeddedAliases),T=u(h,w,_),v=d(y,_,w,m),A=S==="upsert"||S==="put"?p(w,h):void 0;return Qy(S,y,h,b,m,C,x,T,v,A)}function Qy(t,e,n,r,s,i,o,a,l,c){let f={type:t};return e.isRpc?f.function=e.function:f.from=e.from,n.schema&&(f.schema=n.schema),Object.keys(r.join).length>0&&(f.join=r.join),r.select.length>0&&(f.select=Tf(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(f.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(f.values=s.values),t==="rpc"&&(l.args!==void 0&&(f.args=l.args),l.httpMethod&&(f.httpMethod=l.httpMethod),l.paramsType&&(f.paramsType=l.paramsType),l.inputType&&(f.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(f.onConflict=c.onConflict),f.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!f.select||f.select.length===0)&&(f.select=["*"]),o.order&&(f.order=o.order),o.limit!==void 0&&(f.limit=o.limit),o.offset!==void 0&&(f.offset=o.offset),Object.keys(a).length>0&&(f.$meta=a),f}function Tf(t,e,n,r){return t.map(s=>{if(typeof s=="string")return s;let i=Object.keys(s)[0],o=s[i];if(!o.select)return s;let a={...o},l=r?.[i]?.from,c=e[i]||l&&e[l],f=n[i]||l&&n[l];if(c){let u={},d={};for(let[p,y]of Object.entries(c)){let h=p.indexOf(".");if(h>0){let b=p.slice(0,h),m=p.slice(h+1);if(a.join?.[b]||a.select?.some(S=>typeof S=="object"&&b in S&&"select"in(S[b]??{}))){d[b]||(d[b]={}),d[b][m]=y;continue}}u[p]=y;}Object.keys(u).length>0&&(a.where=u);for(let[p,y]of Object.entries(d))e[p]={...e[p],...y};}if(f){let u=f;if(u.order&&(a.order=u.order),u.limit!==void 0&&(a.limit=u.limit),u.offset!==void 0&&(a.offset=u.offset),u._nested)for(let[d,p]of Object.entries(u._nested))n[d]=p;}return a.select&&(a.select=Tf(a.select,e,n,a.join)),{[i]:a}})}function Ai(t){return t!=null&&typeof t=="object"&&"$ref"in t}var Yy=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,Xy=/[;'"\\/*\-#]/,Zy=/['\\;(]/,vt=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Ct(t,e){if(!Yy.test(t))throw new vt(t,e)}function Ja(t,e){if(Xy.test(t))throw new vt(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new vt(t,e);if(n!==0)throw new vt(t,e)}function Hn(t,e){if(Zy.test(t))throw new vt(t,e)}function bn(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 Br(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||Hn(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function k(t){return typeof t=="string"?sql.ref(t):t}function eb(t){return `"${t.replace(/"/g,'""')}"`}function Rf(t){return sql.raw(eb(t))}function Af(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 ki(t,e,n=e.currentTable,r=e.currentSchema){return Af(t,e,n,r)!==void 0}function oe(t,e,n=e.currentTable){return ki(t,e,n)?Rf(t):sql.ref(t)}function Yt(t,e,n,r=n.currentTable){let s=ki(e,n,r)?Rf(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function tb(t){return (t?.pg_type??t?.type??"").toLowerCase()}function kf(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=tb(Af(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function Of(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function $f(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return oe(t,n,r);if(kf(t,n,r)){let l=Of(i);if(l)return sql`${oe(t,n,r)}${sql.raw(l)}`}let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=Br(o,"JSON path key");return sql`${oe(t,n,r)}${sql.raw(a)}`}function qr(t,e,n=e.currentTable,r){let{col:s,parts:i}=bn(t),o=r?Yt(r,s,e,n):oe(s,e,n);if(i.length===0)return o;if(kf(s,e,n)){let c=Of(i.map(f=>f.key));if(c)return sql`${o}${sql.raw(c)}`}let a=e.dialect==="sqlite"?i.map((c,f)=>f===i.length-1?{...c,op:"->>"}:c):i,l=Br(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var Oi={$eq:(t,e,n)=>sql`${k(e)} = ${n}`,$neq:(t,e,n)=>sql`${k(e)} != ${n}`,$gt:(t,e,n)=>sql`${k(e)} > ${n}`,$gte:(t,e,n)=>sql`${k(e)} >= ${n}`,$lt:(t,e,n)=>sql`${k(e)} < ${n}`,$lte:(t,e,n)=>sql`${k(e)} <= ${n}`,$like:(t,e,n)=>sql`${k(e)} like ${n}`,$is:(t,e,n)=>{let r=k(e);return n===Ti?sql`${r} IS NOT NULL`:n===yn?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=k(e);return n===Ti?sql`${r} IS NULL`:n===yn?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=k(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=k(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`${k(e)} is distinct from ${n}`},$i={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function Ka(t){return t!=null&&typeof t=="object"&&t.type==="query"}function Pi(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),Ha(t,e,n)}function nb(t){return t.includes("->")}function If(t,e){let{col:n,parts:r}=bn(t);return r.length===0?oe(t,e):qr(t,e)}function Pe(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=>Pe(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Pe(t,a,n))));}else if(s==="$not")r.push(t.not(Pe(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(Pi(o,n)));}else {let o=i,a=nb(s);for(let[l,c]of Object.entries(o)){if(Ai(c)){let f=$i[l];if(!f)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?If(s,n):oe(s,n)} ${sql.raw(f)} ${oe(c.$ref,n)}`);continue}if(l==="$not"){let f=c;for(let[u,d]of Object.entries(f))if(a)r.push(t.not(Nf(s,u,d,n)));else {let p=Pf(s,u,d,n);if(p){r.push(t.not(p));continue}let y=n.operators[u];if(!y)throw new Error(`Unsupported operator: ${u}`);r.push(t.not(y(t,oe(s,n),d)));}}else if(Ka(c)){let f=Pi(c,n),u=n.operators[l];if(!u)throw new Error(`Unsupported operator: ${l}`);r.push(u(t,oe(s,n),f));}else if(a)r.push(Nf(s,l,c,n));else {let f=Pf(s,l,c,n);if(f){r.push(f);continue}let u=rb(s,l,c,n);if(u){r.push(u);continue}let d=n.operators[l];if(!d)throw new Error(`Unsupported operator: ${l}`);r.push(d(t,oe(s,n),c));}}}}return r.length===1?r[0]:t.and(r)}function Pf(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==yn)return null;let s=Df(t,r);if(!s)return null;let i=jf(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${oe(t,r)} IS NULL`:sql`${oe(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 Df(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?bn(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]}function jf(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 rb(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Df(t,r),i=jf(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=oe(t,r),a=sql`cast(${sql.raw(sb(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function sb(t){return `'${t.replace(/'/g,"''")}'`}function Nf(t,e,n,r){let s=r?If(t,r):k(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&&Ka(n))return sql`${s} in ${Pi(n,r)}`;let a=n;return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&Ka(n))return sql`${s} not in ${Pi(n,r)}`;let a=n;return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function ce(t){return "select"in t||"spread"in t||"join"in t}function ji(t,e,n,r,s,i=false){if(!e||e.length===0)return t.selectAll();for(let o of e)if(typeof o=="string")if(o==="*")t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(o))t=t.select(sql.lit(Number(o)).as("_lit"));else if(mb(o,n,s)){let a=i&&s?Yt(s,o,n,s):oe(o,n,s);t=t.select(sql`json(${a})`.as(o));}else t=i&&s&&!o.includes(".")?t.select(Yt(s,o,n,s).as(o)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)&&ki(o,n,s)?t.select(oe(o,n,s).as(o)):t.select(o);else for(let[a,l]of Object.entries(o))ce(l)?t=Rb(t,a,l,n,r,s):t=lb(t,a,l,n,s,i);return t}function Jr(t,e){if(!e||e.length===0)return t;for(let n of e)if(typeof n=="string")t=n==="*"?t.returningAll():t.returning(n);else for(let[r,s]of Object.entries(n)){if(ce(s))continue;let i=s.column||r;t=t.returning(i);}return t}function wn(t,e,n,r,s,i=false){let o;if(n.aggregate==="count"&&!n.column&&!n.path)o=t.fn.countAll();else {let a=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${ib(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});o=n.path?$f(a,n.path,r,s,n.pathText===true):s&&i?Yt(s,a,r,s):oe(a,r,s),n.preCast&&(Ja(n.preCast,"pre-cast type"),o=sql`cast(${o} as ${sql.raw(n.preCast)})`),n.aggregate&&(o=sql`${sql.raw(n.aggregate)}(${o})`);}return n.cast&&(Ja(n.cast,"cast type"),o=r.dialect==="sqlite"&&(ob(n.cast)||ab(n.cast))?sql`json(${o})`:sql`cast(${o} as ${sql.raw(n.cast)})`),o}function ib(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function ob(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function ab(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function lb(t,e,n,r,s,i=false){return t.select(o=>wn(o,e,n,r,s,i).as(e))}function cb(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!ce(n)&&n.aggregate)return true}return false}function ub(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ce(n)&&n.spread&&Ga(n.select))return true}return false}function fb(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ce(n)&&n.spread)return true}return false}function db(t){return cb(t)||ub(t)}function Ga(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ce(n)){if(Ga(n.select))return true;continue}if(n.aggregate)return true}return false}function Va(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ce(n)){if(n.spread)continue;if(Va(n.select))return true;continue}let r=n;if(r.aggregate&&!r.bareCount)return true}return false}function Qa(t,e,n,r,s){if(!db(e))return t;let i=[];for(let o of e){if(typeof o=="string"){if(o==="*")continue;i.push(oe(o,n,r));continue}for(let[a,l]of Object.entries(o)){if(ce(l))continue;let c=l;c.aggregate||i.push(f=>wn(f,a,c,n,r));}}return pb(i,e,n,r,s),i.length===0?t:t.groupBy(i)}function pb(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(!ce(a)||!a.spread)continue;let l=a,c=s?.[o],f=c?.from||o;f=Rt(f,r,n.introspection);let u=Re(n.introspection,r,f,c?.hint),d=u?.type==="m2o"||u?.type==="o2m"&&ct(u,f,n.introspection);if(!u||!d)continue;let p=Li(l.select,f,n.introspection)??l.select??[],y=`_spread_${o}`;for(let h of p){if(typeof h=="string"){h!=="*"&&t.push(`${y}.${h}`);continue}let[b,m]=Object.entries(h)[0];ce(m)||m.aggregate||t.push(w=>wn(w,b,m,n,y,true));}}}}function Uf(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(!ce(l)||!l.spread)continue;let c=n?.[a],f=c?.from||a;f=Rt(f,r,s.introspection);let u=Re(s.introspection,r,f,c?.hint),d=u?.type==="m2o"||u?.type==="o2m"&&ct(u,f,s.introspection);u&&d&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function Mf(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(!ce(o)||!o.spread)continue;let a=e?.[i],l=a?.from||i;l=Rt(l,n,r.introspection);let c=Re(r.introspection,n,l,a?.hint),f=c?.type==="m2o"||c?.type==="o2m"&&ct(c,l,r.introspection);if(c&&f)return true}return false}function Ni(t){let e=new Map;for(let n of t){let r=n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Ya(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 Xa(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;if(e.type==="m2o"){let[,l]=e.leftCol.split("."),[,c]=e.rightCol.split(".");return t.leftJoin(i,f=>f.onRef(`${s}.${c}`,"=",`${r}.${l}`))}let[,o]=e.leftCol.split("."),[,a]=e.rightCol.split(".");return t.leftJoin(i,l=>l.onRef(`${s}.${o}`,"=",`${r}.${a}`))}function Kr(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;Ct(o.embed,"order embed alias");let a=s?.[o.embed],l=el(o.embed,a,n,r.introspection);l!==o.embed&&Ct(l,"order embed target");let c=Re(r.introspection,n,l,a?.hint),f=c?.type==="m2o"||c?.type==="o2m"&&ct(c,l,r.introspection);!c||!f||(t=Xa(t,c,l,n,o.embed),i.add(o.embed),i.add(l));}return {sub:t,joined:i}}function Ff(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function za(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>za(i,e)):r==="$not"?n[r]=za(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function Ii(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 mb(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Ii(e,n,t)}function hb(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 Wr(t,e,n,r){return Ii(t,e,n)||hb(r,n)}function gb(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:Ii(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(ce(o))return null;let a=Ii(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function yb(t,e,n,r){let s=gb(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 bb(t){return t==="m2o"?"many-to-one":t==="o2m"?"one-to-many":"many-to-many"}function wb(t,e,n){return t.fk?t.type==="m2m"?`${t.fk.foreign_key_name} using ${t.junctionTable}(${t.fk.column}) and ${e}(${t.fk.ref_column})`:`${t.fk.foreign_key_name} using ${t.fk.table}(${t.fk.column}) and ${t.fk.ref_table}(${t.fk.ref_column})`:""}function Sb(t,e){if(!t||!e)return null;let n=[];for(let s of t.tables??[])n.push(s.name);for(let s of t.views??[])n.push(s.name);let r=n.find(s=>s.length===e.length+1&&s.startsWith(e));return r?`Perhaps you meant '${r}' instead of '${e}'.`:null}function Za(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:Sb(t,n)})}function Re(t,e,n,r){if(!t||!t.foreign_keys)return null;let s=t.foreign_keys.filter(p=>p.is_visible!==false);if(r){let p=s.find(E=>E.foreign_key_name===r);if(p){if(p.table===e&&p.ref_table===n)return {leftCol:`${e}.${p.column}`,rightCol:`${n}.${p.ref_column}`,type:"m2o"};if(p.table===n&&p.ref_table===e)return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}let y=s.find(E=>E.table===e&&E.column===r&&E.ref_table===n);if(y)return {leftCol:`${e}.${y.column}`,rightCol:`${n}.${y.ref_column}`,type:"m2o"};let h=s.find(E=>E.table===n&&E.column===r&&E.ref_table===e);if(h)return {leftCol:`${n}.${h.column}`,rightCol:`${e}.${h.ref_column}`,type:"o2m"};let b=s.filter(E=>E.table===r),m=Ni(b.filter(E=>E.ref_table===e)),w=Ni(b.filter(E=>E.ref_table===n));if(m.length>0&&w.length>0){let E=m[0],C=w[0];return {type:"m2m",junctionTable:r,junctionToParentCols:E.map(x=>x.column),parentCols:E.map(x=>x.ref_column),junctionToTargetCols:C.map(x=>x.column),targetCols:C.map(x=>x.ref_column)}}let _=s.find(E=>E.table===n&&E.ref_column===r&&E.ref_table===e);if(_)return {leftCol:`${n}.${_.column}`,rightCol:`${e}.${_.ref_column}`,type:"o2m"};let S=s.find(E=>E.table===e&&E.ref_column===r&&E.ref_table===n);if(S)return {leftCol:`${e}.${S.column}`,rightCol:`${n}.${S.ref_column}`,type:"m2o"};Za(t,e,n,r);}if(e===n){let p=s.find(y=>y.table===n&&y.ref_table===e);if(p)return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}let i=s.filter(p=>p.table===e&&p.ref_table===n),o=[...new Map(i.map(p=>[p.foreign_key_name,p])).values()],a=s.filter(p=>p.table===n&&p.ref_table===e),l=[...new Map(a.map(p=>[p.foreign_key_name,p])).values()],c=[],f=Ni(s.filter(p=>p.ref_table===e));for(let p of f){let y=p[0].table;if(y===e||y===n)continue;let h=s.filter(b=>b.table===y&&b.ref_table===n);if(h.length!==0)for(let b of Ni(h))c.push({type:"m2m",junctionTable:y,junctionToParentCols:p.map(m=>m.column),parentCols:p.map(m=>m.ref_column),junctionToTargetCols:b.map(m=>m.column),targetCols:b.map(m=>m.ref_column),fk:p[0]});}if(o.length+l.length+c.length===0)return null;if(o.length>1||l.length>1){let p=[...o.map(m=>({leftCol:`${e}.${m.column}`,rightCol:`${n}.${m.ref_column}`,type:"m2o",fk:m})),...l.map(m=>({leftCol:`${n}.${m.column}`,rightCol:`${e}.${m.ref_column}`,type:"o2m",fk:m})),...c],y=p.map(m=>({cardinality:bb(m.type),embedding:`${e} with ${n}`,relationship:wb(m,e)})),b=p.map(m=>m.fk?.foreign_key_name).filter(Boolean).map(m=>`'${n}!${m}'`).join(", ");throw new ke({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:y,hint:b?`Try changing '${n}' to one of the following: ${b}. Find the desired relationship in the 'details' key.`:null})}if(o.length===1){let p=o[0];return {leftCol:`${e}.${p.column}`,rightCol:`${n}.${p.ref_column}`,type:"m2o"}}if(l.length===1){let p=l[0];return {leftCol:`${n}.${p.column}`,rightCol:`${e}.${p.ref_column}`,type:"o2m"}}return c.length===1?c[0]:null}function Bf(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=el(s.embed,i,n,r.introspection),a=Re(r.introspection,n,o,i?.hint);if(!a)continue;if(!(a.type==="m2o"||a.type==="o2m"&&ct(a,o,r.introspection)))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 Rt(t,e,n){if(!n?.foreign_keys||n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t))return t;let s=n.foreign_keys,i=s.find(l=>l.table===e&&l.column===t);if(i)return i.ref_table;let o=s.find(l=>l.foreign_key_name===t&&(l.table===e||l.ref_table===e));if(o)return o.table===e?o.ref_table:o.table;let a=s.find(l=>l.ref_table===e&&l.ref_column===t);return a?a.table:t}function Lf(t,e,n,r,s,i){let o=s?.[e],a=o?.from||e;i&&(a=Rt(a,i,r.introspection));let l=i?Re(r.introspection,i,a,o?.hint):null;return t.where(c=>{let f=c.selectFrom(a).select(sql`1`.as("_"));return o?.on?f=f.where(u=>Pe(u,o.on,r)):l&&l.type==="m2m"?f=Ya(f,l,a,i):l?f=f.whereRef(l.leftCol,"=",l.rightCol):i&&(f=f.whereRef(`${a}.${i}_id`,"=",`${i}.id`)),n.where&&Object.keys(n.where).length>0&&(f=f.where(u=>Pe(u,n.where,r))),c.exists(f)})}function ct(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 Eb(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Hr(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=o?.from||e;a=Rt(a,i,r.introspection);let l=Re(r.introspection,i,a,o?.hint),c=Li(n.select,a,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return Tb(t,c,a,i,l);if(!l)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(!(l.type==="m2o"||l.type==="o2m"&&ct(l,a,r.introspection))){if(Ga(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 vb(t,c,n,l,a,i,r)}let u=`_spread_${e}`,[d,p]=l.leftCol.split("."),[,y]=l.rightCol.split("."),h=d===a?p:y,b=d===i?p:y,m="__spread_join_key",w=[],_=new Set;for(let S of c){if(typeof S=="string"&&S==="*")continue;let E;if(typeof S!="string"){let T=Object.values(S)[0];if(ce(T))continue;E=T;}let{colAlias:C,colName:x}=Hr(S);w.push({src:x,out:C,def:E}),_.add(x);}t=t.leftJoin(S=>{let E=S.selectFrom(a);E=E.select(`${a}.${h} as ${m}`);for(let C of _)E=E.select(`${a}.${C} as ${C}`);return E.as(u)},S=>S.onRef(`${u}.${m}`,"=",`${i}.${b}`));for(let{out:S,def:E}of w)E?t=t.select(C=>wn(C,S,E,r,u,true).as(S)):t=t.select(`${u}.${S}`);return t}function xb(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=Object.values(s)[0];if(!ce(i))continue;let{colAlias:o}=Hr(s),a=e.join?.[o],l=Rt(a?.from||o,n,r.introspection),c=Re(r.introspection,n,l,a?.hint);if(!c||c.type!=="o2m"||!ct(c,l,r.introspection))continue;let f=r.introspection?.primary_keys?.find(u=>u.table===l);if(f?.columns?.length)return {nestedTargetTable:l,fkRel:c,pkColumns:f.columns}}return null}function vb(t,e,n,r,s,i,o){let a=n.order?null:xb(e,n,s,o);for(let l of e){if(typeof l=="string"&&l==="*")continue;let c=typeof l=="string"?null:Object.values(l)[0],f=c!==null&&ce(c),u=f&&c.spread,{colAlias:d,colName:p}=Hr(l);if(u){t=Cb(t,d,c,n,r,s,i,o);continue}t=t.select(y=>{let h=y.selectFrom(s);if(h=Di(h,r,s,i),n.where&&Object.keys(n.where).length>0&&(h=h.where(b=>Pe(b,n.where,o))),n.order&&(h=Kr(h,n.order,s,o,n.join).sub,h=Tt(h,Ff(n.order),void 0,o,s)),n.limit!==void 0&&(h=h.limit(n.limit)),n.offset!==void 0&&(h=h.offset(n.offset)),a&&(h=Xa(h,a.fkRel,a.nestedTargetTable,s),h=Tt(h,a.pkColumns.map(b=>({column:b,embed:a.nestedTargetTable})),void 0,o)),f){let b=n.join?.[d];return h=h.select(m=>qf(m,d,c,o,b,s).as("value")),o.jsonScalarArrayFrom(h,"value",true).as(d)}else return c!==null?(h=h.select(b=>wn(b,p,c,o,s).as("value")),o.jsonScalarArrayFrom(h,"value",Wr(o,s,p,n.order)).as(d)):(h=h.select(`${s}.${p} as value`),o.jsonScalarArrayFrom(h,"value",Wr(o,s,p,n.order)).as(d))});}return t}function Cb(t,e,n,r,s,i,o,a){let l=r.join?.[e],c=Rt(l?.from||e,i,a.introspection),f=Re(a.introspection,i,c,l?.hint),u=Li(n.select,c,a.introspection)??n.select??[],d=f?.type==="m2o"||f?.type==="o2m"&&ct(f,c,a.introspection);for(let p of u){if(typeof p=="string"&&p==="*")continue;let y=typeof p=="string"?null:Object.values(p)[0],{colAlias:h,colName:b}=Hr(p);t=t.select(m=>{let w=m.selectFrom(i);w=Di(w,s,i,o),r.where&&Object.keys(r.where).length>0&&(w=w.where(S=>Pe(S,r.where,a)));let _=Kr(w,r.order,i,a,r.join);if(w=_.sub,r.order&&(w=Tt(w,Ff(r.order),void 0,a,i)),r.limit!==void 0&&(w=w.limit(r.limit)),r.offset!==void 0&&(w=w.offset(r.offset)),!f)return w=w.where(sql`1 = 0`).select(sql`null`.as("value")),a.jsonScalarArrayFrom(w).as(h);if(d){if(_.joined.has(c)||(w=Xa(w,f,c,i)),!r.order&&f.type==="o2m"){let S=a.introspection?.primary_keys?.find(E=>E.table===c);S?.columns?.length&&(w=Tt(w,S.columns.map(E=>({column:E,embed:c})),void 0,a));}if(y!==null&&!ce(y)){let S={...y,column:`${c}.${b}`};w=w.select(E=>wn(E,h,S,a).as("value"));}else w=w.select(`${c}.${b} as value`);return a.jsonScalarArrayFrom(w,"value",Wr(a,c,b,r.order)).as(h)}else return w=w.select(S=>{let E=S.selectFrom(c);return E=Di(E,f,c,i),y!==null&&!ce(y)?(E=E.select(C=>wn(C,b,y,a,c).as("value")),a.jsonScalarArrayFrom(E,"value",Wr(a,c,b,r.order)).as("value")):(E=E.select(`${c}.${b} as value`),a.jsonScalarArrayFrom(E,"value",Wr(a,c,b,r.order)).as("value"))}),a.jsonScalarArrayFrom(w,"value",true).as(h)});}return t}function Di(t,e,n,r){return e.type==="m2m"?Ya(t,e,n,r):t.whereRef(e.leftCol,"=",e.rightCol)}function Tb(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Hr(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);return s&&s.type!=="m2m"?c=c.whereRef(s.leftCol,"=",s.rightCol):c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`),c=c.limit(1),c.as(o)});}return t}function Li(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 el(t,e,n,r){let s=e?.from||t;if(!r?.foreign_keys||r.tables?.some(f=>f.name===s)||r.views?.some(f=>f.name===s))return s;let o=r.foreign_keys,a=o.find(f=>f.table===n&&f.column===s);if(a)return a.ref_table;let l=o.find(f=>f.foreign_key_name===s&&(f.table===n||f.ref_table===n));if(l)return l.table===n?l.ref_table:l.table;let c=o.find(f=>f.ref_table===n&&f.ref_column===s);return c?c.table:s}function Rb(t,e,n,r,s,i){let o=s?.[e];if(!n.select||n.select.length===0){if(o?.type==="inner"&&i)return Lf(t,e,n,r,s,i);if(i&&!o?.on&&r.introspection?.foreign_keys){let a=el(e,o,i,r.introspection);Re(r.introspection,i,a,o?.hint)||Za(r.introspection,i,a,o?.hint);}return t}return o?.type==="inner"&&i&&(t=Lf(t,e,n,r,s,i)),n.spread&&i?_b(t,e,n,r,s,i):t.select(a=>qf(a,e,n,r,o,i).as(e))}function qf(t,e,n,r,s,i){let o=s?.from||e;if(i&&r.introspection?.foreign_keys){let _=r.introspection.foreign_keys.find(S=>S.table===i&&S.column===o);if(_)o=_.ref_table;else {let S=r.introspection.foreign_keys.find(E=>E.foreign_key_name===o&&(E.table===i||E.ref_table===i));if(S)o=S.table===i?S.ref_table:S.table;else {let E=r.introspection.foreign_keys.find(C=>C.ref_table===i&&C.ref_column===o);E&&(o=E.table);}}}let a=i===o,l=a?`${o}_self`:o,c=a?`${o} as ${l}`:o,f=t.selectFrom(c),u=i&&!s?.on?Re(r.introspection,i,o,s?.hint):null,d=u?.type==="m2m",p=Li(n.select,o,r.introspection),y=d?Eb(p,l):p;if(f=ji(f,y,r,n.join,l,fb(y)),n.where&&Object.keys(n.where).length>0){let _=Ui(f,n.where,n.select,n.join,o,r);f=_.qb,Object.keys(_.remainingWhere).length>0&&(f=f.where(S=>Pe(S,_.remainingWhere,r)));}let h="o2m";if(s?.on)f=f.where(_=>Pe(_,s.on,r));else if(i){let _=Re(r.introspection,i,o,s?.hint);if(_&&_.type==="m2m")h="m2m",f=Ya(f,_,l,i);else if(_){let S=a?_.leftCol.replace(`${o}.`,`${l}.`):_.leftCol;f=f.whereRef(S,"=",_.rightCol),h=_.type;}else r.introspection?.foreign_keys?Za(r.introspection,i,o,s?.hint):f=f.whereRef(`${l}.${i}_id`,"=",`${i}.id`);}f=Qa(f,y,r,o),n.order?.some(_=>_.embed)&&(f=Kr(f,n.order,o,r,n.join).sub),f=Tt(f,n.order,void 0,r,o),h==="m2m"&&!n.order&&u?.type==="m2m"&&r.dialect==="sqlite"&&(f=f.orderBy(`${u.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(f=f.limit(n.limit)),n.offset!==void 0&&(f=f.offset(n.offset));let b=false;if(h==="o2m"&&i&&r.introspection){let _=Re(r.introspection,i,o,s?.hint);_&&_.type==="o2m"&&(b=ct(_,o,r.introspection));}let m=n.spread||h==="m2o"||b;return m&&r.dialect==="sqlite"?yb(f,y,o,r):(m?r.jsonObjectFrom:r.jsonArrayFrom)(f)}function Wf(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){if(typeof s=="string")continue;let[i,o]=Object.entries(s)[0];if(!ce(o)||!o.spread)continue;let l=e?.[i],c=Rt(l?.from||i,n,r.introspection),f=Re(r.introspection,n,c,l?.hint);if(!f)continue;if(!(f.type==="m2o"||f.type==="o2m"&&ct(f,c,r.introspection)))return true}return false}function Ui(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!Hf(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=Jf(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 Jf(t,e,n,r,s,i){let o=[],a={};for(let[c,f]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(f)){let d=f.map(p=>Jf(t,p,n,r,s,i));if(d.length>0&&d.every(p=>p.fullyHandled&&p.expression)){o.push(c==="$or"?t.or(d.map(p=>p.expression)):t.and(d.map(p=>p.expression)));continue}a[c]=f;continue}let u=Ab(t,c,f,n,r,s,i);u?o.push(u):a[c]=f;}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 Ab(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 f=Kf(r,e);if(!f)return null;let u=s?.[e],d=Rt(u?.from||e,i,o.introspection),p=Re(o.introspection,i,d,u?.hint);if(!p)return null;let y=t.selectFrom(d).select(sql`1`.as("_"));if(u?.on?y=y.where(b=>Pe(b,u.on,o)):y=Di(y,p,d,i),f.where&&Object.keys(f.where).length>0){let b=Ui(y,f.where,f.select,f.join,d,o);if(y=b.qb,Object.keys(b.remainingWhere).length>0){let m=za(b.remainingWhere,d);y=y.where(w=>Pe(w,m,o));}}let h=t.exists(y);return c?h:t.not(h)}function Kf(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&ce(r))return r}return null}function Hf(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>Hf(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)&&Kf(e,n))return true}return false}function kb(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function tl(t,e,n,r,s={}){if(!t)return t;let i=kb(e,n,r),o=a=>{let l=Ob(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):$b(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function Ob(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??Vf(n,r,s,o)??void 0;i[o]=Pb(a,l);}return i}function $b(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=Vf(e,n,r,i);s[i]=Db(a)?jb(o):o;}return s}function Vf(t,e,n,r){let i=(t.introspection?.columns??[]).filter(a=>a.table===n&&a.name===r);if(i.length===0)return;let o=i.find(a=>a.schema===(e??"public"))??i.find(a=>a.schema==="public")??i[0];return o.pg_type??o.type}function Pb(t,e){if(t==null||typeof t!="string")return t;let n=Qf(e);return n==="boolean"?Nb(t):n==="integer"?zf(t,true):n==="number"?zf(t,false):n==="json"?Yf(t):n==="array"?Ib(t):t}function Qf(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 Nb(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 zf(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 Yf(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function Ib(t){let e=Yf(t);return Array.isArray(e)?e:t}function Db(t){let e=Qf(t);return e==="json"||e==="array"}function jb(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function Xf(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema)),t.type){case "query":return Ha(t,e,n);case "insert":return Ub(t,e,n);case "update":return Mb(t,e,n);case "delete":return Fb(t,e,n);case "upsert":case "put":return Bb(t,e,n);case "rpc":return qb(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Tt(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Ct(i.embed,"order embed alias"),i.column.includes("->")?r?qr(i.column,r,s,i.embed):Gf(i.column,i.embed):(Ct(i.column,"order embed column"),r?Yt(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?qr(i.column,r,s,n):Gf(i.column,void 0,n):n?r?Yt(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?oe(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 Gf(t,e,n){let{col:r,parts:s}=bn(t);if(s.length===0)return sql.ref(t);e&&Ct(r,"order embed column");let i=Br(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 zr(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Pe(i,e,{...n,currentTable:r,currentSchema:s}))}function Ha(t,e,n){let r=n.selectFrom(t.from);r=Lb(r,t.join,t.select);let s=t.order?.some(f=>f.embed)===true;r=ji(r,t.select,e,t.join,t.from,s||Mf(t.select,t.join,t.from,e));let i=t.where??{},{qb:o,remainingWhere:a}=t.from?Ui(r,i,t.select,t.join,t.from,e):{qb:r,remainingWhere:i};r=o,r=zr(r,a,e,t.from,t.schema),r=Qa(r,t.select,e,t.from,t.join),Bf(t.order,t.join,t.from,e),t.from&&s&&(r=Kr(r,t.order,t.from,e,t.join).sub);let l=t.from&&Wf(t.select,t.join,t.from,e)?t.from:void 0,c=Uf(t.order,t.select,t.join,t.from,e);return r=Tt(r,c,l,e,t.from),t.limit!==void 0&&(r=r.limit(t.limit)),t.offset!==void 0&&(r=r.offset(t.offset)),r}function Lb(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=>Zf(l,i.on));}return t}function Zf(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=Zf(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=$i[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Ai(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function Ub(t,e,n){let r=n.insertInto(t.from);if(t.values){let s=tl(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(s);}return r=Jr(r,t.select),r}function Mb(t,e,n){let r=n.updateTable(t.from);if(t.values){let s=tl(t.values,e,t.schema,t.from);r=r.set(s);}return t.limit!==void 0||t.offset!==void 0?r=ed(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema),r=Jr(r,t.select),r}function Fb(t,e,n){let r=n.deleteFrom(t.from);return t.limit!==void 0||t.offset!==void 0?r=ed(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema),r=Jr(r,t.select),r}function ed(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=zr(o,e.where??{},n,e.from,e.schema),o=Tt(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 f of i)c=c.whereRef(`${l}.${f}`,"=",`${e.from}.${f}`);return t.where(f=>f.exists(c))}else return t.where(sql.ref(a),"in",o)}function Bb(t,e,n){let r=t.values,s=tl(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);return t.onConflict&&(i=i.onConflict(o=>{let a=t.onConflict.length===1?o.column(t.onConflict[0]):o.columns(t.onConflict);if(t.ignoreDuplicates)return a.doNothing();let l=Array.isArray(s)?s[0]:s,c=Object.keys(l).filter(f=>!t.onConflict.includes(f));return c.length===0?a.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):a.doUpdateSet(f=>{let u={};for(let d of c)u[d]=f.ref(`excluded.${d}`);return u})})),i=Jr(i,t.select),i}function qb(t,e,n){let r=t.function;Ct(r,"RPC function name");let s;if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let a=Object.entries(t.args).map(([l,c])=>(Ct(l,"RPC param key"),sql`${sql.raw(l)} := ${c}`));s=sql`${sql.raw(r)}(${sql.join(a)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let o=t.args.map(a=>sql`${a}`);s=sql`${sql.raw(r)}(${sql.join(o)})`;}else s=sql`${sql.raw(r)}()`;let i=n.selectFrom(s.as(r));return i=ji(i,t.select,e),i=zr(i,t.where??{},e,t.from,t.schema),i=Tt(i,t.order,void 0,e,t.from),t.limit!==void 0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset)),i}var Qb=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),Yb={$ilike:(t,e,n)=>sql`${k(e)} ilike ${n}`,$regex:(t,e,n)=>sql`${k(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${k(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${k(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${k(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${k(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${k(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${k(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${k(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${k(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${k(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`${k(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${k(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${k(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${k(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${k(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${k(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${k(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${k(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${k(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${k(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${k(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${k(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${k(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${k(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${k(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${k(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${k(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${k(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${k(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${k(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${k(e)} ~* all(${n})`};function Xb(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||Hn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function Zb(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var td={db:Qb,operators:{...Oi,...Yb},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:Zb,jsonPath:Xb,rowIdColumn:"ctid"};var aw=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function lw(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||Hn(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function cw(t,e){let n=k(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 uw(t,e){let n=k(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(Hn(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 `)}`}function Mi(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=k(t),i=n==="ilike"?sql`lower(${s})`:s,o=e.map(a=>n==="ilike"?sql`${i} like lower(${a})`:sql`${i} like ${a}`);return sql`(${sql.join(o,r==="any"?sql` or `:sql` and `)})`}var fw={$ilike:(t,e,n)=>sql`lower(${k(e)}) like lower(${n})`,$likeAny:(t,e,n)=>Mi(e,n,"like","any"),$ilikeAny:(t,e,n)=>Mi(e,n,"ilike","any"),$likeAll:(t,e,n)=>Mi(e,n,"like","all"),$ilikeAll:(t,e,n)=>Mi(e,n,"ilike","all"),$contains:(t,e,n)=>{if(Array.isArray(n))return cw(e,n);if(n!==null&&typeof n=="object")return uw(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=k(e);if(n.length===0)return sql`${r} is not null and not exists (select 1 from json_each(${r}))`;let s=sql.join(n.map(i=>sql`${i}`));return sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${s}))`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=k(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 dw(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 nd={db:aw,operators:{...Oi,...fw},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:dw,jsonPath:lw,rowIdColumn:"rowid"};function pw(t){switch(t){case "postgres":return td;case "sqlite":return nd;default:throw new Error(`Unsupported dialect: ${t}`)}}function me(t,e="postgres",n){let r=pw(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return Xf(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var ze=au(id());Xr();Gr();var Zr=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;}},ll=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)}};Yr();var zn=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Wi();function O(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 Ze(t){return O(t.status,t.code,t.message,t.details??null,t.hint??null)}var En=new TextEncoder,At=new TextDecoder;function Ji(...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 Zt(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 yd(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 bd(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 Gn(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:At.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=At.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return bd(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function Ki(t){let e=t;return typeof e=="string"&&(e=En.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:true}):yd(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ot={};xr(Ot,{JOSEAlgNotAllowed:()=>es,JOSEError:()=>he,JOSENotSupported:()=>Fe,JWEDecryptionFailed:()=>cl,JWEInvalid:()=>ul,JWKInvalid:()=>fl,JWKSInvalid:()=>dl,JWKSMultipleMatchingKeys:()=>ml,JWKSNoMatchingKey:()=>pl,JWKSTimeout:()=>hl,JWSInvalid:()=>G,JWSSignatureVerificationFailed:()=>ts,JWTClaimValidationFailed:()=>Ne,JWTExpired:()=>Vn,JWTInvalid:()=>kt});var he=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);}},Ne=class extends he{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;}},Vn=class extends he{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;}},es=class extends he{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Fe=class extends he{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},cl=class extends he{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",n){super(e,n);}},ul=class extends he{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},G=class extends he{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},kt=class extends he{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},fl=class extends he{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},dl=class extends he{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},pl=class extends he{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);}},ml=class extends he{[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);}},hl=class extends he{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",n){super(e,n);}},ts=class extends he{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",n){super(e,n);}};var ut=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Qn=(t,e)=>t.name===e;function gl(t){return parseInt(t.name.slice(4),10)}function Cw(t){switch(t){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}function Tw(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function wd(t,e,n){switch(e){case "HS256":case "HS384":case "HS512":{if(!Qn(t.algorithm,"HMAC"))throw ut("HMAC");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!Qn(t.algorithm,"RSASSA-PKCS1-v1_5"))throw ut("RSASSA-PKCS1-v1_5");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!Qn(t.algorithm,"RSA-PSS"))throw ut("RSA-PSS");let r=parseInt(e.slice(2),10);if(gl(t.algorithm.hash)!==r)throw ut(`SHA-${r}`,"algorithm.hash");break}case "Ed25519":case "EdDSA":{if(!Qn(t.algorithm,"Ed25519"))throw ut("Ed25519");break}case "ML-DSA-44":case "ML-DSA-65":case "ML-DSA-87":{if(!Qn(t.algorithm,e))throw ut(e);break}case "ES256":case "ES384":case "ES512":{if(!Qn(t.algorithm,"ECDSA"))throw ut("ECDSA");let r=Cw(e);if(t.algorithm.namedCurve!==r)throw ut(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tw(t,n);}function Sd(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 Ed=(t,...e)=>Sd("Key must be ",t,...e),yl=(t,e,...n)=>Sd(`Key for the ${t} algorithm must be `,e,...n);var bl=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return true;try{return t instanceof CryptoKey}catch{return false}},wl=t=>t?.[Symbol.toStringTag]==="KeyObject",Sl=t=>bl(t)||wl(t);function Hi(...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 Rw=t=>typeof t=="object"&&t!==null;function en(t){if(!Rw(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 zi(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 Aw(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 Fe('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 Fe('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 Fe('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 Fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Fe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:e,keyUsages:n}}async function _d(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:n}=Aw(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 Gi(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 Fe(`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 xd(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 ns=t=>en(t)&&typeof t.kty=="string",vd=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Cd=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Td=t=>t.kty==="oct"&&typeof t.k=="string";var Yn,Rd=async(t,e,n,r=false)=>{Yn||=new WeakMap;let s=Yn.get(t);if(s?.[n])return s[n];let i=await _d({...e,alg:n});return r&&Object.freeze(t),s?s[n]=i:Yn.set(t,{[n]:i}),i},Ow=(t,e)=>{Yn||=new WeakMap;let n=Yn.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:Yn.set(t,{[e]:i}),i};async function Vi(t,e){if(t instanceof Uint8Array||bl(t))return t;if(wl(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Ow(t,e)}catch(r){if(r instanceof TypeError)throw r}let n=t.export({format:"jwk"});return Rd(t,n,e)}if(ns(t))return t.k?Gn(t.k):Rd(t,t,e,true);throw new Error("unreachable")}var Xn=t=>t?.[Symbol.toStringTag],El=(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},$w=(t,e,n)=>{if(!(e instanceof Uint8Array)){if(ns(e)){if(Td(e)&&El(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(!Sl(e))throw new TypeError(yl(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Xn(e)} instances for symmetric algorithms must be of type "secret"`)}},Pw=(t,e,n)=>{if(ns(e))switch(n){case "decrypt":case "sign":if(vd(e)&&El(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case "encrypt":case "verify":if(Cd(e)&&El(t,e,n))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Sl(e))throw new TypeError(yl(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Xn(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(n){case "sign":throw new TypeError(`${Xn(e)} instances for asymmetric algorithm signing must be of type "private"`);case "decrypt":throw new TypeError(`${Xn(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(n){case "verify":throw new TypeError(`${Xn(e)} instances for asymmetric algorithm verifying must be of type "public"`);case "encrypt":throw new TypeError(`${Xn(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Qi(t,e,n){switch(t.substring(0,2)){case "A1":case "A2":case "di":case "HS":case "PB":$w(t,e,n);break;default:Pw(t,e,n);}}function Yi(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 Fe(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Xi(t,e,n){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Ed(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},false,[n])}return wd(e,t,n),e}async function Ad(t,e,n,r){let s=await Xi(t,e,"verify");zi(t,s);let i=Yi(t,s.algorithm);try{return await crypto.subtle.verify(i,s,n,r)}catch{return false}}async function kd(t,e,n){if(!en(t))throw new G("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new G('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new G("JWS Protected Header incorrect type");if(t.payload===void 0)throw new G("JWS Payload missing");if(typeof t.signature!="string")throw new G("JWS Signature missing or incorrect type");if(t.header!==void 0&&!en(t.header))throw new G("JWS Unprotected Header incorrect type");let r={};if(t.protected)try{let b=Gn(t.protected);r=JSON.parse(At.decode(b));}catch{throw new G("JWS Protected Header is invalid")}if(!Hi(r,t.header))throw new G("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...r,...t.header},i=Gi(G,new Map([["b64",true]]),n?.crit,r,s),o=true;if(i.has("b64")&&(o=r.b64,typeof o!="boolean"))throw new G('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=s;if(typeof a!="string"||!a)throw new G('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=n&&xd("algorithms",n.algorithms);if(l&&!l.has(a))throw new es('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new G("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new G("JWS Payload must be a string or an Uint8Array instance");let c=false;typeof e=="function"&&(e=await e(r,t),c=true),Qi(a,e,"verify");let f=Ji(t.protected!==void 0?Zt(t.protected):new Uint8Array,Zt("."),typeof t.payload=="string"?o?Zt(t.payload):En.encode(t.payload):t.payload),u;try{u=Gn(t.signature);}catch{throw new G("Failed to base64url decode the signature")}let d=await Vi(e,a);if(!await Ad(a,d,u,f))throw new ts;let y;if(o)try{y=Gn(t.payload);}catch{throw new G("Failed to base64url decode the payload")}else typeof t.payload=="string"?y=En.encode(t.payload):y=t.payload;let h={payload:y};return t.protected!==void 0&&(h.protectedHeader=r),t.header!==void 0&&(h.unprotectedHeader=t.header),c?{...h,key:d}:h}async function Od(t,e,n){if(t instanceof Uint8Array&&(t=At.decode(t)),typeof t!="string")throw new G("Compact JWS must be a string or Uint8Array");let{0:r,1:s,2:i,length:o}=t.split(".");if(o!==3)throw new G("Invalid Compact JWS");let a=await kd({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 tn=t=>Math.floor(t.getTime()/1e3),Pd=60,Nd=Pd*60,_l=Nd*24,Nw=_l*7,Iw=_l*365.25,Dw=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function rs(t){let e=Dw.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*Pd);break;case "hour":case "hours":case "hr":case "hrs":case "h":s=Math.round(n*Nd);break;case "day":case "days":case "d":s=Math.round(n*_l);break;case "week":case "weeks":case "w":s=Math.round(n*Nw);break;default:s=Math.round(n*Iw);break}return e[1]==="-"||e[4]==="ago"?-s:s}function _n(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var $d=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,jw=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):false;function Id(t,e,n={}){let r;try{r=JSON.parse(At.decode(e));}catch{}if(!en(r))throw new kt("JWT Claims Set must be a top-level JSON object");let{typ:s}=n;if(s&&(typeof t.typ!="string"||$d(t.typ)!==$d(s)))throw new Ne('unexpected "typ" JWT header value',r,"typ","check_failed");let{requiredClaims:i=[],issuer:o,subject:a,audience:l,maxTokenAge:c}=n,f=[...i];c!==void 0&&f.push("iat"),l!==void 0&&f.push("aud"),a!==void 0&&f.push("sub"),o!==void 0&&f.push("iss");for(let y of new Set(f.reverse()))if(!(y in r))throw new Ne(`missing required "${y}" claim`,r,y,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new Ne('unexpected "iss" claim value',r,"iss","check_failed");if(a&&r.sub!==a)throw new Ne('unexpected "sub" claim value',r,"sub","check_failed");if(l&&!jw(r.aud,typeof l=="string"?[l]:l))throw new Ne('unexpected "aud" claim value',r,"aud","check_failed");let u;switch(typeof n.clockTolerance){case "string":u=rs(n.clockTolerance);break;case "number":u=n.clockTolerance;break;case "undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:d}=n,p=tn(d||new Date);if((r.iat!==void 0||c)&&typeof r.iat!="number")throw new Ne('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new Ne('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>p+u)throw new Ne('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new Ne('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=p-u)throw new Vn('"exp" claim timestamp check failed',r,"exp","check_failed")}if(c){let y=p-r.iat,h=typeof c=="number"?c:rs(c);if(y-u>h)throw new Vn('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(y<0-u)throw new Ne('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}var Zi=class{#e;constructor(e){if(!en(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=_n("setNotBefore",e):e instanceof Date?this.#e.nbf=_n("setNotBefore",tn(e)):this.#e.nbf=tn(new Date)+rs(e);}set exp(e){typeof e=="number"?this.#e.exp=_n("setExpirationTime",e):e instanceof Date?this.#e.exp=_n("setExpirationTime",tn(e)):this.#e.exp=tn(new Date)+rs(e);}set iat(e){e===void 0?this.#e.iat=tn(new Date):e instanceof Date?this.#e.iat=_n("setIssuedAt",tn(e)):typeof e=="string"?this.#e.iat=_n("setIssuedAt",tn(new Date)+rs(e)):this.#e.iat=_n("setIssuedAt",e);}};async function xn(t,e,n){let r=await Od(t,e,n);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===false)throw new kt("JWTs MUST NOT use unencoded payload");let i={payload:Id(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}async function Dd(t,e,n){let r=await Xi(t,e,"sign");zi(t,r);let s=await crypto.subtle.sign(Yi(t,r.algorithm),r,n);return new Uint8Array(s)}var eo=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 G("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Hi(this.#t,this.#n))throw new G("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this.#t,...this.#n},s=Gi(G,new Map([["b64",true]]),n?.crit,this.#t,r),i=true;if(s.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new G('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=r;if(typeof o!="string"||!o)throw new G('JWS "alg" (Algorithm) Header Parameter missing or invalid');Qi(o,e,"sign");let a,l;i?(a=Ki(this.#e),l=Zt(a)):(l=this.#e,a="");let c,f;this.#t?(c=Ki(JSON.stringify(this.#t)),f=Zt(c)):(c="",f=new Uint8Array);let u=Ji(f,Zt("."),l),d=await Vi(e,o),p=await Dd(o,d,u),y={signature:Ki(p),payload:a};return this.#n&&(y.header=this.#n),this.#t&&(y.protected=c),y}};var to=class{#e;constructor(e){this.#e=new eo(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 vn=class{#e;#t;constructor(e={}){this.#t=new Zi(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 to(this.#t.data());if(r.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===false)throw new kt("JWTs MUST NOT use unencoded payload");return r.sign(e,n)}};async function jd(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:Ze({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:Ze({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:Ze({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await xn(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:Ze({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof Ot.JWTExpired?{kind:"error",response:Ze({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:Ze({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}function no(t,e,n,r){return !n||!e?.from?t:t.map(s=>xl(s,e.select,e.from,e.schema,e.join,n,r))}function xl(t,e,n,r,s,i,o){let a=i.get(`${r??o}.${n}`),l=Uw(e,s),c={};for(let[f,u]of Object.entries(t)){let d=l.get(f);if(d&&"embed"in d){let h=d.embed;c[f]=Lw(u,h,r,i,o);continue}let p=d?.sourceColumn??f,y=a?.get(p);c[f]=y?y.deserialize(u):u;}return c}function Lw(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?xl(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?xl(t,e.select,e.table,n,e.join,r,s):t}function Uw(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(Mw(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 Mw(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 ss=Symbol.for("lite-internal-request");function $t(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var Ld=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function Ud(t){let e=t.match(Ld);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 Md(t){return Ld.test(t)}function Fd(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function Cn(t){if(Array.isArray(t))return t.map(e=>Cn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=Cn(r));return e}return t}function Rl(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 f;if(typeof o=="number"&&typeof a=="number"?f=o-a:f=String(o).localeCompare(String(a)),f!==0)return i.direction==="desc"?-f:f}return 0};return [...t].sort(n)}function Bd(t,e){return !e||e.length===0?t:t.map(n=>Al(n,e))}function qd(t,e){if(!e||e.length===0)return t;let n=Fw(e);return n.size===0?t:t.map(r=>{if(!os(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 Wd(t,e){return !e||e.length===0?t:t.map(n=>vl(n,e))}function Jd(t,e){return !e||e.length===0?t:t.map(n=>Cl(n,e))}function Kd(t,e){return !e||e.length===0?t:t.map(n=>Tl(n,e))}function Fw(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&&!Hd(i.cast)&&e.add(r);}return e}function Hd(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function Al(t,e){if(Array.isArray(t))return t.map(r=>Al(r,e));if(!os(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||!ro(i)||s in n&&(n[s]=qw(n[s],i.select));}return n}function vl(t,e){if(Array.isArray(t))return t.map(r=>vl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=vl(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=Bw(n[s]));}return n}function Cl(t,e){if(Array.isArray(t))return t.map(r=>Cl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=Cl(n[s],i.select));continue}Hd(i.cast)&&s in n&&(n[s]=zd(n[s]));}return n}function Tl(t,e){if(Array.isArray(t))return t.map(r=>Tl(r,e));if(!os(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(ro(i)){s in n&&i.select&&(n[s]=Tl(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=zd(n[s]));}return n}function Bw(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 qw(t,e){let n=Ww(t);return !e||e.length===0?n:Al(n,e)}function Ww(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 zd(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function os(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ro(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var Jw=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 Gd(t){let e=Ud(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function Vd(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(Jw.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function Qd(t,e){let n=Ud(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?$t({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function Tn(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}async function is(t,e,n,r){let s=e.join&&Object.values(e.join).some(f=>f.type==="inner"),i=Kw(e);if(s||i){let f={...e,type:"query",order:void 0,limit:void 0,offset:void 0},u=me(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),y=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,b=(await t.executeQuery({sql:y,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(b?.__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 me(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function Yd(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres")return is(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=me(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"],f=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,u=f&&typeof f=="object"?Number(f["Plan Rows"]):Number.NaN;return Number.isFinite(u)?u:is(t,e,n,r)}function Kw(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=Hw(t.select);return e.size===0?false:Xd(t.where,e)}function Xd(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"&&Xd(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 Hw(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}var zw=/[",\n\r ]/;function Zd(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),zw.test(e)?`"${e.replace(/"/g,'""')}"`:e}function so(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>Zd(s)).join(",")];for(let s of t)r.push(n.map(i=>Zd(s[i])).join(","));return r.join(`
81
+ `)}function ep(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function rp(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 O(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=tp(t,e),s=Gw(t.where,r);if(!s)return O(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(!Ol(t.values))return O(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!Qw(t.values[i],s[i]))return O(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:tp(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 sp(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=kl(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*";return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:Pt(t,"representation",e.appliedResolution,false),headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:Pt(t,"no-return",e.appliedResolution,false),headers:r}))}function tp(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 Gw(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=Vw(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function Vw(t){if(!Ol(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function Qw(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):$t(t)===$t(e)}function kl(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 Pt(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 ip(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await np(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(!Ol(o))continue;let a=Yw(s.preflight.conflictColumns,o);if(!a||!await np(t,e.from,e.schema,a,n,r))return true}return false}function Yw(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function np(t,e,n,r,s,i){return await is(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function Ol(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ap(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function op(t,e,n){return ap(e)?`*/${n??0}`:t.type==="update"&&n!==0?Tn(0,n??1,void 0):"*/*"}function Xw(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":Tn(n,1,r)}function lp(t){return "select"in t||"spread"in t||"join"in t}function cp(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))lp(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),cp(r.select,e));}}function Zw(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(lp(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}var eS={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"]},up=t=>new Se().all("/:relation",async e=>{let{app:n}=e.var,r=n.connection;if(!n.config.api?.enabled)return e.notFound();let s=e.req.param("relation"),i=await r.introspect({useCache:true});if(r.config.introspection?.exclude_tables?.some(d=>qi(s,d,"sql")))return e.notFound();if(!(ss in e.req.raw)){let d=await jd(e.req.header("Authorization"),{jwtSecret:n.config.auth?.jwt_secret,anonymousEnabled:n.config.api?.anonymous_enabled!==false});if(d.kind==="error")return d.response;d.payload&&(e.set("userId",d.payload.sub),e.set("sessionId",d.payload.session_id),e.set("jwt",d.payload));}let{dialect:a}=r,l=r.config.translation?.deparse?.schema,c=e.var.jwt,f={auth:{uid:e.var.userId??null,role:c?.role||"anon",jwt:c??null}},u;try{if(u=await Ri(e.req.raw,{basePath:"/rest/v1"}),u.schema){let x=new Set;for(let T of i.tables)T.schema&&x.add(T.schema);for(let T of i.views)T.schema&&x.add(T.schema);if(x.size>0&&x.add("public"),x.size>0&&!x.has(u.schema)){let T=[...x].sort().join(", ");return O(406,"PGRST106",`Invalid schema: ${u.schema}`,null,`Only the following schemas are exposed: ${T}`)}}if(u=await r.onPostgrestAST(u,f),t?.debug&&console.log(ze.default.dim("[POSTGREST:AST]"),u),n.config.api?.aggregates_enabled!==!0&&Va(u.select))return O(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let d=e.req.header("Accept")??"application/json",p=n.config.api?.plan_enabled===!0;if(!Vd(d,p))return O(406,"PGRST107",`None of these media types are available: ${Gd(d)}`,null,null);let y=Fd(d),h=ep(d),b=e.req.header("Prefer");if(b){let x=b.split(",").map(v=>v.trim()).filter(Boolean);if(x.find(v=>v.startsWith("handling="))==="handling=strict"){let v=x.filter(A=>!A.includes("="));if(v.length>0)return O(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${v.join(", ")}`,null)}}if(r.dialect==="sqlite"&&u.from){let x=u.schema??"",T=i.tables.some(A=>A.name===u.from&&(A.schema??"")===x),v=i.views.some(A=>A.name===u.from&&(A.schema??"")===x);if(!T&&!v)throw new Zr(u.schema,u.from)}let m=u.$meta,w=u.type==="update"||u.type==="delete"||u.type==="insert"||u.type==="upsert"||u.type==="put",_={ast:u};if(w&&m?.return!=="representation"&&(u.select=void 0),(u.type==="put"||u.type==="upsert")&&(u.limit!==void 0||u.offset!==void 0))return O(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((u.type==="update"||u.type==="delete"||u.type==="insert")&&n.config.api?.limited_mutations_enabled!==!0&&(u.limit=void 0,u.offset=void 0),n.config.api?.pg_safe_update&&w){let x=u.where&&Object.keys(u.where).length>0;if(u.type==="update"&&!x)return O(400,"21000","UPDATE requires a WHERE clause",null,null);if(u.type==="delete"&&!x)return O(400,"21000","DELETE requires a WHERE clause",null,null)}if(w&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){if((u.type==="update"||u.type==="insert"||u.type==="upsert"||u.type==="put")&&(u.values===void 0||u.values===null))return O(400,"PGRST102","Empty or invalid json",null,null);if(u.type==="update"&&u.values&&typeof u.values=="object"&&!Array.isArray(u.values)&&Object.keys(u.values).length===0){let x=m?.return==="representation"?200:204,T={"Content-Type":"application/json; charset=utf-8","Content-Range":"*/*"};if(m?.return==="representation"){let v=new TextEncoder().encode("[]");return T["Content-Length"]=String(v.byteLength),T["Preference-Applied"]="return=representation",new Response(v,{status:x,headers:T})}return new Response(null,{status:x,headers:T})}if(u.type==="put"&&Array.isArray(u.values)&&(u.values.length===0?_.emptyPayload=!0:u.values=u.values[0]),Array.isArray(u.values)){if(m?.cardinality==="one"&&(u.type==="insert"||u.type==="upsert")&&u.values.length>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${u.values.length} rows`,null);if(u.values.length>0&&u.values.some(x=>typeof x!="object"||x===null||Array.isArray(x)))return m?.columns?O(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):O(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&u.values.length>1){let x=Object.keys(u.values[0]).sort().join(",");for(let T=1;T<u.values.length;T++)if(Object.keys(u.values[T]).sort().join(",")!==x)return O(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&u.from){let x=i.columns.filter(v=>v.table===u.from).map(v=>v.name);for(let v of m.columns){if(v==="")return O(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!x.includes(v))return O(400,"PGRST204",`Could not find the '${v}' column of '${u.from}' in the schema cache`,null,null)}let T=new Set(m.columns);if(u.values)if(Array.isArray(u.values))u.values=u.values.map(v=>{let A={};for(let z of T)z in v&&(A[z]=v[z]);return A});else {let v={};for(let A of T)A in u.values&&(v[A]=u.values[A]);u.values=v;}}if(!m?.columns&&u.values&&u.from&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){let x=i.columns.filter(T=>T.table===u.from).map(T=>T.name);if(x.length>0){let T=Array.isArray(u.values)?u.values.length>0?Object.keys(u.values[0]):[]:Object.keys(u.values);for(let v of T)if(!x.includes(v))return O(400,"PGRST204",`Could not find the '${v}' column of '${u.from}' in the schema cache`,null,null)}}if(u.values&&u.from&&(u.type==="insert"||u.type==="update"||u.type==="upsert"||u.type==="put")){let x=u.schema??"public",T=new Set(i.columns.filter(v=>v.table===u.from&&(v.schema||"public")===x&&v.is_generated===!0).map(v=>v.name));if(T.size>0){let v=Array.isArray(u.values)?u.values:[u.values];for(let A of v)if(!(!A||typeof A!="object")){for(let z of Object.keys(A))if(T.has(z))return O(400,"428C9",`cannot insert a non-DEFAULT value into column "${z}"`,`Column "${z}" is a generated column.`,null)}}}}let S=rp(u,i);if(S instanceof Response)return S;if(_=S,u=_.ast,w&&((u.type==="insert"||u.type==="upsert")&&Array.isArray(u.values)&&u.values.length===0||_.emptyPayload))return m?.cardinality==="one"?O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):sp(u,_);let E=e.req.method.toUpperCase(),C=e.req.header("Range");if(C&&(E==="GET"||E==="HEAD")){let x=C.match(/^(\d+)-(\d*)$/);if(x){let T=parseInt(x[1],10);if(x[2]!==""){let v=parseInt(x[2],10);if(T>v)return O(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);u.offset=T,u.limit=v-T+1;}else u.offset=T;}}if(u.limit!==void 0&&u.limit<0||u.limit===0&&u.offset!==void 0&&u.offset>0)return O(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(u.offset!==void 0&&u.offset<0&&(u.offset=0),!w){let x=n.config.api?.max_rows;x!==void 0&&x>0&&((u.limit===void 0||u.limit>x)&&(u.limit=x),cp(u.select,x));}return await r.withContext(f,async x=>{let T=e.req.header("Accept")??"application/json";if(p&&Md(T)){let W=me(u,a,{db:x,introspection:i,schema:l}).compile();return t?.debug&&console.info(ze.default.dim(`[POSTGREST:PLAN] ${W.sql}
82
+ - ${JSON.stringify([...W.parameters])}`)),Qd(T,W)}let v=w?await ip(x,u,a,i,_):void 0,A=kl(m,_.appliedResolution);if(w&&m?.return==="minimal"){let ae={...u,select:void 0},W=me(ae,a,{db:x,introspection:i,schema:l}),{sql:Y,parameters:nt}=W.compile();t?.debug&&console.info(ze.default.dim(`[POSTGREST:SQL] ${Y}
83
+ - ${JSON.stringify([...nt])}`));let Z=await W.execute(),Ae=Array.isArray(Z)&&Z.length>0&&Z[0]&&typeof Z[0]=="object"&&("numUpdatedRows"in Z[0]||"numInsertedOrUpdatedRows"in Z[0]||"numDeletedRows"in Z[0])?Z[0]:void 0,qt=Ae===void 0?void 0:Number(Ae.numUpdatedRows??Ae.numInsertedOrUpdatedRows??Ae.numDeletedRows??0),De=Pt(u,"no-return",_.appliedResolution,v),je={"Content-Range":op(u,m,qt)};return A&&(je["Preference-Applied"]=A),new Response(null,{status:De,headers:je})}if(w&&m?.return==="headers-only"){let W=i.primary_keys.find(De=>De.table===u.from)?.columns??[],Y={...u,select:W.length>0?W:void 0},nt=me(Y,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:De,parameters:je}=nt.compile();console.info(ze.default.dim(`[POSTGREST:SQL] ${De}
84
+ - ${JSON.stringify([...je])}`));}let Z=await nt.execute(),Ae=Pt(u,"no-return",_.appliedResolution,v),qt={"Content-Range":"*/*"};if(A&&(qt["Preference-Applied"]=A),W.length>0&&Array.isArray(Z)&&Z.length>0){let De=Z[0],je=W.map(yt=>`${yt}=eq.${De[yt]}`).join("&");qt.Location=`/${u.from}?${je}`;}return new Response(null,{status:Ae,headers:qt})}if(w&&(u.type==="update"||u.type==="delete")&&(u.limit!==void 0||u.offset!==void 0)){let ae={...u,select:void 0},W=me(ae,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:yt,parameters:Wt}=W.compile();console.info(ze.default.dim(`[POSTGREST:SQL:LTD] ${yt}
85
85
  - ${JSON.stringify([...Wt])}`));}if(await W.execute(),m?.return==="representation"){let yt={...u,type:"query",values:void 0,limit:void 0,offset:void 0},Wt=me(yt,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:it,parameters:Zs}=Wt.compile();console.info(ze.default.dim(`[POSTGREST:SQL:LTD-SEL] ${it}
86
- - ${JSON.stringify([...Zs])}`));}let qe=await Wt.execute(),_e=Array.isArray(qe)?qe:[];_e=_e.map(it=>r.deserializeRow(it)),_e=no(_e,u,l,"public");let rt=_e.length,We=[];m.return==="representation"&&We.push("return=representation"),m.count&&We.push(`count=${m.count}`),m.tx&&We.push(`tx=${m.tx}`);let Je=u.type==="delete"?"*/*":rt>0?Rn(0,rt,void 0):"*/*",st=y?Cn(_e):_e,Yo=h?so(st):$t(st),_r=new TextEncoder().encode(Yo),bt={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Je,"Content-Length":String(_r.byteLength)};return We.length>0&&(bt["Preference-Applied"]=We.join(", ")),new Response(_r,{status:200,headers:bt})}let X={...u,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},Z=await me(X,a,{db:x,introspection:i,schema:l}).execute(),ke=Number((Array.isArray(Z)?Z[0]:Z)?.__count??0),De={"Content-Range":ke>0?Rn(0,ke,void 0):"*/*"},je=[];return m?.count&&je.push(`count=${m.count}`),m?.tx&&je.push(`tx=${m.tx}`),je.length>0&&(De["Preference-Applied"]=je.join(", ")),new Response(null,{status:204,headers:De})}if(w&&m?.return==="representation"&&Zw(u.select)){let W=i.primary_keys.find(qe=>qe.table===u.from)?.columns??[],X=[];if(u.type==="delete"){let qe={...u,type:"query",values:void 0},_e=me(qe,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:Je,parameters:st}=_e.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-PRE] ${Je}
87
- - ${JSON.stringify([...st])}`));}X=await _e.execute();let rt={...u,select:void 0},We=me(rt,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:Je,parameters:st}=We.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-DEL] ${Je}
86
+ - ${JSON.stringify([...Zs])}`));}let qe=await Wt.execute(),_e=Array.isArray(qe)?qe:[];_e=_e.map(it=>r.deserializeRow(it)),_e=no(_e,u,l,"public");let rt=_e.length,We=[];m.return==="representation"&&We.push("return=representation"),m.count&&We.push(`count=${m.count}`),m.tx&&We.push(`tx=${m.tx}`);let Je=u.type==="delete"?"*/*":rt>0?Tn(0,rt,void 0):"*/*",st=y?Cn(_e):_e,Xo=h?so(st):$t(st),_r=new TextEncoder().encode(Xo),bt={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Je,"Content-Length":String(_r.byteLength)};return We.length>0&&(bt["Preference-Applied"]=We.join(", ")),new Response(_r,{status:200,headers:bt})}let Y={...u,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},Z=await me(Y,a,{db:x,introspection:i,schema:l}).execute(),Ae=Number((Array.isArray(Z)?Z[0]:Z)?.__count??0),De={"Content-Range":Ae>0?Tn(0,Ae,void 0):"*/*"},je=[];return m?.count&&je.push(`count=${m.count}`),m?.tx&&je.push(`tx=${m.tx}`),je.length>0&&(De["Preference-Applied"]=je.join(", ")),new Response(null,{status:204,headers:De})}if(w&&m?.return==="representation"&&Zw(u.select)){let W=i.primary_keys.find(qe=>qe.table===u.from)?.columns??[],Y=[];if(u.type==="delete"){let qe={...u,type:"query",values:void 0},_e=me(qe,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:Je,parameters:st}=_e.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-PRE] ${Je}
87
+ - ${JSON.stringify([...st])}`));}Y=await _e.execute();let rt={...u,select:void 0},We=me(rt,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:Je,parameters:st}=We.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-DEL] ${Je}
88
88
  - ${JSON.stringify([...st])}`));}await We.execute();}else {if(W.length===0)return O(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let qe={...u,select:W},_e=me(qe,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:Je,parameters:st}=_e.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-MUT] ${Je}
89
- - ${JSON.stringify([...st])}`));}let rt=await _e.execute(),We=Array.isArray(rt)?rt:[];if(We.length>0){let Je;if(W.length===1){let bt=W[0];Je={[bt]:{$in:We.map(it=>it[bt])}};}else Je={$or:We.map(bt=>{let it={};for(let Zs of W)it[Zs]={$eq:bt[Zs]};return it})};let st=u.where?{$and:[u.where,Je]}:Je,Yo={...u,type:"query",values:void 0,where:st},_r=me(Yo,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:bt,parameters:it}=_r.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-SEL] ${bt}
90
- - ${JSON.stringify([...it])}`));}X=await _r.execute();}}X=X.map(qe=>r.deserializeRow(qe)),X=no(X,u,l,"public"),u.order&&u.order.length>0&&(X=Tl(X,u.order));let nt=Pt(u,"representation",_.appliedResolution,v),Z=X.length,ke=["return=representation"];m?.count&&ke.push(`count=${m.count}`),m?.tx&&ke.push(`tx=${m.tx}`);let qt=u.type==="delete"||u.type==="insert"||u.type==="upsert"?"*/*":Z>0?Rn(0,Z,void 0):"*/*",De=y?Cn(X):X,je=h?so(De):$t(De),yt=new TextEncoder().encode(je),Wt={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":qt,"Content-Length":String(yt.byteLength)};if(ke.length>0&&(Wt["Preference-Applied"]=ke.join(", ")),(u.type==="insert"||u.type==="upsert")&&W.length>0&&X.length>0){let qe=X[0],_e=W.map(rt=>`${rt}=eq.${qe[rt]}`).join("&");Wt.Location=`/${u.from}?${_e}`;}return new Response(yt,{status:nt,headers:Wt})}let ue=me(u,a,{db:x,introspection:i,schema:l}),{sql:Xe,parameters:Qs}=ue.compile();t?.debug&&console.info(ze.default.dim(`[POSTGREST:SQL] ${Xe}
91
- - ${JSON.stringify([...Qs])}`));let gt=await ue.execute(),re,ru=!1,Sr=0;if(w&&Array.isArray(gt)&&gt.length>0&&gt[0]&&typeof gt[0]=="object"&&("numUpdatedRows"in gt[0]||"numInsertedOrUpdatedRows"in gt[0]||"numDeletedRows"in gt[0])){ru=!0;let ae=gt[0];Sr=Number(ae.numUpdatedRows??ae.numInsertedOrUpdatedRows??ae.numDeletedRows??0),re=[];}else re=gt;let Vo=Array.isArray(re);Vo&&(re=re.map(ae=>r.deserializeRow(ae)),re=no(re,u,l,"public"),re=Fd(re,u.select),re=qd(re,u.select),re=Wd(re,u.select),re=Jd(re,u.select),r.dialect==="sqlite"&&(re=Bd(re,u.select))),w&&Vo&&u.order&&u.order.length>0&&(re=Tl(re,u.order));let Qo=Vo?re:[],Bt=Qo.length,an=u.offset??0;if(w&&ru){if(m?.cardinality==="one"){if(Sr===0)return O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(Sr>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${Sr} rows`,null)}let ae=Pt(u,"no-return",_.appliedResolution,v),W={"Content-Type":"application/json; charset=utf-8","Content-Range":ip(u,m,Sr)};return k&&(W["Preference-Applied"]=k),new Response(null,{status:ae,headers:W})}let we;if(op(m)&&(w?we=Bt:we=await Qd(x,u,a,i)),m?.cardinality==="one"){if(Bt===0)return O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(Bt>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${Bt} rows`,null);let ae=200;w&&(ae=Pt(u,"representation",_.appliedResolution,v));let W=y?Cn(Qo[0]):Qo[0],X=$t(W),nt=new TextEncoder().encode(X),Z={"Content-Type":y?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.object+json; charset=utf-8","Content-Range":Yw(u,w,an,we),"Content-Length":String(nt.byteLength)};return k&&(Z["Preference-Applied"]=k),m?.head?new Response(null,{status:ae,headers:Z}):new Response(nt,{status:ae,headers:Z})}if(we!==void 0&&an>0&&Bt===0&&an>=we){let ae=JSON.stringify({code:"PGRST103",details:`An offset of ${an} was requested, but there are only ${we} rows.`,hint:null,message:"Requested range not satisfiable"}),W=new TextEncoder().encode(ae),X={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${we}`,"Content-Length":String(W.byteLength)};return k&&(X["Preference-Applied"]=k),new Response(W,{status:416,headers:X})}let Er;w&&(u.type==="insert"||u.type==="upsert"||u.type==="delete")?Er=we!==void 0?`*/${we}`:"*/*":w&&m?.return!=="representation"?Er=we!==void 0?`*/${we}`:"*/*":Bt>0?Er=Rn(an,Bt,we):Er=we!==void 0?`*/${we}`:"*/*";let Xs=200;w?Xs=Pt(u,"representation",_.appliedResolution,v):we!==void 0&&(an+Bt<we||an>0)&&(Xs=206);let Ys=y?Cn(re):re,Ph=h?so(Array.isArray(Ys)?Ys:[Ys]):$t(Ys),su=new TextEncoder().encode(Ph),Xo={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Er,"Content-Length":String(su.byteLength)};return k&&(Xo["Preference-Applied"]=k),m?.head?new Response(null,{status:Xs,headers:Xo}):new Response(su,{status:Xs,headers:Xo})},{forceRollback:t?.forceRollback===!0})}catch(d){if(d instanceof pe){let y=`"${d.message}" (line 1, column ${d.position})`;return O(400,"PGRST100",y,d.details,null)}if(d instanceof Me)return O(400,"PGRST100",d.message,d.details,null);if(d instanceof Qt)return O(400,"PGRST100",d.message,d.details,null);if(d instanceof Jn)return O(404,"PGRST125",d.message,d.details,null);if(d instanceof Ae)return O(d.httpStatus,d.code,d.message,d.details,d.hint);if(d instanceof Kn)return O(400,"PGRST102",d.message,null,null);if(d instanceof Error&&d.message.startsWith("Invalid JSON body"))return O(400,"PGRST102","Empty or invalid json",null,null);if(d instanceof vt)return O(400,"PGRST100",d.message,d.message,null);if(d instanceof Sn)return O(400,"23514",d.message,`check constraint "${d.constraint}" violated`,null);if(d instanceof zn){let h=Yt(f,"auth.role","anon")==="anon"?401:403;return Ze({status:h,code:"PGRST301",message:d.message})}let p=r.normalizeDbError(d);if(console.error(p),p instanceof Zr){let y=[...i.tables.map(m=>m.name),...i.views.map(m=>m.name)],h=pd(p.relation,y),b=p.schema||"public";return Ze({status:404,code:"PGRST205",message:p.message,hint:h?`Perhaps you meant the table '${b}.${h}'`:null})}if(p?.code==="42501"){let h=Yt(f,"auth.role","anon")==="anon"?401:403;return Ze({status:h,code:"PGRST301",message:p.message})}if(p?.code==="42P01")return O(404,"PGRST205","Could not find the relation in the schema cache",p.message,null);if(p?.code==="23505"||p?.code==="23503")return O(409,p.code,p.message,p.detail??null,null);if(typeof p?.code=="string"){let y=p.code.slice(0,2);if(p.code==="42883")return O(404,p.code,p.message,p.detail??null,p.hint??null);if(y==="42"||y==="22"||y==="21"||p.code==="23502"){let h=p.message,b=u?.from;return p.code==="42703"&&b&&(h=h.replace(/^column "([^"]+)" does not exist$/,(m,w)=>`column ${b}.${w} does not exist`)),O(400,p.code,h,p.detail??null,p.hint??null)}if(y==="55")return O(500,p.code,p.message,p.detail??null,p.hint??null)}return p?.message?.includes("Unknown operator")?O(400,"PGRST100",p.message,null,null):p instanceof Error&&(p.message.includes("Expected identifier")||p.message.includes("Invalid filter")||p.message.includes("Unexpected input")||p.message.includes("Unsupported operator")||p.message.includes("failed to parse filter")||p.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(p.message)||p.message.startsWith('Expected "(" for spread embed'))?O(400,"PGRST100",p.message,p.message,null):O(500,"SUP",String(p),null,null)}}).use(async(e,n)=>{if(e.req.method==="GET"&&e.req.path.endsWith("/"))return e.json(eS);await n();}).all("*",e=>O(404,"PGRST125","Invalid path specified in request URL",null,null));var Zn=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:up(e)+up(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 up(t){return new TextEncoder().encode(t).byteLength}var io=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 oo=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 ao=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 co=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(()=>(hp(),mp));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var uo=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=Il(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 Il(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(`
89
+ - ${JSON.stringify([...st])}`));}let rt=await _e.execute(),We=Array.isArray(rt)?rt:[];if(We.length>0){let Je;if(W.length===1){let bt=W[0];Je={[bt]:{$in:We.map(it=>it[bt])}};}else Je={$or:We.map(bt=>{let it={};for(let Zs of W)it[Zs]={$eq:bt[Zs]};return it})};let st=u.where?{$and:[u.where,Je]}:Je,Xo={...u,type:"query",values:void 0,where:st},_r=me(Xo,a,{db:x,introspection:i,schema:l});if(t?.debug){let{sql:bt,parameters:it}=_r.compile();console.info(ze.default.dim(`[POSTGREST:SQL:EMB-SEL] ${bt}
90
+ - ${JSON.stringify([...it])}`));}Y=await _r.execute();}}Y=Y.map(qe=>r.deserializeRow(qe)),Y=no(Y,u,l,"public"),u.order&&u.order.length>0&&(Y=Rl(Y,u.order));let nt=Pt(u,"representation",_.appliedResolution,v),Z=Y.length,Ae=["return=representation"];m?.count&&Ae.push(`count=${m.count}`),m?.tx&&Ae.push(`tx=${m.tx}`);let qt=u.type==="delete"||u.type==="insert"||u.type==="upsert"?"*/*":Z>0?Tn(0,Z,void 0):"*/*",De=y?Cn(Y):Y,je=h?so(De):$t(De),yt=new TextEncoder().encode(je),Wt={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":qt,"Content-Length":String(yt.byteLength)};if(Ae.length>0&&(Wt["Preference-Applied"]=Ae.join(", ")),(u.type==="insert"||u.type==="upsert")&&W.length>0&&Y.length>0){let qe=Y[0],_e=W.map(rt=>`${rt}=eq.${qe[rt]}`).join("&");Wt.Location=`/${u.from}?${_e}`;}return new Response(yt,{status:nt,headers:Wt})}let ue=me(u,a,{db:x,introspection:i,schema:l}),{sql:Ye,parameters:Qs}=ue.compile();t?.debug&&console.info(ze.default.dim(`[POSTGREST:SQL] ${Ye}
91
+ - ${JSON.stringify([...Qs])}`));let gt=await ue.execute(),re,su=!1,Sr=0;if(w&&Array.isArray(gt)&&gt.length>0&&gt[0]&&typeof gt[0]=="object"&&("numUpdatedRows"in gt[0]||"numInsertedOrUpdatedRows"in gt[0]||"numDeletedRows"in gt[0])){su=!0;let ae=gt[0];Sr=Number(ae.numUpdatedRows??ae.numInsertedOrUpdatedRows??ae.numDeletedRows??0),re=[];}else re=gt;let Vo=Array.isArray(re);Vo&&(re=re.map(ae=>r.deserializeRow(ae)),re=no(re,u,l,"public"),re=Bd(re,u.select),re=Wd(re,u.select),re=Jd(re,u.select),re=Kd(re,u.select),r.dialect==="sqlite"&&(re=qd(re,u.select))),w&&Vo&&u.order&&u.order.length>0&&(re=Rl(re,u.order));let Qo=Vo?re:[],Bt=Qo.length,an=u.offset??0;if(w&&su){if(m?.cardinality==="one"){if(Sr===0)return O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(Sr>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${Sr} rows`,null)}let ae=Pt(u,"no-return",_.appliedResolution,v),W={"Content-Type":"application/json; charset=utf-8","Content-Range":op(u,m,Sr)};return A&&(W["Preference-Applied"]=A),new Response(null,{status:ae,headers:W})}let we;if(ap(m)&&(w?we=Bt:we=await Yd(x,u,a,i)),m?.cardinality==="one"){if(Bt===0)return O(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(Bt>1)return O(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${Bt} rows`,null);let ae=200;w&&(ae=Pt(u,"representation",_.appliedResolution,v));let W=y?Cn(Qo[0]):Qo[0],Y=$t(W),nt=new TextEncoder().encode(Y),Z={"Content-Type":y?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.object+json; charset=utf-8","Content-Range":Xw(u,w,an,we),"Content-Length":String(nt.byteLength)};return A&&(Z["Preference-Applied"]=A),m?.head?new Response(null,{status:ae,headers:Z}):new Response(nt,{status:ae,headers:Z})}if(we!==void 0&&an>0&&Bt===0&&an>=we){let ae=JSON.stringify({code:"PGRST103",details:`An offset of ${an} was requested, but there are only ${we} rows.`,hint:null,message:"Requested range not satisfiable"}),W=new TextEncoder().encode(ae),Y={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${we}`,"Content-Length":String(W.byteLength)};return A&&(Y["Preference-Applied"]=A),new Response(W,{status:416,headers:Y})}let Er;w&&(u.type==="insert"||u.type==="upsert"||u.type==="delete")?Er=we!==void 0?`*/${we}`:"*/*":w&&m?.return!=="representation"?Er=we!==void 0?`*/${we}`:"*/*":Bt>0?Er=Tn(an,Bt,we):Er=we!==void 0?`*/${we}`:"*/*";let Ys=200;w?Ys=Pt(u,"representation",_.appliedResolution,v):we!==void 0&&(an+Bt<we||an>0)&&(Ys=206);let Xs=y?Cn(re):re,Ph=h?so(Array.isArray(Xs)?Xs:[Xs]):$t(Xs),iu=new TextEncoder().encode(Ph),Yo={"Content-Type":h?"text/csv; charset=utf-8":y?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":Er,"Content-Length":String(iu.byteLength)};return A&&(Yo["Preference-Applied"]=A),m?.head?new Response(null,{status:Ys,headers:Yo}):new Response(iu,{status:Ys,headers:Yo})},{forceRollback:t?.forceRollback===!0})}catch(d){if(d instanceof pe){let y=`"${d.message}" (line 1, column ${d.position})`;return O(400,"PGRST100",y,d.details,null)}if(d instanceof Me)return O(400,"PGRST100",d.message,d.details,null);if(d instanceof Qt)return O(400,"PGRST100",d.message,d.details,null);if(d instanceof Jn)return O(404,"PGRST125",d.message,d.details,null);if(d instanceof ke)return O(d.httpStatus,d.code,d.message,d.details,d.hint);if(d instanceof Kn)return O(400,"PGRST102",d.message,null,null);if(d instanceof Error&&d.message.startsWith("Invalid JSON body"))return O(400,"PGRST102","Empty or invalid json",null,null);if(d instanceof vt)return O(400,"PGRST100",d.message,d.message,null);if(d instanceof Sn)return O(400,"23514",d.message,`check constraint "${d.constraint}" violated`,null);if(d instanceof zn){let h=Xt(f,"auth.role","anon")==="anon"?401:403;return Ze({status:h,code:"PGRST301",message:d.message})}let p=r.normalizeDbError(d);if(console.error(p),p instanceof Zr){let y=[...i.tables.map(m=>m.name),...i.views.map(m=>m.name)],h=md(p.relation,y),b=p.schema||"public";return Ze({status:404,code:"PGRST205",message:p.message,hint:h?`Perhaps you meant the table '${b}.${h}'`:null})}if(p?.code==="42501"){let h=Xt(f,"auth.role","anon")==="anon"?401:403;return Ze({status:h,code:"PGRST301",message:p.message})}if(p?.code==="42P01")return O(404,"PGRST205","Could not find the relation in the schema cache",p.message,null);if(p?.code==="23505"||p?.code==="23503")return O(409,p.code,p.message,p.detail??null,null);if(typeof p?.code=="string"){let y=p.code.slice(0,2);if(p.code==="42883")return O(404,p.code,p.message,p.detail??null,p.hint??null);if(y==="42"||y==="22"||y==="21"||p.code==="23502"){let h=p.message,b=u?.from;return p.code==="42703"&&b&&(h=h.replace(/^column "([^"]+)" does not exist$/,(m,w)=>`column ${b}.${w} does not exist`)),O(400,p.code,h,p.detail??null,p.hint??null)}if(y==="55")return O(500,p.code,p.message,p.detail??null,p.hint??null)}return p?.message?.includes("Unknown operator")?O(400,"PGRST100",p.message,null,null):p instanceof Error&&(p.message.includes("Expected identifier")||p.message.includes("Invalid filter")||p.message.includes("Unexpected input")||p.message.includes("Unsupported operator")||p.message.includes("failed to parse filter")||p.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(p.message)||p.message.startsWith('Expected "(" for spread embed'))?O(400,"PGRST100",p.message,p.message,null):O(500,"SUP",String(p),null,null)}}).use(async(e,n)=>{if(e.req.method==="GET"&&e.req.path.endsWith("/"))return e.json(eS);await n();}).all("*",e=>O(404,"PGRST125","Invalid path specified in request URL",null,null));var Zn=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:fp(e)+fp(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 fp(t){return new TextEncoder().encode(t).byteLength}var io=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 oo=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 ao=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 co=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(()=>(gp(),hp));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var uo=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=Il(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 Il(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(`
92
92
  `)}var ls=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);}}},er=class extends ls{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(`
93
93
  `));}};var cs=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(`
94
- `));}};function gp(t={}){return {email:t.email??new er,sms:t.sms??new cs,cache:t.cache??new Zn}}var Dl=new Map,us=class{constructor(e){this.driver=e;}async sendConfirmation(e,n,r,s){await this.send(sS(e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(iS(e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(oS(e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(aS(e,n,r,s));}async sendReauthentication(e,n,r){await this.send(lS(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 sS(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 iS(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 oS(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 aS(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 lS(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 M=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 M(400,"invalid_credentials","Invalid login credentials"),yp=()=>new M(400,"email_not_confirmed","Email not confirmed"),bp=(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 M(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},wp=(t="Access token is required")=>new M(401,"no_authorization",t),tr=()=>new M(401,"no_authorization","This endpoint requires a valid Bearer token"),fs=t=>new M(403,"bad_jwt",t),jl=()=>fs("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),Ll=t=>fs(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),Sp=()=>fs("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),Ep=()=>fs("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),Ul=()=>fs("invalid claim: missing sub claim"),Ml=()=>new M(400,"bad_jwt","invalid claim: sub claim must be a UUID");var _p=()=>new M(403,"user_not_found","User from sub claim in JWT does not exist"),xp=()=>new M(403,"session_not_found","Session from session_id claim in JWT does not exist"),vp=()=>new M(422,"user_already_exists","User already registered"),Cp=()=>new M(422,"email_exists","A user with this email address has already been registered"),Fl=()=>new M(422,"signup_disabled","Signups not allowed for this instance"),Rp=()=>new M(400,"email_provider_disabled","Email signups are disabled"),Tp=()=>new M(422,"otp_disabled","Signups not allowed for otp"),kp=()=>new M(422,"same_password","New password should be different from the old password."),nr=()=>new M(403,"otp_expired","Email link is invalid or has expired"),ne=(t,e=422)=>new M(e,"validation_failed",t);var ds=t=>new M(400,"bad_json",t),Bl=()=>new M(400,"validation_failed","Refresh token is not valid"),rr=()=>new M(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),fo=(t,e)=>new M(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),Ap=()=>new M(401,"session_not_found","Invalid Refresh Token: Already Used"),ql=(t,e,n)=>new M(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}:{}}),Op=()=>new M(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),$p=()=>new M(400,"invalid_credentials","unsupported_grant_type"),po=()=>new M(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds.");async function Jl(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new vn({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function Pp(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw jl();let r=cS(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await xn(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof Ot.JWTExpired?Ep():i instanceof Ot.JWSSignatureVerificationFailed?Sp():i instanceof Ot.JWSInvalid||i instanceof Ot.JWTInvalid?jl():i}}function cS(t){let e=uS(t);if(!e)return Ll("unexpected end of JSON input");let n=fS(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return Ll(Kl(n))}}function uS(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 fS(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var dS={n:"null",t:"true",f:"false"};function Kl(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=dS[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 ${Wl(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${Wl(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${Wl(r)} looking for beginning of value`}function Wl(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}async function ps(t){return Np.hash(t,10)}async function Hl(t,e){return Np.compare(t,e)}function Ip(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!pS(t,s))&&r.push("characters"),r}function pS(t,e){for(let n of t)if(e.includes(n))return true;return false}function Nt(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 et(){let t=crypto.getRandomValues(new Uint8Array(32));return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function zl(){return v7()}function Ge(){return v7()}function mo(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 ms=class{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;mo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??hS(n.password_requirements),this.sessionTimeboxSeconds=jp(n.sessions?.timebox),this.sessionInactivitySeconds=jp(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;async signUp(e,n,r){if(this.config.enable_signup===false)throw Fl();if(!e)throw Op();if(this.config.email?.enable_signup===false)throw Rp();if(n==null||n===void 0||n==="")throw ne("Signup requires a valid password",400);if(!sr(e))throw ne("Unable to validate email address: invalid format",400);if(n.length>72)throw ne("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"),vp()):po();let a=Ge(),l=await ps(n),c=new Date().toISOString(),f=null,u=null,d=null;i||(f=Nt(),u=et(),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},y={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},h=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:u,confirmation_sent_at:d});await this.repo.createIdentity({id:Ge(),provider:"email",provider_id:a,user_id:a,identity_data:y}),!i&&f&&u&&await this.mailer.sendConfirmation(e,u,f,{userId:a,redirectTo:this.config.site_url});let b=await this.repo.findIdentitiesByUserId(a),m=this.repo.parseUserJson(h),w=this.mapUserToResponse(m,b,"signup");if(i){let _=await this.createSessionForUser(m,b);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:_}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw ne("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 yp();if(!await Hl(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 Bl();let n=await this.repo.findRefreshToken(e);if(!n)throw gS(e)?rr():Bl();if(Lp(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw rr();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw rr();this.assertSessionRefreshable(s);}let i=Up(s?.updated_at,s?.refreshed_at,r.updated_at);await this.repo.revokeRefreshToken(n.id);let o=zl(),a=n.session_id??Ge();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 Ap();if(!e.session_id)throw fo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=yS(n,e.token),s=r.filter(c=>!Lp(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),fo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw fo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw rr();let a=await this.repo.findSessionById(e.session_id);if(!a)throw rr();this.assertSessionRefreshable(a);let l=Up(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 Jl({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 Mp({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 ql(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 ql("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 u=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=mS(u,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await Hl(n.password,s.encrypted_password))throw kp();i.encrypted_password=await ps(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 u=n.email.toLowerCase();if(!sr(u))throw ne("Unable to validate email address: invalid format",400);if(o=true,u!==s.email?.toLowerCase()){let d=await this.repo.findUserByEmail(u);if(d&&d.id!==e)throw Cp();let p=new Date().toISOString(),y=Nt(),h=et(),b=Nt(),m=et(),w=this.config.email?.double_confirm_changes??true;i.email_change=u,i.email_change_token_current=w?h:null,i.email_change_token_new=m,i.email_change_sent_at=p,w?await this.mailer.sendEmailChange(u,h,y,{userId:e,tokenNew:b,tokenHashNew:m,redirectTo:this.config.site_url}):await this.mailer.sendEmailChange(u,m,b,{userId:e,redirectTo:this.config.site_url});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let u=await this.repo.updateUser(e,i);if(!u)throw ft();c=this.repo.parseUserJson(u);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let f=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,f,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw ne(`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 ne("One of email or phone must be set",400);if(e=e.toLowerCase(),!sr(e))throw ne("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=Ge(),c=await ps(et()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,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:Ge(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw Tp();let i=Nt(),o=et(),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),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw ne("Password recovery requires an email",422);if(e=e.toLowerCase(),!sr(e))throw ne("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 Fl();let l=Ge(),c=await ps(et()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,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:Ge(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=Nt(),o=et(),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),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),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 f=n[c];if(f===e.token||this.otpMatchesStoredTokenHash(e.email,e.token,f)){r=c;break}}if(!r)throw nr()}else throw nr();else throw nr();if(!n)throw nr();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 f of c){let u=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...u,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 f=await this.repo.findIdentitiesByUserId(n.id);for(let u of f){let d=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...d,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 nr();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 ne("Password recovery requires an email",400);if(e=e.toLowerCase(),!sr(e))throw ne("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=Nt(),s=et(),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 ne("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw ne("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!sr(n))throw ne("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=Nt(),i=et(),o=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw po()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw po();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 wp();let r=Nt(),s=et(),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=new Date().toISOString(),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=Ge();await this.repo.createSession({id:l,user_id:e.id});let c=zl();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 f=await Jl({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),u=Math.floor(Date.now()/1e3);return Mp({access_token:f,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:u+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=Ip(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw bp(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:(Dl.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:Ge(),payload:o});}};function mS(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function hS(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 jp(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 sr(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function gS(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 Lp(t){return t.revoked===true||t.revoked===1}function yS(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 Up(...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 Mp(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}function Gl(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function Tn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var hs=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:Tn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:Tn(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=Tn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=Tn(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:Ge(),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:Tn(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:Gl(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=Tn(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:Tn(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:Gl(e.raw_app_meta_data),raw_user_meta_data:Gl(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};function Fp(){return {version:bS(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function Bp(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 qp(){return {keys:[]}}function Wp(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function bS(){return [Vl(JSON.stringify({alg:"HS256",typ:"JWT"})),Vl(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),Vl("metadata")].join(".")}function Vl(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 Ql=t=>t;var wS="00000000-0000-0000-0000-000000000000",SS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Xl=({onError:t}={})=>Ql(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await Kp(e);if(r&&t)return t(r,e)}await n();}),gs=()=>Ql(async(t,e)=>{if(!t.var.userId){let n=await Kp(t);if(n)return Jp(t,n);if(!t.var.userId)return Jp(t,tr())}await e();});async function Kp(t){let e=t.req.header("Authorization");if(!e)return tr();if(!e.startsWith("Bearer "))return tr();let n=e.slice(7);if(!n||/^\s/.test(n))return tr();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await Pp(n,r);}catch(c){return c instanceof M?c:tr()}let i=ES(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return _p();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return xp();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function ES(t){let e=t.sub,n=t.role;return e==null||e===""?Ul():typeof e!="string"?Ml():SS.test(e)?e===wS&&n==="service_role"?Ul():null:Ml()}function Jp(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var Yl=new Se().onError((t,e)=>{if(t instanceof M){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 It(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(ho(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",kn("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await It(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return ho(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return ho(t,s),t.json(s,200)}throw $p()}).all("/token",kn("POST")).post("/otp",async t=>{let e=await It(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 It(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",kn("POST")).post("/verify",async t=>{let e=await It(t),{authService:n}=t.var;xS(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return ho(t,r),t.json(r,200)}).get("/verify",t=>{let e=t.req.query("type");throw e?Hp.has(e)?ne("Verify requires a token or a token hash",400):ne("Invalid email verification type",400):ne("Verify requires a verification type",400)}).post("/recover",async t=>{let e=await It(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await It(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Fp(),200)).all("/health",kn("GET")).get("/settings",t=>t.json(Bp(t.var.app.config.auth??{}),200)).all("/settings",kn("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(qp(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(Wp(),200))).all("/nonexistent",_S).use(gs()).post("/logout",async t=>{let e=await It(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 It(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",kn("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",kn("GET"));function kn(t){return e=>(e.header("Allow",t),e.body(null,405))}function _S(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 Hp=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function xS(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw ne("Verify requires a verification type",400);if(!Hp.has(e))throw ne("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 ne("Verify requires either a token or a token hash",400)}async function It(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw ds("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 ds("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 ds("Could not parse request body as JSON: unexpected end of JSON input");let s=Kl(n)||"invalid character ' ' looking for beginning of value";throw ds(`Could not parse request body as JSON: ${s}`)}}function ho(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 zp(t){let e=t.connection.dialect,n=new hs(t.connection.kysely,e);return new ms(n,t.config.auth,t._mailer??new us(t.drivers.email))}function Gp(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function Vp(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function nn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var ys=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:nn(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:nn(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:nn(e.metadata??{}),user_metadata:nn(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=nn(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=nn(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=nn(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=nn(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:Vp(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:Gp(e.metadata),user_metadata:Gp(e.user_metadata),path_tokens:Vp(e.path_tokens)}}};var H=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 bs=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?CS(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw H.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw H.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw H.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){Zl(n);let i=await this.repo.findBucketById(e);if(!i)throw H.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 H.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw H.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw H.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 H.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 H.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await vS(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 H.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 H.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){Zl(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw H.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){Zl(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw H.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 H.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 H.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 H.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 xn(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 vn({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function vS(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 Zl(t){if(!t||t.includes("..")||t.startsWith("/"))throw H.invalidKey(t)}function CS(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 RS=/^[\w!#$%&'*.^`|~+-]+$/,TS=/^[ !#-:<-[\]-~]*$/,ec=(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(!RS.test(o))continue;let a=s.substring(i+1).trim();if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),TS.test(a)&&(r[o]=a.indexOf("%")!==-1?qn(a,Or):a,e));}return r};var Qp=(t,e,n)=>{let r=t.req.raw.headers.get("Cookie");return r?ec(r):{}};var Xp=(t,e)=>new Response(t,{headers:{"Content-Type":e}}).formData();var kS=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,AS=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,OS=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,tc=(t,e)=>async(n,r)=>{let s={},i=n.req.header("Content-Type");switch(t){case "json":if(!i||!kS.test(i))break;try{s=await n.req.json();}catch{let a="Malformed JSON in request body";throw new gi(400,{message:a})}break;case "form":{if(!i||!(AS.test(i)||OS.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 Xp(c,i),n.req.bodyCache.formData=a;}catch(c){let f="Malformed FormData request.";throw f+=c instanceof Error?` ${c.message}`:` ${String(c)}`,new gi(400,{message:f})}let l={};a.forEach((c,f)=>{f.endsWith("[]")?(l[f]??=[]).push(c):Array.isArray(l[f])?l[f].push(c):f in l?l[f]=[l[f],c]:l[f]=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=Qp(n);break}let o=await e(s,n);return o instanceof Response?o:(n.req.addValidatedData(t,o),await r())};var $S=Symbol.for("jsonv"),PS=(t,e)=>Object.assign(t,{[$S]:e}),Dt=(t,e,n,r)=>{let s=tc(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 PS(s,{type:"parameters",skip:n?.skipOpenAPI,value:{target:t,schema:e}})};ee();var NS=g.object({id:g.string(),name:g.string(),public:g.boolean({default:false}).optional(),file_size_limit:g.number().optional(),allowed_mime_types:g.array(g.string()).optional()}),IS=g.object({public:g.boolean().optional(),file_size_limit:g.number().optional(),allowed_mime_types:g.array(g.string()).optional()}),DS=g.object({prefix:g.string().optional(),limit:g.number().optional(),offset:g.number().optional(),sortBy:g.object({column:g.string(),order:g.string()}).optional(),search:g.string().optional()}),Yp=g.object({bucketId:g.string(),sourceKey:g.string(),destinationKey:g.string()}),jS=g.object({expiresIn:g.number()}),LS=g.object({expiresIn:g.number(),paths:g.array(g.string())}),US=g.object({prefixes:g.array(g.string())}),MS=new Se().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=nc(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:rc(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=nc(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:rc(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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)}),FS=new Se().use(gs()).post("/bucket",Dt("json",NS),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",Dt("json",IS),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",Dt("json",DS),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",Dt("json",Yp),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",Dt("json",Yp),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=dt(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/*",Dt("json",jS),async t=>{let e=t.req.param("bucketId"),n=dt(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",Dt("json",LS),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=dt(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",Dt("json",US),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=dt(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 d=(await t.req.formData()).get("file");if(!d)throw new H(400,"InvalidRequest","Missing file in multipart upload");let p=new Uint8Array(await d.arrayBuffer());a=p,l=d.type||"application/octet-stream",c=p.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 f=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${f.name}`,Id:f.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=dt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=nc(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:rc(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),sc=new Se().onError((t,e)=>t instanceof H?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",MS).route("/",FS);function dt(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 nc(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 rc(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}Qr();var ic=`-- supabase/storage core schema (Postgres)
94
+ `));}};function yp(t={}){return {email:t.email??new er,sms:t.sms??new cs,cache:t.cache??new Zn}}var Dl=new Map,us=class{constructor(e){this.driver=e;}async sendConfirmation(e,n,r,s){await this.send(sS(e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(iS(e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(oS(e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(aS(e,n,r,s));}async sendReauthentication(e,n,r){await this.send(lS(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 sS(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 iS(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 oS(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 aS(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 lS(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 M=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 M(400,"invalid_credentials","Invalid login credentials"),bp=()=>new M(400,"email_not_confirmed","Email not confirmed"),wp=(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 M(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},Sp=(t="Access token is required")=>new M(401,"no_authorization",t),tr=()=>new M(401,"no_authorization","This endpoint requires a valid Bearer token"),fs=t=>new M(403,"bad_jwt",t),jl=()=>fs("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),Ll=t=>fs(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),Ep=()=>fs("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),_p=()=>fs("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),Ul=()=>fs("invalid claim: missing sub claim"),Ml=()=>new M(400,"bad_jwt","invalid claim: sub claim must be a UUID");var xp=()=>new M(403,"user_not_found","User from sub claim in JWT does not exist"),vp=()=>new M(403,"session_not_found","Session from session_id claim in JWT does not exist"),Cp=()=>new M(422,"user_already_exists","User already registered"),Tp=()=>new M(422,"email_exists","A user with this email address has already been registered"),Fl=()=>new M(422,"signup_disabled","Signups not allowed for this instance"),Rp=()=>new M(400,"email_provider_disabled","Email signups are disabled"),Ap=()=>new M(422,"otp_disabled","Signups not allowed for otp"),kp=()=>new M(422,"same_password","New password should be different from the old password."),nr=()=>new M(403,"otp_expired","Email link is invalid or has expired"),ne=(t,e=422)=>new M(e,"validation_failed",t);var ds=t=>new M(400,"bad_json",t),Bl=()=>new M(400,"validation_failed","Refresh token is not valid"),rr=()=>new M(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),fo=(t,e)=>new M(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),Op=()=>new M(401,"session_not_found","Invalid Refresh Token: Already Used"),ql=(t,e,n)=>new M(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}:{}}),$p=()=>new M(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),Pp=()=>new M(400,"invalid_credentials","unsupported_grant_type"),po=()=>new M(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds.");async function Jl(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new vn({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function Np(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw jl();let r=cS(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await xn(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof Ot.JWTExpired?_p():i instanceof Ot.JWSSignatureVerificationFailed?Ep():i instanceof Ot.JWSInvalid||i instanceof Ot.JWTInvalid?jl():i}}function cS(t){let e=uS(t);if(!e)return Ll("unexpected end of JSON input");let n=fS(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return Ll(Kl(n))}}function uS(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 fS(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var dS={n:"null",t:"true",f:"false"};function Kl(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=dS[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 ${Wl(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${Wl(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${Wl(r)} looking for beginning of value`}function Wl(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var pS=10,mS=4,hS=4,gS=31;function yS(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(gS,Math.max(hS,Math.trunc(n)))}return t.RUN_SPEC==="1"?mS:pS}async function ps(t){return Ip.hash(t,yS())}async function Hl(t,e){return Ip.compare(t,e)}function Dp(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!bS(t,s))&&r.push("characters"),r}function bS(t,e){for(let n of t)if(e.includes(n))return true;return false}function Nt(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 et(){let t=crypto.getRandomValues(new Uint8Array(32));return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function zl(){return v7()}function Ge(){return v7()}function mo(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 ms=class{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;mo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??SS(n.password_requirements),this.sessionTimeboxSeconds=Lp(n.sessions?.timebox),this.sessionInactivitySeconds=Lp(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;async signUp(e,n,r){if(this.config.enable_signup===false)throw Fl();if(!e)throw $p();if(this.config.email?.enable_signup===false)throw Rp();if(n==null||n===void 0||n==="")throw ne("Signup requires a valid password",400);if(!sr(e))throw ne("Unable to validate email address: invalid format",400);if(n.length>72)throw ne("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"),Cp()):po();let a=Ge(),l=await ps(n),c=new Date().toISOString(),f=null,u=null,d=null;i||(f=Nt(),u=et(),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},y={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},h=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:u,confirmation_sent_at:d});await this.repo.createIdentity({id:Ge(),provider:"email",provider_id:a,user_id:a,identity_data:y}),!i&&f&&u&&await this.mailer.sendConfirmation(e,u,f,{userId:a,redirectTo:this.config.site_url});let b=await this.repo.findIdentitiesByUserId(a),m=this.repo.parseUserJson(h),w=this.mapUserToResponse(m,b,"signup");if(i){let _=await this.createSessionForUser(m,b);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:_}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw ne("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 bp();if(!await Hl(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 Bl();let n=await this.repo.findRefreshToken(e);if(!n)throw ES(e)?rr():Bl();if(Up(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw rr();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw rr();this.assertSessionRefreshable(s);}let i=Gl(s?.updated_at,s?.refreshed_at,r.updated_at);await this.repo.revokeRefreshToken(n.id);let o=zl(),a=n.session_id??Ge();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 Op();if(!e.session_id)throw fo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=_S(n,e.token),s=r.filter(c=>!Up(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),fo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw fo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw rr();let a=await this.repo.findSessionById(e.session_id);if(!a)throw rr();this.assertSessionRefreshable(a);let l=Gl(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 Jl({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 Mp({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 ql(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 ql("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 u=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=wS(u,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await Hl(n.password,s.encrypted_password))throw kp();i.encrypted_password=await ps(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 u=n.email.toLowerCase();if(!sr(u))throw ne("Unable to validate email address: invalid format",400);if(o=true,u!==s.email?.toLowerCase()){let d=await this.repo.findUserByEmail(u);if(d&&d.id!==e)throw Tp();let p=new Date().toISOString(),y=Nt(),h=et(),b=Nt(),m=et(),w=this.config.email?.double_confirm_changes??true;i.email_change=u,i.email_change_token_current=w?h:null,i.email_change_token_new=m,i.email_change_sent_at=p,w?await this.mailer.sendEmailChange(u,h,y,{userId:e,tokenNew:b,tokenHashNew:m,redirectTo:this.config.site_url}):await this.mailer.sendEmailChange(u,m,b,{userId:e,redirectTo:this.config.site_url});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let u=await this.repo.updateUser(e,i);if(!u)throw ft();c=this.repo.parseUserJson(u);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let f=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,f,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw ne(`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 ne("One of email or phone must be set",400);if(e=e.toLowerCase(),!sr(e))throw ne("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=Ge(),c=await ps(et()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,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:Ge(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw Ap();let i=Nt(),o=et(),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),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw ne("Password recovery requires an email",422);if(e=e.toLowerCase(),!sr(e))throw ne("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 Fl();let l=Ge(),c=await ps(et()),f=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:f,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:Ge(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=Nt(),o=et(),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),f=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,f),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 f=n[c];if(f===e.token||this.otpMatchesStoredTokenHash(e.email,e.token,f)){r=c;break}}if(!r)throw nr()}else throw nr();else throw nr();if(!n)throw nr();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 f of c){let u=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...u,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 f=await this.repo.findIdentitiesByUserId(n.id);for(let u of f){let d=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...d,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 nr();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 ne("Password recovery requires an email",400);if(e=e.toLowerCase(),!sr(e))throw ne("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=Nt(),s=et(),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 ne("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw ne("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!sr(n))throw ne("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=Nt(),i=et(),o=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw po()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw po();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 Sp();let r=Nt(),s=et(),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=Gl(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=Ge();await this.repo.createSession({id:l,user_id:e.id});let c=zl();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 f=await Jl({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),u=Math.floor(Date.now()/1e3);return Mp({access_token:f,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:u+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=Dp(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw wp(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:(Dl.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:Ge(),payload:o});}};function wS(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function SS(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 Lp(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 sr(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function ES(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 Up(t){return t.revoked===true||t.revoked===1}function _S(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 Gl(...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 Mp(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}function Vl(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function Rn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var hs=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:Rn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:Rn(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=Rn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=Rn(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:Ge(),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:Rn(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:Vl(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=Rn(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:Rn(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:Vl(e.raw_app_meta_data),raw_user_meta_data:Vl(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};function Fp(){return {version:xS(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function Bp(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 qp(){return {keys:[]}}function Wp(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function xS(){return [Ql(JSON.stringify({alg:"HS256",typ:"JWT"})),Ql(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),Ql("metadata")].join(".")}function Ql(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 Yl=t=>t;var vS="00000000-0000-0000-0000-000000000000",CS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Xl=({onError:t}={})=>Yl(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await Kp(e);if(r&&t)return t(r,e)}await n();}),gs=()=>Yl(async(t,e)=>{if(!t.var.userId){let n=await Kp(t);if(n)return Jp(t,n);if(!t.var.userId)return Jp(t,tr())}await e();});async function Kp(t){let e=t.req.header("Authorization");if(!e)return tr();if(!e.startsWith("Bearer "))return tr();let n=e.slice(7);if(!n||/^\s/.test(n))return tr();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await Np(n,r);}catch(c){return c instanceof M?c:tr()}let i=TS(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return xp();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return vp();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function TS(t){let e=t.sub,n=t.role;return e==null||e===""?Ul():typeof e!="string"?Ml():CS.test(e)?e===vS&&n==="service_role"?Ul():null:Ml()}function Jp(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var Zl=new Se().onError((t,e)=>{if(t instanceof M){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 It(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(ho(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",An("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await It(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return ho(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return ho(t,s),t.json(s,200)}throw Pp()}).all("/token",An("POST")).post("/otp",async t=>{let e=await It(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 It(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",An("POST")).post("/verify",async t=>{let e=await It(t),{authService:n}=t.var;AS(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return ho(t,r),t.json(r,200)}).get("/verify",t=>{let e=t.req.query("type");throw e?Hp.has(e)?ne("Verify requires a token or a token hash",400):ne("Invalid email verification type",400):ne("Verify requires a verification type",400)}).post("/recover",async t=>{let e=await It(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await It(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Fp(),200)).all("/health",An("GET")).get("/settings",t=>t.json(Bp(t.var.app.config.auth??{}),200)).all("/settings",An("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(qp(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(Wp(),200))).all("/nonexistent",RS).use(gs()).post("/logout",async t=>{let e=await It(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 It(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",An("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",An("GET"));function An(t){return e=>(e.header("Allow",t),e.body(null,405))}function RS(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 Hp=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function AS(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw ne("Verify requires a verification type",400);if(!Hp.has(e))throw ne("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 ne("Verify requires either a token or a token hash",400)}async function It(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw ds("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 ds("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 ds("Could not parse request body as JSON: unexpected end of JSON input");let s=Kl(n)||"invalid character ' ' looking for beginning of value";throw ds(`Could not parse request body as JSON: ${s}`)}}function ho(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 zp(t){let e=t.connection.dialect,n=new hs(t.connection.kysely,e);return new ms(n,t.config.auth,t._mailer??new us(t.drivers.email))}function Gp(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function Vp(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function nn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var ys=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:nn(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:nn(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:nn(e.metadata??{}),user_metadata:nn(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=nn(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=nn(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=nn(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=nn(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:Vp(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:Gp(e.metadata),user_metadata:Gp(e.user_metadata),path_tokens:Vp(e.path_tokens)}}};var H=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 bs=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?OS(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw H.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw H.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw H.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw H.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){ec(n);let i=await this.repo.findBucketById(e);if(!i)throw H.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 H.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw H.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw H.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 H.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 H.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await kS(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 H.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 H.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){ec(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw H.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){ec(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw H.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 H.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 H.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 H.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 xn(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 vn({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function kS(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 ec(t){if(!t||t.includes("..")||t.startsWith("/"))throw H.invalidKey(t)}function OS(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 $S=/^[\w!#$%&'*.^`|~+-]+$/,PS=/^[ !#-:<-[\]-~]*$/,tc=(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(!$S.test(o))continue;let a=s.substring(i+1).trim();if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),PS.test(a)&&(r[o]=a.indexOf("%")!==-1?qn(a,Or):a,e));}return r};var Qp=(t,e,n)=>{let r=t.req.raw.headers.get("Cookie");return r?tc(r):{}};var Yp=(t,e)=>new Response(t,{headers:{"Content-Type":e}}).formData();var NS=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,IS=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,DS=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,nc=(t,e)=>async(n,r)=>{let s={},i=n.req.header("Content-Type");switch(t){case "json":if(!i||!NS.test(i))break;try{s=await n.req.json();}catch{let a="Malformed JSON in request body";throw new gi(400,{message:a})}break;case "form":{if(!i||!(IS.test(i)||DS.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 Yp(c,i),n.req.bodyCache.formData=a;}catch(c){let f="Malformed FormData request.";throw f+=c instanceof Error?` ${c.message}`:` ${String(c)}`,new gi(400,{message:f})}let l={};a.forEach((c,f)=>{f.endsWith("[]")?(l[f]??=[]).push(c):Array.isArray(l[f])?l[f].push(c):f in l?l[f]=[l[f],c]:l[f]=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=Qp(n);break}let o=await e(s,n);return o instanceof Response?o:(n.req.addValidatedData(t,o),await r())};var jS=Symbol.for("jsonv"),LS=(t,e)=>Object.assign(t,{[jS]:e}),Dt=(t,e,n,r)=>{let s=nc(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 LS(s,{type:"parameters",skip:n?.skipOpenAPI,value:{target:t,schema:e}})};ee();var US=g.object({id:g.string(),name:g.string(),public:g.boolean({default:false}).optional(),file_size_limit:g.number().optional(),allowed_mime_types:g.array(g.string()).optional()}),MS=g.object({public:g.boolean().optional(),file_size_limit:g.number().optional(),allowed_mime_types:g.array(g.string()).optional()}),FS=g.object({prefix:g.string().optional(),limit:g.number().optional(),offset:g.number().optional(),sortBy:g.object({column:g.string(),order:g.string()}).optional(),search:g.string().optional()}),Xp=g.object({bucketId:g.string(),sourceKey:g.string(),destinationKey:g.string()}),BS=g.object({expiresIn:g.number()}),qS=g.object({expiresIn:g.number(),paths:g.array(g.string())}),WS=g.object({prefixes:g.array(g.string())}),JS=new Se().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=rc(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:sc(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=rc(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:sc(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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)}),KS=new Se().use(gs()).post("/bucket",Dt("json",US),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",Dt("json",MS),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",Dt("json",FS),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",Dt("json",Xp),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",Dt("json",Xp),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=dt(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/*",Dt("json",BS),async t=>{let e=t.req.param("bucketId"),n=dt(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",Dt("json",qS),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=dt(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",Dt("json",WS),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=dt(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 d=(await t.req.formData()).get("file");if(!d)throw new H(400,"InvalidRequest","Missing file in multipart upload");let p=new Uint8Array(await d.arrayBuffer());a=p,l=d.type||"application/octet-stream",c=p.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 f=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o,owner:t.get("userId")??null});return t.json({Key:`${e}/${f.name}`,Id:f.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(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=dt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=rc(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:sc(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=dt(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),ic=new Se().onError((t,e)=>t instanceof H?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",JS).route("/",KS);function dt(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 rc(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 sc(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}Qr();var oc=`-- supabase/storage core schema (Postgres)
95
95
  -- Source: supabase/storage migrations (consolidated)
96
96
 
97
97
  CREATE SCHEMA IF NOT EXISTS storage;
@@ -126,11 +126,11 @@ CREATE TABLE IF NOT EXISTS storage.objects (
126
126
  );
127
127
 
128
128
  CREATE INDEX IF NOT EXISTS storage_objects_name_pattern_search ON storage.objects (name text_pattern_ops);
129
- `;function oc(t=true){return t?Vr(ic):ic}var go=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function Zp(t){if(!t._storageAdapter)throw H.storageNotConfigured();let e=t.connection.dialect,n=new ys(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"secret",s=t._transformationAdapter??new go;return new bs(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?qS(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function qS(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 Ve=Symbol("RENDERER"),rn=Symbol("ERROR_HANDLER"),V=Symbol("STASH"),yo=Symbol("INTERNAL"),ac=Symbol("MEMO"),ir=Symbol("PERMALINK");var lc=t=>(t[yo]=true,t);var cc=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:lc(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:lc(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[rn]=i=>{throw t.pop(),i},s},bo=t=>{let e=[t],n=cc(e);return n.values=e,n.Provider=n,jt.push(n),n};var jt=[],ws=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new uc("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>K(i,i.callbacks)):(e.pop(),K(s))});return n.values=e,n.Provider=n,n[Ve]=cc(e),jt.push(n),n},Ee=t=>t.values.at(-1);var or={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Ss={},ar="data-precedence";var xs={};xr(xs,{button:()=>QS,form:()=>GS,input:()=>VS,link:()=>HS,meta:()=>zS,script:()=>JS,style:()=>KS,title:()=>WS});var An=t=>Array.isArray(t)?t:[t];var em=new WeakMap,tm=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=em.get(i)||{};em.set(i,o);let a=o[t]||=[],l=false,c=or[t];if(c.length>0){e:for(let[,f]of a)for(let u of c)if((f?.[u]??null)===n?.[u]){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 f;if(r===void 0)f=a.map(([u])=>u);else {let u=[];f=a.map(([d,,p])=>{let y=u.indexOf(p);return y===-1&&(u.push(p),y=u.length-1),[d,y]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d);}f.forEach(u=>{s[0]=s[0].replaceAll(u,"");}),s[0]=s[0].replace(/(?=<\/head>)/,f.join(""));}},Es=(t,e,n)=>K(new Be(t,n,An(e??[])).toString()),_s=(t,e,n,r)=>{if("itemProp"in n)return Es(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[ar]=s);let a=new Be(t,o,An(e||[])).toString();return a instanceof Promise?a.then(l=>K(a,[...l.callbacks||[],tm(t,l,o,s)])):K(a,[tm(t,a,o,s)])},WS=({children:t,...e})=>{let n=wo();if(n){let r=Ee(n);if(r==="svg"||r==="head")return new Be("title",e,An(t??[]))}return _s("title",t,e,false)},JS=({children:t,...e})=>{let n=wo();return ["src","async"].some(r=>!e[r])||n&&Ee(n)==="head"?Es("script",t,e):_s("script",t,e,false)},KS=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,_s("style",t,e,true)):Es("style",t,e),HS=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Es("link",t,e):_s("link",t,e,"precedence"in e),zS=({children:t,...e})=>{let n=wo();return n&&Ee(n)==="head"?Es("meta",t,e):_s("meta",t,e,false)},nm=(t,{children:e,...n})=>new Be(t,n,An(e??[])),GS=t=>(typeof t.action=="function"&&(t.action=ir in t.action?t.action[ir]:void 0),nm("form",t)),rm=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=ir in e.formAction?e.formAction[ir]:void 0),nm(t,e)),VS=t=>rm("input",t),QS=t=>rm("button",t);var XS=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),lr=t=>XS.get(t)||t,vs=(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 Cs=void 0,wo=()=>Cs,YS=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,ZS=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],eE=["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"],dc=(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 Be?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):dc(s,e);}}},Be=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?wa(K(t[0],t.callbacks)).toString():t[0]:Si(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Cs&&Ee(Cs)==="svg"?i=>YS(lr(i)):i=>lr(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";vs(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"&&eE.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=[K(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(ZS.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",dc(r,t),t[0]+=`</${e}>`;}},fc=class extends Be{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(jt.length===0)t.unshift("",r);else {let s=jt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof Be&&(i.localContexts=s),i)));}else r instanceof Be?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):_t(r,t);}},uc=class extends Be{toStringToBuffer(t){dc(this.children,t);}},sm=false,Rs=(t,e,n)=>{if(!sm){for(let r in Ss)xs[r][Ve]=Ss[r];sm=true;}return typeof t=="function"?new fc(t,e,n):xs[t]?new fc(xs[t],e,n):t==="svg"||t==="head"?(Cs||=ws(""),new Be(t,e,[new fc(Cs,{value:t},n)])):new Be(t,e,n)};var pt=({children:t})=>new uc("",{children:t},Array.isArray(t)?t:t?[t]:[]);var xo={};xr(xo,{button:()=>$m,clearCache:()=>dE,composeRef:()=>_o,form:()=>km,input:()=>Om,link:()=>Cm,meta:()=>Rm,script:()=>xm,style:()=>vm,title:()=>_m});var ks="_hp",tE={Change:"Input",DoubleClick:"DblClick"},nE={svg:"2000/svg",math:"1998/Math/MathML"},mt=[],hc=new WeakMap,cr=void 0,fm=()=>cr,Lt=t=>"t"in t,mc={onClick:["click",false]},im=t=>{if(!t.startsWith("on"))return;if(mc[t])return mc[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return mc[t]=[(tE[n]||n).toLowerCase(),!!r]}},om=(t,e)=>cr&&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,rE=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=lr(r);let i=im(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),hc.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&vs(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=om(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=lr(r);let i=im(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?hc.get(t)?.():t.removeAttribute(om(t,r));}}},sE=(t,e)=>{e[V][0]=0,mt.push([t,e]);let n=e.tag[Ve]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{mt.pop();}},dm=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[V][1][yc]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Lt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(dm(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);});},iE=t=>{for(;t&&(t.tag===ks||!t.e);)t=t.tag===ks||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},pm=t=>{Lt(t)||(t[V]?.[1][yc]?.forEach(e=>e[2]?.()),hc.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(pm)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(Ts.delete(t),So.delete(t),delete t[V][3],t.a=true);},mm=(t,e,n)=>{t.c=e,hm(t,e,n);},am=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},lm=Symbol(),hm=(t,e,n)=>{let r=[],s=[],i=[];dm(t,e,r,s,i),s.forEach(pm);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=am(o,iE(t.nN));c!==void 0?(l=o[c],a=c):a=am(o,r.find(f=>f.tag!==ks&&f.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,f=r.length;c<f;c++,a++){let u=r[c],d;if(u.s&&u.e)d=u.e,u.s=false;else {let p=n||!u.e;Lt(u)?(u.e&&u.d&&(u.e.textContent=u.t),u.d=false,d=u.e||=document.createTextNode(u.t)):(d=u.e||=u.n?document.createElementNS(u.n,u.tag):document.createElement(u.tag),rE(d,u.props,u.pP),hm(u,d,p));}u.tag===ks?a--:n?d.parentNode||e.appendChild(d):o[a]!==d&&o[a-1]!==d&&(o[a+1]===d?e.appendChild(o[a]):e.insertBefore(d,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],f=[];i.forEach(([,u,,d,p])=>{u&&c.push(u),d&&f.push(d),p?.();}),c.forEach(u=>u()),f.length&&requestAnimationFrame(()=>{f.forEach(u=>u());});}},oE=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),So=new WeakMap,gc=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?sE(t,e):An(e.props.children),n[0]?.tag===""&&n[0][rn]&&(s=n[0][rn],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=aE(n[l]);if(c){typeof c.tag=="function"&&!c.tag[yo]&&(jt.length>0&&(c[V][2]=jt.map(u=>[u,u.values.at(-1)])),t[5]?.length&&(c[V][3]=t[5].at(-1)));let f;if(i&&i.length){let u=i.findIndex(Lt(c)?d=>Lt(d):c.key!==void 0?d=>d.key===c.key&&d.tag===c.tag:d=>d.tag===c.tag);u!==-1&&(f=i[u],i.splice(u,1));}if(f)if(Lt(c))f.t!==c.t&&(f.t=c.t,f.d=!0),c=f;else {let u=f.pP=f.props;if(f.props=c.props,f.f||=c.f||e.f,typeof c.tag=="function"){let d=f[V][2];f[V][2]=c[V][2]||[],f[V][3]=c[V][3],!f.f&&((f.o||f)===c.o||f.tag[ac]?.(u,f.props))&&oE(d,f[V][2])&&(f.s=!0);}c=f;}else if(!Lt(c)&&cr){let u=Ee(cr);u&&(c.n=u);}if(!Lt(c)&&!c.s&&(gc(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let u=a;u&&!Lt(u);u=u.vC?.at(-1))u.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===lm){if(s)return;throw i}let[o,a,l]=e[V]?.[3]||[];if(a){let c=()=>As([0,false,t[2]],l),f=So.get(l)||[];f.push(c),So.set(l,f);let u=a(i,()=>{let d=So.get(l);if(d){let p=d.indexOf(c);if(p!==-1)return d.splice(p,1),c()}});if(u){if(t[0]===1)t[1]=true;else if(gc(t,l,[u]),(a.length===1||t!==o)&&l.c){mm(l,l.c,false);return}throw lm}}throw i}finally{s&&t[5].pop();}},aE=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[V]=[0,[]];else {let e=nE[t.tag];e&&(cr||=bo(""),t.props.children=[{tag:cr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var cm=(t,e)=>{e[V][2]?.forEach(([n,r])=>{n.values.push(r);});try{gc(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[V][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&mm(e,e.c,false);},Ts=new WeakMap,um=[],As=async(t,e)=>{t[5]||=[];let n=Ts.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(Ts.set(e,[r,()=>{t[2]?t[2](t,e,i=>{cm(i,e);}).then(()=>r(e)):(cm(t,e),r(e));}]),um.length)um.at(-1).add(e);else {await Promise.resolve();let i=Ts.get(e);i&&(Ts.delete(e),i[1]());}return s};var gm=(t,e,n)=>({tag:ks,props:{children:t},key:n,e,p:1});var lE=0,yc=1,cE=2,uE=3;var bc=new WeakMap,bm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var fE=void 0;var ym=[];var Eo=t=>{let e=()=>typeof t=="function"?t():t,n=mt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[V][1][lE]||=[],i=r[V][0]++;return s[i]||=[e(),o=>{let a=fE,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,ym.length){let[c,f]=ym.at(-1);Promise.all([c===3?r:As([c,false,a],r),f]).then(([u])=>{if(!u||!(c===2||c===3))return;let d=u.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===u.vC&&As([c===3?1:0,false,a],u);});});});}else As([0,false,a],r);}]};var ur=(t,e)=>{let n=mt.at(-1);if(!n)return t;let[,r]=n,s=r[V][1][cE]||=[],i=r[V][0]++,o=s[i];return bm(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var wc=t=>{let e=bc.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>bc.set(t,[n]),n=>bc.set(t,[void 0,n])),t},Sc=(t,e)=>{let n=mt.at(-1);if(!n)return t();let[,r]=n,s=r[V][1][uE]||=[],i=r[V][0]++,o=s[i];return bm(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Sm=bo({pending:false,data:null,method:null,action:null}),wm=new Set,Em=t=>{wm.add(t),t.finally(()=>wm.delete(t));};var dE=()=>{Ec=Object.create(null),_c=Object.create(null);},_o=(t,e)=>Sc(()=>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]),Ec=Object.create(null),_c=Object.create(null),Os=(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,...f}=e,u=null,d=false,p=or[t],y;if(p.length>0){let w=i.querySelectorAll(t);e:for(let _ of w)for(let S of or[t])if(_.getAttribute(S)===e[S]){u=_;break e}if(!u){let _=p.reduce((S,E)=>e[E]===void 0?S:`${S}-${E}-${e[E]}`,t);d=!_c[_],u=_c[_]||=(()=>{let S=document.createElement(t);for(let E of p)e[E]!==void 0&&S.setAttribute(E,e[E]),e.rel&&S.setAttribute("rel",e.rel);return S})();}}else y=i.querySelectorAll(t);l=r?l??"":void 0,r&&(f[ar]=l);let h=ur(w=>{if(p.length>0){let _=false;for(let S of i.querySelectorAll(t)){if(_&&S.getAttribute(ar)!==l){i.insertBefore(w,S);return}S.getAttribute(ar)===l&&(_=true);}i.appendChild(w);}else if(y){let _=false;for(let S of y)if(S===w){_=true;break}_||i.insertBefore(w,i.contains(y[0])?y[0]:i.querySelector(t)),y=void 0;}},[l]),b=_o(e.ref,w=>{let _=p[0];if(n===2&&(w.innerHTML=""),(d||y)&&h(w),!a&&!o)return;let S=Ec[w.getAttribute(_)]||=new Promise((E,C)=>{w.addEventListener("load",E),w.addEventListener("error",C);});o&&(S=S.then(o)),a&&(S=S.catch(a)),S.catch(()=>{});});if(s&&c==="render"){let w=or[t][0];if(e[w]){let _=e[w],S=Ec[_]||=new Promise((E,C)=>{h(u),u.addEventListener("load",E),u.addEventListener("error",C);});wc(S);}}let m={tag:t,type:t,props:{...f,ref:b},ref:b};return m.p=n,u&&(m.e=u),gm(m,i)},_m=t=>{let e=fm();return (e&&Ee(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Os("title",t,void 0,false,false)},xm=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Os("script",t,1,false,true),vm=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,Os("style",t,2,true,true)),Cm=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}:Os("link",t,1,"precedence"in t,true),Rm=t=>Os("meta",t,void 0,false,false),Tm=Symbol(),km=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Eo([null,false]),i=ur(async c=>{let f=c.isTrusted?e:c.detail[Tm];if(typeof f!="function")return;c.preventDefault();let u=new FormData(c.target);s([u,true]);let d=f(u);d instanceof Promise&&(Em(d),await d),s([null,true]);},[]),o=_o(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Sm,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}},Am=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=ur(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Tm]:e}}));},[]);n.ref=_o(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Om=t=>Am("input",t),$m=t=>Am("button",t);Object.assign(Ss,{title:_m,script:xm,style:vm,link:Cm,meta:Rm,form:km,input:Om,button:$m});ws(null);new TextEncoder;var On=":-hono-global",gE=new RegExp(`^${On}{(.*)}$`),Ro="hono-css",Ut=Symbol(),ge=Symbol(),Ie=Symbol(),ht=Symbol(),To=Symbol(),jm=Symbol();var Lm=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},yE=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),bE=new RegExp(["("+yE+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),wE=t=>t.replace(bE,(e,n,r,s,i)=>n||r||s||i||""),Um=(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,f=l.length;c<f;c++){let u=l[c];if(!(typeof u=="boolean"||u===null||u===void 0))if(typeof u=="string")/([\\"'\/])/.test(u)?i+=u.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=u;else if(typeof u=="number")i+=u;else if(u[jm])i+=u[jm];else if(u[ge].startsWith("@keyframes "))n.push(u),i+=` ${u[ge].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(u),u=`.${u[ge]}`;else {n.push(...u[ht]),r.push(...u[To]),u=u[Ie];let d=u.length;if(d>0){let p=u[d-1];p!==";"&&p!=="}"&&(u+=";");}}i+=`${u||""}`;}}}}return [s,wE(i),n,r]},fr=(t,e)=>{let[n,r,s,i]=Um(t,e),o=gE.exec(r);o&&(r=o[1]);let a=(o?On:"")+Lm(n+r),l=(o?s.map(c=>c[ge]):[a,...i]).join(" ");return {[Ut]:a,[ge]:l,[Ie]:r,[ht]:s,[To]:i}},ko=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ut]:"",[ge]:"",[Ie]:"",[ht]:[],[To]:[r]});}return t},Ao=(t,...e)=>{let[n,r]=Um(t,e);return {[Ut]:"",[ge]:`@keyframes ${Lm(n+r)}`,[Ie]:r,[ht]:[],[To]:[]}},SE=0,Oo=((t,e)=>{t||(t=[`/* h-v-t ${SE++} */`]);let n=Array.isArray(t)?fr(t,e):t,r=n[ge],s=fr(["view-transition-name:",""],[r]);return n[ge]=On+n[ge],n[Ie]=n[Ie].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[ge]=s[Ut]=r,s[ht]=[...n[ht],n],s});var _E=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},Cc=({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(On)?_E(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(f=>{l.insertRule(f,l.cssRules.length);}));};return [{toString(){let o=this[Ut];return r(o,this[Ie]),this[ht].forEach(({[ge]:a,[Ie]:l})=>{r(a,l);}),this[ge]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[Ie])}})]};var vE=({id:t})=>{let[e,n]=Cc({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:m,context:w})=>{let[_,S]=r.get(w),E=Object.keys(_);if(!E.length)return;let C="";if(E.forEach(v=>{S[v]=true,C+=v.startsWith(On)?_[v]:`${v[0]==="@"?"":"."}${v}{${_[v]}}`;}),r.set(w,[{},S]),m&&i.test(m[0])){m[0]=m[0].replace(i,(v,k,z)=>`${k}${C}${z}`);return}let x=s.get(w),R=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(C)}</script>`;if(m){m[0]=`${R}${m[0]}`;return}return Promise.resolve(R)},y=({context:m})=>{r.has(m)||r.set(m,[{},{}]);let[w,_]=r.get(m),S=true;if(_[d[Ut]]||(S=false,w[d[Ut]]=d[Ie]),d[ht].forEach(({[ge]:E,[Ie]:C})=>{_[E]||(S=false,w[E]=C);}),!S)return Promise.resolve(K("",[p]))},h=new String(d[ge]);Object.assign(h,d),h.isEscaped=true,h.callbacks=[y];let b=Promise.resolve(h);return Object.assign(b,d),b.toString=e.toString,b},a=(d,...p)=>o(fr(d,p)),l=(...d)=>(d=ko(d),a(Array(d.length).fill(""),...d)),c=Ao,f=((d,...p)=>o(Oo(d,p))),u=({children:d,nonce:p}={})=>K(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[Ie]:""}</style>`,[({context:y})=>{s.set(y,p);}]);return u[Ve]=n,{css:a,cx:l,keyframes:c,viewTransition:f,Style:u}},Ps=vE({id:Ro}),Mm=Ps.Style;function ye(t,e,n){let r;if(!e||!("children"in e))r=Rs(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Rs(t,e,s):Rs(t,e,[s]);}return r.key=n,r}var Rc=new Se().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>ou(Fm())).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(ye(pt,{children:ye("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[ye("head",{children:[ye("meta",{charset:"UTF-8"}),ye("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),ye("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),ye("title",{children:"Supalite"}),ye(pt,{children:[ye("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>ye("link",{rel:"stylesheet",href:n+s},i))]}),ye(Mm,{})]}),ye("body",{children:ye("div",{id:"root"})})]})}))});async function RE(t){return Rc.fetch(t)}var TE={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Bm=["storage","cloud"],kc=Object.fromEntries(Bm.map(t=>[t,kE(t)]));function kE(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[TE[t]]==="1":false}function dr(t){return kc[t]}function AE(t,e){kc[t]=e;}function qm(){return Bm.filter(t=>kc[t])}function OE(){let t=qm();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 Tc=false;function Wm(t=e=>console.warn(e)){if(Tc)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){Tc=true;return}let e=OE();e&&t(e),Tc=true;}function Jm(t,e={}){let n=e.middlewares??[async(r,s)=>{await s();}];return new Se().use(async(r,s)=>{r.set("app",t),t.config.auth?.enabled&&r.set("authService",zp(t)),t.config.storage?.enabled&&t._storageAdapter&&dr("storage")&&r.set("storageService",Zp(t)),await s();}).use(...n).use(Xl()).route("/auth/v1",Yl).route("/rest/v1",cp({forceRollback:e.forceRollback})).use("/storage/v1/*",async(r,s)=>{if(!dr("storage"))return r.notFound();await s();}).route("/storage/v1",sc).route("/_system",ff).use(async(r,s)=>{if(!e.disableStudio&&t.config.studio?.enabled)return Rc.fetch(r.req.raw);if(!e.disableFallback)return r.notFound();await s();})}ee();var $E=t=>{let e=t.toJSON();return Jt(e)},Ac=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
129
+ `;function ac(t=true){return t?Vr(oc):oc}var go=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function Zp(t){if(!t._storageAdapter)throw H.storageNotConfigured();let e=t.connection.dialect,n=new ys(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"secret",s=t._transformationAdapter??new go;return new bs(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?zS(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function zS(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 Ve=Symbol("RENDERER"),rn=Symbol("ERROR_HANDLER"),V=Symbol("STASH"),yo=Symbol("INTERNAL"),lc=Symbol("MEMO"),ir=Symbol("PERMALINK");var cc=t=>(t[yo]=true,t);var uc=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:cc(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:cc(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[rn]=i=>{throw t.pop(),i},s},bo=t=>{let e=[t],n=uc(e);return n.values=e,n.Provider=n,jt.push(n),n};var jt=[],ws=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new fc("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>K(i,i.callbacks)):(e.pop(),K(s))});return n.values=e,n.Provider=n,n[Ve]=uc(e),jt.push(n),n},Ee=t=>t.values.at(-1);var or={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Ss={},ar="data-precedence";var xs={};xr(xs,{button:()=>tE,form:()=>ZS,input:()=>eE,link:()=>YS,meta:()=>XS,script:()=>VS,style:()=>QS,title:()=>GS});var kn=t=>Array.isArray(t)?t:[t];var em=new WeakMap,tm=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=em.get(i)||{};em.set(i,o);let a=o[t]||=[],l=false,c=or[t];if(c.length>0){e:for(let[,f]of a)for(let u of c)if((f?.[u]??null)===n?.[u]){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 f;if(r===void 0)f=a.map(([u])=>u);else {let u=[];f=a.map(([d,,p])=>{let y=u.indexOf(p);return y===-1&&(u.push(p),y=u.length-1),[d,y]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d);}f.forEach(u=>{s[0]=s[0].replaceAll(u,"");}),s[0]=s[0].replace(/(?=<\/head>)/,f.join(""));}},Es=(t,e,n)=>K(new Be(t,n,kn(e??[])).toString()),_s=(t,e,n,r)=>{if("itemProp"in n)return Es(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[ar]=s);let a=new Be(t,o,kn(e||[])).toString();return a instanceof Promise?a.then(l=>K(a,[...l.callbacks||[],tm(t,l,o,s)])):K(a,[tm(t,a,o,s)])},GS=({children:t,...e})=>{let n=wo();if(n){let r=Ee(n);if(r==="svg"||r==="head")return new Be("title",e,kn(t??[]))}return _s("title",t,e,false)},VS=({children:t,...e})=>{let n=wo();return ["src","async"].some(r=>!e[r])||n&&Ee(n)==="head"?Es("script",t,e):_s("script",t,e,false)},QS=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,_s("style",t,e,true)):Es("style",t,e),YS=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Es("link",t,e):_s("link",t,e,"precedence"in e),XS=({children:t,...e})=>{let n=wo();return n&&Ee(n)==="head"?Es("meta",t,e):_s("meta",t,e,false)},nm=(t,{children:e,...n})=>new Be(t,n,kn(e??[])),ZS=t=>(typeof t.action=="function"&&(t.action=ir in t.action?t.action[ir]:void 0),nm("form",t)),rm=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=ir in e.formAction?e.formAction[ir]:void 0),nm(t,e)),eE=t=>rm("input",t),tE=t=>rm("button",t);var nE=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),lr=t=>nE.get(t)||t,vs=(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 Cs=void 0,wo=()=>Cs,rE=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,sE=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],iE=["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"],pc=(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 Be?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):pc(s,e);}}},Be=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?wa(K(t[0],t.callbacks)).toString():t[0]:Si(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Cs&&Ee(Cs)==="svg"?i=>rE(lr(i)):i=>lr(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";vs(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"&&iE.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=[K(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(sE.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",pc(r,t),t[0]+=`</${e}>`;}},dc=class extends Be{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(jt.length===0)t.unshift("",r);else {let s=jt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof Be&&(i.localContexts=s),i)));}else r instanceof Be?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):_t(r,t);}},fc=class extends Be{toStringToBuffer(t){pc(this.children,t);}},sm=false,Ts=(t,e,n)=>{if(!sm){for(let r in Ss)xs[r][Ve]=Ss[r];sm=true;}return typeof t=="function"?new dc(t,e,n):xs[t]?new dc(xs[t],e,n):t==="svg"||t==="head"?(Cs||=ws(""),new Be(t,e,[new dc(Cs,{value:t},n)])):new Be(t,e,n)};var pt=({children:t})=>new fc("",{children:t},Array.isArray(t)?t:t?[t]:[]);var xo={};xr(xo,{button:()=>$m,clearCache:()=>yE,composeRef:()=>_o,form:()=>Am,input:()=>Om,link:()=>Cm,meta:()=>Tm,script:()=>xm,style:()=>vm,title:()=>_m});var As="_hp",oE={Change:"Input",DoubleClick:"DblClick"},aE={svg:"2000/svg",math:"1998/Math/MathML"},mt=[],gc=new WeakMap,cr=void 0,fm=()=>cr,Lt=t=>"t"in t,hc={onClick:["click",false]},im=t=>{if(!t.startsWith("on"))return;if(hc[t])return hc[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return hc[t]=[(oE[n]||n).toLowerCase(),!!r]}},om=(t,e)=>cr&&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,lE=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=lr(r);let i=im(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),gc.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&vs(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=om(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=lr(r);let i=im(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?gc.get(t)?.():t.removeAttribute(om(t,r));}}},cE=(t,e)=>{e[V][0]=0,mt.push([t,e]);let n=e.tag[Ve]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{mt.pop();}},dm=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[V][1][bc]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Lt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(dm(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);});},uE=t=>{for(;t&&(t.tag===As||!t.e);)t=t.tag===As||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},pm=t=>{Lt(t)||(t[V]?.[1][bc]?.forEach(e=>e[2]?.()),gc.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(pm)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(Rs.delete(t),So.delete(t),delete t[V][3],t.a=true);},mm=(t,e,n)=>{t.c=e,hm(t,e,n);},am=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},lm=Symbol(),hm=(t,e,n)=>{let r=[],s=[],i=[];dm(t,e,r,s,i),s.forEach(pm);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=am(o,uE(t.nN));c!==void 0?(l=o[c],a=c):a=am(o,r.find(f=>f.tag!==As&&f.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,f=r.length;c<f;c++,a++){let u=r[c],d;if(u.s&&u.e)d=u.e,u.s=false;else {let p=n||!u.e;Lt(u)?(u.e&&u.d&&(u.e.textContent=u.t),u.d=false,d=u.e||=document.createTextNode(u.t)):(d=u.e||=u.n?document.createElementNS(u.n,u.tag):document.createElement(u.tag),lE(d,u.props,u.pP),hm(u,d,p));}u.tag===As?a--:n?d.parentNode||e.appendChild(d):o[a]!==d&&o[a-1]!==d&&(o[a+1]===d?e.appendChild(o[a]):e.insertBefore(d,l||o[a]||null));}if(t.pP&&(t.pP=void 0),i.length){let c=[],f=[];i.forEach(([,u,,d,p])=>{u&&c.push(u),d&&f.push(d),p?.();}),c.forEach(u=>u()),f.length&&requestAnimationFrame(()=>{f.forEach(u=>u());});}},fE=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),So=new WeakMap,yc=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?cE(t,e):kn(e.props.children),n[0]?.tag===""&&n[0][rn]&&(s=n[0][rn],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=dE(n[l]);if(c){typeof c.tag=="function"&&!c.tag[yo]&&(jt.length>0&&(c[V][2]=jt.map(u=>[u,u.values.at(-1)])),t[5]?.length&&(c[V][3]=t[5].at(-1)));let f;if(i&&i.length){let u=i.findIndex(Lt(c)?d=>Lt(d):c.key!==void 0?d=>d.key===c.key&&d.tag===c.tag:d=>d.tag===c.tag);u!==-1&&(f=i[u],i.splice(u,1));}if(f)if(Lt(c))f.t!==c.t&&(f.t=c.t,f.d=!0),c=f;else {let u=f.pP=f.props;if(f.props=c.props,f.f||=c.f||e.f,typeof c.tag=="function"){let d=f[V][2];f[V][2]=c[V][2]||[],f[V][3]=c[V][3],!f.f&&((f.o||f)===c.o||f.tag[lc]?.(u,f.props))&&fE(d,f[V][2])&&(f.s=!0);}c=f;}else if(!Lt(c)&&cr){let u=Ee(cr);u&&(c.n=u);}if(!Lt(c)&&!c.s&&(yc(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let u=a;u&&!Lt(u);u=u.vC?.at(-1))u.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===lm){if(s)return;throw i}let[o,a,l]=e[V]?.[3]||[];if(a){let c=()=>ks([0,false,t[2]],l),f=So.get(l)||[];f.push(c),So.set(l,f);let u=a(i,()=>{let d=So.get(l);if(d){let p=d.indexOf(c);if(p!==-1)return d.splice(p,1),c()}});if(u){if(t[0]===1)t[1]=true;else if(yc(t,l,[u]),(a.length===1||t!==o)&&l.c){mm(l,l.c,false);return}throw lm}}throw i}finally{s&&t[5].pop();}},dE=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[V]=[0,[]];else {let e=aE[t.tag];e&&(cr||=bo(""),t.props.children=[{tag:cr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var cm=(t,e)=>{e[V][2]?.forEach(([n,r])=>{n.values.push(r);});try{yc(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[V][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&mm(e,e.c,false);},Rs=new WeakMap,um=[],ks=async(t,e)=>{t[5]||=[];let n=Rs.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(Rs.set(e,[r,()=>{t[2]?t[2](t,e,i=>{cm(i,e);}).then(()=>r(e)):(cm(t,e),r(e));}]),um.length)um.at(-1).add(e);else {await Promise.resolve();let i=Rs.get(e);i&&(Rs.delete(e),i[1]());}return s};var gm=(t,e,n)=>({tag:As,props:{children:t},key:n,e,p:1});var pE=0,bc=1,mE=2,hE=3;var wc=new WeakMap,bm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var gE=void 0;var ym=[];var Eo=t=>{let e=()=>typeof t=="function"?t():t,n=mt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[V][1][pE]||=[],i=r[V][0]++;return s[i]||=[e(),o=>{let a=gE,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,ym.length){let[c,f]=ym.at(-1);Promise.all([c===3?r:ks([c,false,a],r),f]).then(([u])=>{if(!u||!(c===2||c===3))return;let d=u.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===u.vC&&ks([c===3?1:0,false,a],u);});});});}else ks([0,false,a],r);}]};var ur=(t,e)=>{let n=mt.at(-1);if(!n)return t;let[,r]=n,s=r[V][1][mE]||=[],i=r[V][0]++,o=s[i];return bm(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var Sc=t=>{let e=wc.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>wc.set(t,[n]),n=>wc.set(t,[void 0,n])),t},Ec=(t,e)=>{let n=mt.at(-1);if(!n)return t();let[,r]=n,s=r[V][1][hE]||=[],i=r[V][0]++,o=s[i];return bm(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Sm=bo({pending:false,data:null,method:null,action:null}),wm=new Set,Em=t=>{wm.add(t),t.finally(()=>wm.delete(t));};var yE=()=>{_c=Object.create(null),xc=Object.create(null);},_o=(t,e)=>Ec(()=>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]),_c=Object.create(null),xc=Object.create(null),Os=(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,...f}=e,u=null,d=false,p=or[t],y;if(p.length>0){let w=i.querySelectorAll(t);e:for(let _ of w)for(let S of or[t])if(_.getAttribute(S)===e[S]){u=_;break e}if(!u){let _=p.reduce((S,E)=>e[E]===void 0?S:`${S}-${E}-${e[E]}`,t);d=!xc[_],u=xc[_]||=(()=>{let S=document.createElement(t);for(let E of p)e[E]!==void 0&&S.setAttribute(E,e[E]),e.rel&&S.setAttribute("rel",e.rel);return S})();}}else y=i.querySelectorAll(t);l=r?l??"":void 0,r&&(f[ar]=l);let h=ur(w=>{if(p.length>0){let _=false;for(let S of i.querySelectorAll(t)){if(_&&S.getAttribute(ar)!==l){i.insertBefore(w,S);return}S.getAttribute(ar)===l&&(_=true);}i.appendChild(w);}else if(y){let _=false;for(let S of y)if(S===w){_=true;break}_||i.insertBefore(w,i.contains(y[0])?y[0]:i.querySelector(t)),y=void 0;}},[l]),b=_o(e.ref,w=>{let _=p[0];if(n===2&&(w.innerHTML=""),(d||y)&&h(w),!a&&!o)return;let S=_c[w.getAttribute(_)]||=new Promise((E,C)=>{w.addEventListener("load",E),w.addEventListener("error",C);});o&&(S=S.then(o)),a&&(S=S.catch(a)),S.catch(()=>{});});if(s&&c==="render"){let w=or[t][0];if(e[w]){let _=e[w],S=_c[_]||=new Promise((E,C)=>{h(u),u.addEventListener("load",E),u.addEventListener("error",C);});Sc(S);}}let m={tag:t,type:t,props:{...f,ref:b},ref:b};return m.p=n,u&&(m.e=u),gm(m,i)},_m=t=>{let e=fm();return (e&&Ee(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Os("title",t,void 0,false,false)},xm=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Os("script",t,1,false,true),vm=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,Os("style",t,2,true,true)),Cm=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}:Os("link",t,1,"precedence"in t,true),Tm=t=>Os("meta",t,void 0,false,false),Rm=Symbol(),Am=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Eo([null,false]),i=ur(async c=>{let f=c.isTrusted?e:c.detail[Rm];if(typeof f!="function")return;c.preventDefault();let u=new FormData(c.target);s([u,true]);let d=f(u);d instanceof Promise&&(Em(d),await d),s([null,true]);},[]),o=_o(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Sm,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}},km=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=ur(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Rm]:e}}));},[]);n.ref=_o(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Om=t=>km("input",t),$m=t=>km("button",t);Object.assign(Ss,{title:_m,script:xm,style:vm,link:Cm,meta:Tm,form:Am,input:Om,button:$m});ws(null);new TextEncoder;var On=":-hono-global",EE=new RegExp(`^${On}{(.*)}$`),To="hono-css",Ut=Symbol(),ge=Symbol(),Ie=Symbol(),ht=Symbol(),Ro=Symbol(),jm=Symbol();var Lm=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},_E=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),xE=new RegExp(["("+_E+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),vE=t=>t.replace(xE,(e,n,r,s,i)=>n||r||s||i||""),Um=(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,f=l.length;c<f;c++){let u=l[c];if(!(typeof u=="boolean"||u===null||u===void 0))if(typeof u=="string")/([\\"'\/])/.test(u)?i+=u.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=u;else if(typeof u=="number")i+=u;else if(u[jm])i+=u[jm];else if(u[ge].startsWith("@keyframes "))n.push(u),i+=` ${u[ge].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(u),u=`.${u[ge]}`;else {n.push(...u[ht]),r.push(...u[Ro]),u=u[Ie];let d=u.length;if(d>0){let p=u[d-1];p!==";"&&p!=="}"&&(u+=";");}}i+=`${u||""}`;}}}}return [s,vE(i),n,r]},fr=(t,e)=>{let[n,r,s,i]=Um(t,e),o=EE.exec(r);o&&(r=o[1]);let a=(o?On:"")+Lm(n+r),l=(o?s.map(c=>c[ge]):[a,...i]).join(" ");return {[Ut]:a,[ge]:l,[Ie]:r,[ht]:s,[Ro]:i}},Ao=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ut]:"",[ge]:"",[Ie]:"",[ht]:[],[Ro]:[r]});}return t},ko=(t,...e)=>{let[n,r]=Um(t,e);return {[Ut]:"",[ge]:`@keyframes ${Lm(n+r)}`,[Ie]:r,[ht]:[],[Ro]:[]}},CE=0,Oo=((t,e)=>{t||(t=[`/* h-v-t ${CE++} */`]);let n=Array.isArray(t)?fr(t,e):t,r=n[ge],s=fr(["view-transition-name:",""],[r]);return n[ge]=On+n[ge],n[Ie]=n[Ie].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[ge]=s[Ut]=r,s[ht]=[...n[ht],n],s});var RE=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},Tc=({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(On)?RE(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(f=>{l.insertRule(f,l.cssRules.length);}));};return [{toString(){let o=this[Ut];return r(o,this[Ie]),this[ht].forEach(({[ge]:a,[Ie]:l})=>{r(a,l);}),this[ge]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[Ie])}})]};var kE=({id:t})=>{let[e,n]=Tc({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:m,context:w})=>{let[_,S]=r.get(w),E=Object.keys(_);if(!E.length)return;let C="";if(E.forEach(v=>{S[v]=true,C+=v.startsWith(On)?_[v]:`${v[0]==="@"?"":"."}${v}{${_[v]}}`;}),r.set(w,[{},S]),m&&i.test(m[0])){m[0]=m[0].replace(i,(v,A,z)=>`${A}${C}${z}`);return}let x=s.get(w),T=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(C)}</script>`;if(m){m[0]=`${T}${m[0]}`;return}return Promise.resolve(T)},y=({context:m})=>{r.has(m)||r.set(m,[{},{}]);let[w,_]=r.get(m),S=true;if(_[d[Ut]]||(S=false,w[d[Ut]]=d[Ie]),d[ht].forEach(({[ge]:E,[Ie]:C})=>{_[E]||(S=false,w[E]=C);}),!S)return Promise.resolve(K("",[p]))},h=new String(d[ge]);Object.assign(h,d),h.isEscaped=true,h.callbacks=[y];let b=Promise.resolve(h);return Object.assign(b,d),b.toString=e.toString,b},a=(d,...p)=>o(fr(d,p)),l=(...d)=>(d=Ao(d),a(Array(d.length).fill(""),...d)),c=ko,f=((d,...p)=>o(Oo(d,p))),u=({children:d,nonce:p}={})=>K(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[Ie]:""}</style>`,[({context:y})=>{s.set(y,p);}]);return u[Ve]=n,{css:a,cx:l,keyframes:c,viewTransition:f,Style:u}},Ps=kE({id:To}),Mm=Ps.Style;function ye(t,e,n){let r;if(!e||!("children"in e))r=Ts(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Ts(t,e,s):Ts(t,e,[s]);}return r.key=n,r}var Rc=new Se().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>au(Fm())).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(ye(pt,{children:ye("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[ye("head",{children:[ye("meta",{charset:"UTF-8"}),ye("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),ye("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),ye("title",{children:"Supalite"}),ye(pt,{children:[ye("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>ye("link",{rel:"stylesheet",href:n+s},i))]}),ye(Mm,{})]}),ye("body",{children:ye("div",{id:"root"})})]})}))});async function $E(t){return Rc.fetch(t)}var PE={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Bm=["storage","cloud"],kc=Object.fromEntries(Bm.map(t=>[t,NE(t)]));function NE(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[PE[t]]==="1":false}function dr(t){return kc[t]}function IE(t,e){kc[t]=e;}function qm(){return Bm.filter(t=>kc[t])}function DE(){let t=qm();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 Ac=false;function Wm(t=e=>console.warn(e)){if(Ac)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){Ac=true;return}let e=DE();e&&t(e),Ac=true;}function Jm(t,e={}){let n=e.middlewares??[async(r,s)=>{await s();}];return new Se().use(async(r,s)=>{r.set("app",t),t.config.auth?.enabled&&r.set("authService",zp(t)),t.config.storage?.enabled&&t._storageAdapter&&dr("storage")&&r.set("storageService",Zp(t)),await s();}).use(...n).use(Xl()).route("/auth/v1",Zl).route("/rest/v1",up({forceRollback:e.forceRollback})).use("/storage/v1/*",async(r,s)=>{if(!dr("storage"))return r.notFound();await s();}).route("/storage/v1",ic).route("/_system",df).use(async(r,s)=>{if(!e.disableStudio&&t.config.studio?.enabled)return Rc.fetch(r.req.raw);if(!e.disableFallback)return r.notFound();await s();})}ee();var jE=t=>{let e=t.toJSON();return Jt(e)},Oc=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
130
130
 
131
131
  Error: ${JSON.stringify(s[0],null,2)}
132
132
 
133
- 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 Km(t,e,n){let r=n?.clone?$E(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 Ac(r,e,i.errors);return s}Qr();var Oc=`-- supabase/auth core schema (Postgres)
133
+ 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 Km(t,e,n){let r=n?.clone?jE(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 Oc(r,e,i.errors);return s}Qr();var $c=`-- supabase/auth core schema (Postgres)
134
134
  -- Scope: Core Authentication + User Management
135
135
  -- Source: GoTrue migrations + runtime analysis
136
136
 
@@ -307,9 +307,9 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
307
307
  created_at timestamptz DEFAULT now(),
308
308
  ip_address varchar(64) DEFAULT ''
309
309
  );
310
- `;function $c(t=true){return t?Vr(Oc):Oc}var Pc=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=gp(n.drivers),this.config=Km(hi,s,{withDefaults:n.defaults??true}),this.server=Jm(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;Wm(),this.config.auth?.enabled&&mo(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&&$c(),this.config.storage?.enabled&&this._storageAdapter&&dr("storage")&&oc()].filter(Boolean).join(`
310
+ `;function Pc(t=true){return t?Vr($c):$c}var Nc=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=yp(n.drivers),this.config=Km(hi,s,{withDefaults:n.defaults??true}),this.server=Jm(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;Wm(),this.config.auth?.enabled&&mo(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&&Pc(),this.config.storage?.enabled&&this._storageAdapter&&dr("storage")&&ac()].filter(Boolean).join(`
311
311
 
312
- `),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 hi.validate(s).valid}return hi.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,{[ss]:true}),await this.fetch(s)}}})}isLocalRequest(e){return ss 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 Hm=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},zm=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"};$o();Yr();var DE=(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
312
+ `),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 hi.validate(s).valid}return hi.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,{[ss]:true}),await this.fetch(s)}}})}isLocalRequest(e){return ss 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 Hm=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},zm=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"};$o();Xr();var FE=(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
313
313
  json_group_array(
314
314
  json_object(
315
315
  '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 sn(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function Qm(t,e={}){let r=(await t.exec(DE(e)))?.rows?.[0]||{};return {tables:sn(r.tables),columns:sn(r.columns),indexes:sn(r.indexes),foreign_keys:sn(r.foreign_keys),primary_keys:sn(r.primary_keys),views:sn(r.views),triggers:sn(r.triggers),check_constraints:[],unique_constraints:sn(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}var qE=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Ic=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#e=new Set;#t=new Set;transformNodeImpl(n,r){if(!qE.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}},Po=class{#e;constructor(e){this.#e=new Ic(e);}transformQuery(e){return this.#e.transformNode(e.node)}async transformResult(e){return e.result}};No();Dc();jc();function Ns(t){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"}function Ym(t){return {...t,tables:t.tables.filter(e=>!Ns(e.name)),columns:t.columns.filter(e=>!Ns(e.table)),indexes:t.indexes.filter(e=>!Ns(e.table)),foreign_keys:t.foreign_keys.filter(e=>!Ns(e.table)),primary_keys:t.primary_keys.filter(e=>!Ns(e.table))}}var Io=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new pr,this.planner=new mr;}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=Ym(e),a=Ym(i),l=this.differ.diff(o,a),c=this.planner.plan(l,o,a);return {current:e,desired:i,diff:l,plan:c}}finally{await s.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e.sort((n,r)=>{let s=i=>i===PlanStepType.DROP_COLUMN?1:i===PlanStepType.DROP_TABLE?2:i===PlanStepType.RENAME_TABLE?3:0;return s(n.type)-s(r.type)})}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}};Gr();var eh=/^\{\{(.+)\}\}$/;function th(t){return typeof t=="string"&&eh.test(t)}function HE(t){return eh.exec(t)[1]}var Zm=Symbol("unresolved");function nh(t,e){let n=HE(t),r=Yt(e,n,Zm);if(r===Zm)throw new Error(`Unresolved variable: {{${n}}}`);return r}function Mt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>Mt(i,e));continue}if(r==="$not"){n[r]=Mt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?Mt(i.where,e):i?.where};continue}if(th(r)){let i=nh(r,e),a=GE(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=rh(s,e);continue}n[r]=s;}return n}function rh(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=rh(s,e):zE(s)?n[r]={...s,where:s?.where?Mt(s?.where,e):void 0}:th(s)?n[r]=nh(s,e):n[r]=s;return n}function zE(t){return t!=null&&typeof t=="object"&&t.type==="query"}function GE(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}Gr();var jo=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=VE(e.type);if(!s)return e;let i=Yt(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:sh(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:sh(e.where,l)};if(l.$always===false)return c;let f=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(f).length>0){let u=new Set(Object.keys(e.values));this.validateWithCheck(f,e.values,o,a,u);}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 f of c)this.validateWithCheck(l,f,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=>Mt(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=Mt(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=>Mt(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=Mt(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(!Do(e,n,i)){let a=r[0]??s[0];throw a?new zn(a):new Error("RLS policy violation")}}};function VE(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 sh(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function Do(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=>Do(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>Do(l,e,n)))return false;continue}if(r==="$not"){if(Do(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(!QE(o,a,l))return false}return true}function QE(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 Lo=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 ih(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 Vs=class t extends Connection{dialect="sqlite";deserializeRow(e){return this.config.ddlDialect==="postgres"?ih(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"]))}});}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 on(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 Lo),n.push(new Po(sl({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(()=>(nu(),Oh));return await s(e,{forceDefaultSchema:n,introspection:r,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){ud(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 Qm(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 f=c[l],u=c.schema??i;return !u&&i&&f.includes(s)&&([u,f]=f.split(s)),{...c,[l]:f,schema:u??i}},a=l=>{let c=o()(l),f=c.ref_table,u=c.ref_schema??i;return f?.includes(s)&&([u,f]=f.split(s)),{...c,ref_table:f,ref_schema:u??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 this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r=this.markForeignKeyVisibility(r),r={...r,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 f=c.context,u=r.find(d=>d.table===f.table&&d.name===f.column);if(u&&(u.pg_type=f.pgTypeName,f.isGenerated!==void 0&&(u.is_generated=f.isGenerated)),f.fkRef?.constraintName){let d=s.find(p=>p.table===f.table&&p.column===f.column&&p.ref_table===f.fkRef.refTable&&p.ref_column===f.fkRef.refColumn);d&&(d.foreign_key_name=f.fkRef.constraintName);}f.uniqueConstraintName&&i.push({schema:f.schema,table:f.table,name:f.uniqueConstraintName,columns:[f.column]}),f.hasCheck&&o.push({schema:f.schema,table:f.table,expression:"",name:f.checkConstraintName,column:f.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 f=0;f<l.columns.length;f++){let u=s.find(d=>d.table===l.table&&d.column===l.columns[f]&&d.ref_table===c&&d.ref_column===(l.refColumns?.[f]??""));u&&(u.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}}markForeignKeyVisibility(e){let n=new Set(e.views.map(s=>s.name)),r=s=>s.startsWith("private_")?n.has(s.slice(8)):true;return {...e,foreign_keys:e.foreign_keys.map(s=>({...s,is_visible:r(s.table)&&r(s.ref_table)}))}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
508
+ ${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function sn(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function Qm(t,e={}){let r=(await t.exec(FE(e)))?.rows?.[0]||{};return {tables:sn(r.tables),columns:sn(r.columns),indexes:sn(r.indexes),foreign_keys:sn(r.foreign_keys),primary_keys:sn(r.primary_keys),views:sn(r.views),triggers:sn(r.triggers),check_constraints:[],unique_constraints:sn(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}var zE=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Dc=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#e=new Set;#t=new Set;transformNodeImpl(n,r){if(!zE.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}},Po=class{#e;constructor(e){this.#e=new Dc(e);}transformQuery(e){return this.#e.transformNode(e.node)}async transformResult(e){return e.result}};No();jc();Lc();function Ns(t){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"}function Xm(t){return {...t,tables:t.tables.filter(e=>!Ns(e.name)),columns:t.columns.filter(e=>!Ns(e.table)),indexes:t.indexes.filter(e=>!Ns(e.table)),foreign_keys:t.foreign_keys.filter(e=>!Ns(e.table)),primary_keys:t.primary_keys.filter(e=>!Ns(e.table))}}var Io=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new pr,this.planner=new mr;}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=Xm(e),a=Xm(i),l=this.differ.diff(o,a),c=this.planner.plan(l,o,a);return {current:e,desired:i,diff:l,plan:c}}finally{await s.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e.sort((n,r)=>{let s=i=>i===PlanStepType.DROP_COLUMN?1:i===PlanStepType.DROP_TABLE?2:i===PlanStepType.RENAME_TABLE?3:0;return s(n.type)-s(r.type)})}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}};Gr();var eh=/^\{\{(.+)\}\}$/;function th(t){return typeof t=="string"&&eh.test(t)}function YE(t){return eh.exec(t)[1]}var Zm=Symbol("unresolved");function nh(t,e){let n=YE(t),r=Xt(e,n,Zm);if(r===Zm)throw new Error(`Unresolved variable: {{${n}}}`);return r}function Mt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>Mt(i,e));continue}if(r==="$not"){n[r]=Mt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?Mt(i.where,e):i?.where};continue}if(th(r)){let i=nh(r,e),a=ZE(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=rh(s,e);continue}n[r]=s;}return n}function rh(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=rh(s,e):XE(s)?n[r]={...s,where:s?.where?Mt(s?.where,e):void 0}:th(s)?n[r]=nh(s,e):n[r]=s;return n}function XE(t){return t!=null&&typeof t=="object"&&t.type==="query"}function ZE(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}Gr();var jo=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=e_(e.type);if(!s)return e;let i=Xt(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:sh(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:sh(e.where,l)};if(l.$always===false)return c;let f=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(f).length>0){let u=new Set(Object.keys(e.values));this.validateWithCheck(f,e.values,o,a,u);}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 f of c)this.validateWithCheck(l,f,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=>Mt(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=Mt(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=>Mt(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=Mt(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(!Do(e,n,i)){let a=r[0]??s[0];throw a?new zn(a):new Error("RLS policy violation")}}};function e_(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 sh(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function Do(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=>Do(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>Do(l,e,n)))return false;continue}if(r==="$not"){if(Do(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(!t_(o,a,l))return false}return true}function t_(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 Lo=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 ih(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 Vs=class t extends Connection{dialect="sqlite";deserializeRow(e){return this.config.ddlDialect==="postgres"?ih(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"]))}});}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 on(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 Lo),n.push(new Po(sl({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(()=>(ru(),Oh));return await s(e,{forceDefaultSchema:n,introspection:r,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){fd(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 Qm(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 f=c[l],u=c.schema??i;return !u&&i&&f.includes(s)&&([u,f]=f.split(s)),{...c,[l]:f,schema:u??i}},a=l=>{let c=o()(l),f=c.ref_table,u=c.ref_schema??i;return f?.includes(s)&&([u,f]=f.split(s)),{...c,ref_table:f,ref_schema:u??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 this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r=this.markForeignKeyVisibility(r),r={...r,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 f=c.context,u=r.find(d=>d.table===f.table&&d.name===f.column);if(u&&(u.pg_type=f.pgTypeName,f.isGenerated!==void 0&&(u.is_generated=f.isGenerated)),f.fkRef?.constraintName){let d=s.find(p=>p.table===f.table&&p.column===f.column&&p.ref_table===f.fkRef.refTable&&p.ref_column===f.fkRef.refColumn);d&&(d.foreign_key_name=f.fkRef.constraintName);}f.uniqueConstraintName&&i.push({schema:f.schema,table:f.table,name:f.uniqueConstraintName,columns:[f.column]}),f.hasCheck&&o.push({schema:f.schema,table:f.table,expression:"",name:f.checkConstraintName,column:f.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 f=0;f<l.columns.length;f++){let u=s.find(d=>d.table===l.table&&d.column===l.columns[f]&&d.ref_table===c&&d.ref_column===(l.refColumns?.[f]??""));u&&(u.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}}markForeignKeyVisibility(e){let n=new Set(e.views.map(s=>s.name)),r=s=>s.startsWith("private_")?n.has(s.slice(8)):true;return {...e,foreign_keys:e.foreign_keys.map(s=>({...s,is_visible:r(s.table)&&r(s.ref_table)}))}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
509
509
 
510
- `);return new Io(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,f=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,f)}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(f=>f.name===a&&["","public",s].includes(f.schema??""))||i.views.some(f=>f.name===a&&["","public",s].includes(f.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 jo(r.tables,r.policies,s).enforce(e,n)}};var Go=class extends Vs{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 j_(t){return new Go(t)}nu();Yr();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:
510
+ `);return new Io(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,f=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,f)}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(f=>f.name===a&&["","public",s].includes(f.schema??""))||i.views.some(f=>f.name===a&&["","public",s].includes(f.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 jo(r.tables,r.policies,s).enforce(e,n)}};var Go=class extends Vs{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 W_(t){return new Go(t)}ru();Xr();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{Pc as App,co as AwsSesEmailDriver,Go as CloudConnection,io as CloudflareKvCacheDriver,ll as Connection,Gm as DataLossError,ls as InMemoryEmailDriver,Zn as InMemoryLruCacheDriver,zm as InvalidPostgresToSQLiteTranslation,Vm as MigrationError,er as NoopEmailDriver,cs as NoopSmsDriver,Nc as PlanStepType,oo as RedisCacheDriver,Zr as RelationNotFoundError,ao as ResendEmailDriver,uo as SendmailEmailDriver,Vs as SqliteConnection,Hm as UnableToCreateRuntimeConnection,YT as checkPasswordStrength,Vr as cleanSql,j_ as cloud,gp as createAppDrivers,JT as ensureVar,LT as filterSearchParams,Il as formatSendmailMessage,pd as fuzzyMatch,$c as getAuthSchemaSql,Yt as getPath,HT as getStatementsArray,ud as invariant,CT as isBooleanLike,ww as isBun,XT as isEmail,rl as isEqual,dr as isExperimentalEnabled,MT as isNode,ld as isObject,ad as isPlainObject,vT as isPrimitive,RT as isString,IT as jsonStringify,qm as listEnabledExperimentals,WT as measureTime,sl as mergeObject,bw as mergeObjectWith,al as normalizeDefault,ol as normalizeSql,Ew as normalizeString,il as normalizeType,$T as objectDiff,NT as omit,jT as params,ok as parseBigInt,qi as patternMatch,PT as pick,kT as pipe,AT as pipeEach,P as quote,QT as randomString,sk as replacePlaceholders,gs as requireAuth,Xl as resolveAuth,AE as setExperimental,yw as setPath,nk as slugify,tk as snakeToPascalWithSpaces,zT as splitSqlStatements,RE as studioRouteHandler,FT as threw,BT as threwAsync,kh as translatePostgresDdl,rk as truncate,qT as trySync,ZT as ucFirst,ek as ucFirstAll,lk as uuid};
517
+ */export{Nc as App,co as AwsSesEmailDriver,Go as CloudConnection,io as CloudflareKvCacheDriver,ll as Connection,Gm as DataLossError,ls as InMemoryEmailDriver,Zn as InMemoryLruCacheDriver,zm as InvalidPostgresToSQLiteTranslation,Vm as MigrationError,er as NoopEmailDriver,cs as NoopSmsDriver,Ic as PlanStepType,oo as RedisCacheDriver,Zr as RelationNotFoundError,ao as ResendEmailDriver,uo as SendmailEmailDriver,Vs as SqliteConnection,Hm as UnableToCreateRuntimeConnection,iA as checkPasswordStrength,Vr as cleanSql,W_ as cloud,yp as createAppDrivers,YR as ensureVar,JR as filterSearchParams,Il as formatSendmailMessage,md as fuzzyMatch,Pc as getAuthSchemaSql,Xt as getPath,ZR as getStatementsArray,fd as invariant,PR as isBooleanLike,ww as isBun,sA as isEmail,rl as isEqual,dr as isExperimentalEnabled,HR as isNode,cd as isObject,ld as isPlainObject,$R as isPrimitive,NR as isString,BR as jsonStringify,qm as listEnabledExperimentals,QR as measureTime,sl as mergeObject,bw as mergeObjectWith,al as normalizeDefault,ol as normalizeSql,Ew as normalizeString,il as normalizeType,UR as objectDiff,FR as omit,WR as params,pA as parseBigInt,qi as patternMatch,MR as pick,DR as pipe,jR as pipeEach,P as quote,rA as randomString,fA as replacePlaceholders,gs as requireAuth,Xl as resolveAuth,IE as setExperimental,yw as setPath,cA as slugify,lA as snakeToPascalWithSpaces,eA as splitSqlStatements,$E as studioRouteHandler,zR as threw,GR as threwAsync,Ah as translatePostgresDdl,uA as truncate,VR as trySync,oA as ucFirst,aA as ucFirstAll,hA as uuid};