@donotdev/core 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +2 -2
- package/i18n/locales/eager/dndev_ar.json +9 -0
- package/i18n/locales/eager/dndev_da.json +9 -0
- package/i18n/locales/eager/dndev_de.json +9 -0
- package/i18n/locales/eager/dndev_en.json +9 -0
- package/i18n/locales/eager/dndev_es.json +9 -0
- package/i18n/locales/eager/dndev_fr.json +9 -0
- package/i18n/locales/eager/dndev_it.json +9 -0
- package/i18n/locales/eager/dndev_ja.json +9 -0
- package/i18n/locales/eager/dndev_ko.json +9 -0
- package/i18n/locales/eager/dndev_nl.json +9 -0
- package/i18n/locales/eager/dndev_pl.json +9 -0
- package/i18n/locales/eager/dndev_pt.json +9 -0
- package/i18n/locales/eager/dndev_zh.json +9 -0
- package/i18n/locales/lazy/crud_ar.json +51 -2
- package/i18n/locales/lazy/crud_da.json +50 -2
- package/i18n/locales/lazy/crud_de.json +51 -2
- package/i18n/locales/lazy/crud_en.json +50 -2
- package/i18n/locales/lazy/crud_es.json +53 -3
- package/i18n/locales/lazy/crud_fr.json +53 -3
- package/i18n/locales/lazy/crud_it.json +53 -3
- package/i18n/locales/lazy/crud_ja.json +51 -2
- package/i18n/locales/lazy/crud_ko.json +51 -2
- package/i18n/locales/lazy/crud_nl.json +50 -2
- package/i18n/locales/lazy/crud_pl.json +52 -2
- package/i18n/locales/lazy/crud_pt.json +52 -3
- package/i18n/locales/lazy/crud_zh.json +50 -2
- package/index.d.ts +4823 -2947
- package/index.js +5 -5
- package/next/index.d.ts +10 -0
- package/next/index.js +138 -131
- package/package.json +2 -2
- package/server.d.ts +4659 -2895
- package/server.js +1 -1
- package/symbol-index.json +1 -1
- package/vite/index.d.ts +10 -0
- package/vite/index.js +44 -43
package/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ut=Object.defineProperty;var En=(e,t,n)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Sn=(e,t)=>{for(var n in t)ut(e,n,{get:t[n],enumerable:!0})};var T=(e,t,n)=>En(e,typeof t!="symbol"?t+"":t,n);var tn={};Sn(tn,{AuthHardening:()=>ke,CURRENCY_MAP:()=>Ge,ConditionBuilder:()=>Y,DEFAULT_CRUD_TIMEOUT:()=>No,DEFAULT_ERROR_MESSAGES:()=>V,DEFAULT_UPLOAD_TIMEOUT:()=>Do,DoNotDevError:()=>R,FIELD_TEXT_FORMATTERS:()=>Vt,LANGUAGE_COOKIE:()=>co,SESSION_RENDER_SEGMENT:()=>Qt,SingletonManager:()=>K,TRANSLATABLE_FIELD_TYPES:()=>Te,addMonths:()=>ue,addYears:()=>tt,buildProductJsonLd:()=>Br,calculateSubscriptionEndDate:()=>Uo,captureErrorToSentry:()=>qe,clearGlobalSingleton:()=>Zr,commonErrorCodeMappings:()=>oe,compactToISOString:()=>He,configureProviders:()=>ro,createAsyncSingleton:()=>to,createErrorHandler:()=>_,createMetadata:()=>vr,createMethodProxy:()=>no,createSingleton:()=>Jr,createSingletonWithParams:()=>eo,deriveEntitySeo:()=>Lr,detectErrorSource:()=>Ve,ensureSpreadable:()=>cr,evaluateCondition:()=>j,evaluateFieldConditions:()=>Ao,filterVisibleFields:()=>So,formatCurrency:()=>se,formatDate:()=>_t,formatFieldText:()=>Xe,formatRelativeTime:()=>Rr,generateCodeChallenge:()=>Wt,generateCodeVerifier:()=>Ht,generateFirestoreRuleCondition:()=>qr,generatePKCEPair:()=>Gr,generateUUID:()=>Po,getConditionDependencies:()=>Io,getCurrencyLocale:()=>Ft,getCurrencySymbol:()=>hr,getCurrentTimestamp:()=>Er,getGlobalSingleton:()=>ae,getListCardFieldNames:()=>le,getProvider:()=>oo,getRoleFromClaims:()=>Xr,getTranslatedFieldNames:()=>ao,getVisibleFields:()=>et,getWeekFromISOString:()=>Tr,handleError:()=>A,hasProvider:()=>io,hasRestrictedVisibility:()=>xo,hasRoleAccess:()=>Se,hasTierAccess:()=>Qr,i18nFieldName:()=>Re,isCompactDateString:()=>We,isEmptyFieldValue:()=>ze,isFieldVisible:()=>Zt,isMultilingual:()=>Ce,isPKCESupported:()=>Hr,isoToCompactString:()=>yr,languageUrls:()=>fo,lazyImport:()=>zr,localizePath:()=>Je,mapToDoNotDevError:()=>$,maybeTranslate:()=>jr,normalizeToISOString:()=>br,parseAcceptLanguage:()=>mo,parseDate:()=>Ke,parseDateToNoonUTC:()=>Ar,parseISODate:()=>Mo,parseServerCookie:()=>$o,publicPathname:()=>go,readCookieValue:()=>po,resetProviders:()=>so,resolveLanguage:()=>Qe,resolveLanguageRoute:()=>vo,safeValidate:()=>ur,sanitizeHref:()=>Oo,showNotification:()=>or,splitLanguagePath:()=>Ze,stripHtmlTags:()=>ye,timestampToISOString:()=>xr,toDateOnly:()=>kr,toISOString:()=>Sr,translateArray:()=>pr,translateArrayRange:()=>gr,translateArrayWithIndices:()=>fr,translateEntityLabel:()=>he,translateObjectArray:()=>mr,translateRow:()=>uo,updateMetadata:()=>ho,validateCodeChallenge:()=>Kr,validateCodeVerifier:()=>Wr,validateEnvVar:()=>Vo,validateMetadata:()=>Bo,validateUrl:()=>Lo,validateWithSchema:()=>lr,when:()=>ko,withErrorHandling:()=>rr,withGracefulDegradation:()=>Yr,withTimeout:()=>Fo,wrapAuthError:()=>ar,wrapCrudError:()=>ir,wrapStorageError:()=>sr});var N={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},de={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Ai={[N.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"]},[N.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[N.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},ki={maxTokens:4096,temperature:.7,stream:!0},Ii={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"},wi={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"}},Oi=4,Pi={"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 c from"valibot";var ct=c.object({role:c.picklist([de.USER,de.ASSISTANT,de.SYSTEM]),content:c.pipe(c.string(),c.minLength(1)),id:c.optional(c.string()),createdAt:c.optional(c.string())}),Pe=c.lazy(()=>c.object({type:c.picklist(["string","number","boolean","array","object"]),description:c.optional(c.string()),enum:c.optional(c.array(c.string())),items:c.optional(Pe),properties:c.optional(c.record(c.string(),Pe)),required:c.optional(c.array(c.string()))})),xn=c.object({description:c.pipe(c.string(),c.minLength(1)),parameters:c.object({type:c.literal("object"),properties:c.record(c.string(),Pe),required:c.optional(c.array(c.string()))})}),Tn=c.object({id:c.string(),name:c.string(),args:c.record(c.string(),c.unknown())}),Rn=c.object({messages:c.pipe(c.array(ct),c.minLength(1)),provider:c.optional(c.picklist([N.ANTHROPIC,N.OPENAI,N.GOOGLE])),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string()),stream:c.optional(c.boolean()),tools:c.optional(c.record(c.string(),xn))}),Cn=c.object({promptTokens:c.number(),completionTokens:c.number(),totalTokens:c.number()}),An=c.object({message:ct,usage:c.optional(Cn),finishReason:c.optional(c.string()),toolCalls:c.optional(c.array(Tn))}),Fi=c.object({provider:c.picklist([N.ANTHROPIC,N.OPENAI,N.GOOGLE]),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string())});function _i(e){return c.safeParse(Rn,e)}function Ui(e){return c.safeParse(An,e)}var w={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function qi(e){Object.assign(w,e)}var De={FREE:"free",PRO:"pro",PREMIUM:"premium"};function ji(e){Object.assign(De,e)}var Ne={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Gi(e){Object.assign(Ne,e)}var Fe={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 Hi(e){Object.assign(Fe,e)}import*as l from"valibot";var W={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Ki(e){Object.assign(W,e)}var pe={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Yi(e){Object.assign(pe,e)}var zi={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Xi(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var dt={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}},Qi={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as o from"valibot";function F(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}var pt=100,kn=o.object({productId:o.pipe(o.string(),o.minLength(1),o.maxLength(200)),quantity:o.pipe(o.number(),o.integer(),o.minValue(1),o.maxValue(1e4))}),ft=o.pipe(o.object({billingConfigKey:o.optional(o.pipe(o.string(),o.minLength(1))),lineItems:o.optional(o.pipe(o.array(kn),o.minLength(1,"At least one line item is required"),o.maxLength(pt,`At most ${pt} line items`))),successUrl:o.pipe(o.string(),o.url()),cancelUrl:o.pipe(o.string(),o.url()),customerEmail:o.optional(o.pipe(o.string(),o.email())),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),userId:o.optional(o.string()),productId:o.optional(o.string()),priceId:o.optional(o.string()),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code"))),userEmail:o.optional(o.pipe(o.string(),o.email())),mode:o.optional(o.picklist([pe.PAYMENT,pe.SUBSCRIPTION]))}),o.rawTransform(({dataset:e,addIssue:t,NEVER:n})=>{let r=e.value,i=r.billingConfigKey||r.metadata?.billingConfigKey;return i?{...r,billingConfigKey:i,lineItems:r.lineItems??[{productId:i,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),vt=o.object({sessionId:o.string(),sessionUrl:o.nullable(o.pipe(o.string(),o.url()))}),ht=o.object({userId:o.string(),tier:o.string(),status:o.picklist(F(W)),subscriptionId:o.nullable(o.string()),customerId:o.string(),subscriptionEnd:o.nullable(o.pipe(o.string(),o.isoTimestamp())),cancelAtPeriodEnd:o.boolean(),updatedAt:o.pipe(o.string(),o.isoTimestamp())}),yt=o.object({tier:o.string(),subscriptionId:o.nullable(o.string()),customerId:o.string(),status:o.picklist(F(W)),subscriptionEnd:o.nullable(o.pipe(o.string(),o.isoTimestamp())),cancelAtPeriodEnd:o.boolean(),updatedAt:o.pipe(o.string(),o.isoTimestamp()),isDefault:o.optional(o.boolean())}),bt=o.object({id:o.string(),type:o.string(),data:o.object({object:o.any()}),created:o.pipe(o.string(),o.isoTimestamp())}),Et=o.looseObject({userId:o.optional(o.string()),firebaseUid:o.optional(o.string()),productType:o.optional(o.string())});function ns(e){return o.safeParse(ft,e)}function rs(e){return o.safeParse(vt,e)}function os(e){return o.safeParse(ht,e)}function is(e){return o.safeParse(yt,e)}function ss(e){return o.safeParse(bt,e)}function as(e){return o.safeParse(Et,e)}var In=o.object({type:o.literal("StripePayment"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.optional(o.pipe(o.string(),o.minLength(1,"Stripe price ID is required"))),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.pipe(o.string(),o.minLength(1,"Duration is required")),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),wn=o.object({type:o.literal("StripeSubscription"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.pipe(o.string(),o.minLength(1,"Stripe price ID is required")),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),On=o.variant("type",[In,wn]),ls=o.record(o.string(),On),Pn=o.record(o.string(),o.object({name:o.string(),price:o.string(),currency:o.string(),description:o.optional(o.string()),features:o.optional(o.array(o.string())),priceId:o.optional(o.string()),allowPromotionCodes:o.optional(o.boolean())})),mt={name:o.string(),price:o.number(),currency:o.string(),priceId:o.optional(o.string()),tier:o.string(),duration:o.string(),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean())},Dn=o.variant("mode",[o.object({mode:o.literal("manual"),taxRateIds:o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.minLength(1))}),o.object({mode:o.literal("automatic")})]),gt=5,Nn=o.object({allowedCountries:o.pipe(o.array(o.pipe(o.string(),o.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),o.minLength(1)),shippingRateIds:o.optional(o.pipe(o.array(o.pipe(o.string(),o.minLength(1))),o.maxLength(gt,`shippingRateIds: at most ${gt} (Stripe limit)`)))}),Fn=o.object({type:o.literal("StripeOrder"),name:o.string(),currency:o.pipe(o.string(),o.length(3)),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),tax:Dn,taxIdCollection:o.picklist(["disabled","optional","required"]),billingAddressCollection:o.picklist(["auto","required"]),shipping:o.optional(Nn),customerCreation:o.picklist(["always","if_required"]),invoiceCreation:o.boolean(),paymentMethodConfiguration:o.optional(o.pipe(o.string(),o.minLength(1)))}),_n=o.record(o.string(),o.variant("type",[o.object({type:o.literal("StripePayment"),...mt}),o.object({type:o.literal("StripeSubscription"),...mt}),Fn]));function us(e){return o.parse(Pn,e)}function cs(e){return o.parse(_n,e)}function ds(){let e={createCheckoutSessionRequest:o.safeParse(ft,{}),createCheckoutSessionResponse:o.safeParse(vt,{}),subscriptionData:o.safeParse(ht,{}),subscriptionClaims:o.safeParse(yt,{}),webhookEvent:o.safeParse(bt,{}),checkoutSessionMetadata:o.safeParse(Et,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var St=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(F(w))),customClaims:l.optional(l.record(l.string(),l.any()))}),_e=l.object({userId:l.string(),tier:l.picklist(F(De)),status:l.picklist(F(W)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),xt=l.object({role:l.optional(l.picklist(F(w))),subscription:l.optional(_e),features:l.optional(l.array(l.picklist(F(Ne)))),permissions:l.optional(l.array(l.picklist(F(Fe)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function Es(e){return l.safeParse(St,e)}function Ss(e){return l.safeParse(_e,e)}function xs(e){return l.safeParse(xt,e)}function Ts(){let e={authUser:l.safeParse(St,{}),userSubscription:l.safeParse(_e,{}),customClaims:l.safeParse(xt,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Cs={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},As={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function ks(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var Fs={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},_s={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},Us={CLIENT:"client",SERVER:"server",BUILD:"build"},Ms={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},Ls={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Bs={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},Vs={USER:"user",GLOBAL:"global",SESSION:"session"},$s={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},qs={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},js={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var Hs={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},me={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},Ue={create:"admin",read:"guest",update:"admin",delete:"admin"},B={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},Ws={ASC:"asc",DESC:"desc"},Ks={LIST:"list",LIST_CARD:"listCard"},Ys=["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 Qs={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Zs={EQ:B.EQ,NEQ:B.NEQ,LT:B.LT,LTE:B.LTE,GT:B.GT,GTE:B.GTE};var Tt=class extends Error{constructor(n,r){super(`BulkCollisionError: ${n.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${n.join(", ")}`);T(this,"collidingIds");T(this,"where");this.name="BulkCollisionError",this.collidingIds=n,this.where=r}},Rt=class extends Error{constructor(n){super(`[dndev] bulkAcross: circular dependency: ${n.join(" \u2192 ")}`);T(this,"cycle");this.name="BulkAcrossCycleError",this.cycle=n}},Ct=class extends Error{constructor(n){super(`BulkNotImplementedError: adapter "${n}" has not implemented bulk() yet`);T(this,"adapterName");this.name="BulkNotImplementedError",this.adapterName=n}};import*as m from"valibot";var sa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),data:m.record(m.string(),m.unknown()),idempotencyKey:m.optional(m.string())}),aa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),la=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required")),data:m.record(m.string(),m.unknown()),merge:m.optional(m.boolean(),!1)}),ua=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),ca=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),limit:m.optional(m.pipe(m.number(),m.minValue(1),m.maxValue(1e3)),1e3),offset:m.optional(m.pipe(m.number(),m.minValue(0)),0),orderBy:m.optional(m.string()),orderDirection:m.optional(m.picklist(["asc","desc"]),"desc"),where:m.optional(m.array(m.object({field:m.string(),operator:m.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:m.unknown()})))});var Sa={RESEND:"resend"},xa={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 Un=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())}),Mn=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function Ra(e){return E.safeParse(Un,e)}function Ca(e){return E.safeParse(Mn,e)}var re={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"},Pa={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},ge={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Me={[re.PERMISSION_DENIED]:{type:ge.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[re.NOT_FOUND]:{type:ge.NOT_FOUND,message:"The requested resource was not found"},[re.ALREADY_EXISTS]:{type:ge.ALREADY_EXISTS,message:"The resource already exists"},[re.INVALID_ARGUMENT]:{type:ge.VALIDATION_ERROR,message:"Invalid argument provided"}},At=class extends Error{constructor(n,r,i){super(r);T(this,"type");T(this,"originalError");this.name="EntityHookError",this.type=n,this.originalError=i}},Da={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"};function Ln(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}var R=class e extends Error{constructor(n,r=re.INTERNAL,i){super(n);T(this,"code");T(this,"details");T(this,"source");T(this,"originalError");T(this,"context");T(this,"displayable");T(this,"userMessageProvided");Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.userMessageProvided,this.name=this.constructor.name,Ln(Error)&&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 Ma={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 Ba={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 $a={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 ja={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 Ha={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 Le={mobile:0,tablet:768,laptop:1024,desktop:1440},Bn={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function Vn(e){return e>=Le.desktop?"desktop":e>=Le.laptop?"laptop":e>=Le.tablet?"tablet":"mobile"}function ol(e,t){let n=Bn[t];return e>=n.min&&e<=n.max}function il(e,t){let n=Vn(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 $n="landing",qn={FIXED:"fixed",SCROLL:"scroll"},jn={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var kt=["pull","push","admin","maintain","triage"];import"valibot";import*as d from"valibot";var Be=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"))}),Gn=d.picklist([...kt]),yl=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:Be,permission:d.optional(Gn,"push"),customClaims:d.optional(d.record(d.string(),d.any()))}),bl=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:Be}),El=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:Be}),Sl=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()))}),xl=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"))}),Tl=d.object({provider:d.string()}),Rl=d.object({userId:d.pipe(d.string(),d.minLength(1,"User ID is required"))});var Ol={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 g from"valibot";var It=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),Hn=g.object({...It.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),fe=g.union([g.literal(""),g.pipe(g.string(),g.url())]),Wn=g.object({authUrl:fe,tokenUrl:fe,profileUrl:fe,revokeUrl:g.optional(fe)}),Kn=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Yn=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),zn=g.object({...It.entries,type:g.picklist(["oauth","both"]),scopes:Kn,endpoints:Wn,capabilities:Yn}),wt={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"}}},Ot={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"}}},Xn=g.record(g.string(),Hn),Qn=g.record(g.string(),zn);function Dl(){return g.safeParse(Xn,wt)}function Nl(){return g.safeParse(Qn,Ot)}function Fl(e){return e in wt}function _l(e){return e in Ot}var Pt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Hl={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Wl={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Pt.ANALYTICS},marketing:{requiresConsent:Pt.MARKETING}};function Ve(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 Nt from"valibot";function _(e){return(t,n)=>{if(t instanceof R)return t;if(typeof t!="object"||t===null){let p=typeof t=="string"?t:e.defaultErrorMessage;return new R(n||p,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let r;e.extractErrorCode?r=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(r=t.code);let i=e.defaultErrorCode;r&&e.errorCodeMapping&&r in e.errorCodeMapping&&(i=e.errorCodeMapping[r]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),r&&e.friendlyMessageMapping&&r in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[r]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},r&&(a.originalCode=r)),"originalError"in a||(a.originalError=t),new R(n||s,i,{details:a,source:e.errorSource})}}var oe={"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 V={"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."},Zn={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"},$e={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function Jn(e){return e in $e}var M={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",...oe},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",...oe},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(Zn).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};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:oe,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:V.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:V["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:V.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},er=e=>e instanceof Nt.ValiError?new R(V["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):_(M.validation)(e),tr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&Jn(e.type)){let t=$e[e.type]||"unknown";return new R(e.message||V[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Me[e.code]){let t=Me[e.code];if(t){let n=$e[t.type]||"unknown";return new R(t.message||V[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return _(M.entity)(e)},Dt={auth:_(M.auth),oauth:_(M.oauth),api:_(M.api),firebase:_(M.firebase),ui:_(M.ui),validation:er,entity:tr,unknown:_(M.unknown)};function $(e,t,n){return e instanceof R?e:(Dt[t]||Dt.unknown)(e,n)}function qe(e,t,n={}){let r=globalThis.Sentry;r&&r.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{i.setExtra(s,a)}catch{i.setExtra(s,`[${typeof a}]`)}}),Object.entries(n).forEach(([s,a])=>{if(typeof a!="function")try{i.setExtra(`context.${s}`,a)}catch{i.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||n.userId)&&i.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),r.captureException(e)})}function nr(){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?(process.env.NODE_ENV||"development").toLowerCase()!=="production":!1}function A(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:r,context:i={},log:s=!0,reportToSentry:a=!0,showNotification:p=!1,severity:f="error"}=n,h=Ve(e),v=e instanceof R?e:$(e,h,r);if(r&&!v.userMessageProvided&&(v.message.includes("Error")||v.message.includes("Failed")||v.message.length<10?v=new R(r,v.code,{details:{...v.details,originalMessage:v.message},source:h,userMessageProvided:!0}):v=new R(v.message,v.code,{details:{...v.details,userMessage:r},source:h,userMessageProvided:!0})),s){let C=nr()||typeof window<"u"&&window.__DNDEV_DEBUG,te={code:v.code,message:v.message,source:h};switch(f){case"warning":break;case"info":break;case"success":break;default:}}return a&&qe(v,h,i),v}function rr(e,t){return async(...n)=>{try{return await e(...n)}catch(r){throw A(r,t)}}}function or(e,t="info",n){let r=Date.now().toString();return r}function ir(e,t,n,r,i){if(e instanceof R)return e;let{code:s}=$(e,"api");return new R("Request failed.",s,{source:"api",details:{context:`${t}.${n}(${r}${i?`, ${i}`:""})`,originalMessage:je(e),originalError:e}})}function sr(e,t,n,r){let i=`${t}.${n}(${r})`;return $(e,"api",`${i}: ${je(e)}`)}function ar(e,t,n,r){let i=r?` ${JSON.stringify(r)}`:"",s=`${t}.${n}(${i})`,a=$(e,"auth",`${s}: ${je(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new R(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function je(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as ie from"valibot";function lr(e,t,n){try{return ie.parse(e,t)}catch(r){throw r instanceof ie.ValiError?new R(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:t},source:"validation"}):new R(`Unexpected validation error in ${n}: ${dr(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function ur(e,t){try{return ie.parse(e,t)}catch{return null}}function cr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function dr(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function pr(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(p,f)=>{let h=`${t}.${f}`;return e(h)}).filter((p,f)=>{let h=`${t}.${f}`;return!(p===h||s&&p.trim()===""||p.length<i||a&&!a(p,f))})}function mr(e,t,n,r){return Array.from({length:n},(i,s)=>{let a=`${t}.${s}.${String(r[0])}`;if(e(a)===a)return null;let f={};for(let h of r){let v=`${t}.${s}.${String(h)}`;f[h]=e(v)}return f}).filter(i=>i!==null)}function gr(e,t,n,r,i={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:p}=i;return Array.from({length:r-n},(f,h)=>{let v=n+h,C=`${t}.${v}`;return e(C)}).filter((f,h)=>{let v=n+h,C=`${t}.${v}`;return!(f===C||a&&f.trim()===""||f.length<s||p&&!p(f,v))})}function fr(e,t,n,r={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(p,f)=>{let h=`${t}.${f}`;return{item:e(h),originalIndex:f}}).filter(({item:p,originalIndex:f})=>{let h=`${t}.${f}`;return!(p===h||s&&p.trim()===""||p.length<i||a&&!a(p,f))})}function vr(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var Ge={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 Ft(e){return Ge[e]?.locale??"en-US"}function hr(e){return!e||typeof e!="string"?e??"":Ge[e]?.symbol??e}function se(e,t,n={}){if(e==null||isNaN(e))return"";let r=Ft(t);return new Intl.NumberFormat(r,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...n}).format(e)}function He(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],r=t[2],i=t[3],s=t[4],a=t[5],p=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(s,10),parseInt(a,10));if(isNaN(p.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return p.toISOString()}function yr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${n}${r}${i}:${s}${a}`}function We(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function br(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(We(e))return He(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&&typeof e.toDate=="function")return e.toDate().toISOString();throw new Error(`Unsupported date type: ${typeof e}`)}function Er(){return new Date().toISOString()}function Sr(e){return e.toISOString()}function xr(e){return new Date(e).toISOString()}function Tr(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),r=Math.floor((t.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${t.getFullYear()}`}var D={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Rr(e,t="en",n={}){if(!e)return"";let{style:r="long",numeric:i="auto",fallbackThreshold:s=D.WEEK}=n,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let p=new Date,f=a.getTime()-p.getTime(),h=Math.round(f/1e3),v=Math.abs(h);if(v>s)return _t(a.toISOString(),t);let C=new Intl.RelativeTimeFormat(t,{style:r,numeric:i});return v<D.MINUTE?C.format(h,"second"):v<D.HOUR?C.format(Math.round(h/D.MINUTE),"minute"):v<D.DAY?C.format(Math.round(h/D.HOUR),"hour"):v<D.WEEK?C.format(Math.round(h/D.DAY),"day"):v<D.MONTH?C.format(Math.round(h/D.WEEK),"week"):v<D.YEAR?C.format(Math.round(h/D.MONTH),"month"):C.format(Math.round(h/D.YEAR),"year")}function Cr(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 _t(e,t="en",n="long"){if(!e)return"";let r;if(e instanceof Date)r=e;else if(typeof e=="string")r=new Date(e);else if(typeof e=="number")r=new Date(e);else if(typeof e=="object"&&"toDate"in e)r=e.toDate();else return"";if(isNaN(r.getTime()))return"";let i=typeof n=="string"?Cr(n):n;return new Intl.DateTimeFormat(t,i).format(r)}function Ke(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(We(t))try{return He(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&&typeof e.toDate=="function")try{let t=e.toDate();return isNaN(t.getTime())?void 0:t.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,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function Ar(e){let t=Ke(e);if(!t)return;let n=new Date(t);return n.setUTCHours(12,0,0,0),n.toISOString()}function kr(e){let t=Ke(e);return t&&t.split("T")[0]||""}function ze(e){return e==null||e===""}function he(e,t){if(!e.includes(":"))return t(e);let[n,r=e]=e.split(":");if(r.startsWith("status.")){let i=t(r);if(i!==r&&i!==`${n}:${r}`)return i}return t(r,{ns:n})}function ye(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function Bt(e){let t=e.validation?.options;return Array.isArray(t)?t:void 0}function ve(e,t,n){let r=Bt(t)?.find(i=>i.value===e)?.label;return r?he(r,n):String(e)}function Ye(e){return e instanceof Date?e:new Date(e)}var Ut=(e,t,n,{locale:r})=>Ye(e).toLocaleString(r),U=e=>String(e),Mt=e=>e?"Yes":"No",Lt=(e,t,n,{locale:r})=>typeof e=="number"?e.toLocaleString(r):String(e),Vt={timestamp:Ut,"datetime-local":Ut,date:(e,t,n,{locale:r})=>Ye(e).toLocaleDateString(r),time:(e,t,n,{locale:r})=>Ye(e).toLocaleTimeString(r),week:U,month:U,boolean:Mt,checkbox:Mt,switch:(e,t,n)=>{let r=t.options?.fieldSpecific;if(r){let i=r.uncheckedValue??!1,s=r.checkedValue??!0;if(e===s&&r.checkedLabel)return he(r.checkedLabel,n);if(e===i&&r.uncheckedLabel)return he(r.uncheckedLabel,n)}return e?"Yes":"No"},year:U,number:Lt,range:Lt,currency:(e,t)=>{if(Number.isNaN(Number(e)))return"";let n=t.options?.fieldSpecific;return se(Number(e),n?.currency||"EUR")},price:(e,t,n)=>{let r=typeof e=="number"?{amount:e,currency:"EUR",vatIncluded:!0,discountPercent:0}:e;if(!r||typeof r!="object")return"";let i=r.amount;if(ze(i)||Number.isNaN(Number(i)))return"";let s=r.currency||"EUR",a=r.discountPercent??0,p=r.vatIncluded??!0?` ${n("crud:price.vatIncluded",{defaultValue:"VAT Incl."})}`:"";if(a>0){let f=Number(i)*(1-a/100),h=` ${n("crud:price.discountPercent",{percent:Math.round(a),defaultValue:"-{{percent}}%"})}`;return`${se(f,s)}${p}${h}`}return`${se(Number(i),s)}${p}`},duration:(e,t,n)=>{let r=typeof e=="number"?e:parseInt(String(e),10);if(Number.isNaN(r))return"";if(r===0)return n("crud:duration.zero",{defaultValue:"\u2014"});if(r<60)return n("crud:duration.minutes",{count:r,defaultValue:`${r} min`});let i=Math.floor(r/60),s=r%60;return n("crud:duration.hoursMinutes",{hours:i,minutes:s,defaultValue:s===0?`${i}h`:`${i}h ${s}min`})},gdprConsent:(e,t,n,{locale:r})=>{if(!e||typeof e!="object")return"";let i=e;if(i.gdprConsent!==!0)return n("crud:gdprConsent.display.no",{defaultValue:"Not consented"});let s=[n("crud:gdprConsent.display.yes",{defaultValue:"Consented"})];return i.gdprConsentDate&&s.push(new Date(i.gdprConsentDate).toLocaleDateString(r)),i.gdprConsentVersion&&s.push(`v${i.gdprConsentVersion}`),s.join(" \xB7 ")},select:ve,radio:ve,combobox:ve,multiselect:(e,t,n)=>Array.isArray(e)&&Bt(t)?e.map(r=>ve(r,t,n)).join(", "):String(e),reference:e=>{if(e&&typeof e=="object"){let t=e;return String(t.displayName||t.name||t.id||e)}return String(e)},geopoint:e=>{if(e&&typeof e=="object"&&"lat"in e&&"lng"in e){let{lat:t,lng:n}=e;return`${t.toFixed(6)}, ${n.toFixed(6)}`}return""},address:e=>e&&typeof e=="object"&&"formatted_address"in e?String(e.formatted_address):String(e),array:e=>Array.isArray(e)?e.join(", "):"","field-array":(e,t)=>{if(!Array.isArray(e))return"";let n=t.options?.fieldSpecific?.fields;return e.map(r=>{if(typeof r!="object"||r==null)return"";let i=r;return(n?n.map(a=>a.name):Object.keys(i)).map(a=>i[a]).filter(a=>a!=null&&a!=="").map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" \xB7 ")}).filter(Boolean).join(", ")},password:()=>"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",text:U,textarea:U,email:U,tel:U,url:U,color:U,iban:U,richtext:e=>ye(String(e))};function Xe(e,t,n,r={}){let i=t.options?.displayValue;if(i&&r.item)return i(e,r.item,n);if(ze(e))return null;let s=r.formatter??Vt[t.type],a=s?s(e,t,n,{locale:r.locale}):typeof e=="object"?null:String(e);if(a===null||a==="")return null;let p=t.options?.displayKey;if(!p)return a;let f=(Array.isArray(p)?p:[p]).map(h=>h.replace("{{value}}",a));return n(f,{value:a})}var Ir=160,$t="EUR",wr=new Set(["textarea","richtext"]),jt=new Set(["image","images"]),Or=new Set(["price","currency"]),Pr=" \xB7 ",Dr={available:"InStock"};function q(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function Nr(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${(r>t/2?n.slice(0,r):n).trimEnd()}\u2026`}function qt(e){return(Array.isArray(e)?e:[e]).map(n=>{if(typeof n=="string")return q(n);if(n&&typeof n=="object"&&"fullUrl"in n)return q(n.fullUrl)}).filter(n=>n!==void 0)}function Gt(e){let t=e.listCardFields,n=t?Array.isArray(t)?t:[...t.title??[],...t.subtitle??[],...t.content??[],...t.footer??[]]:[];return[...new Set([...n,...Object.keys(e.fields)])]}function be(e,t,n,r){return n.flatMap(i=>{let s=e.fields[i];if(!s||jt.has(s.type))return[];let a=Xe(t[i],s,r.t,{item:t,locale:r.locale});return a?[a]:[]})}function Fr(e,t,n){let r=e.seo?.title;if(r)return q(r(t,n.t));let i=e.listCardFields;if(i&&!Array.isArray(i)&&i.title?.length){let a=be(e,t,i.title,n);return a.length>0?a.join(i.titleSeparator??" "):void 0}let s=Gt(e).find(a=>e.fields[a]?.type==="text");return s?q(be(e,t,[s],n)[0]):void 0}function _r(e,t,n,r){let i=e.seo?.description;if(i)return q(i(t,r.t));let s=n.find(h=>wr.has(e.fields[h]?.type??"")&&q(t[h])!==void 0);if(s)return ye(String(t[s]));let a=e.listCardFields;if(!a||Array.isArray(a))return;let f=[be(e,t,a.subtitle??[],r).join(" "),...be(e,t,a.content??[],r)].filter(Boolean);return f.length>0?f.join(Pr):void 0}function Ur(e,t){if(typeof t.status!="string")return;let r={...Dr,...e.seo?.availability}[t.status];return r?`https://schema.org/${r}`:void 0}function Mr(e,t){if(e.type==="price"&&t&&typeof t=="object"){let{amount:i,currency:s}=t;return typeof i=="number"&&i>0?{amount:i,currency:q(s)??$t}:void 0}let n=typeof t=="string"?Number(t):t;if(typeof n!="number"||!(n>0))return;let r=e.options?.fieldSpecific;return{amount:n,currency:r?.currency??$t}}function Lr(e,t,n){let r=Gt(e),i=v=>e.fields[v],s=_r(e,t,r,n),a=s?Nr(s,Ir):void 0,p=r.find(v=>jt.has(i(v)?.type??"")&&qt(t[v]).length>0),f=p?qt(t[p]):[],h;for(let v of r){let C=i(v);if(!(!C||!Or.has(C.type))&&(h=Mr(C,t[v]),h))break}return{title:Fr(e,t,n),description:a||void 0,image:f[0],images:f,price:h,availability:Ur(e,t)}}function Br(e,t){return e.title?{"@context":"https://schema.org","@type":"Product",name:e.title,...e.description&&{description:e.description},...e.images.length>0&&{image:e.images},url:t,...e.price&&{offers:{"@type":"Offer",price:e.price.amount,priceCurrency:e.price.currency,...e.availability&&{availability:e.availability},url:t}}}:null}function Vr(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function $r(e){let t=`resource.data.${e.field}`,n=Vr(e.value);return`${t} ${e.op} ${n}`}function qr(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let n=e.publicCondition.map($r).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 jr(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function Ht(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Kt(e)}async function Wt(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Kt(new Uint8Array(r))}async function Gr(){let e=Ht(),t=await Wt(e);return{codeVerifier:e,codeChallenge:t}}function Kt(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Hr(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Wr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function Kr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function Yr(e,t,n){try{return await e()}catch{return t(),!1}}var Ee=new Map;function zr(e,t){if(Ee.has(t))return Ee.get(t);let n=e().catch(r=>{throw Ee.delete(t),r});return Ee.set(t,n),n}var Yt={[w.GUEST]:0,[w.USER]:1,[w.ADMIN]:2,[w.SUPER]:3};function Se(e,t){if(!e)return!1;let n=Yt[e]??-1,r=Yt[t]??1/0;return n>=r}function Xr(e){return e?e.role===w.SUPER||e.isSuper===!0?w.SUPER:e.role===w.ADMIN||e.isAdmin===!0?w.ADMIN:e.role===w.USER?w.USER:e.role||w.USER:w.USER}function Qr(e,t,n){if(!e)return!1;let r=n??dt,i=r[e]?.level??-1,s=r[t]?.level??1/0;return i>=s}var zt="__DNDEV_SINGLETONS__";function Xt(){if(typeof globalThis<"u"){let e=globalThis,t=e[zt];if(t)return t;let n=new Map;return e[zt]=n,n}return new Map}function ae(e,t){let n=Xt();return n.has(e)||n.set(e,t()),n.get(e)}function Zr(e){Xt().delete(e)}function Jr(e,...t){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{r=!1}}}function eo(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 to(e){let t=null,n=!1,r=null;return async function(){if(t!==null)return t;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=e(),t=await r,t}finally{n=!1,r=null}}}function no(e,t){return new Proxy({},{get(n,r){if(t.includes(r)){let s=e(),a=s[r];return typeof a=="function"?a.bind(s):a}return e()[r]}})}var K=class{static async getOrCreate(t,n,r={}){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(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u"&&process.env.NODE_ENV,r.fallbackFactory){let i=r.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"&&process.env.NODE_ENV,r.cacheFailures&&this.initialized.add(t),r.fallbackFactory){let s=r.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()}};T(K,"instances",new Map),T(K,"initializing",new Set),T(K,"initialized",new Set);function xe(){return ae("providers",()=>({providers:null}))}function ro(e){let t=xe();t.providers,t.providers=e}function oo(e){let{providers:t}=xe();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 io(e){return!!xe().providers?.[e]}function so(){xe().providers=null}var Te=["text","textarea","richtext","field-array"];function Re(e){return`${e}I18n`}function ao(e){return Object.keys(e).filter(t=>e[t]?.i18n===!0)}function lo(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function uo(e,t,n){let r=null;for(let i of t){let s=e[Re(i)];if(!s||typeof s!="object")continue;let a=s[n];lo(a)&&(r??(r={...e}),r[i]=a)}return r??e}var co="dndev-lang";function po(e,t){if(!e)return null;for(let n of e.split(";")){let r=n.indexOf("=");if(r!==-1&&n.slice(0,r).trim()===t)try{return decodeURIComponent(n.slice(r+1).trim())}catch{return null}}return null}function mo(e){return e?e.split(",").map((t,n)=>{let[r="",...i]=t.trim().split(";"),s=i.find(p=>p.trim().startsWith("q=")),a=s?Number(s.trim().slice(2)):1;return{tag:r.trim(),quality:Number.isFinite(a)?a: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 Qe({supported:e,fallback:t,stored:n,preferred:r}){if(n&&e.includes(n))return n;for(let i of r??[]){if(e.includes(i))return i;let s=i.split("-")[0];if(s&&e.includes(s))return s}return t}function Ce(e){return e.length>1}var Qt="dndev-session";function go(e){let t=e.split("/"),n=t.indexOf(Qt);return n!==1&&n!==2?e:(t.splice(n,1),t.join("/")||"/")}function Ze(e,t){let n={language:t.defaultLanguage,path:e,prefixed:!1};if(!Ce(t.languages))return n;let r=e.indexOf("/",1),i=r===-1?e.slice(1):e.slice(1,r);return t.languages.includes(i)?{language:i,path:r===-1?"/":e.slice(r),prefixed:!0}:n}function Je(e,t,n){if(!e.startsWith("/")||e.startsWith("//")||!Ce(n.languages))return e;let r=e.search(/[?#]/),i=r===-1?e:e.slice(0,r),s=r===-1?"":e.slice(r),a=Ze(i,n),p=a.prefixed?a.language:t;return p===n.defaultLanguage?`${a.path}${s}`:`/${p}${a.path==="/"?"":a.path}${s}`}function fo(e,t,n){return Object.fromEntries(n.languages.map(r=>[r,`${t}${Je(e,r,n)}`]))}function vo(e,t,n){let r=Ze(e,n);if(!Ce(n.languages))return{type:"pass",language:r.language,path:r.path};if(r.prefixed)return r.language===n.defaultLanguage?{type:"redirect",language:r.language,path:r.path,location:r.path,permanent:!0}:{type:"pass",language:r.language,path:r.path};let i=Qe({supported:n.languages,fallback:n.defaultLanguage,stored:t.stored,preferred:t.preferred});return i!==n.defaultLanguage?{type:"redirect",language:i,path:r.path,location:Je(r.path,i,n),permanent:!1}:{type:"rewrite",language:n.defaultLanguage,path:r.path,destination:`/${n.defaultLanguage}${r.path==="/"?"":r.path}`}}function ho(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function yo(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function bo(e){if(yo(e))return e.visibility}function Zt(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?Se(t,"admin"):n==="owner"?!1:Se(t,n)}function Eo(e,t,n){for(let r of n.ownerFields)if(e[r]===t)return!0;return!1}function et(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return[];let r=e.entries,i=[],{documentData:s,uid:a,ownership:p}=n??{},f=p&&a!=null&&s&&Eo(s,a,p);for(let[h,v]of Object.entries(r)){let C=bo(v);if(C==="owner"){f&&i.push(h);continue}Zt(C,t)&&i.push(h)}return i}function So(e,t,n,r){if(!e)return{};let i=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??e,uid:r.uid,ownership:r.ownership}:void 0,s=et(t,n,i),a={};for(let p of s)Object.prototype.hasOwnProperty.call(e,p)&&(a[p]=e[p]);return a}function le(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function Jt(e){return typeof e=="object"&&e!==null}function Ae(e){if(Jt(e)){if(Jt(e.entries))return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let n=Ae(t);if(n)return n}if(e.wrapped)return Ae(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let n=Ae(t);if(n)return n}}}function xo(e){let t=Ae(e);if(!t)return!1;for(let n of Object.values(t)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}var ke=class{constructor(t={}){T(this,"store",new Map);T(this,"maxAttempts");T(this,"lockoutMs");T(this,"sessionTimeoutMs");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 r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let n=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(t,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(t){for(let[n,r]of this.store)r.lockedUntil!==null&&t>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&t-r.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 To(e,t){if(t.includes(".")){let n=t.split("."),r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}return r}return e[t]}function Ro(e,t){let n=To(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 Co(e){return e instanceof Y||"expression"in e?e.expression:e}function j(e,t){let n=Co(e);if(n.type==="condition")return Ro(n,t);let{logic:r,conditions:i}=n;return r==="and"?i.every(s=>j(s,t)):i.some(s=>j(s,t))}function Ao(e,t){return e?{visible:e.visible?j(e.visible,t):!0,disabled:e.disabled?j(e.disabled,t):!1,required:e.required?j(e.required,t):!1,readonly:e.readonly?j(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var Y=class e{constructor(t){T(this,"expression");this.expression=t}get type(){return this.expression.type}or(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="or"?new e({type:"group",logic:"or",conditions:[...r.conditions,n]}):new e({type:"group",logic:"or",conditions:[r,n]})}and(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="and"?new e({type:"group",logic:"and",conditions:[...r.conditions,n]}):new e({type:"group",logic:"and",conditions:[r,n]})}};function ko(e){function t(n,r){return new Y({type:"condition",field:e,operator:n,value:r})}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 Io(e){let t=e instanceof Y?e.expression:e,n=new Set;function r(i){if(i.type==="condition")n.add(i.field);else for(let s of i.conditions)r(s)}return r(t),n}var wo=new Set(["http:","https:","mailto:","tel:","blob:"]);function Oo(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(wo.has(n.protocol))return t}catch{return t}return""}function Po(){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 Do=3e4,No=15e3;function Fo(e,t,n){if(n?.aborted)return Promise.reject(en(n.reason));let r=t>0;return!r&&!n?e:new Promise((i,s)=>{let a=!1,p;function f(){a=!0,p!==void 0&&(clearTimeout(p),p=void 0),n&&n.removeEventListener("abort",h)}function h(){a||(f(),s(en(n?.reason)))}n&&n.addEventListener("abort",h,{once:!0}),r&&(p=setTimeout(()=>{a||(f(),s(_o(t)))},t)),e.then(v=>{a||(f(),i(v))},v=>{a||(f(),s(v))})})}function _o(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function en(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 ue(e,t){let n=new Date(e),r=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==r&&n.setDate(0),n}function tt(e,t){let n=new Date(e),r=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==r&&n.setDate(0),n}function Uo(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=ue(t,1):e==="3months"?n=ue(t,3):e==="6months"?n=ue(t,6):e==="1year"?n=tt(t,1):e==="2years"?n=tt(t,2):n=ue(t,1),n.toISOString()}function Mo(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function Lo(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 Bo(e){let t={};for(let[n,r]of Object.entries(e)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);if(/<[^>]*>/.test(r))throw new Error(`Metadata value for key '${n}' must not contain HTML`);let i=r;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 Vo(e,t=!0){let n=process.env[e];if(t&&!n)throw new Error(`Required environment variable '${e}' is not set`);return n||""}function $o(e,t){if(!e)return null;let n=`${encodeURIComponent(t)}=`,r=e.split(";");for(let i=0;i<r.length;i++){let s=r[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 Rd(e,t){return Object.assign(e,{metadata:t})}import*as u from"valibot";var ce=new Map;function b(e,t){ce.set(e,t)}function Ad(e){return ce.has(e)}function kd(){return Array.from(ce.keys())}function Id(){ce.clear()}function x(e,t){return t?e:u.nullish(e)}var Ie=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(u.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(u.regex(new RegExp(e.validation.pattern),"Invalid format"));let n=t.length>0?u.pipe(u.string(),...t):u.string();return x(n,e.validation?.required)},qo=e=>{let t=u.pipe(u.string(),u.email("Invalid email address"));return x(t,e.validation?.required)},jo=e=>{let t=e.validation?.minLength!==void 0?u.pipe(u.string(),u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u.string();return x(t,e.validation?.required)},Go=e=>{let t=u.pipe(u.string(),u.url("Invalid URL"));return x(t,e.validation?.required)},z=e=>{let t=[];e.validation?.min!==void 0&&t.push(u.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(u.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let n=t.length>0?u.pipe(u.number(),...t):u.number();return x(n,e.validation?.required)},nn=e=>{let t=u.boolean();return x(t,e.validation?.required)},X=e=>{let t=u.pipe(u.string(),u.check(n=>!isNaN(new Date(n).getTime()),"Invalid date format"));return x(t,e.validation?.required)},an=u.object({url:u.string(),filename:u.string(),size:u.number(),mimeType:u.nullish(u.string()),uploadedAt:u.nullish(u.string())}),rn=e=>{let t=u.nullable(an);return x(t,e.validation?.required)},on=e=>{let t=u.array(an);return x(t,e.validation?.required)},ln=u.object({fullUrl:u.string(),thumbUrl:u.string()}),Ho=e=>{let t=u.union([u.string(),ln]);return x(t,e.validation?.required)},Wo=e=>{let t=u.array(u.union([u.string(),ln]));return x(t,e.validation?.required)},Ko=e=>{let t=u.object({lat:u.number(),lng:u.number()});return x(t,e.validation?.required)},Yo=e=>{let t=u.object({formatted_address:u.string(),latitude:u.number(),longitude:u.number(),street_number:u.nullish(u.string()),route:u.nullish(u.string()),locality:u.nullish(u.string()),administrative_area_level_1:u.nullish(u.string()),administrative_area_level_2:u.nullish(u.string()),country:u.nullish(u.string()),postal_code:u.nullish(u.string())});return x(t,e.validation?.required)},zo=e=>{let t=u.record(u.string(),u.unknown());return x(t,e.validation?.required)},Xo=e=>{let t=u.array(u.unknown());return x(t,e.validation?.required)},nt=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let r=t.map(s=>s.value),i=u.picklist(r);return x(i,e.validation?.required)}let n=u.union([u.string(),u.number()]);return x(n,e.validation?.required)},Qo=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let r=t.map(s=>s.value),i=u.array(u.picklist(r));return x(i,e.validation?.required)}let n=u.array(u.string());return x(n,e.validation?.required)},Zo=e=>{let t=u.pipe(u.string(),u.minLength(1,"Invalid ID format"));return x(t,e.validation?.required)},rt=e=>{let t=u.string();return x(t,e.validation?.required)},Jo=e=>{let t=u.string();return x(t,e.validation?.required)},ei=e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,r=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(t!==void 0&&i.push(u.minLength(t,`IBAN must be at least ${t} characters`)),n!==void 0&&i.push(u.maxLength(n,`IBAN must not exceed ${n} characters`)),r){let a=typeof r=="string"?new RegExp(r):r;i.push(u.regex(a,"Invalid IBAN format"))}let s=i.length>0?u.pipe(u.string(),...i):u.string();return x(s,e.validation?.required)},sn=()=>u.never(),ti=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let r=[t.checkedValue,t.uncheckedValue],i=u.picklist(r);return x(i,e.validation?.required)}let n=u.boolean();return x(n,e.validation?.required)},ni=e=>u.custom(n=>e.validation?.required?typeof n=="object"&&n!==null?"gdprConsent"in n&&n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?"gdprConsent"in n&&n.gdprConsent===!0:!1,"GDPR consent must be given"),ri=e=>{let t=u.object({amount:u.number(),currency:u.optional(u.string()),vatIncluded:u.optional(u.boolean()),discountPercent:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(100)))});return x(t,e.validation?.required)};function oi(){b("text",Ie),b("textarea",Ie),b("richtext",Ie),b("color",Ie),b("email",qo),b("password",jo),b("url",Go),b("tel",Jo),b("iban",ei),b("number",z),b("currency",z),b("price",ri),b("range",z),b("year",z),b("rating",z),b("duration",z),b("boolean",nn),b("checkbox",nn),b("gdprConsent",ni),b("date",X),b("datetime-local",X),b("time",X),b("week",X),b("month",X),b("timestamp",X),b("file",rn),b("files",on),b("document",rn),b("documents",on),b("image",Ho),b("images",Wo),b("geopoint",Ko),b("address",Yo),b("map",zo),b("array",Xo),b("select",nt),b("multiselect",Qo),b("radio",nt),b("combobox",nt),b("switch",ti),b("reference",Zo),b("hidden",rt),b("avatar",rt),b("badge",rt),b("submit",sn),b("reset",sn)}oi();function Q(e){if(e.validation?.schema){let r=e.validation.schema;return x(r,e.validation?.required)}let t=ce.get(e.type);if(t){let r=t(e);if(r!==null)return r}let n=u.unknown();return x(n,e.validation?.required)}var un=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function cn(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function dn(e){return typeof e=="object"&&e!==null}function we(e,t=""){if(Array.isArray(e))e.forEach((n,r)=>{let i=`${t}[${r}]`;if(typeof n=="string"&&cn(n)){if(!un.test(n))throw A(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 dn(n)&&we(n,i)});else if(typeof e=="object"&&e!==null)for(let[n,r]of Object.entries(e)){let i=t?`${t}.${n}`:n;if(typeof r=="string"&&cn(r)){if(!un.test(r))throw A(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else dn(r)&&we(r,i)}}import*as mn from"valibot";var ot={};function Nd(e){ot.uniqueConstraintValidator=e}async function pn(e,t,n){let{uniqueFields:r=[],collection:i}=e.metadata;if(r.length!==0){if(!ot.uniqueConstraintValidator){process.env.NODE_ENV;return}await Promise.all(r.map(async({field:s,errorMessage:a})=>{let p=t[s];if(p==null)return;if(await ot.uniqueConstraintValidator.checkDuplicate(i,s,p,n))throw A(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}}async function Md(e,t,n,r){mn.parse(e,t),we(t),await pn(e,t,r),e.metadata.customValidate&&await e.metadata.customValidate(t,n)}function ii(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Wd(e){if(!ii(e)){let t=e,n=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw A(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return e.metadata.collection}var it=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],Yd="available",zd=["draft","deleted"],gn=["id","createdAt","updatedAt","createdById","updatedById"],si=[...gn,"status"];function Xd(e){return si.some(t=>t===e)}function fn(e){return gn.some(t=>t===e)}var k={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...it]}},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 vn=()=>ae("entity-registry",()=>new Map);function hn(e){vn().set(e.collection,e)}function ai(e){return vn().get(e)}var li=new Set(["__proto__","constructor","prototype"]);function ui(e){for(let t of Object.keys(e.fields))if(li.has(t))throw A(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 ci(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:me.CREATE_ONLY,validation:{required:!0,reference:n}}}function di(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})),r=new Set(e.map(i=>i.value));for(let i of t)r.has(i.value)||n.push(i);return n}function pi(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let n=0;n<e.uniqueKeys.length;n++){let r=e.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw A(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=r.fields.filter(s=>!t.has(s));if(i.length>0)throw A(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 mi(e){let{form:t,fields:n}=e,r=Object.keys(n);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw A(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(f=>f.fields),s=i.filter(f=>!r.includes(f));if(s.length>0)throw A(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 a=new Set(i);r.filter(f=>!a.has(f)).length>0&&process.env.NODE_ENV}t.rules&&t.rules.forEach((i,s)=>{let p=(Array.isArray(i.condition)?i.condition.map(v=>v.field):[i.condition.field]).filter(v=>!r.includes(v));if(p.length>0)throw A(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${p.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${p.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:p,operation:"validateFormConfig"},severity:"error"});let h=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(v=>!r.includes(v));if(h.length>0)throw A(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:h,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([i,s])=>{if(s.dependsOn&&!r.includes(s.dependsOn.field))throw A(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 gi(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 op(e){try{ui(e),mi(e);let t=gi(e),n={...e.fields,...k,...e.fields.createdAt&&{createdAt:{...k.createdAt,...e.fields.createdAt,type:k.createdAt.type,visibility:k.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...k.updatedAt,...e.fields.updatedAt,type:k.updatedAt.type,visibility:k.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...k.createdById,...e.fields.createdById,type:k.createdById.type,visibility:k.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...k.updatedById,...e.fields.updatedById,type:k.updatedById.type,visibility:k.updatedById.visibility}},...e.fields.status&&{status:{...k.status,...e.fields.status,validation:{...k.status.validation,...e.fields.status.validation,options:di(it,e.fields.status.validation?.options)}}},...e.scope&&{[e.scope.field]:ci(e.scope)}};if(e.listFields){let a=new Set(Object.keys(n)),p=e.listFields.filter(f=>!a.has(f));if(p.length>0)throw A(new Error(`Entity '${e.name}' defines listFields that do not exist: ${p.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${p.join(", ")}`,context:{entityName:e.name,invalidFields:p,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let a=new Set(Object.keys(n)),f=le(e).filter(h=>!a.has(h));if(f.length>0)throw A(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${f.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${f.join(", ")}`,context:{entityName:e.name,invalidFields:f,operation:"defineEntity"},severity:"error"})}if(e.uniqueKeys){let a=new Set(Object.keys(n));pi(e,a)}let r={...Ue,...e.access||{}},i=e.namespace||`entity-${e.name.toLowerCase()}`,s={...e,form:t,fields:n,access:r,namespace:i,...e.search&&{search:e.search},...e.defaultSort&&{defaultSort:e.defaultSort}};return hn(s),s}catch(t){throw A(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}import*as I from"valibot";function st(e,t){return!!(t.visibility==="hidden"||t.editable===me.GENERATED||fn(e))}function J(e,t){return Object.assign(e,{visibility:t})}function G(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}function fi(e){let t=Q(e);return J(t,e.visibility)}function vi(e,t){if(!Te.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${Te.join(", ")}.`);let n=Q({...t,validation:{...t.validation,required:!1}});return J(I.optional(I.nullable(I.record(I.string(),n))),t.visibility)}function Z(e,t){for(let n of Object.keys(e)){let r=t[n];r?.i18n===!0&&(e[Re(n)]=vi(n,r))}return e}function at(e){let t=Q({...e,validation:{...e.validation,required:!1}});return J(t,e.visibility)}function cp(e){let t=e.fields,n={};for(let[O,P]of Object.entries(t))P.visibility!=="hidden"&&(n[O]=at(P));let r=G(I.object(Z({...n},t)),e),i={};for(let[O,P]of Object.entries(t))st(O,P)||(i[O]=fi(P));let s=G(I.object(Z({...i},t)),e),a={};for(let[O,P]of Object.entries(t))if(!st(O,P))if(O==="status"){let L=I.literal("draft");a[O]=J(L,P.visibility)}else a[O]=at(P);let p=G(I.object(Z({...a},t)),e),f={};for(let[O,P]of Object.entries(t))st(O,P)||(f[O]=at(P));f.id=J(Q(k.id),"technical");let h=G(I.object(Z({...f},t)),e),v;if(e.listFields&&e.listFields.length>0){let O=["id","status"],P=[...new Set([...O,...e.listFields])];v={};for(let L of P){let ne=n[L];ne&&(v[L]=ne)}}else v=n;let C=G(I.object(Z({...v},t)),e),te,lt=le(e);if(lt.length>0){let O=["id","status"],P=[...new Set([...O,...lt])];te={};for(let L of P){let ne=n[L];ne&&(te[L]=ne)}}else te=n;let yn=G(I.object(Z({...te},t)),e),bn=G(I.object({id:J(Q(k.id),"technical")}),e);return{create:s,draft:p,update:h,get:r,list:C,listCard:yn,delete:bn}}function pp(e,t,n=1,r=!1){let i=[];if(r)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 H=new Map;function gp(e,t){H.has(e)&&process.env.NODE_ENV,H.set(e,t)}function fp(e){H.delete(e)}function vp(e){let t=H.get(e);return t?t():(process.env.NODE_ENV,null)}function hp(e){return H.has(e)}function yp(){return Array.from(H.keys())}function bp(){H.clear()}import*as S from"valibot";var hi=S.record(S.string(),S.unknown()),yi=S.object({id:S.string(),patch:S.record(S.string(),S.unknown())}),bi=S.string(),Sp=S.object({inserts:S.optional(S.array(hi)),updates:S.optional(S.array(yi)),deletes:S.optional(S.array(bi))}),xp=S.object({insertedIds:S.array(S.string()),updatedIds:S.array(S.string()),deletedIds:S.array(S.string())});function Tp(e){let t=new Set((e.updates??[]).map(a=>a.id)),n=e.deletes??[],r=[];for(let a of n)t.has(a)&&r.push(a);if(r.length>0)return{collisions:r,where:"updates-deletes"};let i=e.inserts??[],s=[];for(let a of i)typeof a.id=="string"&&t.has(a.id)&&s.push(a.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as y from"valibot";var kp=y.pipe(y.string(),y.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),Ei=y.picklist(["ephemeral","session","persistent"]),Si=y.object({title:y.optional(y.string()),pinnable:y.optional(y.boolean()),preferredHeight:y.optional(y.pipe(y.number(),y.minValue(0)))}),xi=y.object({id:y.pipe(y.string(),y.minLength(1)),kind:y.pipe(y.string(),y.minLength(1)),lifetime:y.optional(Ei,"ephemeral"),metadata:y.optional(Si),payload:y.unknown()}),Ti=y.object({widgetId:y.pipe(y.string(),y.minLength(1)),action:y.pipe(y.string(),y.minLength(1)),payload:y.unknown()}),ee=new Map;function Ip(e){if(ee.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);ee.set(e.kind,e)}function wp(e){return ee.get(e)}function Op(){return Array.from(ee.values())}function Pp(e,t){let n=y.safeParse(xi,e);if(!n.success)return{ok:!1,reason:`Invalid canvas block envelope: ${Oe(n.issues)}`};let r=ee.get(n.output.kind);if(!r)return{ok:!1,reason:`Unknown widget kind: "${n.output.kind}"`};let i=y.safeParse(r.schema,n.output.payload);if(!i.success)return{ok:!1,reason:`Payload rejected by "${n.output.kind}" schema: ${Oe(i.issues)}`};if(t?.caller!==void 0){let a=t.caller.access;if(!Ri(r.surface,a))return{ok:!1,reason:`surface_forbidden: widget "${n.output.kind}" surface=${r.surface} not reachable by caller access=${a===null?"null":a}`}}return{ok:!0,value:{...n.output,payload:i.output},widget:r}}function Ri(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function Dp(e,t){let n=y.safeParse(Ti,e);if(!n.success)return{ok:!1,reason:`Invalid canvas event envelope: ${Oe(n.issues)}`};let r=ee.get(t);if(!r)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let i=r.actions[n.output.action];if(!i)return{ok:!1,reason:`Widget "${t}" has no action "${n.output.action}"`};let s=y.safeParse(i,n.output.payload);return s.success?{ok:!0,value:{...n.output,payload:s.output},widget:r}:{ok:!1,reason:`Payload rejected by "${t}.${n.output.action}" schema: ${Oe(s.issues)}`}}function Oe(e){return e.map(t=>{let n=t.path?.map(r=>String(r.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}export{Zs as AGGREGATE_FILTER_OPERATORS,Qs as AGGREGATE_OPERATIONS,Rn as AIChatRequestSchema,An as AIChatResponseSchema,ct as AIMessageSchema,Fi as AIProviderConfigSchema,Tn as AIToolCallSchema,xn as AIToolDefinitionSchema,Cn as AIUsageSchema,Ii as AI_ERROR_CODES,Ai as AI_MODELS,N as AI_PROVIDERS,de as AI_ROLES,wi as AI_TIERS,Pi as AI_TOKEN_PRICING,Ma as AUTH_EVENTS,wt as AUTH_PARTNERS,As as AUTH_PARTNER_STATE,ke as AuthHardening,St as AuthUserSchema,gn as BACKEND_GENERATED_FIELD_NAMES,Ba as BILLING_EVENTS,Bn as BREAKPOINT_RANGES,Le as BREAKPOINT_THRESHOLDS,Rt as BulkAcrossCycleError,Tt as BulkCollisionError,bi as BulkDeleteIdSchema,hi as BulkInsertSchema,Ct as BulkNotImplementedError,Sp as BulkRequestSchema,xp as BulkResponseSchema,yi as BulkUpdateSchema,dt as COMMON_TIER_CONFIGS,Ms as CONFIDENCE_LEVELS,Pt as CONSENT_CATEGORY,Us as CONTEXTS,B as CRUD_OPERATORS,Ge as CURRENCY_MAP,xi as CanvasBlockSchema,Ti as CanvasEventSchema,Ei as CanvasLifetimeSchema,Si as CanvasWidgetMetadataSchema,kn as CheckoutLineItemInputSchema,Et as CheckoutSessionMetadataSchema,Y as ConditionBuilder,ft as CreateCheckoutSessionRequestSchema,vt as CreateCheckoutSessionResponseSchema,xt as CustomClaimsSchema,ki as DEFAULT_AI_CONFIG,Oi as DEFAULT_AI_MARKUP,No as DEFAULT_CRUD_TIMEOUT,Ue as DEFAULT_ENTITY_ACCESS,V as DEFAULT_ERROR_MESSAGES,$n as DEFAULT_LAYOUT_PRESET,it as DEFAULT_STATUS_OPTIONS,Yd as DEFAULT_STATUS_VALUE,Qi as DEFAULT_SUBSCRIPTION,Do as DEFAULT_UPLOAD_TIMEOUT,Hl as DENSITY,R as DoNotDevError,me as EDITABLE,xa as EMAIL_ERROR_CODES,Sa as EMAIL_PROVIDERS,Cs as EMAIL_VERIFICATION_STATUS,ge as ENTITY_HOOK_ERRORS,_s as ENVIRONMENTS,re as ERROR_CODES,Pa as ERROR_SEVERITY,Da as ERROR_SOURCE,At as EntityHookError,Ne as FEATURES,Wl as FEATURE_CONSENT_MATRIX,Ls as FEATURE_STATUS,Vt as FIELD_TEXT_FORMATTERS,Ys as FIELD_TYPES,Me as FIREBASE_ERROR_MAP,qn as FOOTER_MODE,kt as GITHUB_PERMISSION_LEVELS,zd as HIDDEN_STATUSES,co as LANGUAGE_COOKIE,jn as LAYOUT_PRESET,Ks as LIST_SCHEMA_TYPE,pt as MAX_CHECKOUT_LINE_ITEMS,gt as MAX_SHIPPING_RATE_IDS,$a as OAUTH_EVENTS,Ot as OAUTH_PARTNERS,Ws as ORDER_DIRECTION,Ol as PARTNER_ICONS,ja as PAYLOAD_EVENTS,Fe as PERMISSIONS,Fs as PLATFORMS,qs as PWA_ASSET_TYPES,$s as PWA_DISPLAY_MODES,On as ProductDeclarationSchema,ls as ProductDeclarationsSchema,kp as ProxiedImageUrlSchema,js as ROUTE_SOURCES,Qt as SESSION_RENDER_SEGMENT,Vs as STORAGE_SCOPES,Bs as STORAGE_TYPES,Ha as STRIPE_EVENTS,pe as STRIPE_MODES,zi as SUBSCRIPTION_DURATIONS,W as SUBSCRIPTION_STATUS,De as SUBSCRIPTION_TIERS,Un as SendEmailRequestSchema,Mn as SendEmailResponseSchema,tn as ServerUtils,K as SingletonManager,_n as StripeBackConfigSchema,Pn as StripeFrontConfigSchema,Fn as StripeOrderBackSchema,Nn as StripeOrderShippingSchema,Dn as StripeOrderTaxSchema,In as StripePaymentSchema,wn as StripeSubscriptionSchema,yt as SubscriptionClaimsSchema,ht as SubscriptionDataSchema,si as TECHNICAL_FIELD_NAMES,Te as TRANSLATABLE_FIELD_TYPES,w as USER_ROLES,_e as UserSubscriptionSchema,Hs as VISIBILITY,bt as WebhookEventSchema,ue as addMonths,tt as addYears,Yo as addressSchema,Xo as arraySchema,k as baseFields,nn as booleanSchema,Br as buildProductJsonLd,Uo as calculateSubscriptionEndDate,qe as captureErrorToSentry,El as checkGitHubAccessSchema,Zr as clearGlobalSingleton,Id as clearSchemaGenerators,bp as clearScopeProviders,oe as commonErrorCodeMappings,He as compactToISOString,ro as configureProviders,to as createAsyncSingleton,Xi as createDefaultSubscriptionClaims,ks as createDefaultUserProfile,sa as createEntitySchema,_ as createErrorHandler,vr as createMetadata,no as createMethodProxy,cp as createSchemas,Jr as createSingleton,eo as createSingletonWithParams,X as dateSchema,op as defineEntity,ua as deleteEntitySchema,Lr as deriveEntitySeo,Tp as detectBulkCollisions,Ve as detectErrorSource,Tl as disconnectOAuthSchema,qo as emailSchema,Rd as enhanceSchema,cr as ensureSpreadable,j as evaluateCondition,Ao as evaluateFieldConditions,Sl as exchangeTokenSchema,rn as fileSchema,on as filesSchema,So as filterVisibleFields,se as formatCurrency,_t as formatDate,Xe as formatFieldText,Rr as formatRelativeTime,ni as gdprConsentSchema,Wt as generateCodeChallenge,Ht as generateCodeVerifier,qr as generateFirestoreRuleCondition,Gr as generatePKCEPair,Po as generateUUID,Ko as geopointSchema,Vn as getBreakpointFromWidth,il as getBreakpointUtils,Wd as getCollectionName,Io as getConditionDependencies,Rl as getConnectionsSchema,Ft as getCurrencyLocale,hr as getCurrencySymbol,Er as getCurrentTimestamp,ai as getEntityByCollection,aa as getEntitySchema,ae as getGlobalSingleton,le as getListCardFieldNames,oo as getProvider,kd as getRegisteredSchemaTypes,yp as getRegisteredScopeProviders,Xr as getRoleFromClaims,Q as getSchemaType,vp as getScopeValue,ao as getTranslatedFieldNames,et as getVisibleFields,Tr as getWeekFromISOString,wp as getWidget,Gn as githubPermissionSchema,Be as githubRepoConfigSchema,yl as grantGitHubAccessSchema,A as handleError,Ad as hasCustomSchemaGenerator,ii as hasMetadata,io as hasProvider,xo as hasRestrictedVisibility,Se as hasRoleAccess,hp as hasScopeProvider,Qr as hasTierAccess,Re as i18nFieldName,ei as ibanSchema,Fl as isAuthPartnerId,fn as isBackendGeneratedField,ol as isBreakpoint,We as isCompactDateString,ze as isEmptyFieldValue,Zt as isFieldVisible,Xd as isFrameworkField,Ce as isMultilingual,_l as isOAuthPartnerId,Hr as isPKCESupported,yr as isoToCompactString,fo as languageUrls,zr as lazyImport,ca as listEntitiesSchema,Op as listWidgets,Je as localizePath,zo as mapSchema,$ as mapToDoNotDevError,jr as maybeTranslate,Qo as multiselectSchema,sn as neverSchema,br as normalizeToISOString,z as numberSchema,Gi as overrideFeatures,Yi as overridePaymentModes,Hi as overridePermissions,Ki as overrideSubscriptionStatus,ji as overrideSubscriptionTiers,qi as overrideUserRoles,mo as parseAcceptLanguage,Ke as parseDate,Ar as parseDateToNoonUTC,Mo as parseISODate,$o as parseServerCookie,jo as passwordSchema,Ho as pictureSchema,Wo as picturesSchema,ri as priceSchema,go as publicPathname,pp as rangeOptions,po as readCookieValue,Zo as referenceSchema,xl as refreshTokenSchema,b as registerSchemaGenerator,gp as registerScopeProvider,Nd as registerUniqueConstraintValidator,Ip as registerWidget,so as resetProviders,Qe as resolveLanguage,vo as resolveLanguageRoute,bl as revokeGitHubAccessSchema,ur as safeValidate,Oo as sanitizeHref,nt as selectSchema,or as showNotification,Ze as splitLanguagePath,rt as stringSchema,ye as stripHtmlTags,ti as switchSchema,Jo as telSchema,Ie as textSchema,xr as timestampToISOString,kr as toDateOnly,Sr as toISOString,pr as translateArray,gr as translateArrayRange,fr as translateArrayWithIndices,he as translateEntityLabel,mr as translateObjectArray,uo as translateRow,fp as unregisterScopeProvider,la as updateEntitySchema,ho as updateMetadata,Go as urlSchema,_i as validateAIChatRequest,Ui as validateAIChatResponse,Dl as validateAuthPartners,Ts as validateAuthSchemas,Es as validateAuthUser,ds as validateBillingSchemas,Pp as validateBlock,as as validateCheckoutSessionMetadata,Kr as validateCodeChallenge,Wr as validateCodeVerifier,ns as validateCreateCheckoutSessionRequest,rs as validateCreateCheckoutSessionResponse,xs as validateCustomClaims,we as validateDates,Md as validateDocument,Vo as validateEnvVar,Dp as validateEvent,Bo as validateMetadata,Nl as validateOAuthPartners,Ra as validateSendEmailRequest,Ca as validateSendEmailResponse,cs as validateStripeBackConfig,us as validateStripeFrontConfig,is as validateSubscriptionClaims,os as validateSubscriptionData,pn as validateUniqueFields,Lo as validateUrl,Ss as validateUserSubscription,ss as validateWebhookEvent,lr as validateWithSchema,ko as when,rr as withErrorHandling,Yr as withGracefulDegradation,Fo as withTimeout,ar as wrapAuthError,ir as wrapCrudError,sr as wrapStorageError};
|
|
1
|
+
var At=Object.defineProperty;var or=(e,t,n)=>t in e?At(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ir=(e,t)=>{for(var n in t)At(e,n,{get:t[n],enumerable:!0})};var T=(e,t,n)=>or(e,typeof t!="symbol"?t+"":t,n);var Rn={};ir(Rn,{AuthHardening:()=>Me,CURRENCY_MAP:()=>st,ConditionBuilder:()=>re,DEFAULT_CRUD_TIMEOUT:()=>Ri,DEFAULT_ERROR_MESSAGES:()=>K,DEFAULT_UPLOAD_TIMEOUT:()=>Ti,DoNotDevError:()=>S,FIELD_TEXT_FORMATTERS:()=>an,LANGUAGE_COOKIE:()=>ni,SESSION_RENDER_SEGMENT:()=>vn,SingletonManager:()=>te,TRANSLATABLE_FIELD_TYPES:()=>Ne,addMonths:()=>ve,addYears:()=>ht,buildProductJsonLd:()=>Po,calculateSubscriptionEndDate:()=>Ci,captureErrorToSentry:()=>ot,clearGlobalSingleton:()=>Wo,commonErrorCodeMappings:()=>me,compactToISOString:()=>at,configureProviders:()=>zo,createAsyncSingleton:()=>Go,createErrorHandler:()=>N,createMetadata:()=>ao,createMethodProxy:()=>Yo,createSingleton:()=>Ko,createSingletonWithParams:()=>Ho,deriveEntitySeo:()=>Oo,detectErrorSource:()=>nt,ensureSpreadable:()=>to,evaluateCondition:()=>Y,evaluateFieldConditions:()=>hi,filterVisibleFields:()=>pi,formatCurrency:()=>ge,formatDate:()=>tn,formatFieldText:()=>pt,formatRelativeTime:()=>yo,generateCodeChallenge:()=>mn,generateCodeVerifier:()=>pn,generateFirestoreRuleCondition:()=>No,generatePKCEPair:()=>Uo,generateUUID:()=>xi,getConditionDependencies:()=>bi,getCurrencyLocale:()=>en,getCurrencySymbol:()=>lo,getCurrentTimestamp:()=>po,getGlobalSingleton:()=>ye,getListCardFieldNames:()=>he,getProvider:()=>Xo,getRoleFromClaims:()=>jo,getTranslatedFieldNames:()=>Jo,getVisibleFields:()=>yt,getWeekFromISOString:()=>go,handleError:()=>k,hasProvider:()=>Qo,hasRestrictedVisibility:()=>mi,hasRoleAccess:()=>j,hasTierAccess:()=>qo,i18nFieldName:()=>ne,isCompactDateString:()=>lt,isEmptyFieldValue:()=>dt,isFieldVisible:()=>bn,isMultilingual:()=>_e,isPKCESupported:()=>Mo,isoToCompactString:()=>uo,languageUrls:()=>si,lazyImport:()=>$o,localizePath:()=>gt,mapToDoNotDevError:()=>H,maybeTranslate:()=>_o,normalizeToISOString:()=>co,parseAcceptLanguage:()=>oi,parseDate:()=>ut,parseDateToNoonUTC:()=>vo,parseISODate:()=>Ii,parseServerCookie:()=>Di,publicPathname:()=>ii,readCookieValue:()=>ri,resetProviders:()=>Zo,resolveLanguage:()=>mt,resolveLanguageRoute:()=>ai,resolveUserSubscription:()=>xn,safeValidate:()=>eo,sanitizeHref:()=>Si,showNotification:()=>zr,splitLanguagePath:()=>ft,stripHtmlTags:()=>Oe,timestampToISOString:()=>fo,toDateOnly:()=>bo,toISOString:()=>mo,translateArray:()=>ro,translateArrayRange:()=>io,translateArrayWithIndices:()=>so,translateEntityLabel:()=>we,translateObjectArray:()=>oo,translateRow:()=>ti,updateMetadata:()=>li,validateCodeChallenge:()=>Bo,validateCodeVerifier:()=>Lo,validateEnvVar:()=>Pi,validateMetadata:()=>Oi,validateUrl:()=>wi,validateWithSchema:()=>Jr,when:()=>vi,withErrorHandling:()=>Yr,withGracefulDegradation:()=>Vo,withTimeout:()=>ki,wrapAuthError:()=>Zr,wrapCrudError:()=>Xr,wrapStorageError:()=>Qr});var F={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Se={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},Ws={[F.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"]},[F.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[F.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},Ks={maxTokens:4096,temperature:.7,stream:!0},Hs={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"},Gs={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"}},Ys=4,zs={"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 d from"valibot";var Ct=d.object({role:d.picklist([Se.USER,Se.ASSISTANT,Se.SYSTEM]),content:d.pipe(d.string(),d.minLength(1)),id:d.optional(d.string()),createdAt:d.optional(d.string())}),Ge=d.lazy(()=>d.object({type:d.picklist(["string","number","boolean","array","object"]),description:d.optional(d.string()),enum:d.optional(d.array(d.string())),items:d.optional(Ge),properties:d.optional(d.record(d.string(),Ge)),required:d.optional(d.array(d.string()))})),sr=d.object({description:d.pipe(d.string(),d.minLength(1)),parameters:d.object({type:d.literal("object"),properties:d.record(d.string(),Ge),required:d.optional(d.array(d.string()))})}),ar=d.object({id:d.string(),name:d.string(),args:d.record(d.string(),d.unknown())}),lr=d.object({messages:d.pipe(d.array(Ct),d.minLength(1)),provider:d.optional(d.picklist([F.ANTHROPIC,F.OPENAI,F.GOOGLE])),model:d.optional(d.string()),maxTokens:d.optional(d.pipe(d.number(),d.integer(),d.minValue(1))),temperature:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(2))),systemPrompt:d.optional(d.string()),stream:d.optional(d.boolean()),tools:d.optional(d.record(d.string(),sr))}),ur=d.object({promptTokens:d.number(),completionTokens:d.number(),totalTokens:d.number()}),cr=d.object({message:Ct,usage:d.optional(ur),finishReason:d.optional(d.string()),toolCalls:d.optional(d.array(ar))}),Zs=d.object({provider:d.picklist([F.ANTHROPIC,F.OPENAI,F.GOOGLE]),model:d.optional(d.string()),maxTokens:d.optional(d.pipe(d.number(),d.integer(),d.minValue(1))),temperature:d.optional(d.pipe(d.number(),d.minValue(0),d.maxValue(2))),systemPrompt:d.optional(d.string())});function Js(e){return d.safeParse(lr,e)}function ea(e){return d.safeParse(cr,e)}var xe={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function dr(e){Object.assign(xe,e)}var Te={tier:"free",status:"active",subscriptionEnd:null,updatedAt:"1970-01-01T00:00:00.000Z",isDefault:!0,subscriptionId:null,customerId:null,cancelAtPeriodEnd:!1};function pr(e){return{...Te,updatedAt:new Date().toISOString()}}var Ye={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}},w={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function sa(e){Object.assign(w,e)}var mr={FREE:"free",PRO:"pro",PREMIUM:"premium"};function aa(e){Object.assign(mr,e)}var ze={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function la(e){Object.assign(ze,e)}var Xe={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 ua(e){Object.assign(Xe,e)}import*as l from"valibot";function ue(e){let[t,...n]=Object.values(e);if(t===void 0)throw new Error("picklistOptions: constant map has no values");return[t,...n]}var It=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(ue(w))),customClaims:l.optional(l.record(l.string(),l.any()))}),U=l.object({tier:l.string(),status:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),updatedAt:l.pipe(l.string(),l.isoTimestamp()),isDefault:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.optional(l.nullable(l.string())),customerId:l.optional(l.nullable(l.string())),cancelAtPeriodEnd:l.optional(l.boolean())}),wt=l.object({...U.entries,userId:l.string(),isActive:l.optional(l.boolean())}),Ot=l.object({role:l.optional(l.picklist(ue(w))),subscription:l.optional(U),features:l.optional(l.array(l.picklist(ue(ze)))),permissions:l.optional(l.array(l.picklist(ue(Xe)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function fa(e){return l.safeParse(It,e)}function ga(e){return l.safeParse(wt,e)}function ya(e){return l.safeParse(Ot,e)}function fr(e){return l.safeParse(U,e)}function ha(){let e={authUser:l.safeParse(It,{}),userSubscription:l.safeParse(wt,{}),customClaims:l.safeParse(Ot,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var ba={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},Ea={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Sa(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var Re={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ia(e){Object.assign(Re,e)}var wa={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};import*as i from"valibot";var Pt=100,gr=i.object({productId:i.pipe(i.string(),i.minLength(1),i.maxLength(200)),quantity:i.pipe(i.number(),i.integer(),i.minValue(1),i.maxValue(1e4))}),Nt=i.pipe(i.object({billingConfigKey:i.optional(i.pipe(i.string(),i.minLength(1))),lineItems:i.optional(i.pipe(i.array(gr),i.minLength(1,"At least one line item is required"),i.maxLength(Pt,`At most ${Pt} line items`))),successUrl:i.pipe(i.string(),i.url()),cancelUrl:i.pipe(i.string(),i.url()),customerEmail:i.optional(i.pipe(i.string(),i.email())),metadata:i.optional(i.record(i.string(),i.string())),allowPromotionCodes:i.optional(i.boolean()),userId:i.optional(i.string()),productId:i.optional(i.string()),priceId:i.optional(i.string()),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code"))),userEmail:i.optional(i.pipe(i.string(),i.email())),mode:i.optional(i.picklist([Re.PAYMENT,Re.SUBSCRIPTION]))}),i.rawTransform(({dataset:e,addIssue:t,NEVER:n})=>{let r=e.value,o=r.billingConfigKey||r.metadata?.billingConfigKey;return o?{...r,billingConfigKey:o,lineItems:r.lineItems??[{productId:o,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),_t=i.object({sessionId:i.string(),sessionUrl:i.nullable(i.pipe(i.string(),i.url()))}),ce=i.pipe(i.string(),i.minLength(1),i.regex(/\S/)),yr=i.object({sessionId:ce,billingConfigKey:ce}),hr=i.object({sessionId:ce,orderId:ce,billingConfigKey:ce,sessionStatus:i.picklist(["open","complete","expired"]),paymentStatus:i.picklist(["paid","unpaid","no_payment_required"])});function Ma(e){return i.safeParse(yr,e)}function La(e){return i.safeParse(hr,e)}var Ut=i.object({...U.entries,userId:i.string(),subscriptionId:i.nullable(i.string()),customerId:i.string(),cancelAtPeriodEnd:i.boolean()}),Mt=i.object({id:i.string(),type:i.string(),data:i.object({object:i.any()}),created:i.pipe(i.string(),i.isoTimestamp())}),Lt=i.looseObject({userId:i.optional(i.string()),firebaseUid:i.optional(i.string()),productType:i.optional(i.string())});function Ba(e){return i.safeParse(Nt,e)}function Va(e){return i.safeParse(_t,e)}function $a(e){return i.safeParse(Ut,e)}function ja(e){return i.safeParse(Mt,e)}function qa(e){return i.safeParse(Lt,e)}var vr=i.object({type:i.literal("StripePayment"),name:i.pipe(i.string(),i.minLength(1,"Product name is required")),description:i.optional(i.string()),price:i.string(),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:i.optional(i.pipe(i.string(),i.minLength(1,"Stripe price ID is required"))),tier:i.pipe(i.string(),i.minLength(1,"Tier is required")),duration:i.pipe(i.string(),i.minLength(1,"Duration is required")),allowPromotionCodes:i.optional(i.boolean()),metadata:i.optional(i.record(i.string(),i.string()))}),br=i.object({type:i.literal("StripeSubscription"),name:i.pipe(i.string(),i.minLength(1,"Product name is required")),description:i.optional(i.string()),price:i.string(),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:i.pipe(i.string(),i.minLength(1,"Stripe price ID is required")),tier:i.pipe(i.string(),i.minLength(1,"Tier is required")),duration:i.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:i.optional(i.boolean()),metadata:i.optional(i.record(i.string(),i.string()))}),Er=i.variant("type",[vr,br]),Wa=i.record(i.string(),Er),Sr=i.record(i.string(),i.object({name:i.string(),price:i.string(),currency:i.string(),description:i.optional(i.string()),features:i.optional(i.array(i.string())),priceId:i.optional(i.string()),allowPromotionCodes:i.optional(i.boolean())})),Dt={name:i.string(),price:i.number(),currency:i.string(),priceId:i.optional(i.string()),tier:i.string(),duration:i.string(),description:i.optional(i.string()),metadata:i.optional(i.record(i.string(),i.string())),allowPromotionCodes:i.optional(i.boolean())},xr=i.variant("mode",[i.object({mode:i.literal("manual"),taxRateIds:i.pipe(i.array(i.pipe(i.string(),i.minLength(1))),i.minLength(1))}),i.object({mode:i.literal("automatic")})]),Ft=5,Tr=i.object({allowedCountries:i.pipe(i.array(i.pipe(i.string(),i.regex(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),i.minLength(1)),shippingRateIds:i.optional(i.pipe(i.array(i.pipe(i.string(),i.minLength(1))),i.maxLength(Ft,`shippingRateIds: at most ${Ft} (Stripe limit)`)))}),Rr=i.object({type:i.literal("StripeOrder"),name:i.string(),currency:i.pipe(i.string(),i.length(3)),description:i.optional(i.string()),metadata:i.optional(i.record(i.string(),i.string())),allowPromotionCodes:i.optional(i.boolean()),tax:xr,taxIdCollection:i.picklist(["disabled","optional","required"]),billingAddressCollection:i.picklist(["auto","required"]),shipping:i.optional(Tr),customerCreation:i.picklist(["always","if_required"]),invoiceCreation:i.boolean(),paymentMethodConfiguration:i.optional(i.pipe(i.string(),i.minLength(1)))}),kr=i.record(i.string(),i.variant("type",[i.object({type:i.literal("StripePayment"),...Dt}),i.object({type:i.literal("StripeSubscription"),...Dt}),Rr]));function Ka(e){return i.parse(Sr,e)}function Ha(e){return i.parse(kr,e)}function Ga(){let e={createCheckoutSessionRequest:i.safeParse(Nt,{}),createCheckoutSessionResponse:i.safeParse(_t,{}),subscriptionData:i.safeParse(Ut,{}),subscriptionClaims:i.safeParse(U,{}),webhookEvent:i.safeParse(Mt,{}),checkoutSessionMetadata:i.safeParse(Lt,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var el={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},tl={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},nl={CLIENT:"client",SERVER:"server",BUILD:"build"},rl={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},ol={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},il={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},sl={USER:"user",GLOBAL:"global",SESSION:"session"},al={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},ll={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},ul={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var dl={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},V={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},Qe={create:"admin",read:"guest",update:"admin",delete:"admin"},M={draft:{read:"admin",saveIncomplete:!0,holdIncomplete:!0,isDefault:!1,isRemoved:!1},available:{read:"guest",saveIncomplete:!1,holdIncomplete:!1,isDefault:!0,isRemoved:!1},deleted:{read:"admin",saveIncomplete:!1,holdIncomplete:!0,isDefault:!1,isRemoved:!0}},Bt=M.available,ee=Object.keys(M);function Vt(e){let t=ee.filter(n=>M[n][e]);if(t.length!==1)throw new Error(`[dndev] STATUS_MATRIX: exactly one status must have ${e}`);return t[0]}var ke=Vt("isDefault"),Ze=Vt("isRemoved"),Ar=ee.filter(e=>M[e].read!=="guest"),de=["id","createdAt","updatedAt","createdById","updatedById"],W={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},pl={ASC:"asc",DESC:"desc"},ml={LIST:"list",LIST_CARD:"listCard"},$t=["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 yl={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},hl={EQ:W.EQ,NEQ:W.NEQ,LT:W.LT,LTE:W.LTE,GT:W.GT,GTE:W.GTE};var jt=class extends Error{constructor(n,r,o){super(n,{cause:o});T(this,"outcome");this.name="AtomicBulkError",this.outcome=r}},qt=class extends Error{constructor(n,r){super(`BulkCollisionError: ${n.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${n.join(", ")}`);T(this,"collidingIds");T(this,"where");this.name="BulkCollisionError",this.collidingIds=n,this.where=r}},Wt=class extends Error{constructor(n){super(`[dndev] bulkAcross: circular dependency: ${n.join(" \u2192 ")}`);T(this,"cycle");this.name="BulkAcrossCycleError",this.cycle=n}},Kt=class extends Error{constructor(n){super(`BulkNotImplementedError: adapter "${n}" has not implemented bulk() yet`);T(this,"adapterName");this.name="BulkNotImplementedError",this.adapterName=n}};import*as f from"valibot";var kl=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),data:f.record(f.string(),f.unknown()),idempotencyKey:f.optional(f.string())}),Al=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required"))}),Cl=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required")),data:f.record(f.string(),f.unknown()),merge:f.optional(f.boolean(),!1)}),Il=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),id:f.pipe(f.string(),f.minLength(1,"Entity ID is required"))}),wl=f.object({collection:f.pipe(f.string(),f.minLength(1,"Collection name is required")),limit:f.optional(f.pipe(f.number(),f.minValue(1),f.maxValue(1e3)),1e3),offset:f.optional(f.pipe(f.number(),f.minValue(0)),0),orderBy:f.optional(f.string()),orderDirection:f.optional(f.picklist(["asc","desc"]),"desc"),where:f.optional(f.array(f.object({field:f.string(),operator:f.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:f.unknown()})))});var $l={RESEND:"resend"},jl={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 Cr=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())}),Ir=E.object({success:E.boolean(),messageId:E.optional(E.string()),error:E.optional(E.string())});function Wl(e){return E.safeParse(Cr,e)}function Kl(e){return E.safeParse(Ir,e)}var pe={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"},Ql={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"},Je={[pe.PERMISSION_DENIED]:{type:Ae.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[pe.NOT_FOUND]:{type:Ae.NOT_FOUND,message:"The requested resource was not found"},[pe.ALREADY_EXISTS]:{type:Ae.ALREADY_EXISTS,message:"The resource already exists"},[pe.INVALID_ARGUMENT]:{type:Ae.VALIDATION_ERROR,message:"Invalid argument provided"}},Ht=class extends Error{constructor(n,r,o){super(r);T(this,"type");T(this,"originalError");this.name="EntityHookError",this.type=n,this.originalError=o}},Zl={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"};function wr(e){return"captureStackTrace"in e&&typeof e.captureStackTrace=="function"}var S=class e extends Error{constructor(n,r=pe.INTERNAL,o){super(n);T(this,"code");T(this,"details");T(this,"source");T(this,"originalError");T(this,"context");T(this,"displayable");T(this,"userMessageProvided");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,wr(Error)&&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 ru={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 iu={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 au={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 uu={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 du={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 et={mobile:0,tablet:768,laptop:1024,desktop:1440},Or={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function Pr(e){return e>=et.desktop?"desktop":e>=et.laptop?"laptop":e>=et.tablet?"tablet":"mobile"}function Ru(e,t){let n=Or[t];return e>=n.min&&e<=n.max}function ku(e,t){let n=Pr(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 Dr="landing",Fr={FIXED:"fixed",SCROLL:"scroll"},Nr={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var Gt=["pull","push","admin","maintain","triage"];import"valibot";import*as m from"valibot";var tt=m.object({owner:m.pipe(m.string(),m.minLength(1,"Repository owner is required")),repo:m.pipe(m.string(),m.minLength(1,"Repository name is required"))}),_r=m.picklist([...Gt]),Lu=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:tt,permission:m.optional(_r,"push"),customClaims:m.optional(m.record(m.string(),m.any()))}),Bu=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:tt}),Vu=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required")),githubUsername:m.pipe(m.string(),m.minLength(1,"GitHub username is required")),repoConfig:tt}),$u=m.object({provider:m.string(),purpose:m.picklist(["authentication","api-access"]),code:m.pipe(m.string(),m.minLength(1,"Authorization code is required")),redirectUri:m.pipe(m.string(),m.url("Valid redirect URI is required")),codeVerifier:m.optional(m.string()),state:m.optional(m.string()),instance:m.optional(m.pipe(m.string(),m.url()))}),ju=m.object({provider:m.string(),refreshToken:m.pipe(m.string(),m.minLength(1,"Refresh token is required")),redirectUri:m.pipe(m.string(),m.url("Valid redirect URI is required"))}),qu=m.object({provider:m.string()}),Wu=m.object({userId:m.pipe(m.string(),m.minLength(1,"User ID is required"))});var Xu={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 y from"valibot";var Yt=y.object({name:y.string(),color:y.string(),icon:y.string(),customParameters:y.optional(y.record(y.string(),y.string())),button:y.object({backgroundColor:y.string(),textColor:y.string(),borderColor:y.string(),hoverBackgroundColor:y.string(),focusOutlineColor:y.string(),fontWeight:y.optional(y.string(),"500"),textKey:y.optional(y.string())})}),Ur=y.object({...Yt.entries,type:y.picklist(["auth","both"]),scopes:y.optional(y.array(y.string())),firebaseProviderId:y.optional(y.string())}),Ce=y.union([y.literal(""),y.pipe(y.string(),y.url())]),Mr=y.object({authUrl:Ce,tokenUrl:Ce,profileUrl:Ce,revokeUrl:y.optional(Ce)}),Lr=y.object({authentication:y.optional(y.array(y.string())),"api-access":y.array(y.string())}),Br=y.optional(y.object({pkce:y.optional(y.boolean(),!1),codeChallengeMethod:y.optional(y.picklist(["S256","plain"]),"S256")})),Vr=y.object({...Yt.entries,type:y.picklist(["oauth","both"]),scopes:Lr,endpoints:Mr,capabilities:Br}),zt={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"}}},Xt={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"}}},$r=y.record(y.string(),Ur),jr=y.record(y.string(),Vr);function Zu(){return y.safeParse($r,zt)}function Ju(){return y.safeParse(jr,Xt)}function ec(e){return e in zt}function tc(e){return e in Xt}var Qt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},dc={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},pc={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Qt.ANALYTICS},marketing:{requiresConsent:Qt.MARKETING}};function nt(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 Jt from"valibot";function N(e){return(t,n)=>{if(t instanceof S)return t;if(typeof t!="object"||t===null){let c=typeof t=="string"?t:e.defaultErrorMessage;return new S(n||c,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let r;e.extractErrorCode?r=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(r=t.code);let o=e.defaultErrorCode;r&&e.errorCodeMapping&&r in e.errorCodeMapping&&(o=e.errorCodeMapping[r]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),r&&e.friendlyMessageMapping&&r in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[r]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},r&&(a.originalCode=r)),"originalError"in a||(a.originalError=t),new S(n||s,o,{details:a,source:e.errorSource})}}var me={"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 K={"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."},qr={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"},rt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"};function Wr(e){return e in rt}var $={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",...me},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",...me},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(qr).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};if(typeof e!="object"||e===null)return t;if("response"in e&&e.response){let n=e.response;"status"in n&&(t.statusCode=n.status),"data"in n&&(t.responseData=n.data)}else"status"in e&&(t.statusCode=e.status);return t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:me,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:K.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:K["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:K.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},Kr=e=>e instanceof Jt.ValiError?new S(K["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):N($.validation)(e),Hr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&Wr(e.type)){let t=rt[e.type]||"unknown";return new S(e.message||K[t],t,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Je[e.code]){let t=Je[e.code];if(t){let n=rt[t.type]||"unknown";return new S(t.message||K[n],n,{details:{originalCode:e.code,originalError:e},source:"entity"})}}return N($.entity)(e)},Zt={auth:N($.auth),oauth:N($.oauth),api:N($.api),firebase:N($.firebase),ui:N($.ui),validation:Kr,entity:Hr,unknown:N($.unknown)};function H(e,t,n){return e instanceof S?e:(Zt[t]||Zt.unknown)(e,n)}function ot(e,t,n={}){let r=globalThis.Sentry;r&&r.withScope(o=>{o.setTag("errorSource",t),o.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{o.setExtra(s,a)}catch{o.setExtra(s,`[${typeof a}]`)}}),Object.entries(n).forEach(([s,a])=>{if(typeof a!="function")try{o.setExtra(`context.${s}`,a)}catch{o.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||n.userId)&&o.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),r.captureException(e)})}function Gr(){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?(process.env.NODE_ENV||"development").toLowerCase()!=="production":!1}function k(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:r,context:o={},log:s=!0,reportToSentry:a=!0,showNotification:c=!1,severity:p="error"}=n,h=nt(e),v=e instanceof S?e:H(e,h,r);if(r&&!v.userMessageProvided&&(v.message.includes("Error")||v.message.includes("Failed")||v.message.length<10?v=new S(r,v.code,{details:{...v.details,originalMessage:v.message},source:h,userMessageProvided:!0}):v=new S(v.message,v.code,{details:{...v.details,userMessage:r},source:h,userMessageProvided:!0})),s){let x=Gr()||typeof window<"u"&&window.__DNDEV_DEBUG,B={code:v.code,message:v.message,source:h};switch(p){case"warning":break;case"info":break;case"success":break;default:}}return a&&ot(v,h,o),v}function Yr(e,t){return async(...n)=>{try{return await e(...n)}catch(r){throw k(r,t)}}}function zr(e,t="info",n){let r=Date.now().toString();return r}function Xr(e,t,n,r,o){if(e instanceof S)return e;let{code:s}=H(e,"api");return new S("Request failed.",s,{source:"api",details:{context:`${t}.${n}(${r}${o?`, ${o}`:""})`,originalMessage:it(e),originalError:e}})}function Qr(e,t,n,r){let o=`${t}.${n}(${r})`;return H(e,"api",`${o}: ${it(e)}`)}function Zr(e,t,n,r){let o=r?` ${JSON.stringify(r)}`:"",s=`${t}.${n}(${o})`,a=H(e,"auth",`${s}: ${it(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new S(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function it(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as fe from"valibot";function Jr(e,t,n){try{return fe.parse(e,t)}catch(r){throw r instanceof fe.ValiError?new S(`Validation failed in ${n}: ${r.message}`,"validation-failed",{details:{issues:r.issues,input:t},source:"validation"}):new S(`Unexpected validation error in ${n}: ${no(r)}`,"validation-failed",{originalError:r instanceof Error?r:new Error(String(r)),source:"validation"})}}function eo(e,t){try{return fe.parse(e,t)}catch{return null}}function to(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function no(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function ro(e,t,n,r={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(c,p)=>{let h=`${t}.${p}`;return e(h)}).filter((c,p)=>{let h=`${t}.${p}`;return!(c===h||s&&c.trim()===""||c.length<o||a&&!a(c,p))})}function oo(e,t,n,r){return Array.from({length:n},(o,s)=>{let a=`${t}.${s}.${String(r[0])}`;if(e(a)===a)return null;let p={};for(let h of r){let v=`${t}.${s}.${String(h)}`;p[h]=e(v)}return p}).filter(o=>o!==null)}function io(e,t,n,r,o={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:c}=o;return Array.from({length:r-n},(p,h)=>{let v=n+h,x=`${t}.${v}`;return e(x)}).filter((p,h)=>{let v=n+h,x=`${t}.${v}`;return!(p===x||a&&p.trim()===""||p.length<s||c&&!c(p,v))})}function so(e,t,n,r={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:a}=r;return Array.from({length:n},(c,p)=>{let h=`${t}.${p}`;return{item:e(h),originalIndex:p}}).filter(({item:c,originalIndex:p})=>{let h=`${t}.${p}`;return!(c===h||s&&c.trim()===""||c.length<o||a&&!a(c,p))})}function ao(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var st={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 en(e){return st[e]?.locale??"en-US"}function lo(e){return!e||typeof e!="string"?e??"":st[e]?.symbol??e}function ge(e,t,n={}){if(e==null||isNaN(e))return"";let r=en(t);return new Intl.NumberFormat(r,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...n}).format(e)}function at(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],r=t[2],o=t[3],s=t[4],a=t[5],c=new Date(parseInt(n,10),parseInt(r,10)-1,parseInt(o,10),parseInt(s,10),parseInt(a,10));if(isNaN(c.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return c.toISOString()}function uo(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${n}${r}${o}:${s}${a}`}function lt(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function co(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(lt(e))return at(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&&typeof e.toDate=="function")return e.toDate().toISOString();throw new Error(`Unsupported date type: ${typeof e}`)}function po(){return new Date().toISOString()}function mo(e){return e.toISOString()}function fo(e){return new Date(e).toISOString()}function go(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),r=Math.floor((t.getTime()-n.getTime())/(1440*60*1e3));return`Week ${Math.ceil((r+n.getDay()+1)/7)}, ${t.getFullYear()}`}var O={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function yo(e,t="en",n={}){if(!e)return"";let{style:r="long",numeric:o="auto",fallbackThreshold:s=O.WEEK}=n,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let c=new Date,p=a.getTime()-c.getTime(),h=Math.round(p/1e3),v=Math.abs(h);if(v>s)return tn(a.toISOString(),t);let x=new Intl.RelativeTimeFormat(t,{style:r,numeric:o});return v<O.MINUTE?x.format(h,"second"):v<O.HOUR?x.format(Math.round(h/O.MINUTE),"minute"):v<O.DAY?x.format(Math.round(h/O.HOUR),"hour"):v<O.WEEK?x.format(Math.round(h/O.DAY),"day"):v<O.MONTH?x.format(Math.round(h/O.WEEK),"week"):v<O.YEAR?x.format(Math.round(h/O.MONTH),"month"):x.format(Math.round(h/O.YEAR),"year")}function ho(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 tn(e,t="en",n="long"){if(!e)return"";let r;if(e instanceof Date)r=e;else if(typeof e=="string")r=new Date(e);else if(typeof e=="number")r=new Date(e);else if(typeof e=="object"&&"toDate"in e)r=e.toDate();else return"";if(isNaN(r.getTime()))return"";let o=typeof n=="string"?ho(n):n;return new Intl.DateTimeFormat(t,o).format(r)}function ut(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(lt(t))try{return at(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&&typeof e.toDate=="function")try{let t=e.toDate();return isNaN(t.getTime())?void 0:t.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,r=new Date(n);return isNaN(r.getTime())?void 0:r.toISOString()}}}function vo(e){let t=ut(e);if(!t)return;let n=new Date(t);return n.setUTCHours(12,0,0,0),n.toISOString()}function bo(e){let t=ut(e);return t&&t.split("T")[0]||""}function dt(e){return e==null||e===""}function we(e,t){if(!e.includes(":"))return t(e);let[n,r=e]=e.split(":");if(r.startsWith("status.")){let o=t(r);if(o!==r&&o!==`${n}:${r}`)return o}return t(r,{ns:n})}function Oe(e){return e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function sn(e){let t=e.validation?.options;return Array.isArray(t)?t:void 0}function Ie(e,t,n){let r=sn(t)?.find(o=>o.value===e)?.label;return r?we(r,n):String(e)}function ct(e){return e instanceof Date?e:new Date(e)}var nn=(e,t,n,{locale:r})=>ct(e).toLocaleString(r),_=e=>String(e),rn=e=>e?"Yes":"No",on=(e,t,n,{locale:r})=>typeof e=="number"?e.toLocaleString(r):String(e),an={timestamp:nn,"datetime-local":nn,date:(e,t,n,{locale:r})=>ct(e).toLocaleDateString(r),time:(e,t,n,{locale:r})=>ct(e).toLocaleTimeString(r),week:_,month:_,boolean:rn,checkbox:rn,switch:(e,t,n)=>{let r=t.options?.fieldSpecific;if(r){let o=r.uncheckedValue??!1,s=r.checkedValue??!0;if(e===s&&r.checkedLabel)return we(r.checkedLabel,n);if(e===o&&r.uncheckedLabel)return we(r.uncheckedLabel,n)}return e?"Yes":"No"},year:_,number:on,range:on,currency:(e,t)=>{if(Number.isNaN(Number(e)))return"";let n=t.options?.fieldSpecific;return ge(Number(e),n?.currency||"EUR")},price:(e,t,n)=>{let r=typeof e=="number"?{amount:e,currency:"EUR",vatIncluded:!0,discountPercent:0}:e;if(!r||typeof r!="object")return"";let o=r.amount;if(dt(o)||Number.isNaN(Number(o)))return"";let s=r.currency||"EUR",a=r.discountPercent??0,c=r.vatIncluded??!0?` ${n("crud:price.vatIncluded",{defaultValue:"VAT Incl."})}`:"";if(a>0){let p=Number(o)*(1-a/100),h=` ${n("crud:price.discountPercent",{percent:Math.round(a),defaultValue:"-{{percent}}%"})}`;return`${ge(p,s)}${c}${h}`}return`${ge(Number(o),s)}${c}`},duration:(e,t,n)=>{let r=typeof e=="number"?e:parseInt(String(e),10);if(Number.isNaN(r))return"";if(r===0)return n("crud:duration.zero",{defaultValue:"\u2014"});if(r<60)return n("crud:duration.minutes",{count:r,defaultValue:`${r} min`});let o=Math.floor(r/60),s=r%60;return n("crud:duration.hoursMinutes",{hours:o,minutes:s,defaultValue:s===0?`${o}h`:`${o}h ${s}min`})},gdprConsent:(e,t,n,{locale:r})=>{if(!e||typeof e!="object")return"";let o=e;if(o.gdprConsent!==!0)return n("crud:gdprConsent.display.no",{defaultValue:"Not consented"});let s=[n("crud:gdprConsent.display.yes",{defaultValue:"Consented"})];return o.gdprConsentDate&&s.push(new Date(o.gdprConsentDate).toLocaleDateString(r)),o.gdprConsentVersion&&s.push(`v${o.gdprConsentVersion}`),s.join(" \xB7 ")},select:Ie,radio:Ie,combobox:Ie,multiselect:(e,t,n)=>Array.isArray(e)&&sn(t)?e.map(r=>Ie(r,t,n)).join(", "):String(e),reference:e=>{if(e&&typeof e=="object"){let t=e;return String(t.displayName||t.name||t.id||e)}return String(e)},geopoint:e=>{if(e&&typeof e=="object"&&"lat"in e&&"lng"in e){let{lat:t,lng:n}=e;return`${t.toFixed(6)}, ${n.toFixed(6)}`}return""},address:e=>e&&typeof e=="object"&&"formatted_address"in e?String(e.formatted_address):String(e),array:e=>Array.isArray(e)?e.join(", "):"","field-array":(e,t)=>{if(!Array.isArray(e))return"";let n=t.options?.fieldSpecific?.fields;return e.map(r=>{if(typeof r!="object"||r==null)return"";let o=r;return(n?n.map(a=>a.name):Object.keys(o)).map(a=>o[a]).filter(a=>a!=null&&a!=="").map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" \xB7 ")}).filter(Boolean).join(", ")},password:()=>"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",text:_,textarea:_,email:_,tel:_,url:_,color:_,iban:_,richtext:e=>Oe(String(e))};function pt(e,t,n,r={}){let o=t.options?.displayValue;if(o&&r.item)return o(e,r.item,n);if(dt(e))return null;let s=r.formatter??an[t.type],a=s?s(e,t,n,{locale:r.locale}):typeof e=="object"?null:String(e);if(a===null||a==="")return null;let c=t.options?.displayKey;if(!c)return a;let p=(Array.isArray(c)?c:[c]).map(h=>h.replace("{{value}}",a));return n(p,{value:a})}var Eo=160,ln="EUR",So=new Set(["textarea","richtext"]),cn=new Set(["image","images"]),xo=new Set(["price","currency"]),To=" \xB7 ",Ro={available:"InStock"};function G(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function ko(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(" ");return`${(r>t/2?n.slice(0,r):n).trimEnd()}\u2026`}function un(e){return(Array.isArray(e)?e:[e]).map(n=>{if(typeof n=="string")return G(n);if(n&&typeof n=="object"&&"fullUrl"in n)return G(n.fullUrl)}).filter(n=>n!==void 0)}function dn(e){let t=e.listCardFields,n=t?Array.isArray(t)?t:[...t.title??[],...t.subtitle??[],...t.content??[],...t.footer??[]]:[];return[...new Set([...n,...Object.keys(e.fields)])]}function Pe(e,t,n,r){return n.flatMap(o=>{let s=e.fields[o];if(!s||cn.has(s.type))return[];let a=pt(t[o],s,r.t,{item:t,locale:r.locale});return a?[a]:[]})}function Ao(e,t,n){let r=e.seo?.title;if(r)return G(r(t,n.t));let o=e.listCardFields;if(o&&!Array.isArray(o)&&o.title?.length){let a=Pe(e,t,o.title,n);return a.length>0?a.join(o.titleSeparator??" "):void 0}let s=dn(e).find(a=>e.fields[a]?.type==="text");return s?G(Pe(e,t,[s],n)[0]):void 0}function Co(e,t,n,r){let o=e.seo?.description;if(o)return G(o(t,r.t));let s=n.find(h=>So.has(e.fields[h]?.type??"")&&G(t[h])!==void 0);if(s)return Oe(String(t[s]));let a=e.listCardFields;if(!a||Array.isArray(a))return;let p=[Pe(e,t,a.subtitle??[],r).join(" "),...Pe(e,t,a.content??[],r)].filter(Boolean);return p.length>0?p.join(To):void 0}function Io(e,t){if(typeof t.status!="string")return;let r={...Ro,...e.seo?.availability}[t.status];return r?`https://schema.org/${r}`:void 0}function wo(e,t){if(e.type==="price"&&t&&typeof t=="object"){let{amount:o,currency:s}=t;return typeof o=="number"&&o>0?{amount:o,currency:G(s)??ln}:void 0}let n=typeof t=="string"?Number(t):t;if(typeof n!="number"||!(n>0))return;let r=e.options?.fieldSpecific;return{amount:n,currency:r?.currency??ln}}function Oo(e,t,n){let r=dn(e),o=v=>e.fields[v],s=Co(e,t,r,n),a=s?ko(s,Eo):void 0,c=r.find(v=>cn.has(o(v)?.type??"")&&un(t[v]).length>0),p=c?un(t[c]):[],h;for(let v of r){let x=o(v);if(!(!x||!xo.has(x.type))&&(h=wo(x,t[v]),h))break}return{title:Ao(e,t,n),description:a||void 0,image:p[0],images:p,price:h,availability:Io(e,t)}}function Po(e,t){return e.title?{"@context":"https://schema.org","@type":"Product",name:e.title,...e.description&&{description:e.description},...e.images.length>0&&{image:e.images},url:t,...e.price&&{offers:{"@type":"Offer",price:e.price.amount,priceCurrency:e.price.currency,...e.availability&&{availability:e.availability},url:t}}}:null}function Do(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function Fo(e){let t=`resource.data.${e.field}`,n=Do(e.value);return`${t} ${e.op} ${n}`}function No(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let n=e.publicCondition.map(Fo).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 _o(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function pn(){let e=new Uint8Array(32);return crypto.getRandomValues(e),fn(e)}async function mn(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return fn(new Uint8Array(r))}async function Uo(){let e=pn(),t=await mn(e);return{codeVerifier:e,codeChallenge:t}}function fn(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mo(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function Lo(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function Bo(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function Vo(e,t,n){try{return await e()}catch{return t(),!1}}var De=new Map;function $o(e,t){if(De.has(t))return De.get(t);let n=e().catch(r=>{throw De.delete(t),r});return De.set(t,n),n}var gn={[w.GUEST]:0,[w.USER]:1,[w.ADMIN]:2,[w.SUPER]:3};function j(e,t){if(!e)return!1;let n=gn[e]??-1,r=gn[t]??1/0;return n>=r}function jo(e){return e?e.role===w.SUPER||e.isSuper===!0?w.SUPER:e.role===w.ADMIN||e.isAdmin===!0?w.ADMIN:e.role===w.USER?w.USER:e.role||w.USER:w.USER}function qo(e,t,n){if(!e)return!1;let r=n??Ye,o=r[e]?.level??-1,s=r[t]?.level??1/0;return o>=s}var yn="__DNDEV_SINGLETONS__";function hn(){if(typeof globalThis<"u"){let e=globalThis,t=e[yn];if(t)return t;let n=new Map;return e[yn]=n,n}return new Map}function ye(e,t){let n=hn();return n.has(e)||n.set(e,t()),n.get(e)}function Wo(e){hn().delete(e)}function Ko(e,...t){let n=null,r=!1;return function(){if(n!==null)return n;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{r=!1}}}function Ho(e){let t=null,n=!1;return function(...o){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(...o):t=e(...o),t}finally{n=!1}}}function Go(e){let t=null,n=!1,r=null;return async function(){if(t!==null)return t;if(n&&r)return r;if(n)throw new Error("Circular dependency detected in async singleton initialization");n=!0;try{return r=e(),t=await r,t}finally{n=!1,r=null}}}function Yo(e,t){return new Proxy({},{get(n,r){if(t.includes(r)){let s=e(),a=s[r];return typeof a=="function"?a.bind(s):a}return e()[r]}})}var te=class{static async getOrCreate(t,n,r={}){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(r.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u"&&process.env.NODE_ENV,r.fallbackFactory){let o=r.fallbackFactory();return this.instances.set(t,o),this.initialized.add(t),o}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let o=await n();return this.instances.set(t,o),this.initialized.add(t),o}catch(o){if(typeof process<"u"&&process.env.NODE_ENV,r.cacheFailures&&this.initialized.add(t),r.fallbackFactory){let s=r.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw o}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()}};T(te,"instances",new Map),T(te,"initializing",new Set),T(te,"initialized",new Set);function Fe(){return ye("providers",()=>({providers:null}))}function zo(e){let t=Fe();t.providers,t.providers=e}function Xo(e){let{providers:t}=Fe();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 Qo(e){return!!Fe().providers?.[e]}function Zo(){Fe().providers=null}var Ne=["text","textarea","richtext","field-array"];function ne(e){return`${e}I18n`}function Jo(e){return Object.keys(e).filter(t=>e[t]?.i18n===!0)}function ei(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function ti(e,t,n){let r=null;for(let o of t){let s=e[ne(o)];if(!s||typeof s!="object")continue;let a=s[n];ei(a)&&(r??(r={...e}),r[o]=a)}return r??e}var ni="dndev-lang";function ri(e,t){if(!e)return null;for(let n of e.split(";")){let r=n.indexOf("=");if(r!==-1&&n.slice(0,r).trim()===t)try{return decodeURIComponent(n.slice(r+1).trim())}catch{return null}}return null}function oi(e){return e?e.split(",").map((t,n)=>{let[r="",...o]=t.trim().split(";"),s=o.find(c=>c.trim().startsWith("q=")),a=s?Number(s.trim().slice(2)):1;return{tag:r.trim(),quality:Number.isFinite(a)?a: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 mt({supported:e,fallback:t,stored:n,preferred:r}){if(n&&e.includes(n))return n;for(let o of r??[]){if(e.includes(o))return o;let s=o.split("-")[0];if(s&&e.includes(s))return s}return t}function _e(e){return e.length>1}var vn="dndev-session";function ii(e){let t=e.split("/"),n=t.indexOf(vn);return n!==1&&n!==2?e:(t.splice(n,1),t.join("/")||"/")}function ft(e,t){let n={language:t.defaultLanguage,path:e,prefixed:!1};if(!_e(t.languages))return n;let r=e.indexOf("/",1),o=r===-1?e.slice(1):e.slice(1,r);return t.languages.includes(o)?{language:o,path:r===-1?"/":e.slice(r),prefixed:!0}:n}function gt(e,t,n){if(!e.startsWith("/")||e.startsWith("//")||!_e(n.languages))return e;let r=e.search(/[?#]/),o=r===-1?e:e.slice(0,r),s=r===-1?"":e.slice(r),a=ft(o,n),c=a.prefixed?a.language:t;return c===n.defaultLanguage?`${a.path}${s}`:`/${c}${a.path==="/"?"":a.path}${s}`}function si(e,t,n){return Object.fromEntries(n.languages.map(r=>[r,`${t}${gt(e,r,n)}`]))}function ai(e,t,n){let r=ft(e,n);if(!_e(n.languages))return{type:"pass",language:r.language,path:r.path};if(r.prefixed)return r.language===n.defaultLanguage?{type:"redirect",language:r.language,path:r.path,location:r.path,permanent:!0}:{type:"pass",language:r.language,path:r.path};let o=mt({supported:n.languages,fallback:n.defaultLanguage,stored:t.stored,preferred:t.preferred});return o!==n.defaultLanguage?{type:"redirect",language:o,path:r.path,location:gt(r.path,o,n),permanent:!1}:{type:"rewrite",language:n.defaultLanguage,path:r.path,destination:`/${n.defaultLanguage}${r.path==="/"?"":r.path}`}}function li(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function ui(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function ci(e){if(ui(e))return e.visibility}function bn(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?j(t,"admin"):n==="owner"?!1:j(t,n)}function di(e,t,n){for(let r of n.ownerFields)if(e[r]===t)return!0;return!1}function yt(e,t,n){if(!e||typeof e!="object"||!("entries"in e)||!e.entries)return[];let r=e.entries,o=[],{documentData:s,uid:a,ownership:c}=n??{},p=c&&a!=null&&s&&di(s,a,c);for(let[h,v]of Object.entries(r)){let x=ci(v);if(x==="owner"){p&&o.push(h);continue}bn(x,t)&&o.push(h)}return o}function pi(e,t,n,r){if(!e)return{};let o=r?.uid!=null&&r?.ownership!=null?{documentData:r.documentData??e,uid:r.uid,ownership:r.ownership}:void 0,s=yt(t,n,o),a={};for(let c of s)Object.prototype.hasOwnProperty.call(e,c)&&(a[c]=e[c]);return a}function he(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,r=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(r)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function En(e){return typeof e=="object"&&e!==null}function Ue(e){if(En(e)){if(En(e.entries))return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let n=Ue(t);if(n)return n}if(e.wrapped)return Ue(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let n=Ue(t);if(n)return n}}}function mi(e){let t=Ue(e);if(!t)return!1;for(let n of Object.values(t)){let r=n?.visibility;if(r!==void 0&&r!=="guest")return!0}return!1}import*as Sn from"valibot";function xn(e,t){let n=Sn.parse(U,t??Te);return{...n,userId:e,isActive:n.status===xe.ACTIVE,features:n.features??[]}}var Me=class{constructor(t={}){T(this,"store",new Map);T(this,"maxAttempts");T(this,"lockoutMs");T(this,"sessionTimeoutMs");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 r=Math.ceil((n.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${r} minute${r===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let n=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(n);let r=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return r.attempts+=1,r.lastAttempt=n,r.attempts>=this.maxAttempts&&(r.lockedUntil=n+this.lockoutMs),this.store.set(t,r),{attempts:r.attempts,locked:r.lockedUntil!==null&&Date.now()<r.lockedUntil,lockedUntil:r.lockedUntil}}_evictExpired(t){for(let[n,r]of this.store)r.lockedUntil!==null&&t>r.lockedUntil?this.store.delete(n):r.lockedUntil===null&&t-r.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 fi(e,t){if(t.includes(".")){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}return e[t]}function gi(e,t){let n=fi(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 yi(e){return e instanceof re||"expression"in e?e.expression:e}function Y(e,t){let n=yi(e);if(n.type==="condition")return gi(n,t);let{logic:r,conditions:o}=n;return r==="and"?o.every(s=>Y(s,t)):o.some(s=>Y(s,t))}function hi(e,t){return e?{visible:e.visible?Y(e.visible,t):!0,disabled:e.disabled?Y(e.disabled,t):!1,required:e.required?Y(e.required,t):!1,readonly:e.readonly?Y(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var re=class e{constructor(t){T(this,"expression");this.expression=t}get type(){return this.expression.type}or(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="or"?new e({type:"group",logic:"or",conditions:[...r.conditions,n]}):new e({type:"group",logic:"or",conditions:[r,n]})}and(t){let n=t instanceof e?t.expression:t,r=this.expression;return r.type==="group"&&r.logic==="and"?new e({type:"group",logic:"and",conditions:[...r.conditions,n]}):new e({type:"group",logic:"and",conditions:[r,n]})}};function vi(e){function t(n,r){return new re({type:"condition",field:e,operator:n,value:r})}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 bi(e){let t=e instanceof re?e.expression:e,n=new Set;function r(o){if(o.type==="condition")n.add(o.field);else for(let s of o.conditions)r(s)}return r(t),n}var Ei=new Set(["http:","https:","mailto:","tel:","blob:"]);function Si(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(Ei.has(n.protocol))return t}catch{return t}return""}function xi(){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 Ti=3e4,Ri=15e3;function ki(e,t,n){if(n?.aborted)return Promise.reject(Tn(n.reason));let r=t>0;return!r&&!n?e:new Promise((o,s)=>{let a=!1,c;function p(){a=!0,c!==void 0&&(clearTimeout(c),c=void 0),n&&n.removeEventListener("abort",h)}function h(){a||(p(),s(Tn(n?.reason)))}n&&n.addEventListener("abort",h,{once:!0}),r&&(c=setTimeout(()=>{a||(p(),s(Ai(t)))},t)),e.then(v=>{a||(p(),o(v))},v=>{a||(p(),s(v))})})}function Ai(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function Tn(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 ve(e,t){let n=new Date(e),r=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==r&&n.setDate(0),n}function ht(e,t){let n=new Date(e),r=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==r&&n.setDate(0),n}function Ci(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=ve(t,1):e==="3months"?n=ve(t,3):e==="6months"?n=ve(t,6):e==="1year"?n=ht(t,1):e==="2years"?n=ht(t,2):n=ve(t,1),n.toISOString()}function Ii(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function wi(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 Oi(e){let t={};for(let[n,r]of Object.entries(e)){if(typeof r!="string")throw new Error(`Metadata value for key '${n}' must be a string, got ${typeof r}`);if(/<[^>]*>/.test(r))throw new Error(`Metadata value for key '${n}' must not contain HTML`);let o=r;if(o.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]=o}return t}function Pi(e,t=!0){let n=process.env[e];if(t&&!n)throw new Error(`Required environment variable '${e}' is not set`);return n||""}function Di(e,t){if(!e)return null;let n=`${encodeURIComponent(t)}=`,r=e.split(";");for(let o=0;o<r.length;o++){let s=r[o];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 Gp(e,t){return Object.assign(e,{metadata:t})}import*as ie from"valibot";import*as u from"valibot";var vt=ee.map(e=>({value:e,label:`crud:status.${e}`})),Xp=ke;var Fi=[...de,"status"];function Qp(e){return Fi.some(t=>t===e)}function kn(e){return de.some(t=>t===e)}var C={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...vt]}},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 Le=e=>{let t=[];return e.validation?.minLength!==void 0&&t.push(u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(u.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(u.regex(new RegExp(e.validation.pattern),"Invalid format")),t.length>0?u.pipe(u.string(),...t):u.string()},Ni=()=>u.pipe(u.string(),u.email("Invalid email address")),_i=e=>e.validation?.minLength!==void 0?u.pipe(u.string(),u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u.string(),Ui=()=>u.pipe(u.string(),u.url("Invalid URL")),oe=e=>{let t=[];return e.validation?.min!==void 0&&t.push(u.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(u.maxValue(e.validation.max,`Must be at most ${e.validation.max}`)),t.length>0?u.pipe(u.number(),...t):u.number()},An=()=>u.boolean(),bt=()=>u.pipe(u.string(),u.check(e=>!isNaN(new Date(e).getTime()),"Invalid date format")),Mi=/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/,Li=/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/,Bi=/^\d{4}-(?:0[1-9]|1[0-2])$/,Vi=()=>u.pipe(u.string(),u.regex(Mi,"Invalid time format")),$i=()=>u.pipe(u.string(),u.regex(Li,"Invalid week format")),ji=()=>u.pipe(u.string(),u.regex(Bi,"Invalid month format")),_n=u.object({url:u.string(),filename:u.string(),size:u.number(),mimeType:u.nullish(u.string()),uploadedAt:u.nullish(u.string())}),Cn=()=>_n,In=()=>u.array(_n),Un=u.object({fullUrl:u.string(),thumbUrl:u.string()}),qi=()=>u.union([u.string(),Un]),Wi=()=>u.array(u.union([u.string(),Un])),Ki=()=>u.object({lat:u.number(),lng:u.number()}),Hi=()=>u.object({formatted_address:u.string(),latitude:u.number(),longitude:u.number(),street_number:u.nullish(u.string()),route:u.nullish(u.string()),locality:u.nullish(u.string()),administrative_area_level_1:u.nullish(u.string()),administrative_area_level_2:u.nullish(u.string()),country:u.nullish(u.string()),postal_code:u.nullish(u.string())}),Gi=()=>u.record(u.string(),u.unknown()),Yi=()=>u.array(u.unknown()),zi=()=>u.array(u.record(u.string(),u.unknown())),Et=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?u.picklist(t.map(n=>n.value)):u.union([u.string(),u.number()])},Xi=e=>{let t=e.validation?.options;return Array.isArray(t)&&t.length>0?u.array(u.picklist(t.map(n=>n.value))):u.array(u.string())},Mn=()=>u.pipe(u.string(),u.minLength(1,"Invalid ID format")),St=()=>u.string(),Qi=/^(?:\+[1-9](?:[ .-]?\d){7,14}|0[1-9](?:[ .-]?\d{2}){4})$/,Zi=e=>{let t=e.validation?.pattern?new RegExp(e.validation.pattern):Qi;return u.pipe(u.string(),u.regex(t,"Invalid phone number"))},Ji=e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,r=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$";return u.pipe(u.string(),u.minLength(t,`IBAN must be at least ${t} characters`),u.maxLength(n,`IBAN must not exceed ${n} characters`),u.regex(new RegExp(r),"Invalid IBAN format"))},wn=()=>u.never();function Ln(e){let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue)return[t.checkedValue,t.uncheckedValue]}var es=e=>{let t=Ln(e);return t?u.picklist(t):u.boolean()},On=u.looseObject({gdprConsent:u.literal(!0),gdprConsentDate:u.optional(u.string()),gdprConsentVersion:u.optional(u.string())},"GDPR consent must be given"),ts=e=>e.validation?.required?On:u.union([u.literal(!1),On]),ns=()=>u.object({amount:u.number(),currency:u.optional(u.string()),vatIncluded:u.optional(u.boolean()),discountPercent:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(100)))}),Bn={text:{schema:Le,kind:"text"},textarea:{schema:Le,kind:"text"},richtext:{schema:Le,kind:"text"},color:{schema:Le,kind:"text"},email:{schema:Ni,kind:"text"},password:{schema:_i,kind:"text"},url:{schema:Ui,kind:"text"},tel:{schema:Zi,kind:"text"},iban:{schema:Ji,kind:"text"},number:{schema:oe,kind:"number"},currency:{schema:oe,kind:"number"},range:{schema:oe,kind:"number"},year:{schema:oe,kind:"number"},rating:{schema:oe,kind:"number"},duration:{schema:oe,kind:"number"},price:{schema:ns,kind:"json"},boolean:{schema:An,kind:"boolean"},checkbox:{schema:An,kind:"boolean"},switch:{schema:es,kind:e=>Ln(e)?"text":"boolean"},gdprConsent:{schema:ts,kind:"json"},date:{schema:bt,kind:"date"},"datetime-local":{schema:bt,kind:"timestamp"},timestamp:{schema:bt,kind:"timestamp"},time:{schema:Vi,kind:"time"},week:{schema:$i,kind:"text"},month:{schema:ji,kind:"text"},file:{schema:Cn,kind:"json"},files:{schema:In,kind:"json"},document:{schema:Cn,kind:"json"},documents:{schema:In,kind:"json"},image:{schema:qi,kind:"json"},images:{schema:Wi,kind:"json"},geopoint:{schema:Ki,kind:"json"},address:{schema:Hi,kind:"json"},map:{schema:Gi,kind:"json"},array:{schema:Yi,kind:"json"},"field-array":{schema:zi,kind:"json"},select:{schema:Et,kind:"text"},radio:{schema:Et,kind:"text"},combobox:{schema:Et,kind:"text"},multiselect:{schema:Xi,kind:"json"},reference:{schema:Mn,kind:"ref"},hidden:{schema:St,kind:"text"},avatar:{schema:St,kind:"text"},badge:{schema:St,kind:"text"},submit:{schema:wn,kind:"text"},reset:{schema:wn,kind:"text"}},rs=new Set($t);function os(e){return rs.has(e)}var is=new Set(["optional","exact_optional","nullable","nullish","undefinedable","non_nullable","non_nullish","non_optional"]),ss=new Set(["object","loose_object","strict_object","object_with_rest","record","array","tuple","loose_tuple","strict_tuple","tuple_with_rest","intersect"]),as=new Set(["trim","trim_start","trim_end","to_lower_case","to_upper_case","to_min_value","to_max_value","normalize","brand","flavor","readonly"]),ls={iso_date:"date",iso_time:"time",iso_time_second:"time",iso_date_time:"timestamp",iso_timestamp:"timestamp"};function L(e,t){return t in e?Reflect.get(e,t):void 0}function Pn(e){if(typeof e=="string")return"text";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function Dn(e){if(e.length===0||e.some(n=>n===void 0))return;let t=new Set(e);return t.size===1?e[0]:t.has("json")?"json":void 0}function Be(e){if(typeof e!="object"||e===null)return;let t=L(e,"type");if(typeof t!="string")return;let n=us(e,t),r=L(e,"pipe");if(Array.isArray(r))for(let o of r.slice(1)){if(typeof o!="object"||o===null)continue;let s=L(o,"kind"),a=L(o,"type");if(typeof a=="string"){if(s==="schema")n=Be(o);else if(s==="transformation")as.has(a)||(n=void 0);else if(s==="validation"){a==="integer"&&n==="number"&&(n="integer");let c=ls[a];c&&n==="text"&&(n=c)}}}return n}function us(e,t){if(is.has(t))return Be(L(e,"wrapped"));if(ss.has(t))return"json";switch(t){case"string":return"text";case"number":return"number";case"bigint":return"integer";case"boolean":return"boolean";case"date":return"timestamp";case"literal":return Pn(L(e,"literal"));case"picklist":case"enum":{let n=L(e,"options");return Array.isArray(n)?Dn(n.map(Pn)):void 0}case"union":case"variant":{let n=L(e,"options");if(!Array.isArray(n))return;let r=n.filter(o=>{let s=typeof o=="object"&&o!==null?L(o,"type"):void 0;return s!=="null"&&s!=="undefined"});return Dn(r.map(Be))}default:return}}function Fn(e,t){let{kind:n}=Bn[e];return typeof n=="function"?n(t):n}function xt(e,t=e.name){let n=e.validation?.reference,r=n?{ref:n}:{},o=e.type,s=os(o)?o:void 0,a=e.validation?.schema;if(a){let c=(n?"ref":void 0)??Be(a)??(s?Fn(s,e):void 0);if(!c)throw new Error(`Field '${t}' (custom type '${o}'): the storage kind of its validation.schema cannot be read. Root the schema on a Valibot string, number, boolean, picklist, object or array schema, or set validation.reference.`);return{schema:a,kind:c,...r}}if(n)return{schema:Mn(),kind:"ref",...r};if(s)return{schema:Bn[s].schema(e),kind:Fn(s,e)};throw new Error(`Field '${t}' has custom type '${o}' and no value shape. Add validation.schema (a Valibot schema of the stored value) or validation.reference (the referenced collection) to the field, or use a built-in type.`)}function cs(e){return e.validation?.required===!0?"always":e.conditions?.required!==void 0?"conditional":"never"}function ds(e,t){return t.visibility==="hidden"||t.editable===V.GENERATED||kn(e)?"never":t.editable===V.FALSE?"program":t.editable===V.COMPUTED?"derived":"user"}function ps(e,t){return(n,r)=>{if(t!=="user")return!1;let o=e.editable;return o===void 0||o===V.TRUE?e.visibility!=="technical":o===V.CREATE_ONLY?r==="create":typeof o=="string"?j(n,o):!1}}function ms(e,t,n){let r=ds(e,t);return{value:xt(t,`${n}.${e}`),required:cs(t),write:r,editableFor:ps(t,r),visibleAt:t.visibility,...t.i18n===!0&&{companion:ne(e)}}}var Nn=new WeakMap;function Ve(e){let t=Nn.get(e);if(t)return t;let n={};for(let[o,s]of Object.entries(e.fields))n[o]=ms(o,s,e.name);let r={name:e.name,collection:e.collection,fields:n};return Nn.set(e,r),r}function fs(e,t){return t?ie.pipe(e,ie.check(n=>n!=="","Required")):ie.nullish(e)}function z(e){return fs(xt(e).schema,e.validation?.required)}var Vn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function $n(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function jn(e){return typeof e=="object"&&e!==null}function $e(e,t=""){if(Array.isArray(e))e.forEach((n,r)=>{let o=`${t}[${r}]`;if(typeof n=="string"&&$n(n)){if(!Vn.test(n))throw k(new Error(`Invalid date format for ${o}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for ${o}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:o,value:n},severity:"error"})}else jn(n)&&$e(n,o)});else if(typeof e=="object"&&e!==null)for(let[n,r]of Object.entries(e)){let o=t?`${t}.${n}`:n;if(typeof r=="string"&&$n(r)){if(!Vn.test(r))throw k(new Error(`Invalid date format for field "${o}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for field "${o}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:o,value:r},severity:"error"})}else jn(r)&&$e(r,o)}}import*as Wn from"valibot";var Tt={};function lm(e){Tt.uniqueConstraintValidator=e}async function qn(e,t,n){let{uniqueFields:r=[],collection:o}=e.metadata;if(r.length!==0){if(!Tt.uniqueConstraintValidator){process.env.NODE_ENV;return}await Promise.all(r.map(async({field:s,errorMessage:a})=>{let c=t[s];if(c==null)return;if(await Tt.uniqueConstraintValidator.checkDuplicate(o,s,c,n))throw k(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}}async function pm(e,t,n,r){Wn.parse(e,t),$e(t),await qn(e,t,r),e.metadata.customValidate&&await e.metadata.customValidate(t,n)}function gs(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Sm(e){if(!gs(e)){let t=e,n=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw k(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:n}})}return e.metadata.collection}var Kn=()=>ye("entity-registry",()=>new Map);function Hn(e){Kn().set(e.collection,e)}function ys(e){return Kn().get(e)}var hs=new Set(["__proto__","constructor","prototype"]);function vs(e){for(let t of Object.keys(e.fields))if(hs.has(t))throw k(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 bs(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:V.CREATE_ONLY,validation:{required:!0,reference:n}}}function Es(e,t){if(!t||t.length===0)return e.map(o=>({value:o.value,label:o.label}));let n=e.map(o=>({value:o.value,label:o.label})),r=new Set(e.map(o=>o.value));for(let o of t)r.has(o.value)||n.push(o);return n}function Ss(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let n=0;n<e.uniqueKeys.length;n++){let r=e.uniqueKeys[n];if(!r)continue;if(!r.fields||r.fields.length===0)throw k(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 o=r.fields.filter(s=>!t.has(s));if(o.length>0)throw k(new Error(`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`uniqueKeys[${n}] for entity '${e.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:n,invalidFields:o},severity:"error"})}}function xs(e){let{form:t,fields:n}=e,r=Object.keys(n);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw k(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 o=t.steps.flatMap(p=>p.fields),s=o.filter(p=>!r.includes(p));if(s.length>0)throw k(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 a=new Set(o);r.filter(p=>!a.has(p)).length>0&&process.env.NODE_ENV}t.rules&&t.rules.forEach((o,s)=>{let c=(Array.isArray(o.condition)?o.condition.map(v=>v.field):[o.condition.field]).filter(v=>!r.includes(v));if(c.length>0)throw k(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${c.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${c.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:c,operation:"validateFormConfig"},severity:"error"});let h=[...o.showFields||[],...o.hideFields||[],...o.disableFields||[],...o.enableFields||[]].filter(v=>!r.includes(v));if(h.length>0)throw k(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:h,operation:"validateFormConfig"},severity:"error"})}),Object.entries(n).forEach(([o,s])=>{if(s.dependsOn&&!r.includes(s.dependsOn.field))throw k(new Error(`Field '${o}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${o}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:o,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Ts(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 Om(e){let t=e;try{vs(t),xs(t);let n=Ts(t),r={...t.fields,...C,...t.fields.createdAt&&{createdAt:{...C.createdAt,...t.fields.createdAt,type:C.createdAt.type,visibility:C.createdAt.visibility}},...t.fields.updatedAt&&{updatedAt:{...C.updatedAt,...t.fields.updatedAt,type:C.updatedAt.type,visibility:C.updatedAt.visibility}},...t.fields.createdById&&{createdById:{...C.createdById,...t.fields.createdById,type:C.createdById.type,visibility:C.createdById.visibility}},...t.fields.updatedById&&{updatedById:{...C.updatedById,...t.fields.updatedById,type:C.updatedById.type,visibility:C.updatedById.visibility}},...t.fields.status&&{status:{...C.status,...t.fields.status,validation:{...C.status.validation,...t.fields.status.validation,options:Es(vt,t.fields.status.validation?.options)}}},...t.scope&&{[t.scope.field]:bs(t.scope)}};if(t.listFields){let c=new Set(Object.keys(r)),p=t.listFields.filter(h=>!c.has(h));if(p.length>0)throw k(new Error(`Entity '${t.name}' defines listFields that do not exist: ${p.join(", ")}`),{userMessage:`Entity '${t.name}' defines listFields that do not exist: ${p.join(", ")}`,context:{entityName:t.name,invalidFields:p,operation:"defineEntity"},severity:"error"})}if(t.listCardFields){let c=new Set(Object.keys(r)),h=he(t).filter(v=>!c.has(v));if(h.length>0)throw k(new Error(`Entity '${t.name}' defines listCardFields that do not exist: ${h.join(", ")}`),{userMessage:`Entity '${t.name}' defines listCardFields that do not exist: ${h.join(", ")}`,context:{entityName:t.name,invalidFields:h,operation:"defineEntity"},severity:"error"})}if(t.uniqueKeys){let c=new Set(Object.keys(r));Ss(t,c)}let o={...Qe,...t.access||{}},s=t.namespace||`entity-${t.name.toLowerCase()}`,a={...t,form:n,fields:r,access:o,namespace:s,...t.search&&{search:t.search},...t.defaultSort&&{defaultSort:t.defaultSort}};try{Ve(a)}catch(c){let p=c instanceof Error?c.message:String(c);throw k(new Error(p),{userMessage:p,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}return Hn(a),a}catch(n){throw k(n,{userMessage:`Failed to define entity '${t.name}'`,context:{entityName:t.name,operation:"defineEntity"},severity:"error"})}}import*as I from"valibot";function D(e){let t=e?.status;return typeof t=="string"?t:null}function qe({op:e,status:t,storedStatus:n}){return je(t??n,"saveIncomplete")?"draft":e==="create"?"create":"update"}function Gn({op:e,status:t,storedStatus:n}){if(e!=="update")return!1;let r=t??n;return r==null||r===n?!1:je(n,"holdIncomplete")&&!je(r,"holdIncomplete")}function Yn(e){return e!=null&&Object.hasOwn(M,e)?M[e]:Bt}function je(e,t){return Yn(e)[t]}function We(e,t){let n=Yn(e).read;return n==="guest"||j(t,n)}function Rt(e){return Object.keys(M).filter(t=>M[t][e])}function Q(e,t){return Object.assign(e,{visibility:t})}function X(e,t){return Object.assign(e,{metadata:{collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys},...t.security&&{security:t.security}}})}function Rs(e){let t=z(e);return Q(t,e.visibility)}function ks(e,t){if(!Ne.includes(t.type))throw new Error(`Field '${e}' has i18n: true but type '${t.type}'. Translatable types: ${Ne.join(", ")}.`);let n=z({...t,validation:{...t.validation,required:!1}});return Q(I.optional(I.nullable(I.record(I.string(),n))),t.visibility)}function se(e,t){for(let n of Object.keys(e)){let r=t[n];r?.i18n===!0&&(e[ne(n)]=ks(n,r))}return e}function kt(e){let t=z({...e,validation:{...e.validation,required:!1}});return Q(t,e.visibility)}function As(e){return e.validation?.required?Q(I.optional(z(e)),e.visibility):kt(e)}function Vm(e){let t=e.fields,n=Ve(e).fields,r=A=>n[A]?.write==="never",o={};for(let[A,P]of Object.entries(t))n[A]?.visibleAt!=="hidden"&&(o[A]=kt(P));let s=X(I.object(se({...o},t)),e),a={};for(let[A,P]of Object.entries(t))r(A)||(a[A]=Rs(P));let c=X(I.object(se({...a},t)),e),p={};for(let[A,P]of Object.entries(t))if(!r(A))if(A==="status"){let q=I.picklist(Rt("saveIncomplete"));p[A]=Q(q,P.visibility)}else p[A]=kt(P);let h=X(I.object(se({...p},t)),e),v={};for(let[A,P]of Object.entries(t))r(A)||(v[A]=As(P));v.id=Q(z(C.id),"technical");let x=X(I.object(se({...v},t)),e),B;if(e.listFields&&e.listFields.length>0){let A=["id","status"],P=[...new Set([...A,...e.listFields])];B={};for(let q of P){let le=o[q];le&&(B[q]=le)}}else B=o;let Ee=X(I.object(se({...B},t)),e),R,J=he(e);if(J.length>0){let A=["id","status"],P=[...new Set([...A,...J])];R={};for(let q of P){let le=o[q];le&&(R[q]=le)}}else R=o;let nr=X(I.object(se({...R},t)),e),rr=X(I.object({id:Q(z(C.id),"technical")}),e);return{create:c,draft:h,update:x,get:s,list:Ee,listCard:nr,delete:rr}}function jm(e,t,n=1,r=!1){let o=[];if(r)for(let s=t;s>=e;s-=n)o.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=n)o.push({value:String(s),label:String(s)});return o}var Z=new Map;function Wm(e,t){Z.has(e)&&process.env.NODE_ENV,Z.set(e,t)}function Km(e){Z.delete(e)}function Hm(e){let t=Z.get(e);return t?t():(process.env.NODE_ENV,null)}function Gm(e){return Z.has(e)}function Ym(){return Array.from(Z.keys())}function zm(){Z.clear()}import*as g from"valibot";var Cs=g.record(g.string(),g.unknown()),Is=g.object({id:g.string(),patch:g.record(g.string(),g.unknown())}),ws=g.string(),Qm=g.object({inserts:g.optional(g.array(Cs)),updates:g.optional(g.array(Is)),deletes:g.optional(g.array(ws))}),Os=g.object({insertedIds:g.array(g.string()),updatedIds:g.array(g.string()),deletedIds:g.array(g.string())}),Ps=g.variant("op",[g.object({op:g.literal("insert"),index:g.pipe(g.number(),g.integer(),g.minValue(0)),id:g.optional(g.string()),error:g.string()}),g.object({op:g.literal("update"),id:g.string(),index:g.optional(g.pipe(g.number(),g.integer(),g.minValue(0))),error:g.string()}),g.object({op:g.literal("delete"),id:g.string(),index:g.optional(g.pipe(g.number(),g.integer(),g.minValue(0))),error:g.string()})]),Ds=g.object({...Os.entries,failed:g.optional(g.array(Ps),()=>[])});function Zm(e,t){let n=g.parse(Ds,t),r=c=>{throw new Error(`Invalid bulk acknowledgement: ${c}`)},o=e.inserts??[],s=new Set;for(let c of n.failed){if(c.op!=="insert")continue;(c.index>=o.length||s.has(c.index))&&r("unknown or duplicate insert index");let p=o[c.index];c.id!==void 0&&c.id!==p.id&&r("contradictory insert identity"),s.add(c.index)}n.insertedIds.length+s.size!==o.length&&r("missing or extra insert outcomes"),new Set(n.insertedIds).size!==n.insertedIds.length&&r("duplicate inserted ID");let a=new Set([...s].map(c=>o[c].id).filter(c=>typeof c=="string"));n.insertedIds.some(c=>a.has(c))&&r("insert ID both successful and failed");for(let c of["update","delete"]){let p=c==="update"?(e.updates??[]).map(({id:R})=>R):e.deletes??[],h=c==="update"?n.updatedIds:n.deletedIds,v=new Map;for(let R of p)v.set(R,(v.get(R)??0)+1);let x=new Map,B=new Set;for(let R of n.failed)R.op===c&&((!v.has(R.id)||R.index!==void 0&&p[R.index]!==R.id)&&r(`unknown or contradictory ${c} identity`),R.index!==void 0&&(B.has(R.index)&&r(`duplicate ${c} failure index`),B.add(R.index)),x.set(R.id,(x.get(R.id)??0)+1));let Ee=p.filter(R=>!x.has(R));for(let[R,J]of x)J!==v.get(R)&&r(`duplicate or ambiguous ${c} failures`);(Ee.length!==h.length||Ee.some((R,J)=>h[J]!==R))&&r(`missing, duplicate, unknown or contradictory ${c} outcomes`)}return n}function Jm(e){let t=new Set((e.updates??[]).map(a=>a.id)),n=e.deletes??[],r=[];for(let a of n)t.has(a)&&r.push(a);if(r.length>0)return{collisions:r,where:"updates-deletes"};let o=e.inserts??[],s=[];for(let a of o)typeof a.id=="string"&&t.has(a.id)&&s.push(a.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as zn from"valibot";function Fs(e,t){if(e.ok)return e.written;let n=e.issues.map(r=>`${r.path?.map(o=>String(o.key)).join(".")||"root"}: ${r.message}`).join("; ");throw new S(`Validation failed in ${t}: ${n}`,"validation-failed",{details:{issues:e.issues},source:"validation"})}function Xn(e){let t=e.entries;if(!t||typeof t!="object")throw new S("CRUD write rules: a write schema must be an object schema (createSchemas(entity))","internal");return Object.keys(t)}function Ke(e,t){let n=[e.create,e.draft,e.update].filter(o=>o!==void 0);if(n.some(o=>o.type==="loose_object"))return[];let r=new Set([...n.flatMap(Xn),...de]);return Object.keys(t).filter(o=>!r.has(o))}function Qn(e,t){let n={};for(let r of Xn(t))n[r]=null;for(let[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n}function be(e,t,n,r,o){let s=zn.safeParse(t,n);if(!s.success)return{ok:!1,schemaKey:e,issues:[...s.issues],unknownKeys:o};let a=s.output,c={};for(let p of Object.keys(r))p!=="id"&&Object.hasOwn(a,p)&&(c[p]=a[p]);return{ok:!0,schemaKey:e,written:c,unknownKeys:o}}function Zn(e){return D(e)??ke}function Ns(e,t){let n=Zn(t),r=qe({op:"create",status:n}),o={...t,status:n},s=be(r,r==="draft"?e.draft:e.create,o,o,Ke(e,t));return s.ok?{...s,written:{...s.written,status:n}}:s}function Jn(e){return D(e)!==Ze}function er(e,t){let n={op:"update",status:D(e),storedStatus:D(t)};return{schemaKey:qe(n)==="draft"?"draft":"update",whole:Gn(n)}}function tr(e,{id:t,patch:n,stored:r}){let o=D(n);if(!r&&Jn(n))throw new S(`CRUD update rules: row "${t}" needs its stored row (the row's status${o===null?"":" and the publish check"} come from it); read it before the update.`,"internal");let{schemaKey:s,whole:a}=er(n,r),c=Ke(e,n);if(r&&a)return be(s,e.update,Qn({...r,...n,id:t},e.update),n,c);let p=s==="draft"?{...n,status:D(n)??D(r),id:t}:{...n,id:t};return be(s,s==="draft"?e.draft:e.update,p,n,c)}function _s(e,t){return tr(e,{id:t,patch:{status:Ze}})}function Us(e){return ee.filter(t=>!We(t,e))}function Ms(e,t){return We(D(e),t)}import*as b from"valibot";var xf=b.pipe(b.string(),b.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),Ls=b.picklist(["ephemeral","session","persistent"]),Bs=b.object({title:b.optional(b.string()),pinnable:b.optional(b.boolean()),preferredHeight:b.optional(b.pipe(b.number(),b.minValue(0)))}),Vs=b.object({id:b.pipe(b.string(),b.minLength(1)),kind:b.pipe(b.string(),b.minLength(1)),lifetime:b.optional(Ls,"ephemeral"),metadata:b.optional(Bs),payload:b.unknown()}),$s=b.object({widgetId:b.pipe(b.string(),b.minLength(1)),action:b.pipe(b.string(),b.minLength(1)),payload:b.unknown()}),ae=new Map;function Tf(e){if(ae.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);ae.set(e.kind,e)}function Rf(e){return ae.get(e)}function kf(){return Array.from(ae.values())}function Af(e,t){let n=b.safeParse(Vs,e);if(!n.success)return{ok:!1,reason:`Invalid canvas block envelope: ${He(n.issues)}`};let r=ae.get(n.output.kind);if(!r)return{ok:!1,reason:`Unknown widget kind: "${n.output.kind}"`};let o=b.safeParse(r.schema,n.output.payload);if(!o.success)return{ok:!1,reason:`Payload rejected by "${n.output.kind}" schema: ${He(o.issues)}`};if(t?.caller!==void 0){let a=t.caller.access;if(!js(r.surface,a))return{ok:!1,reason:`surface_forbidden: widget "${n.output.kind}" surface=${r.surface} not reachable by caller access=${a===null?"null":a}`}}return{ok:!0,value:{...n.output,payload:o.output},widget:r}}function js(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function Cf(e,t){let n=b.safeParse($s,e);if(!n.success)return{ok:!1,reason:`Invalid canvas event envelope: ${He(n.issues)}`};let r=ae.get(t);if(!r)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let o=r.actions[n.output.action];if(!o)return{ok:!1,reason:`Widget "${t}" has no action "${n.output.action}"`};let s=b.safeParse(o,n.output.payload);return s.success?{ok:!0,value:{...n.output,payload:s.output},widget:r}:{ok:!1,reason:`Payload rejected by "${t}.${n.output.action}" schema: ${He(s.issues)}`}}function He(e){return e.map(t=>{let n=t.path?.map(r=>String(r.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}export{hl as AGGREGATE_FILTER_OPERATORS,yl as AGGREGATE_OPERATIONS,lr as AIChatRequestSchema,cr as AIChatResponseSchema,Ct as AIMessageSchema,Zs as AIProviderConfigSchema,ar as AIToolCallSchema,sr as AIToolDefinitionSchema,ur as AIUsageSchema,Hs as AI_ERROR_CODES,Ws as AI_MODELS,F as AI_PROVIDERS,Se as AI_ROLES,Gs as AI_TIERS,zs as AI_TOKEN_PRICING,ru as AUTH_EVENTS,zt as AUTH_PARTNERS,Ea as AUTH_PARTNER_STATE,jt as AtomicBulkError,Me as AuthHardening,It as AuthUserSchema,de as BACKEND_GENERATED_FIELD_NAMES,iu as BILLING_EVENTS,Or as BREAKPOINT_RANGES,et as BREAKPOINT_THRESHOLDS,Bn as BUILTIN_VALUES,ee as BUILT_IN_STATUSES,Wt as BulkAcrossCycleError,qt as BulkCollisionError,ws as BulkDeleteIdSchema,Cs as BulkInsertSchema,Kt as BulkNotImplementedError,Ps as BulkOutcomeFailureSchema,Ds as BulkOutcomeSchema,Qm as BulkRequestSchema,Os as BulkResponseSchema,Is as BulkUpdateSchema,Ye as COMMON_TIER_CONFIGS,rl as CONFIDENCE_LEVELS,Qt as CONSENT_CATEGORY,nl as CONTEXTS,W as CRUD_OPERATORS,st as CURRENCY_MAP,Bt as CUSTOM_STATUS,Vs as CanvasBlockSchema,$s as CanvasEventSchema,Ls as CanvasLifetimeSchema,Bs as CanvasWidgetMetadataSchema,gr as CheckoutLineItemInputSchema,Lt as CheckoutSessionMetadataSchema,re as ConditionBuilder,Nt as CreateCheckoutSessionRequestSchema,_t as CreateCheckoutSessionResponseSchema,Ot as CustomClaimsSchema,Ks as DEFAULT_AI_CONFIG,Ys as DEFAULT_AI_MARKUP,Ri as DEFAULT_CRUD_TIMEOUT,Qe as DEFAULT_ENTITY_ACCESS,K as DEFAULT_ERROR_MESSAGES,Dr as DEFAULT_LAYOUT_PRESET,ke as DEFAULT_STATUS,vt as DEFAULT_STATUS_OPTIONS,Xp as DEFAULT_STATUS_VALUE,Te as DEFAULT_SUBSCRIPTION,Ti as DEFAULT_UPLOAD_TIMEOUT,dc as DENSITY,S as DoNotDevError,V as EDITABLE,jl as EMAIL_ERROR_CODES,$l as EMAIL_PROVIDERS,ba as EMAIL_VERIFICATION_STATUS,Ae as ENTITY_HOOK_ERRORS,tl as ENVIRONMENTS,pe as ERROR_CODES,Ql as ERROR_SEVERITY,Zl as ERROR_SOURCE,Ht as EntityHookError,ze as FEATURES,pc as FEATURE_CONSENT_MATRIX,ol as FEATURE_STATUS,an as FIELD_TEXT_FORMATTERS,$t as FIELD_TYPES,Je as FIREBASE_ERROR_MAP,Fr as FOOTER_MODE,Gt as GITHUB_PERMISSION_LEVELS,Ar as HIDDEN_STATUSES,ni as LANGUAGE_COOKIE,Nr as LAYOUT_PRESET,ml as LIST_SCHEMA_TYPE,Pt as MAX_CHECKOUT_LINE_ITEMS,Ft as MAX_SHIPPING_RATE_IDS,au as OAUTH_EVENTS,Xt as OAUTH_PARTNERS,pl as ORDER_DIRECTION,Xu as PARTNER_ICONS,uu as PAYLOAD_EVENTS,Xe as PERMISSIONS,el as PLATFORMS,ll as PWA_ASSET_TYPES,al as PWA_DISPLAY_MODES,Er as ProductDeclarationSchema,Wa as ProductDeclarationsSchema,xf as ProxiedImageUrlSchema,Ze as REMOVED_STATUS,ul as ROUTE_SOURCES,vn as SESSION_RENDER_SEGMENT,M as STATUS_MATRIX,sl as STORAGE_SCOPES,il as STORAGE_TYPES,du as STRIPE_EVENTS,Re as STRIPE_MODES,wa as SUBSCRIPTION_DURATIONS,xe as SUBSCRIPTION_STATUS,mr as SUBSCRIPTION_TIERS,Cr as SendEmailRequestSchema,Ir as SendEmailResponseSchema,Rn as ServerUtils,te as SingletonManager,kr as StripeBackConfigSchema,Sr as StripeFrontConfigSchema,Rr as StripeOrderBackSchema,Tr as StripeOrderShippingSchema,xr as StripeOrderTaxSchema,vr as StripePaymentSchema,br as StripeSubscriptionSchema,U as SubscriptionClaimsSchema,Ut as SubscriptionDataSchema,Fi as TECHNICAL_FIELD_NAMES,Ne as TRANSLATABLE_FIELD_TYPES,w as USER_ROLES,wt as UserSubscriptionSchema,dl as VISIBILITY,yr as VerifyOrderCheckoutRequestSchema,hr as VerifyOrderCheckoutResultSchema,Mt as WebhookEventSchema,ve as addMonths,ht as addYears,Fs as assertWrite,C as baseFields,Po as buildProductJsonLd,Ci as calculateSubscriptionEndDate,ot as captureErrorToSentry,Vu as checkGitHubAccessSchema,Wo as clearGlobalSingleton,zm as clearScopeProviders,me as commonErrorCodeMappings,at as compactToISOString,zo as configureProviders,Go as createAsyncSingleton,pr as createDefaultSubscriptionClaims,Sa as createDefaultUserProfile,kl as createEntitySchema,N as createErrorHandler,ao as createMetadata,Yo as createMethodProxy,Vm as createSchemas,Ko as createSingleton,Ho as createSingletonWithParams,Zn as createStatus,Om as defineEntity,Il as deleteEntitySchema,Oo as deriveEntitySeo,Ve as describeEntity,ms as describeField,Jm as detectBulkCollisions,nt as detectErrorSource,qu as disconnectOAuthSchema,Gp as enhanceSchema,to as ensureSpreadable,Y as evaluateCondition,hi as evaluateFieldConditions,$u as exchangeTokenSchema,pi as filterVisibleFields,ge as formatCurrency,tn as formatDate,pt as formatFieldText,yo as formatRelativeTime,mn as generateCodeChallenge,pn as generateCodeVerifier,No as generateFirestoreRuleCondition,Uo as generatePKCEPair,xi as generateUUID,Pr as getBreakpointFromWidth,ku as getBreakpointUtils,Sm as getCollectionName,bi as getConditionDependencies,Wu as getConnectionsSchema,en as getCurrencyLocale,lo as getCurrencySymbol,po as getCurrentTimestamp,ys as getEntityByCollection,Al as getEntitySchema,ye as getGlobalSingleton,he as getListCardFieldNames,Xo as getProvider,Ym as getRegisteredScopeProviders,jo as getRoleFromClaims,z as getSchemaType,Hm as getScopeValue,Jo as getTranslatedFieldNames,yt as getVisibleFields,go as getWeekFromISOString,Rf as getWidget,_r as githubPermissionSchema,tt as githubRepoConfigSchema,Lu as grantGitHubAccessSchema,k as handleError,gs as hasMetadata,Qo as hasProvider,mi as hasRestrictedVisibility,j as hasRoleAccess,Gm as hasScopeProvider,qo as hasTierAccess,Us as hiddenStatusesFor,ne as i18nFieldName,ec as isAuthPartnerId,kn as isBackendGeneratedField,Ru as isBreakpoint,lt as isCompactDateString,dt as isEmptyFieldValue,bn as isFieldVisible,Qp as isFrameworkField,_e as isMultilingual,tc as isOAuthPartnerId,Mo as isPKCESupported,Ms as isReadableBy,uo as isoToCompactString,si as languageUrls,$o as lazyImport,wl as listEntitiesSchema,kf as listWidgets,gt as localizePath,H as mapToDoNotDevError,_o as maybeTranslate,co as normalizeToISOString,la as overrideFeatures,Ia as overridePaymentModes,ua as overridePermissions,dr as overrideSubscriptionStatus,aa as overrideSubscriptionTiers,sa as overrideUserRoles,oi as parseAcceptLanguage,ut as parseDate,vo as parseDateToNoonUTC,Ii as parseISODate,Di as parseServerCookie,Ns as prepareCreate,_s as prepareRemove,tr as prepareUpdate,ii as publicPathname,jm as rangeOptions,ri as readCookieValue,ju as refreshTokenSchema,Wm as registerScopeProvider,lm as registerUniqueConstraintValidator,Tf as registerWidget,Zo as resetProviders,xt as resolveFieldValue,mt as resolveLanguage,ai as resolveLanguageRoute,xn as resolveUserSubscription,Bu as revokeGitHubAccessSchema,eo as safeValidate,Si as sanitizeHref,zr as showNotification,ft as splitLanguagePath,je as statusCan,D as statusOf,We as statusReadableBy,Rt as statusesThat,Oe as stripHtmlTags,fo as timestampToISOString,bo as toDateOnly,mo as toISOString,ro as translateArray,io as translateArrayRange,so as translateArrayWithIndices,we as translateEntityLabel,oo as translateObjectArray,ti as translateRow,Km as unregisterScopeProvider,er as updateCheck,Cl as updateEntitySchema,li as updateMetadata,Jn as updateNeedsStored,Js as validateAIChatRequest,ea as validateAIChatResponse,Zu as validateAuthPartners,ha as validateAuthSchemas,fa as validateAuthUser,Ga as validateBillingSchemas,Af as validateBlock,Zm as validateBulkOutcome,qa as validateCheckoutSessionMetadata,Bo as validateCodeChallenge,Lo as validateCodeVerifier,Ba as validateCreateCheckoutSessionRequest,Va as validateCreateCheckoutSessionResponse,ya as validateCustomClaims,$e as validateDates,pm as validateDocument,Pi as validateEnvVar,Cf as validateEvent,Oi as validateMetadata,Ju as validateOAuthPartners,Wl as validateSendEmailRequest,Kl as validateSendEmailResponse,Ha as validateStripeBackConfig,Ka as validateStripeFrontConfig,fr as validateSubscriptionClaims,$a as validateSubscriptionData,qn as validateUniqueFields,wi as validateUrl,ga as validateUserSubscription,Ma as validateVerifyOrderCheckoutRequest,La as validateVerifyOrderCheckoutResult,ja as validateWebhookEvent,Jr as validateWithSchema,vi as when,Yr as withErrorHandling,Vo as withGracefulDegradation,ki as withTimeout,Zr as wrapAuthError,Xr as wrapCrudError,Qr as wrapStorageError};
|