@buoy-gg/impersonate 7.0.43 → 7.0.44
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_URI_INLINE_LIMIT=exports.SNAPSHOT_METADATA_INLINE_LIMIT=void 0;exports.createImpersonateSyncAdapter=createImpersonateSyncAdapter;exports.impersonateSyncAdapter=void 0;exports.registerImpersonateSearchUsers=registerImpersonateSearchUsers;exports.toWireUri=toWireUri;var _sharedUi=require("@buoy-gg/shared-ui");var _impersonateStore=require("../impersonate/utils/impersonateStore");let registeredSearchUsers=null;function registerImpersonateSearchUsers(e){registeredSearchUsers=e}const SNAPSHOT_URI_INLINE_LIMIT=exports.SNAPSHOT_URI_INLINE_LIMIT=2*1024;const SNAPSHOT_METADATA_INLINE_LIMIT=exports.SNAPSHOT_METADATA_INLINE_LIMIT=16*1024;const METADATA_ON_DEVICE=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function toWireUri(e){if(!e)return e;if(e.startsWith("data:")){const r=e.indexOf(",");const t=r>=0?e.slice(0,Math.min(r+1,64)):"data:";return`${t}[${e.length} chars]`}if(e.length<=SNAPSHOT_URI_INLINE_LIMIT)return e;return`${e.slice(0,SNAPSHOT_URI_INLINE_LIMIT)}\u2026 [${e.length-SNAPSHOT_URI_INLINE_LIMIT} more]`}function toWireMetadata(e){if(!e)return e;const r=typeof e.role==="string"?e.role:void 0;if(!(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_METADATA_INLINE_LIMIT))return e;return r?{role:r,...METADATA_ON_DEVICE}:{...METADATA_ON_DEVICE}}function toWireUser(e){return{...e,avatarUrl:toWireUri(e.avatarUrl),metadata:toWireMetadata(e.metadata)}}function toWireState(e){return{...e,currentUser:e.currentUser?toWireUser(e.currentUser):null,history:e.history.map(r=>({...r,user:toWireUser(r.user)}))}}const seenUserIds=new Set;function rememberUsers(e){for(const r of e){if(r&&typeof r==="object"&&r.id)seenUserIds.add(String(r.id))}}function isKnownUser(e){if(!e||typeof e!=="object"||!e.id)return false;if(seenUserIds.has(String(e.id)))return true;const r=_impersonateStore.impersonateStore.getState();if(r.currentUser?.id===e.id)return true;return r.history.some(t=>t.user.id===e.id)}function buildActions(e){return{searchUsers:async r=>{const t=String(r?.query??"");const s=await e(t);if(Array.isArray(s))rememberUsers(s);return Array.isArray(s)?s.map(toWireUser):s},startImpersonation:async r=>{const t=r?.user;if(!isKnownUser(t)){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.")}await _impersonateStore.impersonateStore.startImpersonation(t);return{ok:true,userId:t.id}},stopImpersonation:()=>_impersonateStore.impersonateStore.stopImpersonation(),pauseImpersonation:()=>_impersonateStore.impersonateStore.pauseImpersonation(),resumeImpersonation:()=>_impersonateStore.impersonateStore.resumeImpersonation(),updateSettings:r=>{const t=r??{};const s=t.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in t)?t:void 0);if(!s)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return _impersonateStore.impersonateStore.updateSettings(s)},removeFromHistory:r=>_impersonateStore.impersonateStore.removeFromHistory(r.userId),clearHistory:()=>_impersonateStore.impersonateStore.clearHistory()}}function createImpersonateSyncAdapter({onSearchUsers:e}){return{version:1,getSnapshot:()=>toWireState(_impersonateStore.impersonateStore.getState()),subscribe:r=>_impersonateStore.impersonateStore.subscribe(r),actions:buildActions(e)}}const impersonateSyncAdapter=exports.impersonateSyncAdapter={dispose:()=>_impersonateStore.impersonateStore.disposeAccountSession(),version:1,getSnapshot:()=>toWireState(_impersonateStore.impersonateStore.getState()),subscribe:e=>_impersonateStore.impersonateStore.subscribe(e),actions:buildActions(e=>{if(!registeredSearchUsers){throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()")}return registeredSearchUsers(e)})};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_URI_INLINE_LIMIT=exports.SNAPSHOT_METADATA_INLINE_LIMIT=void 0;exports.createImpersonateSyncAdapter=createImpersonateSyncAdapter;exports.impersonateSyncAdapter=void 0;exports.registerImpersonateSearchUsers=registerImpersonateSearchUsers;exports.toWireUri=toWireUri;var _sharedUi=require("@buoy-gg/shared-ui");var _impersonateStore=require("../impersonate/utils/impersonateStore");let registeredSearchUsers=null;function registerImpersonateSearchUsers(e){registeredSearchUsers=e}const SNAPSHOT_URI_INLINE_LIMIT=exports.SNAPSHOT_URI_INLINE_LIMIT=2*1024;const SNAPSHOT_METADATA_INLINE_LIMIT=exports.SNAPSHOT_METADATA_INLINE_LIMIT=16*1024;const METADATA_ON_DEVICE=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function toWireUri(e){if(!e)return e;if(e.startsWith("data:")){const r=e.indexOf(",");const t=r>=0?e.slice(0,Math.min(r+1,64)):"data:";return`${t}[${e.length} chars]`}if(e.length<=SNAPSHOT_URI_INLINE_LIMIT)return e;return`${e.slice(0,SNAPSHOT_URI_INLINE_LIMIT)}\u2026 [${e.length-SNAPSHOT_URI_INLINE_LIMIT} more]`}function toWireMetadata(e){if(!e)return e;const r=typeof e.role==="string"?e.role:void 0;if(!(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_METADATA_INLINE_LIMIT))return e;return r?{role:r,...METADATA_ON_DEVICE}:{...METADATA_ON_DEVICE}}function toWireUser(e){return{...e,avatarUrl:toWireUri(e.avatarUrl),metadata:toWireMetadata(e.metadata)}}function toWireState(e){return{...e,currentUser:e.currentUser?toWireUser(e.currentUser):null,history:e.history.map(r=>({...r,user:toWireUser(r.user)}))}}const seenUserIds=new Set;function rememberUsers(e){for(const r of e){if(r&&typeof r==="object"&&r.id)seenUserIds.add(String(r.id))}}function isKnownUser(e){if(!e||typeof e!=="object"||!e.id)return false;if(seenUserIds.has(String(e.id)))return true;const r=_impersonateStore.impersonateStore.getState();if(r.currentUser?.id===e.id)return true;return r.history.some(t=>t.user.id===e.id)}function buildActions(e){return{searchUsers:async r=>{const t=String(r?.query??"");const s=await e(t);if(Array.isArray(s))rememberUsers(s);return Array.isArray(s)?s.map(toWireUser):s},startImpersonation:async r=>{const t=r?.user;if(!isKnownUser(t)){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.")}await _impersonateStore.impersonateStore.startImpersonation(t);return{ok:true,userId:t.id}},stopImpersonation:()=>_impersonateStore.impersonateStore.stopImpersonation(),pauseImpersonation:()=>_impersonateStore.impersonateStore.pauseImpersonation(),resumeImpersonation:()=>_impersonateStore.impersonateStore.resumeImpersonation(),updateSettings:r=>{const t=r??{};const s=t.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in t)?t:void 0);if(!s)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return _impersonateStore.impersonateStore.updateSettings(s)},removeFromHistory:r=>_impersonateStore.impersonateStore.removeFromHistory(r.userId),clearHistory:()=>_impersonateStore.impersonateStore.clearHistory()}}function createImpersonateSyncAdapter({onSearchUsers:e}){return{version:1,getSnapshot:()=>toWireState(_impersonateStore.impersonateStore.getState()),subscribe:r=>_impersonateStore.impersonateStore.subscribe(r),actions:buildActions(e)}}const impersonateSyncAdapter=exports.impersonateSyncAdapter={dispose:()=>{if(!(0,_sharedUi.hasAccountAccess)())_impersonateStore.impersonateStore.disposeAccountSession()},version:1,getSnapshot:()=>toWireState(_impersonateStore.impersonateStore.getState()),subscribe:e=>_impersonateStore.impersonateStore.subscribe(e),actions:buildActions(e=>{if(!registeredSearchUsers){throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()")}return registeredSearchUsers(e)})};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{isOverWireBudget as
|
|
1
|
+
"use strict";import{hasAccountAccess as f,isOverWireBudget as m}from"@buoy-gg/shared-ui";import{impersonateStore as s}from"../impersonate/utils/impersonateStore";let o=null;export function registerImpersonateSearchUsers(e){o=e}export const SNAPSHOT_URI_INLINE_LIMIT=2*1024;export const SNAPSHOT_METADATA_INLINE_LIMIT=16*1024;const a=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});export function toWireUri(e){if(!e)return e;if(e.startsWith("data:")){const t=e.indexOf(",");const r=t>=0?e.slice(0,Math.min(t+1,64)):"data:";return`${r}[${e.length} chars]`}if(e.length<=SNAPSHOT_URI_INLINE_LIMIT)return e;return`${e.slice(0,SNAPSHOT_URI_INLINE_LIMIT)}\u2026 [${e.length-SNAPSHOT_URI_INLINE_LIMIT} more]`}function h(e){if(!e)return e;const t=typeof e.role==="string"?e.role:void 0;if(!m(e,SNAPSHOT_METADATA_INLINE_LIMIT))return e;return t?{role:t,...a}:{...a}}function i(e){return{...e,avatarUrl:toWireUri(e.avatarUrl),metadata:h(e.metadata)}}function c(e){return{...e,currentUser:e.currentUser?i(e.currentUser):null,history:e.history.map(t=>({...t,user:i(t.user)}))}}const u=new Set;function g(e){for(const t of e){if(t&&typeof t==="object"&&t.id)u.add(String(t.id))}}function S(e){if(!e||typeof e!=="object"||!e.id)return false;if(u.has(String(e.id)))return true;const t=s.getState();if(t.currentUser?.id===e.id)return true;return t.history.some(r=>r.user.id===e.id)}function d(e){return{searchUsers:async t=>{const r=String(t?.query??"");const n=await e(r);if(Array.isArray(n))g(n);return Array.isArray(n)?n.map(i):n},startImpersonation:async t=>{const r=t?.user;if(!S(r)){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.")}await s.startImpersonation(r);return{ok:true,userId:r.id}},stopImpersonation:()=>s.stopImpersonation(),pauseImpersonation:()=>s.pauseImpersonation(),resumeImpersonation:()=>s.resumeImpersonation(),updateSettings:t=>{const r=t??{};const n=r.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(p=>p in r)?r:void 0);if(!n)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return s.updateSettings(n)},removeFromHistory:t=>s.removeFromHistory(t.userId),clearHistory:()=>s.clearHistory()}}export function createImpersonateSyncAdapter({onSearchUsers:e}){return{version:1,getSnapshot:()=>c(s.getState()),subscribe:t=>s.subscribe(t),actions:d(e)}}export const impersonateSyncAdapter={dispose:()=>{if(!f())s.disposeAccountSession()},version:1,getSnapshot:()=>c(s.getState()),subscribe:e=>s.subscribe(e),actions:d(e=>{if(!o){throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()")}return o(e)})};
|
package/lib/web/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";var Ge=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var ir=Object.getOwnPropertyNames;var sr=Object.prototype.hasOwnProperty;var lr=(e,t)=>{for(var r in t)Ge(e,r,{get:t[r],enumerable:true})},et=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ir(t))!sr.call(e,o)&&o!==r&&Ge(e,o,{get:()=>t[o],enumerable:!(a=nr(t,o))||a.enumerable});return e},cr=(e,t,r)=>(et(e,t,"default"),r&&et(r,t,"default"));typeof window<"u"&&typeof globalThis.global>"u"&&(globalThis.global=globalThis);import dr from"@buoy-gg/shared-ui/web/asyncStorage";function tt(){return dr}import{useState as xe,useCallback as ee,useRef as rt,useEffect as ot}from"react";var at={};lr(at,{AccessibilityInfo:()=>pr,ActivityIndicator:()=>st,Alert:()=>co,Animated:()=>mr,AppRegistry:()=>fr,AppState:()=>Sr,Appearance:()=>yr,BackHandler:()=>br,Button:()=>so,CheckBox:()=>Nr,Clipboard:()=>vr,DeviceEventEmitter:()=>Jr,Dimensions:()=>xr,Easing:()=>Cr,FlatList:()=>Ce,I18nManager:()=>wr,Image:()=>Lr,ImageBackground:()=>Er,InteractionManager:()=>kr,Keyboard:()=>Ir,KeyboardAvoidingView:()=>Or,LayoutAnimation:()=>Tr,Linking:()=>Br,LogBox:()=>_r,Modal:()=>no,NativeEventEmitter:()=>Rr,NativeModules:()=>gr,PanResponder:()=>Ar,Picker:()=>Wr,PixelRatio:()=>Hr,Platform:()=>Pr,Pressable:()=>ao,ProgressBar:()=>Fr,RefreshControl:()=>jr,SafeAreaView:()=>Mr,ScrollView:()=>it,SectionList:()=>Kr,Share:()=>zr,StatusBar:()=>Vr,StyleSheet:()=>F,Switch:()=>io,Text:()=>p,TextInput:()=>nt,Touchable:()=>Xr,TouchableHighlight:()=>ro,TouchableNativeFeedback:()=>Qr,TouchableOpacity:()=>T,TouchableWithoutFeedback:()=>oo,UIManager:()=>Dr,Vibration:()=>Ur,View:()=>i,VirtualizedList:()=>$r,YellowBox:()=>qr,findNodeHandle:()=>lo,unstable_createElement:()=>hr,useColorScheme:()=>Zr,useLocaleContext:()=>Yr,useWindowDimensions:()=>Gr});cr(at,ur);import*as ur from"react-native-web";import{unstable_createElement as hr,NativeModules as gr,AccessibilityInfo as pr,Animated as mr,Appearance as yr,AppRegistry as fr,AppState as Sr,BackHandler as br,Clipboard as vr,Dimensions as xr,Easing as Cr,I18nManager as wr,Keyboard as Ir,InteractionManager as kr,LayoutAnimation as Tr,Linking as Br,NativeEventEmitter as Rr,PanResponder as Ar,PixelRatio as Hr,Platform as Pr,Share as zr,StyleSheet as F,UIManager as Dr,Vibration as Ur,CheckBox as Nr,FlatList as Ce,Image as Lr,ImageBackground as Er,KeyboardAvoidingView as Or,Picker as Wr,ProgressBar as Fr,RefreshControl as jr,SafeAreaView as Mr,SectionList as Kr,StatusBar as Vr,Touchable as Xr,TouchableNativeFeedback as Qr,VirtualizedList as $r,YellowBox as qr,LogBox as _r,DeviceEventEmitter as Jr,useColorScheme as Zr,useLocaleContext as Yr,useWindowDimensions as Gr}from"react-native-web";import*as R from"react-native-web";import{createElement as eo,forwardRef as to}from"react";function z(e){let t=to((a,o)=>{let{accessibilityState:c,accessibilityValue:l,...m}=a;for(let n of["busy","checked","disabled","expanded","selected"])c?.[n]!==void 0&&m[`aria-${n}`]===void 0&&(m[`aria-${n}`]=c[n]);for(let[n,d]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))l?.[n]!==void 0&&m[`aria-${d}`]===void 0&&(m[`aria-${d}`]=l[n]);return eo(e,{...m,ref:o})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var i=z(R.View),p=z(R.Text),nt=z(R.TextInput),T=z(R.TouchableOpacity),ro=z(R.TouchableHighlight),oo=z(R.TouchableWithoutFeedback),ao=z(R.Pressable),it=z(R.ScrollView),no=z(R.Modal),io=z(R.Switch),st=z(R.ActivityIndicator),so=z(R.Button),lo=R.findNodeHandle,co={alert(e,t,r,a){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 c=document.createElement("h2");if(c.textContent=e,c.style.cssText="font-size:18px;margin:0 0 12px",o.appendChild(c),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 m=r?.length?r:[{text:"OK"}],n=()=>{o.close?.(),o.remove()};for(let d of m){let y=document.createElement("button");y.type="button",y.textContent=d.text??"OK",y.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${d.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,y.onclick=()=>{n(),d.onPress?.()},l.appendChild(y)}o.addEventListener("cancel",d=>{d.preventDefault(),a?.cancelable!==false&&(n(),a?.onDismiss?.())}),o.appendChild(l),document.body.appendChild(o),o.showModal?o.showModal():o.setAttribute("open","")}};import{JsModal as uo,TabSelector as ho,ModalHeader as te,buoyColors as go,night as lt,Search as po,TickProvider as ct,windowDragProps as mo}from"@buoy-gg/shared-ui/web";import{useState as ge,useEffect as dt,useCallback as U,useSyncExternalStore as yo}from"react";import{assertAccountAccess as ut,getAccountAccess as fo,hasAccountAccess as So,subscribeAccountAccess as bo}from"@buoy-gg/shared-ui/web";var ht=[/\/symbolicate$/,/\/logs$/,/\/debugger-proxy/,/\/reload$/,/\/launch-js-devtools/,/localhost:8081/,/100\.64\.\d+\.\d+:8081/,/10\.0\.\d+\.\d+:8081/,/\.hot-update\./,/__metro/];function we(e,t){for(let r of Object.keys(t))r.startsWith("__buoy")&&(e[r]=t[r])}var vo=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:[...ht]}}setConfig(e){this.config={...this.config,...e},e.ignorePatterns&&(this.config.ignorePatterns=[...ht,...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 a=this,o=async function(d,y){let C=a.extractUrl(d);if(a.shouldInjectHeader(C)){let w=y?.headers??(typeof d=="object"&&"headers"in d?d.headers:void 0),P=new Headers(w);return P.set(a.config.headerKey,a.config.userId),a.originalFetch(d,{...y,headers:P})}return a.originalFetch(d,y)};we(o,e),this.patchedFetch=o,globalThis.fetch=this.patchedFetch;let c=function(d,y,C=true,w,P){let L=this;L._impersonateUrl=typeof y=="string"?y:y.href;let D=typeof y=="string"?y:y.toString();return a.originalXHROpen.call(this,d,D,C,w,P)},l=function(d){let y=this;return y._impersonateUrl&&a.shouldInjectHeader(y._impersonateUrl)&&this.setRequestHeader(a.config.headerKey,a.config.userId),a.originalXHRSend.call(this,d)};we(c,t),we(l,r),this.patchedXHROpen=c,this.patchedXHRSend=l,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend;let m=globalThis,n=m.__buoyHeaderInjectors??(m.__buoyHeaderInjectors=[]);n.includes(this.reportHeader)||n.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)}},re=null;function E(){return re||(re=new vo),re}function xo(){E().startListening()}function Co(){E().stopListening()}function gt(e){E().setConfig(e)}function wo(){return re?.isImpersonating??false}function Io(){return re?.getConfig().userId??null}var oe="@buoy/impersonate/state",ko=10,pt={reactQuery:true,redux:true,asyncStorage:false,mmkv:false},Y={isActive:false,isPaused:false,currentUser:null,headerKey:"x-impersonate-user-id",ignorePatterns:[],dataNukeSettings:pt,showBanner:true,history:[]},Ie=false,mt={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{}}},To=class{constructor(){this.state={...Y};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=fo().status;r==="admitted"?e=true:r==="locked"&&e&&(e=false,this.disposeAccountSession())};bo(t),t()}),typeof localStorage<"u"?this.storageReadyPromise=Promise.resolve():this.storageReadyPromise=new Promise(e=>{this.resolveStorageReady=e})}loadFromStorage(){try{let e=mt.getItem(oe),t=this.getEffectiveDefaults();if(e){let r=JSON.parse(e);this.state={...Y,headerKey:r.headerKey??t.headerKey,ignorePatterns:r.ignorePatterns??Y.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={...Y,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??Y.headerKey,dataNukeSettings:{...pt,...this.developerDefaults?.dataNukeSettings},showBanner:this.developerDefaults?.showBanner??Y.showBanner}}getDeveloperDefaults(){return this.developerDefaults}async initializeAsync(e){if(e){this.asyncStorageRef=e;try{let t=await e.getItem(oe);if(console.log(`[impersonate] initializeAsync read STORAGE_KEY=${oe} 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(ut(),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,ko);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(`[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(ut(),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(!Ie){Ie=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(()=>{Ie=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;gt({headerKey:this.state.headerKey,userId:e?this.state.currentUser?.id??null:null,ignorePatterns:this.state.ignorePatterns.map(t=>new RegExp(t)),gate:So}),E().isListening||E().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(oe,t),console.log(`[impersonate] persist -> AsyncStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)):(mt.setItem(oe,t),console.log(`[impersonate] persist -> localStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`))}catch(r){console.warn("[impersonate] persist failed",r)}}notify(){this.listeners.forEach(e=>{try{e(this.state)}catch{}})}},h=new To;function yt(e={}){let[t,r]=ge(""),[a,o]=ge([]),[c,l]=ge(false),[m,n]=ge(null),d=yo(h.subscribe,h.getSnapshot,h.getSnapshot);dt(()=>{h.registerNukeCallbacks({reactQuery:e.onClearReactQuery,redux:e.onClearRedux,asyncStorage:e.onClearAsyncStorage,mmkv:e.onClearMMKV})},[e.onClearReactQuery,e.onClearRedux,e.onClearAsyncStorage,e.onClearMMKV]),dt(()=>{let f=true;return(async()=>{try{let S=await import("@buoy-gg/shared-ui/web/asyncStorage").then(W=>W.default),Z={getItem:W=>S.getItem(W),setItem:(W,be)=>S.setItem(W,be)};h.setAsyncStorage(Z),f&&await h.initializeAsync(Z)}catch{}})(),E().isListening||E().startListening(),()=>{f=false}},[]);let y=U(async f=>{if(r(f),n(null),!f.trim()){o([]);return}if(!e.onSearchUsers){n("Search not configured"),o([]);return}l(true);try{let S=await e.onSearchUsers(f);o(S)}catch(S){n(S instanceof Error?S.message:"Search failed"),o([])}finally{l(false)}},[e.onSearchUsers]),C=U(()=>{r(""),o([]),n(null)},[]),w=U(async f=>{await h.startImpersonation(f)},[]),P=U(async()=>{await h.stopImpersonation()},[]),L=U(async f=>{await h.quickSwitch(f)},[]),D=U(async f=>{await h.updateSettings({headerKey:f})},[]),he=U(async f=>{await h.updateSettings({ignorePatterns:f})},[]),X=U(async f=>{await h.updateSettings({dataNukeSettings:f})},[]),J=U(async f=>{await h.updateSettings({showBanner:f})},[]),O=U(async f=>{await h.removeFromHistory(f)},[]),G=U(async()=>{await h.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:a,isSearching:c,searchError:m,searchUsers:y,clearSearch:C,startImpersonation:w,stopImpersonation:P,quickSwitch:L,updateHeaderKey:D,updateIgnorePatterns:he,updateDataNukeSettings:X,updateShowBanner:J,removeFromHistory:O,clearHistory:G}}import{useCallback as Bo}from"react";import{dispatchToolAction as ft,getToolAdapters as Ro}from"@buoy-gg/shared-ui/web";function Ao(){let e=!!Ro().query,t=Bo(async()=>{await ft("query","clearQueryCache"),await ft("query","clearMutationCache")},[]);return{isAvailable:e,error:e?null:"Connect React Query to Buoy or provide onClearReactQuery.",clearCache:e?t:null}}import{useCallback as Ho}from"react";import{dispatchToolAction as Po,getToolAdapters as zo}from"@buoy-gg/shared-ui/web";var Do="@@RESET";function Uo({resetActionType:e=Do}={}){let t=!!zo().redux,r=Ho(async()=>{await Po("redux","dispatch",{action:{type:e}})},[e]);return{isAvailable:t,error:t?null:"Connect Redux to Buoy or provide onClearRedux.",resetStore:t?r:null}}import{useCallback as No,useMemo as Lo,useState as St,useEffect as Eo}from"react";var ke=false;function Oo(){let[e,t]=St(null),[r,a]=St(null);Eo(()=>{let c=tt();c?(t(c),a(null)):a("@react-native-async-storage/async-storage is not installed")},[]);let o=No(async()=>{if(!ke){ke=true;try{if(e){let c=(await e.getAllKeys()).filter(l=>!l.startsWith("@buoy/")&&!l.startsWith("@buoy-"));c.length>0&&await e.multiRemove([...c])}}finally{setTimeout(()=>{ke=false},100)}}},[e]);return Lo(()=>!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 Wo}from"react";import{SectionHeader as Te,EmptyState as Fo,night as k,Search as jo,AlertTriangle as bt,Users as Mo}from"@buoy-gg/shared-ui/web";import{buoyColors as Be,night as A,Play as Ko,X as Vo,PowerToggleButton as Xo,monoFont as Qo}from"@buoy-gg/shared-ui/web";import{useMemo as vt}from"react";import{buoyColors as $o,night as qo}from"@buoy-gg/shared-ui/web";import{jsx as Re,jsxs as _o}from"react/jsx-runtime";var xt=["#6366F1","#8B5CF6","#EC4899","#F43F5E","#F97316","#EAB308","#22C55E","#14B8A6","#06B6D4","#3B82F6"],Jo={small:{container:24,font:10,indicator:8},medium:{container:36,font:14,indicator:10},large:{container:44,font:16,indicator:12}};function Zo(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 Yo(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return xt[Math.abs(t)%xt.length]}function Ae({userId:e,name:t,size:r="medium",showActiveIndicator:a=false,backgroundColor:o}){let c=Jo[r],l=vt(()=>o??Yo(e),[e,o]),m=vt(()=>Zo(t),[t]);return _o(i,{style:pe.wrapper,children:[Re(i,{style:[pe.container,{width:c.container,height:c.container,borderRadius:c.container/2,backgroundColor:l}],children:Re(p,{style:[pe.initials,{fontSize:c.font}],children:m})}),a&&Re(i,{style:[pe.indicator,{width:c.indicator,height:c.indicator,borderRadius:c.indicator/2,right:-1,bottom:-1}]})]})}var pe=F.create({wrapper:{position:"relative"},container:{alignItems:"center",justifyContent:"center"},initials:{color:"#FFFFFF",fontWeight:"600",letterSpacing:.5},indicator:{position:"absolute",backgroundColor:$o.success,borderWidth:2,borderColor:qo.color.surface}});import{jsx as H,jsxs as ae}from"react/jsx-runtime";function Ct({user:e,isActive:t=false,onPress:r,onStop:a,onRemove:o,showRemoveButton:c=false,lastUsedTime:l,variant:m="default"}){let n=e.displayName||e.email||e.id,d=e.email&&e.displayName,y=typeof e.metadata?.role=="string"?e.metadata.role:null;return ae(T,{testID:`buoy-impersonate-user-${e.id}`,style:[I.container,t&&I.activeContainer,m==="compact"&&I.compactContainer],onPress:r,disabled:t,activeOpacity:.7,children:[H(i,{style:I.avatarSection,children:H(Ae,{userId:e.id,name:n,size:m==="compact"?"small":"medium",showActiveIndicator:t})}),ae(i,{style:I.content,children:[ae(i,{style:I.nameRow,children:[H(p,{style:[I.name,t&&I.activeName],numberOfLines:1,children:n}),y?H(i,{style:I.roleBadge,children:H(p,{style:I.roleBadgeText,children:y.toUpperCase()})}):null]}),d&&H(p,{style:I.email,numberOfLines:1,children:e.email}),H(i,{style:I.metadataRow,children:ae(p,{style:I.userId,children:["ID: ",e.id]})})]}),ae(i,{style:I.actions,children:[t?H(Xo,{isEnabled:true,onToggle:a||(()=>{}),accessibilityLabel:"Stop impersonation"}):H(T,{style:I.actionButton,onPress:r,activeOpacity:.7,children:H(Ko,{size:14,color:A.color.onAccent})}),c&&o&&!t&&H(T,{style:I.removeButton,onPress:o,activeOpacity:.7,children:H(Vo,{size:12,color:A.color.textTertiary})})]}),l?H(p,{style:I.lastUsed,children:l}):null]})}var I=F.create({container:{flexDirection:"row",alignItems:"center",backgroundColor:A.color.surface,borderRadius:10,borderWidth:1,borderColor:A.color.border,padding:12,gap:12},activeContainer:{backgroundColor:Be.success+"10",borderColor:Be.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:A.color.text,flexShrink:1},activeName:{color:Be.success},roleBadge:{backgroundColor:A.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},roleBadgeText:{fontSize:9,fontWeight:"700",color:A.color.textTertiary,letterSpacing:.5},email:{fontSize:13,color:A.color.textSecondary,marginBottom:4},metadataRow:{flexDirection:"row",alignItems:"center",gap:4},userId:{fontSize:11,color:A.color.textTertiary,fontFamily:Qo},lastUsed:{position:"absolute",bottom:8,right:10,fontSize:10,color:A.color.textTertiary},actions:{flexDirection:"row",alignItems:"center",gap:8,flexShrink:0},actionButton:{width:36,height:36,borderRadius:8,backgroundColor:A.color.accent,alignItems:"center",justifyContent:"center"},removeButton:{width:28,height:28,borderRadius:6,backgroundColor:A.color.surfaceElevated,borderWidth:1,borderColor:A.color.border,alignItems:"center",justifyContent:"center"}});import{jsx as v,jsxs as j}from"react/jsx-runtime";function wt({currentUser:e,searchQuery:t,searchResults:r,isSearching:a,searchError:o,onSelectUser:c,onStopImpersonation:l,searchAvailable:m=true}){let n=Wo(({item:d})=>{let y=e?.id===d.id;return v(Ct,{user:d,isActive:y,onPress:()=>!y&&c(d),onStop:y?l:void 0})},[e,c,l]);return j(i,{style:x.container,children:[!m&&v(i,{style:x.section,children:j(i,{style:x.warningCard,children:[v(bt,{size:18,color:k.color.warning}),j(i,{style:x.warningContent,children:[v(p,{style:x.warningTitle,children:"Search Not Available"}),v(p,{style:x.warningText,children:"Configure the onSearchUsers callback to enable user search."})]})]})}),a&&j(i,{style:x.loadingContainer,children:[v(st,{size:"small",color:k.color.accent}),v(p,{style:x.loadingText,children:"Searching users..."})]}),o?v(i,{style:x.section,children:j(i,{style:x.errorCard,children:[v(bt,{size:16,color:k.color.danger}),v(p,{style:x.errorText,children:o})]})}):null,r.length>0&&j(i,{style:x.resultsSection,children:[j(Te,{children:[v(Te.Title,{children:"Results"}),v(Te.Badge,{count:r.length})]}),v(Ce,{data:r,keyExtractor:d=>d.id,renderItem:n,ItemSeparatorComponent:()=>v(i,{style:x.separator}),contentContainerStyle:x.listContent,showsVerticalScrollIndicator:false})]}),!!t&&!a&&r.length===0&&!o&&j(i,{style:x.emptyStateContainer,children:[v(i,{style:x.emptyStateIcon,children:v(Mo,{size:28,color:k.color.textTertiary})}),v(p,{style:x.emptyStateTitle,children:"No users found"}),j(p,{style:x.emptyStateDescription,children:['No results for "',t,'"']}),v(p,{style:x.emptyStateHint,children:"Try a different search term"})]}),!t&&r.length===0&&!a&&m&&v(Fo,{title:"Search for users",description:"Tap the search icon in the header to find users by email, name, or ID",icon:jo,variant:"minimal"})]})}var x=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:k.color.textSecondary},resultsSection:{flex:1,paddingHorizontal:16},listContent:{paddingBottom:16},separator:{height:8},warningCard:{flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:k.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:k.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:14,fontWeight:"600",color:k.color.warning,marginBottom:4},warningText:{fontSize:13,color:k.color.textSecondary,lineHeight:18},errorCard:{flexDirection:"row",alignItems:"center",gap:10,backgroundColor:k.color.dangerSoft,borderRadius:10,borderWidth:1,borderColor:k.color.danger+"25",padding:12},errorText:{flex:1,fontSize:13,color:k.color.danger},emptyStateContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyStateIcon:{width:56,height:56,borderRadius:28,backgroundColor:k.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyStateTitle:{fontSize:16,fontWeight:"600",color:k.color.text,marginBottom:6},emptyStateDescription:{fontSize:14,color:k.color.textSecondary,textAlign:"center",marginBottom:8},emptyStateHint:{fontSize:12,color:k.color.textTertiary}});import{useCallback as Go}from"react";import{night as Q,Trash2 as ea,useRelativeTime as ta,ToolEmptyState as ra}from"@buoy-gg/shared-ui/web";import{jsx as N,jsxs as It}from"react/jsx-runtime";function oa({item:e,isActive:t,onSelect:r,onStop:a,onRemove:o,showRemoveButton:c}){let l=ta(new Date(e.lastUsedAt));return N(Ct,{user:e.user,isActive:t,onPress:()=>!t&&r(e.user),onStop:t?a:void 0,onRemove:o,showRemoveButton:c,lastUsedTime:l})}function kt({history:e,currentUserId:t,onSelectUser:r,onStopImpersonation:a,onRemoveFromHistory:o,onClearHistory:c}){let l=Go(({item:m})=>{let n=t===m.user.id;return N(oa,{item:m,isActive:n,onSelect:r,onStop:a,onRemove:o?()=>o(m.user.id):void 0,showRemoveButton:!!o})},[t,r,a,o]);return e.length===0?N(ra,{testID:"buoy-impersonate-history-empty",otto:"disguise",title:"No History",message:"Users you impersonate will appear here for quick access"}):It(i,{style:M.container,children:[It(i,{style:M.headerRow,children:[N(p,{style:M.headerTitle,children:"Recent"}),N(i,{style:M.headerBadge,children:N(p,{style:M.headerBadgeText,children:e.length})}),N(i,{style:M.headerSpacer}),c&&N(T,{style:M.clearButton,onPress:c,activeOpacity:.7,children:N(ea,{size:12,color:Q.color.textTertiary})})]}),N(Ce,{data:e,keyExtractor:m=>m.user.id,renderItem:l,ItemSeparatorComponent:()=>N(i,{style:M.separator}),contentContainerStyle:M.listContent,showsVerticalScrollIndicator:false})]})}var M=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 me,useEffect as He,useMemo as Pe}from"react";import{CollapsibleSection as ne,buoyColors as ie,night as g,Settings as aa,AlertTriangle as Tt,Info as na,Zap as ia,RefreshCw as sa,Check as ze,X as Bt,Copy as Rt,Eye as la,copyToClipboard as ca,ToggleRow as da,monoFont as De}from"@buoy-gg/shared-ui/web";import{DataViewer as ua}from"@buoy-gg/shared-ui/web/dataViewer";import{Fragment as Ue,jsx as u,jsxs as b}from"react/jsx-runtime";var se="x-impersonate-user-id",Ne=true,le={reactQuery:true,redux:true,asyncStorage:false,mmkv:false};function ce({label:e,description:t,value:r,onChange:a,recommended:o,dangerous:c,detected:l}){let m=b(Ue,{children:[l!==void 0&&b(i,{style:[s.detectedBadge,l?s.detectedBadgeActive:s.detectedBadgeInactive],children:[l?u(ze,{size:10,color:ie.success}):u(Bt,{size:10,color:g.color.textTertiary}),u(p,{style:[s.detectedText,l?s.detectedTextActive:s.detectedTextInactive],children:l?"Detected":"Not Detected"})]}),o&&l!==false&&b(i,{style:s.recommendedBadge,children:[u(ia,{size:10,color:g.color.accent}),u(p,{style:s.recommendedText,children:"Recommended"})]})]});return u(da,{variant:"plain",label:e,description:t,value:r,onValueChange:a,tone:c?"warning":"accent",emphasizeLabel:c,accessory:m})}function At({headerKey:e,settings:t,showBanner:r,onSave:a,onShowBannerChange:o,detectionStatus:c}){let[l,m]=me(e),[n,d]=me(t),[y,C]=me(r),[w,P]=me(false);He(()=>{m(e)},[e]),He(()=>{d(t)},[t]),He(()=>{C(r)},[r]);let L=Pe(()=>l!==e||n.reactQuery!==t.reactQuery||n.redux!==t.redux||n.asyncStorage!==t.asyncStorage||n.mmkv!==t.mmkv,[l,n,e,t]),D=Pe(()=>l===se&&y===Ne&&n.reactQuery===le.reactQuery&&n.redux===le.redux&&n.asyncStorage===le.asyncStorage&&n.mmkv===le.mmkv,[l,y,n]),he=()=>{a(l.trim()||se,n,y)},X=()=>{m(e),d(t),C(r)},J=()=>{m(se),d(le),C(Ne),o(Ne)},O=(S,Z)=>{d(W=>({...W,[S]:Z}))},G=Pe(()=>({defaults:{headerKey:l,showBanner:y,dataNukeSettings:{reactQuery:n.reactQuery,redux:n.redux,asyncStorage:n.asyncStorage,mmkv:n.mmkv}}}),[l,y,n]),f=async()=>{let S=`defaults: {
|
|
1
|
+
"use client";var Ge=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var lr=(e,t)=>{for(var r in t)Ge(e,r,{get:t[r],enumerable:true})},et=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sr(t))!ir.call(e,o)&&o!==r&&Ge(e,o,{get:()=>t[o],enumerable:!(a=nr(t,o))||a.enumerable});return e},cr=(e,t,r)=>(et(e,t,"default"),r&&et(r,t,"default"));typeof window<"u"&&typeof globalThis.global>"u"&&(globalThis.global=globalThis);import dr from"@buoy-gg/shared-ui/web/asyncStorage";function tt(){return dr}import{useState as xe,useCallback as ee,useRef as rt,useEffect as ot}from"react";var at={};lr(at,{AccessibilityInfo:()=>pr,ActivityIndicator:()=>it,Alert:()=>co,Animated:()=>mr,AppRegistry:()=>fr,AppState:()=>Sr,Appearance:()=>yr,BackHandler:()=>br,Button:()=>io,CheckBox:()=>Nr,Clipboard:()=>vr,DeviceEventEmitter:()=>Jr,Dimensions:()=>xr,Easing:()=>Cr,FlatList:()=>Ce,I18nManager:()=>wr,Image:()=>Lr,ImageBackground:()=>Er,InteractionManager:()=>kr,Keyboard:()=>Ir,KeyboardAvoidingView:()=>Or,LayoutAnimation:()=>Tr,Linking:()=>Br,LogBox:()=>_r,Modal:()=>no,NativeEventEmitter:()=>Rr,NativeModules:()=>gr,PanResponder:()=>Ar,Picker:()=>Wr,PixelRatio:()=>Hr,Platform:()=>Pr,Pressable:()=>ao,ProgressBar:()=>Fr,RefreshControl:()=>jr,SafeAreaView:()=>Mr,ScrollView:()=>st,SectionList:()=>Kr,Share:()=>zr,StatusBar:()=>Vr,StyleSheet:()=>F,Switch:()=>so,Text:()=>p,TextInput:()=>nt,Touchable:()=>Xr,TouchableHighlight:()=>ro,TouchableNativeFeedback:()=>Qr,TouchableOpacity:()=>T,TouchableWithoutFeedback:()=>oo,UIManager:()=>Dr,Vibration:()=>Ur,View:()=>s,VirtualizedList:()=>$r,YellowBox:()=>qr,findNodeHandle:()=>lo,unstable_createElement:()=>hr,useColorScheme:()=>Zr,useLocaleContext:()=>Yr,useWindowDimensions:()=>Gr});cr(at,ur);import*as ur from"react-native-web";import{unstable_createElement as hr,NativeModules as gr,AccessibilityInfo as pr,Animated as mr,Appearance as yr,AppRegistry as fr,AppState as Sr,BackHandler as br,Clipboard as vr,Dimensions as xr,Easing as Cr,I18nManager as wr,Keyboard as Ir,InteractionManager as kr,LayoutAnimation as Tr,Linking as Br,NativeEventEmitter as Rr,PanResponder as Ar,PixelRatio as Hr,Platform as Pr,Share as zr,StyleSheet as F,UIManager as Dr,Vibration as Ur,CheckBox as Nr,FlatList as Ce,Image as Lr,ImageBackground as Er,KeyboardAvoidingView as Or,Picker as Wr,ProgressBar as Fr,RefreshControl as jr,SafeAreaView as Mr,SectionList as Kr,StatusBar as Vr,Touchable as Xr,TouchableNativeFeedback as Qr,VirtualizedList as $r,YellowBox as qr,LogBox as _r,DeviceEventEmitter as Jr,useColorScheme as Zr,useLocaleContext as Yr,useWindowDimensions as Gr}from"react-native-web";import*as R from"react-native-web";import{createElement as eo,forwardRef as to}from"react";function z(e){let t=to((a,o)=>{let{accessibilityState:c,accessibilityValue:l,...m}=a;for(let n of["busy","checked","disabled","expanded","selected"])c?.[n]!==void 0&&m[`aria-${n}`]===void 0&&(m[`aria-${n}`]=c[n]);for(let[n,d]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))l?.[n]!==void 0&&m[`aria-${d}`]===void 0&&(m[`aria-${d}`]=l[n]);return eo(e,{...m,ref:o})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var s=z(R.View),p=z(R.Text),nt=z(R.TextInput),T=z(R.TouchableOpacity),ro=z(R.TouchableHighlight),oo=z(R.TouchableWithoutFeedback),ao=z(R.Pressable),st=z(R.ScrollView),no=z(R.Modal),so=z(R.Switch),it=z(R.ActivityIndicator),io=z(R.Button),lo=R.findNodeHandle,co={alert(e,t,r,a){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 c=document.createElement("h2");if(c.textContent=e,c.style.cssText="font-size:18px;margin:0 0 12px",o.appendChild(c),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 m=r?.length?r:[{text:"OK"}],n=()=>{o.close?.(),o.remove()};for(let d of m){let y=document.createElement("button");y.type="button",y.textContent=d.text??"OK",y.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${d.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,y.onclick=()=>{n(),d.onPress?.()},l.appendChild(y)}o.addEventListener("cancel",d=>{d.preventDefault(),a?.cancelable!==false&&(n(),a?.onDismiss?.())}),o.appendChild(l),document.body.appendChild(o),o.showModal?o.showModal():o.setAttribute("open","")}};import{JsModal as uo,TabSelector as ho,ModalHeader as te,buoyColors as go,night as lt,Search as po,TickProvider as ct,windowDragProps as mo}from"@buoy-gg/shared-ui/web";import{useState as ge,useEffect as dt,useCallback as U,useSyncExternalStore as yo}from"react";import{assertAccountAccess as ut,getAccountAccess as fo,hasAccountAccess as So,subscribeAccountAccess as bo}from"@buoy-gg/shared-ui/web";var ht=[/\/symbolicate$/,/\/logs$/,/\/debugger-proxy/,/\/reload$/,/\/launch-js-devtools/,/localhost:8081/,/100\.64\.\d+\.\d+:8081/,/10\.0\.\d+\.\d+:8081/,/\.hot-update\./,/__metro/];function we(e,t){for(let r of Object.keys(t))r.startsWith("__buoy")&&(e[r]=t[r])}var vo=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:[...ht]}}setConfig(e){this.config={...this.config,...e},e.ignorePatterns&&(this.config.ignorePatterns=[...ht,...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 a=this,o=async function(d,y){let C=a.extractUrl(d);if(a.shouldInjectHeader(C)){let w=y?.headers??(typeof d=="object"&&"headers"in d?d.headers:void 0),P=new Headers(w);return P.set(a.config.headerKey,a.config.userId),a.originalFetch(d,{...y,headers:P})}return a.originalFetch(d,y)};we(o,e),this.patchedFetch=o,globalThis.fetch=this.patchedFetch;let c=function(d,y,C=true,w,P){let L=this;L._impersonateUrl=typeof y=="string"?y:y.href;let D=typeof y=="string"?y:y.toString();return a.originalXHROpen.call(this,d,D,C,w,P)},l=function(d){let y=this;return y._impersonateUrl&&a.shouldInjectHeader(y._impersonateUrl)&&this.setRequestHeader(a.config.headerKey,a.config.userId),a.originalXHRSend.call(this,d)};we(c,t),we(l,r),this.patchedXHROpen=c,this.patchedXHRSend=l,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend;let m=globalThis,n=m.__buoyHeaderInjectors??(m.__buoyHeaderInjectors=[]);n.includes(this.reportHeader)||n.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)}},re=null;function E(){return re||(re=new vo),re}function xo(){E().startListening()}function Co(){E().stopListening()}function gt(e){E().setConfig(e)}function wo(){return re?.isImpersonating??false}function Io(){return re?.getConfig().userId??null}var oe="@buoy/impersonate/state",ko=10,pt={reactQuery:true,redux:true,asyncStorage:false,mmkv:false},Y={isActive:false,isPaused:false,currentUser:null,headerKey:"x-impersonate-user-id",ignorePatterns:[],dataNukeSettings:pt,showBanner:true,history:[]},Ie=false,mt={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{}}},To=class{constructor(){this.state={...Y};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=fo().status;r==="admitted"?e=true:r==="locked"&&e&&(e=false,this.disposeAccountSession())};bo(t),t()}),typeof localStorage<"u"?this.storageReadyPromise=Promise.resolve():this.storageReadyPromise=new Promise(e=>{this.resolveStorageReady=e})}loadFromStorage(){try{let e=mt.getItem(oe),t=this.getEffectiveDefaults();if(e){let r=JSON.parse(e);this.state={...Y,headerKey:r.headerKey??t.headerKey,ignorePatterns:r.ignorePatterns??Y.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={...Y,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??Y.headerKey,dataNukeSettings:{...pt,...this.developerDefaults?.dataNukeSettings},showBanner:this.developerDefaults?.showBanner??Y.showBanner}}getDeveloperDefaults(){return this.developerDefaults}async initializeAsync(e){if(e){this.asyncStorageRef=e;try{let t=await e.getItem(oe);if(console.log(`[impersonate] initializeAsync read STORAGE_KEY=${oe} 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(ut(),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,ko);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(`[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(ut(),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(!Ie){Ie=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(()=>{Ie=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;gt({headerKey:this.state.headerKey,userId:e?this.state.currentUser?.id??null:null,ignorePatterns:this.state.ignorePatterns.map(t=>new RegExp(t)),gate:So}),E().isListening||E().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(oe,t),console.log(`[impersonate] persist -> AsyncStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`)):(mt.setItem(oe,t),console.log(`[impersonate] persist -> localStorage isActive=${e.isActive} userId=${e.currentUser?.id??"null"}`))}catch(r){console.warn("[impersonate] persist failed",r)}}notify(){this.listeners.forEach(e=>{try{e(this.state)}catch{}})}},h=new To;function yt(e={}){let[t,r]=ge(""),[a,o]=ge([]),[c,l]=ge(false),[m,n]=ge(null),d=yo(h.subscribe,h.getSnapshot,h.getSnapshot);dt(()=>{h.registerNukeCallbacks({reactQuery:e.onClearReactQuery,redux:e.onClearRedux,asyncStorage:e.onClearAsyncStorage,mmkv:e.onClearMMKV})},[e.onClearReactQuery,e.onClearRedux,e.onClearAsyncStorage,e.onClearMMKV]),dt(()=>{let f=true;return(async()=>{try{let S=await import("@buoy-gg/shared-ui/web/asyncStorage").then(W=>W.default),Z={getItem:W=>S.getItem(W),setItem:(W,be)=>S.setItem(W,be)};h.setAsyncStorage(Z),f&&await h.initializeAsync(Z)}catch{}})(),E().isListening||E().startListening(),()=>{f=false}},[]);let y=U(async f=>{if(r(f),n(null),!f.trim()){o([]);return}if(!e.onSearchUsers){n("Search not configured"),o([]);return}l(true);try{let S=await e.onSearchUsers(f);o(S)}catch(S){n(S instanceof Error?S.message:"Search failed"),o([])}finally{l(false)}},[e.onSearchUsers]),C=U(()=>{r(""),o([]),n(null)},[]),w=U(async f=>{await h.startImpersonation(f)},[]),P=U(async()=>{await h.stopImpersonation()},[]),L=U(async f=>{await h.quickSwitch(f)},[]),D=U(async f=>{await h.updateSettings({headerKey:f})},[]),he=U(async f=>{await h.updateSettings({ignorePatterns:f})},[]),X=U(async f=>{await h.updateSettings({dataNukeSettings:f})},[]),J=U(async f=>{await h.updateSettings({showBanner:f})},[]),O=U(async f=>{await h.removeFromHistory(f)},[]),G=U(async()=>{await h.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:a,isSearching:c,searchError:m,searchUsers:y,clearSearch:C,startImpersonation:w,stopImpersonation:P,quickSwitch:L,updateHeaderKey:D,updateIgnorePatterns:he,updateDataNukeSettings:X,updateShowBanner:J,removeFromHistory:O,clearHistory:G}}import{useCallback as Bo}from"react";import{dispatchToolAction as ft,getToolAdapters as Ro}from"@buoy-gg/shared-ui/web";function Ao(){let e=!!Ro().query,t=Bo(async()=>{await ft("query","clearQueryCache"),await ft("query","clearMutationCache")},[]);return{isAvailable:e,error:e?null:"Connect React Query to Buoy or provide onClearReactQuery.",clearCache:e?t:null}}import{useCallback as Ho}from"react";import{dispatchToolAction as Po,getToolAdapters as zo}from"@buoy-gg/shared-ui/web";var Do="@@RESET";function Uo({resetActionType:e=Do}={}){let t=!!zo().redux,r=Ho(async()=>{await Po("redux","dispatch",{action:{type:e}})},[e]);return{isAvailable:t,error:t?null:"Connect Redux to Buoy or provide onClearRedux.",resetStore:t?r:null}}import{useCallback as No,useMemo as Lo,useState as St,useEffect as Eo}from"react";var ke=false;function Oo(){let[e,t]=St(null),[r,a]=St(null);Eo(()=>{let c=tt();c?(t(c),a(null)):a("@react-native-async-storage/async-storage is not installed")},[]);let o=No(async()=>{if(!ke){ke=true;try{if(e){let c=(await e.getAllKeys()).filter(l=>!l.startsWith("@buoy/")&&!l.startsWith("@buoy-"));c.length>0&&await e.multiRemove([...c])}}finally{setTimeout(()=>{ke=false},100)}}},[e]);return Lo(()=>!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 Wo}from"react";import{SectionHeader as Te,EmptyState as Fo,night as k,Search as jo,AlertTriangle as bt,Users as Mo}from"@buoy-gg/shared-ui/web";import{buoyColors as Be,night as A,Play as Ko,X as Vo,PowerToggleButton as Xo,monoFont as Qo}from"@buoy-gg/shared-ui/web";import{useMemo as vt}from"react";import{buoyColors as $o,night as qo}from"@buoy-gg/shared-ui/web";import{jsx as Re,jsxs as _o}from"react/jsx-runtime";var xt=["#6366F1","#8B5CF6","#EC4899","#F43F5E","#F97316","#EAB308","#22C55E","#14B8A6","#06B6D4","#3B82F6"],Jo={small:{container:24,font:10,indicator:8},medium:{container:36,font:14,indicator:10},large:{container:44,font:16,indicator:12}};function Zo(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 Yo(e){let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return xt[Math.abs(t)%xt.length]}function Ae({userId:e,name:t,size:r="medium",showActiveIndicator:a=false,backgroundColor:o}){let c=Jo[r],l=vt(()=>o??Yo(e),[e,o]),m=vt(()=>Zo(t),[t]);return _o(s,{style:pe.wrapper,children:[Re(s,{style:[pe.container,{width:c.container,height:c.container,borderRadius:c.container/2,backgroundColor:l}],children:Re(p,{style:[pe.initials,{fontSize:c.font}],children:m})}),a&&Re(s,{style:[pe.indicator,{width:c.indicator,height:c.indicator,borderRadius:c.indicator/2,right:-1,bottom:-1}]})]})}var pe=F.create({wrapper:{position:"relative"},container:{alignItems:"center",justifyContent:"center"},initials:{color:"#FFFFFF",fontWeight:"600",letterSpacing:.5},indicator:{position:"absolute",backgroundColor:$o.success,borderWidth:2,borderColor:qo.color.surface}});import{jsx as H,jsxs as ae}from"react/jsx-runtime";function Ct({user:e,isActive:t=false,onPress:r,onStop:a,onRemove:o,showRemoveButton:c=false,lastUsedTime:l,variant:m="default"}){let n=e.displayName||e.email||e.id,d=e.email&&e.displayName,y=typeof e.metadata?.role=="string"?e.metadata.role:null;return ae(T,{testID:`buoy-impersonate-user-${e.id}`,style:[I.container,t&&I.activeContainer,m==="compact"&&I.compactContainer],onPress:r,disabled:t,activeOpacity:.7,children:[H(s,{style:I.avatarSection,children:H(Ae,{userId:e.id,name:n,size:m==="compact"?"small":"medium",showActiveIndicator:t})}),ae(s,{style:I.content,children:[ae(s,{style:I.nameRow,children:[H(p,{style:[I.name,t&&I.activeName],numberOfLines:1,children:n}),y?H(s,{style:I.roleBadge,children:H(p,{style:I.roleBadgeText,children:y.toUpperCase()})}):null]}),d&&H(p,{style:I.email,numberOfLines:1,children:e.email}),H(s,{style:I.metadataRow,children:ae(p,{style:I.userId,children:["ID: ",e.id]})})]}),ae(s,{style:I.actions,children:[t?H(Xo,{isEnabled:true,onToggle:a||(()=>{}),accessibilityLabel:"Stop impersonation"}):H(T,{style:I.actionButton,onPress:r,activeOpacity:.7,children:H(Ko,{size:14,color:A.color.onAccent})}),c&&o&&!t&&H(T,{style:I.removeButton,onPress:o,activeOpacity:.7,children:H(Vo,{size:12,color:A.color.textTertiary})})]}),l?H(p,{style:I.lastUsed,children:l}):null]})}var I=F.create({container:{flexDirection:"row",alignItems:"center",backgroundColor:A.color.surface,borderRadius:10,borderWidth:1,borderColor:A.color.border,padding:12,gap:12},activeContainer:{backgroundColor:Be.success+"10",borderColor:Be.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:A.color.text,flexShrink:1},activeName:{color:Be.success},roleBadge:{backgroundColor:A.color.surfaceElevated,paddingHorizontal:6,paddingVertical:2,borderRadius:4},roleBadgeText:{fontSize:9,fontWeight:"700",color:A.color.textTertiary,letterSpacing:.5},email:{fontSize:13,color:A.color.textSecondary,marginBottom:4},metadataRow:{flexDirection:"row",alignItems:"center",gap:4},userId:{fontSize:11,color:A.color.textTertiary,fontFamily:Qo},lastUsed:{position:"absolute",bottom:8,right:10,fontSize:10,color:A.color.textTertiary},actions:{flexDirection:"row",alignItems:"center",gap:8,flexShrink:0},actionButton:{width:36,height:36,borderRadius:8,backgroundColor:A.color.accent,alignItems:"center",justifyContent:"center"},removeButton:{width:28,height:28,borderRadius:6,backgroundColor:A.color.surfaceElevated,borderWidth:1,borderColor:A.color.border,alignItems:"center",justifyContent:"center"}});import{jsx as v,jsxs as j}from"react/jsx-runtime";function wt({currentUser:e,searchQuery:t,searchResults:r,isSearching:a,searchError:o,onSelectUser:c,onStopImpersonation:l,searchAvailable:m=true}){let n=Wo(({item:d})=>{let y=e?.id===d.id;return v(Ct,{user:d,isActive:y,onPress:()=>!y&&c(d),onStop:y?l:void 0})},[e,c,l]);return j(s,{style:x.container,children:[!m&&v(s,{style:x.section,children:j(s,{style:x.warningCard,children:[v(bt,{size:18,color:k.color.warning}),j(s,{style:x.warningContent,children:[v(p,{style:x.warningTitle,children:"Search Not Available"}),v(p,{style:x.warningText,children:"Configure the onSearchUsers callback to enable user search."})]})]})}),a&&j(s,{style:x.loadingContainer,children:[v(it,{size:"small",color:k.color.accent}),v(p,{style:x.loadingText,children:"Searching users..."})]}),o?v(s,{style:x.section,children:j(s,{style:x.errorCard,children:[v(bt,{size:16,color:k.color.danger}),v(p,{style:x.errorText,children:o})]})}):null,r.length>0&&j(s,{style:x.resultsSection,children:[j(Te,{children:[v(Te.Title,{children:"Results"}),v(Te.Badge,{count:r.length})]}),v(Ce,{data:r,keyExtractor:d=>d.id,renderItem:n,ItemSeparatorComponent:()=>v(s,{style:x.separator}),contentContainerStyle:x.listContent,showsVerticalScrollIndicator:false})]}),!!t&&!a&&r.length===0&&!o&&j(s,{style:x.emptyStateContainer,children:[v(s,{style:x.emptyStateIcon,children:v(Mo,{size:28,color:k.color.textTertiary})}),v(p,{style:x.emptyStateTitle,children:"No users found"}),j(p,{style:x.emptyStateDescription,children:['No results for "',t,'"']}),v(p,{style:x.emptyStateHint,children:"Try a different search term"})]}),!t&&r.length===0&&!a&&m&&v(Fo,{title:"Search for users",description:"Tap the search icon in the header to find users by email, name, or ID",icon:jo,variant:"minimal"})]})}var x=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:k.color.textSecondary},resultsSection:{flex:1,paddingHorizontal:16},listContent:{paddingBottom:16},separator:{height:8},warningCard:{flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:k.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:k.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:14,fontWeight:"600",color:k.color.warning,marginBottom:4},warningText:{fontSize:13,color:k.color.textSecondary,lineHeight:18},errorCard:{flexDirection:"row",alignItems:"center",gap:10,backgroundColor:k.color.dangerSoft,borderRadius:10,borderWidth:1,borderColor:k.color.danger+"25",padding:12},errorText:{flex:1,fontSize:13,color:k.color.danger},emptyStateContainer:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:32,paddingVertical:48},emptyStateIcon:{width:56,height:56,borderRadius:28,backgroundColor:k.color.surfaceElevated,alignItems:"center",justifyContent:"center",marginBottom:16},emptyStateTitle:{fontSize:16,fontWeight:"600",color:k.color.text,marginBottom:6},emptyStateDescription:{fontSize:14,color:k.color.textSecondary,textAlign:"center",marginBottom:8},emptyStateHint:{fontSize:12,color:k.color.textTertiary}});import{useCallback as Go}from"react";import{night as Q,Trash2 as ea,useRelativeTime as ta,ToolEmptyState as ra}from"@buoy-gg/shared-ui/web";import{jsx as N,jsxs as It}from"react/jsx-runtime";function oa({item:e,isActive:t,onSelect:r,onStop:a,onRemove:o,showRemoveButton:c}){let l=ta(new Date(e.lastUsedAt));return N(Ct,{user:e.user,isActive:t,onPress:()=>!t&&r(e.user),onStop:t?a:void 0,onRemove:o,showRemoveButton:c,lastUsedTime:l})}function kt({history:e,currentUserId:t,onSelectUser:r,onStopImpersonation:a,onRemoveFromHistory:o,onClearHistory:c}){let l=Go(({item:m})=>{let n=t===m.user.id;return N(oa,{item:m,isActive:n,onSelect:r,onStop:a,onRemove:o?()=>o(m.user.id):void 0,showRemoveButton:!!o})},[t,r,a,o]);return e.length===0?N(ra,{testID:"buoy-impersonate-history-empty",otto:"disguise",title:"No History",message:"Users you impersonate will appear here for quick access"}):It(s,{style:M.container,children:[It(s,{style:M.headerRow,children:[N(p,{style:M.headerTitle,children:"Recent"}),N(s,{style:M.headerBadge,children:N(p,{style:M.headerBadgeText,children:e.length})}),N(s,{style:M.headerSpacer}),c&&N(T,{style:M.clearButton,onPress:c,activeOpacity:.7,children:N(ea,{size:12,color:Q.color.textTertiary})})]}),N(Ce,{data:e,keyExtractor:m=>m.user.id,renderItem:l,ItemSeparatorComponent:()=>N(s,{style:M.separator}),contentContainerStyle:M.listContent,showsVerticalScrollIndicator:false})]})}var M=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 me,useEffect as He,useMemo as Pe}from"react";import{CollapsibleSection as ne,buoyColors as se,night as g,Settings as aa,AlertTriangle as Tt,Info as na,Zap as sa,RefreshCw as ia,Check as ze,X as Bt,Copy as Rt,Eye as la,copyToClipboard as ca,ToggleRow as da,monoFont as De}from"@buoy-gg/shared-ui/web";import{DataViewer as ua}from"@buoy-gg/shared-ui/web/dataViewer";import{Fragment as Ue,jsx as u,jsxs as b}from"react/jsx-runtime";var ie="x-impersonate-user-id",Ne=true,le={reactQuery:true,redux:true,asyncStorage:false,mmkv:false};function ce({label:e,description:t,value:r,onChange:a,recommended:o,dangerous:c,detected:l}){let m=b(Ue,{children:[l!==void 0&&b(s,{style:[i.detectedBadge,l?i.detectedBadgeActive:i.detectedBadgeInactive],children:[l?u(ze,{size:10,color:se.success}):u(Bt,{size:10,color:g.color.textTertiary}),u(p,{style:[i.detectedText,l?i.detectedTextActive:i.detectedTextInactive],children:l?"Detected":"Not Detected"})]}),o&&l!==false&&b(s,{style:i.recommendedBadge,children:[u(sa,{size:10,color:g.color.accent}),u(p,{style:i.recommendedText,children:"Recommended"})]})]});return u(da,{variant:"plain",label:e,description:t,value:r,onValueChange:a,tone:c?"warning":"accent",emphasizeLabel:c,accessory:m})}function At({headerKey:e,settings:t,showBanner:r,onSave:a,onShowBannerChange:o,detectionStatus:c}){let[l,m]=me(e),[n,d]=me(t),[y,C]=me(r),[w,P]=me(false);He(()=>{m(e)},[e]),He(()=>{d(t)},[t]),He(()=>{C(r)},[r]);let L=Pe(()=>l!==e||n.reactQuery!==t.reactQuery||n.redux!==t.redux||n.asyncStorage!==t.asyncStorage||n.mmkv!==t.mmkv,[l,n,e,t]),D=Pe(()=>l===ie&&y===Ne&&n.reactQuery===le.reactQuery&&n.redux===le.redux&&n.asyncStorage===le.asyncStorage&&n.mmkv===le.mmkv,[l,y,n]),he=()=>{a(l.trim()||ie,n,y)},X=()=>{m(e),d(t),C(r)},J=()=>{m(ie),d(le),C(Ne),o(Ne)},O=(S,Z)=>{d(W=>({...W,[S]:Z}))},G=Pe(()=>({defaults:{headerKey:l,showBanner:y,dataNukeSettings:{reactQuery:n.reactQuery,redux:n.redux,asyncStorage:n.asyncStorage,mmkv:n.mmkv}}}),[l,y,n]),f=async()=>{let S=`defaults: {
|
|
2
2
|
headerKey: '${l}',
|
|
3
3
|
showBanner: ${y},
|
|
4
4
|
dataNukeSettings: {
|
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
asyncStorage: ${n.asyncStorage},
|
|
8
8
|
mmkv: ${n.mmkv},
|
|
9
9
|
},
|
|
10
|
-
},`;try{await ca(S),P(true),setTimeout(()=>P(false),2e3)}catch{}};return b(it,{style:s.container,contentContainerStyle:s.contentContainer,children:[L&&u(i,{style:s.actionBar,children:b(i,{style:s.actionBarContent,children:[u(p,{style:s.unsavedText,children:"Unsaved changes"}),b(i,{style:s.actionButtons,children:[b(T,{style:s.discardButton,onPress:X,children:[u(Bt,{size:14,color:g.color.textSecondary}),u(p,{style:s.discardButtonText,children:"Discard"})]}),b(T,{style:s.saveButton,onPress:he,children:[u(ze,{size:14,color:g.color.onAccent}),u(p,{style:s.saveButtonText,children:"Save"})]})]})]})}),u(ne,{title:"Header Configuration",icon:aa,defaultOpen:true,variant:"bordered",children:b(i,{style:s.sectionContent,children:[u(p,{style:s.inputLabel,children:"Header Key"}),u(nt,{style:s.input,value:l,onChangeText:m,placeholder:"x-impersonate-user-id",placeholderTextColor:g.color.placeholder,autoCapitalize:"none",autoCorrect:false}),b(i,{style:s.inputFooter,children:[u(p,{style:s.helperText,children:"The HTTP header key used for impersonation. Value will be the user ID."}),l!==se&&u(T,{onPress:()=>m(se),style:s.resetLink,children:u(p,{style:s.resetLinkText,children:"Reset to default"})})]})]})}),u(ne,{title:"Display",icon:la,defaultOpen:true,variant:"bordered",children:u(i,{style:s.sectionContent,children:u(i,{style:s.togglesCard,children:u(ce,{label:"Floating Banner",description:"Show a floating banner when impersonation is active",value:y,onChange:S=>{C(S),o(S)},recommended:true})})})}),u(ne,{title:"Data Clearing",icon:Tt,defaultOpen:true,variant:"bordered",children:b(i,{style:s.sectionContent,children:[u(p,{style:s.sectionDescription,children:"Choose what data to clear when impersonation starts or stops. This ensures you see fresh data for the impersonated user."}),b(i,{style:s.togglesCard,children:[u(ce,{label:"React Query",description:"Clear query cache and cancel pending queries",value:n.reactQuery,onChange:S=>O("reactQuery",S),recommended:true,detected:c?.reactQuery}),u(i,{style:s.divider}),u(ce,{label:"Redux",description:"Reset Redux store to initial state",value:n.redux,onChange:S=>O("redux",S),recommended:true,detected:c?.redux})]}),b(i,{style:s.advancedSection,children:[u(p,{style:s.advancedLabel,children:"Storage Options"}),b(i,{style:[s.togglesCard,s.dangerousCard],children:[u(ce,{label:"AsyncStorage",description:"Clear app data (preserves @buoy/* keys)",value:n.asyncStorage,onChange:S=>O("asyncStorage",S),dangerous:true,detected:c?.asyncStorage}),u(i,{style:s.divider}),u(ce,{label:"MMKV",description:"Clear MMKV storage (preserves @buoy/* keys)",value:n.mmkv,onChange:S=>O("mmkv",S),dangerous:true,detected:c?.mmkv})]})]}),(n.asyncStorage||n.mmkv)&&b(i,{style:s.warningCard,children:[u(Tt,{size:16,color:g.color.warning}),b(i,{style:s.warningContent,children:[u(p,{style:s.warningTitle,children:"Storage Clearing Enabled"}),u(p,{style:s.warningText,children:"This will remove app data like settings and cached content. Auth tokens managed by @buoy/* are preserved."})]})]})]})}),!D&&b(T,{style:s.restoreButton,onPress:J,children:[u(sa,{size:14,color:g.color.textSecondary}),u(p,{style:s.restoreButtonText,children:"Restore Defaults"})]}),u(ne,{title:"How It Works",icon:na,defaultOpen:false,variant:"bordered",children:b(i,{style:s.sectionContent,children:[u(p,{style:s.infoText,children:"When impersonation is enabled, the configured header is automatically added to all outgoing fetch and XMLHttpRequest calls."}),u(p,{style:[s.infoText,s.infoTextSpaced],children:"Your backend should check for this header and return data for the specified user ID instead of the authenticated user."}),b(i,{style:s.codeBlock,children:[u(p,{style:s.codeComment,children:"// Example request header"}),b(p,{style:s.codeText,children:[l||"x-impersonate-user-id",": ",u(p,{style:s.codeValue,children:"user_123"})]})]})]})}),u(ne,{title:"Export Configuration",icon:Rt,defaultOpen:false,variant:"bordered",children:b(i,{style:s.sectionContent,children:[u(p,{style:s.infoText,children:"Copy current settings to use in createImpersonateTool()."}),u(i,{style:s.dataViewerContainer,children:u(ua,{title:"",data:G,showTypeFilter:true,rawMode:true,initialExpanded:true})}),u(T,{style:s.copyButton,onPress:f,children:w?b(Ue,{children:[u(ze,{size:14,color:ie.success}),u(p,{style:[s.copyButtonText,s.copySuccessText],children:"Copied!"})]}):b(Ue,{children:[u(Rt,{size:14,color:g.color.accent}),u(p,{style:s.copyButtonText,children:"Copy Config"})]})})]})})]})}var s=F.create({container:{flex:1},contentContainer:{padding:16,gap:12,paddingBottom:32},actionBar:{backgroundColor:g.color.accentSoft,borderRadius:10,borderWidth:1,borderColor:g.color.accentBorder,padding:12},actionBarContent:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},unsavedText:{fontSize:13,fontWeight:"500",color:g.color.accent},actionButtons:{flexDirection:"row",gap:8},saveButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:g.color.accent,paddingHorizontal:14,paddingVertical:8,borderRadius:6},saveButtonText:{fontSize:13,fontWeight:"600",color:g.color.onAccent},discardButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:g.color.surfaceElevated,paddingHorizontal:14,paddingVertical:8,borderRadius:6,borderWidth:1,borderColor:g.color.border},discardButtonText:{fontSize:13,fontWeight:"500",color:g.color.textSecondary},restoreButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,paddingVertical:12,borderRadius:8,borderWidth:1,borderColor:g.color.border,borderStyle:"dashed"},restoreButtonText:{fontSize:13,color:g.color.textSecondary},sectionContent:{paddingTop:8},sectionDescription:{fontSize:13,color:g.color.textSecondary,lineHeight:18,marginBottom:14},togglesCard:{backgroundColor:g.color.surface,borderRadius:10,borderWidth:1,borderColor:g.color.border,padding:4},dangerousCard:{borderColor:g.color.warning+"30"},advancedSection:{marginTop:16},advancedLabel:{fontSize:11,fontWeight:"600",color:g.color.textTertiary,textTransform:"uppercase",letterSpacing:.5,marginBottom:8,marginLeft:2},inputLabel:{fontSize:12,fontWeight:"600",color:g.color.textSecondary,marginBottom:8},input:{height:42,backgroundColor:g.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:g.color.border,paddingHorizontal:14,fontSize:14,color:g.color.text,fontFamily:De},inputFooter:{flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start",marginTop:8,gap:12},helperText:{flex:1,fontSize:12,color:g.color.textTertiary,lineHeight:16},resetLink:{paddingVertical:2},resetLinkText:{fontSize:12,color:g.color.accent,fontWeight:"500"},recommendedBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:g.color.accentSoft,paddingHorizontal:8,paddingVertical:3,borderRadius:4},recommendedText:{fontSize:10,fontWeight:"600",color:g.color.accent},detectedBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:8,paddingVertical:3,borderRadius:4},detectedBadgeActive:{backgroundColor:ie.success+"15"},detectedBadgeInactive:{backgroundColor:g.color.textTertiary+"15"},detectedText:{fontSize:10,fontWeight:"600"},detectedTextActive:{color:ie.success},detectedTextInactive:{color:g.color.textTertiary},divider:{height:1,backgroundColor:g.color.separator,marginHorizontal:12},warningCard:{marginTop:14,flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:g.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:g.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:13,fontWeight:"600",color:g.color.warning,marginBottom:4},warningText:{fontSize:12,color:g.color.textSecondary,lineHeight:17},infoText:{fontSize:13,color:g.color.textSecondary,lineHeight:19},infoTextSpaced:{marginTop:10},codeBlock:{marginTop:14,backgroundColor:g.color.bg,borderRadius:8,padding:14},codeComment:{fontSize:12,color:g.color.textTertiary,fontFamily:De,marginBottom:6},codeText:{fontSize:13,color:g.color.text,fontFamily:De},codeValue:{color:g.color.accent},dataViewerContainer:{marginTop:12,borderRadius:8,overflow:"hidden",borderWidth:1,borderColor:g.color.border},copyButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,marginTop:14,backgroundColor:g.color.accentSoft,paddingVertical:10,paddingHorizontal:16,borderRadius:8,borderWidth:1,borderColor:g.color.accentBorder},copyButtonText:{fontSize:13,fontWeight:"600",color:g.color.accent},copySuccessText:{color:ie.success}});import{jsx as B,jsxs as Le}from"react/jsx-runtime";var ha=uo,ga=[{key:"search",label:"Search"},{key:"history",label:"History"},{key:"settings",label:"Settings"}],pa=[{key:"search",label:"Search"},{key:"history",label:"History"}];function Ee({visible:e,onClose:t,onBack:r,onMinimize:a,onSearchUsers:o,onClearReactQuery:c,onClearRedux:l,onClearAsyncStorage:m,onClearMMKV:n,showSettingsTab:d=true,inline:y=false}){let C=d?ga:pa,[w,P]=xe("search"),[L,D]=xe(false),he=rt(false),[X,J]=xe(""),O=rt(null),{clearCache:G,isAvailable:f}=Ao(),{resetStore:S,isAvailable:Z}=Uo(),{clearStorage:W,isAvailable:be}=Oo(),Ot=c??G??void 0,Wt=l??S??void 0,Ft=m??W??void 0,jt={reactQuery:!!c||f,redux:!!l||Z,asyncStorage:!!m||be,mmkv:!!n},{isActive:Mt,currentUser:Ve,headerKey:Kt,dataNukeSettings:Vt,showBanner:Xt,searchQuery:Qt,searchResults:$t,isSearching:qt,searchError:_t,searchUsers:Xe,startImpersonation:Qe,stopImpersonation:$e,updateHeaderKey:qe,updateDataNukeSettings:_e,updateShowBanner:ve,history:Jt,removeFromHistory:Zt,clearHistory:Yt}=yt({onSearchUsers:o,onClearReactQuery:Ot,onClearRedux:Wt,onClearAsyncStorage:Ft,onClearMMKV:n});ot(()=>{L&&O.current&&setTimeout(()=>{O.current?.focus()},100)},[L]),ot(()=>{!d&&w==="settings"&&P("search")},[d,w]);let Gt=ee(q=>{J(q)},[]),er=ee(()=>{X.trim()&&Xe(X.trim()),D(false)},[X,Xe]),Je=ee(async q=>{await Qe(q)},[Qe]),tr=ee(async(q,or,ar)=>{await qe(q),await _e(or),await ve(ar)},[qe,_e,ve]),rr=ee(q=>{P(q),D(false)},[]),Ze=()=>Le(te,{children:[r&&B(te.Navigation,{onBack:r}),B(te.Content,{title:"",children:L?B(te.Search,{value:X,onChangeText:Gt,onCancel:()=>{J(""),D(false)},onDismiss:()=>D(false),dismissOnBlur:true,placeholder:"Search by email, name, or ID...",iconSize:14,testID:"buoy-impersonate-search-input",inputProps:{onSubmitEditing:er}}):B(ho,{tabs:C,activeTab:w,onTabChange:rr})}),B(te.Actions,{children:w==="search"&&!L&&B(T,{testID:"buoy-impersonate-search-toggle",onPress:()=>D(true),style:ye.headerActionButton,children:B(po,{size:14,color:lt.color.textSecondary})})})]});if(!e)return null;let Ye=Le(i,{style:ye.container,children:[w==="search"&&B(wt,{currentUser:Ve,isActive:Mt,searchQuery:Qt,searchResults:$t,isSearching:qt,searchError:_t,onSelectUser:Je,onStopImpersonation:$e,searchAvailable:!!o}),w==="history"&&B(kt,{history:Jt,currentUserId:Ve?.id??null,onSelectUser:Je,onStopImpersonation:$e,onRemoveFromHistory:Zt,onClearHistory:Yt}),w==="settings"&&B(At,{headerKey:Kt,settings:Vt,showBanner:Xt,onSave:tr,onShowBannerChange:ve,detectionStatus:jt})]});return y?B(ct,{children:Le(i,{style:ye.inlineRoot,children:[B(i,{style:ye.inlineHeader,...mo,children:Ze()}),Ye]})}):B(ct,{children:B(ha,{visible:e,onClose:t,onMinimize:a,header:{showToggleButton:true,customContent:Ze()},enablePersistence:true,initialMode:"bottomSheet",disableScrollWrapper:true,children:Ye})})}function ma(e){return B(Ee,{...e,inline:true,visible:true,onClose:()=>{}})}var ye=F.create({inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:go.border,backgroundColor:"transparent"},container:{flex:1},headerActionButton:{width:28,height:28,borderRadius:6,backgroundColor:lt.color.buttonSurface,justifyContent:"center",alignItems:"center"}});import{useSyncExternalStore as Ht}from"react";import{buoyColors as fe,X as ya,PowerToggleButton as fa}from"@buoy-gg/shared-ui/web";import{jsx as $,jsxs as Oe}from"react/jsx-runtime";function We({onPress:e,onStopPress:t,position:r="top",offset:a=50}){let o=Ht(h.subscribe,h.getSnapshot,h.getSnapshot);if(!o.isActive||!o.currentUser||!o.showBanner)return null;let c=async()=>{console.log("[impersonate] banner pause/resume pressed"),o.isPaused?await h.resumeImpersonation():await h.pauseImpersonation()},l=o.currentUser.displayName||o.currentUser.email||o.currentUser.id,m=r==="top"?{top:a}:{bottom:a},n=async()=>{console.log("[impersonate] banner STOP pressed"),await h.stopImpersonation()};return $(i,{style:[K.container,m],children:Oe(i,{style:K.banner,children:[Oe(T,{style:K.userSection,onPress:e,activeOpacity:.7,children:[$(Ae,{userId:o.currentUser.id,name:l,size:"small",showActiveIndicator:false}),$(p,{style:[K.userName,o.isPaused&&K.userNamePaused],numberOfLines:1,children:l})]}),$(fa,{isEnabled:!o.isPaused,onToggle:c,size:"small",accessibilityLabel:"Toggle impersonation"}),$(T,{style:K.closeButton,onPress:n,activeOpacity:.7,children:$(ya,{size:12,color:"rgba(255, 255, 255, 0.5)"})})]})})}function Sa({onPress:e}){let t=Ht(h.subscribe,h.getSnapshot,h.getSnapshot);return!t.isActive||!t.currentUser?null:Oe(T,{style:K.minimalBanner,onPress:e,activeOpacity:.8,children:[$(i,{style:K.minimalDot}),$(p,{style:K.minimalText,children:"IMP"})]})}var K=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:fe.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:fe.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:fe.success},minimalText:{fontSize:10,fontWeight:"700",color:fe.success,letterSpacing:.5}});import{isOverWireBudget as ba}from"@buoy-gg/shared-ui/web";var Fe=null;function va(e){Fe=e}var je=2*1024,xa=16*1024,Pt=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function Ca(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<=je?e:`${e.slice(0,je)}\u2026 [${e.length-je} more]`}function wa(e){if(!e)return e;let t=typeof e.role=="string"?e.role:void 0;return ba(e,xa)?t?{role:t,...Pt}:{...Pt}:e}function Me(e){return{...e,avatarUrl:Ca(e.avatarUrl),metadata:wa(e.metadata)}}function zt(e){return{...e,currentUser:e.currentUser?Me(e.currentUser):null,history:e.history.map(t=>({...t,user:Me(t.user)}))}}var Dt=new Set;function Ia(e){for(let t of e)t&&typeof t=="object"&&t.id&&Dt.add(String(t.id))}function ka(e){if(!e||typeof e!="object"||!e.id)return false;if(Dt.has(String(e.id)))return true;let t=h.getState();return t.currentUser?.id===e.id?true:t.history.some(r=>r.user.id===e.id)}function Ut(e){return{searchUsers:async t=>{let r=String(t?.query??""),a=await e(r);return Array.isArray(a)&&Ia(a),Array.isArray(a)?a.map(Me):a},startImpersonation:async t=>{let r=t?.user;if(!ka(r))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.");return await h.startImpersonation(r),{ok:true,userId:r.id}},stopImpersonation:()=>h.stopImpersonation(),pauseImpersonation:()=>h.pauseImpersonation(),resumeImpersonation:()=>h.resumeImpersonation(),updateSettings:t=>{let r=t??{},a=r.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in r)?r:void 0);if(!a)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return h.updateSettings(a)},removeFromHistory:t=>h.removeFromHistory(t.userId),clearHistory:()=>h.clearHistory()}}function Ta({onSearchUsers:e}){return{version:1,getSnapshot:()=>zt(h.getState()),subscribe:t=>h.subscribe(t),actions:Ut(e)}}var Ba={dispose:()=>h.disposeAccountSession(),version:1,getSnapshot:()=>zt(h.getState()),subscribe:e=>h.subscribe(e),actions:Ut(e=>{if(!Fe)throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()");return Fe(e)})};import{ImpersonateIcon as Nt,IMPERSONATE_ICON_COLOR as Ra}from"@buoy-gg/shared-ui/web";import{jsx as Lt}from"react/jsx-runtime";var Et=false;async function Aa(){if(!(typeof window>"u"||Et)){Et=true,console.log("[impersonate] bootstrap: start"),E().isListening||E().startListening();try{let e=tt();if(!e||typeof e.getItem!="function"){console.warn("[impersonate] bootstrap: AsyncStorage shape unexpected",Object.keys(e??{}));return}let t={getItem:r=>e.getItem(r),setItem:(r,a)=>e.setItem(r,a)};h.setAsyncStorage(t),console.log("[impersonate] bootstrap: AsyncStorage adapter installed"),await h.initializeAsync(t),console.log("[impersonate] bootstrap: initializeAsync done")}catch(e){console.warn("[impersonate] bootstrap: failed",e)}}}function Ha(e){let{id:t="impersonate",name:r="IMPERSONATE",description:a="User impersonation for admin testing",defaults:o,showSettingsTab:c=true,onSearchUsers:l,onClearReactQuery:m,onClearRedux:n,onClearAsyncStorage:d,onClearMMKV:y}=e;return o&&h.setDeveloperDefaults(o),va(l??null),Aa(),{id:t,name:r,description:a,slot:"both",icon:({size:C,slot:w})=>Lt(Nt,{size:w==="dial"?C*1.5:C,color:Ra}),component:C=>Lt(Ee,{...C,onSearchUsers:l,onClearReactQuery:m,onClearRedux:n,onClearAsyncStorage:d,onClearMMKV:y,showSettingsTab:c}),props:{enableSharedModalDimensions:false},Banner:We}}import{jsx as Pa}from"react/jsx-runtime";function za(){return Pa(We,{position:"top",offset:50})}import{buoyColors as de,night as ue,X as Da}from"@buoy-gg/shared-ui/web";import{jsx as _,jsxs as Se}from"react/jsx-runtime";function Ua({user:e,onStopImpersonation:t}){let r=e.displayName||e.email||e.id;return Se(i,{style:V.container,children:[Se(i,{style:V.userSection,children:[_(Ae,{userId:e.id,name:r,size:"small",showActiveIndicator:false}),_(i,{style:V.userInfo,children:_(p,{style:V.userName,numberOfLines:1,children:r})})]}),Se(i,{style:V.statusPill,children:[_(i,{style:V.pulseDot}),_(p,{style:V.statusText,children:"Active"})]}),Se(T,{style:V.stopButton,onPress:t,activeOpacity:.7,children:[_(Da,{size:12,color:ue.color.danger}),_(p,{style:V.stopButtonText,children:"Stop"})]})]})}var V=F.create({container:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:10,paddingHorizontal:16,backgroundColor:de.success+"10",borderBottomWidth:1,borderBottomColor:de.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:ue.color.text},statusPill:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:de.success+"20",paddingHorizontal:10,paddingVertical:5,borderRadius:12},pulseDot:{width:6,height:6,borderRadius:3,backgroundColor:de.success},statusText:{fontSize:11,fontWeight:"600",color:de.success,textTransform:"uppercase",letterSpacing:.5},stopButton:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:12,paddingVertical:6,backgroundColor:ue.color.dangerSoft,borderRadius:6,borderWidth:1,borderColor:ue.color.danger+"30"},stopButtonText:{fontSize:12,fontWeight:"600",color:ue.color.danger}});import{useCallback as Ke,useSyncExternalStore as Na}from"react";function La(){let e=Na(h.subscribe,h.getSnapshot,h.getSnapshot),t=Ke(async o=>{await h.quickSwitch(o)},[]),r=Ke(async o=>{await h.removeFromHistory(o)},[]),a=Ke(async()=>{await h.clearHistory()},[]);return{history:e.history,currentUserId:e.currentUser?.id??null,quickSwitch:t,removeFromHistory:r,clearHistory:a}}export{At as DataNukeSettingsComponent,We as ImpersonateBanner,Sa as ImpersonateBannerMinimal,kt as ImpersonateHistoryList,Nt as ImpersonateIcon,Ee as ImpersonateModal,za as ImpersonateOverlay,Ua as ImpersonateStatusBar,ma as ImpersonateToolView,wt as UserSearchView,Ta as createImpersonateSyncAdapter,Ha as createImpersonateTool,Io as getImpersonatedUserId,E as impersonateListener,h as impersonateStore,Ba as impersonateSyncAdapter,wo as isImpersonating,gt as setImpersonateConfig,xo as startImpersonateListener,Co as stopImpersonateListener,yt as useImpersonate,La as useImpersonateHistory};
|
|
10
|
+
},`;try{await ca(S),P(true),setTimeout(()=>P(false),2e3)}catch{}};return b(st,{style:i.container,contentContainerStyle:i.contentContainer,children:[L&&u(s,{style:i.actionBar,children:b(s,{style:i.actionBarContent,children:[u(p,{style:i.unsavedText,children:"Unsaved changes"}),b(s,{style:i.actionButtons,children:[b(T,{style:i.discardButton,onPress:X,children:[u(Bt,{size:14,color:g.color.textSecondary}),u(p,{style:i.discardButtonText,children:"Discard"})]}),b(T,{style:i.saveButton,onPress:he,children:[u(ze,{size:14,color:g.color.onAccent}),u(p,{style:i.saveButtonText,children:"Save"})]})]})]})}),u(ne,{title:"Header Configuration",icon:aa,defaultOpen:true,variant:"bordered",children:b(s,{style:i.sectionContent,children:[u(p,{style:i.inputLabel,children:"Header Key"}),u(nt,{style:i.input,value:l,onChangeText:m,placeholder:"x-impersonate-user-id",placeholderTextColor:g.color.placeholder,autoCapitalize:"none",autoCorrect:false}),b(s,{style:i.inputFooter,children:[u(p,{style:i.helperText,children:"The HTTP header key used for impersonation. Value will be the user ID."}),l!==ie&&u(T,{onPress:()=>m(ie),style:i.resetLink,children:u(p,{style:i.resetLinkText,children:"Reset to default"})})]})]})}),u(ne,{title:"Display",icon:la,defaultOpen:true,variant:"bordered",children:u(s,{style:i.sectionContent,children:u(s,{style:i.togglesCard,children:u(ce,{label:"Floating Banner",description:"Show a floating banner when impersonation is active",value:y,onChange:S=>{C(S),o(S)},recommended:true})})})}),u(ne,{title:"Data Clearing",icon:Tt,defaultOpen:true,variant:"bordered",children:b(s,{style:i.sectionContent,children:[u(p,{style:i.sectionDescription,children:"Choose what data to clear when impersonation starts or stops. This ensures you see fresh data for the impersonated user."}),b(s,{style:i.togglesCard,children:[u(ce,{label:"React Query",description:"Clear query cache and cancel pending queries",value:n.reactQuery,onChange:S=>O("reactQuery",S),recommended:true,detected:c?.reactQuery}),u(s,{style:i.divider}),u(ce,{label:"Redux",description:"Reset Redux store to initial state",value:n.redux,onChange:S=>O("redux",S),recommended:true,detected:c?.redux})]}),b(s,{style:i.advancedSection,children:[u(p,{style:i.advancedLabel,children:"Storage Options"}),b(s,{style:[i.togglesCard,i.dangerousCard],children:[u(ce,{label:"AsyncStorage",description:"Clear app data (preserves @buoy/* keys)",value:n.asyncStorage,onChange:S=>O("asyncStorage",S),dangerous:true,detected:c?.asyncStorage}),u(s,{style:i.divider}),u(ce,{label:"MMKV",description:"Clear MMKV storage (preserves @buoy/* keys)",value:n.mmkv,onChange:S=>O("mmkv",S),dangerous:true,detected:c?.mmkv})]})]}),(n.asyncStorage||n.mmkv)&&b(s,{style:i.warningCard,children:[u(Tt,{size:16,color:g.color.warning}),b(s,{style:i.warningContent,children:[u(p,{style:i.warningTitle,children:"Storage Clearing Enabled"}),u(p,{style:i.warningText,children:"This will remove app data like settings and cached content. Auth tokens managed by @buoy/* are preserved."})]})]})]})}),!D&&b(T,{style:i.restoreButton,onPress:J,children:[u(ia,{size:14,color:g.color.textSecondary}),u(p,{style:i.restoreButtonText,children:"Restore Defaults"})]}),u(ne,{title:"How It Works",icon:na,defaultOpen:false,variant:"bordered",children:b(s,{style:i.sectionContent,children:[u(p,{style:i.infoText,children:"When impersonation is enabled, the configured header is automatically added to all outgoing fetch and XMLHttpRequest calls."}),u(p,{style:[i.infoText,i.infoTextSpaced],children:"Your backend should check for this header and return data for the specified user ID instead of the authenticated user."}),b(s,{style:i.codeBlock,children:[u(p,{style:i.codeComment,children:"// Example request header"}),b(p,{style:i.codeText,children:[l||"x-impersonate-user-id",": ",u(p,{style:i.codeValue,children:"user_123"})]})]})]})}),u(ne,{title:"Export Configuration",icon:Rt,defaultOpen:false,variant:"bordered",children:b(s,{style:i.sectionContent,children:[u(p,{style:i.infoText,children:"Copy current settings to use in createImpersonateTool()."}),u(s,{style:i.dataViewerContainer,children:u(ua,{title:"",data:G,showTypeFilter:true,rawMode:true,initialExpanded:true})}),u(T,{style:i.copyButton,onPress:f,children:w?b(Ue,{children:[u(ze,{size:14,color:se.success}),u(p,{style:[i.copyButtonText,i.copySuccessText],children:"Copied!"})]}):b(Ue,{children:[u(Rt,{size:14,color:g.color.accent}),u(p,{style:i.copyButtonText,children:"Copy Config"})]})})]})})]})}var i=F.create({container:{flex:1},contentContainer:{padding:16,gap:12,paddingBottom:32},actionBar:{backgroundColor:g.color.accentSoft,borderRadius:10,borderWidth:1,borderColor:g.color.accentBorder,padding:12},actionBarContent:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},unsavedText:{fontSize:13,fontWeight:"500",color:g.color.accent},actionButtons:{flexDirection:"row",gap:8},saveButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:g.color.accent,paddingHorizontal:14,paddingVertical:8,borderRadius:6},saveButtonText:{fontSize:13,fontWeight:"600",color:g.color.onAccent},discardButton:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:g.color.surfaceElevated,paddingHorizontal:14,paddingVertical:8,borderRadius:6,borderWidth:1,borderColor:g.color.border},discardButtonText:{fontSize:13,fontWeight:"500",color:g.color.textSecondary},restoreButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,paddingVertical:12,borderRadius:8,borderWidth:1,borderColor:g.color.border,borderStyle:"dashed"},restoreButtonText:{fontSize:13,color:g.color.textSecondary},sectionContent:{paddingTop:8},sectionDescription:{fontSize:13,color:g.color.textSecondary,lineHeight:18,marginBottom:14},togglesCard:{backgroundColor:g.color.surface,borderRadius:10,borderWidth:1,borderColor:g.color.border,padding:4},dangerousCard:{borderColor:g.color.warning+"30"},advancedSection:{marginTop:16},advancedLabel:{fontSize:11,fontWeight:"600",color:g.color.textTertiary,textTransform:"uppercase",letterSpacing:.5,marginBottom:8,marginLeft:2},inputLabel:{fontSize:12,fontWeight:"600",color:g.color.textSecondary,marginBottom:8},input:{height:42,backgroundColor:g.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:g.color.border,paddingHorizontal:14,fontSize:14,color:g.color.text,fontFamily:De},inputFooter:{flexDirection:"row",justifyContent:"space-between",alignItems:"flex-start",marginTop:8,gap:12},helperText:{flex:1,fontSize:12,color:g.color.textTertiary,lineHeight:16},resetLink:{paddingVertical:2},resetLinkText:{fontSize:12,color:g.color.accent,fontWeight:"500"},recommendedBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:g.color.accentSoft,paddingHorizontal:8,paddingVertical:3,borderRadius:4},recommendedText:{fontSize:10,fontWeight:"600",color:g.color.accent},detectedBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:8,paddingVertical:3,borderRadius:4},detectedBadgeActive:{backgroundColor:se.success+"15"},detectedBadgeInactive:{backgroundColor:g.color.textTertiary+"15"},detectedText:{fontSize:10,fontWeight:"600"},detectedTextActive:{color:se.success},detectedTextInactive:{color:g.color.textTertiary},divider:{height:1,backgroundColor:g.color.separator,marginHorizontal:12},warningCard:{marginTop:14,flexDirection:"row",alignItems:"flex-start",gap:12,backgroundColor:g.color.warningSoft,borderRadius:10,borderWidth:1,borderColor:g.color.warning+"25",padding:14},warningContent:{flex:1},warningTitle:{fontSize:13,fontWeight:"600",color:g.color.warning,marginBottom:4},warningText:{fontSize:12,color:g.color.textSecondary,lineHeight:17},infoText:{fontSize:13,color:g.color.textSecondary,lineHeight:19},infoTextSpaced:{marginTop:10},codeBlock:{marginTop:14,backgroundColor:g.color.bg,borderRadius:8,padding:14},codeComment:{fontSize:12,color:g.color.textTertiary,fontFamily:De,marginBottom:6},codeText:{fontSize:13,color:g.color.text,fontFamily:De},codeValue:{color:g.color.accent},dataViewerContainer:{marginTop:12,borderRadius:8,overflow:"hidden",borderWidth:1,borderColor:g.color.border},copyButton:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,marginTop:14,backgroundColor:g.color.accentSoft,paddingVertical:10,paddingHorizontal:16,borderRadius:8,borderWidth:1,borderColor:g.color.accentBorder},copyButtonText:{fontSize:13,fontWeight:"600",color:g.color.accent},copySuccessText:{color:se.success}});import{jsx as B,jsxs as Le}from"react/jsx-runtime";var ha=uo,ga=[{key:"search",label:"Search"},{key:"history",label:"History"},{key:"settings",label:"Settings"}],pa=[{key:"search",label:"Search"},{key:"history",label:"History"}];function Ee({visible:e,onClose:t,onBack:r,onMinimize:a,onSearchUsers:o,onClearReactQuery:c,onClearRedux:l,onClearAsyncStorage:m,onClearMMKV:n,showSettingsTab:d=true,inline:y=false}){let C=d?ga:pa,[w,P]=xe("search"),[L,D]=xe(false),he=rt(false),[X,J]=xe(""),O=rt(null),{clearCache:G,isAvailable:f}=Ao(),{resetStore:S,isAvailable:Z}=Uo(),{clearStorage:W,isAvailable:be}=Oo(),Ot=c??G??void 0,Wt=l??S??void 0,Ft=m??W??void 0,jt={reactQuery:!!c||f,redux:!!l||Z,asyncStorage:!!m||be,mmkv:!!n},{isActive:Mt,currentUser:Ve,headerKey:Kt,dataNukeSettings:Vt,showBanner:Xt,searchQuery:Qt,searchResults:$t,isSearching:qt,searchError:_t,searchUsers:Xe,startImpersonation:Qe,stopImpersonation:$e,updateHeaderKey:qe,updateDataNukeSettings:_e,updateShowBanner:ve,history:Jt,removeFromHistory:Zt,clearHistory:Yt}=yt({onSearchUsers:o,onClearReactQuery:Ot,onClearRedux:Wt,onClearAsyncStorage:Ft,onClearMMKV:n});ot(()=>{L&&O.current&&setTimeout(()=>{O.current?.focus()},100)},[L]),ot(()=>{!d&&w==="settings"&&P("search")},[d,w]);let Gt=ee(q=>{J(q)},[]),er=ee(()=>{X.trim()&&Xe(X.trim()),D(false)},[X,Xe]),Je=ee(async q=>{await Qe(q)},[Qe]),tr=ee(async(q,or,ar)=>{await qe(q),await _e(or),await ve(ar)},[qe,_e,ve]),rr=ee(q=>{P(q),D(false)},[]),Ze=()=>Le(te,{children:[r&&B(te.Navigation,{onBack:r}),B(te.Content,{title:"",children:L?B(te.Search,{value:X,onChangeText:Gt,onCancel:()=>{J(""),D(false)},onDismiss:()=>D(false),dismissOnBlur:true,placeholder:"Search by email, name, or ID...",iconSize:14,testID:"buoy-impersonate-search-input",inputProps:{onSubmitEditing:er}}):B(ho,{tabs:C,activeTab:w,onTabChange:rr})}),B(te.Actions,{children:w==="search"&&!L&&B(T,{testID:"buoy-impersonate-search-toggle",onPress:()=>D(true),style:ye.headerActionButton,children:B(po,{size:14,color:lt.color.textSecondary})})})]});if(!e)return null;let Ye=Le(s,{style:ye.container,children:[w==="search"&&B(wt,{currentUser:Ve,isActive:Mt,searchQuery:Qt,searchResults:$t,isSearching:qt,searchError:_t,onSelectUser:Je,onStopImpersonation:$e,searchAvailable:!!o}),w==="history"&&B(kt,{history:Jt,currentUserId:Ve?.id??null,onSelectUser:Je,onStopImpersonation:$e,onRemoveFromHistory:Zt,onClearHistory:Yt}),w==="settings"&&B(At,{headerKey:Kt,settings:Vt,showBanner:Xt,onSave:tr,onShowBannerChange:ve,detectionStatus:jt})]});return y?B(ct,{children:Le(s,{style:ye.inlineRoot,children:[B(s,{style:ye.inlineHeader,...mo,children:Ze()}),Ye]})}):B(ct,{children:B(ha,{visible:e,onClose:t,onMinimize:a,header:{showToggleButton:true,customContent:Ze()},enablePersistence:true,initialMode:"bottomSheet",disableScrollWrapper:true,children:Ye})})}function ma(e){return B(Ee,{...e,inline:true,visible:true,onClose:()=>{}})}var ye=F.create({inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:go.border,backgroundColor:"transparent"},container:{flex:1},headerActionButton:{width:28,height:28,borderRadius:6,backgroundColor:lt.color.buttonSurface,justifyContent:"center",alignItems:"center"}});import{useSyncExternalStore as Ht}from"react";import{buoyColors as fe,X as ya,PowerToggleButton as fa}from"@buoy-gg/shared-ui/web";import{jsx as $,jsxs as Oe}from"react/jsx-runtime";function We({onPress:e,onStopPress:t,position:r="top",offset:a=50}){let o=Ht(h.subscribe,h.getSnapshot,h.getSnapshot);if(!o.isActive||!o.currentUser||!o.showBanner)return null;let c=async()=>{console.log("[impersonate] banner pause/resume pressed"),o.isPaused?await h.resumeImpersonation():await h.pauseImpersonation()},l=o.currentUser.displayName||o.currentUser.email||o.currentUser.id,m=r==="top"?{top:a}:{bottom:a},n=async()=>{console.log("[impersonate] banner STOP pressed"),await h.stopImpersonation()};return $(s,{style:[K.container,m],children:Oe(s,{style:K.banner,children:[Oe(T,{style:K.userSection,onPress:e,activeOpacity:.7,children:[$(Ae,{userId:o.currentUser.id,name:l,size:"small",showActiveIndicator:false}),$(p,{style:[K.userName,o.isPaused&&K.userNamePaused],numberOfLines:1,children:l})]}),$(fa,{isEnabled:!o.isPaused,onToggle:c,size:"small",accessibilityLabel:"Toggle impersonation"}),$(T,{style:K.closeButton,onPress:n,activeOpacity:.7,children:$(ya,{size:12,color:"rgba(255, 255, 255, 0.5)"})})]})})}function Sa({onPress:e}){let t=Ht(h.subscribe,h.getSnapshot,h.getSnapshot);return!t.isActive||!t.currentUser?null:Oe(T,{style:K.minimalBanner,onPress:e,activeOpacity:.8,children:[$(s,{style:K.minimalDot}),$(p,{style:K.minimalText,children:"IMP"})]})}var K=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:fe.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:fe.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:fe.success},minimalText:{fontSize:10,fontWeight:"700",color:fe.success,letterSpacing:.5}});import{hasAccountAccess as ba,isOverWireBudget as va}from"@buoy-gg/shared-ui/web";var Fe=null;function xa(e){Fe=e}var je=2*1024,Ca=16*1024,Pt=Object.freeze({__buoyOmitted:"user-metadata",note:"User metadata stays on the device."});function wa(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<=je?e:`${e.slice(0,je)}\u2026 [${e.length-je} more]`}function Ia(e){if(!e)return e;let t=typeof e.role=="string"?e.role:void 0;return va(e,Ca)?t?{role:t,...Pt}:{...Pt}:e}function Me(e){return{...e,avatarUrl:wa(e.avatarUrl),metadata:Ia(e.metadata)}}function zt(e){return{...e,currentUser:e.currentUser?Me(e.currentUser):null,history:e.history.map(t=>({...t,user:Me(t.user)}))}}var Dt=new Set;function ka(e){for(let t of e)t&&typeof t=="object"&&t.id&&Dt.add(String(t.id))}function Ta(e){if(!e||typeof e!="object"||!e.id)return false;if(Dt.has(String(e.id)))return true;let t=h.getState();return t.currentUser?.id===e.id?true:t.history.some(r=>r.user.id===e.id)}function Ut(e){return{searchUsers:async t=>{let r=String(t?.query??""),a=await e(r);return Array.isArray(a)&&ka(a),Array.isArray(a)?a.map(Me):a},startImpersonation:async t=>{let r=t?.user;if(!Ta(r))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.");return await h.startImpersonation(r),{ok:true,userId:r.id}},stopImpersonation:()=>h.stopImpersonation(),pauseImpersonation:()=>h.pauseImpersonation(),resumeImpersonation:()=>h.resumeImpersonation(),updateSettings:t=>{let r=t??{},a=r.settings??(["headerKey","ignorePatterns","showBanner","dataNukeSettings"].some(o=>o in r)?r:void 0);if(!a)throw new Error("updateSettings needs { settings: { headerKey?, ignorePatterns?, showBanner?, dataNukeSettings? } }.");return h.updateSettings(a)},removeFromHistory:t=>h.removeFromHistory(t.userId),clearHistory:()=>h.clearHistory()}}function Ba({onSearchUsers:e}){return{version:1,getSnapshot:()=>zt(h.getState()),subscribe:t=>h.subscribe(t),actions:Ut(e)}}var Ra={dispose:()=>{ba()||h.disposeAccountSession()},version:1,getSnapshot:()=>zt(h.getState()),subscribe:e=>h.subscribe(e),actions:Ut(e=>{if(!Fe)throw new Error("No onSearchUsers configured \u2014 pass it to createImpersonateTool()");return Fe(e)})};import{ImpersonateIcon as Nt,IMPERSONATE_ICON_COLOR as Aa}from"@buoy-gg/shared-ui/web";import{jsx as Lt}from"react/jsx-runtime";var Et=false;async function Ha(){if(!(typeof window>"u"||Et)){Et=true,console.log("[impersonate] bootstrap: start"),E().isListening||E().startListening();try{let e=tt();if(!e||typeof e.getItem!="function"){console.warn("[impersonate] bootstrap: AsyncStorage shape unexpected",Object.keys(e??{}));return}let t={getItem:r=>e.getItem(r),setItem:(r,a)=>e.setItem(r,a)};h.setAsyncStorage(t),console.log("[impersonate] bootstrap: AsyncStorage adapter installed"),await h.initializeAsync(t),console.log("[impersonate] bootstrap: initializeAsync done")}catch(e){console.warn("[impersonate] bootstrap: failed",e)}}}function Pa(e){let{id:t="impersonate",name:r="IMPERSONATE",description:a="User impersonation for admin testing",defaults:o,showSettingsTab:c=true,onSearchUsers:l,onClearReactQuery:m,onClearRedux:n,onClearAsyncStorage:d,onClearMMKV:y}=e;return o&&h.setDeveloperDefaults(o),xa(l??null),Ha(),{id:t,name:r,description:a,slot:"both",icon:({size:C,slot:w})=>Lt(Nt,{size:w==="dial"?C*1.5:C,color:Aa}),component:C=>Lt(Ee,{...C,onSearchUsers:l,onClearReactQuery:m,onClearRedux:n,onClearAsyncStorage:d,onClearMMKV:y,showSettingsTab:c}),props:{enableSharedModalDimensions:false},Banner:We}}import{jsx as za}from"react/jsx-runtime";function Da(){return za(We,{position:"top",offset:50})}import{buoyColors as de,night as ue,X as Ua}from"@buoy-gg/shared-ui/web";import{jsx as _,jsxs as Se}from"react/jsx-runtime";function Na({user:e,onStopImpersonation:t}){let r=e.displayName||e.email||e.id;return Se(s,{style:V.container,children:[Se(s,{style:V.userSection,children:[_(Ae,{userId:e.id,name:r,size:"small",showActiveIndicator:false}),_(s,{style:V.userInfo,children:_(p,{style:V.userName,numberOfLines:1,children:r})})]}),Se(s,{style:V.statusPill,children:[_(s,{style:V.pulseDot}),_(p,{style:V.statusText,children:"Active"})]}),Se(T,{style:V.stopButton,onPress:t,activeOpacity:.7,children:[_(Ua,{size:12,color:ue.color.danger}),_(p,{style:V.stopButtonText,children:"Stop"})]})]})}var V=F.create({container:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:10,paddingHorizontal:16,backgroundColor:de.success+"10",borderBottomWidth:1,borderBottomColor:de.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:ue.color.text},statusPill:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:de.success+"20",paddingHorizontal:10,paddingVertical:5,borderRadius:12},pulseDot:{width:6,height:6,borderRadius:3,backgroundColor:de.success},statusText:{fontSize:11,fontWeight:"600",color:de.success,textTransform:"uppercase",letterSpacing:.5},stopButton:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:12,paddingVertical:6,backgroundColor:ue.color.dangerSoft,borderRadius:6,borderWidth:1,borderColor:ue.color.danger+"30"},stopButtonText:{fontSize:12,fontWeight:"600",color:ue.color.danger}});import{useCallback as Ke,useSyncExternalStore as La}from"react";function Ea(){let e=La(h.subscribe,h.getSnapshot,h.getSnapshot),t=Ke(async o=>{await h.quickSwitch(o)},[]),r=Ke(async o=>{await h.removeFromHistory(o)},[]),a=Ke(async()=>{await h.clearHistory()},[]);return{history:e.history,currentUserId:e.currentUser?.id??null,quickSwitch:t,removeFromHistory:r,clearHistory:a}}export{At as DataNukeSettingsComponent,We as ImpersonateBanner,Sa as ImpersonateBannerMinimal,kt as ImpersonateHistoryList,Nt as ImpersonateIcon,Ee as ImpersonateModal,Da as ImpersonateOverlay,Na as ImpersonateStatusBar,ma as ImpersonateToolView,wt as UserSearchView,Ba as createImpersonateSyncAdapter,Pa as createImpersonateTool,Io as getImpersonatedUserId,E as impersonateListener,h as impersonateStore,Ra as impersonateSyncAdapter,wo as isImpersonating,gt as setImpersonateConfig,xo as startImpersonateListener,Co as stopImpersonateListener,yt as useImpersonate,Ea 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.44",
|
|
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.44"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"react": "*"
|