import { createRequire as __createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
import { Buffer } from 'node:buffer';
import process from 'node:process';

const require = __createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

if (typeof globalThis !== 'undefined') {
  globalThis.require = require;
  globalThis.__filename = __filename;
  globalThis.__dirname = __dirname;
  globalThis.Buffer = Buffer;
  globalThis.process = process;
  if (typeof global === 'undefined') {
    globalThis.global = globalThis;
  }
}
var Fi=Object.defineProperty;var i=(e,t)=>Fi(e,"name",{value:t,configurable:!0});var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Z,Le,jt,$t,Gt,rt=u(()=>{"use strict";Z={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Le={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},jt={[Z.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[Z.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[Z.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},$t=4,Gt={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}}});function it(e){return{lang:e?.lang??nt?.lang,message:e?.message,abortEarly:e?.abortEarly??nt?.abortEarly,abortPipeEarly:e?.abortPipeEarly??nt?.abortPipeEarly}}function Ui(e){return Ni?.get(e)}function Li(e){return Mi?.get(e)}function qi(e,t){return Bi?.get(e)?.get(t)}function le(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function T(e,t,r,o,s){let a=s&&"input"in s?s.input:r.value,l=s?.expected??e.expects??null,m=s?.received??le(a),p={kind:e.kind,type:e.type,input:a,expected:l,received:m,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${m}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",f=s?.message??e.message??qi(e.reference,p.lang)??(h?Li(p.lang):null)??o.message??Ui(p.lang);f!==void 0&&(p.message=typeof f=="function"?f(p):f),h&&(r.typed=!1),r.issues?r.issues.push(p):r.issues=[p]}function N(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},it())}}}function Wt(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function ot(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function pe(e,t){return{kind:"validation",type:"check",reference:pe,async:!1,expects:null,requirement:e,message:t,"~run"(r,o){return r.typed&&!this.requirement(r.value)&&T(this,"input",r,o),r}}}function Y(e){return{kind:"validation",type:"email",reference:Y,expects:null,async:!1,requirement:Vi,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&T(this,"email",t,r),t}}}function J(e){return{kind:"validation",type:"integer",reference:J,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&T(this,"integer",t,r),t}}}function Q(e){return{kind:"validation",type:"iso_timestamp",reference:Q,async:!1,expects:null,requirement:ji,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&T(this,"timestamp",t,r),t}}}function Ie(e,t){return{kind:"validation",type:"length",reference:Ie,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,o){return r.typed&&r.value.length!==this.requirement&&T(this,"length",r,o,{received:`${r.value.length}`}),r}}}function he(e,t){return{kind:"validation",type:"max_length",reference:he,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,o){return r.typed&&r.value.length>this.requirement&&T(this,"length",r,o,{received:`${r.value.length}`}),r}}}function re(e,t){return{kind:"validation",type:"max_value",reference:re,async:!1,expects:`<=${e instanceof Date?e.toJSON():le(e)}`,requirement:e,message:t,"~run"(r,o){return r.typed&&!(r.value<=this.requirement)&&T(this,"value",r,o,{received:r.value instanceof Date?r.value.toJSON():le(r.value)}),r}}}function y(e,t){return{kind:"validation",type:"min_length",reference:y,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,o){return r.typed&&r.value.length<this.requirement&&T(this,"length",r,o,{received:`${r.value.length}`}),r}}}function U(e,t){return{kind:"validation",type:"min_value",reference:U,async:!1,expects:`>=${e instanceof Date?e.toJSON():le(e)}`,requirement:e,message:t,"~run"(r,o){return r.typed&&!(r.value>=this.requirement)&&T(this,"value",r,o,{received:r.value instanceof Date?r.value.toJSON():le(r.value)}),r}}}function Be(e,t){return{kind:"validation",type:"regex",reference:Be,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,o){return r.typed&&!this.requirement.test(r.value)&&T(this,"format",r,o),r}}}function q(e){return{kind:"validation",type:"url",reference:q,async:!1,expects:null,requirement(t){try{return new URL(t),!0}catch{return!1}},message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&T(this,"URL",t,r),t}}}function Kt(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Ce(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function de(){return{kind:"schema",type:"any",reference:de,expects:"any",async:!1,get"~standard"(){return N(this)},"~run"(e){return e.typed=!0,e}}}function b(e,t){return{kind:"schema",type:"array",reference:b,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){let s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let a=0;a<s.length;a++){let l=s[a],m=this.item["~run"]({value:l},o);if(m.issues){let p={type:"array",origin:"value",input:s,key:a,value:l};for(let h of m.issues)h.path?h.path.unshift(p):h.path=[p],r.issues?.push(h);if(r.issues||(r.issues=m.issues),o.abortEarly){r.typed=!1;break}}m.typed||(r.typed=!1),r.value.push(m.value)}}else T(this,"type",r,o);return r}}}function I(e){return{kind:"schema",type:"boolean",reference:I,expects:"boolean",async:!1,message:e,get"~standard"(){return N(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:T(this,"type",t,r),t}}}function at(e,t){return{kind:"schema",type:"custom",reference:at,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){return this.check(r.value)?r.typed=!0:T(this,"type",r,o),r}}}function ut(e){return{kind:"schema",type:"lazy",reference:ut,expects:"unknown",async:!1,getter:e,get"~standard"(){return N(this)},"~run"(t,r){return this.getter(t.value)["~run"](t,r)}}}function oe(e,t){return{kind:"schema",type:"literal",reference:oe,expects:le(e),async:!1,literal:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){return r.value===this.literal?r.typed=!0:T(this,"type",r,o),r}}}function ct(e,t){return{kind:"schema",type:"loose_object",reference:ct,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){let s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(let a in this.entries){let l=this.entries[a];if(a in s||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=a in s?s[a]:Ce(l),p=l["~run"]({value:m},o);if(p.issues){let h={type:"object",origin:"value",input:s,key:a,value:m};for(let f of p.issues)f.path?f.path.unshift(h):f.path=[h],r.issues?.push(f);if(r.issues||(r.issues=p.issues),o.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[a]=p.value}else if(l.fallback!==void 0)r.value[a]=Kt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(T(this,"key",r,o,{input:void 0,expected:`"${a}"`,path:[{type:"object",origin:"key",input:s,key:a,value:s[a]}]}),o.abortEarly))break}if(!r.issues||!o.abortEarly)for(let a in s)Wt(s,a)&&!(a in this.entries)&&(r.value[a]=s[a])}else T(this,"type",r,o);return r}}}function lt(e){return{kind:"schema",type:"never",reference:lt,expects:"never",async:!1,message:e,get"~standard"(){return N(this)},"~run"(t,r){return T(this,"type",t,r),t}}}function M(e,t){return{kind:"schema",type:"nullable",reference:M,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return N(this)},"~run"(r,o){return r.value===null&&(this.default!==void 0&&(r.value=Ce(this,r,o)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,o)}}}function z(e,t){return{kind:"schema",type:"nullish",reference:z,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return N(this)},"~run"(r,o){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=Ce(this,r,o)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,o)}}}function S(e){return{kind:"schema",type:"number",reference:S,expects:"number",async:!1,message:e,get"~standard"(){return N(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:T(this,"type",t,r),t}}}function g(e,t){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){let s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(let a in this.entries){let l=this.entries[a];if(a in s||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let m=a in s?s[a]:Ce(l),p=l["~run"]({value:m},o);if(p.issues){let h={type:"object",origin:"value",input:s,key:a,value:m};for(let f of p.issues)f.path?f.path.unshift(h):f.path=[h],r.issues?.push(f);if(r.issues||(r.issues=p.issues),o.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[a]=p.value}else if(l.fallback!==void 0)r.value[a]=Kt(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(T(this,"key",r,o,{input:void 0,expected:`"${a}"`,path:[{type:"object",origin:"key",input:s,key:a,value:s[a]}]}),o.abortEarly))break}}else T(this,"type",r,o);return r}}}function c(e,t){return{kind:"schema",type:"optional",reference:c,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return N(this)},"~run"(r,o){return r.value===void 0&&(this.default!==void 0&&(r.value=Ce(this,r,o)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,o)}}}function E(e,t){return{kind:"schema",type:"picklist",reference:E,expects:ot(e.map(le),"|"),async:!1,options:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){return this.options.includes(r.value)?r.typed=!0:T(this,"type",r,o),r}}}function R(e,t,r){return{kind:"schema",type:"record",reference:R,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return N(this)},"~run"(o,s){let a=o.value;if(a&&typeof a=="object"){o.typed=!0,o.value={};for(let l in a)if(Wt(a,l)){let m=a[l],p=this.key["~run"]({value:l},s);if(p.issues){let f={type:"object",origin:"key",input:a,key:l,value:m};for(let k of p.issues)k.path=[f],o.issues?.push(k);if(o.issues||(o.issues=p.issues),s.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:m},s);if(h.issues){let f={type:"object",origin:"value",input:a,key:l,value:m};for(let k of h.issues)k.path?k.path.unshift(f):k.path=[f],o.issues?.push(k);if(o.issues||(o.issues=h.issues),s.abortEarly){o.typed=!1;break}}(!p.typed||!h.typed)&&(o.typed=!1),p.typed&&(o.value[p.value]=h.value)}}else T(this,"type",o,s);return o}}}function n(e){return{kind:"schema",type:"string",reference:n,expects:"string",async:!1,message:e,get"~standard"(){return N(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:T(this,"type",t,r),t}}}function Ht(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function fe(e,t){return{kind:"schema",type:"union",reference:fe,expects:ot(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return N(this)},"~run"(r,o){let s,a,l;for(let m of this.options){let p=m["~run"]({value:r.value},o);if(p.typed)if(p.issues)a?a.push(p):a=[p];else{s=p;break}else l?l.push(p):l=[p]}if(s)return s;if(a){if(a.length===1)return a[0];T(this,"type",r,o,{issues:Ht(a)}),r.typed=!0}else{if(l?.length===1)return l[0];T(this,"type",r,o,{issues:Ht(l)})}return r}}}function V(){return{kind:"schema",type:"unknown",reference:V,expects:"unknown",async:!1,get"~standard"(){return N(this)},"~run"(e){return e.typed=!0,e}}}function pt(e,t,r){return{kind:"schema",type:"variant",reference:pt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return N(this)},"~run"(o,s){let a=o.value;if(a&&typeof a=="object"){let l,m=0,p=this.key,h=[],f=i((k,A)=>{for(let C of k.options){if(C.type==="variant")f(C,new Set(A).add(C.key));else{let D=!0,L=0;for(let w of A){let F=C.entries[w];if(w in a?F["~run"]({typed:!1,value:a[w]},{abortEarly:!0}).issues:F.type!=="exact_optional"&&F.type!=="optional"&&F.type!=="nullish"){D=!1,p!==w&&(m<L||m===L&&w in a&&!(p in a))&&(m=L,p=w,h=[]),p===w&&h.push(C.entries[w].expects);break}L++}if(D){let w=C["~run"]({value:a},s);(!l||!l.typed&&w.typed)&&(l=w)}}if(l&&!l.issues)break}},"parseOptions");if(f(this,new Set([this.key])),l)return l;T(this,"type",o,s,{input:a[p],expected:ot(h,"|"),path:[{type:"object",origin:"value",input:a,key:p,value:a[p]}]})}else T(this,"type",o,s);return o}}}function dt(e,t,r){let o=e["~run"]({value:t},it(r));if(o.issues)throw new st(o.issues);return o.value}function d(...e){return{...e[0],pipe:e,get"~standard"(){return N(this)},"~run"(t,r){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=o["~run"](t,r))}return t}}}function X(e,t,r){let o=e["~run"]({value:t},it(r));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}var nt,Ni,Mi,Bi,st,Vi,xs,ji,j=u(()=>{i(it,"getGlobalConfig");i(Ui,"getGlobalMessage");i(Li,"getSchemaMessage");i(qi,"getSpecificMessage");i(le,"_stringify");i(T,"_addIssue");i(N,"_getStandardProps");i(Wt,"_isValidObjectKey");i(ot,"_joinExpects");st=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},Vi=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,xs=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u"),ji=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;i(pe,"check");i(Y,"email");i(J,"integer");i(Q,"isoTimestamp");i(Ie,"length");i(he,"maxLength");i(re,"maxValue");i(y,"minLength");i(U,"minValue");i(Be,"regex");i(q,"url");i(Kt,"getFallback");i(Ce,"getDefault");i(de,"any");i(b,"array");i(I,"boolean");i(at,"custom");i(ut,"lazy");i(oe,"literal");i(ct,"looseObject");i(lt,"never");i(M,"nullable");i(z,"nullish");i(S,"number");i(g,"object");i(c,"optional");i(E,"picklist");i(R,"record");i(n,"string");i(Ht,"_subIssues");i(fe,"union");i(V,"unknown");i(pt,"variant");i(dt,"parse");i(d,"pipe");i(X,"safeParse")});function Yt(e){return X(mt,e)}var zt,ft,$i,Gi,mt,Hi,Rs,ws,Xt=u(()=>{"use strict";j();rt();zt=g({role:E([Le.USER,Le.ASSISTANT,Le.SYSTEM]),content:d(n(),y(1)),id:c(n()),createdAt:c(n())}),ft=ut(()=>g({type:E(["string","number","boolean","array","object"]),description:c(n()),enum:c(b(n())),items:c(ft),properties:c(R(n(),ft)),required:c(b(n()))})),$i=g({description:d(n(),y(1)),parameters:g({type:oe("object"),properties:R(n(),ft),required:c(b(n()))})}),Gi=g({id:n(),name:n(),args:R(n(),V())}),mt=g({messages:d(b(zt),y(1)),provider:c(E([Z.ANTHROPIC,Z.OPENAI,Z.GOOGLE])),model:c(n()),maxTokens:c(d(S(),J(),U(1))),temperature:c(d(S(),U(0),re(2))),systemPrompt:c(n()),stream:c(I()),tools:c(R(n(),$i))}),Hi=g({promptTokens:S(),completionTokens:S(),totalTokens:S()}),Rs=g({message:zt,usage:c(Hi),finishReason:c(n()),toolCalls:c(b(Gi))}),ws=g({provider:E([Z.ANTHROPIC,Z.OPENAI,Z.GOOGLE]),model:c(n()),maxTokens:c(d(S(),J(),U(1))),temperature:c(d(S(),U(0),re(2))),systemPrompt:c(n())});i(Yt,"validateAIChatRequest")});var Zt=u(()=>{"use strict"});var Jt=u(()=>{"use strict";rt();Xt();Zt()});var se,Qt,er,tr,gt=u(()=>{"use strict";se={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},Qt={FREE:"free",PRO:"pro",PREMIUM:"premium"},er={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},tr={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"}});var Pe,yt,Ns,ht=u(()=>{"use strict";Pe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},yt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},Ns={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});var Bs,qs,Vs,js,$s,Gs,Wi,Ki,zi,Hs,Ws,Ks,rr=u(()=>{"use strict";j();ht();Bs=d(g({userId:c(n()),productId:c(n()),priceId:c(n()),unitAmount:c(d(S(),J(),U(1))),productName:c(d(n(),y(1))),currency:c(d(n(),Ie(3,"Currency must be 3-letter ISO code"))),successUrl:d(n(),q()),cancelUrl:d(n(),q()),customerEmail:c(d(n(),Y())),userEmail:c(d(n(),Y())),metadata:c(R(n(),n())),allowPromotionCodes:c(I()),mode:c(E([yt.PAYMENT,yt.SUBSCRIPTION]))}),pe(e=>!!(e.priceId||e.unitAmount&&e.productName),"Either priceId or (unitAmount + productName) is required")),qs=g({sessionId:n(),sessionUrl:M(d(n(),q()))}),Vs=g({userId:n(),tier:n(),status:E(Object.values(Pe)),subscriptionId:M(n()),customerId:n(),subscriptionEnd:M(d(n(),Q())),cancelAtPeriodEnd:I(),updatedAt:d(n(),Q())}),js=g({tier:n(),subscriptionId:M(n()),customerId:n(),status:E(Object.values(Pe)),subscriptionEnd:M(d(n(),Q())),cancelAtPeriodEnd:I(),updatedAt:d(n(),Q()),isDefault:c(I())}),$s=g({id:n(),type:n(),data:g({object:de()}),created:d(n(),Q())}),Gs=ct({userId:c(n()),firebaseUid:c(n()),productType:c(n())}),Wi=g({type:oe("StripePayment"),name:d(n(),y(1,"Product name is required")),description:c(n()),price:n(),currency:c(d(n(),Ie(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:c(d(n(),y(1,"Stripe price ID is required"))),unitAmount:c(d(S(),J(),U(1))),productName:c(d(n(),y(1))),maxUnitAmount:c(d(S(),J(),U(1))),tier:d(n(),y(1,"Tier is required")),duration:d(n(),y(1,"Duration is required")),allowPromotionCodes:c(I()),metadata:c(R(n(),n()))}),Ki=g({type:oe("StripeSubscription"),name:d(n(),y(1,"Product name is required")),description:c(n()),price:n(),currency:c(d(n(),Ie(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:d(n(),y(1,"Stripe price ID is required")),tier:d(n(),y(1,"Tier is required")),duration:E(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:c(I()),metadata:c(R(n(),n()))}),zi=pt("type",[Wi,Ki]),Hs=R(n(),zi),Ws=R(n(),g({name:n(),price:n(),currency:n(),description:c(n()),features:c(b(n())),priceId:c(n()),unitAmount:c(S()),productName:c(n()),allowPromotionCodes:c(I())})),Ks=R(n(),g({type:E(["StripePayment","StripeSubscription"]),name:n(),price:S(),currency:n(),priceId:c(n()),unitAmount:c(d(S(),J(),U(1))),productName:c(d(n(),y(1))),maxUnitAmount:c(d(S(),J(),U(1))),tier:n(),duration:n(),description:c(n()),metadata:c(R(n(),n())),allowPromotionCodes:c(I())}))});var nr=u(()=>{"use strict"});var vt=u(()=>{"use strict";ht();rr();nr()});var ra,Yi,na,ir=u(()=>{"use strict";j();gt();vt();ra=g({id:n(),email:c(M(d(n(),Y()))),displayName:c(M(n())),photoURL:c(M(d(n(),q()))),emailVerified:c(I()),lastLoginAt:c(n()),providerData:c(b(g({providerId:n(),uid:n(),email:c(M(d(n(),Y()))),displayName:c(M(n())),photoURL:c(M(d(n(),q()))),phoneNumber:c(M(n()))}))),role:c(E(Object.values(se))),customClaims:c(R(n(),de()))}),Yi=g({userId:n(),tier:E(Object.values(Qt)),status:E(Object.values(Pe)),isActive:c(I()),features:c(b(n())),subscriptionId:M(n()),customerId:n(),subscriptionEnd:M(d(n(),Q())),cancelAtPeriodEnd:I(),updatedAt:d(n(),Q())}),na=g({role:c(E(Object.values(se))),subscription:c(Yi),features:c(b(E(Object.values(er)))),permissions:c(b(E(Object.values(tr)))),githubAccess:c(g({username:c(n()),teamAccess:c(b(n())),repoAccess:c(b(n()))}))})});var or=u(()=>{"use strict"});var sr=u(()=>{"use strict"});var ar=u(()=>{"use strict";gt();ir();or();sr()});var ur=u(()=>{"use strict"});var cr=u(()=>{"use strict"});var me,qe=u(()=>{"use strict";me={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var ya,lr=u(()=>{"use strict";qe();ya={EQ:me.EQ,NEQ:me.NEQ,LT:me.LT,LTE:me.LTE,GT:me.GT,GTE:me.GTE}});var pr=u(()=>{"use strict"});var dr=u(()=>{"use strict"});var fr=u(()=>{"use strict"});var Aa,Ra,wa,Ta,Ia,mr=u(()=>{"use strict";j();qe();Aa=g({collection:d(n(),y(1,"Collection name is required")),data:R(n(),V()),idempotencyKey:c(n())}),Ra=g({collection:d(n(),y(1,"Collection name is required")),id:d(n(),y(1,"Entity ID is required"))}),wa=g({collection:d(n(),y(1,"Collection name is required")),id:d(n(),y(1,"Entity ID is required")),data:R(n(),V()),merge:c(I(),!1)}),Ta=g({collection:d(n(),y(1,"Collection name is required")),id:d(n(),y(1,"Entity ID is required"))}),Ia=g({collection:d(n(),y(1,"Collection name is required")),limit:c(d(S(),U(1),re(1e3)),1e3),offset:c(d(S(),U(0)),0),orderBy:c(n()),orderDirection:c(E(["asc","desc"]),"desc"),where:c(b(g({field:n(),operator:E(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:V()})))})});var gr=u(()=>{"use strict"});var yr=u(()=>{"use strict";cr();lr();pr();qe();dr();fr();mr();gr()});var hr=u(()=>{"use strict"});var qa,Va,vr=u(()=>{"use strict";j();qa=g({templateId:d(n(),y(1)),to:d(n(),Y()),data:R(n(),V()),locale:c(d(n(),y(2),he(5)),"fr"),from:c(n()),replyTo:c(n())}),Va=g({success:I(),messageId:c(n()),error:c(n())})});var br=u(()=>{"use strict"});var Er=u(()=>{"use strict";hr();vr();br()});var Oe,Ve,bt,O,xr=u(()=>{"use strict";Oe={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},Ve={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},bt={[Oe.PERMISSION_DENIED]:{type:Ve.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Oe.NOT_FOUND]:{type:Ve.NOT_FOUND,message:"The requested resource was not found"},[Oe.ALREADY_EXISTS]:{type:Ve.ALREADY_EXISTS,message:"The resource already exists"},[Oe.INVALID_ARGUMENT]:{type:Ve.VALIDATION_ERROR,message:"Invalid argument provided"}},O=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=Oe.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}}});var Sr=u(()=>{"use strict";xr()});var kr=u(()=>{"use strict"});var Ar=u(()=>{"use strict"});var Rr=u(()=>{"use strict"});var wr=u(()=>{"use strict"});var Tr=u(()=>{"use strict"});var Ir=u(()=>{"use strict"});var Cr=u(()=>{"use strict";Ar();Rr();wr();Tr();Ir()});var Pr=u(()=>{"use strict"});var Or=u(()=>{"use strict";Pr()});var _r=u(()=>{"use strict"});var Dr=u(()=>{"use strict";_r()});var Fr=u(()=>{"use strict"});var Nr=u(()=>{"use strict";Fr()});var Ur=u(()=>{"use strict"});var Mr=u(()=>{"use strict";Ur()});var Lr=u(()=>{"use strict"});var Br=u(()=>{"use strict"});var qr=u(()=>{"use strict";Br()});var Vr=u(()=>{"use strict"});var jr=u(()=>{"use strict";Lr();qr();Vr()});var $r=u(()=>{"use strict"});var Gr=u(()=>{"use strict";$r()});var Hr,Et=u(()=>{"use strict";Hr=["pull","push","admin","maintain","triage"]});var Wr=u(()=>{"use strict"});var xt,Zi,Iu,Cu,Pu,Ou,_u,Du,Fu,Kr=u(()=>{"use strict";j();Et();xt=g({owner:d(n(),y(1,"Repository owner is required")),repo:d(n(),y(1,"Repository name is required"))}),Zi=E([...Hr]),Iu=g({userId:d(n(),y(1,"User ID is required")),githubUsername:d(n(),y(1,"GitHub username is required")),repoConfig:xt,permission:c(Zi,"push"),customClaims:c(R(n(),de()))}),Cu=g({userId:d(n(),y(1,"User ID is required")),githubUsername:d(n(),y(1,"GitHub username is required")),repoConfig:xt}),Pu=g({userId:d(n(),y(1,"User ID is required")),githubUsername:d(n(),y(1,"GitHub username is required")),repoConfig:xt}),Ou=g({provider:n(),purpose:E(["authentication","api-access"]),code:d(n(),y(1,"Authorization code is required")),redirectUri:d(n(),q("Valid redirect URI is required")),codeVerifier:c(n()),state:c(n()),instance:c(d(n(),q()))}),_u=g({provider:n(),refreshToken:d(n(),y(1,"Refresh token is required")),redirectUri:d(n(),q("Valid redirect URI is required"))}),Du=g({provider:n()}),Fu=g({userId:d(n(),y(1,"User ID is required"))})});var zr=u(()=>{"use strict";Et();Wr();Kr()});var Yr=u(()=>{"use strict"});var Xr,Ji,je,Qi,eo,to,ro,Vu,ju,Zr=u(()=>{"use strict";j();Xr=g({name:n(),color:n(),icon:n(),customParameters:c(R(n(),n())),button:g({backgroundColor:n(),textColor:n(),borderColor:n(),hoverBackgroundColor:n(),focusOutlineColor:n(),fontWeight:c(n(),"500"),textKey:c(n())})}),Ji=g({...Xr.entries,type:E(["auth","both"]),scopes:c(b(n())),firebaseProviderId:c(n())}),je=fe([oe(""),d(n(),q())]),Qi=g({authUrl:je,tokenUrl:je,profileUrl:je,revokeUrl:c(je)}),eo=g({authentication:c(b(n())),"api-access":b(n())}),to=c(g({pkce:c(I(),!1),codeChallengeMethod:c(E(["S256","plain"]),"S256")})),ro=g({...Xr.entries,type:E(["oauth","both"]),scopes:eo,endpoints:Qi,capabilities:to}),Vu=R(n(),Ji),ju=R(n(),ro)});var Jr=u(()=>{"use strict"});var Qr=u(()=>{"use strict";Yr();Zr();Jr()});var en=u(()=>{"use strict"});var tn=u(()=>{"use strict"});var rn=u(()=>{"use strict";en();tn()});var nn=u(()=>{"use strict"});var on=u(()=>{"use strict";nn()});var sn=u(()=>{"use strict"});var an=u(()=>{"use strict";sn()});var un,Qu,cn=u(()=>{"use strict";un={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Qu={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:un.ANALYTICS},marketing:{requiresConsent:un.MARKETING}}});var ln=u(()=>{"use strict"});var pn=u(()=>{"use strict";cn();ln()});var dn=u(()=>{"use strict"});var fn=u(()=>{"use strict"});var mn=u(()=>{"use strict";dn();fn()});var ne=u(()=>{"use strict";Jt();ar();vt();ur();yr();Er();Sr();kr();Cr();Or();Dr();Nr();Mr();jr();Gr();zr();Qr();rn();on();an();pn();mn()});var _e=u(()=>{"use strict";ne()});function gn(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}var St=u(()=>{"use strict";i(gn,"detectErrorSource")});function ie(e){return(t,r)=>{if(t instanceof O)return t;if(typeof t!="object"||t===null){let m=typeof t=="string"?t:e.defaultErrorMessage;return new O(r||m,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let s=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(s=e.errorCodeMapping[o]);let a;e.extractErrorMessage?a=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(a=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(a=e.friendlyMessageMapping[o]),a||(a=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new O(r||a,s,{details:l,source:e.errorSource})}}var $e,kt=u(()=>{"use strict";_e();i(ie,"createErrorHandler");$e={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"}});function Rt(e,t,r){return e instanceof O?e:(yn[t]||yn.unknown)(e,r)}var ve,no,At,ae,io,oo,yn,wt=u(()=>{"use strict";j();ne();_e();kt();ve={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},no={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},At={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},ae={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...$e},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...$e},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(no).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:$e,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ve.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ve["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ve.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},io=i(e=>e instanceof st?new O(ve["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):ie(ae.validation)(e),"handleValidationError"),oo=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in At){let t=e,r=At[t.type]||"unknown";return new O(t.message||ve[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&bt[e.code]){let t=e,r=bt[t.code];if(r){let o=At[r.type]||"unknown";return new O(r.message||ve[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return ie(ae.entity)(e)},"handleEntityError"),yn={auth:ie(ae.auth),oauth:ie(ae.oauth),api:ie(ae.api),firebase:ie(ae.firebase),ui:ie(ae.ui),validation:io,entity:oo,unknown:ie(ae.unknown)};i(Rt,"mapToDoNotDevError")});function hn(e,t,r={}){let o=globalThis.Sentry;o&&o.withScope(s=>{s.setTag("errorSource",t),s.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([a,l])=>{if(typeof l!="function"&&a!=="originalError")try{s.setExtra(a,l)}catch{s.setExtra(a,`[${typeof l}]`)}}),Object.entries(r).forEach(([a,l])=>{if(typeof l!="function")try{s.setExtra(`context.${a}`,l)}catch{s.setExtra(`context.${a}`,`[${typeof l}]`)}}),(e.details?.userId||r.userId)&&s.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),o.captureException(e)})}var Tt=u(()=>{"use strict";i(hn,"captureErrorToSentry")});function so(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function _(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:s={},log:a=!0,reportToSentry:l=!0,showNotification:m=!1,severity:p="error"}=r,h=gn(e),f=e instanceof O?e:Rt(e,h,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new O(o,f.code,{details:{...f.details,originalMessage:f.message},source:h,userMessageProvided:!0}):f=new O(f.message,f.code,{details:{...f.details,userMessage:o},source:h,userMessageProvided:!0})),a){let k=so()||typeof window<"u"&&window.__DNDEV_DEBUG,A={code:f.code,message:f.message,source:h};switch(p){case"warning":console.warn(`[DoNotDev] ${f.code}: ${f.message}`,k?{...A,details:f.details}:A);break;case"info":console.info(`[DoNotDev] ${f.code}: ${f.message}`,k?{...A,details:f.details}:A);break;case"success":console.log(`[DoNotDev] ${f.code}: ${f.message}`,k?{...A,details:f.details}:A);break;default:console.error(`[DoNotDev] ${f.code}: ${f.message}`,k?{...A,details:f.details,stack:f.stack}:A)}}return l&&hn(f,h,s),m&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),f}var vn=u(()=>{"use strict";_e();St();wt();Tt();i(so,"isDev");i(_,"handleError")});var Ge=u(()=>{"use strict";_e();vn();St();wt();Tt();kt()});var bn=u(()=>{"use strict";Ge()});var En=u(()=>{"use strict";Ge()});var xn=u(()=>{"use strict";bn();En()});var Sn=u(()=>{"use strict"});var kn=u(()=>{"use strict"});var An=u(()=>{"use strict"});var Rn=u(()=>{"use strict"});var wn=u(()=>{"use strict"});var Tn=u(()=>{"use strict"});var In=u(()=>{"use strict"});var Cn=u(()=>{"use strict"});var Pn=u(()=>{"use strict"});var Pl,It=u(()=>{"use strict";ne();Pl={[se.GUEST]:0,[se.USER]:1,[se.ADMIN]:2,[se.SUPER]:3}});var On=u(()=>{"use strict";ne()});function ao(){if(typeof globalThis<"u"){let e=globalThis;return e[Ct]||(e[Ct]=new Map),e[Ct]}return new Map}function _n(e,t){let r=ao();return r.has(e)||r.set(e,t()),r.get(e)}function Dn(e,...t){let r=null,o=!1;return i(function(){if(r!==null)return r;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{o=!1}},"getInstance")}var Ct,Pt=u(()=>{"use strict";Ct="__DNDEV_SINGLETONS__";i(ao,"getSingletonRegistry");i(_n,"getGlobalSingleton");i(Dn,"createSingleton")});function Fn(){return _n("providers",()=>({providers:null}))}function Nn(e){let{providers:t}=Fn();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let r=t[e];if(!r)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return r}function Un(e){return!!Fn().providers?.[e]}var Mn=u(()=>{"use strict";Pt();i(Fn,"getProviderState");i(Nn,"getProvider");i(Un,"hasProvider")});var Ln=u(()=>{"use strict"});var Ot=u(()=>{"use strict";It()});var Bn=u(()=>{"use strict";Ot()});var qn=u(()=>{"use strict"});var Vn=u(()=>{"use strict"});var jn=u(()=>{"use strict";Bn();qn();Ot();Vn()});var $n=u(()=>{"use strict"});var Gn=u(()=>{"use strict";$n()});var Hn=u(()=>{"use strict"});var Wn=u(()=>{"use strict"});var Kn=u(()=>{"use strict"});var zn=u(()=>{"use strict"});var Yn=u(()=>{"use strict";xn();Sn();kn();An();Rn();Ge();wn();Tn();In();Cn();Pn();It();On();Mn();Pt();Ln();jn();Gn();Hn();Wn();Kn();zn()});var Xn=u(()=>{"use strict"});var Zn=u(()=>{"use strict"});var Jn=u(()=>{"use strict"});var ue=u(()=>{Yn();Xn();Zn();Jn()});var Qn=u(()=>{"use strict"});var ei=u(()=>{"use strict"});function v(e,t){co.set(e,t)}function P(e,t){return t?e:z(e)}function To(){v("text",He),v("textarea",He),v("richtext",He),v("color",He),v("email",lo),v("password",po),v("url",fo),v("tel",So),v("iban",ko),v("number",be),v("currency",be),v("price",wo),v("range",be),v("year",be),v("rating",be),v("duration",be),v("boolean",ti),v("checkbox",ti),v("gdprConsent",Ro),v("date",Ee),v("datetime-local",Ee),v("time",Ee),v("week",Ee),v("month",Ee),v("timestamp",Ee),v("file",ri),v("files",ni),v("document",ri),v("documents",ni),v("image",mo),v("images",go),v("geopoint",yo),v("address",ho),v("map",vo),v("array",bo),v("select",_t),v("multiselect",Eo),v("radio",_t),v("combobox",_t),v("switch",Ao),v("reference",xo),v("hidden",Dt),v("avatar",Dt),v("badge",Dt),v("submit",ii),v("reset",ii)}var co,He,lo,po,fo,be,ti,Ee,oi,ri,ni,si,mo,go,yo,ho,vo,bo,_t,Eo,xo,Dt,So,ko,ii,Ao,Ro,wo,Ft=u(()=>{"use strict";j();co=new Map;i(v,"registerSchemaGenerator");i(P,"applyRequired");He=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(he(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(Be(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?d(n(),...t):n();return P(r,e.validation?.required)},"textSchema"),lo=i(e=>{let t=d(n(),Y("Invalid email address"));return P(t,e.validation?.required)},"emailSchema"),po=i(e=>{let t=e.validation?.minLength!==void 0?d(n(),y(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):n();return P(t,e.validation?.required)},"passwordSchema"),fo=i(e=>{let t=d(n(),q("Invalid URL"));return P(t,e.validation?.required)},"urlSchema"),be=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(U(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(re(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?d(S(),...t):S();return P(r,e.validation?.required)},"numberSchema"),ti=i(e=>{let t=I();return P(t,e.validation?.required)},"booleanSchema"),Ee=i(e=>{let t=d(n(),pe(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return P(t,e.validation?.required)},"dateSchema"),oi=g({url:n(),filename:n(),size:S(),mimeType:z(n()),uploadedAt:z(n())}),ri=i(e=>{let t=M(oi);return P(t,e.validation?.required)},"fileSchema"),ni=i(e=>{let t=b(oi);return P(t,e.validation?.required)},"filesSchema"),si=g({fullUrl:n(),thumbUrl:n()}),mo=i(e=>{let t=fe([n(),si]);return P(t,e.validation?.required)},"pictureSchema"),go=i(e=>{let t=b(fe([n(),si]));return P(t,e.validation?.required)},"picturesSchema"),yo=i(e=>{let t=g({lat:S(),lng:S()});return P(t,e.validation?.required)},"geopointSchema"),ho=i(e=>{let t=g({formatted_address:n(),latitude:S(),longitude:S(),street_number:z(n()),route:z(n()),locality:z(n()),administrative_area_level_1:z(n()),administrative_area_level_2:z(n()),country:z(n()),postal_code:z(n())});return P(t,e.validation?.required)},"addressSchema"),vo=i(e=>{let t=R(n(),V());return P(t,e.validation?.required)},"mapSchema"),bo=i(e=>{let t=b(V());return P(t,e.validation?.required)},"arraySchema"),_t=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(a=>a.value),s=E(o);return P(s,e.validation?.required)}let r=fe([n(),S()]);return P(r,e.validation?.required)},"selectSchema"),Eo=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(a=>a.value),s=b(E(o));return P(s,e.validation?.required)}let r=b(n());return P(r,e.validation?.required)},"multiselectSchema"),xo=i(e=>{let t=d(n(),y(1,"Invalid ID format"));return P(t,e.validation?.required)},"referenceSchema"),Dt=i(e=>{let t=n();return P(t,e.validation?.required)},"stringSchema"),So=i(e=>{let t=n();return P(t,e.validation?.required)},"telSchema"),ko=i(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",s=[];if(t!==void 0&&s.push(y(t,`IBAN must be at least ${t} characters`)),r!==void 0&&s.push(he(r,`IBAN must not exceed ${r} characters`)),o){let l=typeof o=="string"?new RegExp(o):o;s.push(Be(l,"Invalid IBAN format"))}let a=s.length>0?d(n(),...s):n();return P(a,e.validation?.required)},"ibanSchema"),ii=i(()=>lt(),"neverSchema"),Ao=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],s=E(o);return P(s,e.validation?.required)}let r=I();return P(r,e.validation?.required)},"switchSchema"),Ro=i(e=>at(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),wo=i(e=>{let t=g({amount:S(),currency:c(n()),vatIncluded:c(I()),discountPercent:c(d(S(),U(0),re(100)))});return P(t,e.validation?.required)},"priceSchema");i(To,"registerBuiltinSchemas");To()});var Nt=u(()=>{"use strict";ue()});var Ut=u(()=>{"use strict";ue()});var ai=u(()=>{"use strict";Nt();Ut()});var ui=u(()=>{"use strict";ei();Ft();Nt();ai();Ut()});var ci=u(()=>{"use strict";ue()});var li,pi,Rd,di,We=u(()=>{"use strict";ne();li=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],pi=["id","createdAt","updatedAt","createdById","updatedById"],Rd=[...pi,"status"],di={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...li]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}}});var fi=u(()=>{"use strict";ne();ue();We()});var mi=u(()=>{"use strict";ne();ue();Ft();We()});var gi=u(()=>{"use strict"});var yi=u(()=>{"use strict"});var Po,Oo,_o,Gd,Hd,hi=u(()=>{"use strict";j();Po=R(n(),V()),Oo=g({id:n(),patch:R(n(),V())}),_o=n(),Gd=g({inserts:c(b(Po)),updates:c(b(Oo)),deletes:c(b(_o))}),Hd=g({insertedIds:b(n()),updatedIds:b(n()),deletedIds:b(n())})});var vi=u(()=>{"use strict";hi()});var Xd,Do,Fo,Zd,Jd,bi=u(()=>{"use strict";j();Xd=d(n(),pe(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),Do=E(["ephemeral","session","persistent"]),Fo=g({title:c(n()),pinnable:c(I()),preferredHeight:c(d(S(),U(0)))}),Zd=g({id:d(n(),y(1)),kind:d(n(),y(1)),lifetime:c(Do,"ephemeral"),metadata:c(Fo),payload:V()}),Jd=g({widgetId:d(n(),y(1)),action:d(n(),y(1)),payload:V()})});var Ei=u(()=>{"use strict";ui();ci();We();fi();mi();gi();yi();vi();bi()});var xi=u(()=>{"use strict";Qn();Ei()});var G=u(()=>{ue();ne();xi();ue()});import{initializeApp as ki,getApps as Go,cert as Ho}from"firebase-admin/app";import{getAuth as Wo}from"firebase-admin/auth";import{getFirestore as Ko}from"firebase-admin/firestore";import{getFunctions as zo}from"firebase-admin/functions";function Yo(){let e=Go(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=ki({credential:Ho({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
`)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=ki():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:Wo(t),firestore:Ko(t),functions:zo(t)}}async function De(){let e=Lt();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function H(){let e=Lt();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function ge(){let e=Lt();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}var Lt,Ye=u(()=>{"use strict";G();i(Yo,"initializeFirebaseAdminServices");Lt=Dn(Yo);i(De,"getFirebaseAdminApp");i(H,"getFirebaseAdminAuth");i(ge,"getFirebaseAdminFirestore")});var Ai=u(()=>{"use strict";G();Ye()});var Xe,$f,xe,Gf,Fe=u(()=>{"use strict";G();Ye();Xe={async getServerAdmin(){try{return De()}catch(e){throw _(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return ge()}catch(e){throw _(e,"Error getting Admin Firestore")}},async generateServerId(){return(await Xe.getServerFirestore()).collection("_").doc().id}},$f=Xe.getServerAdmin,xe=Xe.getServerFirestore,Gf=Xe.generateServerId});function Xo(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw _(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw _(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw _(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw _(t,"Failed to convert to ISO string")}}function Zo(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function Se(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,o=r.data();return{id:r.id,...Se(o)}}if(Array.isArray(e))return e.map(r=>Se(r));if(Zo(e))return Xo(e);if(typeof e=="object"&&e!==null){let r={};for(let[o,s]of Object.entries(e))r[o]=Se(s);return r}return e}function Ne(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>Ne(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[o,s]of Object.entries(e))t.includes(o)||s!==void 0&&(r[o]=Ne(s,t));return r}return e}var Ze=u(()=>{"use strict";G();i(Xo,"firestoreToISOString");i(Zo,"isTimestamp");i(Se,"transformFirestoreData");i(Ne,"prepareForFirestore")});var ke,ee,Ae,Jf,Qf,em,tm,rm,nm,Ri=u(()=>{"use strict";j();G();Fe();Ze();ke=typeof window<"u",ee={async batchWrite(e,t,r,o,s={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:a="id",generateIds:l=!0,maxBatchSize:m=450,removeFields:p=[],validate:h=!!o}=s,f={successes:0,failures:0,failedItems:[]};try{let k=[],A=await xe(),C=A.batch(),D=0;for(let w=0;w<t.length;w++){let F=t[w];if(!F){f.failures++,f.failedItems?.push({index:w,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!F[a])throw _(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});let B=A.collection(e).doc(F[a]);C.delete(B)}else{if(h&&o)try{dt(o,F)}catch(tt){throw _(tt,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:F[a]}})}let B=F[a];if(!B&&r==="create"&&l)B=A.collection(e).doc().id,F={...F,[a]:B};else if(!B)throw _(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});let x=[a,...p],W=Ne(F,x),Te=A.collection(e).doc(B);r==="create"?C.create(Te,W):r==="update"&&C.update(Te,W)}D++,D>=m&&(k.push({batch:C,size:D}),C=A.batch(),D=0)}catch(B){f.failures++,f.failedItems?.push({index:w,error:B instanceof Error?B:new Error(String(B))})}}D>0&&k.push({batch:C,size:D});let L=0;for(let{batch:w,size:F}of k){try{await w.commit(),f.successes+=F}catch(B){let x=B instanceof Error?B:new Error(String(B));for(let W=L;W<L+F;W++)f.failures++,f.failedItems?.push({index:W,error:x})}L+=F}return f}catch(k){throw _(k,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:f.successes+f.failures,successCount:f.successes,failureCount:f.failures}})}},async batchCreate(e,t,r,o={}){return ee.batchWrite(e,t,"create",r,o)},async batchUpdate(e,t,r,o={}){return ee.batchWrite(e,t,"update",r,o)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let o=r.idField||"id",s=t.map(a=>({[o]:a}));return ee.batchWrite(e,s,"delete",void 0,r)}return ee.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await xe()).runTransaction(e)}catch(t){throw _(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:o=30,transform:s=!0}=r;try{let a=[];for(let p=0;p<t.length;p+=o)a.push(t.slice(p,p+o));let l=a.map(async p=>{let k=await(await xe()).collection(e).where("__name__","in",p).get(),A=new Map;return k.forEach(C=>{A.set(C.id,C.data())}),p.map(C=>{let D=A.get(C);return D?s?Se({id:C,...D}):{id:C,...D}:null})});return(await Promise.all(l)).flat()}catch(a){throw _(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},Ae=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),Jf=ke?Ae("batchWrite"):ee.batchWrite,Qf=ke?Ae("batchCreate"):ee.batchCreate,em=ke?Ae("batchUpdate"):ee.batchUpdate,tm=ke?Ae("batchDelete"):ee.batchDelete,rm=ke?Ae("runTransaction"):ee.runTransaction,nm=ke?Ae("bulkGet"):ee.bulkGet});var wi=u(()=>{"use strict";G()});var Ti=u(()=>{"use strict";G();Fe();Ze();wi()});var Je=u(()=>{"use strict";G();Fe()});var Ii=u(()=>{"use strict";G();Je();Je()});import{FieldValue as Vm,Query as jm,Timestamp as $m}from"firebase-admin/firestore";var te=u(()=>{"use strict";Ai();Ye();Fe();Ri();Ti();Ii();Je();Ze()});G();j();G();import{streamText as No,generateText as Uo,tool as Mo,jsonSchema as Lo}from"ai";G();function Si(e,t,r=$t){let o=Gt[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let s=e.promptTokens/1e6*o.promptPer1M,a=e.completionTokens/1e6*o.completionPer1M,l=s+a;return{providerCost:l,billedCost:l*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:s,completionCost:a}}}i(Si,"calculateCost");async function Bo(e,t){let o={anthropic:i(async()=>{let{createAnthropic:l}=await import("@ai-sdk/anthropic");return m=>l({apiKey:m})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:l}=await import("@ai-sdk/openai");return m=>l({apiKey:m})(t)},"openai"),google:i(async()=>{let{createGoogleGenerativeAI:l}=await import("@ai-sdk/google");return m=>l({apiKey:m})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let s=$o(e);return(await o())(s)}i(Bo,"resolveModel");var qo={maxRequests:30,windowMs:6e4},ce=null;async function Vo(){if(ce)return ce;let e=ze("UPSTASH_REDIS_REST_URL"),t=ze("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),ce={check:i(async()=>{},"check")},ce;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),s=new o({url:e,token:t}),a=new Map;return ce={check:i(async(l,m)=>{let p=`${m.maxRequests}:${m.windowMs}`,h=a.get(p);if(h||(h=new r({redis:s,limiter:r.slidingWindow(m.maxRequests,`${m.windowMs}ms`),prefix:"ai_rl"}),a.set(p,h)),!(await h.limit(l)).success)throw new Error(`Rate limit exceeded. Maximum ${m.maxRequests} requests per ${m.windowMs/1e3}s.`)},"check")},ce}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),ce={check:i(async()=>{},"check")},ce}}i(Vo,"getRateLimiter");function jo(e,t){let r={...t,...e};if(Object.keys(r).length===0)return;let o={};for(let[s,a]of Object.entries(r))o[s]=Mo({description:a.description,parameters:Lo(a.parameters)});return o}i(jo,"resolveTools");async function Mt(e,t,r){let o=Yt(e);if(!o.success)return Ke(`Invalid AI request: ${o.issues?.map(x=>x.message).join(", ")}`,400);let s=e.provider||t.provider||"anthropic",a=jt[s],l=e.model||t.model||a?.default||"claude-sonnet-4-20250514";if(a){let x=a.models;if(!x.includes(l))return Ke(`Model '${l}' is not allowed for provider '${s}'. Allowed: ${x.join(", ")}`,400)}try{await(await Vo()).check(r.userId,t.rateLimitConfig||qo)}catch(x){return Ke(x instanceof Error?x.message:"Rate limit exceeded",429)}let m;try{m=await Bo(s,l)}catch(x){return Ke(`Failed to initialize provider: ${x instanceof Error?x.message:String(x)}`,500)}let p=e.messages.filter(x=>x.role==="system").map(x=>x.content),h=e.systemPrompt||t.systemPrompt||(p.length>0?p.join(`
`):void 0),f=e.messages.filter(x=>x.role!=="system").map(x=>({role:x.role,content:x.content})),k=e.maxTokens||t.maxTokens||4096,A=e.temperature??t.temperature??.7,C=r.requestId||crypto.randomUUID(),D=jo(e.tools,t.tools),L=i(async x=>{if(!r.onCostRecord)return;let W=t.cost?.markup??4,Te=Si(x,l,W),tt={userId:r.userId,model:l,provider:s,usage:x,providerCost:Te.providerCost,billedCost:Te.billedCost,markup:W,timestamp:new Date().toISOString(),requestId:C};r.onCostRecord(tt).catch(Di=>{console.error("[AI] Failed to record cost:",Di)})},"recordCost");if(e.stream!==!1)return No({model:m,messages:f,system:h,maxTokens:k,temperature:A,tools:D,onFinish:i(async({usage:W})=>{await L({promptTokens:W.promptTokens,completionTokens:W.completionTokens,totalTokens:W.promptTokens+W.completionTokens})},"onFinish")}).toDataStreamResponse();let w=await Uo({model:m,messages:f,system:h,maxTokens:k,temperature:A,tools:D}),F={promptTokens:w.usage.promptTokens,completionTokens:w.usage.completionTokens,totalTokens:w.usage.promptTokens+w.usage.completionTokens};await L(F);let B=w.toolCalls?.map(x=>({id:x.toolCallId,name:x.toolName,args:x.args}))??[];return new Response(JSON.stringify({message:{role:"assistant",content:w.text},usage:F,finishReason:w.finishReason,toolCalls:B.length>0?B:void 0,model:l,provider:s}),{status:200,headers:{"Content-Type":"application/json"}})}i(Mt,"handleAIRequest");function Ke(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(Ke,"jsonError");function ze(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(ze,"getEnv");function $o(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let s=ze(r);if(s)return s}let o=ze("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}i($o,"getAIApiKey");G();te();function Qo(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}i(Qo,"extractBearerToken");async function Bt(e,t){try{return t==="supabase"?await es(e):t==="firebase"?{uid:(await H().verifyIdToken(e)).uid}:Un("serverAuth")?{uid:(await Nn("serverAuth").verifyToken(e)).uid}:{uid:(await H().verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}i(Bt,"verifyToken");async function es(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let s=t(r,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:a},error:l}=await s.auth.getUser(e);if(l||!a)throw new Error("Invalid or expired token");return{uid:a.id}}i(es,"verifySupabaseToken");async function Qe(e,t){let r=Qo(e.headers.authorization),{uid:o}=await Bt(r,t);return o}i(Qe,"verifyAuthToken");function ts(e){return async t=>{let r=t.headers.get("authorization");if(!r?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let o=r.slice(7),s;try{s=(await Bt(o)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),l=X(mt,a);if(!l.success){let m=l.issues.map(p=>p.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${m}`}),{status:400,headers:{"Content-Type":"application/json"}})}return Mt(l.output,e,{userId:s,requestId:crypto.randomUUID()})}}i(ts,"createAIChatRoute");G();function K(e){let t,r,o;if(e instanceof O)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let s=e;switch(s.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=s.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new O(r,t,o?{details:o}:void 0)}i(K,"handleError");te();var rs=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function ag(e){let t=new Set(e.allowedClaimKeys);for(let r of t)if(rs.has(r))throw new Error(`Claim key "${r}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return i(async function(o,s){if(o.method!=="POST")return s.status(405).json({error:"Method not allowed"});try{let a=await Qe(o),{customClaims:l}=o.body;if(!l||typeof l!="object")throw K(new Error("customClaims must be an object"));let m=Object.keys(l).filter(k=>!t.has(k));if(m.length>0)throw K(new Error(`Claim keys not allowed: ${m.join(", ")}`));let f={...(await H().getUser(a)).customClaims||{},...l};return await H().setCustomUserClaims(a,f),s.status(200).json({success:!0,customClaims:f})}catch(a){throw K(a)}},"handler")}i(ag,"createSetCustomClaimsHandler");import ns from"stripe";G();te();var et=null;function is(e){if(!e)throw new Error("Stripe API key is required");let t=process.env.STRIPE_API_VERSION||"2024-12-18.acacia";return et=new ns(e,{apiVersion:t}),et}i(is,"initStripe");function os(){if(!et){let e=process.env.STRIPE_SECRET_KEY;if(e)is(e);else throw new Error("Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.")}return et}i(os,"getStripe");var ye=new Proxy({},{get(e,t){return os()[t]}});function Re(){if(!process.env.STRIPE_SECRET_KEY)throw new Error("Missing STRIPE_SECRET_KEY environment variable")}i(Re,"validateStripeEnvironment");j();te();import{logger as Ci}from"firebase-functions/v2";async function qt(e){try{await ge().collection("payment_metrics").doc().set({...e,recordedAt:new Date().toISOString()}),Ci.info("Payment metrics recorded",{operation:e.operation,status:e.status,userId:e.userId})}catch(t){Ci.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:e})}}i(qt,"recordPaymentMetrics");te();import{logger as Pi}from"firebase-functions/v2";async function Oi(e,t){let r=ge(),o=r.collection("rateLimits").doc(e);try{let s=Date.now(),a={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(s+t.windowMs),blockRemainingSeconds:null};return await r.runTransaction(async l=>{let m=await l.get(o);if(!m.exists){l.set(o,{attempts:1,windowStart:s,blockUntil:null,lastUpdated:s}),a={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(s+t.windowMs),blockRemainingSeconds:null};return}let p=m.data();if(p.blockUntil&&s<p.blockUntil){a={allowed:!1,remaining:0,resetAt:new Date(p.blockUntil),blockRemainingSeconds:Math.ceil((p.blockUntil-s)/1e3)};return}if(s>=p.windowStart+t.windowMs){l.set(o,{attempts:1,windowStart:s,blockUntil:null,lastUpdated:s}),a={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(s+t.windowMs),blockRemainingSeconds:null};return}if(p.attempts>=t.maxAttempts){let h=s+t.blockDurationMs;l.update(o,{blockUntil:h,lastUpdated:s}),Pi.warn("Rate limit exceeded (Firestore)",{key:e,attempts:p.attempts,blockUntil:new Date(h)}),a={allowed:!1,remaining:0,resetAt:new Date(h),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)};return}l.update(o,{attempts:p.attempts+1,lastUpdated:s}),a={allowed:!0,remaining:t.maxAttempts-(p.attempts+1),resetAt:new Date(p.windowStart+t.windowMs),blockRemainingSeconds:null}}),a}catch(s){return Pi.error("Rate limit check failed",{key:e,error:s instanceof Error?s.message:String(s)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}i(Oi,"checkRateLimitWithFirestore");var Vt={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};function we(e,t,r,o,s,a){return async(l,m)=>{try{if(l.method!==e)return m.status(405).json({error:"Method not allowed"});let p=X(t,l.body);if(!p.success)return m.status(400).json({error:`Validation failed: ${p.issues.map(L=>L.message).join(", ")}`});let h=p.output,f=await Qe(l,a),k=`${r}_${f}`,A=Vt[r]||Vt.api,C=await Oi(k,A);if(!C.allowed)return s?.audit({type:"rate_limit.exceeded",userId:f,metadata:{operation:r,remaining:0}}),m.status(429).json({error:`Rate limit exceeded. Try again in ${C.blockRemainingSeconds} seconds.`,retryAfter:C.blockRemainingSeconds});let D=await o(l,m,h,{uid:f});return D==null&&console.warn(`[${r}] businessLogic returned ${D} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await qt({operation:r,userId:f,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:l.headers["x-request-id"]||"unknown"}}),D}catch(p){process.env.ENABLE_METRICS==="true"&&await qt({operation:r,userId:l.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:p instanceof Error?p.message:"Unknown error",requestId:l.headers["x-request-id"]||"unknown"}});try{K(p)}catch(h){let f=ss(h);return m.status(f.status).json({error:f.message})}return m.status(500).json({error:"Internal server error"})}}}i(we,"createVercelBaseFunction");function ss(e){return e instanceof O?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[e.code]??500,message:e.message}:{status:500,message:"Internal server error"}}i(ss,"classifiedToHttp");async function Ue(e,t,r){let s=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let a={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},l={...s,subscription:a};await r.setCustomUserClaims(e,l)}i(Ue,"updateUserSubscription");j();te();G();async function _i(e,t){Re();let s=((await t.getUser(e)).customClaims||{}).subscription,a=s?.subscriptionId;if(!a)throw K(new Error("No active subscription found"));let l=await ye.subscriptions.update(a,{cancel_at_period_end:!0}),p=["active","canceled","past_due","trialing","incomplete"].includes(l.status)?l.status:"incomplete";return await Ue(e,{tier:s?.tier||"free",status:p,subscriptionEnd:new Date(l.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:!0,subscriptionId:l.id,customerId:l.customer},t),{success:!0,endsAt:new Date(l.current_period_end*1e3).toISOString()}}i(_i,"cancelUserSubscription");var as=g({userId:n()});async function us(e,t,r,o){let s=o.uid,l=await _i(s,{async getUser(m){return H().getUser(m)},async setCustomUserClaims(m,p){await H().setCustomUserClaims(m,p)}});return t.status(200).json({success:l.success,cancelAtPeriodEnd:!0,endsAt:l.endsAt})}i(us,"cancelSubscriptionLogic");var cs=i(()=>we("POST",as,"cancel_subscription",us),"cancelSubscription"),ls=cs;j();te();var ps=g({userId:n(),newPriceId:n(),billingConfigKey:n()});async function ds(e,t,r,o,s){Re();let a=o.uid,{newPriceId:l,billingConfigKey:m}=r,p=s[m];if(!p||p.type!=="StripeSubscription")throw K(new Error("Invalid plan"));if(p.priceId!==l)throw K(new Error("Price ID mismatch"));let f=(await H().getUser(a)).customClaims?.subscription?.subscriptionId;if(!f)throw K(new Error("No active subscription"));let k=await ye.subscriptions.retrieve(f),A=await ye.subscriptions.update(f,{items:[{id:k.items.data[0]?.id,price:l}],proration_behavior:"create_prorations"}),D=["active","canceled","past_due","trialing","incomplete"].includes(A.status)?A.status:"incomplete";return await Ue(a,{tier:p.tier,status:D,subscriptionEnd:new Date(A.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:A.cancel_at_period_end,subscriptionId:A.id,customerId:A.customer},{async getUser(L){return H().getUser(L)},async setCustomUserClaims(L,w){await H().setCustomUserClaims(L,w)}}),t.status(200).json({success:!0,newTier:p.tier,newPrice:p.price})}i(ds,"changePlanLogic");var fs=i(e=>we("POST",ps,"change_plan",(t,r,o,s)=>ds(t,r,o,s,e)),"changePlan"),ms=fs;j();te();var gs=g({userId:n(),returnUrl:c(d(n(),q()))});async function ys(e,t,r,o){Re();let s=o.uid,{returnUrl:a}=r,m=(await H().getUser(s)).customClaims?.subscription?.customerId;if(!m)throw K(new Error("No customer found"));let p=await ye.billingPortal.sessions.create({customer:m,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}i(ys,"createCustomerPortalLogic");var hs=i(()=>we("POST",gs,"create_customer_portal",ys),"createCustomerPortal"),vs=hs;var Me=process.env.FIREBASE_REGION||"europe-west1",dy={region:Me,memory:"1GiB",timeoutSeconds:60},fy={region:Me,memory:"512MiB",timeoutSeconds:30},my={region:Me,memory:"256MiB",timeoutSeconds:20},gy={region:Me,memory:"256MiB",timeoutSeconds:15},yy={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},hy=i(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${Me}`)},"validateEnvironment");te();async function xy(){return await De()}i(xy,"initializeFirebaseAdmin");async function Sy(){return await De()}i(Sy,"getFirebaseAdmin");export{my as AUTH_CONFIG,yy as AVAILABLE_REGIONS,gy as CRUD_CONFIG,Me as FIREBASE_REGION,dy as FUNCTION_CONFIG,fy as STRIPE_CONFIG,ls as cancelSubscription,ms as changePlan,ts as createAIChatRoute,vs as createCustomerPortal,ag as createSetCustomClaimsHandler,Sy as getFirebaseAdmin,xy as initializeFirebaseAdmin,Ue as updateUserSubscription,hy as validateEnvironment};
//# sourceMappingURL=index.js.map
