@buoy-gg/impersonate 7.0.74 → 7.0.75
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/lib/web/index.mjs +2 -2
- package/package.json +2 -2
package/lib/web/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";var ot=Object.defineProperty;var gr=Object.getOwnPropertyDescriptor;var mr=Object.getOwnPropertyNames;var yr=Object.prototype.hasOwnProperty;var fr=(e,t)=>{for(var r in t)ot(e,r,{get:t[r],enumerable:true})},nt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mr(t))!yr.call(e,o)&&o!==r&&ot(e,o,{get:()=>t[o],enumerable:!(n=gr(t,o))||n.enumerable});return e},br=(e,t,r)=>(nt(e,t,"default"),r&&nt(r,t,"default"));var oa=(()=>{try{let e=globalThis.Capacitor;if(e&&typeof e.isNativePlatform=="function"&&e.isNativePlatform())return e.DEBUG===true}catch{}return process.env.NODE_ENV!=="production"})();typeof window<"u"&&typeof globalThis.global>"u"&&(globalThis.global=globalThis);import at from"@buoy-gg/shared-ui/web/asyncStorage";import{getCapacitorAppStorage as Sr}from"@buoy-gg/shared-ui/web";function vr(){return at}function wr(){return Sr()??at}import{useState as xe,useCallback as te,useRef as st,useEffect as it}from"react";var lt={};fr(lt,{AccessibilityInfo:()=>kr,ActivityIndicator:()=>mt,Alert:()=>Bo,Animated:()=>Tr,AppRegistry:()=>Rr,AppState:()=>Ar,Appearance:()=>Br,BackHandler:()=>Hr,Button:()=>ko,CheckBox:()=>Xr,Clipboard:()=>Pr,DeviceEventEmitter:()=>io,Dimensions:()=>Dr,Easing:()=>zr,FlatList:()=>Ie,I18nManager:()=>Er,Image:()=>Qr,ImageBackground:()=>qr,InteractionManager:()=>Nr,Keyboard:()=>Lr,KeyboardAvoidingView:()=>_r,LayoutAnimation:()=>Ur,Linking:()=>Or,LogBox:()=>so,Modal:()=>xo,NativeEventEmitter:()=>Kr,NativeModules:()=>Ir,PanResponder:()=>Wr,Picker:()=>Jr,PixelRatio:()=>Fr,Platform:()=>Mr,Pressable:()=>Co,ProgressBar:()=>Yr,RefreshControl:()=>Gr,SafeAreaView:()=>Zr,ScrollView:()=>pt,SectionList:()=>eo,Share:()=>jr,StatusBar:()=>to,StyleSheet:()=>F,Switch:()=>Io,Text:()=>y,TextInput:()=>ht,Touchable:()=>ro,TouchableHighlight:()=>vo,TouchableNativeFeedback:()=>oo,TouchableOpacity:()=>H,TouchableWithoutFeedback:()=>wo,UIManager:()=>Vr,Vibration:()=>$r,View:()=>c,VirtualizedList:()=>no,YellowBox:()=>ao,findNodeHandle:()=>To,unstable_createElement:()=>xr,useColorScheme:()=>lo,useLocaleContext:()=>co,useWindowDimensions:()=>uo});br(lt,Cr);import*as Cr from"react-native-web";import{unstable_createElement as xr,NativeModules as Ir,AccessibilityInfo as kr,Animated as Tr,Appearance as Br,AppRegistry as Rr,AppState as Ar,BackHandler as Hr,Clipboard as Pr,Dimensions as Dr,Easing as zr,I18nManager as Er,Keyboard as Lr,InteractionManager as Nr,LayoutAnimation as Ur,Linking as Or,NativeEventEmitter as Kr,PanResponder as Wr,PixelRatio as Fr,Platform as Mr,Share as jr,StyleSheet as F,UIManager as Vr,Vibration as $r,CheckBox as Xr,FlatList as Ie,Image as Qr,ImageBackground as qr,KeyboardAvoidingView as _r,Picker as Jr,ProgressBar as Yr,RefreshControl as Gr,SafeAreaView as Zr,SectionList as eo,StatusBar as to,Touchable as ro,TouchableNativeFeedback as oo,VirtualizedList as no,YellowBox as ao,LogBox as so,DeviceEventEmitter as io,useColorScheme as lo,useLocaleContext as co,useWindowDimensions as uo}from"react-native-web";import*as D from"react-native-web";import{createElement as ke,forwardRef as ct,useCallback as ho,useRef as po}from"react";import{useEffect as go,useState as mo}from"react";import{createPortal as yo}from"react-dom";var fo='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';import{jsx as bo}from"react/jsx-runtime";var re=Symbol.for("@buoy-gg/portal-host"),dt=e=>{if(!(e instanceof Element))return false;if(e.closest("input, textarea, select"))return true;let t=e.closest("[contenteditable]")?.getAttribute("contenteditable")?.toLowerCase();return t===""||t==="true"||t==="plaintext-only"};function ut(){let e=document;if(e[re])return e[re].host;let t=document.createElement("div");t.dataset.buoyPortalHost="",Object.assign(t.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none",fontFamily:fo});let r=()=>{let s=document.fullscreenElement,b=s&&s.tagName!=="CANVAS"?s:document.body;t.parentElement!==b&&b.appendChild(t)},n=new Map,o=s=>{(!t.contains(s.target)||!dt(s.target))&&n.set(s.code||s.key,{key:s.key,code:s.code,location:s.location,keyCode:s.keyCode,which:s.which,altKey:s.altKey,ctrlKey:s.ctrlKey,metaKey:s.metaKey,shiftKey:s.shiftKey})},i=s=>{n.delete(s.code||s.key)},l=()=>n.clear(),h=()=>{let s=[...n.values()];n.clear();for(let b of s)document.dispatchEvent(new KeyboardEvent("keyup",{...b,bubbles:true}))},a=s=>{dt(s.target)&&s.stopPropagation()},d=s=>s.stopPropagation();return r(),document.addEventListener("fullscreenchange",r),document.addEventListener("keydown",o,true),document.addEventListener("keyup",i,true),window.addEventListener("blur",l),t.addEventListener("focusin",h),t.addEventListener("keydown",a),t.addEventListener("keyup",a),t.addEventListener("keypress",a),t.addEventListener("wheel",d,{passive:true}),e[re]={host:t,users:0,dispose:()=>{document.removeEventListener("fullscreenchange",r),document.removeEventListener("keydown",o,true),document.removeEventListener("keyup",i,true),window.removeEventListener("blur",l),t.remove(),delete e[re]}},t}function So({children:e}){let[t,r]=mo(null);return go(()=>{let n=ut(),o=document[re];return o.users++,r(n),()=>{--o.users===0&&o.dispose()}},[]),t?yo(bo("div",{"data-buoy-root":"",style:{display:"contents",pointerEvents:"auto"},children:e}),t):null}function L(e){let t=ct((n,o)=>{let{accessibilityState:i,accessibilityValue:l,...h}=n;for(let a of["busy","checked","disabled","expanded","selected"])i?.[a]!==void 0&&h[`aria-${a}`]===void 0&&(h[`aria-${a}`]=i[a]);for(let[a,d]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))l?.[a]!==void 0&&h[`aria-${d}`]===void 0&&(h[`aria-${d}`]=l[a]);return ke(e,{...h,ref:o})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var c=L(D.View),y=L(D.Text),ht=L(D.TextInput),H=L(D.TouchableOpacity),vo=L(D.TouchableHighlight),wo=L(D.TouchableWithoutFeedback),Co=L(D.Pressable),pt=L(D.ScrollView),gt=ct((e,t)=>{let r=po(null),n=ho(o=>{if(o){let i=o;for(;i.parentElement&&i.parentElement!==document.body;)i=i.parentElement;i.parentElement===document.body&&(r.current=i,Object.assign(i.style,{position:"relative",zIndex:"2147483647",pointerEvents:"auto"}),ut().appendChild(i))}else r.current&&(document.body.appendChild(r.current),r.current=null);typeof t=="function"?t(o):t&&(t.current=o)},[t]);return ke(So,null,ke(D.Modal,{...e,ref:n}))});gt.displayName="Modal";var xo=L(gt),Io=L(D.Switch),mt=L(D.ActivityIndicator),ko=L(D.Button),To=D.findNodeHandle,Bo={alert(e,t,r,n){if(typeof document>"u")return;let o=document.createElement("dialog");o.dataset.buoyRoot="",o.setAttribute("aria-label",e),o.style.cssText="position:fixed;inset:0;margin:auto;width:min(440px,90vw);padding:24px;border:1px solid #475569;border-radius:14px;background:#17212e;color:#f1f5f9;font:14px system-ui;box-shadow:0 20px 80px #0008;z-index:2147483647";let i=document.createElement("h2");if(i.textContent=e,i.style.cssText="font-size:18px;margin:0 0 12px",o.appendChild(i),t){let d=document.createElement("p");d.textContent=t,d.style.cssText="line-height:1.5;white-space:pre-wrap;margin:0 0 20px",o.appendChild(d)}let l=document.createElement("div");l.style.cssText="display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px";let h=r?.length?r:[{text:"OK"}],a=()=>{o.close?.(),o.remove()};for(let d of h){let s=document.createElement("button");s.type="button",s.textContent=d.text??"OK",s.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${d.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,s.onclick=()=>{a(),d.onPress?.()},l.appendChild(s)}o.addEventListener("cancel",d=>{d.preventDefault(),n?.cancelable!==false&&(a(),n?.onDismiss?.())}),o.appendChild(l),document.body.appendChild(o),o.showModal?o.showModal():o.setAttribute("open","")}};import{JsModal as Ro,TabSelector as Ao,ModalHeader as oe,buoyColors as Ho,night as yt,Search as Po,TickProvider as ft,windowDragProps as Do}from"@buoy-gg/shared-ui/web";import{useState as me,useEffect as bt,useCallback as N,useSyncExternalStore as zo}from"react";import{assertAccountAccess as St,getAccountAccess as Eo,hasAccountAccess as Lo,subscribeAccountAccess as No}from"@buoy-gg/shared-ui/web";var vt=[/\/symbolicate$/,/\/logs$/,/\/debugger-proxy/,/\/reload$/,/\/launch-js-devtools/,/localhost:8081/,/100\.64\.\d+\.\d+:8081/,/10\.0\.\d+\.\d+:8081/,/\.hot-update\./,/__metro/];function Te(e,t){for(let r of Object.keys(t))r.startsWith("__buoy")&&(e[r]=t[r])}var Uo=class{constructor(){this.isListeningFlag=false;this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.reportHeader=e=>this.shouldInjectHeader(e)?{[this.config.headerKey]:this.config.userId}:null;this.originalFetch=globalThis.fetch.bind(globalThis),this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.config={headerKey:"x-impersonate-user-id",userId:null,ignorePatterns:[...vt]}}setConfig(e){this.config={...this.config,...e},e.ignorePatterns&&(this.config.ignorePatterns=[...vt,...e.ignorePatterns])}getConfig(){return{...this.config}}shouldInjectHeader(e){return!this.config.userId||this.config.gate&&!this.config.gate()?false:!this.config.ignorePatterns.some(t=>t.test(e))}extractUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}startListening(){if(this.isListeningFlag)return;let e=globalThis.fetch,t=XMLHttpRequest.prototype.open,r=XMLHttpRequest.prototype.send;this.originalFetch=e.bind(globalThis),this.originalXHROpen=t,this.originalXHRSend=r;let n=this,o=async function(d,s){let b=n.extractUrl(d);if(n.shouldInjectHeader(b)){let C=s?.headers??(typeof d=="object"&&"headers"in d?d.headers:void 0),f=new Headers(C);return f.set(n.config.headerKey,n.config.userId),n.originalFetch(d,{...s,headers:f})}return n.originalFetch(d,s)};Te(o,e),this.patchedFetch=o,globalThis.fetch=this.patchedFetch;let i=function(d,s,b=true,C,f){let x=this;x._impersonateUrl=typeof s=="string"?s:s.href;let I=typeof s=="string"?s:s.toString();return n.originalXHROpen.call(this,d,I,b,C,f)},l=function(d){let s=this;return s._impersonateUrl&&n.shouldInjectHeader(s._impersonateUrl)&&this.setRequestHeader(n.config.headerKey,n.config.userId),n.originalXHRSend.call(this,d)};Te(i,t),Te(l,r),this.patchedXHROpen=i,this.patchedXHRSend=l,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend;let h=globalThis,a=h.__buoyHeaderInjectors??(h.__buoyHeaderInjectors=[]);a.includes(this.reportHeader)||a.push(this.reportHeader),this.isListeningFlag=true}stopListening(){if(!this.isListeningFlag)return;this.patchedFetch&&globalThis.fetch===this.patchedFetch&&(globalThis.fetch=this.originalFetch),this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen&&(XMLHttpRequest.prototype.open=this.originalXHROpen),this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend&&(XMLHttpRequest.prototype.send=this.originalXHRSend),this.patchedFetch=null,this.patchedXHROpen=null,this.patchedXHRSend=null;let e=globalThis.__buoyHeaderInjectors,t=e?.indexOf(this.reportHeader)??-1;e&&t>=0&&e.splice(t,1),this.isListeningFlag=false}get isListening(){return this.isListeningFlag}get isImpersonating(){return this.config.userId!==null&&(this.config.gate?.()??true)}},ne=null;function O(){return ne||(ne=new Uo),ne}function Oo(){O().startListening()}function Ko(){O().stopListening()}function wt(e){O().setConfig(e)}function Wo(){return ne?.isImpersonating??false}function Fo(){return ne?.getConfig().userId??null}var ae="@buoy/impersonate/state",Mo=10,Ct={reactQuery:true,redux:true,asyncStorage:false,mmkv:false},Z={isActive:false,isPaused:false,currentUser:null,headerKey:"x-impersonate-user-id",ignorePatterns:[],dataNukeSettings:Ct,showBanner:true,history:[]},Be=false,xt={getItem:e=>{try{return typeof localStorage<"u"?localStorage.getItem(e):null}catch{return null}},setItem:(e,t)=>{try{typeof localStorage<"u"&&localStorage.setItem(e,t)}catch{}},removeItem:e=>{try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}}},jo=class{constructor(){this.state={...Z};this.listeners=new Set;this.nukeCallbacks={};this.isInitialized=false;this.asyncStorageRef=null;this.storageReadyPromise=null;this.resolveStorageReady=null;this.developerDefaults=null;this.getSnapshot=()=>this.state;this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));this.remoteHandler=null;this.loadFromStorage(),Promise.resolve().then(()=>{let e=false,t=()=>{let r=Eo().status;r==="admitted"?e=true:r==="locked"&&e&&(e=false,this.disposeAccountSession())};No(t),t()}),typeof localStorage<"u"?this.storageReadyPromise=Promise.resolve():this.storageReadyPromise=new Promise(e=>{this.resolveStorageReady=e})}loadFromStorage(){try{let e=xt.getItem(ae),t=this.getEffectiveDefaults();if(e){let r=JSON.parse(e);this.state={...Z,headerKey:r.headerKey??t.headerKey,ignorePatterns:r.ignorePatterns??Z.ignorePatterns,dataNukeSettings:{...t.dataNukeSettings,...r.dataNukeSettings},showBanner:r.showBanner??t.showBanner,history:r.history??[],isActive:r.isActive??false,isPaused:r.isPaused??false,currentUser:r.currentUser??null},this.state.isActive&&this.state.currentUser&&this.syncWithListener()}else this.state={...Z,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner};this.isInitialized=true}catch{this.isInitialized=true}}setAsyncStorage(e){this.asyncStorageRef=e,this.resolveStorageReady&&(this.resolveStorageReady(),this.resolveStorageReady=null)}setDeveloperDefaults(e){this.developerDefaults=e;let t=this.getEffectiveDefaults();this.isInitialized||(this.state={...this.state,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner})}getEffectiveDefaults(){return{headerKey:this.developerDefaults?.headerKey??Z.headerKey,dataNukeSettings:{...Ct,...this.developerDefaults?.dataNukeSettings},showBanner:this.developerDefaults?.showBanner??Z.showBanner}}getDeveloperDefaults(){return this.developerDefaults}async initializeAsync(e){if(e){this.asyncStorageRef=e;try{let t=await e.getItem(ae);if(console.log("[Buoy]",`[impersonate] initializeAsync read STORAGE_KEY=${ae} stored=${t?t.slice(0,200):"null"}`),t){let r=JSON.parse(t);this.state={...this.state,headerKey:r.headerKey??this.state.headerKey,ignorePatterns:r.ignorePatterns??this.state.ignorePatterns,dataNukeSettings:{...this.state.dataNukeSettings,...r.dataNukeSettings},showBanner:r.showBanner??this.state.showBanner,history:r.history??this.state.history,isActive:r.isActive??this.state.isActive,isPaused:r.isPaused??this.state.isPaused,currentUser:r.currentUser??this.state.currentUser},this.state.isActive&&this.state.currentUser&&this.syncWithListener(),this.notify()}}catch{}}}registerNukeCallbacks(e){this.nukeCallbacks={...this.nukeCallbacks,...e}}getState(){return{...this.state}}setRemoteHandler(e){this.remoteHandler=e}replaceState(e){this.state=e,this.notify()}async startImpersonation(e){if(St(),this.remoteHandler){this.remoteHandler("startImpersonation",{user:e});return}let t=[{user:e,lastUsedAt:new Date().toISOString()},...this.state.history.filter(r=>r.user.id!==e.id)].slice(0,Mo);this.state={...this.state,isActive:true,currentUser:e,history:t},this.syncWithListener(),this.notify(),await this.executeDataNuke(),await this.persist()}async stopImpersonation(){if(this.remoteHandler){this.remoteHandler("stopImpersonation");return}console.log("[Buoy]",`[impersonate] stopImpersonation: isActive ${this.state.isActive} -> false, listeners=${this.listeners.size}`),this.state={...this.state,isActive:false,isPaused:false,currentUser:null},this.syncWithListener(),this.notify(),await this.executeDataNuke(),await this.persist()}async pauseImpersonation(){if(this.remoteHandler){this.remoteHandler("pauseImpersonation");return}!this.state.isActive||this.state.isPaused||(this.state={...this.state,isPaused:true},this.syncWithListener(),await this.persist(),this.notify())}async resumeImpersonation(){if(St(),this.remoteHandler){this.remoteHandler("resumeImpersonation");return}!this.state.isActive||!this.state.isPaused||(this.state={...this.state,isPaused:false},this.syncWithListener(),await this.persist(),this.notify())}async quickSwitch(e){return this.startImpersonation(e)}async updateSettings(e){if(this.remoteHandler){this.remoteHandler("updateSettings",{settings:e});return}this.state={...this.state,headerKey:e.headerKey??this.state.headerKey,ignorePatterns:e.ignorePatterns??this.state.ignorePatterns,showBanner:e.showBanner??this.state.showBanner,dataNukeSettings:e.dataNukeSettings?{...this.state.dataNukeSettings,...e.dataNukeSettings}:this.state.dataNukeSettings},(e.headerKey||e.ignorePatterns)&&this.syncWithListener(),await this.persist(),this.notify()}async removeFromHistory(e){if(this.remoteHandler){this.remoteHandler("removeFromHistory",{userId:e});return}this.state={...this.state,history:this.state.history.filter(t=>t.user.id!==e)},await this.persist(),this.notify()}async clearHistory(){if(this.remoteHandler){this.remoteHandler("clearHistory");return}this.state={...this.state,history:[]},await this.persist(),this.notify()}async executeDataNuke(){if(!Be){Be=true;try{let{dataNukeSettings:e}=this.state,t=[];e.reactQuery&&this.nukeCallbacks.reactQuery&&t.push(Promise.resolve(this.nukeCallbacks.reactQuery())),e.redux&&this.nukeCallbacks.redux&&t.push(Promise.resolve(this.nukeCallbacks.redux())),e.asyncStorage&&this.nukeCallbacks.asyncStorage&&t.push(Promise.resolve(this.nukeCallbacks.asyncStorage())),e.mmkv&&this.nukeCallbacks.mmkv&&t.push(Promise.resolve(this.nukeCallbacks.mmkv())),await Promise.allSettled(t)}finally{setTimeout(()=>{Be=false},100)}}}disposeAccountSession(){this.remoteHandler||!this.state.isActive||(this.state={...this.state,isActive:false,isPaused:false,currentUser:null},this.syncWithListener(),this.notify(),this.persist())}syncWithListener(){let e=this.state.isActive&&!this.state.isPaused;wt({headerKey:this.state.headerKey,userId:e?this.state.currentUser?.id??null:null,ignorePatterns:this.state.ignorePatterns.map(t=>new RegExp(t)),gate:Lo}),O().isListening||O().startListening()}async persist(){this.storageReadyPromise&&await this.storageReadyPromise;let e={headerKey:this.state.headerKey,ignorePatterns:this.state.ignorePatterns,dataNukeSettings:this.state.dataNukeSettings,showBanner:this.state.showBanner,history:this.state.history,isActive:this.state.isActive,isPaused:this.state.isPaused,currentUser:this.state.currentUser},t=JSON.stringify(e);try{this.asyncStorageRef?(await this.asyncStorageRef.setItem(ae,t),console.log("[Buoy]",`[impersonate] persist -> AsyncStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)):(xt.setItem(ae,t),console.log("[Buoy]",`[impersonate] persist -> localStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`))}catch(r){console.warn("[Buoy]","[impersonate] persist failed",r)}}notify(){this.listeners.forEach(e=>{try{e(this.state)}catch{}})}},g=new jo;function It(e={}){let[t,r]=me(""),[n,o]=me([]),[i,l]=me(false),[h,a]=me(null),d=zo(g.subscribe,g.getSnapshot,g.getSnapshot);bt(()=>{g.registerNukeCallbacks({reactQuery:e.onClearReactQuery,redux:e.onClearRedux,asyncStorage:e.onClearAsyncStorage,mmkv:e.onClearMMKV})},[e.onClearReactQuery,e.onClearRedux,e.onClearAsyncStorage,e.onClearMMKV]),bt(()=>{let S=true;return(async()=>{try{let v=await import("@buoy-gg/shared-ui/web/asyncStorage").then(W=>W.default),G={getItem:W=>v.getItem(W),setItem:(W,we)=>v.setItem(W,we)};g.setAsyncStorage(G),S&&await g.initializeAsync(G)}catch{}})(),O().isListening||O().startListening(),()=>{S=false}},[]);let s=N(async S=>{if(r(S),a(null),!S.trim()){o([]);return}if(!e.onSearchUsers){a("Search not configured"),o([]);return}l(true);try{let v=await e.onSearchUsers(S);o(v)}catch(v){a(v instanceof Error?v.message:"Search failed"),o([])}finally{l(false)}},[e.onSearchUsers]),b=N(()=>{r(""),o([]),a(null)},[]),C=N(async S=>{await g.startImpersonation(S)},[]),f=N(async()=>{await g.stopImpersonation()},[]),x=N(async S=>{await g.quickSwitch(S)},[]),I=N(async S=>{await g.updateSettings({headerKey:S})},[]),ge=N(async S=>{await g.updateSettings({ignorePatterns:S})},[]),X=N(async S=>{await g.updateSettings({dataNukeSettings:S})},[]),Y=N(async S=>{await g.updateSettings({showBanner:S})},[]),K=N(async S=>{await g.removeFromHistory(S)},[]),ee=N(async()=>{await g.clearHistory()},[]);return{isActive:d.isActive,currentUser:d.currentUser,headerKey:d.headerKey,ignorePatterns:d.ignorePatterns,dataNukeSettings:d.dataNukeSettings,showBanner:d.showBanner,history:d.history,searchQuery:t,searchResults:n,isSearching:i,searchError:h,searchUsers:s,clearSearch:b,startImpersonation:C,stopImpersonation:f,quickSwitch:x,updateHeaderKey:I,updateIgnorePatterns:ge,updateDataNukeSettings:X,updateShowBanner:Y,removeFromHistory:K,clearHistory:ee}}import{useCallback as Vo}from"react";import{dispatchToolAction as kt,getToolAdapters as $o}from"@buoy-gg/shared-ui/web";function Xo(){let e=!!$o().query,t=Vo(async()=>{await kt("query","clearQueryCache"),await kt("query","clearMutationCache")},[]);return{isAvailable:e,error:e?null:"Connect React Query to Buoy or provide onClearReactQuery.",clearCache:e?t:null}}import{useCallback as Qo}from"react";import{dispatchToolAction as qo,getToolAdapters as _o}from"@buoy-gg/shared-ui/web";var Jo="@@RESET";function Yo({resetActionType:e=Jo}={}){let t=!!_o().redux,r=Qo(async()=>{await qo("redux","dispatch",{action:{type:e}})},[e]);return{isAvailable:t,error:t?null:"Connect Redux to Buoy or provide onClearRedux.",resetStore:t?r:null}}import{isDevToolsStorageKey as Go}from"@buoy-gg/shared-ui/web";import{useCallback as Zo,useMemo as en,useState as Tt,useEffect as tn}from"react";var Re=false;function rn(){let[e,t]=Tt(null),[r,n]=Tt(null);tn(()=>{let i=wr();i?(t(i),n(null)):n("@react-native-async-storage/async-storage is not installed")},[]);let o=Zo(async()=>{if(!Re){Re=true;try{if(e){let i=(await e.getAllKeys()).filter(l=>!Go(l));i.length>0&&await e.multiRemove([...i])}}finally{setTimeout(()=>{Re=false},100)}}},[e]);return en(()=>!e||r?{isAvailable:false,error:r||"@react-native-async-storage/async-storage is not available",clearStorage:null}:{isAvailable:true,error:null,clearStorage:o},[e,r,o])}import{useCallback as on}from"react";import{SectionHeader as Ae,EmptyState as nn,night as A,Search as an,AlertTriangle as Bt,Users as sn}from"@buoy-gg/shared-ui/web";import{buoyColors as He,night as z,Play as ln,X as cn,PowerToggleButton as dn,monoFont as un}from"@buoy-gg/shared-ui/web";import{useMemo as Rt}from"react";import{buoyColors as hn,night as pn}from"@buoy-gg/shared-ui/web";import{jsx as Pe,jsxs as gn}from"react/jsx-runtime";var At=["#6366F1","#8B5CF6","#EC4899","#F43F5E","#F97316","#EAB308","#22C55E","#14B8A6","#06B6D4","#3B82F6"],mn={small:{container:24,font:10,indicator:8},medium:{container:36,font:14,indicator:10},large:{container:44,font:16,indicator:12}};function yn(e){if(!e)return"?";if(e.includes("@"))return e.charAt(0).toUpperCase();let t=e.trim().split(/\s+/);return t.length===1?t[0].charAt(0).toUpperCase():(t[0].charAt(0)+t[t.length-1].charAt(0)).toUpperCase()}function fn(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return At[Math.abs(t)%At.length]}function De({userId:e,name:t,size:r="medium",showActiveIndicator:n=false,backgroundColor:o}){let i=mn[r],l=Rt(()=>o??fn(e),[e,o]),h=Rt(()=>yn(t),[t]);return gn(c,{style:ye.wrapper,children:[Pe(c,{style:[ye.container,{width:i.container,height:i.container,borderRadius:i.container/2,backgroundColor:l}],children:Pe(y,{style:[ye.initials,{fontSize:i.font}],children:h})}),n&&Pe(c,{style:[ye.indicator,{width:i.indicator,height:i.indicator,borderRadius:i.indicator/2,right:-1,bottom:-1}]})]})}var ye=F.create({wrapper:{position:"relative"},container:{alignItems:"center",justifyContent:"center"},initials:{color:"#FFFFFF",fontWeight:"600",letterSpacing:.5},indicator:{position:"absolute",backgroundColor:hn.success,borderWidth:2,borderColor:pn.color.surface}});import{jsx as E,jsxs as se}from"react/jsx-runtime";function Ht({user:e,isActive:t=false,onPress:r,onStop:n,onRemove:o,showRemoveButton:i=false,lastUsedTime:l,variant:h="default"}){let a=e.displayName||e.email||e.id,d=e.email&&e.displayName,s=typeof e.metadata?.role=="string"?e.metadata.role:null;return se(H,{testID:`buoy-impersonate-user-${e.id}`,style:[R.container,t&&R.activeContainer,h==="compact"&&R.compactContainer],onPress:r,disabled:t,activeOpacity:.7,children:[E(c,{style:R.avatarSection,children:E(De,{userId:e.id,name:a,size:h==="compact"?"small":"medium",showActiveIndicator:t})}),se(c,{style:R.content,children:[se(c,{style:R.nameRow,children:[E(y,{style:[R.name,t&&R.activeName],numberOfLines:1,children:a}),s?E(c,{style:R.roleBadge,children:E(y,{style:R.roleBadgeText,children:s.toUpperCase()})}):null]}),d&&E(y,{style:R.email,numberOfLines:1,children:e.email}),E(c,{style:R.metadataRow,children:se(y,{style:R.userId,children:["ID: ",e.id]})})]}),se(c,{style:R.actions,children:[t?E(dn,{isEnabled:true,onToggle:n||(()=>{}),accessibilityLabel:"Stop impersonation",testID:`buoy-impersonate-stop-${e.id}`}):E(H,{testID:`buoy-impersonate-start-${e.id}`,style:R.actionButton,onPress:r,activeOpacity:.7,children:E(ln,{size:14,color:z.color.onAccent})}),i&&o&&!t&&E(H,{testID:`buoy-impersonate-remove-${e.id}`,style:R.removeButton,onPress:o,activeOpacity:.7,children:E(cn,{size:12,color:z.color.textTertiary})})]}),l?E(y,{style:R.lastUsed,children:l}):null]})}var R=F.create({container:{flexDirection:"row",alignItems:"center",backgroundColor:z.color.surface,borderRadius:10,borderWidth:1,borderColor:z.color.border,padding:12,gap:12},activeContainer:{backgroundColor:He.success+"10",borderColor:He.success+"40"},compactContainer:{padding:10,gap:10},avatarSection:{flexShrink:0},content:{flex:1,minWidth:0},nameRow:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},name:{fontSize:15,fontWeight:"600",color:z.color.text,flexShrink:1},activeName:{color:He.success},roleBadge:{backgroundColor:z.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},roleBadgeText:{fontSize:9,fontWeight:"700",color:z.color.textTertiary,letterSpacing:.5},email:{fontSize:13,color:z.color.textSecondary,marginBottom:4},metadataRow:{flexDirection:"row",alignItems:"center",gap:4},userId:{fontSize:11,color:z.color.textTertiary,fontFamily:un},lastUsed:{position:"absolute",bottom:8,right:10,fontSize:10,color:z.color.textTertiary},actions:{flexDirection:"row",alignItems:"center",gap:8,flexShrink:0},actionButton:{width:36,height:36,borderRadius:8,backgroundColor:z.color.accent,alignItems:"center",justifyContent:"center"},removeButton:{width:28,height:28,borderRadius:6,backgroundColor:z.color.surfaceElevated,borderWidth:1,borderColor:z.color.border,alignItems:"center",justifyContent:"center"}});import{jsx as k,jsxs as M}from"react/jsx-runtime";function Pt({currentUser:e,searchQuery:t,searchResults:r,isSearching:n,searchError:o,onSelectUser:i,onStopImpersonation:l,searchAvailable:h=true}){let a=on(({item:d})=>{let s=e?.id===d.id;return k(Ht,{user:d,isActive:s,onPress:()=>!s&&i(d),onStop:s?l:void 0})},[e,i,l]);return M(c,{style:B.container,children:[!h&&k(c,{style:B.section,children:M(c,{style:B.warningCard,children:[k(Bt,{size:18,color:A.color.warning}),M(c,{style:B.warningContent,children:[k(y,{style:B.warningTitle,children:"Search Not Available"}),k(y,{style:B.warningText,children:"Configure the onSearchUsers callback to enable user search."})]})]})}),n&&M(c,{style:B.loadingContainer,children:[k(mt,{size:"small",color:A.color.accent}),k(y,{style:B.loadingText,children:"Searching users..."})]}),o?k(c,{style:B.section,children:M(c,{style:B.errorCard,children:[k(Bt,{size:16,color:A.color.danger}),k(y,{testID:"buoy-impersonate-error",style:B.errorText,children:o})]})}):null,r.length>0&&M(c,{style:B.resultsSection,children:[M(Ae,{children:[k(Ae.Title,{children:"Results"}),k(Ae.Badge,{count:r.length})]}),k(Ie,{testID:"buoy-impersonate-search-scroll",data:r,keyExtractor:d=>d.id,renderItem:a,ItemSeparatorComponent:()=>k(c,{style:B.separator}),contentContainerStyle:B.listContent,showsVerticalScrollIndicator:false})]}),!!t&&!n&&r.length===0&&!o&&M(c,{testID:"buoy-impersonate-no-results",style:B.emptyStateContainer,children:[k(c,{style:B.emptyStateIcon,children:k(sn,{size:28,color:A.color.textTertiary})}),k(y,{style:B.emptyStateTitle,children:"No users found"}),M(y,{style:B.emptyStateDescription,children:['No results for "',t,'"']}),k(y,{style:B.emptyStateHint,children:"Try a different search term"})]}),!t&&r.length===0&&!n&&h&&k(c,{testID:"buoy-impersonate-search-empty",children:k(nn,{title:"Search for users",description:"Tap the search icon in the header to find users by email, name, or ID",icon:an,variant:"minimal"})})]})}var B=F.create({container:{flex:1},section:{padding:16,paddingBottom:8},loadingContainer:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:10,paddingVertical:20},loadingText:{fontSize:13,color:A.color.textSecondary},resultsSection:{flex:1,paddingHorizontal:16},listContent:{paddingBottom:16},separator:{height:8},warningCard:{flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:A.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:A.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:14,fontWeight:"600",color:A.color.warning,marginBottom:4},warningText:{fontSize:13,color:A.color.textSecondary,lineHeight:18},errorCard:{flexDirection:"row",alignItems:"center",gap:10,backgroundColor:A.color.dangerSoft,borderRadius:10,borderWidth:1,borderColor:A.color.danger+"25",padding:12},errorText:{flex:1,fontSize:13,color:A.color.danger},emptyStateContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyStateIcon:{width:56,height:56,borderRadius:28,backgroundColor:A.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyStateTitle:{fontSize:16,fontWeight:"600",color:A.color.text,marginBottom:6},emptyStateDescription:{fontSize:14,color:A.color.textSecondary,textAlign:"center",marginBottom:8},emptyStateHint:{fontSize:12,color:A.color.textTertiary}});import{useCallback as bn}from"react";import{night as Q,Trash2 as Sn,useRelativeTime as vn,ToolEmptyState as wn}from"@buoy-gg/shared-ui/web";import{jsx as U,jsxs as Dt}from"react/jsx-runtime";function Cn({item:e,isActive:t,onSelect:r,onStop:n,onRemove:o,showRemoveButton:i}){let l=vn(new Date(e.lastUsedAt));return U(Ht,{user:e.user,isActive:t,onPress:()=>!t&&r(e.user),onStop:t?n:void 0,onRemove:o,showRemoveButton:i,lastUsedTime:l})}function zt({history:e,currentUserId:t,onSelectUser:r,onStopImpersonation:n,onRemoveFromHistory:o,onClearHistory:i}){let l=bn(({item:h})=>{let a=t===h.user.id;return U(Cn,{item:h,isActive:a,onSelect:r,onStop:n,onRemove:o?()=>o(h.user.id):void 0,showRemoveButton:!!o})},[t,r,n,o]);return e.length===0?U(wn,{testID:"buoy-impersonate-history-empty",otto:"disguise",title:"No History",message:"Users you impersonate will appear here for quick access"}):Dt(c,{style:j.container,children:[Dt(c,{style:j.headerRow,children:[U(y,{style:j.headerTitle,children:"Recent"}),U(c,{style:j.headerBadge,children:U(y,{style:j.headerBadgeText,children:e.length})}),U(c,{style:j.headerSpacer}),i&&U(H,{testID:"buoy-impersonate-clear-history",style:j.clearButton,onPress:i,activeOpacity:.7,children:U(Sn,{size:12,color:Q.color.textTertiary})})]}),U(Ie,{testID:"buoy-impersonate-history-scroll",data:e,keyExtractor:h=>h.user.id,renderItem:l,ItemSeparatorComponent:()=>U(c,{style:j.separator}),contentContainerStyle:j.listContent,showsVerticalScrollIndicator:false})]})}var j=F.create({container:{flex:1,paddingHorizontal:16},headerRow:{flexDirection:"row",alignItems:"center",paddingVertical:10,gap:8},headerTitle:{fontSize:12,fontWeight:"600",color:Q.color.textTertiary,textTransform:"uppercase",letterSpacing:.5},headerBadge:{backgroundColor:Q.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},headerBadgeText:{fontSize:10,fontWeight:"600",color:Q.color.textTertiary},headerSpacer:{flex:1},clearButton:{width:24,height:24,alignItems:"center",justifyContent:"center",backgroundColor:Q.color.surfaceElevated,borderRadius:4},listContent:{paddingBottom:20},separator:{height:8},emptyContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyIcon:{width:56,height:56,borderRadius:28,backgroundColor:Q.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyTitle:{fontSize:16,fontWeight:"600",color:Q.color.text,marginBottom:6},emptyDescription:{fontSize:14,color:Q.color.textSecondary,textAlign:"center"}});import{useState as fe,useEffect as ze,useMemo as Ee}from"react";import{CollapsibleSection as ie,buoyColors as le,night as m,Settings as xn,AlertTriangle as Et,Info as In,Zap as kn,RefreshCw as Tn,Check as Le,X as Lt,Copy as Nt,Eye as Bn,copyToClipboard as Rn,ToggleRow as An,monoFont as Ne}from"@buoy-gg/shared-ui/web";import{DataViewer as Hn}from"@buoy-gg/shared-ui/web/dataViewer";import{Fragment as Ue,jsx as p,jsxs as w}from"react/jsx-runtime";var ce="x-impersonate-user-id",Oe=true,de={reactQuery:true,redux:true,asyncStorage:false,mmkv:false};function ue({label:e,description:t,value:r,onChange:n,recommended:o,dangerous:i,detected:l,testID:h}){let a=w(Ue,{children:[l!==void 0&&w(c,{style:[u.detectedBadge,l?u.detectedBadgeActive:u.detectedBadgeInactive],children:[l?p(Le,{size:10,color:le.success}):p(Lt,{size:10,color:m.color.textTertiary}),p(y,{style:[u.detectedText,l?u.detectedTextActive:u.detectedTextInactive],children:l?"Detected":"Not Detected"})]}),o&&l!==false&&w(c,{style:u.recommendedBadge,children:[p(kn,{size:10,color:m.color.accent}),p(y,{style:u.recommendedText,children:"Recommended"})]})]});return p(An,{variant:"plain",label:e,description:t,value:r,onValueChange:n,tone:i?"warning":"accent",emphasizeLabel:i,accessory:a,testID:h})}function Ut({headerKey:e,settings:t,showBanner:r,onSave:n,onShowBannerChange:o,detectionStatus:i}){let[l,h]=fe(e),[a,d]=fe(t),[s,b]=fe(r),[C,f]=fe(false);ze(()=>{h(e)},[e]),ze(()=>{d(t)},[t]),ze(()=>{b(r)},[r]);let x=Ee(()=>l!==e||a.reactQuery!==t.reactQuery||a.redux!==t.redux||a.asyncStorage!==t.asyncStorage||a.mmkv!==t.mmkv,[l,a,e,t]),I=Ee(()=>l===ce&&s===Oe&&a.reactQuery===de.reactQuery&&a.redux===de.redux&&a.asyncStorage===de.asyncStorage&&a.mmkv===de.mmkv,[l,s,a]),ge=()=>{n(l.trim()||ce,a,s)},X=()=>{h(e),d(t),b(r)},Y=()=>{h(ce),d(de),b(Oe),o(Oe)},K=(v,G)=>{d(W=>({...W,[v]:G}))},ee=Ee(()=>({defaults:{headerKey:l,showBanner:s,dataNukeSettings:{reactQuery:a.reactQuery,redux:a.redux,asyncStorage:a.asyncStorage,mmkv:a.mmkv}}}),[l,s,a]),S=async()=>{let v=`defaults: {
|
|
1
|
+
"use client";var st=Object.defineProperty;var br=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var vr=Object.prototype.hasOwnProperty;var wr=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:true})},it=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Sr(t))!vr.call(e,o)&&o!==r&&st(e,o,{get:()=>t[o],enumerable:!(n=br(t,o))||n.enumerable});return e},xr=(e,t,r)=>(it(e,t,"default"),r&&it(r,t,"default"));var ca=(()=>{try{let e=globalThis.Capacitor;if(e&&typeof e.isNativePlatform=="function"&&e.isNativePlatform())return e.DEBUG===true}catch{}return process.env.NODE_ENV!=="production"})();typeof window<"u"&&typeof globalThis.global>"u"&&(globalThis.global=globalThis);import lt from"@buoy-gg/shared-ui/web/asyncStorage";import{getCapacitorAppStorage as Cr}from"@buoy-gg/shared-ui/web";function Ir(){return lt}function kr(){return Cr()??lt}import{useState as ke,useCallback as oe,useRef as ct,useEffect as dt}from"react";var ut={};wr(ut,{AccessibilityInfo:()=>Ar,ActivityIndicator:()=>St,Alert:()=>Do,Animated:()=>ko,AppRegistry:()=>Pr,AppState:()=>Er,Appearance:()=>Hr,BackHandler:()=>Dr,Button:()=>Po,CheckBox:()=>_r,Clipboard:()=>zr,DeviceEventEmitter:()=>uo,Dimensions:()=>Lr,Easing:()=>Nr,FlatList:()=>Te,I18nManager:()=>Ur,Image:()=>Yr,ImageBackground:()=>Jr,InteractionManager:()=>Kr,Keyboard:()=>Or,KeyboardAvoidingView:()=>Gr,LayoutAnimation:()=>Wr,Linking:()=>jr,LogBox:()=>co,Modal:()=>Ao,NativeEventEmitter:()=>Fr,NativeModules:()=>Rr,PanResponder:()=>Mr,Picker:()=>Zr,PixelRatio:()=>Vr,Platform:()=>$r,Pressable:()=>Ro,ProgressBar:()=>eo,RefreshControl:()=>to,SafeAreaView:()=>ro,ScrollView:()=>ft,SectionList:()=>oo,Share:()=>Xr,StatusBar:()=>no,StyleSheet:()=>j,Switch:()=>Ho,Text:()=>y,TextInput:()=>yt,Touchable:()=>ao,TouchableHighlight:()=>To,TouchableNativeFeedback:()=>so,TouchableOpacity:()=>H,TouchableWithoutFeedback:()=>Bo,UIManager:()=>Qr,Vibration:()=>qr,View:()=>d,VirtualizedList:()=>io,YellowBox:()=>lo,findNodeHandle:()=>Eo,unstable_createElement:()=>Br,useColorScheme:()=>ho,useLocaleContext:()=>po,useWindowDimensions:()=>go});xr(ut,Tr);import*as Tr from"react-native-web";import{unstable_createElement as Br,NativeModules as Rr,AccessibilityInfo as Ar,Appearance as Hr,AppRegistry as Pr,AppState as Er,BackHandler as Dr,Clipboard as zr,Dimensions as Lr,Easing as Nr,I18nManager as Ur,Keyboard as Or,InteractionManager as Kr,LayoutAnimation as Wr,Linking as jr,NativeEventEmitter as Fr,PanResponder as Mr,PixelRatio as Vr,Platform as $r,Share as Xr,UIManager as Qr,Vibration as qr,CheckBox as _r,FlatList as Te,Image as Yr,ImageBackground as Jr,KeyboardAvoidingView as Gr,Picker as Zr,ProgressBar as eo,RefreshControl as to,SafeAreaView as ro,SectionList as oo,StatusBar as no,Touchable as ao,TouchableNativeFeedback as so,VirtualizedList as io,YellowBox as lo,LogBox as co,DeviceEventEmitter as uo,useColorScheme as ho,useLocaleContext as po,useWindowDimensions as go}from"react-native-web";import*as E from"react-native-web";import{createElement as Be,forwardRef as ht,useCallback as mo,useRef as yo}from"react";import{useEffect as fo,useState as bo}from"react";import{createPortal as So}from"react-dom";var vo='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';import{jsx as wo}from"react/jsx-runtime";var ne=Symbol.for("@buoy-gg/portal-host"),pt=e=>{if(!(e instanceof Element))return false;if(e.closest("input, textarea, select"))return true;let t=e.closest("[contenteditable]")?.getAttribute("contenteditable")?.toLowerCase();return t===""||t==="true"||t==="plaintext-only"};function gt(){let e=document;if(e[ne])return e[ne].host;let t=document.createElement("div");t.dataset.buoyPortalHost="",Object.assign(t.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none",fontFamily:vo});let r=()=>{let s=document.fullscreenElement,f=s&&s.tagName!=="CANVAS"?s:document.body;t.parentElement!==f&&f.appendChild(t)},n=new Map,o=s=>{(!t.contains(s.target)||!pt(s.target))&&n.set(s.code||s.key,{key:s.key,code:s.code,location:s.location,keyCode:s.keyCode,which:s.which,altKey:s.altKey,ctrlKey:s.ctrlKey,metaKey:s.metaKey,shiftKey:s.shiftKey})},i=s=>{n.delete(s.code||s.key)},l=()=>n.clear(),p=()=>{let s=[...n.values()];n.clear();for(let f of s)document.dispatchEvent(new KeyboardEvent("keyup",{...f,bubbles:true}))},a=s=>{pt(s.target)&&s.stopPropagation()},c=s=>s.stopPropagation();return r(),document.addEventListener("fullscreenchange",r),document.addEventListener("keydown",o,true),document.addEventListener("keyup",i,true),window.addEventListener("blur",l),t.addEventListener("focusin",p),t.addEventListener("keydown",a),t.addEventListener("keyup",a),t.addEventListener("keypress",a),t.addEventListener("wheel",c,{passive:true}),e[ne]={host:t,users:0,dispose:()=>{document.removeEventListener("fullscreenchange",r),document.removeEventListener("keydown",o,true),document.removeEventListener("keyup",i,true),window.removeEventListener("blur",l),t.remove(),delete e[ne]}},t}function xo({children:e}){let[t,r]=bo(null);return fo(()=>{let n=gt(),o=document[ne];return o.users++,r(n),()=>{--o.users===0&&o.dispose()}},[]),t?So(wo("div",{"data-buoy-root":"",style:{display:"contents",pointerEvents:"auto"},children:e}),t):null}var Z=E,Co=["shadowColor","shadowOffset","shadowOpacity","shadowRadius","textShadowColor","textShadowOffset","textShadowRadius"],ee=e=>typeof e=="number"?`${e}px`:e;function Re(e){if(Array.isArray(e)){let f=e.map(Re);return f.some((S,b)=>S!==e[b])?f:e}if(!e||typeof e!="object"||!Co.some(f=>e[f]!=null))return e;let{shadowColor:t,shadowOffset:r,shadowOpacity:n,shadowRadius:o,textShadowColor:i,textShadowOffset:l,textShadowRadius:p,...a}=e;if(t!=null||r!=null||n!=null||o!=null){let f=t??"black",S=n==null?f:`color-mix(in srgb, ${f} ${Math.min(n,1)*100}%, transparent)`,b=`${ee(r?.width??0)} ${ee(r?.height??0)} ${ee(o??0)} ${S}`;a.boxShadow=typeof a.boxShadow=="string"?`${a.boxShadow}, ${b}`:a.boxShadow??b}let{width:c=0,height:s=0}=l??{};if(i&&(c||s||p)){let f=`${ee(c)} ${ee(s)} ${ee(p??0)} ${i}`;a.textShadow=a.textShadow?`${a.textShadow}, ${f}`:f}return a}var Io=Z.StyleSheet.create({auto:{pointerEvents:"auto"},none:{pointerEvents:"none"},"box-none":{pointerEvents:"box-none"},"box-only":{pointerEvents:"box-only"}});function mt(e,t){if(typeof e=="function")return n=>mt(e(n),t);let r=Re(e);return t?[r,Io[t]]:r}var j={...Z.StyleSheet,create:e=>Z.StyleSheet.create(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Re(r)])))};function L(e){let t=ht((n,o)=>{let{accessibilityState:i,accessibilityValue:l,pointerEvents:p,...a}=n;for(let s of["busy","checked","disabled","expanded","selected"])i?.[s]!==void 0&&a[`aria-${s}`]===void 0&&(a[`aria-${s}`]=i[s]);for(let[s,f]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))l?.[s]!==void 0&&a[`aria-${f}`]===void 0&&(a[`aria-${f}`]=l[s]);let c=mt(a.style,p);return c!==a.style&&(a.style=c),Be(e,{...a,ref:o})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var d=L(E.View),y=L(E.Text),ko={...Z.Animated,View:Z.Animated.createAnimatedComponent(d),Text:Z.Animated.createAnimatedComponent(y)},yt=L(E.TextInput),H=L(E.TouchableOpacity),To=L(E.TouchableHighlight),Bo=L(E.TouchableWithoutFeedback),Ro=L(E.Pressable),ft=L(E.ScrollView),bt=ht((e,t)=>{let r=yo(null),n=mo(o=>{if(o){let i=o;for(;i.parentElement&&i.parentElement!==document.body;)i=i.parentElement;i.parentElement===document.body&&(r.current=i,Object.assign(i.style,{position:"relative",zIndex:"2147483647",pointerEvents:"auto"}),gt().appendChild(i))}else r.current&&(document.body.appendChild(r.current),r.current=null);typeof t=="function"?t(o):t&&(t.current=o)},[t]);return Be(xo,null,Be(E.Modal,{...e,ref:n}))});bt.displayName="Modal";var Ao=L(bt),Ho=L(E.Switch),St=L(E.ActivityIndicator),Po=L(E.Button),Eo=E.findNodeHandle,Do={alert(e,t,r,n){if(typeof document>"u")return;let o=document.createElement("dialog");o.dataset.buoyRoot="",o.setAttribute("aria-label",e),o.style.cssText="position:fixed;inset:0;margin:auto;width:min(440px,90vw);padding:24px;border:1px solid #475569;border-radius:14px;background:#17212e;color:#f1f5f9;font:14px system-ui;box-shadow:0 20px 80px #0008;z-index:2147483647";let i=document.createElement("h2");if(i.textContent=e,i.style.cssText="font-size:18px;margin:0 0 12px",o.appendChild(i),t){let c=document.createElement("p");c.textContent=t,c.style.cssText="line-height:1.5;white-space:pre-wrap;margin:0 0 20px",o.appendChild(c)}let l=document.createElement("div");l.style.cssText="display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px";let p=r?.length?r:[{text:"OK"}],a=()=>{o.close?.(),o.remove()};for(let c of p){let s=document.createElement("button");s.type="button",s.textContent=c.text??"OK",s.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${c.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,s.onclick=()=>{a(),c.onPress?.()},l.appendChild(s)}o.addEventListener("cancel",c=>{c.preventDefault(),n?.cancelable!==false&&(a(),n?.onDismiss?.())}),o.appendChild(l),document.body.appendChild(o),o.showModal?o.showModal():o.setAttribute("open","")}};import{JsModal as zo,TabSelector as Lo,ModalHeader as ae,buoyColors as No,night as vt,Search as Uo,TickProvider as wt,windowDragProps as Oo}from"@buoy-gg/shared-ui/web";import{useState as fe,useEffect as xt,useCallback as N,useSyncExternalStore as Ko}from"react";import{assertAccountAccess as Ct,getAccountAccess as Wo,hasAccountAccess as jo,subscribeAccountAccess as Fo}from"@buoy-gg/shared-ui/web";var It=[/\/symbolicate$/,/\/logs$/,/\/debugger-proxy/,/\/reload$/,/\/launch-js-devtools/,/localhost:8081/,/100\.64\.\d+\.\d+:8081/,/10\.0\.\d+\.\d+:8081/,/\.hot-update\./,/__metro/];function Ae(e,t){for(let r of Object.keys(t))r.startsWith("__buoy")&&(e[r]=t[r])}var Mo=class{constructor(){this.isListeningFlag=false;this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.reportHeader=e=>this.shouldInjectHeader(e)?{[this.config.headerKey]:this.config.userId}:null;this.originalFetch=globalThis.fetch.bind(globalThis),this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.config={headerKey:"x-impersonate-user-id",userId:null,ignorePatterns:[...It]}}setConfig(e){this.config={...this.config,...e},e.ignorePatterns&&(this.config.ignorePatterns=[...It,...e.ignorePatterns])}getConfig(){return{...this.config}}shouldInjectHeader(e){return!this.config.userId||this.config.gate&&!this.config.gate()?false:!this.config.ignorePatterns.some(t=>t.test(e))}extractUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}startListening(){if(this.isListeningFlag)return;let e=globalThis.fetch,t=XMLHttpRequest.prototype.open,r=XMLHttpRequest.prototype.send;this.originalFetch=e.bind(globalThis),this.originalXHROpen=t,this.originalXHRSend=r;let n=this,o=async function(c,s){let f=n.extractUrl(c);if(n.shouldInjectHeader(f)){let S=s?.headers??(typeof c=="object"&&"headers"in c?c.headers:void 0),b=new Headers(S);return b.set(n.config.headerKey,n.config.userId),n.originalFetch(c,{...s,headers:b})}return n.originalFetch(c,s)};Ae(o,e),this.patchedFetch=o,globalThis.fetch=this.patchedFetch;let i=function(c,s,f=true,S,b){let C=this;C._impersonateUrl=typeof s=="string"?s:s.href;let I=typeof s=="string"?s:s.toString();return n.originalXHROpen.call(this,c,I,f,S,b)},l=function(c){let s=this;return s._impersonateUrl&&n.shouldInjectHeader(s._impersonateUrl)&&this.setRequestHeader(n.config.headerKey,n.config.userId),n.originalXHRSend.call(this,c)};Ae(i,t),Ae(l,r),this.patchedXHROpen=i,this.patchedXHRSend=l,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend;let p=globalThis,a=p.__buoyHeaderInjectors??(p.__buoyHeaderInjectors=[]);a.includes(this.reportHeader)||a.push(this.reportHeader),this.isListeningFlag=true}stopListening(){if(!this.isListeningFlag)return;this.patchedFetch&&globalThis.fetch===this.patchedFetch&&(globalThis.fetch=this.originalFetch),this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen&&(XMLHttpRequest.prototype.open=this.originalXHROpen),this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend&&(XMLHttpRequest.prototype.send=this.originalXHRSend),this.patchedFetch=null,this.patchedXHROpen=null,this.patchedXHRSend=null;let e=globalThis.__buoyHeaderInjectors,t=e?.indexOf(this.reportHeader)??-1;e&&t>=0&&e.splice(t,1),this.isListeningFlag=false}get isListening(){return this.isListeningFlag}get isImpersonating(){return this.config.userId!==null&&(this.config.gate?.()??true)}},se=null;function O(){return se||(se=new Mo),se}function Vo(){O().startListening()}function $o(){O().stopListening()}function kt(e){O().setConfig(e)}function Xo(){return se?.isImpersonating??false}function Qo(){return se?.getConfig().userId??null}var ie="@buoy/impersonate/state",qo=10,Tt={reactQuery:true,redux:true,asyncStorage:false,mmkv:false},te={isActive:false,isPaused:false,currentUser:null,headerKey:"x-impersonate-user-id",ignorePatterns:[],dataNukeSettings:Tt,showBanner:true,history:[]},He=false,Bt={getItem:e=>{try{return typeof localStorage<"u"?localStorage.getItem(e):null}catch{return null}},setItem:(e,t)=>{try{typeof localStorage<"u"&&localStorage.setItem(e,t)}catch{}},removeItem:e=>{try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}}},_o=class{constructor(){this.state={...te};this.listeners=new Set;this.nukeCallbacks={};this.isInitialized=false;this.asyncStorageRef=null;this.storageReadyPromise=null;this.resolveStorageReady=null;this.developerDefaults=null;this.getSnapshot=()=>this.state;this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));this.remoteHandler=null;this.loadFromStorage(),Promise.resolve().then(()=>{let e=false,t=()=>{let r=Wo().status;r==="admitted"?e=true:r==="locked"&&e&&(e=false,this.disposeAccountSession())};Fo(t),t()}),typeof localStorage<"u"?this.storageReadyPromise=Promise.resolve():this.storageReadyPromise=new Promise(e=>{this.resolveStorageReady=e})}loadFromStorage(){try{let e=Bt.getItem(ie),t=this.getEffectiveDefaults();if(e){let r=JSON.parse(e);this.state={...te,headerKey:r.headerKey??t.headerKey,ignorePatterns:r.ignorePatterns??te.ignorePatterns,dataNukeSettings:{...t.dataNukeSettings,...r.dataNukeSettings},showBanner:r.showBanner??t.showBanner,history:r.history??[],isActive:r.isActive??false,isPaused:r.isPaused??false,currentUser:r.currentUser??null},this.state.isActive&&this.state.currentUser&&this.syncWithListener()}else this.state={...te,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner};this.isInitialized=true}catch{this.isInitialized=true}}setAsyncStorage(e){this.asyncStorageRef=e,this.resolveStorageReady&&(this.resolveStorageReady(),this.resolveStorageReady=null)}setDeveloperDefaults(e){this.developerDefaults=e;let t=this.getEffectiveDefaults();this.isInitialized||(this.state={...this.state,headerKey:t.headerKey,dataNukeSettings:t.dataNukeSettings,showBanner:t.showBanner})}getEffectiveDefaults(){return{headerKey:this.developerDefaults?.headerKey??te.headerKey,dataNukeSettings:{...Tt,...this.developerDefaults?.dataNukeSettings},showBanner:this.developerDefaults?.showBanner??te.showBanner}}getDeveloperDefaults(){return this.developerDefaults}async initializeAsync(e){if(e){this.asyncStorageRef=e;try{let t=await e.getItem(ie);if(console.log("[Buoy]",`[impersonate] initializeAsync read STORAGE_KEY=${ie} stored=${t?t.slice(0,200):"null"}`),t){let r=JSON.parse(t);this.state={...this.state,headerKey:r.headerKey??this.state.headerKey,ignorePatterns:r.ignorePatterns??this.state.ignorePatterns,dataNukeSettings:{...this.state.dataNukeSettings,...r.dataNukeSettings},showBanner:r.showBanner??this.state.showBanner,history:r.history??this.state.history,isActive:r.isActive??this.state.isActive,isPaused:r.isPaused??this.state.isPaused,currentUser:r.currentUser??this.state.currentUser},this.state.isActive&&this.state.currentUser&&this.syncWithListener(),this.notify()}}catch{}}}registerNukeCallbacks(e){this.nukeCallbacks={...this.nukeCallbacks,...e}}getState(){return{...this.state}}setRemoteHandler(e){this.remoteHandler=e}replaceState(e){this.state=e,this.notify()}async startImpersonation(e){if(Ct(),this.remoteHandler){this.remoteHandler("startImpersonation",{user:e});return}let t=[{user:e,lastUsedAt:new Date().toISOString()},...this.state.history.filter(r=>r.user.id!==e.id)].slice(0,qo);this.state={...this.state,isActive:true,currentUser:e,history:t},this.syncWithListener(),this.notify(),await this.executeDataNuke(),await this.persist()}async stopImpersonation(){if(this.remoteHandler){this.remoteHandler("stopImpersonation");return}console.log("[Buoy]",`[impersonate] stopImpersonation: isActive ${this.state.isActive} -> false, listeners=${this.listeners.size}`),this.state={...this.state,isActive:false,isPaused:false,currentUser:null},this.syncWithListener(),this.notify(),await this.executeDataNuke(),await this.persist()}async pauseImpersonation(){if(this.remoteHandler){this.remoteHandler("pauseImpersonation");return}!this.state.isActive||this.state.isPaused||(this.state={...this.state,isPaused:true},this.syncWithListener(),await this.persist(),this.notify())}async resumeImpersonation(){if(Ct(),this.remoteHandler){this.remoteHandler("resumeImpersonation");return}!this.state.isActive||!this.state.isPaused||(this.state={...this.state,isPaused:false},this.syncWithListener(),await this.persist(),this.notify())}async quickSwitch(e){return this.startImpersonation(e)}async updateSettings(e){if(this.remoteHandler){this.remoteHandler("updateSettings",{settings:e});return}this.state={...this.state,headerKey:e.headerKey??this.state.headerKey,ignorePatterns:e.ignorePatterns??this.state.ignorePatterns,showBanner:e.showBanner??this.state.showBanner,dataNukeSettings:e.dataNukeSettings?{...this.state.dataNukeSettings,...e.dataNukeSettings}:this.state.dataNukeSettings},(e.headerKey||e.ignorePatterns)&&this.syncWithListener(),await this.persist(),this.notify()}async removeFromHistory(e){if(this.remoteHandler){this.remoteHandler("removeFromHistory",{userId:e});return}this.state={...this.state,history:this.state.history.filter(t=>t.user.id!==e)},await this.persist(),this.notify()}async clearHistory(){if(this.remoteHandler){this.remoteHandler("clearHistory");return}this.state={...this.state,history:[]},await this.persist(),this.notify()}async executeDataNuke(){if(!He){He=true;try{let{dataNukeSettings:e}=this.state,t=[];e.reactQuery&&this.nukeCallbacks.reactQuery&&t.push(Promise.resolve(this.nukeCallbacks.reactQuery())),e.redux&&this.nukeCallbacks.redux&&t.push(Promise.resolve(this.nukeCallbacks.redux())),e.asyncStorage&&this.nukeCallbacks.asyncStorage&&t.push(Promise.resolve(this.nukeCallbacks.asyncStorage())),e.mmkv&&this.nukeCallbacks.mmkv&&t.push(Promise.resolve(this.nukeCallbacks.mmkv())),await Promise.allSettled(t)}finally{setTimeout(()=>{He=false},100)}}}disposeAccountSession(){this.remoteHandler||!this.state.isActive||(this.state={...this.state,isActive:false,isPaused:false,currentUser:null},this.syncWithListener(),this.notify(),this.persist())}syncWithListener(){let e=this.state.isActive&&!this.state.isPaused;kt({headerKey:this.state.headerKey,userId:e?this.state.currentUser?.id??null:null,ignorePatterns:this.state.ignorePatterns.map(t=>new RegExp(t)),gate:jo}),O().isListening||O().startListening()}async persist(){this.storageReadyPromise&&await this.storageReadyPromise;let e={headerKey:this.state.headerKey,ignorePatterns:this.state.ignorePatterns,dataNukeSettings:this.state.dataNukeSettings,showBanner:this.state.showBanner,history:this.state.history,isActive:this.state.isActive,isPaused:this.state.isPaused,currentUser:this.state.currentUser},t=JSON.stringify(e);try{this.asyncStorageRef?(await this.asyncStorageRef.setItem(ie,t),console.log("[Buoy]",`[impersonate] persist -> AsyncStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)):(Bt.setItem(ie,t),console.log("[Buoy]",`[impersonate] persist -> localStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`))}catch(r){console.warn("[Buoy]","[impersonate] persist failed",r)}}notify(){this.listeners.forEach(e=>{try{e(this.state)}catch{}})}},g=new _o;function Rt(e={}){let[t,r]=fe(""),[n,o]=fe([]),[i,l]=fe(false),[p,a]=fe(null),c=Ko(g.subscribe,g.getSnapshot,g.getSnapshot);xt(()=>{g.registerNukeCallbacks({reactQuery:e.onClearReactQuery,redux:e.onClearRedux,asyncStorage:e.onClearAsyncStorage,mmkv:e.onClearMMKV})},[e.onClearReactQuery,e.onClearRedux,e.onClearAsyncStorage,e.onClearMMKV]),xt(()=>{let v=true;return(async()=>{try{let w=await import("@buoy-gg/shared-ui/web/asyncStorage").then(W=>W.default),G={getItem:W=>w.getItem(W),setItem:(W,Ce)=>w.setItem(W,Ce)};g.setAsyncStorage(G),v&&await g.initializeAsync(G)}catch{}})(),O().isListening||O().startListening(),()=>{v=false}},[]);let s=N(async v=>{if(r(v),a(null),!v.trim()){o([]);return}if(!e.onSearchUsers){a("Search not configured"),o([]);return}l(true);try{let w=await e.onSearchUsers(v);o(w)}catch(w){a(w instanceof Error?w.message:"Search failed"),o([])}finally{l(false)}},[e.onSearchUsers]),f=N(()=>{r(""),o([]),a(null)},[]),S=N(async v=>{await g.startImpersonation(v)},[]),b=N(async()=>{await g.stopImpersonation()},[]),C=N(async v=>{await g.quickSwitch(v)},[]),I=N(async v=>{await g.updateSettings({headerKey:v})},[]),ye=N(async v=>{await g.updateSettings({ignorePatterns:v})},[]),X=N(async v=>{await g.updateSettings({dataNukeSettings:v})},[]),J=N(async v=>{await g.updateSettings({showBanner:v})},[]),K=N(async v=>{await g.removeFromHistory(v)},[]),re=N(async()=>{await g.clearHistory()},[]);return{isActive:c.isActive,currentUser:c.currentUser,headerKey:c.headerKey,ignorePatterns:c.ignorePatterns,dataNukeSettings:c.dataNukeSettings,showBanner:c.showBanner,history:c.history,searchQuery:t,searchResults:n,isSearching:i,searchError:p,searchUsers:s,clearSearch:f,startImpersonation:S,stopImpersonation:b,quickSwitch:C,updateHeaderKey:I,updateIgnorePatterns:ye,updateDataNukeSettings:X,updateShowBanner:J,removeFromHistory:K,clearHistory:re}}import{useCallback as Yo}from"react";import{dispatchToolAction as At,getToolAdapters as Jo}from"@buoy-gg/shared-ui/web";function Go(){let e=!!Jo().query,t=Yo(async()=>{await At("query","clearQueryCache"),await At("query","clearMutationCache")},[]);return{isAvailable:e,error:e?null:"Connect React Query to Buoy or provide onClearReactQuery.",clearCache:e?t:null}}import{useCallback as Zo}from"react";import{dispatchToolAction as en,getToolAdapters as tn}from"@buoy-gg/shared-ui/web";var rn="@@RESET";function on({resetActionType:e=rn}={}){let t=!!tn().redux,r=Zo(async()=>{await en("redux","dispatch",{action:{type:e}})},[e]);return{isAvailable:t,error:t?null:"Connect Redux to Buoy or provide onClearRedux.",resetStore:t?r:null}}import{isDevToolsStorageKey as nn}from"@buoy-gg/shared-ui/web";import{useCallback as an,useMemo as sn,useState as Ht,useEffect as ln}from"react";var Pe=false;function cn(){let[e,t]=Ht(null),[r,n]=Ht(null);ln(()=>{let i=kr();i?(t(i),n(null)):n("@react-native-async-storage/async-storage is not installed")},[]);let o=an(async()=>{if(!Pe){Pe=true;try{if(e){let i=(await e.getAllKeys()).filter(l=>!nn(l));i.length>0&&await e.multiRemove([...i])}}finally{setTimeout(()=>{Pe=false},100)}}},[e]);return sn(()=>!e||r?{isAvailable:false,error:r||"@react-native-async-storage/async-storage is not available",clearStorage:null}:{isAvailable:true,error:null,clearStorage:o},[e,r,o])}import{useCallback as dn}from"react";import{SectionHeader as Ee,EmptyState as un,night as A,Search as hn,AlertTriangle as Pt,Users as pn}from"@buoy-gg/shared-ui/web";import{buoyColors as De,night as D,Play as gn,X as mn,PowerToggleButton as yn,monoFont as fn}from"@buoy-gg/shared-ui/web";import{useMemo as Et}from"react";import{buoyColors as bn,night as Sn}from"@buoy-gg/shared-ui/web";import{jsx as ze,jsxs as vn}from"react/jsx-runtime";var Dt=["#6366F1","#8B5CF6","#EC4899","#F43F5E","#F97316","#EAB308","#22C55E","#14B8A6","#06B6D4","#3B82F6"],wn={small:{container:24,font:10,indicator:8},medium:{container:36,font:14,indicator:10},large:{container:44,font:16,indicator:12}};function xn(e){if(!e)return"?";if(e.includes("@"))return e.charAt(0).toUpperCase();let t=e.trim().split(/\s+/);return t.length===1?t[0].charAt(0).toUpperCase():(t[0].charAt(0)+t[t.length-1].charAt(0)).toUpperCase()}function Cn(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return Dt[Math.abs(t)%Dt.length]}function Le({userId:e,name:t,size:r="medium",showActiveIndicator:n=false,backgroundColor:o}){let i=wn[r],l=Et(()=>o??Cn(e),[e,o]),p=Et(()=>xn(t),[t]);return vn(d,{style:be.wrapper,children:[ze(d,{style:[be.container,{width:i.container,height:i.container,borderRadius:i.container/2,backgroundColor:l}],children:ze(y,{style:[be.initials,{fontSize:i.font}],children:p})}),n&&ze(d,{style:[be.indicator,{width:i.indicator,height:i.indicator,borderRadius:i.indicator/2,right:-1,bottom:-1}]})]})}var be=j.create({wrapper:{position:"relative"},container:{alignItems:"center",justifyContent:"center"},initials:{color:"#FFFFFF",fontWeight:"600",letterSpacing:.5},indicator:{position:"absolute",backgroundColor:bn.success,borderWidth:2,borderColor:Sn.color.surface}});import{jsx as z,jsxs as le}from"react/jsx-runtime";function zt({user:e,isActive:t=false,onPress:r,onStop:n,onRemove:o,showRemoveButton:i=false,lastUsedTime:l,variant:p="default"}){let a=e.displayName||e.email||e.id,c=e.email&&e.displayName,s=typeof e.metadata?.role=="string"?e.metadata.role:null;return le(H,{testID:`buoy-impersonate-user-${e.id}`,style:[R.container,t&&R.activeContainer,p==="compact"&&R.compactContainer],onPress:r,disabled:t,activeOpacity:.7,children:[z(d,{style:R.avatarSection,children:z(Le,{userId:e.id,name:a,size:p==="compact"?"small":"medium",showActiveIndicator:t})}),le(d,{style:R.content,children:[le(d,{style:R.nameRow,children:[z(y,{style:[R.name,t&&R.activeName],numberOfLines:1,children:a}),s?z(d,{style:R.roleBadge,children:z(y,{style:R.roleBadgeText,children:s.toUpperCase()})}):null]}),c&&z(y,{style:R.email,numberOfLines:1,children:e.email}),z(d,{style:R.metadataRow,children:le(y,{style:R.userId,children:["ID: ",e.id]})})]}),le(d,{style:R.actions,children:[t?z(yn,{isEnabled:true,onToggle:n||(()=>{}),accessibilityLabel:"Stop impersonation",testID:`buoy-impersonate-stop-${e.id}`}):z(H,{testID:`buoy-impersonate-start-${e.id}`,style:R.actionButton,onPress:r,activeOpacity:.7,children:z(gn,{size:14,color:D.color.onAccent})}),i&&o&&!t&&z(H,{testID:`buoy-impersonate-remove-${e.id}`,style:R.removeButton,onPress:o,activeOpacity:.7,children:z(mn,{size:12,color:D.color.textTertiary})})]}),l?z(y,{style:R.lastUsed,children:l}):null]})}var R=j.create({container:{flexDirection:"row",alignItems:"center",backgroundColor:D.color.surface,borderRadius:10,borderWidth:1,borderColor:D.color.border,padding:12,gap:12},activeContainer:{backgroundColor:De.success+"10",borderColor:De.success+"40"},compactContainer:{padding:10,gap:10},avatarSection:{flexShrink:0},content:{flex:1,minWidth:0},nameRow:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:2},name:{fontSize:15,fontWeight:"600",color:D.color.text,flexShrink:1},activeName:{color:De.success},roleBadge:{backgroundColor:D.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},roleBadgeText:{fontSize:9,fontWeight:"700",color:D.color.textTertiary,letterSpacing:.5},email:{fontSize:13,color:D.color.textSecondary,marginBottom:4},metadataRow:{flexDirection:"row",alignItems:"center",gap:4},userId:{fontSize:11,color:D.color.textTertiary,fontFamily:fn},lastUsed:{position:"absolute",bottom:8,right:10,fontSize:10,color:D.color.textTertiary},actions:{flexDirection:"row",alignItems:"center",gap:8,flexShrink:0},actionButton:{width:36,height:36,borderRadius:8,backgroundColor:D.color.accent,alignItems:"center",justifyContent:"center"},removeButton:{width:28,height:28,borderRadius:6,backgroundColor:D.color.surfaceElevated,borderWidth:1,borderColor:D.color.border,alignItems:"center",justifyContent:"center"}});import{jsx as k,jsxs as F}from"react/jsx-runtime";function Lt({currentUser:e,searchQuery:t,searchResults:r,isSearching:n,searchError:o,onSelectUser:i,onStopImpersonation:l,searchAvailable:p=true}){let a=dn(({item:c})=>{let s=e?.id===c.id;return k(zt,{user:c,isActive:s,onPress:()=>!s&&i(c),onStop:s?l:void 0})},[e,i,l]);return F(d,{style:B.container,children:[!p&&k(d,{style:B.section,children:F(d,{style:B.warningCard,children:[k(Pt,{size:18,color:A.color.warning}),F(d,{style:B.warningContent,children:[k(y,{style:B.warningTitle,children:"Search Not Available"}),k(y,{style:B.warningText,children:"Configure the onSearchUsers callback to enable user search."})]})]})}),n&&F(d,{style:B.loadingContainer,children:[k(St,{size:"small",color:A.color.accent}),k(y,{style:B.loadingText,children:"Searching users..."})]}),o?k(d,{style:B.section,children:F(d,{style:B.errorCard,children:[k(Pt,{size:16,color:A.color.danger}),k(y,{testID:"buoy-impersonate-error",style:B.errorText,children:o})]})}):null,r.length>0&&F(d,{style:B.resultsSection,children:[F(Ee,{children:[k(Ee.Title,{children:"Results"}),k(Ee.Badge,{count:r.length})]}),k(Te,{testID:"buoy-impersonate-search-scroll",data:r,keyExtractor:c=>c.id,renderItem:a,ItemSeparatorComponent:()=>k(d,{style:B.separator}),contentContainerStyle:B.listContent,showsVerticalScrollIndicator:false})]}),!!t&&!n&&r.length===0&&!o&&F(d,{testID:"buoy-impersonate-no-results",style:B.emptyStateContainer,children:[k(d,{style:B.emptyStateIcon,children:k(pn,{size:28,color:A.color.textTertiary})}),k(y,{style:B.emptyStateTitle,children:"No users found"}),F(y,{style:B.emptyStateDescription,children:['No results for "',t,'"']}),k(y,{style:B.emptyStateHint,children:"Try a different search term"})]}),!t&&r.length===0&&!n&&p&&k(d,{testID:"buoy-impersonate-search-empty",children:k(un,{title:"Search for users",description:"Tap the search icon in the header to find users by email, name, or ID",icon:hn,variant:"minimal"})})]})}var B=j.create({container:{flex:1},section:{padding:16,paddingBottom:8},loadingContainer:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:10,paddingVertical:20},loadingText:{fontSize:13,color:A.color.textSecondary},resultsSection:{flex:1,paddingHorizontal:16},listContent:{paddingBottom:16},separator:{height:8},warningCard:{flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:A.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:A.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:14,fontWeight:"600",color:A.color.warning,marginBottom:4},warningText:{fontSize:13,color:A.color.textSecondary,lineHeight:18},errorCard:{flexDirection:"row",alignItems:"center",gap:10,backgroundColor:A.color.dangerSoft,borderRadius:10,borderWidth:1,borderColor:A.color.danger+"25",padding:12},errorText:{flex:1,fontSize:13,color:A.color.danger},emptyStateContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyStateIcon:{width:56,height:56,borderRadius:28,backgroundColor:A.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyStateTitle:{fontSize:16,fontWeight:"600",color:A.color.text,marginBottom:6},emptyStateDescription:{fontSize:14,color:A.color.textSecondary,textAlign:"center",marginBottom:8},emptyStateHint:{fontSize:12,color:A.color.textTertiary}});import{useCallback as In}from"react";import{night as Q,Trash2 as kn,useRelativeTime as Tn,ToolEmptyState as Bn}from"@buoy-gg/shared-ui/web";import{jsx as U,jsxs as Nt}from"react/jsx-runtime";function Rn({item:e,isActive:t,onSelect:r,onStop:n,onRemove:o,showRemoveButton:i}){let l=Tn(new Date(e.lastUsedAt));return U(zt,{user:e.user,isActive:t,onPress:()=>!t&&r(e.user),onStop:t?n:void 0,onRemove:o,showRemoveButton:i,lastUsedTime:l})}function Ut({history:e,currentUserId:t,onSelectUser:r,onStopImpersonation:n,onRemoveFromHistory:o,onClearHistory:i}){let l=In(({item:p})=>{let a=t===p.user.id;return U(Rn,{item:p,isActive:a,onSelect:r,onStop:n,onRemove:o?()=>o(p.user.id):void 0,showRemoveButton:!!o})},[t,r,n,o]);return e.length===0?U(Bn,{testID:"buoy-impersonate-history-empty",otto:"disguise",title:"No History",message:"Users you impersonate will appear here for quick access"}):Nt(d,{style:M.container,children:[Nt(d,{style:M.headerRow,children:[U(y,{style:M.headerTitle,children:"Recent"}),U(d,{style:M.headerBadge,children:U(y,{style:M.headerBadgeText,children:e.length})}),U(d,{style:M.headerSpacer}),i&&U(H,{testID:"buoy-impersonate-clear-history",style:M.clearButton,onPress:i,activeOpacity:.7,children:U(kn,{size:12,color:Q.color.textTertiary})})]}),U(Te,{testID:"buoy-impersonate-history-scroll",data:e,keyExtractor:p=>p.user.id,renderItem:l,ItemSeparatorComponent:()=>U(d,{style:M.separator}),contentContainerStyle:M.listContent,showsVerticalScrollIndicator:false})]})}var M=j.create({container:{flex:1,paddingHorizontal:16},headerRow:{flexDirection:"row",alignItems:"center",paddingVertical:10,gap:8},headerTitle:{fontSize:12,fontWeight:"600",color:Q.color.textTertiary,textTransform:"uppercase",letterSpacing:.5},headerBadge:{backgroundColor:Q.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},headerBadgeText:{fontSize:10,fontWeight:"600",color:Q.color.textTertiary},headerSpacer:{flex:1},clearButton:{width:24,height:24,alignItems:"center",justifyContent:"center",backgroundColor:Q.color.surfaceElevated,borderRadius:4},listContent:{paddingBottom:20},separator:{height:8},emptyContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyIcon:{width:56,height:56,borderRadius:28,backgroundColor:Q.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyTitle:{fontSize:16,fontWeight:"600",color:Q.color.text,marginBottom:6},emptyDescription:{fontSize:14,color:Q.color.textSecondary,textAlign:"center"}});import{useState as Se,useEffect as Ne,useMemo as Ue}from"react";import{CollapsibleSection as ce,buoyColors as de,night as m,Settings as An,AlertTriangle as Ot,Info as Hn,Zap as Pn,RefreshCw as En,Check as Oe,X as Kt,Copy as Wt,Eye as Dn,copyToClipboard as zn,ToggleRow as Ln,monoFont as Ke}from"@buoy-gg/shared-ui/web";import{DataViewer as Nn}from"@buoy-gg/shared-ui/web/dataViewer";import{Fragment as We,jsx as h,jsxs as x}from"react/jsx-runtime";var ue="x-impersonate-user-id",je=true,he={reactQuery:true,redux:true,asyncStorage:false,mmkv:false};function pe({label:e,description:t,value:r,onChange:n,recommended:o,dangerous:i,detected:l,testID:p}){let a=x(We,{children:[l!==void 0&&x(d,{style:[u.detectedBadge,l?u.detectedBadgeActive:u.detectedBadgeInactive],children:[l?h(Oe,{size:10,color:de.success}):h(Kt,{size:10,color:m.color.textTertiary}),h(y,{style:[u.detectedText,l?u.detectedTextActive:u.detectedTextInactive],children:l?"Detected":"Not Detected"})]}),o&&l!==false&&x(d,{style:u.recommendedBadge,children:[h(Pn,{size:10,color:m.color.accent}),h(y,{style:u.recommendedText,children:"Recommended"})]})]});return h(Ln,{variant:"plain",label:e,description:t,value:r,onValueChange:n,tone:i?"warning":"accent",emphasizeLabel:i,accessory:a,testID:p})}function jt({headerKey:e,settings:t,showBanner:r,onSave:n,onShowBannerChange:o,detectionStatus:i}){let[l,p]=Se(e),[a,c]=Se(t),[s,f]=Se(r),[S,b]=Se(false);Ne(()=>{p(e)},[e]),Ne(()=>{c(t)},[t]),Ne(()=>{f(r)},[r]);let C=Ue(()=>l!==e||a.reactQuery!==t.reactQuery||a.redux!==t.redux||a.asyncStorage!==t.asyncStorage||a.mmkv!==t.mmkv,[l,a,e,t]),I=Ue(()=>l===ue&&s===je&&a.reactQuery===he.reactQuery&&a.redux===he.redux&&a.asyncStorage===he.asyncStorage&&a.mmkv===he.mmkv,[l,s,a]),ye=()=>{n(l.trim()||ue,a,s)},X=()=>{p(e),c(t),f(r)},J=()=>{p(ue),c(he),f(je),o(je)},K=(w,G)=>{c(W=>({...W,[w]:G}))},re=Ue(()=>({defaults:{headerKey:l,showBanner:s,dataNukeSettings:{reactQuery:a.reactQuery,redux:a.redux,asyncStorage:a.asyncStorage,mmkv:a.mmkv}}}),[l,s,a]),v=async()=>{let w=`defaults: {
|
|
2
2
|
headerKey: '${l}',
|
|
3
3
|
showBanner: ${s},
|
|
4
4
|
dataNukeSettings: {
|
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
asyncStorage: ${a.asyncStorage},
|
|
8
8
|
mmkv: ${a.mmkv},
|
|
9
9
|
},
|
|
10
|
-
},`;try{await Rn(v),f(true),setTimeout(()=>f(false),2e3)}catch{}};return w(pt,{testID:"buoy-impersonate-settings-scroll",style:u.container,contentContainerStyle:u.contentContainer,children:[x&&p(c,{style:u.actionBar,children:w(c,{style:u.actionBarContent,children:[p(y,{style:u.unsavedText,children:"Unsaved changes"}),w(c,{style:u.actionButtons,children:[w(H,{testID:"buoy-impersonate-discard",style:u.discardButton,onPress:X,children:[p(Lt,{size:14,color:m.color.textSecondary}),p(y,{style:u.discardButtonText,children:"Discard"})]}),w(H,{testID:"buoy-impersonate-save",style:u.saveButton,onPress:ge,children:[p(Le,{size:14,color:m.color.onAccent}),p(y,{style:u.saveButtonText,children:"Save"})]})]})]})}),p(ie,{title:"Header Configuration",icon:xn,defaultOpen:true,variant:"bordered",children:w(c,{style:u.sectionContent,children:[p(y,{style:u.inputLabel,children:"Header Key"}),p(ht,{testID:"buoy-impersonate-header-key",style:u.input,value:l,onChangeText:h,placeholder:"x-impersonate-user-id",placeholderTextColor:m.color.placeholder,autoCapitalize:"none",autoCorrect:false}),w(c,{style:u.inputFooter,children:[p(y,{style:u.helperText,children:"The HTTP header key used for impersonation. Value will be the user ID."}),l!==ce&&p(H,{onPress:()=>h(ce),style:u.resetLink,children:p(y,{style:u.resetLinkText,children:"Reset to default"})})]})]})}),p(ie,{title:"Display",icon:Bn,defaultOpen:true,variant:"bordered",children:p(c,{style:u.sectionContent,children:p(c,{style:u.togglesCard,children:p(ue,{label:"Floating Banner",description:"Show a floating banner when impersonation is active",value:s,onChange:v=>{b(v),o(v)},recommended:true,testID:"buoy-impersonate-show-banner"})})})}),p(ie,{title:"Data Clearing",icon:Et,defaultOpen:true,variant:"bordered",children:w(c,{style:u.sectionContent,children:[p(y,{style:u.sectionDescription,children:"Choose what data to clear when impersonation starts or stops. This ensures you see fresh data for the impersonated user."}),w(c,{style:u.togglesCard,children:[p(ue,{label:"React Query",description:"Clear query cache and cancel pending queries",value:a.reactQuery,onChange:v=>K("reactQuery",v),recommended:true,detected:i?.reactQuery}),p(c,{style:u.divider}),p(ue,{label:"Redux",description:"Reset Redux store to initial state",value:a.redux,onChange:v=>K("redux",v),recommended:true,detected:i?.redux})]}),w(c,{style:u.advancedSection,children:[p(y,{style:u.advancedLabel,children:"Storage Options"}),w(c,{style:[u.togglesCard,u.dangerousCard],children:[p(ue,{label:"AsyncStorage",description:"Clear app data (preserves @buoy/* keys)",value:a.asyncStorage,onChange:v=>K("asyncStorage",v),dangerous:true,detected:i?.asyncStorage}),p(c,{style:u.divider}),p(ue,{label:"MMKV",description:"Clear MMKV storage (preserves @buoy/* keys)",value:a.mmkv,onChange:v=>K("mmkv",v),dangerous:true,detected:i?.mmkv})]})]}),(a.asyncStorage||a.mmkv)&&w(c,{style:u.warningCard,children:[p(Et,{size:16,color:m.color.warning}),w(c,{style:u.warningContent,children:[p(y,{style:u.warningTitle,children:"Storage Clearing Enabled"}),p(y,{style:u.warningText,children:"This will remove app data like settings and cached content. Auth tokens managed by @buoy/* are preserved."})]})]})]})}),!I&&w(H,{testID:"buoy-impersonate-restore-defaults",style:u.restoreButton,onPress:Y,children:[p(Tn,{size:14,color:m.color.textSecondary}),p(y,{style:u.restoreButtonText,children:"Restore Defaults"})]}),p(ie,{title:"How It Works",icon:In,defaultOpen:false,variant:"bordered",children:w(c,{style:u.sectionContent,children:[p(y,{style:u.infoText,children:"When impersonation is enabled, the configured header is automatically added to all outgoing fetch and XMLHttpRequest calls."}),p(y,{style:[u.infoText,u.infoTextSpaced],children:"Your backend should check for this header and return data for the specified user ID instead of the authenticated user."}),w(c,{style:u.codeBlock,children:[p(y,{style:u.codeComment,children:"// Example request header"}),w(y,{style:u.codeText,children:[l||"x-impersonate-user-id",": ",p(y,{style:u.codeValue,children:"user_123"})]})]})]})}),p(ie,{title:"Export Configuration",icon:Nt,defaultOpen:false,variant:"bordered",children:w(c,{style:u.sectionContent,children:[p(y,{style:u.infoText,children:"Copy current settings to use in createImpersonateTool()."}),p(c,{style:u.dataViewerContainer,children:p(Hn,{title:"",data:ee,showTypeFilter:true,rawMode:true,initialExpanded:true})}),p(H,{style:u.copyButton,onPress:S,children:C?w(Ue,{children:[p(Le,{size:14,color:le.success}),p(y,{style:[u.copyButtonText,u.copySuccessText],children:"Copied!"})]}):w(Ue,{children:[p(Nt,{size:14,color:m.color.accent}),p(y,{style:u.copyButtonText,children:"Copy Config"})]})})]})})]})}var u=F.create({container:{flex:1},contentContainer:{padding:16,gap:12,paddingBottom:32},actionBar:{backgroundColor:m.color.accentSoft,borderRadius:10,borderWidth:1,borderColor:m.color.accentBorder,padding:12},actionBarContent:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},unsavedText:{fontSize:13,fontWeight:"500",color:m.color.accent},actionButtons:{flexDirection:"row",gap:8},saveButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:m.color.accent,paddingHorizontal:14,paddingVertical:8,borderRadius:6},saveButtonText:{fontSize:13,fontWeight:"600",color:m.color.onAccent},discardButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:m.color.surfaceElevated,paddingHorizontal:14,paddingVertical:8,borderRadius:6,borderWidth:1,borderColor:m.color.border},discardButtonText:{fontSize:13,fontWeight:"500",color:m.color.textSecondary},restoreButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,paddingVertical:12,borderRadius:8,borderWidth:1,borderColor:m.color.border,borderStyle:"dashed"},restoreButtonText:{fontSize:13,color:m.color.textSecondary},sectionContent:{paddingTop:8},sectionDescription:{fontSize:13,color:m.color.textSecondary,lineHeight:18,marginBottom:14},togglesCard:{backgroundColor:m.color.surface,borderRadius:10,borderWidth:1,borderColor:m.color.border,padding:4},dangerousCard:{borderColor:m.color.warning+"30"},advancedSection:{marginTop:16},advancedLabel:{fontSize:11,fontWeight:"600",color:m.color.textTertiary,textTransform:"uppercase",letterSpacing:.5,marginBottom:8,marginLeft:2},inputLabel:{fontSize:12,fontWeight:"600",color:m.color.textSecondary,marginBottom:8},input:{height:42,backgroundColor:m.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:m.color.border,paddingHorizontal:14,fontSize:14,color:m.color.text,fontFamily:Ne},inputFooter:{flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start",marginTop:8,gap:12},helperText:{flex:1,fontSize:12,color:m.color.textTertiary,lineHeight:16},resetLink:{paddingVertical:2},resetLinkText:{fontSize:12,color:m.color.accent,fontWeight:"500"},recommendedBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:m.color.accentSoft,paddingHorizontal:8,paddingVertical:3,borderRadius:4},recommendedText:{fontSize:10,fontWeight:"600",color:m.color.accent},detectedBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:8,paddingVertical:3,borderRadius:4},detectedBadgeActive:{backgroundColor:le.success+"15"},detectedBadgeInactive:{backgroundColor:m.color.textTertiary+"15"},detectedText:{fontSize:10,fontWeight:"600"},detectedTextActive:{color:le.success},detectedTextInactive:{color:m.color.textTertiary},divider:{height:1,backgroundColor:m.color.separator,marginHorizontal:12},warningCard:{marginTop:14,flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:m.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:m.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:13,fontWeight:"600",color:m.color.warning,marginBottom:4},warningText:{fontSize:12,color:m.color.textSecondary,lineHeight:17},infoText:{fontSize:13,color:m.color.textSecondary,lineHeight:19},infoTextSpaced:{marginTop:10},codeBlock:{marginTop:14,backgroundColor:m.color.bg,borderRadius:8,padding:14},codeComment:{fontSize:12,color:m.color.textTertiary,fontFamily:Ne,marginBottom:6},codeText:{fontSize:13,color:m.color.text,fontFamily:Ne},codeValue:{color:m.color.accent},dataViewerContainer:{marginTop:12,borderRadius:8,overflow:"hidden",borderWidth:1,borderColor:m.color.border},copyButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,marginTop:14,backgroundColor:m.color.accentSoft,paddingVertical:10,paddingHorizontal:16,borderRadius:8,borderWidth:1,borderColor:m.color.accentBorder},copyButtonText:{fontSize:13,fontWeight:"600",color:m.color.accent},copySuccessText:{color:le.success}});import{jsx as P,jsxs as Ke}from"react/jsx-runtime";var Pn=Ro,Dn=[{key:"search",label:"Search"},{key:"history",label:"History"},{key:"settings",label:"Settings"}],zn=[{key:"search",label:"Search"},{key:"history",label:"History"}];function We({visible:e,onClose:t,onBack:r,onMinimize:n,onSearchUsers:o,onClearReactQuery:i,onClearRedux:l,onClearAsyncStorage:h,onClearMMKV:a,showSettingsTab:d=true,inline:s=false}){let b=d?Dn:zn,[C,f]=xe("search"),[x,I]=xe(false),ge=st(false),[X,Y]=xe(""),K=st(null),{clearCache:ee,isAvailable:S}=Xo(),{resetStore:v,isAvailable:G}=Yo(),{clearStorage:W,isAvailable:we}=rn(),Qt=i??ee??void 0,qt=l??v??void 0,_t=h??W??void 0,Jt={reactQuery:!!i||S,redux:!!l||G,asyncStorage:!!h||we,mmkv:!!a},{isActive:Yt,currentUser:qe,headerKey:Gt,dataNukeSettings:Zt,showBanner:er,searchQuery:tr,searchResults:rr,isSearching:or,searchError:nr,searchUsers:_e,startImpersonation:Je,stopImpersonation:Ye,updateHeaderKey:Ge,updateDataNukeSettings:Ze,updateShowBanner:Ce,history:ar,removeFromHistory:sr,clearHistory:ir}=It({onSearchUsers:o,onClearReactQuery:Qt,onClearRedux:qt,onClearAsyncStorage:_t,onClearMMKV:a});it(()=>{x&&K.current&&setTimeout(()=>{K.current?.focus()},100)},[x]),it(()=>{!d&&C==="settings"&&f("search")},[d,C]);let lr=te(_=>{Y(_)},[]),cr=te(()=>{X.trim()&&_e(X.trim()),I(false)},[X,_e]),et=te(async _=>{await Je(_)},[Je]),dr=te(async(_,hr,pr)=>{await Ge(_),await Ze(hr),await Ce(pr)},[Ge,Ze,Ce]),ur=te(_=>{f(_),I(false)},[]),tt=()=>Ke(oe,{children:[r&&P(oe.Navigation,{onBack:r}),P(oe.Content,{title:"",children:x?P(oe.Search,{value:X,onChangeText:lr,onCancel:()=>{Y(""),I(false)},onDismiss:()=>I(false),dismissOnBlur:true,placeholder:"Search by email, name, or ID...",iconSize:14,testID:"buoy-impersonate-search-input",inputProps:{onSubmitEditing:cr}}):P(Ao,{tabs:b,activeTab:C,onTabChange:ur,testIDPrefix:"buoy-impersonate-tab"})}),P(oe.Actions,{children:C==="search"&&!x&&P(H,{testID:"buoy-impersonate-search-toggle",onPress:()=>I(true),style:be.headerActionButton,children:P(Po,{size:14,color:yt.color.textSecondary})})})]});if(!e)return null;let rt=Ke(c,{style:be.container,children:[C==="search"&&P(Pt,{currentUser:qe,isActive:Yt,searchQuery:tr,searchResults:rr,isSearching:or,searchError:nr,onSelectUser:et,onStopImpersonation:Ye,searchAvailable:!!o}),C==="history"&&P(zt,{history:ar,currentUserId:qe?.id??null,onSelectUser:et,onStopImpersonation:Ye,onRemoveFromHistory:sr,onClearHistory:ir}),C==="settings"&&P(Ut,{headerKey:Gt,settings:Zt,showBanner:er,onSave:dr,onShowBannerChange:Ce,detectionStatus:Jt})]});return s?P(ft,{children:Ke(c,{style:be.inlineRoot,children:[P(c,{style:be.inlineHeader,...Do,children:tt()}),rt]})}):P(ft,{children:P(Pn,{visible:e,onClose:t,onMinimize:n,header:{showToggleButton:true,customContent:tt()},enablePersistence:true,initialMode:"bottomSheet",disableScrollWrapper:true,children:rt})})}function En(e){return P(We,{...e,inline:true,visible:true,onClose:()=>{}})}var be=F.create({inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:Ho.border,backgroundColor:"transparent"},container:{flex:1},headerActionButton:{width:28,height:28,borderRadius:6,backgroundColor:yt.color.buttonSurface,justifyContent:"center",alignItems:"center"}});import{useSyncExternalStore as Ot}from"react";import{buoyColors as Se,X as Ln,PowerToggleButton as Nn}from"@buoy-gg/shared-ui/web";import{jsx as q,jsxs as Fe}from"react/jsx-runtime";function Me({onPress:e,onStopPress:t,position:r="top",offset:n=50}){let o=Ot(g.subscribe,g.getSnapshot,g.getSnapshot);if(!o.isActive||!o.currentUser||!o.showBanner)return null;let i=async()=>{console.log("[Buoy]","[impersonate] banner pause/resume pressed"),o.isPaused?await g.resumeImpersonation():await g.pauseImpersonation()},l=o.currentUser.displayName||o.currentUser.email||o.currentUser.id,h=r==="top"?{top:n}:{bottom:n},a=async()=>{console.log("[Buoy]","[impersonate] banner STOP pressed"),await g.stopImpersonation()};return q(c,{style:[V.container,h],children:Fe(c,{testID:"buoy-impersonate-banner",style:V.banner,children:[Fe(H,{testID:"buoy-impersonate-banner-open",style:V.userSection,onPress:e,activeOpacity:.7,children:[q(De,{userId:o.currentUser.id,name:l,size:"small",showActiveIndicator:false}),q(y,{style:[V.userName,o.isPaused&&V.userNamePaused],numberOfLines:1,children:l})]}),q(Nn,{isEnabled:!o.isPaused,onToggle:i,size:"small",accessibilityLabel:"Toggle impersonation",testID:"buoy-impersonate-banner-toggle"}),q(H,{testID:"buoy-impersonate-banner-stop",accessibilityLabel:"Stop impersonating",style:V.closeButton,onPress:a,activeOpacity:.7,children:q(Ln,{size:12,color:"rgba(255, 255, 255, 0.5)"})})]})})}function Un({onPress:e}){let t=Ot(g.subscribe,g.getSnapshot,g.getSnapshot);return!t.isActive||!t.currentUser?null:Fe(H,{style:V.minimalBanner,onPress:e,activeOpacity:.8,children:[q(c,{style:V.minimalDot}),q(y,{style:V.minimalText,children:"IMP"})]})}var V=F.create({container:{position:"absolute",left:0,right:0,alignItems:"center",zIndex:9999,pointerEvents:"box-none"},banner:{flexDirection:"row",alignItems:"center",backgroundColor:"rgba(20, 20, 20, 0.94)",borderWidth:1,borderColor:Se.success+"40",borderRadius:22,paddingVertical:7,paddingLeft:7,paddingRight:10,gap:10,marginTop:3,shadowColor:"#000",shadowOffset:{width:0,height:6},shadowOpacity:.3,shadowRadius:14,elevation:10},userSection:{flexDirection:"row",alignItems:"center",gap:10},userName:{fontSize:14,fontWeight:"600",color:"#fff",maxWidth:180},userNamePaused:{opacity:.6},closeButton:{width:22,height:22,borderRadius:11,backgroundColor:"rgba(128, 128, 128, 0.16)",alignItems:"center",justifyContent:"center",marginLeft:-4},minimalBanner:{position:"absolute",top:60,right:16,flexDirection:"row",alignItems:"center",backgroundColor:"rgba(26, 26, 26, 0.92)",borderWidth:1,borderColor:Se.success+"35",borderRadius:12,paddingVertical:5,paddingHorizontal:10,gap:5,zIndex:9999,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.2,shadowRadius:6,elevation:4},minimalDot:{width:6,height:6,borderRadius:3,backgroundColor:Se.success},minimalText:{fontSize:10,fontWeight:"700",color:Se.success,letterSpacing:.5}});import{hasAccountAccess as On,isOverWireBudget as Kn}from"@buoy-gg/shared-ui/web";var je=null;function Wn(e){je=e}var Ve=2*1024,Fn=16*1024,Kt=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function Mn(e){if(!e)return e;if(e.startsWith("data:")){let t=e.indexOf(",");return`${t>=0?e.slice(0,Math.min(t+1,64)):"data:"}[${e.length} chars]`}return e.length<=Ve?e:`${e.slice(0,Ve)}\u2026 [${e.length-Ve} more]`}function jn(e){if(!e)return e;let t=typeof e.role=="string"?e.role:void 0;return Kn(e,Fn)?t?{role:t,...Kt}:{...Kt}:e}function $e(e){return{...e,avatarUrl:Mn(e.avatarUrl),metadata:jn(e.metadata)}}function Wt(e){return{...e,currentUser:e.currentUser?$e(e.currentUser):null,history:e.history.map(t=>({...t,user:$e(t.user)}))}}var Xe=new Map;function Ft(e){for(let t of e)t&&typeof t=="object"&&t.id&&Xe.set(String(t.id),t)}function Vn(e){let t=Xe.get(e);if(t)return t;let r=g.getState();return r.currentUser?.id===e?r.currentUser:r.history.find(n=>n.user.id===e)?.user}function Mt(e){if(!e||typeof e!="object"||!e.id)return false;if(Xe.has(String(e.id)))return true;let t=g.getState();return t.currentUser?.id===e.id?true:t.history.some(r=>r.user.id===e.id)}async function $n(e,t){let r=T(t.userId),n=r??T(t.user?.id),o=(T(t.email)??T(t.user?.email))?.toLowerCase(),i=[T(t.user?.name),T(t.user?.displayName),T(t.query)].map(f=>f?.toLowerCase()).filter(f=>!!f),l=[o,n,T(t.query),T(t.user?.name),T(t.user?.displayName)].filter((f,x,I)=>!!f&&I.indexOf(f)===x),h=new Map;for(let f of l){let x;try{x=await e(f)}catch{continue}if(Array.isArray(x)){Ft(x);for(let I of x)I?.id&&h.set(String(I.id),I)}}let a=[...h.values()],d=f=>T(f.email)?.toLowerCase(),s=n?a.filter(f=>String(f.id)===n):[],b=o?a.filter(f=>d(f)===o):[];if(s.length===1&&b.length&&b[0].id!==s[0].id)throw new Error(`The id ${n} and the email ${o} belong to different users. Pass one of them.`);if(s.length===1)return s[0];if(r)return;if(b.length===1)return b[0];if(n||o)return;let C=a.filter(f=>{let x=f;return[T(x.displayName),T(x.name)].some(I=>I&&i.includes(I.toLowerCase()))});if(C.length>1)throw new Error(`${C.length} users are named that (${C.map(f=>f.id).join(", ")}). Pass the user's id or email.`);return C[0]}function T(e){return typeof e=="string"&&e.trim()?e.trim():typeof e=="number"?String(e):void 0}function jt(e){return{searchUsers:async t=>{let r=String(t?.query??""),n=await e(r);return Array.isArray(n)&&Ft(n),Array.isArray(n)?n.map($e):n},startImpersonation:async t=>{let r=t??{},n=r.user,o=T(r.userId),i=T(n?.id);if(o&&i&&o!==i)throw new Error(`userId ${o} and user.id ${i} are different users. Pass one of them.`);let l=T(r.email)?.toLowerCase(),h=T(n?.email)?.toLowerCase();if(l&&h&&l!==h)throw new Error(`email ${l} and user.email ${h} are different users. Pass one of them.`);let a;if(n?.id&&Mt(n)&&r.userId===void 0&&r.email===void 0?a=Vn(String(n.id)):a=await $n(e,r),!a||!Mt(a))throw new Error("That user isn't in this app's directory. Call searchUsers and impersonate one of its results \u2014 a user object that didn't come from search impersonates nobody.");let d=(T(r.email)??T(n?.email))?.toLowerCase(),s=T(a.email)?.toLowerCase();if(d&&s&&d!==s)throw new Error(`User ${a.id} has a different email than ${d}. Pass the id or the email of one user.`);return await g.startImpersonation(a),{ok:true,userId:a.id}},stopImpersonation:()=>g.stopImpersonation(),pauseImpersonation:()=>g.pauseImpersonation(),resumeImpersonation:()=>g.resumeImpersonation(),updateSettings:t=>{let r=t??{},n=r.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in r)?r:void 0);if(!n)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return g.updateSettings(n)},removeFromHistory:t=>g.removeFromHistory(t.userId),clearHistory:()=>g.clearHistory()}}function Xn({onSearchUsers:e}){return{version:1,getSnapshot:()=>Wt(g.getState()),subscribe:t=>g.subscribe(t),actions:jt(e)}}var Qn={dispose:()=>{On()||g.disposeAccountSession()},version:1,getSnapshot:()=>Wt(g.getState()),subscribe:e=>g.subscribe(e),actions:jt(e=>{if(!je)throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()");return je(e)})};import{ImpersonateIcon as Vt,IMPERSONATE_ICON_COLOR as qn}from"@buoy-gg/shared-ui/web";import{jsx as $t}from"react/jsx-runtime";var Xt=false;async function _n(){if(!(typeof window>"u"||Xt)){Xt=true,console.log("[Buoy]","[impersonate] bootstrap: start"),O().isListening||O().startListening();try{let e=vr();if(!e||typeof e.getItem!="function"){console.warn("[Buoy]","[impersonate] bootstrap: AsyncStorage shape unexpected",Object.keys(e??{}));return}let t={getItem:r=>e.getItem(r),setItem:(r,n)=>e.setItem(r,n)};g.setAsyncStorage(t),console.log("[Buoy]","[impersonate] bootstrap: AsyncStorage adapter installed"),await g.initializeAsync(t),console.log("[Buoy]","[impersonate] bootstrap: initializeAsync done")}catch(e){console.warn("[Buoy]","[impersonate] bootstrap: failed",e)}}}function Jn(e){let{id:t="impersonate",name:r="IMPERSONATE",description:n="User impersonation for admin testing",defaults:o,showSettingsTab:i=true,onSearchUsers:l,onClearReactQuery:h,onClearRedux:a,onClearAsyncStorage:d,onClearMMKV:s}=e;return o&&g.setDeveloperDefaults(o),Wn(l??null),_n(),{id:t,name:r,description:n,slot:"both",icon:({size:b,slot:C})=>$t(Vt,{size:C==="dial"?b*1.5:b,color:qn}),component:b=>$t(We,{...b,onSearchUsers:l,onClearReactQuery:h,onClearRedux:a,onClearAsyncStorage:d,onClearMMKV:s,showSettingsTab:i}),props:{enableSharedModalDimensions:false},Banner:Me}}import{jsx as Yn}from"react/jsx-runtime";function Gn(){return Yn(Me,{position:"top",offset:50})}import{buoyColors as he,night as pe,X as Zn}from"@buoy-gg/shared-ui/web";import{jsx as J,jsxs as ve}from"react/jsx-runtime";function ea({user:e,onStopImpersonation:t}){let r=e.displayName||e.email||e.id;return ve(c,{style:$.container,children:[ve(c,{style:$.userSection,children:[J(De,{userId:e.id,name:r,size:"small",showActiveIndicator:false}),J(c,{style:$.userInfo,children:J(y,{style:$.userName,numberOfLines:1,children:r})})]}),ve(c,{style:$.statusPill,children:[J(c,{style:$.pulseDot}),J(y,{style:$.statusText,children:"Active"})]}),ve(H,{style:$.stopButton,onPress:t,activeOpacity:.7,children:[J(Zn,{size:12,color:pe.color.danger}),J(y,{style:$.stopButtonText,children:"Stop"})]})]})}var $=F.create({container:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:10,paddingHorizontal:16,backgroundColor:he.success+"10",borderBottomWidth:1,borderBottomColor:he.success+"25",gap:12},userSection:{flexDirection:"row",alignItems:"center",flex:1,gap:10,minWidth:0},userInfo:{flex:1,minWidth:0},userName:{fontSize:14,fontWeight:"600",color:pe.color.text},statusPill:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:he.success+"20",paddingHorizontal:10,paddingVertical:5,borderRadius:12},pulseDot:{width:6,height:6,borderRadius:3,backgroundColor:he.success},statusText:{fontSize:11,fontWeight:"600",color:he.success,textTransform:"uppercase",letterSpacing:.5},stopButton:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:12,paddingVertical:6,backgroundColor:pe.color.dangerSoft,borderRadius:6,borderWidth:1,borderColor:pe.color.danger+"30"},stopButtonText:{fontSize:12,fontWeight:"600",color:pe.color.danger}});import{useCallback as Qe,useSyncExternalStore as ta}from"react";function ra(){let e=ta(g.subscribe,g.getSnapshot,g.getSnapshot),t=Qe(async o=>{await g.quickSwitch(o)},[]),r=Qe(async o=>{await g.removeFromHistory(o)},[]),n=Qe(async()=>{await g.clearHistory()},[]);return{history:e.history,currentUserId:e.currentUser?.id??null,quickSwitch:t,removeFromHistory:r,clearHistory:n}}export{Ut as DataNukeSettingsComponent,Me as ImpersonateBanner,Un as ImpersonateBannerMinimal,zt as ImpersonateHistoryList,Vt as ImpersonateIcon,We as ImpersonateModal,Gn as ImpersonateOverlay,ea as ImpersonateStatusBar,En as ImpersonateToolView,Pt as UserSearchView,Xn as createImpersonateSyncAdapter,Jn as createImpersonateTool,Fo as getImpersonatedUserId,O as impersonateListener,g as impersonateStore,Qn as impersonateSyncAdapter,Wo as isImpersonating,wt as setImpersonateConfig,Oo as startImpersonateListener,Ko as stopImpersonateListener,It as useImpersonate,ra as useImpersonateHistory};
|
|
10
|
+
},`;try{await zn(w),b(true),setTimeout(()=>b(false),2e3)}catch{}};return x(ft,{testID:"buoy-impersonate-settings-scroll",style:u.container,contentContainerStyle:u.contentContainer,children:[C&&h(d,{style:u.actionBar,children:x(d,{style:u.actionBarContent,children:[h(y,{style:u.unsavedText,children:"Unsaved changes"}),x(d,{style:u.actionButtons,children:[x(H,{testID:"buoy-impersonate-discard",style:u.discardButton,onPress:X,children:[h(Kt,{size:14,color:m.color.textSecondary}),h(y,{style:u.discardButtonText,children:"Discard"})]}),x(H,{testID:"buoy-impersonate-save",style:u.saveButton,onPress:ye,children:[h(Oe,{size:14,color:m.color.onAccent}),h(y,{style:u.saveButtonText,children:"Save"})]})]})]})}),h(ce,{title:"Header Configuration",icon:An,defaultOpen:true,variant:"bordered",children:x(d,{style:u.sectionContent,children:[h(y,{style:u.inputLabel,children:"Header Key"}),h(yt,{testID:"buoy-impersonate-header-key",style:u.input,value:l,onChangeText:p,placeholder:"x-impersonate-user-id",placeholderTextColor:m.color.placeholder,autoCapitalize:"none",autoCorrect:false}),x(d,{style:u.inputFooter,children:[h(y,{style:u.helperText,children:"The HTTP header key used for impersonation. Value will be the user ID."}),l!==ue&&h(H,{onPress:()=>p(ue),style:u.resetLink,children:h(y,{style:u.resetLinkText,children:"Reset to default"})})]})]})}),h(ce,{title:"Display",icon:Dn,defaultOpen:true,variant:"bordered",children:h(d,{style:u.sectionContent,children:h(d,{style:u.togglesCard,children:h(pe,{label:"Floating Banner",description:"Show a floating banner when impersonation is active",value:s,onChange:w=>{f(w),o(w)},recommended:true,testID:"buoy-impersonate-show-banner"})})})}),h(ce,{title:"Data Clearing",icon:Ot,defaultOpen:true,variant:"bordered",children:x(d,{style:u.sectionContent,children:[h(y,{style:u.sectionDescription,children:"Choose what data to clear when impersonation starts or stops. This ensures you see fresh data for the impersonated user."}),x(d,{style:u.togglesCard,children:[h(pe,{label:"React Query",description:"Clear query cache and cancel pending queries",value:a.reactQuery,onChange:w=>K("reactQuery",w),recommended:true,detected:i?.reactQuery}),h(d,{style:u.divider}),h(pe,{label:"Redux",description:"Reset Redux store to initial state",value:a.redux,onChange:w=>K("redux",w),recommended:true,detected:i?.redux})]}),x(d,{style:u.advancedSection,children:[h(y,{style:u.advancedLabel,children:"Storage Options"}),x(d,{style:[u.togglesCard,u.dangerousCard],children:[h(pe,{label:"AsyncStorage",description:"Clear app data (preserves @buoy/* keys)",value:a.asyncStorage,onChange:w=>K("asyncStorage",w),dangerous:true,detected:i?.asyncStorage}),h(d,{style:u.divider}),h(pe,{label:"MMKV",description:"Clear MMKV storage (preserves @buoy/* keys)",value:a.mmkv,onChange:w=>K("mmkv",w),dangerous:true,detected:i?.mmkv})]})]}),(a.asyncStorage||a.mmkv)&&x(d,{style:u.warningCard,children:[h(Ot,{size:16,color:m.color.warning}),x(d,{style:u.warningContent,children:[h(y,{style:u.warningTitle,children:"Storage Clearing Enabled"}),h(y,{style:u.warningText,children:"This will remove app data like settings and cached content. Auth tokens managed by @buoy/* are preserved."})]})]})]})}),!I&&x(H,{testID:"buoy-impersonate-restore-defaults",style:u.restoreButton,onPress:J,children:[h(En,{size:14,color:m.color.textSecondary}),h(y,{style:u.restoreButtonText,children:"Restore Defaults"})]}),h(ce,{title:"How It Works",icon:Hn,defaultOpen:false,variant:"bordered",children:x(d,{style:u.sectionContent,children:[h(y,{style:u.infoText,children:"When impersonation is enabled, the configured header is automatically added to all outgoing fetch and XMLHttpRequest calls."}),h(y,{style:[u.infoText,u.infoTextSpaced],children:"Your backend should check for this header and return data for the specified user ID instead of the authenticated user."}),x(d,{style:u.codeBlock,children:[h(y,{style:u.codeComment,children:"// Example request header"}),x(y,{style:u.codeText,children:[l||"x-impersonate-user-id",": ",h(y,{style:u.codeValue,children:"user_123"})]})]})]})}),h(ce,{title:"Export Configuration",icon:Wt,defaultOpen:false,variant:"bordered",children:x(d,{style:u.sectionContent,children:[h(y,{style:u.infoText,children:"Copy current settings to use in createImpersonateTool()."}),h(d,{style:u.dataViewerContainer,children:h(Nn,{title:"",data:re,showTypeFilter:true,rawMode:true,initialExpanded:true})}),h(H,{style:u.copyButton,onPress:v,children:S?x(We,{children:[h(Oe,{size:14,color:de.success}),h(y,{style:[u.copyButtonText,u.copySuccessText],children:"Copied!"})]}):x(We,{children:[h(Wt,{size:14,color:m.color.accent}),h(y,{style:u.copyButtonText,children:"Copy Config"})]})})]})})]})}var u=j.create({container:{flex:1},contentContainer:{padding:16,gap:12,paddingBottom:32},actionBar:{backgroundColor:m.color.accentSoft,borderRadius:10,borderWidth:1,borderColor:m.color.accentBorder,padding:12},actionBarContent:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},unsavedText:{fontSize:13,fontWeight:"500",color:m.color.accent},actionButtons:{flexDirection:"row",gap:8},saveButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:m.color.accent,paddingHorizontal:14,paddingVertical:8,borderRadius:6},saveButtonText:{fontSize:13,fontWeight:"600",color:m.color.onAccent},discardButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:m.color.surfaceElevated,paddingHorizontal:14,paddingVertical:8,borderRadius:6,borderWidth:1,borderColor:m.color.border},discardButtonText:{fontSize:13,fontWeight:"500",color:m.color.textSecondary},restoreButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,paddingVertical:12,borderRadius:8,borderWidth:1,borderColor:m.color.border,borderStyle:"dashed"},restoreButtonText:{fontSize:13,color:m.color.textSecondary},sectionContent:{paddingTop:8},sectionDescription:{fontSize:13,color:m.color.textSecondary,lineHeight:18,marginBottom:14},togglesCard:{backgroundColor:m.color.surface,borderRadius:10,borderWidth:1,borderColor:m.color.border,padding:4},dangerousCard:{borderColor:m.color.warning+"30"},advancedSection:{marginTop:16},advancedLabel:{fontSize:11,fontWeight:"600",color:m.color.textTertiary,textTransform:"uppercase",letterSpacing:.5,marginBottom:8,marginLeft:2},inputLabel:{fontSize:12,fontWeight:"600",color:m.color.textSecondary,marginBottom:8},input:{height:42,backgroundColor:m.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:m.color.border,paddingHorizontal:14,fontSize:14,color:m.color.text,fontFamily:Ke},inputFooter:{flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start",marginTop:8,gap:12},helperText:{flex:1,fontSize:12,color:m.color.textTertiary,lineHeight:16},resetLink:{paddingVertical:2},resetLinkText:{fontSize:12,color:m.color.accent,fontWeight:"500"},recommendedBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:m.color.accentSoft,paddingHorizontal:8,paddingVertical:3,borderRadius:4},recommendedText:{fontSize:10,fontWeight:"600",color:m.color.accent},detectedBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:8,paddingVertical:3,borderRadius:4},detectedBadgeActive:{backgroundColor:de.success+"15"},detectedBadgeInactive:{backgroundColor:m.color.textTertiary+"15"},detectedText:{fontSize:10,fontWeight:"600"},detectedTextActive:{color:de.success},detectedTextInactive:{color:m.color.textTertiary},divider:{height:1,backgroundColor:m.color.separator,marginHorizontal:12},warningCard:{marginTop:14,flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:m.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:m.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:13,fontWeight:"600",color:m.color.warning,marginBottom:4},warningText:{fontSize:12,color:m.color.textSecondary,lineHeight:17},infoText:{fontSize:13,color:m.color.textSecondary,lineHeight:19},infoTextSpaced:{marginTop:10},codeBlock:{marginTop:14,backgroundColor:m.color.bg,borderRadius:8,padding:14},codeComment:{fontSize:12,color:m.color.textTertiary,fontFamily:Ke,marginBottom:6},codeText:{fontSize:13,color:m.color.text,fontFamily:Ke},codeValue:{color:m.color.accent},dataViewerContainer:{marginTop:12,borderRadius:8,overflow:"hidden",borderWidth:1,borderColor:m.color.border},copyButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,marginTop:14,backgroundColor:m.color.accentSoft,paddingVertical:10,paddingHorizontal:16,borderRadius:8,borderWidth:1,borderColor:m.color.accentBorder},copyButtonText:{fontSize:13,fontWeight:"600",color:m.color.accent},copySuccessText:{color:de.success}});import{jsx as P,jsxs as Fe}from"react/jsx-runtime";var Un=zo,On=[{key:"search",label:"Search"},{key:"history",label:"History"},{key:"settings",label:"Settings"}],Kn=[{key:"search",label:"Search"},{key:"history",label:"History"}];function Me({visible:e,onClose:t,onBack:r,onMinimize:n,onSearchUsers:o,onClearReactQuery:i,onClearRedux:l,onClearAsyncStorage:p,onClearMMKV:a,showSettingsTab:c=true,inline:s=false}){let f=c?On:Kn,[S,b]=ke("search"),[C,I]=ke(false),ye=ct(false),[X,J]=ke(""),K=ct(null),{clearCache:re,isAvailable:v}=Go(),{resetStore:w,isAvailable:G}=on(),{clearStorage:W,isAvailable:Ce}=cn(),Jt=i??re??void 0,Gt=l??w??void 0,Zt=p??W??void 0,er={reactQuery:!!i||v,redux:!!l||G,asyncStorage:!!p||Ce,mmkv:!!a},{isActive:tr,currentUser:Je,headerKey:rr,dataNukeSettings:or,showBanner:nr,searchQuery:ar,searchResults:sr,isSearching:ir,searchError:lr,searchUsers:Ge,startImpersonation:Ze,stopImpersonation:et,updateHeaderKey:tt,updateDataNukeSettings:rt,updateShowBanner:Ie,history:cr,removeFromHistory:dr,clearHistory:ur}=Rt({onSearchUsers:o,onClearReactQuery:Jt,onClearRedux:Gt,onClearAsyncStorage:Zt,onClearMMKV:a});dt(()=>{C&&K.current&&setTimeout(()=>{K.current?.focus()},100)},[C]),dt(()=>{!c&&S==="settings"&&b("search")},[c,S]);let hr=oe(_=>{J(_)},[]),pr=oe(()=>{X.trim()&&Ge(X.trim()),I(false)},[X,Ge]),ot=oe(async _=>{await Ze(_)},[Ze]),gr=oe(async(_,yr,fr)=>{await tt(_),await rt(yr),await Ie(fr)},[tt,rt,Ie]),mr=oe(_=>{b(_),I(false)},[]),nt=()=>Fe(ae,{children:[r&&P(ae.Navigation,{onBack:r}),P(ae.Content,{title:"",children:C?P(ae.Search,{value:X,onChangeText:hr,onCancel:()=>{J(""),I(false)},onDismiss:()=>I(false),dismissOnBlur:true,placeholder:"Search by email, name, or ID...",iconSize:14,testID:"buoy-impersonate-search-input",inputProps:{onSubmitEditing:pr}}):P(Lo,{tabs:f,activeTab:S,onTabChange:mr,testIDPrefix:"buoy-impersonate-tab"})}),P(ae.Actions,{children:S==="search"&&!C&&P(H,{testID:"buoy-impersonate-search-toggle",onPress:()=>I(true),style:ve.headerActionButton,children:P(Uo,{size:14,color:vt.color.textSecondary})})})]});if(!e)return null;let at=Fe(d,{style:ve.container,children:[S==="search"&&P(Lt,{currentUser:Je,isActive:tr,searchQuery:ar,searchResults:sr,isSearching:ir,searchError:lr,onSelectUser:ot,onStopImpersonation:et,searchAvailable:!!o}),S==="history"&&P(Ut,{history:cr,currentUserId:Je?.id??null,onSelectUser:ot,onStopImpersonation:et,onRemoveFromHistory:dr,onClearHistory:ur}),S==="settings"&&P(jt,{headerKey:rr,settings:or,showBanner:nr,onSave:gr,onShowBannerChange:Ie,detectionStatus:er})]});return s?P(wt,{children:Fe(d,{style:ve.inlineRoot,children:[P(d,{style:ve.inlineHeader,...Oo,children:nt()}),at]})}):P(wt,{children:P(Un,{visible:e,onClose:t,onMinimize:n,header:{showToggleButton:true,customContent:nt()},enablePersistence:true,initialMode:"bottomSheet",disableScrollWrapper:true,children:at})})}function Wn(e){return P(Me,{...e,inline:true,visible:true,onClose:()=>{}})}var ve=j.create({inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:No.border,backgroundColor:"transparent"},container:{flex:1},headerActionButton:{width:28,height:28,borderRadius:6,backgroundColor:vt.color.buttonSurface,justifyContent:"center",alignItems:"center"}});import{useSyncExternalStore as Ft}from"react";import{buoyColors as we,X as jn,PowerToggleButton as Fn}from"@buoy-gg/shared-ui/web";import{jsx as q,jsxs as Ve}from"react/jsx-runtime";function $e({onPress:e,onStopPress:t,position:r="top",offset:n=50}){let o=Ft(g.subscribe,g.getSnapshot,g.getSnapshot);if(!o.isActive||!o.currentUser||!o.showBanner)return null;let i=async()=>{console.log("[Buoy]","[impersonate] banner pause/resume pressed"),o.isPaused?await g.resumeImpersonation():await g.pauseImpersonation()},l=o.currentUser.displayName||o.currentUser.email||o.currentUser.id,p=r==="top"?{top:n}:{bottom:n},a=async()=>{console.log("[Buoy]","[impersonate] banner STOP pressed"),await g.stopImpersonation()};return q(d,{style:[V.container,p],children:Ve(d,{testID:"buoy-impersonate-banner",style:V.banner,children:[Ve(H,{testID:"buoy-impersonate-banner-open",style:V.userSection,onPress:e,activeOpacity:.7,children:[q(Le,{userId:o.currentUser.id,name:l,size:"small",showActiveIndicator:false}),q(y,{style:[V.userName,o.isPaused&&V.userNamePaused],numberOfLines:1,children:l})]}),q(Fn,{isEnabled:!o.isPaused,onToggle:i,size:"small",accessibilityLabel:"Toggle impersonation",testID:"buoy-impersonate-banner-toggle"}),q(H,{testID:"buoy-impersonate-banner-stop",accessibilityLabel:"Stop impersonating",style:V.closeButton,onPress:a,activeOpacity:.7,children:q(jn,{size:12,color:"rgba(255, 255, 255, 0.5)"})})]})})}function Mn({onPress:e}){let t=Ft(g.subscribe,g.getSnapshot,g.getSnapshot);return!t.isActive||!t.currentUser?null:Ve(H,{style:V.minimalBanner,onPress:e,activeOpacity:.8,children:[q(d,{style:V.minimalDot}),q(y,{style:V.minimalText,children:"IMP"})]})}var V=j.create({container:{position:"absolute",left:0,right:0,alignItems:"center",zIndex:9999,pointerEvents:"box-none"},banner:{flexDirection:"row",alignItems:"center",backgroundColor:"rgba(20, 20, 20, 0.94)",borderWidth:1,borderColor:we.success+"40",borderRadius:22,paddingVertical:7,paddingLeft:7,paddingRight:10,gap:10,marginTop:3,shadowColor:"#000",shadowOffset:{width:0,height:6},shadowOpacity:.3,shadowRadius:14,elevation:10},userSection:{flexDirection:"row",alignItems:"center",gap:10},userName:{fontSize:14,fontWeight:"600",color:"#fff",maxWidth:180},userNamePaused:{opacity:.6},closeButton:{width:22,height:22,borderRadius:11,backgroundColor:"rgba(128, 128, 128, 0.16)",alignItems:"center",justifyContent:"center",marginLeft:-4},minimalBanner:{position:"absolute",top:60,right:16,flexDirection:"row",alignItems:"center",backgroundColor:"rgba(26, 26, 26, 0.92)",borderWidth:1,borderColor:we.success+"35",borderRadius:12,paddingVertical:5,paddingHorizontal:10,gap:5,zIndex:9999,shadowColor:"#000",shadowOffset:{width:0,height:2},shadowOpacity:.2,shadowRadius:6,elevation:4},minimalDot:{width:6,height:6,borderRadius:3,backgroundColor:we.success},minimalText:{fontSize:10,fontWeight:"700",color:we.success,letterSpacing:.5}});import{hasAccountAccess as Vn,isOverWireBudget as $n}from"@buoy-gg/shared-ui/web";var Xe=null;function Xn(e){Xe=e}var Qe=2*1024,Qn=16*1024,Mt=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function qn(e){if(!e)return e;if(e.startsWith("data:")){let t=e.indexOf(",");return`${t>=0?e.slice(0,Math.min(t+1,64)):"data:"}[${e.length} chars]`}return e.length<=Qe?e:`${e.slice(0,Qe)}\u2026 [${e.length-Qe} more]`}function _n(e){if(!e)return e;let t=typeof e.role=="string"?e.role:void 0;return $n(e,Qn)?t?{role:t,...Mt}:{...Mt}:e}function qe(e){return{...e,avatarUrl:qn(e.avatarUrl),metadata:_n(e.metadata)}}function Vt(e){return{...e,currentUser:e.currentUser?qe(e.currentUser):null,history:e.history.map(t=>({...t,user:qe(t.user)}))}}var _e=new Map;function $t(e){for(let t of e)t&&typeof t=="object"&&t.id&&_e.set(String(t.id),t)}function Yn(e){let t=_e.get(e);if(t)return t;let r=g.getState();return r.currentUser?.id===e?r.currentUser:r.history.find(n=>n.user.id===e)?.user}function Xt(e){if(!e||typeof e!="object"||!e.id)return false;if(_e.has(String(e.id)))return true;let t=g.getState();return t.currentUser?.id===e.id?true:t.history.some(r=>r.user.id===e.id)}async function Jn(e,t){let r=T(t.userId),n=r??T(t.user?.id),o=(T(t.email)??T(t.user?.email))?.toLowerCase(),i=[T(t.user?.name),T(t.user?.displayName),T(t.query)].map(b=>b?.toLowerCase()).filter(b=>!!b),l=[o,n,T(t.query),T(t.user?.name),T(t.user?.displayName)].filter((b,C,I)=>!!b&&I.indexOf(b)===C),p=new Map;for(let b of l){let C;try{C=await e(b)}catch{continue}if(Array.isArray(C)){$t(C);for(let I of C)I?.id&&p.set(String(I.id),I)}}let a=[...p.values()],c=b=>T(b.email)?.toLowerCase(),s=n?a.filter(b=>String(b.id)===n):[],f=o?a.filter(b=>c(b)===o):[];if(s.length===1&&f.length&&f[0].id!==s[0].id)throw new Error(`The id ${n} and the email ${o} belong to different users. Pass one of them.`);if(s.length===1)return s[0];if(r)return;if(f.length===1)return f[0];if(n||o)return;let S=a.filter(b=>{let C=b;return[T(C.displayName),T(C.name)].some(I=>I&&i.includes(I.toLowerCase()))});if(S.length>1)throw new Error(`${S.length} users are named that (${S.map(b=>b.id).join(", ")}). Pass the user's id or email.`);return S[0]}function T(e){return typeof e=="string"&&e.trim()?e.trim():typeof e=="number"?String(e):void 0}function Qt(e){return{searchUsers:async t=>{let r=String(t?.query??""),n=await e(r);return Array.isArray(n)&&$t(n),Array.isArray(n)?n.map(qe):n},startImpersonation:async t=>{let r=t??{},n=r.user,o=T(r.userId),i=T(n?.id);if(o&&i&&o!==i)throw new Error(`userId ${o} and user.id ${i} are different users. Pass one of them.`);let l=T(r.email)?.toLowerCase(),p=T(n?.email)?.toLowerCase();if(l&&p&&l!==p)throw new Error(`email ${l} and user.email ${p} are different users. Pass one of them.`);let a;if(n?.id&&Xt(n)&&r.userId===void 0&&r.email===void 0?a=Yn(String(n.id)):a=await Jn(e,r),!a||!Xt(a))throw new Error("That user isn't in this app's directory. Call searchUsers and impersonate one of its results \u2014 a user object that didn't come from search impersonates nobody.");let c=(T(r.email)??T(n?.email))?.toLowerCase(),s=T(a.email)?.toLowerCase();if(c&&s&&c!==s)throw new Error(`User ${a.id} has a different email than ${c}. Pass the id or the email of one user.`);return await g.startImpersonation(a),{ok:true,userId:a.id}},stopImpersonation:()=>g.stopImpersonation(),pauseImpersonation:()=>g.pauseImpersonation(),resumeImpersonation:()=>g.resumeImpersonation(),updateSettings:t=>{let r=t??{},n=r.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in r)?r:void 0);if(!n)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return g.updateSettings(n)},removeFromHistory:t=>g.removeFromHistory(t.userId),clearHistory:()=>g.clearHistory()}}function Gn({onSearchUsers:e}){return{version:1,getSnapshot:()=>Vt(g.getState()),subscribe:t=>g.subscribe(t),actions:Qt(e)}}var Zn={dispose:()=>{Vn()||g.disposeAccountSession()},version:1,getSnapshot:()=>Vt(g.getState()),subscribe:e=>g.subscribe(e),actions:Qt(e=>{if(!Xe)throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()");return Xe(e)})};import{ImpersonateIcon as qt,IMPERSONATE_ICON_COLOR as ea}from"@buoy-gg/shared-ui/web";import{jsx as _t}from"react/jsx-runtime";var Yt=false;async function ta(){if(!(typeof window>"u"||Yt)){Yt=true,console.log("[Buoy]","[impersonate] bootstrap: start"),O().isListening||O().startListening();try{let e=Ir();if(!e||typeof e.getItem!="function"){console.warn("[Buoy]","[impersonate] bootstrap: AsyncStorage shape unexpected",Object.keys(e??{}));return}let t={getItem:r=>e.getItem(r),setItem:(r,n)=>e.setItem(r,n)};g.setAsyncStorage(t),console.log("[Buoy]","[impersonate] bootstrap: AsyncStorage adapter installed"),await g.initializeAsync(t),console.log("[Buoy]","[impersonate] bootstrap: initializeAsync done")}catch(e){console.warn("[Buoy]","[impersonate] bootstrap: failed",e)}}}function ra(e){let{id:t="impersonate",name:r="IMPERSONATE",description:n="User impersonation for admin testing",defaults:o,showSettingsTab:i=true,onSearchUsers:l,onClearReactQuery:p,onClearRedux:a,onClearAsyncStorage:c,onClearMMKV:s}=e;return o&&g.setDeveloperDefaults(o),Xn(l??null),ta(),{id:t,name:r,description:n,slot:"both",icon:({size:f,slot:S})=>_t(qt,{size:S==="dial"?f*1.5:f,color:ea}),component:f=>_t(Me,{...f,onSearchUsers:l,onClearReactQuery:p,onClearRedux:a,onClearAsyncStorage:c,onClearMMKV:s,showSettingsTab:i}),props:{enableSharedModalDimensions:false},Banner:$e}}import{jsx as oa}from"react/jsx-runtime";function na(){return oa($e,{position:"top",offset:50})}import{buoyColors as ge,night as me,X as aa}from"@buoy-gg/shared-ui/web";import{jsx as Y,jsxs as xe}from"react/jsx-runtime";function sa({user:e,onStopImpersonation:t}){let r=e.displayName||e.email||e.id;return xe(d,{style:$.container,children:[xe(d,{style:$.userSection,children:[Y(Le,{userId:e.id,name:r,size:"small",showActiveIndicator:false}),Y(d,{style:$.userInfo,children:Y(y,{style:$.userName,numberOfLines:1,children:r})})]}),xe(d,{style:$.statusPill,children:[Y(d,{style:$.pulseDot}),Y(y,{style:$.statusText,children:"Active"})]}),xe(H,{style:$.stopButton,onPress:t,activeOpacity:.7,children:[Y(aa,{size:12,color:me.color.danger}),Y(y,{style:$.stopButtonText,children:"Stop"})]})]})}var $=j.create({container:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:10,paddingHorizontal:16,backgroundColor:ge.success+"10",borderBottomWidth:1,borderBottomColor:ge.success+"25",gap:12},userSection:{flexDirection:"row",alignItems:"center",flex:1,gap:10,minWidth:0},userInfo:{flex:1,minWidth:0},userName:{fontSize:14,fontWeight:"600",color:me.color.text},statusPill:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:ge.success+"20",paddingHorizontal:10,paddingVertical:5,borderRadius:12},pulseDot:{width:6,height:6,borderRadius:3,backgroundColor:ge.success},statusText:{fontSize:11,fontWeight:"600",color:ge.success,textTransform:"uppercase",letterSpacing:.5},stopButton:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:12,paddingVertical:6,backgroundColor:me.color.dangerSoft,borderRadius:6,borderWidth:1,borderColor:me.color.danger+"30"},stopButtonText:{fontSize:12,fontWeight:"600",color:me.color.danger}});import{useCallback as Ye,useSyncExternalStore as ia}from"react";function la(){let e=ia(g.subscribe,g.getSnapshot,g.getSnapshot),t=Ye(async o=>{await g.quickSwitch(o)},[]),r=Ye(async o=>{await g.removeFromHistory(o)},[]),n=Ye(async()=>{await g.clearHistory()},[]);return{history:e.history,currentUserId:e.currentUser?.id??null,quickSwitch:t,removeFromHistory:r,clearHistory:n}}export{jt as DataNukeSettingsComponent,$e as ImpersonateBanner,Mn as ImpersonateBannerMinimal,Ut as ImpersonateHistoryList,qt as ImpersonateIcon,Me as ImpersonateModal,na as ImpersonateOverlay,sa as ImpersonateStatusBar,Wn as ImpersonateToolView,Lt as UserSearchView,Gn as createImpersonateSyncAdapter,ra as createImpersonateTool,Qo as getImpersonatedUserId,O as impersonateListener,g as impersonateStore,Zn as impersonateSyncAdapter,Xo as isImpersonating,kt as setImpersonateConfig,Vo as startImpersonateListener,$o as stopImpersonateListener,Rt as useImpersonate,la as useImpersonateHistory};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buoy-gg/impersonate",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.75",
|
|
4
4
|
"description": "Configure impersonation headers for supported app requests. Your backend must authenticate and authorize user changes.",
|
|
5
5
|
"main": "lib/commonjs/index.js",
|
|
6
6
|
"module": "lib/module/index.js",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
],
|
|
35
35
|
"sideEffects": false,
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@buoy-gg/shared-ui": "^7.0.
|
|
37
|
+
"@buoy-gg/shared-ui": "^7.0.75"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"react": "*"
|