@supabase/lite 0.9.0 → 0.9.1-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/FEATURES.md +176 -0
  2. package/LIMITATIONS.md +9 -6
  3. package/PATTERNS.md +66 -6
  4. package/README.md +16 -8
  5. package/STATUS.md +33 -20
  6. package/dist/{Connection-ZWTDByQ5.d.ts → Connection-f_d5HhQ0.d.ts} +301 -293
  7. package/dist/cli/index.js +127 -124
  8. package/dist/cli/lib.d.ts +1 -12
  9. package/dist/cli/lib.js +44 -39
  10. package/dist/db/fallback.d.ts +1 -1
  11. package/dist/db/postgres/PostgresConnection.js +18 -18
  12. package/dist/db/postgres/pglite/PgliteConnection.js +17 -17
  13. package/dist/index.d.ts +116 -40
  14. package/dist/index.js +181 -73
  15. package/dist/static/.vite/manifest.json +34 -2
  16. package/dist/static/assets/InterVariable-Dx4kXJAl.woff2 +0 -0
  17. package/dist/static/assets/InterVariable-Italic-DpCbqKDY.woff2 +0 -0
  18. package/dist/static/assets/SourceCodePro-Variable-BP8Zz55n.woff2 +0 -0
  19. package/dist/static/assets/SourceCodePro-Variable-Italic-eALmlzX7.woff2 +0 -0
  20. package/dist/static/assets/main-BY4iigay.css +1 -0
  21. package/dist/static/assets/main-BnQ-v4V9.js +199 -0
  22. package/dist/static/assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2 +0 -0
  23. package/dist/static/assets/manrope-latin-wght-normal-DHIcAJRg.woff2 +0 -0
  24. package/dist/vite/index.d.ts +627 -31
  25. package/dist/vite/index.js +2 -2
  26. package/docs/auth/email.mdx +214 -0
  27. package/docs/auth/not-supported.mdx +57 -0
  28. package/docs/auth/overview.mdx +52 -0
  29. package/docs/auth/supported-flows.mdx +120 -0
  30. package/docs/cli/overview.mdx +112 -0
  31. package/docs/cli/telemetry.mdx +34 -0
  32. package/docs/compatibility.mdx +115 -0
  33. package/docs/database/backends.mdx +118 -0
  34. package/docs/database/data-api.mdx +90 -0
  35. package/docs/database/functions-triggers.mdx +93 -0
  36. package/docs/database/migrations.mdx +95 -0
  37. package/docs/database/overview.mdx +66 -0
  38. package/docs/database/postgres-sqlite-translation.mdx +130 -0
  39. package/docs/database/rls.mdx +161 -0
  40. package/docs/database/schemas.mdx +58 -0
  41. package/docs/index.mdx +49 -0
  42. package/docs/integrations/embedded.mdx +100 -0
  43. package/docs/integrations/frameworks.mdx +83 -0
  44. package/docs/integrations/vite.mdx +87 -0
  45. package/docs/llms.txt +52 -0
  46. package/docs/other/edge-functions.mdx +34 -0
  47. package/docs/other/realtime.mdx +22 -0
  48. package/docs/quickstart.mdx +150 -0
  49. package/docs/running.mdx +127 -0
  50. package/docs/storage/adapters.mdx +75 -0
  51. package/docs/storage/limitations.mdx +21 -0
  52. package/docs/storage/overview.mdx +88 -0
  53. package/docs/upgrade.mdx +108 -0
  54. package/package.json +5 -1
  55. package/skills/supalite/SKILL.md +6 -4
  56. package/dist/static/assets/main-1bwWb_1q.js +0 -40996
  57. package/dist/static/assets/main-BDsRycsc.css +0 -4045
  58. package/dist/static/fonts/CustomFont-Black.woff2 +0 -0
  59. package/dist/static/fonts/CustomFont-BlackItalic.woff2 +0 -0
  60. package/dist/static/fonts/CustomFont-Bold.woff2 +0 -0
  61. package/dist/static/fonts/CustomFont-BoldItalic.woff2 +0 -0
  62. package/dist/static/fonts/CustomFont-Book.woff2 +0 -0
  63. package/dist/static/fonts/CustomFont-BookItalic.woff2 +0 -0
  64. package/dist/static/fonts/CustomFont-Medium.woff2 +0 -0
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as yt from'jsonv-ts';import {s}from'jsonv-ts';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 {jwtVerify,createRemoteJWKSet,customFetch,errors,SignJWT}from'jose';import hh from'bcryptjs';import {v7}from'uuid';import {validator}from'jsonv-ts/hono';import {createClient}from'@supabase/supabase-js';try {
1
+ import*as St from'jsonv-ts';import {s}from'jsonv-ts';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 {jwtVerify,errors,createRemoteJWKSet,customFetch,SignJWT}from'jose';import Fh from'bcryptjs';import {v7}from'uuid';import {validator}from'jsonv-ts/hono';import {createClient}from'@supabase/supabase-js';try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,84 +9,84 @@ import*as yt from'jsonv-ts';import {s}from'jsonv-ts';import {Deparser,QuoteUtils
9
9
  };
10
10
  } catch {}
11
11
 
12
- var bb=Object.create;var la=Object.defineProperty;var wb=Object.getOwnPropertyDescriptor;var Sb=Object.getOwnPropertyNames;var _b=Object.getPrototypeOf,Eb=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var Hu=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zs=(t,e)=>{for(var n in e)la(t,n,{get:e[n],enumerable:true});},xb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Sb(e))!Eb.call(t,s)&&s!==n&&la(t,s,{get:()=>e[s],enumerable:!(r=wb(e,s))||r.enumerable});return t};var ca=(t,e,n)=>(n=t!=null?bb(_b(t)):{},xb(la(n,"default",{value:t,enumerable:true}),t));var on,ki=I(()=>{on=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 ie,st=I(()=>{ki();ie=class{context;factoryExtra;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 on(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function LO(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 FO(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!s.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 UO(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 MO(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function BO(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function qO(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function WS(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function HO(t){return WS(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function WO(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function N(t,e='"'){return `${e}${t}${e}`}function Ki(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 KO(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function Jr(t,e,n=.33){if(e.length===0)return null;let r=rp(t),s=[];for(let l of e){let c=KS(r,rp(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-JS(t.toLowerCase(),l.toLowerCase())/c;f>a&&(a=f,o=l);}return o}function rp(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 KS(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 JS(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 Fn=I(()=>{});var Cl=Hu((BP,Rl)=>{var eo=process||{},Cp=eo.argv||[],Zi=eo.env||{},H_=!(Zi.NO_COLOR||Cp.includes("--no-color"))&&(!!Zi.FORCE_COLOR||Cp.includes("--color")||eo.platform==="win32"||(eo.stdout||{}).isTTY&&Zi.TERM!=="dumb"||!!Zi.CI),W_=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+K_(s,e,n,i)+e:t+s+e},K_=(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)},kp=(t=H_)=>{let e=t?W_:()=>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")}};Rl.exports=kp();Rl.exports.createColors=kp;});function qP(t){return ["string","number","boolean"].includes(typeof t)}function HP(t){return [true,false,0,1].includes(t)}function WP(t){return typeof t=="string"}var vp=I(()=>{});function JP(...t){return e=>t.reduce((n,r)=>r(n),e)}function GP(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Ap=I(()=>{});function Op(t){return Object.prototype.toString.call(t)==="[object Object]"}function Pp(t){return t!==null&&typeof t=="object"}function VP(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function qt(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:qt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function J_(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"?[]:{}),J_(t[s],i,n),t)}function QP(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function YP(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 vl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!Op(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Pp(t[r])?vl(t[r],s):t[r]=s);return t}function G_(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&&(!Op(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:Pp(t[r])?G_(t[r],s,n):t[r]=s);}return t}function kl(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)=>kl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&kl(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)&&kl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function $p(...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 Vr=I(()=>{});function ZP(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function e$(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 Ip=I(()=>{});function Np(){try{return !Al()&&global?.process?.release?.name==="node"}catch{return false}}function Al(){try{return typeof Bun<"u"}catch{return false}}function Dp(){try{return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}catch{return false}}function jp(t,e){if(!t)throw new Error(e)}function n$(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function r$(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function s$(t,e){try{return t()}catch{return e}}async function i$(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var o$,Ol=I(()=>{o$={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 Qr(t,e={}){return t.split(`
12
+ var Xb=Object.create;var ka=Object.defineProperty;var Zb=Object.getOwnPropertyDescriptor;var ew=Object.getOwnPropertyNames;var tw=Object.getPrototypeOf,nw=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var yf=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),li=(t,e)=>{for(var n in e)ka(t,n,{get:e[n],enumerable:true});},rw=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ew(e))!nw.call(t,s)&&s!==n&&ka(t,s,{get:()=>e[s],enumerable:!(r=Zb(e,s))||r.enumerable});return t};var Aa=(t,e,n)=>(n=t!=null?Xb(tw(t)):{},rw(ka(n,"default",{value:t,enumerable:true}),t));function Ga(t){let e=t.trim().toLowerCase();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e=e.split("%")[0],e==="::1")return true;e.startsWith("::ffff:")&&(e=e.slice(7));let n=e.split(".");return n.length===4&&n.every(r=>/^\d{1,3}$/.test(r)&&Number(r)<=255)&&Number(n[0])===127}function ld(t){let e=t.trim().toLowerCase();return e==="localhost"||Ga(e)}var Va=I(()=>{});var fn,Ui=I(()=>{fn=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 le,lt=I(()=>{Ui();le=class{context;factoryExtra;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 fn(this.context.table,this.context.column,e,n)}quoteIfNeeded(e){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)?e:`"${e}"`}};});function NP(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 IP(t,e){if(typeof t!="string"){if(e?.panic)throw new Error("Email must be a string");return false}if(!s.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 DP(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 jP(t){return !t||t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)}function LP(t,e=" "){return !t||t.length===0?t:t.split(e).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(e)}function FP(t){return !t||t.length===0?t:t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function E_(t){return String(t).normalize("NFKD").replace(/[\u0300-\u036f]/g,"")}function UP(t){return E_(t).trim().toLowerCase().replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")}function MP(t,e=50,n="..."){return t.length<=e?t:t.substring(0,e)+n}function F(t,e='"'){return `${e}${t}${e}`}function ro(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 BP(t,e,n=/\{\{([\w-]+)\}\}/g){return t.replace(n,(r,s)=>s in e?e[s]:r)}function Xr(t,e,n=.33){if(e.length===0)return null;let r=kp(t),s=[];for(let l of e){let c=x_(r,kp(l));c>.1&&s.push([l,c]);}s.sort((l,c)=>c[1]-l[1]);let i=s.slice(0,50),o=null,a=n;for(let[l]of i){let c=Math.max(t.length,l.length),u=c===0?1:1-T_(t.toLowerCase(),l.toLowerCase())/c;u>a&&(a=u,o=l);}return o}function kp(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 x_(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 T_(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 qn=I(()=>{});var Jl=yf((L$,Kl)=>{var mo=process||{},Qp=mo.argv||[],po=mo.env||{},_E=!(po.NO_COLOR||Qp.includes("--no-color"))&&(!!po.FORCE_COLOR||Qp.includes("--color")||mo.platform==="win32"||(mo.stdout||{}).isTTY&&po.TERM!=="dumb"||!!po.CI),EE=(t,e,n=t)=>r=>{let s=""+r,i=s.indexOf(e,t.length);return ~i?t+xE(s,e,n,i)+e:t+s+e},xE=(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)},Yp=(t=_E)=>{let e=t?EE:()=>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")}};Kl.exports=Yp();Kl.exports.createColors=Yp;});function F$(t){return ["string","number","boolean"].includes(typeof t)}function U$(t){return [true,false,0,1].includes(t)}function M$(t){return typeof t=="string"}var Xp=I(()=>{});function q$(...t){return e=>t.reduce((n,r)=>r(n),e)}function H$(...t){return e=>e.map(n=>t.reduce((r,s)=>s(r),n))}var Zp=I(()=>{});function em(t){return Object.prototype.toString.call(t)==="[object Object]"}function tm(t){return t!==null&&typeof t=="object"}function K$(t,e){let n={};for(let r in t)t[r]!==e[r]&&(n[r]=e[r]);return n}function Wt(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:Wt(t[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}function TE(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"?[]:{}),TE(t[s],i,n),t)}function J$(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function G$(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 Vl(t,...e){for(let n of e)for(let[r,s]of Object.entries(n))s!==void 0&&(!em(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:tm(t[r])?Vl(t[r],s):t[r]=s);return t}function RE(t,e,n){for(let[r,s]of Object.entries(e)){let i=n(t[r],s,r,t,e);if(i!==void 0){t[r]=i;continue}s!==void 0&&(!em(s)&&!Array.isArray(s)||Array.isArray(s)&&!Array.isArray(t[r])?t[r]=s:tm(t[r])?RE(t[r],s,n):t[r]=s);}return t}function Gl(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)=>Gl(s,e[i]));if(r==="map")return t.size===e.size&&[...t].every(([s,i])=>e.has(s)&&Gl(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)&&Gl(a,i.get(o)))}else {if(r==="function")return t.toString()===e.toString();throw new Error("Unreachable")}}function nm(...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 ts=I(()=>{});function z$(t){let e=t instanceof Request?new URL(t.url).searchParams:t;return Object.fromEntries(e.entries())}function Q$(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 rm=I(()=>{});function sm(){try{return !zl()&&global?.process?.release?.name==="node"}catch{return false}}function zl(){try{return typeof Bun<"u"}catch{return false}}function im(){try{return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}catch{return false}}function om(t,e){if(!t)throw new Error(e)}function X$(t,e){try{return t(),!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}async function Z$(t,e){try{return await t,!1}catch(n){if(e){if(n instanceof e)return true;throw n}return true}}function eN(t,e){try{return t()}catch{return e}}async function tN(t,e){let n=performance.now();await t();let r=performance.now();e(r-n);}var nN,Ql=I(()=>{nN={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 ns(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 l$(t,e=true){return (e?Qr(t):t).split(";").filter(Boolean)}function Fp(t){let e=[],n="",r=0,s=t.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=u=>{Lp(u).length>0&&e.push(u.trim());},f=()=>{i=false,o=false,a=0;};for(;r<s;){let u=t[r],d=t[r+1];if(u==="-"&&d==="-"){for(;r<s&&t[r]!==`
15
- `;)n+=t[r],r++;continue}if(u==="/"&&d==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(u==="$"){let p=t.indexOf("$",r+1);if(p!==-1){let g=t.slice(r,p+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=p+1;let h=t.indexOf(g,r);h===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,h+g.length),r=h+g.length);continue}}}if(/[A-Za-z_]/.test(u)){let p=r;for(;p<s&&/[A-Za-z0-9_]/.test(t[p]);)p++;let g=t.slice(r,p),m=g.toLowerCase();if(m==="trigger"&&l.test(Lp(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=g,r=p,i&&o&&a===0){let h=r;for(;h<s&&/\s/.test(t[h]);)h++;t[h]===";"&&(r=h+1),c(n),n="",f();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}c(n),n="",f(),r++;continue}n+=u,r++;}return c(n),e}function Lp(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 $l(t){return (t??"").trim().toLowerCase()}function Up(t,e){let n=e.toLowerCase();return t.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(t)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function to(t){let e=(t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=e,e=e.replace(z_,(r,s,i)=>Up(s,i)?s:r);while(e!==n);do n=e,e=e.replace(V_,"$1");while(e!==n);return e}function X_(t,e,n){let r=0;for(let s=e;s<t.length;s++){let i=t[s];if(i==="'"){for(s++;s<t.length;){if(t[s]==="'"&&t[s+1]==="'"){s+=2;continue}if(t[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=t[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(t.slice(s,s+a.length)!==a)continue;let l=t[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function Z_(t){let e=[],n=0;for(;;){let c=X_(t,n,Y_);if(!c)break;e.push(c),n=c.index+c.kw.length;}if(e.length===0)return {head:t,checks:[],uniques:[]};let r=t.slice(0,e[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<e.length;c++){let f=e[c].index,u=c+1<e.length?e[c+1].index:t.length,d=t.slice(f,u).trim();e[c].kw==="check"?o.push(d):e[c].kw==="unique"&&!d.includes("(")?a++:i.push(d);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function Il(t){let e=to(t),n=e.indexOf("(");if(n===-1)return null;let r=Pl(e,n);if(r===-1)return null;let s=e.slice(n+1,r),i=e.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let u=0;u<s.length;u++){let d=s[u];if(d==="'"){for(c+=d,u++;u<s.length;){if(s[u]==="'"&&s[u+1]==="'"){c+="''",u+=2;continue}if(c+=s[u],s[u]==="'")break;u++;}continue}if(d==="("?l++:d===")"&&l--,d===","&&l===0){a.push(c.trim()),c="";continue}c+=d;}c.trim().length>0&&a.push(c.trim());let f=[];for(let u of a){let d=u.replace(Q_,"");if(/^(primary key|unique|check|foreign key)\b/i.test(d)){f.push(d);continue}let{head:p,checks:g,uniques:m}=Z_(d);f.push(p,...g,...m);}return o.length>0&&f.push(`table options: ${o.join(", ")}`),f}function Pl(t,e){let n=0;for(let r=e;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function eE(t){let e=0,n=-1;for(let r=0;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}s==="("?e++:s===")"?e--:e===0&&/^\s+as\s/i.test(t.slice(r))&&(n=r);}return n}function tE(t){return t.startsWith("'")&&t.endsWith("'")&&t.length>=2||/^-?\d+(\.\d+)?$/.test(t)}function Mp(t){let e=t.trim();for(;;){if(e.startsWith("(")&&Pl(e,0)===e.length-1){e=e.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(e)){let n=e.indexOf("(");if(Pl(e,n)===e.length-1){let r=e.slice(n+1,-1),s=eE(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=Mp(i);if(tE(a)&&Up(a,o)){e=a;continue}}}}break}return e}function Nl(t){if(t==null)return null;let e=Mp(t);if(e.startsWith("'")&&e.endsWith("'")&&e.length>=2){let n=e.slice(1,-1);/(?<!')'(?!')/.test(n)||(e=n);}else if(e.startsWith('"')&&e.endsWith('"')&&e.length>=2){let n=e.slice(1,-1);n.includes('"')||(e=n);}return e}var z_,V_,Q_,Y_,Un=I(()=>{z_=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,V_=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;Q_=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,Y_=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function u$(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var Bp=I(()=>{});function d$(){return crypto.randomUUID()}var qp=I(()=>{});var Yr=I(()=>{vp();Ap();Vr();Ip();Ol();Un();Fn();Bp();qp();});var dn,no=I(()=>{st();dn=class extends ie{get sqliteType(){return "INTEGER"}};});var Xr,Dl=I(()=>{no();Xr=class extends dn{constructor(e){super({...e,isSerial:true});}};});function sE(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 Zr,jl=I(()=>{st();Zr=class extends ie{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(!sE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ae,Ze=I(()=>{st();ae=class extends ie{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 es,Ll=I(()=>{st();es=class extends ie{get sqliteType(){return "BLOB"}};});var ts,Fl=I(()=>{st();ts=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Wp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var ns,Ul=I(()=>{st();ns=class extends ie{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=Wp(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."):Wp(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function iE(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 rs,Ml=I(()=>{Ze();rs=class extends ae{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"||!iE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function oE(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 ss,Bl=I(()=>{Ze();ss=class extends ae{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"||!oE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function aE(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 is,ql=I(()=>{Ze();is=class extends ae{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"||!aE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var os,Hl=I(()=>{Ze();os=class extends ae{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 as,Wl=I(()=>{Ze();as=class extends ae{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 Kp(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Mn,Kl=I(()=>{st();Mn=class extends ie{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=Kp(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=Kp(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 Jp(t){return cE.test(t.toLowerCase())}var lE,cE,ls,Jl=I(()=>{Ze();lE="????????-????-????-????-????????????",cE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ls=class extends ae{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${lE}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!Jp(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Jp(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function uE(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 fE(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 dE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function Gp(t){let e=uE(t);return e?fE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:dE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var cs,Gl=I(()=>{Ze();cs=class extends ae{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(!Gp(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!Gp(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var us,zl=I(()=>{Ze();us=class extends ae{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 We(t,e){let n=kE(t,e);if(e){let{enumValues:r,...s}=e;n.factoryExtra=s;}return n}function kE(t,e){if(e?.isArray){let r=We(t,{...e,isArray:false});return new Mn(t,r)}if(e?.enumValues)return new as(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=We(s);return new Mn(t,i)}return mE.has(n)?new Xr(t):pE.has(n)?new dn(t):bE.has(n)?new ts(t):wE.has(n)?new ns(t):xE.has(n)?new rs(t):TE.has(n)?new ss(t):RE.has(n)?new is(t):CE.has(n)?new os(t):yE.has(n)?new es(t):hE.has(n)?new Zr(t,e?.numericPrecision):SE.has(n)?new ls(t):_E.has(n)?new ae(t,63):EE.has(n)?new cs(t):gE.has(n)?new ae(t,e?.lengthConstraint):new us(t)}var pE,mE,hE,gE,yE,bE,wE,SE,_E,EE,xE,TE,RE,CE,ro=I(()=>{no();Dl();jl();Ze();Ll();Fl();Ul();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();pE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),mE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),hE=new Set(["float4","real","float8","double precision","numeric","decimal"]),gE=new Set(["text","varchar","character varying","char","character","bpchar"]),yE=new Set(["bytea"]),bE=new Set(["bool","boolean"]),wE=new Set(["json","jsonb"]),SE=new Set(["uuid"]),_E=new Set(["name"]),EE=new Set(["inet"]),xE=new Set(["date"]),TE=new Set(["time","timetz","time without time zone","time with time zone"]),RE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),CE=new Set(["interval"]);});function Vl(t,e="auto"){let n=t.toLowerCase(),r=so[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 zp,so,Ql=I(()=>{zp="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)))",so={gen_random_uuid:{sqlite:()=>zp,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>zp,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 at,Yl=I(()=>{at=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 Xl=I(()=>{st();ki();no();Dl();jl();Ze();Ll();Fl();Ul();Ml();Bl();ql();Hl();Wl();Kl();Jl();Gl();zl();ro();Ql();Yl();});var Kh={};Zs(Kh,{AwsClient:()=>Dc,AwsV4Signer:()=>_o});async function _s(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?Nc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,Nc.encode(e))}async function qh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Nc.encode(t):t)}function Ic(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=Hh[s>>>4&15],n+=Hh[s&15];}return n}function Wh(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function ST(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 [bT[i]||i,o||""]}var Nc,bT,wT,Dc,_o,Hh,Jh=I(()=>{Nc=new TextEncoder,bT={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"},wT=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),Dc=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 _o(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")}},_o=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:g,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let h,y;(!l||!c)&&([h,y]=ST(this.url,this.headers)),this.service=l||h||"",this.region=c||y||"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(b=>g||!wT.has(b)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(b=>b+":"+(b==="host"?this.url.host:(this.headers.get(b)||"").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,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Wh(this.encodedPath);let S=new Set;this.encodedSearch=[...this.url.searchParams].filter(([b])=>{if(!b)return false;if(this.service==="s3"){if(S.has(b))return false;S.add(b);}return true}).map(b=>b.map(_=>Wh(encodeURIComponent(_)))).sort(([b,_],[E,x])=>b<E?-1:b>E?1:_<x?-1:_>x?1:0).map(b=>b.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 _s("AWS4"+this.secretAccessKey,e),i=await _s(s,this.region),o=await _s(i,this.service);r=await _s(o,"aws4_request"),this.cache.set(n,r);}return Ic(await _s(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ic(await qh(await this.canonicalString()))].join(`
14
+ `)}function sN(t,e=true){return (e?ns(t):t).split(";").filter(Boolean)}function lm(t){let e=[],n="",r=0,s=t.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=f=>{am(f).length>0&&e.push(f.trim());},u=()=>{i=false,o=false,a=0;};for(;r<s;){let f=t[r],d=t[r+1];if(f==="-"&&d==="-"){for(;r<s&&t[r]!==`
15
+ `;)n+=t[r],r++;continue}if(f==="/"&&d==="*"){for(n+="/*",r+=2;r<s&&!(t[r]==="*"&&t[r+1]==="/");)n+=t[r],r++;r<s&&(n+="*/",r+=2);continue}if(f==="'"){for(n+=f,r++;r<s;){if(t[r]==="'"&&t[r+1]==="'"){n+="''",r+=2;continue}if(n+=t[r],t[r]==="'"){r++;break}r++;}continue}if(f==='"'){for(n+=f,r++;r<s;){if(t[r]==='"'&&t[r+1]==='"'){n+='""',r+=2;continue}if(n+=t[r],t[r]==='"'){r++;break}r++;}continue}if(f==="$"){let p=t.indexOf("$",r+1);if(p!==-1){let h=t.slice(r,p+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(h)){n+=h,r=p+1;let g=t.indexOf(h,r);g===-1?(n+=t.slice(r),r=s):(n+=t.slice(r,g+h.length),r=g+h.length);continue}}}if(/[A-Za-z_]/.test(f)){let p=r;for(;p<s&&/[A-Za-z0-9_]/.test(t[p]);)p++;let h=t.slice(r,p),m=h.toLowerCase();if(m==="trigger"&&l.test(am(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=h,r=p,i&&o&&a===0){let g=r;for(;g<s&&/\s/.test(t[g]);)g++;t[g]===";"&&(r=g+1),c(n),n="",u();}continue}if(f===";"){if(i&&o&&a>0){n+=f,r++;continue}c(n),n="",u(),r++;continue}n+=f,r++;}return c(n),e}function am(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 Xl(t){return (t??"").trim().toLowerCase()}function cm(t,e){let n=e.toLowerCase();return t.startsWith("'")?n.includes("text")||n.includes("char")||n.includes("clob"):/^-?\d+$/.test(t)?n.includes("int"):n.includes("real")||n.includes("floa")||n.includes("doub")||n.includes("num")||n.includes("dec")}function ho(t){let e=(t??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase(),n;do n=e,e=e.replace(CE,(r,s,i)=>cm(s,i)?s:r);while(e!==n);do n=e,e=e.replace(kE,"$1");while(e!==n);return e}function OE(t,e,n){let r=0;for(let s=e;s<t.length;s++){let i=t[s];if(i==="'"){for(s++;s<t.length;){if(t[s]==="'"&&t[s+1]==="'"){s+=2;continue}if(t[s]==="'")break;s++;}continue}if(i==="("?r++:i===")"&&r--,r!==0)continue;let o=t[s-1];if(!(o&&/[a-z0-9_]/.test(o)))for(let a of n){if(t.slice(s,s+a.length)!==a)continue;let l=t[s+a.length];if(!(l&&/[a-z0-9_]/.test(l)))return {index:s,kw:a}}}return null}function PE(t){let e=[],n=0;for(;;){let c=OE(t,n,vE);if(!c)break;e.push(c),n=c.index+c.kw.length;}if(e.length===0)return {head:t,checks:[],uniques:[]};let r=t.slice(0,e[0].index).trim(),s=r.split(/\s+/)[0]??"",i=[],o=[],a=0;for(let c=0;c<e.length;c++){let u=e[c].index,f=c+1<e.length?e[c+1].index:t.length,d=t.slice(u,f).trim();e[c].kw==="check"?o.push(d):e[c].kw==="unique"&&!d.includes("(")?a++:i.push(d);}i.sort();let l=s?Array(a).fill(`unique (${s})`):[];return {head:[r,...i].join(" ").trim(),checks:o,uniques:l}}function Zl(t){let e=ho(t),n=e.indexOf("(");if(n===-1)return null;let r=Yl(e,n);if(r===-1)return null;let s=e.slice(n+1,r),i=e.slice(r+1).replace(/\s+/g," ").trim(),o=[];/\bstrict\b/.test(i)&&o.push("strict"),/\bwithout\s+rowid\b/.test(i)&&o.push("without rowid");let a=[],l=0,c="";for(let f=0;f<s.length;f++){let d=s[f];if(d==="'"){for(c+=d,f++;f<s.length;){if(s[f]==="'"&&s[f+1]==="'"){c+="''",f+=2;continue}if(c+=s[f],s[f]==="'")break;f++;}continue}if(d==="("?l++:d===")"&&l--,d===","&&l===0){a.push(c.trim()),c="";continue}c+=d;}c.trim().length>0&&a.push(c.trim());let u=[];for(let f of a){let d=f.replace(AE,"");if(/^(primary key|unique|check|foreign key)\b/i.test(d)){u.push(d);continue}let{head:p,checks:h,uniques:m}=PE(d);u.push(p,...h,...m);}return o.length>0&&u.push(`table options: ${o.join(", ")}`),u}function Yl(t,e){let n=0;for(let r=e;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r}return -1}function $E(t){let e=0,n=-1;for(let r=0;r<t.length;r++){let s=t[r];if(s==="'"){for(r++;r<t.length;){if(t[r]==="'"&&t[r+1]==="'"){r+=2;continue}if(t[r]==="'")break;r++;}continue}s==="("?e++:s===")"?e--:e===0&&/^\s+as\s/i.test(t.slice(r))&&(n=r);}return n}function NE(t){return t.startsWith("'")&&t.endsWith("'")&&t.length>=2||/^-?\d+(\.\d+)?$/.test(t)}function um(t){let e=t.trim();for(;;){if(e.startsWith("(")&&Yl(e,0)===e.length-1){e=e.slice(1,-1).trim();continue}if(/^cast\s*\(/i.test(e)){let n=e.indexOf("(");if(Yl(e,n)===e.length-1){let r=e.slice(n+1,-1),s=$E(r);if(s!==-1){let i=r.slice(0,s).trim(),o=r.slice(s).replace(/^\s+as\s+/i,"").trim(),a=um(i);if(NE(a)&&cm(a,o)){e=a;continue}}}}break}return e}function ec(t){if(t==null)return null;let e=um(t);if(e.startsWith("'")&&e.endsWith("'")&&e.length>=2){let n=e.slice(1,-1);/(?<!')'(?!')/.test(n)||(e=n);}else if(e.startsWith('"')&&e.endsWith('"')&&e.length>=2){let n=e.slice(1,-1);n.includes('"')||(e=n);}return e}var CE,kE,AE,vE,Hn=I(()=>{CE=/\bcast\s*\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s+as\s+([a-z][a-z0-9 ]*)\)/g,kE=/\(\s*('(?:[^']|'')*'|-?\d+(?:\.\d+)?)\s*\)/g;AE=/\bconstraint\s+\S+\s+(?=(primary key|unique|check|foreign key|references)\b)/gi,vE=["generated always as","not null","primary key","foreign key","references","default","unique","check","collate","null"];});function oN(t){return typeof t=="number"?t:Number.parseInt(String(t),10)}var fm=I(()=>{});function lN(){return crypto.randomUUID()}var dm=I(()=>{});var rs=I(()=>{Xp();Zp();ts();rm();Ql();Hn();qn();fm();dm();Va();});var yn,yo=I(()=>{lt();yn=class extends le{get sqliteType(){return "INTEGER"}};});var ss,tc=I(()=>{yo();ss=class extends yn{constructor(e){super({...e,isSerial:true});}};});function jE(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 is,nc=I(()=>{lt();is=class extends le{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(!jE(e,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ue,nt=I(()=>{lt();ue=class extends le{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 os,rc=I(()=>{lt();os=class extends le{get sqliteType(){return "BLOB"}};});var as,sc=I(()=>{lt();as=class extends le{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(e){if(this.isNullish(e))return e;if(e===true||e===1)return 1;if(e===false||e===0)return 0;throw this.checkError("boolean_range",e)}deserialize(e){if(this.isNullish(e)||e===true||e===false)return e;if(typeof e=="number"&&Number.isFinite(e)){if(e===1)return true;if(e===0)return false}return e===1n?true:e===0n?false:e==="1"||e==="true"?true:e==="0"||e==="false"?false:e}validateStorage(e){return this.isNullish(e)?this.validationPass():e===1||e===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function pm(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var ls,ic=I(()=>{lt();ls=class extends le{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=pm(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."):pm(e).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function LE(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 cs,oc=I(()=>{nt();cs=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR date(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!LE(e)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function FE(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 us,ac=I(()=>{nt();us=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR time(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!FE(e)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function UE(t){let e=t.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!e)return false;let n=Number(e[1]),r=Number(e[2]),s=Number(e[3]),i=Number(e[4]),o=Number(e[5]),a=e[6]===void 0?0:Number(e[6]),l=e[8]===void 0?null:Number(e[8]),c=e[9]===void 0?null:Number(e[9]),u=new Date(Date.UTC(n,r-1,s)),f=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===s,d=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),p=l===null||c!==null&&l<=15&&c<=59;return f&&d&&p}var fs,lc=I(()=>{nt();fs=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.context.column;return `${e} IS NULL OR datetime(${e}) IS NOT NULL`}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!UE(e)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ds,cc=I(()=>{nt();ds=class extends ue{get isShimBacked(){return true}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||e.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(e.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var ps,uc=I(()=>{nt();ps=class extends ue{enumValues;constructor(e,n){super(e),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let e=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${e} IN (${n})`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string"||!this.enumValues.includes(e))throw this.checkError("enum_membership",e);return e}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!this.enumValues.includes(e)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function mm(t){try{return {ok:!0,value:JSON.parse(t)}}catch{return {ok:false}}}var Wn,fc=I(()=>{lt();Wn=class extends le{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=mm(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=mm(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 hm(t){return BE.test(t.toLowerCase())}var ME,BE,ms,dc=I(()=>{nt();ME="????????-????-????-????-????????????",BE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ms=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR ${e} GLOB '${ME}'`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("uuid_format",e);let n=e.toLowerCase();if(!hm(n))throw this.checkError("uuid_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!hm(e)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function qE(t){let e=t.split("/");if(e.length>2)return null;let n=e[0];if(!n)return null;if(e.length===1)return {address:n,prefix:null};let r=e[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function HE(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 WE(t){if(!t.includes(":"))return false;try{return new URL(`http://[${t}]/`),!0}catch{return false}}function gm(t){let e=qE(t);return e?HE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=32:WE(e.address)?e.prefix===null||e.prefix>=0&&e.prefix<=128:false:false}var hs,pc=I(()=>{nt();hs=class extends ue{get isShimBacked(){return true}checkConstraint(){let e=this.quoteIfNeeded(this.context.column);return `${e} IS NULL OR (length(${e}) BETWEEN 3 AND 49 AND (instr(${e}, '.') > 0 OR instr(${e}, ':') > 0))`}serialize(e){if(this.isNullish(e))return e;if(typeof e!="string")throw this.checkError("inet_format",e);let n=e.trim();if(!gm(n))throw this.checkError("inet_format",e);return n}validateStorage(e){return this.isNullish(e)?this.validationPass():typeof e!="string"||!gm(e.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var gs,mc=I(()=>{nt();gs=class extends ue{serialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(e){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function we(t,e){let n=ix(t,e);if(e){let{enumValues:r,...s}=e;n.factoryExtra=s;}return n}function ix(t,e){if(e?.isArray){let r=we(t,{...e,isArray:false});return new Wn(t,r)}if(e?.enumValues)return new ps(t,e.enumValues);let n=t.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...t,pgTypeName:r},i=we(s);return new Wn(t,i)}return JE.has(n)?new ss(t):KE.has(n)?new yn(t):QE.has(n)?new as(t):YE.has(n)?new ls(t):tx.has(n)?new cs(t):nx.has(n)?new us(t):rx.has(n)?new fs(t):sx.has(n)?new ds(t):zE.has(n)?new os(t):GE.has(n)?new is(t,e?.numericPrecision):XE.has(n)?new ms(t):ZE.has(n)?new ue(t,63):ex.has(n)?new hs(t):VE.has(n)?new ue(t,e?.lengthConstraint):new gs(t)}var KE,JE,GE,VE,zE,QE,YE,XE,ZE,ex,tx,nx,rx,sx,bo=I(()=>{yo();tc();nc();nt();rc();sc();ic();oc();ac();lc();cc();uc();fc();dc();pc();mc();KE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),JE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),GE=new Set(["float4","real","float8","double precision","numeric","decimal"]),VE=new Set(["text","varchar","character varying","char","character","bpchar"]),zE=new Set(["bytea"]),QE=new Set(["bool","boolean"]),YE=new Set(["json","jsonb"]),XE=new Set(["uuid"]),ZE=new Set(["name"]),ex=new Set(["inet"]),tx=new Set(["date"]),nx=new Set(["time","timetz","time without time zone","time with time zone"]),rx=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),sx=new Set(["interval"]);});function hc(t,e="auto"){let n=t.toLowerCase(),r=wo[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 ym,wo,gc=I(()=>{ym="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)))",wo={gen_random_uuid:{sqlite:()=>ym,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>ym,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 Qe,yc=I(()=>{Qe=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 bc=I(()=>{lt();Ui();yo();tc();nc();nt();rc();sc();ic();oc();ac();lc();cc();uc();fc();dc();pc();mc();bo();gc();yc();});var mg={};li(mg,{AwsClient:()=>tu,AwsV4Signer:()=>jo});async function ks(t,e){let n=await crypto.subtle.importKey("raw",typeof t=="string"?eu.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},false,["sign"]);return crypto.subtle.sign("HMAC",n,eu.encode(e))}async function fg(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?eu.encode(t):t)}function Zc(t){let e=new Uint8Array(t),n="";for(let r=0;r<e.length;r++){let s=e[r];n+=dg[s>>>4&15],n+=dg[s&15];}return n}function pg(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function XT(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 [QT[i]||i,o||""]}var eu,QT,YT,tu,jo,dg,hg=I(()=>{eu=new TextEncoder,QT={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"},YT=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),tu=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 jo(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")}},jo=class{constructor({method:e,url:n,headers:r,body:s,accessKeyId:i,secretAccessKey:o,sessionToken:a,service:l,region:c,cache:u,datetime:f,signQuery:d,appendSessionToken:p,allHeaders:h,singleEncode:m}){if(n==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(s?"POST":"GET"),this.url=new URL(n),this.headers=new Headers(r||{}),this.body=s,this.accessKeyId=i,this.secretAccessKey=o,this.sessionToken=a;let g,y;(!l||!c)&&([g,y]=XT(this.url,this.headers)),this.service=l||g||"",this.region=c||y||"us-east-1",this.cache=u||new Map,this.datetime=f||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(b=>h||!YT.has(b)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(b=>b+":"+(b==="host"?this.url.host:(this.headers.get(b)||"").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,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=pg(this.encodedPath);let S=new Set;this.encodedSearch=[...this.url.searchParams].filter(([b])=>{if(!b)return false;if(this.service==="s3"){if(S.has(b))return false;S.add(b);}return true}).map(b=>b.map(_=>pg(encodeURIComponent(_)))).sort(([b,_],[E,x])=>b<E?-1:b>E?1:_<x?-1:_>x?1:0).map(b=>b.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 ks("AWS4"+this.secretAccessKey,e),i=await ks(s,this.region),o=await ks(i,this.service);r=await ks(o,"aws4_request"),this.cache.set(n,r);}return Zc(await ks(r,await this.stringToSign()))}async stringToSign(){return ["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Zc(await fg(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=Ic(await qh(this.body||""));}return e}};Hh=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var ey=Hu((LU,NR)=>{NR.exports={"dev/vite/main.tsx":{file:"assets/main-1bwWb_1q.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-BDsRycsc.css"]}};});var ku,_y,Ey,Ho=I(()=>{ku=(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))(ku||{}),_y=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=Zc(await fg(this.body||""));}return e}};dg=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];});var jy=yf((YM,vC)=>{vC.exports={"../packages/studio/upstream/apps/studio/fonts/inter/InterVariable-Italic.woff2":{file:"assets/InterVariable-Italic-DpCbqKDY.woff2",src:"../packages/studio/upstream/apps/studio/fonts/inter/InterVariable-Italic.woff2"},"../packages/studio/upstream/apps/studio/fonts/inter/InterVariable.woff2":{file:"assets/InterVariable-Dx4kXJAl.woff2",src:"../packages/studio/upstream/apps/studio/fonts/inter/InterVariable.woff2"},"../packages/studio/upstream/apps/studio/fonts/manrope/manrope-latin-ext-wght-normal.woff2":{file:"assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2",src:"../packages/studio/upstream/apps/studio/fonts/manrope/manrope-latin-ext-wght-normal.woff2"},"../packages/studio/upstream/apps/studio/fonts/manrope/manrope-latin-wght-normal.woff2":{file:"assets/manrope-latin-wght-normal-DHIcAJRg.woff2",src:"../packages/studio/upstream/apps/studio/fonts/manrope/manrope-latin-wght-normal.woff2"},"../packages/studio/upstream/apps/studio/fonts/source-code-pro/SourceCodePro-Variable-Italic.woff2":{file:"assets/SourceCodePro-Variable-Italic-eALmlzX7.woff2",src:"../packages/studio/upstream/apps/studio/fonts/source-code-pro/SourceCodePro-Variable-Italic.woff2"},"../packages/studio/upstream/apps/studio/fonts/source-code-pro/SourceCodePro-Variable.woff2":{file:"assets/SourceCodePro-Variable-BP8Zz55n.woff2",src:"../packages/studio/upstream/apps/studio/fonts/source-code-pro/SourceCodePro-Variable.woff2"},"dev/vite/main.tsx":{file:"assets/main-BnQ-v4V9.js",name:"main",src:"dev/vite/main.tsx",isEntry:true,css:["assets/main-BY4iigay.css"],assets:["assets/InterVariable-Dx4kXJAl.woff2","assets/InterVariable-Italic-DpCbqKDY.woff2","assets/manrope-latin-wght-normal-DHIcAJRg.woff2","assets/manrope-latin-ext-wght-normal-Ch3YOpNY.woff2","assets/SourceCodePro-Variable-BP8Zz55n.woff2","assets/SourceCodePro-Variable-Italic-eALmlzX7.woff2"]}};});var Xu,ab,lb,la=I(()=>{Xu=(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))(Xu||{}),ab=class extends Error{constructor(n){super(`Migration would cause data loss:
21
21
  ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
22
- `)}`);this.warnings=n;this.name="DataLossError";}},Ey=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 Ge,Js=I(()=>{Ge=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)}};});function OC(t,e){if(t.includes(Py)||e.includes(Py))return true;let n=Il(t),r=Il(e);return !n||!r?to(t)!==to(e):[...n].sort().join("\0")!==[...r].sort().join("\0")}var Py,cr,Pu=I(()=>{Un();Py="/* modified */";cr=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){let n=(e.on_update??"NO ACTION").toUpperCase(),r=(e.on_delete??"NO ACTION").toUpperCase();return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}:${n}:${r}`}diff(e,n){let r=[],s=[],i=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of e.tables){let h=n.tables.find(y=>y.name===m.name);h&&OC(m.sql,h.sql)&&r.push({type:"modified",name:m.name,sql:h.sql});}let c=e.tables.filter(m=>l.has(m.name));for(let m of c){let h=e.columns.filter(b=>b.table===m.name),y=n.columns.filter(b=>b.table===m.name),w=new Map(h.map(b=>[b.name,b])),S=new Map(y.map(b=>[b.name,b]));for(let[b,_]of S)w.has(b)||s.push({type:"added",table:m.name,name:b,column:_});for(let[b]of w)S.has(b)||s.push({type:"removed",table:m.name,name:b});for(let[b,_]of w){let E=S.get(b);if(!E)continue;let x={};$l(_.type)!==$l(E.type)&&(x.type={from:_.type,to:E.type}),!(_.is_primary_key&&E.is_primary_key)&&_.nullable!==E.nullable&&(x.nullable={from:_.nullable,to:E.nullable}),Nl(_.default_value)!==Nl(E.default_value)&&(x.default_value={from:_.default_value,to:E.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:m.name,name:b,changes:x});}}let f=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,h]of u)f.has(m)||i.push({type:"added",...h});for(let[m,h]of f)u.has(m)||i.push({type:"removed",...h});let d=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),p=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,h]of p)d.has(m)||o.push({type:"added",...h});for(let[m,h]of d)p.has(m)||o.push({type:"removed",...h});let g=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:g}}};});var PC,ur,$u=I(()=>{Ho();Fn();PC=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],ur=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 ${N(u.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===u.name);for(let p of d){let g=p.unique?"UNIQUE ":"",m=p.columns.map(h=>N(h)).join(", ");i.push({sql:`CREATE ${g}INDEX ${N(p.name)} ON ${N(u.name)} (${m});`,description:`Create index ${N(p.name)} on ${N(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(m=>m.table===u)||e.indexes.some(m=>m.table===u)||e.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:p,addedCols:g}=this.canSimpleAlter(u,e,r);if(p){for(let y of g)i.push({sql:`ALTER TABLE ${N(u)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${N(y.name)} to ${N(u)}`,type:"add_column"});let m=e.indexes.filter(y=>y.table===u&&y.type==="added"),h=e.indexes.filter(y=>y.table===u&&y.type==="removed");for(let y of h)i.push({sql:`DROP INDEX IF EXISTS ${N(y.name)};`,description:`Drop index ${N(y.name)}`,type:"drop_index"});for(let y of m){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(u)} (${S});`,description:`Create index ${N(y.name)} on ${N(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,n,r,e);i.push(...m.steps),o.push(...m.warnings);}}for(let u of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${N(u.name)};`,description:`Drop table ${N(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(y=>y.name===e);if(!a)return {steps:i,warnings:o};let l=`_${e}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${N(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${N(l)}`,type:"create_table"});let f=n.columns.filter(y=>y.table===e).map(y=>y.name),u=r.columns.filter(y=>y.table===e).map(y=>y.name),d=f.filter(y=>u.includes(y));if(d.length>0){let y=d.map(w=>N(w)).join(", ");i.push({sql:`INSERT INTO ${N(l)} (${y})
22
+ `)}`);this.warnings=n;this.name="DataLossError";}},lb=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 Xe,ni=I(()=>{Xe=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)}};});function kk(t,e){if(t.includes(yb)||e.includes(yb))return true;let n=Zl(t),r=Zl(e);return !n||!r?ho(t)!==ho(e):[...n].sort().join("\0")!==[...r].sort().join("\0")}var yb,pr,nf=I(()=>{Hn();yb="/* modified */";pr=class{makeIndexKey(e){return `${e.table}:${e.name}:${e.unique}:${e.columns.join(",")}`}makeForeignKeyKey(e){let n=(e.on_update??"NO ACTION").toUpperCase(),r=(e.on_delete??"NO ACTION").toUpperCase();return `${e.table}:${e.column}:${e.ref_table}:${e.ref_column}:${n}:${r}`}diff(e,n){let r=[],s=[],i=[],o=[],a=new Set(e.tables.map(m=>m.name)),l=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of e.tables)l.has(m.name)||r.push({type:"removed",name:m.name});for(let m of e.tables){let g=n.tables.find(y=>y.name===m.name);g&&kk(m.sql,g.sql)&&r.push({type:"modified",name:m.name,sql:g.sql});}let c=e.tables.filter(m=>l.has(m.name));for(let m of c){let g=e.columns.filter(b=>b.table===m.name),y=n.columns.filter(b=>b.table===m.name),w=new Map(g.map(b=>[b.name,b])),S=new Map(y.map(b=>[b.name,b]));for(let[b,_]of S)w.has(b)||s.push({type:"added",table:m.name,name:b,column:_});for(let[b]of w)S.has(b)||s.push({type:"removed",table:m.name,name:b});for(let[b,_]of w){let E=S.get(b);if(!E)continue;let x={};Xl(_.type)!==Xl(E.type)&&(x.type={from:_.type,to:E.type}),!(_.is_primary_key&&E.is_primary_key)&&_.nullable!==E.nullable&&(x.nullable={from:_.nullable,to:E.nullable}),ec(_.default_value)!==ec(E.default_value)&&(x.default_value={from:_.default_value,to:E.default_value}),Object.keys(x).length>0&&s.push({type:"modified",table:m.name,name:b,changes:x});}}let u=new Map(e.indexes.map(m=>[this.makeIndexKey(m),m])),f=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,g]of f)u.has(m)||i.push({type:"added",...g});for(let[m,g]of u)f.has(m)||i.push({type:"removed",...g});let d=new Map(e.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),p=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,g]of p)d.has(m)||o.push({type:"added",...g});for(let[m,g]of d)p.has(m)||o.push({type:"removed",...g});let h=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:h}}};});var Ak,mr,rf=I(()=>{la();qn();Ak=["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 f of e.tables.filter(d=>d.type==="added")){i.push({sql:`${f.sql};`,description:`CREATE TABLE ${F(f.name)}`,type:"create_table"});let d=r.indexes.filter(p=>p.table===f.name);for(let p of d){let h=p.unique?"UNIQUE ":"",m=p.columns.map(g=>F(g)).join(", ");i.push({sql:`CREATE ${h}INDEX ${F(p.name)} ON ${F(f.name)} (${m});`,description:`Create index ${F(p.name)} on ${F(f.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(f=>f.name)),l=new Set(r.tables.map(f=>f.name)),c=new Set(e.tables.filter(f=>f.type==="modified").map(f=>f.name)),u=[...a].filter(f=>l.has(f));for(let f of u){if(!(c.has(f)||e.columns.some(m=>m.table===f)||e.indexes.some(m=>m.table===f)||e.foreign_keys.some(m=>m.table===f)))continue;let{canAlter:p,addedCols:h}=this.canSimpleAlter(f,e,r);if(p){for(let y of h)i.push({sql:`ALTER TABLE ${F(f)} ADD COLUMN ${this.columnDef(y)};`,description:`Add column ${F(y.name)} to ${F(f)}`,type:"add_column"});let m=e.indexes.filter(y=>y.table===f&&y.type==="added"),g=e.indexes.filter(y=>y.table===f&&y.type==="removed");for(let y of g)i.push({sql:`DROP INDEX IF EXISTS ${F(y.name)};`,description:`Drop index ${F(y.name)}`,type:"drop_index"});for(let y of m){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>F(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${F(y.name)} ON ${F(f)} (${S});`,description:`Create index ${F(y.name)} on ${F(f)}`,type:"add_index"});}}else {let m=this.rebuildTable(f,n,r,e);i.push(...m.steps),o.push(...m.warnings);}}for(let f of e.tables.filter(d=>d.type==="removed"))i.push({sql:`DROP TABLE ${F(f.name)};`,description:`Drop table ${F(f.name)}`,type:"drop_table"}),o.push({table:f.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(e,n,r,s){let i=[],o=[],a=r.tables.find(y=>y.name===e);if(!a)return {steps:i,warnings:o};let l=`_${e}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${e}"|${e})`,"i"),`$1${F(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${F(l)}`,type:"create_table"});let u=n.columns.filter(y=>y.table===e).map(y=>y.name),f=r.columns.filter(y=>y.table===e).map(y=>y.name),d=u.filter(y=>f.includes(y));if(d.length>0){let y=d.map(w=>F(w)).join(", ");i.push({sql:`INSERT INTO ${F(l)} (${y})
24
24
  SELECT ${y}
25
- FROM ${N(e)};`,description:`Copy data from ${N(e)} to ${N(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${N(e)};`,description:`Drop old table ${N(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${N(l)} RENAME TO ${N(e)};`,description:`Rename ${N(l)} to ${N(e)}`,type:"rename_table"});let p=r.indexes.filter(y=>y.table===e);for(let y of p){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>N(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${N(y.name)} ON ${N(e)} (${S});`,description:`Recreate index ${N(y.name)} on ${N(e)}`,type:"add_index"});}let g=r.triggers?.filter(y=>y.table===e)??[];for(let y of g)i.push({sql:`${y.sql};`,description:`Recreate trigger ${N(y.name)} on ${N(e)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===e&&y.type==="removed");for(let y of m)o.push({table:e,reason:`column "${y.name}" will be dropped`});let h=s.columns.filter(y=>y.table===e&&y.type==="modified");for(let y of h)y.changes?.type&&o.push({table:e,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:e,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(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 PC.includes(n)}columnDef(e){let n=e.column,r=`${N(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function dr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var qy=I(()=>{});function zs(t){if("String"in t)return t.String.sval}function At(t){return t.map(zs).filter(e=>e!=null)}function zt(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function Qo(t){return QuoteUtils.quoteIdentifier(t)}function pr(t){return Object.keys(t)[0]}function Hy(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 _n=I(()=>{});function Ky(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=WC[e];if(!n)throw new En(`Unsupported PostgreSQL type: "${t}"`);return n}function Yo(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function Xo(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function Zo(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var En,L,WC,Wy,KC,ea,mr=I(()=>{_n();En=class extends Error{},L=class extends En{constructor(n,r){super(r??`Unsupported node type: ${pr(n)}`);this.node=n;}},WC={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"},Wy=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];KC={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ea=new Map(Object.entries(KC));});var ze,xn,ju=I(()=>{_n();mr();ze=class extends L{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},xn=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 ze({[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 ze({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?zs(n):void 0;if(!r)throw new ze({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 ze({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]?zs(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 ze({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 ze({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 ze({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 g=this.deparseValue(p.val);Array.isArray(g)?i.push(...g.map(String)):g!=null&&g!==""&&i.push(String(g));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),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 ze({FuncCall:e},`FuncCall: ${At(e.funcname??[]).join(".")}`)}ColumnRef(e){let n=At(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 ze({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new ze({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=At(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]?zs(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function Vy(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=At(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=At(r.vals),o=s.toLowerCase();e.set(o,i),o.startsWith("public.")&&e.set(o.slice(7),i);}return e}function Vs(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function Qy(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=Hy(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function Gy(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&e.push(s.rolename);}return {roles:e,implicitPublic:n}}function ta(t,e){return t&&t.length>0?t:e}function Lu(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&ta(r.data.schema,n)===ta(e.schema,n))}function Fu(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function zy(t,e,n,r){return t.data.table===e&&ta(t.data.schema,r)===ta(n,r)}function Yy(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,s=new xn,i=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",f=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",p=l.permissive===true,{roles:g,implicitPublic:m}=Gy(l.roles),h=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let S=f?`${f}.${c}`:c,b=l.policy_name??"",_=`${S}::${b}`;if(!Jy.has(_)){Jy.add(_);let E=JSON.stringify(h)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(E)||console.warn(`[supalite] policy "${b}" on "${S}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let w=new Ge({name:l.policy_name??"",table:c,schema:f,command:d,permissive:p,roles:g,using:h,withCheck:y});o.push(w);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let f=At(c.List.items??[]),u=f[f.length-1],d=f[f.length-2],p=f.length>=3?f[f.length-3]:void 0;if(u&&d){let g=Lu(o,{name:u,table:d,schema:p},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw Fu(u,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",f=l.table?.relname??"",u=l.table?.schemaname,d=Lu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw Fu(c,f);continue}let p=o[d].data,g=l.roles?Gy(l.roles).roles:p.roles,m=l.qual?s.deparse(l.qual):p.using,h=l.with_check?s.deparse(l.with_check):p.withCheck;o[d]=new Ge({...p,roles:g,using:m,withCheck:h});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",f=l.relation?.relname??"",u=l.relation?.schemaname,d=Lu(o,{name:c,table:f,schema:u},n);if(d===-1){if(r)throw Fu(c,f);continue}l.newname&&(o[d]=new Ge({...o[d].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",f=l.newname??"",u=l.relation?.schemaname;if(c&&f&&c!==f){i.delete(c)&&i.add(f);for(let d=0;d<o.length;d++)zy(o[d],c,u,n)&&(o[d]=new Ge({...o[d].data,table:f}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=At(l.List.items??[]),f=c[c.length-1],u=c.length>=2?c[c.length-2]:void 0;if(f){i.delete(f);for(let d=o.length-1;d>=0;d--)zy(o[d],f,u,n)&&o.splice(d,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let f of l.cmds??[]){if(!("AlterTableCmd"in f))continue;let u=f.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(c):u==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function Xy(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 at(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(R=>R.String?.sval||R.String?.str).filter(Boolean),d=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):void 0;if(!d)continue;let p=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=R=>g[R]?.A_Const?.ival?.ival??g[R]?.A_Const?.val?.ival?.ival,h={isArray:p};if(Xo(d)&&g.length>0){let R=m(0);typeof R=="number"&&R>0&&(h.lengthConstraint=R);}if(Zo(d)&&g.length>=2){let R=m(0),U=m(1);typeof R=="number"&&typeof U=="number"&&R>0&&U>=0&&(h.numericPrecision={precision:R,scale:U});}let y=Vs(e,d);y&&(h.enumValues=y);let w=Array.isArray(c.constraints)?c.constraints:[],S=w.some(R=>R.Constraint?.contype==="CONSTR_PRIMARY"),b=Yo(d)||w.some(R=>R.Constraint?.contype==="CONSTR_IDENTITY"),_=w.some(R=>R.Constraint?.contype==="CONSTR_NOTNULL"),E=w.find(R=>R.Constraint?.contype==="CONSTR_UNIQUE"),x=w.find(R=>R.Constraint?.contype==="CONSTR_GENERATED"),O=w.find(R=>R.Constraint?.contype==="CONSTR_FOREIGN"),v=w.find(R=>R.Constraint?.contype==="CONSTR_CHECK"),P;if(O){let R=O.Constraint,U=R.pktable?.relname,J=R.pktable?.schemaname,F=R.pk_attrs?.[0]?.String?.sval;U&&F&&(P={refSchema:J,refTable:U,refColumn:F,constraintName:R.conname||void 0});}let C={schema:o,table:i,column:f,pgTypeName:d,nullable:!_&&!S,defaultValue:null,defaultFn:null,isPrimaryKey:S,isUnique:!!E,isSerial:b,isGenerated:!!x,fkRef:P,hasCheck:!!v,checkConstraintName:v?.Constraint?.conname||void 0,uniqueConstraintName:E?.Constraint?.conname||void 0};a.set(f,We(C,h));}n.set(`${o}.${i}`,a);}return n}function Zy(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){let f=o.ColumnDef,u=f?.colname;if(!u)continue;for(let d of f.constraints??[]){let p=d?.Constraint;if(!p||p.contype!=="CONSTR_FOREIGN")continue;let g=p.pktable?.relname;if(!g)continue;let m=(p.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);e.push({schema:i,table:s,kind:"foreign_key",name:p.conname||void 0,columns:[u],refSchema:p.pktable?.schemaname,refTable:g,refColumns:m});}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 eb(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 Jy,Uu=I(()=>{ju();_n();Js();Xl();mr();Jy=new Set;});var na,tb=I(()=>{mr();_n();na=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=pr(e),r=ea.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 GC,zC,VC,QC,hr,ra,nb=I(()=>{mr();GC=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],zC=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,VC=/^RETURN\s+(NEW|OLD)$/i,QC=/^(INSERT|UPDATE|DELETE)\b/i,hr=class extends En{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},ra=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(VC);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(zC);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(QC.test(a)){s.push({type:"dml",sql:a});continue}throw new hr(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new En("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 hr('"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 hr("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&&GC.includes(n))throw new hr(`"${n}" is not translatable to SQLite`,e)}};});function tk(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"&&ek.has(e.objtype)}var ek,sa,rb=I(()=>{mr();Uu();_n();_n();tb();Yr();nb();Ho();Pu();$u();Fn();ro();Ql();ek=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);sa=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new ra;introspection;functionResolution;serialColumns;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new na(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=pr(e);if(r==="GrantStmt"&&tk(e))return "";let s=ea.get(r);if(s){if(s.react==="error")throw new L({[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 L({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new L({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 L({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 L({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=>Ki(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new L({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||Vs(this.enums,s)?"TEXT":Ky(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,f=false;if(e.typeName){let u=e.typeName.names?.map(g=>g.String?.sval||g.String?.str).filter(Boolean);c=u&&u.length>0?u.length===2&&u[0]==="pg_catalog"?u[1]:u.join("."):null,i=!!(c&&Yo(c))||this.serialColumns.has(e),f=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=g=>d[g]?.A_Const?.ival?.ival??d[g]?.A_Const?.val?.ival?.ival;if(c&&Xo(c)&&d.length>0){let g=p(0);typeof g=="number"&&g>0&&(a={maxLen:g});}if(c&&Zo(c)&&d.length>=2){let g=p(0),m=p(1);typeof g=="number"&&typeof m=="number"&&g>0&&m>=0&&(l={precision:g,scale:m});}if(e.constraints){let g=Array.isArray(e.constraints)?e.constraints:[];o=g.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),g.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let u=Array.isArray(e.constraints)?e.constraints:[],d=n.spawn("ColumnDef",{isColumnConstraint:true}),p=u.map(m=>this.visit(m,d));r.push(...p.filter(Boolean));let g=u.some(m=>m.Constraint?.contype==="CONSTR_CHECK");i&&o&&!g?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let u={isArray:f};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let d=Vs(this.enums,c);d&&(u.enumValues=d);let m=We({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.unwrapConstCast(e.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",Qo(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 (${zt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${zt(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 L({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=Vl(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=so[i];if(c?.sqlite){let f=c.sqlite();return f.includes("(")?f:`${f}(${a.join(", ")})`}}}throw new L({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 L({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new L({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(e.kind==="AEXPR_OP_ANY"&&(e.name?.[0]?.String?.sval||e.name?.[0]?.String?.str)==="="&&e.lexpr&&e.rexpr&&"A_ArrayExpr"in e.rexpr){let s=zt(e.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(e.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new L({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 L({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 L({A_Expr:e},"A_Expr missing left or right expression");if(!Wy.includes(r.toUpperCase()))throw new L({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(Qo(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(Qo(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(" ")}constFoldCategory(e){if(!e?.names||e.arrayBounds&&e.arrayBounds.length>0)return null;let n=e.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return Vs(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(e,n){if(e.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in e?r==="text":"ival"in e?r==="integer":"fval"in e?r==="real":"boolval"in e?r==="boolean":false:false}findUnderlyingConst(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(e,n){let r=[];for(let s of e){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}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 L({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=zt(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=zt(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","AT_ChangeOwner"],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 L({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 L({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
- `)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new L({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);if(e.subtype==="AT_AddColumn"&&e.def&&"ColumnDef"in e.def){let s=this.ColumnDef(e.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=e.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}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 L({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new L({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new L({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=zt(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new L({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new L({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new L({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 L({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=zt(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new L({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 L({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 L({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new L({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 L({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 L({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 L({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 L({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
- `)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,f)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??f)}`),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 L({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");if(e.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new L({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new L({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 this.foldDropObjectSchemas(e),super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new L({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(e){let n=e.removeType==="OBJECT_TRIGGER"?3:2;for(let r of e.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}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 cr,i=new ur,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=`${N(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 (${N(u.column)}) REFERENCES ${N(u.ref_table)}(${N(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 ${N(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){if(!e.def)return null;let n=this.unwrapConstCast(e.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function sb(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function nk(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function rk(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function ib(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!nk(s));r.length!==n.length?(t.constraints=r,e.add(t)):rk(t)&&e.add(t);}function sk(t,e){let n=e?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=t.tableElts??[];return r==="CONSTR_PRIMARY"&&ob(t,n)||r==="CONSTR_FOREIGN"&&ab(t,n)||(s.push(e),t.tableElts=s),true}function ob(t,e){let n=(e.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function ab(t,e){let n=(e.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:e}],true}function ik(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!ob(t,s)});n.length!==e.length&&(t.tableElts=n);}function ok(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!ab(t,s)});n.length!==e.length&&(t.tableElts=n);}function lb(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(sb(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&ib(o.ColumnDef,e);ik(i),ok(i);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(sb(i.relation)),a=i.cmds??[],l=[];for(let c of a){let f=c.AlterTableCmd;f?.subtype==="AT_AddColumn"&&f.def&&"ColumnDef"in f.def&&ib(f.def.ColumnDef,e),!(o&&f?.subtype==="AT_AddConstraint"&&f.def&&sk(o,f.def))&&l.push(c);}i.cmds=l;}return e}var cb=I(()=>{});var db={};Zs(db,{Policy:()=>Ge,deparseDdl:()=>Mu,deparseExpression:()=>lk,deparsePostgresDdl:()=>ak,deparseSelect:()=>ck,parse:()=>dr,parseExpression:()=>fb,translatePostgresDdl:()=>ub});async function ub(t,e={}){let n=await dr(t);return Mu(n,e).ddl}async function ak(t,e={}){let n=await dr(t);return {ast:n,...Mu(n,e)}}function Mu(t,e={}){let n=lb(t),r=Vy(t),s=Xy(t,r),i=Qy(t),o=Zy(t),a=eb(t),l=new sa(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:f}=Yy(t,{defaultSchema:e.defaultSchema,validateMutations:e.strict});if(e.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!f.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:f,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function fb(t){let n=(await dr(`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 lk(t){let e=await fb(t);return new xn().deparse(e)}async function ck(t){let n=(await dr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new xn().deparse(n)}var Bu=I(()=>{qy();rb();cb();ju();Uu();Js();});function Wu(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 Ku(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Wu(Object(n),true).forEach(function(r){Tb(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Wu(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function Tb(t,e,n){return e=Rb(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function Rb(t){var e=Cb(t,"string");return typeof e=="symbol"?e:String(e)}function Cb(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 kb=Ju({}),je=kb;function Ju(t){return e.withOptions=n=>Ju(Ku(Ku({},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?vb(r[u],l):r[u];l+=p;}}let c=l.split(`
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(`
25
+ FROM ${F(e)};`,description:`Copy data from ${F(e)} to ${F(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${F(e)};`,description:`Drop old table ${F(e)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${F(l)} RENAME TO ${F(e)};`,description:`Rename ${F(l)} to ${F(e)}`,type:"rename_table"});let p=r.indexes.filter(y=>y.table===e);for(let y of p){let w=y.unique?"UNIQUE ":"",S=y.columns.map(b=>F(b)).join(", ");i.push({sql:`CREATE ${w}INDEX ${F(y.name)} ON ${F(e)} (${S});`,description:`Recreate index ${F(y.name)} on ${F(e)}`,type:"add_index"});}let h=r.triggers?.filter(y=>y.table===e)??[];for(let y of h)i.push({sql:`${y.sql};`,description:`Recreate trigger ${F(y.name)} on ${F(e)}`,type:"create_trigger"});let m=s.columns.filter(y=>y.table===e&&y.type==="removed");for(let y of m)o.push({table:e,reason:`column "${y.name}" will be dropped`});let g=s.columns.filter(y=>y.table===e&&y.type==="modified");for(let y of g)y.changes?.type&&o.push({table:e,reason:`column "${y.name}" type changes from ${y.changes.type.from} to ${y.changes.type.to}`}),y.changes?.nullable&&!y.changes.nullable.to&&o.push({table:e,reason:`column "${y.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(e,n,r){let s=n.columns.filter(f=>f.table===e),i=s.filter(f=>f.type==="added"),o=s.filter(f=>f.type==="removed"),a=s.filter(f=>f.type==="modified"),l=n.foreign_keys.some(f=>f.table===e);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=r.tables.find(f=>f.name===e);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(f=>{let d=f.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 Ak.includes(n)}columnDef(e){let n=e.column,r=`${F(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});async function gr(t){let{parse:e}=await import('pgsql-parser');return e(t)}var Eb=I(()=>{});function yr(t){if("String"in t)return t.String.sval}function ne(t){return t.map(yr).filter(e=>e!=null)}function Yt(t){return t==null?[]:t.List!==void 0?t.List.items||[]:Array.isArray(t)?t:[t]}function ri(t){return QuoteUtils.quoteIdentifier(t)}function br(t){return Object.keys(t)[0]}function xb(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 Cn=I(()=>{});function Rb(t){let e=t.toLowerCase().trim();if(e.startsWith("_")||e.endsWith("[]"))return "TEXT";let n=jk[e];if(!n)throw new kn(`Unsupported PostgreSQL type: "${t}"`);return n}function ma(t){let e=t.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(e)}function ha(t){let e=t.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(e)}function ga(t){let e=t.toLowerCase();return ["numeric","decimal"].includes(e)}var kn,L,jk,Tb,Lk,ya,wr=I(()=>{Cn();kn=class extends Error{},L=class extends kn{constructor(n,r){super(r??`Unsupported node type: ${br(n)}`);this.node=n;}},jk={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"},Tb=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];Lk={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},ya=new Map(Object.entries(Lk));});function Xt(t){return t!=null&&typeof t=="object"&&t.kind==="storage.foldername"}function Zt(t){if(t==null||typeof t!="object")return false;let e=t.kind;return e==="storage.filename"||e==="storage.extension"}function si(t,e,n){return {$storageObject:{function:t.kind.slice(8),column:t.column,ops:{[e]:n}}}}function Fk(t){return t.startsWith("storage.")?t.slice(8):t}function Uk(t){return t==="{{storage.operation}}"}function Mk(t){switch(t){case "~~":return "$like";case "!~~":return "$notLike";case "~~*":return "$ilike";case "!~~*":return "$notIlike";default:return}}function lf(t){switch(t){case "$gt":return "$lt";case "$gte":return "$lte";case "$lt":return "$gt";case "$lte":return "$gte";default:return t}}function ba(t,e){return t?"TypeCast"in t&&t.TypeCast.arg?ba(t.TypeCast.arg,e):"A_Const"in t?true:typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"):false}var re,An,cf=I(()=>{Cn();wr();re=class extends L{constructor(e,n){super(e,`Unsupported expression: ${n}`);}},An=class{deparse(e){if("A_Const"in e){let s=e.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}if("FuncCall"in e){let s=this.storageOperationPredicate(e.FuncCall);if(s)return s}let n=Object.keys(e)[0],r=this[n];if(!r)throw new re({[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_Indirection"in e)return this.A_Indirection(e.A_Indirection);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 re({[n]:e},`deparseValue: ${n}`)}A_Expr(e){if(e.kind==="AEXPR_OP"){let n=e.name?.[0],r=n?yr(n):void 0;if(!r)throw new re({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 re({A_Expr:e},`Unsupported operator: ${r}`);if(Xt(i)&&Xt(o))throw new re({A_Expr:e},"comparisons between storage.foldername expressions are unsupported");if(Xt(i))return {$storageFolder:{column:i.column,index:i.index,ops:{[a]:o}}};if(Xt(o)){if(!ba(e.lexpr,i))throw new re({A_Expr:e},"storage.foldername RHS comparisons require a literal or auth placeholder");return {$storageFolder:{column:o.column,index:o.index,ops:{[lf(a)]:i}}}}if(Zt(i)&&Zt(o))throw new re({A_Expr:e},"comparisons between Storage object helper expressions are unsupported");if(Zt(i))return si(i,a,o);if(Zt(o)){if(!ba(e.lexpr,i))throw new re({A_Expr:e},"Storage object helper RHS comparisons require a literal or auth placeholder");return si(o,lf(a),i)}if(Uk(o)){if(!ba(e.lexpr,i))throw new re({A_Expr:e},"storage.operation RHS comparisons require a literal or auth placeholder");return {[o]:{[lf(a)]:i}}}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,s=e.kind==="AEXPR_ILIKE"?"~~*":"~~",i=e.name?.[0]?yr(e.name[0])??s:s,o=Mk(i);if(!o)throw new re({A_Expr:e},`Unsupported pattern operator: ${i}`);if(Xt(r))throw new re({A_Expr:e},"storage.foldername on the right of a pattern predicate is unsupported");if(Xt(n))return {$storageFolder:{column:n.column,index:n.index,ops:{[o]:r}}};if(Zt(r))throw new re({A_Expr:e},"Storage object helpers on the right of a pattern predicate are unsupported");return Zt(n)?si(n,o,r):{[n]:{[o]:r}}}if(e.kind==="AEXPR_IN"){let n=e.lexpr?this.deparseValue(e.lexpr):void 0,s=(e.name?.[0]?yr(e.name[0]):"=")==="<>"?"$notIn":"$in",i=e.rexpr&&"List"in e.rexpr&&e.rexpr.List.items?e.rexpr.List.items.map(o=>this.deparseValue(o)):[];return Xt(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[s]:i}}}:Zt(n)?si(n,s,i):{[n]:{[s]:i}}}throw new re({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 re({BoolExpr:e},`BoolExpr op: ${e.boolop}`)}}NullTest(e){let n=e.arg?this.deparseValue(e.arg):void 0,r=e.nulltesttype==="IS_NULL"?"$is":"$isNot";return Xt(n)?{$storageFolder:{column:n.column,index:n.index,ops:{[r]:null}}}:Zt(n)?si(n,r,null):{[n]:{[r]: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 re({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 h=this.deparseValue(p.val);Array.isArray(h)?i.push(...h.map(String)):h!=null&&h!==""&&i.push(String(h));}}let o=e.whereClause?this.deparse(e.whereClause):void 0,a=this.deparseSortClause(e.sortClause),l=this.deparseLimit(e.limitCount),c=this.deparseLimit(e.limitOffset),u=this.deparseGroupClause(e.groupClause),f={type:"query",from:n,select:i};return r&&(f.schema=r),Object.keys(s).length>0&&(f.join=s),o&&(f.where=o),a.length>0&&(f.order=a),l!==void 0&&(f.limit=l),c!==void 0&&(f.offset=c),u.length>0&&(f.group=u),f}FuncCall(e){let n=this.isAuthFunc(e.funcname??[]);if(n)return n;let r=ne(e.funcname??[]);if(r.length===2&&r[0]==="storage"&&r[1]==="operation"&&(e.args?.length??0)===0)return "{{storage.operation}}";if(r.length===2&&r[0]==="storage"&&(r[1]==="filename"||r[1]==="extension")){let s=e.args?.[0];if(e.args?.length!==1||!s||!("ColumnRef"in s))throw new re({FuncCall:e},`storage.${r[1]} requires one column argument`);let i=this.ColumnRef(s.ColumnRef);if(i!=="name")throw new re({FuncCall:e},`only storage.${r[1]}(name) is supported`);return {kind:`storage.${r[1]}`,column:i}}throw new re({FuncCall:e},`FuncCall: ${ne(e.funcname??[]).join(".")}`)}storageOperationPredicate(e){let n=ne(e.funcname??[]);if(n.length!==2||n[0]!=="storage"||n[1]!=="allow_only_operation"&&n[1]!=="allow_any_operation")return null;let r=e.args?.[0],s;if(n[1]==="allow_only_operation"&&e.args?.length===1&&r)s=[this.deparseValue(r)];else if(n[1]==="allow_any_operation"&&e.args?.length===1&&r)if("A_ArrayExpr"in r)s=(r.A_ArrayExpr.elements??[]).map(o=>this.deparseValue(o));else if(this.deparseValue(r)===null)s=[];else throw new re({FuncCall:e},`storage.${n[1]} requires its canonical operation argument`);else throw new re({FuncCall:e},`storage.${n[1]} requires its canonical operation argument`);if(!s.every(o=>o===null||typeof o=="string"))throw new re({FuncCall:e},`storage.${n[1]} requires text operation names`);let i=s.filter(o=>typeof o=="string"&&o!=="").map(Fk);return n[1]==="allow_only_operation"&&i.length===0?{$always:false}:{"{{storage.normalizedOperation}}":n[1]==="allow_only_operation"?{$eq:i[0]}:{$in:i.filter(Boolean)}}}ColumnRef(e){let n=ne(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 re({A_Const:e},"A_Const: unknown variant")}TypeCast(e){if(!e.arg)throw new re({TypeCast:e},"TypeCast: missing arg");return this.deparseValue(e.arg)}A_Indirection(e){let n=e.arg?.FuncCall,r=n?ne(n.funcname??[]):[],s=e.indirection??[],i=s[0]?.A_Indices,o=i?.uidx?.A_Const,a=o?this.A_Const(o):void 0,l=n?.args?.[0];if(r.length!==2||r[0]!=="storage"||r[1]!=="foldername"||!l||!("ColumnRef"in l)||s.length!==1||i?.is_slice===true||i?.lidx!=null||typeof a!="number"||!Number.isInteger(a)||a<1)throw new re({A_Indirection:e},"only indexed storage.foldername(column) expressions are supported");let c=this.ColumnRef(l.ColumnRef);if(c!=="name")throw new re({A_Indirection:e},"only indexed storage.foldername(name) expressions are supported");return {kind:"storage.foldername",column:c,index:a}}BooleanTest(e){let n=e.arg?this.deparseValue(e.arg):void 0;return e.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(e){let n={};if(e.length===0)return {from:"",join:n};let r=e[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(e,n){let r={from:""};if(e.larg)if("RangeVar"in e.larg){let s=e.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in e.larg&&(r=this.walkJoinExpr(e.larg.JoinExpr,n));if(e.rarg&&"RangeVar"in e.rarg){let s=e.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=e.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};e.quals&&(l.on=this.deparse(e.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(e){if(!e)return [];let n=[];for(let r of e){if(!("SortBy"in r))continue;let s=r.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),n.push(a);}return n}deparseLimit(e){if(!e)return;let n=this.deparseValue(e);return typeof n=="number"?n:Number(n)}deparseGroupClause(e){return e?e.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(e){let n=ne(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]?yr(e.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=e.rexpr&&"A_Const"in e.rexpr?e.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(e.lexpr&&"FuncCall"in e.lexpr)return this.isAuthFunc(e.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(e.lexpr&&"A_Expr"in e.lexpr){let s=this.isJwtAccessor(e.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}return null}mapOperator(e){switch(e){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});function vb(t){let e=new Map,n=i=>{let o=i.toLowerCase();return o.startsWith("public.")?[o,o.slice(7)]:o.includes(".")?[o]:[o,`public.${o}`]},r=(i,o)=>{for(let a of n(i))e.set(a,o);},s=i=>{for(let o of n(i))e.delete(o);};for(let i of t.stmts??[])if(i.stmt){if("CreateEnumStmt"in i.stmt){let o=i.stmt.CreateEnumStmt,a=ne(o.typeName??[]).join(".");a&&o.vals&&r(a,ne(o.vals));continue}if("AlterEnumStmt"in i.stmt){let o=i.stmt.AlterEnumStmt,a=ne(o.typeName??[]).join("."),l=it(e,a);if(!a||!l||!o.newVal)continue;let c=[...l];if(o.oldVal){let d=c.indexOf(o.oldVal);d!==-1&&(c[d]=o.newVal),r(a,c);continue}if(l.includes(o.newVal))continue;let u=o.newValNeighbor?c.indexOf(o.newValNeighbor):-1,f=u===-1?c.length:u+(o.newValIsAfter===true?1:0);c.splice(f,0,o.newVal),r(a,c);continue}if("RenameStmt"in i.stmt&&i.stmt.RenameStmt.renameType==="OBJECT_TYPE"){let o=i.stmt.RenameStmt,a=o.object&&"List"in o.object?ne(o.object.List.items??[]):[],l=a.join("."),c=it(e,l);if(!l||!o.newname||!c)continue;s(l),r([...a.slice(0,-1),o.newname].join("."),c);continue}if("DropStmt"in i.stmt&&i.stmt.DropStmt.removeType==="OBJECT_TYPE")for(let o of i.stmt.DropStmt.objects??[])"TypeName"in o&&s(ne(o.TypeName.names??[]).join("."));}return e}function it(t,e){let n=e.toLowerCase(),r=t.get(n);return r||(n.startsWith("public.")?t.get(n.slice(7)):t.get(`public.${n}`))}function Ob(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=xb(r.args?.[0]??{});e.set(s,{value:i,local:r.is_local});}return e}function kb(t){let e=[],n=false;for(let r of t??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&e.push(s.rolename);}return {roles:e,implicitPublic:n}}function wa(t,e){return t&&t.length>0?t:e}function uf(t,e,n){return t.findIndex(r=>r.data.name===e.name&&r.data.table===e.table&&wa(r.data.schema,n)===wa(e.schema,n))}function ff(t,e){return new Error(`policy "${t}" for table "${e}" does not exist`)}function Ab(t,e,n,r){return t.data.table===e&&wa(t.data.schema,r)===wa(n,r)}function Pb(t,e={}){let n=e.defaultSchema||"public",r=e.validateMutations===true,s=new An,i=new Set,o=[];for(let a of t.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",u=l.table?.schemaname,f={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?f[l.cmd_name]??"ALL":"ALL",p=l.permissive===true,{roles:h,implicitPublic:m}=kb(l.roles),g=l.qual?s.deparse(l.qual):void 0,y=l.with_check?s.deparse(l.with_check):void 0;if(m){let S=u?`${u}.${c}`:c,b=l.policy_name??"",_=`${S}::${b}`;if(!Cb.has(_)){Cb.add(_);let E=JSON.stringify(g)+JSON.stringify(y);/\{\{auth\.(uid|jwt|role)/i.test(E)||console.warn(`[supalite] policy "${b}" on "${S}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let w=new Xe({name:l.policy_name??"",table:c,schema:u,command:d,permissive:p,roles:h,using:g,withCheck:y});o.push(w);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let u=ne(c.List.items??[]),f=u[u.length-1],d=u[u.length-2],p=u.length>=3?u[u.length-3]:void 0;if(f&&d){let h=uf(o,{name:f,table:d,schema:p},n);if(h!==-1)o.splice(h,1);else if(r&&!l.missing_ok)throw ff(f,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",f=l.table?.schemaname,d=uf(o,{name:c,table:u,schema:f},n);if(d===-1){if(r)throw ff(c,u);continue}let p=o[d].data,h=l.roles?kb(l.roles).roles:p.roles,m=l.qual?s.deparse(l.qual):p.using,g=l.with_check?s.deparse(l.with_check):p.withCheck;o[d]=new Xe({...p,roles:h,using:m,withCheck:g});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",f=l.relation?.schemaname,d=uf(o,{name:c,table:u,schema:f},n);if(d===-1){if(r)throw ff(c,u);continue}l.newname&&(o[d]=new Xe({...o[d].data,name:l.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let l=a.stmt.RenameStmt,c=l.relation?.relname??"",u=l.newname??"",f=l.relation?.schemaname;if(c&&u&&c!==u){i.delete(c)&&i.add(u);for(let d=0;d<o.length;d++)Ab(o[d],c,f,n)&&(o[d]=new Xe({...o[d].data,table:u}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let l of a.stmt.DropStmt.objects??[]){if(!("List"in l))continue;let c=ne(l.List.items??[]),u=c[c.length-1],f=c.length>=2?c[c.length-2]:void 0;if(u){i.delete(u);for(let d=o.length-1;d>=0;d--)Ab(o[d],u,f,n)&&o.splice(d,1);}}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt,c=l.relation?.relname??"";for(let u of l.cmds??[]){if(!("AlterTableCmd"in u))continue;let f=u.AlterTableCmd.subtype;f==="AT_EnableRowSecurity"?i.add(c):f==="AT_DisableRowSecurity"&&i.delete(c);}}}return {policies:o,tables:i}}function Sr(t,e=new Set){if(Array.isArray(t)){for(let s of t)Sr(s,e);return e}if(!t||typeof t!="object")return e;let n=t,r=n.ColumnRef;if(r?.fields){let s=ne(r.fields),i=s[s.length-1];i&&i!=="*"&&e.add(i);}for(let s of Object.values(n))Sr(s,e);return e}function ve(t,e,n){if(n.length===0)return;let r=e==="unique"?"key":e==="foreign_key"?"fkey":"check";return `${t}_${n.join("_")}_${r}`}function Sa(t,e,n){let r=new Map;for(let s of t.stmts??[])if(s.stmt){if("CreateStmt"in s.stmt){let i=s.stmt.CreateStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public";if(!o)continue;let l=`${a}.${o}`;if(i.if_not_exists&&r.has(l))continue;let c=new Qe(o,a);for(let f of i.tableElts??[]){if(!("ColumnDef"in f))continue;let d=f.ColumnDef,p=d.colname;if(!p)continue;let h=d.typeName?.names?.map(C=>C.String?.sval||C.String?.str).filter(Boolean),m=h&&h.length>0?h.length===2&&h[0]==="pg_catalog"?h[1]:h.join("."):void 0;if(!m)continue;let g=!!d.typeName?.arrayBounds?.length,y=Array.isArray(d.typeName?.typmods)?d.typeName.typmods:[],w=C=>y[C]?.A_Const?.ival?.ival??y[C]?.A_Const?.val?.ival?.ival,S={isArray:g};if(ha(m)&&y.length>0){let C=w(0);typeof C=="number"&&C>0&&(S.lengthConstraint=C);}if(ga(m)&&y.length>=2){let C=w(0),oe=w(1);typeof C=="number"&&typeof oe=="number"&&C>0&&oe>=0&&(S.numericPrecision={precision:C,scale:oe});}let b=it(e,m);b&&(S.enumValues=b);let _=Array.isArray(d.constraints)?d.constraints:[],E=_.some(C=>C.Constraint?.contype==="CONSTR_PRIMARY"),x=_.find(C=>C.Constraint?.contype==="CONSTR_DEFAULT"),O=ma(m)||n?.has(d)===true||_.some(C=>C.Constraint?.contype==="CONSTR_IDENTITY")||ne(x?.Constraint?.raw_expr?.FuncCall?.funcname??[]).join(".")==="nextval",v=_.some(C=>C.Constraint?.contype==="CONSTR_NOTNULL"),$=_.find(C=>C.Constraint?.contype==="CONSTR_UNIQUE"),k=_.find(C=>C.Constraint?.contype==="CONSTR_GENERATED"),N=_.find(C=>C.Constraint?.contype==="CONSTR_FOREIGN"),H=_.find(C=>C.Constraint?.contype==="CONSTR_CHECK"),V;if(N){let C=N.Constraint,oe=C.pktable?.relname,he=C.pktable?.schemaname,Le=C.pk_attrs?.[0]?.String?.sval;oe&&Le&&(V={refSchema:he,refTable:oe,refColumn:Le,constraintName:C.conname||ve(o,"foreign_key",[p])});}let B={schema:a,table:o,column:p,pgTypeName:m,nullable:!v&&!E,defaultValue:null,defaultFn:null,isPrimaryKey:E,isUnique:!!$,isSerial:O,isGenerated:!!k,fkRef:V,hasCheck:!!H,checkConstraintName:H?H.Constraint?.conname||ve(o,"check",[p]):void 0,uniqueConstraintName:$?$.Constraint?.conname||ve(o,"unique",[p]):void 0};c.set(p,we(B,S));}let u=(f,d)=>{let p=c.get(f);if(!p)return;let h={...p.context,...d},m=it(e,h.pgTypeName);c.set(f,we(h,{...p.factoryExtra,...m?{enumValues:m}:{}}));};for(let f of i.tableElts??[]){if(!("Constraint"in f))continue;let d=f.Constraint,p=ne(d.keys??[]);if(d.contype==="CONSTR_PRIMARY")for(let h of p)u(h,{isPrimaryKey:true,nullable:false});else if(d.contype==="CONSTR_UNIQUE"&&p.length===1)u(p[0],{isUnique:true,uniqueConstraintName:d.conname||ve(o,"unique",p)});else if(d.contype==="CONSTR_FOREIGN"&&p.length===1){let h=d.pktable?.relname,m=ne(d.pk_attrs??[])[0];h&&m&&u(p[0],{fkRef:{refSchema:d.pktable?.schemaname,refTable:h,refColumn:m,constraintName:d.conname||ve(o,"foreign_key",p)}});}else if(d.contype==="CONSTR_CHECK"){let h=[...Sr(d.raw_expr)];h.length===1&&u(h[0],{hasCheck:true,checkConstraintName:d.conname||ve(o,"check",h)});}}r.set(l,c);continue}if("RenameStmt"in s.stmt){let i=s.stmt.RenameStmt,o=i.relation?.schemaname??"public",a=i.relation?.relname??"",l=r.get(`${o}.${a}`);if(!l)continue;let c=i.renameType==="OBJECT_TABLE"?i.newname:void 0,u=i.renameType==="OBJECT_COLUMN"?i.newname:void 0,f=i.renameType==="OBJECT_COLUMN"?i.subname:void 0;if(!c&&!(u&&f))continue;let d=c??a,p=new Qe(d,o);for(let h of l.all()){let m=h.context.column===f?u:h.context.column,g={...h.context,table:d,column:m},y=it(e,g.pgTypeName);p.set(m,we(g,{...h.factoryExtra,...y?{enumValues:y}:{}}));}r.delete(`${o}.${a}`),r.set(`${o}.${d}`,p);for(let h of r.values())for(let m of h.all()){let g=m.context.fkRef;if(!g||(g.refSchema??"public")!==o||g.refTable!==a)continue;let y=f&&g.refColumn===f?u:g.refColumn,w={...m.context,fkRef:{...g,refTable:d,refColumn:y}},S=it(e,w.pgTypeName);h.set(w.column,we(w,{...m.factoryExtra,...S?{enumValues:S}:{}}));}continue}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public",l=`${a}.${o}`,c=r.get(l);if(!c)continue;let u=(f,d,p)=>{let h=c.get(f);if(!h)return;let m={...h.context,...d},g=it(e,m.pgTypeName);c.set(f,we(m,{...p??h.factoryExtra,...g?{enumValues:g}:{}}));};for(let f of i.cmds??[]){if(!("AlterTableCmd"in f))continue;let d=f.AlterTableCmd;if(d.subtype==="AT_AddColumn"&&d.def&&"ColumnDef"in d.def){let p=Sa({stmts:[{stmt:{CreateStmt:{relation:i.relation,tableElts:[d.def]}}}]},e,n).get(l)?.all()[0];p&&c.set(p.context.column,p);continue}if(d.subtype==="AT_AlterColumnType"&&d.name&&d.def&&"ColumnDef"in d.def){let p=Sa({stmts:[{stmt:{CreateStmt:{relation:i.relation,tableElts:[{ColumnDef:{...d.def.ColumnDef,colname:d.name}}]}}}]},e,n).get(l)?.get(d.name);p&&u(d.name,{pgTypeName:p.context.pgTypeName,isSerial:p.context.isSerial},p.factoryExtra);continue}if(d.subtype==="AT_SetNotNull"&&d.name){u(d.name,{nullable:false});continue}if(d.subtype==="AT_DropNotNull"&&d.name){let p=c.get(d.name);u(d.name,{nullable:!p?.context.isPrimaryKey});continue}if(d.subtype==="AT_AddConstraint"&&d.def&&"Constraint"in d.def){let p=d.def.Constraint,h=ne(p.keys??p.fk_attrs??[]);if(p.contype==="CONSTR_PRIMARY")for(let m of h)u(m,{isPrimaryKey:true,nullable:false});else if(p.contype==="CONSTR_UNIQUE"&&h.length===1)u(h[0],{isUnique:true,uniqueConstraintName:p.conname||ve(o,"unique",h)});else if(p.contype==="CONSTR_FOREIGN"&&h.length===1){let m=p.pktable?.relname,g=ne(p.pk_attrs??[])[0];m&&g&&u(h[0],{fkRef:{refSchema:p.pktable?.schemaname,refTable:m,refColumn:g,constraintName:p.conname||ve(o,"foreign_key",h)}});}else if(p.contype==="CONSTR_CHECK"){let m=[...Sr(p.raw_expr)];m.length===1&&u(m[0],{hasCheck:true,checkConstraintName:p.conname||ve(o,"check",m)});}continue}if(d.subtype==="AT_DropConstraint"&&d.name){for(let p of c.all()){let h=p.context;h.uniqueConstraintName===d.name&&u(h.column,{isUnique:false,uniqueConstraintName:void 0}),h.checkConstraintName===d.name&&u(h.column,{hasCheck:false,checkConstraintName:void 0}),h.fkRef?.constraintName===d.name&&u(h.column,{fkRef:void 0});}continue}if(d.subtype==="AT_DropColumn"&&d.name){let p=new Qe(o,a);for(let h of c.all())h.context.column!==d.name&&p.set(h.context.column,h);c=p,r.set(l,p);for(let h of r.values())for(let m of h.all()){let g=m.context.fkRef;if((g?.refSchema??"public")===a&&g?.refTable===o&&g.refColumn===d.name){let y={...m.context,fkRef:void 0};h.set(y.column,we(y,m.factoryExtra));}}}}continue}if("DropStmt"in s.stmt&&s.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let i of s.stmt.DropStmt.objects??[]){if(!("List"in i))continue;let o=ne(i.List.items??[]),a=o[o.length-1],l=o.length>=2?o[o.length-2]:"public";if(a){r.delete(`${l}.${a}`);for(let c of r.values())for(let u of c.all()){let f=u.context.fkRef;if((f?.refSchema??"public")===l&&f?.refTable===a){let d={...u.context,fkRef:void 0};c.set(d.column,we(d,u.factoryExtra));}}}}}return r}function $b(t){let e=[],n=new Set,r=(s,i,o)=>{let a=s.contype,l=ne(s.keys??s.fk_attrs??[]);if(a==="CONSTR_UNIQUE"&&l.length>0)e.push({schema:i,table:o,kind:"unique",name:s.conname||ve(o,"unique",l),columns:l});else if(a==="CONSTR_CHECK"){let c=[...Sr(s.raw_expr)];e.push({schema:i,table:o,kind:"check",name:s.conname||ve(o,"check",c),columns:c});}else if(a==="CONSTR_FOREIGN"){let c=s.pktable?.relname;if(!c)return;e.push({schema:i,table:o,kind:"foreign_key",name:s.conname||ve(o,"foreign_key",l),columns:l,refSchema:s.pktable?.schemaname,refTable:c,refColumns:ne(s.pk_attrs??[])});}};for(let s of t.stmts??[]){if(!s.stmt)continue;if("RenameStmt"in s.stmt){let c=s.stmt.RenameStmt,u=c.relation?.schemaname??"public",f=c.relation?.relname;if(!f||!c.newname)continue;if(c.renameType==="OBJECT_TABLE"){n.delete(`${u}.${f}`),n.add(`${u}.${c.newname}`);for(let d of e)d.schema===u&&d.table===f&&(d.table=c.newname),(d.refSchema??"public")===u&&d.refTable===f&&(d.refTable=c.newname);}else if(c.renameType==="OBJECT_COLUMN"&&c.subname)for(let d of e)d.schema===u&&d.table===f&&(d.columns=d.columns.map(p=>p===c.subname?c.newname:p)),(d.refSchema??"public")===u&&d.refTable===f&&(d.refColumns=d.refColumns?.map(p=>p===c.subname?c.newname:p));continue}if("AlterTableStmt"in s.stmt){let c=s.stmt.AlterTableStmt,u=c.relation?.schemaname??"public",f=c.relation?.relname??"";for(let d of c.cmds??[]){if(!("AlterTableCmd"in d))continue;let p=d.AlterTableCmd;if(p.subtype==="AT_AddConstraint"&&p.def&&"Constraint"in p.def)r(p.def.Constraint,u,f);else if(p.subtype==="AT_DropConstraint"&&p.name)for(let h=e.length-1;h>=0;h--){let m=e[h];m.schema===u&&m.table===f&&m.name===p.name&&e.splice(h,1);}else if(p.subtype==="AT_DropColumn"&&p.name)for(let h=e.length-1;h>=0;h--){let m=e[h];(m.schema===u&&m.table===f&&m.columns.includes(p.name)||(m.refSchema??"public")===u&&m.refTable===f&&m.refColumns?.includes(p.name))&&e.splice(h,1);}}continue}if("DropStmt"in s.stmt&&s.stmt.DropStmt.removeType==="OBJECT_TABLE"){for(let c of s.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let u=ne(c.List.items??[]),f=u[u.length-1],d=u.length>=2?u[u.length-2]:"public";f&&n.delete(`${d}.${f}`);for(let p=e.length-1;p>=0;p--){let h=e[p];(h.schema===d&&h.table===f||(h.refSchema??"public")===d&&h.refTable===f)&&e.splice(p,1);}}continue}if(!("CreateStmt"in s.stmt))continue;let i=s.stmt.CreateStmt,o=i.relation?.relname??"",a=i.relation?.schemaname??"public";if(!o)continue;let l=`${a}.${o}`;if(!(i.if_not_exists&&n.has(l))){n.add(l);for(let c of i.tableElts??[]){if("ColumnDef"in c){let p=c.ColumnDef,h=p?.colname;if(!h)continue;for(let m of p.constraints??[]){let g=m?.Constraint;if(!g||g.contype!=="CONSTR_FOREIGN")continue;let y=g.pktable?.relname;if(!y)continue;let w=(g.pk_attrs??[]).map(S=>S.String?.sval??S.String?.str).filter(Boolean);e.push({schema:a,table:o,kind:"foreign_key",name:g.conname||ve(o,"foreign_key",[h]),columns:[h],refSchema:g.pktable?.schemaname,refTable:y,refColumns:w});}continue}let u=c;if(!u.Constraint)continue;let f=u.Constraint,d=f.contype;if(d==="CONSTR_UNIQUE"){let p=(f.keys??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean);if(p.length===0)continue;e.push({schema:a,table:o,kind:"unique",name:f.conname||ve(o,"unique",p),columns:p});}else if(d==="CONSTR_CHECK"){let p=[...Sr(f.raw_expr)];e.push({schema:a,table:o,kind:"check",name:f.conname||ve(o,"check",p),columns:p});}else if(d==="CONSTR_FOREIGN"){let p=(f.fk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),h=(f.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),m=f.pktable?.relname;if(!m)continue;e.push({schema:a,table:o,kind:"foreign_key",name:f.conname||ve(o,"foreign_key",p),columns:p,refSchema:f.pktable?.schemaname,refTable:m,refColumns:h});}}}}return e}function Nb(t){let e=new Map,n=r=>`${r.schema}.${r.table}.${r.column??""}`;for(let r of t.stmts??[]){if(!r.stmt)continue;if("RenameStmt"in r.stmt){let c=r.stmt.RenameStmt,u=c.relation?.schemaname??"public",f=c.relation?.relname;if(!f||!c.newname)continue;let d=new Map;for(let p of e.values()){if(p.schema!==u||p.table!==f){d.set(n(p),p);continue}let h={...p,table:c.renameType==="OBJECT_TABLE"?c.newname:p.table,column:c.renameType==="OBJECT_COLUMN"&&p.column===c.subname?c.newname:p.column};d.set(n(h),h);}e.clear();for(let[p,h]of d)e.set(p,h);continue}if("AlterTableStmt"in r.stmt){let c=r.stmt.AlterTableStmt,u=c.relation?.schemaname??"public",f=c.relation?.relname??"";for(let d of c.cmds??[])"AlterTableCmd"in d&&d.AlterTableCmd.subtype==="AT_DropColumn"&&d.AlterTableCmd.name&&e.delete(n({schema:u,table:f,column:d.AlterTableCmd.name}));continue}if("DropStmt"in r.stmt&&(r.stmt.DropStmt.removeType==="OBJECT_TABLE"||r.stmt.DropStmt.removeType==="OBJECT_VIEW")){for(let c of r.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let u=ne(c.List.items??[]),f=u[u.length-1],d=u.length>=2?u[u.length-2]:"public";for(let[p,h]of e)h.schema===d&&h.table===f&&e.delete(p);}continue}if(!("CommentStmt"in r.stmt))continue;let s=r.stmt.CommentStmt,i=s.objtype,o=(s.object?.List?.items??s.object?.items??[]).map(c=>c.String?.sval??c.String?.str).filter(Boolean);if(o.length===0)continue;let a;if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[c,u]=o.length>=2?o:["public",o[0]];a={schema:c,table:u};}else if(i==="OBJECT_COLUMN"){let c="public",u,f;o.length>=3?[c,u,f]=o:[u,f]=o,a={schema:c,table:u,column:f};}if(!a)continue;let l=n(a);s.comment===null||s.comment===void 0?e.delete(l):e.set(l,{...a,text:String(s.comment)});}return [...e.values()]}var Cb,df=I(()=>{cf();Cn();ni();bc();wr();Cb=new Set;});var _a,Ib=I(()=>{wr();Cn();_a=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=br(e),r=ya.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 qk,Hk,Wk,Kk,_r,Ea,Db=I(()=>{wr();qk=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],Hk=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,Wk=/^RETURN\s+(NEW|OLD)$/i,Kk=/^(INSERT|UPDATE|DELETE)\b/i,_r=class extends kn{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},Ea=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(Wk);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(Hk);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(Kk.test(a)){s.push({type:"dml",sql:a});continue}throw new _r(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new kn("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 _r('"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 _r("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&&qk.includes(n))throw new _r(`"${n}" is not translatable to SQLite`,e)}};});function Qk(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"&&zk.has(e.objtype)}function jb(t){return t?.String?.sval}function Yk(t){return t?.FuncCall?.funcname?.map(e=>e.String?.sval??e.String?.str).filter(Boolean).at(-1)?.toLowerCase()}var zk,pf,xa,Lb=I(()=>{wr();df();Cn();Cn();Ib();rs();Db();la();nf();rf();qn();bo();gc();zk=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);pf=new Set(["plpgsql","pgcrypto","uuid-ossp"]);xa=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new Ea;introspection;functionResolution;serialColumns;storagePathTokensConstraints=new WeakSet;constructor(e,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(e,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new _a(e),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(e,n){let r=br(e);if(r==="GrantStmt"&&Qk(e))return "";let s=e.AlterObjectSchemaStmt;if(r==="AlterObjectSchemaStmt"&&s?.objectType==="OBJECT_EXTENSION"){let o=jb(s.object);if(o&&pf.has(o))return "";throw new L({[r]:e},"ALTER EXTENSION is not supported in SQLite")}if(r==="AlterExtensionStmt"||r==="AlterExtensionContentsStmt")throw new L({[r]:e},"ALTER EXTENSION is not supported in SQLite");if(r==="AlterEnumStmt"){let o=e.AlterEnumStmt??e,a=ne(o.typeName??[]),l=a.length?`${a.map(u=>ri(u)).join(".")} `:"",c=o.oldVal!==void 0?"RENAME VALUE":"ADD VALUE";throw new L({[r]:e},`ALTER TYPE ${l}${c} is not supported on sqlite-postgres yet. Recreate the type with all values, or track this change in a manual migration.`)}let i=ya.get(r);if(i){if(i.react==="error")throw new L({[r]:e},`Unsupported node type: ${r}`);return i.react==="warn"&&this.warnings.push({type:r,node:e}),""}return super.visit(e,n)}CreateExtensionStmt(e,n){let r=e.extname??"";if(pf.has(r))return "";throw new L({CreateExtensionStmt:e},`CREATE EXTENSION ${JSON.stringify(r)} is not supported in SQLite`)}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 L({CreateStmt:e},"Inheritance is not supported in SQLite");if(e.ofTypename!==void 0)throw new L({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 L({CreateStmt:e},"Empty tables are not supported in SQLite. Define at least one column.");if(e.accessMethod&&(e.accessMethod=void 0),e.relation?.schemaname==="storage"&&e.relation.relname==="objects")for(let s of e.tableElts??[]){let i=s.ColumnDef;if(i?.colname==="path_tokens")for(let o of i.constraints??[]){let a=o.Constraint;a?.contype==="CONSTR_GENERATED"&&Yk(a.raw_expr)==="string_to_array"&&this.storagePathTokensConstraints.add(a);}}return super.CreateStmt(e,n)+" STRICT"}TableLikeClause(e,n){throw new L({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=>ro(e.defname??"",i)))return "";let s=super.DefElem(e,n);throw new L({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||it(this.enums,s)?"TEXT":Rb(s)}ColumnDef(e,n){let r=[],s=e.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,u=false;if(e.typeName){let f=e.typeName.names?.map(h=>h.String?.sval||h.String?.str).filter(Boolean);c=f&&f.length>0?f.length===2&&f[0]==="pg_catalog"?f[1]:f.join("."):null,i=!!(c&&ma(c))||this.serialColumns.has(e),u=!!(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0);let d=Array.isArray(e.typeName.typmods)?e.typeName.typmods:[],p=h=>d[h]?.A_Const?.ival?.ival??d[h]?.A_Const?.val?.ival?.ival;if(c&&ha(c)&&d.length>0){let h=p(0);typeof h=="number"&&h>0&&(a={maxLen:h});}if(c&&ga(c)&&d.length>=2){let h=p(0),m=p(1);typeof h=="number"&&typeof m=="number"&&h>0&&m>=0&&(l={precision:h,scale:m});}if(e.constraints){let h=Array.isArray(e.constraints)?e.constraints:[];o=h.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),h.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}r.push(this.TypeName(e.typeName,n));}if(e.constraints){let f=Array.isArray(e.constraints)?e.constraints:[],d=n.spawn("ColumnDef",{isColumnConstraint:true}),p=f.map(m=>this.visit(m,d));r.push(...p.filter(Boolean));let h=f.some(m=>m.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h?r.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:e},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let f={isArray:u};a&&(f.lengthConstraint=a.maxLen),l&&(f.numericPrecision=l);let d=it(this.enums,c);d&&(f.enumValues=d);let m=we({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},f).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(e,n){let r=e.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&e.raw_expr){let s=this.unwrapConstCast(e.raw_expr),i=this.visit(s,n);return i.includes("(")&&!i.startsWith("(")?`DEFAULT (${i})`:`DEFAULT ${i}`}if(r==="CONSTR_CHECK"&&e.raw_expr){let s=[];e.conname&&s.push("CONSTRAINT",ri(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 (${Yt(e.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return e.keys&&e.keys.length>0?`UNIQUE (${Yt(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 this.storagePathTokensConstraints.has(e)?"":`GENERATED ALWAYS AS (${this.visit(e.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new L({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=hc(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=wo[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${a.join(", ")})`}}}throw new L({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 L({SQLValueFunction:e},`SQLValueFunction "${e.op}" not supported`)}}ResTarget(e,n){if(e.indirection&&e.indirection.length>0)throw new L({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(e.kind==="AEXPR_OP_ANY"&&(e.name?.[0]?.String?.sval||e.name?.[0]?.String?.str)==="="&&e.lexpr&&e.rexpr&&"A_ArrayExpr"in e.rexpr){let s=Yt(e.rexpr.A_ArrayExpr.elements),i=this.tryFoldConstArrayElements(s,n);if(i!==void 0)return `${this.visit(e.lexpr,n)} IN (${i.join(", ")})`}if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(e.kind))throw new L({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 L({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 L({A_Expr:e},"A_Expr missing left or right expression");if(!Tb.includes(r.toUpperCase()))throw new L({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(ri(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(ri(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(" ")}constFoldCategory(e){if(!e?.names||e.arrayBounds&&e.arrayBounds.length>0)return null;let n=e.names.map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(n.length===0)return null;let r=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join("."),s=r.toLowerCase().trim();return it(this.enums,r)?"text":new Set(["bool","boolean"]).has(s)?"boolean":new Set(["int2","smallint","int4","integer","int","int8","bigint","serial","serial4","bigserial","serial8","smallserial","serial2"]).has(s)?"integer":new Set(["float4","real","float8","double precision","numeric","decimal"]).has(s)?"real":new Set(["text","varchar","character varying","char","character","bpchar","name","uuid"]).has(s)?"text":null}isFoldableCast(e,n){if(e.isnull)return true;let r=this.constFoldCategory(n);return r?"sval"in e?r==="text":"ival"in e?r==="integer":"fval"in e?r==="real":"boolval"in e?r==="boolean":false:false}findUnderlyingConst(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(!r.arg)return null;n=r.arg;}return "A_Const"in n?n.A_Const:null}unwrapConstCast(e){let n=e;for(;"TypeCast"in n;){let r=n.TypeCast;if(r.typeName?.arrayBounds&&r.typeName.arrayBounds.length>0||!r.arg)break;if("A_Const"in r.arg){if(!this.isFoldableCast(r.arg.A_Const,r.typeName))break;n=r.arg;continue}if("TypeCast"in r.arg){let s=this.findUnderlyingConst(r.arg);if(!s||!this.isFoldableCast(s,r.typeName))break;n=r.arg;continue}break}return n}tryFoldConstArrayElements(e,n){let r=[];for(let s of e){let i=this.unwrapConstCast(s);if("A_Const"in i){r.push(this.visit(i,n));continue}if(this.findUnderlyingConst(s)===null)return;r.push(this.visit(i,n));}return r}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 L({TypeCast:e},"A.* in type casts are not supported in SQLite");if(e.typeName.arrayBounds&&e.typeName.arrayBounds.length>0){if("A_Const"in e.arg&&e.arg.A_Const.sval){let o=e.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=e.typeName.names?.map(f=>f.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let f=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(f).replace(/'/g,"''")}'`}catch{}}}return this.visit(e.arg,n)}let s=this.visit(e.arg,n),i=this.TypeName(e.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(e,n){let r=Yt(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=Yt(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_DisableRowSecurity","AT_ForceRowSecurity","AT_NoForceRowSecurity","AT_ChangeOwner"],i=r.filter(u=>"AlterTableCmd"in u&&!s.includes(u.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(e.objtype))throw new L({AlterTableStmt:e},`AlterTableStmt with objtype ${e.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let u of i){let f=u.AlterTableCmd.subtype;if(o.includes(f)){let d={...e,cmds:[u]};l.push(super.AlterTableStmt(d,n));}else if(a.includes(f))c.push(u.AlterTableCmd);else throw new L({AlterTableStmt:e},`AlterTableCmd with subtype ${f} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(e.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
26
+ `)}AlterTableCmd(e,n){if(!["AT_AddColumn","AT_DropColumn"].includes(e.subtype))throw new L({AlterTableCmd:e},`AlterTableCmd with subtype ${e.subtype} is not supported`);if(e.subtype==="AT_AddColumn"&&e.def&&"ColumnDef"in e.def){let s=this.ColumnDef(e.def.ColumnDef,n),i=n.objtype==="OBJECT_TYPE"?"ADD ATTRIBUTE":"ADD COLUMN",o=e.missing_ok?" IF NOT EXISTS":"";return `${i}${o} ${s}`}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 L({InsertStmt:e},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(e,n)}SelectStmt(e,n){if(this.helper.hasUnsafeStar())throw new L({SelectStmt:e},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(e.intoClause)throw new L({SelectStmt:e},"SELECT ... INTO clause is not supported in SQLite");if(e.distinctClause){let s=Yt(e.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new L({SelectStmt:e},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(e.limitOffset&&!e.limitCount)throw new L({SelectStmt:e},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(e,n);if(/^SELECT\s+FROM/.test(r))throw new L({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 L({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=Yt(e.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new L({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 L({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 L({SubLink:e},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(e.subLinkType==="ARRAY_SUBLINK")throw new L({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 L({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 L({Alias:e},"Aliasing with column names is not supported in SQLite");return `AS "${e.aliasname}"`}CreateFunctionStmt(e,n){let r=e.options??[],s=e.funcname?.map(u=>u.String?.sval).filter(Boolean).join(".");if(s&&new Set(["storage.foldername","storage.filename","storage.extension","storage.operation","storage.allow_only_operation","storage.allow_any_operation"]).has(s))return "";let i=e.returnType?.names?.map(u=>u.String?.sval).filter(Boolean).join("."),o=r.find(u=>u.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(i!=="trigger"||o!=="plpgsql")throw new L({CreateFunctionStmt:e},"Only trigger functions with LANGUAGE plpgsql are supported");let a=e.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!a)throw new Error("Function has no name");let l=r.find(u=>u.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!l)throw new Error("Function has no body");let c=this.plpgsqlParser.parse(l);return this.triggerFunctions.set(a,c),""}CreateTrigStmt(e,n){let r=e.trigname,s=this.RangeVar(e.relation,n),i=e.funcname?.map(f=>f.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new L({CreateTrigStmt:e},`Trigger "${r}" references unknown function "${i}"`);let a=e.timing===2?"BEFORE":e.timing===64?"INSTEAD OF":"AFTER",l=[];if(e.events&4&&l.push("INSERT"),e.events&8&&l.push("DELETE"),e.events&16)if(e.columns?.length){let f=e.columns.map(d=>d.String?.sval).filter(Boolean);l.push(`UPDATE OF ${f.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),u=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...u.map(f=>` ${f};`),"END"].join(`
27
+ `)}buildTriggerBody(e,n,r){let s=[],i=[];for(let o of e.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(e,n,r){let s=e.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(e,n){try{let r=`SELECT ${e}`,s=e.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":e}catch{return e}}flattenTriggerTableRef(e,n){let r=this.effectiveSchema(e);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(e,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return e=e.replace(r,(s,i,o,a,l,c,u)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??u)}`),e.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(e,n){if(e.arg?.ColumnRef?.fields?.length>1)throw new L({NullTest:e},"row-level NULL tests are not supported in SQLite");return super.NullTest(e,n)}RenameStmt(e,n){if(!e.renameType)throw new Error("RenameStmt requires renameType");if(e.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(e.renameType==="OBJECT_COLUMN"&&(e.relationType==="OBJECT_FOREIGN_TABLE"||e.relationType==="OBJECT_VIEW"))throw new L({RenameStmt:e},`RenameStmt with relationType ${e.relationType} is not supported`);if(!r.includes(e.renameType))throw new L({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(r==="OBJECT_EXTENSION"){let o=e.objects?.map(jb)??[];if(o.length>0&&o.every(a=>a&&pf.has(a)))return "";throw new L({DropStmt:e},"DROP EXTENSION is not supported in SQLite")}if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(e),super.DropStmt(e,n);if(["OBJECT_POLICY"].includes(r))return "";throw new L({DropStmt:e},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(e){let n=e.removeType==="OBJECT_TRIGGER"?3:2;for(let r of e.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),l=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:l}});}}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(f=>f.name===n);if(r===-1)return;let s=e.columns.filter(f=>f.table===n),i=e.foreign_keys.filter(f=>f.table===n),o=e.check_constraints.filter(f=>f.table===n),a=s.map(f=>{let d=`${F(f.name)} ${f.type||"TEXT"}`;return f.is_primary_key&&(d+=" PRIMARY KEY"),f.nullable||(d+=" NOT NULL"),f.default_value!=null&&(d+=` DEFAULT ${f.default_value}`),d}),l=i.map(f=>`FOREIGN KEY (${F(f.column)}) REFERENCES ${F(f.ref_table)}(${F(f.ref_column)}) ON UPDATE ${f.on_update} ON DELETE ${f.on_delete}`),c=o.map(f=>`CHECK (${f.expression})`),u=[...a,...l,...c];e.tables[r]={...e.tables[r],sql:`CREATE TABLE ${F(n)} (${u.join(", ")}) STRICT`};}extractTypeName(e){let n=e.def?.ColumnDef,r=n?.typeName?.TypeName??n?.typeName;return r?(r.names??[]).map(i=>i.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(e){if(!e.def)return null;let n=this.unwrapConstCast(e.def);if("A_Const"in n){let r=n.A_Const;return r.isnull?null:r.ival?String(r.ival.ival??0):r.fval?r.fval.fval:r.sval?`'${String(r.sval.sval).replace(/'/g,"''")}'`:"boolval"in r?r.boolval.boolval?"1":"0":null}return "Integer"in n?String(n.Integer.ival):"Float"in n?n.Float.fval:"String"in n?`'${n.String.sval}'`:null}};});function Fb(t){return `${t?.schemaname??"public"}.${t?.relname??""}`}function Xk(t){let e=t?.Constraint;if(!e||e.contype!=="CONSTR_DEFAULT")return false;let n=e.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function Zk(t){return (Array.isArray(t.constraints)?t.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function Ub(t,e){let n=Array.isArray(t.constraints)?t.constraints:[],r=n.filter(s=>!Xk(s));r.length!==n.length?(t.constraints=r,e.add(t)):Zk(t)&&e.add(t);}function eA(t,e){let n=e?.Constraint;if(!n)return false;let r=n.contype;if(r!=="CONSTR_PRIMARY"&&r!=="CONSTR_UNIQUE"&&r!=="CONSTR_FOREIGN")return false;let s=t.tableElts??[];return r==="CONSTR_PRIMARY"&&Mb(t,n)||r==="CONSTR_FOREIGN"&&Bb(t,n)||(s.push(e),t.tableElts=s),true}function Mb(t,e){let n=(e.keys??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s.filter(i=>i.Constraint?.contype!=="CONSTR_NOTNULL"),{Constraint:{contype:"CONSTR_PRIMARY"}}],true}function Bb(t,e){let n=(e.fk_attrs??[]).map(i=>i.String?.sval??i.String?.str).filter(Boolean);if(n.length!==1)return false;let r=(t.tableElts??[]).find(i=>"ColumnDef"in i&&i.ColumnDef.colname===n[0]);if(!r)return false;let s=Array.isArray(r.ColumnDef.constraints)?r.ColumnDef.constraints:[];return r.ColumnDef.constraints=[...s,{Constraint:e}],true}function tA(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_PRIMARY"?true:!Mb(t,s)});n.length!==e.length&&(t.tableElts=n);}function nA(t){let e=t.tableElts??[],n=e.filter(r=>{let s=r?.Constraint;return !s||s.contype!=="CONSTR_FOREIGN"?true:!Bb(t,s)});n.length!==e.length&&(t.tableElts=n);}function qb(t){let e=new WeakSet,n=new Map;for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(Fb(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&Ub(o.ColumnDef,e);tA(i),nA(i);}for(let r of t.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(Fb(i.relation)),a=i.cmds??[],l=[];for(let c of a){let u=c.AlterTableCmd;u?.subtype==="AT_AddColumn"&&u.def&&"ColumnDef"in u.def&&Ub(u.def.ColumnDef,e),!(o&&u?.subtype==="AT_AddConstraint"&&u.def&&eA(o,u.def))&&l.push(c);}i.cmds=l;}return e}var Hb=I(()=>{});var Jb={};li(Jb,{Policy:()=>Xe,deparseDdl:()=>mf,deparseExpression:()=>sA,deparsePostgresDdl:()=>rA,deparseSelect:()=>iA,parse:()=>gr,parseExpression:()=>Kb,translatePostgresDdl:()=>Wb});async function Wb(t,e={}){let n=await gr(t);return mf(n,e).ddl}async function rA(t,e={}){let n=await gr(t);return {ast:n,...mf(n,e)}}function mf(t,e={}){let n=qb(t),r=vb(t),s=Sa(t,r,n),i=Ob(t),o=$b(t),a=Nb(t),l=new xa(t,{...e,enums:r,serialColumns:n}),{policies:c,tables:u}=Pb(t,{defaultSchema:e.defaultSchema,validateMutations:e.strict});if(e.strict){for(let f of c)if(!s.get(`${f.data.schema??"public"}.${f.data.table}`))throw new Error(`Policy "${f.data.name}" references unknown table "${f.data.table}"`)}return {ddl:l.deparseQuery(),enums:r,rls:{tables:u,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}async function Kb(t){let n=(await gr(`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 sA(t){let e=await Kb(t);return new An().deparse(e)}async function iA(t){let n=(await gr(t)).stmts?.[0]?.stmt;if(!n||!("SelectStmt"in n))throw new Error("expected SelectStmt");return new An().deparse(n)}var hf=I(()=>{Eb();Lb();Hb();cf();df();ni();});function bf(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 wf(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?bf(Object(n),true).forEach(function(r){sw(t,r,n[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):bf(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r));});}return t}function sw(t,e,n){return e=iw(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:true,configurable:true,writable:true}):t[e]=n,t}function iw(t){var e=ow(t,"string");return typeof e=="symbol"?e:String(e)}function ow(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 aw=Sf({}),Be=aw;function Sf(t){return e.withOptions=n=>Sf(wf(wf({},t),n)),e;function e(n,...r){let s=typeof n=="string"?[n]:n.raw,{alignValues:i=false,escapeSpecialCharacters:o=Array.isArray(n),trimWhitespace:a=true}=t,l="";for(let f=0;f<s.length;f++){let d=s[f];if(o&&(d=d.replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{")),l+=d,f<r.length){let p=i?lw(r[f],l):r[f];l+=p;}}let c=l.split(`
29
+ `),u=null;for(let f of c){let d=f.match(/^(\s+)\S+/);if(d){let p=d[1].length;u?u=Math.min(u,p):u=p;}}if(u!==null){let f=u;l=c.map(d=>d[0]===" "||d[0]===" "?d.slice(f):d).join(`
30
30
  `);}return a&&(l=l.trim()),o&&(l=l.replace(/\\n/g,`
31
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(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 g;let m=(g=d??p)!==null&&g!==void 0?g:"";return String.fromCodePoint(parseInt(m,16))})),l}}function vb(t,e){if(typeof t!="string"||!t.includes(`
31
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\v/g,"\v").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\0/g,"\0").replace(/\\x([\da-fA-F]{2})/g,(f,d)=>String.fromCharCode(parseInt(d,16))).replace(/\\u\{([\da-fA-F]{1,6})\}/g,(f,d)=>String.fromCodePoint(parseInt(d,16))).replace(/\\u([\da-fA-F]{4})/g,(f,d)=>String.fromCharCode(parseInt(d,16)))),typeof Bun<"u"&&(l=l.replace(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g,(f,d,p)=>{var h;let m=(h=d??p)!==null&&h!==void 0?h:"";return String.fromCodePoint(parseInt(m,16))})),l}}function lw(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}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ei=["analytics"],zu=s.strictObject({enabled:s.boolean({default:false,description:"Enable the local Logflare service.",tags:ei,links:Gu}),port:s.number({default:54327,description:"Port to the local Logflare service.",tags:ei}),vector_port:s.number({default:54328,description:"Port to the local syslog ingest service.",tags:ei}),backend:s.string({enum:["postgres","bigquery"],default:"postgres",description:je`
34
+ ${s}`)}return t}var _f=[{name:"Self-hosted Logflare Configuration",link:"https://supabase.com/docs/reference/self-hosting-analytics/list-endpoints#getting-started"}],ci=["analytics"],Ef=s.strictObject({enabled:s.boolean({default:false,description:"Enable the local Logflare service.",tags:ci,links:_f}),port:s.number({default:54327,description:"Port to the local Logflare service.",tags:ci}),vector_port:s.number({default:54328,description:"Port to the local syslog ingest service.",tags:ci}),backend:s.string({enum:["postgres","bigquery"],default:"postgres",description:Be`
35
35
  Configure one of the supported backends:
36
36
 
37
37
  - \`postgres\`
38
- - \`bigquery\``,tags:ei,links:Gu})}).partial();var Ab=Symbol.for("lite-only"),Pt=t=>(Object.defineProperty(t,Ab,{value:true,enumerable:false,writable:false,configurable:false}),t);var nt=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Be=["api"],Vu=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local PostgREST service.",tags:Be,links:nt}),port:s.number({default:54321,description:"Port to use for the API URL.",tags:Be,links:nt}),schemas:s.array(s.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:Be,links:nt}),{default:["public","storage","graphql_public"]}),extra_search_path:s.array(s.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Be,links:nt}),{default:["public","extensions"]}),max_rows:s.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:Be,links:nt}),pg_safe_update:s.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Be,links:nt}),plan_enabled:Pt(s.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:Be,links:nt})),aggregates_enabled:Pt(s.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:Be,links:nt})),limited_mutations_enabled:Pt(s.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:Be,links:nt})),anonymous_enabled:Pt(s.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:Be,links:nt})),tls:s.strictObject({enabled:s.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Be})}).partial(),external_url:s.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Be})}).partial();var Vt=["auth"],Qt={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},br=(t,e)=>s.strictObject({subject:s.string({default:e,description:`The subject of the ${t} email.`}),content_path:s.string({description:`The path to the content of the ${t} email.`})}).partial(),Qu=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:Vt,links:[Qt.auth]}),double_confirm_changes:s.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:Vt,links:[Qt.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:Vt,links:[Qt.auth]}),secure_password_change:s.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:Vt,links:[Qt.auth]}),max_frequency:s.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:Vt,links:[Qt.auth]}),smtp:s.strictObject({enabled:s.boolean({default:false,description:"Enable sending emails through a custom SMTP server."}),host:s.string({description:"Hostname or IP address of the SMTP server."}),port:s.number({description:"Port number of the SMTP server."}),user:s.string({description:"Username for authenticating with the SMTP server."}),pass:s.string({description:"Password for authenticating with the SMTP server."}),admin_email:s.string({description:"Email used as the sender for emails sent from the application."}),sender_name:s.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:s.strictObject({invite:br("invite","You have been invited"),confirmation:br("confirmation","Confirm Your Signup"),recovery:br("recovery","Reset Your Password"),magic_link:br("magic link","Your Magic Link"),email_change:br("email change","Confirm Email Change")}).partial(),otp_length:s.number({default:6,description:"Number of characters used in the email OTP.",tags:Vt,links:[Qt.auth]}),otp_expiry:s.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:Vt,links:[Qt.auth]})}).partial();var ti=["auth"],ua=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),wr=(t,e)=>s.strictObject({enabled:s.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:ti,links:[ua(t,e)]}),uri:s.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:ti,links:[ua(t,e)]}),secrets:s.array(s.string({description:"A secret to pass to the function or endpoint.",tags:ti}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:ti,links:[ua(t,e)]})}).partial(),Yu=s.strictObject({mfa_verification_attempt:wr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:wr("Password Verification Hook","password-verification-hook"),custom_access_token:wr("Custom Access Token Hook","custom-access-token-hook"),send_sms:wr("Send SMS Hook","send-sms-hook"),send_email:wr("Send Email Hook","send-email-hook")}).partial();var $t=["auth"],It={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"}},Xu=s.strictObject({totp:s.strictObject({enroll_enabled:s.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:$t,links:[It.totp]}),verify_enabled:s.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:$t,links:[It.totp]})}).partial(),phone:s.strictObject({enroll_enabled:s.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:$t,links:[It.phone]}),verify_enabled:s.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:$t,links:[It.phone]}),otp_length:s.number({default:6,description:"The length of the OTP code.",tags:$t,links:[It.phone]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:$t,links:[It.phone]}),max_frequency:s.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:$t,links:[It.phone]})}).partial(),max_enrolled_factors:s.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:$t,links:[It.mfa]})}).partial();var fa=class extends yt.StringSchema{},gt=t=>new fa(t);var Yt=["auth"],me=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return s.strictObject({enabled:s.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:Yt,links:e}),client_id:s.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:Yt,links:e}),secret:gt({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:je`
38
+ - \`bigquery\``,tags:ci,links:_f})}).partial();var cw=Symbol.for("lite-only"),Nt=t=>(Object.defineProperty(t,cw,{value:true,enumerable:false,writable:false,configurable:false}),t);var ot=[{name:"PostgREST configuration",link:"https://postgrest.org/en/stable/configuration.html"}],Ge=["api"],xf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local PostgREST service.",tags:Ge,links:ot}),port:s.number({default:54321,description:"Port to use for the API URL.",tags:Ge,links:ot}),schemas:s.array(s.string({description:"Schemas to expose in your API. Tables, views and functions in these schemas get API endpoints. `public` and `graphql_public` are included by default.",tags:Ge,links:ot}),{default:["public","graphql_public"]}),extra_search_path:s.array(s.string({description:"Extra schemas to add to the search_path of every request. public is always included.",tags:Ge,links:ot}),{default:["public","extensions"]}),max_rows:s.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:Ge,links:ot}),pg_safe_update:s.boolean({default:false,description:"Require a WHERE clause on UPDATE and DELETE requests. Equivalent to pg_safe_update extension.",tags:Ge,links:ot}),plan_enabled:Nt(s.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:Ge,links:ot})),aggregates_enabled:Nt(s.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:Ge,links:ot})),limited_mutations_enabled:Nt(s.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:Ge,links:ot})),anonymous_enabled:Nt(s.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:Ge,links:ot})),tls:s.strictObject({enabled:s.boolean({default:false,description:"Enable TLS for the local PostgREST service.",tags:Ge})}).partial(),external_url:s.string({default:"http://127.0.0.1:54321",description:"External URL for accessing the API server.",tags:Ge})}).partial();var en=["auth"],tn={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Tr=(t,e)=>s.strictObject({subject:s.string({default:e,description:`The subject of the ${t} email.`}),content_path:s.string({description:`The path to the content of the ${t} email.`})}).partial(),Tf=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via email to your project.",tags:en,links:[tn.auth]}),double_confirm_changes:s.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:en,links:[tn.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their email address before signing in.",tags:en,links:[tn.auth]}),secure_password_change:s.boolean({default:false,description:"If enabled, users will need to reauthenticate or have logged in recently to change their password.",tags:en,links:[tn.auth]}),max_frequency:s.string({default:"1s",description:"Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.",tags:en,links:[tn.auth]}),smtp:s.strictObject({enabled:s.boolean({default:false,description:"Enable sending emails through a custom SMTP server."}),host:s.string({description:"Hostname or IP address of the SMTP server."}),port:s.number({description:"Port number of the SMTP server."}),user:s.string({description:"Username for authenticating with the SMTP server."}),pass:s.string({description:"Password for authenticating with the SMTP server."}),admin_email:s.string({description:"Email used as the sender for emails sent from the application."}),sender_name:s.string({description:"Display name used as the sender for emails sent from the application."})}).partial(),template:s.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:s.number({default:6,description:"Number of characters used in the email OTP.",tags:en,links:[tn.auth]}),otp_expiry:s.number({default:3600,description:"Number of seconds before the email OTP expires (defaults to 1 hour).",tags:en,links:[tn.auth]})}).partial();var ui=["auth"],va=(t,e)=>({name:t,link:`https://supabase.com/docs/guides/auth/auth-hooks/${e}`}),Rr=(t,e)=>s.strictObject({enabled:s.boolean({default:false,description:`Enable/disable the ${t.toLowerCase()}.`,tags:ui,links:[va(t,e)]}),uri:s.string({description:"The URI of the postgres function or HTTP endpoint to call.",tags:ui,links:[va(t,e)]}),secrets:s.array(s.string({description:"A secret to pass to the function or endpoint.",tags:ui}),{description:"The secrets to pass to the postgres function or HTTP endpoint.",tags:ui,links:[va(t,e)]})}).partial(),Rf=s.strictObject({mfa_verification_attempt:Rr("MFA Verification Hook","mfa-verification-hook"),password_verification_attempt:Rr("Password Verification Hook","password-verification-hook"),custom_access_token:Rr("Custom Access Token Hook","custom-access-token-hook"),send_sms:Rr("Send SMS Hook","send-sms-hook"),send_email:Rr("Send Email Hook","send-email-hook")}).partial();var It=["auth"],Dt={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"}},Cf=s.strictObject({totp:s.strictObject({enroll_enabled:s.boolean({default:true,description:"Allow/disallow TOTP enrollment for users.",tags:It,links:[Dt.totp]}),verify_enabled:s.boolean({default:true,description:"Allow/disallow TOTP verification for users.",tags:It,links:[Dt.totp]})}).partial(),phone:s.strictObject({enroll_enabled:s.boolean({default:false,description:"Allow/disallow phone enrollment for users.",tags:It,links:[Dt.phone]}),verify_enabled:s.boolean({default:false,description:"Allow/disallow phone verification for users.",tags:It,links:[Dt.phone]}),otp_length:s.number({default:6,description:"The length of the OTP code.",tags:It,links:[Dt.phone]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the phone message.",tags:It,links:[Dt.phone]}),max_frequency:s.string({default:"60s",description:"The maximum frequency of the phone messages.",tags:It,links:[Dt.phone]})}).partial(),max_enrolled_factors:s.number({default:10,description:"The maximum number of MFA factors a user can enroll in.",tags:It,links:[Dt.mfa]})}).partial();var Oa=class extends St.StringSchema{},wt=t=>new Oa(t);var nn=["auth"],be=t=>{let e=[{name:`Login with ${t.name}`,link:`https://supabase.com/docs/guides/auth/social-login/auth-${t.id}`}];return s.strictObject({enabled:s.boolean({default:false,description:`Use the ${t.name} OAuth provider.`,tags:nn,links:e}),client_id:s.string({description:`Client ID for the ${t.name} OAuth provider.`,tags:nn,links:e}),secret:wt({default:`env(SUPABASE_AUTH_EXTERNAL_${t.id.toUpperCase()}_SECRET)`,description:Be`
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:Yt,links:e}),url:s.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:Yt,links:e}),redirect_uri:s.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:Yt,links:e}),skip_nonce_check:s.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:Yt,links:e}),email_optional:s.boolean({default:false,description:"If true, an email address is not required to sign in with this provider.",tags:Yt,links:e})}).partial()},ef=s.strictObject({apple:me({id:"apple",name:"Apple"}),azure:me({id:"azure",name:"Azure"}),bitbucket:me({id:"bitbucket",name:"Bitbucket"}),discord:me({id:"discord",name:"Discord"}),facebook:me({id:"facebook",name:"Facebook"}),github:me({id:"github",name:"GitHub"}),gitlab:me({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:me({id:"google",name:"Google"}),kakao:me({id:"kakao",name:"Kakao"}),keycloak:me({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:me({id:"linkedin",name:"LinkedIn"}),notion:me({id:"notion",name:"Notion"}),twitch:me({id:"twitch",name:"Twitch"}),twitter:me({id:"twitter",name:"Twitter"}),slack:me({id:"slack",name:"Slack"}),spotify:me({id:"spotify",name:"Spotify"}),workos:me({id:"workos",name:"WorkOS"}),zoom:me({id:"zoom",name:"Zoom"})}).partial();var da=["auth"],pa=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],tf=s.strictObject({timebox:s.string({description:"The timebox for the user session.",tags:da,links:pa}),inactivity_timeout:s.string({description:"The inactivity timeout for the user session.",tags:da,links:pa}),single_per_user:s.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:da,links:pa})}).partial();var se=["auth"],oe={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},nf=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:se,links:[oe.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:se,links:[oe.auth]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:se,links:[oe.auth]}),max_frequency:s.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:se}),twilio:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),twilio_verify:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:se,links:[oe.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:se,links:[oe.phoneLogin("Twilio")]})}).partial(),messagebird:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:se,links:[oe.phoneLogin("MessageBird")]}),originator:s.string({description:"The originator of the SMS message.",tags:se,links:[oe.phoneLogin("MessageBird")]}),api_key:s.string({description:"The API key for the MessageBird API.",tags:se,links:[oe.phoneLogin("MessageBird")]})}).partial(),textlocal:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:s.string({description:"The API key for the Textlocal API.",tags:se,links:[oe.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:se,links:[oe.phoneLogin("Vonage")]}),from:s.string({description:"The sender of the SMS message.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_key:s.string({description:"The API key for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]}),api_secret:s.string({description:"The API secret for the Vonage API.",tags:se,links:[oe.phoneLogin("Vonage")]})}).partial(),test_otp:s.record(s.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:se,links:[oe.auth]})}).partial();var Ce=["auth"],Ie={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},rf=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],sf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local GoTrue service.",tags:Ce,links:[Ie.auth]}),jwt_secret:s.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Ce,links:[Ie.auth]}),publishable_key:s.string({description:"The `sb_publishable_*` API key clients use to authenticate as `anon`.",tags:Ce,links:[Ie.auth]}),secret_key:s.string({description:"The `sb_secret_*` API key clients use to authenticate as `service_role`.",tags:Ce,links:[Ie.auth]}),site_url:s.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:Ce,links:[Ie.auth]}),additional_redirect_urls:s.array(s.string({description:"A URL that auth providers are permitted to redirect to.",tags:Ce}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Ce,links:[Ie.auth]}),jwt_expiry:s.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Ce,links:[Ie.auth]}),enable_refresh_token_rotation:s.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Ce,links:[Ie.auth]}),refresh_token_reuse_interval:s.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:Ce,links:[Ie.auth]}),enable_manual_linking:s.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Ce,links:[Ie.auth]}),enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Ce,links:[Ie.auth]}),enable_anonymous_sign_ins:s.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Ce,links:[Ie.auth]}),minimum_password_length:s.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Ce,links:[Ie.auth]}),password_requirements:s.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${rf.join(", ")}`,enum:["",...rf],tags:Ce,links:[Ie.auth]}),hook:Yu,mfa:Xu,sessions:tf,email:Qu,sms:nf,external:ef}).partial();var Xt={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}`:""}`})},ke=["database"],of=s.object({driver:Pt(s.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite-postgres",description:"The database driver to use.",tags:ke})),url:Pt(s.string({description:"Path to the database file/directory (Supalite only).",tags:ke})),port:s.number({default:54322,description:"Port to use for the local database URL.",tags:ke,links:[Xt.postgres]}),shadow_port:s.number({default:54320,description:"Port to use for the local shadow database.",tags:ke}),major_version:s.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:ke,links:[Xt.postgres]}),pooler:s.object({enabled:s.boolean({default:false,description:"Enable the local PgBouncer service.",tags:ke,links:[Xt.pgbouncer()]}),port:s.number({default:54329,description:"Port to use for the local connection pooler.",tags:ke,links:[Xt.pgbouncer("listen_port")]}),pool_mode:s.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:ke,links:[Xt.pgbouncer("pool_mode")]}),default_pool_size:s.number({default:20,description:"How many server connections to allow per user/database pair.",tags:ke,links:[Xt.pgbouncer("default_pool_size")]}),max_client_conn:s.number({default:100,description:"Maximum number of client connections allowed.",tags:ke,links:[Xt.pgbouncer("max_client_conn")]})}).partial(),seed:s.strictObject({enabled:s.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:ke}),sql_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{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:ke})}).partial(),migrations:s.strictObject({enabled:s.boolean({default:true,description:"Enable migrations.",tags:ke}),schema_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:ke}),{default:["./schemas/schema.sql"]})}).partial()}).partial();var ma=["edge-functions"],af=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:ma}),policy:s.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:ma}),inspector_port:s.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:ma})}).partial();var Sr=["experimental"],cf=s.strictObject({orioledb_version:s.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Sr}),s3_host:gt({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Sr}),s3_region:gt({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Sr}),s3_access_key:gt({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Sr}),s3_secret_key:gt({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Sr})}).partial();var si=["functions"],ii=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],Ob=yt.strictObject({enabled:yt.boolean({default:true,description:je`
42
+ `,tags:nn,links:e}),url:s.string({description:"The base URL used for constructing the URLs to request authorization and access tokens.",...t.url,tags:nn,links:e}),redirect_uri:s.string({description:`The URI the ${t.name} OAuth2 provider will redirect to with the code and state values.`,tags:nn,links:e}),skip_nonce_check:s.boolean({default:false,description:"If true, the nonce check will be skipped.",tags:nn,links:e}),email_optional:s.boolean({default:false,description:"If true, an email address is not required to sign in with this provider.",tags:nn,links:e})}).partial()},Af=s.strictObject({apple:be({id:"apple",name:"Apple"}),azure:be({id:"azure",name:"Azure"}),bitbucket:be({id:"bitbucket",name:"Bitbucket"}),discord:be({id:"discord",name:"Discord"}),facebook:be({id:"facebook",name:"Facebook"}),github:be({id:"github",name:"GitHub"}),gitlab:be({id:"gitlab",name:"Gitlab",url:{default:"https://gitlab.com"}}),google:be({id:"google",name:"Google"}),kakao:be({id:"kakao",name:"Kakao"}),keycloak:be({id:"keycloak",name:"Keycloak",url:{examples:["https://keycloak.example.com/realms/myrealm"]}}),linkedin:be({id:"linkedin",name:"LinkedIn"}),notion:be({id:"notion",name:"Notion"}),twitch:be({id:"twitch",name:"Twitch"}),twitter:be({id:"twitter",name:"Twitter"}),slack:be({id:"slack",name:"Slack"}),spotify:be({id:"spotify",name:"Spotify"}),workos:be({id:"workos",name:"WorkOS"}),zoom:be({id:"zoom",name:"Zoom"})}).partial();var Pa=["auth"],$a=[{name:"User sessions",link:"https://supabase.com/docs/guides/auth/sessions"}],vf=s.strictObject({timebox:s.string({description:"The timebox for the user session.",tags:Pa,links:$a}),inactivity_timeout:s.string({description:"The inactivity timeout for the user session.",tags:Pa,links:$a}),single_per_user:s.boolean({default:false,description:"Limit each user to one active refreshable session.",tags:Pa,links:$a})}).partial();var ae=["auth"],ce={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"},phoneLogin:t=>({name:`Enabling Phone Login (${t})`,link:`https://supabase.com/docs/guides/auth/phone-login?showSmsProvider=${t}#enabling-phone-login`})},Of=s.strictObject({enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups via SMS to your project.",tags:ae,links:[ce.auth]}),enable_confirmations:s.boolean({default:false,description:"If enabled, users need to confirm their phone number before signing in.",tags:ae,links:[ce.auth]}),template:s.string({default:"Your code is {{ .Code }}",description:"The template to use for the SMS message.",tags:ae,links:[ce.auth]}),max_frequency:s.string({default:"60s",description:"Controls the minimum amount of time that must pass before sending another sms otp.",tags:ae}),twilio:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio provider for phone login.",tags:ae,links:[ce.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]})}).partial(),twilio_verify:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Twilio Verify provider for phone verification.",tags:ae,links:[ce.phoneLogin("Twilio")]}),account_sid:s.string({description:"The account SID for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]}),message_service_sid:s.string({description:"The message service SID for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]}),auth_token:s.string({description:"The auth token for the Twilio API.",tags:ae,links:[ce.phoneLogin("Twilio")]})}).partial(),messagebird:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable MessageBird provider for phone login.",tags:ae,links:[ce.phoneLogin("MessageBird")]}),originator:s.string({description:"The originator of the SMS message.",tags:ae,links:[ce.phoneLogin("MessageBird")]}),api_key:s.string({description:"The API key for the MessageBird API.",tags:ae,links:[ce.phoneLogin("MessageBird")]})}).partial(),textlocal:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Textlocal provider for phone login.",tags:ae,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),sender:s.string({description:"The sender of the SMS message.",tags:ae,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]}),api_key:s.string({description:"The API key for the Textlocal API.",tags:ae,links:[ce.phoneLogin("Textlocal%2520(Community%2520Supported)")]})}).partial(),vonage:s.strictObject({enabled:s.boolean({default:false,description:"Enable/disable Vonage provider for phone login.",tags:ae,links:[ce.phoneLogin("Vonage")]}),from:s.string({description:"The sender of the SMS message.",tags:ae,links:[ce.phoneLogin("Vonage")]}),api_key:s.string({description:"The API key for the Vonage API.",tags:ae,links:[ce.phoneLogin("Vonage")]}),api_secret:s.string({description:"The API secret for the Vonage API.",tags:ae,links:[ce.phoneLogin("Vonage")]})}).partial(),test_otp:s.record(s.string(),{description:"Use pre-defined map of phone number to OTP for testing.",tags:ae,links:[ce.auth]})}).partial();var Oe=["auth"],Fe={auth:{name:"Auth Server configuration",link:"https://supabase.com/docs/reference/auth"}},Pf=["letters_digits","lower_upper_letters_digits","lower_upper_letters_digits_symbols"],$f=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local GoTrue service.",tags:Oe,links:[Fe.auth]}),jwt_secret:s.string({default:"unsafe-secret-change-me",description:"The secret used to sign JWT tokens.",tags:Oe,links:[Fe.auth]}),publishable_key:s.string({description:"The `sb_publishable_*` API key clients use to authenticate as `anon`.",tags:Oe,links:[Fe.auth]}),secret_key:s.string({description:"The `sb_secret_*` API key clients use to authenticate as `service_role`.",tags:Oe,links:[Fe.auth]}),site_url:s.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:Oe,links:[Fe.auth]}),additional_redirect_urls:s.array(s.string({description:"A URL that auth providers are permitted to redirect to.",tags:Oe}),{default:["https://localhost:3000"],description:"A list of _exact_ URLs that auth providers are permitted to redirect to post authentication.",tags:Oe,links:[Fe.auth]}),jwt_expiry:s.number({default:3600,description:"How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one week).",tags:Oe,links:[Fe.auth]}),enable_refresh_token_rotation:s.boolean({default:true,description:"If disabled, the refresh token will never expire.",tags:Oe,links:[Fe.auth]}),refresh_token_reuse_interval:s.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:Oe,links:[Fe.auth]}),enable_manual_linking:s.boolean({default:false,description:"Allow/disallow testing manual linking of accounts.",tags:Oe,links:[Fe.auth]}),enable_signup:s.boolean({default:true,description:"Allow/disallow new user signups to your project.",tags:Oe,links:[Fe.auth]}),enable_anonymous_sign_ins:s.boolean({default:false,description:"Allow/disallow anonymous sign-ins to your project.",tags:Oe,links:[Fe.auth]}),minimum_password_length:s.number({default:6,description:"Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.",tags:Oe,links:[Fe.auth]}),password_requirements:s.string({description:`Passwords that do not meet the following requirements will be rejected as weak. Supported values are: ${Pf.join(", ")}`,enum:["",...Pf],tags:Oe,links:[Fe.auth]}),hook:Rf,mfa:Cf,sessions:vf,email:Tf,sms:Of,external:Af}).partial();var rn={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}`:""}`})},Pe=["database"],Nf=s.object({driver:Nt(s.string({enum:["sqlite","sqlite-postgres","pglite","postgres"],default:"sqlite-postgres",description:"The database driver to use.",tags:Pe})),url:Nt(s.string({description:"Path to the database file/directory (Supalite only).",tags:Pe})),port:s.number({default:54322,description:"Port to use for the local database URL.",tags:Pe,links:[rn.postgres]}),shadow_port:s.number({default:54320,description:"Port to use for the local shadow database.",tags:Pe}),major_version:s.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:Pe,links:[rn.postgres]}),pooler:s.object({enabled:s.boolean({default:false,description:"Enable the local PgBouncer service.",tags:Pe,links:[rn.pgbouncer()]}),port:s.number({default:54329,description:"Port to use for the local connection pooler.",tags:Pe,links:[rn.pgbouncer("listen_port")]}),pool_mode:s.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:Pe,links:[rn.pgbouncer("pool_mode")]}),default_pool_size:s.number({default:20,description:"How many server connections to allow per user/database pair.",tags:Pe,links:[rn.pgbouncer("default_pool_size")]}),max_client_conn:s.number({default:100,description:"Maximum number of client connections allowed.",tags:Pe,links:[rn.pgbouncer("max_client_conn")]})}).partial(),seed:s.strictObject({enabled:s.boolean({default:true,description:"Enable seeding the database with SQL files.",tags:Pe}),sql_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:Pe}),{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:Pe})}).partial(),migrations:s.strictObject({enabled:s.boolean({default:true,description:"Enable migrations.",tags:Pe}),schema_paths:s.array(s.string({description:"Path to a SQL file to seed the database with.",tags:Pe}),{default:["./schemas/schema.sql"]})}).partial()}).partial();var Na=["edge-functions"],If=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Edge Runtime service.",tags:Na}),policy:s.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:Na}),inspector_port:s.number({default:8083,description:"Port to run the Edge Functions inspector on.",tags:Na})}).partial();var Cr=["experimental"],jf=s.strictObject({orioledb_version:s.string({description:"Postgres storage engine to use OrioleDB (S3)",tags:Cr}),s3_host:wt({description:"S3 bucket URL.",examples:["<bucket_name>.s3-<region>.amazonaws.com"],default:"env(S3_HOST)",tags:Cr}),s3_region:wt({description:"S3 bucket region.",examples:["us-east-1"],default:"env(S3_REGION)",tags:Cr}),s3_access_key:wt({description:"S3 access key.",default:"env(S3_ACCESS_KEY)",tags:Cr}),s3_secret_key:wt({description:"S3 secret key.",default:"env(S3_SECRET_KEY)",tags:Cr})}).partial();var pi=["functions"],mi=[{name:"`supabase functions` CLI subcommands",link:"https://supabase.com/docs/reference/cli/supabase-functions"}],uw=St.strictObject({enabled:St.boolean({default:true,description:Be`
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:si,links:ii}),verify_jwt:yt.boolean({default:true,description:je`
47
+ `,tags:pi,links:mi}),verify_jwt:St.boolean({default:true,description:Be`
48
48
  By default, when you deploy your Edge Functions or serve them locally, it
49
49
  will reject requests without a valid JWT in the Authorization header.
50
50
  Setting this configuration changes the default behavior.
51
- `,tags:si,links:ii}),import_map:yt.string({description:je`
51
+ `,tags:pi,links:mi}),import_map:St.string({description:Be`
52
52
  Specify the Deno import map file to use for the Function.
53
53
 
54
54
  Note that the \`--import-map\` flag overrides this configuration.
55
- `,tags:si,links:ii}),entrypoint:yt.string({description:je`
55
+ `,tags:pi,links:mi}),entrypoint:St.string({description:Be`
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:si,links:ii})}).partial(),uf=yt.strictObject({},{patternProperties:{"^[a-zA-Z0-9_-]+$":Ob}});var oi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],ai=["local"],ff=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local InBucket service.",tags:ai,links:oi}),port:s.number({default:54324,description:je`
59
+ `,tags:pi,links:mi})}).partial(),Lf=St.strictObject({},{patternProperties:{"^[a-zA-Z0-9_-]+$":uw}});var hi=[{name:"Inbucket documentation",link:"https://www.inbucket.org"}],gi=["local"],Ff=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local InBucket service.",tags:gi,links:hi}),port:s.number({default:54324,description:Be`
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.
63
- `,tags:ai,links:oi}),smtp_port:s.number({default:54325,description:je`
63
+ `,tags:gi,links:hi}),smtp_port:s.number({default:54325,description:Be`
64
64
  Port to use for the email testing server SMTP port.
65
65
 
66
66
  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.
67
67
 
68
68
  If set, you can access the SMTP server from this port.
69
- `,tags:ai,links:oi}),pop3_port:s.number({default:54326,description:je`
69
+ `,tags:gi,links:hi}),pop3_port:s.number({default:54326,description:Be`
70
70
  Port to use for the email testing server POP3 port.
71
71
 
72
72
  Emails sent with the local dev setup are not actually sent - rather, they are monitored, and you can view the emails that would have been sent from the web interface.
73
73
 
74
74
  If set, you can access the POP3 server from this port.
75
- `,tags:ai,links:oi})}).partial();var Pb=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],ha=["realtime"],df=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Realtime service.",tags:ha,links:Pb}),ip_version:s.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:ha,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:s.number({default:4096,description:"Maximum length of the HTTP header.",tags:ha})}).partial();var ci=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Dt=["storage"],$b=s.strictObject({public:s.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Dt,links:ci}),allowed_mime_types:s.array(s.string({description:"A MIME type allowed for the bucket.",tags:Dt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Dt}),objects_path:s.string({description:"The path to the objects in the bucket.",tags:Dt})}).partial(),pf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Storage service.",tags:Dt,links:ci}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Dt,links:ci}),image_transformation:s.strictObject({enabled:s.boolean({default:true,description:"Enable image transformation.",tags:Dt,links:ci})}).partial(),buckets:s.record($b,{description:"Storage buckets configuration.",tags:Dt})}).partial();var ga={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"}},fi=["studio"],mf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:fi,links:[ga.studio]}),port:s.number({default:54323,description:"Port to use for Supabase Studio.",tags:fi}),api_url:s.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:fi,links:[ga.config]}),openai_api_key:gt({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:fi,links:[ga.config]})}).partial();var pi=yt.strictObject({project_id:yt.string({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:zu,api:Vu,auth:sf,db:of,edge_runtime:af,functions:uf,inbucket:ff,realtime:df,storage:pf,studio:mf,experimental:cf}).partial();var ya=(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 hf=Symbol();var gf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof mi?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Ib(t,{all:n,dot:r}):{}};async function Ib(t,e){let n=await t.formData();return n?Nb(n,e):{}}function Nb(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?Db(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(jb(n,r,s),delete n[r]);}),n}var Db=(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;},jb=(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 wa=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},yf=t=>{let{groups:e,path:n}=Lb(t),r=wa(n);return Fb(r,e)},Lb=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},Fb=(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},hi={},bf=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return hi[r]||(n[2]?hi[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:hi[r]=[t,n[1],true]),hi[r]}return null},gi=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},Ub=t=>gi(t,decodeURI),Sa=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 Ub(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var wf=t=>{let e=Sa(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Zt=(t,e,...n)=>(n.length&&(e=Zt(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),yi=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)},ba=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?gi(t,_a):t):t,Sf=(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 ba(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=ba(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=ba(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},_f=Sf,Ef=(t,e)=>Sf(t,e,true),_a=decodeURIComponent;var xf=t=>gi(t,_a),mi=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#e=n,this.#t={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#e[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?xf(n):n}#i(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?xf(r):r);}return t}#r(t){return this.#e[1]?this.#e[1][t]:t}query(t){return _f(this.url,t)}queries(t){return Ef(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 gf(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.#t[t]=e;}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[hf](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ye={Stringify:1},X=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},Mb=/[&<>'"]/,bi=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];bt(i,a),n=a[0];}}return X(n,e)},bt=(t,e)=>{let n=t.search(Mb);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);},Ea=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]},en=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=>en(l,e,false,r,s))).then(()=>s[0]));return n?X(await o,i):o};var Bb="text/plain; charset=UTF-8",xa=(t,e)=>({"Content-Type":t,...e}),Er=(t,e)=>new Response(t,e),Tf=class{#t;#e;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#t=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.#e??=new mi(this.#t,this.#d,this.#f),this.#e}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||=Er(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=Er(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=Er(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 Er(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,xa(Bb,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,xa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,xa("text/html; charset=UTF-8",n));return typeof t=="object"?en(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??=()=>Er(),this.#c(this))};var ne="ALL",Rf="all",Cf=["get","post","put","delete","options","patch"],wi="Can not add a route since the matcher is already built.",Si=class extends Error{};var kf="__COMPOSED_HANDLER";var qb=t=>t.text("404 Not Found",404),vf=(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)},Af=class Of{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Cf,Rf].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#t=o:this.#i(i,this.#t,o),a.forEach(l=>{this.#i(i,this.#t,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#t=l;for(let c of [i].flat())a.map(f=>{this.#i(c.toUpperCase(),this.#t,f);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(a=>{this.#i(ne,this.#t,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??Sa:wf;}#e(){let e=new Of({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=qb;errorHandler=vf;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===vf?i=s.handler:(i=async(o,a)=>(await ya([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[kf]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#e();return n._basePath=Zt(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=Zt(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(ne,Zt(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=Zt(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 Tf(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=ya(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${Zt("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var _i=[];function Ta(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ne],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],_i];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ei="[^/]+",xr=".*",Tr="(?:|/.*)",tn=Symbol(),Hb=new Set(".\\+*[^]$()");function Wb(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===xr||t===Tr?1:e===xr||e===Tr?-1:t===Ei?1:e===Ei?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Pf=class Ra{#t;#e;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#t!==void 0)throw tn;if(i)return;this.#t=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",xr]:["","",Ei]:o==="/*"?["","",Tr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let f=l[1],u=l[2]||Ei;if(f&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw tn;if(c=this.#n[u],!c){if(Object.keys(this.#n).some(d=>d!==xr&&d!==Tr))throw tn;if(i)return;c=this.#n[u]=new Ra,f!==""&&(c.#e=s.varIndex++);}!i&&f!==""&&r.push([f,c.#e]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(f=>f.length>1&&f!==xr&&f!==Tr))throw tn;if(i)return;c=this.#n[o]=new Ra;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Wb).map(r=>{let s=this.#n[r];return (typeof s.#e=="number"?`(${r})@${s.#e}`:Hb.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#t=="number"&&n.unshift(`#${this.#t}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var $f=class{#t={varIndex:0};#e=new Pf;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.#e.insert(i,e,r,this.#t,n),r}buildRegExp(){let t=this.#e.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 Kb=[/^$/,[],Object.create(null)],If=Object.create(null);function Nf(t){return If[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Jb(){If=Object.create(null);}function Gb(t){let e=new $f,n=[];if(t.length===0)return Kb;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,g]=r[c];d?s[p]=[g.map(([h])=>[h,Object.create(null)]),_i]:f++;let m;try{m=e.insert(p,f,d);}catch(h){throw h===tn?new Si(p):h}d||(n[f]=g.map(([h,y])=>{let w=Object.create(null);for(y-=1;y>=0;y--){let[S,b]=m[y];w[S]=b;}return [h,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 g=Object.keys(p);for(let m=0,h=g.length;m<h;m++)p[g[m]]=a[p[g[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Cn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(Nf(n).test(e))return [...t[n]]}}var xi=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[ne]:Object.create(null)},this.#e={[ne]:Object.create(null)};}add(t,e,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(wi);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[ne]).forEach(l=>{a[t][l]=[...a[ne][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=Nf(e);t===ne?Object.keys(r).forEach(l=>{r[l][e]||=Cn(r[l],e)||Cn(r[ne],e)||[];}):r[t][e]||=Cn(r[t],e)||Cn(r[ne],e)||[],Object.keys(r).forEach(l=>{(t===ne||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===ne||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=yi(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(f=>{(t===ne||t===f)&&(s[f][c]||=[...Cn(r[f],c)||Cn(r[ne],c)||[]],s[f][c].push([n,i-l+a+1]));});}}match=Ta;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#n(e);}),this.#t=this.#e=void 0,Jb(),t}#n(t){let e=[],n=t===ne;return [this.#t,this.#e].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!==ne&&e.push(...Object.keys(r[ne]).map(i=>[i,r[ne][i]]));}),n?Gb(e):null}};var Ca=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers;}add(t,e,n){if(!this.#e)throw new Error(wi);this.#e.push([t,e,n]);}match(t,e){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,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 Si)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Rr=Object.create(null),zb=t=>{for(let e in t)return true;return false},Df=class jf{#t;#e;#n;#i=0;#r=Rr;constructor(e,n,r){if(this.#e=r||Object.create(null),this.#t=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#t=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=yf(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],f=i[a+1],u=bf(c,f),d=Array.isArray(u)?u[0]:c;if(d in s.#e){s=s.#e[d],u&&o.push(u[1]);continue}s.#e[d]=new jf,u&&(s.#n.push(u),o.push(u[1])),s=s.#e[d];}return s.#t.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.#t.length;o<a;o++){let l=n.#t[o],c=l[r]||l[ne],f={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Rr||i&&i!==Rr))for(let u=0,d=c.possibleKeys.length;u<d;u++){let p=c.possibleKeys[u],g=f[c.score];c.params[p]=i?.[p]&&!g?i[p]:s[p]??i?.[p],f[c.score]=true;}}}search(e,n){let r=[];this.#r=Rr;let i=[this],o=wa(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 m=0,h=i.length;m<h;m++){let y=i[m],w=y.#e[u];w&&(w.#r=y.#r,d?(w.#e["*"]&&this.#s(r,w.#e["*"],e,y.#r),this.#s(r,w,e,y.#r)):p.push(w));for(let S=0,b=y.#n.length;S<b;S++){let _=y.#n[S],E=y.#r===Rr?{}:{...y.#r};if(_==="*"){let C=y.#e["*"];C&&(this.#s(r,C,e,y.#r),C.#r=E,p.push(C));continue}let[x,O,v]=_;if(!u&&!(v instanceof RegExp))continue;let P=y.#e[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let U=n[0]==="/"?1:0;for(let J=0;J<l;J++)c[J]=U,U+=o[J].length+1;}let C=n.substring(c[f]),R=v.exec(C);if(R){if(E[O]=R[0],this.#s(r,P,e,y.#r,E),zb(P.#e)){P.#r=E;let U=R[0].match(/\//)?.length??0;(a[U]||=[]).push(P);}continue}}(v===true||v.test(u))&&(E[O]=u,d?(this.#s(r,P,e,E,y.#r),P.#e["*"]&&this.#s(r,P.#e["*"],e,E,y.#r)):(P.#r=E,p.push(P)));}}let g=a.shift();i=g?p.concat(g):p;}return r.length>1&&r.sort((f,u)=>f.score-u.score),[r.map(({handler:f,params:u})=>[f,u])]}};var ka=class{name="TrieRouter";#t;constructor(){this.#t=new Df;}add(t,e,n){let r=yi(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#t.insert(t,r[s],n);return}this.#t.insert(t,e,n);}match(t,e){return this.#t.search(t,e)}};var _e=class extends Af{constructor(t={}){super(t),this.router=t.router??new Ca({routers:[new xi,new ka]});}};var Lf=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(f,u){o.res.headers.set(f,u);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let f=await s(o.req.header("origin")||"",o);f.length&&l("Access-Control-Allow-Methods",f.join(","));let u=n.allowHeaders;if(!u?.length){let d=o.req.header("Access-Control-Request-Headers");d&&(u=d.split(/\s*,\s*/));}return u?.length&&(l("Access-Control-Allow-Headers",u.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};var kn=Symbol("lite-internal-request"),Ff=Symbol("lite-peer-address");var Vb=["/rest/v1","/storage/v1"],Qb=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Yb(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let r=e.indexOf("]");return r===-1?e:e.slice(0,r+1)}let n=e.indexOf(":");return n===-1?e:e.slice(0,n)}function Xb(t){let e=t.trim().toLowerCase();return e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e=e.split("%")[0],e==="::1"?true:(e.startsWith("::ffff:")&&(e=e.slice(7)),e==="localhost"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e))}function Zb(t){let e=t.req.header("Origin");if(!e)return true;try{return new URL(e).origin.toLowerCase()===new URL(t.req.url).origin.toLowerCase()}catch{return false}}function ew(t){let e=t.req.header("Host")??new URL(t.req.url).host;if(!Qb.has(Yb(e)))return false;let n=t.req.raw[Ff];return typeof n=="string"&&n.length>0?Xb(n):true}function tw(t){return t.req.header("apikey")!==void 0||t.req.query("apikey")!==void 0||t.req.header("Authorization")!==void 0}function va(t){return Zb(t)&&ew(t)}function nw(t){return t.req.method==="OPTIONS"||!Vb.some(e=>t.req.path.startsWith(e))||tw(t)?false:va(t)}function Uf(t){return async(e,n)=>nw(e)?(e.set("admin",true),e.set("apiKeyType","secret"),e.set("ignoreAuthorization",true),e.set("jwt",{role:"service_role"}),n()):t(e,n)}var qf=t=>JSON.parse(jsonStringify(t)),Mf="[redacted]";function Bf(t){let e=qf(t);return e?.auth&&typeof e.auth=="object"&&("secret_key"in e.auth&&(e.auth.secret_key=Mf),"jwt_secret"in e.auth&&(e.auth.jwt_secret=Mf)),e}var Hf=new _e().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(Bf(t.var.app.config))).get("/info",t=>t.json({connection:qf(t.var.app.connection.config),config:Bf(t.var.app.config),admin:t.var.app.adminMode&&va(t)})).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var ve=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;}},He=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},jt=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},vn=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},An=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},fe=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var sw="/rest/v1";function Aa(t,e=sw){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 vn;return {from:s[0]||void 0,isRpc:false}}function Oa(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 Wf=new Set(["count","sum","avg","min","max"]);function W(t){return t.input[t.pos]??""}function q(t,e=1){t.pos+=e;}function Oe(t){return t.pos>=t.input.length}function Ae(t,e){return t.input.startsWith(e,t.pos)}function $a(t){return /^[a-zA-Z0-9_]$/.test(t)}function z(t){for(;!Oe(t)&&/\s/.test(W(t));)q(t);}function Na(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 He("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=zf(i,r,s);if(z(i),iw(i),!Oe(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(ow(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function iw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;W(t)==="'";)q(t);t.pos!==n&&z(t);}function ow(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(aw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function aw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function zf(t,e,n){let r=[];if(z(t),Oe(t)||W(t)===")"||W(t)===","&&(q(t),z(t),Oe(t)||W(t)===")"))return r;for(r.push(Kf(t,e,n));!Oe(t)&&(z(t),W(t)===",");)q(t),z(t),r.push(Kf(t,e,n));return r}function Kf(t,e,n){if(z(t),W(t)==="*")return q(t),fw(t),Ae(t,".count()")&&q(t,8),"*";if(Ae(t,"..."))return q(t,3),z(t),lw(t,e,n);let r=Xe(t,{allowSpaces:true,allowDollar:true});return z(t),Ae(t,"::")?Ia(r,void 0,t,e,n):W(t)===":"?(q(t),z(t),cw(r,t,e,n)):Ia(r,void 0,t,e,n)}function lw(t,e,n){let r=Xe(t);z(t);let{hint:s,innerJoin:i}=Vf(t);if(z(t),W(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=Qf(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 cw(t,e,n,r){let s=Xe(e,{allowSpaces:true,allowDollar:true});return z(e),Ia(s,t,e,n,r)}function Ia(t,e,n,r,s){return z(n),t==="count"&&(Oe(n)||W(n)===","||W(n)===")"||W(n)==="("||Ae(n,"::"))?pw(e,n):W(n)==="!"||W(n)==="("?uw(t,e,n,r,s):mw(t,e,n)}function uw(t,e,n,r,s){let{hint:i,innerJoin:o}=Vf(n);if(z(n),W(n)!=="(")throw new He("failed to parse select parameter");let{subSelect:a,subJoin:l}=Qf(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 Vf(t){if(z(t),W(t)!=="!")return {};q(t);let e=Xe(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(z(t),W(t)==="!"){q(t);let r=Xe(t);if(r==="inner")return {hint:n,innerJoin:true};if(r==="left")return {hint:n};throw new Error(`Expected "inner" or "left" after hint, got "${r}" at position ${t.pos}`)}return {hint:n}}function fw(t){for(;W(t)==="*";)q(t);for(;W(t)==="!";){let e=t.pos;if(q(t),!dw(t)){t.pos=e;return}}}function dw(t){let e=t.pos;try{return Xe(t),!0}catch{return t.pos=e,false}}function Qf(t,e,n){if(W(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);q(t),z(t);let r={},s=new Set;if(W(t)===")")return q(t),{subSelect:[],subJoin:r};let i=zf(t,r,s);if(z(t),W(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return q(t),{subSelect:i,subJoin:r}}function pw(t,e){z(e);let n=true;if(W(e)==="("){n=false,q(e);let o=e.pos;for(;!Oe(e)&&W(e)!==")";)q(e);if(Oe(e))throw new He("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(q(e),a!=="")throw new He("expected null arg for count()")}z(e);let r;Ae(e,"::")&&(q(e,2),r=kr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function mw(t,e,n){z(n);let r,s,i=false,o;if(Ae(n,"->")){let{path:f,lastProp:u,lastIsText:d,invalidTextTraversalKey:p}=hw(n);r=f,s=u||void 0,i=d,o=p;}z(n);let a,l;if(Ae(n,"::")){q(n,2);let f=kr(n);if(z(n),W(n)==="."&&!Oe(n)){let u=n.input[n.pos+1]??"";if($a(u)){let d=n.pos;q(n);let p=Xe(n);if(Wf.has(p)&&Ae(n,"()"))return a=f,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Pa(n)),Jf(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=f,Pa(n);}let c;if(W(n)==="."&&!Oe(n)){let f=n.input[n.pos+1]??"";if($a(f)){let u=n.pos;q(n);let d=Xe(n);Wf.has(d)&&Ae(n,"()")?(c=d,q(n,2),z(n),Ae(n,"::")&&(q(n,2),l=kr(n),Pa(n))):n.pos=u;}}return Jf(t,e,r,s,i,o,a,c,l)}function Pa(t){for(z(t);Ae(t,"::");)q(t,2),kr(t),z(t);}function kr(t){z(t);let e=[Xe(t)];for(;!Oe(t);){let n=t.pos;if(z(t),t.pos===n)break;let r=W(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(Xe(t));}return e.join(" ")}function Jf(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 hw(t){let e=[],n="",r=false,s;for(;Ae(t,"->");){let o=r;q(t,2);let a=false;W(t)===">"&&(q(t),a=true);let l=gw(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 gw(t){return yw(t)}var Gf=new Set(["(",".",">","<"]);function Cr(t,e,n){throw new He(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function yw(t){z(t);let e=t.pos;if(W(t)==='"')return Xe(t);let n="";for(;!Oe(t)&&!(Ae(t,"->")||Ae(t,"::"));){let s=W(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,q(t);}n===""&&Cr(t,e+1,"unexpected end of input");let r=n[0]??"";Gf.has(r)&&Cr(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];Gf.has(i)&&Cr(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;Cr(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&Cr(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new He("failed to parse select parameter");return n}function Xe(t,e={}){if(z(t),W(t)==='"'){q(t);let r="";for(;!Oe(t)&&W(t)!=='"';)r+=W(t),q(t);if(Oe(t))throw new Error(`Missing closing quote at position ${t.pos}`);return q(t),r}let n="";for(;!Oe(t);){let r=W(t);if($a(r))n+=r,q(t);else if(e.allowDollar&&r==="$")n+=r,q(t);else if(e.allowSpaces&&r===" ")n+=r,q(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,q(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 He("failed to parse select parameter");return n}var bw=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function ww(t){return t.split(";")[0]?.trim().toLowerCase()??""}var vr=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function Da(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=ww(r);if(!n&&r.includes("text/csv"))throw new On('parse error (not enough input) at ""');if(!n)return {};if(s&&!bw.has(s))throw new vr(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:Sw(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function Sw(t){let e=t.replace(/\r\n/g,`
75
+ `,tags:gi,links:hi})}).partial();var fw=[{name:"Supabase Realtime",link:"https://supabase.com/docs/guides/realtime"}],Ia=["realtime"],Uf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Realtime service.",tags:Ia,links:fw}),ip_version:s.string({enum:["IPv4","IPv6"],default:"IPv4",description:"Bind realtime via either IPv4 or IPv6.",tags:Ia,links:[{name:"Supabase Realtime Configuration",link:"https://supabase.com/docs/guides/realtime/self-hosting"}]}),max_header_length:s.number({default:4096,description:"Maximum length of the HTTP header.",tags:Ia})}).partial();var bi=[{name:"Storage server configuration",link:"https://supabase.com/docs/guides/self-hosting/storage/config"}],Lt=["storage"],dw=s.strictObject({public:s.boolean({default:false,description:"Enable public access to the bucket."}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed for the bucket.",examples:["5MB","500KB"],tags:Lt,links:bi}),allowed_mime_types:s.array(s.string({description:"A MIME type allowed for the bucket.",tags:Lt}),{examples:[["image/png","image/jpeg"]],description:"The list of allowed MIME types for the bucket.",tags:Lt}),objects_path:s.string({description:"The path to the objects in the bucket.",tags:Lt})}).partial(),Mf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Storage service.",tags:Lt,links:bi}),file_size_limit:s.string({default:"50MiB",description:"The maximum file size allowed.",examples:["5MB","500KB"],tags:Lt,links:bi}),image_transformation:s.strictObject({enabled:s.boolean({default:true,description:"Enable image transformation.",tags:Lt,links:bi})}).partial(),buckets:s.record(dw,{description:"Storage buckets configuration.",tags:Lt})}).partial();var Da={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"}},Si=["studio"],Bf=s.strictObject({enabled:s.boolean({default:true,description:"Enable the local Supabase Studio dashboard.",tags:Si,links:[Da.studio]}),port:s.number({default:54323,description:"Port to use for Supabase Studio.",tags:Si}),api_url:s.string({default:"http://localhost",description:"External URL of the API server that frontend connects to.",tags:Si,links:[Da.config]}),openai_api_key:wt({default:"env(OPENAI_API_KEY)",description:"OpenAI API key to use for Supabase AI in the Supabase Studio.",tags:Si,links:[Da.config]})}).partial();var Ei=St.strictObject({project_id:St.string({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:Ef,api:xf,auth:$f,db:Nf,edge_runtime:If,functions:Lf,inbucket:Ff,realtime:Uf,storage:Mf,studio:Bf,experimental:jf}).partial();var ja=(t,e,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(t[a]?(u=t[a][0][0],r.req.routeIndex=a):u=a===t.length&&s||void 0,u)try{l=await u(r,()=>o(a+1));}catch(f){if(f instanceof Error&&e)r.error=f,l=await e(f,r),c=true;else throw f}else r.finalized===false&&n&&(l=await n(r));return l&&(r.finalized===false||c)&&(r.res=l),r}};var xi=Symbol();var qf=async(t,e=Object.create(null))=>{let{all:n=false,dot:r=false}=e,i=(t instanceof Ti?t.raw.headers:t.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?pw(t,{all:n,dot:r}):{}};async function pw(t,e){let n=await t.formData();return n?mw(n,e):{}}function mw(t,e){let n=Object.create(null);return t.forEach((r,s)=>{e.all||s.endsWith("[]")?hw(n,s,r):n[s]=r;}),e.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(gw(n,r,s),delete n[r]);}),n}var hw=(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;},gw=(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 Fa=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Ci=t=>{let{groups:e,path:n}=yw(t),r=Fa(n);return bw(r,e)},yw=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return e.push([s,n]),s}),{groups:e,path:t}},bw=(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},Ri={},ki=(t,e)=>{if(t==="*")return "*";let n=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${t}#${e}`;return Ri[r]||(n[2]?Ri[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${e})`)]:[t,n[1],new RegExp(`^${n[2]}$`)]:Ri[r]=[t,n[1],true]),Ri[r]}return null},Ai=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},ww=t=>Ai(t,decodeURI),Ua=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 ww(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return e.slice(n,r)};var Hf=t=>{let e=Ua(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},sn=(t,e,...n)=>(n.length&&(e=sn(e,...n)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),vi=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)},La=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Ai(t,Ma):t):t,Wf=(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 La(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=La(l)),i=o,l==="")continue;let c;a===-1?c="":(c=t.slice(a+1,o===-1?void 0:o),r&&(c=La(c))),n?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return e?s[e]:s},Kf=Wf,Jf=(t,e)=>Wf(t,e,true),Ma=decodeURIComponent;var Gf=t=>Ai(t,Ma),Ti=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",n=[[]]){this.raw=t,this.path=e,this.#e=n,this.#t={};}param(t){return t?this.#n(t):this.#i()}#n(t){let e=this.#e[0][this.routeIndex][1][t],n=this.#r(e);return n&&/\%/.test(n)?Gf(n):n}#i(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let n of e){let r=this.#r(this.#e[0][this.routeIndex][1][n]);r!==void 0&&(t[n]=/\%/.test(r)?Gf(r):r);}return t}#r(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Kf(this.url,t)}queries(t){return Jf(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 qf(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.#t[t]=e;}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[xi](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var et={Stringify:1},Z=(t,e)=>{let n=new String(t);return n.isEscaped=true,n.callbacks=e,n},Sw=/[&<>'"]/,Oi=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 Z(n,e)},_t=(t,e)=>{let n=t.search(Sw);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);},Ba=t=>{let e=t.callbacks;if(!e?.length)return t;let n=[t],r={};return e.forEach(s=>s({phase:et.Stringify,buffer:n,context:r})),n[0]},on=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=>on(l,e,false,r,s))).then(()=>s[0]));return n?Z(await o,i):o};var _w="text/plain; charset=UTF-8",qa=(t,e)=>({"Content-Type":t,...e}),Ar=(t,e)=>new Response(t,e),Vf=class{#t;#e;env={};#n;finalized=false;error;#i;#r;#s;#u;#l;#c;#a;#f;#d;constructor(t,e){this.#t=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.#e??=new Ti(this.#t,this.#d,this.#f),this.#e}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||=Ar(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=Ar(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=Ar(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 Ar(t,{status:s,headers:r})}newResponse=(...t)=>this.#o(...t);body=(t,e,n)=>this.#o(t,e,n);text=(t,e,n)=>!this.#a&&!this.#i&&!e&&!n&&!this.finalized?new Response(t):this.#o(t,e,qa(_w,n));json=(t,e,n)=>this.#o(JSON.stringify(t),e,qa("application/json",n));html=(t,e,n)=>{let r=s=>this.#o(s,e,qa("text/html; charset=UTF-8",n));return typeof t=="object"?on(t,et.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??=()=>Ar(),this.#c(this))};var se="ALL",zf="all",Qf=["get","post","put","delete","options","patch"],Pi="Can not add a route since the matcher is already built.",$i=class extends Error{};var Yf="__COMPOSED_HANDLER";var Ew=t=>t.text("404 Not Found",404),Xf=(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)},Zf=class ed{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Qf,zf].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#t=o:this.#i(i,this.#t,o),a.forEach(l=>{this.#i(i,this.#t,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#t=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#t,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#t=i:(this.#t="*",o.unshift(i)),o.forEach(a=>{this.#i(se,this.#t,a);}),this);let{strict:r,...s}=e;Object.assign(this,s),this.getPath=r??true?e.getPath??Ua:Hf;}#e(){let e=new ed({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#n=this.#n,e.routes=this.routes,e}#n=Ew;errorHandler=Xf;route(e,n){let r=this.basePath(e);return n.routes.map(s=>{let i;n.errorHandler===Xf?i=s.handler:(i=async(o,a)=>(await ja([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[Yf]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(e){let n=this.#e();return n._basePath=sn(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=sn(this._basePath,e),c=l==="/"?0:l.length;return u=>{let f=new URL(u.url);return f.pathname=f.pathname.slice(c)||"/",new Request(f,u)}})();let a=async(l,c)=>{let u=await n(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(se,sn(e,"*"),a),this}#i(e,n,r){e=e.toUpperCase(),n=sn(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 Vf(e,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(u){return this.#r(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#n(a))).catch(u=>this.#r(u,a)):c??this.#n(a)}let l=ja(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${sn("/",e)}`,n),r,s));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method));});}};var Ni=[];function Ha(t,e){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[se],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],Ni];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=r,r(t,e)}var Ii="[^/]+",vr=".*",Or="(?:|/.*)",an=Symbol(),xw=new Set(".\\+*[^]$()");function Tw(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===vr||t===Or?1:e===vr||e===Or?-1:t===Ii?1:e===Ii?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var td=class Wa{#t;#e;#n=Object.create(null);insert(e,n,r,s,i){if(e.length===0){if(this.#t!==void 0)throw an;if(i)return;this.#t=n;return}let[o,...a]=e,l=o==="*"?a.length===0?["","",vr]:["","",Ii]:o==="/*"?["","",Or]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],f=l[2]||Ii;if(u&&l[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))))throw an;if(c=this.#n[f],!c){if(Object.keys(this.#n).some(d=>d!==vr&&d!==Or))throw an;if(i)return;c=this.#n[f]=new Wa,u!==""&&(c.#e=s.varIndex++);}!i&&u!==""&&r.push([u,c.#e]);}else if(c=this.#n[o],!c){if(Object.keys(this.#n).some(u=>u.length>1&&u!==vr&&u!==Or))throw an;if(i)return;c=this.#n[o]=new Wa;}c.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Tw).map(r=>{let s=this.#n[r];return (typeof s.#e=="number"?`(${r})@${s.#e}`:xw.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#t=="number"&&n.unshift(`#${this.#t}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};var nd=class{#t={varIndex:0};#e=new td;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.#e.insert(i,e,r,this.#t,n),r}buildRegExp(){let t=this.#e.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 Rw=[/^$/,[],Object.create(null)],rd=Object.create(null);function sd(t){return rd[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Cw(){rd=Object.create(null);}function kw(t){let e=new nd,n=[];if(t.length===0)return Rw;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[f,d])=>c?1:f?-1:u.length-d.length),s=Object.create(null);for(let c=0,u=-1,f=r.length;c<f;c++){let[d,p,h]=r[c];d?s[p]=[h.map(([g])=>[g,Object.create(null)]),Ni]:u++;let m;try{m=e.insert(p,u,d);}catch(g){throw g===an?new $i(p):g}d||(n[u]=h.map(([g,y])=>{let w=Object.create(null);for(y-=1;y>=0;y--){let[S,b]=m[y];w[S]=b;}return [g,w]}));}let[i,o,a]=e.buildRegExp();for(let c=0,u=n.length;c<u;c++)for(let f=0,d=n[c].length;f<d;f++){let p=n[c][f]?.[1];if(!p)continue;let h=Object.keys(p);for(let m=0,g=h.length;m<g;m++)p[h[m]]=a[p[h[m]]];}let l=[];for(let c in o)l[c]=n[o[c]];return [i,l,s]}function Pn(t,e){if(t){for(let n of Object.keys(t).sort((r,s)=>s.length-r.length))if(sd(n).test(e))return [...t[n]]}}var Di=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[se]:Object.create(null)},this.#e={[se]:Object.create(null)};}add(t,e,n){let r=this.#t,s=this.#e;if(!r||!s)throw new Error(Pi);r[t]||[r,s].forEach(a=>{a[t]=Object.create(null),Object.keys(a[se]).forEach(l=>{a[t][l]=[...a[se][l]];});}),e==="/*"&&(e="*");let i=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=sd(e);t===se?Object.keys(r).forEach(l=>{r[l][e]||=Pn(r[l],e)||Pn(r[se],e)||[];}):r[t][e]||=Pn(r[t],e)||Pn(r[se],e)||[],Object.keys(r).forEach(l=>{(t===se||t===l)&&Object.keys(r[l]).forEach(c=>{a.test(c)&&r[l][c].push([n,i]);});}),Object.keys(s).forEach(l=>{(t===se||t===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([n,i]));});return}let o=vi(e)||[e];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(t===se||t===u)&&(s[u][c]||=[...Pn(r[u],c)||Pn(r[se],c)||[]],s[u][c].push([n,i-l+a+1]));});}}match=Ha;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#n(e);}),this.#t=this.#e=void 0,Cw(),t}#n(t){let e=[],n=t===se;return [this.#t,this.#e].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!==se&&e.push(...Object.keys(r[se]).map(i=>[i,r[se][i]]));}),n?kw(e):null}};var Ka=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers;}add(t,e,n){if(!this.#e)throw new Error(Pi);this.#e.push([t,e,n]);}match(t,e){if(!this.#e)throw new Error("Fatal error");let n=this.#t,r=this.#e,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.#t=[a],this.#e=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var Pr=Object.create(null),Aw=t=>{for(let e in t)return true;return false},id=class od{#t;#e;#n;#i=0;#r=Pr;constructor(e,n,r){if(this.#e=r||Object.create(null),this.#t=[],e&&n){let s=Object.create(null);s[e]={handler:n,possibleKeys:[],score:0},this.#t=[s];}this.#n=[];}insert(e,n,r){this.#i=++this.#i;let s=this,i=Ci(n),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],f=ki(c,u),d=Array.isArray(f)?f[0]:c;if(d in s.#e){s=s.#e[d],f&&o.push(f[1]);continue}s.#e[d]=new od,f&&(s.#n.push(f),o.push(f[1])),s=s.#e[d];}return s.#t.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.#t.length;o<a;o++){let l=n.#t[o],c=l[r]||l[se],u={};if(c!==void 0&&(c.params=Object.create(null),e.push(c),s!==Pr||i&&i!==Pr))for(let f=0,d=c.possibleKeys.length;f<d;f++){let p=c.possibleKeys[f],h=u[c.score];c.params[p]=i?.[p]&&!h?i[p]:s[p]??i?.[p],u[c.score]=true;}}}search(e,n){let r=[];this.#r=Pr;let i=[this],o=Fa(n),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let f=o[u],d=u===l-1,p=[];for(let m=0,g=i.length;m<g;m++){let y=i[m],w=y.#e[f];w&&(w.#r=y.#r,d?(w.#e["*"]&&this.#s(r,w.#e["*"],e,y.#r),this.#s(r,w,e,y.#r)):p.push(w));for(let S=0,b=y.#n.length;S<b;S++){let _=y.#n[S],E=y.#r===Pr?{}:{...y.#r};if(_==="*"){let k=y.#e["*"];k&&(this.#s(r,k,e,y.#r),k.#r=E,p.push(k));continue}let[x,O,v]=_;if(!f&&!(v instanceof RegExp))continue;let $=y.#e[x];if(v instanceof RegExp){if(c===null){c=new Array(l);let H=n[0]==="/"?1:0;for(let V=0;V<l;V++)c[V]=H,H+=o[V].length+1;}let k=n.substring(c[u]),N=v.exec(k);if(N){if(E[O]=N[0],this.#s(r,$,e,y.#r,E),Aw($.#e)){$.#r=E;let H=N[0].match(/\//)?.length??0;(a[H]||=[]).push($);}continue}}(v===true||v.test(f))&&(E[O]=f,d?(this.#s(r,$,e,E,y.#r),$.#e["*"]&&this.#s(r,$.#e["*"],e,E,y.#r)):($.#r=E,p.push($)));}}let h=a.shift();i=h?p.concat(h):p;}return r.length>1&&r.sort((u,f)=>u.score-f.score),[r.map(({handler:u,params:f})=>[u,f])]}};var Ja=class{name="TrieRouter";#t;constructor(){this.#t=new id;}add(t,e,n){let r=vi(e);if(r){for(let s=0,i=r.length;s<i;s++)this.#t.insert(t,r[s],n);return}this.#t.insert(t,e,n);}match(t,e){return this.#t.search(t,e)}};var Te=class extends Zf{constructor(t={}){super(t),this.router=t.router??new Ka({routers:[new Di,new Ja]});}};var ad=t=>{let n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(i=>typeof i=="string"?i==="*"?()=>i:o=>i===o?o:null:typeof i=="function"?i:o=>i.includes(o)?o:null)(n.origin),s=(i=>typeof i=="function"?i:Array.isArray(i)?()=>i:()=>[])(n.allowMethods);return async function(o,a){function l(u,f){o.res.headers.set(u,f);}let c=await r(o.req.header("origin")||"",o);if(c&&l("Access-Control-Allow-Origin",c),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),o.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());let u=await s(o.req.header("origin")||"",o);u.length&&l("Access-Control-Allow-Methods",u.join(","));let f=n.allowHeaders;if(!f?.length){let d=o.req.header("Access-Control-Request-Headers");d&&(f=d.split(/\s*,\s*/));}return f?.length&&(l("Access-Control-Allow-Headers",f.join(",")),o.res.headers.append("Vary","Access-Control-Request-Headers")),o.res.headers.delete("Content-Length"),o.res.headers.delete("Content-Type"),new Response(null,{headers:o.res.headers,status:204,statusText:"No Content"})}await a(),n.origin!=="*"&&o.header("Vary","Origin",{append:true});}};Va();var vw=["/rest/v1","/storage/v1"];function Ow(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let r=e.indexOf("]");return r===-1?e:e.slice(0,r+1)}let n=e.indexOf(":");return n===-1?e:e.slice(0,n)}function Pw(t){let e=t.req.header("Origin");if(!e)return true;try{return new URL(e).origin.toLowerCase()===new URL(t.req.url).origin.toLowerCase()}catch{return false}}function $w(t){let e=t.req.header("Host")??new URL(t.req.url).host;if(!ld(Ow(e)))return false;let n=t.env;return n&&Object.hasOwn(n,"peerAddress")?typeof n.peerAddress=="string"&&Ga(n.peerAddress):true}function Nw(t){return t.req.header("apikey")!==void 0||t.req.query("apikey")!==void 0||t.req.header("Authorization")!==void 0}function za(t){return Pw(t)&&$w(t)}function Iw(t){return t.req.method==="OPTIONS"||!vw.some(e=>t.req.path.startsWith(e))||Nw(t)?false:za(t)}function cd(t){return async(e,n)=>Iw(e)?(e.set("admin",true),e.set("apiKeyType","secret"),e.set("ignoreAuthorization",true),e.set("jwt",{role:"service_role"}),n()):t(e,n)}var dd=t=>JSON.parse(jsonStringify(t)),ud="[redacted]";function fd(t){let e=dd(t);return e?.auth&&typeof e.auth=="object"&&("secret_key"in e.auth&&(e.auth.secret_key=ud),"jwt_secret"in e.auth&&(e.auth.jwt_secret=ud)),e}var pd=new Te().get("/ping",t=>t.json({message:"pong"})).get("/config",t=>t.json(fd(t.var.app.config))).get("/info",t=>t.json({connection:dd(t.var.app.connection.config),config:fd(t.var.app.config),admin:t.var.app.adminMode&&za(t)})).get("/introspect",async t=>{let e=await t.var.app.connection.introspect();return t.json(e)});var $e=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;}},ze=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="SelectParseError";}},Ft=class extends Error{constructor(n,r=n){super(n);this.details=r;this.name="QueryParamParseError";}},$n=class extends Error{constructor(n="Invalid path specified in request URL",r=null){super(n);this.details=r;this.name="RouteValidationError";}},Nn=class extends Error{constructor(n){super(`invalid input syntax for type integer: "${n}"`);this.rawValue=n;this.name="SqliteIntegerCastError";}code="22P02"},ge=class extends Error{constructor(n,r,s){super(n);this.details=r;this.position=s;this.name="OrderParseError";}};var jw="/rest/v1";function Qa(t,e=jw){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 $n;return {from:s[0]||void 0,isRpc:false}}function Ya(t){let e=t.method.toUpperCase(),n;e==="GET"||e==="HEAD"?n=t.headers.get("Accept-Profile")??void 0:n=t.headers.get("Content-Profile")??void 0;let r=[],s=[],i=t.headers.get("Prefer");i&&s.push(i);for(let a of s){let l=a.split(",").map(c=>c.trim()).filter(Boolean);for(let c of l){let u=c.indexOf("=");if(u===-1)continue;let f=c.slice(0,u).trim(),d=c.slice(u+1).trim();f==="max-affected"?r.push({key:"max-affected",value:Number(d)}):r.push({key:f,value:d});}}let o=t.headers.get("Accept")??"application/json";return {schema:n,preferTokens:r,accept:o}}var md=new Set(["count","sum","avg","min","max"]);function J(t){return t.input[t.pos]??""}function W(t,e=1){t.pos+=e;}function Ie(t){return t.pos>=t.input.length}function Ne(t,e){return t.input.startsWith(e,t.pos)}function Za(t){return /^[a-zA-Z0-9_]$/.test(t)}function Q(t){for(;!Ie(t)&&/\s/.test(J(t));)W(t);}function tl(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 ze("failed to parse select parameter");let r={},s=new Set;try{let i={input:n,pos:0},o=bd(i,r,s);if(Q(i),Lw(i),!Ie(i))throw new Error(`Unexpected input at position ${i.pos}: "${i.input.slice(i.pos)}"`);return {select:o,join:r,embeddedAliases:s}}catch(i){if(Fw(n))return {select:[],join:{},embeddedAliases:new Set};throw i}}function Lw(t){let e=t.pos-1;for(;e>=0&&/\s/.test(t.input[e]??"");)e--;if(t.input[e]!==")")return;let n=t.pos;for(;J(t)==="'";)W(t);t.pos!==n&&Q(t);}function Fw(t){if(/^\s/.test(t))return false;let e=t.trimStart();if(e==="")return false;if(Uw(e)||e.startsWith("::")||e.startsWith("->"))return true;let n=e[0]??"";return new Set([".",":","!","@","#","%","`","[","-","(","'","~"]).has(n)}function Uw(t){return t.startsWith("...")?!/^\.{3}\s*(?:"[^"]+"|[a-zA-Z_][a-zA-Z0-9_$ -]*)\s*(?:![a-zA-Z_][a-zA-Z0-9_]*)*\s*\(/.test(t):false}function bd(t,e,n){let r=[];if(Q(t),Ie(t)||J(t)===")"||J(t)===","&&(W(t),Q(t),Ie(t)||J(t)===")"))return r;for(r.push(hd(t,e,n));!Ie(t)&&(Q(t),J(t)===",");)W(t),Q(t),r.push(hd(t,e,n));return r}function hd(t,e,n){if(Q(t),J(t)==="*")return W(t),Hw(t),Ne(t,".count()")&&W(t,8),"*";if(Ne(t,"..."))return W(t,3),Q(t),Mw(t,e,n);let r=tt(t,{allowSpaces:true,allowDollar:true});return Q(t),Ne(t,"::")?el(r,void 0,t,e,n):J(t)===":"?(W(t),Q(t),Bw(r,t,e,n)):el(r,void 0,t,e,n)}function Mw(t,e,n){let r=tt(t);Q(t);let{hint:s,innerJoin:i}=wd(t);if(Q(t),J(t)!=="(")throw new Error(`Expected "(" for spread embed at position ${t.pos}`);let{subSelect:o,subJoin:a}=Sd(t),l=r,c={};i&&(c.type="inner"),s&&(c.hint=s),e[l]=c,n.add(l);let u={spread:true,select:o};return Object.keys(a).length>0&&(u.join=a),{[l]:u}}function Bw(t,e,n,r){let s=tt(e,{allowSpaces:true,allowDollar:true});return Q(e),el(s,t,e,n,r)}function el(t,e,n,r,s){return Q(n),t==="count"&&(Ie(n)||J(n)===","||J(n)===")"||J(n)==="("||Ne(n,"::"))?Kw(e,n):J(n)==="!"||J(n)==="("?qw(t,e,n,r,s):Jw(t,e,n)}function qw(t,e,n,r,s){let{hint:i,innerJoin:o}=wd(n);if(Q(n),J(n)!=="(")throw new ze("failed to parse select parameter");let{subSelect:a,subJoin:l}=Sd(n),c=e??t,u={};e&&(u.from=t),o&&(u.type="inner"),i&&(u.hint=i),r[c]=u,s.add(c),e&&t!==c&&s.add(t);let f={select:a};return Object.keys(l).length>0&&(f.join=l),{[c]:f}}function wd(t){if(Q(t),J(t)!=="!")return {};W(t);let e=tt(t);if(e==="inner")return {innerJoin:true};if(e==="left")return {};let n=e;if(Q(t),J(t)==="!"){W(t);let r=tt(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 Hw(t){for(;J(t)==="*";)W(t);for(;J(t)==="!";){let e=t.pos;if(W(t),!Ww(t)){t.pos=e;return}}}function Ww(t){let e=t.pos;try{return tt(t),!0}catch{return t.pos=e,false}}function Sd(t,e,n){if(J(t)!=="(")throw new Error(`Expected "(" at position ${t.pos}`);W(t),Q(t);let r={},s=new Set;if(J(t)===")")return W(t),{subSelect:[],subJoin:r};let i=bd(t,r,s);if(Q(t),J(t)!==")")throw new Error(`Expected ")" at position ${t.pos}`);return W(t),{subSelect:i,subJoin:r}}function Kw(t,e){Q(e);let n=true;if(J(e)==="("){n=false,W(e);let o=e.pos;for(;!Ie(e)&&J(e)!==")";)W(e);if(Ie(e))throw new ze("expected closing paren for count()");let a=e.input.slice(o,e.pos).trim();if(W(e),a!=="")throw new ze("expected null arg for count()")}Q(e);let r;Ne(e,"::")&&(W(e,2),r=Nr(e));let s=t??"count",i={aggregate:"count"};return n&&(i.bareCount=true),r&&(i.cast=r),{[s]:i}}function Jw(t,e,n){Q(n);let r,s,i=false,o;if(Ne(n,"->")){let{path:u,lastProp:f,lastIsText:d,invalidTextTraversalKey:p}=Gw(n);r=u,s=f||void 0,i=d,o=p;}Q(n);let a,l;if(Ne(n,"::")){W(n,2);let u=Nr(n);if(Q(n),J(n)==="."&&!Ie(n)){let f=n.input[n.pos+1]??"";if(Za(f)){let d=n.pos;W(n);let p=tt(n);if(md.has(p)&&Ne(n,"()"))return a=u,W(n,2),Q(n),Ne(n,"::")&&(W(n,2),l=Nr(n),Xa(n)),gd(t,e,r,s,i,o,a,p,l);n.pos=d;}}l=u,Xa(n);}let c;if(J(n)==="."&&!Ie(n)){let u=n.input[n.pos+1]??"";if(Za(u)){let f=n.pos;W(n);let d=tt(n);md.has(d)&&Ne(n,"()")?(c=d,W(n,2),Q(n),Ne(n,"::")&&(W(n,2),l=Nr(n),Xa(n))):n.pos=f;}}return gd(t,e,r,s,i,o,a,c,l)}function Xa(t){for(Q(t);Ne(t,"::");)W(t,2),Nr(t),Q(t);}function Nr(t){Q(t);let e=[tt(t)];for(;!Ie(t);){let n=t.pos;if(Q(t),t.pos===n)break;let r=J(t);if(!(r==='"'||/^[a-zA-Z0-9_]$/.test(r))){t.pos=n;break}e.push(tt(t));}return e.join(" ")}function gd(t,e,n,r,s,i,o,a,l){let c=e??(a||void 0)??r;if(!c&&!o&&!l&&!a&&!n)return t;let u=c??t,f={};return t!==u&&(f.column=t),a&&!f.column&&t===u&&(f.column=t),n&&(f.column||(f.column=t),f.path=n,s&&(f.pathText=true),i&&(f.invalidJsonTextTraversalKey=i)),o&&(f.preCast=o),a&&(f.aggregate=a),l&&(f.cast=l),{[u]:f}}function Gw(t){let e=[],n="",r=false,s;for(;Ne(t,"->");){let o=r;W(t,2);let a=false;J(t)===">"&&(W(t),a=true);let l=Vw(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 Vw(t){return zw(t)}var yd=new Set(["(",".",">","<"]);function $r(t,e,n){throw new ze(`"failed to parse select parameter (${t.input})" (line 1, column ${e})`,n)}function zw(t){Q(t);let e=t.pos;if(J(t)==='"')return tt(t);let n="";for(;!Ie(t)&&!(Ne(t,"->")||Ne(t,"::"));){let s=J(t);if(s===","||s==="."||s===":"||/\s/.test(s))break;n+=s,W(t);}n===""&&$r(t,e+1,"unexpected end of input");let r=n[0]??"";yd.has(r)&&$r(t,e+1,`unexpected "${r}" expecting "-", digit or any non reserved character different from: .,>()`);for(let s=1;s<n.length;s++){let i=n[s];yd.has(i)&&$r(t,e+s+1,`unexpected "${i}" expecting "-", digit or any non reserved character different from: .,>()`);}if(n.includes("--")){let s=n.indexOf("--"),i=s===0&&n.length>1?e+2:e+s+1;$r(t,i,'unexpected "-" expecting digit');}if(n.endsWith("-")&&$r(t,e+n.length,'unexpected "-" expecting digit'),/^-\d+\D/.test(n))throw new ze("failed to parse select parameter");return n}function tt(t,e={}){if(Q(t),J(t)==='"'){W(t);let r="";for(;!Ie(t)&&J(t)!=='"';)r+=J(t),W(t);if(Ie(t))throw new Error(`Missing closing quote at position ${t.pos}`);return W(t),r}let n="";for(;!Ie(t);){let r=J(t);if(Za(r))n+=r,W(t);else if(e.allowDollar&&r==="$")n+=r,W(t);else if(e.allowSpaces&&r===" ")n+=r,W(t);else if(r==="-"&&n.length>0){if((t.input[t.pos+1]??"")===">")break;n+=r,W(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 ze("failed to parse select parameter");return n}var Qw=new Set(["application/json","text/csv","application/x-www-form-urlencoded"]);function Yw(t){return t.split(";")[0]?.trim().toLowerCase()??""}var Ir=class extends Error{mediaType;constructor(e){super(`Content-Type not acceptable: ${e}`),this.name="ContentTypeNotAcceptableError",this.mediaType=e;}};async function nl(t){let e=t.method.toUpperCase();if(e==="GET"||e==="HEAD")return {};let n=await t.text(),r=t.headers.get("Content-Type")??"",s=Yw(r);if(!n&&r.includes("text/csv"))throw new In('parse error (not enough input) at ""');if(!n)return {};if(s&&!Qw.has(s))throw new Ir(s);if(r.includes("application/json")||s===""||s==="application/json")try{let i=JSON.parse(n);return Array.isArray(i)?{values:i}:{values:i}}catch{throw new Error(`Invalid JSON body: ${n.slice(0,100)}`)}if(r.includes("text/csv"))return {values:Xw(n)};if(r.includes("application/x-www-form-urlencoded")){let i=new URLSearchParams(n),o={};for(let[a,l]of i)o[a]=l;return {values:o}}return {raw:n}}function Xw(t){let e=t.replace(/\r\n/g,`
76
76
  `).replace(/\r/g,`
77
- `),n=_w(e);if(n.length===0)throw new On("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 _w(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
78
- `);){let{row:s,nextPos:i}=Ew(t,n);e.push(s),n=i;}return e}function Ew(t,e){let n=[],r=e,s=t.length;for(;r<=s;){if(r===s||t[r]===`
77
+ `),n=Zw(e);if(n.length===0)throw new In("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 Zw(t){let e=[],n=0,r=t.length;for(;n<r&&!(n===r-1&&t[n]===`
78
+ `);){let{row:s,nextPos:i}=eS(t,n);e.push(s),n=i;}return e}function eS(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 On=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function ja(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 La(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 Xf=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"]),Yf={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"},xw={any:"Any",all:"All"},Tw=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),Rw={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function Ti(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!Tw.has(s))return null;let o=Yf[s];return o?{astOp:o+xw[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:Rw[s],ftsConfig:i}}let r=Yf[t];return r?{astOp:r}:null}function Ar(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return Xf.has(r)}var nn=new Set(["select","order","limit","offset","on_conflict","columns","apikey"]);function Or(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(rt(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function rn(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(rt(r));}n<t.length&&t[n]===","&&n++;}return e}var Pn=Symbol.for("postgrest:not_null"),sn=Symbol.for("postgrest:unknown");function rt(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 Pn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Ir(t,e,n,r){let s={},i={};for(let[o,a]of t){if(nn.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let f=o.slice(0,c),u=o.slice(c+1);if(e.has(f)){if(u==="order"||u==="limit"||u==="offset")continue;if(u.includes(".")){let d=u.lastIndexOf("."),p=u.slice(d+1);if(p==="order"||p==="limit"||p==="offset")continue}i[f]||(i[f]={}),Aw(u,a,i[f]);continue}if(o!=="not.or"&&o!=="not.and")throw kw(f)}if(e.has(o)&&!a.every(Cw)&&!r?.has(o)){let f=n?`${n}.${o}`:o,u=new Error(`column ${f} does not exist`);throw u.code="42703",u}Ua(o,a,s);}return {where:s,embeddedWheres:i}}function Cw(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function kw(t){return new ve({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 Ua(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)vw(t,o,n);return}let s=e.map(o=>ed(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=>ed(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=td(Nw(t),{stopAtSpace:false});nd(r);for(let s of e){let i=Ma(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function vw(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=Ma(o);n[i]?Object.assign(n[i],a):n[i]=a;}function Aw(t,e,n){let r=Ow(t);if(!r){Ua(t,e,n);return}let s={};Ua(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function Ow(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 Ma(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=Ti(s);if(!o){let u=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw u?new Error(`"failed to parse filter (${t})" (line 1, column ${u[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:Fa(a,i)};if(n&&a==="$is")return {$isNot:Fa(a,i)};let f=a==="$textSearch"?$w(i,l,c):Fa(a,i);return n?{$not:{[a]:f}}:{[a]:f}}function Fa(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 Or(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return rn(e);if(!Pw(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return Or(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 rn(e)}return e.startsWith("[")||e.startsWith("(")?e:rt(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?sn:s==="not_null"?Pn:s==="null"?null:s==="true"?true:s==="false"?false:rt(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("{")?rn(n):Or(n):n}if(t==="$isDistinct")return e.startsWith("{")?rn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return rn(e)}return rt(e)}function Pw(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function $w(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function Iw(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function Zf(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${Iw(t)})`)}function ed(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 Zf(t);try{return Pr(e).map(r=>$r(r))}catch{throw Zf(t)}}function Pr(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 $r(t){let e=t.trim(),n=e.match(/^and\s*\((.*)\)$/s);if(n)return {$and:Pr(n[1]).map(d=>$r(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Pr(r[1]).map(d=>$r(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Pr(s[1]).map(d=>$r(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Pr(i[1]).map(d=>$r(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let p=o.slice(4).split(".")[0];if(!(p.length>0&&Ti(p)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=td(o.slice(0,l),{stopAtSpace:true});nd(c);let f=o.slice(l+1),u=Ma(f);return {[c]:u}}function td(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function Nw(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function nd(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function Dw(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function rd(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 Ba(t,e){let n=rd(t),r=rd(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 Ha(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let g=p[0],m=d.indexOf(".");if(m>0){let h=d.slice(0,m),y=d.slice(m+1);if(e.has(h)){if(y==="order"||y==="limit"||y==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={}),y==="order"?n.embeddedTransforms[h].order=qa(g):y==="limit"?i[h]=g:y==="offset"&&(o[h]=g);continue}if(y.includes(".")){let w=y.lastIndexOf("."),S=y.slice(w+1);if(S==="order"||S==="limit"||S==="offset"){n.embeddedTransforms[h]||(n.embeddedTransforms[h]={});let b=n.embeddedTransforms[h],_=y.slice(0,w);b._nested||(b._nested={});let E=b._nested;E[_]||(E[_]={});let x=E[_];S==="order"?x.order=qa(g):S==="limit"?(a[h]||(a[h]={}),a[h][_]=g):S==="offset"&&(l[h]||(l[h]={}),l[h][_]=g);continue}}}}d==="order"?n.order=qa(g):d==="limit"?r=g:d==="offset"&&(s=g);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new ve({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=Ba(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=Ba(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 g of p){let m=Ba(a[d]?.[g],l[d]?.[g]),h=n.embeddedTransforms[d]?._nested?.[g];h&&(m.limit!==void 0&&(h.limit=m.limit),m.offset!==void 0&&(h.offset=m.offset));}}return n}function qa(t){return jw(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return Lw(s,t,i)})}function jw(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 Lw(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new fe(`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 fe(`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 fe(`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 fe(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new fe(`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 fe(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let f=Dw(i);if(f){if(f.column.includes(","))throw new fe(`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;}else if(i.includes("(")||i.includes(")")){let g=i.search(/[()]/);throw new fe(`failed to parse order (${e})`,`unexpected '${i[g]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+g+1)}let u=n+i.length+1,d=false,p=false;for(let g=1;g<r.length;g++){let m=r[g];if(m==="asc"||m==="desc"){if(d)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.direction=m,d=true,u+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(p)throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1);s.nullsFirst=m==="nullsfirst",p=true,u+=m.length+1;}else {let h=["asc","desc","nullsfirst","nullslast"],y=null;for(let w of h)if(m.startsWith(w)&&m.length>w.length){y=w;break}if(y){let w=m[y.length],S=u+y.length;throw new fe(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,S+1)}throw new fe(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,u+1)}}return s}function Wa(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=Mw(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=Fw("columns",i);}return r}function Fw(t,e){let n=e.split(",").map(r=>Uw(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new jt(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function Uw(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function Mw(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 Ka(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(nn.has(a))continue;let c=l.filter(f=>!Ar(f));c.length!==0&&(c.length>1?i[a]=c.map(f=>rt(f)):i[a]=rt(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function Ja(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:Bw(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function Bw(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new jt(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function Ri(t,e){let n=e?.basePath,r=e?.parseRoute??(C=>Aa(C,n)),s=e?.parseHeaders??Oa,i=e?.parseSelect??Na,o=e?.parseBody??Da,a=e?.parseQueryParams??ja,l=e?.resolveType??La,c=e?.resolveFilters??Ir,f=e?.resolveTransforms??Ha,u=e?.resolveMeta??Wa,d=e?.resolveRpcParams??Ka,p=e?.resolveUpsertParams??Ja,[g,m,h,y,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),S=t.method,b=l(g,S,m),_=w;if(g.isRpc&&S.toUpperCase()==="GET"){_=new Map;for(let[C,R]of w){if(nn.has(C)){_.set(C,R);continue}let U=R.filter(J=>Ar(J));U.length>0&&_.set(C,U);}}let E=c(_,h.embeddedAliases,g.isRpc?void 0:g.from,e?.parentColumns),x=f(w,h.embeddedAliases),O=u(m,w,S),v=d(g,S,w,y),P=b==="upsert"||b==="put"?p(w,m):void 0;return qw(b,g,m,h,y,E,x,O,v,P)}function qw(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=sd(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 Hw(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function sd(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,f=e[o]||c&&e[c],u=n[o]||c&&n[c];if(f&&s!==o){let d={},p={};for(let[g,m]of Object.entries(f)){let h=g.indexOf(".");if(h>0){let y=g.slice(0,h),w=g.slice(h+1);if(l.join?.[y]||l.select?.some(_=>typeof _=="object"&&y in _&&"select"in(_[y]??{}))){p[y]||(p[y]={}),p[y][w]=m;continue}}d[g]=m;}Object.keys(d).length>0&&(l.where=d);for(let[g,m]of Object.entries(p))l.select=Hw(l.select??[],g,m);}if(u){let d=u;if(d.order&&(l.order=d.order),d.limit!==void 0&&(l.limit=d.limit),d.offset!==void 0&&(l.offset=d.offset),d._nested)for(let[p,g]of Object.entries(d._nested))n[p]=g;}return l.select&&(l.select=sd(l.select,e,n,l.join,o)),{[o]:l}})}function Ci(t){return t!=null&&typeof t=="object"&&"$ref"in t}st();var Ga=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return $n(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return id(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return id(n)}return e}},za=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},Va=class extends ie{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},Qa=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},Ya=class extends ie{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function $n(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function id(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function ad(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var Ww=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),Kw=new Set(["bool","boolean"]),ld=new Map;function Le(t){if(!t)return false;let e=t.toLowerCase().trim();return Ww.has(e)||ld.has(e)}function Ne(t,e){return (t??e).toLowerCase().trim()}function Xa(t,e){let n=Ne(t.pg_type,t.type);return Le(n)||!e?n:Jw(t.table,t.name,e)??n}function Jw(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(Le(a)||Kw.has(a))return a}}function Za(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function cd(t){return Array.isArray(t)?t.map(e=>od(e)):od(t)}function od(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return $n(e.startsWith("#")?e:`#${e}`)}return t}function vi(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function ud(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function Nr(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ne(a.pg_type,a.type);return Le(l)?vi(t,l)??t:t}function fd(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?Le(Ne(i.pg_type,i.type)):false}function Dr(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:Le(Ne(s.pg_type,s.type)))}function el(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ne(s.pg_type,s.type),o=Le(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function dd(t){let e=t.pgTypeName.toLowerCase().trim(),n=ld.get(e);if(n)return n(t);switch(e){case "color":return new Ga(t);case "isodate":case "isodatetext":return new za(t);case "unixtz":return new Va(t);case "monetary":case "monetarytext":return new Qa(t);case "bytea_b64":return new Ya(t);default:return null}}var Gw=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,zw=/[;'"\\/*\-#]/,Vw=/['\\;(]/,wt=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function Pe(t,e){if(!Gw.test(t))throw new wt(t,e)}function ln(t,e){if(zw.test(t))throw new wt(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new wt(t,e);if(n!==0)throw new wt(t,e)}function In(t,e){if(Vw.test(t))throw new wt(t,e)}function cn(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 jr(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||In(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 Qw(t){return `"${t.replace(/"/g,'""')}"`}function tl(t){return sql.raw(Qw(t))}function nl(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 nl(t,e,n,r)!==void 0}function de(t,e,n=e.currentTable){return Ai(t,e,n)?tl(t):sql.ref(t)}function St(t,e,n,r=n.currentTable){let s=Ai(e,n,r)?tl(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function Yw(t){return (t?.pg_type??t?.type??"").toLowerCase()}function pd(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=Yw(nl(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function md(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Lt(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=nl(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function hd(t,e){let n=t;for(let r of e)n=sql`(${n}).${tl(r)}`;return n}function gd(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return de(t,n,r);if(pd(t,n,r)){let l=md(i);if(l)return sql`${de(t,n,r)}${sql.raw(l)}`}if(Lt(t,n,r))return hd(de(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=jr(o,"JSON path key");return sql`${de(t,n,r)}${sql.raw(a)}`}function Lr(t,e,n=e.currentTable,r){let{col:s,parts:i}=cn(t),o=r?St(r,s,e,n):de(s,e,n);if(i.length===0)return o;if(pd(s,e,n)){let c=md(i.map(f=>f.key));if(c)return sql`${o}${sql.raw(c)}`}if(Lt(s,e,n))return hd(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,f)=>f===i.length-1?{...c,op:"->>"}:c):i,l=jr(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===Pn?sql`${r} IS NOT NULL`:n===sn?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===Pn?sql`${r} IS NULL`:n===sn?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}`},Pi={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function yd(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function rl(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function Ii(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function $i(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Ft(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!rl(a.arg_types[0],e,a.schema)||!$i(t,e,a.schema)||a.return_typtype!=="c")continue;let l=yd(a.return_type);if(rl(a.return_type,l,a.schema)&&$i(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function Fr(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Ni(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&rl(a.arg_types[0],e,a.schema)&&$i(t,e,a.schema)&&!(a.return_typtype==="c"&&$i(t,yd(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Di(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return Pe(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var Xw=new Set(["$like","$ilike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function sl(t){return t!=null&&typeof t=="object"&&t.type==="query"}function un(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!Ii(e.introspection,e.currentTable,t,e.currentSchema)){let r=Ni(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Di(r,e.currentTableAlias??e.currentTable)}return de(t,e)}function ji(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),ol(t,e,n)}function Zw(t){return t.includes("->")}function Ed(t,e){let{col:n,parts:r}=cn(t);return r.length===0?de(t,e):Lr(t,e)}function Ee(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Ee(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Ee(t,a,n))));}else if(s==="$not")r.push(t.not(Ee(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(ji(o,n)));}else {let o=i,a=Zw(s);for(let[l,c]of Object.entries(o)){if(Ci(c)){let f=Pi[l];if(!f)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Ed(s,n):un(s,n)} ${sql.raw(f)} ${de(c.$ref,n)}`);continue}if(l==="$not"){let f=c;for(let[u,d]of Object.entries(f))if(a)r.push(t.not(_d(s,u,d,n)));else {let p=bd(s,u,d,n);if(p){r.push(t.not(p));continue}let g=Sd(s,u,d,n);if(g){r.push(t.not(g));continue}let m=wd(s,u,d,n);if(m){r.push(t.not(m));continue}let h=n.operators[u];if(!h)throw new Error(`Unsupported operator: ${u}`);r.push(t.not(h(t,un(s,n),d)));}}else if(sl(c)){let f=ji(c,n),u=n.operators[l];if(!u)throw new Error(`Unsupported operator: ${l}`);r.push(u(t,un(s,n),f));}else if(a)r.push(_d(s,l,c,n));else {let f=bd(s,l,c,n);if(f){r.push(f);continue}let u=tS(s,l,c,n);if(u){r.push(u);continue}rS(s,l,n);let d=il(s,c,n),p=Sd(s,l,d,n);if(p){r.push(p);continue}let g=wd(s,l,d,n);if(g){r.push(g);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,un(s,n),d));}}}}return r.length===1?r[0]:t.and(r)}function bd(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==sn)return null;let s=Dn(t,r);if(!s)return null;let i=xd(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${de(t,r)} IS NULL`:sql`${de(t,r)} IS NOT NULL`;throw Object.assign(new Error(`argument of IS UNKNOWN must be type boolean, not type ${i}`),{code:"42804",detail:null})}function Dn(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?cn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var eS={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function wd(t,e,n,r){if(r.dialect!=="postgres")return null;let s=eS[e];if(!s)return null;let i=Dn(t,r);if(!i||Ne(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${un(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function Sd(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Dn(t,r);if(!s||Ne(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${un(t,r)})`:sql`to_tsvector(${un(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function xd(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 tS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Dn(t,r),i=xd(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=de(t,r),a=sql`cast(${sql.raw(nS(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function nS(t){return `'${t.replace(/'/g,"''")}'`}function rS(t,e,n){if(!Xw.has(e))return;let r=Dn(t,n);if(!r||Ne(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function il(t,e,n){if(!n?.currentTable)return e;let r=Dn(t,n);if(!r)return e;let s=Ne(r.pg_type,r.type);if(s==="color")return cd(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)Za(i);else Za(e);return e}function _d(t,e,n,r){let s=r?Ed(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&&sl(n))return sql`${s} in ${ji(n,r)}`;let a=il(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&sl(n))return sql`${s} not in ${ji(n,r)}`;let a=il(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function Ur(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>Ur(i,e)):r==="$not"?n[r]=Ur(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function it(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function al(t,e){return `${t}_${e}_fkey`}function Li(t,e){return e===al(t.table,t.column)}function Td(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Rd(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function Cd(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function sS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?Rd(e,n,t.fk):Cd(e,n,t.fk);case "parent_column":return Rd(e,n,t.fk);case "target_column":return Cd(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function kd(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function vd(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&Li(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&Li(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Ad(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function Od(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function Pd(t,e,n,r){let s=r.filter(a=>a.table===t),i=Td(s.filter(a=>a.ref_table===e)),o=Td(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function $d(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function Id(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var iS=[kd,vd,Ad,Od,Pd,$d,Id];function Nd(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[kd,vd,Od,Ad,Pd,$d,Id]:iS;for(let o of i){let a=o(t,e,n,r);if(a)return sS(a,e,n)}return null}function Fi(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 Mr(t,e,n,r){if(e.type==="m2m")return Fi(t,e,n,r);for(let{leftCol:s,rightCol:i}of it(e))t=t.whereRef(s,"=",i);return t}function Br(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:al(t.table,t.column)}function jn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!Ld(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=Dd(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 Dd(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=>Dd(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=oS(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 oS(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=jd(r,e);if(!f)return null;let u=s?.[e],d=Ft(o.introspection,i,u?.from||e,o.dialect,o.currentSchema);if(d){let w=t.selectFrom(Fr(d,i,d.targetTable)).select(sql`1`.as("_"));if(f.where&&Object.keys(f.where).length>0){let b=jn(w,f.where,f.select,f.join,d.targetTable,o);if(w=b.qb,Object.keys(b.remainingWhere).length>0){let _=Ur(b.remainingWhere,d.targetTable);w=w.where(E=>Ee(E,_,o));}}let S=t.exists(w);return c?S:t.not(S)}let p=xe(i,e,u,o.introspection),{targetTable:g,fkRel:m}=p;if(!m)return null;let h=t.selectFrom(g).select(sql`1`.as("_"));if(u?.on?h=h.where(w=>Ee(w,u.on,o)):h=Mr(h,m,g,i),f.where&&Object.keys(f.where).length>0){let w=jn(h,f.where,f.select,f.join,g,o);if(h=w.qb,Object.keys(w.remainingWhere).length>0){let S=Ur(w.remainingWhere,g);h=h.where(b=>Ee(b,S,o));}}let y=t.exists(h);return c?y:t.not(y)}function jd(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&re(r))return r}return null}function Ld(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>Ld(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)&&jd(e,n))return true}return false}function re(t){return "select"in t||"spread"in t||"join"in t}function dl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function Hr(t){return dl(t)?.def??null}function aS(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function Fd(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function qi(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(Dr(l,n.introspection,Fe(n))||Mi(l,n))?Ud(t,l,n,new Set,false,s):t.selectAll();for(let f of e)if(typeof f=="string")if(f==="*")if(c&&l&&(Dr(l,n.introspection,Fe(n))||Mi(l,n))){let u=new Set;for(let d of e){if(d===f)break;if(typeof d=="string"&&d!=="*")u.add(d.includes(".")?d.split(".").pop():d);else if(typeof d!="string")for(let[p]of Object.entries(d))u.add(p);}t=Ud(t,l,n,u,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(f))t=t.select(sql.lit(Number(f)).as("_lit"));else if(wS(f,n,s)){let u=i&&s?St(s,f,n,s):de(f,n,s);t=t.select(sql`json(${u})`.as(f));}else if(c&&l&&s&&!f.includes(".")&&!Ii(n.introspection,l,f,n.currentSchema)){let u=Ni(n.introspection,l,f,n.dialect,n.currentSchema);t=u?t.select(Di(u,s).as(f)):t.select(f);}else if(c&&s&&l&&fd(l,Fd(f),n.introspection,Fe(n))){let u=Fd(f),d=f.includes(".")?sql.ref(f):i?St(s,f,n,s):sql.ref(f);t=t.select(Nr(d,l,u,n.dialect,n.introspection,Fe(n)).as(u));}else t=i&&s&&!f.includes(".")?t.select(St(s,f,n,s).as(f)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f)&&Ai(f,n,s)?t.select(de(f,n,s).as(f)):t.select(f);else for(let[u,d]of Object.entries(f))re(d)?t=qS(t,u,d,n,r,l,a):t=pS(t,u,d,n,s,i,l);return t}function Fe(t){return t.currentSchema??t.introspection?.default_schema??"public"}function Mi(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=Fe(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Lt(r.name,e,t))}function Ud(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=el(e,n.introspection,Fe(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let f=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let u=vi(f,c);t=t.select((u??f).as(a));}else Lt(a,n,e)?t=t.select(sql`to_jsonb(${f})`.as(a)):t=s?t.select(f.as(a)):t.select(a);}return t}function Wr(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(Dr(s,n.introspection,Fe(n))||Mi(s,n))?Md(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(Dr(s,n.introspection,Fe(n))||Mi(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=Md(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Lt(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=Nr(o,s,i,n.dialect,n.introspection,Fe(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(re(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Lt(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),f=Nr(c,s,l,n.dialect,n.introspection,Fe(n));t=f!==c?t.returning(f.as(o)):t.returning(l);}else t=t.returning(l);}return t}function Md(t,e,n,r){if(!n.introspection)return t.returningAll();let s=el(e,n.introspection,Fe(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=vi(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Lt(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function Kr(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${cS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=gd(l,n.path,r,s,n.pathText===true);else {let c=s&&i?St(s,l,r,s):de(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?Nr(c,o??s??r.currentTable,l,r.dialect,r.introspection,Fe(r)):c;}n.preCast&&(ln(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(ln(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&lS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&dS(r,s,n.column)?a=ad(a,r.dialect):a=r.dialect==="sqlite"&&(uS(n.cast)||fS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function lS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function cS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function uS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function fS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function dS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===Fe(t))??s.find(o=>o.schema==="public")??s[0];return Ne(i.pg_type,i.type)==="color"}function pS(t,e,n,r,s,i=false,o){return t.select(a=>Kr(a,e,n,r,s,i,o).as(e))}function mS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!re(n)&&n.aggregate)return true}return false}function hS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread&&pl(n.select))return true}return false}function Bd(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(re(n)&&n.spread)return true}return false}function gS(t){return mS(t)||hS(t)}function pl(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(pl(n.select))return true;continue}if(n.aggregate)return true}return false}function ml(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(re(n)){if(n.spread)continue;if(ml(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function hl(t,e,n,r,s,i=false,o){if(!gS(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(de(l,n,r));continue}for(let[c,f]of Object.entries(l))re(f)||f.aggregate||a.push(u=>Kr(u,c,f,n,r,i,o));}return yS(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function yS(t,e,n,r,s){if(!(!e||!r||!n.introspection?.foreign_keys)){for(let i of e)if(typeof i!="string")for(let[o,a]of Object.entries(i)){if(!re(a)||!a.spread)continue;let l=a,c=s?.[o],f=xe(r,o,c,n.introspection);if(!f.fkRel||!_t(f))continue;let u=f.targetTable;f.fkRel;let p=Wi(l.select,u,n.introspection)??l.select??[],g=`_spread_${o}`;for(let m of p){if(typeof m=="string"){m!=="*"&&t.push(`${g}.${m}`);continue}let[h,y]=Object.entries(m)[0];re(y)||y.aggregate||t.push(w=>Kr(w,h,y,n,g,true));}}}}function Jd(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(!re(l)||!l.spread)continue;let c=n?.[a],f=xe(r,a,c,s.introspection);f.fkRel&&_t(f)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function Gd(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(!re(o)||!o.spread)continue;let a=e?.[i],l=xe(n,i,a,r.introspection);if(l.fkRel&&_t(l))return true}return false}function Ln(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function qr(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function gl(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of it(e)){let[,f]=l.split("."),[,u]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a})}function Hi(t,e,n,r,s){let i=new Set;if(!e||!r.introspection?.foreign_keys)return {sub:t,joined:i};for(let o of e){if(!o.embed||i.has(o.embed))continue;Pe(o.embed,"order embed alias");let a=s?.[o.embed],l=xe(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&Pe(l.targetTable,"order embed target"),!l.fkRel||!_t(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:f}=l;t=gl(t,f,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function bS(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function Bi(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 wS(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Bi(e,n,t)}function SS(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 zd(t,e,n,r){return Bi(t,e,n)||SS(r,n)}function _S(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:Bi(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(re(o))return null;let a=Bi(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function ES(t,e,n,r){let s=_S(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 Vd(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=dl(e);if(n&&(!re(n.def)||Vd(n.def.select)))return true}return false}function Qd(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function xS(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return Qd(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(ep(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function TS(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&RS(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function RS(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function CS(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of TS(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function kS(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function qd(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function vS(t){let e=[],n=new Map;for(let r of t){let s=kS(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}qd(r)<qd(e[i])&&(e[i]=r);}return e}function cl(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return Br(t.fk)}function ul(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${Br(a)}(${a.column}) and ${Br(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=Br(t.fk);if(t.type==="o2m"){let a=Ui(t.rightCols??[t.rightCol]),l=Ui(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=Ui(t.leftCols??[t.leftCol]),o=Ui(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function Ui(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function AS(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function yl(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 ve({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:AS(t,n,s)})}function OS(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(h=>h.is_visible!==false);if(r){let h=Nd(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(h)return h;yl(t,e,n,r);}if(e===n){let h=Ln(i.filter(y=>y.table===n&&y.ref_table===e))[0];if(h)return qr(e,n,h,"o2m")}let o=i.filter(h=>h.table===e&&h.ref_table===n),a=Ln(o),l=i.filter(h=>h.table===n&&h.ref_table===e),c=Ln(l),f=[],u=Ln(i.filter(h=>h.ref_table===e));for(let h of u){let y=h[0].table;if(y===e||y===n)continue;let w=i.filter(S=>S.table===y&&S.ref_table===n);if(w.length!==0)for(let S of Ln(w))f.push({type:"m2m",junctionTable:y,junctionToParentCols:h.map(b=>b.column),parentCols:h.map(b=>b.ref_column),junctionToTargetCols:S.map(b=>b.column),targetCols:S.map(b=>b.ref_column),fk:h[0],parentFkGroup:h,targetFkGroup:S});}if(a.length+c.length+f.length===0)return null;let p=[...f];CS(p,t),p=vS(p);let g=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&p.length>1||g||a.length>0&&p.length>1){let h=[...a.map(E=>qr(e,n,E,"m2o")),...c.map(E=>qr(e,n,E,"o2m")),...p],y={o2m:0,m2o:1,m2m:2},w=[...h].sort((E,x)=>{let O=y[E.type]??3,v=y[x.type]??3;if(O!==v)return O-v;let P=cl(E)??"",C=cl(x)??"",R=P.localeCompare(C);return R!==0?R:ul(E,e,n).localeCompare(ul(x,e,n))}),S=w.map(E=>({cardinality:xS(E,e,n,t),embedding:`${e} with ${n}`,relationship:ul(E,e,n)})),_=w.map(E=>cl(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new ve({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:S,hint:_?`Try changing '${n}' to one of the following: ${_}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?qr(e,n,a[0],"m2o"):c.length===1?qr(e,n,c[0],"o2m"):f.length===1?f[0]:null}function PS(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||Li(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function $S(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return Qd(e,i,s)?"o2o":"m2o"}return ep(s,e,n,r,t)?"o2o":"o2m"}function xe(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=PS(s,t,r),a=aS(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?OS(r,t,i,a,l):null,f=$S(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:f,displayHint:a}}function _t(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function Yd(t,e,n,r){if(!(!t||!n||!r.introspection?.foreign_keys))for(let s of t){if(!s.embed)continue;let i=e?.[s.embed],o=xe(n,s.embed,i,r.introspection);if(o.fkRel&&!_t(o))throw new ve({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 Hd(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!re(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let f=Ft(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),u=f?f.targetTable:xe(n,a,c,s.introspection).targetTable;t=t.where(d=>Xd(d,l,u,n,c,l.join??i,s));}return t}function Xd(t,e,n,r,s,i,o){let a=r?Ft(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let u=t.selectFrom(Fr(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(u=u.where(d=>Ee(d,e.where,{...o,currentTable:a.targetTable}))),r&&(u=Hd(u,e,a.targetTable,i,o)),t.exists(u)}let c=(r?xe(r,s?.from??n,s,o.introspection):null)?.fkRel??null,f=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)f=f.where(u=>Ee(u,s.on,o));else if(c&&c.type==="m2m")f=Fi(f,c,n,r);else if(c)for(let{leftCol:u,rightCol:d}of it(c))f=f.whereRef(u,"=",d);else r&&(f=f.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(f=f.where(u=>Ee(u,e.where,{...o,currentTable:n}))),r&&(f=Hd(f,e,n,i,o)),t.exists(f)}function Wd(t,e,n,r,s,i){let o=s?.[e],a=i?Ft(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?xe(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>Xd(c,n,l,i,o,s,r))}function Zd(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 ep(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(Zd(s,n,t))return true;let o=t.foreign_keys.filter(u=>u.is_visible!==false).filter(u=>u.table===n&&u.ref_table===e);if(r){let u=o.filter(d=>d.foreign_key_name===r);u.length>0&&(o=u);}let a=Ln(o);if(a.length!==1)return false;let l=[...a[0].map(u=>u.column)].sort(),c=t.primary_keys?.find(u=>u.table===n);if(!c?.columns?.length)return false;let f=[...c.columns].sort();return l.length===f.length&&l.every((u,d)=>u===f[d])}function IS(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function Mt(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 NS(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=xe(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,f=Wi(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return BS(t,f,l,i,c);if(!c)throw new ve({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(!_t(a)){if(pl(n.select))throw new ve({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 MS(t,f,n,c,l,i,r)}let u=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new ve({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let d=it(c).map(({leftCol:m,rightCol:h},y)=>{let[w,S]=m.split("."),[,b]=h.split(".");return {targetSideCol:w===l?S:b,parentSideCol:w===i?S:b,joinKey:`__spread_join_key_${y}`}}),p=[],g=new Set;for(let m of f){if(typeof m=="string"&&m==="*")continue;let h;if(typeof m!="string"){let S=Hr(m);if(!S||re(S))continue;h=S;}let{colAlias:y,colName:w}=Mt(m);p.push({src:w,out:y,def:h}),g.add(w);}t=t.leftJoin(m=>{let h=m.selectFrom(l);for(let{targetSideCol:y,joinKey:w}of d)h=h.select(`${l}.${y} as ${w}`);for(let y of g)h=h.select(`${l}.${y} as ${y}`);return h.as(u)},m=>{let h=m;for(let{joinKey:y,parentSideCol:w}of d)h=h.onRef(`${u}.${y}`,"=",`${i}.${w}`);return h});for(let{out:m,def:h}of p)h?t=t.select(y=>Kr(y,m,h,r,u,true).as(m)):t=t.select(`${u}.${m}`);return t}function DS(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=Hr(s);if(!i||!re(i))continue;let{colAlias:o}=Mt(s),a=e.join?.[o],l=xe(n,o,a,r.introspection),c=l.targetTable,f=l.fkRel;if(!f||f.type!=="o2m"||!Zd(f,c,r.introspection))continue;let u=r.introspection?.primary_keys?.find(d=>d.table===c);if(u?.columns?.length)return {nestedTargetTable:c,fkRel:f,pkColumns:u.columns}}return null}function jS(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=Mr(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(f=>Ee(f,o.where,c));}let l=Hi(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Ut(a,bS(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=gl(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Ut(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function LS(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Ut(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function FS(t,e,n){if(n&&re(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!_t(s))return true;let{colName:i}=Mt(e);return zd(t.config,r.fromTable,i,t.frames[0].embed.order)}function US(t,e,n,r){let s=Hr(n),{colAlias:i,colName:o}=Mt(n),l=e.frames[r].fromTable;if(r===0&&s&&re(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(f=>tp(f,i,s,e.config,c,l).as("value"))}if(s&&!re(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,f=r>0?i:o;return t.select(u=>Kr(u,f,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function fl(t,e,n,r,s){if(r===e.frames.length-1)return US(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(_t(l))return s.has(a.fromTable)||(t=gl(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=LS(t,e,a),fl(t,e,n,r+1,s);let{colName:c}=Mt(n);return t.select(f=>{let u=f.selectFrom(a.fromTable);return u=Mr(u,a.fkRel,a.fromTable,o.fromTable),u=fl(u,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(u,"value",zd(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function Kd(t,e,n){let{colAlias:r}=Mt(n),s=Hr(n);return t.select(i=>{let{inner:o,joinedToOne:a}=jS(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let f=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(f).as(r)}let c=fl(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",FS(e,n,s)).as(r)})}function MS(t,e,n,r,s,i,o){let a=n.order?null:DS(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let f=Hr(c),u=f!==null&&re(f)&&f.spread,{colAlias:d}=Mt(c);if(u){let p=f,g=n.join?.[d],m=xe(s,d,g,o.introspection),h=Wi(p.select,m.targetTable,o.introspection)??p.select??[],y={...l,frames:[...l.frames,{embed:p,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let w of h)typeof w=="string"&&w==="*"||(t=Kd(t,y,w));continue}t=Kd(t,l,c);}return t}function BS(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=Mt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:f,rightCol:u}of it(s))c=c.whereRef(f,"=",u);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function Wi(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 qS(t,e,n,r,s,i,o){let a=s?.[e];if(!Vd(n.select)){if(a?.type==="inner"&&i)return Wd(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Ft(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=xe(i,e,a,r.introspection);l.fkRel||yl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=Wd(t,e,n,r,s,i)),n.spread&&i?NS(t,e,n,r,s,i):t.select(l=>tp(l,e,n,r,a,i,o).as(e))}function tp(t,e,n,r,s,i,o){let a=i?Ft(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:xe(i,e,s,r.introspection),c=l.targetTable,{displayHint:f,fkRel:u}=l,d=i===c,p=d?o?`${c}_nested`:`${c}_self`:c,g=d?`${c} as ${p}`:c,m=a?t.selectFrom(Fr(a,o??i,p)):t.selectFrom(g),h=i&&!s?.on&&!a?u:null,y=h?.type==="m2m",w=Wi(n.select,c,r.introspection),S=y?IS(w,p):w;if(m=qi(m,S,r,n.join,p,y||Bd(S),d?c:p,d?p:void 0),n.where&&Object.keys(n.where).length>0){let x=jn(m,n.where,n.select,n.join,c,r);m=x.qb,Object.keys(x.remainingWhere).length>0&&(m=m.where(O=>Ee(O,x.remainingWhere,{...r,currentTable:c,currentTableAlias:p})));}let b=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(x=>Ee(x,s.on,r));else if(i&&!a){let x=h;if(x&&x.type==="m2m")b="m2m",m=Fi(m,x,p,i);else if(x?.type==="m2o"){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=o?`${o}.${P}`:`${i}.${P}`;m=m.whereRef(`${p}.${C}`,"=",R);}b="m2o";}else if(x){for(let{leftCol:O,rightCol:v}of it(x)){let[,P]=O.split("."),[,C]=v.split("."),R=d?`${p}.${P}`:O,U=o?`${o}.${C}`:d?v.replace(`${c}.`,`${i}.`):v;m=m.whereRef(R,"=",U);}b=x.type;}else r.introspection?.foreign_keys?yl(r.introspection,i,c,f):m=m.whereRef(`${p}.${i}_id`,"=",`${i}.id`);}m=hl(m,S,r,p,void 0,y||Bd(S),d?c:p),n.order?.some(x=>x.embed)&&(m=Hi(m,n.order,c,r,n.join).sub),m=Ut(m,n.order,void 0,r,c),b==="m2m"&&!n.order&&h?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${h.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let _=n.spread?true:a?a.toOne:b==="m2o"||l.cardinality==="o2o";return _&&r.dialect==="sqlite"?ES(m,S,c,r):(_?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function np(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=dl(s);if(!i||!re(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=xe(n,o,l,r.introspection);if(c.fkRel&&!_t(c))return true}return false}Fn();function bl(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function GS(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${bl(s)}`);return `${t}.${e}(${r.join(", ")})`}function zS(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(bl).join(","),i=n.arg_types.map(bl).join(",");return s<i?-1:s>i?1:0})}function sp(t,e,n){return {message:`Could not choose the best candidate function between: ${zS(n).map(i=>GS(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function op(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(u=>u.schema===r&&u.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let u=Bt(n,{schema:r,fnName:s,providedNames:o});if(u.length>1)return sp(r,s,c);if(u.length===1)return null}if(i==="POST"&&a!=="text"){let u=c.filter(d=>!d.has_variadic&&d.arg_types.length===1&&d.arg_names.length===0&&(d.arg_types[0]==="json"||d.arg_types[0]==="jsonb"));if(u.length>1)return sp(r,s,u)}return null}function fn(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function ap(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function VS(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function Bt(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&VS(i,s))}function Ji(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function Gi(t,e){let n=Ji(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function lp(t,e){let n=Ji(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function QS(t){return [...t].sort().join(", ")}function YS(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:QS(e)}}function XS(t,e,n,r){let s=r.filter(d=>d.schema===t),i=()=>{let d=[...new Set(s.map(p=>p.name))].filter(p=>p!==e);return Jr(e,d)},o=d=>`Perhaps you meant to call the function ${t}.${d}`,a=d=>`Perhaps you meant to call the function ${t}.${e}(${d})`,l=s.filter(d=>d.name===e).map(YS).filter(d=>d!==null);if(l.length===0){let d=i();return d?o(d):null}if(s.filter(d=>d.name===e).length>1){let d=l.filter(p=>p.arity===n.length);return d.length===1?a(d[0].sig):null}return l[0].sig.split(", ").every(d=>n.includes(d)||Jr(d,n)!==null)?a(l[0].sig):null}function ip(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",f=c&&o==="text",u;f?u=`with a single unnamed ${a??"text"} parameter`:c?u=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:u=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let d=`Searched for the function ${n}.${r} ${u}, but no matches were found in the schema cache.`,p;l.length>0?p=`${n}.${r}(${l.join(", ")})`:f?p=`${n}.${r}`:p=`${n}.${r} without parameters`;let g=`Could not find the function ${p} in the schema cache`,m=XS(n,r,i,e);return {message:g,details:d,hint:m}}function wl(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?ip(e,n):e.paramsType==="positional"&&e.providedNames.length===0||Bt(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:ip(e,n)}function ZS(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function _l(t,e,n,r,s={}){if(!t)return t;let i=ZS(e,n,r),o=a=>{let l=e_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):t_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function e_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??pp(n,r,s,o)??void 0;i[o]=n_(a,l,n.dialect);}return i}function t_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=pp(e,n,r,i);s[i]=r_(a)?Vi(o):o;}return s}function pp(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ne(a.pg_type,a.type)}function n_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&Le(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}return t}return ud(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return $n(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=Gr(e);return i==="boolean"?cp(t):i==="integer"?zi(t,true):i==="number"?zi(t,false):i==="json"?Sl(t):i==="array"?up(t):t}if(r==="color")return $n(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=Gr(e);return s==="boolean"?cp(t):s==="integer"?zi(t,true):s==="number"?zi(t,false):s==="json"?Sl(t):s==="array"?up(t):t}function Gr(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 cp(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 zi(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 Sl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function up(t){let e=Sl(t);return Array.isArray(e)?e:t}function r_(t){let e=Gr(t);return e==="json"||e==="array"}var s_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function fp(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !s_.has(n)}function Vi(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function mp(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return ol(t,e,n);case "insert":return o_(t,e,n);case "update":return a_(t,e,n);case "delete":return l_(t,e,n);case "upsert":case "put":return c_(t,e,n);case "rpc":return f_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Ut(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(Pe(i.embed,"order embed alias"),i.column.includes("->")?r?Lr(i.column,r,s,i.embed):dp(i.column,i.embed):(Pe(i.column,"order embed column"),r?St(i.embed,i.column,r,s):sql`${sql.ref(i.embed)}.${sql.ref(i.column)}`)):i.column.includes("->")?r?Lr(i.column,r,s,n):dp(i.column,void 0,n):n?r?St(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?de(i.column,r,s):i.column,a=i.nullsFirst!==void 0?i.nullsFirst:r?.dialect==="sqlite"?i.direction==="desc":void 0;a!==void 0?t=t.orderBy(o,l=>{let c=i.direction==="desc"?l.desc():l.asc();return a?c.nullsFirst():c.nullsLast()}):t=t.orderBy(o,i.direction||"asc");}return t}function dp(t,e,n){let{col:r,parts:s}=cn(t);if(s.length===0)return sql.ref(t);e&&Pe(r,"order embed column");let i=jr(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=>Ee(i,e,{...n,currentTable:r,currentSchema:s}))}function ol(t,e,n){let r=n.selectFrom(t.from);return hp(r,t,e,t.from)}function hp(t,e,n,r){t=i_(t,e.join,e.select);let s=e.order?.some(f=>f.embed)===true;t=qi(t,e.select,n,e.join,r,s||Gd(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=jn(t,i,e.select,e.join,r,n);t=o,t=zr(t,a,n,r,e.schema),t=hl(t,e.select,n,r,e.join),Yd(e.order,e.join,r,n),s&&(t=Hi(t,e.order,r,n,e.join).sub);let l=np(e.select,e.join,r,n)?r:void 0,c=Jd(e.order,e.select,e.join,r,n);return t=Ut(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function i_(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=>gp(l,i.on));}return t}function gp(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=gp(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Pi[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Ci(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function o_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=_l(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function a_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=_l(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=yp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function l_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=yp(r,t,e,n):r=zr(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Wr(r,t.select,s),r}function yp(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=Ut(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 c_(t,e,n){let r=t.values,s=_l(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,f=Object.keys(c).filter(u=>!t.onConflict.includes(u));return f.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(u=>{let d={};for(let p of f)d[p]=u.ref(`excluded.${p}`);return d})}));let o=t.from?{...e,currentTable:t.from}:e;return i=Wr(i,t.select,o),i}function u_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?fn(t):Object.keys(t.args);if(Bt(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function f_(t,e,n){let r=t.function;Pe(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(Pe(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,Pe(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?u_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${Vi(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let u=Object.entries(t.args),d=null,p=null,g=null;if(e.dialect==="postgres"&&e.introspection?.functions){let y=u.map(([S])=>S),w=Bt(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:y});if(w.length===1){let S=w[0];d=new Map;for(let b=0;b<S.arg_names.length;b++)d.set(S.arg_names[b],S.arg_types[b]);if(S.has_variadic&&S.arg_names.length>0){p=S.arg_names[S.arg_names.length-1];let b=S.arg_types[S.arg_types.length-1];g=b.endsWith("[]")?b.slice(0,-2):b;}}}let m=t.httpMethod==="GET",h=u.map(([y,w])=>{if(Pe(y,"RPC param key"),d){let b=d.get(y);if(b){if(y===p&&g){ln(g,"RPC variadic elem type"),Pe(y,"RPC variadic param key");let _=Array.isArray(w)?w:[w];return sql`VARIADIC ${sql.raw(y)} := ${_}::${sql.raw(g+"[]")}`}if(fp(b)){ln(b,"RPC arg type");let _=m&&Array.isArray(w)?w[w.length-1]:w,E=Gr(b),x=E==="json"||E==="array"&&!Array.isArray(_)?Vi(_):_;return sql`${sql.raw(y)} := ${x}::${sql.raw(b)}`}}}let S=m&&Array.isArray(w)?w[w.length-1]:w;return sql`${sql.raw(y)} := ${S}`});o=sql`${sql.raw(i)}(${sql.join(h)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let u=null;if(e.dialect==="postgres"&&e.introspection?.functions){let p=e.introspection.functions,g=t.schema??e.introspection?.default_schema??"public",h=t.args.length,y=p.filter(w=>w.schema===g&&w.name===r&&w.arg_types.length===h);y.length===1&&(u=y[0].arg_types);}let d=t.args.map((p,g)=>{if(u){let m=u[g];if(m&&fp(m)){ln(m,"RPC positional arg type");let h=Gr(m),y=h==="json"||h==="array"&&!Array.isArray(p)?Vi(p):p;return sql`${y}::${sql.raw(m)}`}}return sql`${p}`});o=sql`${sql.raw(i)}(${sql.join(d)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let u=lp(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:fn(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(u)return hp(n.selectFrom(o.as(u)),t,e,u)}let f=n.selectFrom(o.as(r));return f=qi(f,t.select,e),f=zr(f,t.where??{},e,t.from,t.schema),f=Ut(f,t.order,void 0,e,t.from),t.limit!==void 0&&(f=f.limit(t.limit)),t.offset!==void 0&&(f=f.offset(t.offset)),f}var w_=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),S_={$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 __(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||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function E_(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var bp={db:w_,operators:{...Oi,...S_},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:E_,jsonPath:__,rowIdColumn:"ctid"};var x_=/[.*+?[\]{}()|]/;function Qi(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function wp(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function El(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=wp(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=wp(r),n+=1;}return e}function Yi(t){return t?x_.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function Sp(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return Yi(e)?{mode:"exact",text:Qi(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return Yi(e)?{mode:"prefix",text:Qi(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return Yi(e)?{mode:"suffix",text:Qi(e)}:null}return Yi(t)?{mode:"contains",text:Qi(t)}:null}function _p(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Ep(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var P_=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function $_(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||In(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function I_(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 N_(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=>(In(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var D_=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function j_(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function xp(t,e,n){let r=j_(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function L_(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function xl(t,e){let n=k(t),r=L_(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>xl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>xl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>xp(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!D_.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>xp(n,o,e.config)),i)})`}function Tl(t,e){return sql`${k(t)} GLOB ${e}`}function F_(t,e){let n=k(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function U_(t,e){let n=k(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Tp(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=Sp(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Ep(r.mode,r.text),o=k(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=_p(r.mode,r.text);return Tl(t,s)}function Xi(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=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:Tl(t,typeof o=="string"?El(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var M_={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?F_(e,n):sql`${k(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${k(e)}) != json(${JSON.stringify(n)})`:sql`${k(e)} != ${n}`,$textSearch:(t,e,n)=>xl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return Tl(e,El(n))},$regex:(t,e,n)=>Tp(e,n,false),$iregex:(t,e,n)=>Tp(e,n,true),$ilike:(t,e,n)=>sql`lower(${k(e)}) like lower(${n})`,$likeAny:(t,e,n)=>Xi(e,n,"like","any"),$ilikeAny:(t,e,n)=>Xi(e,n,"ilike","any"),$likeAll:(t,e,n)=>Xi(e,n,"like","all"),$ilikeAll:(t,e,n)=>Xi(e,n,"ilike","all"),$isDistinct:(t,e,n)=>U_(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return I_(e,n);if(n!==null&&typeof n=="object")return N_(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),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=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 B_(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 Rp={db:P_,operators:{...Oi,...M_},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:B_,jsonPath:$_,rowIdColumn:"rowid"};function q_(t){switch(t){case "postgres":return bp;case "sqlite":return Rp;default:throw new Error(`Unsupported dialect: ${t}`)}}function te(t,e="postgres",n){let r=q_(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return mp(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var cc=ca(Cl());Yr();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function ot(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}async function Hp(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ot({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:ot({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:ot({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await jwtVerify(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof errors.JWTExpired?{kind:"error",response:ot({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:ot({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}Xl();function vE(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function AE(t,e){let n=t.schema||"public",r=Xa(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function Vp(t,e){let n=AE(t,e);return Le(n.pgTypeName)?dd(n)??We(n):We(n)}function OE(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new at(r.table,s),n.set(i,o)),o.set(r.name,Vp(r,t));}return n}function PE(t,e){for(let n of e.columns){if(!Le(Xa(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new at(n.table,r),t.set(s,i)),i.set(n.name,Vp(n,e));}return t}function Qp(t,e,n){if(n==="sqlite")return OE(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return PE(new Map(r),e)}return t&&t.size>0?t:new Map}function Yp(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function Xp(t,e,n,r){return !n||!e?.from?t:t.map(s=>Zl(s,e.select,e.from,e.schema,e.join,n,r))}function Zl(t,e,n,r,s,i,o){let a=vE(i,n,r,o),l=IE(e,s),c={};for(let[f,u]of Object.entries(t)){let d=l.get(f);if(d&&"embed"in d){let m=d.embed;c[f]=$E(u,m,r,i,o);continue}let p=d?.sourceColumn??f,g=a?.get(p);c[f]=g?.isShimBacked?g.deserialize(u):u;}return c}function $E(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?Zl(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?Zl(t,e.select,e.table,n,e.join,r,s):t}function IE(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(NE(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 NE(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 Bn=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;}},ec=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")}async runInTransaction(e){return this.kysely.transaction().execute(n=>e(n))}createMigrator(e){throw new Error("This Connection does not support migrations")}async onPostgrestAST(e,n){return e}deserializeRow(e){return e}normalizeDbError(e){return e}async withContext(e,n,r){return n(this.kysely)}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function Et(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var Zp=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function em(t){let e=t.match(Zp);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 tm(t){return Zp.test(t)}function nm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function pn(t){if(Array.isArray(t))return t.map(e=>pn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=pn(r));return e}return t}function io(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let 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 jE(t,e){return !e||e.length===0?t:t.map(n=>ic(n,e))}function rm(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=jE(t,e);return r=FE(r,e),r=UE(r,e),r=ME(r,e),n==="sqlite"&&(r=BE(r,e),r=LE(r,e)),r}function LE(t,e){if(!e||e.length===0)return t;let n=qE(e);return n.size===0?t:t.map(r=>{if(!Hn(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 FE(t,e){return !e||e.length===0?t:t.map(n=>nc(n,e))}function UE(t,e){return !e||e.length===0?t:t.map(n=>rc(n,e))}function ME(t,e){return !e||e.length===0?t:t.map(n=>sc(n,e))}function BE(t,e){return !e||e.length===0?t:t.map(n=>tc(n,e))}function qE(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&&!sm(i.cast)&&e.add(r);}return e}function sm(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function HE(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function tc(t,e){if(Array.isArray(t))return t.map(r=>tc(r,e));if(!Hn(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(fs(i)){s in n&&i.select&&(n[s]=tc(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!HE(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new An(l);n[s]=Number.parseInt(l,10);}return n}function ic(t,e){if(Array.isArray(t))return t.map(r=>ic(r,e));if(!Hn(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||!fs(i)||s in n&&(n[s]=KE(n[s],i.select));}return n}function nc(t,e){if(Array.isArray(t))return t.map(r=>nc(r,e));if(!Hn(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(fs(i)){s in n&&i.select&&(n[s]=nc(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=WE(n[s]));}return n}function rc(t,e){if(Array.isArray(t))return t.map(r=>rc(r,e));if(!Hn(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(fs(i)){s in n&&i.select&&(n[s]=rc(n[s],i.select));continue}sm(i.cast)&&s in n&&(n[s]=im(n[s]));}return n}function sc(t,e){if(Array.isArray(t))return t.map(r=>sc(r,e));if(!Hn(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(fs(i)){s in n&&i.select&&(n[s]=sc(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=im(n[s]));}return n}function WE(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 KE(t,e){let n=JE(t);return !e||e.length===0?n:ic(n,e)}function JE(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 im(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function Hn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function fs(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var GE=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 om(t){let e=em(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function am(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(GE.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function lm(t,e){let n=em(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?Et({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function lt(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function cm(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function qn(t,e,n,r){if(e.type==="rpc"){let f={...e,order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,m=await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(f=>f.type==="inner"),i=zE(e);if(s||i){let f={...e,type:"query",order:void 0,limit:void 0,offset:void 0},u=te(f,n,{db:t,introspection:r}),{sql:d,parameters:p}=u.compile(),g=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,h=(await t.executeQuery({sql:g,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(h?.__count??0)}let o={...e,type:"query",select:[{__count:{aggregate:"count"}}],order:void 0,limit:void 0,offset:void 0,join:void 0},l=await te(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function oc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return qn(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=te(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:qn(t,e,n,r)}function zE(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=VE(t.select);return e.size===0?false:um(t.where,e)}function um(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"&&um(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 VE(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function ac(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function Ht(t,e,n){return ac(e)?`*/${n??0}`:t.type==="update"&&n!==0?lt(0,n??1,void 0):"*/*"}function fm(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":lt(n,1,r)}var QE=/[",\n\r ]/;function dm(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),QE.test(e)?`"${e.replace(/"/g,'""')}"`:e}function oo(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>dm(s)).join(",")];for(let s of t)r.push(n.map(i=>dm(s[i])).join(","));return r.join(`
81
- `)}function pm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function gm(t){return t==null?[]:Array.isArray(t)?t.map(e=>ds(e)?new Set(Object.keys(e)):new Set):ds(t)?[new Set(Object.keys(t))]:[]}function ym(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function bm(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=mm(t,e),s=YE(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!ds(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!ZE(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:mm(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 wm(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=ps(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:et(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function mm(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 YE(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=XE(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function XE(t){if(!ds(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function ZE(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):Et(t)===Et(e)}function ps(t,e){let n=[];return e&&n.push(`resolution=${e}`),t?.missing&&n.push(`missing=${t.missing}`),t?.return&&n.push(`return=${t.return}`),t?.count&&t.count!=="none"&&n.push(`count=${t.count}`),t?.tx&&n.push(`tx=${t.tx}`),n.length>0?n.join(", "):void 0}function et(t,e,n,r){switch(t.type){case "insert":return 201;case "upsert":return !n||n==="ignore-duplicates"?201:r===false?200:201;case "put":return e==="representation"?r?201:200:204;case "update":case "delete":return e==="representation"?200:204;default:return 200}}async function Sm(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await hm(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(!ds(o))continue;let a=ex(s.preflight.conflictColumns,o);if(!a||!await hm(t,e.from,e.schema,a,n,r))return true}return false}function ex(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function hm(t,e,n,r,s,i){return await qn(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function ds(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function tx(t){return "select"in t||"spread"in t||"join"in t}function _m(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))tx(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),_m(r.select,e));}}var nx={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function rx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!sx(i,s))}function sx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=nx[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function ix(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function Em(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&ml(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let f=c?.plan_enabled===true;if(!t.allowRawMedia&&!am(i,f))return T(406,"PGRST107",`None of these media types are available: ${om(i)}`,null,null);let u=nm(i),d=pm(i),p=rx(o,r.timezones);if(p.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${p.join(", ")}`,null);let g=ix(e);if(g)return g;if(n==="sqlite"&&e.from){let b=e.schema??"",_=r.tables.some(x=>x.name===e.from&&(x.schema??"")===b),E=r.views.some(x=>x.name===e.from&&(x.schema??"")===b);if(!_&&!E)throw new Bn(e.schema,e.from)}let m=e.$meta,h=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",y={ast:e};if(h&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&h){let b=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!b)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!b)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(h&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let b=m?.return==="representation"?200:204,_=ps(m,y.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,m,0)};if(_&&(E["Preference-Applied"]=_),m?.return==="representation"){let x=new TextEncoder().encode("[]");return E["Content-Length"]=String(x.byteLength),new Response(x,{status:b,headers:E})}return new Response(null,{status:b,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?y.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(b=>typeof b!="object"||b===null||Array.isArray(b)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let b=Object.keys(e.values[0]).sort().join(",");for(let _=1;_<e.values.length;_++)if(Object.keys(e.values[_]).sort().join(",")!==b)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){y.bodyKeySets=gm(e.values);let b=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let _=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let x={};for(let O of _)O in E&&(x[O]=E[O]);return x});else {let E={};for(let x of _)x in e.values&&(E[x]=e.values[x]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=r.columns.filter(_=>_.table===e.from).map(_=>_.name);if(b.length>0){let _=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of _)if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=e.schema??"public",_=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===b&&E.is_generated===true).map(E=>E.name));if(_.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let x of E)if(!(!x||typeof x!="object")){for(let O of Object.keys(x))if(_.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let w=bm(e,r);if(w instanceof Response)return w;let S=y.bodyKeySets;if(y=w,y.bodyKeySets=S,e=y.ast,h&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||y.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):wm(e,y);if(l&&(a==="GET"||a==="HEAD")){let b=l.match(/^(\d+)-(\d*)$/);if(b){let _=parseInt(b[1],10);if(b[2]!==""){let E=parseInt(b[2],10);if(_>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=_,e.limit=E-_+1;}else e.offset=_;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!h){let b=c?.max_rows;b!==void 0&&b>0&&((e.limit===void 0||e.limit>b)&&(e.limit=b),_m(e.select,b));}return {ast:e,meta:m,mutationPlan:y,isMutation:h,stripNullsResponse:u,csvResponse:d,planEnabled:f}}var Wn=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};ki();Vr();Fn();function xm(t){if(t.from)return t.from}function Cm(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof fe){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof He)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof An)return T(400,t.code,t.message,null,null);if(t instanceof jt)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof vn)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof ve)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof On)return T(400,"PGRST102",t.message,null,null);if(t instanceof vr)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof wt)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof on)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof Wn){let l=qt(s,"auth.role","anon")==="anon"?401:403;return ot({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof Bn){let a=o.schema||"public",l=[...r.tables.filter(d=>(d.schema||"public")===a).map(d=>d.name),...r.views.filter(d=>(d.schema||"public")===a).map(d=>d.name)],c=l.length>0?l:[...r.tables.map(d=>d.name),...r.views.map(d=>d.name)],f=Jr(o.relation,c),u=f?`Perhaps you meant the table '${a}.${f}'`:null;return ot({status:404,code:"PGRST205",message:o.message,hint:u})}if(typeof o?.code=="string"){if(o.code==="PGRST")return ax(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=qt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?xm(i):void 0;if(o.code==="42703"&&c){let f=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(u,d)=>f?.includes(d)?u:`column ${c}.${d} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var lc=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,ox="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",Tm="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function Rm(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ax(t){let e=typeof t.message=="string"?t.message:"",n=Rm(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",lc,`Invalid JSON value for MESSAGE: '${e}'`,ox);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",lc,"DETAIL is missing in the RAISE statement",Tm);let s=Rm(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",lc,`Invalid JSON value for DETAIL: '${r}'`,Tm);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[u,d]of Object.entries(i))typeof d=="string"&&(c[u]=d);let f={status:s.status,headers:c};typeof s.status_text=="string"&&(f.statusText=s.status_text);try{return new Response(l,f)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var cx="response.status guc must be a valid status code",Kn="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function km(t,e){let n=(await sql`
80
+ `;)i+=t[r],r++;n.push(i),r<s&&t[r]===","&&r++;}}return {row:n,nextPos:r}}var In=class extends Error{constructor(e){super(e),this.name="CsvParseError";}};function rl(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 sl(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 Ed=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"]),_d={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"},tS={any:"Any",all:"All"},nS=new Set(["eq","gt","gte","lt","lte","like","ilike","match","imatch"]),rS={fts:void 0,plfts:"plain",phfts:"phrase",wfts:"websearch"};function ji(t){let e=t.match(/^(\w+)\((any|all)\)$/);if(e){let[,s,i]=e;if(!nS.has(s))return null;let o=_d[s];return o?{astOp:o+tS[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:rS[s],ftsConfig:i}}let r=_d[t];return r?{astOp:r}:null}function Dr(t){let e=t.indexOf(".");if(e===-1)return false;let r=t.substring(0,e).replace(/\((any|all)\)$/,"").replace(/^(p[lh]fts|wfts|fts)\([^)]+\)$/,"$1");return Ed.has(r)}var ln=new Set(["select","order","limit","offset","on_conflict","columns","apikey"]);function jr(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(at(r,{preserveWhitespace:true}));}n<t.length&&t[n]===","&&(n++,n===t.length&&e.push(""));}return e}function cn(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(at(r));}n<t.length&&t[n]===","&&n++;}return e}var Dn=Symbol.for("postgrest:not_null"),un=Symbol.for("postgrest:unknown");function at(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 Dn;if(s==="true")return true;if(s==="false")return false;if(s==="unknown")return null;if(/^-?0\d+$/.test(r)||/^[0-9A-Fa-f]+$/.test(r)&&/[A-Fa-f]/.test(r))return r;if(r!==""&&!Number.isNaN(Number(r))&&Number.isFinite(Number(r)))return Number(r);if(r.startsWith("{")&&r.endsWith("}"))try{let i=JSON.parse(r);if(typeof i=="object"&&!Array.isArray(i))return i}catch{}return n?r===""?"":t:r}function Ur(t,e,n,r){let s={},i={};for(let[o,a]of t){if(ln.has(o))continue;let c=o.startsWith('"')?-1:o.indexOf(".");if(c>0&&!o.slice(0,c).includes("->")){let u=o.slice(0,c),f=o.slice(c+1);if(e.has(u)){if(f==="order"||f==="limit"||f==="offset")continue;if(f.includes(".")){let d=f.lastIndexOf("."),p=f.slice(d+1);if(p==="order"||p==="limit"||p==="offset")continue}i[u]||(i[u]={}),aS(f,a,i[u]);continue}if(o!=="not.or"&&o!=="not.and")throw iS(u)}if(e.has(o)&&!a.every(sS)&&!r?.has(o)){let u=n?`${n}.${o}`:o,f=new Error(`column ${u} does not exist`);throw f.code="42703",f}ol(o,a,s);}return {where:s,embeddedWheres:i}}function sS(t){return /^(not\.)?is\.(null|true|false|distinct\.)/.test(t.trim())}function iS(t){return new $e({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 ol(t,e,n){if(t==="or"||t==="and"){if(e.every(o=>!o.includes("("))){for(let o of e)oS(t,o,n);return}let s=e.map(o=>Td(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=>Td(a)),o=i.length===1?i[0]:i.flat();n.$not={[`$${s}`]:o};return}let r=Rd(dS(t),{stopAtSpace:false});Cd(r);for(let s of e){let i=al(s);n[r]?Object.assign(n[r],i):n[r]=i;}}function oS(t,e,n){let r=e.indexOf("."),s=r===-1?e:e.slice(0,r),i=`${t}${s}`,o=r===-1?"":e.slice(r+1),a=al(o);n[i]?Object.assign(n[i],a):n[i]=a;}function aS(t,e,n){let r=lS(t);if(!r){ol(t,e,n);return}let s={};ol(r.filterKey,e,s);for(let[i,o]of Object.entries(s))n[`${r.path}.${i}`]=o;}function lS(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 al(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=ji(s);if(!o){let f=s.match(/^(p[lh]fts|wfts|fts)\(\)$/);throw f?new Error(`"failed to parse filter (${t})" (line 1, column ${f[1].length+2})`):new Error(`"failed to parse filter (${t})" (line 1, column 1)`)}let{astOp:a,ftsType:l,ftsConfig:c}=o;if(n&&a==="$in")return {$notIn:il(a,i)};if(n&&a==="$is")return {$isNot:il(a,i)};let u=a==="$textSearch"?uS(i,l,c):il(a,i);return n?{$not:{[a]:u}}:{[a]:u}}function il(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 jr(e)}if(t.endsWith("Any")||t.endsWith("All")){if(e.startsWith("{"))return cn(e);if(!cS(t))throw Object.assign(new Error(`malformed array literal: "${e}"`),{code:"22P02",detail:'Array value must start with "{" or dimension information.'});return jr(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 cn(e)}return e.startsWith("[")||e.startsWith("(")?e:at(e)}if(t.startsWith("$range"))return e;if(t==="$is"){let n=e.toLowerCase().trim(),s=["not_null","unknown","null","true","false"].find(i=>n===i||n.startsWith(i));if(!s)throw new Error(`"failed to parse filter (is.${e})" (line 1, column ${2+e.length})`);return s==="unknown"?un:s==="not_null"?Dn:s==="null"?null:s==="true"?true:s==="false"?false:at(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("{")?cn(n):jr(n):n}if(t==="$isDistinct")return e.startsWith("{")?cn(e):e;if((t==="$eq"||t==="$neq")&&e.startsWith("{")&&e.endsWith("}")){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&!Array.isArray(n))return n}catch{}return cn(e)}return at(e)}function cS(t){return t==="$likeAny"||t==="$ilikeAny"||t==="$likeAll"||t==="$ilikeAll"}function uS(t,e,n){let r={query:t};return e&&(r.type=e),n&&(r.config=n),r}function fS(t){let e=t.match(/^\(\(or\([^)]*\),/);if(e)return e[0].length+8;let n=t.match(/^\(or\([^)]*\),/);return n?n[0].length+8:t.length+2}function xd(t){return new Error(`"failed to parse logic tree (${t})" (line 1, column ${fS(t)})`)}function Td(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 xd(t);try{return Lr(e).map(r=>Fr(r))}catch{throw xd(t)}}function Lr(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:Lr(n[1]).map(d=>Fr(d))};let r=e.match(/^or\s*\((.*)\)$/s);if(r)return {$or:Lr(r[1]).map(d=>Fr(d))};let s=e.match(/^not\.and\s*\((.*)\)$/s);if(s)return {$not:{$and:Lr(s[1]).map(d=>Fr(d))}};let i=e.match(/^not\.or\s*\((.*)\)$/s);if(i)return {$not:{$or:Lr(i[1]).map(d=>Fr(d))}};if(/^(?:and|or|not)=/.test(e))throw new Error(`Invalid filter expression: "${t}"`);if(e.startsWith("not("))throw new Error(`Invalid filter expression: "${t}"`);let o=t;if(o.startsWith("not.")){let p=o.slice(4).split(".")[0];if(!(p.length>0&&ji(p)!==null))throw new Error(`Invalid filter expression: "${t}"`)}let l=o.indexOf(".");if(l===-1)throw new Error(`Invalid filter expression: "${t}"`);let c=Rd(o.slice(0,l),{stopAtSpace:true});Cd(c);let u=o.slice(l+1),f=al(u);return {[c]:f}}function Rd(t,e){let r=(e.stopAtSpace?/[!@/\\~[\]()\t ]/:/[!@/\\~[\]()\t]/).exec(t),s=r?t.slice(0,r.index):t,i=s.indexOf("::");i!==-1&&(s=s.slice(0,i));let o=s.indexOf("=");o!==-1&&(s=s.slice(0,o));let a=s.indexOf(":");return a!==-1&&(s=s.slice(0,a)),s}function dS(t){return t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t}function Cd(t){if(t===""||t==="*"||t.startsWith(".")||t.includes("--")||t.endsWith("-"))throw new Error(`Invalid filter expression: "${t}"`);if(/->>?-\d+[A-Za-z]/.test(t))throw new Error(`Invalid filter expression: "${t}"`)}function pS(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\(([^)]+)\)$/);return e?{embed:e[1],column:e[2]}:null}function kd(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 ll(t,e){let n=kd(t),r=kd(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 ul(t,e){let n={embeddedTransforms:{}},r,s,i={},o={},a={},l={};for(let[d,p]of t){let h=p[0],m=d.indexOf(".");if(m>0){let g=d.slice(0,m),y=d.slice(m+1);if(e.has(g)){if(y==="order"||y==="limit"||y==="offset"){n.embeddedTransforms[g]||(n.embeddedTransforms[g]={}),y==="order"?n.embeddedTransforms[g].order=cl(h):y==="limit"?i[g]=h:y==="offset"&&(o[g]=h);continue}if(y.includes(".")){let w=y.lastIndexOf("."),S=y.slice(w+1);if(S==="order"||S==="limit"||S==="offset"){n.embeddedTransforms[g]||(n.embeddedTransforms[g]={});let b=n.embeddedTransforms[g],_=y.slice(0,w);b._nested||(b._nested={});let E=b._nested;E[_]||(E[_]={});let x=E[_];S==="order"?x.order=cl(h):S==="limit"?(a[g]||(a[g]={}),a[g][_]=h):S==="offset"&&(l[g]||(l[g]={}),l[g][_]=h);continue}}}}d==="order"?n.order=cl(h):d==="limit"?r=h:d==="offset"&&(s=h);}if(n.order){for(let d of n.order)if(d.embed&&!e.has(d.embed))throw new $e({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=ll(r,s);c.limit!==void 0&&(n.limit=c.limit),c.offset!==void 0&&(n.offset=c.offset);let u=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of u){let p=ll(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 f=new Set([...Object.keys(a),...Object.keys(l)]);for(let d of f){let p=new Set([...Object.keys(a[d]??{}),...Object.keys(l[d]??{})]);for(let h of p){let m=ll(a[d]?.[h],l[d]?.[h]),g=n.embeddedTransforms[d]?._nested?.[h];g&&(m.limit!==void 0&&(g.limit=m.limit),m.offset!==void 0&&(g.offset=m.offset));}}return n}function cl(t){return mS(t).map(({entry:e,start:n},r)=>{let s=r===0?e.trim():e.trimEnd(),i=r===0?n+e.length-e.trimStart().length:n;return hS(s,t,i)})}function mS(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 hS(t,e,n){let r=t.split("."),s={column:r[0].replace(/\s+$/,"")},i=r[0];if(!i)throw new ge(`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 ge(`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 ge(`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 ge(`failed to parse order (${e})`,`unexpected '${i[l]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+l+1);if(i.endsWith("-"))throw new ge(`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 ge(`failed to parse order (${e})`,`unexpected ':' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+c+1);let u=pS(i);if(u){if(u.column.includes(","))throw new ge(`failed to parse order (${e})`,`unexpected ',' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+i.indexOf(",",u.embed.length)+1);s.column=u.column,s.embed=u.embed;}else if(i.includes("(")||i.includes(")")){let h=i.search(/[()]/);throw new ge(`failed to parse order (${e})`,`unexpected '${i[h]}' expecting letter, digit, "-", "->>", "->", delimiter (.), "," or end of input`,n+h+1)}let f=n+i.length+1,d=false,p=false;for(let h=1;h<r.length;h++){let m=r[h];if(m==="asc"||m==="desc"){if(d)throw new ge(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);if(p)throw new ge(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.direction=m,d=true,f+=m.length+1;}else if(m==="nullsfirst"||m==="nullslast"){if(p)throw new ge(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1);s.nullsFirst=m==="nullsfirst",p=true,f+=m.length+1;}else {let g=["asc","desc","nullsfirst","nullslast"],y=null;for(let w of g)if(m.startsWith(w)&&m.length>w.length){y=w;break}if(y){let w=m[y.length],S=f+y.length;throw new ge(`failed to parse order (${e})`,`unexpected '${w}' expecting "," or end of input`,S+1)}throw new ge(`failed to parse order (${e})`,`unexpected '${m[0]}' expecting "," or end of input`,f+1)}}return s}function fl(t,e,n){let r={};for(let i of t.preferTokens)switch(i.key){case "count":r.count===void 0&&(r.count=i.value);break;case "missing":r.missing===void 0&&(r.missing=i.value);break;case "handling":r.handling===void 0&&(r.handling=i.value);break;case "tx":r.tx===void 0&&(r.tx=i.value,i.value==="rollback"&&(r.rollback=true));break;case "max-affected":r.maxAffected===void 0&&(r.maxAffected=i.value);break;case "timezone":r.timezone===void 0&&(r.timezone=i.value);break;case "return":r.return===void 0&&(r.return=i.value);break}n.toUpperCase()==="HEAD"&&(r.head=true),t.accept.includes("application/vnd.pgrst.object")&&(r.cardinality="one"),t.accept.includes("application/vnd.pgrst.plan")&&(r.explain=bS(t.accept));let s=e.get("columns");if(s){let i=s[0];r.columns=gS("columns",i);}return r}function gS(t,e){let n=e.split(",").map(r=>yS(r));if(n.length===0||n.some(r=>r===""||r==="*"||r.includes("--")||r.endsWith("-")))throw new Ft(`"failed to parse ${t} parameter (${e})" (line 1, column 1)`,"unexpected input");return n}function yS(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e.replace(/@.*$/,"")}function bS(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 dl(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(ln.has(a))continue;let c=l.filter(u=>!Dr(u));c.length!==0&&(c.length>1?i[a]=c.map(u=>at(u)):i[a]=at(c[0]));}let o={httpMethod:"GET",paramsType:"named",inputType:"json"};return Object.keys(i).length>0&&(o.args=i),o}function pl(t,e){let n=t.get("on_conflict"),r=n===void 0?void 0:wS(n[0]),i=e.preferTokens.find(o=>o.key==="resolution")?.value==="ignore-duplicates";return {onConflict:r?.length?r:void 0,ignoreDuplicates:i}}function wS(t){let e=t.split(",").map(n=>n.trim());if(e.length===0||e.some(n=>n===""||n.includes("--")||n.endsWith("-")))throw new Ft(`"failed to parse on_conflict parameter (${t})" (line 1, column 1)`,"unexpected input");return e.map(n=>n.replace(/[!@/\\~[\]()\t ].*$/,""))}async function Li(t,e){let n=e?.basePath,r=e?.parseRoute??(k=>Qa(k,n)),s=e?.parseHeaders??Ya,i=e?.parseSelect??tl,o=e?.parseBody??nl,a=e?.parseQueryParams??rl,l=e?.resolveType??sl,c=e?.resolveFilters??Ur,u=e?.resolveTransforms??ul,f=e?.resolveMeta??fl,d=e?.resolveRpcParams??dl,p=e?.resolveUpsertParams??pl,[h,m,g,y,w]=await Promise.all([r(t),s(t),i(t),o(t),a(t)]),S=t.method,b=l(h,S,m),_=w;if(h.isRpc&&S.toUpperCase()==="GET"){_=new Map;for(let[k,N]of w){if(ln.has(k)){_.set(k,N);continue}let H=N.filter(V=>Dr(V));H.length>0&&_.set(k,H);}}let E=c(_,g.embeddedAliases,h.isRpc?void 0:h.from,e?.parentColumns),x=u(w,g.embeddedAliases),O=f(m,w,S),v=d(h,S,w,y),$=b==="upsert"||b==="put"?p(w,m):void 0;return SS(b,h,m,g,y,E,x,O,v,$)}function SS(t,e,n,r,s,i,o,a,l,c){let u={type:t};return e.isRpc?u.function=e.function:u.from=e.from,n.schema&&(u.schema=n.schema),Object.keys(r.join).length>0&&(u.join=r.join),r.select.length>0&&(u.select=Ad(r.select,i.embeddedWheres,o.embeddedTransforms,r.join)),Object.keys(i.where).length>0&&(u.where=i.where),(t==="insert"||t==="update"||t==="upsert"||t==="put")&&s.values!==void 0&&(u.values=s.values),t==="rpc"&&(l.args!==void 0&&(u.args=l.args),l.httpMethod&&(u.httpMethod=l.httpMethod),l.paramsType&&(u.paramsType=l.paramsType),l.inputType&&(u.inputType=l.inputType)),(t==="upsert"||t==="put")&&c&&(c.onConflict&&(u.onConflict=c.onConflict),u.ignoreDuplicates=c.ignoreDuplicates),a.return==="representation"&&(t==="insert"||t==="update"||t==="delete"||t==="upsert"||t==="put")&&(!u.select||u.select.length===0)&&(u.select=["*"]),o.order&&(u.order=o.order),o.limit!==void 0&&(u.limit=o.limit),o.offset!==void 0&&(u.offset=o.offset),Object.keys(a).length>0&&(u.$meta=a),u}function _S(t,e,n){return t.map(r=>{if(typeof r=="string"||!(e in r))return r;let s=r[e];return s.select?{[e]:{...s,where:{...s.where??{},...n}}}:r})}function Ad(t,e,n,r,s){return t.map(i=>{if(typeof i=="string")return i;let o=Object.keys(i)[0],a=i[o];if(!a.select)return i;let l={...a},c=r?.[o]?.from,u=e[o]||c&&e[c],f=n[o]||c&&n[c];if(u&&s!==o){let d={},p={};for(let[h,m]of Object.entries(u)){let g=h.indexOf(".");if(g>0){let y=h.slice(0,g),w=h.slice(g+1);if(l.join?.[y]||l.select?.some(_=>typeof _=="object"&&y in _&&"select"in(_[y]??{}))){p[y]||(p[y]={}),p[y][w]=m;continue}}d[h]=m;}Object.keys(d).length>0&&(l.where=d);for(let[h,m]of Object.entries(p))l.select=_S(l.select??[],h,m);}if(f){let d=f;if(d.order&&(l.order=d.order),d.limit!==void 0&&(l.limit=d.limit),d.offset!==void 0&&(l.offset=d.offset),d._nested)for(let[p,h]of Object.entries(d._nested))n[p]=h;}return l.select&&(l.select=Ad(l.select,e,n,l.join,o)),{[o]:l}})}function Fi(t){return t!=null&&typeof t=="object"&&"$ref"in t}lt();var ml=class extends le{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string")return jn(e);throw this.checkError("color_range",e)}deserialize(e){if(this.isNullish(e))return "";if(typeof e=="number"&&Number.isFinite(e))return vd(e);if(typeof e=="string"&&e.startsWith("#"))return e;if(typeof e=="string"||typeof e=="bigint"){let n=Number(e);if(Number.isFinite(n))return vd(n)}return e}},hl=class extends le{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="string"?e.replace(/Z$/,"+00:00"):e}deserialize(e){if(this.isNullish(e)||typeof e!="string")return e;let n=e.trim();if(/^\d{4}-\d{2}-\d{2}T/.test(n))return n.replace(/\+00:00$/,"Z");if(/^\d{4}-\d{2}-\d{2}$/.test(n))return `${n}T00:00:00Z`;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(n)){let r=n.replace(" ","T");return /(?:Z|[+-]\d{2}:\d{2})$/.test(r)?r.replace(/\+00:00$/,"Z"):`${r}Z`}return n.replace(/\+00:00$/,"Z")}},gl=class extends le{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}serialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="string"){let n=Date.parse(e);if(Number.isFinite(n))return Math.trunc(n/1e3)}return e}deserialize(e){if(this.isNullish(e))return e;if(typeof e=="number"&&Number.isFinite(e))return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(e instanceof Date&&Number.isFinite(e.getTime()))return Math.trunc(e.getTime()/1e3);if(typeof e=="string"){let n=e.trim();if(/^\d+$/.test(n))return Number(n);let r=Date.parse(n);if(Number.isFinite(r))return Math.trunc(r/1e3)}return e}},yl=class extends le{get isShimBacked(){return true}get sqliteType(){return "TEXT"}serialize(e){return this.isNullish(e)?e:typeof e=="number"&&Number.isFinite(e)?e.toFixed(2):e}deserialize(e){return e}},bl=class extends le{get isShimBacked(){return true}get sqliteType(){return "TEXT"}deserialize(e){if(this.isNullish(e))return e;let n=null;if(typeof e=="string")n=e;else if(e instanceof Uint8Array)n=Buffer.from(e).toString("base64");else if(e&&typeof e=="object"&&!Array.isArray(e)){let s=Object.values(e);n=Buffer.from(s).toString("base64");}if(n===null)return e;n=n.replace(/\s/g,"");let r=(4-n.length%4)%4;return r===0?n:n+"=".repeat(r)}};function jn(t){let e=t.trim(),r=(e.startsWith("#")?e.slice(1):e).padStart(8,"0");return Number.parseInt(r,16)>>>0}function vd(t){return `#${(Math.trunc(t)&16777215).toString(16).toUpperCase().padStart(6,"0")}`}function Pd(t,e){return e==="postgres"||e==="pglite"?sql`('"' || upper('#' || lpad(to_hex((${t})::bigint & 16777215), 6, '0')) || '"')`:sql`('"' || upper(printf('#%06X', (${t}) & 16777215)) || '"')`}var ES=new Set(["color","isodate","isodatetext","unixtz","monetary","monetarytext","bytea_b64"]),xS=new Set(["bool","boolean"]),$d=new Map;function qe(t){if(!t)return false;let e=t.toLowerCase().trim();return ES.has(e)||$d.has(e)}function Ue(t,e){return (t??e).toLowerCase().trim()}function wl(t,e){let n=Ue(t.pg_type,t.type);return qe(n)||!e?n:TS(t.table,t.name,e)??n}function TS(t,e,n){let r=n.views.find(i=>i.name===t);if(!r?.sql)return;let s=[new RegExp(`CAST\\s*\\(.+?\\s+AS\\s+([\\w.]+)\\)\\s+AS\\s+${e}\\b`,"is"),new RegExp(`::\\s*(?:[\\w.]+\\.)?([\\w]+)\\s+AS\\s+${e}\\b`,"i")];for(let i of s){let o=r.sql.match(i);if(!o)continue;let a=o[1].split(".").pop().toLowerCase();if(qe(a)||xS.has(a))return a}}function Sl(t){if(typeof t=="string"&&t.trim()==="Z")throw Object.assign(new Error('invalid input syntax for type timestamp with time zone: "Z"'),{code:"22007",detail:null,hint:null})}function Nd(t){return Array.isArray(t)?t.map(e=>Od(e)):Od(t)}function Od(t){if(typeof t=="number"&&Number.isFinite(t))return Math.trunc(t);if(typeof t=="string"){let e=t.trim();return jn(e.startsWith("#")?e:`#${e}`)}return t}function Mi(t,e){let n=e.toLowerCase().trim();return n==="color"?sql`to_json('#' || lpad(upper(to_hex((${t})::bigint & 16777215)), 6, '0'))`:n==="unixtz"?sql`to_json(EXTRACT(EPOCH FROM ${t})::bigint)`:n==="monetary"||n==="monetarytext"?sql`to_json((${t})::text)`:n==="bytea_b64"?sql`to_json(encode((${t})::bytea, 'base64'))`:n==="isodate"||n==="isodatetext"?sql`to_json(to_char((${t}) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))`:null}function Id(t,e){let n=e.toLowerCase().trim();if(n==="unixtz"){let r=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;if(Number.isFinite(r)){let s=new Date(r*1e3);if(Number.isFinite(s.getTime()))return s.toISOString()}return t}if(n==="bytea_b64"){if(typeof t=="string")try{let r=t.replace(/=+$/,"");for(;r.length%4!==0;)r+="=";let s=atob(r),i="";for(let o=0;o<s.length;o++)i+=s.charCodeAt(o).toString(16).padStart(2,"0");return `\\x${i}`}catch{return t}return t}return n==="monetary"||n==="monetarytext"?typeof t=="number"?String(t):t:(n==="isodate"||n==="isodatetext")&&typeof t=="string"?t.replace(/Z$/,"+00:00"):t}function Mr(t,e,n,r,s,i){if(r!=="postgres"||!e||!s?.columns)return t;let o=i??"public",a=s.columns.find(c=>c.table===e&&c.name===n&&(c.schema??"public")===o);if(!a)return t;let l=Ue(a.pg_type,a.type);return qe(l)?Mi(t,l)??t:t}function Dd(t,e,n,r){if(!t||!n?.columns)return false;let s=r??"public",i=n.columns.find(o=>o.table===t&&o.name===e&&(o.schema??"public")===s);return i?qe(Ue(i.pg_type,i.type)):false}function Br(t,e,n){if(!t||!e?.columns)return false;let r=n??"public";return e.columns.some(s=>s.table!==t||(s.schema??"public")!==r?false:qe(Ue(s.pg_type,s.type)))}function _l(t,e,n){let r=n??"public";return e.columns.filter(s=>s.table===t&&(s.schema??"public")===r).sort((s,i)=>s.ordinal_position-i.ordinal_position).map(s=>{let i=Ue(s.pg_type,s.type),o=qe(i);return {name:s.name,isDomain:o,domainTypeName:o?i:null}})}function jd(t){let e=t.pgTypeName.toLowerCase().trim(),n=$d.get(e);if(n)return n(t);switch(e){case "color":return new ml(t);case "isodate":case "isodatetext":return new hl(t);case "unixtz":return new gl(t);case "monetary":case "monetarytext":return new yl(t);case "bytea_b64":return new bl(t);default:return null}}var RS=/^[a-zA-Z_][a-zA-Z0-9_.]*$/,CS=/[;'"\\/*\-#]/,kS=/['\\;(]/,Et=class extends Error{constructor(n,r){super(`Unsafe ${r}: "${n}"`);this.value=n;this.context=r;this.name="SanitizeError";}};function De(t,e){if(!RS.test(t))throw new Et(t,e)}function pn(t,e){if(CS.test(t))throw new Et(t,e);let n=0;for(let r of t)if(r==="("?n++:r===")"&&n--,n<0)throw new Et(t,e);if(n!==0)throw new Et(t,e)}function Ln(t,e){if(kS.test(t))throw new Et(t,e)}function mn(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 qr(t,e){return t.map(n=>{let r=/^-?\d+$/.test(n.key);return r||Ln(n.key,e),r?`${n.op}${n.key}`:`${n.op}'${n.key}'`}).join("")}function R(t){return typeof t=="string"?sql.ref(t):t}function AS(t){return `"${t.replace(/"/g,'""')}"`}function El(t){return sql.raw(AS(t))}function xl(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 Bi(t,e,n=e.currentTable,r=e.currentSchema){return xl(t,e,n,r)!==void 0}function fe(t,e,n=e.currentTable){return Bi(t,e,n)?El(t):sql.ref(t)}function xt(t,e,n,r=n.currentTable){let s=Bi(e,n,r)?El(e):sql.ref(e);return sql`${sql.ref(t)}.${s}`}function vS(t){return (t?.pg_type??t?.type??"").toLowerCase()}function Ld(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=vS(xl(t,e,n));return r.endsWith("[]")||r.startsWith("_")||r==="array"}function Fd(t){let e=[];for(let n of t){if(!/^\d+$/.test(n))return;e.push(`[${Number(n)+1}]`);}return e.join("")}function Ut(t,e,n=e.currentTable){if(e.dialect!=="postgres")return false;let r=e.currentSchema??e.introspection?.default_schema,s=xl(t,e,n,r),i=s?.pg_type??s?.type;return i?e.introspection?.custom_types?.some(o=>o.kind==="composite"&&o.type===i&&(!s?.udt_schema||!o.schema||o.schema===s.udt_schema))??false:false}function Ud(t,e){let n=t;for(let r of e)n=sql`(${n}).${El(r)}`;return n}function Md(t,e,n,r=n.currentTable,s=false){let i=e.replace(/^\$\./,"").split(".").filter(Boolean);if(i.length===0)return fe(t,n,r);if(Ld(t,n,r)){let l=Fd(i);if(l)return sql`${fe(t,n,r)}${sql.raw(l)}`}if(Ut(t,n,r))return Ud(fe(t,n,r),i);let o=i.map((l,c)=>({op:c===i.length-1&&s?"->>":"->",key:l})),a=qr(o,"JSON path key");return sql`${fe(t,n,r)}${sql.raw(a)}`}function Hr(t,e,n=e.currentTable,r){let{col:s,parts:i}=mn(t),o=r?xt(r,s,e,n):fe(s,e,n);if(i.length===0)return o;if(Ld(s,e,n)){let c=Fd(i.map(u=>u.key));if(c)return sql`${o}${sql.raw(c)}`}if(Ut(s,e,n))return Ud(o,i.map(c=>c.key));let a=e.dialect==="sqlite"?i.map((c,u)=>u===i.length-1?{...c,op:"->>"}:c):i,l=qr(a,"JSON path key");return sql`${o}${sql.raw(l)}`}var qi={$eq:(t,e,n)=>sql`${R(e)} = ${n}`,$neq:(t,e,n)=>sql`${R(e)} != ${n}`,$gt:(t,e,n)=>sql`${R(e)} > ${n}`,$gte:(t,e,n)=>sql`${R(e)} >= ${n}`,$lt:(t,e,n)=>sql`${R(e)} < ${n}`,$lte:(t,e,n)=>sql`${R(e)} <= ${n}`,$like:(t,e,n)=>sql`${R(e)} like ${n}`,$notLike:(t,e,n)=>sql`${R(e)} not like ${n}`,$is:(t,e,n)=>{let r=R(e);return n===Dn?sql`${r} IS NOT NULL`:n===un?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=R(e);return n===Dn?sql`${r} IS NULL`:n===un?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=R(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=R(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`${R(e)} is distinct from ${n}`},Hi={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<="};function Bd(t){let e=t.replace(/^setof\s+/i,"").trim();return (e.includes(".")?e.slice(e.lastIndexOf(".")+1):e).replace(/^"|"$/g,"").trim()}function Tl(t,e,n){let r=t.replace(/^setof\s+/i,"").trim(),s=r.lastIndexOf(".");if(s>=0){let i=r.slice(0,s).replace(/^"|"$/g,"").trim(),o=r.slice(s+1).replace(/^"|"$/g,"").trim();return i===n&&o===e}return r.replace(/^"|"$/g,"").trim()===e}function Ki(t,e,n,r){let s=r??t?.default_schema??"public";return !!t?.columns?.some(i=>i.table===e&&i.name===n&&i.schema===s)}function Wi(t,e,n){return !!(t?.tables?.some(r=>r.name===e&&r.schema===n)||t?.views?.some(r=>r.name===e&&r.schema===n))}function Mt(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i){if(a.name!==n||a.schema!==o||a.has_variadic||a.arg_types.length!==1||!Tl(a.arg_types[0],e,a.schema)||!Wi(t,e,a.schema)||a.return_typtype!=="c")continue;let l=Bd(a.return_type);if(Tl(a.return_type,l,a.schema)&&Wi(t,l,a.schema))return {fnName:a.name,schema:a.schema,targetTable:l,toOne:!a.return_is_setof||a.return_rows===1}}return null}function Wr(t,e,n){let r=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return De(r,"computed relationship function reference"),sql`${sql.raw(r)}(${sql.ref(e)})`.as(n)}function Ji(t,e,n,r,s){if(r!=="postgres")return null;let i=t?.functions;if(!i)return null;let o=s??t?.default_schema??"public";for(let a of i)if(a.name===n&&a.schema===o&&!(a.has_variadic||a.arg_types.length!==1)&&Tl(a.arg_types[0],e,a.schema)&&Wi(t,e,a.schema)&&!(a.return_typtype==="c"&&Wi(t,Bd(a.return_type),a.schema)))return {fnName:a.name,schema:a.schema};return null}function Gi(t,e){let n=t.schema?`${t.schema}.${t.fnName}`:t.fnName;return De(n,"computed column function reference"),sql`${sql.raw(n)}(${sql.ref(e)})`}var OS=new Set(["$like","$notLike","$ilike","$notIlike","$likeAny","$ilikeAny","$likeAll","$ilikeAll"]);function Rl(t){return t!=null&&typeof t=="object"&&t.type==="query"}function hn(t,e){if(e.dialect==="postgres"&&e.currentTable&&!t.includes("->")&&!Ki(e.introspection,e.currentTable,t,e.currentSchema)){let r=Ji(e.introspection,e.currentTable,t,e.dialect,e.currentSchema);if(r)return Gi(r,e.currentTableAlias??e.currentTable)}return fe(t,e)}function Vi(t,e){let n=e.db;return t.schema&&(n=n.withSchema(t.schema)),kl(t,e,n)}function PS(t){return t.includes("->")}function Jd(t,e){let{col:n,parts:r}=mn(t);return r.length===0?fe(t,e):Hr(t,e)}function Re(t,e,n){let r=[];for(let[s,i]of Object.entries(e)){if(s==="$always"){i===false&&r.push(sql`0 = 1`),i===null&&r.push(sql`null`);continue}if(s==="$or"){let o=i;r.push(t.or(o.map(a=>Re(t,a,n))));}else if(s==="$and"){let o=i;r.push(t.and(o.map(a=>Re(t,a,n))));}else if(s==="$not")r.push(t.not(Re(t,i,n)));else if(s==="$exists"){let o=i;r.push(t.exists(Vi(o,n)));}else if(s==="$storageFolder"){let o=i,l=`$[${o.index-1}]`,c=fe("path_tokens",n),u=sql`CASE WHEN json_array_length(${c}) > ${o.index} THEN json_extract(${c}, ${l}) ELSE NULL END`;for(let[f,d]of Object.entries(o.ops)){let p=n.operators[f];if(!p)throw new Error(`Unsupported operator: ${f}`);r.push(p(t,u,d));}}else if(s==="$storageObject"){let o=i,a=fe("path_tokens",n),l=sql`json_extract(${a}, '$[#-1]')`,c=o.function==="filename"?l:sql`substr(${l}, length(rtrim(${l}, replace(${l}, '.', ''))) + 1)`;for(let[u,f]of Object.entries(o.ops)){let d=n.operators[u];if(!d)throw new Error(`Unsupported operator: ${u}`);r.push(d(t,c,f));}}else {let o=i,a=PS(s);for(let[l,c]of Object.entries(o)){if(Fi(c)){let u=Hi[l];if(!u)throw new Error(`Unsupported ref operator: ${l}`);r.push(sql`${a?Jd(s,n):hn(s,n)} ${sql.raw(u)} ${fe(c.$ref,n)}`);continue}if(l==="$not"){let u=c;for(let[f,d]of Object.entries(u))if(a)r.push(t.not(Kd(s,f,d,n)));else {let p=qd(s,f,d,n);if(p){r.push(t.not(p));continue}let h=Wd(s,f,d,n);if(h){r.push(t.not(h));continue}let m=Hd(s,f,d,n);if(m){r.push(t.not(m));continue}let g=n.operators[f];if(!g)throw new Error(`Unsupported operator: ${f}`);r.push(t.not(g(t,hn(s,n),d)));}}else if(Rl(c)){let u=Vi(c,n),f=n.operators[l];if(!f)throw new Error(`Unsupported operator: ${l}`);r.push(f(t,hn(s,n),u));}else if(a)r.push(Kd(s,l,c,n));else {let u=qd(s,l,c,n);if(u){r.push(u);continue}let f=NS(s,l,c,n);if(f){r.push(f);continue}DS(s,l,n);let d=Cl(s,c,n),p=Wd(s,l,d,n);if(p){r.push(p);continue}let h=Hd(s,l,d,n);if(h){r.push(h);continue}let m=n.operators[l];if(!m)throw new Error(`Unsupported operator: ${l}`);r.push(m(t,hn(s,n),d));}}}}return r.length===1?r[0]:t.and(r)}function qd(t,e,n,r){if(e!=="$is"&&e!=="$isNot"||n!==un)return null;let s=Un(t,r);if(!s)return null;let i=Gd(s.pg_type??s.type);if(i==="boolean")return r.dialect!=="sqlite"?null:e==="$is"?sql`${fe(t,r)} IS NULL`:sql`${fe(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 Un(t,e){if(!e.introspection?.columns||!e.currentTable)return null;let n=t.includes("->")?mn(t).col:t,r=e.introspection.columns.filter(i=>i.table===e.currentTable&&i.name===n);if(r.length===0)return null;let s=e.currentSchema;return r.find(i=>!s||i.schema===s)??r.find(i=>["","public"].includes(i.schema??""))??r[0]}var $S={$contains:{sym:"@>",cast:"ltree"},$containedBy:{sym:"<@",cast:"ltree"},$regex:{sym:"~",cast:"lquery"},$iregex:{sym:"~*",cast:"lquery"}};function Hd(t,e,n,r){if(r.dialect!=="postgres")return null;let s=$S[e];if(!s)return null;let i=Un(t,r);if(!i||Ue(i.pg_type,i.type)!=="ltree")return null;let o=`"${(i.udt_schema??"public").replace(/"/g,'""')}"`;return sql`${hn(t,r)} OPERATOR(${sql.raw(`${o}.${s.sym}`)}) ${n}::${sql.raw(`${o}.${s.cast}`)}`}function Wd(t,e,n,r){if(r.dialect!=="postgres"||e!=="$textSearch")return null;let s=Un(t,r);if(!s||Ue(s.pg_type,s.type)==="tsvector")return null;let i=n,o=i.config,a="to_tsquery";i.type==="plain"?a="plainto_tsquery":i.type==="phrase"?a="phraseto_tsquery":i.type==="websearch"&&(a="websearch_to_tsquery");let l=o?sql`to_tsvector(${sql.literal(o)}, ${hn(t,r)})`:sql`to_tsvector(${hn(t,r)})`,c=o?sql`${sql.raw(a)}(${sql.literal(o)}, ${i.query})`:sql`${sql.raw(a)}(${i.query})`;return sql`${l} @@ ${c}`}function Gd(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 NS(t,e,n,r){if(r.dialect!=="postgres"||e!=="$eq"&&e!=="$neq"||typeof n!="string"||!/^\s*[[{]/.test(n))return null;let s=Un(t,r),i=Gd(s?.pg_type??s?.type??"");if(i!=="json"&&i!=="jsonb")return null;let o=fe(t,r),a=sql`cast(${sql.raw(IS(n))} as ${sql.raw(i)})`;return e==="$eq"?sql`${o} = ${a}`:sql`${o} != ${a}`}function IS(t){return `'${t.replace(/'/g,"''")}'`}function DS(t,e,n){if(!OS.has(e))return;let r=Un(t,n);if(!r||Ue(r.pg_type,r.type)!=="color")return;let i=e.includes("ilike")?"~~*":"~~";throw Object.assign(new Error(`operator does not exist: color ${i} unknown`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."})}function Cl(t,e,n){if(!n?.currentTable)return e;let r=Un(t,n);if(!r)return e;let s=Ue(r.pg_type,r.type);if(s==="color")return Nd(e);if(s==="isodate"||s==="isodatetext")if(Array.isArray(e))for(let i of e)Sl(i);else Sl(e);return e}function Kd(t,e,n,r){let s=r?Jd(t,r):R(t),o={$eq:"=",$neq:"!=",$gt:">",$gte:">=",$lt:"<",$lte:"<=",$like:"like",$notLike:"not like",$ilike:"ilike",$notIlike:"not 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&&Rl(n))return sql`${s} in ${Vi(n,r)}`;let a=Cl(t,n,r);return a.length===0?sql`false`:sql`${s} in (${sql.join(a.map(l=>sql`${l}`))})`}if(e==="$notIn"){if(r&&Rl(n))return sql`${s} not in ${Vi(n,r)}`;let a=Cl(t,n,r);return a.length===0?sql`true`:sql`${s} not in (${sql.join(a.map(l=>sql`${l}`))})`}return sql`${s} = ${n}`}function Kr(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$or"||r==="$and"?n[r]=s.map(i=>Kr(i,e)):r==="$not"?n[r]=Kr(s,e):r.startsWith("$")||r.includes(".")?n[r]=s:n[`${e}.${r}`]=s;return n}function ct(t){let e=t.leftCols??[t.leftCol],n=t.rightCols??[t.rightCol];return e.map((r,s)=>({leftCol:r,rightCol:n[s]??t.rightCol}))}function Al(t,e){return `${t}_${e}_fkey`}function zi(t,e){return e===Al(t.table,t.column)}function Vd(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function zd(t,e,n){return {leftCol:`${t}.${n.column}`,rightCol:`${e}.${n.ref_column}`,type:"m2o"}}function Qd(t,e,n){return {leftCol:`${e}.${n.column}`,rightCol:`${t}.${n.ref_column}`,type:"o2m"}}function jS(t,e,n){switch(t.kind){case "constraint":case "pg_autogen":case "ref_column":return t.direction==="m2o"?zd(e,n,t.fk):Qd(e,n,t.fk);case "parent_column":return zd(e,n,t.fk);case "target_column":return Qd(e,n,t.fk);case "junction_table":return {type:"m2m",junctionTable:t.junctionTable,junctionToParentCols:t.toParent.map(r=>r.column),parentCols:t.toParent.map(r=>r.ref_column),junctionToTargetCols:t.toTarget.map(r=>r.column),targetCols:t.toTarget.map(r=>r.ref_column)}}}function Yd(t,e,n,r){let s=r.find(o=>o.foreign_key_name===t&&o.table===e&&o.ref_table===n);if(s)return {kind:"constraint",fk:s,direction:"m2o"};let i=r.find(o=>o.foreign_key_name===t&&o.table===n&&o.ref_table===e);return i?{kind:"constraint",fk:i,direction:"o2m"}:null}function Xd(t,e,n,r){let s=r.find(o=>o.table===e&&o.ref_table===n&&zi(o,t));if(s)return {kind:"pg_autogen",fk:s,direction:"m2o"};let i=r.find(o=>o.table===n&&o.ref_table===e&&zi(o,t));return i?{kind:"pg_autogen",fk:i,direction:"o2m"}:null}function Zd(t,e,n,r){let s=r.find(i=>i.table===e&&i.column===t&&i.ref_table===n);return s?{kind:"parent_column",fk:s}:null}function ep(t,e,n,r){let s=r.find(i=>i.table===n&&i.column===t&&i.ref_table===e);return s?{kind:"target_column",fk:s}:null}function tp(t,e,n,r){let s=r.filter(a=>a.table===t),i=Vd(s.filter(a=>a.ref_table===e)),o=Vd(s.filter(a=>a.ref_table===n));return i.length===0||o.length===0?null:{kind:"junction_table",junctionTable:t,toParent:i[0],toTarget:o[0]}}function np(t,e,n,r){let s=r.find(i=>i.table===n&&i.ref_column===t&&i.ref_table===e);return s?{kind:"ref_column",fk:s,direction:"o2m"}:null}function rp(t,e,n,r){let s=r.find(i=>i.table===e&&i.ref_column===t&&i.ref_table===n);return s?{kind:"ref_column",fk:s,direction:"m2o"}:null}var LS=[Yd,Xd,Zd,ep,tp,np,rp];function sp(t,e,n,r,s={}){let i=s.preferSelfReferenceTargetColumn&&e===n?[Yd,Xd,ep,Zd,tp,np,rp]:LS;for(let o of i){let a=o(t,e,n,r);if(a)return jS(a,e,n)}return null}function Qi(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 Jr(t,e,n,r){if(e.type==="m2m")return Qi(t,e,n,r);for(let{leftCol:s,rightCol:i}of ct(e))t=t.whereRef(s,"=",i);return t}function Gr(t){return t.foreign_key_name?.endsWith("_fkey")||t.foreign_key_name&&!t.foreign_key_name.startsWith("fk_")?t.foreign_key_name:Al(t.table,t.column)}function Mn(t,e,n,r,s,i){if(!n||!e||!i.introspection?.foreign_keys)return {qb:t,remainingWhere:e};if(Object.keys(e).length===0||!ap(e,n))return {qb:t,remainingWhere:e};let o=e;return t=t.where(a=>{let l=ip(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 ip(t,e,n,r,s,i){let o=[],a={};for(let[c,u]of Object.entries(e)){if((c==="$or"||c==="$and")&&Array.isArray(u)){let d=u.map(p=>ip(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]=u;continue}let f=FS(t,c,u,n,r,s,i);f?o.push(f):a[c]=u;}let l=o.length===0?null:o.length===1?o[0]:t.and(o);return {expression:l,remainingWhere:a,fullyHandled:l!==null&&Object.keys(a).length===0}}function FS(t,e,n,r,s,i,o){let a=n;if(!a||typeof a!="object")return null;let l="$is"in a&&a.$is===null,c="$isNot"in a&&a.$isNot===null;if(!l&&!c)return null;let u=op(r,e);if(!u)return null;let f=s?.[e],d=Mt(o.introspection,i,f?.from||e,o.dialect,o.currentSchema);if(d){let w=t.selectFrom(Wr(d,i,d.targetTable)).select(sql`1`.as("_"));if(u.where&&Object.keys(u.where).length>0){let b=Mn(w,u.where,u.select,u.join,d.targetTable,o);if(w=b.qb,Object.keys(b.remainingWhere).length>0){let _=Kr(b.remainingWhere,d.targetTable);w=w.where(E=>Re(E,_,o));}}let S=t.exists(w);return c?S:t.not(S)}let p=Ce(i,e,f,o.introspection),{targetTable:h,fkRel:m}=p;if(!m)return null;let g=t.selectFrom(h).select(sql`1`.as("_"));if(f?.on?g=g.where(w=>Re(w,f.on,o)):g=Jr(g,m,h,i),u.where&&Object.keys(u.where).length>0){let w=Mn(g,u.where,u.select,u.join,h,o);if(g=w.qb,Object.keys(w.remainingWhere).length>0){let S=Kr(w.remainingWhere,h);g=g.where(b=>Re(b,S,o));}}let y=t.exists(g);return c?y:t.not(y)}function op(t,e){for(let n of t){if(typeof n=="string")continue;let r=n[e];if(r&&ie(r))return r}return null}function ap(t,e){for(let[n,r]of Object.entries(t)){if((n==="$or"||n==="$and")&&Array.isArray(r)){if(r.some(a=>ap(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)&&op(e,n))return true}return false}function ie(t){return "select"in t||"spread"in t||"join"in t}function Nl(t){if(typeof t=="string")return null;let[e,n]=Object.entries(t)[0]??[];return !e||n===void 0?null:{alias:e,def:n}}function zr(t){return Nl(t)?.def??null}function US(t,e,n,r){if(t?.hint)return t.hint;if(!n||!r?.foreign_keys)return;let s=t?.from;return s&&s!==e&&r.foreign_keys.some(a=>a.table===n&&a.column===s)?s:r.foreign_keys.some(o=>o.table===n&&o.column===e)?e:void 0}function lp(t){return t.includes(".")?t.slice(t.lastIndexOf(".")+1):t}function eo(t,e,n,r,s,i=false,o,a){let l=o??s,c=n.dialect==="postgres";if(!e||e.length===0)return c&&l&&(Br(l,n.introspection,He(n))||Xi(l,n))?cp(t,l,n,new Set,false,s):t.selectAll();for(let u of e)if(typeof u=="string")if(u==="*")if(c&&l&&(Br(l,n.introspection,He(n))||Xi(l,n))){let f=new Set;for(let d of e){if(d===u)break;if(typeof d=="string"&&d!=="*")f.add(d.includes(".")?d.split(".").pop():d);else if(typeof d!="string")for(let[p]of Object.entries(d))f.add(p);}t=cp(t,l,n,f,i,s);}else t=i&&s?t.selectAll(s):t.selectAll();else if(/^-?\d+(?:\.\d+)?$/.test(u))t=t.select(sql.lit(Number(u)).as("_lit"));else if(YS(u,n,s)){let f=i&&s?xt(s,u,n,s):fe(u,n,s);t=t.select(sql`json(${f})`.as(u));}else if(c&&l&&s&&!u.includes(".")&&!Ki(n.introspection,l,u,n.currentSchema)){let f=Ji(n.introspection,l,u,n.dialect,n.currentSchema);t=f?t.select(Gi(f,s).as(u)):t.select(u);}else if(c&&s&&l&&Dd(l,lp(u),n.introspection,He(n))){let f=lp(u),d=u.includes(".")?sql.ref(u):i?xt(s,u,n,s):sql.ref(u);t=t.select(Mr(d,l,f,n.dialect,n.introspection,He(n)).as(f));}else t=i&&s&&!u.includes(".")?t.select(xt(s,u,n,s).as(u)):!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&Bi(u,n,s)?t.select(fe(u,n,s).as(u)):t.select(u);else for(let[f,d]of Object.entries(u))ie(d)?t=S_(t,f,d,n,r,l,a):t=KS(t,f,d,n,s,i,l);return t}function He(t){return t.currentSchema??t.introspection?.default_schema??"public"}function Xi(t,e){if(!t||e.dialect!=="postgres"||!e.introspection?.columns)return false;let n=He(e);return e.introspection.columns.some(r=>r.table===t&&(r.schema??"public")===n&&Ut(r.name,e,t))}function cp(t,e,n,r,s=false,i=e){if(!n.introspection)return s?t.selectAll(i):t.selectAll();let o=_l(e,n.introspection,He(n));if(o.length===0)return s?t.selectAll(i):t.selectAll();for(let{name:a,isDomain:l,domainTypeName:c}of o){if(r.has(a))continue;let u=s?sql`${sql.ref(i)}.${sql.ref(a)}`:sql.ref(a);if(l&&c){let f=Mi(u,c);t=t.select((f??u).as(a));}else Ut(a,n,e)?t=t.select(sql`to_jsonb(${u})`.as(a)):t=s?t.select(u.as(a)):t.select(a);}return t}function Qr(t,e,n){let r=n?.dialect==="postgres",s=n?.currentTable;if(!e||e.length===0)return r&&s&&(Br(s,n.introspection,He(n))||Xi(s,n))?up(t,s,n):t;for(let i of e)if(typeof i=="string")if(i==="*")if(r&&s&&(Br(s,n.introspection,He(n))||Xi(s,n))){let o=new Set;for(let a of e){if(a===i)break;if(typeof a=="string"&&a!=="*")o.add(a.includes(".")?a.split(".").pop():a);else if(typeof a!="string")for(let[l]of Object.entries(a))o.add(l);}t=up(t,s,n,o);}else t=t.returningAll();else if(r&&s&&Ut(i,n,s))t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i));else if(r&&s){let o=sql.ref(i),a=Mr(o,s,i,n.dialect,n.introspection,He(n));t=a!==o?t.returning(a.as(i)):t.returning(i);}else t=t.returning(i);else for(let[o,a]of Object.entries(i)){if(ie(a))continue;let l=a.column||o;if(r&&s&&!a.cast&&!a.path&&!a.aggregate&&Ut(l,n,s))t=t.returning(sql`to_jsonb(${sql.ref(l)})`.as(o));else if(r&&s&&!a.cast&&!a.path&&!a.aggregate){let c=sql.ref(l),u=Mr(c,s,l,n.dialect,n.introspection,He(n));t=u!==c?t.returning(u.as(o)):t.returning(l);}else t=t.returning(l);}return t}function up(t,e,n,r){if(!n.introspection)return t.returningAll();let s=_l(e,n.introspection,He(n));if(s.length===0)return t.returningAll();for(let{name:i,isDomain:o,domainTypeName:a}of s)if(!r?.has(i))if(o&&a){let l=sql.ref(i),c=Mi(l,a);c?t=t.returning(c.as(i)):t=t.returning(i);}else Ut(i,n,e)?t=t.returning(sql`to_jsonb(${sql.ref(i)})`.as(i)):t=t.returning(i);return t}function Yr(t,e,n,r,s,i=false,o){let a;if(n.aggregate==="count"&&!n.column&&!n.path)a=t.fn.countAll();else {let l=n.column||e;if(n.invalidJsonTextTraversalKey&&r.dialect==="postgres")throw Object.assign(new Error(`operator does not exist: text -> ${BS(n.invalidJsonTextTraversalKey)}`),{code:"42883",detail:null,hint:"No operator matches the given name and argument types. You might need to add explicit type casts."});if(n.path)a=Md(l,n.path,r,s,n.pathText===true);else {let c=s&&i?xt(s,l,r,s):fe(l,r,s);a=r.dialect==="postgres"&&!n.cast&&!n.preCast&&!n.aggregate?Mr(c,o??s??r.currentTable,l,r.dialect,r.introspection,He(r)):c;}n.preCast&&(pn(n.preCast,"pre-cast type"),a=sql`cast(${a} as ${sql.raw(n.preCast)})`),n.aggregate&&(a=sql`${sql.raw(n.aggregate)}(${a})`);}return n.cast&&(pn(n.cast,"cast type"),r.dialect==="sqlite"&&n.pathText===true&&MS(n.cast)||(n.cast.trim().toLowerCase()==="text"&&n.column&&WS(r,s,n.column)?a=Pd(a,r.dialect):a=r.dialect==="sqlite"&&(qS(n.cast)||HS(n.cast))?sql`json(${a})`:sql`cast(${a} as ${sql.raw(n.cast)})`)),a}function MS(t){let e=t.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function BS(t){return /^-?\d+$/.test(t)?"integer":"unknown"}function qS(t){let e=t.trim().toLowerCase();return e==="json"||e==="jsonb"}function HS(t){let e=t.trim().toLowerCase();return e.startsWith("_")||e.endsWith("[]")}function WS(t,e,n){let r=e??t.currentTable;if(!r||!t.introspection?.columns)return false;let s=t.introspection.columns.filter(o=>o.table===r&&o.name===n);if(s.length===0)return false;let i=s.find(o=>o.schema===He(t))??s.find(o=>o.schema==="public")??s[0];return Ue(i.pg_type,i.type)==="color"}function KS(t,e,n,r,s,i=false,o){return t.select(a=>Yr(a,e,n,r,s,i,o).as(e))}function JS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(!ie(n)&&n.aggregate)return true}return false}function GS(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ie(n)&&n.spread&&Il(n.select))return true}return false}function fp(t){if(!t)return false;for(let e of t)if(typeof e!="string"){for(let n of Object.values(e))if(ie(n)&&n.spread)return true}return false}function VS(t){return JS(t)||GS(t)}function Il(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ie(n)){if(Il(n.select))return true;continue}if(n.aggregate)return true}return false}function Dl(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let n of Object.values(e)){if(ie(n)){if(n.spread)continue;if(Dl(n.select))return true;continue}if(n.aggregate&&!n.bareCount)return true}return false}function jl(t,e,n,r,s,i=false,o){if(!VS(e))return t;let a=[];for(let l of e){if(typeof l=="string"){if(l==="*")continue;a.push(fe(l,n,r));continue}for(let[c,u]of Object.entries(l))ie(u)||u.aggregate||a.push(f=>Yr(f,c,u,n,r,i,o));}return zS(a,e,n,r,s),a.length===0?t:t.groupBy(a)}function zS(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(!ie(a)||!a.spread)continue;let l=a,c=s?.[o],u=Ce(r,o,c,n.introspection);if(!u.fkRel||!Tt(u))continue;let f=u.targetTable;u.fkRel;let p=no(l.select,f,n.introspection)??l.select??[],h=`_spread_${o}`;for(let m of p){if(typeof m=="string"){m!=="*"&&t.push(`${h}.${m}`);continue}let[g,y]=Object.entries(m)[0];ie(y)||y.aggregate||t.push(w=>Yr(w,g,y,n,h,true));}}}}function gp(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(!ie(l)||!l.spread)continue;let c=n?.[a],u=Ce(r,a,c,s.introspection);u.fkRel&&Tt(u)&&i.add(a);}return i.size===0?t:t.map(o=>o.embed&&i.has(o.embed)?{...o,embed:`_spread_${o.embed}`}:o)}function yp(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(!ie(o)||!o.spread)continue;let a=e?.[i],l=Ce(n,i,a,r.introspection);if(l.fkRel&&Tt(l))return true}return false}function Bn(t){let e=new Map;for(let n of t){let r=n.foreign_key_group??n.foreign_key_name,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function Vr(t,e,n,r){let s=r==="m2o"?n.map(o=>`${t}.${o.column}`):n.map(o=>`${e}.${o.column}`),i=r==="m2o"?n.map(o=>`${e}.${o.ref_column}`):n.map(o=>`${t}.${o.ref_column}`);return {leftCol:s[0],rightCol:i[0],leftCols:s,rightCols:i,type:r,fk:n[0]}}function Ll(t,e,n,r,s=n){let i=s===n?n:`${n} as ${s}`;return e.type==="m2o"?t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ct(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${f}`,"=",`${r}.${u}`);}return a}):t.leftJoin(i,o=>{let a=o;for(let{leftCol:l,rightCol:c}of ct(e)){let[,u]=l.split("."),[,f]=c.split(".");a=a.onRef(`${s}.${u}`,"=",`${r}.${f}`);}return a})}function to(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;De(o.embed,"order embed alias");let a=s?.[o.embed],l=Ce(n,o.embed,a,r.introspection);if(l.targetTable!==o.embed&&De(l.targetTable,"order embed target"),!l.fkRel||!Tt(l)||l.fkRel.type==="m2m")continue;let{targetTable:c,fkRel:u}=l;t=Ll(t,u,c,n,o.embed),i.add(o.embed),i.add(c);}return {sub:t,joined:i}}function QS(t){return t&&t.map(e=>e.embed&&e.nullsFirst===void 0?{...e,nullsFirst:e.direction==="desc"}:e)}function Zi(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 YS(t,e,n){return e.dialect==="sqlite"&&n!==void 0&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&Zi(e,n,t)}function XS(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 bp(t,e,n,r){return Zi(t,e,n)||XS(r,n)}function ZS(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:Zi(n,e,l)});continue}let[i,o]=Object.entries(s)[0];if(!i||!o)continue;if(ie(o))return null;let a=Zi(n,e,o.column||i);r.push({alias:i,asJson:a});}return r}function e_(t,e,n,r){let s=ZS(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 wp(t){if(!t||t.length===0)return false;for(let e of t){if(typeof e=="string")return true;let n=Nl(e);if(n&&(!ie(n.def)||wp(n.def.select)))return true}return false}function Sp(t,e,n){return n?n.indexes?.some(i=>i.table===t&&i.unique&&i.columns.length===1&&i.columns[0]===e)||n.unique_constraints?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)?true:n.primary_keys?.some(i=>i.table===t&&i.columns.length===1&&i.columns[0]===e)??false:false}function t_(t,e,n,r){if(t.type==="m2m")return "many-to-many";if(t.type==="m2o"&&r&&t.fk)return Sp(e,t.fk.column,r)?"one-to-one":"many-to-one";if(t.type==="o2m"&&r&&t.fk){let s={leftCol:`${n}.${t.fk.column}`,rightCol:`${e}.${t.fk.ref_column}`,type:"o2m"};if(Tp(r,e,n,void 0,s))return "one-to-one"}return "one-to-many"}function n_(t,e,n){if(!t?.views?.length)return [];let r=n??t.tables?.find(s=>s.name===e)?.schema??t.foreign_keys?.find(s=>s.table===e)?.schema;return t.views.filter(s=>s.name!==e&&s.sql&&r_(s.sql)===e&&(!r||s.schema===r)).map(s=>s.name)}function r_(t){let e=t.match(/\bfrom\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[\w$]+))?)/i);if(!e)return;let n=e[1].split(/\s*\.\s*/);return n[n.length-1].replace(/^["`[]|["`\]]$/g,"")}function s_(t,e){let n=new Set(e?.views?.map(s=>s.name)??[]),r=t.filter(s=>s.type==="m2m"&&!n.has(s.junctionTable));for(let s of r){if(s.type!=="m2m")continue;let i=s.parentFkGroup?.[0]?.schema;for(let o of n_(e,s.junctionTable,i))t.push({...s,junctionTable:o});}}function i_(t){if(t.type!=="m2m")return null;let e=t.parentFkGroup?.[0]?.foreign_key_name??"",n=t.targetFkGroup?.[0]?.foreign_key_name??"";return `${t.junctionTable}:${e}:${n}`}function dp(t){return t.type!=="m2m"?0:[...t.parentFkGroup??[],...t.targetFkGroup??[]].filter(n=>n.foreign_key_group).length}function o_(t){let e=[],n=new Map;for(let r of t){let s=i_(r);if(!s){e.push(r);continue}let i=n.get(s);if(i===void 0){n.set(s,e.length),e.push(r);continue}dp(r)<dp(e[i])&&(e[i]=r);}return e}function Ol(t,e){if(t.type==="m2m")return t.junctionTable;if(t.fk)return Gr(t.fk)}function Pl(t,e,n,r){if(t.type==="m2m"&&t.parentFkGroup?.[0]&&t.targetFkGroup?.[0]){let a=t.parentFkGroup[0],l=t.targetFkGroup[0];return `${t.junctionTable} using ${Gr(a)}(${a.column}) and ${Gr(l)}(${l.column})`}if(t.type==="m2m"||!t.fk)return "";let s=Gr(t.fk);if(t.type==="o2m"){let a=Yi(t.rightCols??[t.rightCol]),l=Yi(t.leftCols??[t.leftCol]);return `${s} using ${e}(${a}) and ${n}(${l})`}let i=Yi(t.leftCols??[t.leftCol]),o=Yi(t.rightCols??[t.rightCol]);return `${s} using ${e}(${i}) and ${n}(${o})`}function Yi(t){return t.map(e=>e.split(".").at(-1)??e).join(", ")}function a_(t,e,n){if(!t||!e)return null;let r=t.partitions?.find(o=>o.name===e&&(!n||o.schema===n));if(r)return `Perhaps you meant '${r.parent}' instead of '${e}'.`;let s=[];for(let o of t.tables??[])s.push(o.name);for(let o of t.views??[])s.push(o.name);let i=s.find(o=>o.length===e.length+1&&o.startsWith(e));return i?`Perhaps you meant '${i}' instead of '${e}'.`:null}function Fl(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 $e({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:a_(t,n,s)})}function l_(t,e,n,r,s=false){if(!t||!t.foreign_keys)return null;let i=t.foreign_keys.filter(g=>g.is_visible!==false);if(r){let g=sp(r,e,n,i,{preferSelfReferenceTargetColumn:s});if(g)return g;Fl(t,e,n,r);}if(e===n){let g=Bn(i.filter(y=>y.table===n&&y.ref_table===e))[0];if(g)return Vr(e,n,g,"o2m")}let o=i.filter(g=>g.table===e&&g.ref_table===n),a=Bn(o),l=i.filter(g=>g.table===n&&g.ref_table===e),c=Bn(l),u=[],f=Bn(i.filter(g=>g.ref_table===e));for(let g of f){let y=g[0].table;if(y===e||y===n)continue;let w=i.filter(S=>S.table===y&&S.ref_table===n);if(w.length!==0)for(let S of Bn(w))u.push({type:"m2m",junctionTable:y,junctionToParentCols:g.map(b=>b.column),parentCols:g.map(b=>b.ref_column),junctionToTargetCols:S.map(b=>b.column),targetCols:S.map(b=>b.ref_column),fk:g[0],parentFkGroup:g,targetFkGroup:S});}if(a.length+c.length+u.length===0)return null;let p=[...u];s_(p,t),p=o_(p);let h=e!==n&&a.length>0&&c.length>0;if(a.length>1||c.length>1||a.length===0&&c.length===0&&p.length>1||h||a.length>0&&p.length>1){let g=[...a.map(E=>Vr(e,n,E,"m2o")),...c.map(E=>Vr(e,n,E,"o2m")),...p],y={o2m:0,m2o:1,m2m:2},w=[...g].sort((E,x)=>{let O=y[E.type]??3,v=y[x.type]??3;if(O!==v)return O-v;let $=Ol(E)??"",k=Ol(x)??"",N=$.localeCompare(k);return N!==0?N:Pl(E,e,n).localeCompare(Pl(x,e,n))}),S=w.map(E=>({cardinality:t_(E,e,n,t),embedding:`${e} with ${n}`,relationship:Pl(E,e,n)})),_=w.map(E=>Ol(E)).filter(Boolean).map(E=>`'${n}!${E}'`).join(", ");throw new $e({httpStatus:300,code:"PGRST201",message:`Could not embed because more than one relationship was found for '${e}' and '${n}'`,details:S,hint:_?`Try changing '${n}' to one of the following: ${_}. Find the desired relationship in the 'details' key.`:null})}return a.length===1?Vr(e,n,a[0],"m2o"):c.length===1?Vr(e,n,c[0],"o2m"):u.length===1?u[0]:null}function c_(t,e,n){if(!n?.foreign_keys)return {targetTable:t};let r=n.foreign_keys,s=r.find(l=>l.table===e&&l.column===t);if(s)return {targetTable:s.ref_table,resolvedFkHint:t};let i=r.find(l=>(l.foreign_key_name===t||zi(l,t))&&(l.table===e||l.ref_table===e));if(i)return {targetTable:i.table===e?i.ref_table:i.table,resolvedFkHint:t};let o=r.find(l=>l.ref_table===e&&l.ref_column===t);return o?{targetTable:o.table,resolvedFkHint:t}:n.tables?.some(l=>l.name===t)||n.views?.some(l=>l.name===t)?{targetTable:t}:{targetTable:t}}function u_(t,e,n,r,s){if(!t)return "o2m";if(t.type==="m2m")return "m2m";if(t.type==="m2o"){let i=t.leftCol.split(".")[1];return Sp(e,i,s)?"o2o":"m2o"}return Tp(s,e,n,r,t)?"o2o":"o2m"}function Ce(t,e,n,r){let s=n?.from||e,{targetTable:i,resolvedFkHint:o}=c_(s,t,r),a=US(n,e,t,r)??o,l=t===i&&!!(n?.hint&&n.from&&n.from!==e),c=r?.foreign_keys&&t?l_(r,t,i,a,l):null,u=u_(c,t,i,a,r);return {targetTable:i,fkRel:c,cardinality:u,displayHint:a}}function Tt(t){return t.cardinality==="m2o"||t.cardinality==="o2o"}function _p(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=Ce(n,s.embed,i,r.introspection);if(o.fkRel&&!Tt(o))throw new $e({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 pp(t,e,n,r,s){let i=e.join??r;if(!e.select||!i)return t;for(let o of e.select){if(typeof o=="string")continue;let a=Object.keys(o)[0],l=o[a];if(!ie(l)||!l.select)continue;let c=i[a];if(c?.type!=="inner")continue;let u=Mt(s.introspection,n,c?.from||a,s.dialect,s.currentSchema),f=u?u.targetTable:Ce(n,a,c,s.introspection).targetTable;t=t.where(d=>Ep(d,l,f,n,c,l.join??i,s));}return t}function Ep(t,e,n,r,s,i,o){let a=r?Mt(o.introspection,r,s?.from??n,o.dialect,o.currentSchema):null;if(a){let f=t.selectFrom(Wr(a,r,a.targetTable)).select(sql`1`.as("_"));return e.where&&Object.keys(e.where).length>0&&(f=f.where(d=>Re(d,e.where,{...o,currentTable:a.targetTable}))),r&&(f=pp(f,e,a.targetTable,i,o)),t.exists(f)}let c=(r?Ce(r,s?.from??n,s,o.introspection):null)?.fkRel??null,u=t.selectFrom(n).select(sql`1`.as("_"));if(s?.on)u=u.where(f=>Re(f,s.on,o));else if(c&&c.type==="m2m")u=Qi(u,c,n,r);else if(c)for(let{leftCol:f,rightCol:d}of ct(c))u=u.whereRef(f,"=",d);else r&&(u=u.whereRef(`${n}.${r}_id`,"=",`${r}.id`));return e.where&&Object.keys(e.where).length>0&&(u=u.where(f=>Re(f,e.where,{...o,currentTable:n}))),r&&(u=pp(u,e,n,i,o)),t.exists(u)}function mp(t,e,n,r,s,i){let o=s?.[e],a=i?Mt(r.introspection,i,o?.from||e,r.dialect,r.currentSchema):null,l=a?a.targetTable:i?Ce(i,e,o,r.introspection).targetTable:o?.from||e;return t.where(c=>Ep(c,n,l,i,o,s,r))}function xp(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 Tp(t,e,n,r,s){if(!t?.foreign_keys||!s||s.type!=="o2m")return false;if(xp(s,n,t))return true;let o=t.foreign_keys.filter(f=>f.is_visible!==false).filter(f=>f.table===n&&f.ref_table===e);if(r){let f=o.filter(d=>d.foreign_key_name===r);f.length>0&&(o=f);}let a=Bn(o);if(a.length!==1)return false;let l=[...a[0].map(f=>f.column)].sort(),c=t.primary_keys?.find(f=>f.table===n);if(!c?.columns?.length)return false;let u=[...c.columns].sort();return l.length===u.length&&l.every((f,d)=>f===u[d])}function f_(t,e){return t&&t.map(n=>typeof n!="string"||n==="*"||n.includes(".")||/^-?\d+(?:\.\d+)?$/.test(n)?n:`${e}.${n}`)}function qt(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 d_(t,e,n,r,s,i){if(!n.select||!i)return t;let o=s?.[e],a=Ce(i,e,o,r.introspection),{targetTable:l,fkRel:c}=a,u=no(n.select,l,r.introspection)??n.select;if(!r.introspection?.foreign_keys)return w_(t,u,l,i,c);if(!c)throw new $e({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(!Tt(a)){if(Il(n.select))throw new $e({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 b_(t,u,n,c,l,i,r)}let f=`_spread_${e}`;if(c.type!=="m2o"&&c.type!=="o2m")throw new $e({httpStatus:400,code:"PGRST120",message:"Could not embed because the relationship is not a one-to-one or many-to-one",details:null,hint:null});let d=ct(c).map(({leftCol:m,rightCol:g},y)=>{let[w,S]=m.split("."),[,b]=g.split(".");return {targetSideCol:w===l?S:b,parentSideCol:w===i?S:b,joinKey:`__spread_join_key_${y}`}}),p=[],h=new Set;for(let m of u){if(typeof m=="string"&&m==="*")continue;let g;if(typeof m!="string"){let S=zr(m);if(!S||ie(S))continue;g=S;}let{colAlias:y,colName:w}=qt(m);p.push({src:w,out:y,def:g}),h.add(w);}t=t.leftJoin(m=>{let g=m.selectFrom(l);for(let{targetSideCol:y,joinKey:w}of d)g=g.select(`${l}.${y} as ${w}`);for(let y of h)g=g.select(`${l}.${y} as ${y}`);return g.as(f)},m=>{let g=m;for(let{joinKey:y,parentSideCol:w}of d)g=g.onRef(`${f}.${y}`,"=",`${i}.${w}`);return g});for(let{out:m,def:g}of p)g?t=t.select(y=>Yr(y,m,g,r,f,true).as(m)):t=t.select(`${f}.${m}`);return t}function p_(t,e,n,r){for(let s of t){if(typeof s=="string")continue;let i=zr(s);if(!i||!ie(i))continue;let{colAlias:o}=qt(s),a=e.join?.[o],l=Ce(n,o,a,r.introspection),c=l.targetTable,u=l.fkRel;if(!u||u.type!=="o2m"||!xp(u,c,r.introspection))continue;let f=r.introspection?.primary_keys?.find(d=>d.table===c);if(f?.columns?.length)return {nestedTargetTable:c,fkRel:u,pkColumns:f.columns}}return null}function m_(t,e){let n=e.frames[0],{fkRel:r,fromTable:s,parentTable:i,embed:o}=n,a=t.selectFrom(s);if(a=Jr(a,r,s,i),o.where&&Object.keys(o.where).length>0){let c=e.frames.length>1?e.config:{...e.config,currentTable:s};a=a.where(u=>Re(u,o.where,c));}let l=to(a,o.order,s,e.config,o.join);return a=l.sub,o.order&&(a=Bt(a,QS(o.order),void 0,e.config,s)),o.limit!==void 0&&(a=a.limit(o.limit)),o.offset!==void 0&&(a=a.offset(o.offset)),e.tieBreaker&&e.frames.length===1&&(a=Ll(a,e.tieBreaker.fkRel,e.tieBreaker.nestedTargetTable,s),a=Bt(a,e.tieBreaker.pkColumns.map(c=>({column:c,embed:e.tieBreaker.nestedTargetTable})),void 0,e.config)),{inner:a,joinedToOne:l.joined}}function h_(t,e,n,r){if(e.frames[0].embed.order||!n.fkRel||n.fkRel.type!=="o2m")return t;let s=e.config.introspection?.primary_keys?.find(i=>i.table===n.fromTable);return s?.columns?.length?Bt(t,s.columns.map(i=>({column:i,embed:n.fromTable})),void 0,e.config):t}function g_(t,e,n){if(n&&ie(n)&&!n.spread)return true;let r=t.frames[t.frames.length-1],s=r.embedRel;if(t.frames.length>1&&s&&!Tt(s))return true;let{colName:i}=qt(e);return bp(t.config,r.fromTable,i,t.frames[0].embed.order)}function y_(t,e,n,r){let s=zr(n),{colAlias:i,colName:o}=qt(n),l=e.frames[r].fromTable;if(r===0&&s&&ie(s)&&!s.spread){let c=e.frames[0].embed.join?.[i];return t.select(u=>Rp(u,i,s,e.config,c,l).as("value"))}if(s&&!ie(s)){let c=r>0?{...s,column:`${l}.${o}`}:s,u=r>0?i:o;return t.select(f=>Yr(f,u,c,e.config,r>0?void 0:l).as("value"))}return t.select(`${l}.${o} as value`)}function $l(t,e,n,r,s){if(r===e.frames.length-1)return y_(t,e,n,r);let o=e.frames[r],a=e.frames[r+1];if(!a.fkRel)return t.where(sql`1 = 0`).select(sql`null`.as("value"));let l=a.embedRel;if(!l)return t.where(sql`1 = 0`).select(sql`null`.as("value"));if(Tt(l))return s.has(a.fromTable)||(t=Ll(t,a.fkRel,a.fromTable,o.fromTable),s.add(a.fromTable)),t=h_(t,e,a),$l(t,e,n,r+1,s);let{colName:c}=qt(n);return t.select(u=>{let f=u.selectFrom(a.fromTable);return f=Jr(f,a.fkRel,a.fromTable,o.fromTable),f=$l(f,e,n,r+1,new Set),e.config.jsonScalarArrayFrom(f,"value",bp(e.config,a.fromTable,c,e.frames[0].embed.order)).as("value")})}function hp(t,e,n){let{colAlias:r}=qt(n),s=zr(n);return t.select(i=>{let{inner:o,joinedToOne:a}=m_(i,e),l=e.frames[e.frames.length-1];if(e.frames.length>1&&!l.fkRel){let u=o.where(sql`1 = 0`).select(sql`null`.as("value"));return e.config.jsonScalarArrayFrom(u).as(r)}let c=$l(o,e,n,0,a);return e.config.jsonScalarArrayFrom(c,"value",g_(e,n,s)).as(r)})}function b_(t,e,n,r,s,i,o){let a=n.order?null:p_(e,n,s,o),l={frames:[{embed:n,fkRel:r,fromTable:s,parentTable:i}],config:o,tieBreaker:a};for(let c of e){if(typeof c=="string"&&c==="*")continue;let u=zr(c),f=u!==null&&ie(u)&&u.spread,{colAlias:d}=qt(c);if(f){let p=u,h=n.join?.[d],m=Ce(s,d,h,o.introspection),g=no(p.select,m.targetTable,o.introspection)??p.select??[],y={...l,frames:[...l.frames,{embed:p,fkRel:m.fkRel,fromTable:m.targetTable,parentTable:s,embedRel:m}]};for(let w of g)typeof w=="string"&&w==="*"||(t=hp(t,y,w));continue}t=hp(t,l,c);}return t}function w_(t,e,n,r,s){for(let i of e){if(typeof i=="string"&&i==="*")continue;let{colAlias:o,colName:a}=qt(i);t=t.select(l=>{let c=l.selectFrom(n).select(`${n}.${a}`);if(s&&s.type!=="m2m")for(let{leftCol:u,rightCol:f}of ct(s))c=c.whereRef(u,"=",f);else c=c.whereRef(`${n}.${r}_id`,"=",`${r}.id`);return c=c.limit(1),c.as(o)});}return t}function no(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 S_(t,e,n,r,s,i,o){let a=s?.[e];if(!wp(n.select)){if(a?.type==="inner"&&i)return mp(t,e,n,r,s,i);if(i&&!a?.on&&r.introspection?.foreign_keys&&!Mt(r.introspection,i,a?.from||e,r.dialect,r.currentSchema)){let l=Ce(i,e,a,r.introspection);l.fkRel||Fl(r.introspection,i,l.targetTable,l.displayHint);}return t}return a?.type==="inner"&&i&&(t=mp(t,e,n,r,s,i)),n.spread&&i?d_(t,e,n,r,s,i):t.select(l=>Rp(l,e,n,r,a,i,o).as(e))}function Rp(t,e,n,r,s,i,o){let a=i?Mt(r.introspection,i,s?.from||e,r.dialect,r.currentSchema):null,l=a||!i?{targetTable:a?.targetTable??(s?.from||e),fkRel:null,cardinality:"o2m",displayHint:void 0}:Ce(i,e,s,r.introspection),c=l.targetTable,{displayHint:u,fkRel:f}=l,d=i===c,p=d?o?`${c}_nested`:`${c}_self`:c,h=d?`${c} as ${p}`:c,m=a?t.selectFrom(Wr(a,o??i,p)):t.selectFrom(h),g=i&&!s?.on&&!a?f:null,y=g?.type==="m2m",w=no(n.select,c,r.introspection),S=y?f_(w,p):w;if(m=eo(m,S,r,n.join,p,y||fp(S),d?c:p,d?p:void 0),n.where&&Object.keys(n.where).length>0){let x=Mn(m,n.where,n.select,n.join,c,r);m=x.qb,Object.keys(x.remainingWhere).length>0&&(m=m.where(O=>Re(O,x.remainingWhere,{...r,currentTable:c,currentTableAlias:p})));}let b=l.cardinality==="m2m"?"m2m":l.cardinality==="m2o"?"m2o":"o2m";if(s?.on)m=m.where(x=>Re(x,s.on,r));else if(i&&!a){let x=g;if(x&&x.type==="m2m")b="m2m",m=Qi(m,x,p,i);else if(x?.type==="m2o"){for(let{leftCol:O,rightCol:v}of ct(x)){let[,$]=O.split("."),[,k]=v.split("."),N=o?`${o}.${$}`:`${i}.${$}`;m=m.whereRef(`${p}.${k}`,"=",N);}b="m2o";}else if(x){for(let{leftCol:O,rightCol:v}of ct(x)){let[,$]=O.split("."),[,k]=v.split("."),N=d?`${p}.${$}`:O,H=o?`${o}.${k}`:d?v.replace(`${c}.`,`${i}.`):v;m=m.whereRef(N,"=",H);}b=x.type;}else r.introspection?.foreign_keys?Fl(r.introspection,i,c,u):m=m.whereRef(`${p}.${i}_id`,"=",`${i}.id`);}m=jl(m,S,r,p,void 0,y||fp(S),d?c:p),n.order?.some(x=>x.embed)&&(m=to(m,n.order,c,r,n.join).sub),m=Bt(m,n.order,void 0,r,c),b==="m2m"&&!n.order&&g?.type==="m2m"&&r.dialect==="sqlite"&&(m=m.orderBy(`${g.junctionTable}.${r.rowIdColumn}`,"asc")),n.limit!==void 0&&(m=m.limit(n.limit)),n.offset!==void 0&&(m=m.offset(n.offset)),a?.toOne&&(m=m.limit(1));let _=n.spread?true:a?a.toOne:b==="m2o"||l.cardinality==="o2o";return _&&r.dialect==="sqlite"?e_(m,S,c,r):(_?r.jsonObjectFrom:r.jsonArrayFrom)(m)}function Cp(t,e,n,r){if(!t||!r.introspection?.foreign_keys)return false;for(let s of t){let i=Nl(s);if(!i||!ie(i.def))continue;let{alias:o,def:a}=i;if(!a.spread)continue;let l=e?.[o],c=Ce(n,o,l,r.introspection);if(c.fkRel&&!Tt(c))return true}return false}qn();function Ul(t){return t.startsWith("pg_catalog.")?t.slice(11):t}function R_(t,e,n){let r=n.arg_types.map((s,i)=>`${n.arg_names[i]??""} => ${Ul(s)}`);return `${t}.${e}(${r.join(", ")})`}function C_(t){return [...t].sort((e,n)=>{let r=e.arg_types.length-n.arg_types.length;if(r!==0)return r;let s=e.arg_types.map(Ul).join(","),i=n.arg_types.map(Ul).join(",");return s<i?-1:s>i?1:0})}function Ap(t,e,n){return {message:`Could not choose the best candidate function between: ${C_(n).map(i=>R_(t,e,i)).join(", ")}`,details:null,hint:"Try renaming the parameters or the function itself in the database so function overloading can be resolved"}}function Op(t,e){let n=t??[],{schema:r,fnName:s,method:i,providedNames:o,inputType:a,paramsType:l}=e,c=n.filter(f=>f.schema===r&&f.name===s);if(c.length===0)return null;if(!(l==="positional"&&o.length===0)){let f=Ht(n,{schema:r,fnName:s,providedNames:o});if(f.length>1)return Ap(r,s,c);if(f.length===1)return null}if(i==="POST"&&a!=="text"){let f=c.filter(d=>!d.has_variadic&&d.arg_types.length===1&&d.arg_names.length===0&&(d.arg_types[0]==="json"||d.arg_types[0]==="jsonb"));if(f.length>1)return Ap(r,s,f)}return null}function gn(t){let e=t.args;if(e==null)return [];if(Array.isArray(e)){let n=e[0];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[]}return typeof e=="object"?"_raw"in e?[]:Object.keys(e):[]}function Pp(t){if(!t)return;let e=t.toLowerCase();if(e.includes("application/octet-stream"))return "bytea";if(e.includes("xml"))return "xml";if(e.includes("text/plain"))return "text"}function k_(t,e){let n=new Set(t.arg_names.filter(i=>i!=="")),r=new Set(e);for(let i of e)if(!n.has(i))return false;let s=t.arg_types.length-(t.arg_defaults||0)-(t.has_variadic?1:0);for(let i=0;i<s;i++){let o=t.arg_names[i];if(!o||!r.has(o))return false}return true}function Ht(t,e){let{schema:n,fnName:r,providedNames:s}=e;return t.filter(i=>i.schema===n&&i.name===r&&k_(i,s))}function so(t,e){let n=t??[],r=e.paramsType==="positional"&&e.providedNames.length===0&&e.method==="POST"&&e.inputType!=="text",s;if(r)s=[];else if(e.paramsType==="positional"){let i=e.argCount??0;s=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&o.arg_types.length===i);}else s=Ht(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames});if(s.length===1)return s[0];if(s.length===0&&e.method==="POST"&&e.inputType!=="text"){let i=n.filter(o=>o.schema===e.schema&&o.name===e.fnName&&!o.has_variadic&&o.arg_types.length===1&&o.arg_names.length===0&&(o.arg_types[0]==="json"||o.arg_types[0]==="jsonb"));if(i.length===1)return i[0]}return null}function io(t,e){let n=so(t,e);if(!n)return null;let r=n.has_out_args||n.return_typtype==="c"||n.return_typtype==="p",s=n.return_type.toLowerCase()==="void"&&!n.has_out_args;return {return_is_setof:n.return_is_setof,return_type:n.return_type,returns_object:r,returns_void:s,volatility:n.volatility}}function $p(t,e){let n=so(t?.functions,e);if(!n||n.return_typtype!=="c")return null;let r=n.return_type.replace(/^setof\s+/i,"").trim(),s=(r.includes(".")?r.slice(r.lastIndexOf(".")+1):r).replace(/^"|"$/g,""),i=[...t?.tables??[],...t?.views??[]];return i.find(a=>a.name===s&&a.schema===e.schema)??i.find(a=>a.name===s)?s:null}function A_(t){return [...t].sort().join(", ")}function v_(t){if(t.arg_types.length===0)return null;let e=t.arg_names.filter(n=>n!=="");return e.length!==t.arg_types.length?null:{arity:t.arg_types.length,sig:A_(e)}}function O_(t,e,n,r){let s=r.filter(d=>d.schema===t),i=()=>{let d=[...new Set(s.map(p=>p.name))].filter(p=>p!==e);return Xr(e,d)},o=d=>`Perhaps you meant to call the function ${t}.${d}`,a=d=>`Perhaps you meant to call the function ${t}.${e}(${d})`,l=s.filter(d=>d.name===e).map(v_).filter(d=>d!==null);if(l.length===0){let d=i();return d?o(d):null}if(s.filter(d=>d.name===e).length>1){let d=l.filter(p=>p.arity===n.length);return d.length===1?a(d[0].sig):null}return l[0].sig.split(", ").every(d=>n.includes(d)||Xr(d,n)!==null)?a(l[0].sig):null}function vp(t,e){let{schema:n,fnName:r,method:s,providedNames:i,inputType:o,rawKind:a}=t,l=[...i].sort(),c=s==="POST",u=c&&o==="text",f;u?f=`with a single unnamed ${a??"text"} parameter`:c?f=l.length===0?"without parameters or with a single unnamed json/jsonb parameter":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")} or with a single unnamed json/jsonb parameter`:f=l.length===0?"without parameters":`with ${l.length===1?"parameter":"parameters"} ${l.join(", ")}`;let d=`Searched for the function ${n}.${r} ${f}, but no matches were found in the schema cache.`,p;l.length>0?p=`${n}.${r}(${l.join(", ")})`:u?p=`${n}.${r}`:p=`${n}.${r} without parameters`;let h=`Could not find the function ${p} in the schema cache`,m=O_(n,r,i,e);return {message:h,details:d,hint:m}}function Ml(t,e){let n=t??[],r=n.filter(s=>s.schema===e.schema&&s.name===e.fnName);return r.length===0?vp(e,n):e.paramsType==="positional"&&e.providedNames.length===0||Ht(n,{schema:e.schema,fnName:e.fnName,providedNames:e.providedNames}).length>0||e.method==="POST"&&e.inputType!=="text"&&r.some(i=>!i.has_variadic&&i.arg_types.length===1&&i.arg_names.length===0&&(i.arg_types[0]==="json"||i.arg_types[0]==="jsonb"))||e.inputType==="text"?null:vp(e,n)}function P_(t,e,n){return t.schema?.get(`${e??"public"}.${n}`)}function ql(t,e,n,r,s={}){if(!t)return t;let i=P_(e,n,r),o=a=>{let l=$_(a,i,e,n,r),c=s.applyDefaults&&i?i.applyDefaults(l):l;return i?i.serializeRow(c):N_(c,e,n,r)};return Array.isArray(t)?t.map(a=>o(a)):o(t)}function $_(t,e,n,r,s){let i={};for(let[o,a]of Object.entries(t)){let l=e?.get(o)?.context.pgTypeName??Lp(n,r,s,o)??void 0;i[o]=I_(a,l,n.dialect);}return i}function N_(t,e,n,r){if(e.dialect!=="sqlite")return t;let s={};for(let[i,o]of Object.entries(t)){let a=Lp(e,n,r,i);s[i]=D_(a)?ao(o):o;}return s}function Lp(t,e,n,r){let i=(t.introspection?.columns??[]).filter(l=>l.table===n&&l.name===r);if(i.length===0)return;let o=e??t.introspection?.default_schema??"public",a=i.find(l=>l.schema===o)??i.find(l=>l.schema==="public")??i[0];return Ue(a.pg_type,a.type)}function I_(t,e,n){if(t==null)return t;let r=e?.toLowerCase().trim();if(n!=="sqlite"&&r&&qe(r)){if(r==="color"){if(typeof t=="string"){let i=t.trim();return jn(i.startsWith("#")?i:`#${i}`)}return t}return Id(t,r)}if(typeof t!="string")return t;if(r==="color"){let i=t.trim();return jn(i.startsWith("#")?i:`#${i}`)}if(n!=="sqlite"){let i=Zr(e);return i==="boolean"?Np(t):i==="integer"?oo(t,true):i==="number"?oo(t,false):i==="json"?Bl(t):i==="array"?Ip(t):t}if(r==="color")return jn(t);if(r==="isodate"||r==="isodatetext")return t.replace(/Z$/,"+00:00");if(r==="unixtz"){let i=Date.parse(t);if(Number.isFinite(i))return Math.trunc(i/1e3)}if(r==="monetary"||r==="monetarytext"){let i=Number(t);return Number.isFinite(i)?i.toFixed(2):t}let s=Zr(e);return s==="boolean"?Np(t):s==="integer"?oo(t,true):s==="number"?oo(t,false):s==="json"?Bl(t):s==="array"?Ip(t):t}function Zr(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 Np(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 oo(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 Bl(t){let e=t.trim();if(e==="")return t;try{return JSON.parse(e)}catch{return t}}function Ip(t){let e=Bl(t);return Array.isArray(e)?e:t}function D_(t){let e=Zr(t);return e==="json"||e==="array"}var j_=new Set(["text","character","character varying","bpchar","varchar","name","citext"]);function Dp(t){let e=t.toLowerCase().trim(),n=e.endsWith("[]")?e.slice(0,-2).trim():e;return !j_.has(n)}function ao(t){return t==null||typeof t=="string"?t:JSON.stringify(t)}function Fp(t,e){let n=e.db;switch(t.schema&&(n=n.withSchema(t.schema),e={...e,currentSchema:t.schema}),t.type){case "query":return kl(t,e,n);case "insert":return F_(t,e,n);case "update":return U_(t,e,n);case "delete":return M_(t,e,n);case "upsert":case "put":return B_(t,e,n);case "rpc":return H_(t,e,n);default:throw t&&"type"in t?(console.error(t),new Error(`Unsupported AST type: ${t.type}`)):new Error("Invalid AST")}}function Bt(t,e,n,r,s){if(!e)return t;for(let i of e){let o=i.embed?(De(i.embed,"order embed alias"),i.column.includes("->")?r?Hr(i.column,r,s,i.embed):jp(i.column,i.embed):(De(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?Hr(i.column,r,s,n):jp(i.column,void 0,n):n?r?xt(n,i.column,r,s):sql`${sql.ref(n)}.${sql.ref(i.column)}`:r?fe(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 jp(t,e,n){let{col:r,parts:s}=mn(t);if(s.length===0)return sql.ref(t);e&&De(r,"order embed column");let i=qr(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 es(t,e,n,r,s){return !e||Object.keys(e).length===0?t:t.where(i=>Re(i,e,{...n,currentTable:r,currentSchema:s}))}function kl(t,e,n){let r=n.selectFrom(t.from);return Up(r,t,e,t.from)}function Up(t,e,n,r){t=L_(t,e.join,e.select);let s=e.order?.some(u=>u.embed)===true;t=eo(t,e.select,n,e.join,r,s||yp(e.select,e.join,r,n));let i=e.where??{},{qb:o,remainingWhere:a}=Mn(t,i,e.select,e.join,r,n);t=o,t=es(t,a,n,r,e.schema),t=jl(t,e.select,n,r,e.join),_p(e.order,e.join,r,n),s&&(t=to(t,e.order,r,n,e.join).sub);let l=Cp(e.select,e.join,r,n)?r:void 0,c=gp(e.order,e.select,e.join,r,n);return t=Bt(t,c,l,n,r),e.limit!==void 0&&(t=t.limit(e.limit)),e.offset!==void 0&&(t=t.offset(e.offset)),t}function L_(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=>Mp(l,i.on));}return t}function Mp(t,e){for(let[n,r]of Object.entries(e))if(n==="$and")for(let s of r)t=Mp(t,s);else {let s=r;for(let[i,o]of Object.entries(s)){let a=Hi[i];if(!a)throw new Error(`Unsupported join operator: ${i}`);Fi(o)?t=t.onRef(n,a,o.$ref):t=t.on(n,a,o);}}return t}function F_(t,e,n){let r=n.insertInto(t.from);if(t.values){let i=ql(t.values,e,t.schema,t.from,{applyDefaults:true});r=r.values(i);}let s=t.from?{...e,currentTable:t.from}:e;return r=Qr(r,t.select,s),r}function U_(t,e,n){let r=n.updateTable(t.from);if(t.values){let i=t.values;Array.isArray(i)&&(i=i.length>0?i[0]:i);let o=ql(i,e,t.schema,t.from);r=r.set(o);}t.limit!==void 0||t.offset!==void 0?r=Bp(r,t,e,n):r=es(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Qr(r,t.select,s),r}function M_(t,e,n){let r=n.deleteFrom(t.from);t.limit!==void 0||t.offset!==void 0?r=Bp(r,t,e,n):r=es(r,t.where??{},e,t.from,t.schema);let s=t.from?{...e,currentTable:t.from}:e;return r=Qr(r,t.select,s),r}function Bp(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=es(o,e.where??{},n,e.from,e.schema),o=Bt(o,e.order,void 0,n,e.from),e.limit!==void 0&&(o=o.limit(e.limit)),e.offset!==void 0&&(o=o.offset(e.offset)),i.length===1)return t.where(i[0],"in",o);if(i.length>1){let l="__ltd_target",c=r.selectFrom(o.as(l)).select(sql`1`.as("_"));for(let u of i)c=c.whereRef(`${l}.${u}`,"=",`${e.from}.${u}`);return t.where(u=>u.exists(c))}else return t.where(sql.ref(a),"in",o)}function B_(t,e,n){let r=t.values,s=ql(r,e,t.schema,t.from,{applyDefaults:true}),i=n.insertInto(t.from).values(s);t.onConflict&&(i=i.onConflict(a=>{let l=t.onConflict.length===1?a.column(t.onConflict[0]):a.columns(t.onConflict);if(t.ignoreDuplicates)return l.doNothing();let c=Array.isArray(s)?s[0]:s,u=Object.keys(c).filter(f=>!t.onConflict.includes(f));return u.length===0?l.doUpdateSet({[t.onConflict[0]]:sql.ref(`excluded.${t.onConflict[0]}`)}):l.doUpdateSet(f=>{let d={};for(let p of u)d[p]=f.ref(`excluded.${p}`);return d})}));let o=t.from?{...e,currentTable:t.from}:e;return i=Qr(i,t.select,o),i}function q_(t,e,n){let r=n.introspection?.functions;if(!r)return null;let s=t.schema??n.introspection?.default_schema??"public",i=Array.isArray(t.args)?gn(t):Object.keys(t.args);if(Ht(r,{schema:s,fnName:e,providedNames:i}).length>0)return null;let o=r.filter(a=>a.schema===s&&a.name===e&&!a.has_variadic&&a.arg_types.length===1&&a.arg_names.length===0&&(a.arg_types[0]==="json"||a.arg_types[0]==="jsonb"));return o.length===1?o[0].arg_types[0]:null}function H_(t,e,n){let r=t.function;De(r,"RPC function name");let s=t.schema??e.introspection?.default_schema,i;r.includes(".")?s!==void 0?(De(s,"RPC schema"),i=`"${s}"."${r}"`):i=r:(i=s?`${s}.${r}`:r,De(i,"RPC function reference"));let o,l=e.dialect==="postgres"&&t.httpMethod==="POST"&&t.inputType!=="text"&&t.args!=null?q_(t,r,e):null;if(l)o=sql`${sql.raw(i)}(${ao(t.args)}::${sql.raw(l)})`;else if(t.args&&!Array.isArray(t.args)&&Object.keys(t.args).length>0){let f=Object.entries(t.args),d=null,p=null,h=null;if(e.dialect==="postgres"&&e.introspection?.functions){let y=f.map(([S])=>S),w=Ht(e.introspection.functions,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:y});if(w.length===1){let S=w[0];d=new Map;for(let b=0;b<S.arg_names.length;b++)d.set(S.arg_names[b],S.arg_types[b]);if(S.has_variadic&&S.arg_names.length>0){p=S.arg_names[S.arg_names.length-1];let b=S.arg_types[S.arg_types.length-1];h=b.endsWith("[]")?b.slice(0,-2):b;}}}let m=t.httpMethod==="GET",g=f.map(([y,w])=>{if(De(y,"RPC param key"),d){let b=d.get(y);if(b){if(y===p&&h){pn(h,"RPC variadic elem type"),De(y,"RPC variadic param key");let _=Array.isArray(w)?w:[w];return sql`VARIADIC ${sql.raw(y)} := ${_}::${sql.raw(h+"[]")}`}if(Dp(b)){pn(b,"RPC arg type");let _=m&&Array.isArray(w)?w[w.length-1]:w,E=Zr(b),x=E==="json"||E==="array"&&!Array.isArray(_)?ao(_):_;return sql`${sql.raw(y)} := ${x}::${sql.raw(b)}`}}}let S=m&&Array.isArray(w)?w[w.length-1]:w;return sql`${sql.raw(y)} := ${S}`});o=sql`${sql.raw(i)}(${sql.join(g)})`;}else if(Array.isArray(t.args)&&t.args.length>0){let f=null;if(e.dialect==="postgres"&&e.introspection?.functions){let p=e.introspection.functions,h=t.schema??e.introspection?.default_schema??"public",g=t.args.length,y=p.filter(w=>w.schema===h&&w.name===r&&w.arg_types.length===g);y.length===1&&(f=y[0].arg_types);}let d=t.args.map((p,h)=>{if(f){let m=f[h];if(m&&Dp(m)){pn(m,"RPC positional arg type");let g=Zr(m),y=g==="json"||g==="array"&&!Array.isArray(p)?ao(p):p;return sql`${y}::${sql.raw(m)}`}}return sql`${p}`});o=sql`${sql.raw(i)}(${sql.join(d)})`;}else o=sql`${sql.raw(i)}()`;let c=!!t.join&&Object.keys(t.join).length>0;if(e.dialect==="postgres"&&c){let f=$p(e.introspection,{schema:t.schema??e.introspection?.default_schema??"public",fnName:r,providedNames:gn(t),paramsType:t.paramsType,argCount:Array.isArray(t.args)?t.args.length:void 0,method:t.httpMethod,inputType:t.inputType});if(f)return Up(n.selectFrom(o.as(f)),t,e,f)}let u=n.selectFrom(o.as(r));return u=eo(u,t.select,e),u=es(u,t.where??{},e,t.from,t.schema),u=Bt(u,t.order,void 0,e,t.from),t.limit!==void 0&&(u=u.limit(t.limit)),t.offset!==void 0&&(u=u.offset(t.offset)),u}var Y_=new Kysely({dialect:{createAdapter:()=>new PostgresAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new PostgresIntrospector(t),createQueryCompiler:()=>new PostgresQueryCompiler}}),X_={$ilike:(t,e,n)=>sql`${R(e)} ilike ${n}`,$notIlike:(t,e,n)=>sql`${R(e)} not ilike ${n}`,$regex:(t,e,n)=>sql`${R(e)} ~ ${n}`,$iregex:(t,e,n)=>sql`${R(e)} ~* ${n}`,$contains:(t,e,n)=>sql`${R(e)} @> ${n}`,$containedBy:(t,e,n)=>sql`${R(e)} <@ ${n}`,$overlaps:(t,e,n)=>sql`${R(e)} && ${n}`,$rangeLt:(t,e,n)=>sql`${R(e)} << ${n}`,$rangeGt:(t,e,n)=>sql`${R(e)} >> ${n}`,$rangeGte:(t,e,n)=>sql`${R(e)} &> ${n}`,$rangeLte:(t,e,n)=>sql`${R(e)} &< ${n}`,$rangeAdjacent:(t,e,n)=>sql`${R(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`${R(e)} @@ ${sql.raw(i)}(${sql.literal(s)}, ${r.query})`},$eqAny:(t,e,n)=>sql`${R(e)} = any(${n})`,$neqAny:(t,e,n)=>sql`${R(e)} != any(${n})`,$gtAny:(t,e,n)=>sql`${R(e)} > any(${n})`,$gteAny:(t,e,n)=>sql`${R(e)} >= any(${n})`,$ltAny:(t,e,n)=>sql`${R(e)} < any(${n})`,$lteAny:(t,e,n)=>sql`${R(e)} <= any(${n})`,$likeAny:(t,e,n)=>sql`${R(e)} like any(${n})`,$ilikeAny:(t,e,n)=>sql`${R(e)} ilike any(${n})`,$eqAll:(t,e,n)=>sql`${R(e)} = all(${n})`,$neqAll:(t,e,n)=>sql`${R(e)} != all(${n})`,$gtAll:(t,e,n)=>sql`${R(e)} > all(${n})`,$gteAll:(t,e,n)=>sql`${R(e)} >= all(${n})`,$ltAll:(t,e,n)=>sql`${R(e)} < all(${n})`,$lteAll:(t,e,n)=>sql`${R(e)} <= all(${n})`,$likeAll:(t,e,n)=>sql`${R(e)} like all(${n})`,$ilikeAll:(t,e,n)=>sql`${R(e)} ilike all(${n})`,$regexAny:(t,e,n)=>sql`${R(e)} ~ any(${n})`,$iregexAny:(t,e,n)=>sql`${R(e)} ~* any(${n})`,$regexAll:(t,e,n)=>sql`${R(e)} ~ all(${n})`,$iregexAll:(t,e,n)=>sql`${R(e)} ~* all(${n})`};function Z_(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||Ln(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function eE(t,e="value",n=false){let r=sql.ref(e);return sql`(select coalesce(json_agg(${r}), '[]'::json) from ${t} as _agg)`}var qp={db:Y_,operators:{...qi,...X_},jsonArrayFrom:jsonArrayFrom$1,jsonObjectFrom:jsonObjectFrom$1,jsonScalarArrayFrom:eE,jsonPath:Z_,rowIdColumn:"ctid"};var tE=/[.*+?[\]{}()|]/;function lo(t){let e="";for(let n of t)n==="\\"||n==="*"||n==="?"||n==="["?e+=`[${n}]`:e+=n;return e}function Hp(t){return t==="\\"||t==="*"||t==="?"||t==="["?`[${t}]`:t}function uo(t){let e="";for(let n=0;n<t.length;){let r=t[n];if(r==="\\"){if(n+1>=t.length){e+="[\\\\]",n+=1;continue}e+=Hp(t[n+1]),n+=2;continue}if(r==="%"){e+="*",n+=1;continue}if(r==="_"){e+="?",n+=1;continue}e+=Hp(r),n+=1;}return e}function co(t){return t?tE.test(t)?/^[A-Za-z0-9_\-\\%]+$/.test(t):true:false}function Wp(t){if(t.startsWith("^")&&t.endsWith("$")&&t.length>=2){let e=t.slice(1,-1);return co(e)?{mode:"exact",text:lo(e)}:null}if(t.startsWith("^")){let e=t.slice(1);return co(e)?{mode:"prefix",text:lo(e)}:null}if(t.endsWith("$")){let e=t.slice(0,-1);return co(e)?{mode:"suffix",text:lo(e)}:null}return co(t)?{mode:"contains",text:lo(t)}:null}function Kp(t,e){switch(t){case "exact":return e;case "prefix":return `${e}*`;case "suffix":return `*${e}`;case "contains":return `*${e}*`}}function Jp(t,e){switch(t){case "exact":return e;case "prefix":return `${e}%`;case "suffix":return `%${e}`;case "contains":return `%${e}%`}}var cE=new Kysely({dialect:{createAdapter:()=>new SqliteAdapter,createDriver:()=>new DummyDriver,createIntrospector:t=>new SqliteIntrospector(t),createQueryCompiler:()=>new SqliteQueryCompiler}});function uE(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||Ln(s,"JSON path key"),a?`${o}${s}`:`${o}'${s}'`}).join("");return sql`${sql.ref(t)}${sql.raw(r)}`}function fE(t,e){let n=R(t);if(e.length===0)return sql`(${n} is not null)`;let r=sql.join(e.map(s=>sql`${s}`));return sql`(${n} is not null and (select count(distinct value) from json_each(${n}) where value in (${r})) = ${sql.lit(e.length)})`}function dE(t,e){let n=R(t),r=Object.keys(e);if(r.length===0)return sql`${n} is not null`;let s=r.map(i=>(Ln(i,"JSON object key"),sql`json_extract(${n}, ${sql.raw(`'$.${i}'`)}) = ${e[i]}`));return sql`(${n} is not null and ${sql.join(s,sql` and `)})`}var pE=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","to","was","with"]);function mE(t){let e=t.toLowerCase().replace(/'/g,"''");return e.endsWith("s")&&!e.endsWith("ss")&&e.length>3&&(e=e.slice(0,-1)),e.length===7?e.slice(0,4):e.length>6?e.slice(0,6):e}function Gp(t,e,n){let r=mE(e);if(!r)return sql`1 = 1`;let i=n!=null&&n!=="english"&&n!=="simple"&&r.length>=5?`%'${r}%':%`:`%'${r}':%`;return sql`lower(${t}) like ${i}`}function hE(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch{return t}}function Hl(t,e){let n=R(t),r=hE(e.query).trim();if(!r)return sql`1 = 1`;if(e.type==="websearch"){let o=r.split(/\s+or\s+/i).map(l=>l.trim()).filter(Boolean);if(o.length>1){let l=o.map(c=>Hl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` or `)})`}let a=r.split(/\s+and\s+/i).map(l=>l.trim()).filter(Boolean);if(a.length>1){let l=a.map(c=>Hl(t,{...e,query:c,type:"plain",config:e.config}));return sql`(${sql.join(l,sql` and `)})`}}if(r.includes("|")&&e.type!=="phrase"&&e.type!=="plain"){let o=r.split("|").map(a=>a.trim()).filter(Boolean);return o.length===0?sql`1 = 1`:sql`(${sql.join(o.map(a=>Gp(n,a,e.config)),sql` or `)})`}let s=r.split(/\s+/).map(o=>o.trim()).filter(Boolean);if((e.type==="phrase"||e.type==="plain")&&(s=s.filter(o=>!pE.has(o.toLowerCase()))),s.length===0)return sql`1 = 1`;let i=sql` and `;return sql`(${sql.join(s.map(o=>Gp(n,o,e.config)),i)})`}function Wl(t,e){return sql`${R(t)} GLOB ${e}`}function gE(t,e){let n=R(t);return sql`json(${n}) = json(${JSON.stringify(e)})`}function yE(t,e){let n=R(t);return Array.isArray(e)||e!==null&&typeof e=="object"?sql`json(${n}) is distinct from json(${JSON.stringify(e)})`:sql`${n} is distinct from ${e}`}function Vp(t,e,n){if(typeof e!="string")throw new Error(`$${n?"iregex":"regex"} on sqlite requires a string value`);let r=Wp(e);if(!r)throw new Error(`Unsupported operator: $${n?"iregex":"regex"}`);if(n){let i=Jp(r.mode,r.text),o=R(t);return sql`lower(${o}) like lower(${i}) escape '\\'`}let s=Kp(r.mode,r.text);return Wl(t,s)}function fo(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=R(t),i=e.map(o=>n==="ilike"?sql`lower(${s}) like lower(${o})`:Wl(t,typeof o=="string"?uo(o):o));return sql`(${sql.join(i,r==="any"?sql` or `:sql` and `)})`}var bE={$eq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?gE(e,n):sql`${R(e)} = ${n}`,$neq:(t,e,n)=>Array.isArray(n)||n!==null&&typeof n=="object"?sql`json(${R(e)}) != json(${JSON.stringify(n)})`:sql`${R(e)} != ${n}`,$textSearch:(t,e,n)=>Hl(e,n),$like:(t,e,n)=>{if(typeof n!="string")throw new Error("$like on sqlite requires a string value");return Wl(e,uo(n))},$notLike:(t,e,n)=>{if(typeof n!="string")throw new Error("$notLike on sqlite requires a string value");return sql`${R(e)} NOT GLOB ${uo(n)}`},$regex:(t,e,n)=>Vp(e,n,false),$iregex:(t,e,n)=>Vp(e,n,true),$ilike:(t,e,n)=>sql`lower(${R(e)}) like lower(${n})`,$notIlike:(t,e,n)=>sql`lower(${R(e)}) not like lower(${n})`,$likeAny:(t,e,n)=>fo(e,n,"like","any"),$ilikeAny:(t,e,n)=>fo(e,n,"ilike","any"),$likeAll:(t,e,n)=>fo(e,n,"like","all"),$ilikeAll:(t,e,n)=>fo(e,n,"ilike","all"),$isDistinct:(t,e,n)=>yE(e,n),$contains:(t,e,n)=>{if(Array.isArray(n))return fE(e,n);if(n!==null&&typeof n=="object")return dE(e,n);throw new Error("$contains on sqlite requires an array or object value")},$containedBy:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$containedBy on sqlite requires an array value");let r=R(e),s=n.length===0?sql`${r} is not null and not exists (select 1 from json_each(${r}))`:sql`${r} is not null and not exists (select 1 from json_each(${r}) where value not in (${sql.join(n.map(i=>sql`${i}`))}))`;return sql`(case when ${r} is null then null else (${s}) end)`},$overlaps:(t,e,n)=>{if(!Array.isArray(n))throw new Error("$overlaps on sqlite requires an array value");let r=R(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 wE(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 zp={db:cE,operators:{...qi,...bE},jsonArrayFrom:jsonArrayFrom,jsonObjectFrom:jsonObjectFrom,jsonScalarArrayFrom:wE,jsonPath:uE,rowIdColumn:"rowid"};function SE(t){switch(t){case "postgres":return qp;case "sqlite":return zp;default:throw new Error(`Unsupported dialect: ${t}`)}}function ee(t,e="postgres",n){let r=SE(e),s=n&&"introspection"in n?n:{db:n,introspection:void 0};return Fp(t,{...r,dialect:e,db:s.db??r.db,introspection:s.introspection,schema:s.schema})}var vc=Aa(Jl());rs();function T(t,e,n,r,s){let i=JSON.stringify({code:e,details:r,hint:s,message:n}),o=new TextEncoder().encode(i);return new Response(o,{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(o.byteLength)}})}function ut(t){return T(t.status,t.code,t.message,t.details??null,t.hint??null)}async function go(t,e){if(!t||!t.startsWith("Bearer "))return e.anonymousEnabled?{kind:"ok",payload:null}:{kind:"error",response:ut({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:ut({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:ut({status:500,code:"PGRST300",message:"Server lacks JWT secret"})};try{let s=new TextEncoder().encode(e.jwtSecret),{payload:i}=await jwtVerify(n,s,{algorithms:["HS256"]});return typeof i.iat=="number"&&i.iat>Math.floor(Date.now()/1e3)?{kind:"error",response:ut({status:401,code:"PGRST303",message:"JWT issued at future"})}:{kind:"ok",payload:i}}catch(s){return s instanceof errors.JWTExpired?{kind:"error",response:ut({status:401,code:"PGRST303",message:"JWT expired"})}:{kind:"error",response:ut({status:401,code:"PGRST301",message:"No suitable key or wrong key type",details:"None of the keys was able to decode the JWT"})}}}bc();function ox(t,e,n,r){if(n){let i=t.get(`${n}.${e}`);if(i)return i}let s=t.get(`${r}.${e}`);if(s)return s;for(let[i,o]of t)if(i.endsWith(`.${e}`))return o}function ax(t,e){let n=t.schema||"public",r=wl(t,e);return {schema:n,table:t.table,column:t.name,pgTypeName:r,nullable:t.nullable,defaultValue:t.default_value??null,isPrimaryKey:t.is_primary_key,isUnique:false,isSerial:!!t.is_identity,isGenerated:t.is_generated}}function bm(t,e){let n=ax(t,e);return qe(n.pgTypeName)?jd(n)??we(n):we(n)}function lx(t,e="sqlite"){let n=new Map;for(let r of t.columns){let s=r.schema||"public",i=`${s}.${r.table}`,o=n.get(i);o||(o=new Qe(r.table,s),n.set(i,o)),o.set(r.name,bm(r,t));}return n}function cx(t,e){for(let n of e.columns){if(!qe(wl(n,e)))continue;let r=n.schema||"public",s=`${r}.${n.table}`,i=t.get(s);i||(i=new Qe(n.table,r),t.set(s,i)),i.set(n.name,bm(n,e));}return t}function wm(t,e,n){if(n==="sqlite")return lx(e,n);if(n==="postgres"||n==="pglite"){let r=t&&t.size>0?t:new Map;return cx(new Map(r),e)}return t&&t.size>0?t:new Map}function Sm(t,e){let n=t.config?.translation?.schemas;return e.schema??n?.defaultSchema??"public"}function _m(t,e,n,r){return !n||!e?.from?t:t.map(s=>wc(s,e.select,e.from,e.schema,e.join,n,r))}function wc(t,e,n,r,s,i,o){let a=ox(i,n,r,o),l=fx(e,s),c={};for(let[u,f]of Object.entries(t)){let d=l.get(u);if(d&&"embed"in d){let m=d.embed;c[u]=ux(f,m,r,i,o);continue}let p=d?.sourceColumn??u,h=a?.get(p);c[u]=h?.isShimBacked?h.deserialize(f):f;}return c}function ux(t,e,n,r,s){return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?wc(i,e.select,e.table,n,e.join,r,s):i):t&&typeof t=="object"?wc(t,e.select,e.table,n,e.join,r,s):t}function fx(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(dx(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 dx(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 So=class extends Error{constructor(n){super("Force rollback");this.result=n;}},Kn=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;}},Sc=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")}async runInTransaction(e){return this.kysely.transaction().execute(n=>e(n))}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){if(r?.transaction){if(r.forceRollback)throw new Error("Cannot force rollback an existing transaction");return n(r.transaction)}if(r?.forceRollback!==true)return n(this.kysely);try{return await this.runInTransaction(async s=>{let i=await n(s);throw new So(i)})}catch(s){if(s instanceof So)return s.result;throw s}}get supportsRpc(){return false}async viewOptionsMetadata(e,n){return null}};function Rt(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?Number.parseInt(n.toString(),10):n)}var Em=/application\/vnd\.pgrst\.plan(?:\+(json|text))?/i;function xm(t){let e=t.match(Em);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 Tm(t){return Em.test(t)}function Rm(t){return /;\s*nulls\s*=\s*stripped/i.test(t)}function bn(t){if(Array.isArray(t))return t.map(e=>bn(e));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))r!==null&&(e[n]=bn(r));return e}return t}function _o(t,e){if(!e||e.length===0)return t;let n=(r,s)=>{for(let i of e){if(i.embed)continue;let o=r[i.column],a=s[i.column],l=o==null,c=a==null;if(l&&c)continue;if(l)return i.nullsFirst?-1:1;if(c)return i.nullsFirst?1:-1;let u;if(typeof o=="number"&&typeof a=="number"?u=o-a:u=String(o).localeCompare(String(a)),u!==0)return i.direction==="desc"?-u:u}return 0};return [...t].sort(n)}function mx(t,e){return !e||e.length===0?t:t.map(n=>Rc(n,e))}function Cm(t,e,n){if(!e||e.length===0||t.length===0)return t;let r=mx(t,e);return r=gx(r,e),r=yx(r,e),r=bx(r,e),n==="sqlite"&&(r=wx(r,e),r=hx(r,e)),r}function hx(t,e){if(!e||e.length===0)return t;let n=Sx(e);return n.size===0?t:t.map(r=>{if(!Gn(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 gx(t,e){return !e||e.length===0?t:t.map(n=>Ec(n,e))}function yx(t,e){return !e||e.length===0?t:t.map(n=>xc(n,e))}function bx(t,e){return !e||e.length===0?t:t.map(n=>Tc(n,e))}function wx(t,e){return !e||e.length===0?t:t.map(n=>_c(n,e))}function Sx(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&&!km(i.cast)&&e.add(r);}return e}function km(t){let e=t?.trim().toLowerCase();return e==="json"||e==="jsonb"}function _x(t){let e=t?.trim().toLowerCase();return e==="integer"||e==="int"||e==="int2"||e==="int4"||e==="int8"||e==="bigint"||e==="smallint"}function _c(t,e){if(Array.isArray(t))return t.map(r=>_c(r,e));if(!Gn(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(ys(i)){s in n&&i.select&&(n[s]=_c(n[s],i.select));continue}let o=i;if(!o.path||o.pathText!==true||!_x(o.cast)||!(s in n))continue;let a=n[s];if(a==null)continue;let l=String(a);if(!/^-?\d+$/.test(l))throw new Nn(l);n[s]=Number.parseInt(l,10);}return n}function Rc(t,e){if(Array.isArray(t))return t.map(r=>Rc(r,e));if(!Gn(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||!ys(i)||s in n&&(n[s]=xx(n[s],i.select));}return n}function Ec(t,e){if(Array.isArray(t))return t.map(r=>Ec(r,e));if(!Gn(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(ys(i)){s in n&&i.select&&(n[s]=Ec(n[s],i.select));continue}let o=i;o.aggregate==="avg"&&o.cast!=="text"&&s in n&&(n[s]=Ex(n[s]));}return n}function xc(t,e){if(Array.isArray(t))return t.map(r=>xc(r,e));if(!Gn(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(ys(i)){s in n&&i.select&&(n[s]=xc(n[s],i.select));continue}km(i.cast)&&s in n&&(n[s]=Am(n[s]));}return n}function Tc(t,e){if(Array.isArray(t))return t.map(r=>Tc(r,e));if(!Gn(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(ys(i)){s in n&&i.select&&(n[s]=Tc(n[s],i.select));continue}let o=i;o.path&&!o.pathText&&s in n&&(n[s]=Am(n[s]));}return n}function Ex(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 xx(t,e){let n=Tx(t);return !e||e.length===0?n:Rc(n,e)}function Tx(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 Am(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}function Gn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ys(t){return t!==null&&typeof t=="object"&&("select"in t||"spread"in t||"join"in t)}var Rx=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 vm(t){let e=xm(t);return e?`application/vnd.pgrst.plan+${e.format}; for="application/json"${e.optionsSegment}`:t}function Om(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(Rx.has(r)||e&&r.startsWith("application/vnd.pgrst.plan"))return true;return false}function Pm(t,e){let n=xm(t)??{format:"text",optionsSegment:""},r=`application/vnd.pgrst.plan+${n.format}; for="application/json"${n.optionsSegment}; charset=utf-8`,s=n.format==="json"?Rt({sql:e.sql,parameters:[...e.parameters]}):e.sql;return new Response(s,{status:200,headers:{"Content-Type":r}})}function ft(t,e,n){let r=t+e-1,s=n!==void 0?`${n}`:"*";return `${t}-${r}/${s}`}function $m(t,e){let n=e.startsWith("?")?e.slice(1):e;if(!n)return;let s=[...new URLSearchParams(n).entries()].sort(([o],[a])=>o.localeCompare(a)),i=new URLSearchParams(s).toString();return i?`${t}?${i}`:t}async function Jn(t,e,n,r){if(e.type==="rpc"){let u={...e,order:void 0,limit:void 0,offset:void 0},f=ee(u,n,{db:t,introspection:r}),{sql:d,parameters:p}=f.compile(),h=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,m=await t.executeQuery({sql:h,parameters:p,query:{kind:"RawNode"}});return Number(m.rows?.[0]?.__count??0)}let s=e.join&&Object.values(e.join).some(u=>u.type==="inner"),i=Cx(e);if(s||i){let u={...e,type:"query",order:void 0,limit:void 0,offset:void 0},f=ee(u,n,{db:t,introspection:r}),{sql:d,parameters:p}=f.compile(),h=`SELECT count(*) as __count FROM (${d}) AS __inner_count`,g=(await t.executeQuery({sql:h,parameters:p,query:{kind:"RawNode"}})).rows?.[0];return Number(g?.__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 ee(o,n,{db:t,introspection:r}).execute(),c=Array.isArray(l)?l[0]:l;return Number(c?.__count??0)}async function Cc(t,e,n,r){if(e.$meta?.count!=="planned"&&e.$meta?.count!=="estimated"||n!=="postgres"||e.type==="rpc")return Jn(t,e,n,r);let s={...e,type:"query",order:void 0,limit:void 0,offset:void 0},o=ee(s,n,{db:t,introspection:r}).compile(),c=(await t.executeQuery({sql:`EXPLAIN (FORMAT JSON) ${o.sql}`,parameters:o.parameters,query:{kind:"RawNode"}})).rows?.[0]?.["QUERY PLAN"],u=Array.isArray(c)&&c[0]&&typeof c[0]=="object"?c[0].Plan:void 0,f=u&&typeof u=="object"?Number(u["Plan Rows"]):Number.NaN;return Number.isFinite(f)?f:Jn(t,e,n,r)}function Cx(t){if(t.type!=="query"||!t.where||!t.select)return false;let e=kx(t.select);return e.size===0?false:Nm(t.where,e)}function Nm(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"&&Nm(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 kx(t){let e=new Set;for(let n of t){if(typeof n=="string")continue;let[r,s]=Object.entries(n)[0]??[];r&&s&&typeof s=="object"&&"select"in s&&e.add(r);}return e}function kc(t){return t?.count==="exact"||t?.count==="planned"||t?.count==="estimated"}function Kt(t,e,n){return kc(e)?`*/${n??0}`:t.type==="update"&&n!==0?ft(0,n??1,void 0):"*/*"}function Im(t,e,n,r){return e&&(t.type==="insert"||t.type==="upsert"||t.type==="delete")?r!==void 0?`*/${r}`:"*/*":ft(n,1,r)}var Ax=/[",\n\r ]/;function Dm(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),Ax.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Eo(t,e){let n=t.length>0?Object.keys(t[0]):[];if(n.length===0)return "";let r=[n.map(s=>Dm(s)).join(",")];for(let s of t)r.push(n.map(i=>Dm(s[i])).join(","));return r.join(`
81
+ `)}function jm(t){return t.split(",").map(n=>n.split(";")[0].trim().toLowerCase()).includes("text/csv")}function Um(t){return t==null?[]:Array.isArray(t)?t.map(e=>bs(e)?new Set(Object.keys(e)):new Set):bs(t)?[new Set(Object.keys(t))]:[]}function Mm(t,e,n){return !e?.length||!n?.length||t.length===0?t:t.map((r,s)=>{let i=n[s]??n[0],o={...r};for(let a of e)i.has(a)||(o[a]=null);return o})}function Bm(t,e){if(t.type!=="upsert"&&t.type!=="put")return {ast:t};if(t.type==="put"){if(t.limit!==void 0||t.offset!==void 0)return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);let r=Lm(t,e),s=vx(t.where,r);if(!s)return T(405,"PGRST105","Filters must include all and only primary key columns with 'eq' operators",null,null);if(Array.isArray(t.values)&&t.values.length===0)return {ast:t,emptyPayload:true};if(!bs(t.values))return T(400,"PGRST102","Empty or invalid json",null,null);for(let i of r)if(!Px(t.values[i],s[i]))return T(400,"PGRST115","Payload values do not match URL in primary key column(s)",null,null);return t.onConflict=r,t.ignoreDuplicates=false,{ast:t,preflight:{mode:"put",conflictColumns:r}}}let n=t.onConflict?.length?t.onConflict:Lm(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 qm(t,e){let n=t.$meta,r={"Content-Type":"application/json; charset=utf-8"},s=ws(n,e.appliedResolution),i=n?.count==="exact"||n?.count==="planned"||n?.count==="estimated"?"*/0":"*/*",o=t.type==="upsert"?200:rt(t,n?.return==="representation"?"representation":"no-return",e.appliedResolution,false);return n?.return==="representation"?(r["Content-Range"]=i,r["Content-Length"]="2",s&&(r["Preference-Applied"]=s),new Response("[]",{status:o,headers:r})):(r["Content-Range"]=i,s&&(r["Preference-Applied"]=s),new Response(null,{status:o,headers:r}))}function Lm(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 vx(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=Ox(t[s]);if(!i.ok)return null;r[s]=i.value;}return r}function Ox(t){if(!bs(t))return {ok:false};let e=Object.keys(t);return e.length!==1||e[0]!=="$eq"?{ok:false}:{ok:true,value:t.$eq}}function Px(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):Rt(t)===Rt(e)}function ws(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 rt(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 Hm(t,e,n,r,s){if(e.type==="insert")return true;if(!s.preflight||!e.from)return;if(s.preflight.mode==="put")return !await Fm(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(!bs(o))continue;let a=$x(s.preflight.conflictColumns,o);if(!a||!await Fm(t,e.from,e.schema,a,n,r))return true}return false}function $x(t,e){let n={};for(let r of t){if(!(r in e))return;n[r]={$eq:e[r]};}return n}async function Fm(t,e,n,r,s,i){return await Jn(t,{type:"query",from:e,schema:n,where:r},s,i)>0}function bs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Nx(t){return "select"in t||"spread"in t||"join"in t}function Wm(t,e){if(t){for(let n of t)if(typeof n!="string")for(let r of Object.values(n))Nx(r)&&((r.limit===void 0||r.limit>e)&&(r.limit=e),Wm(r.select,e));}}var Ix={count:new Set(["exact","planned","estimated"]),resolution:new Set(["merge-duplicates","ignore-duplicates"]),return:new Set(["minimal","headers-only","representation"]),tx:new Set(["commit","rollback"]),missing:new Set(["default","null"]),handling:new Set(["strict","lenient"]),"max-affected":"number",timezone:"string",params:new Set(["single-object","multiple-objects"])};function Dx(t,e){if(!t)return [];let n=t.split(",").map(i=>i.trim()).filter(Boolean);if(n.find(i=>i.startsWith("handling="))!=="handling=strict")return [];let s=e?new Set(e):void 0;return n.filter(i=>!jx(i,s))}function jx(t,e){let n=t.indexOf("=");if(n===-1)return false;let r=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(r==="timezone")return e?e.has(s):s.length>0;let i=Ix[r];return i?i==="string"?s.length>0:i==="number"?/^-?\d+$/.test(s):i.has(s):false}function Lx(t){if(!t.from||!t.order)return null;let e=t.order.find(n=>/^\s+/.test(n.column));return e?T(400,"42703",`column ${t.from}.${e.column.trim()} does not exist`,null,null):null}function Km(t){let e=t.ast,{dialect:n,introspection:r,apiConfig:s,acceptHeader:i,preferHeader:o,httpMethod:a,rangeHeader:l}=t,c=s??{};if(c?.aggregates_enabled!==true&&Dl(e.select))return T(400,"PGRST123","Use of aggregate functions is not allowed",null,null);let u=c?.plan_enabled===true;if(!t.allowRawMedia&&!Om(i,u))return T(406,"PGRST107",`None of these media types are available: ${vm(i)}`,null,null);let f=Rm(i),d=jm(i),p=Dx(o,r.timezones);if(p.length>0)return T(400,"PGRST122","Invalid preferences given with handling=strict",`Invalid preferences: ${p.join(", ")}`,null);let h=Lx(e);if(h)return h;if(n==="sqlite"&&e.from){let b=e.schema??"",_=r.tables.some(x=>x.name===e.from&&(x.schema??"")===b),E=r.views.some(x=>x.name===e.from&&(x.schema??"")===b);if(!_&&!E)throw new Kn(e.schema,e.from)}let m=e.$meta,g=e.type==="update"||e.type==="delete"||e.type==="insert"||e.type==="upsert"||e.type==="put",y={ast:e};if(g&&m?.return!=="representation"&&(e.select=void 0),(e.type==="put"||e.type==="upsert")&&(e.limit!==void 0||e.offset!==void 0))return T(400,"PGRST114","limit/offset querystring parameters are not allowed for PUT",null,null);if((e.type==="update"||e.type==="delete"||e.type==="insert")&&c?.limited_mutations_enabled!==true&&(e.limit=void 0,e.offset=void 0),c?.pg_safe_update&&g){let b=e.where&&Object.keys(e.where).length>0;if(e.type==="update"&&!b)return T(400,"21000","UPDATE requires a WHERE clause",null,null);if(e.type==="delete"&&!b)return T(400,"21000","DELETE requires a WHERE clause",null,null)}if(g&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){if((e.type==="update"||e.type==="insert"||e.type==="upsert"||e.type==="put")&&(e.values===void 0||e.values===null))return T(400,"PGRST102","Empty or invalid json",null,null);if(e.type==="update"&&e.values&&typeof e.values=="object"&&!Array.isArray(e.values)&&Object.keys(e.values).length===0){let b=m?.return==="representation"?200:204,_=ws(m,y.appliedResolution),E={"Content-Type":"application/json; charset=utf-8","Content-Range":Kt(e,m,0)};if(_&&(E["Preference-Applied"]=_),m?.return==="representation"){let x=new TextEncoder().encode("[]");return E["Content-Length"]=String(x.byteLength),new Response(x,{status:b,headers:E})}return new Response(null,{status:b,headers:E})}if(e.type==="put"&&Array.isArray(e.values)&&(e.values.length===0?y.emptyPayload=true:e.values=e.values[0]),Array.isArray(e.values)){if(m?.cardinality==="one"&&(e.type==="insert"||e.type==="upsert")&&e.values.length>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${e.values.length} rows`,null);if(e.values.length>0&&e.values.some(b=>typeof b!="object"||b===null||Array.isArray(b)))return m?.columns?T(400,"22023","argument of jsonb_to_recordset must be an array of objects",null,null):T(400,"PGRST102","All object keys must match",null,null);if(!m?.columns&&e.values.length>1){let b=Object.keys(e.values[0]).sort().join(",");for(let _=1;_<e.values.length;_++)if(Object.keys(e.values[_]).sort().join(",")!==b)return T(400,"PGRST102","All object keys must match",null,null)}}if(m?.columns&&e.from){y.bodyKeySets=Um(e.values);let b=r.columns.filter(E=>E.table===e.from).map(E=>E.name);for(let E of m.columns){if(E==="")return T(400,"PGRST100",'"failed to parse columns parameter ()" (line 1, column 1)',"unexpected end of input",null);if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}let _=new Set(m.columns);if(e.values)if(Array.isArray(e.values))e.values=e.values.map(E=>{let x={};for(let O of _)O in E&&(x[O]=E[O]);return x});else {let E={};for(let x of _)x in e.values&&(E[x]=e.values[x]);e.values=E;}}if(!m?.columns&&e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=r.columns.filter(_=>_.table===e.from).map(_=>_.name);if(b.length>0){let _=Array.isArray(e.values)?e.values.length>0?Object.keys(e.values[0]):[]:Object.keys(e.values);for(let E of _)if(!b.includes(E))return T(400,"PGRST204",`Could not find the '${E}' column of '${e.from}' in the schema cache`,null,null)}}if(e.values&&e.from&&(e.type==="insert"||e.type==="update"||e.type==="upsert"||e.type==="put")){let b=e.schema??"public",_=new Set(r.columns.filter(E=>E.table===e.from&&(E.schema||"public")===b&&E.is_generated===true).map(E=>E.name));if(_.size>0){let E=Array.isArray(e.values)?e.values:[e.values];for(let x of E)if(!(!x||typeof x!="object")){for(let O of Object.keys(x))if(_.has(O))return T(400,"428C9",`cannot insert a non-DEFAULT value into column "${O}"`,`Column "${O}" is a generated column.`,null)}}}}let w=Bm(e,r);if(w instanceof Response)return w;let S=y.bodyKeySets;if(y=w,y.bodyKeySets=S,e=y.ast,g&&((e.type==="insert"||e.type==="upsert")&&Array.isArray(e.values)&&e.values.length===0||y.emptyPayload))return m?.cardinality==="one"?T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null):qm(e,y);if(l&&(a==="GET"||a==="HEAD")){let b=l.match(/^(\d+)-(\d*)$/);if(b){let _=parseInt(b[1],10);if(b[2]!==""){let E=parseInt(b[2],10);if(_>E)return T(416,"PGRST103","Requested range not satisfiable","The lower boundary must be lower than or equal to the upper boundary in the Range header.",null);e.offset=_,e.limit=E-_+1;}else e.offset=_;}}if(e.limit!==void 0&&e.limit<0||e.limit===0&&e.offset!==void 0&&e.offset>0)return T(416,"PGRST103","Requested range not satisfiable","Limit should be greater than or equal to zero.",null);if(e.offset!==void 0&&e.offset<0&&(e.offset=0),!g){let b=c?.max_rows;b!==void 0&&b>0&&((e.limit===void 0||e.limit>b)&&(e.limit=b),Wm(e.select,b));}return {ast:e,meta:m,mutationPlan:y,isMutation:g,stripNullsResponse:f,csvResponse:d,planEnabled:u}}var Jt=class extends Error{constructor(n){super(`new row violates row-level security policy for table "${n.data.table}"`);this.policy=n;this.name="PolicyViolation";}};Ui();ts();qn();function Jm(t){if(t.from)return t.from}function zm(t,e){let{connection:n,introspection:r,vars:s,ast:i}=e;if(t instanceof ge){let a=`"${t.message}" (line 1, column ${t.position})`;return T(400,"PGRST100",a,t.details,null)}if(t instanceof ze)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof Nn)return T(400,t.code,t.message,null,null);if(t instanceof Ft)return T(400,"PGRST100",t.message,t.details,null);if(t instanceof $n)return T(404,"PGRST125",t.message,t.details,null);if(t instanceof $e)return T(t.httpStatus,t.code,t.message,t.details,t.hint);if(t instanceof In)return T(400,"PGRST102",t.message,null,null);if(t instanceof Ir)return T(400,"PGRST102",t.message,null,null);if(t instanceof Error&&t.message.startsWith("Invalid JSON body"))return T(400,"PGRST102","Empty or invalid json",null,null);if(t instanceof Et)return T(400,"PGRST100",t.message,t.message,null);if(t instanceof fn)return T(400,"23514",t.message,`check constraint "${t.constraint}" violated`,null);if(t instanceof Jt){let l=Wt(s,"auth.role","anon")==="anon"?401:403;return ut({status:l,code:"PGRST301",message:t.message})}let o=n.normalizeDbError(t);if(console.error(o),o instanceof Kn){let a=o.schema||"public",l=[...r.tables.filter(d=>(d.schema||"public")===a).map(d=>d.name),...r.views.filter(d=>(d.schema||"public")===a).map(d=>d.name)],c=l.length>0?l:[...r.tables.map(d=>d.name),...r.views.map(d=>d.name)],u=Xr(o.relation,c),f=u?`Perhaps you meant the table '${a}.${u}'`:null;return ut({status:404,code:"PGRST205",message:o.message,hint:f})}if(typeof o?.code=="string"){if(o.code==="PGRST")return Ux(o);let a=/^PT(\d{3})$/.exec(o.code);if(a){let l=Number(a[1]);return T(l>=200&&l<=599?l:500,o.code,o.message,o.detail??null,o.hint??null)}if(o.code.startsWith("PT"))return T(500,o.code,o.message,o.detail??null,o.hint??null)}if(o?.code==="42501"){let l=Wt(s,"auth.role","anon")==="anon"?401:403;return T(l,"42501",o.message,o.detail??null,o.hint??null)}if(o?.code==="42P01")return T(404,"PGRST205","Could not find the relation in the schema cache",o.message,null);if(o?.code==="23505"||o?.code==="23503")return T(409,o.code,o.message,o.detail??null,null);if(o?.code==="25006")return T(405,"25006",o.message,o.detail??null,o.hint??null);if(typeof o?.code=="string"){let a=o.code.slice(0,2);if(o.code==="42883"){let l=o.message;return l=l.replace(/^operator does not exist: [\w.]+\.([\w]+) /,"operator does not exist: $1 "),T(404,o.code,l,o.detail??null,o.hint??null)}if(o.code==="42P17")return T(500,o.code,o.message,o.detail??null,o.hint??null);if(a==="42"||a==="22"||a==="21"||o.code==="23502"){let l=o.message,c=i?Jm(i):void 0;if(o.code==="42703"&&c){let u=i?.onConflict;l=l.replace(/^column "([^"]+)" does not exist$/,(f,d)=>u?.includes(d)?f:`column ${c}.${d} does not exist`);}return T(400,o.code,l,o.detail??null,o.hint??null)}if(a==="55"||a==="53")return T(500,o.code,o.message,o.detail??null,o.hint??null)}return o?.message?.includes("Unknown operator")?T(400,"PGRST100",o.message,null,null):o instanceof Error&&(o.message.includes("Expected identifier")||o.message.includes("Invalid filter")||o.message.includes("Unexpected input")||o.message.includes("Unsupported operator")||o.message.includes("failed to parse filter")||o.message.includes("failed to parse logic tree")||/^Expected .* at position \d+$/.test(o.message)||o.message.startsWith('Expected "(" for spread embed'))?T(400,"PGRST100",o.message,o.message,null):T(500,"SUP",String(o),null,null)}var Ac=`Could not parse JSON in the "RAISE SQLSTATE 'PGRST'" error`,Fx="MESSAGE must be a JSON object with obligatory keys: 'code', 'message' and optional keys: 'details', 'hint'.",Gm="DETAIL must be a JSON object with obligatory keys: 'status', 'headers' and optional key: 'status_text'.";function Vm(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Ux(t){let e=typeof t.message=="string"?t.message:"",n=Vm(e);if(!n||typeof n.code!="string"||typeof n.message!="string")return T(500,"PGRST121",Ac,`Invalid JSON value for MESSAGE: '${e}'`,Fx);let r=t.detail;if(r==null||r==="")return T(500,"PGRST121",Ac,"DETAIL is missing in the RAISE statement",Gm);let s=Vm(r),i=s?.headers,o=!!i&&typeof i=="object"&&!Array.isArray(i);if(!s||typeof s.status!="number"||!o)return T(500,"PGRST121",Ac,`Invalid JSON value for DETAIL: '${r}'`,Gm);let a=JSON.stringify({code:n.code,details:n.details??null,hint:n.hint??null,message:n.message}),l=new TextEncoder().encode(a),c={"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)};for(let[f,d]of Object.entries(i))typeof d=="string"&&(c[f]=d);let u={status:s.status,headers:c};typeof s.status_text=="string"&&(u.statusText=s.status_text);try{return new Response(l,u)}catch{return new Response(l,{status:500,headers:{"Content-Type":"application/json; charset=utf-8","Content-Length":String(l.byteLength)}})}}var Bx="response.status guc must be a valid status code",Vn="response.headers guc must be a JSON array composed of objects with a single key and a string value";async function Qm(t,e){let n=(await sql`
82
82
  SELECT current_setting('response.status', true) AS status,
83
83
  current_setting('response.headers', true) AS headers
84
- `.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let f=Number(r);if(!Number.isInteger(f)||f<200||f>599)return T(500,"PGRST112",cx,null,null);i=f;}let o;if(s&&s.length>0){let f;try{f=JSON.parse(s);}catch{return T(500,"PGRST111",Kn,null,null)}if(!Array.isArray(f))return T(500,"PGRST111",Kn,null,null);let u=[];for(let d of f){if(!d||typeof d!="object"||Array.isArray(d))return T(500,"PGRST111",Kn,null,null);let p=Object.keys(d);if(p.length!==1)return T(500,"PGRST111",Kn,null,null);let g=d[p[0]];if(typeof g!="string")return T(500,"PGRST111",Kn,null,null);u.push([p[0],g]);}o=u;}if(i===void 0&&!o)return e;let a=i??e.status,l=new Headers(e.headers);if(o)try{for(let[f,u]of o)l.set(f,u);}catch{return T(500,"PGRST111",Kn,null,null)}let c;return ux.has(a)?(c=null,l.delete("Content-Length"),l.delete("Content-Type")):c=e.body?await e.arrayBuffer():null,new Response(c,{status:a,statusText:e.statusText,headers:l})}var ux=new Set([101,204,205,304]);var fx=/^[\w.+*-]+\/[\w.+*-]+$/,dx=new Set(["text/plain","text/xml","text/csv","application/json","application/geo+json","application/openapi+json"]);function px(t){return t.replace(/^"([\s\S]*)"$/,"$1")}function mx(t){let e=t.match(/^(?:"(?:[^"]|"")*"|[^."]+)\.([\s\S]+)$/);return e?e[1]:t}function hx(t){if(t.return_typtype!=="d"||t.return_is_setof)return null;let e=px(mx(t.return_type));return fx.test(e)?e:null}function vm(t){if(!t)return [];let e=[];for(let n of t.split(",")){let r=n.split(";"),s=r[0].trim().toLowerCase();if(!s)continue;let i=1;for(let o of r.slice(1)){let a=o.trim().match(/^q=(.+)$/i);if(a){let l=Number.parseFloat(a[1]);Number.isFinite(l)&&(i=l);}}e.push({media:s,q:i});}return e}function Am(t){return dx.has(t)?`${t}; charset=utf-8`:t}function gx(t,e){let n=e.indexOf("/"),r=n>0?e.slice(0,n):e,s=-1,i=0;for(let o of t){let a=o.media===e?2:o.media===`${r}/*`?1:o.media==="*/*"?0:-1;a<0||(a>s?(s=a,i=o.q):a===s&&(i=Math.max(i,o.q)));}return s<0?0:i}function yx(t,e){let n=hx(t);if(!n)return null;if(n==="*/*"){let r=vm(e);return r.some(s=>s.media==="*/*"&&s.q<=0)?null:!e||r.some(s=>s.q>0)?{mediaType:"application/octet-stream",isBinary:true}:null}return gx(vm(e),n)>0?{mediaType:n,isBinary:(t.return_base_type??"").toLowerCase()==="bytea"}:null}function ao(t,e,n){let r=Ji(t,e);return r?yx(r,n):null}function Om(t,e){if(t instanceof Uint8Array){let s=new Uint8Array(t.byteLength);return s.set(t),s}if(e&&typeof t=="string"&&t.startsWith("\\x")){let s=t.slice(2),i=new Uint8Array(Math.floor(s.length/2));for(let o=0;o<i.length;o++)i[o]=parseInt(s.substr(o*2,2),16);return i}let n=new TextEncoder().encode(t==null?"":String(t)),r=new Uint8Array(n.byteLength);return r.set(n),r}var Pm=ca(Cl());function Te(t,e,n){if(!n)return;let{sql:r,parameters:s}=e.compile();console.info(Pm.default.dim(`[POSTGREST:SQL:${t}] ${r}
85
- - ${JSON.stringify([...s])}`));}async function $m(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},f=te(c,s,{db:r,introspection:i,schema:o});Te("",f,t.debug);let u=await f.execute(),d=Array.isArray(u)&&u.length>0&&u[0]&&typeof u[0]=="object"&&("numUpdatedRows"in u[0]||"numInsertedOrUpdatedRows"in u[0]||"numDeletedRows"in u[0])?u[0]:void 0,p=d===void 0?void 0:Number(d.numUpdatedRows??d.numInsertedOrUpdatedRows??d.numDeletedRows??0),g=et(e,"no-return",a.appliedResolution,l),m={"Content-Range":Ht(e,n,p)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:g,headers:m})}async function Im(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let u=i.primary_keys.find(w=>w.table===e.from)?.columns??[],d={...e,select:u.length>0?u:void 0},p=te(d,s,{db:r,introspection:i,schema:o});Te("",p,t.debug);let g=await p.execute(),m=Array.isArray(g)?g.length:0,h=et(e,"no-return",a.appliedResolution,l),y={"Content-Range":Ht(e,n,m)};if(c&&(y["Preference-Applied"]=c),u.length>0&&Array.isArray(g)&&g.length>0){let w=g[0],S=u.map(b=>`${b}=eq.${w[b]}`).join("&");y.Location=`/${e.from}?${S}`;}return new Response(null,{status:h,headers:y})}function Jn({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=Xp(i,e,r,Yp(n,e)),i=rm(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=ym(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function lo(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?pn(e):e,f=r?oo(Array.isArray(c)?c:[c]):Et(c),u=new TextEncoder().encode(f),d={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(u.byteLength)};return o&&(d["Preference-Applied"]=o),a&&(d.Location=a),new Response(u,{status:i,headers:d})}async function Nm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let f={...e,select:void 0},u=te(f,s,{db:r,introspection:i,schema:o});if(Te("LTD",u,t.debug),await u.execute(),n?.return==="representation"){let S={...e,type:"query",values:void 0,limit:void 0,offset:void 0},b=te(S,s,{db:r,introspection:i,schema:o});Te("LTD-SEL",b,t.debug);let _=await b.execute(),E=Array.isArray(_)?_:[],x=Jn({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=x.length,v=[];n.return==="representation"&&v.push("return=representation"),n.count&&v.push(`count=${n.count}`),n.tx&&v.push(`tx=${n.tx}`);let P=e.type==="delete"?"*/*":O>0?lt(0,O,void 0):"*/*";return lo({rows:x,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:P,preferenceApplied:v.length>0?v.join(", "):void 0})}let d={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},g=await te(d,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(g)?g[0]:g)?.__count??0),y={"Content-Range":m>0?lt(0,m,void 0):"*/*"},w=[];return n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`),w.length>0&&(y["Preference-Applied"]=w.join(", ")),new Response(null,{status:204,headers:y})}function bx(t){return "select"in t||"spread"in t||"join"in t}function Dm(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(bx(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function jm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f}=t;if(!(t.isMutation&&n?.return==="representation"&&Dm(e.select)))return null;let p=i.primary_keys.find(_=>_.table===e.from)?.columns??[],g=[];if(e.type==="delete"){let _={...e,type:"query",values:void 0},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-PRE",E,t.debug),g=await E.execute();let x={...e,select:void 0},O=te(x,s,{db:r,introspection:i,schema:o});Te("EMB-DEL",O,t.debug),await O.execute();}else {if(p.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let _={...e,select:p},E=te(_,s,{db:r,introspection:i,schema:o});Te("EMB-MUT",E,t.debug);let x=await E.execute(),O=Array.isArray(x)?x:[];if(O.length>0){let v;if(p.length===1){let U=p[0];v={[U]:{$in:O.map(J=>J[U])}};}else v={$or:O.map(U=>{let J={};for(let F of p)J[F]={$eq:U[F]};return J})};let P=e.where?{$and:[e.where,v]}:v,C={...e,type:"query",values:void 0,where:P},R=te(C,s,{db:r,introspection:i,schema:o});Te("EMB-SEL",R,t.debug),g=await R.execute();}}let m=Jn({rows:g,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=io(m,e.order));let h=et(e,"representation",c.appliedResolution,f),y=m.length,w=["return=representation"];n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`);let S=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":y>0?lt(0,y,void 0):"*/*",b;if((e.type==="insert"||e.type==="upsert")&&p.length>0&&m.length>0){let _=m[0],E=p.map(x=>`${x}=eq.${_[x]}`).join("&");b=`/${e.from}?${E}`;}return lo({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:S,status:h,preferenceApplied:w.join(", "),location:b})}function wx(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function Lm(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function Sx(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function Fm(t){if(!t.isMutation)return null;let e=wx(t.meta);if(e===null)return null;let n=Sx(t.ast);if(n!==null)return n>e?Lm(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=te(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});Te("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?Lm(o):null}function mn(t){return t||"public"}function _x(t,e,n){let r=mn(e);return n.views.some(s=>s.name===t&&mn(s.schema)===r)}function Ex(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function xx(t,e,n){let r=mn(e);for(let s of n.triggers){if(s.table!==t||mn(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=Ex(s.sql);if(i)return i}}async function Um(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!_x(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=mn(e.schema),l=n.primary_keys.find(h=>h.table===e.from&&mn(h.schema)===a)?.columns??[];if(l.length===0){let h=xx(e.from,e.schema,n);h&&(l=n.primary_keys.find(y=>y.table===h&&mn(y.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],f=t.map(h=>h[c]).filter(h=>h!=null);if(f.length===0)return t;let u={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:f}}},p=await te(u,r,{db:s,introspection:n,schema:i}).execute(),g=h=>String(h[c]),m=new Map(p.map(h=>[g(h),h]));return t.map(h=>m.get(g(h))??h)}async function Mm(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:f,prefApplied:u,isMutation:d,stripNullsResponse:p,csvResponse:g,requestUrl:m,acceptHeader:h}=t,y=te(e,s,{db:r,introspection:i,schema:o});Te("",y,t.debug);let w=await y.execute(),S,b=false,_=0;if(d&&Array.isArray(w)&&w.length>0&&w[0]&&typeof w[0]=="object"&&("numUpdatedRows"in w[0]||"numInsertedOrUpdatedRows"in w[0]||"numDeletedRows"in w[0])){b=true;let G=w[0];_=Number(G.numUpdatedRows??G.numInsertedOrUpdatedRows??G.numDeletedRows??0),S=[];}else S=w;d&&Array.isArray(S)&&S.length>0&&(S=await Um(S,e,i,s,r,o));let E=false,x,O=false,v=false,P=false,C=null;if(e.type==="rpc"&&Array.isArray(S)){let G={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:fn(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};C=ao(i.functions,G,h);let pe=Gi(i.functions,G);if(pe){let Me=e.function??"",ht=S;E=!pe.returns_object&&ht.length>0&&ht.every(Xs=>{let gr=Object.keys(Xs);return gr.length===1&&gr[0]===Me}),E&&(x=Me,S=ht.map(Xs=>Xs[Me])),O=!pe.return_is_setof,P=pe.volatility!=="v",v=pe.returns_void;}}if(v){let G={"Content-Range":"0-0/*"};return u&&(G["Preference-Applied"]=u),new Response(null,{status:204,headers:G})}if(C&&Array.isArray(S)&&S.length===1){let G=S[0];if(!E&&G&&typeof G=="object"&&!Array.isArray(G)&&!(G instanceof Uint8Array)){let ht=Object.keys(G);ht.length===1&&(G=G[ht[0]]);}let pe=Om(G,C.isBinary),Me={"Content-Type":Am(C.mediaType),"Content-Range":"0-0/*","Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),n?.head?new Response(null,{status:200,headers:Me}):new Response(pe,{status:200,headers:Me})}let R=Array.isArray(S);R&&!E&&(S=Jn({rows:S,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),d&&R&&e.order&&e.order.length>0&&(S=io(S,e.order));let U=R?S:[],J=U.length,F=e.offset??0;if(d&&b){if(n?.cardinality==="one"){if(_===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(_>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${_} rows`,null)}let G=et(e,"no-return",c.appliedResolution,f),pe={"Content-Type":"application/json; charset=utf-8","Content-Range":Ht(e,n,_)};return u&&(pe["Preference-Applied"]=u),new Response(null,{status:G,headers:pe})}let V;if(ac(n)&&(d?V=J:e.type==="rpc"?F===0&&J<(e.limit??Number.POSITIVE_INFINITY)?V=J:P&&(V=await oc(r,e,s,i)):V=await oc(r,e,s,i)),n?.cardinality==="one"||O){if(J===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(J>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${J} rows`,null);let G=200;d&&(G=et(e,"representation",c.appliedResolution,f));let pe=p?pn(U[0]):U[0],Me=Et(pe),ht=new TextEncoder().encode(Me),gr=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",aa={"Content-Type":p?`${gr};nulls=stripped; charset=utf-8`:`${gr}; charset=utf-8`,"Content-Range":fm(e,d,F,V),"Content-Length":String(ht.byteLength)};return u&&(aa["Preference-Applied"]=u),n?.head?new Response(null,{status:G,headers:aa}):new Response(ht,{status:G,headers:aa})}if(V!==void 0&&F>0&&J===0&&F>=V){let G=JSON.stringify({code:"PGRST103",details:`An offset of ${F} was requested, but there are only ${V} rows.`,hint:null,message:"Requested range not satisfiable"}),pe=new TextEncoder().encode(G),Me={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${V}`,"Content-Length":String(pe.byteLength)};return u&&(Me["Preference-Applied"]=u),new Response(pe,{status:416,headers:Me})}let be;d&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?be=V!==void 0?`*/${V}`:"*/*":d&&n?.return!=="representation"?be=V!==void 0?`*/${V}`:"*/*":J>0?be=lt(F,J,V):be=V!==void 0?`*/${V}`:"*/*";let he=200;d?he=et(e,"representation",c.appliedResolution,f):V!==void 0&&(F+J<V||F>0)&&(he=206);let Ve=p?pn(S):S,Tn=Array.isArray(Ve)?Ve:[Ve];if(g&&E&&x!==void 0){let G=x;Tn=Tn.map(pe=>({[G]:pe}));}let Ys=g?oo(Tn):Et(Ve),oa=new TextEncoder().encode(Ys),Ot={"Content-Type":g?"text/csv; charset=utf-8":p?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":be,"Content-Length":String(oa.byteLength)};if(!d&&e.from&&m){let G=cm(`/${e.from}`,new URL(m).search);G&&(Ot["Content-Location"]=G);}return u&&(Ot["Preference-Applied"]=u),n?.head?new Response(null,{status:he,headers:Ot}):new Response(oa,{status:he,headers:Ot})}function Bm(t){return t==="snake_case"?"__":"."}function qm(t,e){let n=new Set;for(let r of t.tables)r.schema&&n.add(r.schema);for(let r of t.views)r.schema&&n.add(r.schema);if(e?.deparseSchema)for(let r of e.deparseSchema.values())r?.schema&&n.add(r.schema);for(let r of e?.internalSchemas??[])n.add(r);return n}function Hm(t){let e=new Set(t.exposedSchemas??["public"]),n=()=>[...e].sort().join(", ");if(t.explicitProfileSchema!==void 0&&!e.has(t.explicitProfileSchema))return T(406,"PGRST106",`Invalid schema: ${t.explicitProfileSchema}`,null,`Only the following schemas are exposed: ${n()}`);let r=t.isRpc?-1:t.relation.indexOf(t.separator);if(r>0){let s=t.relation.slice(0,r);if(t.knownSchemas.has(s)&&!e.has(s)){let i=t.relation.slice(r+t.separator.length);return T(404,"PGRST205",`Could not find the table '${s}.${i}' in the schema cache`,null,null)}}return null}var Tx={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"]},Wm=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let h=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(h))return T(405,"PGRST101",`Cannot use the ${h} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(h=>Ki(o,h,"sql")))return n.notFound();if(!(kn in n.req.raw)){let h=i.config.translation,y=Bm(h?.schemas?.approach),w=[];s.config.auth?.enabled&&w.push("auth"),s.config.storage?.enabled&&w.push("storage");let S=n.req.method.toUpperCase(),b=n.req.header("Content-Profile"),_=n.req.header("Accept-Profile"),E=S==="OPTIONS"?b??_:["POST","PUT","PATCH","DELETE"].includes(S)?b:_,x=Hm({relation:o,explicitProfileSchema:E,exposedSchemas:s.config.api?.schemas,knownSchemas:qm(l,{deparseSchema:h?.deparse?.schema,internalSchemas:w}),separator:y,isRpc:a});if(x)return x}if(!(kn in n.req.raw)&&n.req.method!=="OPTIONS"){let h=n.var.ignoreAuthorization?void 0:n.req.header("Authorization");if(h||!n.var.apiKeyType){let y=await Hp(h,{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(y.kind==="error")return y.response;y.payload&&(n.set("userId",y.payload.sub),n.set("sessionId",y.payload.session_id),n.set("jwt",y.payload));}}if(a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",y=wl(l.functions,{schema:h,fnName:o,method:"OPTIONS",providedNames:[]});if(y)return T(404,"PGRST202",y.message,y.details,y.hint);let w=Bt(l.functions??[],{schema:h,fnName:o,providedNames:[]}),S=w.length>0&&w.every(b=>b.volatility!=="v");return n.header("Allow",S?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=b=>{let _=b||"public";return i.dialect==="sqlite"?_===h||_==="public"||_==="":_===h},w=l.views.find(b=>b.name===o&&y(b.schema)),S=!w&&l.tables.find(b=>b.name===o&&b.type!=="view"&&y(b.schema));if(S||w){let b=new Set(["OPTIONS","GET","HEAD"]);if(S)b.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,x=false,O=false,v=(F,V)=>`${F||"public"}\0${V}`,P=new Set,C=w.schema||"public",R=await i.viewOptionsMetadata(o,C).catch(()=>null);if(R){E=R.canInsert,x=R.canUpdate,O=R.canDelete;for(let F of R.baseTables)P.add(v(F.schema,F.name));}else {let F=l.triggers.filter(he=>he.table===o&&y(he.schema)),V=he=>F.some(Ve=>new RegExp(`instead\\s+of\\s+${he}`,"i").test(Ve.sql));E=V("insert"),x=V("update"),O=V("delete");let be=w?.sql??"";for(let he of l.tables){if(he.type==="view")continue;let Ve=he.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Ve}\\b`,"i").test(be)&&P.add(v(he.schema,he.name));}}let U=new Set(l.columns.filter(F=>F.table===o&&y(F.schema)).map(F=>F.name)),J=l.tables.some(F=>{if(F.type==="view"||!P.has(v(F.schema,F.name)))return false;let V=l.columns.filter(be=>be.table===F.name&&(be.schema||"public")===(F.schema||"public")&&be.is_primary_key);return V.length>0&&V.every(be=>U.has(be.name))});E&&b.add("POST"),x&&b.add("PATCH"),O&&b.add("DELETE"),E&&x&&J&&b.add("PUT");}let _=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>b.has(E));return n.header("Allow",_.join(",")),n.body(null,200)}}let{dialect:f}=i,u=i.config.translation?.deparse?.schema,d=Qp(u,l,f),p=n.var.jwt,g={auth:{uid:n.var.userId??null,role:p?.role||"anon",jwt:p??null}},m;try{let h=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=new Set(l.columns.filter(C=>{if(C.table!==o)return !1;let R=C.schema||"public";return f==="sqlite"?R===h||R==="public"||R==="":R===h}).map(C=>C.name));m=await Ri(n.req.raw,{basePath:"/rest/v1",parentColumns:y,resolveFilters:(C,R,U)=>Ir(C,R,U,y)}),m=await i.onPostgrestAST(m,g);let w=m.function,S=!1;if(a&&w){let C={schema:m.schema??l.default_schema??"public",fnName:w,method:n.req.method.toUpperCase(),providedNames:fn(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:ap(n.req.header("Content-Type"))},R=wl(l.functions,C);if(R)return T(404,"PGRST202",R.message,R.details,R.hint);let U=op(l.functions,C);if(U)return T(300,"PGRST203",U.message,U.details,U.hint);if(C.method==="OPTIONS"){let J=Gi(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType}),F=J&&J.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:F,"Access-Control-Allow-Origin":"*"}})}S=ao(l.functions,{schema:C.schema,fnName:C.fnName,providedNames:C.providedNames,paramsType:C.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:C.method,inputType:C.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(cc.default.dim("[POSTGREST:AST]"),m);let b=Em({ast:m,dialect:f,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:S,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(b instanceof Response)return b;m=b.ast;let{meta:_,mutationPlan:E,isMutation:x,stripNullsResponse:O,csvResponse:v,planEnabled:P}=b;return await i.withContext(g,async C=>{let R=n.req.header("Accept")??"application/json";if(P&&tm(R)){let Ot=te(m,f,{db:C,introspection:l,schema:u}).compile();return t?.debug&&console.info(cc.default.dim(`[POSTGREST:PLAN] ${Ot.sql}
86
- - ${JSON.stringify([...Ot.parameters])}`)),lm(R,Ot)}let U=x?await Sm(C,m,f,l,E):void 0,J=ps(_,E.appliedResolution),F={ast:m,meta:_,db:C,dialect:f,introspection:l,deparseSchema:u,connection:i,responseSchemaMap:d,mutationPlan:E,mutationCreated:U,prefApplied:J,isMutation:x,stripNullsResponse:O,csvResponse:v,acceptHeader:R,requestUrl:n.req.url,debug:t?.debug},V=await Fm(F);if(V)return V;let be=await $m(F);if(be)return be;let he=await Im(F);if(he)return he;let Ve=await Nm(F);if(Ve)return Ve;let Tn=await jm(F);if(Tn)return Tn;let Ys=await Mm(F);return a&&f==="postgres"?await km(C,Ys):Ys},{forceRollback:t?.forceRollback===!0,rpc:a&&f==="postgres"?{method:n.req.method.toUpperCase(),path:`/rpc/${o}`,readOnly:["GET","HEAD"].includes(n.req.method.toUpperCase()),requestHeaders:Object.fromEntries(n.req.raw.headers)}:void 0})}catch(h){return Cm(h,{connection:i,introspection:l,vars:g,ast:m})}};return new _e().all("/rpc/:function",n=>e(n,{relation:n.req.param("function"),isRpc:true})).all("/:relation",n=>e(n,{relation:n.req.param("relation"),isRpc:false})).use(async(n,r)=>{if(n.req.method==="GET"&&n.req.path.endsWith("/")){if(n.var.apiKeyType==="publishable")return n.json({message:"You cannot consume this service"},403);let{app:s}=n.var,i=n.req.header("Accept-Profile")??n.req.header("Content-Profile")??null;if(i){let o=new Set(s.config.api?.schemas??["public"]);if(o.size>0&&!o.has(i)){let a=[...o].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${i}`,null,`Only the following schemas are exposed: ${a}`)}}return n.json(Tx)}await r();}).all("*",n=>T(404,"PGRST125","Invalid path specified in request URL",null,null))};var $=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";}withInternalError(n){return this.cause=n,this}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},ct=()=>new $(400,"invalid_credentials","Invalid login credentials"),Km=()=>new $(400,"email_not_confirmed","Email not confirmed"),Jm=(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 $(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},Gm=(t="Access token is required")=>new $(401,"no_authorization",t),hn=()=>new $(401,"no_authorization","This endpoint requires a valid Bearer token"),ms=t=>new $(403,"bad_jwt",t),uc=()=>ms("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),fc=t=>ms(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),zm=()=>ms("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),Vm=()=>ms("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),dc=()=>ms("invalid claim: missing sub claim"),pc=()=>new $(400,"bad_jwt","invalid claim: sub claim must be a UUID");var Qm=()=>new $(403,"user_not_found","User from sub claim in JWT does not exist"),Ym=()=>new $(403,"session_not_found","Session from session_id claim in JWT does not exist"),Xm=()=>new $(422,"user_already_exists","User already registered"),Zm=()=>new $(422,"email_exists","A user with this email address has already been registered"),co=()=>new $(422,"signup_disabled","Signups not allowed for this instance"),eh=()=>new $(400,"email_provider_disabled","Email signups are disabled"),th=()=>new $(422,"otp_disabled","Signups not allowed for otp"),nh=()=>new $(422,"same_password","New password should be different from the old password."),gn=()=>new $(403,"otp_expired","Email link is invalid or has expired"),H=(t,e=422)=>new $(e,"validation_failed",t);var hs=t=>new $(400,"bad_json",t),mc=()=>new $(400,"validation_failed","Refresh token is not valid"),Gn=()=>new $(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),uo=(t,e)=>new $(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),rh=()=>new $(401,"session_not_found","Invalid Refresh Token: Already Used"),hc=(t,e,n)=>new $(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}:{}}),sh=()=>new $(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),ih=()=>new $(400,"invalid_credentials","unsupported_grant_type"),fo=()=>new $(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds."),po=t=>new $(400,"bad_oauth_state",t),gc=t=>new $(400,"bad_oauth_callback",t);var mo=(t="invalid flow state, no valid flow state found")=>new $(404,"flow_state_not_found",t),oh=()=>new $(422,"flow_state_expired","invalid flow state, flow state has expired"),ho=()=>new $(400,"flow_state_already_used","State has already been used"),ah=t=>new $(400,"bad_code_verifier",t),lh=t=>new $(422,"provider_email_needs_verification",t),ch=()=>new $(403,"user_banned","User is banned"),uh=()=>new $(404,"user_not_found","User identified by token not found"),fh=()=>new $(404,"invite_not_found","Invite not found"),gs=t=>new $(500,"unexpected_failure",t),dh=t=>gs(`Unable to exchange external code: ${t.slice(0,4)}`),ph=()=>gs("Error getting user profile from external provider");async function bc(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new SignJWT({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function mh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw uc();let r=kx(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await jwtVerify(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof errors.JWTExpired?Vm():i instanceof errors.JWSSignatureVerificationFailed?zm():i instanceof errors.JWSInvalid||i instanceof errors.JWTInvalid?uc():i}}function kx(t){let e=vx(t);if(!e)return fc("unexpected end of JSON input");let n=Ax(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return fc(wc(n))}}function vx(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 Ax(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var Ox={n:"null",t:"true",f:"false"};function wc(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=Ox[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 ${yc(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${yc(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${yc(r)} looking for beginning of value`}function yc(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var Px=10,$x=4,Ix=4,Nx=31;function Dx(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(Nx,Math.max(Ix,Math.trunc(n)))}return t.RUN_SPEC==="1"?$x:Px}async function ys(t){return hh.hash(t,Dx())}async function Sc(t,e){return hh.compare(t,e)}function gh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!jx(t,s))&&r.push("characters"),r}function jx(t,e){for(let n of t)if(e.includes(n))return true;return false}function ut(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 _c(){let t=crypto.getRandomValues(new Uint8Array(32));return bh(t)}async function tt(t,e){let n=new TextEncoder().encode(t.toLowerCase()+e),r=await crypto.subtle.digest("SHA-256",n);return bh(new Uint8Array(r))}function bh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ec(){return v7()}function ue(){return v7()}var Lx=["iss","sub","aud","iat","exp","name","family_name","given_name","middle_name","nickname","preferred_username","profile","picture","website","gender","birthdate","zoneinfo","locale","updated_at","email","phone","custom_claims","full_name","avatar_url","slug","provider_id","user_name"];function Fx(t){return !!(t==null||t===""||typeof t=="number"&&t===0||Array.isArray(t)&&t.length===0||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)}function wh(t){let e={};for(let n of Lx){let r=t[n];Fx(r)||(e[n]=r);}return e.email_verified=t.email_verified??false,e.phone_verified=t.phone_verified??false,e}var Sh=43,_h=128,Ux="PKCE flow requires code_challenge_method and code_challenge",Mx=/^[a-zA-Z._~0-9-]+$/;function Bx(t){let e=t.length;if(e<Sh||e>_h)throw H(`code challenge has to be between ${Sh} and ${_h} characters`,400);if(!Mx.test(t))throw H("code challenge can only contain alphanumeric characters, hyphens, periods, underscores and tildes",400);return true}function xc(t){return t.toLowerCase()}var qx=new Set(["s256","plain"]);function Eh(t,e){if(e===""!=(t===""))throw H(Ux,400);if(e!==""&&(Bx(e),!qx.has(xc(t))))throw H("Invalid code_challenge_method",400)}function Hx(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Wx(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Hx(new Uint8Array(n))}async function xh(t,e,n){return e.toLowerCase()==="s256"?await Wx(n)===t:n===t}var Kx="github.com",Th="api.github.com",Jx=["user:email"];function Gx(t){let e=t?t.split(","):[];return [...Jx,...e].join(" ")}function Tc(t,e){let n=JSON.parse(e);if(typeof n.error=="string"&&n.error!=="")throw new Error(`${t}: token endpoint returned error ${n.error}`,{cause:e});if(!n.access_token)throw new Error(`${t}: server response missing access_token`,{cause:e});return n}function Rh(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:`https://${e}`}function zx(t){let e=Rh(t,Kx),n=Rh(t,Th);return n.endsWith(Th)||(n+="/api/v3"),{authHost:e,apiHost:n}}function Ch(t){let{authHost:e,apiHost:n}=zx(t);return {id:"github",authorizeUrl({clientId:r,redirectUri:s,scopes:i,state:o,extraParams:a}){let l=new URLSearchParams({client_id:r,redirect_uri:s,scope:Gx(i),state:o,...a});return `${e}/login/oauth/authorize?${l.toString()}`},async exchangeCode(r,{clientId:s,secret:i,redirectUri:o,fetch:a=globalThis.fetch}){let l=new URLSearchParams({client_id:s,client_secret:i,code:r,redirect_uri:o}),c=await a(`${e}/login/oauth/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l.toString(),signal:AbortSignal.timeout(1e4)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`github: token endpoint returned ${c.status}`,{cause:f});return Tc("github",f)},async getUserData(r,{fetch:s=globalThis.fetch}){let i={Authorization:`Bearer ${r.access_token}`},o=()=>({headers:i,signal:AbortSignal.timeout(1e4)}),a=await s(`${n}/user`,o()),l=await a.text();if(a.status<200||a.status>=300)throw new Error(`github: /user returned ${a.status}`,{cause:l});let c=JSON.parse(l),f=await s(`${n}/user/emails`,o()),u=await f.text();if(f.status<200||f.status>=300)throw new Error(`github: /user/emails returned ${f.status}`,{cause:u});let d=JSON.parse(u);if(!Array.isArray(d))throw new Error("github: /user/emails did not return a JSON array");let p=String(c.id);return {claims:{iss:n,sub:p,name:c.name||void 0,preferred_username:c.login,avatar_url:c.avatar_url||void 0,full_name:c.name||void 0,provider_id:p,user_name:c.login,email_verified:false,phone_verified:false},emails:d.filter(g=>g.email).map(g=>({email:g.email,verified:g.verified,primary:g.primary}))}}}}var Rc="https://accounts.google.com",Xx="accounts.google.com",Zx="https://accounts.google.com/o/oauth2/v2/auth",eT="https://oauth2.googleapis.com/token",tT="https://www.googleapis.com/oauth2/v3/certs",nT="https://www.googleapis.com/userinfo/v2/me",rT=["email","profile"],kc=1e4,kh=new Map;function vh(t,e){return createRemoteJWKSet(new URL(t),{[customFetch]:e,timeoutDuration:kc})}function sT(t,e){if(e!==globalThis.fetch)return vh(t,e);let n=kh.get(t);return n||(n=vh(t,e),kh.set(t,n)),n}async function iT(t,e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),r=new Uint8Array(n).slice(0,n.byteLength/2),s="";for(let o of r)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")===e}function oT(t){let e=t?t.split(","):[];return [...rT,...e].join(" ")}function Cc(t){return !!(t.verified_email||t.email_verified)}function Ah(t={}){let e=t.issuer??Rc,n=e===Rc?[Rc,Xx]:e,r=t.userInfoEndpoint??nT,s=t.getKey,i=t.clientIds??[];return {id:"google",authorizeUrl({clientId:o,redirectUri:a,scopes:l,state:c,extraParams:f}){let u=new URLSearchParams({client_id:o,redirect_uri:a,response_type:"code",scope:oT(l),state:c,...f});return `${Zx}?${u.toString()}`},async exchangeCode(o,{clientId:a,secret:l,redirectUri:c,fetch:f=globalThis.fetch}){let u=new URLSearchParams({client_id:a,client_secret:l,code:o,redirect_uri:c,grant_type:"authorization_code"}),d=await f(eT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString(),signal:AbortSignal.timeout(kc)}),p=await d.text();if(d.status<200||d.status>=300)throw new Error(`google: token endpoint returned ${d.status}`,{cause:p});return Tc("google",p)},async getUserData(o,{fetch:a=globalThis.fetch,clientId:l}){if(o.id_token){let d=s??sT(tT,a),p=i[0]??l??void 0,{payload:g}=await jwtVerify(o.id_token,d,{issuer:n,...p?{audience:p}:{}}),m=g;if(m.at_hash){if(!o.access_token)throw new Error("oidc: id_token had at_hash but no access_token was returned");if(!await iT(o.access_token,m.at_hash))throw new Error("oidc: access token hash does not match value in ID token")}let h=m.email||"",y=Cc(m),w={};return m.hd&&(w.hd=m.hd),{emails:h?[{email:h,verified:y,primary:true}]:[],claims:{iss:m.iss,sub:m.sub,name:m.name,picture:m.picture,avatar_url:m.picture,full_name:m.name,provider_id:m.sub,custom_claims:Object.keys(w).length?w:void 0,email_verified:false,phone_verified:false}}}let c=await a(r,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(kc)}),f=await c.text();if(c.status<200||c.status>=300)throw new Error(`google: userinfo returned ${c.status}`,{cause:f});let u=JSON.parse(f);return {emails:u.email?[{email:u.email,verified:Cc(u),primary:true}]:[],claims:{iss:r,sub:u.id,name:u.name,picture:u.picture,email:u.email,email_verified:Cc(u),avatar_url:u.picture,full_name:u.name,provider_id:u.id,phone_verified:false}}}}}function Oh(t){return (t??"").split(",").map(e=>e.trim()).filter(e=>e!=="")}var Ph={github:t=>Ch(t.url),google:t=>Ah({clientIds:Oh(t.client_id)})},$h=new Set(Object.keys(Ph)),vc=["apple","azure","bitbucket","discord","facebook","github","gitlab","google","kakao","keycloak","linkedin","notion","twitch","twitter","slack","spotify","workos","zoom"],Ac=["snapchat","figma","fly","linkedin_oidc","slack_oidc"],aT=new Set([...vc,...Ac]);function Oc(t,e,n){let r=(t??"").toLowerCase();if(!aT.has(r))throw H(`Unsupported provider: Provider ${r} could not be found`,400);let s=e?.[r];if(!s?.enabled)throw H("Unsupported provider: provider is not enabled",400);let i=Oh(s.client_id);if(i.length===0)throw H("Unsupported provider: missing OAuth client ID",400);if(!s.secret)throw H("Unsupported provider: missing OAuth secret",400);let o=Ph[r];if(!o)throw H(`Unsupported provider: provider ${r} is not yet implemented`,400);let a=o(s);return {name:r,provider:a,config:s,clientId:i[0],clientIds:i,secret:s.secret,redirectUri:s.redirect_uri||n.defaultRedirectUri,skipNonceCheck:s.skip_nonce_check??false,emailOptional:s.email_optional??false}}var Ih=3e5,lT=1440*60*1e3;function yo(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.')}function cT(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function uT(t){let e="^";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"){let s=t[++n];s!==void 0?e+=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e+="\\\\";}else if(r==="*")t[n+1]==="*"?(e+=".*",n++):e+="[^./]*";else if(r==="?")e+="[^./]";else if(r==="["){let s=t.indexOf("]",n+1);if(s===-1)e+="\\[";else {let i=t.slice(n+1,s);i.startsWith("!")&&(i=`^${i.slice(1)}`),e+=`[${i}]`,n=s;}}else e+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");}return new RegExp(`${e}$`)}function Nh(t,e){let n=t.indexOf("//");if(n===-1)return e;let r=t.slice(n+2),s=r.search(/[/?#]/);s!==-1&&(r=r.slice(0,s));let i=r.lastIndexOf("@");if(i!==-1&&(r=r.slice(i+1)),r.startsWith("[")){let a=r.indexOf("]");return a===-1?r.slice(1):r.slice(1,a)}let o=r.lastIndexOf(":");return o===-1?r:r.slice(0,o)}function fT(t){let e=t,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(n){let r=n.slice(1).map(Number);return r.some(s=>s>255)?{isIp:false,isLoopback:false}:{isIp:true,isLoopback:r[0]===127}}return e.includes(":")?{isIp:true,isLoopback:e.toLowerCase()==="::1"}:{isIp:false,isLoopback:false}}var dT=/^[0-9]+$/,pT=/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/;function Pc(t,e,n){if(t==="")return false;let r;try{r=new URL(t);}catch{return false}let s=r.protocol.replace(/:$/,"").toLowerCase(),i=s==="http"||s==="https",o=Nh(t,r.hostname);try{let c=new URL(e);if(c.protocol===r.protocol&&Nh(e,c.hostname)===o&&(c.port===r.port||cT(o)))return !0}catch{}let a=fT(o);if(dT.test(o))return false;if(a.isIp)return a.isLoopback;if(i&&!pT.test(o))return false;let l=t.split("#")[0];for(let c of n)if(uT(c).test(l))return true;return false}var bs=class t{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;yo(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??hT(n.password_requirements),this.sessionTimeboxSeconds=Lh(n.sessions?.timebox),this.sessionInactivitySeconds=Lh(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;get otpLength(){return this.config.email?.otp_length??6}get otpExpirySeconds(){return this.config.email?.otp_expiry??3600}resolveEmailRedirect(e){let n=this.config.site_url??"http://localhost:3000";return e&&Pc(e,n,this.config.additional_redirect_urls??[])?e:n}async signUp(e,n,r){if(this.config.enable_signup===false)throw co();if(!e)throw sh();if(this.config.email?.enable_signup===false)throw eh();if(n==null||n===void 0||n==="")throw H("Signup requires a valid password",400);if(!zn(e))throw H("Unable to validate email address: invalid format",400);if(n.length>72)throw H("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"),Xm()):fo();let a=ue(),l=await ys(n),c=new Date().toISOString(),f=null,u=null,d=null;i||(f=ut(this.otpLength),u=await tt(e,f),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},g={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:u,confirmation_sent_at:d});await this.repo.createIdentity({id:ue(),provider:"email",provider_id:a,user_id:a,identity_data:g}),!i&&f&&u&&await this.mailer.sendConfirmation(e,u,f,{userId:a,redirectTo:this.config.site_url});let h=await this.repo.findIdentitiesByUserId(a),y=this.repo.parseUserJson(m),w=this.mapUserToResponse(y,h,"signup");if(i){let S=await this.createSessionForUser(y,h);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:S}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw H("missing email or phone",400);if(!n)throw ct();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw ct();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw Km();if(!await Sc(n,s.encrypted_password))throw ct();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw mc();let n=await this.repo.findRefreshToken(e);if(!n)throw Fh(e)?Gn():mc();if(Uh(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw Gn();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw Gn();this.assertSessionRefreshable(s);}let i=$c(s?.updated_at,s?.refreshed_at,r.updated_at,r.last_sign_in_at);await this.repo.revokeRefreshToken(n.id);let o=Ec(),a=n.session_id??ue();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 rh();if(!e.session_id)throw uo(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=gT(n,e.token),s=r.filter(c=>!Uh(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),uo(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw uo(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw Gn();let a=await this.repo.findSessionById(e.session_id);if(!a)throw Gn();this.assertSessionRefreshable(a);let l=$c(a.updated_at,a.refreshed_at,o.updated_at,o.last_sign_in_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 bc({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 Mh({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 hc(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 hc("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw ct();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 ct();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=jh(u,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await Sc(n.password,s.encrypted_password))throw nh();i.encrypted_password=await ys(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(!zn(u))throw H("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 Zm();let p=new Date().toISOString(),g=s.email??"",m=ut(this.otpLength),h=await tt(u,m),y=(this.config.email?.double_confirm_changes??true)&&g!=="",w=ut(this.otpLength),S=y?await tt(g,w):null;i.email_change=u,i.email_change_token_current=S,i.email_change_token_new=h,i.email_change_sent_at=p,y&&S?await this.mailer.sendEmailChange(g,S,w,{userId:e,tokenNew:m,tokenHashNew:h,redirectTo:this.config.site_url,currentEmail:g,newEmail:u}):await this.mailer.sendEmailChange(u,h,m,{userId:e,redirectTo:this.config.site_url,currentEmail:g,newEmail:u});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let u=await this.repo.updateUser(e,i);if(!u)throw ct();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 H(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw ct();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 H("One of email or phone must be set",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=ue(),c=await ys(_c()),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:ue(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw th();let i=ut(this.otpLength),o=await tt(e,i),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 ct();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 H("Password recovery requires an email",422);if(e=e.toLowerCase(),!zn(e))throw H("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 co();let l=ue(),c=await ys(_c()),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:ue(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=ut(this.otpLength),o=await tt(e,i),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 ct();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;if(e.token_hash)n=e.token_hash;else if(e.email&&e.token)n=await tt(e.email.toLowerCase(),e.token);else throw gn();return await this.repo.transaction(async r=>{let s=this.repo;this.repo=r;try{let i=await this.findUserByTokenAndType(n,e.type),o=i?.user??null,a=i?.tokenColumn??null;if(!o||!a)throw gn();if(this.isTokenExpired(o,a))throw gn();if(e.type==="email_change"){let c=(this.config.email?.double_confirm_changes??!0)&&!!o.email?"email_change_token_current":"email_change_token_new";if(a!==c)throw gn()}if(!await this.repo.claimUserToken(o.id,a,n))throw gn();return await this.completeVerifyOtp(o,a,e.type)}finally{this.repo=s;}})}async completeVerifyOtp(e,n,r){let s=this.repo.parseUserJson(e),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),r==="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 f=(await this.repo.findIdentitiesByUserId(e.id)).find(u=>u.provider==="email");if(f){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}});}else await this.repo.createIdentity({id:ue(),provider:"email",provider_id:e.id,user_id:e.id,identity_data:{sub:e.id,email:s.email_change,email_verified:true,phone_verified:false}});o.raw_app_meta_data=await this.buildAppMetaDataProviders(e.id,s.raw_app_meta_data),await this.createAuditLog(e.id,s.email??"","user_modified","user",false);}else if(r==="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(e.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}});}n&&(o[n]=null);}else n&&(o[n]=null);o.last_sign_in_at=i,await this.repo.updateUser(e.id,o);let a=await this.repo.findUserById(e.id);if(!a)throw gn();let l=await this.repo.findIdentitiesByUserId(e.id);return r==="signup"&&await this.createAuditLog(e.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(r),includeLoginProviderTrait:!["magiclink","recovery"].includes(r),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(r)?"otp":"password"})}async recover(e){if(!e)throw H("Password recovery requires an email",400);if(e=e.toLowerCase(),!zn(e))throw H("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=ut(this.otpLength),s=await tt(e,r),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 H("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw H("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!zn(n))throw H("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=ut(this.otpLength),i=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw fo()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw fo();let o=await tt(r.email_change,s);await this.repo.updateUser(r.id,{email_change_token_new:o,email_change_sent_at:i}),await this.mailer.sendEmailChange(r.email_change,o,s,{userId:r.id,redirectTo:this.config.site_url,currentEmail:r.email??void 0,newEmail:r.email_change});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw Gm();if(!n.email)throw H("Reauthentication requires the user to have an email or a phone number",400);let r=ut(this.otpLength),s=await tt(n.email,r),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=$c(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=ue();await this.repo.createSession({id:l,user_id:e.id});let c=Ec();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,s.provider??"email",s.providerTraitKey??"provider");let f=await bc({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 Mh({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=gh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw Jm(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:e.provider,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}static SENT_AT_COLUMN={confirmation_token:"confirmation_sent_at",recovery_token:"recovery_sent_at",email_change_token_current:"email_change_sent_at",email_change_token_new:"email_change_sent_at",reauthentication_token:"reauthentication_sent_at"};isTokenExpired(e,n){let r=t.SENT_AT_COLUMN[n];if(!r)return false;let s=e[r];if(!s)return false;let i=new Date(s).getTime();return Number.isNaN(i)?false:Date.now()-i>this.otpExpirySeconds*1e3}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","email_change_token_current"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true,o="email",a="provider"){let l={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(l.traits={[a]:o}),await this.repo.createAuditLogEntry({id:ue(),payload:l});}async createAuditLogWithTraits(e,n,r,s,i){await this.repo.createAuditLogEntry({id:ue(),payload:{action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s,traits:i}});}async getExternalProviderRedirectUrl(e,n){let r=e.provider??"",s=Oc(r,this.config.external,{defaultRedirectUri:n.defaultRedirectUri}),i=e.invite_token??"";if(i!==""&&!await this.repo.findUserByToken("confirmation_token",i))throw uh();let o=e.code_challenge??"",a=e.code_challenge_method??"";Eh(a,o);let l=this.resolveOAuthReferrer(e.redirect_to,n.refererHeader),c={};for(let[d,p]of Object.entries(e))p!==void 0&&(["provider","scopes","code_challenge","code_challenge_method"].includes(d)||(c[d]=p));let f=ue(),u=o!==""?ue():null;return await this.repo.deleteFlowStatesCreatedBefore(new Date(Date.now()-lT).toISOString()),await this.repo.createFlowState({id:f,auth_code:u,authentication_method:"oauth",code_challenge:o!==""?o:null,code_challenge_method:o!==""?xc(a):null,provider_type:s.name,invite_token:i!==""?i:null,referrer:l,email_optional:s.emailOptional}),s.provider.authorizeUrl({clientId:s.clientId,redirectUri:s.redirectUri,scopes:e.scopes,state:f,extraParams:c})}async loadOAuthFlowState(e){if(!e)throw gc("OAuth state parameter missing");if(!Fh(e))throw po("OAuth state parameter is invalid");let n=await this.repo.findFlowStateById(e);if(!n)throw po("OAuth state not found or expired");if(Date.now()-Date.parse(n.created_at)>Ih)throw po("OAuth state has expired");if(n.code_challenge!==null&&n.user_id!==null)throw ho();return n}resolveOAuthRedirectTarget(e){return e.referrer||this.config.site_url||"http://localhost:3000"}async handleExternalProviderCallback(e,n,r){let s=this.resolveOAuthRedirectTarget(e),i=e.provider_type,o=n.code;if(!o)throw gc("OAuth callback with missing authorization code missing");let a=Oc(i,this.config.external,{defaultRedirectUri:r.defaultRedirectUri}),l;try{l=await a.provider.exchangeCode(o,{clientId:a.clientId,secret:a.secret,redirectUri:a.redirectUri});}catch(h){throw dh(o).withInternalError(h)}let c;try{c=await a.provider.getUserData(l,{clientId:a.clientId});}catch(h){throw ph().withInternalError(h)}if(c.emails.length===0&&!e.email_optional)throw gs("Error getting user email from external provider");let f,u=false;for(let h of c.emails)if(f=h.email,u=h.verified,h.primary)break;let d={...c.claims,email:f,email_verified:u},p=wh(d),g=d.sub??"",m=await this.repo.transaction(async h=>{let y=this.repo;this.repo=h;try{let w=e.invite_token??"";if(w!==""){let v=await this.processInvite(w,i,c.emails,p,g);return await this.issueOAuthCallbackResult(v,e,l,s)}let S=await this.determineAccountLinking(c.emails,i,g),b,_,E=!1;if(S.decision==="AccountExists")b=S.user,_=S.identity.id,await this.repo.updateIdentity(_,{identity_data:p,last_sign_in_at:new Date().toISOString()}),await this.updateUserMetaDataAndProviders(b.id,p);else if(S.decision==="LinkAccount"){b=S.user;let v=await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:b.id,identity_data:p});_=v.id,await this.updateUserMetaDataAndProviders(b.id,p),await this.createAuditLogWithTraits(b.id,b.email??"","identity_linked","user",{identity_id:v.id,provider:i,provider_id:g});}else if(S.decision==="CreateAccount"){if(this.config.enable_signup===!1)throw co();E=!0;let v=ue();b=await this.repo.createUser({id:v,email:S.candidateEmail.email||null,raw_app_meta_data:{provider:i,providers:[i]},raw_user_meta_data:p}),_=(await this.repo.createIdentity({id:ue(),provider:i,provider_id:g,user_id:v,identity_data:p})).id;}else throw gs("Multiple accounts with the same email address in the same linking domain detected: default");let x=this.repo.parseUserJson(await this.repo.findUserById(b.id));if(mT(x))throw ch();if(!(e.email_optional&&S.candidateEmail.email==="")&&!x.confirmed_at){await this.removeUnconfirmedIdentities(x.id,_,p);let v=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??!1);if(S.candidateEmail.verified||v)await this.createAuditLog(x.id,S.candidateEmail.email,"user_signedup","team",!0,i),await this.repo.updateUser(x.id,{confirmed_at:new Date().toISOString(),raw_user_meta_data:{...p,email_verified:!0}});else {let P=!1;if(S.candidateEmail.email){let C=ut(this.otpLength),R=await tt(S.candidateEmail.email,C),U=new Date().toISOString();await this.repo.updateUser(x.id,{confirmation_token:R,confirmation_sent_at:U}),await this.mailer.sendConfirmation(S.candidateEmail.email,R,C,{userId:x.id,redirectTo:this.config.site_url}),P=!0;}return {commitError:lh(P?`Unverified email with ${i}. A confirmation email has been sent to your ${i} email`:`Unverified email with ${i}. Verify the email with ${i} in order to sign in`)}}}else await this.createAuditLog(x.id,x.email??"","login","account",!0,i);return await this.issueOAuthCallbackResult(x,e,l,s)}finally{this.repo=y;}});if(m.commitError)throw m.commitError;return m}async issueOAuthCallbackResult(e,n,r,s){if(n.code_challenge!=null&&n.auth_code!=null){if(!await this.repo.claimFlowStateForPkce(n.id,{user_id:e.id,provider_access_token:r.access_token??"",provider_refresh_token:r.refresh_token??"",auth_code_issued_at:new Date().toISOString()}))throw ho();let m=new URL(s);return m.searchParams.set("code",n.auth_code),{commitError:void 0,type:"pkce",redirectUrl:m.toString()}}let o=this.repo.parseUserJson(await this.repo.findUserById(e.id)),a=await this.repo.findIdentitiesByUserId(e.id),l=await this.createSessionForUser(o,a,"session",{createLoginAudit:false});if(!await this.repo.deleteFlowState(n.id))throw ho();let f={access_token:l.access_token,expires_at:String(l.expires_at),expires_in:String(l.expires_in),provider_token:r.access_token??""};r.refresh_token&&(f.provider_refresh_token=r.refresh_token),f.refresh_token=l.refresh_token,f.sb="",f.token_type=l.token_type;let d=Object.keys(f).sort().map(g=>`${encodeURIComponent(g)}=${encodeURIComponent(f[g])}`).join("&"),p=new URL(s);return p.hash=d,{commitError:void 0,type:"implicit",redirectUrl:p.toString()}}async processInvite(e,n,r,s,i){let o=await this.repo.findUserByToken("confirmation_token",e);if(!o)throw fh();let a=this.repo.parseUserJson(o),l=(a.email??"").toLowerCase();if(!r.some(u=>u.email.toLowerCase()===l))throw H("Invited email does not match emails from external provider",400);let f=await this.repo.createIdentity({id:ue(),provider:n,provider_id:i,user_id:a.id,identity_data:s});return await this.updateUserMetaDataAndProviders(a.id,s),await this.createAuditLog(a.id,a.email??"","invite_accepted","account",true,n),await this.removeUnconfirmedIdentities(a.id,f.id,s),await this.repo.updateUser(a.id,{confirmation_token:null,confirmed_at:new Date().toISOString(),raw_user_meta_data:{...s,email_verified:true}}),this.repo.parseUserJson(await this.repo.findUserById(a.id))}async exchangePkceCode(e,n){if(!e||!n)throw H("invalid request: both auth code and code verifier should be non-empty",400);let r=await this.repo.findFlowStateByAuthCode(e);if(!r||!r.user_id)throw mo();if(Date.now()-Date.parse(r.created_at)>Ih)throw oh();if(!await xh(r.code_challenge??"",r.code_challenge_method??"",n))throw ah("code challenge does not match previously saved code verifier");return {...await this.repo.transaction(async o=>{let a=this.repo;this.repo=o;try{if(!await this.repo.deleteFlowState(r.id))throw mo();let c=await this.repo.findUserById(r.user_id);if(!c)throw mo();let f=this.repo.parseUserJson(c),u=await this.repo.findIdentitiesByUserId(c.id);return await this.createSessionForUser(f,u,"session",{includeLoginProviderTrait:!0,provider:r.provider_type,providerTraitKey:"provider_type"})}finally{this.repo=a;}}),...r.provider_access_token?{provider_token:r.provider_access_token}:{},...r.provider_refresh_token?{provider_refresh_token:r.provider_refresh_token}:{}}}resolveOAuthReferrer(e,n){let r=this.config.site_url??"http://localhost:3000",s=this.config.additional_redirect_urls??[];return e&&Pc(e,r,s)?e:n&&Pc(n,r,s)?n:r}async updateUserMetaDataAndProviders(e,n){let r=await this.repo.findUserById(e);if(!r)return;let s=this.repo.parseUserJson(r),i=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{},o=jh(i,n),a=await this.buildAppMetaDataProviders(e,s.raw_app_meta_data);await this.repo.updateUser(e,{raw_user_meta_data:o,raw_app_meta_data:a});}async buildAppMetaDataProviders(e,n){let r=typeof n=="object"&&n?{...n}:{},i=[...await this.repo.findIdentitiesByUserId(e)].sort((a,l)=>Date.parse(a.created_at)-Date.parse(l.created_at)),o=[];for(let a of i)o.includes(a.provider)||o.push(a.provider);return r.providers=o,o.length>0&&(r.provider=o[0]),r}async removeUnconfirmedIdentities(e,n,r){await this.repo.deleteIdentitiesExcept(e,n);let s=await this.repo.findUserById(e),i=await this.buildAppMetaDataProviders(e,s?this.repo.parseUserJson(s).raw_app_meta_data:{});await this.repo.updateUser(e,{raw_user_meta_data:r,raw_app_meta_data:i,encrypted_password:null});}async determineAccountLinking(e,n,r){let s=e.find(p=>p.primary),i=s?{email:s.email.toLowerCase(),verified:s.verified}:{email:"",verified:false},o=r?await this.repo.findIdentityByProviderAndId(n,r):null;if(o){let p=await this.repo.findUserById(o.user_id);if(!p)throw new Error("Database error finding user for existing identity");return i={email:(p.email??"").toLowerCase(),verified:i.verified},{decision:"AccountExists",user:p,identity:o,candidateEmail:i}}let a=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false),l=Array.from(new Set(e.filter(p=>p.verified||a).map(p=>p.email.toLowerCase())));if(l.length===0)return i.email&&await this.repo.findUserByEmail(i.email)&&(i={...i,email:""}),{decision:"CreateAccount",candidateEmail:i};let c=await this.repo.findIdentitiesByEmails(l),f=Array.from(new Set(c.map(p=>p.user_id))),d=(await Promise.all(f.map(p=>this.repo.findUserById(p)))).filter(p=>p!==null).filter(p=>!Dh(p));if(d.length===0){let p=await Promise.all(l.map(m=>this.repo.findUserByEmail(m))),g=new Map;for(let m of p)m&&!Dh(m)&&g.set(m.id,m);d=Array.from(g.values());}return d.length===0?{decision:"CreateAccount",candidateEmail:i}:d.length>1?{decision:"MultipleAccounts"}:{decision:"LinkAccount",user:d[0],candidateEmail:i}}};function Dh(t){return t.is_sso_user===true||t.is_sso_user===1}function mT(t){return t.banned_until?Date.parse(t.banned_until)>Date.now():false}function jh(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function hT(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 Lh(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 zn(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function Fh(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 Uh(t){return t.revoked===true||t.revoked===1}function gT(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 $c(...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 Mh(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}var yT=100;function ws(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function yn(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Ss=class t{constructor(e,n,r=s=>e.transaction().execute(s)){this.db=e;this.dialect=n;this.runInTransaction=r;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}async transaction(e){return this.runInTransaction(n=>e(new t(n,this.dialect,this.runInTransaction)))}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 claimUserToken(e,n,r){let s=await this.update("users").set({[n]:null}).where("id","=",e).where(n,"=",r).executeTakeFirst();return Number(s.numUpdatedRows??0)>0}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email?e.email.toLowerCase():null,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:yn(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:yn(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=yn(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=yn(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:ue(),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:yn(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:ws(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=yn(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async deleteIdentitiesExcept(e,n){await this.deleteFrom("identities").where("user_id","=",e).where("id","!=",n).execute();}async findIdentityByProviderAndId(e,n){let r=await this.table("identities").selectAll().where("provider","=",e).where("provider_id","=",n).executeTakeFirst();if(!r)return null;let s=r;return {...s,identity_data:ws(s.identity_data)}}async findIdentitiesByEmails(e){return e.length===0?[]:(await this.table("identities").selectAll().where("email","in",e.map(r=>r.toLowerCase())).execute()).map(r=>({...r,identity_data:ws(r.identity_data)}))}async createFlowState(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id??null,auth_code:e.auth_code??null,authentication_method:e.authentication_method,code_challenge_method:e.code_challenge_method??null,code_challenge:e.code_challenge??null,provider_type:e.provider_type,provider_access_token:"",provider_refresh_token:"",auth_code_issued_at:null,invite_token:e.invite_token??null,referrer:e.referrer??null,oauth_client_state_id:e.oauth_client_state_id??null,linking_target_id:e.linking_target_id??null,email_optional:this.bool(e.email_optional??false),created_at:n,updated_at:n};return await this.insertInto("flow_state").values(r).execute(),r}async findFlowStateById(e){return await this.table("flow_state").selectAll().where("id","=",e).executeTakeFirst()??null}async findFlowStateByAuthCode(e){return await this.table("flow_state").selectAll().where("auth_code","=",e).executeTakeFirst()??null}async updateFlowState(e,n){let r={...n,updated_at:new Date().toISOString()};r.email_optional!=null&&(r.email_optional=this.bool(!!r.email_optional)),await this.update("flow_state").set(r).where("id","=",e).execute();}async claimFlowStateForPkce(e,n){let r=await this.update("flow_state").set({...n,updated_at:new Date().toISOString()}).where("id","=",e).where("user_id","is",null).executeTakeFirst();return Number(r.numUpdatedRows??0)>0}async deleteFlowStatesCreatedBefore(e){let n=await this.deleteFrom("flow_state").where("id","in",this.db.selectFrom("flow_state").select("id").where("created_at","<",e).limit(yT)).executeTakeFirst();return Number(n.numDeletedRows??0)}async deleteFlowState(e){let n=await this.deleteFrom("flow_state").where("id","=",e).executeTakeFirst();return Number(n.numDeletedRows??0)>0}async createAuditLogEntry(e){let n={id:e.id,payload:yn(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:ws(e.raw_app_meta_data),raw_user_meta_data:ws(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??null}}};var Vn=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:Bh(e)+Bh(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 Bh(t){return new TextEncoder().encode(t).byteLength}var bo=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 wo=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 So=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 Eo=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(()=>(Jh(),Kh));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var xo=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=jc(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 jc(t,e){let n=e.html?"text/html; charset=UTF-8":"text/plain; charset=UTF-8";return [`From: ${t}`,`To: ${e.to}`,`Subject: ${e.subject}`,"MIME-Version: 1.0",`Content-Type: ${n}`,"",e.html??e.text??""].join(`
87
- `)}Ol();function To(t){let e=t.port??587,n=t.timeoutMs??3e4,r=!!(t.user&&t.pass),s=r?{user:t.user,pass:t.pass}:void 0,i=t.secure??e===465;return {host:t.host,port:e,secure:i,...s?{auth:s}:{},requireTLS:t.requireTls??(r&&!i),...t.rejectUnauthorized===false?{tls:{rejectUnauthorized:false}}:{},connectionTimeout:n,greetingTimeout:n,socketTimeout:n}}function Lc(t,e){return {from:t,to:e.to,subject:e.subject,...e.text!==void 0?{text:e.text}:{},...e.html!==void 0?{html:e.html}:{}}}function Fc(t){if(!t)throw new Error("SMTP email is not supported in this runtime (SmtpEmailDriver requires Node or Bun)")}var _T="nodemailer",Qn=class{constructor(e){this.options=e;}transporter;async send(e){Fc(!Dp()&&(Np()||Al()));let n=await this.getTransporter();try{await n.sendMail(Lc(this.options.from,e));}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`SmtpEmailDriver send failed: ${s}`,{cause:r})}}async getTransporter(){if(this.transporter)return this.transporter;if(this.options.createTransport)return this.transporter=this.options.createTransport(To(this.options)),this.transporter;let e=await import(_T);return this.transporter=e.createTransport(To(this.options)),this.transporter}};var Es=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);}}},Yn=class extends Es{silent;logger;constructor(e={}){super({maxKeepCount:0}),this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){if(await super.send(e),!this.silent){let n=e.text?e.text:"(html-only email, body omitted)";this.logger.info(["[@supabase/lite] email captured (not delivered)",`To: ${e.to}`,`Subject: ${e.subject}`,"",n].join(`
88
- `));}}};var xs=class{silent;logger;constructor(e={}){this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){this.silent||this.logger.info(["[@supabase/lite] SMS driver noop send",`To: ${e.to}`,`Body: ${e.body}`].join(`
89
- `));}};function ET(t){let e=t?.auth?.email?.smtp;if(e?.enabled!==true)return;if(!e.host)throw new Error("Missing required field in config: auth.email.smtp.host");if(!e.port)throw new Error("Missing required field in config: auth.email.smtp.port");if(!e.user)throw new Error("Missing required field in config: auth.email.smtp.user");if(!e.pass)throw new Error("Missing required field in config: auth.email.smtp.pass");if(!e.admin_email)throw new Error("Missing required field in config: auth.email.smtp.admin_email");let n=e.sender_name?{name:e.sender_name,address:e.admin_email}:e.admin_email;return new Qn({host:e.host,port:e.port,user:e.user,pass:e.pass,from:n})}function Gh(t={},e){return {email:t.email??ET(e)??new Yn,sms:t.sms??new xs,cache:t.cache??new Vn}}var xT="/auth/v1/verify";function zh(t,e,n,r){let s=new URL(xT,TT(t));return s.searchParams.set("token",e),s.searchParams.set("type",n),s.searchParams.set("redirect_to",r),s.toString()}function TT(t){return t.endsWith("/")?t:`${t}/`}function Co(t,e){return t.replace(/\{\{\s*\.(\w+)\s*\}\}/g,(n,r)=>r in e?e[r]??"":n)}var Vh={invite:"You have been invited",confirmation:"Confirm Your Signup",recovery:"Reset Your Password",magic_link:"Your Magic Link",email_change:"Confirm Email Change",reauthentication:"Confirm Reauthentication"},Ro="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji'";function Xn(t,e){return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
84
+ `.execute(t)).rows[0],r=n?.status??null,s=n?.headers??null,i;if(r&&r.length>0){let u=Number(r);if(!Number.isInteger(u)||u<200||u>599)return T(500,"PGRST112",Bx,null,null);i=u;}let o;if(s&&s.length>0){let u;try{u=JSON.parse(s);}catch{return T(500,"PGRST111",Vn,null,null)}if(!Array.isArray(u))return T(500,"PGRST111",Vn,null,null);let f=[];for(let d of u){if(!d||typeof d!="object"||Array.isArray(d))return T(500,"PGRST111",Vn,null,null);let p=Object.keys(d);if(p.length!==1)return T(500,"PGRST111",Vn,null,null);let h=d[p[0]];if(typeof h!="string")return T(500,"PGRST111",Vn,null,null);f.push([p[0],h]);}o=f;}if(i===void 0&&!o)return e;let a=i??e.status,l=new Headers(e.headers);if(o)try{for(let[u,f]of o)l.set(u,f);}catch{return T(500,"PGRST111",Vn,null,null)}let c;return qx.has(a)?(c=null,l.delete("Content-Length"),l.delete("Content-Type")):c=e.body?await e.arrayBuffer():null,new Response(c,{status:a,statusText:e.statusText,headers:l})}var qx=new Set([101,204,205,304]);var Hx=/^[\w.+*-]+\/[\w.+*-]+$/,Wx=new Set(["text/plain","text/xml","text/csv","application/json","application/geo+json","application/openapi+json"]);function Kx(t){return t.replace(/^"([\s\S]*)"$/,"$1")}function Jx(t){let e=t.match(/^(?:"(?:[^"]|"")*"|[^."]+)\.([\s\S]+)$/);return e?e[1]:t}function Gx(t){if(t.return_typtype!=="d"||t.return_is_setof)return null;let e=Kx(Jx(t.return_type));return Hx.test(e)?e:null}function Ym(t){if(!t)return [];let e=[];for(let n of t.split(",")){let r=n.split(";"),s=r[0].trim().toLowerCase();if(!s)continue;let i=1;for(let o of r.slice(1)){let a=o.trim().match(/^q=(.+)$/i);if(a){let l=Number.parseFloat(a[1]);Number.isFinite(l)&&(i=l);}}e.push({media:s,q:i});}return e}function Xm(t){return Wx.has(t)?`${t}; charset=utf-8`:t}function Vx(t,e){let n=e.indexOf("/"),r=n>0?e.slice(0,n):e,s=-1,i=0;for(let o of t){let a=o.media===e?2:o.media===`${r}/*`?1:o.media==="*/*"?0:-1;a<0||(a>s?(s=a,i=o.q):a===s&&(i=Math.max(i,o.q)));}return s<0?0:i}function zx(t,e){let n=Gx(t);if(!n)return null;if(n==="*/*"){let r=Ym(e);return r.some(s=>s.media==="*/*"&&s.q<=0)?null:!e||r.some(s=>s.q>0)?{mediaType:"application/octet-stream",isBinary:true}:null}return Vx(Ym(e),n)>0?{mediaType:n,isBinary:(t.return_base_type??"").toLowerCase()==="bytea"}:null}function xo(t,e,n){let r=so(t,e);return r?zx(r,n):null}function Zm(t,e){if(t instanceof Uint8Array){let s=new Uint8Array(t.byteLength);return s.set(t),s}if(e&&typeof t=="string"&&t.startsWith("\\x")){let s=t.slice(2),i=new Uint8Array(Math.floor(s.length/2));for(let o=0;o<i.length;o++)i[o]=parseInt(s.substr(o*2,2),16);return i}let n=new TextEncoder().encode(t==null?"":String(t)),r=new Uint8Array(n.byteLength);return r.set(n),r}var eh=Aa(Jl());function ke(t,e,n){if(!n)return;let{sql:r,parameters:s}=e.compile();console.info(eh.default.dim(`[POSTGREST:SQL:${t}] ${r}
85
+ - ${JSON.stringify([...s])}`));}async function th(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l}=t;if(!t.isMutation||n?.return!=="minimal")return null;let c={...e,select:void 0},u=ee(c,s,{db:r,introspection:i,schema:o});ke("",u,t.debug);let f=await u.execute(),d=Array.isArray(f)&&f.length>0&&f[0]&&typeof f[0]=="object"&&("numUpdatedRows"in f[0]||"numInsertedOrUpdatedRows"in f[0]||"numDeletedRows"in f[0])?f[0]:void 0,p=d===void 0?void 0:Number(d.numUpdatedRows??d.numInsertedOrUpdatedRows??d.numDeletedRows??0),h=rt(e,"no-return",a.appliedResolution,l),m={"Content-Range":Kt(e,n,p)};return t.prefApplied&&(m["Preference-Applied"]=t.prefApplied),new Response(null,{status:h,headers:m})}async function nh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,mutationPlan:a,mutationCreated:l,prefApplied:c}=t;if(!t.isMutation||n?.return!=="headers-only")return null;let f=i.primary_keys.find(w=>w.table===e.from)?.columns??[],d={...e,select:f.length>0?f:void 0},p=ee(d,s,{db:r,introspection:i,schema:o});ke("",p,t.debug);let h=await p.execute(),m=Array.isArray(h)?h.length:0,g=rt(e,"no-return",a.appliedResolution,l),y={"Content-Range":Kt(e,n,m)};if(c&&(y["Preference-Applied"]=c),f.length>0&&Array.isArray(h)&&h.length>0){let w=h[0],S=f.map(b=>`${b}=eq.${w[b]}`).join("&");y.Location=`/${e.from}?${S}`;}return new Response(null,{status:g,headers:y})}function zn({rows:t,ast:e,connection:n,responseSchemaMap:r,mutationNullify:s}){let i=t.map(o=>n.deserializeRow(o));return i=_m(i,e,r,Sm(n,e)),i=Cm(i,e.select,n.dialect),s?.meta?.return==="representation"&&(e.type==="insert"||e.type==="upsert"||e.type==="update")&&(i=Mm(i,s.meta?.columns,s.mutationPlan.bodyKeySets)),i}function To(t){let{rows:e,stripNullsResponse:n,csvResponse:r,contentRange:s,status:i=200,preferenceApplied:o,location:a,contentType:l="array"}=t,c=n?bn(e):e,u=r?Eo(Array.isArray(c)?c:[c]):Rt(c),f=new TextEncoder().encode(u),d={"Content-Type":r?"text/csv; charset=utf-8":n?l==="object"?"application/vnd.pgrst.object+json;nulls=stripped; charset=utf-8":"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":l==="object"?"application/vnd.pgrst.object+json; charset=utf-8":"application/json; charset=utf-8","Content-Range":s,"Content-Length":String(f.byteLength)};return o&&(d["Preference-Applied"]=o),a&&(d.Location=a),new Response(f,{status:i,headers:d})}async function rh(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l}=t;if(!(t.isMutation&&(e.type==="update"||e.type==="delete")&&(e.limit!==void 0||e.offset!==void 0)))return null;let u={...e,select:void 0},f=ee(u,s,{db:r,introspection:i,schema:o});if(ke("LTD",f,t.debug),await f.execute(),n?.return==="representation"){let S={...e,type:"query",values:void 0,limit:void 0,offset:void 0},b=ee(S,s,{db:r,introspection:i,schema:o});ke("LTD-SEL",b,t.debug);let _=await b.execute(),E=Array.isArray(_)?_:[],x=zn({rows:E,ast:e,connection:a,responseSchemaMap:l}),O=x.length,v=[];n.return==="representation"&&v.push("return=representation"),n.count&&v.push(`count=${n.count}`),n.tx&&v.push(`tx=${n.tx}`);let $=e.type==="delete"?"*/*":O>0?ft(0,O,void 0):"*/*";return To({rows:x,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:$,preferenceApplied:v.length>0?v.join(", "):void 0})}let d={...e,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},h=await ee(d,s,{db:r,introspection:i,schema:o}).execute(),m=Number((Array.isArray(h)?h[0]:h)?.__count??0),y={"Content-Range":m>0?ft(0,m,void 0):"*/*"},w=[];return n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`),w.length>0&&(y["Preference-Applied"]=w.join(", ")),new Response(null,{status:204,headers:y})}function Qx(t){return "select"in t||"spread"in t||"join"in t}function sh(t){if(!t)return false;for(let e of t)if(typeof e!="string")for(let[n,r]of Object.entries(e)){if(Qx(r))return true;let s=r;if(s.path||s.cast||s.preCast||s.aggregate||(s.column??n)!==n)return true}return false}async function ih(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u}=t;if(!(t.isMutation&&n?.return==="representation"&&sh(e.select)))return null;let p=i.primary_keys.find(_=>_.table===e.from)?.columns??[],h=[];if(e.type==="delete"){let _={...e,type:"query",values:void 0},E=ee(_,s,{db:r,introspection:i,schema:o});ke("EMB-PRE",E,t.debug),h=await E.execute();let x={...e,select:void 0},O=ee(x,s,{db:r,introspection:i,schema:o});ke("EMB-DEL",O,t.debug),await O.execute();}else {if(p.length===0)return T(500,"PGRSTXXX","Cannot return embedded data on a table without a primary key",null,null);let _={...e,select:p},E=ee(_,s,{db:r,introspection:i,schema:o});ke("EMB-MUT",E,t.debug);let x=await E.execute(),O=Array.isArray(x)?x:[];if(O.length>0){let v;if(p.length===1){let H=p[0];v={[H]:{$in:O.map(V=>V[H])}};}else v={$or:O.map(H=>{let V={};for(let B of p)V[B]={$eq:H[B]};return V})};let $=e.where?{$and:[e.where,v]}:v,k={...e,type:"query",values:void 0,where:$},N=ee(k,s,{db:r,introspection:i,schema:o});ke("EMB-SEL",N,t.debug),h=await N.execute();}}let m=zn({rows:h,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}});e.order&&e.order.length>0&&(m=_o(m,e.order));let g=rt(e,"representation",c.appliedResolution,u),y=m.length,w=["return=representation"];n?.count&&w.push(`count=${n.count}`),n?.tx&&w.push(`tx=${n.tx}`);let S=e.type==="delete"||e.type==="insert"||e.type==="upsert"?"*/*":y>0?ft(0,y,void 0):"*/*",b;if((e.type==="insert"||e.type==="upsert")&&p.length>0&&m.length>0){let _=m[0],E=p.map(x=>`${x}=eq.${_[x]}`).join("&");b=`/${e.from}?${E}`;}return To({rows:m,stripNullsResponse:t.stripNullsResponse,csvResponse:t.csvResponse,contentRange:S,status:g,preferenceApplied:w.join(", "),location:b})}function Yx(t){return t?.handling!=="strict"||typeof t.maxAffected!="number"||!Number.isFinite(t.maxAffected)?null:t.maxAffected}function oh(t){return T(400,"PGRST124","Query result exceeds max-affected preference constraint",`The query affects ${t} rows`,null)}function Xx(t){return t.type!=="insert"&&t.type!=="upsert"&&t.type!=="put"?null:Array.isArray(t.values)?t.values.length:t.values&&typeof t.values=="object"?1:0}async function ah(t){if(!t.isMutation)return null;let e=Yx(t.meta);if(e===null)return null;let n=Xx(t.ast);if(n!==null)return n>e?oh(n):null;if(t.ast.type!=="update"&&t.ast.type!=="delete")return null;let r={...t.ast,type:"query",select:[{__count:{aggregate:"count"}}],values:void 0,order:void 0,limit:void 0,offset:void 0},s=ee(r,t.dialect,{db:t.db,introspection:t.introspection,schema:t.deparseSchema});ke("MAX-AFFECTED",s,t.debug);let i=await s.execute(),o=Number((Array.isArray(i)?i[0]:i)?.__count??0);return t.ast.offset!==void 0&&(o=Math.max(o-t.ast.offset,0)),t.ast.limit!==void 0&&(o=Math.min(o,t.ast.limit)),o>e?oh(o):null}function wn(t){return t||"public"}function Zx(t,e,n){let r=wn(e);return n.views.some(s=>s.name===t&&wn(s.schema)===r)}function eT(t){let e=t.match(/\bINSERT\s+INTO\s+(?:(?:"([^"]+)"|'([^']+)')|(\w+))(?:\.(?:(?:"([^"]+)"|'([^']+)')|(\w+)))?/i);if(e)return e[6]??e[3]}function tT(t,e,n){let r=wn(e);for(let s of n.triggers){if(s.table!==t||wn(s.schema)!==r||!/\bINSTEAD\s+OF\b/i.test(s.sql))continue;let i=eT(s.sql);if(i)return i}}async function lh(t,e,n,r,s,i){if(r!=="sqlite"&&r!=="postgres"||!e.from||t.length===0||!Zx(e.from,e.schema,n))return t;let o=e.select;if(!o?.length)return t;let a=wn(e.schema),l=n.primary_keys.find(g=>g.table===e.from&&wn(g.schema)===a)?.columns??[];if(l.length===0){let g=tT(e.from,e.schema,n);g&&(l=n.primary_keys.find(y=>y.table===g&&wn(y.schema)===a)?.columns??[]);}if(l.length===0&&t[0]&&"id"in t[0]&&(l=["id"]),l.length!==1)return t;let c=l[0],u=t.map(g=>g[c]).filter(g=>g!=null);if(u.length===0)return t;let f={type:"query",from:e.from,schema:e.schema,select:o,where:{[c]:{$in:u}}},p=await ee(f,r,{db:s,introspection:n,schema:i}).execute(),h=g=>String(g[c]),m=new Map(p.map(g=>[h(g),g]));return t.map(g=>m.get(h(g))??g)}async function ch(t){let{ast:e,meta:n,db:r,dialect:s,introspection:i,deparseSchema:o,connection:a,responseSchemaMap:l,mutationPlan:c,mutationCreated:u,prefApplied:f,isMutation:d,stripNullsResponse:p,csvResponse:h,requestUrl:m,acceptHeader:g}=t,y=ee(e,s,{db:r,introspection:i,schema:o});ke("",y,t.debug);let w=await y.execute(),S,b=false,_=0;if(d&&Array.isArray(w)&&w.length>0&&w[0]&&typeof w[0]=="object"&&("numUpdatedRows"in w[0]||"numInsertedOrUpdatedRows"in w[0]||"numDeletedRows"in w[0])){b=true;let z=w[0];_=Number(z.numUpdatedRows??z.numInsertedOrUpdatedRows??z.numDeletedRows??0),S=[];}else S=w;d&&Array.isArray(S)&&S.length>0&&(S=await lh(S,e,i,s,r,o));let E=false,x,O=false,v=false,$=false,k=null;if(e.type==="rpc"&&Array.isArray(S)){let z={schema:e.schema??i.default_schema??"public",fnName:e.function??"",providedNames:gn(e),paramsType:e.paramsType,argCount:Array.isArray(e.args)?e.args.length:void 0,method:e.httpMethod,inputType:e.inputType};k=xo(i.functions,z,g);let ye=io(i.functions,z);if(ye){let Je=e.function??"",bt=S;E=!ye.returns_object&&bt.length>0&&bt.every(ai=>{let Er=Object.keys(ai);return Er.length===1&&Er[0]===Je}),E&&(x=Je,S=bt.map(ai=>ai[Je])),O=!ye.return_is_setof,$=ye.volatility!=="v",v=ye.returns_void;}}if(v){let z={"Content-Range":"0-0/*"};return f&&(z["Preference-Applied"]=f),new Response(null,{status:204,headers:z})}if(k&&Array.isArray(S)&&S.length===1){let z=S[0];if(!E&&z&&typeof z=="object"&&!Array.isArray(z)&&!(z instanceof Uint8Array)){let bt=Object.keys(z);bt.length===1&&(z=z[bt[0]]);}let ye=Zm(z,k.isBinary),Je={"Content-Type":Xm(k.mediaType),"Content-Range":"0-0/*","Content-Length":String(ye.byteLength)};return f&&(Je["Preference-Applied"]=f),n?.head?new Response(null,{status:200,headers:Je}):new Response(ye,{status:200,headers:Je})}let N=Array.isArray(S);N&&!E&&(S=zn({rows:S,ast:e,connection:a,responseSchemaMap:l,mutationNullify:{meta:n,mutationPlan:c}})),d&&N&&e.order&&e.order.length>0&&(S=_o(S,e.order));let H=N?S:[],V=H.length,B=e.offset??0;if(d&&b){if(n?.cardinality==="one"){if(_===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(_>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${_} rows`,null)}let z=rt(e,"no-return",c.appliedResolution,u),ye={"Content-Type":"application/json; charset=utf-8","Content-Range":Kt(e,n,_)};return f&&(ye["Preference-Applied"]=f),new Response(null,{status:z,headers:ye})}let C;if(kc(n)&&(d?C=V:e.type==="rpc"?B===0&&V<(e.limit??Number.POSITIVE_INFINITY)?C=V:$&&(C=await Cc(r,e,s,i)):C=await Cc(r,e,s,i)),n?.cardinality==="one"||O){if(V===0)return T(406,"PGRST116","Cannot coerce the result to a single JSON object","The result contains 0 rows",null);if(V>1)return T(406,"PGRST116","Cannot coerce the result to a single JSON object",`The result contains ${V} rows`,null);let z=200;d&&(z=rt(e,"representation",c.appliedResolution,u));let ye=p?bn(H[0]):H[0],Je=Rt(ye),bt=new TextEncoder().encode(Je),Er=n?.cardinality==="one"?"application/vnd.pgrst.object+json":"application/json",Ca={"Content-Type":p?`${Er};nulls=stripped; charset=utf-8`:`${Er}; charset=utf-8`,"Content-Range":Im(e,d,B,C),"Content-Length":String(bt.byteLength)};return f&&(Ca["Preference-Applied"]=f),n?.head?new Response(null,{status:z,headers:Ca}):new Response(bt,{status:z,headers:Ca})}if(C!==void 0&&B>0&&V===0&&B>=C){let z=JSON.stringify({code:"PGRST103",details:`An offset of ${B} was requested, but there are only ${C} rows.`,hint:null,message:"Requested range not satisfiable"}),ye=new TextEncoder().encode(z),Je={"Content-Type":"application/json; charset=utf-8","Content-Range":`*/${C}`,"Content-Length":String(ye.byteLength)};return f&&(Je["Preference-Applied"]=f),new Response(ye,{status:416,headers:Je})}let oe;d&&(e.type==="insert"||e.type==="upsert"||e.type==="delete")?oe=C!==void 0?`*/${C}`:"*/*":d&&n?.return!=="representation"?oe=C!==void 0?`*/${C}`:"*/*":V>0?oe=ft(B,V,C):oe=C!==void 0?`*/${C}`:"*/*";let he=200;d?he=rt(e,"representation",c.appliedResolution,u):C!==void 0&&(B+V<C||B>0)&&(he=206);let Le=p?bn(S):S,vn=Array.isArray(Le)?Le:[Le];if(h&&E&&x!==void 0){let z=x;vn=vn.map(ye=>({[z]:ye}));}let oi=h?Eo(vn):Rt(Le),Ra=new TextEncoder().encode(oi),$t={"Content-Type":h?"text/csv; charset=utf-8":p?"application/vnd.pgrst.array+json;nulls=stripped; charset=utf-8":"application/json; charset=utf-8","Content-Range":oe,"Content-Length":String(Ra.byteLength)};if(!d&&e.from&&m){let z=$m(`/${e.from}`,new URL(m).search);z&&($t["Content-Location"]=z);}return f&&($t["Preference-Applied"]=f),n?.head?new Response(null,{status:he,headers:$t}):new Response(Ra,{status:he,headers:$t})}var Qn=Symbol("lite-internal-request");function uh(t){return t==="snake_case"?"__":"."}function fh(t,e){let n=new Set;for(let r of t.tables)r.schema&&n.add(r.schema);for(let r of t.views)r.schema&&n.add(r.schema);if(e?.deparseSchema)for(let r of e.deparseSchema.values())r?.schema&&n.add(r.schema);for(let r of e?.internalSchemas??[])n.add(r);return n}function dh(t){let e=new Set(t.exposedSchemas??["public"]),n=()=>[...e].sort().join(", ");if(t.explicitProfileSchema!==void 0&&!e.has(t.explicitProfileSchema))return T(406,"PGRST106",`Invalid schema: ${t.explicitProfileSchema}`,null,`Only the following schemas are exposed: ${n()}`);let r=t.isRpc?-1:t.relation.indexOf(t.separator);if(r>0){let s=t.relation.slice(0,r);if(t.knownSchemas.has(s)&&!e.has(s)){let i=t.relation.slice(r+t.separator.length);return T(404,"PGRST205",`Could not find the table '${s}.${i}' in the schema cache`,null,null)}}return null}var nT={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"]},ph=t=>{let e=async(n,r)=>{let{app:s}=n.var,i=s.connection;if(!s.config.api?.enabled)return n.notFound();let{relation:o,isRpc:a}=r;if(a&&!i.supportsRpc)return T(404,"PGRST202",`Could not find the function public.${o} in the schema cache`,null,null);if(a){let g=n.req.method.toUpperCase();if(!["GET","POST","HEAD","OPTIONS"].includes(g))return T(405,"PGRST101",`Cannot use the ${g} method on RPC`,null,null)}let l=await i.introspect({useCache:true});if(!a&&i.config.introspection?.exclude_tables?.some(g=>ro(o,g,"sql")))return n.notFound();if(!(Qn in n.req.raw)){let g=i.config.translation,y=uh(g?.schemas?.approach),w=[];s.config.auth?.enabled&&w.push("auth"),s.config.storage?.enabled&&w.push("storage");let S=n.req.method.toUpperCase(),b=n.req.header("Content-Profile"),_=n.req.header("Accept-Profile"),E=S==="OPTIONS"?b??_:["POST","PUT","PATCH","DELETE"].includes(S)?b:_,x=dh({relation:o,explicitProfileSchema:E,exposedSchemas:s.config.api?.schemas,knownSchemas:fh(l,{deparseSchema:g?.deparse?.schema,internalSchemas:w}),separator:y,isRpc:a});if(x)return x}if(!(Qn in n.req.raw)&&n.req.method!=="OPTIONS"){let g=n.var.ignoreAuthorization?void 0:n.req.header("Authorization");if(g||!n.var.apiKeyType){let y=await go(g,{jwtSecret:s.config.auth?.jwt_secret,anonymousEnabled:s.config.api?.anonymous_enabled!==false});if(y.kind==="error")return y.response;y.payload&&(n.set("userId",y.payload.sub),n.set("sessionId",y.payload.session_id),n.set("jwt",y.payload));}}if(a&&n.req.method==="OPTIONS"){let g=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??l.default_schema??"public",y=Ml(l.functions,{schema:g,fnName:o,method:"OPTIONS",providedNames:[]});if(y)return T(404,"PGRST202",y.message,y.details,y.hint);let w=Ht(l.functions??[],{schema:g,fnName:o,providedNames:[]}),S=w.length>0&&w.every(b=>b.volatility!=="v");return n.header("Allow",S?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST"),n.body(null,200)}if(!a&&n.req.method==="OPTIONS"){let g=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=b=>{let _=b||"public";return i.dialect==="sqlite"?_===g||_==="public"||_==="":_===g},w=l.views.find(b=>b.name===o&&y(b.schema)),S=!w&&l.tables.find(b=>b.name===o&&b.type!=="view"&&y(b.schema));if(S||w){let b=new Set(["OPTIONS","GET","HEAD"]);if(S)b.add("POST").add("PUT").add("PATCH").add("DELETE");else {let E=false,x=false,O=false,v=(B,C)=>`${B||"public"}\0${C}`,$=new Set,k=w.schema||"public",N=await i.viewOptionsMetadata(o,k).catch(()=>null);if(N){E=N.canInsert,x=N.canUpdate,O=N.canDelete;for(let B of N.baseTables)$.add(v(B.schema,B.name));}else {let B=l.triggers.filter(he=>he.table===o&&y(he.schema)),C=he=>B.some(Le=>new RegExp(`instead\\s+of\\s+${he}`,"i").test(Le.sql));E=C("insert"),x=C("update"),O=C("delete");let oe=w?.sql??"";for(let he of l.tables){if(he.type==="view")continue;let Le=he.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");new RegExp(`\\b${Le}\\b`,"i").test(oe)&&$.add(v(he.schema,he.name));}}let H=new Set(l.columns.filter(B=>B.table===o&&y(B.schema)).map(B=>B.name)),V=l.tables.some(B=>{if(B.type==="view"||!$.has(v(B.schema,B.name)))return false;let C=l.columns.filter(oe=>oe.table===B.name&&(oe.schema||"public")===(B.schema||"public")&&oe.is_primary_key);return C.length>0&&C.every(oe=>H.has(oe.name))});E&&b.add("POST"),x&&b.add("PATCH"),O&&b.add("DELETE"),E&&x&&V&&b.add("PUT");}let _=["OPTIONS","GET","HEAD","POST","PUT","PATCH","DELETE"].filter(E=>b.has(E));return n.header("Allow",_.join(",")),n.body(null,200)}}let{dialect:u}=i,f=i.config.translation?.deparse?.schema,d=wm(f,l,u),p=n.var.jwt,h={auth:{uid:n.var.userId??null,role:p?.role||"anon",jwt:p??null}},m;try{let g=n.req.header("Content-Profile")??n.req.header("Accept-Profile")??"public",y=new Set(l.columns.filter(k=>{if(k.table!==o)return !1;let N=k.schema||"public";return u==="sqlite"?N===g||N==="public"||N==="":N===g}).map(k=>k.name));m=await Li(n.req.raw,{basePath:"/rest/v1",parentColumns:y,resolveFilters:(k,N,H)=>Ur(k,N,H,y)}),m=await i.onPostgrestAST(m,h);let w=m.function,S=!1;if(a&&w){let k={schema:m.schema??l.default_schema??"public",fnName:w,method:n.req.method.toUpperCase(),providedNames:gn(m),paramsType:m.paramsType,inputType:m.inputType,rawKind:Pp(n.req.header("Content-Type"))},N=Ml(l.functions,k);if(N)return T(404,"PGRST202",N.message,N.details,N.hint);let H=Op(l.functions,k);if(H)return T(300,"PGRST203",H.message,H.details,H.hint);if(k.method==="OPTIONS"){let V=io(l.functions,{schema:k.schema,fnName:k.fnName,providedNames:k.providedNames,paramsType:k.paramsType}),B=V&&V.volatility!=="v"?"OPTIONS,GET,HEAD,POST":"OPTIONS,POST";return new Response(null,{status:200,headers:{Allow:B,"Access-Control-Allow-Origin":"*"}})}S=xo(l.functions,{schema:k.schema,fnName:k.fnName,providedNames:k.providedNames,paramsType:k.paramsType,argCount:Array.isArray(m.args)?m.args.length:void 0,method:k.method,inputType:k.inputType},n.req.header("Accept"))!==null;}t?.debug&&console.log(vc.default.dim("[POSTGREST:AST]"),m);let b=Km({ast:m,dialect:u,introspection:l,apiConfig:s.config.api,acceptHeader:n.req.header("Accept")??"application/json",allowRawMedia:S,preferHeader:n.req.header("Prefer"),httpMethod:n.req.method.toUpperCase(),rangeHeader:n.req.header("Range")});if(b instanceof Response)return b;m=b.ast;let{meta:_,mutationPlan:E,isMutation:x,stripNullsResponse:O,csvResponse:v,planEnabled:$}=b;return await i.withContext(h,async k=>{let N=n.req.header("Accept")??"application/json";if($&&Tm(N)){let $t=ee(m,u,{db:k,introspection:l,schema:f}).compile();return t?.debug&&console.info(vc.default.dim(`[POSTGREST:PLAN] ${$t.sql}
86
+ - ${JSON.stringify([...$t.parameters])}`)),Pm(N,$t)}let H=x?await Hm(k,m,u,l,E):void 0,V=ws(_,E.appliedResolution),B={ast:m,meta:_,db:k,dialect:u,introspection:l,deparseSchema:f,connection:i,responseSchemaMap:d,mutationPlan:E,mutationCreated:H,prefApplied:V,isMutation:x,stripNullsResponse:O,csvResponse:v,acceptHeader:N,requestUrl:n.req.url,debug:t?.debug},C=await ah(B);if(C)return C;let oe=await th(B);if(oe)return oe;let he=await nh(B);if(he)return he;let Le=await rh(B);if(Le)return Le;let vn=await ih(B);if(vn)return vn;let oi=await ch(B);return a&&u==="postgres"?await Qm(k,oi):oi},{forceRollback:t?.forceRollback===!0,rpc:a&&u==="postgres"?{method:n.req.method.toUpperCase(),path:`/rpc/${o}`,readOnly:["GET","HEAD"].includes(n.req.method.toUpperCase()),requestHeaders:Object.fromEntries(n.req.raw.headers)}:void 0})}catch(g){return zm(g,{connection:i,introspection:l,vars:h,ast:m})}};return new Te().all("/rpc/:function",n=>e(n,{relation:n.req.param("function"),isRpc:true})).all("/:relation",n=>e(n,{relation:n.req.param("relation"),isRpc:false})).use(async(n,r)=>{if(n.req.method==="GET"&&n.req.path.endsWith("/")){if(n.var.apiKeyType==="publishable")return n.json({message:"You cannot consume this service"},403);let{app:s}=n.var,i=n.req.header("Accept-Profile")??n.req.header("Content-Profile")??null;if(i){let o=new Set(s.config.api?.schemas??["public"]);if(o.size>0&&!o.has(i)){let a=[...o].sort().join(", ");return T(406,"PGRST106",`Invalid schema: ${i}`,null,`Only the following schemas are exposed: ${a}`)}}return n.json(nT)}await r();}).all("*",n=>T(404,"PGRST125","Invalid path specified in request URL",null,null))};var D=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";}withInternalError(n){return this.cause=n,this}toJSON(){return {code:this.status,error_code:this.code,msg:this.message,...this.details}}},dt=()=>new D(400,"invalid_credentials","Invalid login credentials"),mh=()=>new D(400,"email_not_confirmed","Email not confirmed"),hh=(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 D(422,"weak_password",r.join(" "),{weak_password:{reasons:n}})},gh=(t="Access token is required")=>new D(401,"no_authorization",t),Sn=()=>new D(401,"no_authorization","This endpoint requires a valid Bearer token"),Ss=t=>new D(403,"bad_jwt",t),Oc=()=>Ss("invalid JWT: unable to parse or verify signature, token is malformed: token contains an invalid number of segments"),Pc=t=>Ss(`invalid JWT: unable to parse or verify signature, token is malformed: could not JSON decode header: ${t}`),yh=()=>Ss("invalid JWT: unable to parse or verify signature, token signature is invalid: signature is invalid"),bh=()=>Ss("invalid JWT: unable to parse or verify signature, token has invalid claims: token is expired"),$c=()=>Ss("invalid claim: missing sub claim"),Nc=()=>new D(400,"bad_jwt","invalid claim: sub claim must be a UUID");var wh=()=>new D(403,"user_not_found","User from sub claim in JWT does not exist"),Sh=()=>new D(403,"session_not_found","Session from session_id claim in JWT does not exist"),_h=()=>new D(422,"user_already_exists","User already registered"),Eh=()=>new D(422,"email_exists","A user with this email address has already been registered"),Ro=()=>new D(422,"signup_disabled","Signups not allowed for this instance"),xh=()=>new D(400,"email_provider_disabled","Email signups are disabled"),Th=()=>new D(422,"otp_disabled","Signups not allowed for otp"),Rh=()=>new D(422,"same_password","New password should be different from the old password."),_n=()=>new D(403,"otp_expired","Email link is invalid or has expired"),K=(t,e=422)=>new D(e,"validation_failed",t);var _s=t=>new D(400,"bad_json",t),Ic=()=>new D(400,"validation_failed","Refresh token is not valid"),Yn=()=>new D(400,"refresh_token_not_found","Invalid Refresh Token: Refresh Token Not Found"),Co=(t,e)=>new D(400,"refresh_token_already_used","Invalid Refresh Token: Already Used",void 0,{...t?{"Sb-Auth-Session-Id":t}:{},...e?{"Sb-Auth-User-Id":e}:{}}),Ch=()=>new D(401,"session_not_found","Invalid Refresh Token: Already Used"),Dc=(t,e,n)=>new D(400,"session_expired",t==="inactivity"?"Invalid Refresh Token: Session Expired (Inactivity)":"Invalid Refresh Token: Session Expired",void 0,{...e?{"Sb-Auth-Session-Id":e}:{},...n?{"Sb-Auth-User-Id":n}:{}}),kh=()=>new D(422,"anonymous_provider_disabled","Anonymous sign-ins are disabled"),Ah=()=>new D(400,"invalid_credentials","unsupported_grant_type"),ko=()=>new D(429,"over_email_send_rate_limit","For security purposes, you can only request this after 59 seconds."),Ao=t=>new D(400,"bad_oauth_state",t),jc=t=>new D(400,"bad_oauth_callback",t);var vo=(t="invalid flow state, no valid flow state found")=>new D(404,"flow_state_not_found",t),vh=()=>new D(422,"flow_state_expired","invalid flow state, flow state has expired"),Oo=()=>new D(400,"flow_state_already_used","State has already been used"),Oh=t=>new D(400,"bad_code_verifier",t),Ph=t=>new D(422,"provider_email_needs_verification",t),$h=()=>new D(403,"user_banned","User is banned"),Nh=()=>new D(404,"user_not_found","User identified by token not found"),Ih=()=>new D(404,"invite_not_found","Invite not found"),Es=t=>new D(500,"unexpected_failure",t),Dh=t=>Es(`Unable to exchange external code: ${t.slice(0,4)}`),jh=()=>Es("Error getting user profile from external provider");async function Fc(t,e,n){let r=new TextEncoder().encode(e),s=Math.floor(Date.now()/1e3);return new SignJWT({...t,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}async function Lh(t,e){let n=t.split(".");if(n.length!==3||n.some(i=>i===""))throw Oc();let r=iT(n[0]);if(r)throw r;let s=new TextEncoder().encode(e);try{let{payload:i}=await jwtVerify(t,s,{algorithms:["HS256"]});return i}catch(i){throw i instanceof errors.JWTExpired?bh():i instanceof errors.JWSSignatureVerificationFailed?yh():i instanceof errors.JWSInvalid||i instanceof errors.JWTInvalid?Oc():i}}function iT(t){let e=oT(t);if(!e)return Pc("unexpected end of JSON input");let n=aT(e);try{return JSON.parse(new TextDecoder("utf-8").decode(e)),null}catch{return Pc(Uc(n))}}function oT(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 aT(t){let e="";for(let n of t)e+=String.fromCharCode(n);return e}var lT={n:"null",t:"true",f:"false"};function Uc(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=lT[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 ${Lc(n[i])} in literal ${s} (expecting '${s[i]}')`}return `invalid character ${Lc(n[s.length]??" ")} after top-level value`}return r==="{"||r==="["||r==='"'||r==="-"||r>="0"&&r<="9"?"":`invalid character ${Lc(r)} looking for beginning of value`}function Lc(t){let e=t.codePointAt(0)??0;return e>=32&&e<127?`'${t}'`:`'\\u${e.toString(16).padStart(4,"0")}'`}var cT=10,uT=4,fT=4,dT=31;function pT(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(dT,Math.max(fT,Math.trunc(n)))}return t.RUN_SPEC==="1"?uT:cT}async function xs(t){return Fh.hash(t,pT())}async function Mc(t,e){return Fh.compare(t,e)}function Uh(t,e=6,n=[]){let r=[];return t.length<e&&r.push("length"),n.length>0&&n.some(s=>!mT(t,s))&&r.push("characters"),r}function mT(t,e){for(let n of t)if(e.includes(n))return true;return false}function pt(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 Bc(){let t=crypto.getRandomValues(new Uint8Array(32));return Bh(t)}async function st(t,e){let n=new TextEncoder().encode(t.toLowerCase()+e),r=await crypto.subtle.digest("SHA-256",n);return Bh(new Uint8Array(r))}function Bh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function qc(){return v7()}function me(){return v7()}var hT=["iss","sub","aud","iat","exp","name","family_name","given_name","middle_name","nickname","preferred_username","profile","picture","website","gender","birthdate","zoneinfo","locale","updated_at","email","phone","custom_claims","full_name","avatar_url","slug","provider_id","user_name"];function gT(t){return !!(t==null||t===""||typeof t=="number"&&t===0||Array.isArray(t)&&t.length===0||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)}function qh(t){let e={};for(let n of hT){let r=t[n];gT(r)||(e[n]=r);}return e.email_verified=t.email_verified??false,e.phone_verified=t.phone_verified??false,e}var Hh=43,Wh=128,yT="PKCE flow requires code_challenge_method and code_challenge",bT=/^[a-zA-Z._~0-9-]+$/;function wT(t){let e=t.length;if(e<Hh||e>Wh)throw K(`code challenge has to be between ${Hh} and ${Wh} characters`,400);if(!bT.test(t))throw K("code challenge can only contain alphanumeric characters, hyphens, periods, underscores and tildes",400);return true}function Hc(t){return t.toLowerCase()}var ST=new Set(["s256","plain"]);function Kh(t,e){if(e===""!=(t===""))throw K(yT,400);if(e!==""&&(wT(e),!ST.has(Hc(t))))throw K("Invalid code_challenge_method",400)}function _T(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ET(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return _T(new Uint8Array(n))}async function Jh(t,e,n){return e.toLowerCase()==="s256"?await ET(n)===t:n===t}var xT="github.com",Gh="api.github.com",TT=["user:email"];function RT(t){let e=t?t.split(","):[];return [...TT,...e].join(" ")}function Wc(t,e){let n=JSON.parse(e);if(typeof n.error=="string"&&n.error!=="")throw new Error(`${t}: token endpoint returned error ${n.error}`,{cause:e});if(!n.access_token)throw new Error(`${t}: server response missing access_token`,{cause:e});return n}function Vh(t,e){return t?t.endsWith("/")?t.slice(0,-1):t:`https://${e}`}function CT(t){let e=Vh(t,xT),n=Vh(t,Gh);return n.endsWith(Gh)||(n+="/api/v3"),{authHost:e,apiHost:n}}function zh(t){let{authHost:e,apiHost:n}=CT(t);return {id:"github",authorizeUrl({clientId:r,redirectUri:s,scopes:i,state:o,extraParams:a}){let l=new URLSearchParams({client_id:r,redirect_uri:s,scope:RT(i),state:o,...a});return `${e}/login/oauth/authorize?${l.toString()}`},async exchangeCode(r,{clientId:s,secret:i,redirectUri:o,fetch:a=globalThis.fetch}){let l=new URLSearchParams({client_id:s,client_secret:i,code:r,redirect_uri:o}),c=await a(`${e}/login/oauth/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l.toString(),signal:AbortSignal.timeout(1e4)}),u=await c.text();if(c.status<200||c.status>=300)throw new Error(`github: token endpoint returned ${c.status}`,{cause:u});return Wc("github",u)},async getUserData(r,{fetch:s=globalThis.fetch}){let i={Authorization:`Bearer ${r.access_token}`},o=()=>({headers:i,signal:AbortSignal.timeout(1e4)}),a=await s(`${n}/user`,o()),l=await a.text();if(a.status<200||a.status>=300)throw new Error(`github: /user returned ${a.status}`,{cause:l});let c=JSON.parse(l),u=await s(`${n}/user/emails`,o()),f=await u.text();if(u.status<200||u.status>=300)throw new Error(`github: /user/emails returned ${u.status}`,{cause:f});let d=JSON.parse(f);if(!Array.isArray(d))throw new Error("github: /user/emails did not return a JSON array");let p=String(c.id);return {claims:{iss:n,sub:p,name:c.name||void 0,preferred_username:c.login,avatar_url:c.avatar_url||void 0,full_name:c.name||void 0,provider_id:p,user_name:c.login,email_verified:false,phone_verified:false},emails:d.filter(h=>h.email).map(h=>({email:h.email,verified:h.verified,primary:h.primary}))}}}}var Kc="https://accounts.google.com",OT="accounts.google.com",PT="https://accounts.google.com/o/oauth2/v2/auth",$T="https://oauth2.googleapis.com/token",NT="https://www.googleapis.com/oauth2/v3/certs",IT="https://www.googleapis.com/userinfo/v2/me",DT=["email","profile"],Gc=1e4,Qh=new Map;function Yh(t,e){return createRemoteJWKSet(new URL(t),{[customFetch]:e,timeoutDuration:Gc})}function jT(t,e){if(e!==globalThis.fetch)return Yh(t,e);let n=Qh.get(t);return n||(n=Yh(t,e),Qh.set(t,n)),n}async function LT(t,e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),r=new Uint8Array(n).slice(0,n.byteLength/2),s="";for(let o of r)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")===e}function FT(t){let e=t?t.split(","):[];return [...DT,...e].join(" ")}function Jc(t){return !!(t.verified_email||t.email_verified)}function Xh(t={}){let e=t.issuer??Kc,n=e===Kc?[Kc,OT]:e,r=t.userInfoEndpoint??IT,s=t.getKey,i=t.clientIds??[];return {id:"google",authorizeUrl({clientId:o,redirectUri:a,scopes:l,state:c,extraParams:u}){let f=new URLSearchParams({client_id:o,redirect_uri:a,response_type:"code",scope:FT(l),state:c,...u});return `${PT}?${f.toString()}`},async exchangeCode(o,{clientId:a,secret:l,redirectUri:c,fetch:u=globalThis.fetch}){let f=new URLSearchParams({client_id:a,client_secret:l,code:o,redirect_uri:c,grant_type:"authorization_code"}),d=await u($T,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f.toString(),signal:AbortSignal.timeout(Gc)}),p=await d.text();if(d.status<200||d.status>=300)throw new Error(`google: token endpoint returned ${d.status}`,{cause:p});return Wc("google",p)},async getUserData(o,{fetch:a=globalThis.fetch,clientId:l}){if(o.id_token){let d=s??jT(NT,a),p=i[0]??l??void 0,{payload:h}=await jwtVerify(o.id_token,d,{issuer:n,...p?{audience:p}:{}}),m=h;if(m.at_hash){if(!o.access_token)throw new Error("oidc: id_token had at_hash but no access_token was returned");if(!await LT(o.access_token,m.at_hash))throw new Error("oidc: access token hash does not match value in ID token")}let g=m.email||"",y=Jc(m),w={};return m.hd&&(w.hd=m.hd),{emails:g?[{email:g,verified:y,primary:true}]:[],claims:{iss:m.iss,sub:m.sub,name:m.name,picture:m.picture,avatar_url:m.picture,full_name:m.name,provider_id:m.sub,custom_claims:Object.keys(w).length?w:void 0,email_verified:false,phone_verified:false}}}let c=await a(r,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(Gc)}),u=await c.text();if(c.status<200||c.status>=300)throw new Error(`google: userinfo returned ${c.status}`,{cause:u});let f=JSON.parse(u);return {emails:f.email?[{email:f.email,verified:Jc(f),primary:true}]:[],claims:{iss:r,sub:f.id,name:f.name,picture:f.picture,email:f.email,email_verified:Jc(f),avatar_url:f.picture,full_name:f.name,provider_id:f.id,phone_verified:false}}}}}function Zh(t){return (t??"").split(",").map(e=>e.trim()).filter(e=>e!=="")}var eg={github:t=>zh(t.url),google:t=>Xh({clientIds:Zh(t.client_id)})},tg=new Set(Object.keys(eg)),Vc=["apple","azure","bitbucket","discord","facebook","github","gitlab","google","kakao","keycloak","linkedin","notion","twitch","twitter","slack","spotify","workos","zoom"],zc=["snapchat","figma","fly","linkedin_oidc","slack_oidc"],UT=new Set([...Vc,...zc]);function Qc(t,e,n){let r=(t??"").toLowerCase();if(!UT.has(r))throw K(`Unsupported provider: Provider ${r} could not be found`,400);let s=e?.[r];if(!s?.enabled)throw K("Unsupported provider: provider is not enabled",400);let i=Zh(s.client_id);if(i.length===0)throw K("Unsupported provider: missing OAuth client ID",400);if(!s.secret)throw K("Unsupported provider: missing OAuth secret",400);let o=eg[r];if(!o)throw K(`Unsupported provider: provider ${r} is not yet implemented`,400);let a=o(s);return {name:r,provider:a,config:s,clientId:i[0],clientIds:i,secret:s.secret,redirectUri:s.redirect_uri||n.defaultRedirectUri,skipNonceCheck:s.skip_nonce_check??false,emailOptional:s.email_optional??false}}var ng=3e5,MT=1440*60*1e3;function $o(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.')}function BT(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function qT(t){let e="^";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"){let s=t[++n];s!==void 0?e+=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e+="\\\\";}else if(r==="*")t[n+1]==="*"?(e+=".*",n++):e+="[^./]*";else if(r==="?")e+="[^./]";else if(r==="["){let s=t.indexOf("]",n+1);if(s===-1)e+="\\[";else {let i=t.slice(n+1,s);i.startsWith("!")&&(i=`^${i.slice(1)}`),e+=`[${i}]`,n=s;}}else e+=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");}return new RegExp(`${e}$`)}function rg(t,e){let n=t.indexOf("//");if(n===-1)return e;let r=t.slice(n+2),s=r.search(/[/?#]/);s!==-1&&(r=r.slice(0,s));let i=r.lastIndexOf("@");if(i!==-1&&(r=r.slice(i+1)),r.startsWith("[")){let a=r.indexOf("]");return a===-1?r.slice(1):r.slice(1,a)}let o=r.lastIndexOf(":");return o===-1?r:r.slice(0,o)}function HT(t){let e=t,n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e);if(n){let r=n.slice(1).map(Number);return r.some(s=>s>255)?{isIp:false,isLoopback:false}:{isIp:true,isLoopback:r[0]===127}}return e.includes(":")?{isIp:true,isLoopback:e.toLowerCase()==="::1"}:{isIp:false,isLoopback:false}}var WT=/^[0-9]+$/,KT=/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/;function Yc(t,e,n){if(t==="")return false;let r;try{r=new URL(t);}catch{return false}let s=r.protocol.replace(/:$/,"").toLowerCase(),i=s==="http"||s==="https",o=rg(t,r.hostname);try{let c=new URL(e);if(c.protocol===r.protocol&&rg(e,c.hostname)===o&&(c.port===r.port||BT(o)))return !0}catch{}let a=HT(o);if(WT.test(o))return false;if(a.isIp)return a.isLoopback;if(i&&!KT.test(o))return false;let l=t.split("#")[0];for(let c of n)if(qT(c).test(l))return true;return false}var Ts=class t{constructor(e,n,r){this.repo=e;this.config=n;this.mailer=r;$o(n),this.jwtExpiry=n.jwt_expiry??3600,this.minPasswordLength=n.minimum_password_length??6,this.passwordRequiredCharacters=n.password_required_characters??GT(n.password_requirements),this.sessionTimeboxSeconds=og(n.sessions?.timebox),this.sessionInactivitySeconds=og(n.sessions?.inactivity_timeout);}jwtExpiry;minPasswordLength;passwordRequiredCharacters;sessionTimeboxSeconds;sessionInactivitySeconds;get otpLength(){return this.config.email?.otp_length??6}get otpExpirySeconds(){return this.config.email?.otp_expiry??3600}resolveEmailRedirect(e){let n=this.config.site_url??"http://localhost:3000";return e&&Yc(e,n,this.config.additional_redirect_urls??[])?e:n}async signUp(e,n,r){if(this.config.enable_signup===false)throw Ro();if(!e)throw kh();if(this.config.email?.enable_signup===false)throw xh();if(n==null||n===void 0||n==="")throw K("Signup requires a valid password",400);if(!Xn(e))throw K("Unable to validate email address: invalid format",400);if(n.length>72)throw K("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"),_h()):ko();let a=me(),l=await xs(n),c=new Date().toISOString(),u=null,f=null,d=null;i||(u=pt(this.otpLength),f=await st(e,u),d=c);let p={...r??{},email:e,email_verified:i,phone_verified:false,sub:a},h={...r??{},email:e,email_verified:false,phone_verified:false,sub:a},m=await this.repo.createUser({id:a,email:e,encrypted_password:l,confirmed_at:i?c:null,raw_user_meta_data:p,raw_app_meta_data:{provider:"email",providers:["email"]},confirmation_token:f,confirmation_sent_at:d});await this.repo.createIdentity({id:me(),provider:"email",provider_id:a,user_id:a,identity_data:h}),!i&&u&&f&&await this.mailer.sendConfirmation(e,f,u,{userId:a,redirectTo:this.config.site_url});let g=await this.repo.findIdentitiesByUserId(a),y=this.repo.parseUserJson(m),w=this.mapUserToResponse(y,g,"signup");if(i){let S=await this.createSessionForUser(y,g);return await this.createAuditLog(a,e,"user_signedup","team"),{user:w,session:S}}return await this.createAuditLog(a,e,"user_confirmation_requested","user"),{user:w}}async signInWithPassword(e,n){if(!e)throw K("missing email or phone",400);if(!n)throw dt();let r=await this.repo.findUserByEmail(e.toLowerCase());if(!r||!r.encrypted_password)throw dt();let s=this.repo.parseUserJson(r);if(!s.confirmed_at)throw mh();if(!await Mc(n,s.encrypted_password))throw dt();let o=await this.repo.findIdentitiesByUserId(r.id);return this.createSessionForUser(s,o,"user")}async refreshSession(e){if(!e)throw Ic();let n=await this.repo.findRefreshToken(e);if(!n)throw ag(e)?Yn():Ic();if(lg(n))return this.refreshWithRevokedToken(n);let r=await this.repo.findUserById(n.user_id);if(!r)throw Yn();let s=null;if(n.session_id){if(s=await this.repo.findSessionById(n.session_id),!s)throw Yn();this.assertSessionRefreshable(s);}let i=Xc(s?.updated_at,s?.refreshed_at,r.updated_at,r.last_sign_in_at);await this.repo.revokeRefreshToken(n.id);let o=qc(),a=n.session_id??me();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 Ch();if(!e.session_id)throw Co(e.session_id,e.user_id);let n=await this.repo.findRefreshTokensBySession(e.session_id),r=VT(n,e.token),s=r.filter(c=>!lg(c));if((this.config.enable_refresh_token_rotation??false)&&r.length>1)throw await this.repo.revokeRefreshTokensByIds(s.map(c=>c.id)),Co(e.session_id,e.user_id);let i=s.at(-1);if(!i)throw Co(e.session_id,e.user_id);let o=await this.repo.findUserById(e.user_id);if(!o)throw Yn();let a=await this.repo.findSessionById(e.session_id);if(!a)throw Yn();this.assertSessionRefreshable(a);let l=Xc(a.updated_at,a.refreshed_at,o.updated_at,o.last_sign_in_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 Fc({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 cg({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 Dc(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 Dc("inactivity",e.id,e.user_id)}async getUser(e){let n=await this.repo.findUserById(e);if(!n)throw dt();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 dt();let s=this.repo.parseUserJson(r),i={},o=false,a=false,l=n.data!==void 0||n.password!==void 0||n.email!==void 0;if(n.data!==void 0){let f=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};i.raw_user_meta_data=ig(f,n.data??{}),o=true;}if(n.password!==void 0){if(this.assertPasswordStrong(n.password),s.encrypted_password&&await Mc(n.password,s.encrypted_password))throw Rh();i.encrypted_password=await xs(n.password),i.recovery_token=null,i.recovery_sent_at=null,o=true,a=true;}if(n.email!==void 0)if(n.email==="")o=true;else {let f=n.email.toLowerCase();if(!Xn(f))throw K("Unable to validate email address: invalid format",400);if(o=true,f!==s.email?.toLowerCase()){let d=await this.repo.findUserByEmail(f);if(d&&d.id!==e)throw Eh();let p=new Date().toISOString(),h=s.email??"",m=pt(this.otpLength),g=await st(f,m),y=(this.config.email?.double_confirm_changes??true)&&h!=="",w=pt(this.otpLength),S=y?await st(h,w):null;i.email_change=f,i.email_change_token_current=S,i.email_change_token_new=g,i.email_change_sent_at=p,y&&S?await this.mailer.sendEmailChange(h,S,w,{userId:e,tokenNew:m,tokenHashNew:g,redirectTo:this.config.site_url,currentEmail:h,newEmail:f}):await this.mailer.sendEmailChange(f,g,m,{userId:e,redirectTo:this.config.site_url,currentEmail:h,newEmail:f});}}l||(o=true);let c=s;if(Object.keys(i).length>0){let f=await this.repo.updateUser(e,i);if(!f)throw dt();c=this.repo.parseUserJson(f);}a&&await this.createAuditLog(e,s.email??"","user_updated_password","user",false),o&&await this.createAuditLog(e,s.email??"","user_modified","user",false);let u=await this.repo.findIdentitiesByUserId(e);return this.mapUserToResponse(c,u,"user")}async signOut(e,n,r){let s=n??"local";if(!["global","local","others"].includes(s))throw K(`Unsupported logout scope "${s}"`,400);let i=await this.repo.findUserById(r);if(!i)throw dt();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 K("One of email or phone must be set",400);if(e=e.toLowerCase(),!Xn(e))throw K("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(e),s=!r;if(!r&&n?.shouldCreateUser!==false){let l=me(),c=await xs(Bc()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:me(),provider:"email",provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}if(!r)throw Th();let i=pt(this.otpLength),o=await st(e,i),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 dt();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async requestMagicLink(e,n){if(!e)throw K("Password recovery requires an email",422);if(e=e.toLowerCase(),!Xn(e))throw K("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 Ro();let l=me(),c=await xs(Bc()),u=new Date().toISOString();r=await this.repo.createUser({id:l,email:e,encrypted_password:c,confirmed_at:u,raw_app_meta_data:{provider:"email",providers:["email"]},raw_user_meta_data:{email:e,email_verified:true,phone_verified:false,sub:l}}),await this.repo.createIdentity({id:me(),provider:l,provider_id:l,user_id:l,identity_data:{email:e,email_verified:false,phone_verified:false,sub:l}});}let i=pt(this.otpLength),o=await st(e,i),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 dt();let c=this.repo.parseUserJson(l),u=await this.repo.findIdentitiesByUserId(r.id);await this.createSessionForUser(c,u),await this.createAuditLog(r.id,e,"user_signedup","team");}}async verifyOtp(e){let n;if(e.token_hash)n=e.token_hash;else if(e.email&&e.token)n=await st(e.email.toLowerCase(),e.token);else throw _n();return await this.repo.transaction(async r=>{let s=this.repo;this.repo=r;try{let i=await this.findUserByTokenAndType(n,e.type),o=i?.user??null,a=i?.tokenColumn??null;if(!o||!a)throw _n();if(this.isTokenExpired(o,a))throw _n();if(e.type==="email_change"){let c=(this.config.email?.double_confirm_changes??!0)&&!!o.email?"email_change_token_current":"email_change_token_new";if(a!==c)throw _n()}if(!await this.repo.claimUserToken(o.id,a,n))throw _n();return await this.completeVerifyOtp(o,a,e.type)}finally{this.repo=s;}})}async completeVerifyOtp(e,n,r){let s=this.repo.parseUserJson(e),i=new Date().toISOString(),o={};if(s.confirmed_at||(o.confirmed_at=i),r==="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 u=(await this.repo.findIdentitiesByUserId(e.id)).find(f=>f.provider==="email");if(u){let f=typeof u.identity_data=="string"?JSON.parse(u.identity_data):{...u.identity_data??{}};await this.repo.updateIdentity(u.id,{identity_data:{...f,email:s.email_change,email_verified:true}});}else await this.repo.createIdentity({id:me(),provider:"email",provider_id:e.id,user_id:e.id,identity_data:{sub:e.id,email:s.email_change,email_verified:true,phone_verified:false}});o.raw_app_meta_data=await this.buildAppMetaDataProviders(e.id,s.raw_app_meta_data),await this.createAuditLog(e.id,s.email??"","user_modified","user",false);}else if(r==="signup"){let c=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{};o.raw_user_meta_data={...c,email_verified:true};let u=await this.repo.findIdentitiesByUserId(e.id);for(let f of u){let d=typeof f.identity_data=="string"?JSON.parse(f.identity_data):{...f.identity_data??{}};await this.repo.updateIdentity(f.id,{identity_data:{...d,email_verified:true}});}n&&(o[n]=null);}else n&&(o[n]=null);o.last_sign_in_at=i,await this.repo.updateUser(e.id,o);let a=await this.repo.findUserById(e.id);if(!a)throw _n();let l=await this.repo.findIdentitiesByUserId(e.id);return r==="signup"&&await this.createAuditLog(e.id,a.email??"","user_signedup","team"),this.createSessionForUser(this.repo.parseUserJson(a),l,"verify",{createLoginAudit:["magiclink","recovery"].includes(r),includeLoginProviderTrait:!["magiclink","recovery"].includes(r),authenticationMethod:["email_change","magiclink","recovery","signup"].includes(r)?"otp":"password"})}async recover(e){if(!e)throw K("Password recovery requires an email",400);if(e=e.toLowerCase(),!Xn(e))throw K("Unable to validate email address: invalid format",400);let n=await this.repo.findUserByEmail(e);if(!n)return;let r=pt(this.otpLength),s=await st(e,r),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 K("Missing one of these types: signup, email_change, sms, phone_change",400);if((e==="signup"||e==="email_change")&&!n)throw K("Type provided requires an email address",400);if(!n)return;if(n=n.toLowerCase(),!Xn(n))throw K("Unable to validate email address: invalid format",400);let r=await this.repo.findUserByEmail(n);if(!r)return;let s=pt(this.otpLength),i=new Date().toISOString();if(e==="signup"){if(r.confirmed_at||!r.confirmation_sent_at)return;throw ko()}else if(e==="email_change"){if(!r.email_change)return;if(r.email_change_sent_at)throw ko();let o=await st(r.email_change,s);await this.repo.updateUser(r.id,{email_change_token_new:o,email_change_sent_at:i}),await this.mailer.sendEmailChange(r.email_change,o,s,{userId:r.id,redirectTo:this.config.site_url,currentEmail:r.email??void 0,newEmail:r.email_change});}}async reauthenticate(e){let n=await this.repo.findUserById(e);if(!n)throw gh();if(!n.email)throw K("Reauthentication requires the user to have an email or a phone number",400);let r=pt(this.otpLength),s=await st(n.email,r),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=Xc(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=me();await this.repo.createSession({id:l,user_id:e.id});let c=qc();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,s.provider??"email",s.providerTraitKey??"provider");let u=await Fc({sub:e.id,aud:e.aud||"authenticated",role:e.role||"authenticated",email:e.email??void 0,session_id:l},this.config.jwt_secret,this.jwtExpiry),f=Math.floor(Date.now()/1e3);return cg({access_token:u,refresh_token:c,token_type:"bearer",expires_in:this.jwtExpiry,expires_at:f+this.jwtExpiry,user:this.mapUserToResponse(a,n,r)},l,e.id)}assertPasswordStrong(e){let n=Uh(e,this.minPasswordLength,this.passwordRequiredCharacters);if(n.length>0)throw hh(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:e.provider,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}static SENT_AT_COLUMN={confirmation_token:"confirmation_sent_at",recovery_token:"recovery_sent_at",email_change_token_current:"email_change_sent_at",email_change_token_new:"email_change_sent_at",reauthentication_token:"reauthentication_sent_at"};isTokenExpired(e,n){let r=t.SENT_AT_COLUMN[n];if(!r)return false;let s=e[r];if(!s)return false;let i=new Date(s).getTime();return Number.isNaN(i)?false:Date.now()-i>this.otpExpirySeconds*1e3}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","email_change_token_current"];case "reauthentication":return ["reauthentication_token"];default:return []}}async createAuditLog(e,n,r,s,i=true,o="email",a="provider"){let l={action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s};i&&(l.traits={[a]:o}),await this.repo.createAuditLogEntry({id:me(),payload:l});}async createAuditLogWithTraits(e,n,r,s,i){await this.repo.createAuditLogEntry({id:me(),payload:{action:r,actor_id:e,actor_username:n,actor_via_sso:false,log_type:s,traits:i}});}async getExternalProviderRedirectUrl(e,n){let r=e.provider??"",s=Qc(r,this.config.external,{defaultRedirectUri:n.defaultRedirectUri}),i=e.invite_token??"";if(i!==""&&!await this.repo.findUserByToken("confirmation_token",i))throw Nh();let o=e.code_challenge??"",a=e.code_challenge_method??"";Kh(a,o);let l=this.resolveOAuthReferrer(e.redirect_to,n.refererHeader),c={};for(let[d,p]of Object.entries(e))p!==void 0&&(["provider","scopes","code_challenge","code_challenge_method"].includes(d)||(c[d]=p));let u=me(),f=o!==""?me():null;return await this.repo.deleteFlowStatesCreatedBefore(new Date(Date.now()-MT).toISOString()),await this.repo.createFlowState({id:u,auth_code:f,authentication_method:"oauth",code_challenge:o!==""?o:null,code_challenge_method:o!==""?Hc(a):null,provider_type:s.name,invite_token:i!==""?i:null,referrer:l,email_optional:s.emailOptional}),s.provider.authorizeUrl({clientId:s.clientId,redirectUri:s.redirectUri,scopes:e.scopes,state:u,extraParams:c})}async loadOAuthFlowState(e){if(!e)throw jc("OAuth state parameter missing");if(!ag(e))throw Ao("OAuth state parameter is invalid");let n=await this.repo.findFlowStateById(e);if(!n)throw Ao("OAuth state not found or expired");if(Date.now()-Date.parse(n.created_at)>ng)throw Ao("OAuth state has expired");if(n.code_challenge!==null&&n.user_id!==null)throw Oo();return n}resolveOAuthRedirectTarget(e){return e.referrer||this.config.site_url||"http://localhost:3000"}async handleExternalProviderCallback(e,n,r){let s=this.resolveOAuthRedirectTarget(e),i=e.provider_type,o=n.code;if(!o)throw jc("OAuth callback with missing authorization code missing");let a=Qc(i,this.config.external,{defaultRedirectUri:r.defaultRedirectUri}),l;try{l=await a.provider.exchangeCode(o,{clientId:a.clientId,secret:a.secret,redirectUri:a.redirectUri});}catch(g){throw Dh(o).withInternalError(g)}let c;try{c=await a.provider.getUserData(l,{clientId:a.clientId});}catch(g){throw jh().withInternalError(g)}if(c.emails.length===0&&!e.email_optional)throw Es("Error getting user email from external provider");let u,f=false;for(let g of c.emails)if(u=g.email,f=g.verified,g.primary)break;let d={...c.claims,email:u,email_verified:f},p=qh(d),h=d.sub??"",m=await this.repo.transaction(async g=>{let y=this.repo;this.repo=g;try{let w=e.invite_token??"";if(w!==""){let v=await this.processInvite(w,i,c.emails,p,h);return await this.issueOAuthCallbackResult(v,e,l,s)}let S=await this.determineAccountLinking(c.emails,i,h),b,_,E=!1;if(S.decision==="AccountExists")b=S.user,_=S.identity.id,await this.repo.updateIdentity(_,{identity_data:p,last_sign_in_at:new Date().toISOString()}),await this.updateUserMetaDataAndProviders(b.id,p);else if(S.decision==="LinkAccount"){b=S.user;let v=await this.repo.createIdentity({id:me(),provider:i,provider_id:h,user_id:b.id,identity_data:p});_=v.id,await this.updateUserMetaDataAndProviders(b.id,p),await this.createAuditLogWithTraits(b.id,b.email??"","identity_linked","user",{identity_id:v.id,provider:i,provider_id:h});}else if(S.decision==="CreateAccount"){if(this.config.enable_signup===!1)throw Ro();E=!0;let v=me();b=await this.repo.createUser({id:v,email:S.candidateEmail.email||null,raw_app_meta_data:{provider:i,providers:[i]},raw_user_meta_data:p}),_=(await this.repo.createIdentity({id:me(),provider:i,provider_id:h,user_id:v,identity_data:p})).id;}else throw Es("Multiple accounts with the same email address in the same linking domain detected: default");let x=this.repo.parseUserJson(await this.repo.findUserById(b.id));if(JT(x))throw $h();if(!(e.email_optional&&S.candidateEmail.email==="")&&!x.confirmed_at){await this.removeUnconfirmedIdentities(x.id,_,p);let v=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??!1);if(S.candidateEmail.verified||v)await this.createAuditLog(x.id,S.candidateEmail.email,"user_signedup","team",!0,i),await this.repo.updateUser(x.id,{confirmed_at:new Date().toISOString(),raw_user_meta_data:{...p,email_verified:!0}});else {let $=!1;if(S.candidateEmail.email){let k=pt(this.otpLength),N=await st(S.candidateEmail.email,k),H=new Date().toISOString();await this.repo.updateUser(x.id,{confirmation_token:N,confirmation_sent_at:H}),await this.mailer.sendConfirmation(S.candidateEmail.email,N,k,{userId:x.id,redirectTo:this.config.site_url}),$=!0;}return {commitError:Ph($?`Unverified email with ${i}. A confirmation email has been sent to your ${i} email`:`Unverified email with ${i}. Verify the email with ${i} in order to sign in`)}}}else await this.createAuditLog(x.id,x.email??"","login","account",!0,i);return await this.issueOAuthCallbackResult(x,e,l,s)}finally{this.repo=y;}});if(m.commitError)throw m.commitError;return m}async issueOAuthCallbackResult(e,n,r,s){if(n.code_challenge!=null&&n.auth_code!=null){if(!await this.repo.claimFlowStateForPkce(n.id,{user_id:e.id,provider_access_token:r.access_token??"",provider_refresh_token:r.refresh_token??"",auth_code_issued_at:new Date().toISOString()}))throw Oo();let m=new URL(s);return m.searchParams.set("code",n.auth_code),{commitError:void 0,type:"pkce",redirectUrl:m.toString()}}let o=this.repo.parseUserJson(await this.repo.findUserById(e.id)),a=await this.repo.findIdentitiesByUserId(e.id),l=await this.createSessionForUser(o,a,"session",{createLoginAudit:false});if(!await this.repo.deleteFlowState(n.id))throw Oo();let u={access_token:l.access_token,expires_at:String(l.expires_at),expires_in:String(l.expires_in),provider_token:r.access_token??""};r.refresh_token&&(u.provider_refresh_token=r.refresh_token),u.refresh_token=l.refresh_token,u.sb="",u.token_type=l.token_type;let d=Object.keys(u).sort().map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(u[h])}`).join("&"),p=new URL(s);return p.hash=d,{commitError:void 0,type:"implicit",redirectUrl:p.toString()}}async processInvite(e,n,r,s,i){let o=await this.repo.findUserByToken("confirmation_token",e);if(!o)throw Ih();let a=this.repo.parseUserJson(o),l=(a.email??"").toLowerCase();if(!r.some(f=>f.email.toLowerCase()===l))throw K("Invited email does not match emails from external provider",400);let u=await this.repo.createIdentity({id:me(),provider:n,provider_id:i,user_id:a.id,identity_data:s});return await this.updateUserMetaDataAndProviders(a.id,s),await this.createAuditLog(a.id,a.email??"","invite_accepted","account",true,n),await this.removeUnconfirmedIdentities(a.id,u.id,s),await this.repo.updateUser(a.id,{confirmation_token:null,confirmed_at:new Date().toISOString(),raw_user_meta_data:{...s,email_verified:true}}),this.repo.parseUserJson(await this.repo.findUserById(a.id))}async exchangePkceCode(e,n){if(!e||!n)throw K("invalid request: both auth code and code verifier should be non-empty",400);let r=await this.repo.findFlowStateByAuthCode(e);if(!r||!r.user_id)throw vo();if(Date.now()-Date.parse(r.created_at)>ng)throw vh();if(!await Jh(r.code_challenge??"",r.code_challenge_method??"",n))throw Oh("code challenge does not match previously saved code verifier");return {...await this.repo.transaction(async o=>{let a=this.repo;this.repo=o;try{if(!await this.repo.deleteFlowState(r.id))throw vo();let c=await this.repo.findUserById(r.user_id);if(!c)throw vo();let u=this.repo.parseUserJson(c),f=await this.repo.findIdentitiesByUserId(c.id);return await this.createSessionForUser(u,f,"session",{includeLoginProviderTrait:!0,provider:r.provider_type,providerTraitKey:"provider_type"})}finally{this.repo=a;}}),...r.provider_access_token?{provider_token:r.provider_access_token}:{},...r.provider_refresh_token?{provider_refresh_token:r.provider_refresh_token}:{}}}resolveOAuthReferrer(e,n){let r=this.config.site_url??"http://localhost:3000",s=this.config.additional_redirect_urls??[];return e&&Yc(e,r,s)?e:n&&Yc(n,r,s)?n:r}async updateUserMetaDataAndProviders(e,n){let r=await this.repo.findUserById(e);if(!r)return;let s=this.repo.parseUserJson(r),i=typeof s.raw_user_meta_data=="object"?s.raw_user_meta_data:{},o=ig(i,n),a=await this.buildAppMetaDataProviders(e,s.raw_app_meta_data);await this.repo.updateUser(e,{raw_user_meta_data:o,raw_app_meta_data:a});}async buildAppMetaDataProviders(e,n){let r=typeof n=="object"&&n?{...n}:{},i=[...await this.repo.findIdentitiesByUserId(e)].sort((a,l)=>Date.parse(a.created_at)-Date.parse(l.created_at)),o=[];for(let a of i)o.includes(a.provider)||o.push(a.provider);return r.providers=o,o.length>0&&(r.provider=o[0]),r}async removeUnconfirmedIdentities(e,n,r){await this.repo.deleteIdentitiesExcept(e,n);let s=await this.repo.findUserById(e),i=await this.buildAppMetaDataProviders(e,s?this.repo.parseUserJson(s).raw_app_meta_data:{});await this.repo.updateUser(e,{raw_user_meta_data:r,raw_app_meta_data:i,encrypted_password:null});}async determineAccountLinking(e,n,r){let s=e.find(p=>p.primary),i=s?{email:s.email.toLowerCase(),verified:s.verified}:{email:"",verified:false},o=r?await this.repo.findIdentityByProviderAndId(n,r):null;if(o){let p=await this.repo.findUserById(o.user_id);if(!p)throw new Error("Database error finding user for existing identity");return i={email:(p.email??"").toLowerCase(),verified:i.verified},{decision:"AccountExists",user:p,identity:o,candidateEmail:i}}let a=!(this.config.email?.enable_confirmations??this.config.enable_confirmations??false),l=Array.from(new Set(e.filter(p=>p.verified||a).map(p=>p.email.toLowerCase())));if(l.length===0)return i.email&&await this.repo.findUserByEmail(i.email)&&(i={...i,email:""}),{decision:"CreateAccount",candidateEmail:i};let c=await this.repo.findIdentitiesByEmails(l),u=Array.from(new Set(c.map(p=>p.user_id))),d=(await Promise.all(u.map(p=>this.repo.findUserById(p)))).filter(p=>p!==null).filter(p=>!sg(p));if(d.length===0){let p=await Promise.all(l.map(m=>this.repo.findUserByEmail(m))),h=new Map;for(let m of p)m&&!sg(m)&&h.set(m.id,m);d=Array.from(h.values());}return d.length===0?{decision:"CreateAccount",candidateEmail:i}:d.length>1?{decision:"MultipleAccounts"}:{decision:"LinkAccount",user:d[0],candidateEmail:i}}};function sg(t){return t.is_sso_user===true||t.is_sso_user===1}function JT(t){return t.banned_until?Date.parse(t.banned_until)>Date.now():false}function ig(t,e){let n={...t};for(let[r,s]of Object.entries(e))s===null?delete n[r]:n[r]=s;return n}function GT(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 og(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 Xn(t){return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function ag(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 lg(t){return t.revoked===true||t.revoked===1}function VT(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 Xc(...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 cg(t,e,n){return Object.defineProperties(t,{session_id:{value:e,enumerable:false},user_id:{value:n,enumerable:false}}),t}var zT=100;function Rs(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function En(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Cs=class t{constructor(e,n,r=s=>e.transaction().execute(s)){this.db=e;this.dialect=n;this.runInTransaction=r;this.schema="auth";}schema;bool(e){return this.dialect==="sqlite"?e?1:0:e}async transaction(e){return this.runInTransaction(n=>e(new t(n,this.dialect,this.runInTransaction)))}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 claimUserToken(e,n,r){let s=await this.update("users").set({[n]:null}).where("id","=",e).where(n,"=",r).executeTakeFirst();return Number(s.numUpdatedRows??0)>0}async createUser(e){let n=new Date().toISOString(),r={id:e.id,aud:e.aud??"authenticated",role:e.role??"authenticated",email:e.email?e.email.toLowerCase():null,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:En(e.raw_app_meta_data??{provider:"email",providers:["email"]}),raw_user_meta_data:En(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=En(r.raw_app_meta_data)),r.raw_user_meta_data!=null&&(r.raw_user_meta_data=En(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:me(),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:En(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:Rs(r.identity_data)}))}async updateIdentity(e,n){let r={...n,updated_at:new Date().toISOString()};r.identity_data!=null&&(r.identity_data=En(r.identity_data)),delete r.email,await this.update("identities").set(r).where("id","=",e).execute();}async deleteIdentitiesExcept(e,n){await this.deleteFrom("identities").where("user_id","=",e).where("id","!=",n).execute();}async findIdentityByProviderAndId(e,n){let r=await this.table("identities").selectAll().where("provider","=",e).where("provider_id","=",n).executeTakeFirst();if(!r)return null;let s=r;return {...s,identity_data:Rs(s.identity_data)}}async findIdentitiesByEmails(e){return e.length===0?[]:(await this.table("identities").selectAll().where("email","in",e.map(r=>r.toLowerCase())).execute()).map(r=>({...r,identity_data:Rs(r.identity_data)}))}async createFlowState(e){let n=new Date().toISOString(),r={id:e.id,user_id:e.user_id??null,auth_code:e.auth_code??null,authentication_method:e.authentication_method,code_challenge_method:e.code_challenge_method??null,code_challenge:e.code_challenge??null,provider_type:e.provider_type,provider_access_token:"",provider_refresh_token:"",auth_code_issued_at:null,invite_token:e.invite_token??null,referrer:e.referrer??null,oauth_client_state_id:e.oauth_client_state_id??null,linking_target_id:e.linking_target_id??null,email_optional:this.bool(e.email_optional??false),created_at:n,updated_at:n};return await this.insertInto("flow_state").values(r).execute(),r}async findFlowStateById(e){return await this.table("flow_state").selectAll().where("id","=",e).executeTakeFirst()??null}async findFlowStateByAuthCode(e){return await this.table("flow_state").selectAll().where("auth_code","=",e).executeTakeFirst()??null}async updateFlowState(e,n){let r={...n,updated_at:new Date().toISOString()};r.email_optional!=null&&(r.email_optional=this.bool(!!r.email_optional)),await this.update("flow_state").set(r).where("id","=",e).execute();}async claimFlowStateForPkce(e,n){let r=await this.update("flow_state").set({...n,updated_at:new Date().toISOString()}).where("id","=",e).where("user_id","is",null).executeTakeFirst();return Number(r.numUpdatedRows??0)>0}async deleteFlowStatesCreatedBefore(e){let n=await this.deleteFrom("flow_state").where("id","in",this.db.selectFrom("flow_state").select("id").where("created_at","<",e).limit(zT)).executeTakeFirst();return Number(n.numDeletedRows??0)}async deleteFlowState(e){let n=await this.deleteFrom("flow_state").where("id","=",e).executeTakeFirst();return Number(n.numDeletedRows??0)>0}async createAuditLogEntry(e){let n={id:e.id,payload:En(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:Rs(e.raw_app_meta_data),raw_user_meta_data:Rs(e.raw_user_meta_data),confirmed_at:e.confirmed_at??e.email_confirmed_at??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:ug(e)+ug(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 ug(t){return new TextEncoder().encode(t).byteLength}var No=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 Io=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 Do=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 Lo=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(()=>(hg(),mg));return this.client=new e({accessKeyId:this.options.accessKeyId,secretAccessKey:this.options.secretAccessKey,service:"ses",region:this.options.region}),this.client}};var Fo=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=nu(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 nu(t,e){let n=e.html?"text/html; charset=UTF-8":"text/plain; charset=UTF-8";return [`From: ${t}`,`To: ${e.to}`,`Subject: ${e.subject}`,"MIME-Version: 1.0",`Content-Type: ${n}`,"",e.html??e.text??""].join(`
87
+ `)}Ql();function Uo(t){let e=t.port??587,n=t.timeoutMs??3e4,r=!!(t.user&&t.pass),s=r?{user:t.user,pass:t.pass}:void 0,i=t.secure??e===465;return {host:t.host,port:e,secure:i,...s?{auth:s}:{},requireTLS:t.requireTls??(r&&!i),...t.rejectUnauthorized===false?{tls:{rejectUnauthorized:false}}:{},connectionTimeout:n,greetingTimeout:n,socketTimeout:n}}function ru(t,e){return {from:t,to:e.to,subject:e.subject,...e.text!==void 0?{text:e.text}:{},...e.html!==void 0?{html:e.html}:{}}}function su(t){if(!t)throw new Error("SMTP email is not supported in this runtime (SmtpEmailDriver requires Node or Bun)")}var ZT="nodemailer",er=class{constructor(e){this.options=e;}transporter;async send(e){su(!im()&&(sm()||zl()));let n=await this.getTransporter();try{await n.sendMail(ru(this.options.from,e));}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`SmtpEmailDriver send failed: ${s}`,{cause:r})}}async getTransporter(){if(this.transporter)return this.transporter;if(this.options.createTransport)return this.transporter=this.options.createTransport(Uo(this.options)),this.transporter;let e=await import(ZT);return this.transporter=e.createTransport(Uo(this.options)),this.transporter}};var As=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);}}},tr=class extends As{silent;logger;constructor(e={}){super({maxKeepCount:0}),this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){if(await super.send(e),!this.silent){let n=e.text?e.text:"(html-only email, body omitted)";this.logger.info(["[@supabase/lite] email captured (not delivered)",`To: ${e.to}`,`Subject: ${e.subject}`,"",n].join(`
88
+ `));}}};var vs=class{silent;logger;constructor(e={}){this.silent=e.silent??false,this.logger=e.logger??console;}async send(e){this.silent||this.logger.info(["[@supabase/lite] SMS driver noop send",`To: ${e.to}`,`Body: ${e.body}`].join(`
89
+ `));}};function eR(t){let e=t?.auth?.email?.smtp;if(e?.enabled!==true)return;if(!e.host)throw new Error("Missing required field in config: auth.email.smtp.host");if(!e.port)throw new Error("Missing required field in config: auth.email.smtp.port");if(!e.user)throw new Error("Missing required field in config: auth.email.smtp.user");if(!e.pass)throw new Error("Missing required field in config: auth.email.smtp.pass");if(!e.admin_email)throw new Error("Missing required field in config: auth.email.smtp.admin_email");let n=e.sender_name?{name:e.sender_name,address:e.admin_email}:e.admin_email;return new er({host:e.host,port:e.port,user:e.user,pass:e.pass,from:n})}function gg(t={},e){return {email:t.email??eR(e)??new tr,sms:t.sms??new vs,cache:t.cache??new Zn}}var tR="/auth/v1/verify";function yg(t,e,n,r){let s=new URL(tR,nR(t));return s.searchParams.set("token",e),s.searchParams.set("type",n),s.searchParams.set("redirect_to",r),s.toString()}function nR(t){return t.endsWith("/")?t:`${t}/`}function Bo(t,e){return t.replace(/\{\{\s*\.(\w+)\s*\}\}/g,(n,r)=>r in e?e[r]??"":n)}var bg={invite:"You have been invited",confirmation:"Confirm Your Signup",recovery:"Reset Your Password",magic_link:"Your Magic Link",email_change:"Confirm Email Change",reauthentication:"Confirm Reauthentication"},Mo="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif,'Apple Color Emoji','Segoe UI Emoji'";function nr(t,e){return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
90
90
  <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
91
91
  <head>
92
92
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -105,16 +105,16 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
105
105
  :root { color-scheme: light dark; supported-color-schemes: light dark }
106
106
  </style>
107
107
  </head>
108
- <body style="height:100%;margin:0;-webkit-text-size-adjust:none;font-family:${Ro};background-color:#FFFFFF;color:#687076;width:100% !important;">
108
+ <body style="height:100%;margin:0;-webkit-text-size-adjust:none;font-family:${Mo};background-color:#FFFFFF;color:#687076;width:100% !important;">
109
109
  <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;margin:0;padding:0;background-color:#FFFFFF;">
110
110
  <tr>
111
- <td align="center" style="font-family:${Ro};font-size:16px;padding:0;">
111
+ <td align="center" style="font-family:${Mo};font-size:16px;padding:0;">
112
112
  <table class="email-content" width="100%" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;margin:0;padding:0;">
113
113
  <tr>
114
- <td class="email-body" width="570" cellpadding="0" cellspacing="0" style="font-family:${Ro};font-size:16px;padding:0;width:100%;margin:0;">
114
+ <td class="email-body" width="570" cellpadding="0" cellspacing="0" style="font-family:${Mo};font-size:16px;padding:0;width:100%;margin:0;">
115
115
  <table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0" role="presentation" style="width:570px;margin:0 auto;padding:0;background-color:#FFFFFF;">
116
116
  <tr>
117
- <td class="content-cell" style="font-family:${Ro};font-size:16px;padding:15px;">
117
+ <td class="content-cell" style="font-family:${Mo};font-size:16px;padding:15px;">
118
118
  <h1 style="margin:0;color:#1C1C1C;font-size:22px;font-weight:600;">${t}</h1>
119
119
  ${e}
120
120
  <p style="margin:1.5em 0 0;font-size:13px;line-height:1.625;color:#A8AAAF;text-align:left;">Powered by Supabase Lite</p>
@@ -128,25 +128,25 @@ ${s}`)}return t}var Gu=[{name:"Self-hosted Logflare Configuration",link:"https:/
128
128
  </tr>
129
129
  </table>
130
130
  </body>
131
- </html>`}function Zn(t){return `<p style="margin:0.4em 0 1.1875em;font-size:16px;line-height:1.625;color:#687076;">${t}</p>`}function Ts(t,e){return `<div style="margin-top:30px;margin-bottom:30px;">
131
+ </html>`}function rr(t){return `<p style="margin:0.4em 0 1.1875em;font-size:16px;line-height:1.625;color:#687076;">${t}</p>`}function Os(t,e){return `<div style="margin-top:30px;margin-bottom:30px;">
132
132
  <a href="${t}" style="color:#FFFFFF;background-color:#2B825B;border:1px solid #2B825B;padding:8px 12px;display:inline-block;font-size:14px;text-decoration:none;border-radius:4px;-webkit-text-size-adjust:none;box-sizing:border-box;box-shadow:0 0 rgba(0,0,0,0.1),0 1px 1px rgba(0,0,0,0.22),0 0 1px #DFE3E6,0 2px 5px rgba(64,68,82,0.08);">${e}</a>
133
- </div>`}function Rs(){return `<p style="margin:0.4em 0 0.5em;font-size:16px;line-height:1.625;color:#687076;">Or enter this code:</p>
133
+ </div>`}function Ps(){return `<p style="margin:0.4em 0 0.5em;font-size:16px;line-height:1.625;color:#687076;">Or enter this code:</p>
134
134
  <div class="code-box" style="background-color:#f4f4f4;border:1px solid #eee;border-radius:5px;padding:24px 10px;text-align:center;">
135
135
  <span style="font-size:28px;font-weight:700;letter-spacing:6px;color:#1C1C1C;">{{ .Token }}</span>
136
- </div>`}var RT={signup:Xn("Confirm your signup",`${Zn("Follow this link to confirm your account:")}
137
- ${Ts("{{ .ConfirmationURL }}","Confirm your email")}
138
- ${Rs()}`),recovery:Xn("Reset your password",`${Zn("Follow this link to reset the password for your account:")}
139
- ${Ts("{{ .ConfirmationURL }}","Reset password")}
140
- ${Rs()}`),magiclink:Xn("Your magic link",`${Zn("Follow this link to sign in:")}
141
- ${Ts("{{ .ConfirmationURL }}","Sign in")}
142
- ${Rs()}`),email_change:Xn("Confirm your new email",`${Zn("Follow this link to confirm the update of your email from {{ .Email }} to {{ .NewEmail }}:")}
143
- ${Ts("{{ .ConfirmationURL }}","Change email")}
144
- ${Rs()}`),invite:Xn("You have been invited",`${Zn("You have been invited to create a user. Follow this link to accept the invite:")}
145
- ${Ts("{{ .ConfirmationURL }}","Accept the invite")}
146
- ${Rs()}`),reauthentication:Xn("Confirm reauthentication",`${Zn("Enter this code to continue:")}
136
+ </div>`}var rR={signup:nr("Confirm your signup",`${rr("Follow this link to confirm your account:")}
137
+ ${Os("{{ .ConfirmationURL }}","Confirm your email")}
138
+ ${Ps()}`),recovery:nr("Reset your password",`${rr("Follow this link to reset the password for your account:")}
139
+ ${Os("{{ .ConfirmationURL }}","Reset password")}
140
+ ${Ps()}`),magiclink:nr("Your magic link",`${rr("Follow this link to sign in:")}
141
+ ${Os("{{ .ConfirmationURL }}","Sign in")}
142
+ ${Ps()}`),email_change:nr("Confirm your new email",`${rr("Follow this link to confirm the update of your email from {{ .Email }} to {{ .NewEmail }}:")}
143
+ ${Os("{{ .ConfirmationURL }}","Change email")}
144
+ ${Ps()}`),invite:nr("You have been invited",`${rr("You have been invited to create a user. Follow this link to accept the invite:")}
145
+ ${Os("{{ .ConfirmationURL }}","Accept the invite")}
146
+ ${Ps()}`),reauthentication:nr("Confirm reauthentication",`${rr("Enter this code to continue:")}
147
147
  <div class="code-box" style="background-color:#f4f4f4;border:1px solid #eee;border-radius:5px;padding:24px 10px;text-align:center;">
148
148
  <span style="font-size:28px;font-weight:700;letter-spacing:6px;color:#1C1C1C;">{{ .Token }}</span>
149
- </div>`)},CT={signup:`Confirm your signup with this code: {{ .Token }}
149
+ </div>`)},sR={signup:`Confirm your signup with this code: {{ .Token }}
150
150
 
151
151
  Or follow this link: {{ .ConfirmationURL }}`,recovery:`Reset your password with this code: {{ .Token }}
152
152
 
@@ -154,8 +154,13 @@ Or follow this link: {{ .ConfirmationURL }}`,magiclink:`Your login code is: {{ .
154
154
 
155
155
  Or follow this link: {{ .ConfirmationURL }}`,email_change:`Confirm your email change with this code: {{ .Token }}
156
156
 
157
- Or follow this link: {{ .ConfirmationURL }}`,invite:"You have been invited. Accept with this link: {{ .ConfirmationURL }}",reauthentication:"Enter this code to continue: {{ .Token }}"};function Uc(t){return RT[t]}function Qh(t){return CT[t]}var kT={signup:"confirmation",recovery:"recovery",magiclink:"magic_link",email_change:"email_change",invite:"invite"},Cs=class{constructor(e,n={}){this.driver=e;this.config=n;}async sendConfirmation(e,n,r,s){await this.send(await this.render("signup",e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(await this.render("recovery",e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(await this.render("magiclink",e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(await this.render("email_change",e,n,r,s));}async sendReauthentication(e,n,r){await this.send(await this.render("reauthentication",e,r?.tokenHash??"",n,r));}async render(e,n,r,s,i){let o=this.config.site_url??"http://localhost:3000",a=i?.redirectTo??o,l={ConfirmationURL:e==="reauthentication"?"":zh(o,r,e,a),Token:s,TokenHash:r,SiteURL:o,Email:i?.currentEmail??n,NewEmail:i?.newEmail??n,RedirectTo:a,Data:i?.data??""},c=kT[e],f=c?this.config.email?.template?.[c]:void 0,u=f?.subject??Vh[c??"reauthentication"]??"Notification",d=f?.content_path?await vT(f.content_path)??Uc(e):Uc(e);return {to:n,subject:Co(u,l),body:{text:Co(Qh(e),l),html:Co(d,l)},otp:s,tokenHash:r,meta:{...i,emailActionType:i?.emailActionType??e}}}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};async function vT(t){try{let{readFile:e}=await import('node:fs/promises');return await e(t,"utf8")}catch(e){return console.warn(`[auth] failed to load email template "${t}":`,e),null}}function Yh(){return {version:AT(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function Xh(t){let e={};for(let n of vc)e[n]=(t.external?.[n]?.enabled??false)&&$h.has(n);for(let n of Ac)e[n]=false;return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,...e,email:t.email?.enable_signup??true,phone:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function Zh(){return {keys:[]}}function eg(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function AT(){return [Mc(JSON.stringify({alg:"HS256",typ:"JWT"})),Mc(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),Mc("metadata")].join(".")}function Mc(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 ks=t=>t;var OT="00000000-0000-0000-0000-000000000000",PT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bc=({onError:t}={})=>ks(async(e,n)=>{if(!e.var.userId||!e.var.sessionId){let r=await ng(e);if(r&&t)return t(r,e)}await n();}),vs=(t={})=>ks(async(e,n)=>{if(t.acceptSecretApiKey&&e.var.apiKeyType==="secret"&&e.var.ignoreAuthorization)return n();if(!e.var.userId){let r=await ng(e);if(r)return tg(e,r);if(!e.var.userId)return tg(e,hn())}await n();});async function ng(t){if(t.var.ignoreAuthorization)return hn();let e=t.req.header("Authorization");if(!e)return hn();if(!e.startsWith("Bearer "))return hn();let n=e.slice(7);if(!n||/^\s/.test(n))return hn();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await mh(n,r);}catch(c){return c instanceof $?c:hn()}let i=$T(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return Qm();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Ym();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function $T(t){let e=t.sub,n=t.role;return e==null||e===""?dc():typeof e!="string"?pc():PT.test(e)?e===OT&&n==="service_role"?dc():null:pc()}function tg(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var Hc=new _e().onError((t,e)=>{if(t instanceof $){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 xt(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(As(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",bn("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await xt(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return As(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return As(t,s),t.json(s,200)}if(e==="pkce"){let s=await r.exchangePkceCode(n.auth_code,n.code_verifier);return As(t,s),t.json(s,200)}throw ih()}).all("/token",bn("POST")).post("/otp",async t=>{let e=await xt(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 xt(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",bn("POST")).post("/verify",async t=>{let e=await xt(t),{authService:n}=t.var;LT(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return As(t,r),t.json(r,200)}).get("/verify",async t=>{let e=t.req.query("type"),n=t.req.query("token"),{authService:r}=t.var;if(!e)throw H("Verify requires a verification type",400);if(!lg.has(e))throw H("Invalid email verification type",400);if(!n)throw H("Verify requires a token or a token hash",400);let s=r.resolveEmailRedirect(t.req.query("redirect_to"));try{let i=await r.verifyOtp({token_hash:n,type:e}),o=new URLSearchParams({access_token:i.access_token,refresh_token:i.refresh_token,expires_in:String(i.expires_in),expires_at:String(i.expires_at),token_type:i.token_type,type:e});return t.redirect(`${s}#${o.toString()}`,303)}catch(i){let o=i instanceof $?i.code:"server_error",a=i instanceof $?i.message:"Verification failed",l=new URLSearchParams({error:"access_denied",error_code:o,error_description:a});return t.redirect(`${s}#${l.toString()}`,303)}}).post("/recover",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await xt(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Yh(),200)).all("/health",bn("GET")).get("/settings",t=>t.json(Xh(t.var.app.config.auth??{}),200)).all("/settings",bn("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(Zh(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(eg(),200))).get("/authorize",async t=>{let{authService:e}=t.var,n=Object.fromEntries(new URL(t.req.url).searchParams),r=await e.getExternalProviderRedirectUrl(n,{refererHeader:t.req.header("Referer"),defaultRedirectUri:og(t.req.url,t.var.app.config.api?.external_url)});return t.header("Content-Type","text/html; charset=utf-8"),t.header("Location",r),t.body(ag(r,"Found"),302)}).get("/callback",ig).post("/callback",ig).all("/nonexistent",IT).use(vs()).post("/logout",async t=>{let e=await xt(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 xt(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",bn("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",bn("GET"));function bn(t){return e=>(e.header("Allow",t),e.body(null,405))}function IT(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)}function og(t,e){return `${(e||new URL(t).origin).replace(/\/+$/,"")}/auth/v1/callback`}function ag(t,e){return `<a href="${NT(t)}">${e}</a>.
158
- `}function NT(t){return t.replace(/&/g,"&amp;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&#34;")}var DT={400:"invalid_request",401:"unauthorized_client",403:"access_denied",500:"server_error",503:"temporarily_unavailable"},jT=new Set(["signup_disabled","user_banned","provider_email_needs_verification"]);function rg(t){return t instanceof $?{error:jT.has(t.code)?"access_denied":DT[t.status]??"server_error",description:t.message,code:t.code}:{error:"server_error",description:"Unexpected failure, please check server logs for more information"}}function sg(t,e){let n=new URL(t);n.searchParams.set("error",e.error),n.searchParams.set("error_description",e.description),e.code&&n.searchParams.set("error_code",e.code);let r=new URLSearchParams;return r.set("error",e.error),r.set("error_description",e.description),e.code&&r.set("error_code",e.code),r.set("sb",""),n.hash=r.toString(),n.toString()}function qc(t,e,n){return t.header("Location",e),n?(t.header("Content-Type","text/html; charset=utf-8"),t.body(ag(e,"Found"),302)):t.body(null,302)}async function ig(t){let{authService:e}=t.var,n=t.req.method==="GET",r;if(n)r=Object.fromEntries(new URL(t.req.url).searchParams);else {let o=t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim();if(o==="application/x-www-form-urlencoded"||o==="multipart/form-data"){let a=await t.req.parseBody();r=Object.fromEntries(Object.entries(a).map(([l,c])=>[l,typeof c=="string"?c:void 0]));}else r={};}let s;try{s=await e.loadOAuthFlowState(r.state);}catch(o){let a=t.var.app.config.auth?.site_url??"http://localhost:3000",l=new URL(a),c=rg(o);l.searchParams.set("error",c.error),l.searchParams.set("error_description",c.description),c.code&&l.searchParams.set("error_code",c.code),t.header("Location",l.toString()),t.header("Content-Type","text/plain; charset=utf-8");let f=o instanceof $?JSON.stringify(o.toJSON()):JSON.stringify(c);return t.body(f,303)}let i=e.resolveOAuthRedirectTarget(s);if(r.error){let o=sg(i,{error:r.error,description:r.error_description??""});return qc(t,o,n)}try{let o=og(t.req.url,t.var.app.config.api?.external_url),a=await e.handleExternalProviderCallback(s,r,{defaultRedirectUri:o});return qc(t,a.redirectUrl,n)}catch(o){(!(o instanceof $)||o.status>=500)&&console.error("Auth error:",o);let a=rg(o),l=sg(i,a);return qc(t,l,n)}}var lg=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function LT(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw H("Verify requires a verification type",400);if(!lg.has(e))throw H("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 H("Verify requires either a token or a token hash",400)}async function xt(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw hs("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 hs("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 hs("Could not parse request body as JSON: unexpected end of JSON input");let s=wc(n)||"invalid character ' ' looking for beginning of value";throw hs(`Could not parse request body as JSON: ${s}`)}}function As(t,e){e.session_id&&t.header("Sb-Auth-Session-Id",e.session_id),e.user_id&&t.header("Sb-Auth-User-Id",e.user_id),e.refresh_token&&t.header("Sb-Auth-Refresh-Token-Prefix",String(e.refresh_token).slice(0,8));}function cg(t){let e=t.connection.dialect,n=new Ss(t.connection.kysely,e,s=>t.connection.runInTransaction(s)),r=t.config.auth;return new bs(n,r,t._mailer??new Cs(t.drivers.email,{site_url:r.site_url,email:r.email}))}function ug(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function fg(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function Wt(t){return typeof t=="string"?t:JSON.stringify(t??{})}var Os=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:Wt(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:Wt(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:Wt(e.metadata??{}),user_metadata:Wt(e.user_metadata??{}),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=Wt(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=Wt(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=Wt(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=Wt(n.user_metadata)),n.version!==void 0&&(r.version=n.version),n.owner!==void 0&&(r.owner=n.owner),n.owner_id!==void 0&&(r.owner_id=n.owner_id),await this.update("objects").set(r).where("id","=",e).execute(),this.findObjectById(e)}async deleteObject(e){await this.deleteFrom("objects").where("id","=",e).execute();}async deleteObjectsByBucket(e){let r=(await this.table("objects").select("name").where("bucket_id","=",e).execute()).map(s=>s.name);return r.length>0&&await this.deleteFrom("objects").where("bucket_id","=",e).execute(),r}async objectExists(e,n){return !!await this.table("objects").select("id").where("bucket_id","=",e).where("name","=",n).executeTakeFirst()}async touchObject(e){await this.update("objects").set({last_accessed_at:new Date().toISOString()}).where("id","=",e).execute();}parseBucketRow(e){return {...e,owner:e.owner??"",owner_id:e.owner_id??"",public:!!e.public,allowed_mime_types:e.allowed_mime_types==null?null:fg(e.allowed_mime_types)}}parseObjectRow(e){return {...e,metadata:ug(e.metadata),user_metadata:ug(e.user_metadata),path_tokens:fg(e.path_tokens)}}};var Z=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 Ps=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?BT(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){if(await this.repo.findBucketById(e.id))throw Z.bucketAlreadyExists(e.id);return this.repo.createBucket(e)}async getBucket(e){let n=await this.repo.findBucketById(e);if(!n)throw Z.bucketNotFound(e);return n}async listBuckets(){return this.repo.listBuckets()}async updateBucket(e,n){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);return await this.repo.updateBucket(e,n)}async deleteBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);if(!await this.repo.isBucketEmpty(e))throw Z.bucketNotEmpty(e);await this.repo.deleteBucket(e);}async emptyBucket(e){if(!await this.repo.findBucketById(e))throw Z.bucketNotFound(e);let r=await this.repo.deleteObjectsByBucket(e);r.length>0&&await this.adapter.deleteObjects(e,r);}async upload(e,n,r,s){Wc(n);let i=await this.repo.findBucketById(e);if(!i)throw Z.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 Z.invalidMimeType(o,i.allowed_mime_types);let l=i.file_size_limit??this.config.fileSizeLimit??null;if(l&&s?.contentLength&&s.contentLength>l)throw Z.fileTooLarge(l);let c=await this.repo.findObjectByPath(e,n);if(c&&!s?.upsert)throw Z.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 Z.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 Z.objectNotFound(n);if(r?.transform&&this.transformationAdapter?.requiresBuffer){let o=await MT(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 Z.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 Z.bucketNotFound(e);return this.repo.listObjects(e,n,r)}async move(e,n,r){Wc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.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){Wc(r);let s=await this.repo.findObjectByPath(e,n);if(!s)throw Z.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 Z.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 Z.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 Z.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 jwtVerify(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 SignJWT({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}};async function MT(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 Wc(t){if(!t||t.includes("..")||t.startsWith("/"))throw Z.invalidKey(t)}function BT(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 qT=s.object({id:s.string(),name:s.string(),public:s.boolean({default:false}).optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),HT=s.object({public:s.boolean().optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),WT=s.object({prefix:s.string().optional(),limit:s.number().optional(),offset:s.number().optional(),sortBy:s.object({column:s.string(),order:s.string()}).optional(),search:s.string().optional()}),dg=s.object({bucketId:s.string(),sourceKey:s.string(),destinationKey:s.string()}),KT=s.object({expiresIn:s.number()}),JT=s.object({expiresIn:s.number(),paths:s.array(s.string())}),GT=s.object({prefixes:s.array(s.string())}),zT=new _e().get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(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=Kc(t.req.query()),o=await r.download(e,n,{transform:i??void 0});return new Response(o.body,{headers:Jc(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(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=Kc(t.req.query()),a=await s.download(e,n,{transform:o??void 0});return new Response(a.body,{headers:Jc(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(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)}),VT=new _e().use(vs({acceptSecretApiKey:true})).post("/bucket",validator("json",qT),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",validator("json",HT),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",validator("json",WT),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",validator("json",dg),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",validator("json",dg),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=ft(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/*",validator("json",KT),async t=>{let e=t.req.param("bucketId"),n=ft(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",validator("json",JT),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=ft(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",validator("json",GT),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=ft(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 Z(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=ft(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=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=Kc(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:Jc(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=ft(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),Gc=new _e().onError((t,e)=>t instanceof Z?e.json(t.toJSON(),400):(console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500))).route("/",zT).route("/",VT);function ft(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 Kc(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 Jc(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}Un();var zc=`-- supabase/storage core schema (Postgres)
157
+ Or follow this link: {{ .ConfirmationURL }}`,invite:"You have been invited. Accept with this link: {{ .ConfirmationURL }}",reauthentication:"Enter this code to continue: {{ .Token }}"};function iu(t){return rR[t]}function wg(t){return sR[t]}var iR={signup:"confirmation",recovery:"recovery",magiclink:"magic_link",email_change:"email_change",invite:"invite"},$s=class{constructor(e,n={}){this.driver=e;this.config=n;}async sendConfirmation(e,n,r,s){await this.send(await this.render("signup",e,n,r,s));}async sendRecovery(e,n,r,s){await this.send(await this.render("recovery",e,n,r,s));}async sendMagicLink(e,n,r,s){await this.send(await this.render("magiclink",e,n,r,s));}async sendEmailChange(e,n,r,s){await this.send(await this.render("email_change",e,n,r,s));}async sendReauthentication(e,n,r){await this.send(await this.render("reauthentication",e,r?.tokenHash??"",n,r));}async render(e,n,r,s,i){let o=this.config.site_url??"http://localhost:3000",a=i?.redirectTo??o,l={ConfirmationURL:e==="reauthentication"?"":yg(o,r,e,a),Token:s,TokenHash:r,SiteURL:o,Email:i?.currentEmail??n,NewEmail:i?.newEmail??n,RedirectTo:a,Data:i?.data??""},c=iR[e],u=c?this.config.email?.template?.[c]:void 0,f=u?.subject??bg[c??"reauthentication"]??"Notification",d=u?.content_path?await oR(u.content_path)??iu(e):iu(e);return {to:n,subject:Bo(f,l),body:{text:Bo(wg(e),l),html:Bo(d,l)},otp:s,tokenHash:r,meta:{...i,emailActionType:i?.emailActionType??e}}}async send(e){await this.driver.send({to:e.to,subject:e.subject,text:e.body.text,html:e.body.html});}};async function oR(t){try{let{readFile:e}=await import('node:fs/promises');return await e(t,"utf8")}catch(e){return console.warn(`[auth] failed to load email template "${t}":`,e),null}}function Sg(){return {version:aR(),name:"GoTrue",description:"GoTrue is a user registration and authentication API"}}function _g(t){let e={};for(let n of Vc)e[n]=(t.external?.[n]?.enabled??false)&&tg.has(n);for(let n of zc)e[n]=false;return {external:{anonymous_users:t.enable_anonymous_sign_ins??false,...e,email:t.email?.enable_signup??true,phone:false},disable_signup:!(t.enable_signup??true),mailer_autoconfirm:!(t.email?.enable_confirmations??false),phone_autoconfirm:false,sms_provider:"",saml_enabled:false}}function Eg(){return {keys:[]}}function xg(){return {issuer:"",jwks_uri:"/.well-known/jwks.json"}}function aR(){return [ou(JSON.stringify({alg:"HS256",typ:"JWT"})),ou(JSON.stringify({name:"GoTrue",implementation:"@supabase/lite"})),ou("metadata")].join(".")}function ou(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 Ns=t=>t;var lR="00000000-0000-0000-0000-000000000000",cR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,au=({onError:t}={})=>Ns(async(e,n)=>{if(new URL(e.req.url).pathname.startsWith("/storage/v1/")){await n();return}if(!e.var.userId||!e.var.sessionId){let r=await Rg(e);if(r&&t)return t(r,e)}await n();}),lu=(t={})=>Ns(async(e,n)=>{if(t.acceptSecretApiKey&&e.var.apiKeyType==="secret"&&e.var.ignoreAuthorization)return n();if(!e.var.userId){let r=await Rg(e);if(r)return Tg(e,r);if(!e.var.userId)return Tg(e,Sn())}await n();});async function Rg(t){if(t.var.ignoreAuthorization)return Sn();let e=t.req.header("Authorization");if(!e)return Sn();if(!e.startsWith("Bearer "))return Sn();let n=e.slice(7);if(!n||/^\s/.test(n))return Sn();let r=t.get("app").config.auth?.jwt_secret;if(!r)return null;let s;try{s=await Lh(n,r);}catch(c){return c instanceof D?c:Sn()}let i=uR(s);if(i)return i;let o=s.sub;if(s.role!=="service_role"&&!await t.var.authService.repo.findUserById(o))return wh();let l=s.session_id;if(l){if(!await t.var.authService.repo.findSessionById(l))return Sh();t.set("sessionId",l);}return t.set("userId",o),t.set("jwt",s),null}function uR(t){let e=t.sub,n=t.role;return e==null||e===""?$c():typeof e!="string"?Nc():cR.test(e)?e===lR&&n==="service_role"?$c():null:Nc()}function Tg(t,e){return t.header("X-Sb-Error-Code",e.code),t.json(e.toJSON(),e.status)}var uu=new Te().onError((t,e)=>{if(t instanceof D){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 Ct(t,{requireBody:true}),{authService:n}=t.var,r=await n.signUp(e.email,e.password,e.data);return r.session?(Is(t,r.session),t.json(r.session,200)):t.json(r.user,200)}).all("/signup",xn("POST")).post("/token",async t=>{let e=t.req.query("grant_type"),n=await Ct(t,{requireBody:true}),{authService:r}=t.var;if(e==="password"){let s=await r.signInWithPassword(n.email,n.password);return Is(t,s),t.json({...s,weak_password:null},200)}if(e==="refresh_token"){let s=await r.refreshSession(n.refresh_token);return Is(t,s),t.json(s,200)}if(e==="pkce"){let s=await r.exchangePkceCode(n.auth_code,n.code_verifier);return Is(t,s),t.json(s,200)}throw Ah()}).all("/token",xn("POST")).post("/otp",async t=>{let e=await Ct(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 Ct(t),{authService:n}=t.var;return await n.requestMagicLink(e.email,e.gotrue_meta_security),t.json({},200)}).all("/magiclink",xn("POST")).post("/verify",async t=>{let e=await Ct(t),{authService:n}=t.var;hR(e);let r=await n.verifyOtp({email:e.email,token:e.token,token_hash:e.token_hash,type:e.type});return Is(t,r),t.json(r,200)}).get("/verify",async t=>{let e=t.req.query("type"),n=t.req.query("token"),{authService:r}=t.var;if(!e)throw K("Verify requires a verification type",400);if(!Pg.has(e))throw K("Invalid email verification type",400);if(!n)throw K("Verify requires a token or a token hash",400);let s=r.resolveEmailRedirect(t.req.query("redirect_to"));try{let i=await r.verifyOtp({token_hash:n,type:e}),o=new URLSearchParams({access_token:i.access_token,refresh_token:i.refresh_token,expires_in:String(i.expires_in),expires_at:String(i.expires_at),token_type:i.token_type,type:e});return t.redirect(`${s}#${o.toString()}`,303)}catch(i){let o=i instanceof D?i.code:"server_error",a=i instanceof D?i.message:"Verification failed",l=new URLSearchParams({error:"access_denied",error_code:o,error_description:a});return t.redirect(`${s}#${l.toString()}`,303)}}).post("/recover",async t=>{let e=await Ct(t),{authService:n}=t.var;return await n.recover(e.email),t.json({},200)}).post("/resend",async t=>{let e=await Ct(t),{authService:n}=t.var;return await n.resend(e.type,e.email),t.json({},200)}).get("/health",t=>t.json(Sg(),200)).all("/health",xn("GET")).get("/settings",t=>t.json(_g(t.var.app.config.auth??{}),200)).all("/settings",xn("GET")).get("/.well-known/jwks.json",t=>(t.header("Cache-Control","public, max-age=600"),t.json(Eg(),200))).get("/.well-known/openid-configuration",t=>(t.header("Cache-Control","public, max-age=600"),t.json(xg(),200))).get("/authorize",async t=>{let{authService:e}=t.var,n=Object.fromEntries(new URL(t.req.url).searchParams),r=await e.getExternalProviderRedirectUrl(n,{refererHeader:t.req.header("Referer"),defaultRedirectUri:vg(t.req.url,t.var.app.config.api?.external_url)});return t.header("Content-Type","text/html; charset=utf-8"),t.header("Location",r),t.body(Og(r,"Found"),302)}).get("/callback",Ag).post("/callback",Ag).all("/nonexistent",fR).use(lu()).post("/logout",async t=>{let e=await Ct(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 Ct(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",xn("GET, PUT")).get("/reauthenticate",async t=>{let{authService:e}=t.var;return await e.reauthenticate(t.get("userId")),t.json({},200)}).all("/reauthenticate",xn("GET"));function xn(t){return e=>(e.header("Allow",t),e.body(null,405))}function fR(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)}function vg(t,e){return `${(e||new URL(t).origin).replace(/\/+$/,"")}/auth/v1/callback`}function Og(t,e){return `<a href="${dR(t)}">${e}</a>.
158
+ `}function dR(t){return t.replace(/&/g,"&amp;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&#34;")}var pR={400:"invalid_request",401:"unauthorized_client",403:"access_denied",500:"server_error",503:"temporarily_unavailable"},mR=new Set(["signup_disabled","user_banned","provider_email_needs_verification"]);function Cg(t){return t instanceof D?{error:mR.has(t.code)?"access_denied":pR[t.status]??"server_error",description:t.message,code:t.code}:{error:"server_error",description:"Unexpected failure, please check server logs for more information"}}function kg(t,e){let n=new URL(t);n.searchParams.set("error",e.error),n.searchParams.set("error_description",e.description),e.code&&n.searchParams.set("error_code",e.code);let r=new URLSearchParams;return r.set("error",e.error),r.set("error_description",e.description),e.code&&r.set("error_code",e.code),r.set("sb",""),n.hash=r.toString(),n.toString()}function cu(t,e,n){return t.header("Location",e),n?(t.header("Content-Type","text/html; charset=utf-8"),t.body(Og(e,"Found"),302)):t.body(null,302)}async function Ag(t){let{authService:e}=t.var,n=t.req.method==="GET",r;if(n)r=Object.fromEntries(new URL(t.req.url).searchParams);else {let o=t.req.header("Content-Type")?.toLowerCase().split(";")[0]?.trim();if(o==="application/x-www-form-urlencoded"||o==="multipart/form-data"){let a=await t.req.parseBody();r=Object.fromEntries(Object.entries(a).map(([l,c])=>[l,typeof c=="string"?c:void 0]));}else r={};}let s;try{s=await e.loadOAuthFlowState(r.state);}catch(o){let a=t.var.app.config.auth?.site_url??"http://localhost:3000",l=new URL(a),c=Cg(o);l.searchParams.set("error",c.error),l.searchParams.set("error_description",c.description),c.code&&l.searchParams.set("error_code",c.code),t.header("Location",l.toString()),t.header("Content-Type","text/plain; charset=utf-8");let u=o instanceof D?JSON.stringify(o.toJSON()):JSON.stringify(c);return t.body(u,303)}let i=e.resolveOAuthRedirectTarget(s);if(r.error){let o=kg(i,{error:r.error,description:r.error_description??""});return cu(t,o,n)}try{let o=vg(t.req.url,t.var.app.config.api?.external_url),a=await e.handleExternalProviderCallback(s,r,{defaultRedirectUri:o});return cu(t,a.redirectUrl,n)}catch(o){(!(o instanceof D)||o.status>=500)&&console.error("Auth error:",o);let a=Cg(o),l=kg(i,a);return cu(t,l,n)}}var Pg=new Set(["signup","magiclink","recovery","email_change","reauthentication"]);function hR(t){let e=typeof t.type=="string"?t.type:"";if(!e)throw K("Verify requires a verification type",400);if(!Pg.has(e))throw K("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 K("Verify requires either a token or a token hash",400)}async function Ct(t,e={}){if(!t.req.raw.body){if(e.requireBody)throw _s("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 _s("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 _s("Could not parse request body as JSON: unexpected end of JSON input");let s=Uc(n)||"invalid character ' ' looking for beginning of value";throw _s(`Could not parse request body as JSON: ${s}`)}}function Is(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 $g(t){let e=t.connection.dialect,n=new Cs(t.connection.kysely,e,s=>t.connection.runInTransaction(s)),r=t.config.auth;return new Ts(n,r,t._mailer??new $s(t.drivers.email,{site_url:r.site_url,email:r.email}))}function Ng(t){if(t==null)return {};if(typeof t=="string")try{return JSON.parse(t)}catch{return {}}return t}function Ig(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return []}return []}function Gt(t){return t===null?null:typeof t=="string"?t:JSON.stringify(t??{})}var Ds=class{schema;db;dialect;constructor(e){this.db=e.kysely,this.dialect=e.dialect,this.schema="storage";}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:Gt(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:Gt(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:Gt(e.metadata===void 0?{}:e.metadata),user_metadata:Gt(e.user_metadata===void 0?{}:e.user_metadata),version:e.version??null,created_at:n,updated_at:n,last_accessed_at:n};return this.dialect!=="postgres"&&(r.path_tokens=Gt(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:n.updated_at??new Date().toISOString()};return n.bucket_id!==void 0&&(r.bucket_id=n.bucket_id),n.name!==void 0&&(r.name=n.name,this.dialect!=="postgres"&&(r.path_tokens=Gt(n.name.split("/")))),n.metadata!==void 0&&(r.metadata=Gt(n.metadata)),n.user_metadata!==void 0&&(r.user_metadata=Gt(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:Ig(e.allowed_mime_types)}}parseObjectRow(e){return {...e,owner:e.owner??null,owner_id:e.owner_id??null,metadata:Ng(e.metadata),user_metadata:Ng(e.user_metadata),path_tokens:Ig(e.path_tokens)}}};var P=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")}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,"not_found","Object not found")}static relatedResourceNotFound(){return new t(404,"InvalidRequest","The related resource does not exist")}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}}};ts();var Lg=/^\{\{(.+)\}\}$/;function Fg(t){return typeof t=="string"&&Lg.test(t)}function gR(t){return Lg.exec(t)[1]}var Dg=Symbol("unresolved");function Ug(t,e){let n=gR(t),r=Wt(e,n,Dg);if(r===Dg)throw new Error(`Unresolved variable: {{${n}}}`);return r}function kt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>kt(i,e));continue}if(r==="$not"){n[r]=kt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?kt(i.where,e):i?.where};continue}if(r==="$storageFolder"){let i=s;n[r]={...i,ops:Ho(i.ops,e)};continue}if(r==="$storageObject"){let i=s;n[r]={...i,ops:Ho(i.ops,e)};continue}if(Fg(r)){let i=Ug(r,e),a=bR(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=Ho(s,e);continue}n[r]=s;}return n}function Ho(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=Ho(s,e):yR(s)?n[r]={...s,where:s?.where?kt(s?.where,e):void 0}:Fg(s)?n[r]=Ug(s,e):n[r]=s;return n}function yR(t){return t!=null&&typeof t=="object"&&t.type==="query"}function bR(t,e){let n=true;for(let[r,s]of Object.entries(e)){let i=js(t,r,s);if(i===false)return false;i===null&&(n=null);}return n}function js(t,e,n){if(e!=="$is"&&e!=="$isNot"&&(t==null||n==null))return null;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)?true:n.includes(null)?null:false:false;case "$notIn":return Array.isArray(n)?n.includes(t)?false:n.includes(null)?null:true:true;case "$is":return t===n;case "$isNot":return t!==n;case "$like":return qo(t,n);case "$notLike":return !qo(t,n);case "$ilike":return qo(t,n,true);case "$notIlike":return !qo(t,n,true);default:throw new Error(`Cannot evaluate operator "${e}" against a resolved value`)}}function qo(t,e,n=false){return typeof t=="string"&&typeof e=="string"&&wR(e,n).test(t)}function wR(t,e=false){let n="^";for(let r=0;r<t.length;r++){let s=t[r];s==="\\"&&r+1<t.length?n+=jg(t[++r]):s==="%"?n+=".*":s==="_"?n+=".":n+=jg(s);}return new RegExp(`${n}$`,e?"si":"s")}function jg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}ts();var Ls=class{constructor(e,n,r){this.policies=n;this.defaultSchema=r;this.tables=new Set([...e].map(SR));}tables;enforce(e,n){let r=e.from;if(!r||!this.isRlsEnabled(r,e.schema))return e;let s=_R(e.type);if(!s)return e;let i=Wt(n,"auth.role")??"anon";if(i==="service_role")return e;let{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:Mg(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Mg(e.where,l)};if(l.$always===false)return c;let u=this.combineWithCheck(o,a,n,s);if(e.values&&Object.keys(u).length>0){let f=new Set(Object.keys(e.values));this.validateWithCheck(u,e.values,o,a,f);}return c}case "INSERT":{let l=this.combineWithCheck(o,a,n,s);if(e.values){let c=Array.isArray(e.values)?e.values:[e.values];for(let u of c)this.validateWithCheck(l,u,o,a);}return e}default:return e}}isRlsEnabled(e,n){return this.tables.has(e)}resolvePolicies(e,n,r,s){let i=this.policies.filter(o=>o.data.table===e&&this.schemasMatch(o.data.schema,n)&&o.appliesTo(r)&&o.appliesToRole(s));return {permissive:i.filter(o=>o.data.permissive),restrictive:i.filter(o=>!o.data.permissive)}}schemasMatch(e,n){let r=e||this.defaultSchema,s=n||this.defaultSchema;return r===s}combineUsing(e,n,r){if(e.length===0)return {$always:false};let s=e.map(o=>o.data.using).filter(o=>o!=null&&Object.keys(o).length>0).map(o=>kt(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=kt(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=>kt(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=kt(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(!fu(e,n,i)){let a=r[0]??s[0];throw a?new Jt(a):new Error("RLS policy violation")}}};function SR(t){if(t.startsWith('"'))return t.replace(/^"(.*)"$/,"$1");let e=t.split(".");return (e[e.length-1]??t).replace(/^"(.*)"$/,"$1")}function _R(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 Mg(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function fu(t,e,n){return Wo(t,e,n)===true}function Wo(t,e,n){let r=true;for(let[s,i]of Object.entries(t)){if(s==="$always"){if(i===false)return false;i===null&&(r=null);continue}if(s==="$and"){let c=ER(i.map(u=>Wo(u,e,n)));if(c===false)return false;c===null&&(r=null);continue}if(s==="$or"){let c=xR(i.map(u=>Wo(u,e,n)));if(c===false)return false;c===null&&(r=null);continue}if(s==="$not"){let l=Wo(i,e,n);if(l===true)return false;l===null&&(r=null);continue}if(s==="$storageFolder"){let l=i;if(n&&!n.has(l.column))continue;let c=e[l.column],f=(typeof c=="string"?c.split("/").slice(0,-1):[])[l.index-1]??null;for(let[d,p]of Object.entries(l.ops)){let h=js(f,d,p);if(h===false)return false;h===null&&(r=null);}continue}if(s==="$storageObject"){let l=i;if(n&&!n.has(l.column))continue;let c=e[l.column],u=typeof c=="string"?c.split("/").at(-1)??"":null,f=u==null?null:l.function==="filename"?u:u.split(".").at(-1)??"";for(let[d,p]of Object.entries(l.ops)){let h=js(f,d,p);if(h===false)return false;h===null&&(r=null);}continue}if(n&&!n.has(s))continue;let o=i,a=e[s];for(let[l,c]of Object.entries(o)){let u=js(a,l,c);if(u===false)return false;u===null&&(r=null);}}return r}function ER(t){return t.includes(false)?false:t.includes(null)?null:true}function xR(t){return t.includes(true)?true:t.includes(null)?null:false}var Hg={role:"service_role",sub:null,jwt:{role:"service_role"}},Us=class{constructor(e,n,r){this.connection=e;this.auth=n;this.operation=r;}get ownerId(){return this.auth.role==="service_role"?null:this.auth.sub}async findBucketById(e){let n=await this.findBucketPolicyRow(e);return n?qg(n):null}async findBucketPolicyRow(e){return (await this.execute({type:"query",schema:"storage",from:"buckets",select:["*"],where:{id:{$eq:e}},limit:1}))[0]??null}async listBuckets(){return (await this.execute({type:"query",schema:"storage",from:"buckets",select:["*"]})).map(qg)}async createBucket(e){await this.execute({type:"insert",schema:"storage",from:"buckets",values:e});}async updateBucket(e,n){let r={type:"update",schema:"storage",from:"buckets",values:n,where:{id:{$eq:e}},select:["id"]};if(this.connection.dialect==="sqlite"){let i=await this.findBucketPolicyRow(e);if(!i)return 0;let o={...i,public:!!i.public,...n},a=await this.check({...r,values:o});return (await this.executeAuthorized({...a,values:n})).length}return (await this.execute(r)).length}async deleteBucket(e){let n={type:"delete",schema:"storage",from:"buckets",where:{id:{$eq:e}}},r=await this.check(n);if(this.connection.dialect==="sqlite"){if(!await this.connection.kysely.withSchema("storage").selectFrom("buckets").select("id").where("id","=",e).executeTakeFirst())return "not_found";if(await this.countBucketObjects(e)>0)return "not_empty";let i;try{i=await this.executeAuthorized(r);}catch(a){if(await this.countBucketObjects(e)>0)return "not_empty";throw a}return i.length>0?"deleted":await this.connection.kysely.withSchema("storage").selectFrom("buckets").select("id").where("id","=",e).executeTakeFirst()?await this.countBucketObjects(e)>0?"not_empty":"denied":"not_found"}return this.connection.runInTransaction(async s=>{if(await sql`
159
+ DECLARE storage_bucket_delete NO SCROLL CURSOR FOR
160
+ SELECT id FROM storage.buckets WHERE id = ${e} FOR UPDATE
161
+ `.execute(s),(await sql`
162
+ FETCH FORWARD 1 FROM storage_bucket_delete
163
+ `.execute(s)).rows.length===0)return "not_found";let o=await s.withSchema("storage").selectFrom("objects").select(s.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();if(Number(o?.count??0)>0)return "not_empty";let a=await this.connection.withContext(this.vars(),l=>sql`DELETE FROM storage.buckets WHERE CURRENT OF storage_bucket_delete`.execute(l),{transaction:s});return Number(pu(a)??0)>0?"deleted":"denied"})}async countBucketObjects(e){let n=await this.connection.kysely.withSchema("storage").selectFrom("objects").select(this.connection.kysely.fn.count("id").as("count")).where("bucket_id","=",e).executeTakeFirst();return Number(n?.count??0)}async findObjectByPath(e,n){let r=await this.findObjectPolicyRow(e,n);return r?mu(r):null}async findObjectForCopy(e,n){let r=await this.findObjectPolicyRow(e,n);return r?{...mu(r),metadata:Ko(r.metadata),user_metadata:RR(r.user_metadata)}:null}async findObjectPolicyRow(e,n){return (await this.execute({type:"query",schema:"storage",from:"objects",select:["*"],where:{$and:[{bucket_id:{$eq:e}},{name:{$eq:n}}]},limit:1}))[0]??null}async findObjectPolicyRowById(e){return (await this.execute({type:"query",schema:"storage",from:"objects",select:["*"],where:{id:{$eq:e}},limit:1}))[0]??null}async listObjects(e,n,r){let s=[{bucket_id:{$eq:e}}];return n&&s.push({name:{$like:`${n}%`}}),r?.search&&s.push({name:{$like:`%${r.search}%`}}),(await this.execute({type:"query",schema:"storage",from:"objects",select:["*"],where:s.length===1?s[0]:{$and:s},order:[r?.sortBy??{column:"name",direction:"asc"}].map(o=>({column:o.column,direction:o.direction??o.order})),limit:r?.limit,offset:r?.offset})).map(mu)}async probeInsertObject(e){let n={type:"insert",schema:"storage",from:"objects",values:this.connection.dialect==="sqlite"?Bg(e):e};if(this.connection.dialect==="sqlite"){await this.check(n);return}await this.execute(n,true);}async probeUpsertObject(e,n){if(this.connection.dialect==="sqlite"){let r=Bg(e);await this.check({type:"insert",schema:"storage",from:"objects",values:r});let s=await n();if(!s)return await this.probeProspectiveUpsert(r),null;let i=await this.findObjectPolicyRow(s.bucket_id,s.name);if(!i)throw Fs();return await this.probeUpdateObject(s.id,{...i,...e}),s}return await this.execute({type:"upsert",schema:"storage",from:"objects",values:e,onConflict:["bucket_id","name"]},true),n()}async probeProspectiveUpsert(e){let n={$and:[{bucket_id:{$eq:e.bucket_id}},{name:{$eq:e.name}}]};for(let r of [{type:"query",schema:"storage",from:"objects",select:["id"],where:n},{type:"update",schema:"storage",from:"objects",values:e,where:n}]){let s=await this.check(r);if(!fu(s.where??{},e))throw Fs()}}async probeUpdateObject(e,n){let r={type:"update",schema:"storage",from:"objects",values:n,where:{id:{$eq:e}}};if(this.connection.dialect==="sqlite"){let i=await this.findObjectPolicyRowById(e);if(!i)throw Fs();let o={...i,...n};typeof n.name=="string"&&(o.path_tokens=n.name.split("/"));let a=await this.check({...r,values:o});if((await this.executeAuthorized({type:"query",schema:"storage",from:"objects",select:["id"],where:a.where})).length===0)throw Fs();return}if((await this.execute(r,true)).length===0)throw Fs()}async probeDeleteObject(e){let n={type:"delete",schema:"storage",from:"objects",where:{id:{$eq:e}}};if(this.connection.dialect==="sqlite"){let s=await this.check(n);return (await this.executeAuthorized({type:"query",schema:"storage",from:"objects",select:["id"],where:s.where})).length>0}return (await this.execute(n,true)).length>0}vars(){return {auth:{uid:this.auth.sub,role:this.auth.role,jwt:this.auth.jwt},storage:{operation:this.operation??null,normalizedOperation:TR(this.operation)}}}async check(e){return this.connection.onPostgrestAST(e,this.vars())}async execute(e,n=false){let r=await this.check(e);return this.executeAuthorized(r,n)}async executeAuthorized(e,n=false,r){let s=await this.connection.introspect({useCache:true}),i=this.connection.config.translation?.deparse?.schema;return this.connection.withContext(this.vars(),async o=>{let a=await ee(e,this.connection.dialect,{db:o,introspection:s,schema:i}).execute(),l=Array.isArray(a)&&a.length===1&&pu(a[0])!==void 0?a[0]:a;if(Array.isArray(l))return l;let c=pu(l);return c===void 0?[]:Array(Number(c)).fill({})},{forceRollback:n,transaction:r})}};function TR(t){return t?t.startsWith("storage.")?t.slice(8):t:null}function pu(t){return t?.numUpdatedRows??t?.numDeletedRows??t?.numInsertedOrUpdatedRows??t?.numAffectedRows}function Fs(){return Object.assign(new Error("new row violates row-level security policy"),{code:"42501"})}function Bg(t){let e=new Date().toISOString(),n={id:crypto.randomUUID(),bucket_id:null,name:null,owner:null,owner_id:null,metadata:null,user_metadata:null,version:null,created_at:e,updated_at:e,last_accessed_at:e,path_tokens:typeof t.name=="string"?t.name.split("/"):null,...t};for(let r of Object.keys(n))n[r]===void 0&&(n[r]=null);return n}function Ko(t){if(t==null)return {};if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return {}}}function RR(t){return t==null?null:Ko(t)}function Wg(t){if(Array.isArray(t))return t.map(String);if(typeof t!="string")return [];try{let e=JSON.parse(t);return Array.isArray(e)?e.map(String):[]}catch{return []}}function qg(t){return {...t,owner:t.owner??"",owner_id:t.owner_id??"",public:!!t.public,allowed_mime_types:t.allowed_mime_types==null?null:Wg(t.allowed_mime_types)}}function mu(t){return {...t,owner:t.owner??null,owner_id:t.owner_id??null,metadata:Ko(t.metadata),user_metadata:Ko(t.user_metadata),path_tokens:Wg(t.path_tokens)}}var Ms=class{constructor(e,n,r,s={},i,o){this.repo=e;this.adapter=n;this.config=r;this.options=s;this.transformationAdapter=i;this.connection=o;if(!o)throw new Error("StorageService requires a database connection");this.access=new Us(o,Hg);}initialized=false;access;setRequestAuth(e,n){this.access=new Us(this.connection,e,n);}get requestAuth(){return this.access.auth}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?vR(n.file_size_limit):null,allowed_mime_types:n.allowed_mime_types});}async createBucket(e){let n=new Date().toISOString(),r=this.access.ownerId;try{await this.access.createBucket({id:e.id,name:e.name,owner:r,owner_id:r,public:e.public??!1,file_size_limit:e.file_size_limit??null,allowed_mime_types:e.allowed_mime_types??null,created_at:n,updated_at:n});}catch(s){throw this.databaseErrorCode(s)==="23505"?P.bucketAlreadyExists(e.id):s}return await this.repo.findBucketById(e.id)}async getBucket(e){let n=await this.access.findBucketById(e);if(!n)throw P.bucketNotFound(e);return n}async getBucketBypass(e){let n=await this.repo.findBucketById(e);if(!n)throw P.bucketNotFound(e);return n}async listBuckets(){return this.access.listBuckets()}async updateBucket(e,n){if(!await this.access.findBucketById(e))throw P.bucketNotFound(e);let s={updated_at:new Date().toISOString()};if(n.public!==void 0&&(s.public=n.public),n.file_size_limit!==void 0&&(s.file_size_limit=n.file_size_limit),n.allowed_mime_types!==void 0&&(s.allowed_mime_types=n.allowed_mime_types),await this.access.updateBucket(e,s)===0)throw P.bucketNotFound(e);return await this.repo.findBucketById(e)}async deleteBucket(e){let n=await this.access.deleteBucket(e);if(n==="not_empty")throw P.bucketNotEmpty(e);if(n!=="deleted")throw P.bucketNotFound(e)}async emptyBucket(e){if(!await this.access.findBucketById(e))throw P.bucketNotFound(e);if((await this.access.listObjects(e,void 0,{limit:1})).length===0)return;let i=(await this.repo.listObjects(e)).map(o=>o.name);i.length>0&&(await this.adapter.deleteObjects(e,i),await this.repo.deleteObjectsByBucket(e));}async upload(e,n,r,s){return this.uploadInternal(e,n,r,s,false,this.access.ownerId)}async uploadInternal(e,n,r,s,i,o){hu(n);let a=await this.repo.findBucketById(e);if(!a)throw P.bucketNotFound(e);let l=s?.contentType??"application/octet-stream",c=s?.cacheControl??"no-cache";if(a.allowed_mime_types&&a.allowed_mime_types.length>0&&!a.allowed_mime_types.includes(l))throw P.invalidMimeType(l,a.allowed_mime_types);let u=a.file_size_limit??this.config.fileSizeLimit??null;if(u&&s?.contentLength&&s.contentLength>u)throw P.fileTooLarge(u);let f={mimetype:l};s?.contentLength!==void 0&&(f.contentLength=s.contentLength),Object.assign(f,s?.metadata);let d=this.uploadPermissionValues({bucketId:e,path:n,owner:o,metadata:f}),p;if(i)p=await this.repo.findObjectByPath(e,n);else if(s?.upsert)p=await this.access.probeUpsertObject(d,()=>this.repo.findObjectByPath(e,n));else {try{await this.access.probeInsertObject(d);}catch(w){throw this.databaseErrorCode(w)==="23505"?P.bucketAlreadyExists(n):w}p=await this.repo.findObjectByPath(e,n);}if(p&&!s?.upsert)throw P.bucketAlreadyExists(n);let h=crypto.randomUUID(),m=p?.id??crypto.randomUUID(),y={httpStatusCode:200,...await this.adapter.uploadObject(e,n,void 0,r,l,c),...s?.metadata};return p&&s?.upsert?await this.repo.updateObject(p.id,{metadata:y,version:h,owner:o,owner_id:o}):this.repo.createObject({id:m,bucket_id:e,name:n,owner:o,owner_id:o,metadata:y,version:h})}async download(e,n,r){let s=await this.repo.findBucketById(e);if(!s)throw P.bucketNotFound(e);this.assertBucketRetrievable(s);let i=s.public?await this.repo.findObjectByPath(e,n):await this.access.findObjectByPath(e,n);if(!i)throw P.objectNotFound(n);return this.downloadObject(e,n,i,r)}async downloadBypass(e,n,r){let s=await this.repo.findObjectByPath(e,n);if(!s)throw P.objectNotFound(n);return this.downloadObject(e,n,s,r)}async downloadObject(e,n,r,s){if(await this.repo.touchObject(r.id),s?.transform&&this.transformationAdapter&&!this.transformationAdapter.requiresBuffer&&this.transformationAdapter.transformFromUrl){let o=await this.adapter.privateAssetUrl(e,n,r.version??void 0),a=await this.transformationAdapter.transformFromUrl(o,s.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,r.version??void 0);if(!i.body)throw P.objectNotFound(n);if(s?.transform&&this.transformationAdapter?.requiresBuffer){let o=await AR(i.body),a=await this.transformationAdapter.transform(o,s.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 P.bucketNotFound(e);let s=[];for(let i of n){let o=await this.repo.findObjectByPath(e,i);if(o){if(!await this.access.probeDeleteObject(o.id))continue;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 P.bucketNotFound(e);return this.access.listObjects(e,n,r)}async move(e,n,r,s=e){if(hu(r),!await this.repo.findBucketById(e))throw P.bucketNotFound(e);let o=await this.access.findObjectByPath(e,n);if(!o)throw P.objectNotFound(n);let a=e===s&&n===r,l=crypto.randomUUID(),c={bucket_id:s,name:r,version:l,owner:this.access.ownerId,owner_id:this.access.ownerId,updated_at:new Date().toISOString()};try{await this.access.probeUpdateObject(o.id,c);}catch(u){let f=this.databaseErrorCode(u);throw f==="23505"?P.bucketAlreadyExists(r):f==="23503"?P.relatedResourceNotFound():u}if(!a){if(!await this.repo.findBucketById(s))throw P.relatedResourceNotFound();if(await this.repo.findObjectByPath(s,r))throw P.bucketAlreadyExists(r);await this.adapter.copyObject(e,n,o.version??void 0,s,r,l),await this.adapter.deleteObject(e,n,o.version??void 0),await this.repo.updateObject(o.id,c);}}async copy(e,n,r,s=e,i=false){if(hu(r),!await this.repo.findBucketById(e))throw P.bucketNotFound(e);let a=await this.access.findObjectForCopy(e,n);if(!a)throw P.objectNotFound(n);let l=this.access.ownerId,c=this.uploadPermissionValues({bucketId:s,path:r,owner:l,metadata:a.metadata,userMetadata:a.user_metadata}),u;try{i?u=await this.access.probeUpsertObject(c,()=>this.repo.findObjectByPath(s,r)):(await this.access.probeInsertObject(c),u=await this.repo.findObjectByPath(s,r));}catch(m){let g=this.databaseErrorCode(m);throw g==="23505"?P.bucketAlreadyExists(r):g==="23503"?P.relatedResourceNotFound():m}if(!await this.repo.findBucketById(s))throw P.relatedResourceNotFound();if(u&&!i)throw P.bucketAlreadyExists(r);let f=u?.id??crypto.randomUUID(),d=crypto.randomUUID(),p=await this.adapter.copyObject(e,n,a.version??void 0,s,r,void 0),h={...a.metadata,lastModified:p.lastModified,eTag:p.eTag};return u?await this.repo.updateObject(u.id,{metadata:h,user_metadata:a.user_metadata,version:d,owner:l,owner_id:l}):await this.repo.createObject({id:f,bucket_id:s,name:r,owner:l,owner_id:l,metadata:h,user_metadata:a.user_metadata,version:d}),{key:r}}async info(e,n){let r=await this.repo.findBucketById(e);if(!r)throw P.bucketNotFound(e);this.assertBucketRetrievable(r);let s=r.public?await this.repo.findObjectByPath(e,n):await this.access.findObjectByPath(e,n);if(!s)throw P.objectNotFound(n);let i=await this.adapter.headObject(e,n,s.version??void 0);return {...s,httpMetadata:i}}async exists(e,n){let r=await this.repo.findBucketById(e);return r?(this.assertBucketRetrievable(r),r.public?this.repo.objectExists(e,n):await this.access.findObjectByPath(e,n)!==null):false}assertBucketRetrievable(e){if(!e.public&&this.access.auth.jwt===null)throw P.bucketNotFound(e.id)}async createSignedUrl(e,n,r){if(!await this.repo.findBucketById(e))throw P.bucketNotFound(e);if(!await this.access.findObjectByPath(e,n))throw P.objectNotFound(n);let o=await this.signStorageToken({sub:n,bucket:e,intent:"download"},r);return {signedUrl:`/storage/v1/object/sign/${e}/${n}?token=${o}`}}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,r=false,s){let i=this.access.ownerId,o=this.uploadPermissionValues({bucketId:e,path:n,owner:i,metadata:s?.metadata,userMetadata:s?.userMetadata});try{r?await this.access.probeUpsertObject(o,()=>this.repo.findObjectByPath(e,n)):await this.access.probeInsertObject(o);}catch(l){let c=this.databaseErrorCode(l);throw c==="23505"?P.bucketAlreadyExists(n):c==="23503"?P.relatedResourceNotFound():l}if(!await this.repo.findBucketById(e))throw P.relatedResourceNotFound();if(!r&&await this.repo.findObjectByPath(e,n))throw P.bucketAlreadyExists(n);let a=await this.signStorageToken({sub:n,bucket:e,intent:"upload",owner:i,upsert:r},7200);return {signedUrl:`/storage/v1/object/upload/sign/${e}/${n}?token=${a}`,token:a,path:n}}async verifySignedUrl(e){let n=new TextEncoder().encode(this.config.jwtSecret),{payload:r}=await jwtVerify(e,n,{algorithms:["HS256"]});return {bucket:r.bucket,path:r.sub,intent:r.intent,owner:typeof r.owner=="string"?r.owner:null,upsert:r.upsert===true}}async downloadSigned(e,n,r){return this.downloadBypass(e,n,r)}async uploadSigned(e,n,r,s){let{owner:i,...o}=s;return this.uploadInternal(e,n,r,o,true,i)}async signStorageToken(e,n){let r=new TextEncoder().encode(this.config.jwtSecret),s=Math.floor(Date.now()/1e3);return new SignJWT({...e,iat:s}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt(s).setExpirationTime(s+n).sign(r)}uploadPermissionValues(e){let n={bucket_id:e.bucketId,name:e.path,owner:e.owner,owner_id:e.owner,version:"1"};return e.metadata!==void 0&&(n.metadata=e.metadata),e.userMetadata!==void 0&&(n.user_metadata=e.userMetadata),this.connection?.dialect==="sqlite"&&(n.path_tokens=e.path.split("/")),n}databaseErrorCode(e){return this.connection.normalizeDbError(e)?.code}};async function AR(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 hu(t){if(!t||t.includes("..")||t.startsWith("/"))throw P.invalidKey(t)}function vR(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 OR=t=>t.req[xi][0].map(([[,e]])=>e);var PR=(t,e)=>OR(t).at(e??t.req.routeIndex)?.basePath??"",Kg=new WeakMap,Jg=(t,e)=>{e??=t.req.routeIndex;let n=Kg.get(t)||[];if(typeof n[e]=="string")return n[e];let r,s=PR(t,e);if(!/[:*]/.test(s))r=s;else {let i=Ci(s),o=t.req.path,a=0;for(let l=0,c=i.length;l<c;l++){let u=ki(i[l],i[l+1]);if(u){let f=u[2]===true||u==="*"?/[^\/]+/:u[2];a+=o.substring(a+1).match(f)?.[0].length||0;}else a+=i[l].length;a+=1;}r=o.substring(0,a);}return n[e]=r,Kg.set(t,n),r};var $R=s.object({id:s.string(),name:s.string(),public:s.boolean({default:false}).optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),NR=s.object({public:s.boolean().optional(),file_size_limit:s.number().optional(),allowed_mime_types:s.array(s.string()).optional()}),IR=s.object({prefix:s.string().optional(),limit:s.number().optional(),offset:s.number().optional(),sortBy:s.object({column:s.string(),order:s.string()}).optional(),search:s.string().optional()}),Gg=s.object({bucketId:s.string(),sourceKey:s.string(),destinationBucket:s.string().optional(),destinationKey:s.string()}),DR=s.object({expiresIn:s.number()}),jR=s.object({expiresIn:s.number(),paths:s.array(s.string())}),LR=s.object({prefixes:s.array(s.string())}),FR=new Te().get("/status",async t=>t.json({status:"ok"},200)).get("/object/public/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(t.req.path,`/object/public/${e}/`),{storageService:r}=t.var;if(!(await r.getBucketBypass(e)).public)throw P.bucketNotFound(e);let i=gu(t.req.query()),o=await r.downloadSigned(e,n,{transform:i??void 0});return new Response(o.body,{headers:bu(o.metadata)})}).get("/object/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(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||i.intent!=="download")return t.json({error:"Invalid token"},403);let o=gu(t.req.query()),a=await s.downloadSigned(e,n,{transform:o??void 0});return new Response(a.body,{headers:bu(a.metadata)})}).put("/object/upload/sign/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(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=yu(t.req.header("content-type")),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.uploadSigned(e,n,l,{contentType:o,contentLength:a,upsert:i.upsert,owner:i.owner});return t.json({Key:c.name},200)}),UR=new Te().use("*",MR).post("/bucket",validator("json",$R),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",validator("json",NR),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",validator("json",IR),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",validator("json",Gg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var;return await n.move(e.bucketId,e.sourceKey,e.destinationKey,e.destinationBucket),t.json({message:"Successfully moved"},200)}).post("/object/copy",validator("json",Gg),async t=>{let e=t.req.valid("json"),{storageService:n}=t.var,r=await n.copy(e.bucketId,e.sourceKey,e.destinationKey,e.destinationBucket,t.req.header("x-upsert")==="true");return t.json({key:r.key},200)}).get("/object/info/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(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/*",validator("json",DR),async t=>{let e=t.req.param("bucketId"),n=mt(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",validator("json",jR),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=mt(t.req.path,`/object/upload/sign/${e}/`),{storageService:r}=t.var,s=t.req.header("content-type"),i=t.req.header("content-length"),o={};s!==void 0&&(o.mimetype=s),i!==void 0&&(o.contentLength=Number(i));let a=await r.createSignedUploadUrl(e,n,t.req.header("x-upsert")==="true",{metadata:o,userMetadata:WR(t.req.header("x-metadata"))});return t.json(a,200)}).delete("/object/:bucketId",validator("json",LR),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=mt(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 P(400,"InvalidRequest","Missing file in multipart upload");let p=new Uint8Array(await d.arrayBuffer());a=p,l=HR(d.type),c=p.length;}else a=t.req.raw.body??new Uint8Array(await t.req.arrayBuffer()),l=yu(s),c=t.req.header("content-length")?Number.parseInt(t.req.header("content-length"),10):void 0;let u=await r.upload(e,n,a,{contentType:l,cacheControl:i,contentLength:c,upsert:o});return t.json({Key:`${e}/${u.name}`,Id:u.id},200)}).put("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=yu(t.req.header("content-type")),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});return t.json({Key:`${e}/${l.name}`,Id:l.id},200)}).get("/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(t.req.path,`/object/${e}/`),{storageService:r}=t.var,s=gu(t.req.query()),i=await r.download(e,n,{transform:s??void 0});return new Response(i.body,{headers:bu(i.metadata)})}).on("HEAD","/object/:bucketId/*",async t=>{let e=t.req.param("bucketId"),n=mt(t.req.path,`/object/${e}/`),{storageService:r}=t.var;return await r.exists(e,n)?t.body(null,200):t.body(null,404)}),wu=new Te().onError((t,e)=>{if(t instanceof P)return e.json(t.toJSON(),t.status===401?401:400);if(t instanceof Jt||qR(e.var.app.connection.normalizeDbError(t))){let n=new P(403,"Unauthorized","new row violates row-level security policy");return e.json(n.toJSON(),400)}return console.error("Storage error:",t),e.json({error:"server_error",message:"Internal server error"},500)}).route("/",FR).route("/",UR).all("*",async t=>{let e=t.req.path.replace(Jg(t),"");return t.json({message:`Route ${t.req.method}:${e} not found`,error:"Not Found",statusCode:404},404)});function mt(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)}async function MR(t,e){let r=t.var.ignoreAuthorization?t.var.jwt:void 0;if(!r){let a=t.req.header("Authorization"),l=await go(a,{jwtSecret:t.var.app.config.auth?.jwt_secret,anonymousEnabled:a===void 0||Vg(t.req.method,t.req.path)});if(l.kind==="error")if(Vg(t.req.method,t.req.path))r=void 0;else {let c=await l.response.json().catch(()=>({})),u=new P(401,"InvalidJWT",c.message??"Invalid JWT");return t.json(u.toJSON(),401)}else r=l.payload;}let s=r?.role,o={role:typeof s=="string"&&s.length>0?s:"anon",sub:typeof r?.sub=="string"?r.sub:null,jwt:r??null};t.var.storageService.setRequestAuth(o,BR(t.req.method,t.req.path)),await e();}function BR(t,e){let n=e.replace(/^\/storage\/v1/,"");if(n==="/bucket"){if(t==="POST")return "storage.bucket.create";if(t==="GET")return "storage.bucket.list"}if(/^\/bucket\/[^/]+\/empty$/.test(n)&&t==="POST")return "storage.bucket.empty";if(/^\/bucket\/[^/]+$/.test(n)){if(t==="GET")return "storage.bucket.get";if(t==="PUT")return "storage.bucket.update";if(t==="DELETE")return "storage.bucket.delete"}if(/^\/object\/list\/[^/]+$/.test(n)&&t==="POST")return "storage.object.list";if(n==="/object/move"&&t==="POST")return "storage.object.move";if(n==="/object/copy"&&t==="POST")return "storage.object.copy";if(/^\/object\/info\/[^/]+\/.+/.test(n)&&t==="GET")return "object.get_authenticated_info";if(/^\/object\/upload\/sign\/[^/]+\/.+/.test(n)&&t==="POST")return "storage.object.sign_upload_url";if(/^\/object\/sign\/[^/]+\/.+/.test(n)&&t==="POST")return "storage.object.sign";if(/^\/object\/sign\/[^/]+$/.test(n)&&t==="POST")return "storage.object.sign_many";if(/^\/object\/[^/]+$/.test(n)&&t==="DELETE")return "storage.object.delete_many";if(/^\/object\/[^/]+\/.+/.test(n)){if(t==="POST")return "storage.object.upload";if(t==="PUT")return "storage.object.upload_update";if(t==="GET")return "storage.object.get_authenticated";if(t==="HEAD")return "object.head_authenticated_info"}}function Vg(t,e){let n=e.replace(/^\/storage\/v1/,"");return t==="GET"&&/^\/object\/info\/[^/]+\/.+/.test(n)?true:(t==="GET"||t==="HEAD")&&/^\/object\/(?!info\/|public\/|sign\/|upload\/)[^/]+\/.+/.test(n)}function qR(t){return t?.code==="42501"||t instanceof Error&&t.message==="RLS policy violation"}function gu(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 yu(t){return t||"application/octet-stream"}function HR(t){return t?.split(";",1)[0].trim()||"application/octet-stream"}function WR(t){if(t!==void 0)try{let e=atob(t),n=Uint8Array.from(e,r=>r.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}catch{return}}function bu(t){let e={"Content-Type":t.mimetype,"Cache-Control":t.cacheControl,ETag:t.eTag,"Accept-Ranges":"bytes","X-Robots-Tag":"none"};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}Hn();var Su=`-- supabase/storage core schema (Postgres)
159
164
  -- Source: supabase/storage migrations (consolidated)
160
165
 
161
166
  CREATE SCHEMA IF NOT EXISTS storage;
@@ -173,14 +178,14 @@ CREATE TABLE IF NOT EXISTS storage.buckets (
173
178
  );
174
179
 
175
180
  CREATE TABLE IF NOT EXISTS storage.objects (
176
- id uuid NOT NULL PRIMARY KEY,
181
+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
177
182
  bucket_id text REFERENCES storage.buckets(id),
178
183
  name text,
179
184
  owner uuid,
180
185
  owner_id text,
181
186
  metadata jsonb,
182
187
  user_metadata jsonb,
183
- path_tokens text[],
188
+ path_tokens text[] GENERATED ALWAYS AS (string_to_array(name, '/')) STORED,
184
189
  version text,
185
190
  created_at timestamptz DEFAULT now(),
186
191
  updated_at timestamptz DEFAULT now(),
@@ -190,11 +195,111 @@ CREATE TABLE IF NOT EXISTS storage.objects (
190
195
  );
191
196
 
192
197
  CREATE INDEX IF NOT EXISTS storage_objects_name_pattern_search ON storage.objects (name text_pattern_ops);
193
- `;function ko(t=true){return t?Qr(zc):zc}var vo=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function pg(t){if(!t._storageAdapter)throw Z.storageNotConfigured();let e=t.connection.dialect,n=new Os(t.connection.kysely,e),r=t.config.auth?.jwt_secret??"",s=t._transformationAdapter??new vo;return new Ps(n,t._storageAdapter,{jwtSecret:r,fileSizeLimit:t.config.storage?.file_size_limit?YT(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},s)}function YT(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 Ke=Symbol("RENDERER"),Jt=Symbol("ERROR_HANDLER"),ee=Symbol("STASH"),Ao=Symbol("INTERNAL"),Vc=Symbol("MEMO"),er=Symbol("PERMALINK");var Qc=t=>(t[Ao]=true,t);var Yc=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:Qc(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Qc(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[Jt]=i=>{throw t.pop(),i},s},Oo=t=>{let e=[t],n=Yc(e);return n.values=e,n.Provider=n,Tt.push(n),n};var Tt=[],$s=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new Xc("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>X(i,i.callbacks)):(e.pop(),X(s))});return n.values=e,n.Provider=n,n[Ke]=Yc(e),Tt.push(n),n},Re=t=>t.values.at(-1);var tr={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Is={},nr="data-precedence";var js={};Zs(js,{button:()=>iR,form:()=>rR,input:()=>sR,link:()=>tR,meta:()=>nR,script:()=>ZT,style:()=>eR,title:()=>XT});var wn=t=>Array.isArray(t)?t:[t];var mg=new WeakMap,hg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=mg.get(i)||{};mg.set(i,o);let a=o[t]||=[],l=false,c=tr[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 g=u.indexOf(p);return g===-1&&(u.push(p),g=u.length-1),[d,g]}).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(""));}},Ns=(t,e,n)=>X(new Ue(t,n,wn(e??[])).toString()),Ds=(t,e,n,r)=>{if("itemProp"in n)return Ns(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[nr]=s);let a=new Ue(t,o,wn(e||[])).toString();return a instanceof Promise?a.then(l=>X(a,[...l.callbacks||[],hg(t,l,o,s)])):X(a,[hg(t,a,o,s)])},XT=({children:t,...e})=>{let n=Po();if(n){let r=Re(n);if(r==="svg"||r==="head")return new Ue("title",e,wn(t??[]))}return Ds("title",t,e,false)},ZT=({children:t,...e})=>{let n=Po();return ["src","async"].some(r=>!e[r])||n&&Re(n)==="head"?Ns("script",t,e):Ds("script",t,e,false)},eR=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ds("style",t,e,true)):Ns("style",t,e),tR=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ns("link",t,e):Ds("link",t,e,"precedence"in e),nR=({children:t,...e})=>{let n=Po();return n&&Re(n)==="head"?Ns("meta",t,e):Ds("meta",t,e,false)},gg=(t,{children:e,...n})=>new Ue(t,n,wn(e??[])),rR=t=>(typeof t.action=="function"&&(t.action=er in t.action?t.action[er]:void 0),gg("form",t)),yg=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=er in e.formAction?e.formAction[er]:void 0),gg(t,e)),sR=t=>yg("input",t),iR=t=>yg("button",t);var oR=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),rr=t=>oR.get(t)||t,Ls=(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 Fs=void 0,Po=()=>Fs,aR=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,lR=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],cR=["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"],eu=(t,e)=>{for(let n=0,r=t.length;n<r;n++){let s=t[n];if(typeof s=="string")bt(s,e);else {if(typeof s=="boolean"||s===null||s===void 0)continue;s instanceof Ue?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):eu(s,e);}}},Ue=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?Ea(X(t[0],t.callbacks)).toString():t[0]:bi(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Fs&&Re(Fs)==="svg"?i=>aR(rr(i)):i=>rr(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";Ls(o,(l,c)=>{c!=null&&(a+=`${a?";":""}${l}:${c}`);}),t[0]+=' style="',bt(a,t),t[0]+='"';}else if(typeof o=="string")t[0]+=` ${i}="`,bt(o,t),t[0]+='"';else if(o!=null)if(typeof o=="number"||o.isEscaped)t[0]+=` ${i}="${o}"`;else if(typeof o=="boolean"&&cR.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=[X(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}="`,bt(o.toString(),t),t[0]+='"';}if(lR.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",eu(r,t),t[0]+=`</${e}>`;}},Zc=class extends Ue{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(Tt.length===0)t.unshift("",r);else {let s=Tt.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof Ue&&(i.localContexts=s),i)));}else r instanceof Ue?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):bt(r,t);}},Xc=class extends Ue{toStringToBuffer(t){eu(this.children,t);}},bg=false,Us=(t,e,n)=>{if(!bg){for(let r in Is)js[r][Ke]=Is[r];bg=true;}return typeof t=="function"?new Zc(t,e,n):js[t]?new Zc(js[t],e,n):t==="svg"||t==="head"?(Fs||=$s(""),new Ue(t,e,[new Zc(Fs,{value:t},n)])):new Ue(t,e,n)};var dt=({children:t})=>new Xc("",{children:t},Array.isArray(t)?t:t?[t]:[]);var Do={};Zs(Do,{button:()=>Kg,clearCache:()=>_R,composeRef:()=>No,form:()=>qg,input:()=>Wg,link:()=>Ug,meta:()=>Mg,script:()=>Lg,style:()=>Fg,title:()=>jg});var Bs="_hp",uR={Change:"Input",DoubleClick:"DblClick"},fR={svg:"2000/svg",math:"1998/Math/MathML"},pt=[],ru=new WeakMap,sr=void 0,Rg=()=>sr,Rt=t=>"t"in t,nu={onClick:["click",false]},wg=t=>{if(!t.startsWith("on"))return;if(nu[t])return nu[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return nu[t]=[(uR[n]||n).toLowerCase(),!!r]}},Sg=(t,e)=>sr&&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,dR=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=rr(r);let i=wg(r);if(i){if(n?.[r]!==s&&(n&&t.removeEventListener(i[0],n[r],i[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(i[0],s,i[1]);}}else if(r==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(r==="ref"){let o;typeof s=="function"?o=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,o=()=>s.current=null),ru.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&Ls(s,o.setProperty.bind(o)));}else {if(r==="value"){let a=t.nodeName;if(a==="INPUT"||a==="TEXTAREA"||a==="SELECT"){if(t.value=s==null||s===false?null:s,a==="TEXTAREA"){t.textContent=s;continue}else if(a==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else (r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=s);let o=Sg(t,r);s==null||s===false?t.removeAttribute(o):s===true?t.setAttribute(o,""):typeof s=="string"||typeof s=="number"?t.setAttribute(o,s):t.setAttribute(o,s.toString());}}}if(n)for(let r in n){let s=n[r];if(r!=="children"&&!(r in e)){r=rr(r);let i=wg(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?ru.get(t)?.():t.removeAttribute(Sg(t,r));}}},pR=(t,e)=>{e[ee][0]=0,pt.push([t,e]);let n=e.tag[Ke]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{pt.pop();}},Cg=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ee][1][iu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(Rt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(Cg(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);});},mR=t=>{for(;t&&(t.tag===Bs||!t.e);)t=t.tag===Bs||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},kg=t=>{Rt(t)||(t[ee]?.[1][iu]?.forEach(e=>e[2]?.()),ru.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(kg)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(Ms.delete(t),$o.delete(t),delete t[ee][3],t.a=true);},vg=(t,e,n)=>{t.c=e,Ag(t,e,n);},_g=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Eg=Symbol(),Ag=(t,e,n)=>{let r=[],s=[],i=[];Cg(t,e,r,s,i),s.forEach(kg);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=_g(o,mR(t.nN));c!==void 0?(l=o[c],a=c):a=_g(o,r.find(f=>f.tag!==Bs&&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;Rt(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),dR(d,u.props,u.pP),Ag(u,d,p));}u.tag===Bs?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());});}},hR=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),$o=new WeakMap,su=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?pR(t,e):wn(e.props.children),n[0]?.tag===""&&n[0][Jt]&&(s=n[0][Jt],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=gR(n[l]);if(c){typeof c.tag=="function"&&!c.tag[Ao]&&(Tt.length>0&&(c[ee][2]=Tt.map(u=>[u,u.values.at(-1)])),t[5]?.length&&(c[ee][3]=t[5].at(-1)));let f;if(i&&i.length){let u=i.findIndex(Rt(c)?d=>Rt(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(Rt(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[ee][2];f[ee][2]=c[ee][2]||[],f[ee][3]=c[ee][3],!f.f&&((f.o||f)===c.o||f.tag[Vc]?.(u,f.props))&&hR(d,f[ee][2])&&(f.s=!0);}c=f;}else if(!Rt(c)&&sr){let u=Re(sr);u&&(c.n=u);}if(!Rt(c)&&!c.s&&(su(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let u=a;u&&!Rt(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===Eg){if(s)return;throw i}let[o,a,l]=e[ee]?.[3]||[];if(a){let c=()=>qs([0,false,t[2]],l),f=$o.get(l)||[];f.push(c),$o.set(l,f);let u=a(i,()=>{let d=$o.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(su(t,l,[u]),(a.length===1||t!==o)&&l.c){vg(l,l.c,false);return}throw Eg}}throw i}finally{s&&t[5].pop();}},gR=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return {t:t.toString(),d:true};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ee]=[0,[]];else {let e=fR[t.tag];e&&(sr||=Oo(""),t.props.children=[{tag:sr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var xg=(t,e)=>{e[ee][2]?.forEach(([n,r])=>{n.values.push(r);});try{su(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[ee][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&vg(e,e.c,false);},Ms=new WeakMap,Tg=[],qs=async(t,e)=>{t[5]||=[];let n=Ms.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(Ms.set(e,[r,()=>{t[2]?t[2](t,e,i=>{xg(i,e);}).then(()=>r(e)):(xg(t,e),r(e));}]),Tg.length)Tg.at(-1).add(e);else {await Promise.resolve();let i=Ms.get(e);i&&(Ms.delete(e),i[1]());}return s};var Og=(t,e,n)=>({tag:Bs,props:{children:t},key:n,e,p:1});var yR=0,iu=1,bR=2,wR=3;var ou=new WeakMap,$g=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var SR=void 0;var Pg=[];var Io=t=>{let e=()=>typeof t=="function"?t():t,n=pt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[ee][1][yR]||=[],i=r[ee][0]++;return s[i]||=[e(),o=>{let a=SR,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,Pg.length){let[c,f]=Pg.at(-1);Promise.all([c===3?r:qs([c,false,a],r),f]).then(([u])=>{if(!u||!(c===2||c===3))return;let d=u.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===u.vC&&qs([c===3?1:0,false,a],u);});});});}else qs([0,false,a],r);}]};var ir=(t,e)=>{let n=pt.at(-1);if(!n)return t;let[,r]=n,s=r[ee][1][bR]||=[],i=r[ee][0]++,o=s[i];return $g(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var au=t=>{let e=ou.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ou.set(t,[n]),n=>ou.set(t,[void 0,n])),t},lu=(t,e)=>{let n=pt.at(-1);if(!n)return t();let[,r]=n,s=r[ee][1][wR]||=[],i=r[ee][0]++,o=s[i];return $g(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var Ng=Oo({pending:false,data:null,method:null,action:null}),Ig=new Set,Dg=t=>{Ig.add(t),t.finally(()=>Ig.delete(t));};var _R=()=>{cu=Object.create(null),uu=Object.create(null);},No=(t,e)=>lu(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null);}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null;}));let s=e(n);return ()=>{s?.(),r?.();}},[t]),cu=Object.create(null),uu=Object.create(null),Hs=(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=tr[t],g;if(p.length>0){let w=i.querySelectorAll(t);e:for(let S of w)for(let b of tr[t])if(S.getAttribute(b)===e[b]){u=S;break e}if(!u){let S=p.reduce((b,_)=>e[_]===void 0?b:`${b}-${_}-${e[_]}`,t);d=!uu[S],u=uu[S]||=(()=>{let b=document.createElement(t);for(let _ of p)e[_]!==void 0&&b.setAttribute(_,e[_]),e.rel&&b.setAttribute("rel",e.rel);return b})();}}else g=i.querySelectorAll(t);l=r?l??"":void 0,r&&(f[nr]=l);let m=ir(w=>{if(p.length>0){let S=false;for(let b of i.querySelectorAll(t)){if(S&&b.getAttribute(nr)!==l){i.insertBefore(w,b);return}b.getAttribute(nr)===l&&(S=true);}i.appendChild(w);}else if(g){let S=false;for(let b of g)if(b===w){S=true;break}S||i.insertBefore(w,i.contains(g[0])?g[0]:i.querySelector(t)),g=void 0;}},[l]),h=No(e.ref,w=>{let S=p[0];if(n===2&&(w.innerHTML=""),(d||g)&&m(w),!a&&!o)return;let b=cu[w.getAttribute(S)]||=new Promise((_,E)=>{w.addEventListener("load",_),w.addEventListener("error",E);});o&&(b=b.then(o)),a&&(b=b.catch(a)),b.catch(()=>{});});if(s&&c==="render"){let w=tr[t][0];if(e[w]){let S=e[w],b=cu[S]||=new Promise((_,E)=>{m(u),u.addEventListener("load",_),u.addEventListener("error",E);});au(b);}}let y={tag:t,type:t,props:{...f,ref:h},ref:h};return y.p=n,u&&(y.e=u),Og(y,i)},jg=t=>{let e=Rg();return (e&&Re(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Hs("title",t,void 0,false,false)},Lg=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Hs("script",t,1,false,true),Fg=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,Hs("style",t,2,true,true)),Ug=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}:Hs("link",t,1,"precedence"in t,true),Mg=t=>Hs("meta",t,void 0,false,false),Bg=Symbol(),qg=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Io([null,false]),i=ir(async c=>{let f=c.isTrusted?e:c.detail[Bg];if(typeof f!="function")return;c.preventDefault();let u=new FormData(c.target);s([u,true]);let d=f(u);d instanceof Promise&&(Dg(d),await d),s([null,true]);},[]),o=No(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:Ng,props:{value:{pending:a!==null,data:a,method:a?"post":null,action:a?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},Hg=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=ir(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Bg]:e}}));},[]);n.ref=No(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Wg=t=>Hg("input",t),Kg=t=>Hg("button",t);Object.assign(Is,{title:jg,script:Lg,style:Fg,link:Ug,meta:Mg,form:qg,input:Wg,button:Kg});$s(null);new TextEncoder;var Sn=":-hono-global",RR=new RegExp(`^${Sn}{(.*)}$`),Fo="hono-css",Ct=Symbol(),ge=Symbol(),De=Symbol(),mt=Symbol(),Uo=Symbol(),Qg=Symbol();var Yg=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},CR=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),kR=new RegExp(["("+CR+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),vR=t=>t.replace(kR,(e,n,r,s,i)=>n||r||s||i||""),Xg=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,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[Qg])i+=u[Qg];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[mt]),r.push(...u[Uo]),u=u[De];let d=u.length;if(d>0){let p=u[d-1];p!==";"&&p!=="}"&&(u+=";");}}i+=`${u||""}`;}}}}return [s,vR(i),n,r]},or=(t,e)=>{let[n,r,s,i]=Xg(t,e),o=RR.exec(r);o&&(r=o[1]);let a=(o?Sn:"")+Yg(n+r),l=(o?s.map(c=>c[ge]):[a,...i]).join(" ");return {[Ct]:a,[ge]:l,[De]:r,[mt]:s,[Uo]:i}},Mo=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ct]:"",[ge]:"",[De]:"",[mt]:[],[Uo]:[r]});}return t},Bo=(t,...e)=>{let[n,r]=Xg(t,e);return {[Ct]:"",[ge]:`@keyframes ${Yg(n+r)}`,[De]:r,[mt]:[],[Uo]:[]}},AR=0,qo=((t,e)=>{t||(t=[`/* h-v-t ${AR++} */`]);let n=Array.isArray(t)?or(t,e):t,r=n[ge],s=or(["view-transition-name:",""],[r]);return n[ge]=Sn+n[ge],n[De]=n[De].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[ge]=s[Ct]=r,s[mt]=[...n[mt],n],s});var PR=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},pu=({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(Sn)?PR(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(f=>{l.insertRule(f,l.cssRules.length);}));};return [{toString(){let o=this[Ct];return r(o,this[De]),this[mt].forEach(({[ge]:a,[De]: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[De])}})]};var IR=({id:t})=>{let[e,n]=pu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:y,context:w})=>{let[S,b]=r.get(w),_=Object.keys(S);if(!_.length)return;let E="";if(_.forEach(v=>{b[v]=true,E+=v.startsWith(Sn)?S[v]:`${v[0]==="@"?"":"."}${v}{${S[v]}}`;}),r.set(w,[{},b]),y&&i.test(y[0])){y[0]=y[0].replace(i,(v,P,C)=>`${P}${E}${C}`);return}let x=s.get(w),O=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(y){y[0]=`${O}${y[0]}`;return}return Promise.resolve(O)},g=({context:y})=>{r.has(y)||r.set(y,[{},{}]);let[w,S]=r.get(y),b=true;if(S[d[Ct]]||(b=false,w[d[Ct]]=d[De]),d[mt].forEach(({[ge]:_,[De]:E})=>{S[_]||(b=false,w[_]=E);}),!b)return Promise.resolve(X("",[p]))},m=new String(d[ge]);Object.assign(m,d),m.isEscaped=true,m.callbacks=[g];let h=Promise.resolve(m);return Object.assign(h,d),h.toString=e.toString,h},a=(d,...p)=>o(or(d,p)),l=(...d)=>(d=Mo(d),a(Array(d.length).fill(""),...d)),c=Bo,f=((d,...p)=>o(qo(d,p))),u=({children:d,nonce:p}={})=>X(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[De]:""}</style>`,[({context:g})=>{s.set(g,p);}]);return u[Ke]=n,{css:a,cx:l,keyframes:c,viewTransition:f,Style:u}},Ks=IR({id:Fo}),Zg=Ks.Style;function ye(t,e,n){let r;if(!e||!("children"in e))r=Us(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Us(t,e,s):Us(t,e,[s]);}return r.key=n,r}var mu=new _e().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>ca(ey())).then(s=>s.default);try{let s=Object.values(r).find(i=>i.isEntry);if(!s)throw new Error("No entry found in manifest");e.js=s?.file,e.css=s?.css??[];}catch(s){console.warn("Couldn't find assets in manifest",s);}return t.html(ye(dt,{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(dt,{children:[ye("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>ye("link",{rel:"stylesheet",href:n+s},i))]}),ye(Zg,{})]}),ye("body",{children:ye("div",{id:"root"})})]})}))});async function DR(t){return mu.fetch(t)}var jR={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ty=["storage","cloud"],gu=Object.fromEntries(ty.map(t=>[t,LR(t)]));function LR(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[jR[t]]==="1":false}function ar(t){return gu[t]}function FR(t,e){gu[t]=e;}function ny(){return ty.filter(t=>gu[t])}function UR(){let t=ny();if(t.length===0)return null;let e=t.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${t.join(", ")} - not supported, do not use in production.${e}`}var hu=false;function ry(t=e=>console.warn(e)){if(hu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){hu=true;return}let e=UR();e&&t(e),hu=true;}var MR=["/rest/v1","/auth/v1","/storage/v1"],BR=[/^\/auth\/v1\/(callback|authorize|verify)$/,/^\/auth\/v1\/oauth\//,/^\/auth\/v1\/sso\/saml\//,/^\/auth\/v1\/\.well-known\//,/^\/auth\/v1\/scim\/v2/],qR=/^\s*Mozilla\s*\/\s*5\s*\.\s*0/i;function HR(t){return MR.some(e=>t.startsWith(e))?!BR.some(e=>e.test(t)):false}function yu(){return {"Access-Control-Allow-Origin":"*"}}function WR(t){return t.startsWith("/storage/v1")}function sy(t){return ks(async(e,n)=>{if(e.req.method==="OPTIONS"||!HR(e.req.path))return n();let r=WR(e.req.path),s=e.req.header("Authorization")?.match(/^Bearer\s+(.+)$/)?.[1],i=e.req.header("apikey")??e.req.query("apikey");if(!i)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"No API key found in request",hint:"No `apikey` request header or url param was found."},401,{"sb-error-code":"UNAUTHORIZED_MISSING_API_KEY",...yu()});let o=await t(i,e);if(!o)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"Invalid API key",hint:"Double check your Supabase `apikey`"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY",...yu()});if(o.type==="secret"){let a=e.req.header("User-Agent");if(a&&qR.test(a))return e.json({message:"Forbidden use of secret API key in browser"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY_TYPE",...yu()})}return e.set("apiKeyType",o.type),s&&s!==i&&!s.startsWith("sb_")||(e.set("ignoreAuthorization",true),e.set("jwt",o.claims),typeof o.claims.sub=="string"&&e.set("userId",o.claims.sub)),n()})}function iy(t){let e=t.config.auth?.publishable_key,n=t.config.auth?.secret_key,r=typeof e=="string"&&e.length>0,s=typeof n=="string"&&n.length>0;return !r&&!s?null:async i=>r&&i===e?{type:"publishable",claims:{role:"anon"}}:s&&i===n?{type:"secret",claims:{role:"service_role"}}:null}function oy(t,e={}){let n=e.middlewares??[async(u,d)=>{await d();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=e.apiKeys===false?null:e.apiKeys?.resolver??iy(t),a=o?sy(o):async(u,d)=>{await d();},l=e.admin?Uf(a):a,c=Lf({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),f=async(u,d)=>{await d();let p=u.res.headers;p.has("Access-Control-Allow-Origin")||p.set("Access-Control-Allow-Origin","*"),p.set("Access-Control-Expose-Headers",i.join(", ")),u.req.method==="OPTIONS"&&(p.set("Access-Control-Allow-Methods",r.join(", ")),p.set("Access-Control-Allow-Headers",u.req.header("Access-Control-Request-Headers")??s.join(", ")),p.set("Access-Control-Max-Age","86400"));};return new _e().use("/storage/v1/*",c).use("/rest/v1/*",f).use(async(u,d)=>{u.set("app",t),t.config.auth?.enabled&&u.set("authService",cg(t)),t.config.storage?.enabled&&t._storageAdapter&&ar("storage")&&u.set("storageService",pg(t)),await d();}).use(...n).use(l).use(Bc()).route("/auth/v1",Hc).route("/rest/v1",Wm({forceRollback:e.forceRollback})).use("/storage/v1/*",async(u,d)=>{if(!ar("storage"))return u.notFound();await d();}).route("/storage/v1",Gc).route("/_system",Hf).use(async(u,d)=>{if(!e.disableStudio&&t.config.studio?.enabled)return mu.fetch(u.req.raw);if(!e.disableFallback)return u.notFound();await d();})}var KR=t=>{let e=t.toJSON();return yt.fromSchema(e)},bu=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
198
+
199
+ ALTER TABLE storage.buckets ENABLE ROW LEVEL SECURITY;
200
+ ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY;
201
+
202
+ CREATE OR REPLACE FUNCTION storage.foldername(name text)
203
+ RETURNS text[]
204
+ LANGUAGE plpgsql
205
+ IMMUTABLE
206
+ AS $function$
207
+ DECLARE
208
+ _parts text[];
209
+ BEGIN
210
+ SELECT string_to_array(name, '/') INTO _parts;
211
+ RETURN _parts[1:array_length(_parts, 1) - 1];
212
+ END
213
+ $function$;
214
+
215
+ CREATE OR REPLACE FUNCTION storage.filename(name text)
216
+ RETURNS text
217
+ LANGUAGE plpgsql
218
+ IMMUTABLE
219
+ AS $function$
220
+ DECLARE
221
+ _parts text[];
222
+ BEGIN
223
+ SELECT string_to_array(name, '/') INTO _parts;
224
+ RETURN _parts[array_length(_parts, 1)];
225
+ END
226
+ $function$;
227
+
228
+ CREATE OR REPLACE FUNCTION storage.extension(name text)
229
+ RETURNS text
230
+ LANGUAGE plpgsql
231
+ IMMUTABLE
232
+ AS $function$
233
+ DECLARE
234
+ _parts text[];
235
+ _filename text;
236
+ BEGIN
237
+ SELECT string_to_array(name, '/') INTO _parts;
238
+ SELECT _parts[array_length(_parts, 1)] INTO _filename;
239
+ RETURN reverse(split_part(reverse(_filename), '.', 1));
240
+ END
241
+ $function$;
242
+
243
+ CREATE OR REPLACE FUNCTION storage.operation()
244
+ RETURNS text
245
+ LANGUAGE plpgsql
246
+ STABLE
247
+ AS $function$
248
+ BEGIN
249
+ RETURN current_setting('storage.operation', true);
250
+ END
251
+ $function$;
252
+
253
+ CREATE OR REPLACE FUNCTION storage.allow_only_operation(expected_operation text)
254
+ RETURNS boolean
255
+ LANGUAGE sql
256
+ STABLE
257
+ AS $function$
258
+ WITH current_operation AS (
259
+ SELECT storage.operation() AS raw_operation
260
+ ),
261
+ normalized AS (
262
+ SELECT
263
+ CASE WHEN raw_operation LIKE 'storage.%' THEN substr(raw_operation, 9) ELSE raw_operation END AS current_operation,
264
+ CASE WHEN expected_operation LIKE 'storage.%' THEN substr(expected_operation, 9) ELSE expected_operation END AS requested_operation
265
+ FROM current_operation
266
+ )
267
+ SELECT CASE
268
+ WHEN requested_operation IS NULL OR requested_operation = '' THEN false
269
+ ELSE COALESCE(current_operation = requested_operation, false)
270
+ END
271
+ FROM normalized;
272
+ $function$;
273
+
274
+ CREATE OR REPLACE FUNCTION storage.allow_any_operation(expected_operations text[])
275
+ RETURNS boolean
276
+ LANGUAGE sql
277
+ STABLE
278
+ AS $function$
279
+ WITH current_operation AS (
280
+ SELECT storage.operation() AS raw_operation
281
+ ),
282
+ normalized AS (
283
+ SELECT CASE WHEN raw_operation LIKE 'storage.%' THEN substr(raw_operation, 9) ELSE raw_operation END AS current_operation
284
+ FROM current_operation
285
+ )
286
+ SELECT EXISTS (
287
+ SELECT 1
288
+ FROM normalized n
289
+ CROSS JOIN LATERAL unnest(expected_operations) AS expected_operation
290
+ WHERE expected_operation IS NOT NULL
291
+ AND expected_operation <> ''
292
+ AND n.current_operation = CASE
293
+ WHEN expected_operation LIKE 'storage.%' THEN substr(expected_operation, 9)
294
+ ELSE expected_operation
295
+ END
296
+ );
297
+ $function$;
298
+ `;function Jo(t=true){return t?ns(Su):Su}var Go=class{driver=null;requiresBuffer=false;async transform(e,n){return {body:e,contentType:"application/octet-stream",contentLength:e.byteLength}}};function zg(t){if(!t._storageAdapter)throw P.storageNotConfigured();let e=new Ds(t.connection),n=t.config.auth?.jwt_secret??"",r=t._transformationAdapter??new Go;return new Ms(e,t._storageAdapter,{jwtSecret:n,fileSizeLimit:t.config.storage?.file_size_limit?JR(t.config.storage.file_size_limit):void 0,buckets:t.config.storage?.buckets},{autoCreateBuckets:true},r,t.connection)}function JR(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 Ye=Symbol("RENDERER"),zt=Symbol("ERROR_HANDLER"),te=Symbol("STASH"),Vo=Symbol("INTERNAL"),_u=Symbol("MEMO"),sr=Symbol("PERMALINK");var Eu=t=>(t[Vo]=true,t);var xu=t=>({value:e,children:n})=>{if(!n)return;let r={children:[{tag:Eu(()=>{t.push(e);}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Eu(()=>{t.pop();}),props:{}});let s={tag:"",props:r,type:""};return s[zt]=i=>{throw t.pop(),i},s},zo=t=>{let e=[t],n=xu(e);return n.values=e,n.Provider=n,At.push(n),n};var At=[],Bs=t=>{let e=[t],n=(r=>{e.push(r.value);let s;try{s=r.children?(Array.isArray(r.children)?new Tu("",{},r.children):r.children).toString():"";}catch(i){throw e.pop(),i}return s instanceof Promise?s.finally(()=>e.pop()).then(i=>Z(i,i.callbacks)):(e.pop(),Z(s))});return n.values=e,n.Provider=n,n[Ye]=xu(e),At.push(n),n},Ae=t=>t.values.at(-1);var ir={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},qs={},or="data-precedence";var Ks={};li(Ks,{button:()=>eC,form:()=>XR,input:()=>ZR,link:()=>QR,meta:()=>YR,script:()=>VR,style:()=>zR,title:()=>GR});var Tn=t=>Array.isArray(t)?t:[t];var Qg=new WeakMap,Yg=(t,e,n,r)=>({buffer:s,context:i})=>{if(!s)return;let o=Qg.get(i)||{};Qg.set(i,o);let a=o[t]||=[],l=false,c=ir[t];if(c.length>0){e:for(let[,u]of a)for(let f of c)if((u?.[f]??null)===n?.[f]){l=true;break e}}if(l?s[0]=s[0].replaceAll(e,""):c.length>0?a.push([e,n,r]):a.unshift([e,n,r]),s[0].indexOf("</head>")!==-1){let u;if(r===void 0)u=a.map(([f])=>f);else {let f=[];u=a.map(([d,,p])=>{let h=f.indexOf(p);return h===-1&&(f.push(p),h=f.length-1),[d,h]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d);}u.forEach(f=>{s[0]=s[0].replaceAll(f,"");}),s[0]=s[0].replace(/(?=<\/head>)/,u.join(""));}},Hs=(t,e,n)=>Z(new We(t,n,Tn(e??[])).toString()),Ws=(t,e,n,r)=>{if("itemProp"in n)return Hs(t,e,n);let{precedence:s,blocking:i,...o}=n;s=r?s??"":void 0,r&&(o[or]=s);let a=new We(t,o,Tn(e||[])).toString();return a instanceof Promise?a.then(l=>Z(a,[...l.callbacks||[],Yg(t,l,o,s)])):Z(a,[Yg(t,a,o,s)])},GR=({children:t,...e})=>{let n=Qo();if(n){let r=Ae(n);if(r==="svg"||r==="head")return new We("title",e,Tn(t??[]))}return Ws("title",t,e,false)},VR=({children:t,...e})=>{let n=Qo();return ["src","async"].some(r=>!e[r])||n&&Ae(n)==="head"?Hs("script",t,e):Ws("script",t,e,false)},zR=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ws("style",t,e,true)):Hs("style",t,e),QR=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Hs("link",t,e):Ws("link",t,e,"precedence"in e),YR=({children:t,...e})=>{let n=Qo();return n&&Ae(n)==="head"?Hs("meta",t,e):Ws("meta",t,e,false)},Xg=(t,{children:e,...n})=>new We(t,n,Tn(e??[])),XR=t=>(typeof t.action=="function"&&(t.action=sr in t.action?t.action[sr]:void 0),Xg("form",t)),Zg=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=sr in e.formAction?e.formAction[sr]:void 0),Xg(t,e)),ZR=t=>Zg("input",t),eC=t=>Zg("button",t);var tC=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),ar=t=>tC.get(t)||t,Js=(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 Gs=void 0,Qo=()=>Gs,nC=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,rC=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],sC=["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"],Cu=(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 We?s.toStringToBuffer(e):typeof s=="number"||s.isEscaped?e[0]+=s:s instanceof Promise?e.unshift("",s):Cu(s,e);}}},We=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?Ba(Z(t[0],t.callbacks)).toString():t[0]:Oi(t,t.callbacks)}toStringToBuffer(t){let e=this.tag,n=this.props,{children:r}=this;t[0]+=`<${e}`;let s=Gs&&Ae(Gs)==="svg"?i=>nC(ar(i)):i=>ar(i);for(let[i,o]of Object.entries(n))if(i=s(i),i!=="children"){if(i==="style"&&typeof o=="object"){let a="";Js(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"&&sC.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=[Z(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(rC.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",Cu(r,t),t[0]+=`</${e}>`;}},Ru=class extends We{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(At.length===0)t.unshift("",r);else {let s=At.map(i=>[i,i.values.at(-1)]);t.unshift("",r.then(i=>(i instanceof We&&(i.localContexts=s),i)));}else r instanceof We?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):_t(r,t);}},Tu=class extends We{toStringToBuffer(t){Cu(this.children,t);}},ey=false,Vs=(t,e,n)=>{if(!ey){for(let r in qs)Ks[r][Ye]=qs[r];ey=true;}return typeof t=="function"?new Ru(t,e,n):Ks[t]?new Ru(Ks[t],e,n):t==="svg"||t==="head"?(Gs||=Bs(""),new We(t,e,[new Ru(Gs,{value:t},n)])):new We(t,e,n)};var ht=({children:t})=>new Tu("",{children:t},Array.isArray(t)?t:t?[t]:[]);var ea={};li(ea,{button:()=>ky,clearCache:()=>gC,composeRef:()=>Zo,form:()=>Ty,input:()=>Cy,link:()=>_y,meta:()=>Ey,script:()=>wy,style:()=>Sy,title:()=>by});var Qs="_hp",iC={Change:"Input",DoubleClick:"DblClick"},oC={svg:"2000/svg",math:"1998/Math/MathML"},gt=[],vu=new WeakMap,lr=void 0,ay=()=>lr,vt=t=>"t"in t,Au={onClick:["click",false]},ty=t=>{if(!t.startsWith("on"))return;if(Au[t])return Au[t];let e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){let[,n,r]=e;return Au[t]=[(iC[n]||n).toLowerCase(),!!r]}},ny=(t,e)=>lr&&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,aC=(t,e,n)=>{e||={};for(let r in e){let s=e[r];if(r!=="children"&&(!n||n[r]!==s)){r=ar(r);let i=ty(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),vu.set(t,o);}else if(r==="style"){let o=t.style;typeof s=="string"?o.cssText=s:(o.cssText="",s!=null&&Js(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=ny(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=ar(r);let i=ty(r);i?t.removeEventListener(i[0],s,i[1]):r==="ref"?vu.get(t)?.():t.removeAttribute(ny(t,r));}}},lC=(t,e)=>{e[te][0]=0,gt.push([t,e]);let n=e.tag[Ye]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return [n.call(null,r)]}finally{gt.pop();}},ly=(t,e,n,r,s)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[te][1][Pu]?.forEach(i=>s.push(i)),t.vC.forEach(i=>{if(vt(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=e;let o=n.length;if(ly(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);});},cC=t=>{for(;t&&(t.tag===Qs||!t.e);)t=t.tag===Qs||!t.vC?.[0]?t.nN:t.vC[0];return t?.e},cy=t=>{vt(t)||(t[te]?.[1][Pu]?.forEach(e=>e[2]?.()),vu.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(cy)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(zs.delete(t),Yo.delete(t),delete t[te][3],t.a=true);},uy=(t,e,n)=>{t.c=e,fy(t,e,n);},ry=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},sy=Symbol(),fy=(t,e,n)=>{let r=[],s=[],i=[];ly(t,e,r,s,i),s.forEach(cy);let o=n?void 0:e.childNodes,a,l=null;if(n)a=-1;else if(!o.length)a=0;else {let c=ry(o,cC(t.nN));c!==void 0?(l=o[c],a=c):a=ry(o,r.find(u=>u.tag!==Qs&&u.e)?.e)??-1,a===-1&&(n=true);}for(let c=0,u=r.length;c<u;c++,a++){let f=r[c],d;if(f.s&&f.e)d=f.e,f.s=false;else {let p=n||!f.e;vt(f)?(f.e&&f.d&&(f.e.textContent=f.t),f.d=false,d=f.e||=document.createTextNode(f.t)):(d=f.e||=f.n?document.createElementNS(f.n,f.tag):document.createElement(f.tag),aC(d,f.props,f.pP),fy(f,d,p));}f.tag===Qs?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=[],u=[];i.forEach(([,f,,d,p])=>{f&&c.push(f),d&&u.push(d),p?.();}),c.forEach(f=>f()),u.length&&requestAnimationFrame(()=>{u.forEach(f=>f());});}},uC=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Yo=new WeakMap,Ou=(t,e,n)=>{let r=!n&&e.pC;n&&(e.pC||=e.vC);let s;try{n||=typeof e.tag=="function"?lC(t,e):Tn(e.props.children),n[0]?.tag===""&&n[0][zt]&&(s=n[0][zt],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=fC(n[l]);if(c){typeof c.tag=="function"&&!c.tag[Vo]&&(At.length>0&&(c[te][2]=At.map(f=>[f,f.values.at(-1)])),t[5]?.length&&(c[te][3]=t[5].at(-1)));let u;if(i&&i.length){let f=i.findIndex(vt(c)?d=>vt(d):c.key!==void 0?d=>d.key===c.key&&d.tag===c.tag:d=>d.tag===c.tag);f!==-1&&(u=i[f],i.splice(f,1));}if(u)if(vt(c))u.t!==c.t&&(u.t=c.t,u.d=!0),c=u;else {let f=u.pP=u.props;if(u.props=c.props,u.f||=c.f||e.f,typeof c.tag=="function"){let d=u[te][2];u[te][2]=c[te][2]||[],u[te][3]=c[te][3],!u.f&&((u.o||u)===c.o||u.tag[_u]?.(f,u.props))&&uC(d,u[te][2])&&(u.s=!0);}c=u;}else if(!vt(c)&&lr){let f=Ae(lr);f&&(c.n=f);}if(!vt(c)&&!c.s&&(Ou(t,c),delete c.f),o.push(c),a&&!a.s&&!c.s)for(let f=a;f&&!vt(f);f=f.vC?.at(-1))f.nN=c;a=c;}}e.vR=r?[...e.vC,...i||[]]:i||[],e.vC=o,r&&delete e.pC;}catch(i){if(e.f=true,i===sy){if(s)return;throw i}let[o,a,l]=e[te]?.[3]||[];if(a){let c=()=>Ys([0,false,t[2]],l),u=Yo.get(l)||[];u.push(c),Yo.set(l,u);let f=a(i,()=>{let d=Yo.get(l);if(d){let p=d.indexOf(c);if(p!==-1)return d.splice(p,1),c()}});if(f){if(t[0]===1)t[1]=true;else if(Ou(t,l,[f]),(a.length===1||t!==o)&&l.c){uy(l,l.c,false);return}throw sy}}throw i}finally{s&&t[5].pop();}},fC=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[te]=[0,[]];else {let e=oC[t.tag];e&&(lr||=zo(""),t.props.children=[{tag:lr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}]);}return t}};var iy=(t,e)=>{e[te][2]?.forEach(([n,r])=>{n.values.push(r);});try{Ou(t,e,void 0);}catch{return}if(e.a){delete e.a;return}e[te][2]?.forEach(([n])=>{n.values.pop();}),(t[0]!==1||!t[1])&&uy(e,e.c,false);},zs=new WeakMap,oy=[],Ys=async(t,e)=>{t[5]||=[];let n=zs.get(e);n&&n[0](void 0);let r,s=new Promise(i=>r=i);if(zs.set(e,[r,()=>{t[2]?t[2](t,e,i=>{iy(i,e);}).then(()=>r(e)):(iy(t,e),r(e));}]),oy.length)oy.at(-1).add(e);else {await Promise.resolve();let i=zs.get(e);i&&(zs.delete(e),i[1]());}return s};var dy=(t,e,n)=>({tag:Qs,props:{children:t},key:n,e,p:1});var dC=0,Pu=1,pC=2,mC=3;var $u=new WeakMap,my=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]);var hC=void 0;var py=[];var Xo=t=>{let e=()=>typeof t=="function"?t():t,n=gt.at(-1);if(!n)return [e(),()=>{}];let[,r]=n,s=r[te][1][dC]||=[],i=r[te][0]++;return s[i]||=[e(),o=>{let a=hC,l=s[i];if(typeof o=="function"&&(o=o(l[0])),!Object.is(o,l[0]))if(l[0]=o,py.length){let[c,u]=py.at(-1);Promise.all([c===3?r:Ys([c,false,a],r),u]).then(([f])=>{if(!f||!(c===2||c===3))return;let d=f.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===f.vC&&Ys([c===3?1:0,false,a],f);});});});}else Ys([0,false,a],r);}]};var cr=(t,e)=>{let n=gt.at(-1);if(!n)return t;let[,r]=n,s=r[te][1][pC]||=[],i=r[te][0]++,o=s[i];return my(o?.[1],e)?s[i]=[t,e]:t=s[i][0],t};var Nu=t=>{let e=$u.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>$u.set(t,[n]),n=>$u.set(t,[void 0,n])),t},Iu=(t,e)=>{let n=gt.at(-1);if(!n)return t();let[,r]=n,s=r[te][1][mC]||=[],i=r[te][0]++,o=s[i];return my(o?.[1],e)&&(s[i]=[t(),e]),s[i][0]};var gy=zo({pending:false,data:null,method:null,action:null}),hy=new Set,yy=t=>{hy.add(t),t.finally(()=>hy.delete(t));};var gC=()=>{Du=Object.create(null),ju=Object.create(null);},Zo=(t,e)=>Iu(()=>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]),Du=Object.create(null),ju=Object.create(null),Xs=(t,e,n,r,s)=>{if(e?.itemProp)return {tag:t,props:e,type:t,ref:e.ref};let i=document.head,{onLoad:o,onError:a,precedence:l,blocking:c,...u}=e,f=null,d=false,p=ir[t],h;if(p.length>0){let w=i.querySelectorAll(t);e:for(let S of w)for(let b of ir[t])if(S.getAttribute(b)===e[b]){f=S;break e}if(!f){let S=p.reduce((b,_)=>e[_]===void 0?b:`${b}-${_}-${e[_]}`,t);d=!ju[S],f=ju[S]||=(()=>{let b=document.createElement(t);for(let _ of p)e[_]!==void 0&&b.setAttribute(_,e[_]),e.rel&&b.setAttribute("rel",e.rel);return b})();}}else h=i.querySelectorAll(t);l=r?l??"":void 0,r&&(u[or]=l);let m=cr(w=>{if(p.length>0){let S=false;for(let b of i.querySelectorAll(t)){if(S&&b.getAttribute(or)!==l){i.insertBefore(w,b);return}b.getAttribute(or)===l&&(S=true);}i.appendChild(w);}else if(h){let S=false;for(let b of h)if(b===w){S=true;break}S||i.insertBefore(w,i.contains(h[0])?h[0]:i.querySelector(t)),h=void 0;}},[l]),g=Zo(e.ref,w=>{let S=p[0];if(n===2&&(w.innerHTML=""),(d||h)&&m(w),!a&&!o)return;let b=Du[w.getAttribute(S)]||=new Promise((_,E)=>{w.addEventListener("load",_),w.addEventListener("error",E);});o&&(b=b.then(o)),a&&(b=b.catch(a)),b.catch(()=>{});});if(s&&c==="render"){let w=ir[t][0];if(e[w]){let S=e[w],b=Du[S]||=new Promise((_,E)=>{m(f),f.addEventListener("load",_),f.addEventListener("error",E);});Nu(b);}}let y={tag:t,type:t,props:{...u,ref:g},ref:g};return y.p=n,f&&(y.e=f),dy(y,i)},by=t=>{let e=ay();return (e&&Ae(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Xs("title",t,void 0,false,false)},wy=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Xs("script",t,1,false,true),Sy=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,Xs("style",t,2,true,true)),_y=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}:Xs("link",t,1,"precedence"in t,true),Ey=t=>Xs("meta",t,void 0,false,false),xy=Symbol(),Ty=t=>{let{action:e,...n}=t;typeof e!="function"&&(n.action=e);let[r,s]=Xo([null,false]),i=cr(async c=>{let u=c.isTrusted?e:c.detail[xy];if(typeof u!="function")return;c.preventDefault();let f=new FormData(c.target);s([f,true]);let d=u(f);d instanceof Promise&&(yy(d),await d),s([null,true]);},[]),o=Zo(t.ref,c=>(c.addEventListener("submit",i),()=>{c.removeEventListener("submit",i);})),[a,l]=r;return r[1]=false,{tag:gy,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}},Ry=(t,{formAction:e,...n})=>{if(typeof e=="function"){let r=cr(s=>{s.preventDefault(),s.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[xy]:e}}));},[]);n.ref=Zo(n.ref,s=>(s.addEventListener("click",r),()=>{s.removeEventListener("click",r);}));}return {tag:t,props:n,type:t,ref:n.ref}},Cy=t=>Ry("input",t),ky=t=>Ry("button",t);Object.assign(qs,{title:by,script:wy,style:Sy,link:_y,meta:Ey,form:Ty,input:Cy,button:ky});Bs(null);new TextEncoder;var Rn=":-hono-global",SC=new RegExp(`^${Rn}{(.*)}$`),ra="hono-css",Ot=Symbol(),Se=Symbol(),Me=Symbol(),yt=Symbol(),sa=Symbol(),$y=Symbol();var Ny=t=>{let e=0,n=11;for(;e<t.length;)n=101*n+t.charCodeAt(e++)>>>0;return "css-"+n},_C=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),EC=new RegExp(["("+_C+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g"),xC=t=>t.replace(EC,(e,n,r,s,i)=>n||r||s||i||""),Iy=(t,e)=>{let n=[],r=[],s=t[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",i="";for(let o=0,a=t.length;o<a;o++){i+=t[o];let l=e[o];if(!(typeof l=="boolean"||l===null||l===void 0)){Array.isArray(l)||(l=[l]);for(let c=0,u=l.length;c<u;c++){let f=l[c];if(!(typeof f=="boolean"||f===null||f===void 0))if(typeof f=="string")/([\\"'\/])/.test(f)?i+=f.replace(/([\\"']|(?<=<)\/)/g,"\\$1"):i+=f;else if(typeof f=="number")i+=f;else if(f[$y])i+=f[$y];else if(f[Se].startsWith("@keyframes "))n.push(f),i+=` ${f[Se].substring(11)} `;else {if(t[o+1]?.match(/^\s*{/))n.push(f),f=`.${f[Se]}`;else {n.push(...f[yt]),r.push(...f[sa]),f=f[Me];let d=f.length;if(d>0){let p=f[d-1];p!==";"&&p!=="}"&&(f+=";");}}i+=`${f||""}`;}}}}return [s,xC(i),n,r]},ur=(t,e)=>{let[n,r,s,i]=Iy(t,e),o=SC.exec(r);o&&(r=o[1]);let a=(o?Rn:"")+Ny(n+r),l=(o?s.map(c=>c[Se]):[a,...i]).join(" ");return {[Ot]:a,[Se]:l,[Me]:r,[yt]:s,[sa]:i}},ia=t=>{for(let e=0,n=t.length;e<n;e++){let r=t[e];typeof r=="string"&&(t[e]={[Ot]:"",[Se]:"",[Me]:"",[yt]:[],[sa]:[r]});}return t},oa=(t,...e)=>{let[n,r]=Iy(t,e);return {[Ot]:"",[Se]:`@keyframes ${Ny(n+r)}`,[Me]:r,[yt]:[],[sa]:[]}},TC=0,aa=((t,e)=>{t||(t=[`/* h-v-t ${TC++} */`]);let n=Array.isArray(t)?ur(t,e):t,r=n[Se],s=ur(["view-transition-name:",""],[r]);return n[Se]=Rn+n[Se],n[Me]=n[Me].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,r),s[Se]=s[Ot]=r,s[yt]=[...n[yt],n],s});var CC=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},Uu=({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(Rn)?CC(a):[`${o[0]==="@"?"":"."}${o}{${a}}`]).forEach(u=>{l.insertRule(u,l.cssRules.length);}));};return [{toString(){let o=this[Ot];return r(o,this[Me]),this[yt].forEach(({[Se]:a,[Me]:l})=>{r(a,l);}),this[Se]}},({children:o,nonce:a})=>({tag:"style",props:{id:t,nonce:a,children:o&&(Array.isArray(o)?o:[o]).map(l=>l[Me])}})]};var AC=({id:t})=>{let[e,n]=Uu({id:t}),r=new WeakMap,s=new WeakMap,i=new RegExp(`(<style id="${t}"(?: nonce="[^"]*")?>.*?)(</style>)`),o=d=>{let p=({buffer:y,context:w})=>{let[S,b]=r.get(w),_=Object.keys(S);if(!_.length)return;let E="";if(_.forEach(v=>{b[v]=true,E+=v.startsWith(Rn)?S[v]:`${v[0]==="@"?"":"."}${v}{${S[v]}}`;}),r.set(w,[{},b]),y&&i.test(y[0])){y[0]=y[0].replace(i,(v,$,k)=>`${$}${E}${k}`);return}let x=s.get(w),O=`<script${x?` nonce="${x}"`:""}>document.querySelector('#${t}').textContent+=${JSON.stringify(E)}</script>`;if(y){y[0]=`${O}${y[0]}`;return}return Promise.resolve(O)},h=({context:y})=>{r.has(y)||r.set(y,[{},{}]);let[w,S]=r.get(y),b=true;if(S[d[Ot]]||(b=false,w[d[Ot]]=d[Me]),d[yt].forEach(({[Se]:_,[Me]:E})=>{S[_]||(b=false,w[_]=E);}),!b)return Promise.resolve(Z("",[p]))},m=new String(d[Se]);Object.assign(m,d),m.isEscaped=true,m.callbacks=[h];let g=Promise.resolve(m);return Object.assign(g,d),g.toString=e.toString,g},a=(d,...p)=>o(ur(d,p)),l=(...d)=>(d=ia(d),a(Array(d.length).fill(""),...d)),c=oa,u=((d,...p)=>o(aa(d,p))),f=({children:d,nonce:p}={})=>Z(`<style id="${t}"${p?` nonce="${p}"`:""}>${d?d[Me]:""}</style>`,[({context:h})=>{s.set(h,p);}]);return f[Ye]=n,{css:a,cx:l,keyframes:c,viewTransition:u,Style:f}},ei=AC({id:ra}),Dy=ei.Style;function _e(t,e,n){let r;if(!e||!("children"in e))r=Vs(t,e,[]);else {let s=e.children;r=Array.isArray(s)?Vs(t,e,s):Vs(t,e,[s]);}return r.key=n,r}var Mu=new Te().get("/*",async t=>{let e={js:"main.js",css:["styles.css"]},n="/static/",r=await Promise.resolve().then(()=>Aa(jy())).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(_e(ht,{children:_e("html",{lang:"en","data-theme":"dark",style:"color-scheme: dark",class:"dark",children:[_e("head",{children:[_e("meta",{charset:"UTF-8"}),_e("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),_e("link",{rel:"icon",href:n+"favicon.ico",type:"image/x-icon"}),_e("title",{children:"Supalite"}),_e(ht,{children:[_e("script",{type:"module",src:n+e?.js}),e?.css.map((s,i)=>_e("link",{rel:"stylesheet",href:n+s},i))]}),_e(Dy,{})]}),_e("body",{children:_e("div",{id:"root"})})]})}))});async function OC(t){return Mu.fetch(t)}var PC={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Ly=["storage","cloud"],qu=Object.fromEntries(Ly.map(t=>[t,$C(t)]));function $C(t){let e=typeof process<"u"&&process.env||void 0;return e?e.NODE_ENV==="test"?true:e[PC[t]]==="1":false}function fr(t){return qu[t]}function NC(t,e){qu[t]=e;}function Fy(){return Ly.filter(t=>qu[t])}function IC(){let t=Fy();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 Bu=false;function Uy(t=e=>console.warn(e)){if(Bu)return;if(typeof process<"u"&&process.env?.NODE_ENV==="test"){Bu=true;return}let e=IC();e&&t(e),Bu=true;}var DC=["/rest/v1","/auth/v1","/storage/v1"],jC=[/^\/auth\/v1\/(callback|authorize|verify)$/,/^\/auth\/v1\/oauth\//,/^\/auth\/v1\/sso\/saml\//,/^\/auth\/v1\/\.well-known\//,/^\/auth\/v1\/scim\/v2/],LC=/^\s*Mozilla\s*\/\s*5\s*\.\s*0/i;function FC(t){return DC.some(e=>t.startsWith(e))?!jC.some(e=>e.test(t)):false}function Hu(){return {"Access-Control-Allow-Origin":"*"}}function UC(t){return t.startsWith("/storage/v1")}function My(t){return Ns(async(e,n)=>{if(e.req.method==="OPTIONS"||!FC(e.req.path))return n();let r=UC(e.req.path),s=e.req.header("Authorization")?.match(/^Bearer\s+(.+)$/)?.[1],i=e.req.header("apikey")??e.req.query("apikey");if(!i)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"No API key found in request",hint:"No `apikey` request header or url param was found."},401,{"sb-error-code":"UNAUTHORIZED_MISSING_API_KEY",...Hu()});let o=await t(i,e);if(!o)return r?(s?.startsWith("sb_")&&e.set("ignoreAuthorization",true),n()):e.json({message:"Invalid API key",hint:"Double check your Supabase `apikey`"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY",...Hu()});if(o.type==="secret"){let a=e.req.header("User-Agent");if(a&&LC.test(a))return e.json({message:"Forbidden use of secret API key in browser"},401,{"sb-error-code":"UNAUTHORIZED_INVALID_API_KEY_TYPE",...Hu()})}return e.set("apiKeyType",o.type),s&&s!==i&&!s.startsWith("sb_")||(e.set("ignoreAuthorization",true),e.set("jwt",o.claims),typeof o.claims.sub=="string"&&e.set("userId",o.claims.sub)),n()})}function By(t){let e=t.config.auth?.publishable_key,n=t.config.auth?.secret_key,r=typeof e=="string"&&e.length>0,s=typeof n=="string"&&n.length>0;return !r&&!s?null:async i=>r&&i===e?{type:"publishable",claims:{role:"anon"}}:s&&i===n?{type:"secret",claims:{role:"service_role"}}:null}function qy(t,e={}){let n=e.middlewares??[async(f,d)=>{await d();}],r=["GET","POST","PATCH","PUT","DELETE","OPTIONS","HEAD"],s=["authorization","apikey","content-type","cache-control","prefer","x-client-info","x-upsert","x-region","x-metadata","accept-profile","content-profile","range","range-unit","accept","x-supabase-api-version"],i=["Content-Range","Content-Location","Preference-Applied"],o=e.apiKeys===false?null:e.apiKeys?.resolver??By(t),a=o?My(o):async(f,d)=>{await d();},l=e.admin?cd(a):a,c=ad({origin:"*",allowMethods:r,allowHeaders:s,exposeHeaders:i,maxAge:86400}),u=async(f,d)=>{await d();let p=f.res.headers;p.has("Access-Control-Allow-Origin")||p.set("Access-Control-Allow-Origin","*"),p.set("Access-Control-Expose-Headers",i.join(", ")),f.req.method==="OPTIONS"&&(p.set("Access-Control-Allow-Methods",r.join(", ")),p.set("Access-Control-Allow-Headers",f.req.header("Access-Control-Request-Headers")??s.join(", ")),p.set("Access-Control-Max-Age","86400"));};return new Te().use("/storage/v1/*",c).use("/rest/v1/*",u).use(async(f,d)=>{f.set("app",t),t.config.auth?.enabled&&f.set("authService",$g(t)),t.config.storage?.enabled&&t._storageAdapter&&fr("storage")&&f.set("storageService",zg(t)),await d();}).use(...n).use(l).use(au()).route("/auth/v1",uu).route("/rest/v1",ph({forceRollback:e.forceRollback})).use("/storage/v1/*",async(f,d)=>{if(!fr("storage"))return f.notFound();await d();}).route("/storage/v1",wu).route("/_system",pd).use(async(f,d)=>{if(!e.disableStudio&&t.config.studio?.enabled)return Mu.fetch(f.req.raw);if(!e.disableFallback)return f.notFound();await d();})}var MC=t=>{let e=t.toJSON();return St.fromSchema(e)},Wu=class extends Error{constructor(n,r,s=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)}
194
299
 
195
300
  Error: ${JSON.stringify(s[0],null,2)}
196
301
 
197
- 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 ly(t,e,n){let r=n?.clone?KR(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 bu(r,e,i.errors);return s}Un();var wu=`-- supabase/auth core schema (Postgres)
302
+ 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 Wy(t,e,n){let r=n?.clone?MC(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 Wu(r,e,i.errors);return s}Hn();var Ku=`-- supabase/auth core schema (Postgres)
198
303
  -- Scope: Core Authentication + User Management
199
304
  -- Source: GoTrue migrations + runtime analysis
200
305
 
@@ -402,7 +507,7 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
402
507
  created_at timestamptz DEFAULT now(),
403
508
  ip_address varchar(64) DEFAULT ''
404
509
  );
405
- `;function Su(t=true){return t?Qr(wu):wu}function Je(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function kt(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function lr(t){return `'${t.replace(/'/g,"''")}'`}function GR(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function cy(t,e){return e==null?"NULL":t==="pg"?GR(e):lr(JSON.stringify(e))}function _u(t){return t==null?"NULL":lr(t)}function uy(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function fy(t){return {version:String(t.version),name:t.name??null,statements:uy(t.statements),rollback:uy(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}var zR=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function dy(t){let{schema_migrations:e,seed_files:n}=kt(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
510
+ `;function Ju(t=true){return t?ns(Ku):Ku}function Ke(t){return t.dialect==="postgres"?"pg":t.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Pt(t){return t==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:t==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function dr(t){return `'${t.replace(/'/g,"''")}'`}function qC(t){return `'${`{${t.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function Ky(t,e){return e==null?"NULL":t==="pg"?qC(e):dr(JSON.stringify(e))}function Gu(t){return t==null?"NULL":dr(t)}function Jy(t){if(t==null)return [];if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e==="")return [];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return []}}return []}function HC(t,e){let n=()=>{throw new Error(`Migration history ${String(e)} has invalid statements`)};if(t==null)return n();let r=t;if(typeof t=="string")try{r=JSON.parse(t);}catch{return n()}return !Array.isArray(r)||!r.every(s=>typeof s=="string")?n():r}function Vu(t){return {version:String(t.version),name:t.name??null,statements:Jy(t.statements),rollback:Jy(t.rollback),created_by:t.created_by??null,idempotency_key:t.idempotency_key??null}}function WC(t){return {...Vu(t),statements:HC(t.statements,t.version)}}var KC=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];function Gy(t){let{schema_migrations:e,seed_files:n}=Pt(t);return t==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${e} (
406
511
  version text NOT NULL PRIMARY KEY,
407
512
  statements text[],
408
513
  name text,
@@ -422,12 +527,12 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
422
527
  )`,`CREATE TABLE IF NOT EXISTS ${n} (
423
528
  path TEXT NOT NULL PRIMARY KEY,
424
529
  hash TEXT NOT NULL
425
- )`]}function py(t){let{schema_migrations:e}=kt(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function VR(t){let e=dy(t),n=py(t);return [...e.slice(0,1),...n,...e.slice(1)]}function Eu(t){return VR(t).map(e=>e.trim()).join(`;
426
- `)+";"}function QR(t,e){let{schema_migrations:n}=kt(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${lr(e.version)}, ${_u(e.name)}, ${cy(t,e.statements)}, ${cy(t,e.rollback??null)}, ${_u(e.created_by??null)}, ${_u(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function YR(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version = ${lr(e)}`}function XR(t){let{schema_migrations:e}=kt(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var my="version, name, statements, rollback, created_by, idempotency_key";function ZR(t){let{schema_migrations:e}=kt(t);return `SELECT ${my} FROM ${e} ORDER BY version ASC`}function eC(t,e){let{schema_migrations:n}=kt(t);return `SELECT ${my} FROM ${n} WHERE version = ${lr(e)}`}function tC(t,e){let{schema_migrations:n}=kt(t);return `DELETE FROM ${n} WHERE version >= ${lr(e)}`}async function nC(t,e){let{schema_migrations:n}=kt(e);for(let r of zR){let s=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function xu(t){let e=Je(t);for(let n of dy(e))await t.exec(n);await nC(t,e);for(let n of py(e))await t.exec(n);}async function rC(t){let e=Je(t);return ((await t.exec(XR(e)))?.rows??[]).map(r=>r.version)}async function sC(t,e){let n=Je(t);await t.exec(QR(n,e));}async function iC(t,e){let n=Je(t);await t.exec(YR(n,e));}async function Tu(t){let e=Je(t);return ((await t.exec(ZR(e)))?.rows??[]).map(fy)}async function oC(t,e){let n=Je(t),s=(await t.exec(eC(n,e)))?.rows?.[0];return s?fy(s):null}async function aC(t,e){let n=Je(t);await t.exec(tC(n,e));}Un();var Ru=[{schema:"auth",enabled:t=>!!t.config.auth?.enabled,getSchemaSql:()=>Su(),provision:"baseSchema"},{schema:"storage",enabled:t=>!!(t.config.storage?.enabled&&t.storageAdapter&&ar("storage")),getSchemaSql:()=>ko(),provision:"baseSchema"},{schema:"supabase_migrations",enabled:t=>(t.config.db?.migrations?.enabled??true)!==false,getSchemaSql:t=>Eu(Je(t.connection)),provision:"direct"}],hy=Ru.filter(t=>t.provision==="baseSchema").map(t=>t.schema);function gy(t){return Ru.filter(e=>e.provision==="baseSchema"&&e.enabled(t)).map(e=>e.getSchemaSql(t)).filter(Boolean).join(`
530
+ )`]}function Vy(t){let{schema_migrations:e}=Pt(t);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${t==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${e} (idempotency_key)`]}function JC(t){let e=Gy(t),n=Vy(t);return [...e.slice(0,1),...n,...e.slice(1)]}function zu(t){return JC(t).map(e=>e.trim()).join(`;
531
+ `)+";"}function GC(t,e){let{schema_migrations:n}=Pt(t);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${dr(e.version)}, ${Gu(e.name)}, ${Ky(t,e.statements)}, ${Ky(t,e.rollback??null)}, ${Gu(e.created_by??null)}, ${Gu(e.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function VC(t,e){let{schema_migrations:n}=Pt(t);return `DELETE FROM ${n} WHERE version = ${dr(e)}`}function zC(t){let{schema_migrations:e}=Pt(t);return `SELECT version FROM ${e} ORDER BY version ASC`}var zy="version, name, statements, rollback, created_by, idempotency_key";function Qy(t){let{schema_migrations:e}=Pt(t);return `SELECT ${zy} FROM ${e} ORDER BY version ASC`}function QC(t,e){let{schema_migrations:n}=Pt(t);return `SELECT ${zy} FROM ${n} WHERE version = ${dr(e)}`}function YC(t,e){let{schema_migrations:n}=Pt(t);return `DELETE FROM ${n} WHERE version >= ${dr(e)}`}async function XC(t,e){let{schema_migrations:n}=Pt(e);for(let r of KC){let s=e==="pg"?r.pgType:r.sqliteType;if(e==="pg")await t.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await t.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function Qu(t){let e=Ke(t);for(let n of Gy(e))await t.exec(n);await XC(t,e);for(let n of Vy(e))await t.exec(n);}async function ZC(t){let e=Ke(t);return ((await t.exec(zC(e)))?.rows??[]).map(r=>r.version)}async function ek(t,e){let n=Ke(t);await t.exec(GC(n,e));}async function tk(t,e){let n=Ke(t);await t.exec(VC(n,e));}async function nk(t){let e=Ke(t);return ((await t.exec(Qy(e)))?.rows??[]).map(Vu)}async function Yy(t){let e=Ke(t);return ((await t.exec(Qy(e)))?.rows??[]).map(WC)}async function rk(t,e){let n=Ke(t),s=(await t.exec(QC(n,e)))?.rows?.[0];return s?Vu(s):null}async function sk(t,e){let n=Ke(t);await t.exec(YC(n,e));}Hn();var ti=[{schema:"auth",enabled:t=>!!t.config.auth?.enabled,getSchemaSql:()=>Ju(),provision:"baseSchema"},{schema:"storage",enabled:t=>!!(t.config.storage?.enabled&&t.storageAdapter&&fr("storage")),getSchemaSql:()=>Jo(),provision:"baseSchema",rlsTables:["buckets","objects"]},{schema:"supabase_migrations",enabled:t=>(t.config.db?.migrations?.enabled??true)!==false,getSchemaSql:t=>zu(Ke(t.connection)),provision:"direct"}],Xy=ti.filter(t=>t.provision==="baseSchema").map(t=>t.schema);function Zy(t){return ti.some(e=>e.provision==="baseSchema"&&e.enabled(t))}function eb(t){return ti.filter(e=>e.provision==="baseSchema"&&e.enabled(t)).map(e=>e.getSchemaSql(t)).filter(Boolean).join(`
427
532
 
428
- `)}function yy(t){return !!Ru.find(n=>n.schema==="supabase_migrations")?.enabled(t)}async function by(t){let e=t.config?.baseSchema;if(!e||!e.trim())return;let n=t,r=e;if(n.dialect==="sqlite"&&n.config.ddlDialect!=="sqlite"&&n.translateDdl){let s=await n.translateDdl(e);r=typeof s=="string"?s:s.ddl??e;}for(let s of Fp(r))try{await n.exec(s);}catch{}}var Cu=class{_connection;_rls;config;server;adminMode;drivers;#t;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.#t=n.system??{},this.config=ly(pi,s,{withDefaults:n.defaults??true}),this.drivers=Gh(n.drivers,this.config),this.adminMode=n.server?.admin===true,this.server=oy(this,n.server);}get connection(){if(this._connection instanceof Promise)throw new Error("Connection is not available yet");return this._connection}async init(){if(this.#e)return this;ry(),this.config.auth?.enabled&&yo(this.config.auth),await this._connection;let e=this.connection;if(e.config.schemaCache??=this.drivers.cache,e.config.baseSchema=[e.config.baseSchema??"",gy(this.#n())].filter(Boolean).join(`
533
+ `)}function tb(t){return ti.filter(e=>e.enabled(t)&&e.rlsTables?.length).map(e=>({schema:e.schema,tables:[...e.rlsTables]}))}function nb(...t){let e=new Map;for(let n of t)for(let r of n??[]){let s=e.get(r.schema)??new Set;for(let i of r.tables)s.add(i);e.set(r.schema,s);}return [...e].map(([n,r])=>({schema:n,tables:[...r]}))}function rb(t){return !!ti.find(n=>n.schema==="supabase_migrations")?.enabled(t)}async function sb(t){let e=t.config?.baseSchema;if(!e||!e.trim())return;let n=t,r=e;if(n.dialect==="sqlite"&&n.config.ddlDialect!=="sqlite"&&n.translateDdl){let s=await n.translateDdl(e);r=typeof s=="string"?s:s.ddl??e;}for(let s of lm(r))try{await n.exec(s);}catch{}}var Yu=class{_connection;_rls;config;server;adminMode;drivers;#t;#e=false;_mailer;_storageAdapter;_transformationAdapter;constructor({connection:e,options:n={},rls:r,...s}){this._connection=e,this._rls=r,this.#t=n.system??{},this.config=Wy(Ei,s,{withDefaults:n.defaults??true}),this.drivers=gg(n.drivers,this.config),this.adminMode=n.server?.admin===true,this.server=qy(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;Uy(),this.config.auth?.enabled&&$o(this.config.auth),await this._connection;let e=this.connection;if(e.config.schemaCache??=this.drivers.cache,e.config.baseSchema=[e.config.baseSchema??"",eb(this.#n())].filter(Boolean).join(`
429
534
 
430
- `),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}#n(){return {config:this.config,connection:this.connection,storageAdapter:this._storageAdapter}}async ensureSystemSchema(e){await this.init();let n=this.connection,r=this.#n();if(yy(r)&&await xu(n),(this.#t.schemaReconciliation??"additive")==="full"&&Je(n)!=="sqlite"){let i=n.createMigrator(""),{plan:o}=await i.diff({schemas:hy});await i.migratePlan(o,{force:e?.force});}else await by(n);}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return pi.validate(s).valid}return pi.validate(e).valid}getClient(e){let n=s=>{let i=s?.trim();return i&&i.length>0?i:void 0},r=n(e?.apikey)??n(this.config.auth?.publishable_key)??"<nokey>";return createClient("http://localhost",r,{...e,global:{...e?.global,fetch:async(s,i)=>{let o=new Request(s,i);return Object.assign(o,{[kn]:true}),await this.fetch(o)}}})}isLocalRequest(e){return kn 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 wy=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},Sy=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"};Ho();Yr();var uC=(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
535
+ `),e.config.systemRls=nb(e.config.systemRls,tb(this.#n())),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}#n(){return {config:this.config,connection:this.connection,storageAdapter:this._storageAdapter}}async ensureSystemSchema(e){await this.init();let n=this.connection,r=this.#n();if(rb(r)&&await Qu(n),(this.#t.schemaReconciliation??"additive")==="full"&&Ke(n)!=="sqlite"){let i=n.createMigrator(""),{plan:o}=await i.diff({schemas:Xy});await i.migratePlan(o,{force:e?.force});}else await sb(n);}hasEnabledSystemBaseSchema(){return Zy(this.#n())}isValidConfig(e){if(typeof e=="object"&&e!==null&&("connection"in e||"options"in e)){let{connection:n,options:r,...s}=e;return Ei.validate(s).valid}return Ei.validate(e).valid}getClient(e){let n=s=>{let i=s?.trim();return i&&i.length>0?i:void 0},r=n(e?.apikey)??n(this.config.auth?.publishable_key)??"<nokey>";return createClient("http://localhost",r,{...e,global:{...e?.global,fetch:async(s,i)=>{let o=new Request(s,i);return Object.assign(o,{[Qn]:true}),await this.fetch(o)}}})}isLocalRequest(e){return Qn in e}fetch=async(e,n)=>(await this.init(),this.server.fetch(e,n));getInfoJson(){return JSON.parse(jsonStringify({connection:this.connection?.config??{},config:this.config}))}};var ib=class extends Error{name="UnableToCreateRuntimeConnection";constructor(e){super(`Unable to create runtime connection: ${e}`);}},ob=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"};la();rs();var ak=(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
431
536
  json_group_array(
432
537
  json_object(
433
538
  'name', m.name,
@@ -523,14 +628,17 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
523
628
  WHEN idx_data.is_unique = 1 THEN json('true')
524
629
  ELSE json('false') END,
525
630
  'columns', json(idx_data.cols),
526
- 'schema', ''
631
+ 'schema', '',
632
+ 'sql', idx_data.sql
527
633
  )
528
634
  ) AS data
529
635
  FROM (SELECT
530
636
  m.name AS tbl,
531
637
  idx.name AS idx_name,
532
638
  idx."unique" AS is_unique,
533
- json_group_array(ic.name ORDER BY ic.seqno) AS cols
639
+ json_group_array(ic.name ORDER BY ic.seqno) AS cols,
640
+ (SELECT im.sql FROM sqlite_master im
641
+ WHERE im.type = 'index' AND im.name = idx.name) AS sql
534
642
  FROM sqlite_master m
535
643
  JOIN pragma_index_list(m.name) idx
536
644
  ON m.type = 'table' AND ${e()}
@@ -628,15 +736,15 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
628
736
  (SELECT data FROM trigger_info) AS triggers,
629
737
  (SELECT data FROM unique_info) AS unique_constraints,
630
738
  ${t.name?`'${t.name}'`:"'sqlite'"} AS database_name,
631
- ${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function Gt(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function xy(t,e={}){let r=(await t.exec(uC(e)))?.rows?.[0]||{};return {tables:Gt(r.tables),columns:Gt(r.columns),indexes:Gt(r.indexes),foreign_keys:Gt(r.foreign_keys),primary_keys:Gt(r.primary_keys),views:Gt(r.views),triggers:Gt(r.triggers),check_constraints:[],unique_constraints:Gt(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function fC(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function Ty(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function vu(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function dC(t){let e=new Map;for(let r of t){if(!Ty(r.foreign_key_name))continue;let s=e.get(vu(r));s?s.push(r):e.set(vu(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get(vu(r));return s?{...r,foreign_key_name:s}:r})}function Ry(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!Ty(r.foreign_key_name))return r;let s=e.get(r.table),i=fC(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:dC(n)}}function Au(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function pC(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function mC(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(Au);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?Au(r):i}}function Cy(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function hC(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!Cy(t[s-1])&&!Cy(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function gC(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function ky(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function yC(t,e){if(!t)return null;let n=hC(t);if(!n)return null;let r=gC(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(Au).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of pC(n.selectList)){let f=c.trim();if(f==="*"||f.endsWith(".*")){for(let d of l)ky(a,d,d);continue}let u=mC(c);u&&ky(a,u.baseColumn,u.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function bC(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function wC(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(f=>f.name===l.name&&f.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=yC(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let f=new Map;for(let[d,p]of l.columns){let g=p.filter(m=>c.has(m));g.length>0&&f.set(d,g);}if(f.size===0)continue;let u={name:a.name,schema:a.schema,columnByBaseColumn:f,fromRelation:l.baseTable};s.set(a.name,u);}let i=16;function o(a,l,c){if(l>i)return null;let f=a.fromRelation;if(e.has(f))return {physicalBase:f,columnByBaseColumn:a.columnByBaseColumn};let u=s.get(f);if(!u||c.has(f))return null;c.add(f);let d=o(u,l+1,c);if(c.delete(f),!d)return null;let p=bC(a.columnByBaseColumn,d.columnByBaseColumn);return p.size===0?null:{physicalBase:d.physicalBase,columnByBaseColumn:p}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function vy(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function SC(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function _C(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function EC(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function Ay(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=wC(t),n=new Set(t.foreign_keys.map(vy)),r=[];for(let s of SC(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let f=[];for(let u of s){let d=l.columnByBaseColumn.get(u.column)??[],p=c.columnByBaseColumn.get(u.ref_column)??[],g=d.flatMap(m=>p.map(h=>({fk:u,childColumn:m,parentColumn:h})));if(g.length===0){f.length=0;break}f.push(g);}for(let u of _C(f)){let p=l.name===i.table&&c.name===i.ref_table&&u.every(g=>g.childColumn===g.fk.column&&g.parentColumn===g.fk.ref_column)?void 0:EC(l,c,i.foreign_key_name,u);for(let g of u){let m={...g.fk,table:l.name,column:g.childColumn,schema:l.schema,ref_table:c.name,ref_column:g.parentColumn,ref_schema:c.schema,foreign_key_group:p},h=vy(m);n.has(h)||(n.add(h),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var AC=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),Ou=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#t=new Set;#e=new Set;transformNodeImpl(n,r){if(!AC.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#e.add(o);let i=this.#n(n);for(let o of i)this.#t.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#t.delete(o);for(let o of s)this.#e.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#e.has(s)&&this.#t.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.#e.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}},Wo=class{#t;constructor(e){this.#t=new Ou(e);}transformQuery(e){return this.#t.transformNode(e.node)}async transformResult(e){return e.result}};Js();Pu();$u();function NC(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function $y(t,e){let n=r=>NC(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}function fr(t,e,n){return n.includes(t)?true:n.some(r=>e.startsWith(`${r}.`)||e.startsWith(`${r}__`))}function Iy(t,e){let n=t.tables.filter(i=>fr(i.schema,i.name,e)),r=new Set(n.map(i=>i.name)),s=i=>i.filter(o=>r.has(o.table)||fr(o.schema,o.table,e));return {...t,tables:n,columns:s(t.columns),indexes:s(t.indexes),foreign_keys:s(t.foreign_keys),primary_keys:s(t.primary_keys),views:t.views.filter(i=>fr(i.schema,i.name,e)),check_constraints:s(t.check_constraints),unique_constraints:s(t.unique_constraints),comments:s(t.comments),custom_types:t.custom_types.filter(i=>fr(i.schema,i.type,e)),triggers:t.triggers.filter(i=>fr(i.schema,i.table,e)),functions:t.functions?.filter(i=>e.includes(i.schema)),partitions:t.partitions?.filter(i=>fr(i.schema,i.name,e))}}var Jo=class{constructor(e,n,r={}){this.conn=e;this.desiredSchema=n;this.options=r;this.differ=new cr,this.planner=new ur;}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(e){let n=await this.conn.introspect({postprocess:false}),r=await this.getDesiredSchema();if(!r||r.trim().length===0)return {current:n,desired:n,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:s}=await import('@supabase/lite/sqlite'),i=await s({url:":memory:"});try{await i.exec(r);let o=await i.introspect({postprocess:!1}),a=this.conn.config.ddlDialect,[l,c]=e?.schemas?[Iy(n,e.schemas),Iy(o,e.schemas)]:[$y(n,a),$y(o,a)],f=this.differ.diff(l,c),u=this.planner.plan(f,l,c);return {current:n,desired:o,diff:f,plan:u}}finally{await i.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff({schemas:e?.schemas});return await this.migratePlan(n.plan,e),n}};Vr();var Dy=/^\{\{(.+)\}\}$/;function jy(t){return typeof t=="string"&&Dy.test(t)}function DC(t){return Dy.exec(t)[1]}var Ny=Symbol("unresolved");function Ly(t,e){let n=DC(t),r=qt(e,n,Ny);if(r===Ny)throw new Error(`Unresolved variable: {{${n}}}`);return r}function vt(t,e){let n={};for(let[r,s]of Object.entries(t)){if(r==="$or"||r==="$and"){n[r]=s.map(i=>vt(i,e));continue}if(r==="$not"){n[r]=vt(s,e);continue}if(r==="$always"){n[r]=s;continue}if(r==="$exists"){let i=s;n[r]={...i,where:i?.where?vt(i.where,e):i?.where};continue}if(jy(r)){let i=Ly(r,e),a=LC(i,s);n.$always=a;continue}if(s!=null&&typeof s=="object"&&!Array.isArray(s)){n[r]=Fy(s,e);continue}n[r]=s;}return n}function Fy(t,e){let n={};for(let[r,s]of Object.entries(t))r==="$not"&&s!=null&&typeof s=="object"?n[r]=Fy(s,e):jC(s)?n[r]={...s,where:s?.where?vt(s?.where,e):void 0}:jy(s)?n[r]=Ly(s,e):n[r]=s;return n}function jC(t){return t!=null&&typeof t=="object"&&t.type==="query"}function LC(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}Vr();var Gs=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=FC(e.type);if(!s)return e;let i=qt(n,"auth.role")??"anon";if(i==="service_role")return e;let{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:Uy(e.where,l)}}case "UPDATE":{let l=this.combineUsing(o,a,n),c={...e,where:Uy(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=>vt(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=vt(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=>vt(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=vt(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(!Go(e,n,i)){let a=r[0]??s[0];throw a?new Wn(a):new Error("RLS policy violation")}}};function FC(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 Uy(t,e){return !t||Object.keys(t).length===0?e:Object.keys(e).length===0?t:{$and:[t,e]}}function Go(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=>Go(l,e,n)))return false;continue}if(r==="$or"){if(!s.some(l=>Go(l,e,n)))return false;continue}if(r==="$not"){if(Go(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(!UC(o,a,l))return false}return true}function UC(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 zo=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 My(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}Yl();ro();function MC(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function BC(t){let e=t.trim();return e.startsWith('"')?e.replace(/^"(.*)"$/,"$1"):e.toLowerCase()}function Vo(t){let e=t.split(".");return BC(e[e.length-1]??t)}var Du='(?:"[^"]+"|[A-Za-z_][\\w$]*)',Iu=`${Du}(?:\\s*\\.\\s*${Du})?`,Nu=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${Iu})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${Du}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${Iu}(?:\\s*,\\s*${Iu})*)`].join("|"),"gi");function By(t){let e=[...t].sort((i,o)=>i.version.localeCompare(o.version)),n=MC(e.flatMap(i=>i.statements??[]).join(`
632
- `)),r=new Set;Nu.lastIndex=0;let s=Nu.exec(n);for(;s!==null;){let[,i,o,a,l]=s;if(i&&o){let c=Vo(i);o.toUpperCase()==="ENABLE"?r.add(c):r.delete(c);}else if(i&&a)r.delete(Vo(i))&&r.add(Vo(a));else if(l)for(let c of l.split(","))r.delete(Vo(c));s=Nu.exec(n);}return r}var Qs=class t extends Connection{dialect="sqlite";#t=false;#e;deserializeRow(e){return this.config.ddlDialect==="postgres"?My(e):e}constructor(e={}){let n=e.translation?.deparse!=null;super({...e,translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}}),this.#t=n;}static parseDeparseInfo(e,n){try{if(typeof e!="object"||e===null)return {};let r=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),s=(e?.rls?.policies??[]).map(f=>new Ge(JSON.parse(JSON.stringify(f)))),i=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{})),o=e?.enums instanceof Map?e.enums:new Map(Object.entries(e.enums??{})),a;if(e?.schema instanceof Map)a=e.schema;else if(e?.schema&&typeof e.schema=="object"){a=new Map;for(let[f,u]of Object.entries(e.schema)){let d;for(let{context:p,extra:g}of u??[]){d??=new at(p.table,p.schema);let m=o.get(p.pgTypeName.toLowerCase());d.set(p.column,We({...p,defaultFn:null},{...g,...m?{enumValues:m}:{}}));}d&&a.set(f,d);}}let l=e?.tableConstraints??void 0,c=e?.comments??void 0;return {rls:{tables:r,policies:s},vars:i,enums:o,...a?{schema:a}:{},...l?{tableConstraints:l}:{},...c?{comments:c}:{}}}catch(r){if(n?.strict)throw r;return console.log("error parsing deparse info",r),{}}}static serializeDeparseInfo(e){let n=e?.rls??{tables:new Set,policies:[]},r=e?.vars??new Map,s=e?.enums??new Map,i={};for(let[l,c]of e?.schema??new Map)i[l]=c.all().map(f=>{let{defaultFn:u,...d}=f.context;return {context:d,extra:f.factoryExtra}});let o=e?.tableConstraints??[],a=e?.comments??[];return JSON.parse($p({rls:{tables:n.tables,policies:n.policies},vars:r,enums:s,schema:i,tableConstraints:o,comments:a}))}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e},this.#t=true;}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new zo),n.push(new Wo(vl({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(()=>(Bu(),db));return await s(e,{forceDefaultSchema:n,introspection:r,defaultSchema:this.config.translation?.schemas?.defaultSchema||void 0,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default"})}async introspect(e){jp(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 xy(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 r=Ry(r),r=Ay(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&Le(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let 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}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
739
+ ${t.version?`'${t.version}'`:"sqlite_version()"} AS version;`};function Qt(t){if(!t)return [];try{return Array.isArray(t)?t:JSON.parse(t)}catch{return []}}async function cb(t,e={}){let r=(await t.exec(ak(e)))?.rows?.[0]||{};return {tables:Qt(r.tables),columns:Qt(r.columns),indexes:Qt(r.indexes),foreign_keys:Qt(r.foreign_keys),primary_keys:Qt(r.primary_keys),views:Qt(r.views),triggers:Qt(r.triggers),check_constraints:[],unique_constraints:Qt(r.unique_constraints),comments:[],custom_types:[],database_name:r.database_name??"sqlite",version:r.version??""}}function lk(t,e){if(!t||!e.ref_column)return;let n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`CONSTRAINT\\s+("?)(\\w+)\\1\\s+FOREIGN\\s+KEY\\s*\\(\\s*"?${n(e.column)}"?\\s*\\)\\s+REFERENCES\\s+"?${n(e.ref_table)}"?\\s*\\(\\s*"?${n(e.ref_column)}"?\\s*\\)`,"i");return t.match(r)?.[2]}function ub(t){return t.startsWith("fk_")&&!t.endsWith("_fkey")}function Zu(t){return `${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`}function ck(t){let e=new Map;for(let r of t){if(!ub(r.foreign_key_name))continue;let s=e.get(Zu(r));s?s.push(r):e.set(Zu(r),[r]);}let n=new Map;for(let[r,s]of e)s.length<2||n.set(r,`${s[0].table}_${s.map(i=>i.column).join("_")}_fkey`);return n.size===0?t:t.map(r=>{let s=n.get(Zu(r));return s?{...r,foreign_key_name:s}:r})}function fb(t){if(!t.tables?.length||!t.foreign_keys?.length)return t;let e=new Map(t.tables.map(r=>[r.name,r.sql])),n=t.foreign_keys.map(r=>{if(r.foreign_key_name?.endsWith("_fkey")||r.foreign_key_name&&!ub(r.foreign_key_name))return r;let s=e.get(r.table),i=lk(s,r);return i?{...r,foreign_key_name:i}:r});return {...t,foreign_keys:ck(n)}}function ef(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function uk(t){let e=[],n="",r=0,s=null;for(let i=0;i<t.length;i++){let o=t[i];if(s){n+=o,o===s&&(s=null);continue}if(o==='"'||o==="`"||o==="'"){s=o,n+=o;continue}if(o==="("?r++:o===")"&&r>0&&r--,o===","&&r===0){e.push(n.trim()),n="";continue}n+=o;}return n.trim()&&e.push(n.trim()),e}function fk(t){let e=t.match(/^(.*?)\s+as\s+(.+)$/i),n=e?e[1].trim():t.trim(),r=e?e[2].trim():void 0;if(!r){let o=t.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);o&&!/[()]/.test(o[1])&&(n=o[1].trim(),r=o[2].trim());}let s=n.split(".").map(ef);if(s.length>2)return null;let i=s.at(-1);return !i||!/^[A-Za-z_][\w$]*$/.test(i)?null:{baseColumn:i,viewColumn:r?ef(r):i}}function db(t){return !!(t&&/[A-Za-z0-9_$]/.test(t))}function dk(t){let e=/\bselect\b/i.exec(t);if(!e)return null;let n=0,r=null;for(let s=e.index+e[0].length;s<t.length;s++){let i=t[s];if(r){i===r&&(r=null);continue}if(i==='"'||i==="`"||i==="'"){r=i;continue}if(i==="("){n++;continue}if(i===")"&&n>0){n--;continue}if(n===0&&t.slice(s,s+4).toLowerCase()==="from"&&!db(t[s-1])&&!db(t[s+4]))return {selectList:t.slice(e.index+e[0].length,s).trim(),fromRest:t.slice(s+4).trim()}}return null}function pk(t){let e=0,n=[];for(;e<t.length;){for(;/\s/.test(t[e]??"");)e++;let r=t[e],s="";if(r==='"'||r==="`"){let a=t.indexOf(r,e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else if(r==="["){let a=t.indexOf("]",e+1);if(a===-1)return null;s=t.slice(e,a+1),e=a+1;}else {let a=/^[A-Za-z_][\w$]*/.exec(t.slice(e));if(!a)return null;s=a[0],e+=s.length;}n.push(s);let i=t.slice(e),o=/^\s*\./.exec(i);if(!o)break;e+=o[0].length;}return n.length===0?null:{raw:n.join("."),rest:t.slice(e).trim()}}function pb(t,e,n){let r=t.get(e)??[];r.includes(n)||r.push(n),t.set(e,r);}function mk(t,e){if(!t)return null;let n=dk(t);if(!n)return null;let r=pk(n.fromRest);if(!r)return null;let{raw:s,rest:i}=r;if(/\b(join|union|intersect|except)\b/i.test(i))return null;let o=s.split(".").map(ef).at(-1);if(!o)return null;let a=new Map,l=e.get(o)??new Set;for(let c of uk(n.selectList)){let u=c.trim();if(u==="*"||u.endsWith(".*")){for(let d of l)pb(a,d,d);continue}let f=fk(c);f&&pb(a,f.baseColumn,f.viewColumn);}return a.size===0?null:{baseTable:o,columns:a}}function hk(t,e){let n=new Map;for(let[r,s]of e){let i=[];for(let o of s){let a=t.get(o);if(a)for(let l of a)i.includes(l)||i.push(l);}i.length>0&&n.set(r,i);}return n}function gk(t){let e=new Map,n=new Map;for(let a of t.columns??[]){let l=n.get(a.table)??new Set;l.add(a.name),n.set(a.table,l);}let r=(a,l)=>{let c=e.get(a)??[];c.some(u=>u.name===l.name&&u.schema===l.schema)||c.push(l),e.set(a,c);};for(let a of t.tables??[]){if(a.type!=="table")continue;let l=n.get(a.name);l&&r(a.name,{name:a.name,schema:a.schema,columnByBaseColumn:new Map([...l].map(c=>[c,[c]]))});}let s=new Map;for(let a of t.views??[]){let l=mk(a.sql,n);if(!l)continue;let c=n.get(a.name);if(!c)continue;let u=new Map;for(let[d,p]of l.columns){let h=p.filter(m=>c.has(m));h.length>0&&u.set(d,h);}if(u.size===0)continue;let f={name:a.name,schema:a.schema,columnByBaseColumn:u,fromRelation:l.baseTable};s.set(a.name,f);}let i=16;function o(a,l,c){if(l>i)return null;let u=a.fromRelation;if(e.has(u))return {physicalBase:u,columnByBaseColumn:a.columnByBaseColumn};let f=s.get(u);if(!f||c.has(u))return null;c.add(u);let d=o(f,l+1,c);if(c.delete(u),!d)return null;let p=hk(a.columnByBaseColumn,d.columnByBaseColumn);return p.size===0?null:{physicalBase:d.physicalBase,columnByBaseColumn:p}}for(let a of s.values()){let l=o(a,0,new Set([a.name]));l&&r(l.physicalBase,{name:a.name,schema:a.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function mb(t){return `${t.foreign_key_group??""}:${t.table}.${t.column}->${t.ref_table}.${t.ref_column}`}function yk(t){let e=new Map;for(let n of t){let r=`${n.schema}.${n.table}.${n.foreign_key_name}.${n.ref_schema??""}.${n.ref_table}`,s=e.get(r);s?s.push(n):e.set(r,[n]);}return [...e.values()]}function bk(t){let e=[[]];for(let n of t){let r=[];for(let s of e)for(let i of n)r.push([...s,i]);e=r;}return e}function wk(t,e,n,r){let s=r.map(o=>o.childColumn).join(","),i=r.map(o=>o.parentColumn).join(",");return `${n}:${t.name}(${s})->${e.name}(${i})`}function hb(t){if(!t.foreign_keys?.length||!t.views?.length)return t;let e=gk(t),n=new Set(t.foreign_keys.map(mb)),r=[];for(let s of yk(t.foreign_keys)){let i=s[0],o=e.get(i.table)??[],a=e.get(i.ref_table)??[];for(let l of o)for(let c of a){if(l.schema!==c.schema)continue;let u=[];for(let f of s){let d=l.columnByBaseColumn.get(f.column)??[],p=c.columnByBaseColumn.get(f.ref_column)??[],h=d.flatMap(m=>p.map(g=>({fk:f,childColumn:m,parentColumn:g})));if(h.length===0){u.length=0;break}u.push(h);}for(let f of bk(u)){let p=l.name===i.table&&c.name===i.ref_table&&f.every(h=>h.childColumn===h.fk.column&&h.parentColumn===h.fk.ref_column)?void 0:wk(l,c,i.foreign_key_name,f);for(let h of f){let m={...h.fk,table:l.name,column:h.childColumn,schema:l.schema,ref_table:c.name,ref_column:h.parentColumn,ref_schema:c.schema,foreign_key_group:p},g=mb(m);n.has(g)||(n.add(g),r.push(m));}}}}return r.length?{...t,foreign_keys:[...t.foreign_keys,...r]}:t}var Ck=new Set(["AlterTableNode","CreateIndexNode","CreateSchemaNode","CreateTableNode","CreateTypeNode","CreateViewNode","RefreshMaterializedViewNode","DeleteQueryNode","DropIndexNode","DropSchemaNode","DropTableNode","DropTypeNode","DropViewNode","InsertQueryNode","RawNode","SelectQueryNode","UpdateQueryNode","MergeQueryNode"]),tf=class extends OperationNodeTransformer{constructor(n){super();this.config=n;}#t=new Set;#e=new Set;transformNodeImpl(n,r){if(!Ck.has(n.kind))return super.transformNodeImpl(n,r);let s=this.#s(n);for(let o of s)this.#e.add(o);let i=this.#n(n);for(let o of i)this.#t.add(o);try{return super.transformNodeImpl(n,r)}finally{for(let o of i)this.#t.delete(o);for(let o of s)this.#e.delete(o);}}transformSchemableIdentifier(n,r){let s=n.identifier.name,i=n.schema?.name,o=!i&&this.config.appendDefaultSchema&&this.config.defaultSchema&&!this.#e.has(s)&&this.#t.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.#e.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}},ca=class{#t;constructor(e){this.#t=new tf(e);}transformQuery(e){return this.#t.transformNode(e.node)}async transformResult(e){return e.result}};ni();nf();rf();function Pk(t,e){return t==="migrations"||t==="supabase_migrations.schema_migrations"||t==="supabase_migrations.seed_files"||e==="sqlite"&&t==="seed_files"}function bb(t,e){let n=r=>Pk(r,e);return {...t,tables:t.tables.filter(r=>!n(r.name)),columns:t.columns.filter(r=>!n(r.table)),indexes:t.indexes.filter(r=>!n(r.table)),foreign_keys:t.foreign_keys.filter(r=>!n(r.table)),primary_keys:t.primary_keys.filter(r=>!n(r.table))}}function hr(t,e,n){return n.includes(t)?true:n.some(r=>e.startsWith(`${r}.`)||e.startsWith(`${r}__`))}function wb(t,e){let n=t.tables.filter(i=>hr(i.schema,i.name,e)),r=new Set(n.map(i=>i.name)),s=i=>i.filter(o=>r.has(o.table)||hr(o.schema,o.table,e));return {...t,tables:n,columns:s(t.columns),indexes:s(t.indexes),foreign_keys:s(t.foreign_keys),primary_keys:s(t.primary_keys),views:t.views.filter(i=>hr(i.schema,i.name,e)),check_constraints:s(t.check_constraints),unique_constraints:s(t.unique_constraints),comments:s(t.comments),custom_types:t.custom_types.filter(i=>hr(i.schema,i.type,e)),triggers:t.triggers.filter(i=>hr(i.schema,i.table,e)),functions:t.functions?.filter(i=>e.includes(i.schema)),partitions:t.partitions?.filter(i=>hr(i.schema,i.name,e))}}var fa=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(e){let n=await this.conn.introspect({postprocess:false}),r=await this.getDesiredSchema();if(!r||r.trim().length===0)return {current:n,desired:n,diff:{tables:[],columns:[],indexes:[],foreign_keys:[],has_changes:false},plan:{steps:[],warnings:[],unsafe:false}};let{createConnection:s}=await import('@supabase/lite/sqlite'),i=await s({url:":memory:"});try{await i.exec(r);let o=await i.introspect({postprocess:!1}),a=this.conn.config.ddlDialect,[l,c]=e?.schemas?[wb(n,e.schemas),wb(o,e.schemas)]:[bb(n,a),bb(o,a)],u=this.differ.diff(l,c),f=this.planner.plan(u,l,c);return {current:n,desired:o,diff:u,plan:f}}finally{await i.close();}}safeSortPlanSteps(e){return invariant(Array.isArray(e),"steps must be an array"),e}async migratePlan(e,n){if(e.steps.length===0)return;if(e.unsafe&&!n?.force)throw new DataLossError(e.warnings??[]);let r=this.safeSortPlanSteps(e.steps).filter(s=>![PlanStepType.DISABLE_FOREIGN_KEYS,PlanStepType.BEGIN_TRANSACTION,PlanStepType.COMMIT_TRANSACTION,PlanStepType.ENABLE_FOREIGN_KEYS].includes(s.type));await this.conn.transaction(r.map(s=>s.sql),{intent:"migration"});}async migrate(e){let n=await this.diff({schemas:e?.schemas});return await this.migratePlan(n.plan,e),n}};var da=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 Sb(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}yc();bo();function $k(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function Nk(t){let e=t.trim();return e.startsWith('"')?e.replace(/^"(.*)"$/,"$1"):e.toLowerCase()}function pa(t){let e=t.split(".");return Nk(e[e.length-1]??t)}var af='(?:"[^"]+"|[A-Za-z_][\\w$]*)',sf=`${af}(?:\\s*\\.\\s*${af})?`,of=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${sf})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${af}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${sf}(?:\\s*,\\s*${sf})*)`].join("|"),"gi");function _b(t){let e=[...t].sort((i,o)=>i.version.localeCompare(o.version)),n=$k(e.flatMap(i=>i.statements??[]).join(`
740
+ `)),r=new Set;of.lastIndex=0;let s=of.exec(n);for(;s!==null;){let[,i,o,a,l]=s;if(i&&o){let c=pa(i);o.toUpperCase()==="ENABLE"?r.add(c):r.delete(c);}else if(i&&a)r.delete(pa(i))&&r.add(pa(a));else if(l)for(let c of l.split(","))r.delete(pa(c));s=of.exec(n);}return r}var ii=class t extends Connection{dialect="sqlite";#t=false;#e;deserializeRow(e){return this.config.ddlDialect==="postgres"?Sb(e):e}constructor(e={}){let n=e.translation?.deparse!=null;super({...e,ddlDialect:e.ddlDialect??"postgres",translation:{...e.translation,schemas:{appendDefaultSchema:false,approach:"quote",defaultSchema:"public",...e.translation?.schemas},deparse:t.parseDeparseInfo(e.translation?.deparse)},introspection:{name:"sqlite",...e.introspection,exclude_tables:Array.from(new Set([...e.introspection?.exclude_tables??[],"sqlite_%","supabase_migrations.%","migrations",...e.ddlDialect==="sqlite"?["seed_files"]:[]]))}}),this.#t=n;}static parseDeparseInfo(e,n){try{if(typeof e!="object"||e===null)return {};let r=e?.rls?.tables instanceof Set?e.rls.tables:new Set(e.rls?.tables??[]),s=(e?.rls?.policies??[]).map(u=>new Xe(JSON.parse(JSON.stringify(u)))),i=e?.vars instanceof Map?e.vars:new Map(Object.entries(e.vars??{})),o=e?.enums instanceof Map?e.enums:new Map(Object.entries(e.enums??{})),a;if(e?.schema instanceof Map)a=e.schema;else if(e?.schema&&typeof e.schema=="object"){a=new Map;for(let[u,f]of Object.entries(e.schema)){let d;for(let{context:p,extra:h}of f??[]){d??=new Qe(p.table,p.schema);let m=o.get(p.pgTypeName.toLowerCase());d.set(p.column,we({...p,defaultFn:null},{...h,...m?{enumValues:m}:{}}));}d&&a.set(u,d);}}let l=e?.tableConstraints??void 0,c=e?.comments??void 0;return {rls:{tables:r,policies:s},vars:i,enums:o,...a?{schema:a}:{},...l?{tableConstraints:l}:{},...c?{comments:c}:{}}}catch(r){if(n?.strict)throw r;return console.log("error parsing deparse info",r),{}}}static serializeDeparseInfo(e){let n=e?.rls??{tables:new Set,policies:[]},r=e?.vars??new Map,s=e?.enums??new Map,i={};for(let[l,c]of e?.schema??new Map)i[l]=c.all().map(u=>{let{defaultFn:f,...d}=u.context;return {context:d,extra:u.factoryExtra}});let o=e?.tableConstraints??[],a=e?.comments??[];return JSON.parse(nm({rls:{tables:n.tables,policies:n.policies},vars:r,enums:s,schema:i,tableConstraints:o,comments:a}))}updateDeparseInfo(e){this.config.translation={...this.config.translation,deparse:e},this.#t=true;}withSqlitePlugins(e=[]){let n=[];return this.config.ddlDialect==="sqlite"&&n.push(new da),n.push(new ca(Vl({appendDefaultSchema:false,approach:"quote",defaultSchema:"public"},{...this.config.translation?.schemas}))),[...n,...e]}async translateDdl(e,n){if(e.trim().length===0)return {ddl:e};if(this.config.ddlDialect==="sqlite")return {ddl:e};let r=this.config.translation?.schemas?.defaultSchema&&this.config.translation?.schemas?.appendDefaultSchema?this.config.translation?.schemas?.defaultSchema:false,s=await this.introspect({postprocess:false}).catch(()=>{}),{deparsePostgresDdl:i}=await Promise.resolve().then(()=>(hf(),Jb));return await i(e,{forceDefaultSchema:r,introspection:s,defaultSchema:this.config.translation?.schemas?.defaultSchema||void 0,schemaHandling:this.config.translation?.schemas?.approach==="snake_case"?"prefix":"default",strict:n?.strict})}async introspect(e){om(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 cb(this,this.config.introspection),s=this.config.translation?.schemas?.approach==="snake_case"?"__":".";if(this.config.ddlDialect==="postgres"&&e?.postprocess!==false){let i=this.config.translation?.schemas?.defaultSchema??this.config.translation?.schemas?.appendDefaultSchema?"public":void 0,o=(l="table")=>c=>{let u=c[l],f=c.schema??i;return !f&&i&&u.includes(s)&&([f,u]=u.split(s)),{...c,[l]:u,schema:f??i}},a=l=>{let c=o()(l),u=c.ref_table,f=c.ref_schema??i;return u?.includes(s)&&([f,u]=u.split(s)),{...c,ref_table:u,ref_schema:f??i}};r={...r,tables:r.tables.map(o("name")),columns:r.columns.map(o()),indexes:r.indexes.map(o()),primary_keys:r.primary_keys.map(o()),foreign_keys:r.foreign_keys.map(a),views:r.views.map(o("name")),check_constraints:r.check_constraints.map(o("table"))};}return r=fb(r),r=hb(r),this.config.ddlDialect==="postgres"&&e?.postprocess!==false&&(r=this.mergeDeparseMetadata(r)),r={...r,columns:r.columns.map(i=>!i.pg_type&&qe(i.type)?{...i,pg_type:i.type.toLowerCase().trim()}:i),ddl_dialect:this.config.ddlDialect??"postgres",schema_separator:s},e?.postprocess!==false&&await this.writeCachedIntrospection(r,{useDriver:n}),r}async transaction(e,n){n?.intent==="migration"&&await this.exec("PRAGMA foreign_keys=OFF;"),await this.exec("BEGIN");try{for(let r of e)try{await this.exec(r);}catch(s){throw console.error(`Failed to execute statement: ${r}`),s}await this.exec("COMMIT");}catch(r){throw await this.exec("ROLLBACK"),r}finally{n?.intent==="migration"&&(await this.exec("PRAGMA foreign_keys=ON;"),await this.clearSchemaCache());}}async close(){}mergeDeparseMetadata(e){let n=this.config.translation?.deparse;if(!n?.schema)return e;let r=e.columns.map(l=>({...l})),s=e.foreign_keys.map(l=>({...l})),i=[...e.unique_constraints??[]],o=[...e.check_constraints??[]];for(let[,l]of n.schema)for(let c of l.all()){let u=c.context,f=r.find(d=>d.table===u.table&&d.name===u.column);if(f&&(f.pg_type=u.pgTypeName,u.isGenerated!==void 0&&(f.is_generated=u.isGenerated)),u.fkRef?.constraintName){let d=s.find(p=>p.table===u.table&&p.column===u.column&&p.ref_table===u.fkRef.refTable&&p.ref_column===u.fkRef.refColumn);d&&(d.foreign_key_name=u.fkRef.constraintName);}u.uniqueConstraintName&&i.push({schema:u.schema,table:u.table,name:u.uniqueConstraintName,columns:[u.column]}),u.hasCheck&&o.push({schema:u.schema,table:u.table,expression:"",name:u.checkConstraintName,column:u.column});}for(let l of n.tableConstraints??[])if(l.kind==="unique")i.push({schema:l.schema,table:l.table,name:l.name??"",columns:l.columns});else if(l.kind==="check")o.push({schema:l.schema,table:l.table,expression:"",name:l.name});else if(l.kind==="foreign_key"&&l.name){let c=l.refTable;for(let u=0;u<l.columns.length;u++){let f=s.find(d=>d.table===l.table&&d.column===l.columns[u]&&d.ref_table===c&&d.ref_column===(l.refColumns?.[u]??""));f&&(f.foreign_key_name=l.name);}}let a=[...e.comments??[],...n.comments??[]];return {...e,columns:r,foreign_keys:s,unique_constraints:i,check_constraints:o,comments:a}}createMigrator(e){let n=[this.config.baseSchema,e].filter(Boolean).join(`
633
741
 
634
- `);return new Jo(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.updateDeparseInfo(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,await 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 await this.applyRls(e,n)}rlsEnabledFromHistory(){return this.config.ddlDialect!=="postgres"?Promise.resolve(new Set):(this.#e||(this.#e=Tu(this).then(e=>By(e)).catch(()=>new Set)),this.#e)}async applyRls(e,n){let r=this.config.translation?.deparse,s=this.config.translation?.schemas?.defaultSchema||void 0,i=n??{auth:{uid:null,role:"anon",jwt:null}};if(this.config.ddlDialect==="postgres"&&!this.#t){let l=await this.rlsEnabledFromHistory();if(l.size>0)return mb||(mb=true,console.error("[ RLS ] RLS metadata is missing for this database \u2014 denying requests to protected tables (fail closed). Run `lite migration up` or `lite db reset` to regenerate RLS metadata.")),e.from?new Gs(l,[],s).enforce(e,i):e}let o=r?.rls;return o?new Gs(o.tables,o.policies,s).enforce(e,i):e}},mb=false;var ia=class extends Qs{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}`);if(i.trim())try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function fk(t){return new ia(t)}Bu();Js();Yr();var dk=["anon","authenticated","service_role"];function pk(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function mk(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
742
+ `);return new fa(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.updateDeparseInfo(s);}}})}get maxBoundParameters(){return this.config.maxBoundParameters??100}assertParamLimit(e){let n=e?.length??0,r=this.maxBoundParameters;if(!(n<=r))throw Object.assign(new Error(`Query exceeds max bound parameters (${n} > ${r}). SQLite drivers vary in how many parameters they accept per statement; @supabase/lite enforces a conservative limit of ${r} for portability. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000"})}prepareBindParams(e){return this.assertParamLimit(e),this.normalizeBindParams(e)}normalizeBindParams(e){if(!e||e.length===0)return [];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(s===void 0)continue;if(s===null){n.push(s);continue}let i=typeof s;if(i==="boolean"){n.push(s?1:0);continue}if(i==="number"||i==="bigint"||i==="string"){n.push(s);continue}if(s instanceof Uint8Array||s instanceof ArrayBuffer||s instanceof Date){n.push(s);continue}throw new Error(`Cannot bind value at parameter ${r+1}: unsupported type ${Array.isArray(s)?"array":i}`)}return n}normalizeDbError(e){let n=e,r=n?.cause?.code??n?.code,s=n?.cause?.message??n?.message??String(e);if(r==="SQLITE_CONSTRAINT_NOTNULL")return Object.assign(new Error(s),{code:"23502",detail:s});if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT_PRIMARYKEY")return Object.assign(new Error(s),{code:"23505",detail:s});if(r==="SQLITE_CONSTRAINT_FOREIGNKEY")return Object.assign(new Error(s),{code:"23503",detail:s});if(typeof s=="string"){if(/too many SQL variables/i.test(s)){let a=this.maxBoundParameters;return Object.assign(new Error(`Query exceeds SQLite bound-parameter limit. @supabase/lite enforces a conservative limit of ${a} for portability across drivers. Split the query (e.g. chunk large .in() filters or batch INSERTs) on the caller.`),{code:"54000",detail:s})}let i=s.match(/no such table:\s*([A-Za-z0-9_.]+)/i);if(i){let a=i[1],l=a.lastIndexOf("."),c=l>=0?a.slice(0,l):void 0,u=l>=0?a.slice(l+1):a;return new RelationNotFoundError(c,u)}let o=s.match(/no such column:\s*([A-Za-z0-9_.]+)/i);if(o)return Object.assign(new Error(`column ${o[1]} does not exist`),{code:"42703",detail:s})}return e}async onPostgrestAST(e,n){if(this.config.ddlDialect==="sqlite")return e.schema=void 0,await this.applyRls(e,n);let r=this.config.translation?.schemas?.appendDefaultSchema,s=this.config.translation?.schemas?.defaultSchema;if(e.schema&&e.schema===s&&!r?e.schema=void 0:!e.schema&&s&&r&&(e.schema=s),!e.from)return e;let i=await this.introspect({useCache:true}),o=e.schema??(r&&s?s:""),a=e.from;if(!(i.tables.some(c=>c.name===a&&(c.schema??"")===o)||i.views.some(c=>c.name===a&&(c.schema??"")===o))){if(!(i.tables.some(u=>u.name===a&&["","public",s].includes(u.schema??""))||i.views.some(u=>u.name===a&&["","public",s].includes(u.schema??""))))throw new RelationNotFoundError(o,a);e.schema=void 0;}return await this.applyRls(e,n)}rlsEnabledFromHistory(){return this.config.ddlDialect!=="postgres"?Promise.resolve(new Set):(this.#e||(this.#e=Yy(this).then(e=>_b(e)).catch(e=>{if(String(e).includes("no such table"))return new Set;throw e})),this.#e)}async applyRls(e,n){let r=this.config.translation?.deparse,s=this.config.translation?.schemas?.defaultSchema||void 0,i=n??{auth:{uid:null,role:"anon",jwt:null}},o=e.schema?this.config.systemRls?.find(f=>f.schema===e.schema)?.tables??[]:[],a=!!e.from&&o.includes(e.from);if(this.config.ddlDialect==="postgres"&&!this.#t){let f=await this.rlsEnabledFromHistory(),d=a?new Set([...f,e.from]):f;if(d.size>0)return Vb||(Vb=true,console.error("[ RLS ] RLS metadata is missing for this database \u2014 denying requests to protected tables (fail closed). Run `lite migration up` or `lite db reset` to regenerate RLS metadata.")),e.from?new Ls(d,[],s).enforce(e,i):e}let l=r?.rls;if(!l&&!a)return e;let c=a?new Set([...l?.tables??[],e.from]):l.tables;return new Ls(c,l?.policies??[],s).enforce(e,i)}},Vb=false;var Ta=class extends ii{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}`);if(i.trim())try{return JSON.parse(i)}catch(o){throw console.error(o),new Error(`Failed to parse exec response: "${i}"`)}}async close(){}};function aA(t){return new Ta(t)}hf();ni();rs();var lA=["anon","authenticated","service_role"];function cA(t){return t==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function uA(t){return t.size===0?"":`DO $$ BEGIN${[...t].map(n=>`
635
743
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
636
- CREATE ROLE ${n} ${pk(n)};
744
+ CREATE ROLE ${n} ${cA(n)};
637
745
  END IF;`).join("")}
638
746
  END $$;
639
- `}mk(new Set(dk));var hk=`
747
+ `}uA(new Set(lA));var fA=`
640
748
  CREATE SCHEMA IF NOT EXISTS auth;
641
749
 
642
750
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
@@ -657,11 +765,11 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
657
765
  '{}'
658
766
  )::jsonb;
659
767
  $$ LANGUAGE SQL STABLE;
660
- `;var hb="supabase-self-hosted";function qu(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gb(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function gk(t,e=hb,n){let r=n??crypto.getRandomValues(new Uint8Array(17)),s=`sb_${t}_`,i=s+qu(r).slice(0,22),o=qu(await gb(`${e}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await yb(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:t}}async function yb(t){return qu(await gb(t))}function yk(t){return t.startsWith("sb_publishable_")?"publishable":t.startsWith("sb_secret_")?"secret":null}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:
768
+ `;var zb="supabase-self-hosted";function gf(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Qb(t){let e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}async function dA(t,e=zb,n){let r=n??crypto.getRandomValues(new Uint8Array(17)),s=`sb_${t}_`,i=s+gf(r).slice(0,22),o=gf(await Qb(`${e}|${i}`)).slice(0,8),a=`${i}_${o}`,l=await Yb(a),c=a.slice(0,s.length+5);return {key:a,hash:l,prefix:c,type:t}}async function Yb(t){return gf(await Qb(t))}function pA(t){return t.startsWith("sb_publishable_")?"publishable":t.startsWith("sb_secret_")?"secret":null}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:
661
769
 
662
770
  aws4fetch/dist/aws4fetch.esm.mjs:
663
771
  (**
664
772
  * @license MIT <https://opensource.org/licenses/MIT>
665
773
  * @copyright Michael Hart 2024
666
774
  *)
667
- */export{Cu as App,Eo as AwsSesEmailDriver,ia as CloudConnection,bo as CloudflareKvCacheDriver,ec as Connection,Yn as ConsoleEmailDriver,_y as DataLossError,Es as InMemoryEmailDriver,Vn as InMemoryLruCacheDriver,Sy as InvalidPostgresToSQLiteTranslation,Ey as MigrationError,xs as NoopSmsDriver,ku as PlanStepType,Ge as Policy,wo as RedisCacheDriver,Bn as RelationNotFoundError,So as ResendEmailDriver,hb as SELF_HOSTED_PROJECT_REF,hk as SUPABASE_AUTH_HELPERS_SQL,xo as SendmailEmailDriver,Qn as SmtpEmailDriver,Qs as SqliteConnection,wy as UnableToCreateRuntimeConnection,yk as apiKeyType,rC as appliedVersions,Fc as assertSmtpSupportedRuntime,Lc as buildSmtpMail,To as buildSmtpTransportOptions,UO as checkPasswordStrength,Qr as cleanSql,fk as cloud,Gh as createAppDrivers,xu as ensureHistoryTable,o$ as ensureVar,e$ as filterSearchParams,jc as formatSendmailMessage,Jr as fuzzyMatch,gk as generateApiKey,Su as getAuthSchemaSql,Eu as getMigrationHistorySchemaSql,qt as getPath,l$ as getStatementsArray,ko as getStorageSchemaSql,oC as getVersion,yb as hashApiKey,Je as historyVariant,jp as invariant,HP as isBooleanLike,Al as isBun,FO as isEmail,kl as isEqual,ar as isExperimentalEnabled,Np as isNode,Pp as isObject,Op as isPlainObject,qP as isPrimitive,WP as isString,Dp as isWorkerd,$p as jsonStringify,ny as listEnabledExperimentals,Tu as listHistory,i$ as measureTime,vl as mergeObject,G_ as mergeObjectWith,Nl as normalizeDefault,to as normalizeSql,WS as normalizeString,$l as normalizeType,VP as objectDiff,YP as omit,ZP as params,u$ as parseBigInt,Ki as patternMatch,QP as pick,JP as pipe,GP as pipeEach,N as quote,LO as randomString,sC as recordVersion,iC as removeVersion,aC as removeVersionsGte,KO as replacePlaceholders,vs as requireAuth,Bc as resolveAuth,FR as setExperimental,J_ as setPath,HO as slugify,qO as snakeToPascalWithSpaces,Fp as splitSqlStatements,DR as studioRouteHandler,Il as tableStructuralItems,n$ as threw,r$ as threwAsync,ub as translatePostgresDdl,WO as truncate,s$ as trySync,MO as ucFirst,BO as ucFirstAll,d$ as uuid};
775
+ */export{Yu as App,Lo as AwsSesEmailDriver,Ta as CloudConnection,No as CloudflareKvCacheDriver,Sc as Connection,tr as ConsoleEmailDriver,ab as DataLossError,As as InMemoryEmailDriver,Zn as InMemoryLruCacheDriver,ob as InvalidPostgresToSQLiteTranslation,lb as MigrationError,vs as NoopSmsDriver,Xu as PlanStepType,Xe as Policy,Io as RedisCacheDriver,Kn as RelationNotFoundError,Do as ResendEmailDriver,zb as SELF_HOSTED_PROJECT_REF,fA as SUPABASE_AUTH_HELPERS_SQL,Fo as SendmailEmailDriver,er as SmtpEmailDriver,ii as SqliteConnection,ib as UnableToCreateRuntimeConnection,pA as apiKeyType,ZC as appliedVersions,su as assertSmtpSupportedRuntime,ru as buildSmtpMail,Uo as buildSmtpTransportOptions,DP as checkPasswordStrength,ns as cleanSql,aA as cloud,gg as createAppDrivers,Qu as ensureHistoryTable,nN as ensureVar,Q$ as filterSearchParams,nu as formatSendmailMessage,Xr as fuzzyMatch,dA as generateApiKey,Ju as getAuthSchemaSql,zu as getMigrationHistorySchemaSql,Wt as getPath,sN as getStatementsArray,Jo as getStorageSchemaSql,rk as getVersion,Yb as hashApiKey,Ke as historyVariant,om as invariant,U$ as isBooleanLike,zl as isBun,IP as isEmail,Gl as isEqual,fr as isExperimentalEnabled,Ga as isLoopbackAddress,ld as isLoopbackHostname,sm as isNode,tm as isObject,em as isPlainObject,F$ as isPrimitive,M$ as isString,im as isWorkerd,nm as jsonStringify,Fy as listEnabledExperimentals,nk as listHistory,tN as measureTime,Vl as mergeObject,RE as mergeObjectWith,ec as normalizeDefault,ho as normalizeSql,E_ as normalizeString,Xl as normalizeType,K$ as objectDiff,G$ as omit,z$ as params,oN as parseBigInt,ro as patternMatch,J$ as pick,q$ as pipe,H$ as pipeEach,F as quote,NP as randomString,ek as recordVersion,tk as removeVersion,sk as removeVersionsGte,BP as replacePlaceholders,lu as requireAuth,au as resolveAuth,NC as setExperimental,TE as setPath,UP as slugify,FP as snakeToPascalWithSpaces,lm as splitSqlStatements,OC as studioRouteHandler,Zl as tableStructuralItems,X$ as threw,Z$ as threwAsync,Wb as translatePostgresDdl,MP as truncate,eN as trySync,jP as ucFirst,LP as ucFirstAll,lN as uuid};