@buoy-gg/impersonate 7.0.56 → 7.0.58

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