@stackone/hub 1.11.2 → 1.11.4
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 +1 -1
- package/dist/index.js +1 -1
- package/dist/webcomponent.js +2 -2
- package/dist/webcomponent.js.map +1 -1
- package/package.json +2 -2
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 u,Spacer as l,Alert as d,Form as h,CodeBlock as p,Input as f,TextArea as g,Dropdown as y,Divider as v,PillButton as m,ButtonList as b,Spinner as C,getCurrentTheme as w,CustomIcons as O,Button as S,FooterLinks as k,Card as R,applyDarkTheme as x,applyLightTheme as q,applyTheme as j,MalachiteContext as T}from"@stackone/malachite";import*as I from"react";import D,{useMemo as F,useEffect as E,useState as P,useCallback as Q,useRef as A,createContext as L,memo as M}from"react";import{zodResolver as U}from"@hookform/resolvers/zod";import{useForm as _}from"react-hook-form";import{z}from"zod";var H=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(){}},$="undefined"==typeof window||"Deno"in globalThis;function K(){}function N(e){return"number"==typeof e&&e>=0&&e!==1/0}function V(e,t){return Math.max(e+(t||0)-Date.now(),0)}function B(e,t){return"function"==typeof e?e(t):e}function W(e,t){return"function"==typeof e?e(t):e}function G(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==Y(o,t.options))return!1}else if(!Z(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 J(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(X(t.options.mutationKey)!==X(s))return!1}else if(!Z(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function Y(e,t){return(t?.queryKeyHashFn||X)(e)}function X(e){return JSON.stringify(e,((e,t)=>ie(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function Z(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>Z(e[n],t[n]))))}function ee(e,t){if(e===t)return e;const n=ne(e)&&ne(t);if(n||ie(e)&&ie(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]=ee(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&c++)}return r===o&&c===r?e:a}return t}function te(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 ne(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ie(e){if(!re(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!re(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function re(e){return"[object Object]"===Object.prototype.toString.call(e)}function se(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?ee(e,t):t}function oe(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function ae(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var ce=Symbol();function ue(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:e.queryFn&&e.queryFn!==ce?e.queryFn:()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`))}var le=new class extends H{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!$&&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}},de=new class extends H{#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!$&&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 he(){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 pe(e){return Math.min(1e3*2**e,3e4)}function fe(e){return"online"!==(e??"online")||de.isOnline()}var ge=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ye(e){return e instanceof ge}function ve(e){let t,n=!1,i=0,r=!1;const s=he(),o=()=>le.isFocused()&&("always"===e.networkMode||de.isOnline())&&e.canRun(),a=()=>fe(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??($?0:3),a=e.retryDelay??pe,c="function"==typeof a?a(i,t):a,h=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var p;!n&&h?(i++,e.onFail?.(i,t),(p=c,new Promise((e=>{setTimeout(e,p)}))).then((()=>o()?void 0:l())).then((()=>{n?u(t):d()}))):u(t)}))};return{promise:s,cancel:t=>{r||(u(new ge(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?d():l().then(d),s)}}var me=e=>setTimeout(e,0);var be=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=me;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}}}(),Ce=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),N(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},we=class extends Ce{#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=se(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(K).catch(K):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==W(e.options.enabled,this)))}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ce||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||!V(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=ue(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=>{ye(e)&&e.silent||this.#h({type:"error",error:e}),ye(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#u=ve({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,...Oe(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 ye(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),be.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function Oe(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fe(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var Se=class extends H{constructor(e={}){super(),this.config=e,this.#p=new Map}#p;build(e,t,n){const i=t.queryKey,r=t.queryHash??Y(i,t);let s=this.get(r);return s||(s=new we({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#p.has(e.queryHash)||(this.#p.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#p.get(e.queryHash);t&&(e.destroy(),t===e&&this.#p.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){be.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#p.get(e)}getAll(){return[...this.#p.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>G(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>G(e,t))):t}notify(e){be.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){be.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){be.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},ke=class extends Ce{#f;#g;#u;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#f=[],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.#f.includes(e)||(this.#f.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#f=this.#f.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#f.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=ve({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),be.batch((()=>{this.#f.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var Re=class extends H{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 ke({mutationCache:this,mutationId:++this.#m,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#y.add(e);const t=xe(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=xe(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=xe(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=xe(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(){be.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=>J(t,e)))}findAll(e={}){return this.getAll().filter((t=>J(e,t)))}notify(e){be.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return be.batch((()=>Promise.all(e.map((e=>e.continue().catch(K))))))}};function xe(e){return e.options.scope?.id}function qe(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=ue(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?ae:oe;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?Te:je)(i,t);a=await l(t,n,e)}else{const t=e??s.length;do{const e=0===c?o[0]??i.initialPageParam:je(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 je(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 Ie=class{#b;#g;#l;#C;#w;#O;#S;#k;constructor(e={}){this.#b=e.queryCache||new Se,this.#g=e.mutationCache||new Re,this.#l=e.defaultOptions||{},this.#C=new Map,this.#w=new Map,this.#O=0}mount(){this.#O++,1===this.#O&&(this.#S=le.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#k=de.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(B(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 be.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;be.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return be.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=be.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(K).catch(K)}invalidateQueries(e,t={}){return be.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=be.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(K)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(K)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(B(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(K).catch(K)}fetchInfiniteQuery(e){return e.behavior=qe(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(K).catch(K)}ensureInfiniteQueryData(e){return e.behavior=qe(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return de.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(X(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{Z(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#w.set(X(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#w.values()],n={};return t.forEach((t=>{Z(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=Y(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===ce&&(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()}},De=class extends H{constructor(e,t){super(),this.options=t,this.#c=e,this.#R=null,this.#x=he(),this.options.experimental_prefetchInRender||this.#x.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#c;#q=void 0;#j=void 0;#T=void 0;#I;#D;#x;#R;#F;#E;#P;#Q;#A;#L;#M=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#q.addObserver(this),Fe(this.#q,this.options)?this.#U():this.updateResult(),this.#_())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ee(this.#q,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ee(this.#q,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#z(),this.#H(),this.#q.removeObserver(this)}setOptions(e){const t=this.options,n=this.#q;if(this.options=this.#c.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof W(this.options.enabled,this.#q))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#$(),this.#q.setOptions(this.options),t._defaulted&&!te(this.options,t)&&this.#c.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#q,observer:this});const i=this.hasListeners();i&&Pe(this.#q,n,this.options,t)&&this.#U(),this.updateResult(),!i||this.#q===n&&W(this.options.enabled,this.#q)===W(t.enabled,this.#q)&&B(this.options.staleTime,this.#q)===B(t.staleTime,this.#q)||this.#K();const r=this.#N();!i||this.#q===n&&W(this.options.enabled,this.#q)===W(t.enabled,this.#q)&&r===this.#L||this.#V(r)}getOptimisticResult(e){const t=this.#c.getQueryCache().build(this.#c,e),n=this.createResult(t,e);return function(e,t){if(!te(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#T=n,this.#D=this.options,this.#I=this.#q.state),n}getCurrentResult(){return this.#T}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#M.add(e)}getCurrentQuery(){return this.#q}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.#U({...e,cancelRefetch:e.cancelRefetch??!0}).then((()=>(this.updateResult(),this.#T)))}#U(e){this.#$();let t=this.#q.fetch(this.options,e);return e?.throwOnError||(t=t.catch(K)),t}#K(){this.#z();const e=B(this.options.staleTime,this.#q);if($||this.#T.isStale||!N(e))return;const t=V(this.#T.dataUpdatedAt,e)+1;this.#Q=setTimeout((()=>{this.#T.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#q):this.options.refetchInterval)??!1}#V(e){this.#H(),this.#L=e,!$&&!1!==W(this.options.enabled,this.#q)&&N(this.#L)&&0!==this.#L&&(this.#A=setInterval((()=>{(this.options.refetchIntervalInBackground||le.isFocused())&&this.#U()}),this.#L))}#_(){this.#K(),this.#V(this.#N())}#z(){this.#Q&&(clearTimeout(this.#Q),this.#Q=void 0)}#H(){this.#A&&(clearInterval(this.#A),this.#A=void 0)}createResult(e,t){const n=this.#q,i=this.options,r=this.#T,s=this.#I,o=this.#D,a=e!==n?e.state:this.#j,{state:c}=e;let u,l={...c},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&Fe(e,t),o=r&&Pe(e,n,t,i);(s||o)&&(l={...l,...Oe(c.data,e.options)}),"isRestoring"===t._optimisticResults&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:p,status:f}=l;u=l.data;let g=!1;if(void 0!==t.placeholderData&&void 0===u&&"pending"===f){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#P?.state.data,this.#P):t.placeholderData,void 0!==e&&(f="success",u=se(r?.data,e,t),d=!0)}if(t.select&&void 0!==u&&!g)if(r&&u===s?.data&&t.select===this.#F)u=this.#E;else try{this.#F=t.select,u=t.select(u),u=se(r?.data,u,t),this.#E=u,this.#R=null}catch(e){this.#R=e}this.#R&&(h=this.#R,u=this.#E,p=Date.now(),f="error");const y="fetching"===l.fetchStatus,v="pending"===f,m="error"===f,b=v&&y,C=void 0!==u,w={status:f,fetchStatus:l.fetchStatus,isPending:v,isSuccess:"success"===f,isError:m,isInitialLoading:b,isLoading:b,data:u,dataUpdatedAt:l.dataUpdatedAt,error:h,errorUpdatedAt:p,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:Qe(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=he();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.#T,t=this.createResult(this.#q,this.options);if(this.#I=this.#q.state,this.#D=this.options,void 0!==this.#I.data&&(this.#P=this.#q),te(t,e))return;this.#T=t;this.#B({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#M.size)return!0;const i=new Set(n??this.#M);return this.options.throwOnError&&i.add("error"),Object.keys(this.#T).some((t=>{const n=t;return this.#T[n]!==e[n]&&i.has(n)}))})()})}#$(){const e=this.#c.getQueryCache().build(this.#c,this.options);if(e===this.#q)return;const t=this.#q;this.#q=e,this.#j=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#_()}#B(e){be.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#T)})),this.#c.getQueryCache().notify({query:this.#q,type:"observerResultsUpdated"})}))}};function Fe(e,t){return function(e,t){return!1!==W(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Ee(e,t,t.refetchOnMount)}function Ee(e,t,n){if(!1!==W(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&Qe(e,t)}return!1}function Pe(e,t,n,i){return(e!==t||!1===W(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&Qe(e,n)}function Qe(e,t){return!1!==W(t.enabled,e)&&e.isStaleByTime(B(t.staleTime,e))}var Ae=I.createContext(void 0),Le=({client:t,children:n})=>(I.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e(Ae.Provider,{value:t,children:n})),Me=I.createContext(!1);Me.Provider;var Ue=I.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 ze(e,t,n){const i=(()=>{const e=I.useContext(Ae);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=I.useContext(Me),s=I.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=>{I.useEffect((()=>{e.clearReset()}),[e])})(s);const a=!i.getQueryCache().get(o.queryHash),[c]=I.useState((()=>new t(i,o))),u=c.getOptimisticResult(o),l=!r&&!1!==e.subscribed;if(I.useSyncExternalStore(I.useCallback((e=>{const t=l?c.subscribe(be.batchCalls(e)):K;return c.updateResult(),t}),[c,l]),(()=>c.getCurrentResult()),(()=>c.getCurrentResult())),I.useEffect((()=>{c.setOptions(o)}),[o,c]),((e,t)=>e?.suspense&&t.isPending)(o,u))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: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&&!$&&((e,t)=>e.isLoading&&e.isFetching&&!t)(u,r)){const e=a?_e(o,c,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(K).finally((()=>{c.updateResult()}))}return o.notifyOnChangeProps?u:c.trackResult(u)}function He(e,t){return ze(e,De)}const $e=({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 Ke=Object.prototype.hasOwnProperty;function Ne(e,t,n){for(n of e.keys())if(Ve(n,t))return n}function Ve(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--&&Ve(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=Ne(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=Ne(t,r)))return!1;if(!Ve(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(Ke.call(e,n)&&++i&&!Ke.call(t,n))return!1;if(!(n in t)||!Ve(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function Be(e,t){return I.useEffect(e,(n=t,i=I.useRef(n),r=I.useRef(0),Ve(n,i.current)||(i.current=n,r.current+=1),I.useMemo((function(){return i.current}),[r.current])));var n,i,r}function We(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const Ge=/^__secretvalue:\*\*redacted\*\*(.*)$/,Je=e=>(e=>"string"==typeof e)(e)&&Ge.test(e),Ye=e=>{const t="••••••••••";if(!Je(e))return e;const n=e.match(Ge);if(!n)return t;const i=n[1];return i?t+i:t};function Xe(e){let t=z.string();if(e.required&&(t=t.min(1,`${e.label} is required`)),"number"===e.type){if(!e.required)return z.string().refine((e=>""===e||/^\d+$/.test(e)),"Must be a valid number");t=t.regex(/^\d+$/,"Must be a valid number")}if(e.validation)if("html-pattern"===e.validation.type){const n=new RegExp(e.validation.pattern),i=e.validation.error||`Please match the required format: ${e.validation.pattern}`;if(!e.required)return z.string().refine((e=>""===e||n.test(e)),i);t=t.regex(n,i)}else if("domain"===e.validation.type){const n=new RegExp(`.*${e.validation.pattern}\\.com.*`),i=e.validation.error||`Please enter a valid ${e.validation.pattern}.com domain`;if(!e.required)return z.string().refine((e=>""===e||n.test(e)),i);t=t.regex(n,i)}return e.required?t:z.union([z.string().length(0),t])}const Ze=({field:i,errors:r,setValue:s,editingSecrets:o,setEditingSecrets:a})=>{var u,l,d,h,p,v,m,b,C,w,O,S,k,R,x,q,j,T,I,D,F,E,P;const Q="object"==typeof i.key?JSON.stringify(i.key):String(i.key),A=r[Q]&&e(c.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(u=r[Q])||void 0===u?void 0:u.message});if("text"===(L=i.type)||"number"===L||"password"===L){const c=i.readOnly,u=null===(l=i.value)||void 0===l?void 0:l.toString(),g="external-trigger-token"!==i.key&&(!1!==i.secret||"password"===i.type),y=c&&u&&!g,S=null!==(d=null==o?void 0:o.has(Q))&&void 0!==d&&d;if(g&&Je(u)&&!S)return t(n,{children:[e(f,{name:`${Q}-display`,label:i.label,placeholder:i.placeholder,type:"text",required:i.required,disabled:!0,readOnly:!0,defaultValue:u?Ye(u):"",description:null!==(p=null===(h=i.guide)||void 0===h?void 0:h.description)&&void 0!==p?p:i.description,tooltip:null!==(m=null===(v=i.guide)||void 0===v?void 0:v.tooltip)&&void 0!==m?m:i.tooltip,showCopyButton:!1,buttons:a?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{a((e=>new Set(e).add(Q))),s(Q,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),A]});const k=!g&&(i.readOnly||!1),R=g?void 0:y?()=>{}:void 0;return t(n,{children:[e(f,{name:Q,required:!!c||i.required,placeholder:i.placeholder,disabled:k,readOnly:i.readOnly,label:i.label,tooltip:null!==(C=null===(b=i.guide)||void 0===b?void 0:b.tooltip)&&void 0!==C?C:i.tooltip,description:null!==(O=null===(w=i.guide)||void 0===w?void 0:w.description)&&void 0!==O?O:i.description,type:i.type,error:!!r[Q],onChange:e=>s(Q,e,{shouldValidate:!0}),defaultValue:g&&S?"":u,showPasswordToggle:!1,onCopyClick:R},`${Q}-${S?"editing":"view"}`),A]})}var L;return"text_area"===i.type?t(n,{children:[e(g,{name:Q,required:i.required,placeholder:i.placeholder,disabled:i.readOnly,label:i.label,tooltip:null!==(k=null===(S=i.guide)||void 0===S?void 0:S.tooltip)&&void 0!==k?k:i.tooltip,description:null!==(x=null===(R=i.guide)||void 0===R?void 0:R.description)&&void 0!==x?x:i.description,error:!!r[Q],onChange:e=>s(Q,e,{shouldValidate:!0}),defaultValue:(null===(q=i.value)||void 0===q?void 0:q.toString())||""}),A]}):"select"===i.type?t(n,{children:[e(y,{defaultValue:(null===(j=i.value)||void 0===j?void 0:j.toString())||"",disabled:i.readOnly,items:null!==(I=null===(T=i.options)||void 0===T?void 0:T.map((e=>({id:e.value,label:e.label}))))&&void 0!==I?I:[],onItemSelected:e=>s(Q,null!=e?e:"",{shouldValidate:!0}),name:Q,label:i.label,placeholder:i.placeholder,tooltip:null!==(F=null===(D=i.guide)||void 0===D?void 0:D.tooltip)&&void 0!==F?F:i.tooltip,description:null!==(P=null===(E=i.guide)||void 0===E?void 0:E.description)&&void 0!==P?P:i.description,required:i.required,error:!!r[Q]}),A]}):null},et=({error:t})=>{if(!t)return null;try{return e(p,{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(p,{code:null==t?void 0:t.provider_response}):null}},tt=({integrationName:n,error:h,notices:p=[]})=>{var f;const g=p.filter((e=>!e.position||"top"===e.position));return t(u,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[h&&e(d,{type:"error",message:(null===(f=h.provider_response)||void 0===f?void 0:f.trim())||h.message,hasMargin:!1,children:e(et,{error:h})}),g.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."]})]})})]})},nt=({fields:n,notices:i=[],onChange:r,error:s,onValidationChange:o,integrationName:a,editingSecrets:c,setEditingSecrets:p})=>{const f=n.filter((e=>!1!==e.display)),g=f.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:y,noticesAfter:v}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>We(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!We(e)&&"bottom"===e.position&&t===i))}}(i,g),m=F((()=>function(e){const t={};for(const n of e)t[n.key]=Xe(n);return z.object(t)}(n)),[n]),b=F((()=>{const e={};return n.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[n]),{formState:C,watch:w,reset:O,setValue:S}=_({resolver:U(m),mode:"onTouched",defaultValues:b}),{errors:k,isValid:R}=C;Be((()=>{O(b)}),[b]);const x=w();return Be((()=>{r(x)}),[x]),E((()=>{null==o||o(R)}),[R,o]),0===f.length?e(tt,{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(et,{error:s})}),e(h,{children:f.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=y(i).length>0||v(i).length>0;return t("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[y(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(Ze,{field:n,errors:k,setValue:S,editingSecrets:c,setEditingSecrets:p}),v(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key)))]},i)}))})]})})},it=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,editingSecrets:a,setEditingSecrets:c})=>e(nt,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,editingSecrets:a,setEditingSecrets:c}),rt=[{label:"HRIS",value:"hris"},{label:"ATS",value:"ats"},{label:"CRM",value:"crm"},{label:"Marketing",value:"marketing"},{label:"IAM",value:"iam"},{label:"LMS",value:"lms"},{label:"Documents",value:"documents"},{label:"Ticketing",value:"ticketing"},{label:"Screening",value:"screening"},{label:"Messaging",value:"messaging"},{label:"Accounting",value:"accounting"},{label:"Scheduling",value:"scheduling"}],st=({src:t,alt:n,fallbackUrl:i="https://stackone-logos.com/api/stackone/filled/png",style:r,className:s})=>{const[o,a]=P(t);return e("img",{src:o,alt:n,style:r,className:s,onError:()=>{a(i)}})},ot=({integration:n})=>{var u,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(st,{src:n.logo_url,alt:n.provider,style:{width:"24px",height:"24px"}}),e(c.Text,{textAlign:"left",children:null!==(u=n.name)&&void 0!==u?u:"N/A"})]}),e(c.SecondaryText,{children:(null===(l=rt.find((e=>e.value===n.type)))||void 0===l?void 0:l.label)||n.type})]})},at=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=Q((e=>{s(r===e?null:e)}),[r,s]),c=F((()=>Array.from(new Set(i.map((e=>e.type))))),[i]);return t(n,{children:[e(f,{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=>{var n;return e(u,{vertical:"none",horizontal:"small",fullHeight:!1,children:e(m,{label:(null===(n=rt.find((e=>e.value===t)))||void 0===n?void 0:n.label)||t,selected:r===t,onClick:()=>a(t)})},t)}))})})})]})]})},ct=({integrations:t,onSelect:r,selectedCategory:s,search:d})=>{const h=F((()=>t.filter((e=>e.active&&e.name&&(!s||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(ot,{integration:t}),onClick:()=>r(t)})))})})}):e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.SecondaryText,{children:"No integrations found"})})})},ut=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e(ct,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e("div",{children:"No integrations found."}),lt=({title:n,description:u,onCancel:l})=>{const[d,h]=P(!1),p=A(null);return E((()=>{if(l)return p.current=setTimeout((()=>h(!0)),5e3),()=>{p.current&&clearTimeout(p.current)}}),[l]),t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(C,{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"})]})]})},dt=({title:t,description:n,onCancel:i})=>e(lt,{title:t,description:n,onCancel:i}),ht=({integrationName:n})=>{const u=w();return t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(O.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]})]})},pt=({integrationName:t})=>e(ht,{integrationName:t}),ft=({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:p,onChange:f,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,C;return t?e(dt,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e(dt,{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($e,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e(pt,{integrationName:null!==(C=null==s?void 0:s.name)&&void 0!==C?C:r.name}):r?s?e(it,{fields:a,notices:c,error:i.error,onChange:f,onValidationChange:g,integrationName:s.name,editingSecrets:v,setEditingSecrets:m}):null:(null==o?void 0:o.integrations.length)?e(ut,{integrations:o.integrations,onSelect:p,selectedCategory:u,search:l}):e($e,{message:"No configured integrations available."})},gt=({connectorData:n,onBack:u,guide:l})=>{var d;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(S,{variant:"ghost",onClick:u,icon:"←",size:"small"}),e(st,{src:null===(d=n.assets)||void 0===d?void 0:d.icon,alt:n.key,style:{width:"16px",height:"16px"}}),e(c.Text,{fontWeight:"semi-bold",size:"medium",children:n.name})]}),(null==l?void 0:l.supportLink)?e(c.LinkText,{href:l.supportLink,target:"_blank",children:e(S,{variant:"outline",size:"small",children:"Connection guide"})}):null]})},yt=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:c,onCategoryChange:u,onSearchChange:l,hideBackButton:d})=>{if(t)return e(gt,{connectorData:t,onBack:n||d?void 0:i,guide:r});return!s&&!o&&(null==a?void 0:a.integrations)?e(at,{integrations:a.integrations,selectedCategory:c,onCategoryChange:u,onSearchChange:l}):null},vt=({fullWidth:n=!0,selectedIntegration:r,showActions:o,onBack:c,onNext:d,isFormValid:h=!0,isLoading:p=!1,showFooterLinks:f=!0})=>{const g=F((()=>{if(!r||!o)return[];const e=[];return c&&e.push({label:"Back",type:"outline",onClick:c,disabled:p,loading:!1}),e.push({label:"Connect",type:"filled",onClick:d,disabled:!h||p,loading:p}),e}),[r,c,d,o,h,p]);return 0===g.length?f?e(k,{fullWidth:n}):null:t(l,{direction:"horizontal",size:4,justifyContent:"space-between",children:[f&&e(k,{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(S,{size:"small",variant:t.type,onClick:t.onClick,disabled:t.disabled,loading:t.loading,iconPosition:"end",children:t.label},t.label)))})})})]})},mt=({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(k,{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(S,{size:"small",variant:"filled",onClick:r,children:null!=o?o:"Close"})})})})]}):null};function bt(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 Ct="x-hub-version",wt=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==Ct.toLowerCase()&&(t[n]=i);return t[Ct]="1.11.2",t};function Ot(e){return bt(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:wt(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 St(e){return bt(this,void 0,void 0,(function*(){return Ot(Object.assign(Object.assign({},e),{method:"POST"}))}))}function kt(e){return bt(this,void 0,void 0,(function*(){return Ot(Object.assign(Object.assign({},e),{method:"GET"}))}))}const Rt=(e,t,n)=>bt(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 kt({url:r,headers:i})})),xt=(e,t,n)=>bt(void 0,void 0,void 0,(function*(){return yield kt({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),qt=e=>bt(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return bt(this,void 0,void 0,(function*(){return Ot(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}})})),jt=(e,t,n)=>bt(void 0,void 0,void 0,(function*(){return yield kt({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Tt=(e,t,n)=>bt(void 0,void 0,void 0,(function*(){return yield function(e){return bt(this,void 0,void 0,(function*(){return Ot(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),It={retry:(e,t)=>{if(t&&"object"==typeof t&&"message"in t)try{const e=JSON.parse(t.message);if(401===e.status||403===e.status)return!1}catch(e){}return e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)};var Dt;!function(e){e.AccountConnected="AccountConnected"}(Dt||(Dt={}));const Ft=({token:e,baseUrl:t,accountId:n,onSuccess:i,dashboardUrl:r,debug:s})=>{const[o,a]=P(null),[c,u]=P({}),[l,d]=P(new Set),h=Q((e=>{u(e)}),[]),p=A(null),f=A(null),g=A(null),y=A(null),v=A(!1),[m,b]=P({loading:!1,success:!1}),C=Q((()=>{null!==g.current&&(clearTimeout(g.current),g.current=null),f.current=null}),[]),w=Q((e=>{b({loading:!1,success:!0}),null==i||i(e)}),[i]),O=A(s);O.current=s;const S=Q((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null)}),[]),k=Q((()=>{C(),S(),p.current&&(p.current.close(),p.current=null)}),[C,S]);E((()=>()=>{C(),S()}),[C,S]);const{data:R,isLoading:x,error:q}=He(Object.assign({queryKey:["accountData",n],queryFn:()=>bt(void 0,void 0,void 0,(function*(){return n?((e,t,n)=>bt(void 0,void 0,void 0,(function*(){return yield kt({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,n):null})),enabled:!!n},It)),{data:j,isLoading:T,error:I}=He(Object.assign({queryKey:["hubData",null==R?void 0:R.provider],queryFn:()=>(null==R?void 0:R.provider)?Rt(e,t,R.provider):Rt(e,t),enabled:!n||!!R},It));E((()=>{if(R&&j){const e=j.integrations.find((e=>e.provider===R.provider));a(null!=e?e:null)}}),[R,j]),E((()=>{if(j&&!o){const e=j.integrations.filter((e=>e.active));1===e.length&&a(e[0])}}),[j,o]);const{data:D,isLoading:L,error:M}=He(Object.assign({queryKey:["connectorData",null==R?void 0:R.integrationId,null==o?void 0:o.integration_id],queryFn:()=>bt(void 0,void 0,void 0,(function*(){return R?xt(t,e,R.integrationId):o?xt(t,e,o.integration_id):null})),enabled:Boolean(o)||Boolean(R)},It)),{fields:U,guide:_,notices:z}=F((()=>{var e,t,n,i,r,s,a,c,u;if(!D||!o){return{fields:[],notices:[]}}if(("configFields"in(u=D.config)||"configNotices"in u)&&!("authentication"in u)){const s=(null!==(e=D.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==R?void 0:R.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==j?void 0:j.external_trigger_token});if(R&&(!1!==e.secret||"password"===e.type)){const t=null===(n=R.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=D.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=D.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=D.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let l=o.authentication_config_key,d=o.environment;R&&R.authConfigKey&&(null===(s=D.config.authentication)||void 0===s?void 0:s[R.authConfigKey])&&(l=R.authConfigKey,d=null!==(a=R.environment)&&void 0!==a?a:o.environment);const h=null===(c=D.config.authentication)||void 0===c?void 0:c[l],p=null==h?void 0:h[d],f=((null==p?void 0:p.fields)||[]).map((e=>{var t,n;const i=null===(t=null==R?void 0:R.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==j?void 0:j.external_trigger_token});if(R&&(!1!==e.secret||"password"===e.type)){const t=null===(n=R.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:f,notices:[],guide:null==p?void 0:p.guide}}),[D,o,R,j]),H=F((()=>{var e,t,n,i,r;if(!D||!o)return null;if("authentication"in(r=D.config)&&!("configFields"in r)){let r=o.authentication_config_key,s=o.environment;return R&&R.authConfigKey&&(null===(e=D.config.authentication)||void 0===e?void 0:e[R.authConfigKey])&&(r=R.authConfigKey,s=null!==(t=R.environment)&&void 0!==t?t:o.environment),null===(i=null===(n=D.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return D.config}),[D,o,R]),[$,K]=P(!0),N=Q(((n,i)=>{const r=Date.now(),s=()=>bt(void 0,void 0,void 0,(function*(){var o,a,c,u;if(!g.current)return;if(Date.now()-r>3e5)return O.current&&console.debug("[hub] poll timed out",{attemptId:n}),k(),Tt(t,e,n).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void b({loading:!1,success:!1,timedOut:!0});const l=yield jt(t,e,n).catch((()=>null));if(g.current){if(!l)return O.current&&console.debug("[hub] poll failed (network error), retrying"),void(g.current=window.setTimeout(s,2e3));O.current&&"pending"!==l.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},l)),"authenticated"===l.status&&l.account?(k(),w({id:l.account.id,provider:i}),parent.postMessage({type:Dt.AccountConnected,account:{id:l.account.id,provider:i}},"*")):"error"===l.status?(k(),b({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?(k(),b({loading:!1,success:!1})):g.current=window.setTimeout(s,2e3)}}));g.current=window.setTimeout(s,2e3)}),[t,e,k,w]),V=Q((n=>{let i=!0;const r=()=>bt(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!p.current||p.current.closed))return O.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),v.current=!0,void(y.current=null);if(p.current&&!p.current.closed)return void(y.current=window.setTimeout(r,1e3));if(y.current=null,!g.current)return;if(v.current)return;const s=f.current;if(!s)return;const o=yield jt(t,e,s).catch((e=>(O.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return g.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(O.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),k(),w({id:o.account.id,provider:n}),void parent.postMessage({type:Dt.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(O.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}));y.current=window.setTimeout(r,1e3)}),[t,e,k,w]),B=Q((()=>bt(void 0,void 0,void 0,(function*(){var i;if(o)if($){b({loading:!0,success:!1});try{const s=Object.assign({},c);R&&U.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=s[e.key];Je(t)&&!l.has(e.key)&&delete s[e.key]}})),Object.keys(s).forEach((e=>{""===s[e]&&delete s[e]}));const a="oauth2"===(null==H?void 0:H.type)&&(!("grantType"in H)||"authorization_code"===H.grantType);if(O.current&&console.debug("[hub] handleConnect",{integration:o.integration_id,path:a?"oauth-redirect":"credential-form",updating:!!n}),a){const n=yield((e,t)=>bt(void 0,void 0,void 0,(function*(){return yield St({url:`${e}/hub/connection_attempts`,headers:{"Content-Type":"application/json","x-hub-session-token":t},body:{token:t}})})))(t,e).catch((()=>null)),a=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(f.current=a,!a)return O.current&&console.debug("[hub] connection attempt creation failed"),void b({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});O.current&&console.debug("[hub] connection attempt created",{attemptId:a});const c=encodeURIComponent(`${r}/embedded/accounts/callback`);let u=`${t}/connect/oauth2/${o.integration_id}?redirect_uri=${c}&token=${e}&connection_attempt_id=${a}`;Object.keys(s).forEach((e=>{u+=`&${e}=${encodeURIComponent(s[e])}`}));const l=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,g=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,m=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,C=parseInt((h+(y-l)/2).toString(),10),w=`width=${l},height=${d},left=${C},top=${parseInt((g+(m-d)/2.5).toString(),10)},noopener=0`;return p.current=window.open(u,"Connect Account",w),p.current?(v.current=!1,"function"==typeof p.current.focus&&p.current.focus(),N(a,o.provider),void V(o.provider)):(O.current&&console.debug("[hub] popup was blocked by browser"),k(),Tt(t,e,a).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:a,error:e})})),void b({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 u;if(n)yield qt({baseUrl:t,accountId:n,token:e,integrationId:o.integration_id,credentials:s}),u={id:n,provider:o.provider};else{const n=yield(e=>bt(void 0,[e],void 0,(function*({baseUrl:e,token:t,credentials:n,integrationId:i}){return yield St({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:o.integration_id});if(!n)throw new Error("Failed to create account");u={id:n.id,provider:o.provider}}w(u)}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}b({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else b({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,r,e,o,c,l,w,R,U,n,H,k,N,V,$]),W=Q((()=>{const n=f.current;O.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),k(),b({loading:!1,success:!1}),n&&Tt(t,e,n).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,k]),G=T||L||x,J=!!(I||M||q);E((()=>{d(new Set)}),[o]),E((()=>{J&&m.loading&&b((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[J,m.loading]);const Y=A(m.loading);E((()=>{s&&Y.current&&!m.loading&&console.debug("[hub] connectionState.loading → false",m),Y.current=m.loading}),[s,m]);const X=Q((()=>{b({loading:!1,success:!1}),d(new Set)}),[]),Z=Q((()=>{b({loading:!1,success:!1}),d(new Set)}),[]);return{hubData:j,accountData:R,connectorData:D,selectedIntegration:o,fields:U,notices:z,guide:_,formData:c,connectionState:m,isLoading:G,hasError:J,isFormValid:$,errorHubData:I,errorConnectorData:M,errorAccountData:q,setSelectedIntegration:a,setFormData:h,setIsFormValid:K,handleConnect:B,handleCancelOAuth:W,resetConnectionState:X,resetAllErrors:Z,editingSecrets:l,setEditingSecrets:d}},Et=({token:n,baseUrl:i,height:r,accountId:s,onSuccess:o,onClose:a,dashboardUrl:c,showFooterLinks:u=!0,onCloseLabel:l,debug:h})=>{var p,f,g,y;const[v,m]=P(null),[b,C]=P(""),{hubData:w,accountData:O,connectorData:S,selectedIntegration:k,fields:x,notices:q,guide:j,connectionState:T,isLoading:I,hasError:D,isFormValid:E,errorHubData:A,errorConnectorData:L,setSelectedIntegration:M,setFormData:U,setIsFormValid:_,handleConnect:z,handleCancelOAuth:H,resetConnectionState:$,editingSecrets:K,setEditingSecrets:N}=Ft({token:n,baseUrl:i,accountId:s,onSuccess:o,dashboardUrl:c,debug:h}),V=Q((e=>{_(e)}),[_]),B=F((()=>{if(!w)return!1;return 1===w.integrations.filter((e=>e.active)).length}),[w]),W=()=>{M(null),$(),m(null),C("")};return t(R,{glassFooter:!0,footer:T.success?e(mt,{onClose:a,showFooterLinks:u,onCloseLabel:l}):e(vt,{selectedIntegration:k,showActions:!T.loading&&!T.success,onBack:O||B?void 0:W,onNext:z,isFormValid:E,isLoading:I,showFooterLinks:u}),title:I||T.loading||T.success?null:e(yt,{accountData:O,onBack:W,guide:j,isLoading:I,hasError:D,hubData:w,selectedCategory:v,onCategoryChange:m,onSearchChange:C,hideBackButton:T.loading||T.success||B,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null}),height:r,padding:"0",headerConfig:k?void 0:{padding:"0"},children:[T.timedOut&&e(d,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e(ft,{isLoading:I,hasError:D,connectionState:T,selectedIntegration:k,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,hubData:null!=w?w:null,fields:x,notices:q,errorHubData:null!==(g=A)&&void 0!==g?g:null,errorConnectorData:null!==(y=L)&&void 0!==y?y:null,onSelect:M,onChange:U,onValidationChange:V,onCancelOAuth:H,selectedCategory:v,search:b,editingSecrets:K,setEditingSecrets:N})]})},Pt=L({featureFlags:[]}),Qt=({featureFlags:t,children:n})=>{const i=F((()=>({featureFlags:t})),[t]);return e(Pt.Provider,{value:i,children:n})},At=M((({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:p}=He({queryKey:["settings"],queryFn:()=>((e,t)=>bt(void 0,void 0,void 0,(function*(){return yield kt({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e(Qt,{featureFlags:null!==(h=null==p?void 0:p.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e(Et,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:l,accountId:null!=c?c:null==p?void 0:p.existing_account_id,showFooterLinks:u,debug:d})})})),Lt=()=>t(i,{justify:a.Center,align:o.Center,direction:s.Vertical,gapSize:r.Small,fullHeight:!0,children:[e(O.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 Mt 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 Ut=({mode:t,token:n,baseUrl:r,appUrl:s,height:u="500px",theme:l="light",accountId:d,onSuccess:h,onClose:p,onCloseLabel:f,showFooterLinks:g,debug:y})=>{const v=null!=r?r:"https://api.stackone.com",m=null!=s?s:"https://app.stackone.com";E((()=>{"dark"===l?x():"light"===l?q():j(l)}),[l]);const[b]=P((()=>new Ie({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),C=A(n);return E((()=>{C.current!==n&&(C.current=n,b.clear())}),[n,b]),e(T,n?{children:e(Mt,{fallback:e(R,{height:u,children:e(Lt,{})}),children:e(Le,{client:b,children:e(At,{mode:null!=t?t:"integration-picker",token:n,apiUrl:v,dashboardUrl:m,height:u,onSuccess:h,accountId:d,onClose:p,onCloseLabel:f,showFooterLinks:g,debug:y})})})}:{children:e(Mt,{fallback:e(R,{height:u,children:e(Lt,{})}),children:e(R,{height:u,footer:e(k,{}),children:e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.PageTitle,{children:"No token provided"})})})})})};export{Ut 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 p,Input as f,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,Button as k,FooterLinks as x,Card as R,applyDarkTheme as q,applyLightTheme as j,applyTheme as F,MalachiteContext as T}from"@stackone/malachite";import*as D from"react";import I,{useMemo as E,useEffect as P,useState as Q,useCallback as A,useRef as L,createContext as U,memo as M}from"react";import{zodResolver as z}from"@hookform/resolvers/zod";import{useForm as _}from"react-hook-form";import{z as H}from"zod";var $=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(){}},K="undefined"==typeof window||"Deno"in globalThis;function N(){}function V(e){return"number"==typeof e&&e>=0&&e!==1/0}function B(e,t){return Math.max(e+(t||0)-Date.now(),0)}function W(e,t){return"function"==typeof e?e(t):e}function G(e,t){return"function"==typeof e?e(t):e}function J(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:s,queryKey:o,stale:a}=e;if(o)if(i){if(t.queryHash!==X(o,t.options))return!1}else if(!ee(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 Y(e,t){const{exact:n,status:i,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(Z(t.options.mutationKey)!==Z(s))return!1}else if(!ee(t.options.mutationKey,s))return!1}return(!i||t.state.status===i)&&!(r&&!r(t))}function X(e,t){return(t?.queryKeyHashFn||Z)(e)}function Z(e){return JSON.stringify(e,((e,t)=>re(t)?Object.keys(t).sort().reduce(((e,n)=>(e[n]=t[n],e)),{}):t))}function ee(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&Object.keys(t).every((n=>ee(e[n],t[n]))))}function te(e,t){if(e===t)return e;const n=ie(e)&&ie(t);if(n||re(e)&&re(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]=te(e[o],t[o]),a[o]===e[o]&&void 0!==e[o]&&c++)}return r===o&&c===r?e:a}return t}function ne(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 ie(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function re(e){if(!se(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!!se(n)&&(!!n.hasOwnProperty("isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)}function se(e){return"[object Object]"===Object.prototype.toString.call(e)}function oe(e,t,n){return"function"==typeof n.structuralSharing?n.structuralSharing(e,t):!1!==n.structuralSharing?te(e,t):t}function ae(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function ce(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var ue=Symbol();function le(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 de=new class extends ${#e;#t;#n;constructor(){super(),this.#n=e=>{if(!K&&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}},he=new class extends ${#i=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!K&&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 fe(e){return Math.min(1e3*2**e,3e4)}function ge(e){return"online"!==(e??"online")||he.isOnline()}var ye=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ve(e){return e instanceof ye}function me(e){let t,n=!1,i=0,r=!1;const s=pe(),o=()=>de.isFocused()&&("always"===e.networkMode||he.isOnline())&&e.canRun(),a=()=>ge(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??(K?0:3),a=e.retryDelay??fe,c="function"==typeof a?a(i,t):a,h=!0===s||"number"==typeof s&&i<s||"function"==typeof s&&s(i,t);var p;!n&&h?(i++,e.onFail?.(i,t),(p=c,new Promise((e=>{setTimeout(e,p)}))).then((()=>o()?void 0:l())).then((()=>{n?u(t):d()}))):u(t)}))};return{promise:s,cancel:t=>{r||(u(new ye(t)),e.abort?.())},continue:()=>(t?.(),s),cancelRetry:()=>{n=!0},continueRetry:()=>{n=!1},canStart:a,start:()=>(a()?d():l().then(d),s)}}var be=e=>setTimeout(e,0);var Ce=function(){let e=[],t=0,n=e=>{e()},i=e=>{e()},r=be;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}}}(),we=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),V(this.gcTime)&&(this.#r=setTimeout((()=>{this.optionalRemove()}),this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(K?1/0:3e5))}clearGcTimeout(){this.#r&&(clearTimeout(this.#r),this.#r=void 0)}},Oe=class extends we{#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=oe(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(N).catch(N):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#s)}isActive(){return this.observers.some((e=>!1!==G(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||!B(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=le(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=>{ve(e)&&e.silent||this.#h({type:"error",error:e}),ve(e)||(this.#a.config.onError?.(e,this),this.#a.config.onSettled?.(this.state.data,e,this)),this.scheduleGc()};return this.#u=me({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,...Se(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 ve(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),Ce.batch((()=>{this.observers.forEach((e=>{e.onQueryUpdate()})),this.#a.notify({query:this,type:"updated",action:e})}))}};function Se(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ge(t.networkMode)?"fetching":"paused",...void 0===e&&{error:null,status:"pending"}}}var ke=class extends ${constructor(e={}){super(),this.config=e,this.#p=new Map}#p;build(e,t,n){const i=t.queryKey,r=t.queryHash??X(i,t);let s=this.get(r);return s||(s=new Oe({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(s)),s}add(e){this.#p.has(e.queryHash)||(this.#p.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#p.get(e.queryHash);t&&(e.destroy(),t===e&&this.#p.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ce.batch((()=>{this.getAll().forEach((e=>{this.remove(e)}))}))}get(e){return this.#p.get(e)}getAll(){return[...this.#p.values()]}find(e){const t={exact:!0,...e};return this.getAll().find((e=>J(t,e)))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter((t=>J(e,t))):t}notify(e){Ce.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}onFocus(){Ce.batch((()=>{this.getAll().forEach((e=>{e.onFocus()}))}))}onOnline(){Ce.batch((()=>{this.getAll().forEach((e=>{e.onOnline()}))}))}},xe=class extends we{#f;#g;#u;constructor(e){super(),this.mutationId=e.mutationId,this.#g=e.mutationCache,this.#f=[],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.#f.includes(e)||(this.#f.push(e),this.clearGcTimeout(),this.#g.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#f=this.#f.filter((t=>t!==e)),this.scheduleGc(),this.#g.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#f.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=me({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),Ce.batch((()=>{this.#f.forEach((t=>{t.onMutationUpdate(e)})),this.#g.notify({mutation:this,type:"updated",action:e})}))}};var Re=class extends ${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 xe({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(){Ce.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=>Y(t,e)))}findAll(e={}){return this.getAll().filter((t=>Y(e,t)))}notify(e){Ce.batch((()=>{this.listeners.forEach((t=>{t(e)}))}))}resumePausedMutations(){const e=this.getAll().filter((e=>e.state.isPaused));return Ce.batch((()=>Promise.all(e.map((e=>e.continue().catch(N))))))}};function qe(e){return e.options.scope?.id}function je(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=le(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?ce:ae;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?Te:Fe)(i,t);a=await l(t,n,e)}else{const t=e??s.length;do{const e=0===c?o[0]??i.initialPageParam:Fe(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 Fe(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 De=class{#b;#g;#l;#C;#w;#O;#S;#k;constructor(e={}){this.#b=e.queryCache||new ke,this.#g=e.mutationCache||new Re,this.#l=e.defaultOptions||{},this.#C=new Map,this.#w=new Map,this.#O=0}mount(){this.#O++,1===this.#O&&(this.#S=de.subscribe((async e=>{e&&(await this.resumePausedMutations(),this.#b.onFocus())})),this.#k=he.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(W(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 Ce.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;Ce.batch((()=>{t.findAll(e).forEach((e=>{t.remove(e)}))}))}resetQueries(e,t){const n=this.#b;return Ce.batch((()=>(n.findAll(e).forEach((e=>{e.reset()})),this.refetchQueries({type:"active",...e},t))))}cancelQueries(e,t={}){const n={revert:!0,...t},i=Ce.batch((()=>this.#b.findAll(e).map((e=>e.cancel(n)))));return Promise.all(i).then(N).catch(N)}invalidateQueries(e,t={}){return Ce.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=Ce.batch((()=>this.#b.findAll(e).filter((e=>!e.isDisabled())).map((e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(N)),"paused"===e.state.fetchStatus?Promise.resolve():t}))));return Promise.all(i).then(N)}fetchQuery(e){const t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);const n=this.#b.build(this,t);return n.isStaleByTime(W(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(N).catch(N)}fetchInfiniteQuery(e){return e.behavior=je(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(N).catch(N)}ensureInfiniteQueryData(e){return e.behavior=je(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return he.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(Z(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#C.values()],n={};return t.forEach((t=>{ee(e,t.queryKey)&&Object.assign(n,t.defaultOptions)})),n}setMutationDefaults(e,t){this.#w.set(Z(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#w.values()],n={};return t.forEach((t=>{ee(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=X(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.#l.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#b.clear(),this.#g.clear()}},Ie=class extends ${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;#q=void 0;#j=void 0;#F=void 0;#T;#D;#R;#x;#I;#E;#P;#Q;#A;#L;#U=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#q.addObserver(this),Ee(this.#q,this.options)?this.#M():this.updateResult(),this.#z())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Pe(this.#q,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Pe(this.#q,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#H(),this.#q.removeObserver(this)}setOptions(e){const t=this.options,n=this.#q;if(this.options=this.#c.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof G(this.options.enabled,this.#q))throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#$(),this.#q.setOptions(this.options),t._defaulted&&!ne(this.options,t)&&this.#c.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#q,observer:this});const i=this.hasListeners();i&&Qe(this.#q,n,this.options,t)&&this.#M(),this.updateResult(),!i||this.#q===n&&G(this.options.enabled,this.#q)===G(t.enabled,this.#q)&&W(this.options.staleTime,this.#q)===W(t.staleTime,this.#q)||this.#K();const r=this.#N();!i||this.#q===n&&G(this.options.enabled,this.#q)===G(t.enabled,this.#q)&&r===this.#L||this.#V(r)}getOptimisticResult(e){const t=this.#c.getQueryCache().build(this.#c,e),n=this.createResult(t,e);return function(e,t){if(!ne(e.getCurrentResult(),t))return!0;return!1}(this,n)&&(this.#F=n,this.#D=this.options,this.#T=this.#q.state),n}getCurrentResult(){return this.#F}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#U.add(e)}getCurrentQuery(){return this.#q}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.#F)))}#M(e){this.#$();let t=this.#q.fetch(this.options,e);return e?.throwOnError||(t=t.catch(N)),t}#K(){this.#_();const e=W(this.options.staleTime,this.#q);if(K||this.#F.isStale||!V(e))return;const t=B(this.#F.dataUpdatedAt,e)+1;this.#Q=setTimeout((()=>{this.#F.isStale||this.updateResult()}),t)}#N(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#q):this.options.refetchInterval)??!1}#V(e){this.#H(),this.#L=e,!K&&!1!==G(this.options.enabled,this.#q)&&V(this.#L)&&0!==this.#L&&(this.#A=setInterval((()=>{(this.options.refetchIntervalInBackground||de.isFocused())&&this.#M()}),this.#L))}#z(){this.#K(),this.#V(this.#N())}#_(){this.#Q&&(clearTimeout(this.#Q),this.#Q=void 0)}#H(){this.#A&&(clearInterval(this.#A),this.#A=void 0)}createResult(e,t){const n=this.#q,i=this.options,r=this.#F,s=this.#T,o=this.#D,a=e!==n?e.state:this.#j,{state:c}=e;let u,l={...c},d=!1;if(t._optimisticResults){const r=this.hasListeners(),s=!r&&Ee(e,t),o=r&&Qe(e,n,t,i);(s||o)&&(l={...l,...Se(c.data,e.options)}),"isRestoring"===t._optimisticResults&&(l.fetchStatus="idle")}let{error:h,errorUpdatedAt:p,status:f}=l;u=l.data;let g=!1;if(void 0!==t.placeholderData&&void 0===u&&"pending"===f){let e;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=r.data,g=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#P?.state.data,this.#P):t.placeholderData,void 0!==e&&(f="success",u=oe(r?.data,e,t),d=!0)}if(t.select&&void 0!==u&&!g)if(r&&u===s?.data&&t.select===this.#I)u=this.#E;else try{this.#I=t.select,u=t.select(u),u=oe(r?.data,u,t),this.#E=u,this.#x=null}catch(e){this.#x=e}this.#x&&(h=this.#x,u=this.#E,p=Date.now(),f="error");const y="fetching"===l.fetchStatus,v="pending"===f,m="error"===f,b=v&&y,C=void 0!==u,w={status:f,fetchStatus:l.fetchStatus,isPending:v,isSuccess:"success"===f,isError:m,isInitialLoading:b,isLoading:b,data:u,dataUpdatedAt:l.dataUpdatedAt,error:h,errorUpdatedAt:p,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:Ae(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.#F,t=this.createResult(this.#q,this.options);if(this.#T=this.#q.state,this.#D=this.options,void 0!==this.#T.data&&(this.#P=this.#q),ne(t,e))return;this.#F=t;this.#B({listeners:(()=>{if(!e)return!0;const{notifyOnChangeProps:t}=this.options,n="function"==typeof t?t():t;if("all"===n||!n&&!this.#U.size)return!0;const i=new Set(n??this.#U);return this.options.throwOnError&&i.add("error"),Object.keys(this.#F).some((t=>{const n=t;return this.#F[n]!==e[n]&&i.has(n)}))})()})}#$(){const e=this.#c.getQueryCache().build(this.#c,this.options);if(e===this.#q)return;const t=this.#q;this.#q=e,this.#j=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#z()}#B(e){Ce.batch((()=>{e.listeners&&this.listeners.forEach((e=>{e(this.#F)})),this.#c.getQueryCache().notify({query:this.#q,type:"observerResultsUpdated"})}))}};function Ee(e,t){return function(e,t){return!1!==G(t.enabled,e)&&void 0===e.state.data&&!("error"===e.state.status&&!1===t.retryOnMount)}(e,t)||void 0!==e.state.data&&Pe(e,t,t.refetchOnMount)}function Pe(e,t,n){if(!1!==G(t.enabled,e)){const i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&Ae(e,t)}return!1}function Qe(e,t,n,i){return(e!==t||!1===G(i.enabled,e))&&(!n.suspense||"error"!==e.state.status)&&Ae(e,n)}function Ae(e,t){return!1!==G(t.enabled,e)&&e.isStaleByTime(W(t.staleTime,e))}var Le=D.createContext(void 0),Ue=({client:t,children:n})=>(D.useEffect((()=>(t.mount(),()=>{t.unmount()})),[t]),e(Le.Provider,{value:t,children:n})),Me=D.createContext(!1);Me.Provider;var ze=D.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=D.useContext(Le);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e})(),r=D.useContext(Me),s=D.useContext(ze),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(Ce.batchCalls(e)):N;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 _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: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&&!K&&((e,t)=>e.isLoading&&e.isFetching&&!t)(u,r)){const e=a?_e(o,c,s):i.getQueryCache().get(o.queryHash)?.promise;e?.catch(N).finally((()=>{c.updateResult()}))}return o.notifyOnChangeProps?u:c.trackResult(u)}function $e(e,t){return He(e,Ie)}const Ke=({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 Ne=Object.prototype.hasOwnProperty;function Ve(e,t,n){for(n of e.keys())if(Be(n,t))return n}function Be(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--&&Be(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=Ve(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=Ve(t,r)))return!1;if(!Be(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(Ne.call(e,n)&&++i&&!Ne.call(t,n))return!1;if(!(n in t)||!Be(e[n],t[n]))return!1}return Object.keys(t).length===i}}return e!=e&&t!=t}function We(e,t){return D.useEffect(e,(n=t,i=D.useRef(n),r=D.useRef(0),Be(n,i.current)||(i.current=n,r.current+=1),D.useMemo((function(){return i.current}),[r.current])));var n,i,r}function Ge(e){return"anchor"in e&&"string"==typeof e.anchor&&e.anchor.trim().length>0}const Je=/^__secretvalue:\*\*redacted\*\*(.*)$/,Ye=e=>(e=>"string"==typeof e)(e)&&Je.test(e),Xe=e=>{const t="••••••••••";if(!Ye(e))return e;const n=e.match(Je);if(!n)return t;const i=n[1];return i?t+i:t};function Ze(e){let t=H.string();if(e.required&&(t=t.min(1,`${e.label} is required`)),"number"===e.type){if(!e.required)return H.string().refine((e=>""===e||/^\d+$/.test(e)),"Must be a valid number");t=t.regex(/^\d+$/,"Must be a valid number")}if(e.validation)if("html-pattern"===e.validation.type){const n=new RegExp(e.validation.pattern),i=e.validation.error||`Please match the required format: ${e.validation.pattern}`;if(!e.required)return H.string().refine((e=>""===e||n.test(e)),i);t=t.regex(n,i)}else if("domain"===e.validation.type){const n=new RegExp(`.*${e.validation.pattern}\\.com.*`),i=e.validation.error||`Please enter a valid ${e.validation.pattern}.com domain`;if(!e.required)return H.string().refine((e=>""===e||n.test(e)),i);t=t.regex(n,i)}return e.required?t:H.union([H.string().length(0),t])}const et=({field:i,errors:r,setValue:s,editingSecrets:o,setEditingSecrets:a})=>{var u,l,d,h,p,v,m,b,C,w,O,S,k,x,R,q,j,F,T,D,I,E,P;const Q="object"==typeof i.key?JSON.stringify(i.key):String(i.key),A=r[Q]&&e(c.Text,{color:"error",style:{marginTop:"4px",fontSize:"12px"},children:null===(u=r[Q])||void 0===u?void 0:u.message});if("text"===(L=i.type)||"number"===L||"password"===L){const c=i.readOnly,u=null===(l=i.value)||void 0===l?void 0:l.toString(),g="external-trigger-token"!==i.key&&(!1!==i.secret||"password"===i.type),y=c&&u&&!g,S=null!==(d=null==o?void 0:o.has(Q))&&void 0!==d&&d;if(g&&Ye(u)&&!S)return t(n,{children:[e(f,{name:`${Q}-display`,label:i.label,placeholder:i.placeholder,type:"text",required:i.required,disabled:!0,readOnly:!0,defaultValue:u?Xe(u):"",description:null!==(p=null===(h=i.guide)||void 0===h?void 0:h.description)&&void 0!==p?p:i.description,tooltip:null!==(m=null===(v=i.guide)||void 0===v?void 0:v.tooltip)&&void 0!==m?m:i.tooltip,showCopyButton:!1,buttons:a?[{label:"Edit",variant:"filled",size:"xsmall",onClick:()=>{a((e=>new Set(e).add(Q))),s(Q,"",{shouldValidate:!0,shouldDirty:!0})}}]:void 0}),A]});const k=!g&&(i.readOnly||!1),x=g?void 0:y?()=>{}:void 0;return t(n,{children:[e(f,{name:Q,required:!!c||i.required,placeholder:i.placeholder,disabled:k,readOnly:i.readOnly,label:i.label,tooltip:null!==(C=null===(b=i.guide)||void 0===b?void 0:b.tooltip)&&void 0!==C?C:i.tooltip,description:null!==(O=null===(w=i.guide)||void 0===w?void 0:w.description)&&void 0!==O?O:i.description,type:i.type,error:!!r[Q],onChange:e=>s(Q,e,{shouldValidate:!0}),defaultValue:g&&S?"":u,showPasswordToggle:!1,onCopyClick:x},`${Q}-${S?"editing":"view"}`),A]})}var L;return"text_area"===i.type?t(n,{children:[e(g,{name:Q,required:i.required,placeholder:i.placeholder,disabled:i.readOnly,label:i.label,tooltip:null!==(k=null===(S=i.guide)||void 0===S?void 0:S.tooltip)&&void 0!==k?k:i.tooltip,description:null!==(R=null===(x=i.guide)||void 0===x?void 0:x.description)&&void 0!==R?R:i.description,error:!!r[Q],onChange:e=>s(Q,e,{shouldValidate:!0}),defaultValue:(null===(q=i.value)||void 0===q?void 0:q.toString())||""}),A]}):"select"===i.type?t(n,{children:[e(y,{defaultValue:(null===(j=i.value)||void 0===j?void 0:j.toString())||"",disabled:i.readOnly,items:null!==(T=null===(F=i.options)||void 0===F?void 0:F.map((e=>({id:e.value,label:e.label}))))&&void 0!==T?T:[],onItemSelected:e=>s(Q,null!=e?e:"",{shouldValidate:!0}),name:Q,label:i.label,placeholder:i.placeholder,tooltip:null!==(I=null===(D=i.guide)||void 0===D?void 0:D.tooltip)&&void 0!==I?I:i.tooltip,description:null!==(P=null===(E=i.guide)||void 0===E?void 0:E.description)&&void 0!==P?P:i.description,required:i.required,error:!!r[Q]}),A]}):null},tt=({error:t})=>{if(!t)return null;try{return e(p,{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(p,{code:null==t?void 0:t.provider_response}):null}},nt=({integrationName:n,error:h,notices:p=[]})=>{var f;return t(u,{vertical:"large",horizontal:"medium",overflow:"auto",fullHeight:!0,children:[h&&e(d,{type:"error",message:(null===(f=h.provider_response)||void 0===f?void 0:f.trim())||h.message,hasMargin:!1,children:e(tt,{error:h})}),p.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."]})]})})]})},it=({fields:n,notices:i=[],onChange:r,error:s,onValidationChange:o,integrationName:a,editingSecrets:c,setEditingSecrets:p})=>{const f=n.filter((e=>!1!==e.display)),g=f.map((e=>"object"==typeof e.key?JSON.stringify(e.key):String(e.key))),{noticesBefore:y,noticesAfter:v}=function(e,t=[]){const n=t[0],i=t[t.length-1];return{noticesBefore:t=>e.filter((e=>Ge(e)?e.anchor===t:(!e.position||"top"===e.position)&&t===n)),noticesAfter:t=>e.filter((e=>!Ge(e)&&"bottom"===e.position&&t===i))}}(i,g),m=E((()=>function(e){const t={};for(const n of e)t[n.key]=Ze(n);return H.object(t)}(n)),[n]),b=E((()=>{const e={};return n.forEach((t=>{void 0!==t.value?e[t.key]=t.value.toString():e[t.key]=""})),e}),[n]),{formState:C,watch:w,reset:O,setValue:S}=_({resolver:z(m),mode:"onTouched",defaultValues:b}),{errors:k,isValid:x}=C;We((()=>{O(b)}),[b]);const R=w();return We((()=>{r(R)}),[R]),P((()=>{null==o||o(x)}),[x,o]),0===f.length?e(nt,{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(tt,{error:s})}),e(h,{children:f.map((n=>{const i="object"==typeof n.key?JSON.stringify(n.key):String(n.key),r=y(i).length>0||v(i).length>0;return t("div",{style:Object.assign(Object.assign({},r&&{display:"flex",flexDirection:"column",gap:"8px"}),{width:"100%"}),children:[y(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key))),e(et,{field:n,errors:k,setValue:S,editingSecrets:c,setEditingSecrets:p}),v(i).map((t=>e(d,{type:t.type,message:t.description,hasMargin:!1},t.key)))]},i)}))})]})})},rt=({fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,editingSecrets:a,setEditingSecrets:c})=>e(it,{fields:t,notices:n,error:i,onChange:r,onValidationChange:s,integrationName:o,editingSecrets:a,setEditingSecrets:c}),st=e=>e.split(/[-_\s]+/).filter(Boolean),ot=e=>st(e).join(" ").toLowerCase(),at=e=>st(e).join(" ").toUpperCase(),ct=({src:t,alt:n,fallbackUrl:i="https://stackone-logos.com/api/stackone/filled/png",style:r,className:s})=>{const[o,a]=Q(t);return e("img",{src:o,alt:n,style:r,className:s,onError:()=>{a(i)}})},ut=e=>Boolean(e.active&&e.name),lt=({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(ct,{src:n.logo_url,alt:n.provider,style:{width:"24px",height:"24px"}}),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(C,{text:at(n.type),children:at(n.type)})})]})},dt=({integrations:i,selectedCategory:r,onCategoryChange:s,onSearchChange:o})=>{const a=A((e=>{s(r===e?null:e)}),[r,s]),c=E((()=>Array.from(new Set(i.filter(ut).map((e=>ot(e.type)))))),[i]);return t(n,{children:[e(f,{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:at(t),selected:r===t,onClick:()=>a(t)})},t)))})})})]})]})},ht=({integrations:t,onSelect:r,selectedCategory:s,search:d})=>{const h=E((()=>t.filter((e=>ut(e)&&(!s||ot(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(lt,{integration:t}),onClick:()=>r(t)})))})})}):e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.SecondaryText,{children:"No integrations found"})})})},pt=({integrations:t,onSelect:n,selectedCategory:i,search:r})=>t.length?e(ht,{integrations:t,onSelect:n,selectedCategory:i,search:r}):e("div",{children:"No integrations found."}),ft=({title:n,description:u,onCancel:l})=>{const[d,h]=Q(!1),p=L(null);return P((()=>{if(l)return p.current=setTimeout((()=>h(!0)),5e3),()=>{p.current&&clearTimeout(p.current)}}),[l]),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: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"})]})]})},gt=({title:t,description:n,onCancel:i})=>e(ft,{title:t,description:n,onCancel:i}),yt=({integrationName:n})=>{const u=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:u.colors.success.foreground}}),e(c.Text,{fontWeight:"bold",size:"large",children:"Connection Successful"}),t(c.SecondaryText,{children:["Account successfully connected to ",n]})]})},vt=({integrationName:t})=>e(yt,{integrationName:t}),mt=({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:p,onChange:f,onValidationChange:g,onCancelOAuth:y,editingSecrets:v,setEditingSecrets:m})=>{var b,C;return t?e(gt,{title:"Loading integration data",description:"Please wait, this may take a moment."}):i.loading&&r?e(gt,{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(Ke,{message:(null==d?void 0:d.message)||(null==h?void 0:h.message)||"Unknown error"}):i.success&&r?e(vt,{integrationName:null!==(C=null==s?void 0:s.name)&&void 0!==C?C:r.name}):r?s?e(rt,{fields:a,notices:c,error:i.error,onChange:f,onValidationChange:g,integrationName:s.name,editingSecrets:v,setEditingSecrets:m}):null:(null==o?void 0:o.integrations.length)?e(pt,{integrations:o.integrations,onSelect:p,selectedCategory:u,search:l}):e(Ke,{message:"No configured integrations available."})},bt=({connectorData:n,onBack:u,guide:l})=>{var d;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(k,{variant:"ghost",onClick:u,icon:"←",size:"small"}),e(ct,{src:null===(d=n.assets)||void 0===d?void 0:d.icon,alt:n.key,style:{width:"16px",height:"16px"}}),e(c.Text,{fontWeight:"semi-bold",size:"medium",children:n.name})]}),(null==l?void 0:l.supportLink)?e(c.LinkText,{href:l.supportLink,target:"_blank",children:e(k,{variant:"outline",size:"small",children:"Connection guide"})}):null]})},Ct=({connectorData:t,accountData:n,onBack:i,guide:r,isLoading:s,hasError:o,hubData:a,selectedCategory:c,onCategoryChange:u,onSearchChange:l,hideBackButton:d})=>{if(t)return e(bt,{connectorData:t,onBack:n||d?void 0:i,guide:r});return!s&&!o&&(null==a?void 0:a.integrations)?e(dt,{integrations:a.integrations,selectedCategory:c,onCategoryChange:u,onSearchChange:l}):null},wt=({fullWidth:n=!0,selectedIntegration:r,showActions:o,onBack:c,onNext:d,isFormValid:h=!0,isLoading:p=!1,showFooterLinks:f=!0})=>{const g=E((()=>{if(!r||!o)return[];const e=[];return c&&e.push({label:"Back",type:"outline",onClick:c,disabled:p,loading:!1}),e.push({label:"Connect",type:"filled",onClick:d,disabled:!h||p,loading:p}),e}),[r,c,d,o,h,p]);return 0===g.length?f?e(x,{fullWidth:n}):null:t(l,{direction:"horizontal",size:4,justifyContent:"space-between",children:[f&&e(x,{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(k,{size:"small",variant:t.type,onClick:t.onClick,disabled:t.disabled,loading:t.loading,iconPosition:"end",children:t.label},t.label)))})})})]})},Ot=({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(x,{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(k,{size:"small",variant:"filled",onClick:r,children:null!=o?o:"Close"})})})})]}):null};function St(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 kt="x-hub-version",xt=e=>{const t={};for(const[n,i]of Object.entries(null!=e?e:{}))n.toLowerCase()!==kt.toLowerCase()&&(t[n]=i);return t[kt]="1.11.4",t};function Rt(e){return St(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:xt(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 St(this,void 0,void 0,(function*(){return Rt(Object.assign(Object.assign({},e),{method:"POST"}))}))}function jt(e){return St(this,void 0,void 0,(function*(){return Rt(Object.assign(Object.assign({},e),{method:"GET"}))}))}const Ft=(e,t,n)=>St(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 jt({url:r,headers:i})})),Tt=(e,t,n)=>St(void 0,void 0,void 0,(function*(){return yield jt({url:`${e}/hub/connectors/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Dt=e=>St(void 0,[e],void 0,(function*({baseUrl:e,accountId:t,token:n,credentials:i,integrationId:r}){return yield function(e){return St(this,void 0,void 0,(function*(){return Rt(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}})})),It=(e,t,n)=>St(void 0,void 0,void 0,(function*(){return yield jt({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Et=(e,t,n)=>St(void 0,void 0,void 0,(function*(){return yield function(e){return St(this,void 0,void 0,(function*(){return Rt(Object.assign(Object.assign({},e),{method:"DELETE"}))}))}({url:`${e}/hub/connection_attempts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})),Pt={retry:(e,t)=>{if(t&&"object"==typeof t&&"message"in t)try{const e=JSON.parse(t.message);if(401===e.status||403===e.status)return!1}catch(e){}return e<2},retryDelay:e=>Math.min(1e3*Math.pow(2,e),3e4)};var Qt;!function(e){e.AccountConnected="AccountConnected"}(Qt||(Qt={}));const At=({token:e,baseUrl:t,accountId:n,onSuccess:i,dashboardUrl:r,debug:s})=>{const[o,a]=Q(null),[c,u]=Q({}),[l,d]=Q(new Set),h=A((e=>{u(e)}),[]),p=L(null),f=L(null),g=L(null),y=L(null),v=L(!1),[m,b]=Q({loading:!1,success:!1}),C=A((()=>{null!==g.current&&(clearTimeout(g.current),g.current=null),f.current=null}),[]),w=A((e=>{b({loading:!1,success:!0}),null==i||i(e)}),[i]),O=L(s);O.current=s;const S=A((()=>{null!==y.current&&(clearTimeout(y.current),y.current=null)}),[]),k=A((()=>{C(),S(),p.current&&(p.current.close(),p.current=null)}),[C,S]);P((()=>()=>{C(),S()}),[C,S]);const{data:x,isLoading:R,error:q}=$e(Object.assign({queryKey:["accountData",n],queryFn:()=>St(void 0,void 0,void 0,(function*(){return n?((e,t,n)=>St(void 0,void 0,void 0,(function*(){return yield jt({url:`${e}/hub/accounts/${n}`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(t,e,n):null})),enabled:!!n},Pt)),{data:j,isLoading:F,error:T}=$e(Object.assign({queryKey:["hubData",null==x?void 0:x.provider],queryFn:()=>(null==x?void 0:x.provider)?Ft(e,t,x.provider):Ft(e,t),enabled:!n||!!x},Pt));P((()=>{if(x&&j){const e=j.integrations.find((e=>e.provider===x.provider));a(null!=e?e:null)}}),[x,j]),P((()=>{if(j&&!o){const e=j.integrations.filter((e=>e.active));1===e.length&&a(e[0])}}),[j,o]);const{data:D,isLoading:I,error:U}=$e(Object.assign({queryKey:["connectorData",null==x?void 0:x.integrationId,null==o?void 0:o.integration_id],queryFn:()=>St(void 0,void 0,void 0,(function*(){return x?Tt(t,e,x.integrationId):o?Tt(t,e,o.integration_id):null})),enabled:Boolean(o)||Boolean(x)},Pt)),{fields:M,guide:z,notices:_}=E((()=>{var e,t,n,i,r,s,a,c,u;if(!D||!o){return{fields:[],notices:[]}}if(("configFields"in(u=D.config)||"configNotices"in u)&&!("authentication"in u)){const s=(null!==(e=D.config.configFields)&&void 0!==e?e:[]).map((e=>{var t,n;const i=null===(t=null==x?void 0:x.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==j?void 0:j.external_trigger_token});if(x&&(!1!==e.secret||"password"===e.type)){const t=null===(n=x.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=D.config.configNotices)&&void 0!==t?t:[],guide:{supportLink:null===(n=D.config.support)||void 0===n?void 0:n.link,description:null!==(r=null===(i=D.config.support)||void 0===i?void 0:i.description)&&void 0!==r?r:""}}}let l=o.authentication_config_key,d=o.environment;x&&x.authConfigKey&&(null===(s=D.config.authentication)||void 0===s?void 0:s[x.authConfigKey])&&(l=x.authConfigKey,d=null!==(a=x.environment)&&void 0!==a?a:o.environment);const h=null===(c=D.config.authentication)||void 0===c?void 0:c[l],p=null==h?void 0:h[d],f=((null==p?void 0:p.fields)||[]).map((e=>{var t,n;const i=null===(t=null==x?void 0:x.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==j?void 0:j.external_trigger_token});if(x&&(!1!==e.secret||"password"===e.type)){const t=null===(n=x.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:f,notices:[],guide:null==p?void 0:p.guide}}),[D,o,x,j]),H=E((()=>{var e,t,n,i,r;if(!D||!o)return null;if("authentication"in(r=D.config)&&!("configFields"in r)){let r=o.authentication_config_key,s=o.environment;return x&&x.authConfigKey&&(null===(e=D.config.authentication)||void 0===e?void 0:e[x.authConfigKey])&&(r=x.authConfigKey,s=null!==(t=x.environment)&&void 0!==t?t:o.environment),null===(i=null===(n=D.config.authentication)||void 0===n?void 0:n[r])||void 0===i?void 0:i[s]}return D.config}),[D,o,x]),[$,K]=Q(!0),N=A(((n,i)=>{const r=Date.now(),s=()=>St(void 0,void 0,void 0,(function*(){var o,a,c,u;if(!g.current)return;if(Date.now()-r>3e5)return O.current&&console.debug("[hub] poll timed out",{attemptId:n}),k(),Et(t,e,n).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})})),void b({loading:!1,success:!1,timedOut:!0});const l=yield It(t,e,n).catch((()=>null));if(g.current){if(!l)return O.current&&console.debug("[hub] poll failed (network error), retrying"),void(g.current=window.setTimeout(s,2e3));O.current&&"pending"!==l.status&&console.debug("[hub] poll result",Object.assign({attemptId:n},l)),"authenticated"===l.status&&l.account?(k(),w({id:l.account.id,provider:i}),parent.postMessage({type:Qt.AccountConnected,account:{id:l.account.id,provider:i}},"*")):"error"===l.status?(k(),b({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?(k(),b({loading:!1,success:!1})):g.current=window.setTimeout(s,2e3)}}));g.current=window.setTimeout(s,2e3)}),[t,e,k,w]),V=A((n=>{let i=!0;const r=()=>St(void 0,void 0,void 0,(function*(){if(i&&(i=!1,!p.current||p.current.closed))return O.current&&console.debug("[hub] popup reads as closed on first tick, assuming COOP isolation — popup-close detection disabled"),v.current=!0,void(y.current=null);if(p.current&&!p.current.closed)return void(y.current=window.setTimeout(r,1e3));if(y.current=null,!g.current)return;if(v.current)return;const s=f.current;if(!s)return;const o=yield It(t,e,s).catch((e=>(O.current&&console.debug("[hub] final poll failed after popup closed",{attemptId:s,error:e}),null)));return g.current?"authenticated"===(null==o?void 0:o.status)&&o.account?(O.current&&console.debug("[hub] popup closed but auth completed",{attemptId:s}),k(),w({id:o.account.id,provider:n}),void parent.postMessage({type:Qt.AccountConnected,account:{id:o.account.id,provider:n}},"*")):void(O.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}));y.current=window.setTimeout(r,1e3)}),[t,e,k,w]),B=A((()=>St(void 0,void 0,void 0,(function*(){var i;if(o)if($){b({loading:!0,success:!1});try{const s=Object.assign({},c);x&&M.forEach((e=>{if(!1!==e.secret||"password"===e.type){const t=s[e.key];Ye(t)&&!l.has(e.key)&&delete s[e.key]}})),Object.keys(s).forEach((e=>{""===s[e]&&delete s[e]}));const a="oauth2"===(null==H?void 0:H.type)&&(!("grantType"in H)||"authorization_code"===H.grantType);if(O.current&&console.debug("[hub] handleConnect",{integration:o.integration_id,path:a?"oauth-redirect":"credential-form",updating:!!n}),a){const n=yield((e,t)=>St(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)),a=null!==(i=null==n?void 0:n.id)&&void 0!==i?i:null;if(f.current=a,!a)return O.current&&console.debug("[hub] connection attempt creation failed"),void b({loading:!1,success:!1,error:{message:"Failed to start OAuth flow",provider_response:"Could not create a connection attempt. Please try again."}});O.current&&console.debug("[hub] connection attempt created",{attemptId:a});const c=encodeURIComponent(`${r}/embedded/accounts/callback`);let u=`${t}/connect/oauth2/${o.integration_id}?redirect_uri=${c}&token=${e}&connection_attempt_id=${a}`;Object.keys(s).forEach((e=>{u+=`&${e}=${encodeURIComponent(s[e])}`}));const l=1024,d=800,h=void 0!==window.screenX?window.screenX:window.screenLeft,g=void 0!==window.screenY?window.screenY:window.screenTop,y=void 0!==window.outerWidth?window.outerWidth:document.body.clientWidth,m=void 0!==window.outerHeight?window.outerHeight:document.body.clientHeight-22,C=parseInt((h+(y-l)/2).toString(),10),w=`width=${l},height=${d},left=${C},top=${parseInt((g+(m-d)/2.5).toString(),10)},noopener=0`;return p.current=window.open(u,"Connect Account",w),p.current?(v.current=!1,"function"==typeof p.current.focus&&p.current.focus(),N(a,o.provider),void V(o.provider)):(O.current&&console.debug("[hub] popup was blocked by browser"),k(),Et(t,e,a).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:a,error:e})})),void b({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 u;if(n)yield Dt({baseUrl:t,accountId:n,token:e,integrationId:o.integration_id,credentials:s}),u={id:n,provider:o.provider};else{const n=yield(e=>St(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:o.integration_id});if(!n)throw new Error("Failed to create account");u={id:n.id,provider:o.provider}}w(u)}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}b({loading:!1,success:!1,error:{message:t,provider_response:n}})}}else b({loading:!1,success:!1,error:{message:"Please fix the validation errors before continuing",provider_response:"Form validation failed"}})}))),[t,r,e,o,c,l,w,x,M,n,H,k,N,V,$]),W=A((()=>{const n=f.current;O.current&&console.debug("[hub] OAuth cancelled by user",{attemptId:n}),k(),b({loading:!1,success:!1}),n&&Et(t,e,n).catch((e=>{O.current&&console.debug("[hub] cancelConnectionAttempt failed",{attemptId:n,error:e})}))}),[t,e,k]),G=F||I||R,J=!!(T||U||q);P((()=>{d(new Set)}),[o]),P((()=>{J&&m.loading&&b((e=>Object.assign(Object.assign({},e),{loading:!1})))}),[J,m.loading]);const Y=L(m.loading);P((()=>{s&&Y.current&&!m.loading&&console.debug("[hub] connectionState.loading → false",m),Y.current=m.loading}),[s,m]);const X=A((()=>{b({loading:!1,success:!1}),d(new Set)}),[]),Z=A((()=>{b({loading:!1,success:!1}),d(new Set)}),[]);return{hubData:j,accountData:x,connectorData:D,selectedIntegration:o,fields:M,notices:_,guide:z,formData:c,connectionState:m,isLoading:G,hasError:J,isFormValid:$,errorHubData:T,errorConnectorData:U,errorAccountData:q,setSelectedIntegration:a,setFormData:h,setIsFormValid:K,handleConnect:B,handleCancelOAuth:W,resetConnectionState:X,resetAllErrors:Z,editingSecrets:l,setEditingSecrets:d}},Lt=({token:n,baseUrl:i,height:r,accountId:s,onSuccess:o,onClose:a,dashboardUrl:c,showFooterLinks:u=!0,onCloseLabel:l,debug:h})=>{var p,f,g,y;const[v,m]=Q(null),[b,C]=Q(""),{hubData:w,accountData:O,connectorData:S,selectedIntegration:k,fields:x,notices:q,guide:j,connectionState:F,isLoading:T,hasError:D,isFormValid:I,errorHubData:P,errorConnectorData:L,setSelectedIntegration:U,setFormData:M,setIsFormValid:z,handleConnect:_,handleCancelOAuth:H,resetConnectionState:$,editingSecrets:K,setEditingSecrets:N}=At({token:n,baseUrl:i,accountId:s,onSuccess:o,dashboardUrl:c,debug:h}),V=A((e=>{z(e)}),[z]),B=E((()=>{if(!w)return!1;return 1===w.integrations.filter((e=>e.active)).length}),[w]),W=()=>{U(null),$(),m(null),C("")};return t(R,{glassFooter:!0,footer:F.success?e(Ot,{onClose:a,showFooterLinks:u,onCloseLabel:l}):e(wt,{selectedIntegration:k,showActions:!F.loading&&!F.success,onBack:O||B?void 0:W,onNext:_,isFormValid:I,isLoading:T,showFooterLinks:u}),title:T||F.loading||F.success?null:e(Ct,{accountData:O,onBack:W,guide:j,isLoading:T,hasError:D,hubData:w,selectedCategory:v,onCategoryChange:m,onSearchChange:C,hideBackButton:F.loading||F.success||B,connectorData:null!==(p=null==S?void 0:S.config)&&void 0!==p?p:null}),height:r,padding:"0",headerConfig:k?void 0:{padding:"0"},children:[F.timedOut&&e(d,{type:"warning",message:"Connection timed out. Please try again.",hasMargin:!0}),e(mt,{isLoading:T,hasError:D,connectionState:F,selectedIntegration:k,connectorData:null!==(f=null==S?void 0:S.config)&&void 0!==f?f:null,hubData:null!=w?w:null,fields:x,notices:q,errorHubData:null!==(g=P)&&void 0!==g?g:null,errorConnectorData:null!==(y=L)&&void 0!==y?y:null,onSelect:U,onChange:M,onValidationChange:V,onCancelOAuth:H,selectedCategory:v,search:b,editingSecrets:K,setEditingSecrets:N})]})},Ut=U({featureFlags:[]}),Mt=({featureFlags:t,children:n})=>{const i=E((()=>({featureFlags:t})),[t]);return e(Ut.Provider,{value:i,children:n})},zt=M((({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:p}=$e({queryKey:["settings"],queryFn:()=>((e,t)=>St(void 0,void 0,void 0,(function*(){return yield jt({url:`${e}/hub/settings`,headers:{"Content-Type":"application/json","x-hub-session-token":t}})})))(i,n)});return e(Mt,{featureFlags:null!==(h=null==p?void 0:p.enabled_features)&&void 0!==h?h:[],children:"integration-picker"===t&&e(Lt,{token:n,baseUrl:i,dashboardUrl:r,height:s,onSuccess:o,onClose:a,onCloseLabel:l,accountId:null!=c?c:null==p?void 0:p.existing_account_id,showFooterLinks:u,debug:d})})})),_t=()=>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 Ht extends I.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 $t=({mode:t,token:n,baseUrl:r,appUrl:s,height:u="500px",theme:l="light",accountId:d,onSuccess:h,onClose:p,onCloseLabel:f,showFooterLinks:g,debug:y})=>{const v=null!=r?r:"https://api.stackone.com",m=null!=s?s:"https://app.stackone.com";P((()=>{"dark"===l?q():"light"===l?j():F(l)}),[l]);const[b]=Q((()=>new De({defaultOptions:{queries:{refetchOnWindowFocus:!1,retry:1,retryDelay:500,refetchOnMount:!1,retryOnMount:!1}}}))),C=L(n);return P((()=>{C.current!==n&&(C.current=n,b.clear())}),[n,b]),e(T,n?{children:e(Ht,{fallback:e(R,{height:u,children:e(_t,{})}),children:e(Ue,{client:b,children:e(zt,{mode:null!=t?t:"integration-picker",token:n,apiUrl:v,dashboardUrl:m,height:u,onSuccess:h,accountId:d,onClose:p,onCloseLabel:f,showFooterLinks:g,debug:y})})})}:{children:e(Ht,{fallback:e(R,{height:u,children:e(_t,{})}),children:e(R,{height:u,footer:e(x,{}),children:e(i,{justify:a.Center,align:o.Center,fullHeight:!0,children:e(c.PageTitle,{children:"No token provided"})})})})})};export{$t as StackOneHub};
|