@stackone/hub 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- "use client";import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{Flex as i,FlexGapSize as r,FlexDirection as s,FlexAlign as o,FlexJustify as a,Typography as c,Padded as l,Spacer as u,Alert as d,Form as h,CodeBlock as f,Input as p,TextArea as g,Dropdown as y,Divider as v,PillButton as m,ButtonList as b,TruncatedTooltip as C,Spinner as w,getCurrentTheme as O,CustomIcons as S,Tag as k,Button as x,FooterLinks as R,Card as j,applyDarkTheme as q,applyLightTheme as P,applyTheme as I,MalachiteContext as T}from"@stackone/malachite";import*as F from"react";import D,{useMemo as E,useEffect as Q,useState as A,useCallback as _,useRef as L,createContext as M,memo as z}from"react";import{zodResolver as U}from"@hookform/resolvers/zod";import{useForm as $}from"react-hook-form";import{z as H}from"zod";var K=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},N="undefined"==typeof window||"Deno"in globalThis;function V(){}function B(e){return"number"==typeof e&&e>=0&&e!==1/0}function W(e,t){return Math.max(e+(t||0)-Date.now(),0)}function G(e,t){return"function"==typeof e?e(t):e}function J(e,t){return"function"==typeof e?e(t):e}function Y(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==Z(o,t.options))return!1}else if(!te(t.queryKey,o))return!1;if("all"!==n){const e=t.isActive();if("active"===n&&!e)return!1;if("inactive"===n&&e)return!1}return("boolean"!=typeof a||t.isStale()===a)&&((!r||r===t.state.fetchStatus)&&!(s&&!s(t)))}function X(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(ee(t.options.mutationKey)!==ee(s))return!1}else if(!te(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function Z(e,t){return(t?.queryKeyHashFn||ee)(e)}function ee(e){return JSON.stringify(e,((e,t)=>se(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function te(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>te(e[n],t[n]))))}function ne(e,t){if(e===t)return e;const n=re(e)&&re(t);if(n||se(e)&&se(t)){const i=n?e:Object.keys(e),r=i.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let c=0;for(let r=0;r<o;r++){const o=n?r:s[r];(!n&&i.includes(o)||n)&&void 0===e[o]&&void 0===t[o]?(a[o]=void 0,c++):(a[o]=ne(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&c++)}return r===o&&c===r?e:a}return t}function ie(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function re(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function se(e){if(!oe(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!oe(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function oe(e){return"[object Object]"===Object.prototype.toString.call(e)}function ae(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?ne(e,t):t}function ce(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function le(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var ue=Symbol();function de(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:e.queryFn&&e.queryFn!==ue?e.queryFn:()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`))}var he=new class extends K{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!N&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e((e=>{"boolean"==typeof e?this.setFocused(e):this.onFocus()}))}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach((t=>{t(e)}))}isFocused(){return"boolean"==typeof this.#e?this.#e:"hidden"!==globalThis.document?.visibilityState}},fe=new class extends K{#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!N&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#i!==e&&(this.#i=e,this.listeners.forEach((t=>{t(e)})))}isOnline(){return this.#i}};function pe(){let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));function i(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.status="pending",n.catch((()=>{})),n.resolve=t=>{i({status:"fulfilled",value:t}),e(t)},n.reject=e=>{i({status:"rejected",reason:e}),t(e)},n}function ge(e){return Math.min(1e3*2**e,3e4)}function ye(e){return"online"!==(e??"online")||fe.isOnline()}var ve=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function me(e){return e instanceof ve}function be(e){let t,n=!1,i=0,r=!1;const s=pe(),o=()=>he.isFocused()&&("always"===e.networkMode||fe.isOnline())&&e.canRun(),a=()=>ye(e.networkMode)&&e.canRun(),c=n=>{r||(r=!0,e.onSuccess?.(n),t?.(),s.resolve(n))},l=n=>{r||(r=!0,e.onError?.(n),t?.(),s.reject(n))},u=()=>new Promise((n=>{t=e=>{(r||o())&&n(e)},e.onPause?.()})).then((()=>{t=void 0,r||e.onContinue?.()})),d=()=>{if(r)return;let t;const s=0===i?e.initialPromise:void 0;try{t=s??e.fn()}catch(e){t=Promise.reject(e)}Promise.resolve(t).then(c).catch((t=>{if(r)return;const s=e.retry??(N?0:3),a=e.retryDelay??ge,c="function"==typeof a?a(i,t):a,h=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var f;!n&&h?(i++,e.onFail?.(i,t),(f=c,new Promise((e=>{setTimeout(e,f)}))).then((()=>o()?void 0:u())).then((()=>{n?l(t):d()}))):l(t)}))};return{promise:s,cancel:t=>{r||(l(new ve(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?d():u().then(d),s)}}var Ce=e=>setTimeout(e,0);var we=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=Ce;const s=i=>{t?e.push(i):r((()=>{n(i)}))};return{batch:s=>{let o;t++;try{o=s()}finally{t--,t||(()=>{const t=e;e=[],t.length&&r((()=>{i((()=>{t.forEach((e=>{n(e)}))}))}))})()}return o},batchCalls:e=>(...t)=>{s((()=>{e(...t)}))},schedule:s,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{i=e},setScheduler:e=>{r=e}}}(),Oe=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),B(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(N?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},Se=class extends Oe{#s;#o;#a;#c;#l;#u;#d;constructor(e){super(),this.#d=!1,this.#u=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#c=e.client,this.#a=this.#c.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#s=function(e){const t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==t,i=n?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=e.state??this.#s,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#l?.promise}setOptions(e){this.options={...this.#u,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.observers.length||"idle"!==this.state.fetchStatus||this.#a.remove(this)}setData(e,t){const n=ae(this.state.data,e,this.options);return this.#h({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#h({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#l?.promise;return this.#l?.cancel(e),t?t.then(V).catch(V):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==J(e.options.enabled,this)))}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ue||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return!!this.state.isInvalidated||(this.getObserversCount()>0?this.observers.some((e=>e.getCurrentResult().isStale)):void 0===this.state.data)}isStaleByTime(e=0){return this.state.isInvalidated||void 0===this.state.data||!W(this.state.dataUpdatedAt,e)}onFocus(){const e=this.observers.find((e=>e.shouldFetchOnWindowFocus()));e?.refetch({cancelRefetch:!1}),this.#l?.continue()}onOnline(){const e=this.observers.find((e=>e.shouldFetchOnReconnect()));e?.refetch({cancelRefetch:!1}),this.#l?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter((t=>t!==e)),this.observers.length||(this.#l&&(this.#d?this.#l.cancel({revert:!0}):this.#l.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#h({type:"invalidate"})}fetch(e,t){if("idle"!==this.state.fetchStatus)if(void 0!==this.state.data&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#l)return this.#l.continueRetry(),this.#l.promise;if(e&&this.setOptions(e),!this.options.queryFn){const e=this.observers.find((e=>e.options.queryFn));e&&this.setOptions(e.options)}const n=new AbortController,i=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#d=!0,n.signal)})},r={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#c,state:this.state,fetchFn:()=>{const e=de(this.options,t),n={client:this.#c,queryKey:this.queryKey,meta:this.meta};return i(n),this.#d=!1,this.options.persister?this.options.persister(e,n,this):e(n)}};i(r),this.options.behavior?.onFetch(r,this),this.#o=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===r.fetchOptions?.meta||this.#h({type:"fetch",meta:r.fetchOptions?.meta});const s=e=>{me(e)&&e.silent||this.#h({type:"error",error:e}),me(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#l=be({initialPromise:t?.initialPromise,fn:r.fetchFn,abort:n.abort.bind(n),onSuccess:e=>{if(void 0!==e){try{this.setData(e)}catch(e){return void s(e)}this.#a.config.onSuccess?.(e,this),this.#a.config.onSettled?.(e,this.state.error,this),this.scheduleGc()}else s(new Error(`${this.queryHash} data is undefined`))},onError:s,onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:()=>{this.#h({type:"continue"})},retry:r.options.retry,retryDelay:r.options.retryDelay,networkMode:r.options.networkMode,canRun:()=>!0}),this.#l.start()}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...t,fetchStatus:"paused"};case"continue":return{...t,fetchStatus:"fetching"};case"fetch":return{...t,...ke(t.data,this.options),fetchMeta:e.meta??null};case"success":return{...t,data:e.data,dataUpdateCount:t.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=e.error;return me(n)&&n.revert&&this.#o?{...this.#o,fetchStatus:"idle"}:{...t,error:n,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...t,isInvalidated:!0};case"setState":return{...t,...e.state}}})(this.state),we.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function ke(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ye(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var xe=class extends K{constructor(e={}){super(),this.config=e,this.#f=new Map}#f;build(e,t,n){const i=t.queryKey,r=t.queryHash??Z(i,t);let s=this.get(r);return s||(s=new Se({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#f.has(e.queryHash)||(this.#f.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#f.get(e.queryHash);t&&(e.destroy(),t===e&&this.#f.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){we.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#f.get(e)}getAll(){return[...this.#f.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>Y(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>Y(e,t))):t}notify(e){we.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){we.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){we.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},Re=class extends Oe{#p;#g;#l;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#p=[],this.state=e.state||{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0},this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#p.includes(e)||(this.#p.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#p=this.#p.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#p.length||("pending"===this.state.status?this.scheduleGc():this.#g.remove(this))}continue(){return this.#l?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#h({type:"continue"})};this.#l=be({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#g.canRun(this)});const n="pending"===this.state.status,i=!this.#l.canStart();try{if(n)t();else{this.#h({type:"pending",variables:e,isPaused:i}),await(this.#g.config.onMutate?.(e,this));const t=await(this.options.onMutate?.(e));t!==this.state.context&&this.#h({type:"pending",context:t,variables:e,isPaused:i})}const r=await this.#l.start();return await(this.#g.config.onSuccess?.(r,e,this.state.context,this)),await(this.options.onSuccess?.(r,e,this.state.context)),await(this.#g.config.onSettled?.(r,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(r,null,e,this.state.context)),this.#h({type:"success",data:r}),r}catch(t){try{throw await(this.#g.config.onError?.(t,e,this.state.context,this)),await(this.options.onError?.(t,e,this.state.context)),await(this.#g.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,t,e,this.state.context)),t}finally{this.#h({type:"error",error:t})}}finally{this.#g.runNext(this)}}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...t,isPaused:!0};case"continue":return{...t,isPaused:!1};case"pending":return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}})(this.state),we.batch((()=>{this.#p.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var je=class extends K{constructor(e={}){super(),this.config=e,this.#y=new Set,this.#v=new Map,this.#m=0}#y;#v;#m;build(e,t,n){const i=new Re({mutationCache:this,mutationId:++this.#m,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#y.add(e);const t=qe(e);if("string"==typeof t){const n=this.#v.get(t);n?n.push(e):this.#v.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#y.delete(e)){const t=qe(e);if("string"==typeof t){const n=this.#v.get(t);if(n)if(n.length>1){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}else n[0]===e&&this.#v.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=qe(e);if("string"==typeof t){const n=this.#v.get(t),i=n?.find((e=>"pending"===e.state.status));return!i||i===e}return!0}runNext(e){const t=qe(e);if("string"==typeof t){const n=this.#v.get(t)?.find((t=>t!==e&&t.state.isPaused));return n?.continue()??Promise.resolve()}return Promise.resolve()}clear(){we.batch((()=>{this.#y.forEach((e=>{this.notify({type:"removed",mutation:e})})),this.#y.clear(),this.#v.clear()}))}getAll(){return Array.from(this.#y)}find(e){const t={exact:!0,...e};return this.getAll().find((e=>X(t,e)))}findAll(e={}){return this.getAll().filter((t=>X(e,t)))}notify(e){we.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return we.batch((()=>Promise.all(e.map((e=>e.continue().catch(V))))))}};function qe(e){return e.options.scope?.id}function Pe(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},c=0;const l=async()=>{let n=!1;const l=de(t.options,t.fetchOptions),u=async(e,i,r)=>{if(n)return Promise.reject();if(null==i&&e.pages.length)return Promise.resolve(e);const s={client:t.client,queryKey:t.queryKey,pageParam:i,direction:r?"backward":"forward",meta:t.options.meta};var o;o=s,Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(t.signal.aborted?n=!0:t.signal.addEventListener("abort",(()=>{n=!0})),t.signal)});const a=await l(s),{maxPages:c}=t.options,u=r?le:ce;return{pages:u(e.pages,a,c),pageParams:u(e.pageParams,i,c)}};if(r&&s.length){const e="backward"===r,t={pages:s,pageParams:o},n=(e?Te:Ie)(i,t);a=await u(t,n,e)}else{const t=e??s.length;do{const e=0===c?o[0]??i.initialPageParam:Ie(i,a);if(c>0&&null==e)break;a=await u(a,e),c++}while(c<t)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Ie(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function Te(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Fe=class{#b;#g;#u;#C;#w;#O;#S;#k;constructor(e={}){this.#b=e.queryCache||new xe,this.#g=e.mutationCache||new je,this.#u=e.defaultOptions||{},this.#C=new Map,this.#w=new Map,this.#O=0}mount(){this.#O++,1===this.#O&&(this.#S=he.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#k=fe.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onOnline())})))}unmount(){this.#O--,0===this.#O&&(this.#S?.(),this.#S=void 0,this.#k?.(),this.#k=void 0)}isFetching(e){return this.#b.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#g.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#b.build(this,t),i=n.state.data;return void 0===i?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(G(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#b.findAll(e).map((({queryKey:e,state:t})=>[e,t.data]))}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),r=this.#b.get(i.queryHash),s=r?.state.data,o=function(e,t){return"function"==typeof e?e(t):e}(t,s);if(void 0!==o)return this.#b.build(this,i).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return we.batch((()=>this.#b.findAll(e).map((({queryKey:e})=>[e,this.setQueryData(e,t,n)]))))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state}removeQueries(e){const t=this.#b;we.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return we.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=we.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(V).catch(V)}invalidateQueries(e,t={}){return we.batch((()=>(this.#b.findAll(e).forEach((e=>{e.invalidate()})),"none"===e?.refetchType?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t))))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=we.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(V)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(V)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(G(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(V).catch(V)}fetchInfiniteQuery(e){return e.behavior=Pe(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(V).catch(V)}ensureInfiniteQueryData(e){return e.behavior=Pe(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#g.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#b}getMutationCache(){return this.#g}getDefaultOptions(){return this.#u}setDefaultOptions(e){this.#u=e}setQueryDefaults(e,t){this.#C.set(ee(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{te(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#w.set(ee(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#w.values()],n={};return t.forEach((t=>{te(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)})),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#u.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Z(t.queryKey,t)),void 0===t.refetchOnReconnect&&(t.refetchOnReconnect="always"!==t.networkMode),void 0===t.throwOnError&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===ue&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#u.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#b.clear(),this.#g.clear()}},De=class extends K{constructor(e,t){super(),this.options=t,this.#c=e,this.#x=null,this.#R=pe(),this.options.experimental_prefetchInRender||this.#R.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#c;#j=void 0;#q=void 0;#P=void 0;#I;#T;#R;#x;#F;#D;#E;#Q;#A;#_;#L=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#j.addObserver(this),Ee(this.#j,this.options)?this.#M():this.updateResult(),this.#z())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Qe(this.#j,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Qe(this.#j,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#U(),this.#$(),this.#j.removeObserver(this)}setOptions(e){const t=this.options,n=this.#j;if(this.options=this.#c.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof J(this.options.enabled,this.#j))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#H(),this.#j.setOptions(this.options),t._defaulted&&!ie(this.options,t)&&this.#c.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#j,observer:this});const i=this.hasListeners();i&&Ae(this.#j,n,this.options,t)&&this.#M(),this.updateResult(),!i||this.#j===n&&J(this.options.enabled,this.#j)===J(t.enabled,this.#j)&&G(this.options.staleTime,this.#j)===G(t.staleTime,this.#j)||this.#K();const r=this.#N();!i||this.#j===n&&J(this.options.enabled,this.#j)===J(t.enabled,this.#j)&&r===this.#_||this.#V(r)}getOptimisticResult(e){const t=this.#c.getQueryCache().build(this.#c,e),n=this.createResult(t,e);return function(e,t){if(!ie(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#P=n,this.#T=this.options,this.#I=this.#j.state),n}getCurrentResult(){return this.#P}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#L.add(e)}getCurrentQuery(){return this.#j}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#c.defaultQueryOptions(e),n=this.#c.getQueryCache().build(this.#c,t);return n.fetch().then((()=>this.createResult(n,t)))}fetch(e){return this.#M({...e,cancelRefetch:e.cancelRefetch??!0}).then((()=>(this.updateResult(),this.#P)))}#M(e){this.#H();let t=this.#j.fetch(this.options,e);return e?.throwOnError||(t=t.catch(V)),t}#K(){this.#U();const e=G(this.options.staleTime,this.#j);if(N||this.#P.isStale||!B(e))return;const t=W(this.#P.dataUpdatedAt,e)+1;this.#Q=setTimeout((()=>{this.#P.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#j):this.options.refetchInterval)??!1}#V(e){this.#$(),this.#_=e,!N&&!1!==J(this.options.enabled,this.#j)&&B(this.#_)&&0!==this.#_&&(this.#A=setInterval((()=>{(this.options.refetchIntervalInBackground||he.isFocused())&&this.#M()}),this.#_))}#z(){this.#K(),this.#V(this.#N())}#U(){this.#Q&&(clearTimeout(this.#Q),this.#Q=void 0)}#$(){this.#A&&(clearInterval(this.#A),this.#A=void 0)}createResult(e,t){const n=this.#j,i=this.options,r=this.#P,s=this.#I,o=this.#T,a=e!==n?e.state:this.#q,{state:c}=e;let l,u={...c},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&Ee(e,t),o=r&&Ae(e,n,t,i);(s||o)&&(u={...u,...ke(c.data,e.options)}),"isRestoring"===t._optimisticResults&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:f,status:p}=u;l=u.data;let g=!1;if(void 0!==t.placeholderData&&void 0===l&&"pending"===p){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#E?.state.data,this.#E):t.placeholderData,void 0!==e&&(p="success",l=ae(r?.data,e,t),d=!0)}if(t.select&&void 0!==l&&!g)if(r&&l===s?.data&&t.select===this.#F)l=this.#D;else try{this.#F=t.select,l=t.select(l),l=ae(r?.data,l,t),this.#D=l,this.#x=null}catch(e){this.#x=e}this.#x&&(h=this.#x,l=this.#D,f=Date.now(),p="error");const y="fetching"===u.fetchStatus,v="pending"===p,m="error"===p,b=v&&y,C=void 0!==l,w={status:p,fetchStatus:u.fetchStatus,isPending:v,isSuccess:"success"===p,isError:m,isInitialLoading:b,isLoading:b,data:l,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>a.dataUpdateCount||u.errorUpdateCount>a.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:m&&!C,isPaused:"paused"===u.fetchStatus,isPlaceholderData:d,isRefetchError:m&&C,isStale:_e(e,t),refetch:this.refetch,promise:this.#R};if(this.options.experimental_prefetchInRender){const t=e=>{"error"===w.status?e.reject(w.error):void 0!==w.data&&e.resolve(w.data)},i=()=>{const e=this.#R=w.promise=pe();t(e)},r=this.#R;switch(r.status){case"pending":e.queryHash===n.queryHash&&t(r);break;case"fulfilled":"error"!==w.status&&w.data===r.value||i();break;case"rejected":"error"===w.status&&w.error===r.reason||i()}}return w}updateResult(){const e=this.#P,t=this.createResult(this.#j,this.options);if(this.#I=this.#j.state,this.#T=this.options,void 0!==this.#I.data&&(this.#E=this.#j),ie(t,e))return;this.#P=t;this.#B({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#L.size)return!0;const i=new Set(n??this.#L);return this.options.throwOnError&&i.add("error"),Object.keys(this.#P).some((t=>{const n=t;return this.#P[n]!==e[n]&&i.has(n)}))})()})}#H(){const e=this.#c.getQueryCache().build(this.#c,this.options);if(e===this.#j)return;const t=this.#j;this.#j=e,this.#q=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#z()}#B(e){we.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#P)})),this.#c.getQueryCache().notify({query:this.#j,type:"observerResultsUpdated"})}))}};function Ee(e,t){return function(e,t){return!1!==J(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Qe(e,t,t.refetchOnMount)}function Qe(e,t,n){if(!1!==J(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&_e(e,t)}return!1}function Ae(e,t,n,i){return(e!==t||!1===J(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&_e(e,n)}function _e(e,t){return!1!==J(t.enabled,e)&&e.isStaleByTime(G(t.staleTime,e))}var Le=F.createContext(void 0),Me=({client:t,children:n})=>(F.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e(Le.Provider,{value:t,children:n})),ze=F.createContext(!1);ze.Provider;var Ue=F.createContext(function(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}()),$e=(e,t,n)=>t.fetchOptimistic(e).catch((()=>{n.clearReset()}));function He(e,t,n){const i=(()=>{const e=F.useContext(Le);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=F.useContext(ze),s=F.useContext(Ue),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",(e=>{const t=e.staleTime;e.suspense&&(e.staleTime="function"==typeof t?(...e)=>Math.max(t(...e),1e3):Math.max(t??1e3,1e3),"number"==typeof e.gcTime&&(e.gcTime=Math.max(e.gcTime,1e3)))})(o),((e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))})(o,s),(e=>{F.useEffect((()=>{e.clearReset()}),[e])})(s);const a=!i.getQueryCache().get(o.queryHash),[c]=F.useState((()=>new t(i,o))),l=c.getOptimisticResult(o),u=!r&&!1!==e.subscribed;if(F.useSyncExternalStore(F.useCallback((e=>{const t=u?c.subscribe(we.batchCalls(e)):V;return c.updateResult(),t}),[c,u]),(()=>c.getCurrentResult()),(()=>c.getCurrentResult())),F.useEffect((()=>{c.setOptions(o)}),[o,c]),((e,t)=>e?.suspense&&t.isPending)(o,l))throw $e(o,c,s);if((({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&void 0===e.data||function(e,t){return"function"==typeof e?e(...t):!!e}(n,[e.error,i])))({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:i.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw l.error;if(i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!N&&((e,t)=>e.isLoading&&e.isFetching&&!t)(l,r)){const e=a?$e(o,c,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(V).finally((()=>{c.updateResult()}))}return o.notifyOnChangeProps?l:c.trackResult(l)}function Ke(e,t){return He(e,De)}const Ne=({message:t})=>e(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:e(c.Text,{size:"medium",fontWeight:"semi-bold",children:t})});var Ve=Object.prototype.hasOwnProperty;function Be(e,t,n){for(n of e.keys())if(We(n,t))return n}function We(e,t){var n,i,r;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((i=e.length)===t.length)for(;i--&&We(e[i],t[i]););return-1===i}if(n===Set){if(e.size!==t.size)return!1;for(i of e){if((r=i)&&"object"==typeof r&&!(r=Be(t,r)))return!1;if(!t.has(r))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(i of e){if((r=i[0])&&"object"==typeof r&&!(r=Be(t,r)))return!1;if(!We(i[1],t.get(r)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((i=e.byteLength)===t.byteLength)for(;i--&&e.getInt8(i)===t.getInt8(i););return-1===i}if(ArrayBuffer.isView(e)){if((i=e.byteLength)===t.byteLength)for(;i--&&e[i]===t[i];);return-1===i}if(!n||"object"==typeof e){for(n in i=0,e){if(Ve.call(e,n)&&++i&&!Ve.call(t,n))return!1;if(!(n in t)||!We(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function Ge(e,t){return F.useEffect(e,(n=t,i=F.useRef(n),r=F.useRef(0),We(n,i.current)||(i.current=n,r.current+=1),F.useMemo((function(){return i.current}),[r.current])));var n,i,r}function Je(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const Ye=/^__secretvalue:\*\*redacted\*\*(.*)$/,Xe=e=>(e=>"string"==typeof e)(e)&&Ye.test(e),Ze=e=>{const t="••••••••••";if(!Xe(e))return e;const n=e.match(Ye);if(!n)return t;const i=n[1];return i?t+i:t},et={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/};function tt(e){return void 0!==e.type}function nt(e){if((e=>{const t=[];let n=!1;const i=/\{(\d+)(?:(,)(\d*))?\}/y,r=t=>{const n=e[t];if("*"===n||"+"===n)return{length:1,variable:!0,amplifying:!0};if("?"===n)return{length:1,variable:!0,amplifying:!1};if("{"===n){i.lastIndex=t;const n=i.exec(e);if(n){const e=Number(n[1]),t=void 0===n[2]?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let i=0;i<e.length;i++){const s=e[i];if("\\"===s){i++;continue}if(n){"]"===s&&(n=!1);continue}if("["===s){n=!0;continue}if("|"===s){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if("("===s){t.push({hasVariable:!1,hasAlternation:!1}),"?"===e[i+1]&&(i+="<"!==e[i+2]||"="!==e[i+3]&&"!"!==e[i+3]?1:2);continue}if(")"===s){const e=t.pop(),n=r(i+1);if(n){if(n.amplifying&&((null==e?void 0:e.hasVariable)||(null==e?void 0:e.hasAlternation)))return!0;i+=n.length}t.length>0&&(((null==n?void 0:n.variable)||(null==e?void 0:e.hasVariable))&&(t[t.length-1].hasVariable=!0),(null==e?void 0:e.hasAlternation)&&(t[t.length-1].hasAlternation=!0));continue}const o=r(i);o&&(o.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),i+=o.length-1)}return!1})(e))return console.warn(`[stackone-hub] pattern "${e}" risks catastrophic backtracking — field validation skipped`),null;try{return new RegExp(e)}catch(t){return console.warn(`[stackone-hub] pattern "${e}" failed to compile — field validation skipped`),null}}function it(e){return e.validation?tt(e.validation)?function(e){if("html-pattern"===e.type){const t=nt(e.pattern);return t?{pattern:t,errorMessage:e.error||`Please match the required format: ${e.pattern}`}:null}if("domain"===e.type){const t=nt(`.*${e.pattern}\\.com.*`);return t?{pattern:t,errorMessage:e.error||`Please enter a valid ${e.pattern}.com domain`}:null}return null}(e.validation):function(e,t){if(e.format){const t=Object.prototype.hasOwnProperty.call(et,e.format)?et[e.format]:void 0;return t?{pattern:t,errorMessage:e.errorMessage||`Must be a valid ${e.format}`}:(console.warn(`[stackone-hub] no pattern for format "${e.format}" — field validation skipped; hub FORMAT_PATTERNS has drifted from @stackone/core`),null)}if(e.pattern){const n=nt(e.pattern);return n?{pattern:n,errorMessage:e.errorMessage||`${t} format is invalid`}:null}return null}(e.validation,e.label):null}function rt(e){const t=new Map;for(const n of e){if("number"===n.type&&!n.required)continue;const e=it(n);e&&t.set(n.key,e)}return t}function st(e,t){return!(!e||"string"!=typeof t||""===t||Xe(t))&&!e.pattern.test(t)}function ot(e,t){let n=H.string();e.required&&(n=n.min(1,`${e.label} is required`));const i=t=>n=>""===n?!e.required:t(n);return"number"===e.type&&(n=n.refine(i((e=>Xe(e)||/^\d+$/.test(e))),"Must be a valid number")),t&&(n=n.refine(i((e=>!st(t,e))),t.errorMessage)),n}const at=({field:i,errors:r,setValue:s,onLeave:o,editingSecrets:a,setEditingSecrets:l})=>{var u,d,h,f,v,m,b,C,w,O,S,k,x,R,j,q,P,I,T,F,D,E,Q;const A="object"==typeof i.key?JSON.stringify(i.key):String(i.key),_=r[A]&&e(c.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(u=r[A])||void 0===u?void 0:u.message});if("text"===(L=i.type)||"number"===L||"password"===L){const c=i.readOnly,u=null===(d=i.value)||void 0===d?void 0:d.toString(),g="external-trigger-token"!==i.key&&(!1!==i.secret||"password"===i.type),y=c&&u&&!g,k=null!==(h=null==a?void 0:a.has(A))&&void 0!==h&&h;if(g&&Xe(u)&&!k)return t(n,{children:[e(p,{name:`${A}-display`,label:i.label,placeholder:i.placeholder,type:"text",required:i.required,disabled:!0,readOnly:!0,defaultValue:u?Ze(u):"",description:null!==(v=null===(f=i.guide)||void 0===f?void 0:f.description)&&void 0!==v?v:i.description,tooltip:null!==(b=null===(m=i.guide)||void 0===m?void 0:m.tooltip)&&void 0!==b?b:i.tooltip,showCopyButton:!1,buttons:l?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{l((e=>new Set(e).add(A))),s(A,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),_]});const x=!g&&(i.readOnly||!1),R=g?void 0:y?()=>{}:void 0;return t(n,{children:[e(p,{name:A,required:!!c||i.required,placeholder:i.placeholder,disabled:x,readOnly:i.readOnly,label:i.label,tooltip:null!==(w=null===(C=i.guide)||void 0===C?void 0:C.tooltip)&&void 0!==w?w:i.tooltip,description:null!==(S=null===(O=i.guide)||void 0===O?void 0:O.description)&&void 0!==S?S:i.description,type:i.type,error:!!r[A],onChange:e=>s(A,e,{shouldValidate:!0}),onBlur:o,defaultValue:g&&k?"":u,showPasswordToggle:!1,onCopyClick:R},`${A}-${k?"editing":"view"}`),_]})}var L;return"text_area"===i.type?t(n,{children:[e(g,{name:A,required:i.required,placeholder:i.placeholder,disabled:i.readOnly,label:i.label,tooltip:null!==(x=null===(k=i.guide)||void 0===k?void 0:k.tooltip)&&void 0!==x?x:i.tooltip,description:null!==(j=null===(R=i.guide)||void 0===R?void 0:R.description)&&void 0!==j?j:i.description,error:!!r[A],onChange:e=>s(A,e,{shouldValidate:!0}),onBlur:o,defaultValue:(null===(q=i.value)||void 0===q?void 0:q.toString())||""}),_]}):"select"===i.type?t(n,{children:[e(y,{defaultValue:(null===(P=i.value)||void 0===P?void 0:P.toString())||"",disabled:i.readOnly,items:null!==(T=null===(I=i.options)||void 0===I?void 0:I.map((e=>({id:e.value,label:e.label}))))&&void 0!==T?T:[],onItemSelected:e=>s(A,null!=e?e:"",{shouldValidate:!0}),name:A,label:i.label,placeholder:i.placeholder,tooltip:null!==(D=null===(F=i.guide)||void 0===F?void 0:F.tooltip)&&void 0!==D?D:i.tooltip,description:null!==(Q=null===(E=i.guide)||void 0===E?void 0:E.description)&&void 0!==Q?Q:i.description,required:i.required,error:!!r[A]}),_]}):null},ct=({error:t})=>{if(!t)return null;try{return e(f,{json:JSON.parse(t.provider_response)})}catch(n){return(null==t?void 0:t.provider_response)&&(null==t?void 0:t.provider_response.length)>0?e(f,{code:null==t?void 0:t.provider_response}):null}},lt=({integrationName:n,error:h,notices:f=[]})=>{var p;return t(l,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[h&&e(d,{type:"error",message:(null===(p=h.provider_response)||void 0===p?void 0:p.trim())||h.message,hasMargin:!1,children:e(ct,{error:h})}),f.map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(i,{direction:s.Vertical,gapSize:r.Small,fullHeight:!0,justify:a.Center,align:o.Center,children:t(u,{direction:"vertical",size:8,fullWidth:!0,children:[e(c.Text,{size:"small",fontWeight:"semi-bold",children:'Press "Connect" below to authenticate'}),t(c.Text,{size:"small",color:"secondary",children:["An authentication window for ",n," will display,",e("br",{}),"please complete the necessary steps."]})]})})]})},ut=({fields:n,notices:i=[],onChange:r,error:s,onValidationChange:o,integrationName:a,connectorKey:c,editingSecrets:f,setEditingSecrets:p})=>{const g=n.filter((e=>!1!==e.display)),y=g.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:v,noticesAfter:m}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>Je(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!Je(e)&&"bottom"===e.position&&t===i))}}(i,y),b=E((()=>function(e){const t=new Set;return(n,i)=>{if("undefined"==typeof window||t.has(n.key))return;t.add(n.key);const r=tt(i)?void 0:i.format;window.dispatchEvent(new CustomEvent("stackone-hub:field-validation-failed",{detail:Object.assign(Object.assign(Object.assign({},e?{connector:e}:{}),{field:n.key,ruleKind:tt(i)?"legacy":r?"format":"pattern"}),r?{format:r}:{})}))}}(c)),[c]),C=E((()=>rt(n)),[n]),w=E((()=>function(e,t=rt(e)){const n={};for(const i of e)n[i.key]=ot(i,t.get(i.key));return H.object(n)}(n,C)),[n,C]),O=E((()=>{const e={};return n.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[n]),{formState:S,watch:k,reset:x,setValue:R,getValues:j}=$({resolver:U(w),mode:"onTouched",defaultValues:O}),{errors:q,isValid:P}=S;Ge((()=>{x(O)}),[O]);const I=k();Ge((()=>{r(I)}),[I]),Q((()=>{null==o||o(P)}),[P,o]);const T=e=>{document.hasFocus()&&e.validation&&function(e,t,n){return st(t.get(e.key),n)}(e,C,j(e.key))&&b(e,e.validation)};return 0===g.length?e(lt,{integrationName:a,error:s,notices:i}):e(l,{vertical:"large",horizontal:"medium",overflow:"auto",children:t(u,{direction:"vertical",size:8,fullWidth:!0,children:[s&&e(d,{type:"error",message:s.message,hasMargin:!1,children:e(ct,{error:s})}),e(h,{children:g.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=v(i).length>0||m(i).length>0;return t("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[v(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(at,{field:n,errors:q,setValue:R,onLeave:()=>T(n),editingSecrets:f,setEditingSecrets:p}),m(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key)))]},i)}))})]})})},dt=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:c,setEditingSecrets:l})=>e(ut,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:c,setEditingSecrets:l}),ht=e=>e.split(/[-_\s]+/).filter(Boolean),ft=e=>ht(e).join(" ").toLowerCase(),pt=e=>ht(e).join(" ").toUpperCase(),gt=({src:t,alt:n,fallbackUrl:i="https://stackone-logos.com/api/stackone/filled/png",style:r,className:s})=>{const[o,a]=A(t);return e("img",{src:o,alt:n,style:r,className:s,onError:()=>{a(i)}})},yt=e=>Boolean(e.active&&e.name),vt=({integration:n})=>{var l;return t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.SpaceBetween,width:"100%",children:[t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Left,width:"100%",children:[e(gt,{src:n.logo_url,alt:n.provider,style:{width:"24px",height:"24px"}}),e(c.Text,{textAlign:"left",children:null!==(l=n.name)&&void 0!==l?l:"N/A"})]}),e(c.SecondaryText,{size:"xsmall",style:{maxWidth:"45%",flexShrink:0},children:e(C,{text:pt(n.type),children:pt(n.type)})})]})},mt=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=_((e=>{s(r===e?null:e)}),[r,s]),c=E((()=>Array.from(new Set(i.filter(yt).map((e=>ft(e.type)))))),[i]);return t(n,{children:[e(p,{name:"search",placeholder:"Search Integrations",variant:"ghost",size:"large",onChange:o}),c.length>1&&t(n,{children:[e(v,{}),e(l,{vertical:"small",horizontal:"none",fullHeight:!1,children:e("div",{style:{overflowX:"auto",overflowY:"hidden",backgroundColor:"var(--malachite-card-background)",scrollbarWidth:"none",msOverflowStyle:"none"},className:"hide-scrollbar",children:e("div",{style:{display:"flex",minWidth:"max-content"},children:c.map((t=>e(l,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(m,{size:"xsmall",label:pt(t),selected:r===t,onClick:()=>a(t)})},t)))})})})]})]})},bt=({integrations:t,onSelect:r,selectedCategory:s,search:d})=>{const h=E((()=>t.filter((e=>yt(e)&&(!s||ft(e.type)===s)&&(!d||e.name.toLowerCase().includes(d.toLowerCase()))))),[t,s,d]);return e(n,{children:h.length>0?e(l,{vertical:"small",horizontal:"small",fullHeight:!1,children:e(u,{direction:"vertical",size:10,align:"start",children:e(b,{buttons:h.map((t=>({key:`${t.provider}@${t.version}`,children:e(vt,{integration:t}),onClick:()=>r(t)})))})})}):e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.SecondaryText,{children:"No integrations found"})})})},Ct=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e(bt,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e("div",{children:"No integrations found."}),wt=({title:n,description:l,onCancel:u})=>{const[d,h]=A(!1),f=L(null);return Q((()=>{if(u)return f.current=setTimeout((()=>h(!0)),5e3),()=>{f.current&&clearTimeout(f.current)}}),[u]),t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(w,{size:"xxxsmall"}),e(c.Text,{fontWeight:"bold",size:"large",children:n}),e(c.SecondaryText,{children:l}),d&&u&&t(c.SecondaryText,{children:["Having trouble?"," ",e("button",{type:"button",onClick:u,style:{background:"none",border:"none",padding:0,cursor:"pointer",textDecoration:"underline",font:"inherit",color:"inherit"},children:"Cancel and start over"})]})]})},Ot=({title:t,description:n,onCancel:i})=>e(wt,{title:t,description:n,onCancel:i}),St=({integrationName:n})=>{const l=O();return t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(S.CheckCircleFilled,{size:16,style:{color:l.colors.success.foreground}}),e(c.Text,{fontWeight:"bold",size:"large",children:"Connection Successful"}),t(c.SecondaryText,{children:["Account successfully connected to ",n]})]})},kt=({integrationName:t})=>e(St,{integrationName:t}),xt=({isLoading:t,hasError:n,connectionState:i,selectedIntegration:r,connectorData:s,hubData:o,fields:a,notices:c,selectedCategory:l,search:u,errorHubData:d,errorConnectorData:h,onSelect:f,onChange:p,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,C;return t?e(Ot,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e(Ot,{title:`Connecting to ${null!==(b=null==s?void 0:s.name)&&void 0!==b?b:r.name}`,description:"Please wait, this may take a moment.",onCancel:y}):n?e(Ne,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e(kt,{integrationName:null!==(C=null==s?void 0:s.name)&&void 0!==C?C:r.name}):r?s?e(dt,{fields:a,notices:c,error:i.error,onChange:p,onValidationChange:g,integrationName:s.name,connectorKey:s.key,editingSecrets:v,setEditingSecrets:m},null==r?void 0:r.integration_id):null:(null==o?void 0:o.integrations.length)?e(Ct,{integrations:o.integrations,onSelect:f,selectedCategory:l,search:u}):e(Ne,{message:"No configured integrations available."})};function Rt(t){return!t||t.length<2?[]:t.map((t=>({id:t.integration_id,label:t.profile_name||t.name,subtitle:t.is_default?"Default":void 0,badge:t.authentication_config_label?e(k,{type:"info",fontSize:"xsmall",value:t.authentication_config_label}):void 0})))}const jt=({connectorData:l,onBack:u,guide:d,profileOptions:h,selectedProfileId:f,onProfileChange:p})=>{var g;return t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.SpaceBetween,children:[t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Left,children:[u&&e(x,{variant:"ghost",onClick:u,icon:"←",size:"small"}),e(gt,{src:null===(g=l.assets)||void 0===g?void 0:g.icon,alt:l.key,style:{width:"16px",height:"16px"}}),e(c.Text,{fontWeight:"semi-bold",size:"medium",children:l.name})]}),t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Right,children:[(null==d?void 0:d.supportLink)?e(c.LinkText,{href:d.supportLink,target:"_blank",children:e(x,{variant:"outline",size:"small",children:"Connection guide"})}):null,h&&h.length>0&&t(n,{children:[e(c.SecondaryText,{children:"Connector profile"}),e(y,{name:"connector-profile","aria-label":"Connector profile",size:"small",minWidth:240,menuAlign:"end",items:h,value:f,onItemSelected:e=>e&&(null==p?void 0:p(e))})]})]})]})},qt=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:c,onCategoryChange:l,onSearchChange:u,hideBackButton:d,profiles:h,selectedProfileId:f,onProfileChange:p})=>{if(t)return e(jt,{connectorData:t,onBack:n||d?void 0:i,guide:r,profileOptions:Rt(h),selectedProfileId:f,onProfileChange:p});return!s&&!o&&(null==a?void 0:a.integrations)?e(mt,{integrations:a.integrations,selectedCategory:c,onCategoryChange:l,onSearchChange:u}):null},Pt=({fullWidth:n=!0,selectedIntegration:r,showActions:o,onBack:c,onNext:d,isFormValid:h=!0,isLoading:f=!1,showFooterLinks:p=!0})=>{const g=E((()=>{if(!r||!o)return[];const e=[];return c&&e.push({label:"Back",type:"outline",onClick:c,disabled:f,loading:!1}),e.push({label:"Connect",type:"filled",onClick:d,disabled:!h||f,loading:f}),e}),[r,c,d,o,h,f]);return 0===g.length?p?e(R,{fullWidth:n}):null:t(u,{direction:"horizontal",size:4,justifyContent:"space-between",children:[p&&e(R,{fullWidth:n}),e(l,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(i,{direction:s.Horizontal,justify:a.Right,children:e(u,{direction:"horizontal",size:10,children:g.map((t=>e(x,{size:"small",variant:t.type,onClick:t.onClick,disabled:t.disabled,loading:t.loading,iconPosition:"end",children:t.label},t.label)))})})})]})},It=({showFooterLinks:n=!0,onClose:r,onCloseLabel:o})=>{const c=n,d=Boolean(r);return c||d?t(u,{direction:"horizontal",size:4,justifyContent:c&&d?"space-between":d?"end":void 0,children:[c&&e(R,{fullWidth:!0}),d&&e(l,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(i,{direction:s.Horizontal,justify:a.Right,children:e(u,{direction:"horizontal",size:10,children:e(x,{size:"small",variant:"filled",onClick:r,children:null!=o?o:"Close"})})})})]}):null};function Tt(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Ft="x-hub-version",Dt=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==Ft.toLowerCase()&&(t[n]=i);return t[Ft]="1.13.0",t};function Et(e){return Tt(this,arguments,void 0,(function*({url:e,body:t,headers:n,method:i,requestFn:r=fetch,logger:s=console}){try{const a=yield r(e,{method:i,headers:Dt(n),body:JSON.stringify(t)});if((e=>401===(null==e?void 0:e.status)||403===(null==e?void 0:e.status))(a))return s.warn("Token expired"),null;{if(!a.ok){const e=yield a.json();if(e&&void 0!==(o=e).statusCode){const{statusCode:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["statusCode"]);throw new Error(JSON.stringify(Object.assign({status:t},n)))}}const e=yield a.text();return e?JSON.parse(e):null}}catch(o){throw s.error(`Error making request to ${e}`,o),o}var o}))}function Qt(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"POST"}))}))}function At(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"GET"}))}))}const _t=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){const i={"Content-Type":"application/json","x-hub-session-token":e};let r=`${t}/hub/connectors`;return n&&(r+=`?provider=${encodeURIComponent(n)}`),yield At({url:r,headers:i})})),Lt=e=>Tt(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"PATCH"}))}))}({url:`${e}/hub/accounts/${t}`,headers:{"Content-Type":"application/json","x-hub-session-token":n},body:{integration_id:r,credentials:i}})})),Mt=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),zt=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield function(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Ut=e=>{if(e&&"object"==typeof e&&"message"in e)try{return JSON.parse(e.message).status}catch(e){return}},$t={retry:(e,t)=>{const n=Ut(t);return 401!==n&&403!==n&&e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)},Ht=Object.assign(Object.assign({},$t),{retry:(e,t)=>404!==Ut(t)&&$t.retry(e,t)});var Kt;!function(e){e.AccountConnected="AccountConnected"}(Kt||(Kt={}));const Nt=({token:e,baseUrl:t,accountId:n,onSuccess:i,dashboardUrl:r,debug:s})=>{var o;const[a,c]=A(null),[l,u]=A({}),[d,h]=A(new Set),f=_((e=>{u(e)}),[]),p=L(null),g=L(null),y=L(null),v=L(null),m=L(!1),[b,C]=A({loading:!1,success:!1}),w=_((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null),g.current=null}),[]),O=_((e=>{C({loading:!1,success:!0}),null==i||i(e)}),[i]),S=L(s);S.current=s;const k=_((()=>{null!==v.current&&(clearTimeout(v.current),v.current=null)}),[]),x=_((()=>{w(),k(),p.current&&(p.current.close(),p.current=null)}),[w,k]);Q((()=>()=>{w(),k()}),[w,k]);const{data:R,isLoading:j,error:q}=Ke(Object.assign({queryKey:["accountData",n],queryFn:()=>Tt(void 0,void 0,void 0,(function*(){return n?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,n):null})),enabled:!!n},$t)),{data:P,isLoading:I,error:T}=Ke(Object.assign({queryKey:["hubData",null==R?void 0:R.provider],queryFn:()=>(null==R?void 0:R.provider)?_t(e,t,R.provider):_t(e,t),enabled:!n||!!R},$t));Q((()=>{var e;if(R&&P){const t=null!==(e=P.integrations.find((e=>e.integration_id===R.integrationId)))&&void 0!==e?e:P.integrations.find((e=>e.provider===R.provider));c(null!=t?t:null)}}),[R,P]),Q((()=>{if(P&&!a){const e=P.integrations.filter((e=>e.active));1===e.length&&c(e[0])}}),[P,a]);const F=null!==(o=null==a?void 0:a.integration_id)&&void 0!==o?o:null==R?void 0:R.integrationId,D=!R||a&&a.integration_id!==R.integrationId?void 0:R,{data:M,isLoading:z,error:U}=Ke(Object.assign({queryKey:["connectorData",F],queryFn:()=>F?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,F):null,enabled:Boolean(F)},$t)),{data:$}=Ke(Object.assign({queryKey:["connectorProfiles",null==a?void 0:a.provider],queryFn:()=>a?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connectors/${n}/profiles`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,a.integration_id):null,enabled:Boolean(a)},Ht)),H=null==$?void 0:$.profiles,K=_((e=>{const t=null==H?void 0:H.find((t=>t.integration_id===e));t&&t.integration_id!==(null==a?void 0:a.integration_id)&&(C({loading:!1,success:!1}),c(t))}),[H,a]),{fields:N,guide:V,notices:B}=E((()=>{var e,t,n,i,r,s,o,c,l;if(!M||!a){return{fields:[],notices:[]}}if(("configFields"in(l=M.config)||"configNotices"in l)&&!("authentication"in l)){const s=(null!==(e=M.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==D?void 0:D.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==P?void 0:P.external_trigger_token});if(D&&(!1!==e.secret||"password"===e.type)){const t=null===(n=D.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:s,notices:null!==(t=M.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=M.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=M.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let u=a.authentication_config_key,d=a.environment;(null==D?void 0:D.authConfigKey)&&(null===(s=M.config.authentication)||void 0===s?void 0:s[D.authConfigKey])&&(u=D.authConfigKey,d=null!==(o=D.environment)&&void 0!==o?o:a.environment);const h=null===(c=M.config.authentication)||void 0===c?void 0:c[u],f=null==h?void 0:h[d],p=((null==f?void 0:f.fields)||[]).map((e=>{var t,n;const i=null===(t=null==D?void 0:D.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==P?void 0:P.external_trigger_token});if(D&&(!1!==e.secret||"password"===e.type)){const t=null===(n=D.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:p,notices:[],guide:null==f?void 0:f.guide}}),[M,a,D,P]),W=E((()=>{var e,t,n,i,r;if(!M||!a)return null;if("authentication"in(r=M.config)&&!("configFields"in r)){let r=a.authentication_config_key,s=a.environment;return(null==D?void 0:D.authConfigKey)&&(null===(e=M.config.authentication)||void 0===e?void 0:e[D.authConfigKey])&&(r=D.authConfigKey,s=null!==(t=D.environment)&&void 0!==t?t:a.environment),null===(i=null===(n=M.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return M.config}),[M,a,D]),[G,J]=A(!0),Y=_(((n,i)=>{const r=Date.now(),s=()=>Tt(void 0,void 0,void 0,(function*(){var o,a,c,l;if(!y.current)return;if(Date.now()-r>3e5)return S.current&&console.debug("[hub] poll timed out",{attemptId:n}),x(),zt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void C({loading:!1,success:!1,timedOut:!0});const u=yield Mt(t,e,n).catch((()=>null));if(y.current){if(!u)return S.current&&console.debug("[hub] poll failed (network error), retrying"),void(y.current=window.setTimeout(s,2e3));S.current&&"pending"!==u.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},u)),"authenticated"===u.status&&u.account?(x(),O({id:u.account.id,provider:i}),parent.postMessage({type:Kt.AccountConnected,account:{id:u.account.id,provider:i}},"*")):"error"===u.status?(x(),C({loading:!1,success:!1,error:{message:null!==(a=null===(o=u.error)||void 0===o?void 0:o.code)&&void 0!==a?a:"OAuth error",provider_response:null!==(l=null===(c=u.error)||void 0===c?void 0:c.description)&&void 0!==l?l:"No description"}})):"cancelled"===u.status||"expired"===u.status?(x(),C({loading:!1,success:!1})):y.current=window.setTimeout(s,2e3)}}));y.current=window.setTimeout(s,2e3)}),[t,e,x,O]),X=_((n=>{let i=!0;const r=()=>Tt(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!p.current||p.current.closed))return S.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),m.current=!0,void(v.current=null);if(p.current&&!p.current.closed)return void(v.current=window.setTimeout(r,1e3));if(v.current=null,!y.current)return;if(m.current)return;const s=g.current;if(!s)return;const o=yield Mt(t,e,s).catch((e=>(S.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return y.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(S.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),x(),O({id:o.account.id,provider:n}),void parent.postMessage({type:Kt.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(S.current&&console.debug("[hub] popup reported closed but attempt still pending — deferring to poll loop (likely cross-origin/COOP false-close)",{attemptId:s})):void 0}));v.current=window.setTimeout(r,1e3)}),[t,e,x,O]),Z=_((()=>Tt(void 0,void 0,void 0,(function*(){var i;if(a)if(G){C({loading:!0,success:!1});try{const s=Object.assign({},l);R&&N.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=s[e.key];Xe(t)&&!d.has(e.key)&&delete s[e.key]}})),Object.keys(s).forEach((e=>{""===s[e]&&delete s[e]}));const o="oauth2"===(null==W?void 0:W.type)&&(!("grantType"in W)||"authorization_code"===W.grantType);if(S.current&&console.debug("[hub] handleConnect",{integration:a.integration_id,path:o?"oauth-redirect":"credential-form",updating:!!n}),o){const n=yield((e,t)=>Tt(void 0,void 0,void 0,(function*(){return yield Qt({url:`${e}/hub/connection_attempts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{token:t}})})))(t,e).catch((()=>null)),o=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(g.current=o,!o)return S.current&&console.debug("[hub] connection attempt creation failed"),void C({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});S.current&&console.debug("[hub] connection attempt created",{attemptId:o});const c=encodeURIComponent(`${r}/embedded/accounts/callback`);let l=`${t}/connect/oauth2/${a.integration_id}?redirect_uri=${c}&token=${e}&connection_attempt_id=${o}`;Object.keys(s).forEach((e=>{l+=`&${e}=${encodeURIComponent(s[e])}`}));const u=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,f=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,v=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,b=parseInt((h+(y-u)/2).toString(),10),w=`width=${u},height=${d},left=${b},top=${parseInt((f+(v-d)/2.5).toString(),10)},noopener=0`;return p.current=window.open(l,"Connect Account",w),p.current?(m.current=!1,"function"==typeof p.current.focus&&p.current.focus(),Y(o,a.provider),void X(a.provider)):(S.current&&console.debug("[hub] popup was blocked by browser"),x(),zt(t,e,o).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:o,error:e})})),void C({loading:!1,success:!1,error:{message:"Popup blocked",provider_response:"Your browser blocked the login popup. Please allow popups for this site and try again."}}))}let c;if(n)yield Lt({baseUrl:t,accountId:n,token:e,integrationId:a.integration_id,credentials:s}),c={id:n,provider:a.provider};else{const n=yield(e=>Tt(void 0,[e],void 0,(function*({baseUrl:e,token:t,credentials:n,integrationId:i}){return yield Qt({url:`${e}/hub/accounts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{integration_id:i,credentials:n}})})))({baseUrl:t,token:e,credentials:s,integrationId:a.integration_id});if(!n)throw new Error("Failed to create account");c={id:n.id,provider:a.provider}}O(c)}catch(e){let t="An unexpected error occurred",n="Please try again later";try{const i=JSON.parse(e.message);try{const e=JSON.parse(i.message);t=e.message||t,n=e.provider_response||n}catch(e){t=i.message||t,n=i.provider_response||n}}catch(n){t=e.message||t}C({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else C({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,r,e,a,l,d,O,R,N,n,W,x,Y,X,G]),ee=_((()=>{const n=g.current;S.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),x(),C({loading:!1,success:!1}),n&&zt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,x]),te=I||z||j,ne=!!(T||U||q);Q((()=>{h(new Set)}),[a]),Q((()=>{ne&&b.loading&&C((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[ne,b.loading]);const ie=L(b.loading);Q((()=>{s&&ie.current&&!b.loading&&console.debug("[hub] connectionState.loading → false",b),ie.current=b.loading}),[s,b]);const re=_((()=>{C({loading:!1,success:!1}),h(new Set)}),[]),se=_((()=>{C({loading:!1,success:!1}),h(new Set)}),[]);return{hubData:P,accountData:R,connectorData:M,selectedIntegration:a,profiles:H,fields:N,notices:B,guide:V,formData:l,connectionState:b,isLoading:te,hasError:ne,isFormValid:G,errorHubData:T,errorConnectorData:U,errorAccountData:q,setSelectedIntegration:c,selectProfile:K,setFormData:f,setIsFormValid:J,handleConnect:Z,handleCancelOAuth:ee,resetConnectionState:re,resetAllErrors:se,editingSecrets:d,setEditingSecrets:h}},Vt=({token:n,baseUrl:i,height:r,accountId:s,onSuccess:o,onClose:a,dashboardUrl:c,showFooterLinks:l=!0,onCloseLabel:u,debug:h})=>{var f,p,g,y;const[v,m]=A(null),[b,C]=A(""),{hubData:w,accountData:O,connectorData:S,selectedIntegration:k,profiles:x,fields:R,notices:q,guide:P,connectionState:I,isLoading:T,hasError:F,isFormValid:D,errorHubData:Q,errorConnectorData:L,setSelectedIntegration:M,selectProfile:z,setFormData:U,setIsFormValid:$,handleConnect:H,handleCancelOAuth:K,resetConnectionState:N,editingSecrets:V,setEditingSecrets:B}=Nt({token:n,baseUrl:i,accountId:s,onSuccess:o,dashboardUrl:c,debug:h}),W=_((e=>{$(e)}),[$]),G=E((()=>{if(!w)return!1;return 1===w.integrations.filter((e=>e.active)).length}),[w]),J=()=>{M(null),N(),m(null),C("")};return t(j,{glassFooter:!0,footer:I.success?e(It,{onClose:a,showFooterLinks:l,onCloseLabel:u}):e(Pt,{selectedIntegration:k,showActions:!I.loading&&!I.success,onBack:O||G?void 0:J,onNext:H,isFormValid:D,isLoading:T,showFooterLinks:l}),title:T||I.loading||I.success?null:e(qt,{accountData:O,onBack:J,guide:P,isLoading:T,hasError:F,hubData:w,selectedCategory:v,onCategoryChange:m,onSearchChange:C,hideBackButton:I.loading||I.success||G,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,profiles:x,selectedProfileId:null==k?void 0:k.integration_id,onProfileChange:z}),height:r,padding:"0",headerConfig:k?void 0:{padding:"0"},children:[I.timedOut&&e(d,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e(xt,{isLoading:T,hasError:F,connectionState:I,selectedIntegration:k,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null,hubData:null!=w?w:null,fields:R,notices:q,errorHubData:null!==(g=Q)&&void 0!==g?g:null,errorConnectorData:null!==(y=L)&&void 0!==y?y:null,onSelect:M,onChange:U,onValidationChange:W,onCancelOAuth:K,selectedCategory:v,search:b,editingSecrets:V,setEditingSecrets:B})]})},Bt=M({featureFlags:[]}),Wt=({featureFlags:t,children:n})=>{const i=E((()=>({featureFlags:t})),[t]);return e(Bt.Provider,{value:i,children:n})},Gt=z((({mode:t,token:n,apiUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,accountId:c,showFooterLinks:l,onCloseLabel:u,debug:d})=>{var h;const{data:f}=Ke({queryKey:["settings"],queryFn:()=>((e,t)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e(Wt,{featureFlags:null!==(h=null==f?void 0:f.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e(Vt,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:u,accountId:null!=c?c:null==f?void 0:f.existing_account_id,showFooterLinks:l,debug:d})})})),Jt=()=>t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(S.RejectIcon,{style:{color:"red"}}),e(c.Text,{fontWeight:"bold",size:"large",children:"Error"}),e(c.SecondaryText,{children:"Something went wrong, our team has been notified."})]});class Yt extends D.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?this.props.fallback:this.props.children}}const Xt=({mode:t,token:n,baseUrl:r,appUrl:s,height:l="500px",theme:u="light",accountId:d,onSuccess:h,onClose:f,onCloseLabel:p,showFooterLinks:g,debug:y})=>{const v=null!=r?r:"https://api.stackone.com",m=null!=s?s:"https://app.stackone.com";Q((()=>{"dark"===u?q():"light"===u?P():I(u)}),[u]);const[b]=A((()=>new Fe({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),C=L(n);return Q((()=>{C.current!==n&&(C.current=n,b.clear())}),[n,b]),e(T,n?{children:e(Yt,{fallback:e(j,{height:l,children:e(Jt,{})}),children:e(Me,{client:b,children:e(Gt,{mode:null!=t?t:"integration-picker",token:n,apiUrl:v,dashboardUrl:m,height:l,onSuccess:h,accountId:d,onClose:f,onCloseLabel:p,showFooterLinks:g,debug:y})})})}:{children:e(Yt,{fallback:e(j,{height:l,children:e(Jt,{})}),children:e(j,{height:l,footer:e(R,{}),children:e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.PageTitle,{children:"No token provided"})})})})})};export{Xt as StackOneHub};
1
+ "use client";import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{Flex as i,FlexGapSize as r,FlexDirection as s,FlexAlign as o,FlexJustify as a,Typography as c,Padded as u,Spacer as l,Alert as d,Form as h,CodeBlock as f,Input as p,TextArea as g,Dropdown as y,Divider as v,PillButton as m,ButtonList as b,Avatar as C,TruncatedTooltip as w,Spinner as O,getCurrentTheme as S,CustomIcons as k,Tag as R,Button as x,FooterLinks as j,Card as q,applyDarkTheme as P,applyLightTheme as I,applyTheme as T,MalachiteContext as F}from"@stackone/malachite";import*as D from"react";import E,{useMemo as Q,useEffect as A,useCallback as _,useState as L,useRef as M,createContext as z,memo as U}from"react";import{zodResolver as $}from"@hookform/resolvers/zod";import{useForm as H}from"react-hook-form";import{z as K}from"zod";var N=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},V="undefined"==typeof window||"Deno"in globalThis;function B(){}function W(e){return"number"==typeof e&&e>=0&&e!==1/0}function G(e,t){return Math.max(e+(t||0)-Date.now(),0)}function J(e,t){return"function"==typeof e?e(t):e}function Y(e,t){return"function"==typeof e?e(t):e}function X(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==ee(o,t.options))return!1}else if(!ne(t.queryKey,o))return!1;if("all"!==n){const e=t.isActive();if("active"===n&&!e)return!1;if("inactive"===n&&e)return!1}return("boolean"!=typeof a||t.isStale()===a)&&((!r||r===t.state.fetchStatus)&&!(s&&!s(t)))}function Z(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(te(t.options.mutationKey)!==te(s))return!1}else if(!ne(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function ee(e,t){return(t?.queryKeyHashFn||te)(e)}function te(e){return JSON.stringify(e,((e,t)=>oe(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function ne(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>ne(e[n],t[n]))))}function ie(e,t){if(e===t)return e;const n=se(e)&&se(t);if(n||oe(e)&&oe(t)){const i=n?e:Object.keys(e),r=i.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let c=0;for(let r=0;r<o;r++){const o=n?r:s[r];(!n&&i.includes(o)||n)&&void 0===e[o]&&void 0===t[o]?(a[o]=void 0,c++):(a[o]=ie(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&c++)}return r===o&&c===r?e:a}return t}function re(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function se(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function oe(e){if(!ae(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!ae(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function ae(e){return"[object Object]"===Object.prototype.toString.call(e)}function ce(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?ie(e,t):t}function ue(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function le(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var de=Symbol();function he(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:e.queryFn&&e.queryFn!==de?e.queryFn:()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`))}var fe=new class extends N{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!V&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e((e=>{"boolean"==typeof e?this.setFocused(e):this.onFocus()}))}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach((t=>{t(e)}))}isFocused(){return"boolean"==typeof this.#e?this.#e:"hidden"!==globalThis.document?.visibilityState}},pe=new class extends N{#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!V&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#i!==e&&(this.#i=e,this.listeners.forEach((t=>{t(e)})))}isOnline(){return this.#i}};function ge(){let e,t;const n=new Promise(((n,i)=>{e=n,t=i}));function i(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.status="pending",n.catch((()=>{})),n.resolve=t=>{i({status:"fulfilled",value:t}),e(t)},n.reject=e=>{i({status:"rejected",reason:e}),t(e)},n}function ye(e){return Math.min(1e3*2**e,3e4)}function ve(e){return"online"!==(e??"online")||pe.isOnline()}var me=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function be(e){return e instanceof me}function Ce(e){let t,n=!1,i=0,r=!1;const s=ge(),o=()=>fe.isFocused()&&("always"===e.networkMode||pe.isOnline())&&e.canRun(),a=()=>ve(e.networkMode)&&e.canRun(),c=n=>{r||(r=!0,e.onSuccess?.(n),t?.(),s.resolve(n))},u=n=>{r||(r=!0,e.onError?.(n),t?.(),s.reject(n))},l=()=>new Promise((n=>{t=e=>{(r||o())&&n(e)},e.onPause?.()})).then((()=>{t=void 0,r||e.onContinue?.()})),d=()=>{if(r)return;let t;const s=0===i?e.initialPromise:void 0;try{t=s??e.fn()}catch(e){t=Promise.reject(e)}Promise.resolve(t).then(c).catch((t=>{if(r)return;const s=e.retry??(V?0:3),a=e.retryDelay??ye,c="function"==typeof a?a(i,t):a,h=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var f;!n&&h?(i++,e.onFail?.(i,t),(f=c,new Promise((e=>{setTimeout(e,f)}))).then((()=>o()?void 0:l())).then((()=>{n?u(t):d()}))):u(t)}))};return{promise:s,cancel:t=>{r||(u(new me(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?d():l().then(d),s)}}var we=e=>setTimeout(e,0);var Oe=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=we;const s=i=>{t?e.push(i):r((()=>{n(i)}))};return{batch:s=>{let o;t++;try{o=s()}finally{t--,t||(()=>{const t=e;e=[],t.length&&r((()=>{i((()=>{t.forEach((e=>{n(e)}))}))}))})()}return o},batchCalls:e=>(...t)=>{s((()=>{e(...t)}))},schedule:s,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{i=e},setScheduler:e=>{r=e}}}(),Se=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),W(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(V?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},ke=class extends Se{#s;#o;#a;#c;#u;#l;#d;constructor(e){super(),this.#d=!1,this.#l=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#c=e.client,this.#a=this.#c.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#s=function(e){const t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==t,i=n?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}(this.options),this.state=e.state??this.#s,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#u?.promise}setOptions(e){this.options={...this.#l,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){this.observers.length||"idle"!==this.state.fetchStatus||this.#a.remove(this)}setData(e,t){const n=ce(this.state.data,e,this.options);return this.#h({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#h({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#u?.promise;return this.#u?.cancel(e),t?t.then(B).catch(B):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==Y(e.options.enabled,this)))}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===de||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return!!this.state.isInvalidated||(this.getObserversCount()>0?this.observers.some((e=>e.getCurrentResult().isStale)):void 0===this.state.data)}isStaleByTime(e=0){return this.state.isInvalidated||void 0===this.state.data||!G(this.state.dataUpdatedAt,e)}onFocus(){const e=this.observers.find((e=>e.shouldFetchOnWindowFocus()));e?.refetch({cancelRefetch:!1}),this.#u?.continue()}onOnline(){const e=this.observers.find((e=>e.shouldFetchOnReconnect()));e?.refetch({cancelRefetch:!1}),this.#u?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter((t=>t!==e)),this.observers.length||(this.#u&&(this.#d?this.#u.cancel({revert:!0}):this.#u.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#h({type:"invalidate"})}fetch(e,t){if("idle"!==this.state.fetchStatus)if(void 0!==this.state.data&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#u)return this.#u.continueRetry(),this.#u.promise;if(e&&this.setOptions(e),!this.options.queryFn){const e=this.observers.find((e=>e.options.queryFn));e&&this.setOptions(e.options)}const n=new AbortController,i=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#d=!0,n.signal)})},r={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#c,state:this.state,fetchFn:()=>{const e=he(this.options,t),n={client:this.#c,queryKey:this.queryKey,meta:this.meta};return i(n),this.#d=!1,this.options.persister?this.options.persister(e,n,this):e(n)}};i(r),this.options.behavior?.onFetch(r,this),this.#o=this.state,"idle"!==this.state.fetchStatus&&this.state.fetchMeta===r.fetchOptions?.meta||this.#h({type:"fetch",meta:r.fetchOptions?.meta});const s=e=>{be(e)&&e.silent||this.#h({type:"error",error:e}),be(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#u=Ce({initialPromise:t?.initialPromise,fn:r.fetchFn,abort:n.abort.bind(n),onSuccess:e=>{if(void 0!==e){try{this.setData(e)}catch(e){return void s(e)}this.#a.config.onSuccess?.(e,this),this.#a.config.onSettled?.(e,this.state.error,this),this.scheduleGc()}else s(new Error(`${this.queryHash} data is undefined`))},onError:s,onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:()=>{this.#h({type:"continue"})},retry:r.options.retry,retryDelay:r.options.retryDelay,networkMode:r.options.networkMode,canRun:()=>!0}),this.#u.start()}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...t,fetchStatus:"paused"};case"continue":return{...t,fetchStatus:"fetching"};case"fetch":return{...t,...Re(t.data,this.options),fetchMeta:e.meta??null};case"success":return{...t,data:e.data,dataUpdateCount:t.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const n=e.error;return be(n)&&n.revert&&this.#o?{...this.#o,fetchStatus:"idle"}:{...t,error:n,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...t,isInvalidated:!0};case"setState":return{...t,...e.state}}})(this.state),Oe.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function Re(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ve(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var xe=class extends N{constructor(e={}){super(),this.config=e,this.#f=new Map}#f;build(e,t,n){const i=t.queryKey,r=t.queryHash??ee(i,t);let s=this.get(r);return s||(s=new ke({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#f.has(e.queryHash)||(this.#f.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#f.get(e.queryHash);t&&(e.destroy(),t===e&&this.#f.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Oe.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#f.get(e)}getAll(){return[...this.#f.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>X(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>X(e,t))):t}notify(e){Oe.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){Oe.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){Oe.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},je=class extends Se{#p;#g;#u;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#p=[],this.state=e.state||{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0},this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#p.includes(e)||(this.#p.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#p=this.#p.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#p.length||("pending"===this.state.status?this.scheduleGc():this.#g.remove(this))}continue(){return this.#u?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#h({type:"continue"})};this.#u=Ce({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(e,t)=>{this.#h({type:"failed",failureCount:e,error:t})},onPause:()=>{this.#h({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#g.canRun(this)});const n="pending"===this.state.status,i=!this.#u.canStart();try{if(n)t();else{this.#h({type:"pending",variables:e,isPaused:i}),await(this.#g.config.onMutate?.(e,this));const t=await(this.options.onMutate?.(e));t!==this.state.context&&this.#h({type:"pending",context:t,variables:e,isPaused:i})}const r=await this.#u.start();return await(this.#g.config.onSuccess?.(r,e,this.state.context,this)),await(this.options.onSuccess?.(r,e,this.state.context)),await(this.#g.config.onSettled?.(r,null,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(r,null,e,this.state.context)),this.#h({type:"success",data:r}),r}catch(t){try{throw await(this.#g.config.onError?.(t,e,this.state.context,this)),await(this.options.onError?.(t,e,this.state.context)),await(this.#g.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this)),await(this.options.onSettled?.(void 0,t,e,this.state.context)),t}finally{this.#h({type:"error",error:t})}}finally{this.#g.runNext(this)}}#h(e){this.state=(t=>{switch(e.type){case"failed":return{...t,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...t,isPaused:!0};case"continue":return{...t,isPaused:!1};case"pending":return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}})(this.state),Oe.batch((()=>{this.#p.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var qe=class extends N{constructor(e={}){super(),this.config=e,this.#y=new Set,this.#v=new Map,this.#m=0}#y;#v;#m;build(e,t,n){const i=new je({mutationCache:this,mutationId:++this.#m,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#y.add(e);const t=Pe(e);if("string"==typeof t){const n=this.#v.get(t);n?n.push(e):this.#v.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#y.delete(e)){const t=Pe(e);if("string"==typeof t){const n=this.#v.get(t);if(n)if(n.length>1){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}else n[0]===e&&this.#v.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Pe(e);if("string"==typeof t){const n=this.#v.get(t),i=n?.find((e=>"pending"===e.state.status));return!i||i===e}return!0}runNext(e){const t=Pe(e);if("string"==typeof t){const n=this.#v.get(t)?.find((t=>t!==e&&t.state.isPaused));return n?.continue()??Promise.resolve()}return Promise.resolve()}clear(){Oe.batch((()=>{this.#y.forEach((e=>{this.notify({type:"removed",mutation:e})})),this.#y.clear(),this.#v.clear()}))}getAll(){return Array.from(this.#y)}find(e){const t={exact:!0,...e};return this.getAll().find((e=>Z(t,e)))}findAll(e={}){return this.getAll().filter((t=>Z(e,t)))}notify(e){Oe.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return Oe.batch((()=>Promise.all(e.map((e=>e.continue().catch(B))))))}};function Pe(e){return e.options.scope?.id}function Ie(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let a={pages:[],pageParams:[]},c=0;const u=async()=>{let n=!1;const u=he(t.options,t.fetchOptions),l=async(e,i,r)=>{if(n)return Promise.reject();if(null==i&&e.pages.length)return Promise.resolve(e);const s={client:t.client,queryKey:t.queryKey,pageParam:i,direction:r?"backward":"forward",meta:t.options.meta};var o;o=s,Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(t.signal.aborted?n=!0:t.signal.addEventListener("abort",(()=>{n=!0})),t.signal)});const a=await u(s),{maxPages:c}=t.options,l=r?le:ue;return{pages:l(e.pages,a,c),pageParams:l(e.pageParams,i,c)}};if(r&&s.length){const e="backward"===r,t={pages:s,pageParams:o},n=(e?Fe:Te)(i,t);a=await l(t,n,e)}else{const t=e??s.length;do{const e=0===c?o[0]??i.initialPageParam:Te(i,a);if(c>0&&null==e)break;a=await l(a,e),c++}while(c<t)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function Te(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function Fe(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var De=class{#b;#g;#l;#C;#w;#O;#S;#k;constructor(e={}){this.#b=e.queryCache||new xe,this.#g=e.mutationCache||new qe,this.#l=e.defaultOptions||{},this.#C=new Map,this.#w=new Map,this.#O=0}mount(){this.#O++,1===this.#O&&(this.#S=fe.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#k=pe.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onOnline())})))}unmount(){this.#O--,0===this.#O&&(this.#S?.(),this.#S=void 0,this.#k?.(),this.#k=void 0)}isFetching(e){return this.#b.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#g.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#b.build(this,t),i=n.state.data;return void 0===i?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(J(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#b.findAll(e).map((({queryKey:e,state:t})=>[e,t.data]))}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),r=this.#b.get(i.queryHash),s=r?.state.data,o=function(e,t){return"function"==typeof e?e(t):e}(t,s);if(void 0!==o)return this.#b.build(this,i).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return Oe.batch((()=>this.#b.findAll(e).map((({queryKey:e})=>[e,this.setQueryData(e,t,n)]))))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#b.get(t.queryHash)?.state}removeQueries(e){const t=this.#b;Oe.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return Oe.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=Oe.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(B).catch(B)}invalidateQueries(e,t={}){return Oe.batch((()=>(this.#b.findAll(e).forEach((e=>{e.invalidate()})),"none"===e?.refetchType?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t))))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=Oe.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(B)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(B)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(J(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(B).catch(B)}fetchInfiniteQuery(e){return e.behavior=Ie(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(B).catch(B)}ensureInfiniteQueryData(e){return e.behavior=Ie(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return pe.isOnline()?this.#g.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#b}getMutationCache(){return this.#g}getDefaultOptions(){return this.#l}setDefaultOptions(e){this.#l=e}setQueryDefaults(e,t){this.#C.set(te(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{ne(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#w.set(te(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#w.values()],n={};return t.forEach((t=>{ne(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)})),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#l.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=ee(t.queryKey,t)),void 0===t.refetchOnReconnect&&(t.refetchOnReconnect="always"!==t.networkMode),void 0===t.throwOnError&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===de&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#l.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#b.clear(),this.#g.clear()}},Ee=class extends N{constructor(e,t){super(),this.options=t,this.#c=e,this.#R=null,this.#x=ge(),this.options.experimental_prefetchInRender||this.#x.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#c;#j=void 0;#q=void 0;#P=void 0;#I;#T;#x;#R;#F;#D;#E;#Q;#A;#_;#L=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#j.addObserver(this),Qe(this.#j,this.options)?this.#M():this.updateResult(),this.#z())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ae(this.#j,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ae(this.#j,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#U(),this.#$(),this.#j.removeObserver(this)}setOptions(e){const t=this.options,n=this.#j;if(this.options=this.#c.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof Y(this.options.enabled,this.#j))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#H(),this.#j.setOptions(this.options),t._defaulted&&!re(this.options,t)&&this.#c.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#j,observer:this});const i=this.hasListeners();i&&_e(this.#j,n,this.options,t)&&this.#M(),this.updateResult(),!i||this.#j===n&&Y(this.options.enabled,this.#j)===Y(t.enabled,this.#j)&&J(this.options.staleTime,this.#j)===J(t.staleTime,this.#j)||this.#K();const r=this.#N();!i||this.#j===n&&Y(this.options.enabled,this.#j)===Y(t.enabled,this.#j)&&r===this.#_||this.#V(r)}getOptimisticResult(e){const t=this.#c.getQueryCache().build(this.#c,e),n=this.createResult(t,e);return function(e,t){if(!re(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#P=n,this.#T=this.options,this.#I=this.#j.state),n}getCurrentResult(){return this.#P}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#L.add(e)}getCurrentQuery(){return this.#j}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#c.defaultQueryOptions(e),n=this.#c.getQueryCache().build(this.#c,t);return n.fetch().then((()=>this.createResult(n,t)))}fetch(e){return this.#M({...e,cancelRefetch:e.cancelRefetch??!0}).then((()=>(this.updateResult(),this.#P)))}#M(e){this.#H();let t=this.#j.fetch(this.options,e);return e?.throwOnError||(t=t.catch(B)),t}#K(){this.#U();const e=J(this.options.staleTime,this.#j);if(V||this.#P.isStale||!W(e))return;const t=G(this.#P.dataUpdatedAt,e)+1;this.#Q=setTimeout((()=>{this.#P.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#j):this.options.refetchInterval)??!1}#V(e){this.#$(),this.#_=e,!V&&!1!==Y(this.options.enabled,this.#j)&&W(this.#_)&&0!==this.#_&&(this.#A=setInterval((()=>{(this.options.refetchIntervalInBackground||fe.isFocused())&&this.#M()}),this.#_))}#z(){this.#K(),this.#V(this.#N())}#U(){this.#Q&&(clearTimeout(this.#Q),this.#Q=void 0)}#$(){this.#A&&(clearInterval(this.#A),this.#A=void 0)}createResult(e,t){const n=this.#j,i=this.options,r=this.#P,s=this.#I,o=this.#T,a=e!==n?e.state:this.#q,{state:c}=e;let u,l={...c},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&Qe(e,t),o=r&&_e(e,n,t,i);(s||o)&&(l={...l,...Re(c.data,e.options)}),"isRestoring"===t._optimisticResults&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:f,status:p}=l;u=l.data;let g=!1;if(void 0!==t.placeholderData&&void 0===u&&"pending"===p){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#E?.state.data,this.#E):t.placeholderData,void 0!==e&&(p="success",u=ce(r?.data,e,t),d=!0)}if(t.select&&void 0!==u&&!g)if(r&&u===s?.data&&t.select===this.#F)u=this.#D;else try{this.#F=t.select,u=t.select(u),u=ce(r?.data,u,t),this.#D=u,this.#R=null}catch(e){this.#R=e}this.#R&&(h=this.#R,u=this.#D,f=Date.now(),p="error");const y="fetching"===l.fetchStatus,v="pending"===p,m="error"===p,b=v&&y,C=void 0!==u,w={status:p,fetchStatus:l.fetchStatus,isPending:v,isSuccess:"success"===p,isError:m,isInitialLoading:b,isLoading:b,data:u,dataUpdatedAt:l.dataUpdatedAt,error:h,errorUpdatedAt:f,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>a.dataUpdateCount||l.errorUpdateCount>a.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:m&&!C,isPaused:"paused"===l.fetchStatus,isPlaceholderData:d,isRefetchError:m&&C,isStale:Le(e,t),refetch:this.refetch,promise:this.#x};if(this.options.experimental_prefetchInRender){const t=e=>{"error"===w.status?e.reject(w.error):void 0!==w.data&&e.resolve(w.data)},i=()=>{const e=this.#x=w.promise=ge();t(e)},r=this.#x;switch(r.status){case"pending":e.queryHash===n.queryHash&&t(r);break;case"fulfilled":"error"!==w.status&&w.data===r.value||i();break;case"rejected":"error"===w.status&&w.error===r.reason||i()}}return w}updateResult(){const e=this.#P,t=this.createResult(this.#j,this.options);if(this.#I=this.#j.state,this.#T=this.options,void 0!==this.#I.data&&(this.#E=this.#j),re(t,e))return;this.#P=t;this.#B({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#L.size)return!0;const i=new Set(n??this.#L);return this.options.throwOnError&&i.add("error"),Object.keys(this.#P).some((t=>{const n=t;return this.#P[n]!==e[n]&&i.has(n)}))})()})}#H(){const e=this.#c.getQueryCache().build(this.#c,this.options);if(e===this.#j)return;const t=this.#j;this.#j=e,this.#q=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#z()}#B(e){Oe.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#P)})),this.#c.getQueryCache().notify({query:this.#j,type:"observerResultsUpdated"})}))}};function Qe(e,t){return function(e,t){return!1!==Y(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Ae(e,t,t.refetchOnMount)}function Ae(e,t,n){if(!1!==Y(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&Le(e,t)}return!1}function _e(e,t,n,i){return(e!==t||!1===Y(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&Le(e,n)}function Le(e,t){return!1!==Y(t.enabled,e)&&e.isStaleByTime(J(t.staleTime,e))}var Me=D.createContext(void 0),ze=({client:t,children:n})=>(D.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e(Me.Provider,{value:t,children:n})),Ue=D.createContext(!1);Ue.Provider;var $e=D.createContext(function(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}()),He=(e,t,n)=>t.fetchOptimistic(e).catch((()=>{n.clearReset()}));function Ke(e,t,n){const i=(()=>{const e=D.useContext(Me);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=D.useContext(Ue),s=D.useContext($e),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",(e=>{const t=e.staleTime;e.suspense&&(e.staleTime="function"==typeof t?(...e)=>Math.max(t(...e),1e3):Math.max(t??1e3,1e3),"number"==typeof e.gcTime&&(e.gcTime=Math.max(e.gcTime,1e3)))})(o),((e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))})(o,s),(e=>{D.useEffect((()=>{e.clearReset()}),[e])})(s);const a=!i.getQueryCache().get(o.queryHash),[c]=D.useState((()=>new t(i,o))),u=c.getOptimisticResult(o),l=!r&&!1!==e.subscribed;if(D.useSyncExternalStore(D.useCallback((e=>{const t=l?c.subscribe(Oe.batchCalls(e)):B;return c.updateResult(),t}),[c,l]),(()=>c.getCurrentResult()),(()=>c.getCurrentResult())),D.useEffect((()=>{c.setOptions(o)}),[o,c]),((e,t)=>e?.suspense&&t.isPending)(o,u))throw He(o,c,s);if((({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&void 0===e.data||function(e,t){return"function"==typeof e?e(...t):!!e}(n,[e.error,i])))({result:u,errorResetBoundary:s,throwOnError:o.throwOnError,query:i.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw u.error;if(i.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!V&&((e,t)=>e.isLoading&&e.isFetching&&!t)(u,r)){const e=a?He(o,c,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(B).finally((()=>{c.updateResult()}))}return o.notifyOnChangeProps?u:c.trackResult(u)}function Ne(e,t){return Ke(e,Ee)}const Ve=({message:t})=>e(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:e(c.Text,{size:"medium",fontWeight:"semi-bold",children:t})});var Be=Object.prototype.hasOwnProperty;function We(e,t,n){for(n of e.keys())if(Ge(n,t))return n}function Ge(e,t){var n,i,r;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((i=e.length)===t.length)for(;i--&&Ge(e[i],t[i]););return-1===i}if(n===Set){if(e.size!==t.size)return!1;for(i of e){if((r=i)&&"object"==typeof r&&!(r=We(t,r)))return!1;if(!t.has(r))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(i of e){if((r=i[0])&&"object"==typeof r&&!(r=We(t,r)))return!1;if(!Ge(i[1],t.get(r)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((i=e.byteLength)===t.byteLength)for(;i--&&e.getInt8(i)===t.getInt8(i););return-1===i}if(ArrayBuffer.isView(e)){if((i=e.byteLength)===t.byteLength)for(;i--&&e[i]===t[i];);return-1===i}if(!n||"object"==typeof e){for(n in i=0,e){if(Be.call(e,n)&&++i&&!Be.call(t,n))return!1;if(!(n in t)||!Ge(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function Je(e,t){return D.useEffect(e,(n=t,i=D.useRef(n),r=D.useRef(0),Ge(n,i.current)||(i.current=n,r.current+=1),D.useMemo((function(){return i.current}),[r.current])));var n,i,r}function Ye(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const Xe=/^__secretvalue:\*\*redacted\*\*(.*)$/,Ze=e=>(e=>"string"==typeof e)(e)&&Xe.test(e),et=e=>{const t="••••••••••";if(!Ze(e))return e;const n=e.match(Xe);if(!n)return t;const i=n[1];return i?t+i:t},tt={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/};function nt(e){return void 0!==e.type}function it(e){if((e=>{const t=[];let n=!1;const i=/\{(\d+)(?:(,)(\d*))?\}/y,r=t=>{const n=e[t];if("*"===n||"+"===n)return{length:1,variable:!0,amplifying:!0};if("?"===n)return{length:1,variable:!0,amplifying:!1};if("{"===n){i.lastIndex=t;const n=i.exec(e);if(n){const e=Number(n[1]),t=void 0===n[2]?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let i=0;i<e.length;i++){const s=e[i];if("\\"===s){i++;continue}if(n){"]"===s&&(n=!1);continue}if("["===s){n=!0;continue}if("|"===s){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if("("===s){t.push({hasVariable:!1,hasAlternation:!1}),"?"===e[i+1]&&(i+="<"!==e[i+2]||"="!==e[i+3]&&"!"!==e[i+3]?1:2);continue}if(")"===s){const e=t.pop(),n=r(i+1);if(n){if(n.amplifying&&((null==e?void 0:e.hasVariable)||(null==e?void 0:e.hasAlternation)))return!0;i+=n.length}t.length>0&&(((null==n?void 0:n.variable)||(null==e?void 0:e.hasVariable))&&(t[t.length-1].hasVariable=!0),(null==e?void 0:e.hasAlternation)&&(t[t.length-1].hasAlternation=!0));continue}const o=r(i);o&&(o.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),i+=o.length-1)}return!1})(e))return console.warn(`[stackone-hub] pattern "${e}" risks catastrophic backtracking — field validation skipped`),null;try{return new RegExp(e)}catch(t){return console.warn(`[stackone-hub] pattern "${e}" failed to compile — field validation skipped`),null}}function rt(e){return e.validation?nt(e.validation)?function(e){if("html-pattern"===e.type){const t=it(e.pattern);return t?{pattern:t,errorMessage:e.error||`Please match the required format: ${e.pattern}`}:null}if("domain"===e.type){const t=it(`.*${e.pattern}\\.com.*`);return t?{pattern:t,errorMessage:e.error||`Please enter a valid ${e.pattern}.com domain`}:null}return null}(e.validation):function(e,t){if(e.format){const t=Object.prototype.hasOwnProperty.call(tt,e.format)?tt[e.format]:void 0;return t?{pattern:t,errorMessage:e.errorMessage||`Must be a valid ${e.format}`}:(console.warn(`[stackone-hub] no pattern for format "${e.format}" — field validation skipped; hub FORMAT_PATTERNS has drifted from @stackone/core`),null)}if(e.pattern){const n=it(e.pattern);return n?{pattern:n,errorMessage:e.errorMessage||`${t} format is invalid`}:null}return null}(e.validation,e.label):null}function st(e){const t=new Map;for(const n of e){if("number"===n.type&&!n.required)continue;const e=rt(n);e&&t.set(n.key,e)}return t}function ot(e,t){return!(!e||"string"!=typeof t||""===t||Ze(t))&&!e.pattern.test(t)}function at(e,t){let n=K.string();e.required&&(n=n.min(1,`${e.label} is required`));const i=t=>n=>""===n?!e.required:t(n);return"number"===e.type&&(n=n.refine(i((e=>Ze(e)||/^\d+$/.test(e))),"Must be a valid number")),t&&(n=n.refine(i((e=>!ot(t,e))),t.errorMessage)),n}const ct=({field:i,errors:r,setValue:s,onLeave:o,editingSecrets:a,setEditingSecrets:u})=>{var l,d,h,f,v,m,b,C,w,O,S,k,R,x,j,q,P,I,T,F,D,E,Q;const A="object"==typeof i.key?JSON.stringify(i.key):String(i.key),_=r[A]&&e(c.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(l=r[A])||void 0===l?void 0:l.message});if("text"===(L=i.type)||"number"===L||"password"===L){const c=i.readOnly,l=null===(d=i.value)||void 0===d?void 0:d.toString(),g="external-trigger-token"!==i.key&&(!1!==i.secret||"password"===i.type),y=c&&l&&!g,k=null!==(h=null==a?void 0:a.has(A))&&void 0!==h&&h;if(g&&Ze(l)&&!k)return t(n,{children:[e(p,{name:`${A}-display`,label:i.label,placeholder:i.placeholder,type:"text",required:i.required,disabled:!0,readOnly:!0,defaultValue:l?et(l):"",description:null!==(v=null===(f=i.guide)||void 0===f?void 0:f.description)&&void 0!==v?v:i.description,tooltip:null!==(b=null===(m=i.guide)||void 0===m?void 0:m.tooltip)&&void 0!==b?b:i.tooltip,showCopyButton:!1,buttons:u?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{u((e=>new Set(e).add(A))),s(A,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),_]});const R=!g&&(i.readOnly||!1),x=g?void 0:y?()=>{}:void 0;return t(n,{children:[e(p,{name:A,required:!!c||i.required,placeholder:i.placeholder,disabled:R,readOnly:i.readOnly,label:i.label,tooltip:null!==(w=null===(C=i.guide)||void 0===C?void 0:C.tooltip)&&void 0!==w?w:i.tooltip,description:null!==(S=null===(O=i.guide)||void 0===O?void 0:O.description)&&void 0!==S?S:i.description,type:i.type,error:!!r[A],onChange:e=>s(A,e,{shouldValidate:!0}),onBlur:o,defaultValue:g&&k?"":l,showPasswordToggle:!1,onCopyClick:x},`${A}-${k?"editing":"view"}`),_]})}var L;return"text_area"===i.type?t(n,{children:[e(g,{name:A,required:i.required,placeholder:i.placeholder,disabled:i.readOnly,label:i.label,tooltip:null!==(R=null===(k=i.guide)||void 0===k?void 0:k.tooltip)&&void 0!==R?R:i.tooltip,description:null!==(j=null===(x=i.guide)||void 0===x?void 0:x.description)&&void 0!==j?j:i.description,error:!!r[A],onChange:e=>s(A,e,{shouldValidate:!0}),onBlur:o,defaultValue:(null===(q=i.value)||void 0===q?void 0:q.toString())||""}),_]}):"select"===i.type?t(n,{children:[e(y,{defaultValue:(null===(P=i.value)||void 0===P?void 0:P.toString())||"",disabled:i.readOnly,items:null!==(T=null===(I=i.options)||void 0===I?void 0:I.map((e=>({id:e.value,label:e.label}))))&&void 0!==T?T:[],onItemSelected:e=>s(A,null!=e?e:"",{shouldValidate:!0}),name:A,label:i.label,placeholder:i.placeholder,tooltip:null!==(D=null===(F=i.guide)||void 0===F?void 0:F.tooltip)&&void 0!==D?D:i.tooltip,description:null!==(Q=null===(E=i.guide)||void 0===E?void 0:E.description)&&void 0!==Q?Q:i.description,required:i.required,error:!!r[A]}),_]}):null},ut=({error:t})=>{if(!t)return null;try{return e(f,{json:JSON.parse(t.provider_response)})}catch(n){return(null==t?void 0:t.provider_response)&&(null==t?void 0:t.provider_response.length)>0?e(f,{code:null==t?void 0:t.provider_response}):null}},lt=({integrationName:n,error:h,notices:f=[]})=>{var p;return t(u,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[h&&e(d,{type:"error",message:(null===(p=h.provider_response)||void 0===p?void 0:p.trim())||h.message,hasMargin:!1,children:e(ut,{error:h})}),f.map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(i,{direction:s.Vertical,gapSize:r.Small,fullHeight:!0,justify:a.Center,align:o.Center,children:t(l,{direction:"vertical",size:8,fullWidth:!0,children:[e(c.Text,{size:"small",fontWeight:"semi-bold",children:'Press "Connect" below to authenticate'}),t(c.Text,{size:"small",color:"secondary",children:["An authentication window for ",n," will display,",e("br",{}),"please complete the necessary steps."]})]})})]})},dt=({fields:n,notices:i=[],onChange:r,error:s,onValidationChange:o,integrationName:a,connectorKey:c,editingSecrets:f,setEditingSecrets:p})=>{const g=n.filter((e=>!1!==e.display)),y=g.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:v,noticesAfter:m}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>Ye(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!Ye(e)&&"bottom"===e.position&&t===i))}}(i,y),b=Q((()=>function(e){const t=new Set;return(n,i)=>{if("undefined"==typeof window||t.has(n.key))return;t.add(n.key);const r=nt(i)?void 0:i.format;window.dispatchEvent(new CustomEvent("stackone-hub:field-validation-failed",{detail:Object.assign(Object.assign(Object.assign({},e?{connector:e}:{}),{field:n.key,ruleKind:nt(i)?"legacy":r?"format":"pattern"}),r?{format:r}:{})}))}}(c)),[c]),C=Q((()=>st(n)),[n]),w=Q((()=>function(e,t=st(e)){const n={};for(const i of e)n[i.key]=at(i,t.get(i.key));return K.object(n)}(n,C)),[n,C]),O=Q((()=>{const e={};return n.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[n]),{formState:S,watch:k,reset:R,setValue:x,getValues:j}=H({resolver:$(w),mode:"onTouched",defaultValues:O}),{errors:q,isValid:P}=S;Je((()=>{R(O)}),[O]);const I=k();Je((()=>{r(I)}),[I]),A((()=>{null==o||o(P)}),[P,o]);const T=e=>{document.hasFocus()&&e.validation&&function(e,t,n){return ot(t.get(e.key),n)}(e,C,j(e.key))&&b(e,e.validation)};return 0===g.length?e(lt,{integrationName:a,error:s,notices:i}):e(u,{vertical:"large",horizontal:"medium",overflow:"auto",children:t(l,{direction:"vertical",size:8,fullWidth:!0,children:[s&&e(d,{type:"error",message:s.message,hasMargin:!1,children:e(ut,{error:s})}),e(h,{children:g.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=v(i).length>0||m(i).length>0;return t("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[v(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(ct,{field:n,errors:q,setValue:x,onLeave:()=>T(n),editingSecrets:f,setEditingSecrets:p}),m(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key)))]},i)}))})]})})},ht=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:c,setEditingSecrets:u})=>e(dt,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,connectorKey:a,editingSecrets:c,setEditingSecrets:u}),ft=e=>e.split(/[-_\s]+/).filter(Boolean),pt=e=>ft(e).join(" ").toLowerCase(),gt=e=>ft(e).join(" ").toUpperCase(),yt=e=>Boolean(e.active&&e.name),vt=({integration:n})=>{var u;return t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.SpaceBetween,width:"100%",children:[t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Left,width:"100%",children:[e(C,{src:n.logo_url,name:n.provider,size:24,fallback:"placeholder"}),e(c.Text,{textAlign:"left",children:null!==(u=n.name)&&void 0!==u?u:"N/A"})]}),e(c.SecondaryText,{size:"xsmall",style:{maxWidth:"45%",flexShrink:0},children:e(w,{text:gt(n.type),children:gt(n.type)})})]})},mt=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=_((e=>{s(r===e?null:e)}),[r,s]),c=Q((()=>Array.from(new Set(i.filter(yt).map((e=>pt(e.type)))))),[i]);return t(n,{children:[e(p,{name:"search",placeholder:"Search Integrations",variant:"ghost",size:"large",onChange:o}),c.length>1&&t(n,{children:[e(v,{}),e(u,{vertical:"small",horizontal:"none",fullHeight:!1,children:e("div",{style:{overflowX:"auto",overflowY:"hidden",backgroundColor:"var(--malachite-card-background)",scrollbarWidth:"none",msOverflowStyle:"none"},className:"hide-scrollbar",children:e("div",{style:{display:"flex",minWidth:"max-content"},children:c.map((t=>e(u,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(m,{size:"xsmall",label:gt(t),selected:r===t,onClick:()=>a(t)})},t)))})})})]})]})},bt=({integrations:t,onSelect:r,selectedCategory:s,search:d})=>{const h=Q((()=>t.filter((e=>yt(e)&&(!s||pt(e.type)===s)&&(!d||e.name.toLowerCase().includes(d.toLowerCase()))))),[t,s,d]);return e(n,{children:h.length>0?e(u,{vertical:"small",horizontal:"small",fullHeight:!1,children:e(l,{direction:"vertical",size:10,align:"start",children:e(b,{buttons:h.map((t=>({key:`${t.provider}@${t.version}`,children:e(vt,{integration:t}),onClick:()=>r(t)})))})})}):e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.SecondaryText,{children:"No integrations found"})})})},Ct=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e(bt,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e("div",{children:"No integrations found."}),wt=({title:n,description:u,onCancel:l})=>{const[d,h]=L(!1),f=M(null);return A((()=>{if(l)return f.current=setTimeout((()=>h(!0)),5e3),()=>{f.current&&clearTimeout(f.current)}}),[l]),t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(O,{size:"xxxsmall"}),e(c.Text,{fontWeight:"bold",size:"large",children:n}),e(c.SecondaryText,{children:u}),d&&l&&t(c.SecondaryText,{children:["Having trouble?"," ",e("button",{type:"button",onClick:l,style:{background:"none",border:"none",padding:0,cursor:"pointer",textDecoration:"underline",font:"inherit",color:"inherit"},children:"Cancel and start over"})]})]})},Ot=({title:t,description:n,onCancel:i})=>e(wt,{title:t,description:n,onCancel:i}),St=({integrationName:n})=>{const u=S();return t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(k.CheckCircleFilled,{size:16,style:{color:u.colors.success.foreground}}),e(c.Text,{fontWeight:"bold",size:"large",children:"Connection Successful"}),t(c.SecondaryText,{children:["Account successfully connected to ",n]})]})},kt=({integrationName:t})=>e(St,{integrationName:t}),Rt=({isLoading:t,hasError:n,connectionState:i,selectedIntegration:r,connectorData:s,hubData:o,fields:a,notices:c,selectedCategory:u,search:l,errorHubData:d,errorConnectorData:h,onSelect:f,onChange:p,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,C;return t?e(Ot,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e(Ot,{title:`Connecting to ${null!==(b=null==s?void 0:s.name)&&void 0!==b?b:r.name}`,description:"Please wait, this may take a moment.",onCancel:y}):n?e(Ve,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e(kt,{integrationName:null!==(C=null==s?void 0:s.name)&&void 0!==C?C:r.name}):r?s?e(ht,{fields:a,notices:c,error:i.error,onChange:p,onValidationChange:g,integrationName:s.name,connectorKey:s.key,editingSecrets:v,setEditingSecrets:m},null==r?void 0:r.integration_id):null:(null==o?void 0:o.integrations.length)?e(Ct,{integrations:o.integrations,onSelect:f,selectedCategory:u,search:l}):e(Ve,{message:"No configured integrations available."})};function xt(t){return!t||t.length<2?[]:t.map((t=>({id:t.integration_id,label:t.profile_name||t.name,subtitle:t.is_default?"Default":void 0,badge:t.authentication_config_label?e(R,{type:"default",fontSize:"xsmall",value:t.authentication_config_label}):void 0})))}const jt=({connectorData:u,onBack:l,guide:d,profileOptions:h,selectedProfileId:f,onProfileChange:p})=>{var g;return t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.SpaceBetween,children:[t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Left,children:[l&&e(x,{variant:"ghost",onClick:l,icon:"←",size:"small"}),e(C,{src:null===(g=u.assets)||void 0===g?void 0:g.icon,name:u.key,size:16,fallback:"placeholder"}),e(c.Text,{fontWeight:"semi-bold",size:"medium",children:u.name})]}),t(i,{direction:s.Horizontal,align:o.Center,gapSize:r.Small,justify:a.Right,children:[(null==d?void 0:d.supportLink)?e(c.LinkText,{href:d.supportLink,target:"_blank",children:e(x,{variant:"outline",size:"small",children:"Connection guide"})}):null,h&&h.length>0&&t(n,{children:[e(c.SecondaryText,{children:"Connector profile"}),e(y,{name:"connector-profile","aria-label":"Connector profile",size:"small",minWidth:400,menuAlign:"end",items:h,value:f,onItemSelected:e=>e&&(null==p?void 0:p(e))})]})]})]})},qt=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:c,onCategoryChange:u,onSearchChange:l,hideBackButton:d,profiles:h,selectedProfileId:f,onProfileChange:p})=>{if(t)return e(jt,{connectorData:t,onBack:n||d?void 0:i,guide:r,profileOptions:xt(h),selectedProfileId:f,onProfileChange:p});return!s&&!o&&(null==a?void 0:a.integrations)?e(mt,{integrations:a.integrations,selectedCategory:c,onCategoryChange:u,onSearchChange:l}):null},Pt=({fullWidth:n=!0,selectedIntegration:r,showActions:o,onBack:c,onNext:d,isFormValid:h=!0,isLoading:f=!1,showFooterLinks:p=!0})=>{const g=Q((()=>{if(!r||!o)return[];const e=[];return c&&e.push({label:"Back",type:"outline",onClick:c,disabled:f,loading:!1}),e.push({label:"Connect",type:"filled",onClick:d,disabled:!h||f,loading:f}),e}),[r,c,d,o,h,f]);return 0===g.length?p?e(j,{fullWidth:n}):null:t(l,{direction:"horizontal",size:4,justifyContent:"space-between",children:[p&&e(j,{fullWidth:n}),e(u,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(i,{direction:s.Horizontal,justify:a.Right,children:e(l,{direction:"horizontal",size:10,children:g.map((t=>e(x,{size:"small",variant:t.type,onClick:t.onClick,disabled:t.disabled,loading:t.loading,iconPosition:"end",children:t.label},t.label)))})})})]})},It=({showFooterLinks:n=!0,onClose:r,onCloseLabel:o})=>{const c=n,d=Boolean(r);return c||d?t(l,{direction:"horizontal",size:4,justifyContent:c&&d?"space-between":d?"end":void 0,children:[c&&e(j,{fullWidth:!0}),d&&e(u,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(i,{direction:s.Horizontal,justify:a.Right,children:e(l,{direction:"horizontal",size:10,children:e(x,{size:"small",variant:"filled",onClick:r,children:null!=o?o:"Close"})})})})]}):null};function Tt(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Ft="x-hub-version",Dt=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==Ft.toLowerCase()&&(t[n]=i);return t[Ft]="1.13.2",t};function Et(e){return Tt(this,arguments,void 0,(function*({url:e,body:t,headers:n,method:i,requestFn:r=fetch,logger:s=console}){try{const a=yield r(e,{method:i,headers:Dt(n),body:JSON.stringify(t)});if((e=>401===(null==e?void 0:e.status)||403===(null==e?void 0:e.status))(a))return s.warn("Token expired"),null;{if(!a.ok){const e=yield a.json();if(e&&void 0!==(o=e).statusCode){const{statusCode:t}=e,n=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(e,["statusCode"]);throw new Error(JSON.stringify(Object.assign({status:t},n)))}}const e=yield a.text();return e?JSON.parse(e):null}}catch(o){throw s.error(`Error making request to ${e}`,o),o}var o}))}function Qt(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"POST"}))}))}function At(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"GET"}))}))}const _t=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){const i={"Content-Type":"application/json","x-hub-session-token":e};let r=`${t}/hub/connectors`;return n&&(r+=`?provider=${encodeURIComponent(n)}`),yield At({url:r,headers:i})})),Lt=e=>Tt(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"PATCH"}))}))}({url:`${e}/hub/accounts/${t}`,headers:{"Content-Type":"application/json","x-hub-session-token":n},body:{integration_id:r,credentials:i}})})),Mt=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),zt=(e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield function(e){return Tt(this,void 0,void 0,(function*(){return Et(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Ut=e=>{if(e&&"object"==typeof e&&"message"in e)try{return JSON.parse(e.message).status}catch(e){return}},$t={retry:(e,t)=>{const n=Ut(t);return 401!==n&&403!==n&&e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)},Ht=Object.assign(Object.assign({},$t),{retry:(e,t)=>404!==Ut(t)&&$t.retry(e,t)});var Kt;!function(e){e.AccountConnected="AccountConnected"}(Kt||(Kt={}));const Nt=({token:e,baseUrl:t,accountId:n,onSuccess:i,dashboardUrl:r,debug:s})=>{var o;const[a,c]=L(null),[u,l]=L({}),[d,h]=L(new Set),f=_((e=>{l(e)}),[]),p=M(null),g=M(null),y=M(null),v=M(null),m=M(!1),[b,C]=L({loading:!1,success:!1}),w=_((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null),g.current=null}),[]),O=_((e=>{C({loading:!1,success:!0}),null==i||i(e)}),[i]),S=M(s);S.current=s;const k=_((()=>{null!==v.current&&(clearTimeout(v.current),v.current=null)}),[]),R=_((()=>{w(),k(),p.current&&(p.current.close(),p.current=null)}),[w,k]);A((()=>()=>{w(),k()}),[w,k]);const{data:x,isLoading:j,error:q}=Ne(Object.assign({queryKey:["accountData",n],queryFn:()=>Tt(void 0,void 0,void 0,(function*(){return n?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,n):null})),enabled:!!n},$t)),{data:P,isLoading:I,error:T}=Ne(Object.assign({queryKey:["hubData",null==x?void 0:x.provider],queryFn:()=>(null==x?void 0:x.provider)?_t(e,t,x.provider):_t(e,t),enabled:!n||!!x},$t));A((()=>{var e;if(x&&P){const t=null!==(e=P.integrations.find((e=>e.integration_id===x.integrationId)))&&void 0!==e?e:P.integrations.find((e=>e.provider===x.provider));c(null!=t?t:null)}}),[x,P]),A((()=>{if(P&&!a){const e=P.integrations.filter((e=>e.active));1===e.length&&c(e[0])}}),[P,a]);const F=null!==(o=null==a?void 0:a.integration_id)&&void 0!==o?o:null==x?void 0:x.integrationId,D=!x||a&&a.integration_id!==x.integrationId?void 0:x,{data:E,isLoading:z,error:U}=Ne(Object.assign({queryKey:["connectorData",F],queryFn:()=>F?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,F):null,enabled:Boolean(F)},$t)),{data:$}=Ne(Object.assign({queryKey:["connectorProfiles",null==a?void 0:a.provider],queryFn:()=>a?((e,t,n)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/connectors/${n}/profiles`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,a.integration_id):null,enabled:Boolean(a)},Ht)),H=null==$?void 0:$.profiles,K=_((e=>{const t=null==H?void 0:H.find((t=>t.integration_id===e));t&&t.integration_id!==(null==a?void 0:a.integration_id)&&(C({loading:!1,success:!1}),c(t))}),[H,a]),{fields:N,guide:V,notices:B}=Q((()=>{var e,t,n,i,r,s,o,c,u;if(!E||!a){return{fields:[],notices:[]}}if(("configFields"in(u=E.config)||"configNotices"in u)&&!("authentication"in u)){const s=(null!==(e=E.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==D?void 0:D.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==P?void 0:P.external_trigger_token});if(D&&(!1!==e.secret||"password"===e.type)){const t=null===(n=D.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:s,notices:null!==(t=E.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=E.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=E.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let l=a.authentication_config_key,d=a.environment;(null==D?void 0:D.authConfigKey)&&(null===(s=E.config.authentication)||void 0===s?void 0:s[D.authConfigKey])&&(l=D.authConfigKey,d=null!==(o=D.environment)&&void 0!==o?o:a.environment);const h=null===(c=E.config.authentication)||void 0===c?void 0:c[l],f=null==h?void 0:h[d],p=((null==f?void 0:f.fields)||[]).map((e=>{var t,n;const i=null===(t=null==D?void 0:D.setupInformation)||void 0===t?void 0:t[e.key];if("external-trigger-token"===e.key)return Object.assign(Object.assign({},e),{key:e.key,value:null==P?void 0:P.external_trigger_token});if(D&&(!1!==e.secret||"password"===e.type)){const t=null===(n=D.secrets)||void 0===n?void 0:n[e.key];return t?Object.assign(Object.assign({},e),{key:e.key,value:t}):Object.assign(Object.assign({},e),{key:e.key,value:""})}const r=void 0!==i?i:e.value;return r?Object.assign(Object.assign({},e),{key:e.key,value:r}):Object.assign(Object.assign({},e),{key:e.key})})).filter((e=>null!=e));return{fields:p,notices:[],guide:null==f?void 0:f.guide}}),[E,a,D,P]),W=Q((()=>{var e,t,n,i,r;if(!E||!a)return null;if("authentication"in(r=E.config)&&!("configFields"in r)){let r=a.authentication_config_key,s=a.environment;return(null==D?void 0:D.authConfigKey)&&(null===(e=E.config.authentication)||void 0===e?void 0:e[D.authConfigKey])&&(r=D.authConfigKey,s=null!==(t=D.environment)&&void 0!==t?t:a.environment),null===(i=null===(n=E.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return E.config}),[E,a,D]),[G,J]=L(!0),Y=_(((n,i)=>{const r=Date.now(),s=()=>Tt(void 0,void 0,void 0,(function*(){var o,a,c,u;if(!y.current)return;if(Date.now()-r>3e5)return S.current&&console.debug("[hub] poll timed out",{attemptId:n}),R(),zt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void C({loading:!1,success:!1,timedOut:!0});const l=yield Mt(t,e,n).catch((()=>null));if(y.current){if(!l)return S.current&&console.debug("[hub] poll failed (network error), retrying"),void(y.current=window.setTimeout(s,2e3));S.current&&"pending"!==l.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},l)),"authenticated"===l.status&&l.account?(R(),O({id:l.account.id,provider:i}),parent.postMessage({type:Kt.AccountConnected,account:{id:l.account.id,provider:i}},"*")):"error"===l.status?(R(),C({loading:!1,success:!1,error:{message:null!==(a=null===(o=l.error)||void 0===o?void 0:o.code)&&void 0!==a?a:"OAuth error",provider_response:null!==(u=null===(c=l.error)||void 0===c?void 0:c.description)&&void 0!==u?u:"No description"}})):"cancelled"===l.status||"expired"===l.status?(R(),C({loading:!1,success:!1})):y.current=window.setTimeout(s,2e3)}}));y.current=window.setTimeout(s,2e3)}),[t,e,R,O]),X=_((n=>{let i=!0;const r=()=>Tt(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!p.current||p.current.closed))return S.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),m.current=!0,void(v.current=null);if(p.current&&!p.current.closed)return void(v.current=window.setTimeout(r,1e3));if(v.current=null,!y.current)return;if(m.current)return;const s=g.current;if(!s)return;const o=yield Mt(t,e,s).catch((e=>(S.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return y.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(S.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),R(),O({id:o.account.id,provider:n}),void parent.postMessage({type:Kt.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(S.current&&console.debug("[hub] popup reported closed but attempt still pending — deferring to poll loop (likely cross-origin/COOP false-close)",{attemptId:s})):void 0}));v.current=window.setTimeout(r,1e3)}),[t,e,R,O]),Z=_((()=>Tt(void 0,void 0,void 0,(function*(){var i;if(a)if(G){C({loading:!0,success:!1});try{const s=Object.assign({},u);x&&N.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=s[e.key];Ze(t)&&!d.has(e.key)&&delete s[e.key]}})),Object.keys(s).forEach((e=>{""===s[e]&&delete s[e]}));const o="oauth2"===(null==W?void 0:W.type)&&(!("grantType"in W)||"authorization_code"===W.grantType);if(S.current&&console.debug("[hub] handleConnect",{integration:a.integration_id,path:o?"oauth-redirect":"credential-form",updating:!!n}),o){const n=yield((e,t)=>Tt(void 0,void 0,void 0,(function*(){return yield Qt({url:`${e}/hub/connection_attempts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{token:t}})})))(t,e).catch((()=>null)),o=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(g.current=o,!o)return S.current&&console.debug("[hub] connection attempt creation failed"),void C({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});S.current&&console.debug("[hub] connection attempt created",{attemptId:o});const c=encodeURIComponent(`${r}/embedded/accounts/callback`);let u=`${t}/connect/oauth2/${a.integration_id}?redirect_uri=${c}&token=${e}&connection_attempt_id=${o}`;Object.keys(s).forEach((e=>{u+=`&${e}=${encodeURIComponent(s[e])}`}));const l=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,f=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,v=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,b=parseInt((h+(y-l)/2).toString(),10),w=`width=${l},height=${d},left=${b},top=${parseInt((f+(v-d)/2.5).toString(),10)},noopener=0`;return p.current=window.open(u,"Connect Account",w),p.current?(m.current=!1,"function"==typeof p.current.focus&&p.current.focus(),Y(o,a.provider),void X(a.provider)):(S.current&&console.debug("[hub] popup was blocked by browser"),R(),zt(t,e,o).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:o,error:e})})),void C({loading:!1,success:!1,error:{message:"Popup blocked",provider_response:"Your browser blocked the login popup. Please allow popups for this site and try again."}}))}let c;if(n)yield Lt({baseUrl:t,accountId:n,token:e,integrationId:a.integration_id,credentials:s}),c={id:n,provider:a.provider};else{const n=yield(e=>Tt(void 0,[e],void 0,(function*({baseUrl:e,token:t,credentials:n,integrationId:i}){return yield Qt({url:`${e}/hub/accounts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{integration_id:i,credentials:n}})})))({baseUrl:t,token:e,credentials:s,integrationId:a.integration_id});if(!n)throw new Error("Failed to create account");c={id:n.id,provider:a.provider}}O(c)}catch(e){let t="An unexpected error occurred",n="Please try again later";try{const i=JSON.parse(e.message);try{const e=JSON.parse(i.message);t=e.message||t,n=e.provider_response||n}catch(e){t=i.message||t,n=i.provider_response||n}}catch(n){t=e.message||t}C({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else C({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,r,e,a,u,d,O,x,N,n,W,R,Y,X,G]),ee=_((()=>{const n=g.current;S.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),R(),C({loading:!1,success:!1}),n&&zt(t,e,n).catch((e=>{S.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,R]),te=I||z||j,ne=!!(T||U||q);A((()=>{h(new Set)}),[a]),A((()=>{ne&&b.loading&&C((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[ne,b.loading]);const ie=M(b.loading);A((()=>{s&&ie.current&&!b.loading&&console.debug("[hub] connectionState.loading → false",b),ie.current=b.loading}),[s,b]);const re=_((()=>{C({loading:!1,success:!1}),h(new Set)}),[]),se=_((()=>{C({loading:!1,success:!1}),h(new Set)}),[]);return{hubData:P,accountData:x,connectorData:E,selectedIntegration:a,profiles:H,fields:N,notices:B,guide:V,formData:u,connectionState:b,isLoading:te,hasError:ne,isFormValid:G,errorHubData:T,errorConnectorData:U,errorAccountData:q,setSelectedIntegration:c,selectProfile:K,setFormData:f,setIsFormValid:J,handleConnect:Z,handleCancelOAuth:ee,resetConnectionState:re,resetAllErrors:se,editingSecrets:d,setEditingSecrets:h}},Vt=({token:n,baseUrl:i,height:r,accountId:s,onSuccess:o,onClose:a,dashboardUrl:c,showFooterLinks:u=!0,onCloseLabel:l,debug:h})=>{var f,p,g,y;const[v,m]=L(null),[b,C]=L(""),{hubData:w,accountData:O,connectorData:S,selectedIntegration:k,profiles:R,fields:x,notices:j,guide:P,connectionState:I,isLoading:T,hasError:F,isFormValid:D,errorHubData:E,errorConnectorData:A,setSelectedIntegration:M,selectProfile:z,setFormData:U,setIsFormValid:$,handleConnect:H,handleCancelOAuth:K,resetConnectionState:N,editingSecrets:V,setEditingSecrets:B}=Nt({token:n,baseUrl:i,accountId:s,onSuccess:o,dashboardUrl:c,debug:h}),W=_((e=>{$(e)}),[$]),G=Q((()=>{if(!w)return!1;return 1===w.integrations.filter((e=>e.active)).length}),[w]),J=()=>{M(null),N(),m(null),C("")};return t(q,{glassFooter:!0,footer:I.success?e(It,{onClose:a,showFooterLinks:u,onCloseLabel:l}):e(Pt,{selectedIntegration:k,showActions:!I.loading&&!I.success,onBack:O||G?void 0:J,onNext:H,isFormValid:D,isLoading:T,showFooterLinks:u}),title:T||I.loading||I.success?null:e(qt,{accountData:O,onBack:J,guide:P,isLoading:T,hasError:F,hubData:w,selectedCategory:v,onCategoryChange:m,onSearchChange:C,hideBackButton:I.loading||I.success||G,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,profiles:R,selectedProfileId:null==k?void 0:k.integration_id,onProfileChange:z}),height:r,padding:"0",headerConfig:k?void 0:{padding:"0"},children:[I.timedOut&&e(d,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e(Rt,{isLoading:T,hasError:F,connectionState:I,selectedIntegration:k,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null,hubData:null!=w?w:null,fields:x,notices:j,errorHubData:null!==(g=E)&&void 0!==g?g:null,errorConnectorData:null!==(y=A)&&void 0!==y?y:null,onSelect:M,onChange:U,onValidationChange:W,onCancelOAuth:K,selectedCategory:v,search:b,editingSecrets:V,setEditingSecrets:B})]})},Bt=z({featureFlags:[]}),Wt=({featureFlags:t,children:n})=>{const i=Q((()=>({featureFlags:t})),[t]);return e(Bt.Provider,{value:i,children:n})},Gt=U((({mode:t,token:n,apiUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,accountId:c,showFooterLinks:u,onCloseLabel:l,debug:d})=>{var h;const{data:f}=Ne({queryKey:["settings"],queryFn:()=>((e,t)=>Tt(void 0,void 0,void 0,(function*(){return yield At({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e(Wt,{featureFlags:null!==(h=null==f?void 0:f.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e(Vt,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:l,accountId:null!=c?c:null==f?void 0:f.existing_account_id,showFooterLinks:u,debug:d})})})),Jt=()=>t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(k.RejectIcon,{style:{color:"red"}}),e(c.Text,{fontWeight:"bold",size:"large",children:"Error"}),e(c.SecondaryText,{children:"Something went wrong, our team has been notified."})]});class Yt extends E.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?this.props.fallback:this.props.children}}const Xt=({mode:t,token:n,baseUrl:r,appUrl:s,height:u="500px",theme:l="light",accountId:d,onSuccess:h,onClose:f,onCloseLabel:p,showFooterLinks:g,debug:y})=>{const v=null!=r?r:"https://api.stackone.com",m=null!=s?s:"https://app.stackone.com";A((()=>{"dark"===l?P():"light"===l?I():T(l)}),[l]);const[b]=L((()=>new De({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),C=M(n);return A((()=>{C.current!==n&&(C.current=n,b.clear())}),[n,b]),e(F,n?{children:e(Yt,{fallback:e(q,{height:u,children:e(Jt,{})}),children:e(ze,{client:b,children:e(Gt,{mode:null!=t?t:"integration-picker",token:n,apiUrl:v,dashboardUrl:m,height:u,onSuccess:h,accountId:d,onClose:f,onCloseLabel:p,showFooterLinks:g,debug:y})})})}:{children:e(Yt,{fallback:e(q,{height:u,children:e(Jt,{})}),children:e(q,{height:u,footer:e(j,{}),children:e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.PageTitle,{children:"No token provided"})})})})})};export{Xt as StackOneHub};