@donotdev/core 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +25 -112
- package/index.js +5 -5
- package/next/index.js +28 -28
- package/package.json +2 -2
- package/server.d.ts +17 -100
- package/server.js +1 -1
- package/symbol-index.json +1 -1
- package/vite/index.js +34 -34
package/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Lt=Object.defineProperty;var Bt=(e,t)=>{for(var n in t)Lt(e,n,{get:t[n],enumerable:!0})};var Ct={};Bt(Ct,{AuthHardening:()=>pe,CURRENCY_MAP:()=>we,ConditionBuilder:()=>j,DEFAULT_CRUD_TIMEOUT:()=>Nr,DEFAULT_ERROR_MESSAGES:()=>L,DEFAULT_UPLOAD_TIMEOUT:()=>Dr,DoNotDevError:()=>T,LANGUAGE_COOKIE:()=>mr,SingletonManager:()=>Fe,addMonths:()=>J,addYears:()=>Le,calculateSubscriptionEndDate:()=>_r,captureErrorToSentry:()=>ke,clearGlobalSingleton:()=>or,commonErrorCodeMappings:()=>X,compactToISOString:()=>Oe,configureProviders:()=>ur,createAsyncSingleton:()=>sr,createErrorHandler:()=>D,createMetadata:()=>Nn,createMethodProxy:()=>lr,createSingleton:()=>ir,createSingletonWithParams:()=>ar,detectErrorSource:()=>Ie,ensureSpreadable:()=>An,evaluateCondition:()=>V,evaluateFieldConditions:()=>Ir,filterVisibleFields:()=>Sr,formatCurrency:()=>Fn,formatDate:()=>ht,formatRelativeTime:()=>$n,generateCodeChallenge:()=>bt,generateCodeVerifier:()=>yt,generateFirestoreRuleCondition:()=>Yn,generatePKCEPair:()=>Xn,generateUUID:()=>Or,getConditionDependencies:()=>kr,getCurrencyLocale:()=>vt,getCurrencySymbol:()=>Un,getCurrentTimestamp:()=>Ln,getGlobalSingleton:()=>_e,getListCardFieldNames:()=>Z,getProvider:()=>cr,getRoleFromClaims:()=>nr,getVisibleFields:()=>Me,getWeekFromISOString:()=>qn,handleError:()=>R,hasProvider:()=>dr,hasRestrictedVisibility:()=>xr,hasRoleAccess:()=>ue,hasTierAccess:()=>rr,isCompactDateString:()=>De,isFieldVisible:()=>Tt,isPKCESupported:()=>Qn,isoToCompactString:()=>_n,lazyImport:()=>tr,mapToDoNotDevError:()=>B,maybeTranslate:()=>zn,normalizeToISOString:()=>Mn,parseAcceptLanguage:()=>fr,parseDate:()=>Ne,parseDateToNoonUTC:()=>jn,parseISODate:()=>Mr,parseServerCookie:()=>qr,readCookieValue:()=>gr,resetProviders:()=>pr,resolveLanguage:()=>vr,safeValidate:()=>In,sanitizeHref:()=>wr,showNotification:()=>Sn,timestampToISOString:()=>Vn,toDateOnly:()=>Hn,toISOString:()=>Bn,translateArray:()=>Pn,translateArrayRange:()=>On,translateArrayWithIndices:()=>Dn,translateObjectArray:()=>wn,updateMetadata:()=>hr,validateCodeChallenge:()=>Jn,validateCodeVerifier:()=>Zn,validateEnvVar:()=>Vr,validateMetadata:()=>Br,validateUrl:()=>Lr,validateWithSchema:()=>Cn,when:()=>Ar,withErrorHandling:()=>En,withGracefulDegradation:()=>er,withTimeout:()=>Ur,wrapAuthError:()=>Rn,wrapCrudError:()=>xn,wrapStorageError:()=>Tn});var O={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},re={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Co={[O.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"]},[O.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[O.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Io={maxTokens:4096,temperature:.7,stream:!0},Ao={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},ko={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Po=4,wo={"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"}};import*as u from"valibot";var We=u.object({role:u.picklist([re.USER,re.ASSISTANT,re.SYSTEM]),content:u.pipe(u.string(),u.minLength(1)),id:u.optional(u.string()),createdAt:u.optional(u.string())}),he=u.lazy(()=>u.object({type:u.picklist(["string","number","boolean","array","object"]),description:u.optional(u.string()),enum:u.optional(u.array(u.string())),items:u.optional(he),properties:u.optional(u.record(u.string(),he)),required:u.optional(u.array(u.string()))})),Vt=u.object({description:u.pipe(u.string(),u.minLength(1)),parameters:u.object({type:u.literal("object"),properties:u.record(u.string(),he),required:u.optional(u.array(u.string()))})}),qt=u.object({id:u.string(),name:u.string(),args:u.record(u.string(),u.unknown())}),$t=u.object({messages:u.pipe(u.array(We),u.minLength(1)),provider:u.optional(u.picklist([O.ANTHROPIC,O.OPENAI,O.GOOGLE])),model:u.optional(u.string()),maxTokens:u.optional(u.pipe(u.number(),u.integer(),u.minValue(1))),temperature:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(2))),systemPrompt:u.optional(u.string()),stream:u.optional(u.boolean()),tools:u.optional(u.record(u.string(),Vt))}),Gt=u.object({promptTokens:u.number(),completionTokens:u.number(),totalTokens:u.number()}),jt=u.object({message:We,usage:u.optional(Gt),finishReason:u.optional(u.string()),toolCalls:u.optional(u.array(qt))}),No=u.object({provider:u.picklist([O.ANTHROPIC,O.OPENAI,O.GOOGLE]),model:u.optional(u.string()),maxTokens:u.optional(u.pipe(u.number(),u.integer(),u.minValue(1))),temperature:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(2))),systemPrompt:u.optional(u.string())});function Uo(e){return u.safeParse($t,e)}function Fo(e){return u.safeParse(jt,e)}var A={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function qo(e){Object.assign(A,e)}var ye={FREE:"free",PRO:"pro",PREMIUM:"premium"};function $o(e){Object.assign(ye,e)}var be={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Go(e){Object.assign(be,e)}var Ee={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"};function jo(e){Object.assign(Ee,e)}import*as a from"valibot";var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Wo(e){Object.assign(G,e)}var oe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ko(e){Object.assign(oe,e)}var Yo={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function zo(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Ke={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Xo={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as r from"valibot";var Ye=100,Ht=r.object({productId:r.pipe(r.string(),r.minLength(1),r.maxLength(200)),quantity:r.pipe(r.number(),r.integer(),r.minValue(1),r.maxValue(1e4))}),Qe=r.pipe(r.object({billingConfigKey:r.optional(r.pipe(r.string(),r.minLength(1))),lineItems:r.optional(r.pipe(r.array(Ht),r.minLength(1,"At least one line item is required"),r.maxLength(Ye,`At most ${Ye} line items`))),successUrl:r.pipe(r.string(),r.url()),cancelUrl:r.pipe(r.string(),r.url()),customerEmail:r.optional(r.pipe(r.string(),r.email())),metadata:r.optional(r.record(r.string(),r.string())),allowPromotionCodes:r.optional(r.boolean()),userId:r.optional(r.string()),productId:r.optional(r.string()),priceId:r.optional(r.string()),unitAmount:r.optional(r.pipe(r.number(),r.integer(),r.minValue(1))),productName:r.optional(r.pipe(r.string(),r.minLength(1))),currency:r.optional(r.pipe(r.string(),r.length(3,"Currency must be 3-letter ISO code"))),userEmail:r.optional(r.pipe(r.string(),r.email())),mode:r.optional(r.picklist([oe.PAYMENT,oe.SUBSCRIPTION]))}),r.rawTransform(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,i=o.billingConfigKey||o.metadata?.billingConfigKey;return i?{...o,billingConfigKey:i,lineItems:o.lineItems??[{productId:i,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),Ze=r.object({sessionId:r.string(),sessionUrl:r.nullable(r.pipe(r.string(),r.url()))}),Je=r.object({userId:r.string(),tier:r.string(),status:r.picklist(Object.values(G)),subscriptionId:r.nullable(r.string()),customerId:r.string(),subscriptionEnd:r.nullable(r.pipe(r.string(),r.isoTimestamp())),cancelAtPeriodEnd:r.boolean(),updatedAt:r.pipe(r.string(),r.isoTimestamp())}),et=r.object({tier:r.string(),subscriptionId:r.nullable(r.string()),customerId:r.string(),status:r.picklist(Object.values(G)),subscriptionEnd:r.nullable(r.pipe(r.string(),r.isoTimestamp())),cancelAtPeriodEnd:r.boolean(),updatedAt:r.pipe(r.string(),r.isoTimestamp()),isDefault:r.optional(r.boolean())}),tt=r.object({id:r.string(),type:r.string(),data:r.object({object:r.any()}),created:r.pipe(r.string(),r.isoTimestamp())}),nt=r.looseObject({userId:r.optional(r.string()),firebaseUid:r.optional(r.string()),productType:r.optional(r.string())});function Jo(e){return r.safeParse(Qe,e)}function ei(e){return r.safeParse(Ze,e)}function ti(e){return r.safeParse(Je,e)}function ni(e){return r.safeParse(et,e)}function ri(e){return r.safeParse(tt,e)}function oi(e){return r.safeParse(nt,e)}var Wt=r.object({type:r.literal("StripePayment"),name:r.pipe(r.string(),r.minLength(1,"Product name is required")),description:r.optional(r.string()),price:r.string(),currency:r.optional(r.pipe(r.string(),r.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:r.optional(r.pipe(r.string(),r.minLength(1,"Stripe price ID is required"))),unitAmount:r.optional(r.pipe(r.number(),r.integer(),r.minValue(1))),productName:r.optional(r.pipe(r.string(),r.minLength(1))),maxUnitAmount:r.optional(r.pipe(r.number(),r.integer(),r.minValue(1))),tier:r.pipe(r.string(),r.minLength(1,"Tier is required")),duration:r.pipe(r.string(),r.minLength(1,"Duration is required")),allowPromotionCodes:r.optional(r.boolean()),metadata:r.optional(r.record(r.string(),r.string()))}),Kt=r.object({type:r.literal("StripeSubscription"),name:r.pipe(r.string(),r.minLength(1,"Product name is required")),description:r.optional(r.string()),price:r.string(),currency:r.optional(r.pipe(r.string(),r.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:r.pipe(r.string(),r.minLength(1,"Stripe price ID is required")),tier:r.pipe(r.string(),r.minLength(1,"Tier is required")),duration:r.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:r.optional(r.boolean()),metadata:r.optional(r.record(r.string(),r.string()))}),Yt=r.variant("type",[Wt,Kt]),ii=r.record(r.string(),Yt),zt=r.record(r.string(),r.object({name:r.string(),price:r.string(),currency:r.string(),description:r.optional(r.string()),features:r.optional(r.array(r.string())),priceId:r.optional(r.string()),unitAmount:r.optional(r.number()),productName:r.optional(r.string()),allowPromotionCodes:r.optional(r.boolean())})),ze={name:r.string(),price:r.number(),currency:r.string(),priceId:r.optional(r.string()),unitAmount:r.optional(r.pipe(r.number(),r.integer(),r.minValue(1))),productName:r.optional(r.pipe(r.string(),r.minLength(1))),maxUnitAmount:r.optional(r.pipe(r.number(),r.integer(),r.minValue(1))),tier:r.string(),duration:r.string(),description:r.optional(r.string()),metadata:r.optional(r.record(r.string(),r.string())),allowPromotionCodes:r.optional(r.boolean())},Xt=r.variant("mode",[r.object({mode:r.literal("manual"),taxRateIds:r.pipe(r.array(r.pipe(r.string(),r.minLength(1))),r.minLength(1))}),r.object({mode:r.literal("automatic")})]),Xe=5,Qt=r.object({allowedCountries:r.pipe(r.array(r.pipe(r.string(),r.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),r.minLength(1)),shippingRateIds:r.optional(r.pipe(r.array(r.pipe(r.string(),r.minLength(1))),r.maxLength(Xe,`shippingRateIds: at most ${Xe} (Stripe limit)`)))}),Zt=r.object({type:r.literal("StripeOrder"),name:r.string(),currency:r.pipe(r.string(),r.length(3)),description:r.optional(r.string()),metadata:r.optional(r.record(r.string(),r.string())),allowPromotionCodes:r.optional(r.boolean()),tax:Xt,taxIdCollection:r.picklist(["disabled","optional","required"]),billingAddressCollection:r.picklist(["auto","required"]),shipping:r.optional(Qt),customerCreation:r.picklist(["always","if_required"]),invoiceCreation:r.boolean(),paymentMethodConfiguration:r.optional(r.pipe(r.string(),r.minLength(1)))}),Jt=r.record(r.string(),r.variant("type",[r.object({type:r.literal("StripePayment"),...ze}),r.object({type:r.literal("StripeSubscription"),...ze}),Zt]));function ai(e){return r.parse(zt,e)}function si(e){return r.parse(Jt,e)}function li(){let e={createCheckoutSessionRequest:r.safeParse(Qe,{}),createCheckoutSessionResponse:r.safeParse(Ze,{}),subscriptionData:r.safeParse(Je,{}),subscriptionClaims:r.safeParse(et,{}),webhookEvent:r.safeParse(tt,{}),checkoutSessionMetadata:r.safeParse(nt,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var rt=a.object({id:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),emailVerified:a.optional(a.boolean()),lastLoginAt:a.optional(a.string()),providerData:a.optional(a.array(a.object({providerId:a.string(),uid:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),phoneNumber:a.optional(a.nullable(a.string()))}))),role:a.optional(a.picklist(Object.values(A))),customClaims:a.optional(a.record(a.string(),a.any()))}),Se=a.object({userId:a.string(),tier:a.picklist(Object.values(ye)),status:a.picklist(Object.values(G)),isActive:a.optional(a.boolean()),features:a.optional(a.array(a.string())),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),ot=a.object({role:a.optional(a.picklist(Object.values(A))),subscription:a.optional(Se),features:a.optional(a.array(a.picklist(Object.values(be)))),permissions:a.optional(a.array(a.picklist(Object.values(Ee)))),githubAccess:a.optional(a.object({username:a.optional(a.string()),teamAccess:a.optional(a.array(a.string())),repoAccess:a.optional(a.array(a.string()))}))});function vi(e){return a.safeParse(rt,e)}function hi(e){return a.safeParse(Se,e)}function yi(e){return a.safeParse(ot,e)}function bi(){let e={authUser:a.safeParse(rt,{}),userSubscription:a.safeParse(Se,{}),customClaims:a.safeParse(ot,{}),getUserAuthStatus:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1))}),{}),getCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.optional(a.array(a.string()))}),{}),setCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claims:a.record(a.string(),a.any()),merge:a.optional(a.boolean(),!1)}),{}),removeCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.pipe(a.array(a.string()),a.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Si={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},xi={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Ti(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var wi={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},Oi={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},Di={CLIENT:"client",SERVER:"server",BUILD:"build"},Ni={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ui={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Fi={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},_i={USER:"user",GLOBAL:"global",SESSION:"session"},Mi={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Li={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Bi={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var qi={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},ie={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},xe={create:"admin",read:"guest",update:"admin",delete:"admin"},M={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},$i={ASC:"asc",DESC:"desc"},Gi={LIST:"list",LIST_CARD:"listCard"},ji=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Ki={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Yi={EQ:M.EQ,NEQ:M.NEQ,LT:M.LT,LTE:M.LTE,GT:M.GT,GTE:M.GTE};var it=class extends Error{collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}},at=class extends Error{cycle;constructor(t){super(`[dndev] bulkAcross: circular dependency: ${t.join(" \u2192 ")}`),this.name="BulkAcrossCycleError",this.cycle=t}},st=class extends Error{adapterName;constructor(t){super(`BulkNotImplementedError: adapter "${t}" has not implemented bulk() yet`),this.name="BulkNotImplementedError",this.adapterName=t}};import*as p from"valibot";var ta=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),data:p.record(p.string(),p.unknown()),idempotencyKey:p.optional(p.string())}),na=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required"))}),ra=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required")),data:p.record(p.string(),p.unknown()),merge:p.optional(p.boolean(),!1)}),oa=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required"))}),ia=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),limit:p.optional(p.pipe(p.number(),p.minValue(1),p.maxValue(1e3)),1e3),offset:p.optional(p.pipe(p.number(),p.minValue(0)),0),orderBy:p.optional(p.string()),orderDirection:p.optional(p.picklist(["asc","desc"]),"desc"),where:p.optional(p.array(p.object({field:p.string(),operator:p.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:p.unknown()})))});var va={RESEND:"resend"},ha={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as E from"valibot";var en=E.object({templateId:E.pipe(E.string(),E.minLength(1)),to:E.pipe(E.string(),E.email()),data:E.record(E.string(),E.unknown()),locale:E.optional(E.pipe(E.string(),E.minLength(2),E.maxLength(5)),"fr"),from:E.optional(E.string()),replyTo:E.optional(E.string())}),tn=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function ba(e){return E.safeParse(en,e)}function Ea(e){return E.safeParse(tn,e)}var z={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"},Ia={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},ae={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Te={[z.PERMISSION_DENIED]:{type:ae.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[z.NOT_FOUND]:{type:ae.NOT_FOUND,message:"The requested resource was not found"},[z.ALREADY_EXISTS]:{type:ae.ALREADY_EXISTS,message:"The resource already exists"},[z.INVALID_ARGUMENT]:{type:ae.VALIDATION_ERROR,message:"Invalid argument provided"}},lt=class extends Error{type;originalError;constructor(t,n,o){super(n),this.name="EntityHookError",this.type=t,this.originalError=o}},Aa={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},T=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=z.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,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 Oa={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var Na={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var Fa={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Ma={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Ba={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Re={mobile:0,tablet:768,laptop:1024,desktop:1440},nn={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function rn(e){return e>=Re.desktop?"desktop":e>=Re.laptop?"laptop":e>=Re.tablet?"tablet":"mobile"}function Za(e,t){let n=nn[t];return e>=n.min&&e<=n.max}function Ja(e,t){let n=rn(e);return{current:n,width:e,height:t,isMobile:n==="mobile",isTablet:n==="tablet",isLaptop:n==="laptop",isDesktop:n==="desktop",isMobileOrTablet:n==="mobile"||n==="tablet",isLaptopOrDesktop:n==="laptop"||n==="desktop"}}var on="landing",an={FIXED:"fixed",SCROLL:"scroll"},sn={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var ut=["pull","push","admin","maintain","triage"];import"valibot";import*as d from"valibot";var Ce=d.object({owner:d.pipe(d.string(),d.minLength(1,"Repository owner is required")),repo:d.pipe(d.string(),d.minLength(1,"Repository name is required"))}),ln=d.picklist([...ut]),ps=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce,permission:d.optional(ln,"push"),customClaims:d.optional(d.record(d.string(),d.any()))}),ms=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce}),gs=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce}),fs=d.object({provider:d.string(),purpose:d.picklist(["authentication","api-access"]),code:d.pipe(d.string(),d.minLength(1,"Authorization code is required")),redirectUri:d.pipe(d.string(),d.url("Valid redirect URI is required")),codeVerifier:d.optional(d.string()),state:d.optional(d.string()),instance:d.optional(d.pipe(d.string(),d.url()))}),vs=d.object({provider:d.string(),refreshToken:d.pipe(d.string(),d.minLength(1,"Refresh token is required")),redirectUri:d.pipe(d.string(),d.url("Valid redirect URI is required"))}),hs=d.object({provider:d.string()}),ys=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required"))});var Rs={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as m from"valibot";var ct=m.object({name:m.string(),color:m.string(),icon:m.string(),customParameters:m.optional(m.record(m.string(),m.string())),button:m.object({backgroundColor:m.string(),textColor:m.string(),borderColor:m.string(),hoverBackgroundColor:m.string(),focusOutlineColor:m.string(),fontWeight:m.optional(m.string(),"500"),textKey:m.optional(m.string())})}),un=m.object({...ct.entries,type:m.picklist(["auth","both"]),scopes:m.optional(m.array(m.string())),firebaseProviderId:m.optional(m.string())}),se=m.union([m.literal(""),m.pipe(m.string(),m.url())]),cn=m.object({authUrl:se,tokenUrl:se,profileUrl:se,revokeUrl:m.optional(se)}),dn=m.object({authentication:m.optional(m.array(m.string())),"api-access":m.array(m.string())}),pn=m.optional(m.object({pkce:m.optional(m.boolean(),!1),codeChallengeMethod:m.optional(m.picklist(["S256","plain"]),"S256")})),mn=m.object({...ct.entries,type:m.picklist(["oauth","both"]),scopes:dn,endpoints:cn,capabilities:pn}),dt={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},pt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},gn=m.record(m.string(),un),fn=m.record(m.string(),mn);function Is(){return m.safeParse(gn,dt)}function As(){return m.safeParse(fn,pt)}function ks(e){return e in dt}function Ps(e){return e in pt}var mt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Bs={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Vs={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:mt.ANALYTICS},marketing:{requiresConsent:mt.MARKETING}};function Ie(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"}import*as ft from"valibot";function D(e){return(t,n)=>{if(t instanceof T)return t;if(typeof t!="object"||t===null){let g=typeof t=="string"?t:e.defaultErrorMessage;return new T(n||g,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 i=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(i=e.errorCodeMapping[o]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[o]),s||(s=e.defaultErrorMessage);let c;return e.processMetadata?c=e.processMetadata(t):(c={originalError:t},o&&(c.originalCode=o)),"originalError"in c||(c.originalError=t),new T(n||s,i,{details:c,source:e.errorSource})}}var X={"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"};var L={"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."},vn={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"},Ae={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},F={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",...X},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",...X},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(vn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode: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()},processMetadata: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}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:X,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:L.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:L["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:L.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},hn=e=>e instanceof ft.ValiError?new T(L["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):D(F.validation)(e),yn=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Ae){let t=e,n=Ae[t.type]||"unknown";return new T(t.message||L[n],n,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Te[e.code]){let t=e,n=Te[t.code];if(n){let o=Ae[n.type]||"unknown";return new T(n.message||L[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return D(F.entity)(e)},gt={auth:D(F.auth),oauth:D(F.oauth),api:D(F.api),firebase:D(F.firebase),ui:D(F.ui),validation:hn,entity:yn,unknown:D(F.unknown)};function B(e,t,n){return e instanceof T?e:(gt[t]||gt.unknown)(e,n)}function ke(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,c])=>{if(typeof c!="function"&&s!=="originalError")try{i.setExtra(s,c)}catch{i.setExtra(s,`[${typeof c}]`)}}),Object.entries(n).forEach(([s,c])=>{if(typeof c!="function")try{i.setExtra(`context.${s}`,c)}catch{i.setExtra(`context.${s}`,`[${typeof c}]`)}}),(e.details?.userId||n.userId)&&i.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}function bn(){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 R(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:i={},log:s=!0,reportToSentry:c=!0,showNotification:g=!1,severity:y="error"}=n,b=Ie(e),f=e instanceof T?e:B(e,b,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new T(o,f.code,{details:{...f.details,originalMessage:f.message},source:b,userMessageProvided:!0}):f=new T(f.message,f.code,{details:{...f.details,userMessage:o},source:b,userMessageProvided:!0})),s){let I=bn()||typeof window<"u"&&window.__DNDEV_DEBUG,U={code:f.code,message:f.message,source:b};switch(y){case"warning":break;case"info":break;case"success":break;default:}}return c&&ke(f,b,i),f}function En(e,t){return async(...n)=>{try{return await e(...n)}catch(o){throw R(o,t)}}}function Sn(e,t="info",n){let o=Date.now().toString();return o}function xn(e,t,n,o,i){if(e instanceof T)return e;let{code:s}=B(e,"api");return new T("Request failed.",s,{source:"api",details:{context:`${t}.${n}(${o}${i?`, ${i}`:""})`,originalMessage:Pe(e),originalError:e}})}function Tn(e,t,n,o){let i=`${t}.${n}(${o})`;return B(e,"api",`${i}: ${Pe(e)}`)}function Rn(e,t,n,o){let i=o?` ${JSON.stringify(o)}`:"",s=`${t}.${n}(${i})`,c=B(e,"auth",`${s}: ${Pe(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&c.code==="unknown"&&e.code!=="unknown"?new T(c.message,c.code,{details:{...c.details,originalCode:e.code},source:c.source}):c}function Pe(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as Q from"valibot";function Cn(e,t,n){try{return Q.parse(e,t)}catch(o){throw o instanceof Q.ValiError?new T(`Validation failed in ${n}: ${o.message}`,"validation-failed",{details:{issues:o.issues,input:t},source:"validation"}):new T(`Unexpected validation error in ${n}: ${kn(o)}`,"validation-failed",{originalError:o instanceof Error?o:new Error(String(o)),source:"validation"})}}function In(e,t){try{return Q.parse(e,t)}catch{return null}}function An(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function kn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function Pn(e,t,n,o={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:c}=o;return Array.from({length:n},(g,y)=>{let b=`${t}.${y}`;return e(b)}).filter((g,y)=>{let b=`${t}.${y}`;return!(g===b||s&&g.trim()===""||g.length<i||c&&!c(g,y))})}function wn(e,t,n,o){return Array.from({length:n},(i,s)=>{let c=`${t}.${s}.${String(o[0])}`;if(e(c)===c)return null;let y={};for(let b of o){let f=`${t}.${s}.${String(b)}`;y[b]=e(f)}return y}).filter(i=>i!==null)}function On(e,t,n,o,i={}){let{minLength:s=0,excludeEmpty:c=!0,customFilter:g}=i;return Array.from({length:o-n},(y,b)=>{let f=n+b,I=`${t}.${f}`;return e(I)}).filter((y,b)=>{let f=n+b,I=`${t}.${f}`;return!(y===I||c&&y.trim()===""||y.length<s||g&&!g(y,f))})}function Dn(e,t,n,o={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:c}=o;return Array.from({length:n},(g,y)=>{let b=`${t}.${y}`;return{item:e(b),originalIndex:y}}).filter(({item:g,originalIndex:y})=>{let b=`${t}.${y}`;return!(g===b||s&&g.trim()===""||g.length<i||c&&!c(g,y))})}function Nn(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var we={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function vt(e){return we[e]?.locale??"en-US"}function Un(e){return!e||typeof e!="string"?e??"":we[e]?.symbol??e}function Fn(e,t,n={}){if(e==null||isNaN(e))return"";let o=vt(t);return new Intl.NumberFormat(o,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...n}).format(e)}function Oe(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let n=t[1],o=t[2],i=t[3],s=t[4],c=t[5],g=new Date(parseInt(n,10),parseInt(o,10)-1,parseInt(i,10),parseInt(s,10),parseInt(c,10));if(isNaN(g.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return g.toISOString()}function _n(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${n}${o}${i}:${s}${c}`}function De(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function Mn(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(De(e))return Oe(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")return t.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof e}`)}function Ln(){return new Date().toISOString()}function Bn(e){return e.toISOString()}function Vn(e){return new Date(e).toISOString()}function qn(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=new Date(t.getFullYear(),0,1),o=Math.floor((t.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((o+n.getDay()+1)/7)}, ${t.getFullYear()}`}var w={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function $n(e,t="en",n={}){if(!e)return"";let{style:o="long",numeric:i="auto",fallbackThreshold:s=w.WEEK}=n,c;if(e instanceof Date)c=e;else if(typeof e=="string")c=new Date(e);else if(typeof e=="number")c=new Date(e);else if(typeof e=="object"&&"toDate"in e)c=e.toDate();else return"";if(isNaN(c.getTime()))return"";let g=new Date,y=c.getTime()-g.getTime(),b=Math.round(y/1e3),f=Math.abs(b);if(f>s)return ht(c.toISOString(),t);let I=new Intl.RelativeTimeFormat(t,{style:o,numeric:i});return f<w.MINUTE?I.format(b,"second"):f<w.HOUR?I.format(Math.round(b/w.MINUTE),"minute"):f<w.DAY?I.format(Math.round(b/w.HOUR),"hour"):f<w.WEEK?I.format(Math.round(b/w.DAY),"day"):f<w.MONTH?I.format(Math.round(b/w.WEEK),"week"):f<w.YEAR?I.format(Math.round(b/w.MONTH),"month"):I.format(Math.round(b/w.YEAR),"year")}function Gn(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function ht(e,t="en",n="long"){if(!e)return"";let o;if(e instanceof Date)o=e;else if(typeof e=="string")o=new Date(e);else if(typeof e=="number")o=new Date(e);else if(typeof e=="object"&&"toDate"in e)o=e.toDate();else return"";if(isNaN(o.getTime()))return"";let i=typeof n=="string"?Gn(n):n;return new Intl.DateTimeFormat(t,i).format(o)}function Ne(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(De(t))try{return Oe(t)}catch{return}let n=new Date(t);return isNaN(n.getTime())?void 0:n.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")try{let n=t.toDate();return isNaN(n.getTime())?void 0:n.toISOString()}catch{return}}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,n=t.seconds*1e3+(t.nanoseconds||0)/1e6,o=new Date(n);return isNaN(o.getTime())?void 0:o.toISOString()}}}function jn(e){let t=Ne(e);if(!t)return;let n=new Date(t);return n.setUTCHours(12,0,0,0),n.toISOString()}function Hn(e){let t=Ne(e);return t&&t.split("T")[0]||""}function Wn(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function Kn(e){let t=`resource.data.${e.field}`,n=Wn(e.value);return`${t} ${e.op} ${n}`}function Yn(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let n=e.publicCondition.map(Kn).join(" && ");t.push(`(${n})`)}for(let n of e.ownerFields)t.push(`request.auth.uid == resource.data.${n}`);return t.length===0?"false":t.join(" || ")}function zn(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function yt(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Et(e)}async function bt(e){let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return Et(new Uint8Array(o))}async function Xn(){let e=yt(),t=await bt(e);return{codeVerifier:e,codeChallenge:t}}function Et(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Qn(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Zn(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function Jn(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function er(e,t,n){try{return await e()}catch{return t(),!1}}var le=new Map;function tr(e,t){if(le.has(t))return le.get(t);let n=e().catch(o=>{throw le.delete(t),o});return le.set(t,n),n}var St={[A.GUEST]:0,[A.USER]:1,[A.ADMIN]:2,[A.SUPER]:3};function ue(e,t){if(!e)return!1;let n=St[e]??-1,o=St[t]??1/0;return n>=o}function nr(e){return e?e.role===A.SUPER||e.isSuper===!0?A.SUPER:e.role===A.ADMIN||e.isAdmin===!0?A.ADMIN:e.role===A.USER?A.USER:e.role||A.USER:A.USER}function rr(e,t,n){if(!e)return!1;let o=n??Ke,i=o[e]?.level??-1,s=o[t]?.level??1/0;return i>=s}var Ue="__DNDEV_SINGLETONS__";function xt(){if(typeof globalThis<"u"){let e=globalThis;return e[Ue]||(e[Ue]=new Map),e[Ue]}return new Map}function _e(e,t){let n=xt();return n.has(e)||n.set(e,t()),n.get(e)}function or(e){xt().delete(e)}function ir(e,...t){let n=null,o=!1;return function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}}}function ar(e){let t=null,n=!1;return function(...i){if(t!==null)return t;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?t=new e(...i):t=e(...i),t}finally{n=!1}}}function sr(e){let t=null,n=!1,o=null;return async function(){if(t!==null)return t;if(n&&o)return o;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return o=e(),t=await o,t}finally{n=!1,o=null}}}function lr(e,t){return new Proxy({},{get(n,o){if(t.includes(o)){let s=e(),c=s[o];return typeof c=="function"?c.bind(s):c}return e()[o]}})}var Fe=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,n,o={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(o.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",o.fallbackFactory){let i=o.fallbackFactory();return this.instances.set(t,i),this.initialized.add(t),i}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let i=await n();return this.instances.set(t,i),this.initialized.add(t),i}catch(i){if(typeof process<"u",o.cacheFailures&&this.initialized.add(t),o.fallbackFactory){let s=o.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw i}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function ce(){return _e("providers",()=>({providers:null}))}function ur(e){let t=ce();t.providers,t.providers=e}function cr(e){let{providers:t}=ce();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}function dr(e){return!!ce().providers?.[e]}function pr(){ce().providers=null}var mr="dndev-lang";function gr(e,t){if(!e)return null;for(let n of e.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)try{return decodeURIComponent(n.slice(o+1).trim())}catch{return null}}return null}function fr(e){return e?e.split(",").map((t,n)=>{let[o="",...i]=t.trim().split(";"),s=i.find(g=>g.trim().startsWith("q=")),c=s?Number(s.trim().slice(2)):1;return{tag:o.trim(),quality:Number.isFinite(c)?c:0,index:n}}).filter(t=>t.tag!==""&&t.tag!=="*"&&t.quality>0).sort((t,n)=>n.quality-t.quality||t.index-n.index).map(t=>t.tag):[]}function vr({supported:e,fallback:t,stored:n,preferred:o}){if(n&&e.includes(n))return n;for(let i of o??[]){if(e.includes(i))return i;let s=i.split("-")[0];if(s&&e.includes(s))return s}return t}function hr(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function yr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function br(e){if(yr(e))return e.visibility}function Tt(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?ue(t,"admin"):n==="owner"?!1:ue(t,n)}function Er(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}function Me(e,t,n){let o=e;if(!o||typeof o!="object"||!o.entries)return[];let i=o.entries,s=[],{documentData:c,uid:g,ownership:y}=n??{},b=y&&g!=null&&c&&Er(c,g,y);for(let[f,I]of Object.entries(i)){let U=br(I);if(U==="owner"){b&&s.push(f);continue}Tt(U,t)&&s.push(f)}return s}function Sr(e,t,n,o){if(!e)return{};let i=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,s=Me(t,n,i),c={};for(let g of s)Object.prototype.hasOwnProperty.call(e,g)&&(c[g]=e[g]);return c}function Z(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function de(e){if(!(!e||typeof e!="object")){if(e.entries&&typeof e.entries=="object")return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let n=de(t);if(n)return n}if(e.wrapped)return de(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let n=de(t);if(n)return n}}}function xr(e){let t=de(e);if(!t)return!1;for(let n of Object.values(t)){let o=n?.visibility;if(o!==void 0&&o!=="guest")return!0}return!1}var pe=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(t={}){this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let n=this.store.get(t);if(n?.lockedUntil){if(Date.now()<n.lockedUntil){let o=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${o} minute${o===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let n=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(n);let o=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return o.attempts+=1,o.lastAttempt=n,o.attempts>=this.maxAttempts&&(o.lockedUntil=n+this.lockoutMs),this.store.set(t,o),{attempts:o.attempts,locked:o.lockedUntil!==null&&Date.now()<o.lockedUntil,lockedUntil:o.lockedUntil}}_evictExpired(t){for(let[n,o]of this.store)o.lockedUntil!==null&&t>o.lockedUntil?this.store.delete(n):o.lockedUntil===null&&t-o.lastAttempt>this.lockoutMs&&this.store.delete(n)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function Tr(e,t){if(t.includes(".")){let n=t.split("."),o=e;for(let i of n){if(o==null||typeof o!="object")return;o=o[i]}return o}return e[t]}function Rr(e,t){let n=Tr(t,e.field);switch(e.operator){case"equals":return n===e.value;case"notEquals":return n!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(n);case"notIn":return Array.isArray(e.value)&&!e.value.includes(n);case"greaterThan":return typeof n=="number"&&typeof e.value=="number"&&n>e.value;case"lessThan":return typeof n=="number"&&typeof e.value=="number"&&n<e.value;case"greaterThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n>=e.value;case"lessThanOrEqual":return typeof n=="number"&&typeof e.value=="number"&&n<=e.value;case"exists":return n!=null&&n!==""&&n!==!1;case"notExists":return n==null||n===""||n===!1;case"contains":return typeof n=="string"&&typeof e.value=="string"||Array.isArray(n)?n.includes(e.value):!1;default:return!1}}function Cr(e){return e instanceof j||"expression"in e?e.expression:e}function V(e,t){let n=Cr(e);if(n.type==="condition")return Rr(n,t);let{logic:o,conditions:i}=n;return o==="and"?i.every(s=>V(s,t)):i.some(s=>V(s,t))}function Ir(e,t){return e?{visible:e.visible?V(e.visible,t):!0,disabled:e.disabled?V(e.disabled,t):!1,required:e.required?V(e.required,t):!1,readonly:e.readonly?V(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var j=class e{expression;constructor(t){this.expression=t}get type(){return this.expression.type}or(t){let n=t instanceof e?t.expression:t,o=this.expression;return o.type==="group"&&o.logic==="or"?new e({type:"group",logic:"or",conditions:[...o.conditions,n]}):new e({type:"group",logic:"or",conditions:[o,n]})}and(t){let n=t instanceof e?t.expression:t,o=this.expression;return o.type==="group"&&o.logic==="and"?new e({type:"group",logic:"and",conditions:[...o.conditions,n]}):new e({type:"group",logic:"and",conditions:[o,n]})}};function Ar(e){function t(n,o){return new j({type:"condition",field:e,operator:n,value:o})}return{equals:n=>t("equals",n),notEquals:n=>t("notEquals",n),in:n=>t("in",n),notIn:n=>t("notIn",n),greaterThan:n=>t("greaterThan",n),lessThan:n=>t("lessThan",n),greaterThanOrEqual:n=>t("greaterThanOrEqual",n),lessThanOrEqual:n=>t("lessThanOrEqual",n),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:n=>t("contains",n)}}function kr(e){let t=e instanceof j?e.expression:e,n=new Set;function o(i){if(i.type==="condition")n.add(i.field);else for(let s of i.conditions)o(s)}return o(t),n}var Pr=new Set(["http:","https:","mailto:","tel:","blob:"]);function wr(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(Pr.has(n.protocol))return t}catch{return t}return""}function Or(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Dr=3e4,Nr=15e3;function Ur(e,t,n){if(n?.aborted)return Promise.reject(Rt(n.reason));let o=t>0;return!o&&!n?e:new Promise((i,s)=>{let c=!1,g;function y(){c=!0,g!==void 0&&(clearTimeout(g),g=void 0),n&&n.removeEventListener("abort",b)}function b(){c||(y(),s(Rt(n?.reason)))}n&&n.addEventListener("abort",b,{once:!0}),o&&(g=setTimeout(()=>{c||(y(),s(Fr(t)))},t)),e.then(f=>{c||(y(),i(f))},f=>{c||(y(),s(f))})})}function Fr(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function Rt(e){if(e instanceof Error){let n=new Error(e.message);return n.name="AbortError",n}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}function J(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}function Le(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}function _r(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=J(t,1):e==="3months"?n=J(t,3):e==="6months"?n=J(t,6):e==="1year"?n=Le(t,1):e==="2years"?n=Le(t,2):n=J(t,1),n.toISOString()}function Mr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function Lr(e,t="URL"){try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol))throw new Error(`Invalid protocol: ${n.protocol}`);return e}catch(n){throw new Error(`Invalid ${t}: ${e}. ${n instanceof Error?n.message:"Invalid URL format"}`)}}function Br(e){let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof o}`);if(/<[^>]*>/.test(o))throw new Error(`Metadata value for key '${n}' must not contain HTML`);let i=o;if(i.length>1e3)throw new Error(`Metadata value for key '${n}' is too long (max 1000 characters)`);if(n.length>100)throw new Error(`Metadata key '${n}' is too long (max 100 characters)`);t[n]=i}return t}function Vr(e,t=!0){let n=process.env[e];if(t&&!n)throw new Error(`Required environment variable '${e}' is not set`);return n||""}function qr(e,t){if(!e)return null;let n=`${encodeURIComponent(t)}=`,o=e.split(";");for(let i=0;i<o.length;i++){let s=o[i];if(s){for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(n)===0)return decodeURIComponent(s.substring(n.length,s.length))}}return null}function oc(e,t){let n=e;return n.metadata=t,n}import*as l from"valibot";var ee=new Map;function h(e,t){ee.set(e,t)}function ac(e){return ee.has(e)}function sc(){return Array.from(ee.keys())}function lc(){ee.clear()}function x(e,t){return t?e:l.nullish(e)}var me=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(l.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(l.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(l.regex(new RegExp(e.validation.pattern),"Invalid format"));let n=t.length>0?l.pipe(l.string(),...t):l.string();return x(n,e.validation?.required)},$r=e=>{let t=l.pipe(l.string(),l.email("Invalid email address"));return x(t,e.validation?.required)},Gr=e=>{let t=e.validation?.minLength!==void 0?l.pipe(l.string(),l.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):l.string();return x(t,e.validation?.required)},jr=e=>{let t=l.pipe(l.string(),l.url("Invalid URL"));return x(t,e.validation?.required)},H=e=>{let t=[];e.validation?.min!==void 0&&t.push(l.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(l.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let n=t.length>0?l.pipe(l.number(),...t):l.number();return x(n,e.validation?.required)},It=e=>{let t=l.boolean();return x(t,e.validation?.required)},W=e=>{let t=l.pipe(l.string(),l.check(n=>!isNaN(new Date(n).getTime()),"Invalid date format"));return x(t,e.validation?.required)},wt=l.object({url:l.string(),filename:l.string(),size:l.number(),mimeType:l.nullish(l.string()),uploadedAt:l.nullish(l.string())}),At=e=>{let t=l.nullable(wt);return x(t,e.validation?.required)},kt=e=>{let t=l.array(wt);return x(t,e.validation?.required)},Ot=l.object({fullUrl:l.string(),thumbUrl:l.string()}),Hr=e=>{let t=l.union([l.string(),Ot]);return x(t,e.validation?.required)},Wr=e=>{let t=l.array(l.union([l.string(),Ot]));return x(t,e.validation?.required)},Kr=e=>{let t=l.object({lat:l.number(),lng:l.number()});return x(t,e.validation?.required)},Yr=e=>{let t=l.object({formatted_address:l.string(),latitude:l.number(),longitude:l.number(),street_number:l.nullish(l.string()),route:l.nullish(l.string()),locality:l.nullish(l.string()),administrative_area_level_1:l.nullish(l.string()),administrative_area_level_2:l.nullish(l.string()),country:l.nullish(l.string()),postal_code:l.nullish(l.string())});return x(t,e.validation?.required)},zr=e=>{let t=l.record(l.string(),l.unknown());return x(t,e.validation?.required)},Xr=e=>{let t=l.array(l.unknown());return x(t,e.validation?.required)},Be=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(s=>s.value),i=l.picklist(o);return x(i,e.validation?.required)}let n=l.union([l.string(),l.number()]);return x(n,e.validation?.required)},Qr=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(s=>s.value),i=l.array(l.picklist(o));return x(i,e.validation?.required)}let n=l.array(l.string());return x(n,e.validation?.required)},Zr=e=>{let t=l.pipe(l.string(),l.minLength(1,"Invalid ID format"));return x(t,e.validation?.required)},Ve=e=>{let t=l.string();return x(t,e.validation?.required)},Jr=e=>{let t=l.string();return x(t,e.validation?.required)},eo=e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(t!==void 0&&i.push(l.minLength(t,`IBAN must be at least ${t} characters`)),n!==void 0&&i.push(l.maxLength(n,`IBAN must not exceed ${n} characters`)),o){let c=typeof o=="string"?new RegExp(o):o;i.push(l.regex(c,"Invalid IBAN format"))}let s=i.length>0?l.pipe(l.string(),...i):l.string();return x(s,e.validation?.required)},Pt=()=>l.never(),to=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],i=l.picklist(o);return x(i,e.validation?.required)}let n=l.boolean();return x(n,e.validation?.required)},no=e=>l.custom(n=>e.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),ro=e=>{let t=l.object({amount:l.number(),currency:l.optional(l.string()),vatIncluded:l.optional(l.boolean()),discountPercent:l.optional(l.pipe(l.number(),l.minValue(0),l.maxValue(100)))});return x(t,e.validation?.required)};function oo(){h("text",me),h("textarea",me),h("richtext",me),h("color",me),h("email",$r),h("password",Gr),h("url",jr),h("tel",Jr),h("iban",eo),h("number",H),h("currency",H),h("price",ro),h("range",H),h("year",H),h("rating",H),h("duration",H),h("boolean",It),h("checkbox",It),h("gdprConsent",no),h("date",W),h("datetime-local",W),h("time",W),h("week",W),h("month",W),h("timestamp",W),h("file",At),h("files",kt),h("document",At),h("documents",kt),h("image",Hr),h("images",Wr),h("geopoint",Kr),h("address",Yr),h("map",zr),h("array",Xr),h("select",Be),h("multiselect",Qr),h("radio",Be),h("combobox",Be),h("switch",to),h("reference",Zr),h("hidden",Ve),h("avatar",Ve),h("badge",Ve),h("submit",Pt),h("reset",Pt)}oo();function te(e){if(e.validation?.schema){let o=e.validation.schema;return x(o,e.validation?.required)}let t=ee.get(e.type);if(t){let o=t(e);if(o!==null)return o}let n=l.unknown();return x(n,e.validation?.required)}var Dt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Nt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ge(e,t=""){if(Array.isArray(e))e.forEach((n,o)=>{let i=`${t}[${o}]`;if(typeof n=="string"&&Nt(n)){if(!Dt.test(n))throw R(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&ge(n,i)});else if(typeof e=="object"&&e!==null)for(let[n,o]of Object.entries(e)){let i=t?`${t}.${n}`:n;if(typeof o=="string"&&Nt(o)){if(!Dt.test(o))throw R(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`,context:{field:i,value:o},severity:"error"})}else typeof o=="object"&&o!==null&&ge(o,i)}}import*as Ft from"valibot";var qe={};function mc(e){qe.uniqueConstraintValidator=e}async function Ut(e,t,n){let{uniqueFields:o=[],collection:i}=e.metadata;o.length!==0&&qe.uniqueConstraintValidator&&await Promise.all(o.map(async({field:s,errorMessage:c})=>{let g=t[s];if(g==null)return;if(await qe.uniqueConstraintValidator.checkDuplicate(i,s,g,n))throw R(new Error(c||`${s} must be unique`),{userMessage:c||`${s} must be unique`,context:{field:s}})}))}async function hc(e,t,n,o){Ft.parse(e,t),ge(t),await Ut(e,t,o),e.metadata.customValidate&&await e.metadata.customValidate(t,n)}function io(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Ic(e){if(!io(e)){let t=e,n=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw R(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return e.metadata.collection}var $e=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],kc="available",Pc=["draft","deleted"],fe=["id","createdAt","updatedAt","createdById","updatedById"],ao=[...fe,"status"];function wc(e){return ao.includes(e)}function Oc(e){return fe.includes(e)}var C={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...$e]}},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 so=new Set(["__proto__","constructor","prototype"]);function lo(e){for(let t of Object.keys(e.fields))if(so.has(t))throw R(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function uo(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,n=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:ie.CREATE_ONLY,validation:{required:!0,reference:n}}}function co(e,t){if(!t||t.length===0)return e.map(i=>({value:i.value,label:i.label}));let n=e.map(i=>({value:i.value,label:i.label})),o=new Set(e.map(i=>i.value));for(let i of t)o.has(i.value)||n.push(i);return n}function po(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let n=0;n<e.uniqueKeys.length;n++){let o=e.uniqueKeys[n];if(!o)continue;if(!o.fields||o.fields.length===0)throw R(new Error(`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:n},severity:"error"});let i=o.fields.filter(s=>!t.has(s));if(i.length>0)throw R(new Error(`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:n,invalidFields:i},severity:"error"})}}function mo(e){let{form:t,fields:n}=e,o=Object.keys(n);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw R(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let i=t.steps.flatMap(y=>y.fields),s=i.filter(y=>!o.includes(y));if(s.length>0)throw R(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let c=new Set(i);o.filter(y=>!c.has(y)).length>0}t.rules&&t.rules.forEach((i,s)=>{let g=(Array.isArray(i.condition)?i.condition.map(f=>f.field):[i.condition.field]).filter(f=>!o.includes(f));if(g.length>0)throw R(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${g.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${g.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:g,operation:"validateFormConfig"},severity:"error"});let b=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(f=>!o.includes(f));if(b.length>0)throw R(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${b.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${b.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:b,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,s])=>{if(s.dependsOn&&!o.includes(s.dependsOn.field))throw R(new Error(`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:i,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function go(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function _c(e){try{lo(e),mo(e);let t=go(e),n={...e.fields,...C,...e.fields.createdAt&&{createdAt:{...C.createdAt,...e.fields.createdAt,type:C.createdAt.type,visibility:C.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...C.updatedAt,...e.fields.updatedAt,type:C.updatedAt.type,visibility:C.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...C.createdById,...e.fields.createdById,type:C.createdById.type,visibility:C.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...C.updatedById,...e.fields.updatedById,type:C.updatedById.type,visibility:C.updatedById.visibility}},...e.fields.status&&{status:{...C.status,...e.fields.status,validation:{...C.status.validation,...e.fields.status.validation,options:co($e,e.fields.status.validation?.options)}}},...e.scope&&{[e.scope.field]:uo(e.scope)}};if(e.listFields){let s=new Set(Object.keys(n)),c=e.listFields.filter(g=>!s.has(g));if(c.length>0)throw R(new Error(`Entity '${e.name}' defines listFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${c.join(", ")}`,context:{entityName:e.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(n)),g=Z(e).filter(y=>!s.has(y));if(g.length>0)throw R(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${g.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${g.join(", ")}`,context:{entityName:e.name,invalidFields:g,operation:"defineEntity"},severity:"error"})}if(e.uniqueKeys){let s=new Set(Object.keys(n));po(e,s)}let o={...xe,...e.access||{}},i=e.namespace||`entity-${e.name.toLowerCase()}`;return{...e,form:t,fields:n,access:o,namespace:i,...e.search&&{search:e.search},...e.defaultSort&&{defaultSort:e.defaultSort}}}catch(t){throw R(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}import*as N from"valibot";function Ge(e,t){return!!(t.visibility==="hidden"||t.editable===ie.GENERATED||fe.includes(e))}function ne(e,t){return Object.assign(e,{visibility:t})}function q(e,t){let n=e;return n.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},n}function fo(e){let t=te(e);return ne(t,e.visibility)}function je(e){let t=te({...e,validation:{...e.validation,required:!1}});return ne(t,e.visibility)}function $c(e){let t=e.fields,n={};for(let[k,P]of Object.entries(t))P.visibility!=="hidden"&&(n[k]=je(P));let o=q(N.object(n),e),i={};for(let[k,P]of Object.entries(t))Ge(k,P)||(i[k]=fo(P));let s=q(N.object(i),e),c={};for(let[k,P]of Object.entries(t))if(!Ge(k,P))if(k==="status"){let _=N.literal("draft");c[k]=ne(_,P.visibility)}else c[k]=je(P);let g=q(N.object(c),e),y={};for(let[k,P]of Object.entries(t))Ge(k,P)||(y[k]=je(P));y.id=ne(te(C.id),"technical");let b=q(N.object(y),e),f;if(e.listFields&&e.listFields.length>0){let k=["id","status"],P=[...new Set([...k,...e.listFields])];f={};for(let _ of P){let Y=n[_];Y&&(f[_]=Y)}}else f=n;let I=q(N.object(f),e),U,He=Z(e);if(He.length>0){let k=["id","status"],P=[...new Set([...k,...He])];U={};for(let _ of P){let Y=n[_];Y&&(U[_]=Y)}}else U=n;let _t=q(N.object(U),e),Mt=q(N.object({id:ne(te(C.id),"technical")}),e);return{create:s,draft:g,update:b,get:o,list:I,listCard:_t,delete:Mt}}function jc(e,t,n=1,o=!1){let i=[];if(o)for(let s=t;s>=e;s-=n)i.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=n)i.push({value:String(s),label:String(s)});return i}var $=new Map;function Wc(e,t){$.has(e),$.set(e,t)}function Kc(e){$.delete(e)}function Yc(e){let t=$.get(e);return t?t():null}function zc(e){return $.has(e)}function Xc(){return Array.from($.keys())}function Qc(){$.clear()}import*as S from"valibot";var vo=S.record(S.string(),S.unknown()),ho=S.object({id:S.string(),patch:S.record(S.string(),S.unknown())}),yo=S.string(),Jc=S.object({inserts:S.optional(S.array(vo)),updates:S.optional(S.array(ho)),deletes:S.optional(S.array(yo))}),ed=S.object({insertedIds:S.array(S.string()),updatedIds:S.array(S.string()),deletedIds:S.array(S.string())});function td(e){let t=new Set((e.updates??[]).map(c=>c.id)),n=e.deletes??[],o=[];for(let c of n)t.has(c)&&o.push(c);if(o.length>0)return{collisions:o,where:"updates-deletes"};let i=e.inserts??[],s=[];for(let c of i)typeof c.id=="string"&&t.has(c.id)&&s.push(c.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as v from"valibot";var id=v.pipe(v.string(),v.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),bo=v.picklist(["ephemeral","session","persistent"]),Eo=v.object({title:v.optional(v.string()),pinnable:v.optional(v.boolean()),preferredHeight:v.optional(v.pipe(v.number(),v.minValue(0)))}),So=v.object({id:v.pipe(v.string(),v.minLength(1)),kind:v.pipe(v.string(),v.minLength(1)),lifetime:v.optional(bo,"ephemeral"),metadata:v.optional(Eo),payload:v.unknown()}),xo=v.object({widgetId:v.pipe(v.string(),v.minLength(1)),action:v.pipe(v.string(),v.minLength(1)),payload:v.unknown()}),K=new Map;function ad(e){if(K.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);K.set(e.kind,e)}function sd(e){return K.get(e)}function ld(){return Array.from(K.values())}function ud(e,t){let n=v.safeParse(So,e);if(!n.success)return{ok:!1,reason:`Invalid canvas block envelope: ${ve(n.issues)}`};let o=K.get(n.output.kind);if(!o)return{ok:!1,reason:`Unknown widget kind: "${n.output.kind}"`};let i=v.safeParse(o.schema,n.output.payload);if(!i.success)return{ok:!1,reason:`Payload rejected by "${n.output.kind}" schema: ${ve(i.issues)}`};if(t?.caller!==void 0){let c=t.caller.access;if(!To(o.surface,c))return{ok:!1,reason:`surface_forbidden: widget "${n.output.kind}" surface=${o.surface} not reachable by caller access=${c===null?"null":c}`}}return{ok:!0,value:{...n.output,payload:i.output},widget:o}}function To(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function cd(e,t){let n=v.safeParse(xo,e);if(!n.success)return{ok:!1,reason:`Invalid canvas event envelope: ${ve(n.issues)}`};let o=K.get(t);if(!o)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let i=o.actions[n.output.action];if(!i)return{ok:!1,reason:`Widget "${t}" has no action "${n.output.action}"`};let s=v.safeParse(i,n.output.payload);return s.success?{ok:!0,value:{...n.output,payload:s.output},widget:o}:{ok:!1,reason:`Payload rejected by "${t}.${n.output.action}" schema: ${ve(s.issues)}`}}function ve(e){return e.map(t=>{let n=t.path?.map(o=>String(o.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}export{Yi as AGGREGATE_FILTER_OPERATORS,Ki as AGGREGATE_OPERATIONS,$t as AIChatRequestSchema,jt as AIChatResponseSchema,We as AIMessageSchema,No as AIProviderConfigSchema,qt as AIToolCallSchema,Vt as AIToolDefinitionSchema,Gt as AIUsageSchema,Ao as AI_ERROR_CODES,Co as AI_MODELS,O as AI_PROVIDERS,re as AI_ROLES,ko as AI_TIERS,wo as AI_TOKEN_PRICING,Oa as AUTH_EVENTS,dt as AUTH_PARTNERS,xi as AUTH_PARTNER_STATE,pe as AuthHardening,rt as AuthUserSchema,fe as BACKEND_GENERATED_FIELD_NAMES,Na as BILLING_EVENTS,nn as BREAKPOINT_RANGES,Re as BREAKPOINT_THRESHOLDS,at as BulkAcrossCycleError,it as BulkCollisionError,yo as BulkDeleteIdSchema,vo as BulkInsertSchema,st as BulkNotImplementedError,Jc as BulkRequestSchema,ed as BulkResponseSchema,ho as BulkUpdateSchema,Ke as COMMON_TIER_CONFIGS,Ni as CONFIDENCE_LEVELS,mt as CONSENT_CATEGORY,Di as CONTEXTS,M as CRUD_OPERATORS,we as CURRENCY_MAP,So as CanvasBlockSchema,xo as CanvasEventSchema,bo as CanvasLifetimeSchema,Eo as CanvasWidgetMetadataSchema,Ht as CheckoutLineItemInputSchema,nt as CheckoutSessionMetadataSchema,j as ConditionBuilder,Qe as CreateCheckoutSessionRequestSchema,Ze as CreateCheckoutSessionResponseSchema,ot as CustomClaimsSchema,Io as DEFAULT_AI_CONFIG,Po as DEFAULT_AI_MARKUP,Nr as DEFAULT_CRUD_TIMEOUT,xe as DEFAULT_ENTITY_ACCESS,L as DEFAULT_ERROR_MESSAGES,on as DEFAULT_LAYOUT_PRESET,$e as DEFAULT_STATUS_OPTIONS,kc as DEFAULT_STATUS_VALUE,Xo as DEFAULT_SUBSCRIPTION,Dr as DEFAULT_UPLOAD_TIMEOUT,Bs as DENSITY,T as DoNotDevError,ie as EDITABLE,ha as EMAIL_ERROR_CODES,va as EMAIL_PROVIDERS,Si as EMAIL_VERIFICATION_STATUS,ae as ENTITY_HOOK_ERRORS,Oi as ENVIRONMENTS,z as ERROR_CODES,Ia as ERROR_SEVERITY,Aa as ERROR_SOURCE,lt as EntityHookError,be as FEATURES,Vs as FEATURE_CONSENT_MATRIX,Ui as FEATURE_STATUS,ji as FIELD_TYPES,Te as FIREBASE_ERROR_MAP,an as FOOTER_MODE,ut as GITHUB_PERMISSION_LEVELS,Pc as HIDDEN_STATUSES,mr as LANGUAGE_COOKIE,sn as LAYOUT_PRESET,Gi as LIST_SCHEMA_TYPE,Ye as MAX_CHECKOUT_LINE_ITEMS,Xe as MAX_SHIPPING_RATE_IDS,Fa as OAUTH_EVENTS,pt as OAUTH_PARTNERS,$i as ORDER_DIRECTION,Rs as PARTNER_ICONS,Ma as PAYLOAD_EVENTS,Ee as PERMISSIONS,wi as PLATFORMS,Li as PWA_ASSET_TYPES,Mi as PWA_DISPLAY_MODES,Yt as ProductDeclarationSchema,ii as ProductDeclarationsSchema,id as ProxiedImageUrlSchema,Bi as ROUTE_SOURCES,_i as STORAGE_SCOPES,Fi as STORAGE_TYPES,Ba as STRIPE_EVENTS,oe as STRIPE_MODES,Yo as SUBSCRIPTION_DURATIONS,G as SUBSCRIPTION_STATUS,ye as SUBSCRIPTION_TIERS,en as SendEmailRequestSchema,tn as SendEmailResponseSchema,Ct as ServerUtils,Fe as SingletonManager,Jt as StripeBackConfigSchema,zt as StripeFrontConfigSchema,Zt as StripeOrderBackSchema,Qt as StripeOrderShippingSchema,Xt as StripeOrderTaxSchema,Wt as StripePaymentSchema,Kt as StripeSubscriptionSchema,et as SubscriptionClaimsSchema,Je as SubscriptionDataSchema,ao as TECHNICAL_FIELD_NAMES,A as USER_ROLES,Se as UserSubscriptionSchema,qi as VISIBILITY,tt as WebhookEventSchema,J as addMonths,Le as addYears,Yr as addressSchema,Xr as arraySchema,C as baseFields,It as booleanSchema,_r as calculateSubscriptionEndDate,ke as captureErrorToSentry,gs as checkGitHubAccessSchema,or as clearGlobalSingleton,lc as clearSchemaGenerators,Qc as clearScopeProviders,X as commonErrorCodeMappings,Oe as compactToISOString,ur as configureProviders,sr as createAsyncSingleton,zo as createDefaultSubscriptionClaims,Ti as createDefaultUserProfile,ta as createEntitySchema,D as createErrorHandler,Nn as createMetadata,lr as createMethodProxy,$c as createSchemas,ir as createSingleton,ar as createSingletonWithParams,W as dateSchema,_c as defineEntity,oa as deleteEntitySchema,td as detectBulkCollisions,Ie as detectErrorSource,hs as disconnectOAuthSchema,$r as emailSchema,oc as enhanceSchema,An as ensureSpreadable,V as evaluateCondition,Ir as evaluateFieldConditions,fs as exchangeTokenSchema,At as fileSchema,kt as filesSchema,Sr as filterVisibleFields,Fn as formatCurrency,ht as formatDate,$n as formatRelativeTime,no as gdprConsentSchema,bt as generateCodeChallenge,yt as generateCodeVerifier,Yn as generateFirestoreRuleCondition,Xn as generatePKCEPair,Or as generateUUID,Kr as geopointSchema,rn as getBreakpointFromWidth,Ja as getBreakpointUtils,Ic as getCollectionName,kr as getConditionDependencies,ys as getConnectionsSchema,vt as getCurrencyLocale,Un as getCurrencySymbol,Ln as getCurrentTimestamp,na as getEntitySchema,_e as getGlobalSingleton,Z as getListCardFieldNames,cr as getProvider,sc as getRegisteredSchemaTypes,Xc as getRegisteredScopeProviders,nr as getRoleFromClaims,te as getSchemaType,Yc as getScopeValue,Me as getVisibleFields,qn as getWeekFromISOString,sd as getWidget,ln as githubPermissionSchema,Ce as githubRepoConfigSchema,ps as grantGitHubAccessSchema,R as handleError,ac as hasCustomSchemaGenerator,io as hasMetadata,dr as hasProvider,xr as hasRestrictedVisibility,ue as hasRoleAccess,zc as hasScopeProvider,rr as hasTierAccess,eo as ibanSchema,ks as isAuthPartnerId,Oc as isBackendGeneratedField,Za as isBreakpoint,De as isCompactDateString,Tt as isFieldVisible,wc as isFrameworkField,Ps as isOAuthPartnerId,Qn as isPKCESupported,_n as isoToCompactString,tr as lazyImport,ia as listEntitiesSchema,ld as listWidgets,zr as mapSchema,B as mapToDoNotDevError,zn as maybeTranslate,Qr as multiselectSchema,Pt as neverSchema,Mn as normalizeToISOString,H as numberSchema,Go as overrideFeatures,Ko as overridePaymentModes,jo as overridePermissions,Wo as overrideSubscriptionStatus,$o as overrideSubscriptionTiers,qo as overrideUserRoles,fr as parseAcceptLanguage,Ne as parseDate,jn as parseDateToNoonUTC,Mr as parseISODate,qr as parseServerCookie,Gr as passwordSchema,Hr as pictureSchema,Wr as picturesSchema,ro as priceSchema,jc as rangeOptions,gr as readCookieValue,Zr as referenceSchema,vs as refreshTokenSchema,h as registerSchemaGenerator,Wc as registerScopeProvider,mc as registerUniqueConstraintValidator,ad as registerWidget,pr as resetProviders,vr as resolveLanguage,ms as revokeGitHubAccessSchema,In as safeValidate,wr as sanitizeHref,Be as selectSchema,Sn as showNotification,Ve as stringSchema,to as switchSchema,Jr as telSchema,me as textSchema,Vn as timestampToISOString,Hn as toDateOnly,Bn as toISOString,Pn as translateArray,On as translateArrayRange,Dn as translateArrayWithIndices,wn as translateObjectArray,Kc as unregisterScopeProvider,ra as updateEntitySchema,hr as updateMetadata,jr as urlSchema,Uo as validateAIChatRequest,Fo as validateAIChatResponse,Is as validateAuthPartners,bi as validateAuthSchemas,vi as validateAuthUser,li as validateBillingSchemas,ud as validateBlock,oi as validateCheckoutSessionMetadata,Jn as validateCodeChallenge,Zn as validateCodeVerifier,Jo as validateCreateCheckoutSessionRequest,ei as validateCreateCheckoutSessionResponse,yi as validateCustomClaims,ge as validateDates,hc as validateDocument,Vr as validateEnvVar,cd as validateEvent,Br as validateMetadata,As as validateOAuthPartners,ba as validateSendEmailRequest,Ea as validateSendEmailResponse,si as validateStripeBackConfig,ai as validateStripeFrontConfig,ni as validateSubscriptionClaims,ti as validateSubscriptionData,Ut as validateUniqueFields,Lr as validateUrl,hi as validateUserSubscription,ri as validateWebhookEvent,Cn as validateWithSchema,Ar as when,En as withErrorHandling,er as withGracefulDegradation,Ur as withTimeout,Rn as wrapAuthError,xn as wrapCrudError,Tn as wrapStorageError};
|
|
1
|
+
var Lt=Object.defineProperty;var Bt=(e,t)=>{for(var r in t)Lt(e,r,{get:t[r],enumerable:!0})};var Ct={};Bt(Ct,{AuthHardening:()=>pe,CURRENCY_MAP:()=>we,ConditionBuilder:()=>j,DEFAULT_CRUD_TIMEOUT:()=>Nn,DEFAULT_ERROR_MESSAGES:()=>L,DEFAULT_UPLOAD_TIMEOUT:()=>Dn,DoNotDevError:()=>T,LANGUAGE_COOKIE:()=>mn,SingletonManager:()=>Fe,addMonths:()=>J,addYears:()=>Le,calculateSubscriptionEndDate:()=>_n,captureErrorToSentry:()=>ke,clearGlobalSingleton:()=>nn,commonErrorCodeMappings:()=>X,compactToISOString:()=>Oe,configureProviders:()=>un,createAsyncSingleton:()=>sn,createErrorHandler:()=>D,createMetadata:()=>Dr,createMethodProxy:()=>ln,createSingleton:()=>on,createSingletonWithParams:()=>an,detectErrorSource:()=>Ie,ensureSpreadable:()=>Ir,evaluateCondition:()=>V,evaluateFieldConditions:()=>In,filterVisibleFields:()=>Sn,formatCurrency:()=>Ur,formatDate:()=>ht,formatRelativeTime:()=>qr,generateCodeChallenge:()=>bt,generateCodeVerifier:()=>yt,generateFirestoreRuleCondition:()=>Kr,generatePKCEPair:()=>zr,generateUUID:()=>On,getConditionDependencies:()=>kn,getCurrencyLocale:()=>vt,getCurrencySymbol:()=>Nr,getCurrentTimestamp:()=>Mr,getGlobalSingleton:()=>_e,getListCardFieldNames:()=>Z,getProvider:()=>cn,getRoleFromClaims:()=>tn,getVisibleFields:()=>Me,getWeekFromISOString:()=>Vr,handleError:()=>R,hasProvider:()=>dn,hasRestrictedVisibility:()=>xn,hasRoleAccess:()=>ue,hasTierAccess:()=>rn,isCompactDateString:()=>De,isFieldVisible:()=>Tt,isPKCESupported:()=>Xr,isoToCompactString:()=>Fr,lazyImport:()=>en,mapToDoNotDevError:()=>B,maybeTranslate:()=>Yr,normalizeToISOString:()=>_r,parseAcceptLanguage:()=>fn,parseDate:()=>Ne,parseDateToNoonUTC:()=>Gr,parseISODate:()=>Mn,parseServerCookie:()=>qn,readCookieValue:()=>gn,resetProviders:()=>pn,resolveLanguage:()=>vn,safeValidate:()=>Cr,sanitizeHref:()=>wn,showNotification:()=>Er,timestampToISOString:()=>Br,toDateOnly:()=>jr,toISOString:()=>Lr,translateArray:()=>kr,translateArrayRange:()=>wr,translateArrayWithIndices:()=>Or,translateObjectArray:()=>Pr,updateMetadata:()=>hn,validateCodeChallenge:()=>Zr,validateCodeVerifier:()=>Qr,validateEnvVar:()=>Vn,validateMetadata:()=>Bn,validateUrl:()=>Ln,validateWithSchema:()=>Rr,when:()=>An,withErrorHandling:()=>br,withGracefulDegradation:()=>Jr,withTimeout:()=>Un,wrapAuthError:()=>Tr,wrapCrudError:()=>Sr,wrapStorageError:()=>xr});var O={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},ne={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Co={[O.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"]},[O.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[O.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Io={maxTokens:4096,temperature:.7,stream:!0},Ao={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},ko={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Po=4,wo={"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"}};import*as u from"valibot";var We=u.object({role:u.picklist([ne.USER,ne.ASSISTANT,ne.SYSTEM]),content:u.pipe(u.string(),u.minLength(1)),id:u.optional(u.string()),createdAt:u.optional(u.string())}),he=u.lazy(()=>u.object({type:u.picklist(["string","number","boolean","array","object"]),description:u.optional(u.string()),enum:u.optional(u.array(u.string())),items:u.optional(he),properties:u.optional(u.record(u.string(),he)),required:u.optional(u.array(u.string()))})),Vt=u.object({description:u.pipe(u.string(),u.minLength(1)),parameters:u.object({type:u.literal("object"),properties:u.record(u.string(),he),required:u.optional(u.array(u.string()))})}),qt=u.object({id:u.string(),name:u.string(),args:u.record(u.string(),u.unknown())}),$t=u.object({messages:u.pipe(u.array(We),u.minLength(1)),provider:u.optional(u.picklist([O.ANTHROPIC,O.OPENAI,O.GOOGLE])),model:u.optional(u.string()),maxTokens:u.optional(u.pipe(u.number(),u.integer(),u.minValue(1))),temperature:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(2))),systemPrompt:u.optional(u.string()),stream:u.optional(u.boolean()),tools:u.optional(u.record(u.string(),Vt))}),Gt=u.object({promptTokens:u.number(),completionTokens:u.number(),totalTokens:u.number()}),jt=u.object({message:We,usage:u.optional(Gt),finishReason:u.optional(u.string()),toolCalls:u.optional(u.array(qt))}),No=u.object({provider:u.picklist([O.ANTHROPIC,O.OPENAI,O.GOOGLE]),model:u.optional(u.string()),maxTokens:u.optional(u.pipe(u.number(),u.integer(),u.minValue(1))),temperature:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(2))),systemPrompt:u.optional(u.string())});function Uo(e){return u.safeParse($t,e)}function Fo(e){return u.safeParse(jt,e)}var A={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function qo(e){Object.assign(A,e)}var ye={FREE:"free",PRO:"pro",PREMIUM:"premium"};function $o(e){Object.assign(ye,e)}var be={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Go(e){Object.assign(be,e)}var Ee={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"};function jo(e){Object.assign(Ee,e)}import*as a from"valibot";var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Wo(e){Object.assign(G,e)}var oe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ko(e){Object.assign(oe,e)}var Yo={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function zo(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Ke={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Xo={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as n from"valibot";var Ye=100,Ht=n.object({productId:n.pipe(n.string(),n.minLength(1),n.maxLength(200)),quantity:n.pipe(n.number(),n.integer(),n.minValue(1),n.maxValue(1e4))}),Qe=n.pipe(n.object({billingConfigKey:n.optional(n.pipe(n.string(),n.minLength(1))),lineItems:n.optional(n.pipe(n.array(Ht),n.minLength(1,"At least one line item is required"),n.maxLength(Ye,`At most ${Ye} line items`))),successUrl:n.pipe(n.string(),n.url()),cancelUrl:n.pipe(n.string(),n.url()),customerEmail:n.optional(n.pipe(n.string(),n.email())),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean()),userId:n.optional(n.string()),productId:n.optional(n.string()),priceId:n.optional(n.string()),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code"))),userEmail:n.optional(n.pipe(n.string(),n.email())),mode:n.optional(n.picklist([oe.PAYMENT,oe.SUBSCRIPTION]))}),n.rawTransform(({dataset:e,addIssue:t,NEVER:r})=>{let o=e.value,i=o.billingConfigKey||o.metadata?.billingConfigKey;return i?{...o,billingConfigKey:i,lineItems:o.lineItems??[{productId:i,quantity:1}]}:(t({message:"billingConfigKey is required"}),r)})),Ze=n.object({sessionId:n.string(),sessionUrl:n.nullable(n.pipe(n.string(),n.url()))}),Je=n.object({userId:n.string(),tier:n.string(),status:n.picklist(Object.values(G)),subscriptionId:n.nullable(n.string()),customerId:n.string(),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp())}),et=n.object({tier:n.string(),subscriptionId:n.nullable(n.string()),customerId:n.string(),status:n.picklist(Object.values(G)),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp()),isDefault:n.optional(n.boolean())}),tt=n.object({id:n.string(),type:n.string(),data:n.object({object:n.any()}),created:n.pipe(n.string(),n.isoTimestamp())}),rt=n.looseObject({userId:n.optional(n.string()),firebaseUid:n.optional(n.string()),productType:n.optional(n.string())});function Jo(e){return n.safeParse(Qe,e)}function ei(e){return n.safeParse(Ze,e)}function ti(e){return n.safeParse(Je,e)}function ri(e){return n.safeParse(et,e)}function ni(e){return n.safeParse(tt,e)}function oi(e){return n.safeParse(rt,e)}var Wt=n.object({type:n.literal("StripePayment"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.optional(n.pipe(n.string(),n.minLength(1,"Stripe price ID is required"))),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.pipe(n.string(),n.minLength(1,"Duration is required")),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),Kt=n.object({type:n.literal("StripeSubscription"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),Yt=n.variant("type",[Wt,Kt]),ii=n.record(n.string(),Yt),zt=n.record(n.string(),n.object({name:n.string(),price:n.string(),currency:n.string(),description:n.optional(n.string()),features:n.optional(n.array(n.string())),priceId:n.optional(n.string()),allowPromotionCodes:n.optional(n.boolean())})),ze={name:n.string(),price:n.number(),currency:n.string(),priceId:n.optional(n.string()),tier:n.string(),duration:n.string(),description:n.optional(n.string()),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean())},Xt=n.variant("mode",[n.object({mode:n.literal("manual"),taxRateIds:n.pipe(n.array(n.pipe(n.string(),n.minLength(1))),n.minLength(1))}),n.object({mode:n.literal("automatic")})]),Xe=5,Qt=n.object({allowedCountries:n.pipe(n.array(n.pipe(n.string(),n.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),n.minLength(1)),shippingRateIds:n.optional(n.pipe(n.array(n.pipe(n.string(),n.minLength(1))),n.maxLength(Xe,`shippingRateIds: at most ${Xe} (Stripe limit)`)))}),Zt=n.object({type:n.literal("StripeOrder"),name:n.string(),currency:n.pipe(n.string(),n.length(3)),description:n.optional(n.string()),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean()),tax:Xt,taxIdCollection:n.picklist(["disabled","optional","required"]),billingAddressCollection:n.picklist(["auto","required"]),shipping:n.optional(Qt),customerCreation:n.picklist(["always","if_required"]),invoiceCreation:n.boolean(),paymentMethodConfiguration:n.optional(n.pipe(n.string(),n.minLength(1)))}),Jt=n.record(n.string(),n.variant("type",[n.object({type:n.literal("StripePayment"),...ze}),n.object({type:n.literal("StripeSubscription"),...ze}),Zt]));function ai(e){return n.parse(zt,e)}function si(e){return n.parse(Jt,e)}function li(){let e={createCheckoutSessionRequest:n.safeParse(Qe,{}),createCheckoutSessionResponse:n.safeParse(Ze,{}),subscriptionData:n.safeParse(Je,{}),subscriptionClaims:n.safeParse(et,{}),webhookEvent:n.safeParse(tt,{}),checkoutSessionMetadata:n.safeParse(rt,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var nt=a.object({id:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),emailVerified:a.optional(a.boolean()),lastLoginAt:a.optional(a.string()),providerData:a.optional(a.array(a.object({providerId:a.string(),uid:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),phoneNumber:a.optional(a.nullable(a.string()))}))),role:a.optional(a.picklist(Object.values(A))),customClaims:a.optional(a.record(a.string(),a.any()))}),Se=a.object({userId:a.string(),tier:a.picklist(Object.values(ye)),status:a.picklist(Object.values(G)),isActive:a.optional(a.boolean()),features:a.optional(a.array(a.string())),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),ot=a.object({role:a.optional(a.picklist(Object.values(A))),subscription:a.optional(Se),features:a.optional(a.array(a.picklist(Object.values(be)))),permissions:a.optional(a.array(a.picklist(Object.values(Ee)))),githubAccess:a.optional(a.object({username:a.optional(a.string()),teamAccess:a.optional(a.array(a.string())),repoAccess:a.optional(a.array(a.string()))}))});function vi(e){return a.safeParse(nt,e)}function hi(e){return a.safeParse(Se,e)}function yi(e){return a.safeParse(ot,e)}function bi(){let e={authUser:a.safeParse(nt,{}),userSubscription:a.safeParse(Se,{}),customClaims:a.safeParse(ot,{}),getUserAuthStatus:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1))}),{}),getCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.optional(a.array(a.string()))}),{}),setCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claims:a.record(a.string(),a.any()),merge:a.optional(a.boolean(),!1)}),{}),removeCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.pipe(a.array(a.string()),a.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Si={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},xi={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Ti(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var wi={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},Oi={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},Di={CLIENT:"client",SERVER:"server",BUILD:"build"},Ni={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ui={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Fi={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},_i={USER:"user",GLOBAL:"global",SESSION:"session"},Mi={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Li={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Bi={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var qi={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},ie={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},xe={create:"admin",read:"guest",update:"admin",delete:"admin"},M={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},$i={ASC:"asc",DESC:"desc"},Gi={LIST:"list",LIST_CARD:"listCard"},ji=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var Ki={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Yi={EQ:M.EQ,NEQ:M.NEQ,LT:M.LT,LTE:M.LTE,GT:M.GT,GTE:M.GTE};var it=class extends Error{collidingIds;where;constructor(t,r){super(`BulkCollisionError: ${t.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=r}},at=class extends Error{cycle;constructor(t){super(`[dndev] bulkAcross: circular dependency: ${t.join(" \u2192 ")}`),this.name="BulkAcrossCycleError",this.cycle=t}},st=class extends Error{adapterName;constructor(t){super(`BulkNotImplementedError: adapter "${t}" has not implemented bulk() yet`),this.name="BulkNotImplementedError",this.adapterName=t}};import*as p from"valibot";var ta=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),data:p.record(p.string(),p.unknown()),idempotencyKey:p.optional(p.string())}),ra=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required"))}),na=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required")),data:p.record(p.string(),p.unknown()),merge:p.optional(p.boolean(),!1)}),oa=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),id:p.pipe(p.string(),p.minLength(1,"Entity ID is required"))}),ia=p.object({collection:p.pipe(p.string(),p.minLength(1,"Collection name is required")),limit:p.optional(p.pipe(p.number(),p.minValue(1),p.maxValue(1e3)),1e3),offset:p.optional(p.pipe(p.number(),p.minValue(0)),0),orderBy:p.optional(p.string()),orderDirection:p.optional(p.picklist(["asc","desc"]),"desc"),where:p.optional(p.array(p.object({field:p.string(),operator:p.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:p.unknown()})))});var va={RESEND:"resend"},ha={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as E from"valibot";var er=E.object({templateId:E.pipe(E.string(),E.minLength(1)),to:E.pipe(E.string(),E.email()),data:E.record(E.string(),E.unknown()),locale:E.optional(E.pipe(E.string(),E.minLength(2),E.maxLength(5)),"fr"),from:E.optional(E.string()),replyTo:E.optional(E.string())}),tr=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function ba(e){return E.safeParse(er,e)}function Ea(e){return E.safeParse(tr,e)}var z={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"},Ia={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},ae={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Te={[z.PERMISSION_DENIED]:{type:ae.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[z.NOT_FOUND]:{type:ae.NOT_FOUND,message:"The requested resource was not found"},[z.ALREADY_EXISTS]:{type:ae.ALREADY_EXISTS,message:"The resource already exists"},[z.INVALID_ARGUMENT]:{type:ae.VALIDATION_ERROR,message:"Invalid argument provided"}},lt=class extends Error{type;originalError;constructor(t,r,o){super(r),this.name="EntityHookError",this.type=t,this.originalError=o}},Aa={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},T=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=z.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 Oa={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var Na={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var Fa={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var Ma={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Ba={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Re={mobile:0,tablet:768,laptop:1024,desktop:1440},rr={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function nr(e){return e>=Re.desktop?"desktop":e>=Re.laptop?"laptop":e>=Re.tablet?"tablet":"mobile"}function Za(e,t){let r=rr[t];return e>=r.min&&e<=r.max}function Ja(e,t){let r=nr(e);return{current:r,width:e,height:t,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var or="landing",ir={FIXED:"fixed",SCROLL:"scroll"},ar={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var ut=["pull","push","admin","maintain","triage"];import"valibot";import*as d from"valibot";var Ce=d.object({owner:d.pipe(d.string(),d.minLength(1,"Repository owner is required")),repo:d.pipe(d.string(),d.minLength(1,"Repository name is required"))}),sr=d.picklist([...ut]),ps=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce,permission:d.optional(sr,"push"),customClaims:d.optional(d.record(d.string(),d.any()))}),ms=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce}),gs=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required")),githubUsername:d.pipe(d.string(),d.minLength(1,"GitHub username is required")),repoConfig:Ce}),fs=d.object({provider:d.string(),purpose:d.picklist(["authentication","api-access"]),code:d.pipe(d.string(),d.minLength(1,"Authorization code is required")),redirectUri:d.pipe(d.string(),d.url("Valid redirect URI is required")),codeVerifier:d.optional(d.string()),state:d.optional(d.string()),instance:d.optional(d.pipe(d.string(),d.url()))}),vs=d.object({provider:d.string(),refreshToken:d.pipe(d.string(),d.minLength(1,"Refresh token is required")),redirectUri:d.pipe(d.string(),d.url("Valid redirect URI is required"))}),hs=d.object({provider:d.string()}),ys=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required"))});var Rs={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as m from"valibot";var ct=m.object({name:m.string(),color:m.string(),icon:m.string(),customParameters:m.optional(m.record(m.string(),m.string())),button:m.object({backgroundColor:m.string(),textColor:m.string(),borderColor:m.string(),hoverBackgroundColor:m.string(),focusOutlineColor:m.string(),fontWeight:m.optional(m.string(),"500"),textKey:m.optional(m.string())})}),lr=m.object({...ct.entries,type:m.picklist(["auth","both"]),scopes:m.optional(m.array(m.string())),firebaseProviderId:m.optional(m.string())}),se=m.union([m.literal(""),m.pipe(m.string(),m.url())]),ur=m.object({authUrl:se,tokenUrl:se,profileUrl:se,revokeUrl:m.optional(se)}),cr=m.object({authentication:m.optional(m.array(m.string())),"api-access":m.array(m.string())}),dr=m.optional(m.object({pkce:m.optional(m.boolean(),!1),codeChallengeMethod:m.optional(m.picklist(["S256","plain"]),"S256")})),pr=m.object({...ct.entries,type:m.picklist(["oauth","both"]),scopes:cr,endpoints:ur,capabilities:dr}),dt={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},pt={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},mr=m.record(m.string(),lr),gr=m.record(m.string(),pr);function Is(){return m.safeParse(mr,dt)}function As(){return m.safeParse(gr,pt)}function ks(e){return e in dt}function Ps(e){return e in pt}var mt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Bs={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Vs={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:mt.ANALYTICS},marketing:{requiresConsent:mt.MARKETING}};function Ie(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"}import*as ft from"valibot";function D(e){return(t,r)=>{if(t instanceof T)return t;if(typeof t!="object"||t===null){let g=typeof t=="string"?t:e.defaultErrorMessage;return new T(r||g,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 i=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(i=e.errorCodeMapping[o]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[o]),s||(s=e.defaultErrorMessage);let c;return e.processMetadata?c=e.processMetadata(t):(c={originalError:t},o&&(c.originalCode=o)),"originalError"in c||(c.originalError=t),new T(r||s,i,{details:c,source:e.errorSource})}}var X={"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"};var L={"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."},fr={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"},Ae={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},F={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",...X},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",...X},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(fr).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode: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()},processMetadata: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}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:X,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:L.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:L["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:L.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},vr=e=>e instanceof ft.ValiError?new T(L["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):D(F.validation)(e),hr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Ae){let t=e,r=Ae[t.type]||"unknown";return new T(t.message||L[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Te[e.code]){let t=e,r=Te[t.code];if(r){let o=Ae[r.type]||"unknown";return new T(r.message||L[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return D(F.entity)(e)},gt={auth:D(F.auth),oauth:D(F.oauth),api:D(F.api),firebase:D(F.firebase),ui:D(F.ui),validation:vr,entity:hr,unknown:D(F.unknown)};function B(e,t,r){return e instanceof T?e:(gt[t]||gt.unknown)(e,r)}function ke(e,t,r={}){let o=globalThis.Sentry;o&&o.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,c])=>{if(typeof c!="function"&&s!=="originalError")try{i.setExtra(s,c)}catch{i.setExtra(s,`[${typeof c}]`)}}),Object.entries(r).forEach(([s,c])=>{if(typeof c!="function")try{i.setExtra(`context.${s}`,c)}catch{i.setExtra(`context.${s}`,`[${typeof c}]`)}}),(e.details?.userId||r.userId)&&i.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),o.captureException(e)})}function yr(){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 R(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:i={},log:s=!0,reportToSentry:c=!0,showNotification:g=!1,severity:y="error"}=r,b=Ie(e),f=e instanceof T?e:B(e,b,o);if(o&&!f.userMessageProvided&&(f.message.includes("Error")||f.message.includes("Failed")||f.message.length<10?f=new T(o,f.code,{details:{...f.details,originalMessage:f.message},source:b,userMessageProvided:!0}):f=new T(f.message,f.code,{details:{...f.details,userMessage:o},source:b,userMessageProvided:!0})),s){let I=yr()||typeof window<"u"&&window.__DNDEV_DEBUG,U={code:f.code,message:f.message,source:b};switch(y){case"warning":break;case"info":break;case"success":break;default:}}return c&&ke(f,b,i),f}function br(e,t){return async(...r)=>{try{return await e(...r)}catch(o){throw R(o,t)}}}function Er(e,t="info",r){let o=Date.now().toString();return o}function Sr(e,t,r,o,i){if(e instanceof T)return e;let{code:s}=B(e,"api");return new T("Request failed.",s,{source:"api",details:{context:`${t}.${r}(${o}${i?`, ${i}`:""})`,originalMessage:Pe(e),originalError:e}})}function xr(e,t,r,o){let i=`${t}.${r}(${o})`;return B(e,"api",`${i}: ${Pe(e)}`)}function Tr(e,t,r,o){let i=o?` ${JSON.stringify(o)}`:"",s=`${t}.${r}(${i})`,c=B(e,"auth",`${s}: ${Pe(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&c.code==="unknown"&&e.code!=="unknown"?new T(c.message,c.code,{details:{...c.details,originalCode:e.code},source:c.source}):c}function Pe(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as Q from"valibot";function Rr(e,t,r){try{return Q.parse(e,t)}catch(o){throw o instanceof Q.ValiError?new T(`Validation failed in ${r}: ${o.message}`,"validation-failed",{details:{issues:o.issues,input:t},source:"validation"}):new T(`Unexpected validation error in ${r}: ${Ar(o)}`,"validation-failed",{originalError:o instanceof Error?o:new Error(String(o)),source:"validation"})}}function Cr(e,t){try{return Q.parse(e,t)}catch{return null}}function Ir(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Ar(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function kr(e,t,r,o={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:c}=o;return Array.from({length:r},(g,y)=>{let b=`${t}.${y}`;return e(b)}).filter((g,y)=>{let b=`${t}.${y}`;return!(g===b||s&&g.trim()===""||g.length<i||c&&!c(g,y))})}function Pr(e,t,r,o){return Array.from({length:r},(i,s)=>{let c=`${t}.${s}.${String(o[0])}`;if(e(c)===c)return null;let y={};for(let b of o){let f=`${t}.${s}.${String(b)}`;y[b]=e(f)}return y}).filter(i=>i!==null)}function wr(e,t,r,o,i={}){let{minLength:s=0,excludeEmpty:c=!0,customFilter:g}=i;return Array.from({length:o-r},(y,b)=>{let f=r+b,I=`${t}.${f}`;return e(I)}).filter((y,b)=>{let f=r+b,I=`${t}.${f}`;return!(y===I||c&&y.trim()===""||y.length<s||g&&!g(y,f))})}function Or(e,t,r,o={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:c}=o;return Array.from({length:r},(g,y)=>{let b=`${t}.${y}`;return{item:e(b),originalIndex:y}}).filter(({item:g,originalIndex:y})=>{let b=`${t}.${y}`;return!(g===b||s&&g.trim()===""||g.length<i||c&&!c(g,y))})}function Dr(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var we={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function vt(e){return we[e]?.locale??"en-US"}function Nr(e){return!e||typeof e!="string"?e??"":we[e]?.symbol??e}function Ur(e,t,r={}){if(e==null||isNaN(e))return"";let o=vt(t);return new Intl.NumberFormat(o,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...r}).format(e)}function Oe(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let r=t[1],o=t[2],i=t[3],s=t[4],c=t[5],g=new Date(parseInt(r,10),parseInt(o,10)-1,parseInt(i,10),parseInt(s,10),parseInt(c,10));if(isNaN(g.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return g.toISOString()}function Fr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${o}${i}:${s}${c}`}function De(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function _r(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(De(e))return Oe(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")return t.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof e}`)}function Mr(){return new Date().toISOString()}function Lr(e){return e.toISOString()}function Br(e){return new Date(e).toISOString()}function Vr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=new Date(t.getFullYear(),0,1),o=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((o+r.getDay()+1)/7)}, ${t.getFullYear()}`}var w={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function qr(e,t="en",r={}){if(!e)return"";let{style:o="long",numeric:i="auto",fallbackThreshold:s=w.WEEK}=r,c;if(e instanceof Date)c=e;else if(typeof e=="string")c=new Date(e);else if(typeof e=="number")c=new Date(e);else if(typeof e=="object"&&"toDate"in e)c=e.toDate();else return"";if(isNaN(c.getTime()))return"";let g=new Date,y=c.getTime()-g.getTime(),b=Math.round(y/1e3),f=Math.abs(b);if(f>s)return ht(c.toISOString(),t);let I=new Intl.RelativeTimeFormat(t,{style:o,numeric:i});return f<w.MINUTE?I.format(b,"second"):f<w.HOUR?I.format(Math.round(b/w.MINUTE),"minute"):f<w.DAY?I.format(Math.round(b/w.HOUR),"hour"):f<w.WEEK?I.format(Math.round(b/w.DAY),"day"):f<w.MONTH?I.format(Math.round(b/w.WEEK),"week"):f<w.YEAR?I.format(Math.round(b/w.MONTH),"month"):I.format(Math.round(b/w.YEAR),"year")}function $r(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function ht(e,t="en",r="long"){if(!e)return"";let o;if(e instanceof Date)o=e;else if(typeof e=="string")o=new Date(e);else if(typeof e=="number")o=new Date(e);else if(typeof e=="object"&&"toDate"in e)o=e.toDate();else return"";if(isNaN(o.getTime()))return"";let i=typeof r=="string"?$r(r):r;return new Intl.DateTimeFormat(t,i).format(o)}function Ne(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(De(t))try{return Oe(t)}catch{return}let r=new Date(t);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")try{let r=t.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,r=t.seconds*1e3+(t.nanoseconds||0)/1e6,o=new Date(r);return isNaN(o.getTime())?void 0:o.toISOString()}}}function Gr(e){let t=Ne(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function jr(e){let t=Ne(e);return t&&t.split("T")[0]||""}function Hr(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function Wr(e){let t=`resource.data.${e.field}`,r=Hr(e.value);return`${t} ${e.op} ${r}`}function Kr(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let r=e.publicCondition.map(Wr).join(" && ");t.push(`(${r})`)}for(let r of e.ownerFields)t.push(`request.auth.uid == resource.data.${r}`);return t.length===0?"false":t.join(" || ")}function Yr(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function yt(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Et(e)}async function bt(e){let r=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",r);return Et(new Uint8Array(o))}async function zr(){let e=yt(),t=await bt(e);return{codeVerifier:e,codeChallenge:t}}function Et(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xr(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Qr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function Zr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function Jr(e,t,r){try{return await e()}catch{return t(),!1}}var le=new Map;function en(e,t){if(le.has(t))return le.get(t);let r=e().catch(o=>{throw le.delete(t),o});return le.set(t,r),r}var St={[A.GUEST]:0,[A.USER]:1,[A.ADMIN]:2,[A.SUPER]:3};function ue(e,t){if(!e)return!1;let r=St[e]??-1,o=St[t]??1/0;return r>=o}function tn(e){return e?e.role===A.SUPER||e.isSuper===!0?A.SUPER:e.role===A.ADMIN||e.isAdmin===!0?A.ADMIN:e.role===A.USER?A.USER:e.role||A.USER:A.USER}function rn(e,t,r){if(!e)return!1;let o=r??Ke,i=o[e]?.level??-1,s=o[t]?.level??1/0;return i>=s}var Ue="__DNDEV_SINGLETONS__";function xt(){if(typeof globalThis<"u"){let e=globalThis;return e[Ue]||(e[Ue]=new Map),e[Ue]}return new Map}function _e(e,t){let r=xt();return r.has(e)||r.set(e,t()),r.get(e)}function nn(e){xt().delete(e)}function on(e,...t){let r=null,o=!1;return 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}}}function an(e){let t=null,r=!1;return function(...i){if(t!==null)return t;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?t=new e(...i):t=e(...i),t}finally{r=!1}}}function sn(e){let t=null,r=!1,o=null;return async function(){if(t!==null)return t;if(r&&o)return o;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return o=e(),t=await o,t}finally{r=!1,o=null}}}function ln(e,t){return new Proxy({},{get(r,o){if(t.includes(o)){let s=e(),c=s[o];return typeof c=="function"?c.bind(s):c}return e()[o]}})}var Fe=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,o={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(o.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",o.fallbackFactory){let i=o.fallbackFactory();return this.instances.set(t,i),this.initialized.add(t),i}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let i=await r();return this.instances.set(t,i),this.initialized.add(t),i}catch(i){if(typeof process<"u",o.cacheFailures&&this.initialized.add(t),o.fallbackFactory){let s=o.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw i}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function ce(){return _e("providers",()=>({providers:null}))}function un(e){let t=ce();t.providers,t.providers=e}function cn(e){let{providers:t}=ce();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 dn(e){return!!ce().providers?.[e]}function pn(){ce().providers=null}var mn="dndev-lang";function gn(e,t){if(!e)return null;for(let r of e.split(";")){let o=r.indexOf("=");if(o!==-1&&r.slice(0,o).trim()===t)try{return decodeURIComponent(r.slice(o+1).trim())}catch{return null}}return null}function fn(e){return e?e.split(",").map((t,r)=>{let[o="",...i]=t.trim().split(";"),s=i.find(g=>g.trim().startsWith("q=")),c=s?Number(s.trim().slice(2)):1;return{tag:o.trim(),quality:Number.isFinite(c)?c:0,index:r}}).filter(t=>t.tag!==""&&t.tag!=="*"&&t.quality>0).sort((t,r)=>r.quality-t.quality||t.index-r.index).map(t=>t.tag):[]}function vn({supported:e,fallback:t,stored:r,preferred:o}){if(r&&e.includes(r))return r;for(let i of o??[]){if(e.includes(i))return i;let s=i.split("-")[0];if(s&&e.includes(s))return s}return t}function hn(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function yn(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function bn(e){if(yn(e))return e.visibility}function Tt(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?ue(t,"admin"):r==="owner"?!1:ue(t,r)}function En(e,t,r){for(let o of r.ownerFields)if(e[o]===t)return!0;return!1}function Me(e,t,r){let o=e;if(!o||typeof o!="object"||!o.entries)return[];let i=o.entries,s=[],{documentData:c,uid:g,ownership:y}=r??{},b=y&&g!=null&&c&&En(c,g,y);for(let[f,I]of Object.entries(i)){let U=bn(I);if(U==="owner"){b&&s.push(f);continue}Tt(U,t)&&s.push(f)}return s}function Sn(e,t,r,o){if(!e)return{};let i=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,s=Me(t,r,i),c={};for(let g of s)Object.prototype.hasOwnProperty.call(e,g)&&(c[g]=e[g]);return c}function Z(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let r=t,o=[...r.title??[],...r.subtitle??[],...r.content??[],...r.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function de(e){if(!(!e||typeof e!="object")){if(e.entries&&typeof e.entries=="object")return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let r=de(t);if(r)return r}if(e.wrapped)return de(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let r=de(t);if(r)return r}}}function xn(e){let t=de(e);if(!t)return!1;for(let r of Object.values(t)){let o=r?.visibility;if(o!==void 0&&o!=="guest")return!0}return!1}var pe=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(t={}){this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let r=this.store.get(t);if(r?.lockedUntil){if(Date.now()<r.lockedUntil){let o=Math.ceil((r.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${o} minute${o===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let r=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(r);let o=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return o.attempts+=1,o.lastAttempt=r,o.attempts>=this.maxAttempts&&(o.lockedUntil=r+this.lockoutMs),this.store.set(t,o),{attempts:o.attempts,locked:o.lockedUntil!==null&&Date.now()<o.lockedUntil,lockedUntil:o.lockedUntil}}_evictExpired(t){for(let[r,o]of this.store)o.lockedUntil!==null&&t>o.lockedUntil?this.store.delete(r):o.lockedUntil===null&&t-o.lastAttempt>this.lockoutMs&&this.store.delete(r)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function Tn(e,t){if(t.includes(".")){let r=t.split("."),o=e;for(let i of r){if(o==null||typeof o!="object")return;o=o[i]}return o}return e[t]}function Rn(e,t){let r=Tn(t,e.field);switch(e.operator){case"equals":return r===e.value;case"notEquals":return r!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(r);case"notIn":return Array.isArray(e.value)&&!e.value.includes(r);case"greaterThan":return typeof r=="number"&&typeof e.value=="number"&&r>e.value;case"lessThan":return typeof r=="number"&&typeof e.value=="number"&&r<e.value;case"greaterThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r>=e.value;case"lessThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r<=e.value;case"exists":return r!=null&&r!==""&&r!==!1;case"notExists":return r==null||r===""||r===!1;case"contains":return typeof r=="string"&&typeof e.value=="string"||Array.isArray(r)?r.includes(e.value):!1;default:return!1}}function Cn(e){return e instanceof j||"expression"in e?e.expression:e}function V(e,t){let r=Cn(e);if(r.type==="condition")return Rn(r,t);let{logic:o,conditions:i}=r;return o==="and"?i.every(s=>V(s,t)):i.some(s=>V(s,t))}function In(e,t){return e?{visible:e.visible?V(e.visible,t):!0,disabled:e.disabled?V(e.disabled,t):!1,required:e.required?V(e.required,t):!1,readonly:e.readonly?V(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var j=class e{expression;constructor(t){this.expression=t}get type(){return this.expression.type}or(t){let r=t instanceof e?t.expression:t,o=this.expression;return o.type==="group"&&o.logic==="or"?new e({type:"group",logic:"or",conditions:[...o.conditions,r]}):new e({type:"group",logic:"or",conditions:[o,r]})}and(t){let r=t instanceof e?t.expression:t,o=this.expression;return o.type==="group"&&o.logic==="and"?new e({type:"group",logic:"and",conditions:[...o.conditions,r]}):new e({type:"group",logic:"and",conditions:[o,r]})}};function An(e){function t(r,o){return new j({type:"condition",field:e,operator:r,value:o})}return{equals:r=>t("equals",r),notEquals:r=>t("notEquals",r),in:r=>t("in",r),notIn:r=>t("notIn",r),greaterThan:r=>t("greaterThan",r),lessThan:r=>t("lessThan",r),greaterThanOrEqual:r=>t("greaterThanOrEqual",r),lessThanOrEqual:r=>t("lessThanOrEqual",r),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:r=>t("contains",r)}}function kn(e){let t=e instanceof j?e.expression:e,r=new Set;function o(i){if(i.type==="condition")r.add(i.field);else for(let s of i.conditions)o(s)}return o(t),r}var Pn=new Set(["http:","https:","mailto:","tel:","blob:"]);function wn(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let r=new URL(t);if(Pn.has(r.protocol))return t}catch{return t}return""}function On(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Dn=3e4,Nn=15e3;function Un(e,t,r){if(r?.aborted)return Promise.reject(Rt(r.reason));let o=t>0;return!o&&!r?e:new Promise((i,s)=>{let c=!1,g;function y(){c=!0,g!==void 0&&(clearTimeout(g),g=void 0),r&&r.removeEventListener("abort",b)}function b(){c||(y(),s(Rt(r?.reason)))}r&&r.addEventListener("abort",b,{once:!0}),o&&(g=setTimeout(()=>{c||(y(),s(Fn(t)))},t)),e.then(f=>{c||(y(),i(f))},f=>{c||(y(),s(f))})})}function Fn(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function Rt(e){if(e instanceof Error){let r=new Error(e.message);return r.name="AbortError",r}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}function J(e,t){let r=new Date(e),o=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==o&&r.setDate(0),r}function Le(e,t){let r=new Date(e),o=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==o&&r.setDate(0),r}function _n(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=J(t,1):e==="3months"?r=J(t,3):e==="6months"?r=J(t,6):e==="1year"?r=Le(t,1):e==="2years"?r=Le(t,2):r=J(t,1),r.toISOString()}function Mn(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function Ln(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function Bn(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);if(/<[^>]*>/.test(o))throw new Error(`Metadata value for key '${r}' must not contain HTML`);let i=o;if(i.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=i}return t}function Vn(e,t=!0){let r=process.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}function qn(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,o=e.split(";");for(let i=0;i<o.length;i++){let s=o[i];if(s){for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(r)===0)return decodeURIComponent(s.substring(r.length,s.length))}}return null}function oc(e,t){let r=e;return r.metadata=t,r}import*as l from"valibot";var ee=new Map;function h(e,t){ee.set(e,t)}function ac(e){return ee.has(e)}function sc(){return Array.from(ee.keys())}function lc(){ee.clear()}function x(e,t){return t?e:l.nullish(e)}var me=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(l.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(l.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(l.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?l.pipe(l.string(),...t):l.string();return x(r,e.validation?.required)},$n=e=>{let t=l.pipe(l.string(),l.email("Invalid email address"));return x(t,e.validation?.required)},Gn=e=>{let t=e.validation?.minLength!==void 0?l.pipe(l.string(),l.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):l.string();return x(t,e.validation?.required)},jn=e=>{let t=l.pipe(l.string(),l.url("Invalid URL"));return x(t,e.validation?.required)},H=e=>{let t=[];e.validation?.min!==void 0&&t.push(l.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(l.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?l.pipe(l.number(),...t):l.number();return x(r,e.validation?.required)},It=e=>{let t=l.boolean();return x(t,e.validation?.required)},W=e=>{let t=l.pipe(l.string(),l.check(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return x(t,e.validation?.required)},wt=l.object({url:l.string(),filename:l.string(),size:l.number(),mimeType:l.nullish(l.string()),uploadedAt:l.nullish(l.string())}),At=e=>{let t=l.nullable(wt);return x(t,e.validation?.required)},kt=e=>{let t=l.array(wt);return x(t,e.validation?.required)},Ot=l.object({fullUrl:l.string(),thumbUrl:l.string()}),Hn=e=>{let t=l.union([l.string(),Ot]);return x(t,e.validation?.required)},Wn=e=>{let t=l.array(l.union([l.string(),Ot]));return x(t,e.validation?.required)},Kn=e=>{let t=l.object({lat:l.number(),lng:l.number()});return x(t,e.validation?.required)},Yn=e=>{let t=l.object({formatted_address:l.string(),latitude:l.number(),longitude:l.number(),street_number:l.nullish(l.string()),route:l.nullish(l.string()),locality:l.nullish(l.string()),administrative_area_level_1:l.nullish(l.string()),administrative_area_level_2:l.nullish(l.string()),country:l.nullish(l.string()),postal_code:l.nullish(l.string())});return x(t,e.validation?.required)},zn=e=>{let t=l.record(l.string(),l.unknown());return x(t,e.validation?.required)},Xn=e=>{let t=l.array(l.unknown());return x(t,e.validation?.required)},Be=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(s=>s.value),i=l.picklist(o);return x(i,e.validation?.required)}let r=l.union([l.string(),l.number()]);return x(r,e.validation?.required)},Qn=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(s=>s.value),i=l.array(l.picklist(o));return x(i,e.validation?.required)}let r=l.array(l.string());return x(r,e.validation?.required)},Zn=e=>{let t=l.pipe(l.string(),l.minLength(1,"Invalid ID format"));return x(t,e.validation?.required)},Ve=e=>{let t=l.string();return x(t,e.validation?.required)},Jn=e=>{let t=l.string();return x(t,e.validation?.required)},eo=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}$",i=[];if(t!==void 0&&i.push(l.minLength(t,`IBAN must be at least ${t} characters`)),r!==void 0&&i.push(l.maxLength(r,`IBAN must not exceed ${r} characters`)),o){let c=typeof o=="string"?new RegExp(o):o;i.push(l.regex(c,"Invalid IBAN format"))}let s=i.length>0?l.pipe(l.string(),...i):l.string();return x(s,e.validation?.required)},Pt=()=>l.never(),to=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],i=l.picklist(o);return x(i,e.validation?.required)}let r=l.boolean();return x(r,e.validation?.required)},ro=e=>l.custom(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"),no=e=>{let t=l.object({amount:l.number(),currency:l.optional(l.string()),vatIncluded:l.optional(l.boolean()),discountPercent:l.optional(l.pipe(l.number(),l.minValue(0),l.maxValue(100)))});return x(t,e.validation?.required)};function oo(){h("text",me),h("textarea",me),h("richtext",me),h("color",me),h("email",$n),h("password",Gn),h("url",jn),h("tel",Jn),h("iban",eo),h("number",H),h("currency",H),h("price",no),h("range",H),h("year",H),h("rating",H),h("duration",H),h("boolean",It),h("checkbox",It),h("gdprConsent",ro),h("date",W),h("datetime-local",W),h("time",W),h("week",W),h("month",W),h("timestamp",W),h("file",At),h("files",kt),h("document",At),h("documents",kt),h("image",Hn),h("images",Wn),h("geopoint",Kn),h("address",Yn),h("map",zn),h("array",Xn),h("select",Be),h("multiselect",Qn),h("radio",Be),h("combobox",Be),h("switch",to),h("reference",Zn),h("hidden",Ve),h("avatar",Ve),h("badge",Ve),h("submit",Pt),h("reset",Pt)}oo();function te(e){if(e.validation?.schema){let o=e.validation.schema;return x(o,e.validation?.required)}let t=ee.get(e.type);if(t){let o=t(e);if(o!==null)return o}let r=l.unknown();return x(r,e.validation?.required)}var Dt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Nt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ge(e,t=""){if(Array.isArray(e))e.forEach((r,o)=>{let i=`${t}[${o}]`;if(typeof r=="string"&&Nt(r)){if(!Dt.test(r))throw R(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&ge(r,i)});else if(typeof e=="object"&&e!==null)for(let[r,o]of Object.entries(e)){let i=t?`${t}.${r}`:r;if(typeof o=="string"&&Nt(o)){if(!Dt.test(o))throw R(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`,context:{field:i,value:o},severity:"error"})}else typeof o=="object"&&o!==null&&ge(o,i)}}import*as Ft from"valibot";var qe={};function mc(e){qe.uniqueConstraintValidator=e}async function Ut(e,t,r){let{uniqueFields:o=[],collection:i}=e.metadata;o.length!==0&&qe.uniqueConstraintValidator&&await Promise.all(o.map(async({field:s,errorMessage:c})=>{let g=t[s];if(g==null)return;if(await qe.uniqueConstraintValidator.checkDuplicate(i,s,g,r))throw R(new Error(c||`${s} must be unique`),{userMessage:c||`${s} must be unique`,context:{field:s}})}))}async function hc(e,t,r,o){Ft.parse(e,t),ge(t),await Ut(e,t,o),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}function io(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Ic(e){if(!io(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw R(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}var $e=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],kc="available",Pc=["draft","deleted"],fe=["id","createdAt","updatedAt","createdById","updatedById"],ao=[...fe,"status"];function wc(e){return ao.includes(e)}function Oc(e){return fe.includes(e)}var C={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...$e]}},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 so=new Set(["__proto__","constructor","prototype"]);function lo(e){for(let t of Object.keys(e.fields))if(so.has(t))throw R(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function uo(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,r=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:ie.CREATE_ONLY,validation:{required:!0,reference:r}}}function co(e,t){if(!t||t.length===0)return e.map(i=>({value:i.value,label:i.label}));let r=e.map(i=>({value:i.value,label:i.label})),o=new Set(e.map(i=>i.value));for(let i of t)o.has(i.value)||r.push(i);return r}function po(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let r=0;r<e.uniqueKeys.length;r++){let o=e.uniqueKeys[r];if(!o)continue;if(!o.fields||o.fields.length===0)throw R(new Error(`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:r},severity:"error"});let i=o.fields.filter(s=>!t.has(s));if(i.length>0)throw R(new Error(`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:r,invalidFields:i},severity:"error"})}}function mo(e){let{form:t,fields:r}=e,o=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw R(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let i=t.steps.flatMap(y=>y.fields),s=i.filter(y=>!o.includes(y));if(s.length>0)throw R(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let c=new Set(i);o.filter(y=>!c.has(y)).length>0}t.rules&&t.rules.forEach((i,s)=>{let g=(Array.isArray(i.condition)?i.condition.map(f=>f.field):[i.condition.field]).filter(f=>!o.includes(f));if(g.length>0)throw R(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${g.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${g.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:g,operation:"validateFormConfig"},severity:"error"});let b=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(f=>!o.includes(f));if(b.length>0)throw R(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${b.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${b.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:b,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([i,s])=>{if(s.dependsOn&&!o.includes(s.dependsOn.field))throw R(new Error(`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:i,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function go(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function _c(e){try{lo(e),mo(e);let t=go(e),r={...e.fields,...C,...e.fields.createdAt&&{createdAt:{...C.createdAt,...e.fields.createdAt,type:C.createdAt.type,visibility:C.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...C.updatedAt,...e.fields.updatedAt,type:C.updatedAt.type,visibility:C.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...C.createdById,...e.fields.createdById,type:C.createdById.type,visibility:C.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...C.updatedById,...e.fields.updatedById,type:C.updatedById.type,visibility:C.updatedById.visibility}},...e.fields.status&&{status:{...C.status,...e.fields.status,validation:{...C.status.validation,...e.fields.status.validation,options:co($e,e.fields.status.validation?.options)}}},...e.scope&&{[e.scope.field]:uo(e.scope)}};if(e.listFields){let s=new Set(Object.keys(r)),c=e.listFields.filter(g=>!s.has(g));if(c.length>0)throw R(new Error(`Entity '${e.name}' defines listFields that do not exist: ${c.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${c.join(", ")}`,context:{entityName:e.name,invalidFields:c,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),g=Z(e).filter(y=>!s.has(y));if(g.length>0)throw R(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${g.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${g.join(", ")}`,context:{entityName:e.name,invalidFields:g,operation:"defineEntity"},severity:"error"})}if(e.uniqueKeys){let s=new Set(Object.keys(r));po(e,s)}let o={...xe,...e.access||{}},i=e.namespace||`entity-${e.name.toLowerCase()}`;return{...e,form:t,fields:r,access:o,namespace:i,...e.search&&{search:e.search},...e.defaultSort&&{defaultSort:e.defaultSort}}}catch(t){throw R(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}import*as N from"valibot";function Ge(e,t){return!!(t.visibility==="hidden"||t.editable===ie.GENERATED||fe.includes(e))}function re(e,t){return Object.assign(e,{visibility:t})}function q(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},r}function fo(e){let t=te(e);return re(t,e.visibility)}function je(e){let t=te({...e,validation:{...e.validation,required:!1}});return re(t,e.visibility)}function $c(e){let t=e.fields,r={};for(let[k,P]of Object.entries(t))P.visibility!=="hidden"&&(r[k]=je(P));let o=q(N.object(r),e),i={};for(let[k,P]of Object.entries(t))Ge(k,P)||(i[k]=fo(P));let s=q(N.object(i),e),c={};for(let[k,P]of Object.entries(t))if(!Ge(k,P))if(k==="status"){let _=N.literal("draft");c[k]=re(_,P.visibility)}else c[k]=je(P);let g=q(N.object(c),e),y={};for(let[k,P]of Object.entries(t))Ge(k,P)||(y[k]=je(P));y.id=re(te(C.id),"technical");let b=q(N.object(y),e),f;if(e.listFields&&e.listFields.length>0){let k=["id","status"],P=[...new Set([...k,...e.listFields])];f={};for(let _ of P){let Y=r[_];Y&&(f[_]=Y)}}else f=r;let I=q(N.object(f),e),U,He=Z(e);if(He.length>0){let k=["id","status"],P=[...new Set([...k,...He])];U={};for(let _ of P){let Y=r[_];Y&&(U[_]=Y)}}else U=r;let _t=q(N.object(U),e),Mt=q(N.object({id:re(te(C.id),"technical")}),e);return{create:s,draft:g,update:b,get:o,list:I,listCard:_t,delete:Mt}}function jc(e,t,r=1,o=!1){let i=[];if(o)for(let s=t;s>=e;s-=r)i.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=r)i.push({value:String(s),label:String(s)});return i}var $=new Map;function Wc(e,t){$.has(e),$.set(e,t)}function Kc(e){$.delete(e)}function Yc(e){let t=$.get(e);return t?t():null}function zc(e){return $.has(e)}function Xc(){return Array.from($.keys())}function Qc(){$.clear()}import*as S from"valibot";var vo=S.record(S.string(),S.unknown()),ho=S.object({id:S.string(),patch:S.record(S.string(),S.unknown())}),yo=S.string(),Jc=S.object({inserts:S.optional(S.array(vo)),updates:S.optional(S.array(ho)),deletes:S.optional(S.array(yo))}),ed=S.object({insertedIds:S.array(S.string()),updatedIds:S.array(S.string()),deletedIds:S.array(S.string())});function td(e){let t=new Set((e.updates??[]).map(c=>c.id)),r=e.deletes??[],o=[];for(let c of r)t.has(c)&&o.push(c);if(o.length>0)return{collisions:o,where:"updates-deletes"};let i=e.inserts??[],s=[];for(let c of i)typeof c.id=="string"&&t.has(c.id)&&s.push(c.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as v from"valibot";var id=v.pipe(v.string(),v.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),bo=v.picklist(["ephemeral","session","persistent"]),Eo=v.object({title:v.optional(v.string()),pinnable:v.optional(v.boolean()),preferredHeight:v.optional(v.pipe(v.number(),v.minValue(0)))}),So=v.object({id:v.pipe(v.string(),v.minLength(1)),kind:v.pipe(v.string(),v.minLength(1)),lifetime:v.optional(bo,"ephemeral"),metadata:v.optional(Eo),payload:v.unknown()}),xo=v.object({widgetId:v.pipe(v.string(),v.minLength(1)),action:v.pipe(v.string(),v.minLength(1)),payload:v.unknown()}),K=new Map;function ad(e){if(K.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);K.set(e.kind,e)}function sd(e){return K.get(e)}function ld(){return Array.from(K.values())}function ud(e,t){let r=v.safeParse(So,e);if(!r.success)return{ok:!1,reason:`Invalid canvas block envelope: ${ve(r.issues)}`};let o=K.get(r.output.kind);if(!o)return{ok:!1,reason:`Unknown widget kind: "${r.output.kind}"`};let i=v.safeParse(o.schema,r.output.payload);if(!i.success)return{ok:!1,reason:`Payload rejected by "${r.output.kind}" schema: ${ve(i.issues)}`};if(t?.caller!==void 0){let c=t.caller.access;if(!To(o.surface,c))return{ok:!1,reason:`surface_forbidden: widget "${r.output.kind}" surface=${o.surface} not reachable by caller access=${c===null?"null":c}`}}return{ok:!0,value:{...r.output,payload:i.output},widget:o}}function To(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function cd(e,t){let r=v.safeParse(xo,e);if(!r.success)return{ok:!1,reason:`Invalid canvas event envelope: ${ve(r.issues)}`};let o=K.get(t);if(!o)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let i=o.actions[r.output.action];if(!i)return{ok:!1,reason:`Widget "${t}" has no action "${r.output.action}"`};let s=v.safeParse(i,r.output.payload);return s.success?{ok:!0,value:{...r.output,payload:s.output},widget:o}:{ok:!1,reason:`Payload rejected by "${t}.${r.output.action}" schema: ${ve(s.issues)}`}}function ve(e){return e.map(t=>{let r=t.path?.map(o=>String(o.key)).join(".")??"";return r?`${r}: ${t.message}`:t.message}).join("; ")}export{Yi as AGGREGATE_FILTER_OPERATORS,Ki as AGGREGATE_OPERATIONS,$t as AIChatRequestSchema,jt as AIChatResponseSchema,We as AIMessageSchema,No as AIProviderConfigSchema,qt as AIToolCallSchema,Vt as AIToolDefinitionSchema,Gt as AIUsageSchema,Ao as AI_ERROR_CODES,Co as AI_MODELS,O as AI_PROVIDERS,ne as AI_ROLES,ko as AI_TIERS,wo as AI_TOKEN_PRICING,Oa as AUTH_EVENTS,dt as AUTH_PARTNERS,xi as AUTH_PARTNER_STATE,pe as AuthHardening,nt as AuthUserSchema,fe as BACKEND_GENERATED_FIELD_NAMES,Na as BILLING_EVENTS,rr as BREAKPOINT_RANGES,Re as BREAKPOINT_THRESHOLDS,at as BulkAcrossCycleError,it as BulkCollisionError,yo as BulkDeleteIdSchema,vo as BulkInsertSchema,st as BulkNotImplementedError,Jc as BulkRequestSchema,ed as BulkResponseSchema,ho as BulkUpdateSchema,Ke as COMMON_TIER_CONFIGS,Ni as CONFIDENCE_LEVELS,mt as CONSENT_CATEGORY,Di as CONTEXTS,M as CRUD_OPERATORS,we as CURRENCY_MAP,So as CanvasBlockSchema,xo as CanvasEventSchema,bo as CanvasLifetimeSchema,Eo as CanvasWidgetMetadataSchema,Ht as CheckoutLineItemInputSchema,rt as CheckoutSessionMetadataSchema,j as ConditionBuilder,Qe as CreateCheckoutSessionRequestSchema,Ze as CreateCheckoutSessionResponseSchema,ot as CustomClaimsSchema,Io as DEFAULT_AI_CONFIG,Po as DEFAULT_AI_MARKUP,Nn as DEFAULT_CRUD_TIMEOUT,xe as DEFAULT_ENTITY_ACCESS,L as DEFAULT_ERROR_MESSAGES,or as DEFAULT_LAYOUT_PRESET,$e as DEFAULT_STATUS_OPTIONS,kc as DEFAULT_STATUS_VALUE,Xo as DEFAULT_SUBSCRIPTION,Dn as DEFAULT_UPLOAD_TIMEOUT,Bs as DENSITY,T as DoNotDevError,ie as EDITABLE,ha as EMAIL_ERROR_CODES,va as EMAIL_PROVIDERS,Si as EMAIL_VERIFICATION_STATUS,ae as ENTITY_HOOK_ERRORS,Oi as ENVIRONMENTS,z as ERROR_CODES,Ia as ERROR_SEVERITY,Aa as ERROR_SOURCE,lt as EntityHookError,be as FEATURES,Vs as FEATURE_CONSENT_MATRIX,Ui as FEATURE_STATUS,ji as FIELD_TYPES,Te as FIREBASE_ERROR_MAP,ir as FOOTER_MODE,ut as GITHUB_PERMISSION_LEVELS,Pc as HIDDEN_STATUSES,mn as LANGUAGE_COOKIE,ar as LAYOUT_PRESET,Gi as LIST_SCHEMA_TYPE,Ye as MAX_CHECKOUT_LINE_ITEMS,Xe as MAX_SHIPPING_RATE_IDS,Fa as OAUTH_EVENTS,pt as OAUTH_PARTNERS,$i as ORDER_DIRECTION,Rs as PARTNER_ICONS,Ma as PAYLOAD_EVENTS,Ee as PERMISSIONS,wi as PLATFORMS,Li as PWA_ASSET_TYPES,Mi as PWA_DISPLAY_MODES,Yt as ProductDeclarationSchema,ii as ProductDeclarationsSchema,id as ProxiedImageUrlSchema,Bi as ROUTE_SOURCES,_i as STORAGE_SCOPES,Fi as STORAGE_TYPES,Ba as STRIPE_EVENTS,oe as STRIPE_MODES,Yo as SUBSCRIPTION_DURATIONS,G as SUBSCRIPTION_STATUS,ye as SUBSCRIPTION_TIERS,er as SendEmailRequestSchema,tr as SendEmailResponseSchema,Ct as ServerUtils,Fe as SingletonManager,Jt as StripeBackConfigSchema,zt as StripeFrontConfigSchema,Zt as StripeOrderBackSchema,Qt as StripeOrderShippingSchema,Xt as StripeOrderTaxSchema,Wt as StripePaymentSchema,Kt as StripeSubscriptionSchema,et as SubscriptionClaimsSchema,Je as SubscriptionDataSchema,ao as TECHNICAL_FIELD_NAMES,A as USER_ROLES,Se as UserSubscriptionSchema,qi as VISIBILITY,tt as WebhookEventSchema,J as addMonths,Le as addYears,Yn as addressSchema,Xn as arraySchema,C as baseFields,It as booleanSchema,_n as calculateSubscriptionEndDate,ke as captureErrorToSentry,gs as checkGitHubAccessSchema,nn as clearGlobalSingleton,lc as clearSchemaGenerators,Qc as clearScopeProviders,X as commonErrorCodeMappings,Oe as compactToISOString,un as configureProviders,sn as createAsyncSingleton,zo as createDefaultSubscriptionClaims,Ti as createDefaultUserProfile,ta as createEntitySchema,D as createErrorHandler,Dr as createMetadata,ln as createMethodProxy,$c as createSchemas,on as createSingleton,an as createSingletonWithParams,W as dateSchema,_c as defineEntity,oa as deleteEntitySchema,td as detectBulkCollisions,Ie as detectErrorSource,hs as disconnectOAuthSchema,$n as emailSchema,oc as enhanceSchema,Ir as ensureSpreadable,V as evaluateCondition,In as evaluateFieldConditions,fs as exchangeTokenSchema,At as fileSchema,kt as filesSchema,Sn as filterVisibleFields,Ur as formatCurrency,ht as formatDate,qr as formatRelativeTime,ro as gdprConsentSchema,bt as generateCodeChallenge,yt as generateCodeVerifier,Kr as generateFirestoreRuleCondition,zr as generatePKCEPair,On as generateUUID,Kn as geopointSchema,nr as getBreakpointFromWidth,Ja as getBreakpointUtils,Ic as getCollectionName,kn as getConditionDependencies,ys as getConnectionsSchema,vt as getCurrencyLocale,Nr as getCurrencySymbol,Mr as getCurrentTimestamp,ra as getEntitySchema,_e as getGlobalSingleton,Z as getListCardFieldNames,cn as getProvider,sc as getRegisteredSchemaTypes,Xc as getRegisteredScopeProviders,tn as getRoleFromClaims,te as getSchemaType,Yc as getScopeValue,Me as getVisibleFields,Vr as getWeekFromISOString,sd as getWidget,sr as githubPermissionSchema,Ce as githubRepoConfigSchema,ps as grantGitHubAccessSchema,R as handleError,ac as hasCustomSchemaGenerator,io as hasMetadata,dn as hasProvider,xn as hasRestrictedVisibility,ue as hasRoleAccess,zc as hasScopeProvider,rn as hasTierAccess,eo as ibanSchema,ks as isAuthPartnerId,Oc as isBackendGeneratedField,Za as isBreakpoint,De as isCompactDateString,Tt as isFieldVisible,wc as isFrameworkField,Ps as isOAuthPartnerId,Xr as isPKCESupported,Fr as isoToCompactString,en as lazyImport,ia as listEntitiesSchema,ld as listWidgets,zn as mapSchema,B as mapToDoNotDevError,Yr as maybeTranslate,Qn as multiselectSchema,Pt as neverSchema,_r as normalizeToISOString,H as numberSchema,Go as overrideFeatures,Ko as overridePaymentModes,jo as overridePermissions,Wo as overrideSubscriptionStatus,$o as overrideSubscriptionTiers,qo as overrideUserRoles,fn as parseAcceptLanguage,Ne as parseDate,Gr as parseDateToNoonUTC,Mn as parseISODate,qn as parseServerCookie,Gn as passwordSchema,Hn as pictureSchema,Wn as picturesSchema,no as priceSchema,jc as rangeOptions,gn as readCookieValue,Zn as referenceSchema,vs as refreshTokenSchema,h as registerSchemaGenerator,Wc as registerScopeProvider,mc as registerUniqueConstraintValidator,ad as registerWidget,pn as resetProviders,vn as resolveLanguage,ms as revokeGitHubAccessSchema,Cr as safeValidate,wn as sanitizeHref,Be as selectSchema,Er as showNotification,Ve as stringSchema,to as switchSchema,Jn as telSchema,me as textSchema,Br as timestampToISOString,jr as toDateOnly,Lr as toISOString,kr as translateArray,wr as translateArrayRange,Or as translateArrayWithIndices,Pr as translateObjectArray,Kc as unregisterScopeProvider,na as updateEntitySchema,hn as updateMetadata,jn as urlSchema,Uo as validateAIChatRequest,Fo as validateAIChatResponse,Is as validateAuthPartners,bi as validateAuthSchemas,vi as validateAuthUser,li as validateBillingSchemas,ud as validateBlock,oi as validateCheckoutSessionMetadata,Zr as validateCodeChallenge,Qr as validateCodeVerifier,Jo as validateCreateCheckoutSessionRequest,ei as validateCreateCheckoutSessionResponse,yi as validateCustomClaims,ge as validateDates,hc as validateDocument,Vn as validateEnvVar,cd as validateEvent,Bn as validateMetadata,As as validateOAuthPartners,ba as validateSendEmailRequest,Ea as validateSendEmailResponse,si as validateStripeBackConfig,ai as validateStripeFrontConfig,ri as validateSubscriptionClaims,ti as validateSubscriptionData,Ut as validateUniqueFields,Ln as validateUrl,hi as validateUserSubscription,ni as validateWebhookEvent,Rr as validateWithSchema,An as when,br as withErrorHandling,Jr as withGracefulDegradation,Un as withTimeout,Tr as wrapAuthError,Sr as wrapCrudError,xr as wrapStorageError};
|