@buoy-gg/network 7.0.79 → 7.0.80

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.
Files changed (91) hide show
  1. package/README.md +8 -0
  2. package/lib/commonjs/index.js +1 -1
  3. package/lib/commonjs/index.web.js +1 -1
  4. package/lib/commonjs/network/components/NetworkEventDetailView.js +1 -1
  5. package/lib/commonjs/network/components/NetworkEventDetailView.web.js +1 -1
  6. package/lib/commonjs/network/components/NetworkModal.js +1 -1
  7. package/lib/commonjs/network/components/sockets/NetworkSocketsButton.js +1 -0
  8. package/lib/commonjs/network/components/sockets/NetworkSocketsScreen.js +1 -0
  9. package/lib/commonjs/network/components/sockets/SocketFrameView.js +1 -0
  10. package/lib/commonjs/network/components/sockets/SocketListView.js +1 -0
  11. package/lib/commonjs/network/components/sockets/SocketRows.js +1 -0
  12. package/lib/commonjs/network/components/sockets/SocketTricksView.js +1 -0
  13. package/lib/commonjs/network/conditions/NetworkConditionsControl.js +1 -1
  14. package/lib/commonjs/network/conditions/profiles.js +1 -1
  15. package/lib/commonjs/network/conditions/store.js +1 -1
  16. package/lib/commonjs/network/hooks/useSocketsState.js +1 -0
  17. package/lib/commonjs/network/overrides/engine.js +1 -1
  18. package/lib/commonjs/network/overrides/matchRule.js +1 -1
  19. package/lib/commonjs/network/overrides/overrideRulesStore.js +1 -1
  20. package/lib/commonjs/network/sockets/findProblems.js +1 -0
  21. package/lib/commonjs/network/sockets/foldFrames.js +1 -0
  22. package/lib/commonjs/network/sockets/format.js +1 -0
  23. package/lib/commonjs/network/sockets/readMessage.js +1 -0
  24. package/lib/commonjs/network/sockets/socketMoments.js +1 -0
  25. package/lib/commonjs/network/sockets/socketStore.js +1 -0
  26. package/lib/commonjs/network/sockets/socketsSyncAdapter.js +1 -0
  27. package/lib/commonjs/network/sockets/types.js +1 -0
  28. package/lib/commonjs/network/sockets/webSocketPatch.js +1 -0
  29. package/lib/commonjs/network/sync/networkSyncAdapter.js +1 -1
  30. package/lib/commonjs/network/utils/networkEventStore.js +1 -1
  31. package/lib/commonjs/network/utils/networkListener.js +4 -4
  32. package/lib/commonjs/network/utils/startNetworkCapture.js +1 -1
  33. package/lib/commonjs/preset.js +1 -1
  34. package/lib/module/index.js +1 -1
  35. package/lib/module/index.web.js +1 -1
  36. package/lib/module/network/components/NetworkEventDetailView.js +1 -1
  37. package/lib/module/network/components/NetworkEventDetailView.web.js +1 -1
  38. package/lib/module/network/components/NetworkModal.js +1 -1
  39. package/lib/module/network/components/sockets/NetworkSocketsButton.js +1 -0
  40. package/lib/module/network/components/sockets/NetworkSocketsScreen.js +1 -0
  41. package/lib/module/network/components/sockets/SocketFrameView.js +1 -0
  42. package/lib/module/network/components/sockets/SocketListView.js +1 -0
  43. package/lib/module/network/components/sockets/SocketRows.js +1 -0
  44. package/lib/module/network/components/sockets/SocketTricksView.js +1 -0
  45. package/lib/module/network/conditions/NetworkConditionsControl.js +1 -1
  46. package/lib/module/network/conditions/profiles.js +1 -1
  47. package/lib/module/network/conditions/store.js +1 -1
  48. package/lib/module/network/hooks/useSocketsState.js +1 -0
  49. package/lib/module/network/overrides/engine.js +1 -1
  50. package/lib/module/network/overrides/matchRule.js +1 -1
  51. package/lib/module/network/overrides/overrideRulesStore.js +1 -1
  52. package/lib/module/network/sockets/findProblems.js +1 -0
  53. package/lib/module/network/sockets/foldFrames.js +1 -0
  54. package/lib/module/network/sockets/format.js +1 -0
  55. package/lib/module/network/sockets/readMessage.js +1 -0
  56. package/lib/module/network/sockets/socketMoments.js +1 -0
  57. package/lib/module/network/sockets/socketStore.js +1 -0
  58. package/lib/module/network/sockets/socketsSyncAdapter.js +1 -0
  59. package/lib/module/network/sockets/types.js +1 -0
  60. package/lib/module/network/sockets/webSocketPatch.js +1 -0
  61. package/lib/module/network/sync/networkSyncAdapter.js +1 -1
  62. package/lib/module/network/utils/networkEventStore.js +1 -1
  63. package/lib/module/network/utils/networkListener.js +4 -4
  64. package/lib/module/network/utils/startNetworkCapture.js +1 -1
  65. package/lib/module/preset.js +1 -1
  66. package/lib/typescript/index.d.ts +11 -0
  67. package/lib/typescript/index.web.d.ts +4 -0
  68. package/lib/typescript/network/components/sockets/NetworkSocketsButton.d.ts +17 -0
  69. package/lib/typescript/network/components/sockets/NetworkSocketsScreen.d.ts +19 -0
  70. package/lib/typescript/network/components/sockets/SocketFrameView.d.ts +9 -0
  71. package/lib/typescript/network/components/sockets/SocketListView.d.ts +9 -0
  72. package/lib/typescript/network/components/sockets/SocketRows.d.ts +19 -0
  73. package/lib/typescript/network/components/sockets/SocketTricksView.d.ts +23 -0
  74. package/lib/typescript/network/conditions/store.d.ts +1 -1
  75. package/lib/typescript/network/hooks/useSocketsState.d.ts +3 -0
  76. package/lib/typescript/network/overrides/overrideRulesStore.d.ts +19 -0
  77. package/lib/typescript/network/overrides/types.d.ts +14 -0
  78. package/lib/typescript/network/sockets/findProblems.d.ts +31 -0
  79. package/lib/typescript/network/sockets/foldFrames.d.ts +50 -0
  80. package/lib/typescript/network/sockets/format.d.ts +19 -0
  81. package/lib/typescript/network/sockets/readMessage.d.ts +41 -0
  82. package/lib/typescript/network/sockets/socketMoments.d.ts +24 -0
  83. package/lib/typescript/network/sockets/socketStore.d.ts +94 -0
  84. package/lib/typescript/network/sockets/socketsSyncAdapter.d.ts +66 -0
  85. package/lib/typescript/network/sockets/types.d.ts +139 -0
  86. package/lib/typescript/network/sockets/webSocketPatch.d.ts +57 -0
  87. package/lib/typescript/network/sync/networkSyncAdapter.d.ts +3 -1
  88. package/lib/typescript/network/types/index.d.ts +6 -0
  89. package/lib/typescript/network/utils/networkListener.d.ts +6 -0
  90. package/lib/web/index.mjs +58 -58
  91. package/package.json +2 -2
package/lib/web/index.mjs CHANGED
@@ -1,115 +1,115 @@
1
- "use client";var qo=Object.defineProperty;var Sa=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var xa=Object.prototype.hasOwnProperty;var Ir=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ca=(e,t)=>{for(var r in t)qo(e,r,{get:t[r],enumerable:true})},Oo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of wa(t))!xa.call(e,n)&&n!==r&&qo(e,n,{get:()=>t[n],enumerable:!(o=Sa(t,n))||o.enumerable});return e},ka=(e,t,r)=>(Oo(e,t,"default"),r&&Oo(r,t,"default"));var Ta=e=>Oo(qo({},"__esModule",{value:true}),e);var me,O=Ir(()=>{"use strict";me=(()=>{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)});var _n,Ra=Ir(()=>{"use strict";O();_n='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'});import{useEffect as Ea,useState as Ia}from"react";import{createPortal as Pa}from"react-dom";import{jsx as La}from"react/jsx-runtime";function Xn(){let e=document;if(e[Xt])return e[Xt].host;let t=document.createElement("div");t.dataset.buoyPortalHost="",Object.assign(t.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none",fontFamily:_n});let r=()=>{let d=document.fullscreenElement,g=d&&d.tagName!=="CANVAS"?d:document.body;t.parentElement!==g&&g.appendChild(t)},o=new Map,n=d=>{(!t.contains(d.target)||!zo(d.target))&&o.set(d.code||d.key,{key:d.key,code:d.code,location:d.location,keyCode:d.keyCode,which:d.which,altKey:d.altKey,ctrlKey:d.ctrlKey,metaKey:d.metaKey,shiftKey:d.shiftKey})},i=d=>{o.delete(d.code||d.key)},s=()=>o.clear(),l=()=>{let d=[...o.values()];o.clear();for(let g of d)document.dispatchEvent(new KeyboardEvent("keyup",{...g,bubbles:true}))},a=d=>{zo(d.target)&&d.stopPropagation()},u=d=>d.stopPropagation();return r(),document.addEventListener("fullscreenchange",r),document.addEventListener("keydown",n,true),document.addEventListener("keyup",i,true),window.addEventListener("blur",s),t.addEventListener("focusin",l),t.addEventListener("keydown",a),t.addEventListener("keyup",a),t.addEventListener("keypress",a),t.addEventListener("wheel",u,{passive:true}),e[Xt]={host:t,users:0,dispose:()=>{document.removeEventListener("fullscreenchange",r),document.removeEventListener("keydown",n,true),document.removeEventListener("keyup",i,true),window.removeEventListener("blur",s),t.remove(),delete e[Xt]}},t}function Ba({children:e}){let[t,r]=Ia(null);return Ea(()=>{let o=Xn(),n=document[Xt];return n.users++,r(o),()=>{--n.users===0&&n.dispose()}},[]),t?Pa(La("div",{"data-buoy-root":"",style:{display:"contents",pointerEvents:"auto"},children:e}),t):null}var Xt,zo,qa=Ir(()=>{"use strict";O();Ra();Xt=Symbol.for("@buoy-gg/portal-host"),zo=e=>{if(!(e instanceof Element))return false;if(e.closest("input, textarea, select"))return true;let t=e.closest("[contenteditable]")?.getAttribute("contenteditable")?.toLowerCase();return t===""||t==="true"||t==="plaintext-only"}});var Do={};Ca(Do,{AccessibilityInfo:()=>Aa,ActivityIndicator:()=>Lr,Alert:()=>ai,Animated:()=>Qn,AppRegistry:()=>Ma,AppState:()=>Na,Appearance:()=>Ha,BackHandler:()=>$a,Button:()=>ii,CheckBox:()=>tl,Clipboard:()=>Fa,DeviceEventEmitter:()=>gl,Dimensions:()=>ja,Easing:()=>Wa,FlatList:()=>Ao,I18nManager:()=>Va,Image:()=>rl,ImageBackground:()=>ol,InteractionManager:()=>_a,Keyboard:()=>Ua,KeyboardAvoidingView:()=>nl,LayoutAnimation:()=>Xa,Linking:()=>Ja,LogBox:()=>yl,Modal:()=>oi,NativeEventEmitter:()=>Ga,NativeModules:()=>Da,PanResponder:()=>Ka,Picker:()=>il,PixelRatio:()=>Ya,Platform:()=>Pr,Pressable:()=>ri,ProgressBar:()=>sl,RefreshControl:()=>al,SafeAreaView:()=>ll,ScrollView:()=>yt,SectionList:()=>dl,Share:()=>Za,StatusBar:()=>ul,StyleSheet:()=>ve,Switch:()=>ni,Text:()=>b,TextInput:()=>Jt,Touchable:()=>cl,TouchableHighlight:()=>ei,TouchableNativeFeedback:()=>hl,TouchableOpacity:()=>F,TouchableWithoutFeedback:()=>ti,UIManager:()=>Qa,Vibration:()=>el,View:()=>m,VirtualizedList:()=>pl,YellowBox:()=>fl,findNodeHandle:()=>si,unstable_createElement:()=>za,useColorScheme:()=>ml,useLocaleContext:()=>bl,useWindowDimensions:()=>Jn});import*as Oa from"react-native-web";import{unstable_createElement as za,NativeModules as Da,AccessibilityInfo as Aa,Appearance as Ha,AppRegistry as Ma,AppState as Na,BackHandler as $a,Clipboard as Fa,Dimensions as ja,Easing as Wa,I18nManager as Va,Keyboard as Ua,InteractionManager as _a,LayoutAnimation as Xa,Linking as Ja,NativeEventEmitter as Ga,PanResponder as Ka,PixelRatio as Ya,Platform as Pr,Share as Za,UIManager as Qa,Vibration as el,CheckBox as tl,FlatList as Ao,Image as rl,ImageBackground as ol,KeyboardAvoidingView as nl,Picker as il,ProgressBar as sl,RefreshControl as al,SafeAreaView as ll,SectionList as dl,StatusBar as ul,Touchable as cl,TouchableNativeFeedback as hl,VirtualizedList as pl,YellowBox as fl,LogBox as yl,DeviceEventEmitter as gl,useColorScheme as ml,useLocaleContext as bl,useWindowDimensions as Jn}from"react-native-web";import*as He from"react-native-web";import{createElement as Ho,forwardRef as Gn,useCallback as vl,useRef as Sl}from"react";function Mo(e){if(Array.isArray(e)){let g=e.map(Mo);return g.some((x,y)=>x!==e[y])?g:e}if(!e||typeof e!="object"||!Yn.some(g=>e[g]!=null))return e;let{shadowColor:t,shadowOffset:r,shadowOpacity:o,shadowRadius:n,textShadowColor:i,textShadowOffset:s,textShadowRadius:l,...a}=e;if(t!=null||r!=null||o!=null||n!=null){let g=t??"black",x=o==null?g:`color-mix(in srgb, ${g} ${Math.min(o,1)*100}%, transparent)`,y=`${kt(r?.width??0)} ${kt(r?.height??0)} ${kt(n??0)} ${x}`;a.boxShadow=typeof a.boxShadow=="string"?`${a.boxShadow}, ${y}`:a.boxShadow??y}let{width:u=0,height:d=0}=s??{};if(i&&(u||d||l)){let g=`${kt(u)} ${kt(d)} ${kt(l??0)} ${i}`;a.textShadow=a.textShadow?`${a.textShadow}, ${g}`:g}return a}function Kn(e,t){if(typeof e=="function")return o=>Kn(e(o),t);let r=Mo(e);return t?[r,Zn[t]]:r}function Ve(e){let t=Gn((o,n)=>{let{accessibilityState:i,accessibilityValue:s,pointerEvents:l,...a}=o;for(let d of["busy","checked","disabled","expanded","selected"])i?.[d]!==void 0&&a[`aria-${d}`]===void 0&&(a[`aria-${d}`]=i[d]);for(let[d,g]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))s?.[d]!==void 0&&a[`aria-${g}`]===void 0&&(a[`aria-${g}`]=s[d]);let u=Kn(a.style,l);return u!==a.style&&(a.style=u),Ho(e,{...a,ref:n})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var Ct,Yn,kt,Zn,ve,m,b,Qn,Jt,F,ei,ti,ri,yt,No,oi,ni,Lr,ii,si,ai,Se=Ir(()=>{O();ka(Do,Oa);qa();Ct=He,Yn=["shadowColor","shadowOffset","shadowOpacity","shadowRadius","textShadowColor","textShadowOffset","textShadowRadius"],kt=e=>typeof e=="number"?`${e}px`:e;Zn=Ct.StyleSheet.create({auto:{pointerEvents:"auto"},none:{pointerEvents:"none"},"box-none":{pointerEvents:"box-none"},"box-only":{pointerEvents:"box-only"}});ve={...Ct.StyleSheet,create:e=>Ct.StyleSheet.create(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Mo(r)])))};m=Ve(He.View),b=Ve(He.Text),Qn={...Ct.Animated,View:Ct.Animated.createAnimatedComponent(m),Text:Ct.Animated.createAnimatedComponent(b)},Jt=Ve(He.TextInput),F=Ve(He.TouchableOpacity),ei=Ve(He.TouchableHighlight),ti=Ve(He.TouchableWithoutFeedback),ri=Ve(He.Pressable),yt=Ve(He.ScrollView),No=Gn((e,t)=>{let r=Sl(null),o=vl(n=>{if(n){let i=n;for(;i.parentElement&&i.parentElement!==document.body;)i=i.parentElement;i.parentElement===document.body&&(r.current=i,Object.assign(i.style,{position:"relative",zIndex:"2147483647",pointerEvents:"auto"}),Xn().appendChild(i))}else r.current&&(document.body.appendChild(r.current),r.current=null);typeof t=="function"?t(n):t&&(t.current=n)},[t]);return Ho(Ba,null,Ho(He.Modal,{...e,ref:o}))});No.displayName="Modal";oi=Ve(No),ni=Ve(He.Switch),Lr=Ve(He.ActivityIndicator),ii=Ve(He.Button),si=He.findNodeHandle,ai={alert(e,t,r,o){if(typeof document>"u")return;let n=document.createElement("dialog");n.dataset.buoyRoot="",n.setAttribute("aria-label",e),n.style.cssText="position:fixed;inset:0;margin:auto;width:min(440px,90vw);padding:24px;border:1px solid #475569;border-radius:14px;background:#17212e;color:#f1f5f9;font:14px system-ui;box-shadow:0 20px 80px #0008;z-index:2147483647";let i=document.createElement("h2");if(i.textContent=e,i.style.cssText="font-size:18px;margin:0 0 12px",n.appendChild(i),t){let u=document.createElement("p");u.textContent=t,u.style.cssText="line-height:1.5;white-space:pre-wrap;margin:0 0 20px",n.appendChild(u)}let s=document.createElement("div");s.style.cssText="display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px";let l=r?.length?r:[{text:"OK"}],a=()=>{n.close?.(),n.remove()};for(let u of l){let d=document.createElement("button");d.type="button",d.textContent=u.text??"OK",d.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${u.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,d.onclick=()=>{a(),u.onPress?.()},s.appendChild(d)}n.addEventListener("cancel",u=>{u.preventDefault(),o?.cancelable!==false&&(a(),o?.onDismiss?.())}),n.appendChild(s),document.body.appendChild(n),n.showModal?n.showModal():n.setAttribute("open","")}}});O();O();O();Se();import{useSyncExternalStore as li}from"react";import{NetworkIcon as wl}from"@buoy-gg/shared-ui/web";O();import{hasAccountAccess as di,subscribeAccountAccess as xl}from"@buoy-gg/shared-ui/web";O();O();O();function ue(){let e=globalThis.__buoyRealNow;return typeof e=="function"?e():Date.now()}function ui(){return globalThis.__buoyRealTimers??globalThis}function lr(e,t){return ui().setTimeout(e,t)}function Tt(e){ui().clearTimeout(e)}O();function lt(e){if(!e?.aborted)return;if(e.reason!==void 0)throw e.reason;let t=new Error("The request was aborted.");throw t.name="AbortError",t}function $o(e,t){return new Promise((r,o)=>{try{lt(t)}catch(l){o(l);return}let n=()=>t?.removeEventListener("abort",i),i=()=>{Tt(s),n();try{lt(t)}catch(l){o(l)}},s=lr(()=>{n(),r()},e);t?.addEventListener("abort",i,{once:true})})}var Br=e=>Math.max(1,Math.min(16384,Math.floor(e*.02))),Fo=e=>new TextEncoder().encode(e).byteLength;function qr(e){return e==null?0:typeof e=="string"?Fo(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:typeof Blob<"u"&&e instanceof Blob?e.size:typeof URLSearchParams<"u"&&e instanceof URLSearchParams?Fo(e.toString()):null}async function Or(e,t,r,o){let n=Br(t),i=ue();for(let s=0;s<e;){let l=Math.min(n,e-s);await $o(Math.max(0,i+(s+l)/t*1e3-ue()),r),lt(r),s+=l,o?.(s,e)}}function Cl(e,t){try{let r=typeof e=="object"&&"method"in e?e:void 0,o=t?.body!==void 0?t.body:r&&"_bodyInit"in r?r._bodyInit:r?.body;return jo(o)}catch{return ci(0)}}function ci(e){return{knownBytes:e,status:e>0?"partial":"not-applied",note:e>0?"upload cap partial: size unknown":"upload cap not applied: size unknown"}}function jo(e){let t=0;try{let r=qr(e);if(r!==null)return{knownBytes:r,status:"applied"};if(e&&typeof e=="object"){let o=e,n=Array.isArray(o._parts)?o._parts:typeof FormData<"u"&&e instanceof FormData&&o.entries?o.entries():void 0;if(n)for(let[,i]of n)try{let s=qr(i);s!==null?t+=s:i&&typeof i=="object"&&"uri"in i&&"size"in i&&typeof i.size=="number"&&Number.isSafeInteger(i.size)&&i.size>=0&&(t+=i.size)}catch{}}}catch{}return ci(t)}function hi(e){let t=0;return async(r,o)=>{let n=r/e*1e3,i=ue(),s=Math.max(0,n-t);s>0&&await $o(s,o),lt(o),t=Math.min(Br(e)/e*1e3,Math.max(0,t+ue()-i-n))}}function kl(e,t,r,o){let n=hi(t),i,s=()=>{i?.releaseLock(),i=void 0},l=h=>{(i?i.cancel(h):e.cancel(h)).catch(()=>{}),s()},a=new AbortController,u,d=0,g=false,x,y=(h,C=false)=>{g||(g=true,r?.removeEventListener("abort",R),a.abort(),u=void 0,C?x.error(h):(s(),x.close()),o?.(null,h))},R=()=>{let h=r?.reason!==void 0?r.reason:Object.assign(new Error("The request was aborted."),{name:"AbortError"});y(h,true),l(h)};return new ReadableStream({start(h){x=h,r?.addEventListener("abort",R,{once:true}),r?.aborted&&R()},async pull(){try{if(!u||d===u.byteLength){let k=await(i??(i=e.getReader())).read();if(g)return;if(k.done){y();return}u=k.value,d=0}let h=Math.min(Br(t),u.byteLength-d),C=u.subarray(d,d+h);if(await n(h,a.signal),g)return;d+=h,o?.(C),x.enqueue(C)}catch(h){g||(y(h,true),l(h))}},cancel(h){g||(g=true,r?.removeEventListener("abort",R),a.abort(),u=void 0,o?.(null,h??new Error("Body read stopped."))),l(h)}},{highWaterMark:0})}function pi(e,t,r,o,n=false){if(n||[204,205,304].includes(e.status)||e.body===null)return o?.(null),e;let i,s=false,l=()=>{if(!i){let u,d=false,g=new ReadableStream({async pull(x){s=true;try{if(e.body?.getReader){u??(u=e.body.getReader());let y=await u.read();if(d)return;y.done?(d=true,u.releaseLock(),u=void 0,x.close()):x.enqueue(y.value)}else{let y=new Uint8Array(await e.arrayBuffer());if(d)return;x.enqueue(y),d=true,x.close()}}catch(y){d||(d=true,u?.releaseLock(),u=void 0,x.error(y))}},cancel(x){s=true,d=true;let y=u?u.cancel(x):e.body?.cancel?.(x);return u?.releaseLock(),u=void 0,y}},{highWaterMark:0});i=kl(g,t,r,o)}return i},a=async(u=true)=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");s=true;let d=l().getReader(),g=[],x=0;try{for(;;){let h=await d.read();if(h.done)break;u&&(g.push(h.value),x+=h.value.byteLength)}}finally{d.releaseLock()}let y=new Uint8Array(x),R=0;for(let h of g)y.set(h,R),R+=h.byteLength;return y};return new Proxy(e,{get(u,d){if(d==="body")return l();if(d==="bodyUsed")return s||e.bodyUsed;if(d==="arrayBuffer")return async()=>(await a()).buffer;if(d==="bytes")return a;if(d==="text")return async()=>new TextDecoder().decode(await a());if(d==="json")return async()=>JSON.parse(new TextDecoder().decode(await a()));if(d==="blob")return async()=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");lt(r);let x=false;try{new Blob([new Uint8Array(0)]),x=true}catch{}if(x)return new Blob([await a()],{type:u.headers.get("content-type")??""});let y=u.clone(),R;Object.defineProperty(y,"arrayBuffer",{configurable:true,value:async()=>(y.body&&!y.body.locked&&y.body.cancel().catch(()=>{}),R??(R=a()),(await R).buffer)});try{let h=y.blob();return h.catch(()=>{}),await(R??a(false)),lt(r),await h}finally{y.body&&!y.body.locked&&y.body.cancel().catch(()=>{})}};if(d==="formData")return async()=>{let x=await a();return new Response(x,{headers:u.headers}).formData()};if(d==="clone")return()=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");return pi(u.clone(),t,r)};let g=Reflect.get(u,d,u);return typeof g=="function"?g.bind(u):g}})}import{isBuoyRequest as Tl}from"@buoy-gg/shared-ui/web";O();function zr(e){if(typeof document>"u")return e;try{return new URL(e,document.baseURI).href}catch{return e}}O();var fi=globalThis;function Dr(e){let t=fi.__BUOY_NETWORK_REQUEST_SEQUENCE__??(fi.__BUOY_NETWORK_REQUEST_SEQUENCE__={session:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,next:0});return`${e}_${t.session}_${++t.next}`}O();O();var yi=2,gi=3,dr=4,Ar=e=>e,mi=false;function bi(e){let t=Ar(e);return typeof t.setReadyState=="function"&&typeof t.setResponseHeaders=="function"}function Rl(e){return typeof e.addEventListener=="function"&&typeof e.removeEventListener=="function"&&typeof e.dispatchEvent=="function"}function El(){mi||(mi=true,typeof me<"u"&&me&&console.warn("[Buoy] Network overrides need an XMLHttpRequest they can drive (React Native's, or a standards EventTarget one) and this environment provides neither \u2014 requests will run normally."))}function vi(e,t,r){let o=Ar(e);o.responseURL=t,o.status=r.status,o.statusText=r.statusText,o.setResponseHeaders?.(r.headers),o.setReadyState?.(yi),!o._aborted&&(o._responseType="text",o._response=r.body,o._cachedResponse=void 0,o.setReadyState?.(gi),!o._aborted&&o.setReadyState?.(dr))}function Si(e,t){let r=Ar(e),o=t.failKind==="timeout";r._hasError=true,r._timedOut=o,r._responseType="text",r._response=o?"Request timed out (Buoy override)":"Network request failed (Buoy override)",r._cachedResponse=void 0,r.setReadyState?.(dr)}function dt(e,t,r){Object.defineProperty(e,t,{value:r,configurable:true,enumerable:true,writable:false})}function Il(e){if(e!=="readystatechange"&&typeof ProgressEvent=="function")try{return new ProgressEvent(e)}catch{}if(typeof Event=="function")try{return new Event(e)}catch{}return{type:e}}function Rt(e,t){e.dispatchEvent(Il(t))}function ur(e,t){dt(e,"readyState",t),Rt(e,"readystatechange")}function Pl(e,t){let r="";try{r=e.responseType}catch{}switch(r){case"":case"text":return t.body;case"json":try{return JSON.parse(t.body)}catch{return null}case"arraybuffer":return typeof TextEncoder=="function"?new TextEncoder().encode(t.body).buffer:t.body;case"blob":if(typeof Blob=="function"){let o=Object.entries(t.headers).find(([n])=>n.toLowerCase()==="content-type")?.[1]??"";return new Blob([t.body],{type:o})}return t.body;default:return t.body}}function Ll(e,t,r,o){let n=r.headers,i=Object.entries(n).map(([s,l])=>`${s.toLowerCase()}: ${l}\r
2
- `).join("");dt(e,"getAllResponseHeaders",()=>i),dt(e,"getResponseHeader",s=>{let l=String(s).toLowerCase();for(let[a,u]of Object.entries(n))if(a.toLowerCase()===l)return u;return null}),dt(e,"responseURL",t),dt(e,"status",r.status),dt(e,"statusText",r.statusText),dt(e,"response",Pl(e,r)),dt(e,"responseText",r.body),ur(e,yi),!o()&&(ur(e,gi),!o()&&(ur(e,dr),!o()&&(Rt(e,"load"),Rt(e,"loadend"))))}function Wo(e,t){ur(e,dr),Rt(e,t.failKind==="timeout"?"timeout":"error"),Rt(e,"loadend")}var Gt=new WeakMap;function Bl(e){return Gt.has(e)}function ql(e,t,r,o){let n=ue(),i={},s,l,a=false,u=false,d=false,g=e.timeout,x=e.abort,y=e.open,R=["abort","open","timeout","readyState","status","statusText","response","responseText","responseURL","getAllResponseHeaders","getResponseHeader"],h=new Map(R.map($=>[$,Object.getOwnPropertyDescriptor(e,$)])),C=Object.getPrototypeOf(e),k;for(;C&&!k;)k=Object.getOwnPropertyDescriptor(C,"timeout"),C=Object.getPrototypeOf(C);let w=()=>{a=true,Gt.get(e)===i&&Gt.delete(e),clearTimeout(s),Tt(l),e.removeEventListener("loadend",w)},I=()=>{w();for(let[$,P]of h)P?Object.defineProperty(e,$,P):delete e[$];e.timeout=g},z=()=>{Tt(l),d?k?.set?.call(e,g>0?Math.max(1,g-(ue()-n)):0):g>0&&(l=lr(()=>{a||(clearTimeout(s),Wo(e,{...r,kind:"fail",failKind:"timeout"}),w())},Math.max(0,g-(ue()-n))))};return Object.defineProperty(e,"timeout",{configurable:true,get:()=>g,set:$=>{g=Math.max(0,Number($)||0),z()}}),Object.defineProperty(e,"open",{configurable:true,value:(...$)=>(I(),Reflect.apply(y,e,$))}),Object.defineProperty(e,"abort",{configurable:true,value:()=>{if(d||a){I(),x.call(e);return}u=true,clearTimeout(s),ur(e,dr),Rt(e,"abort"),Rt(e,"loadend"),w(),Gt.has(e)||dt(e,"readyState",0)}}),Gt.set(e,i),e.addEventListener("loadend",w),z(),s=setTimeout(()=>{if(!(a||u)){if(r.kind==="delay"){d=true,z();try{o()}catch{Wo(e,{...r,kind:"fail",failKind:"network"}),w()}return}r.kind==="fail"?Wo(e,r):Ll(e,t,r,()=>u||Gt.get(e)!==i),w()}},r.delayMs),true}function wi(e,t,r,o){if(!bi(e))return Rl(e)?ql(e,t,r,o):(El(),false);let n=Ar(e);n._sent=true,n._requestId=null;let i=null,s=()=>{e.removeEventListener("abort",s),i!==null&&(clearTimeout(i),i=null)};return e.addEventListener("abort",s),i=setTimeout(()=>{if(i=null,e.removeEventListener("abort",s),!n._aborted){if(r.kind==="delay"){n._sent=false,o();return}if(r.kind==="fail"){Si(e,r);return}vi(e,t,r)}},r.delayMs),true}function Ol(e,t,r){r.kind==="fail"?Si(e,r):r.kind==="respond"&&vi(e,t,r)}function zl(e,t,r,o,n,i){if(!bi(e)){if(r.downloadBytesPerSecond)throw new Error("Byte caps need RN XHR. This XHR only supports waits and Offline.");let H={id:"condition",enabled:true,urlPattern:t,kind:"delay",hits:0,seen:0,createdAt:Date.now()},V=r.profile==="offline"?{kind:"fail",rule:H,failKind:"network",delayMs:0}:o?{...o,delayMs:r.delayMs+o.delayMs}:{kind:"delay",rule:H,delayMs:r.delayMs};if(!wi(e,t,V,n))throw new Error("Network conditions are unavailable for this XMLHttpRequest implementation.");return}let s=e;if(s.readyState!==1||s._sent)throw new Error("Request is not open or has already been sent.");let l=ue(),a=s.timeout,u=false,d=new AbortController,g=[],x=false,y,R,h=s.abort,C=s.open,k=Object.getOwnPropertyDescriptor(s,"abort"),w=Object.getOwnPropertyDescriptor(s,"open"),I=Object.getOwnPropertyDescriptor(s,"timeout"),z=(H,V)=>{V?Object.defineProperty(s,H,V):delete s[H]},$=()=>{u||(u=true,Tt(R),d.abort(),g.forEach(H=>H()),Tt(y),s.removeEventListener("loadend",$),z("abort",k),z("open",w),z("timeout",I),s.timeout=a)},P=(H,V)=>{u||(Object.assign(s,{readyState:4}),h.call(s),s._aborted=false,s._hasError=true,s._timedOut=H,s._response=V??(H?"Request timed out (Buoy conditions)":"Network request failed (Buoy Offline)"),s.setReadyState(4),$())},A=()=>a>0&&ue()-l>=a,v=()=>{Tt(y),a>0&&(y=lr(()=>P(true),Math.max(0,a-(ue()-l))))};Object.defineProperty(s,"timeout",{configurable:true,get:()=>x?0:a,set:H=>{a=Math.max(0,Number(H)||0),v()}}),Object.defineProperty(s,"abort",{configurable:true,value:()=>{u||(h.call(s),$())}}),Object.defineProperty(s,"open",{configurable:true,value:(...H)=>{let V=Reflect.apply(C,s,H);return $(),V}}),s._sent=true,s._requestId=null,s.addEventListener("loadend",$),v();let c=s,p=(H,V)=>{let Z=Object.getOwnPropertyDescriptor(s,H);Object.defineProperty(s,H,{configurable:true,writable:true,value:V}),g.push(()=>z(H,Z))},f=(H,V,Z)=>{let Y=new Event("progress");Object.defineProperties(Y,{loaded:{value:V},total:{value:Z},lengthComputable:{value:true}}),H.dispatchEvent(Y)},S=r.downloadBytesPerSecond;if(S&&typeof c.__didReceiveData=="function"&&typeof c.__didCompleteResponse=="function"){let H=c.__didReceiveData.bind(s),V=c.__didReceiveIncrementalData?.bind(s),Z=c.__didCompleteResponse.bind(s),Y=c.__didReceiveDataProgress?.bind(s),L=Promise.resolve(),M=0,N=hi(S),J=ne=>{L=L.then(async()=>{u||await ne()}).catch(K=>{u||P(false,K instanceof Error?K.message:String(K))})},le=async(ne,K,be=-1)=>{if((!s.responseType||s.responseType==="text"||s.responseType==="json")&&typeof K=="string"&&V){let pe=new TextEncoder().encode(K),ft=new TextDecoder;for(let Ae=0;Ae<pe.byteLength;){let Ye=Math.min(Br(S),pe.byteLength-Ae);if(await N(Ye,d.signal),u)return;let Eo=ft.decode(pe.subarray(Ae,Ae+Ye),{stream:Ae+Ye<pe.byteLength});Ae+=Ye,M+=Ye,V(ne,Eo,M,be),Y?.(ne,M,be)}}else{let pe=typeof K=="object"&&K?K.size:s.responseType==="arraybuffer"&&typeof K=="string"?Math.max(0,K.length*3/4-(K.endsWith("==")?2:K.endsWith("=")?1:0)):qr(K);if(typeof pe!="number")throw new Error("Cannot read this response size.");let ft=M;await Or(pe,S,d.signal,Ae=>{M=ft+Ae,Y?.(ne,M,be<0?pe:be)}),u||H(ne,K)}};p("__didReceiveData",(ne,K)=>J(()=>le(ne,K))),p("__didReceiveIncrementalData",(ne,K,be,pe)=>J(()=>le(ne,K,pe))),p("__didReceiveDataProgress",()=>{}),p("__didCompleteResponse",(ne,K,be)=>{if(K){Z(ne,K,be);return}J(async()=>{u||Z(ne,K,be)})})}else if(S)throw $(),new Error("This XHR lacks the RN byte hooks.");let D=typeof c.__didUploadProgress=="function"?c.__didUploadProgress.bind(s):void 0;r.uploadBytesPerSecond&&D&&p("__didUploadProgress",()=>{}),R=lr(()=>{(async()=>{if(!u){if(A()){P(true);return}if(r.profile==="offline"){P(false);return}if(r.uploadBytesPerSecond){let H=(r.uploadCap??jo(i)).knownBytes;await Or(H,r.uploadBytesPerSecond,d.signal,(V,Z)=>{D?D(s._requestId,V,Z):s.upload&&f(s.upload,V,Z)})}if(!u){if(o&&o.kind!=="delay"){S&&o.kind==="respond"&&await Or(qr(o.body)??0,S,d.signal),u||Ol(s,t,o);return}s._sent=false,x=true;try{n()}finally{x=false}}}})().catch(H=>{u||P(false,H instanceof Error?H.message:String(H))})},r.delayMs+(o?.delayMs??0))}O();import{getAccountAccess as xi,hasAccountAccess as Vo,subscribeAccountAccess as Dl}from"@buoy-gg/shared-ui/web";O();O();var Ci=[204,205,304];function Uo(){return typeof Response=="function"}function Al(e,t){let r=Ci.includes(t.status)?null:t.body,o=new Response(r,{status:t.status,statusText:t.statusText,headers:t.headers});try{Object.defineProperty(o,"url",{value:e,configurable:true})}catch{}return o}function Hl(e){return new TypeError(e.failKind==="timeout"?"Network request timed out":"Network request failed")}O();var Ml="[]{}()\\.^$+|-,?";function ki(e){let t="";for(let r=0;r<e.length;r++){let o=e.charAt(r);Ml.indexOf(o)!==-1&&(t+="\\"),t+=o}return t.split("*").join(".*")}var Hr=new Map;function Nl(e){let t=Hr.get(e);if(t)return t;let r=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${ki(e)}`:ki(e),o=new RegExp(`^${r}$`);return Hr.size>200&&Hr.clear(),Hr.set(e,o),o}function $l(e,t){if(!e)return false;let r=t.toLowerCase();for(let o of Object.keys(e))if(o.toLowerCase()===r&&e[o]!==void 0&&e[o]!=="")return true;return false}function Fl(e){let t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(o=>[o,t(r[o])])):r;return JSON.stringify(t(e))??"null"}function jl(e,t,r){if(typeof e!="string"||!e.includes(t))return false;try{let o=JSON.parse(e);return(Array.isArray(o)?o:[o]).some(n=>!n||typeof n!="object"||n.operationName!==t?false:r===void 0||Fl(n.variables??{})===r)}catch{return false}}function _o(e,t,r,o,n){if(e.methods&&e.methods.length>0&&!e.methods.includes(r.toUpperCase())||e.requireHeader&&!$l(o,e.requireHeader)||e.bodyIncludes&&(typeof n!="string"||!n.includes(e.bodyIncludes))||e.graphqlOperation&&!jl(n,e.graphqlOperation,e.graphqlVariables))return false;try{return Nl(e.urlPattern).test(t)}catch{return false}}O();import{TIER_LIMITS as Wl}from"@buoy-gg/shared-ui/web";var cr=200,hr=599,Ze=50,Ti=Wl["network.overrideRules"].free;function Ri(e){return{ruleId:e.rule.id,ruleName:e.rule.name,kind:e.kind,delayMs:e.delayMs||void 0}}var Vl=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function Ul(e){return Vl.some(t=>t.test(e))}function _l(e){let t=e.trim();if(t==="")return"text/plain; charset=utf-8";if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t),"application/json"}catch{}return"text/plain; charset=utf-8"}function Xl(e,t){let r=t.toLowerCase();return Object.keys(e).some(o=>o.toLowerCase()===r)}function Jl(e){let t=Math.max(0,e.delayMs??0);if(e.kind==="delay")return{kind:"delay",rule:e,delayMs:t};if(e.kind==="fail")return{kind:"fail",rule:e,delayMs:t,failKind:e.failKind??"network"};let r=Math.min(hr,Math.max(cr,e.status??200)),o=Ci.includes(r)?"":e.body??"",n={...e.headers??{}};return Xl(n,"content-type")||(n["content-type"]=_l(o)),{kind:"respond",rule:e,delayMs:t,status:r,statusText:e.statusText??"",headers:n,body:o}}function Xo(e){return typeof e.times=="number"&&e.hits>=e.times}function Gl(e){return e.alternate?e.seen%2===1:true}function Jo(e,t,r,o,n){if(r.length===0||t.toUpperCase()==="OPTIONS"||Ul(e))return null;for(let i of r)if(i.enabled&&!Xo(i)&&_o(i,e,t,o,n))return i;return null}var Oe=null;function Kl(e){Oe=e}function Ei(){return Oe?.ready?.()??Promise.resolve()}function Yl(){return Oe?.isReady?.()??true}function Zl(){return!!Oe?.getRules().some(e=>e.enabled&&(e.bodyIncludes||e.graphqlOperation))}function Ql(){return Vo()&&!(typeof me<"u"&&!me)}var ed="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";function td(e,t){return{hooksInstalled:Oe!==null,devFlag:typeof me>"u"?"undefined":me,ruleCount:Oe?Oe.getRules().length:0,matches:Oe?Jo(e,t,Oe.getRules())!==null:false}}var rd=3e3;function od(e,t,r,o){return!Oe||Vo()||typeof me<"u"&&!me||xi().status!=="initializing"||!Jo(e,t,Oe.getRules(),r,o)?null:new Promise(n=>{let i=()=>{},s=()=>{Tt(l),i(),n()},l=lr(s,rd);i=Dl(()=>{xi().status!=="initializing"&&s()})})}function Ii(e,t,r,o){if(!Oe||typeof me<"u"&&!me)return null;let n=Oe.getRules();if(n.length===0||!Vo()&&(n=n.filter(l=>l.sandbox===true),n.length===0))return null;let i=Jo(e,t,n,r,o);if(!i)return null;let s=Gl(i);return Oe.recordMatch(i.id),s?(Oe.recordHit(i.id),Jl(i)):null}O();var nd={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",408:"Request Timeout",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function id(e){return typeof e=="number"&&e>0?"response":"error"}function sd(e,t){let r=(t??"").trim();return r||(nd[e]??"")}var Et;function Pi(e){let t=globalThis.__buoyHeaderInjectors;if(!t||t.length===0)return;let r;for(let o of t)try{let n=o(e);n&&(r={...r,...n})}catch{}return r}function ad(){if(Et!==void 0)return Et;Et=null;try{if(typeof me<"u"&&!me)return Et;let e=(Se(),Ta(Do))?.NativeModules?.SourceCode,t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t=="string"&&/^https?:\/\//.test(t)){let r=new URL(t);Et=`${r.protocol}//${r.host}`}}catch{Et=null}return Et}var It=false,ld=Symbol.for("buoy.earlyNetwork");function dd(e){let t={};if(!e)return t;if(typeof Headers<"u"&&e instanceof Headers)e.forEach((r,o)=>{t[o]=r});else if(Array.isArray(e))for(let[r,o]of e)t[r]=o;else Object.assign(t,e);return t}var Li="__buoyNetworkFetchIntercepted",Bi="__buoyNetworkXhrIntercepted",ud=["text/event-stream","application/x-ndjson","application/stream+json"],Go="[streaming\u2026]",Ko=false;function cd(){return Ko?true:(Ko=!!globalThis.document?.querySelector?.("[ng-version]"),Ko)}function qi(e){if(!e)return false;let t=e.toLowerCase();return ud.some(r=>t.includes(r))}var hd="__BUOY_INTERNAL_HOSTS__";function pd(e){let t=globalThis[hd];if(!(t instanceof Set)||t.size===0)return false;let r;try{r=new URL(e).host.toLowerCase()}catch{return false}for(let o of t)if(typeof o=="string"&&o&&r===o.toLowerCase())return true;return false}var fd=class{constructor(){this.listeners=[];this.isListening=false;this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.fetchGeneration=0;this.xhrGeneration=0;this.originalFetch=globalThis.fetch,this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if(Tl(e))return true;try{let t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh")||(t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/"))||(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2")&&["8081","8802"].includes(t.port))return true;let r=ad();if(r&&`${t.protocol}//${t.host}`===r)return true}catch{return false}return pd(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch{}})}parseUrl(e){let t=null,r=e.indexOf("?");return r>-1&&(t={},e.substring(r+1).split("&").forEach(o=>{let[n,i]=o.split("=");n&&i!==void 0&&(t[n]=decodeURIComponent(i.replace(/\+/g," ")))})),{url:r>-1?e.substring(0,r):e,params:t}}async readStreamedBody(e,t=256*1024){let r=e.body;if(!r||typeof r.getReader!="function"){let a=await e.text();return a.length>t?{body:`${a.slice(0,t)}
1
+ "use client";var Sn=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var Ul=Object.getOwnPropertyNames;var Jl=Object.prototype.hasOwnProperty;var po=(e,t)=>()=>(e&&(t=e(e=0)),t);var Gl=(e,t)=>{for(var r in t)Sn(e,r,{get:t[r],enumerable:true})},kn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ul(t))!Jl.call(e,n)&&n!==r&&Sn(e,n,{get:()=>t[n],enumerable:!(o=Vl(t,n))||o.enumerable});return e},Xl=(e,t,r)=>(kn(e,t,"default"),r&&kn(r,t,"default"));var Kl=e=>kn(Sn({},"__esModule",{value:true}),e);var we,q=po(()=>{"use strict";we=(()=>{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)});var Ji,Ql=po(()=>{"use strict";q();Ji='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'});import{useEffect as Yl,useState as Zl}from"react";import{createPortal as ed}from"react-dom";import{jsx as td}from"react/jsx-runtime";function Gi(){let e=document;if(e[vr])return e[vr].host;let t=document.createElement("div");t.dataset.buoyPortalHost="",Object.assign(t.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none",fontFamily:Ji});let r=()=>{let c=document.fullscreenElement,y=c&&c.tagName!=="CANVAS"?c:document.body;t.parentElement!==y&&y.appendChild(t)},o=new Map,n=c=>{(!t.contains(c.target)||!xn(c.target))&&o.set(c.code||c.key,{key:c.key,code:c.code,location:c.location,keyCode:c.keyCode,which:c.which,altKey:c.altKey,ctrlKey:c.ctrlKey,metaKey:c.metaKey,shiftKey:c.shiftKey})},i=c=>{o.delete(c.code||c.key)},s=()=>o.clear(),d=()=>{let c=[...o.values()];o.clear();for(let y of c)document.dispatchEvent(new KeyboardEvent("keyup",{...y,bubbles:true}))},a=c=>{xn(c.target)&&c.stopPropagation()},l=c=>c.stopPropagation();return r(),document.addEventListener("fullscreenchange",r),document.addEventListener("keydown",n,true),document.addEventListener("keyup",i,true),window.addEventListener("blur",s),t.addEventListener("focusin",d),t.addEventListener("keydown",a),t.addEventListener("keyup",a),t.addEventListener("keypress",a),t.addEventListener("wheel",l,{passive:true}),e[vr]={host:t,users:0,dispose:()=>{document.removeEventListener("fullscreenchange",r),document.removeEventListener("keydown",n,true),document.removeEventListener("keyup",i,true),window.removeEventListener("blur",s),t.remove(),delete e[vr]}},t}function rd({children:e}){let[t,r]=Zl(null);return Yl(()=>{let o=Gi(),n=document[vr];return n.users++,r(o),()=>{--n.users===0&&n.dispose()}},[]),t?ed(td("div",{"data-buoy-root":"",style:{display:"contents",pointerEvents:"auto"},children:e}),t):null}var vr,xn,od=po(()=>{"use strict";q();Ql();vr=Symbol.for("@buoy-gg/portal-host"),xn=e=>{if(!(e instanceof Element))return false;if(e.closest("input, textarea, select"))return true;let t=e.closest("[contenteditable]")?.getAttribute("contenteditable")?.toLowerCase();return t===""||t==="true"||t==="plaintext-only"}});var Cn={};Gl(Cn,{AccessibilityInfo:()=>ad,ActivityIndicator:()=>yo,Alert:()=>ls,Animated:()=>es,AppRegistry:()=>dd,AppState:()=>cd,Appearance:()=>ld,BackHandler:()=>ud,Button:()=>ss,CheckBox:()=>Rd,Clipboard:()=>hd,DeviceEventEmitter:()=>jd,Dimensions:()=>pd,Easing:()=>fd,FlatList:()=>go,I18nManager:()=>gd,Image:()=>Id,ImageBackground:()=>Pd,InteractionManager:()=>md,Keyboard:()=>yd,KeyboardAvoidingView:()=>Ed,LayoutAnimation:()=>bd,Linking:()=>vd,LogBox:()=>Hd,Modal:()=>ns,NativeEventEmitter:()=>wd,NativeModules:()=>sd,PanResponder:()=>Sd,Picker:()=>Bd,PixelRatio:()=>kd,Platform:()=>fo,Pressable:()=>os,ProgressBar:()=>Ld,RefreshControl:()=>zd,SafeAreaView:()=>Od,ScrollView:()=>ht,SectionList:()=>qd,Share:()=>xd,StatusBar:()=>Dd,StyleSheet:()=>se,Switch:()=>is,Text:()=>b,TextInput:()=>Xt,Touchable:()=>Ad,TouchableHighlight:()=>ts,TouchableNativeFeedback:()=>Nd,TouchableOpacity:()=>W,TouchableWithoutFeedback:()=>rs,UIManager:()=>Cd,Vibration:()=>Td,View:()=>S,VirtualizedList:()=>Md,YellowBox:()=>$d,findNodeHandle:()=>as,unstable_createElement:()=>id,useColorScheme:()=>Fd,useLocaleContext:()=>Wd,useWindowDimensions:()=>Xi});import*as nd from"react-native-web";import{unstable_createElement as id,NativeModules as sd,AccessibilityInfo as ad,Appearance as ld,AppRegistry as dd,AppState as cd,BackHandler as ud,Clipboard as hd,Dimensions as pd,Easing as fd,I18nManager as gd,Keyboard as yd,InteractionManager as md,LayoutAnimation as bd,Linking as vd,NativeEventEmitter as wd,PanResponder as Sd,PixelRatio as kd,Platform as fo,Share as xd,UIManager as Cd,Vibration as Td,CheckBox as Rd,FlatList as go,Image as Id,ImageBackground as Pd,KeyboardAvoidingView as Ed,Picker as Bd,ProgressBar as Ld,RefreshControl as zd,SafeAreaView as Od,SectionList as qd,StatusBar as Dd,Touchable as Ad,TouchableNativeFeedback as Nd,VirtualizedList as Md,YellowBox as $d,LogBox as Hd,DeviceEventEmitter as jd,useColorScheme as Fd,useLocaleContext as Wd,useWindowDimensions as Xi}from"react-native-web";import*as Qe from"react-native-web";import{createElement as Tn,forwardRef as Ki,useCallback as _d,useRef as Vd}from"react";function Rn(e){if(Array.isArray(e)){let y=e.map(Rn);return y.some((w,p)=>w!==e[p])?y:e}if(!e||typeof e!="object"||!Yi.some(y=>e[y]!=null))return e;let{shadowColor:t,shadowOffset:r,shadowOpacity:o,shadowRadius:n,textShadowColor:i,textShadowOffset:s,textShadowRadius:d,...a}=e;if(t!=null||r!=null||o!=null||n!=null){let y=t??"black",w=o==null?y:`color-mix(in srgb, ${y} ${Math.min(o,1)*100}%, transparent)`,p=`${Gt(r?.width??0)} ${Gt(r?.height??0)} ${Gt(n??0)} ${w}`;a.boxShadow=typeof a.boxShadow=="string"?`${a.boxShadow}, ${p}`:a.boxShadow??p}let{width:l=0,height:c=0}=s??{};if(i&&(l||c||d)){let y=`${Gt(l)} ${Gt(c)} ${Gt(d??0)} ${i}`;a.textShadow=a.textShadow?`${a.textShadow}, ${y}`:y}return a}function Qi(e,t){if(typeof e=="function")return o=>Qi(e(o),t);let r=Rn(e);return t?[r,Zi[t]]:r}function at(e){let t=Ki((o,n)=>{let{accessibilityState:i,accessibilityValue:s,pointerEvents:d,...a}=o;for(let c of["busy","checked","disabled","expanded","selected"])i?.[c]!==void 0&&a[`aria-${c}`]===void 0&&(a[`aria-${c}`]=i[c]);for(let[c,y]of Object.entries({min:"valuemin",max:"valuemax",now:"valuenow",text:"valuetext"}))s?.[c]!==void 0&&a[`aria-${y}`]===void 0&&(a[`aria-${y}`]=s[c]);let l=Qi(a.style,d);return l!==a.style&&(a.style=l),Tn(e,{...a,ref:n})}),r=e.State;return r&&Object.assign(t,{State:r}),t.displayName=e.displayName??e.name??"NativeWebView",t}var Jt,Yi,Gt,Zi,se,S,b,es,Xt,W,ts,rs,os,ht,In,ns,is,yo,ss,as,ls,he=po(()=>{q();Xl(Cn,nd);od();Jt=Qe,Yi=["shadowColor","shadowOffset","shadowOpacity","shadowRadius","textShadowColor","textShadowOffset","textShadowRadius"],Gt=e=>typeof e=="number"?`${e}px`:e;Zi=Jt.StyleSheet.create({auto:{pointerEvents:"auto"},none:{pointerEvents:"none"},"box-none":{pointerEvents:"box-none"},"box-only":{pointerEvents:"box-only"}});se={...Jt.StyleSheet,create:e=>Jt.StyleSheet.create(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Rn(r)])))};S=at(Qe.View),b=at(Qe.Text),es={...Jt.Animated,View:Jt.Animated.createAnimatedComponent(S),Text:Jt.Animated.createAnimatedComponent(b)},Xt=at(Qe.TextInput),W=at(Qe.TouchableOpacity),ts=at(Qe.TouchableHighlight),rs=at(Qe.TouchableWithoutFeedback),os=at(Qe.Pressable),ht=at(Qe.ScrollView),In=Ki((e,t)=>{let r=Vd(null),o=_d(n=>{if(n){let i=n;for(;i.parentElement&&i.parentElement!==document.body;)i=i.parentElement;i.parentElement===document.body&&(r.current=i,Object.assign(i.style,{position:"relative",zIndex:"2147483647",pointerEvents:"auto"}),Gi().appendChild(i))}else r.current&&(document.body.appendChild(r.current),r.current=null);typeof t=="function"?t(n):t&&(t.current=n)},[t]);return Tn(rd,null,Tn(Qe.Modal,{...e,ref:o}))});In.displayName="Modal";ns=at(In),is=at(Qe.Switch),yo=at(Qe.ActivityIndicator),ss=at(Qe.Button),as=Qe.findNodeHandle,ls={alert(e,t,r,o){if(typeof document>"u")return;let n=document.createElement("dialog");n.dataset.buoyRoot="",n.setAttribute("aria-label",e),n.style.cssText="position:fixed;inset:0;margin:auto;width:min(440px,90vw);padding:24px;border:1px solid #475569;border-radius:14px;background:#17212e;color:#f1f5f9;font:14px system-ui;box-shadow:0 20px 80px #0008;z-index:2147483647";let i=document.createElement("h2");if(i.textContent=e,i.style.cssText="font-size:18px;margin:0 0 12px",n.appendChild(i),t){let l=document.createElement("p");l.textContent=t,l.style.cssText="line-height:1.5;white-space:pre-wrap;margin:0 0 20px",n.appendChild(l)}let s=document.createElement("div");s.style.cssText="display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px";let d=r?.length?r:[{text:"OK"}],a=()=>{n.close?.(),n.remove()};for(let l of d){let c=document.createElement("button");c.type="button",c.textContent=l.text??"OK",c.style.cssText=`padding:9px 14px;border:1px solid #64748b;border-radius:7px;color:white;background:${l.style==="destructive"?"#a52b38":"#283a4d"};cursor:pointer;font:inherit`,c.onclick=()=>{a(),l.onPress?.()},s.appendChild(c)}n.addEventListener("cancel",l=>{l.preventDefault(),o?.cancelable!==false&&(a(),o?.onDismiss?.())}),n.appendChild(s),document.body.appendChild(n),n.showModal?n.showModal():n.setAttribute("open","")}}});q();q();q();he();import{useSyncExternalStore as ds}from"react";import{NetworkIcon as Ud}from"@buoy-gg/shared-ui/web";q();import{hasAccountAccess as cs,subscribeAccountAccess as Jd}from"@buoy-gg/shared-ui/web";q();q();q();function fe(){let e=globalThis.__buoyRealNow;return typeof e=="function"?e():Date.now()}function us(){return globalThis.__buoyRealTimers??globalThis}function Ar(e,t){return us().setTimeout(e,t)}function Kt(e){us().clearTimeout(e)}q();function Et(e){if(!e?.aborted)return;if(e.reason!==void 0)throw e.reason;let t=new Error("The request was aborted.");throw t.name="AbortError",t}function Pn(e,t){return new Promise((r,o)=>{try{Et(t)}catch(d){o(d);return}let n=()=>t?.removeEventListener("abort",i),i=()=>{Kt(s),n();try{Et(t)}catch(d){o(d)}},s=Ar(()=>{n(),r()},e);t?.addEventListener("abort",i,{once:true})})}var mo=e=>Math.max(1,Math.min(16384,Math.floor(e*.02))),En=e=>new TextEncoder().encode(e).byteLength;function bo(e){return e==null?0:typeof e=="string"?En(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:typeof Blob<"u"&&e instanceof Blob?e.size:typeof URLSearchParams<"u"&&e instanceof URLSearchParams?En(e.toString()):null}async function vo(e,t,r,o){let n=mo(t),i=fe();for(let s=0;s<e;){let d=Math.min(n,e-s);await Pn(Math.max(0,i+(s+d)/t*1e3-fe()),r),Et(r),s+=d,o?.(s,e)}}function Gd(e,t){try{let r=typeof e=="object"&&"method"in e?e:void 0,o=t?.body!==void 0?t.body:r&&"_bodyInit"in r?r._bodyInit:r?.body;return Bn(o)}catch{return hs(0)}}function hs(e){return{knownBytes:e,status:e>0?"partial":"not-applied",note:e>0?"upload cap partial: size unknown":"upload cap not applied: size unknown"}}function Bn(e){let t=0;try{let r=bo(e);if(r!==null)return{knownBytes:r,status:"applied"};if(e&&typeof e=="object"){let o=e,n=Array.isArray(o._parts)?o._parts:typeof FormData<"u"&&e instanceof FormData&&o.entries?o.entries():void 0;if(n)for(let[,i]of n)try{let s=bo(i);s!==null?t+=s:i&&typeof i=="object"&&"uri"in i&&"size"in i&&typeof i.size=="number"&&Number.isSafeInteger(i.size)&&i.size>=0&&(t+=i.size)}catch{}}}catch{}return hs(t)}function ps(e){let t=0;return async(r,o)=>{let n=r/e*1e3,i=fe(),s=Math.max(0,n-t);s>0&&await Pn(s,o),Et(o),t=Math.min(mo(e)/e*1e3,Math.max(0,t+fe()-i-n))}}function Xd(e,t,r,o){let n=ps(t),i,s=()=>{i?.releaseLock(),i=void 0},d=u=>{(i?i.cancel(u):e.cancel(u)).catch(()=>{}),s()},a=new AbortController,l,c=0,y=false,w,p=(u,R=false)=>{y||(y=true,r?.removeEventListener("abort",C),a.abort(),l=void 0,R?w.error(u):(s(),w.close()),o?.(null,u))},C=()=>{let u=r?.reason!==void 0?r.reason:Object.assign(new Error("The request was aborted."),{name:"AbortError"});p(u,true),d(u)};return new ReadableStream({start(u){w=u,r?.addEventListener("abort",C,{once:true}),r?.aborted&&C()},async pull(){try{if(!l||c===l.byteLength){let h=await(i??(i=e.getReader())).read();if(y)return;if(h.done){p();return}l=h.value,c=0}let u=Math.min(mo(t),l.byteLength-c),R=l.subarray(c,c+u);if(await n(u,a.signal),y)return;c+=u,o?.(R),w.enqueue(R)}catch(u){y||(p(u,true),d(u))}},cancel(u){y||(y=true,r?.removeEventListener("abort",C),a.abort(),l=void 0,o?.(null,u??new Error("Body read stopped."))),d(u)}},{highWaterMark:0})}function fs(e,t,r,o,n=false){if(n||[204,205,304].includes(e.status)||e.body===null)return o?.(null),e;let i,s=false,d=()=>{if(!i){let l,c=false,y=new ReadableStream({async pull(w){s=true;try{if(e.body?.getReader){l??(l=e.body.getReader());let p=await l.read();if(c)return;p.done?(c=true,l.releaseLock(),l=void 0,w.close()):w.enqueue(p.value)}else{let p=new Uint8Array(await e.arrayBuffer());if(c)return;w.enqueue(p),c=true,w.close()}}catch(p){c||(c=true,l?.releaseLock(),l=void 0,w.error(p))}},cancel(w){s=true,c=true;let p=l?l.cancel(w):e.body?.cancel?.(w);return l?.releaseLock(),l=void 0,p}},{highWaterMark:0});i=Xd(y,t,r,o)}return i},a=async(l=true)=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");s=true;let c=d().getReader(),y=[],w=0;try{for(;;){let u=await c.read();if(u.done)break;l&&(y.push(u.value),w+=u.value.byteLength)}}finally{c.releaseLock()}let p=new Uint8Array(w),C=0;for(let u of y)p.set(u,C),C+=u.byteLength;return p};return new Proxy(e,{get(l,c){if(c==="body")return d();if(c==="bodyUsed")return s||e.bodyUsed;if(c==="arrayBuffer")return async()=>(await a()).buffer;if(c==="bytes")return a;if(c==="text")return async()=>new TextDecoder().decode(await a());if(c==="json")return async()=>JSON.parse(new TextDecoder().decode(await a()));if(c==="blob")return async()=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");Et(r);let w=false;try{new Blob([new Uint8Array(0)]),w=true}catch{}if(w)return new Blob([await a()],{type:l.headers.get("content-type")??""});let p=l.clone(),C;Object.defineProperty(p,"arrayBuffer",{configurable:true,value:async()=>(p.body&&!p.body.locked&&p.body.cancel().catch(()=>{}),C??(C=a()),(await C).buffer)});try{let u=p.blob();return u.catch(()=>{}),await(C??a(false)),Et(r),await u}finally{p.body&&!p.body.locked&&p.body.cancel().catch(()=>{})}};if(c==="formData")return async()=>{let w=await a();return new Response(w,{headers:l.headers}).formData()};if(c==="clone")return()=>{if(s||i?.locked||e.bodyUsed)throw new TypeError("Body has already been read.");return fs(l.clone(),t,r)};let y=Reflect.get(l,c,l);return typeof y=="function"?y.bind(l):y}})}import{isBuoyRequest as Kd}from"@buoy-gg/shared-ui/web";q();function wo(e){if(typeof document>"u")return e;try{return new URL(e,document.baseURI).href}catch{return e}}q();var gs=globalThis;function So(e){let t=gs.__BUOY_NETWORK_REQUEST_SEQUENCE__??(gs.__BUOY_NETWORK_REQUEST_SEQUENCE__={session:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,next:0});return`${e}_${t.session}_${++t.next}`}q();q();var ys=2,ms=3,Nr=4,ko=e=>e,bs=false;function vs(e){let t=ko(e);return typeof t.setReadyState=="function"&&typeof t.setResponseHeaders=="function"}function Qd(e){return typeof e.addEventListener=="function"&&typeof e.removeEventListener=="function"&&typeof e.dispatchEvent=="function"}function Yd(){bs||(bs=true,typeof we<"u"&&we&&console.warn("[Buoy] Network overrides need an XMLHttpRequest they can drive (React Native's, or a standards EventTarget one) and this environment provides neither \u2014 requests will run normally."))}function ws(e,t,r){let o=ko(e);o.responseURL=t,o.status=r.status,o.statusText=r.statusText,o.setResponseHeaders?.(r.headers),o.setReadyState?.(ys),!o._aborted&&(o._responseType="text",o._response=r.body,o._cachedResponse=void 0,o.setReadyState?.(ms),!o._aborted&&o.setReadyState?.(Nr))}function Ss(e,t){let r=ko(e),o=t.failKind==="timeout";r._hasError=true,r._timedOut=o,r._responseType="text",r._response=o?"Request timed out (Buoy override)":"Network request failed (Buoy override)",r._cachedResponse=void 0,r.setReadyState?.(Nr)}function Bt(e,t,r){Object.defineProperty(e,t,{value:r,configurable:true,enumerable:true,writable:false})}function Zd(e){if(e!=="readystatechange"&&typeof ProgressEvent=="function")try{return new ProgressEvent(e)}catch{}if(typeof Event=="function")try{return new Event(e)}catch{}return{type:e}}function Qt(e,t){e.dispatchEvent(Zd(t))}function Mr(e,t){Bt(e,"readyState",t),Qt(e,"readystatechange")}function ec(e,t){let r="";try{r=e.responseType}catch{}switch(r){case"":case"text":return t.body;case"json":try{return JSON.parse(t.body)}catch{return null}case"arraybuffer":return typeof TextEncoder=="function"?new TextEncoder().encode(t.body).buffer:t.body;case"blob":if(typeof Blob=="function"){let o=Object.entries(t.headers).find(([n])=>n.toLowerCase()==="content-type")?.[1]??"";return new Blob([t.body],{type:o})}return t.body;default:return t.body}}function tc(e,t,r,o){let n=r.headers,i=Object.entries(n).map(([s,d])=>`${s.toLowerCase()}: ${d}\r
2
+ `).join("");Bt(e,"getAllResponseHeaders",()=>i),Bt(e,"getResponseHeader",s=>{let d=String(s).toLowerCase();for(let[a,l]of Object.entries(n))if(a.toLowerCase()===d)return l;return null}),Bt(e,"responseURL",t),Bt(e,"status",r.status),Bt(e,"statusText",r.statusText),Bt(e,"response",ec(e,r)),Bt(e,"responseText",r.body),Mr(e,ys),!o()&&(Mr(e,ms),!o()&&(Mr(e,Nr),!o()&&(Qt(e,"load"),Qt(e,"loadend"))))}function Ln(e,t){Mr(e,Nr),Qt(e,t.failKind==="timeout"?"timeout":"error"),Qt(e,"loadend")}var wr=new WeakMap;function rc(e){return wr.has(e)}function oc(e,t,r,o){let n=fe(),i={},s,d,a=false,l=false,c=false,y=e.timeout,w=e.abort,p=e.open,C=["abort","open","timeout","readyState","status","statusText","response","responseText","responseURL","getAllResponseHeaders","getResponseHeader"],u=new Map(C.map(B=>[B,Object.getOwnPropertyDescriptor(e,B)])),R=Object.getPrototypeOf(e),h;for(;R&&!h;)h=Object.getOwnPropertyDescriptor(R,"timeout"),R=Object.getPrototypeOf(R);let m=()=>{a=true,wr.get(e)===i&&wr.delete(e),clearTimeout(s),Kt(d),e.removeEventListener("loadend",m)},x=()=>{m();for(let[B,E]of u)E?Object.defineProperty(e,B,E):delete e[B];e.timeout=y},I=()=>{Kt(d),c?h?.set?.call(e,y>0?Math.max(1,y-(fe()-n)):0):y>0&&(d=Ar(()=>{a||(clearTimeout(s),Ln(e,{...r,kind:"fail",failKind:"timeout"}),m())},Math.max(0,y-(fe()-n))))};return Object.defineProperty(e,"timeout",{configurable:true,get:()=>y,set:B=>{y=Math.max(0,Number(B)||0),I()}}),Object.defineProperty(e,"open",{configurable:true,value:(...B)=>(x(),Reflect.apply(p,e,B))}),Object.defineProperty(e,"abort",{configurable:true,value:()=>{if(c||a){x(),w.call(e);return}l=true,clearTimeout(s),Mr(e,Nr),Qt(e,"abort"),Qt(e,"loadend"),m(),wr.has(e)||Bt(e,"readyState",0)}}),wr.set(e,i),e.addEventListener("loadend",m),I(),s=setTimeout(()=>{if(!(a||l)){if(r.kind==="delay"){c=true,I();try{o()}catch{Ln(e,{...r,kind:"fail",failKind:"network"}),m()}return}r.kind==="fail"?Ln(e,r):tc(e,t,r,()=>l||wr.get(e)!==i),m()}},r.delayMs),true}function ks(e,t,r,o){if(!vs(e))return Qd(e)?oc(e,t,r,o):(Yd(),false);let n=ko(e);n._sent=true,n._requestId=null;let i=null,s=()=>{e.removeEventListener("abort",s),i!==null&&(clearTimeout(i),i=null)};return e.addEventListener("abort",s),i=setTimeout(()=>{if(i=null,e.removeEventListener("abort",s),!n._aborted){if(r.kind==="delay"){n._sent=false,o();return}if(r.kind==="fail"){Ss(e,r);return}ws(e,t,r)}},r.delayMs),true}function nc(e,t,r){r.kind==="fail"?Ss(e,r):r.kind==="respond"&&ws(e,t,r)}function ic(e,t,r,o,n,i){if(!vs(e)){if(r.downloadBytesPerSecond)throw new Error("Byte caps need RN XHR. This XHR only supports waits and Offline.");let P={id:"condition",enabled:true,urlPattern:t,kind:"delay",hits:0,seen:0,createdAt:Date.now()},A=r.profile==="offline"?{kind:"fail",rule:P,failKind:"network",delayMs:0}:o?{...o,delayMs:r.delayMs+o.delayMs}:{kind:"delay",rule:P,delayMs:r.delayMs};if(!ks(e,t,A,n))throw new Error("Network conditions are unavailable for this XMLHttpRequest implementation.");return}let s=e;if(s.readyState!==1||s._sent)throw new Error("Request is not open or has already been sent.");let d=fe(),a=s.timeout,l=false,c=new AbortController,y=[],w=false,p,C,u=s.abort,R=s.open,h=Object.getOwnPropertyDescriptor(s,"abort"),m=Object.getOwnPropertyDescriptor(s,"open"),x=Object.getOwnPropertyDescriptor(s,"timeout"),I=(P,A)=>{A?Object.defineProperty(s,P,A):delete s[P]},B=()=>{l||(l=true,Kt(C),c.abort(),y.forEach(P=>P()),Kt(p),s.removeEventListener("loadend",B),I("abort",h),I("open",m),I("timeout",x),s.timeout=a)},E=(P,A)=>{l||(Object.assign(s,{readyState:4}),u.call(s),s._aborted=false,s._hasError=true,s._timedOut=P,s._response=A??(P?"Request timed out (Buoy conditions)":"Network request failed (Buoy Offline)"),s.setReadyState(4),B())},D=()=>a>0&&fe()-d>=a,k=()=>{Kt(p),a>0&&(p=Ar(()=>E(true),Math.max(0,a-(fe()-d))))};Object.defineProperty(s,"timeout",{configurable:true,get:()=>w?0:a,set:P=>{a=Math.max(0,Number(P)||0),k()}}),Object.defineProperty(s,"abort",{configurable:true,value:()=>{l||(u.call(s),B())}}),Object.defineProperty(s,"open",{configurable:true,value:(...P)=>{let A=Reflect.apply(R,s,P);return B(),A}}),s._sent=true,s._requestId=null,s.addEventListener("loadend",B),k();let g=s,v=(P,A)=>{let _=Object.getOwnPropertyDescriptor(s,P);Object.defineProperty(s,P,{configurable:true,writable:true,value:A}),y.push(()=>I(P,_))},f=(P,A,_)=>{let F=new Event("progress");Object.defineProperties(F,{loaded:{value:A},total:{value:_},lengthComputable:{value:true}}),P.dispatchEvent(F)},T=r.downloadBytesPerSecond;if(T&&typeof g.__didReceiveData=="function"&&typeof g.__didCompleteResponse=="function"){let P=g.__didReceiveData.bind(s),A=g.__didReceiveIncrementalData?.bind(s),_=g.__didCompleteResponse.bind(s),F=g.__didReceiveDataProgress?.bind(s),L=Promise.resolve(),H=0,j=ps(T),J=Z=>{L=L.then(async()=>{l||await Z()}).catch(Y=>{l||E(false,Y instanceof Error?Y.message:String(Y))})},ee=async(Z,Y,Oe=-1)=>{if((!s.responseType||s.responseType==="text"||s.responseType==="json")&&typeof Y=="string"&&A){let Xe=new TextEncoder().encode(Y),De=new TextDecoder;for(let Ce=0;Ce<Xe.byteLength;){let Ke=Math.min(mo(T),Xe.byteLength-Ce);if(await j(Ke,c.signal),l)return;let ut=De.decode(Xe.subarray(Ce,Ce+Ke),{stream:Ce+Ke<Xe.byteLength});Ce+=Ke,H+=Ke,A(Z,ut,H,Oe),F?.(Z,H,Oe)}}else{let Xe=typeof Y=="object"&&Y?Y.size:s.responseType==="arraybuffer"&&typeof Y=="string"?Math.max(0,Y.length*3/4-(Y.endsWith("==")?2:Y.endsWith("=")?1:0)):bo(Y);if(typeof Xe!="number")throw new Error("Cannot read this response size.");let De=H;await vo(Xe,T,c.signal,Ce=>{H=De+Ce,F?.(Z,H,Oe<0?Xe:Oe)}),l||P(Z,Y)}};v("__didReceiveData",(Z,Y)=>J(()=>ee(Z,Y))),v("__didReceiveIncrementalData",(Z,Y,Oe,Xe)=>J(()=>ee(Z,Y,Xe))),v("__didReceiveDataProgress",()=>{}),v("__didCompleteResponse",(Z,Y,Oe)=>{if(Y){_(Z,Y,Oe);return}J(async()=>{l||_(Z,Y,Oe)})})}else if(T)throw B(),new Error("This XHR lacks the RN byte hooks.");let M=typeof g.__didUploadProgress=="function"?g.__didUploadProgress.bind(s):void 0;r.uploadBytesPerSecond&&M&&v("__didUploadProgress",()=>{}),C=Ar(()=>{(async()=>{if(!l){if(D()){E(true);return}if(r.profile==="offline"){E(false);return}if(r.uploadBytesPerSecond){let P=(r.uploadCap??Bn(i)).knownBytes;await vo(P,r.uploadBytesPerSecond,c.signal,(A,_)=>{M?M(s._requestId,A,_):s.upload&&f(s.upload,A,_)})}if(!l){if(o&&o.kind!=="delay"){T&&o.kind==="respond"&&await vo(bo(o.body)??0,T,c.signal),l||nc(s,t,o);return}s._sent=false,w=true;try{n()}finally{w=false}}}})().catch(P=>{l||E(false,P instanceof Error?P.message:String(P))})},r.delayMs+(o?.delayMs??0))}q();import{getAccountAccess as xs,hasAccountAccess as zn,subscribeAccountAccess as sc}from"@buoy-gg/shared-ui/web";q();q();var Cs=[204,205,304];function On(){return typeof Response=="function"}function ac(e,t){let r=Cs.includes(t.status)?null:t.body,o=new Response(r,{status:t.status,statusText:t.statusText,headers:t.headers});try{Object.defineProperty(o,"url",{value:e,configurable:true})}catch{}return o}function lc(e){return new TypeError(e.failKind==="timeout"?"Network request timed out":"Network request failed")}q();var dc="[]{}()\\.^$+|-,?";function Ts(e){let t="";for(let r=0;r<e.length;r++){let o=e.charAt(r);dc.indexOf(o)!==-1&&(t+="\\"),t+=o}return t.split("*").join(".*")}var xo=new Map;function cc(e){let t=xo.get(e);if(t)return t;let r=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${Ts(e)}`:Ts(e),o=new RegExp(`^${r}$`);return xo.size>200&&xo.clear(),xo.set(e,o),o}function uc(e,t){if(!e)return false;let r=t.toLowerCase();for(let o of Object.keys(e))if(o.toLowerCase()===r&&e[o]!==void 0&&e[o]!=="")return true;return false}function Rs(e){let t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(o=>[o,t(r[o])])):r;return JSON.stringify(t(e))??"null"}function hc(e,t,r,o){if(typeof e!="string"||!e.includes(t))return false;try{let n=JSON.parse(e);return o&&Array.isArray(n)?false:(Array.isArray(n)?n:[n]).some(i=>!i||typeof i!="object"||i.operationName!==t?false:r===void 0||Rs(i.variables??{})===r)}catch{return false}}function pc(e,t){if(typeof e!="string")return false;try{return Rs(JSON.parse(e))===t}catch{return JSON.stringify(e)===t}}function qn(e,t,r,o,n){if(e.methods&&e.methods.length>0&&!e.methods.includes(r.toUpperCase())||e.requireHeader&&!uc(o,e.requireHeader)||e.bodyIncludes&&(typeof n!="string"||!n.includes(e.bodyIncludes))||e.graphqlOperation&&!hc(n,e.graphqlOperation,e.graphqlVariables,e.graphqlSingle)||e.bodyJson!==void 0&&!pc(n,e.bodyJson))return false;try{return cc(e.urlPattern).test(t)}catch{return false}}q();import{TIER_LIMITS as fc}from"@buoy-gg/shared-ui/web";var $r=200,Hr=599,wt=50,Is=fc["network.overrideRules"].free;function Ps(e){return{ruleId:e.rule.id,ruleName:e.rule.name,kind:e.kind,delayMs:e.delayMs||void 0}}var gc=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function yc(e){return gc.some(t=>t.test(e))}function mc(e){let t=e.trim();if(t==="")return"text/plain; charset=utf-8";if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t),"application/json"}catch{}return"text/plain; charset=utf-8"}function bc(e,t){let r=t.toLowerCase();return Object.keys(e).some(o=>o.toLowerCase()===r)}function vc(e){let t=Math.max(0,e.delayMs??0);if(e.kind==="delay")return{kind:"delay",rule:e,delayMs:t};if(e.kind==="fail")return{kind:"fail",rule:e,delayMs:t,failKind:e.failKind??"network"};let r=Math.min(Hr,Math.max($r,e.status??200)),o=Cs.includes(r)?"":e.body??"",n={...e.headers??{}};return bc(n,"content-type")||(n["content-type"]=mc(o)),{kind:"respond",rule:e,delayMs:t,status:r,statusText:e.statusText??"",headers:n,body:o}}function Dn(e){return typeof e.times=="number"&&e.hits>=e.times}function wc(e){return e.alternate?e.seen%2===1:true}function An(e,t,r,o,n){if(r.length===0||t.toUpperCase()==="OPTIONS"||yc(e))return null;for(let i of r)if(i.enabled&&!Dn(i)&&qn(i,e,t,o,n))return i;return null}var _e=null;function Sc(e){_e=e}function Es(){return _e?.ready?.()??Promise.resolve()}function kc(){return _e?.isReady?.()??true}function xc(){return!!_e?.getRules().some(e=>e.enabled&&(e.bodyIncludes||e.graphqlOperation||e.bodyJson!==void 0))}function Cc(){return zn()&&!(typeof we<"u"&&!we)}var Tc="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";function Rc(e,t){return{hooksInstalled:_e!==null,devFlag:typeof we>"u"?"undefined":we,ruleCount:_e?_e.getRules().length:0,matches:_e?An(e,t,_e.getRules())!==null:false}}var Ic=3e3;function Pc(e,t,r,o){return!_e||zn()||typeof we<"u"&&!we||xs().status!=="initializing"||!An(e,t,_e.getRules(),r,o)?null:new Promise(n=>{let i=()=>{},s=()=>{Kt(d),i(),n()},d=Ar(s,Ic);i=sc(()=>{xs().status!=="initializing"&&s()})})}function Bs(e,t,r,o){if(!_e||typeof we<"u"&&!we)return null;let n=_e.getRules();if(n.length===0||!zn()&&(n=n.filter(d=>d.sandbox===true),n.length===0))return null;let i=An(e,t,n,r,o);if(!i)return null;let s=wc(i);return _e.recordMatch(i.id),s?(_e.recordHit(i.id),vc(i)):null}q();var Ec={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",408:"Request Timeout",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function Bc(e){return typeof e=="number"&&e>0?"response":"error"}function Lc(e,t){let r=(t??"").trim();return r||(Ec[e]??"")}var Yt;function Ls(e){let t=globalThis.__buoyHeaderInjectors;if(!t||t.length===0)return;let r;for(let o of t)try{let n=o(e);n&&(r={...r,...n})}catch{}return r}function zc(){if(Yt!==void 0)return Yt;Yt=null;try{if(typeof we<"u"&&!we)return Yt;let e=(he(),Kl(Cn))?.NativeModules?.SourceCode,t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t=="string"&&/^https?:\/\//.test(t)){let r=new URL(t);Yt=`${r.protocol}//${r.host}`}}catch{Yt=null}return Yt}var Zt=false,Oc=Symbol.for("buoy.earlyNetwork");function qc(e){let t={};if(!e)return t;if(typeof Headers<"u"&&e instanceof Headers)e.forEach((r,o)=>{t[o]=r});else if(Array.isArray(e))for(let[r,o]of e)t[r]=o;else Object.assign(t,e);return t}var zs="__buoyNetworkFetchIntercepted",Os="__buoyNetworkXhrIntercepted",Dc=["text/event-stream","application/x-ndjson","application/stream+json"],Nn="[streaming\u2026]",Mn=false;function Ac(){return Mn?true:(Mn=!!globalThis.document?.querySelector?.("[ng-version]"),Mn)}function qs(e){if(!e)return false;let t=e.toLowerCase();return Dc.some(r=>t.includes(r))}var Nc="__BUOY_INTERNAL_HOSTS__";function Mc(e){let t=globalThis[Nc];if(!(t instanceof Set)||t.size===0)return false;let r;try{r=new URL(e).host.toLowerCase()}catch{return false}for(let o of t)if(typeof o=="string"&&o&&r===o.toLowerCase())return true;return false}var $c=class{constructor(){this.listeners=[];this.isListening=false;this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.fetchGeneration=0;this.xhrGeneration=0;this.originalFetch=globalThis.fetch,this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if(Kd(e))return true;try{let t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh")||(t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/"))||(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2")&&["8081","8802"].includes(t.port))return true;let r=zc();if(r&&`${t.protocol}//${t.host}`===r)return true}catch{return false}return Mc(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch{}})}parseUrl(e){let t=null,r=e.indexOf("?");return r>-1&&(t={},e.substring(r+1).split("&").forEach(o=>{let[n,i]=o.split("=");n&&i!==void 0&&(t[n]=decodeURIComponent(i.replace(/\+/g," ")))})),{url:r>-1?e.substring(0,r):e,params:t}}async readStreamedBody(e,t=256*1024){let r=e.body;if(!r||typeof r.getReader!="function"){let a=await e.text();return a.length>t?{body:`${a.slice(0,t)}
3
3
 
4
- ... [truncated]`,size:a.length}:{body:a,size:a.length}}let o=r.getReader(),n=new TextDecoder,i="",s=0,l=false;try{for(;;){let{done:a,value:u}=await o.read();if(a)break;if(s+=u?.byteLength??0,!l&&(i+=n.decode(u,{stream:true}),s>=t)){i=`${i.slice(0,t)}
4
+ ... [truncated]`,size:a.length,truncated:true}:{body:a,size:a.length}}let o=r.getReader(),n=new TextDecoder,i="",s=0,d=false;try{for(;;){let{done:a,value:l}=await o.read();if(a)break;if(s+=l?.byteLength??0,!d&&(i+=n.decode(l,{stream:true}),s>=t)){i=`${i.slice(0,t)}
5
5
 
6
- ... [truncated]`,l=true;break}}l||(i+=n.decode())}finally{try{Promise.resolve(o.cancel()).catch(()=>{})}catch{}try{o.releaseLock()}catch{}}return{body:i,size:s}}async processResponseBody(e,t=1024*1024){try{let r=e.headers.get("content-length");if(r){let i=parseInt(r,10);if(!isNaN(i)&&i>t)return{body:`[Response too large: ${this.formatBytes(i)}]`,size:i,truncated:true}}let o=await e.text(),n=o.length;if(n>t){let i=o.substring(0,t),s=n-t;return{body:`${i}
6
+ ... [truncated]`,d=true;break}}d||(i+=n.decode())}finally{try{Promise.resolve(o.cancel()).catch(()=>{})}catch{}try{o.releaseLock()}catch{}}return{body:i,size:s,truncated:d||void 0}}async processResponseBody(e,t=1024*1024){try{let r=e.headers.get("content-length");if(r){let i=parseInt(r,10);if(!isNaN(i)&&i>t)return{body:`[Response too large: ${this.formatBytes(i)}]`,size:i,truncated:true,json:false}}let o=await e.text(),n=o.length;if(n>t){let i=o.substring(0,t),s=n-t;return{body:`${i}
7
7
 
8
- ... [truncated, ${this.formatBytes(s)} omitted]`,size:n,truncated:true}}try{return{body:JSON.parse(o),size:n,truncated:false}}catch{return{body:o,size:n,truncated:false}}}catch{return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";let t=1024,r=["B","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,o)*100)/100} ${r[o]}`}handleXHRResponse(e,t,r,o,n,i,s,l,a=false,u="xhr",d,g){let x=l?ue()-l:0,y=e._buoyTtfb,R=y===void 0?void 0:{ttfb:y,download:Math.max(0,x-y)};if(a||e.status===0){this.emit({type:"error",timestamp:new Date,duration:x,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:u},error:{message:a?"Request failed":"Network error or request aborted"},override:d,condition:g});return}let h,C=0;try{let w=e.response;if(e.responseType==="json"&&w)h=w,C=JSON.stringify(w).length;else if(e.responseType===""||e.responseType==="text"){if(e.responseText){C=e.responseText.length;try{h=JSON.parse(e.responseText)}catch{h=e.responseText}}}else if(e.responseType==="arraybuffer")if(w)try{let I=new TextDecoder("utf-8").decode(w);C=I.length;try{h=JSON.parse(I)}catch{h=I}}catch{h=`[arraybuffer response - ${w.byteLength||0} bytes]`,C=w.byteLength||0}else h="[arraybuffer response - no data]",C=0;else if(e.responseType==="blob")if(w instanceof Blob)h=`[blob response - ${w.size} bytes, type: ${w.type||"unknown"}]`,C=w.size;else if(w)try{h=typeof w=="string"?JSON.parse(w):w,C=JSON.stringify(h).length}catch{h="[blob response - unable to parse]",C=0}else h="[blob response - no data]",C=0;else if(w)if(typeof w=="string"){h=w,C=w.length;try{h=JSON.parse(w)}catch{}}else typeof w=="object"?(h=w,C=JSON.stringify(w).length):(h=String(w),C=String(w).length)}catch{h="~~~ unable to read body ~~~"}if(g?.downloadBytesPerSecond&&(!e.responseType||e.responseType==="text"||e.responseType==="json")){let w=e._response;typeof w=="string"&&(C=Fo(w))}let k={};try{let w=e.getAllResponseHeaders();w&&w.split(`\r
9
- `).forEach(I=>{if(I){let z=I.indexOf(": ");if(z>0){let $=I.substring(0,z).toLowerCase(),P=I.substring(z+2);k[$]=P}}})}catch{}id(e.status)==="response"?this.emit({type:"response",timestamp:new Date,duration:x,timings:R,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:u},response:{status:e.status,statusText:sd(e.status,e.statusText),headers:k,body:h,size:C},override:d,condition:g}):this.emit({type:"error",timestamp:new Date,duration:x,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:u},response:{status:e.status,statusText:e.statusText,headers:k,body:h,size:C},error:{message:"Network Error"},override:d,condition:g})}isFetchInterceptionLive(){return globalThis.fetch[Li]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[Bi]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){let e=this.isListening&&this.isFetchInterceptionLive(),t=this.isListening&&this.isXhrInterceptionLive();e&&t||(e||this.installFetchInterceptor(),t||this.installXhrInterceptor(),this.isListening=true)}installFetchInterceptor(){let e=this,t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let r=++this.fetchGeneration,o=async(n,i)=>{let s=zr(typeof n=="string"?n:n instanceof URL?n.href:n.url);if(r!==e.fetchGeneration)return t(n,i);if(i?.__buoyInternal||e.shouldIgnoreUrl(s)){let c=It;It=true;try{return t(n,i)}finally{It=c}}let l=ue(),a=Dr("fetch"),u=typeof n=="object"&&"method"in n?n:void 0,d=i?.method??u?.method??"GET",g=i?.signal!==void 0?i.signal:u?.signal;lt(g);let x=Di(s),y=x?.uploadBytesPerSecond?{...x,uploadCap:Cl(n,i)}:x,{url:R,params:h}=e.parseUrl(s),C={},k=i?.headers??u?.headers;k&&(k instanceof Headers?k.forEach((c,p)=>{C[p]=c}):Array.isArray(k)?k.forEach(([c,p])=>{C[c]=p}):C={...k}),Object.assign(C,Pi(s));let w;if(i?.body)if(typeof i.body=="string")try{w=JSON.parse(i.body)}catch{w=i.body}else w=i.body;let I=C["X-Request-Client"]||C["x-request-client"]||"fetch";y?.profile!=="offline"&&Uo()&&await Ei();let z=typeof i?.body=="string"?i.body:void 0;if(z===void 0&&i?.body===void 0&&u&&!u.bodyUsed&&d!=="GET"&&d!=="HEAD"&&Zl())try{z=(await e.readStreamedBody(u.clone())).body}catch{}let $=y?.profile!=="offline"&&Uo()?od(s,d,C,z):null;$&&await $;let P=y?.profile!=="offline"&&Uo()?Ii(s,d,C,z):null,A=P?Ri(P):void 0;e.emit({type:"request",timestamp:new Date,request:{id:a||"unknown",url:R,method:d,headers:C,data:w,params:h||void 0,client:I},override:A,condition:y});let v=c=>{try{w=JSON.parse(c)}catch{w=c}e.emit({type:"request-body",timestamp:new Date,request:{id:a||"unknown",url:R,method:d,data:w,client:I}})};if(i?.body===void 0&&u&&typeof z=="string")v(z);else if(!y?.uploadBytesPerSecond&&i?.body===void 0&&u&&!u.bodyUsed&&d!=="GET"&&d!=="HEAD")try{let c=u.clone();e.readStreamedBody(c).then(({body:p})=>{p&&v(p)}).catch(()=>{})}catch{}try{if((y||P)&&await $o((y?.delayMs??0)+(P?.delayMs??0),g),lt(g),y?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(P?.kind==="fail")throw Hl(P);y?.uploadBytesPerSecond&&(await Or(y.uploadCap?.knownBytes??0,y.uploadBytesPerSecond,g),lt(g));let c;if(P?.kind==="respond")c=Al(s,P);else{let M=It;It=true;let N;try{N=t(n,i)}finally{It=M}c=await N}if(y?.downloadBytesPerSecond){let M={};c.headers.forEach((K,be)=>{M[be.toLowerCase()]=K});let N=0,J=0,le=[],ne=(K,be)=>{let pe=new Uint8Array(J),ft=0;for(let Ye of le)pe.set(Ye,ft),ft+=Ye.byteLength;let Ae=K?new TextDecoder().decode(pe):Go;if(K&&M["content-type"]?.includes("json"))try{Ae=JSON.parse(Ae)}catch{}e.emit({type:be!==void 0?"error":"response",timestamp:new Date,duration:ue()-l,request:{id:a,url:R,method:d,headers:C,data:w,params:h||void 0,client:I},response:{status:c.status,statusText:c.statusText,headers:M,body:Ae,size:N},...be!==void 0?{error:{message:be instanceof Error?be.message:String(be)}}:{},override:A,condition:y})};return ne(false),pi(c,y.downloadBytesPerSecond,g,(K,be)=>{if(K){N+=K.byteLength;let pe=Math.min(K.byteLength,65536-J);pe>0&&(le.push(K.slice(0,pe)),J+=pe)}else ne(true,be)},d.toUpperCase()==="HEAD")}let p=ue()-l,f=typeof c.body?.getReader=="function"||qi(c.headers?.get?.("content-type")),S=c.clone(),{body:D,size:H}=f?{body:Go,size:0}:await e.processResponseBody(S),V=ue()-l,Z=Math.max(0,V-p),Y=Z>0?{ttfb:p,download:Z}:void 0,L={};if(c.headers.forEach((M,N)=>{L[N.toLowerCase()]=M}),e.emit({type:"response",timestamp:new Date,duration:V,timings:Y,request:{id:a||"unknown",url:R,method:d,headers:C,data:w,params:h||void 0,client:I},response:{status:c.status,statusText:c.statusText,headers:L,body:D,size:H},override:A,condition:y}),f){let M=c.headers?.get?.("content-type");e.readStreamedBody(S,qi(M)?void 0:1024*1024).then(N=>{let J=N.body;if(M?.includes("json"))try{J=JSON.parse(N.body)}catch{}e.emit({type:"response",timestamp:new Date,duration:ue()-l,timings:Y,request:{id:a||"unknown",url:R,method:d,headers:C,data:w,params:h||void 0,client:I},response:{status:c.status,statusText:c.statusText,headers:L,body:J,size:N.size},override:A,condition:y})}).catch(()=>{})}return c}catch(c){let p=ue()-l;throw e.emit({type:"error",timestamp:new Date,duration:p,request:{id:a||"unknown",url:R,method:d,headers:C,data:w,params:h||void 0,client:I},error:{message:c instanceof Error?c.message:"Network error",stack:c instanceof Error?c.stack:void 0},override:A,condition:y}),c}};o[Li]=true,this.patchedFetch=o,globalThis.fetch=this.patchedFetch}installXhrInterceptor(){let e=this,t=XMLHttpRequest.prototype.open,r=XMLHttpRequest.prototype.send,o=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t,this.originalXHRSend=r,this.originalXHRSetRequestHeader=o;let n=++this.xhrGeneration,i=new WeakMap,s=function(u,d,g,x,y){let R=t.call(this,u,d,g??true,x,y);if(n===e.xhrGeneration){i.get(this)?.();let h=this;h._buoyRequestId=Dr("xhr"),h._method=u,h._url=zr(d),h._buoyStartTime=ue(),h._requestHeaders={},h._buoyAsync=g!==false,h._buoyRestoreAbort?.(),h._buoyWaitedForRules=false,h._buoyHeldSend=false,h._buoyOpenSeq=(h._buoyOpenSeq??0)+1}return R},l=function(u,d){let g=this;return n===e.xhrGeneration&&g._requestHeaders&&(g._requestHeaders[u]=d),o.call(this,u,d)},a=function(u){if(n!==e.xhrGeneration||It)return r.call(this,u);if(Bl(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent)return r.call(this,u);let d=this;if(d._buoyHeldSend)throw new DOMException("The request has already been sent.","InvalidStateError");if(!Yl()&&d._buoyAsync!==false&&!d._buoyWaitedForRules){d._buoyWaitedForRules=true,d._buoyHeldSend=true;let L=d._buoyOpenSeq,M=false,N=Object.prototype.hasOwnProperty.call(this,"abort")?this.abort:void 0,J=()=>{d._buoyRestoreAbort===J&&(d._buoyRestoreAbort=void 0,N?this.abort=N:delete this.abort)};d._buoyRestoreAbort=J;let le=N??Object.getPrototypeOf(this).abort;this.abort=function(){return M=true,d._buoyHeldSend=false,J(),le.call(this)};let ne=()=>{J(),!(M||d._buoyOpenSeq!==L)&&(d._buoyHeldSend=false,this.readyState===1&&!this._sent&&a.call(this,u))};Ei().then(ne,ne);return}let g=d._buoyRequestId,x=d._method||"GET",y=d._url||"",R=ue();d._buoyStartTime=R,d._buoyTtfb=void 0;let h=d._requestHeaders||{};if(Object.assign(h,Pi(y)),e.shouldIgnoreUrl(y))return r.call(this,u);let{url:C,params:k}=e.parseUrl(y),w;if(u)if(typeof u=="string")try{w=JSON.parse(u)}catch{w=u}else w=u;let I=h["X-Request-Client"]||h["x-request-client"],z=h.Accept||h.accept||"",$=z.includes("application/json")&&z.includes("text/plain")&&z.includes("*/*")&&!cd(),P=I||($?"axios":"xhr"),A=Di(y),v=A?.uploadBytesPerSecond?{...A,uploadCap:jo(u)}:A,c=v?.profile==="offline"?null:Ii(y,x,h,typeof u=="string"?u:void 0),p=c?Ri(c):void 0;e.emit({type:"request",timestamp:new Date,request:{id:g||"unknown",url:C,method:x,headers:h,data:w,params:k||void 0,client:P},override:p,condition:v});let f=false,S=(L=false)=>{f||(f=true,e.handleXHRResponse(this,g||"unknown",C,x,h,w,k,R||0,L,P,p,v),D())},D=()=>{i.delete(this),this.removeEventListener("load",H),this.removeEventListener("error",V),this.removeEventListener("abort",Z),this.removeEventListener("readystatechange",Y)};i.set(this,D);let H=()=>{S(false)},V=()=>{S(true)},Z=()=>{S(true)},Y=()=>{if(this.readyState===2){let L=this;L._buoyTtfb===void 0&&L._buoyStartTime&&(L._buoyTtfb=ue()-L._buoyStartTime)}this.readyState===4&&!f&&S(false)};if(this.addEventListener("load",H),this.addEventListener("error",V),this.addEventListener("abort",Z),this.addEventListener("readystatechange",Y),v){zl(this,y,v,c,()=>r.call(this,u),u);return}if(!(c&&wi(this,y,c,()=>r.call(this,u))))return r.call(this,u)};a[Bi]=true,this.patchedXHROpen=s,this.patchedXHRSend=a,this.patchedXHRSetRequestHeader=l,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend,XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){this.isListening&&(this.fetchGeneration++,this.xhrGeneration++,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.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader),this.patchedFetch=null,this.patchedXHROpen=null,this.patchedXHRSend=null,this.patchedXHRSetRequestHeader=null,this.isListening=false)}adoptEarlyRequests(){let e=globalThis,t=e[ld]??e.__BUOY_EARLY_NETWORK__;if(t?.version===1)for(let r of t.adopt())try{r.kind==="fetch"?this.adoptEarlyFetch(r):this.adoptEarlyXhr(r)}catch{}}adoptEarlyFetch(e){let{input:t,init:r}=e,o=typeof t=="object"&&"method"in t?t:void 0,n=zr(typeof t=="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(n))return;let i=Dr("fetch"),s=r?.method??o?.method??"GET",{url:l,params:a}=this.parseUrl(n),u=dd(r?.headers??o?.headers),d=r?.body;if(typeof d=="string")try{d=JSON.parse(d)}catch{}let g=u["X-Request-Client"]||u["x-request-client"]||"fetch",x=()=>({id:i,url:l,method:s,headers:u,data:d,params:a||void 0,client:g});this.emit({type:"request",timestamp:new Date(e.start),request:x()}),e.requestCopy&&this.readStreamedBody(e.requestCopy).then(({body:y})=>{try{d=JSON.parse(y)}catch{d=y}this.emit({type:"request-body",timestamp:new Date,request:{id:i,url:l,method:s,data:d,client:g}})}).catch(()=>{}),e.settled.then(async({response:y,clone:R,error:h,headersAt:C})=>{if(!y){this.emit({type:"error",timestamp:new Date,duration:C-e.start,request:x(),error:{message:h instanceof Error?h.message:"Network error",stack:h instanceof Error?h.stack:void 0}});return}let{body:k,size:w}=R?await this.processResponseBody(R):{body:Go,size:0},I=Math.max(0,ue()-e.start),z=C-e.start,$={};y.headers.forEach((P,A)=>{$[A.toLowerCase()]=P}),this.emit({type:"response",timestamp:new Date,duration:I,timings:I>z?{ttfb:z,download:I-z}:void 0,request:x(),response:{status:y.status,statusText:y.statusText,headers:$,body:k,size:w}})})}adoptEarlyXhr(e){let t=zr(e.url);if(this.shouldIgnoreUrl(t))return;let r=Dr("xhr"),o=e.method.toUpperCase(),{url:n,params:i}=this.parseUrl(t),s=e.body;if(typeof s=="string")try{s=JSON.parse(s)}catch{}let l=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:r,url:n,method:o,headers:e.headers,data:s,params:i||void 0,client:l}});let a=e.xhr,u=()=>{let d=(a._buoyEarlyEnd??ue())-e.start;this.handleXHRResponse(a,r,n,o,e.headers,s,i,ue()-d,false,l)};a.readyState===4?u():a.addEventListener("loadend",u,{once:true})}addListener(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}},gt=null,Yo=()=>(gt||(gt=new fd),gt),Mr=Yo,Oi=()=>Yo().startListening(),pr=()=>gt?.stopListening(),fr=e=>Yo().addListener(e),yd=()=>gt?.removeAllListeners(),zi=()=>gt?.isActive??false,Pt=()=>gt?.listenerCount??0,gd=()=>gt?.isInterceptionLive()??false;O();var mt={normal:{label:"Normal",delayMs:0},offline:{label:"Offline (requests)",delayMs:0},slow:{label:"Slow (+500 ms)",delayMs:500},verySlow:{label:"Very slow (+2000 ms)",delayMs:2e3},slow3g:{label:"Slow 3G",delayMs:2e3,downloadBytesPerSecond:5e4,uploadBytesPerSecond:5e4},slow4g:{label:"Slow 4G",delayMs:562.5,downloadBytesPerSecond:18e4,uploadBytesPerSecond:84375},fast4g:{label:"Fast 4G",delayMs:165,downloadBytesPerSecond:1012500,uploadBytesPerSecond:168750}},md=["auto","real","offline","wifi","cellular","noInternet"],bd={download:"Paces bytes to the app in JS. The socket stays at its real speed.",upload:"Waits before send for known body bytes. Unknown sizes pass through with latency only. Multipart overhead is not counted. Each call marks a partial or skipped cap. Upload time is simulated; the socket is not paced.",transports:"Affects global fetch and RN XHR. WebSocket, native images, native SDKs and file transfers are not affected."};var Zo={netInfo:{supported:false,reason:"Load the NetInfo hook before app code."},expoNetwork:{supported:false,reason:"Load the Expo Network hook before app code."}},Kt="auto",Qo=0,vd=()=>Kt,Lt=()=>Qo;var en=()=>Qe!=="normal"||!["auto","real"].includes(Kt);function Bt(){let e=mt[Qe];return{version:2,runtimeId:Sd,revision:Qo,profile:Qe,connection:Kt,available:qt(),active:en(),delayMs:e.delayMs,downloadBytesPerSecond:e.downloadBytesPerSecond??null,uploadBytesPerSecond:e.uploadBytesPerSecond??null,capabilities:{...Zo,fetch:"JS body delivery",xhr:"RN progress and body delivery",upload:"time-simulated",webSocket:false,nativeImages:false,nativeModules:false},scope:bd}}function Nr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Choose a speed or link state.");let t=e;if(Object.keys(t).some(i=>i!=="profile"&&i!=="connection")||!("profile"in t)&&!("connection"in t))throw new Error("Choose a speed or link state.");let r="profile"in t?t.profile:Qe,o="connection"in t?t.connection:r==="normal"&&"profile"in t?"auto":Kt;if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(mt,r))throw new Error("Choose a valid speed profile.");if(!md.includes(o))throw new Error("Choose a valid link state.");if((r!=="normal"||!["auto","real"].includes(o))&&!qt())throw new Error("Use a signed-in account and a dev build.");if(!["auto","real"].includes(o)&&!Zo.netInfo.supported&&!Zo.expoNetwork.supported)throw new Error("Load a link hook before app code.");if(r===Qe&&o===Kt)return Bt();let n=r!=="normal";return n&&!$r&&(Oi(),$r=fr(()=>{})),n||($r?.(),$r=void 0,Pt()===0&&pr()),Qe=r,Kt=o,Qo++,Fr.forEach(i=>i()),Bt()}var Sd=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Qe="normal",$r,Fr=new Set,qt=()=>typeof me<"u"&&me&&di(),Ot=()=>Qe,et=e=>(Fr.add(e),()=>{Fr.delete(e)});function jr(e){return Nr({profile:e}).profile}function Di(e){if(Qe==="normal"||!qt()||!/^https?:\/\//i.test(e))return;let{label:t,...r}=mt[Qe];return Object.freeze({profile:Qe,...r})}xl(()=>{di()||jr("normal"),Fr.forEach(e=>e())});import{jsx as tn,jsxs as wd}from"react/jsx-runtime";function xd({size:e}){li(et,Lt,Lt);let t=en(),r=li(et,Ot,Ot);return wd(m,{accessibilityLabel:r==="normal"?"Network":`Network: ${mt[r].label}`,children:[tn(wl,{size:e}),t&&tn(m,{pointerEvents:"none",style:{position:"absolute",top:-6,right:-8,width:48,alignItems:"flex-end"},children:tn(b,{testID:"buoy-network-condition-indicator",numberOfLines:1,style:{color:"#FFCC66",fontSize:10,fontWeight:"700"},children:r==="normal"?"LINK":r==="offline"?"OFF":`+${mt[r].delayMs}`})})]})}import{createToolFactory as Cd,defineToolPreset as kd}from"@buoy-gg/shared-ui/web";O();O();Se();import{useEffect as rn,useRef as on,useState as nn,useSyncExternalStore as Wr}from"react";import{FloatingTool as Td,night as ze,openFloatingTool as Rd,persistentStorage as Ed,registerPersistentFloatingTool as Id}from"@buoy-gg/shared-ui/web";O();Se();import{useEffect as Ai,useRef as sn,useState as Vr,useSyncExternalStore as an}from"react";import{ChevronDown as Pd,Check as Ld,night as de}from"@buoy-gg/shared-ui/web";import{jsx as we,jsxs as zt}from"react/jsx-runtime";var Hi=[{profile:"normal",label:"No throttling"},{profile:"slow",label:"Slow"},{profile:"verySlow",label:"Very slow"},{profile:"offline",label:"Offline"},{profile:"slow3g",label:"Slow 3G"},{profile:"slow4g",label:"Slow 4G"},{profile:"fast4g",label:"Fast 4G"}],Mi={normal:"No added delay",slow:"+500 ms before each new request",verySlow:"+2 seconds before each new request",offline:"New requests fail before sending",slow3g:"50 KB/s down, 50 KB/s up; +2000 ms",slow4g:"180 KB/s down, 84.375 KB/s up; +562.5 ms",fast4g:"1012.5 KB/s down, 168.75 KB/s up; +165 ms"};function Bd({remote:e,compact:t=false}){an(et,Lt,Lt);let r=e?e.state:Bt(),[o,n]=Vr(false),i=an(et,Ot,Ot),s=an(et,qt,qt),[l,a]=Vr(false),[u,d]=Vr(),[g,x]=Vr(false),y=sn(false),R=sn(true),h=sn(0);Ai(()=>{h.current++,y.current=false,x(false),d(void 0)},[e?.targetId]),Ai(()=>(R.current=true,()=>{R.current=false}),[]);let C=e?e.profile:i,k=e?e.available:s,w=r?.active??(C!==null&&C!=="normal"),I=C==="offline"?de.color.danger:w?de.color.warning:de.color.accent;async function z(v){if(!k||y.current)return;if(v===C&&(v!=="normal"||!r?.active)){a(false);return}let c=++h.current;y.current=true,x(true),d(void 0);try{e?await e.onChange(v):jr(v),R.current&&h.current===c&&a(false)}catch(p){R.current&&h.current===c&&d(p instanceof Error?p.message:String(p))}finally{h.current===c&&(y.current=false,R.current&&x(false))}}let $=[["auto","Follow speed"],["real","Real link"],["offline","Offline"],["wifi","Wi-Fi"],["cellular","Cellular"],["noInternet","No internet"]],P=(!e||!!e.onConnectionChange)&&(r?.capabilities.netInfo.supported||r?.capabilities.expoNetwork.supported),A=Hi.find(v=>v.profile===C)?.label??"Unavailable";return zt(m,{style:se.container,testID:"buoy-network-throttling-screen",children:[we(b,{style:se.heading,children:"Connection profile"}),zt(F,{testID:"buoy-network-conditions",accessibilityRole:"button",accessibilityLabel:`Network throttling: ${A}`,accessibilityState:{expanded:l,disabled:!k||g},disabled:!k||g,onPress:()=>a(v=>!v),style:[se.dropdown,l&&se.dropdownOpen,!k&&se.disabled],children:[we(b,{style:[se.value,w&&{color:I}],children:A}),g?we(Lr,{size:"small",color:de.color.textSecondary}):we(Pd,{size:16,color:de.color.textSecondary})]}),l&&we(m,{accessibilityRole:"radiogroup",accessibilityLabel:"Connection profile",style:se.options,children:Hi.map(v=>{let c=C===v.profile;return zt(F,{testID:`buoy-network-condition-${v.profile}`,accessibilityRole:"radio",accessibilityLabel:v.label,accessibilityState:{checked:c,disabled:!k||g},disabled:!k||g,onPress:()=>void z(v.profile),style:[se.option,c&&se.selected],children:[zt(m,{style:se.optionBody,children:[we(b,{style:[se.optionTitle,c&&{color:I}],children:v.label}),we(b,{style:se.caption,children:Mi[v.profile]})]}),c&&we(Ld,{size:16,color:I})]},v.profile)})}),we(b,{style:se.caption,accessibilityLiveRegion:"polite",children:g?"Applying to device\u2026":k?C?Mi[C]:"Waiting for device status":e?"Conditions unavailable on this device":"Requires a signed-in account and a development build"}),!!u&&we(b,{accessibilityRole:"alert",style:se.error,children:u}),we(F,{testID:"buoy-network-link-state",accessibilityRole:"button",accessibilityLabel:"App link state",disabled:!k||g||!P,onPress:()=>n(v=>!v),style:se.dropdown,children:zt(b,{style:se.value,children:["App link: ",$.find(([v])=>v===r?.connection)?.[1]??"Unavailable"]})}),o&&$.map(([v,c])=>we(F,{testID:`buoy-network-link-${v}`,accessibilityRole:"radio",accessibilityState:{checked:r?.connection===v,disabled:g||!k},disabled:g||!k,style:se.option,onPress:async()=>{if(y.current)return;let p=++h.current;y.current=true,x(true),d(void 0);try{e?await e.onConnectionChange?.(v):Nr({connection:v}),R.current&&h.current===p&&n(false)}catch(f){R.current&&h.current===p&&d(f instanceof Error?f.message:String(f))}finally{h.current===p&&(y.current=false,R.current&&x(false))}},children:we(b,{style:se.optionTitle,children:c})},v)),!P&&we(b,{style:se.caption,children:r?.capabilities.netInfo.reason??"This device has no link hook."}),!t&&zt(m,{style:se.help,children:[we(b,{style:se.heading,children:"How it works"}),r&&zt(b,{style:se.caption,children:["NetInfo: ",r.capabilities.netInfo.supported?"Hook on":r.capabilities.netInfo.reason??"No hook",". Expo Network: ",r.capabilities.expoNetwork.supported?"Hook on":r.capabilities.expoNetwork.reason??"No hook","."]}),we(b,{style:se.caption,children:"Down caps pace bytes to the app in JS. The socket stays at its real speed."}),we(b,{style:se.caption,children:"Up caps wait before send for known bytes. Upload time is simulated. The socket is not paced. Unknown sizes pass through with latency only. Each call shows any cap gap."}),we(b,{style:se.caption,children:"Caps apply per call through global fetch and RN XHR. WebSocket, native images, native SDKs and file transfers are not affected."}),we(b,{style:se.caption,children:"Link state changes what NetInfo and Expo Network report. It does not change the radio or web calls."}),we(b,{style:se.caption,children:"Stays on when this tool closes or capture pauses. No throttling clears both controls. App reload clears them too."})]})]})}var se=ve.create({container:{padding:de.gutter,gap:10},heading:{fontSize:de.font.caption,fontWeight:"600",color:de.color.textSecondary},dropdown:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingHorizontal:12,paddingVertical:10,borderRadius:de.radius.segment,borderWidth:1,borderColor:de.color.separator,backgroundColor:de.color.surfaceElevated},dropdownOpen:{borderColor:de.color.accentBorderStrong},value:{flex:1,fontSize:de.font.body,color:de.color.text},options:{padding:4,borderRadius:de.radius.row,borderWidth:1,borderColor:de.color.border,backgroundColor:de.color.surface},option:{flexDirection:"row",alignItems:"center",gap:12,minHeight:54,padding:10,borderRadius:de.radius.segment},optionBody:{flex:1,gap:4},optionTitle:{fontSize:de.font.caption,fontWeight:"600",color:de.color.text},selected:{backgroundColor:de.color.surfaceElevated},disabled:{opacity:.45},caption:{fontSize:de.font.caption,lineHeight:19,color:de.color.textSecondary},help:{marginTop:14,paddingTop:16,gap:10,borderTopWidth:1,borderTopColor:de.color.separator},error:{fontSize:de.font.caption,lineHeight:18,color:de.color.danger}});import{jsx as Ce,jsxs as Ur}from"react/jsx-runtime";function qd(){let e,t=new Set;return{getSnapshot:()=>e,subscribe:r=>(t.add(r),()=>{t.delete(r)}),update(r){e=r,t.forEach(o=>o())}}}var Od=()=>()=>{},Ni=()=>{},_r=[{id:"normal",label:"No throttling",detail:"No added delay"},{id:"slow",label:"Slow",detail:"+500 ms before sending"},{id:"verySlow",label:"Very slow",detail:"+2 seconds before sending"},{id:"offline",label:"Offline",detail:"New requests fail"}],zd={id:"network-throttling",render:e=>Ce(ji,{...e})};function $i(){return typeof me>"u"||!me?()=>{}:Id(zd,Ed)}typeof me<"u"&&me&&typeof navigator<"u"&&navigator.product==="ReactNative"&&$i();function Fi(e,t=false){Rd({id:"network-throttling",render:r=>Ce(ji,{...r,source:e,showControls:t})})}function ji({id:e,revealToken:t,dismiss:r,source:o,showControls:n=false}){Wr(et,Lt,Lt);let i=Bt(),s=Wr(et,Ot,Ot),l=Wr(et,qt,qt),a=Wr(o?.subscribe??Od,o?.getSnapshot??Ni,Ni),u=o?a?.profile??null:s,d=o?a?.available===true:l,[g,x]=nn(n);rn(()=>{x(n)},[n,t]);let[y,R]=nn(false),[h,C]=nn(),k=on(false),w=on(0),I=on(true),{width:z,height:$}=Jn();rn(()=>(I.current=true,()=>{I.current=false}),[]),rn(()=>{w.current+=1,k.current=false,R(false),C(void 0)},[o,a?.targetId]);let P=o?a?.state?.active??(u!==null&&u!=="normal"):i.active,A=u??"normal",v=_r.find(H=>H.id===A)??{label:mt[A].label},c=_r[(_r.findIndex(H=>H.id===A)+1)%_r.length],p=!d||A==="offline"?0:A==="verySlow"?1:A==="slow"?2:4,f=y?"Applying\u2026":d?A==="normal"?P?"Link set":"0 ms":A==="slow"?"+500 ms":A==="verySlow"?"+2000 ms":A==="offline"?"Blocked":`${Math.round((mt[A].downloadBytesPerSecond??0)/1e3)} kB/s`:"Unavailable";async function S(H,V=false){if(k.current)return;let Z=++w.current;k.current=true,R(true),C(void 0);let Y=o?.getSnapshot();try{if(o){if(!Y?.available)throw new Error("Device unavailable. Open Network again to reconnect these controls.");await Y.onChange(H)}else jr(H);I.current&&w.current===Z&&V&&r()}catch(L){I.current&&w.current===Z&&C(L instanceof Error?L.message:String(L))}finally{w.current===Z&&(k.current=false,I.current&&R(false))}}let D=h||g?Ur(m,{style:De.menu,children:[!!h&&Ce(b,{accessibilityRole:"alert",style:De.error,children:h}),g&&Ce(yt,{testID:"throttling-controls-scroll",style:{maxHeight:Math.min(420,$-180)},children:Ce(Bd,{remote:o?a??{profile:null,available:false,onChange:async()=>{throw new Error("Device unavailable.")}}:void 0})})]}):void 0;return Ce(Td,{id:e,revealToken:t,variant:"strip",dragFromSurface:Pr.OS!=="android"||!g,accessibilityLabel:`Move or hide network throttling. ${P?"Active":"Off"}`,accessory:Pr.OS==="android"?void 0:D,children:Ur(m,{style:{width:Math.max(220,Math.min(336,z-64))},children:[Ur(m,{style:[De.row,{width:Math.max(220,Math.min(336,z-64))}],children:[Ce(F,{testID:"throttling-cycle",accessibilityRole:"button",accessibilityLabel:`Network: ${v.label}. Switch to ${c.label}`,accessibilityState:{disabled:y||!d},disabled:y||!d,onPress:()=>void S(c.id),style:De.signalButton,children:y?Ce(Lr,{size:"small",color:ze.color.accent}):Ur(m,{testID:`throttling-signal-${A}`,style:De.signal,children:[[7,12,18,24].map((H,V)=>Ce(m,{style:{width:4,height:H,borderRadius:2,backgroundColor:V<p?A==="offline"?ze.color.danger:ze.color.accent:ze.color.fillTertiary}},H)),A==="offline"&&Ce(m,{style:De.slash})]})}),Ce(m,{style:De.profile,children:Ce(b,{testID:"throttling-profile",accessibilityLabel:`Connection profile: ${v.label}`,accessibilityLiveRegion:"polite",numberOfLines:1,style:De.profileLabel,children:v.label})}),Ce(b,{testID:"throttling-status",numberOfLines:1,accessibilityLiveRegion:"polite",style:De.status,children:f}),Ce(F,{testID:"throttling-edit",accessibilityRole:"button",accessibilityLabel:g?"Hide speed and link controls":"Edit speed and link state",onPress:()=>x(H=>!H),style:De.action,children:Ce(b,{style:De.actionText,children:g?"Done":"Edit"})}),Ce(m,{style:De.separator}),Ce(F,{testID:"throttling-close",accessibilityRole:"button",accessibilityLabel:"Close and turn off throttling",disabled:y,accessibilityState:{disabled:y},onPress:()=>{P?S("normal",true):r()},style:[De.action,y&&De.disabled],children:Ce(b,{style:De.actionText,children:"Close"})})]}),Pr.OS==="android"&&D]})})}var De=ve.create({row:{flexDirection:"row",alignItems:"center",gap:6,paddingVertical:4,minHeight:48},signalButton:{width:36,minHeight:44,alignItems:"center",justifyContent:"center"},signal:{flexDirection:"row",alignItems:"flex-end",gap:3,height:24},slash:{position:"absolute",width:30,height:2,backgroundColor:ze.color.danger,top:11,left:-2,transform:[{rotate:"-45deg"}]},separator:{height:20,width:1,backgroundColor:ze.color.separator,marginHorizontal:2},status:{color:ze.color.textSecondary,fontSize:10,lineHeight:15,flexShrink:1},profile:{flex:1,flexDirection:"row",alignItems:"center",gap:6,minHeight:44},profileLabel:{color:ze.color.text,fontSize:13,fontWeight:"500",flexShrink:1},action:{minHeight:36,minWidth:52,borderRadius:ze.radius.input,borderWidth:1,borderColor:ze.color.accentBorderStrong,alignItems:"center",justifyContent:"center",paddingHorizontal:10},actionText:{color:ze.color.accent,fontSize:12,fontWeight:"600"},disabled:{opacity:.4},menu:{marginVertical:8,padding:6,borderRadius:ze.radius.card,borderWidth:1,borderColor:ze.color.separator,backgroundColor:ze.color.surface,shadowColor:"#000",shadowOffset:{width:0,height:6},shadowOpacity:.25,shadowRadius:16,elevation:8},error:{color:ze.color.danger,fontSize:12,lineHeight:18,padding:10}});Se();import{useState as Te,useRef as Xr,useEffect as Dt,useCallback as ln}from"react";import{Search as Dd,Wifi as Wi,Filter as Ad,Bookmark as Hd,JsModal as Md,ModalHeader as ke,devToolsStorageKeys as Jr,macOSColors as Nd,night as tt,persistentStorage as Vi,NightSegmented as $d,useFeatureGate as Fd,UpgradeModal as jd,PowerToggleButton as Wd,useIgnoredPatterns as Vd,windowDragProps as Ud}from"@buoy-gg/shared-ui/web";O();Se();import{CheckCircle as _d,Clock as Xd,DynamicFilterView as Jd,Film as Gd,FileJson as Kd,FileText as Yd,Filter as Ui,Globe as _i,Image as Zd,macOSColors as Re,night as Me,Music as Qd,XCircle as eu,monoFont as dn}from"@buoy-gg/shared-ui/web";import{useCallback as Gr,useMemo as rt,useState as tu}from"react";import{jsx as ut,jsxs as Xi}from"react/jsx-runtime";var ru=()=>false;function un(e){let t=e.responseHeaders||e.requestHeaders,r=t?.["content-type"]||t?.["Content-Type"]||"";return r.includes("json")?{type:"JSON",color:Re.semantic.info}:r.includes("xml")?{type:"XML",color:Re.semantic.success}:r.includes("html")?{type:"HTML",color:Re.semantic.warning}:r.includes("text")?{type:"TEXT",color:Re.semantic.success}:r.includes("image")?{type:"IMAGE",color:Re.semantic.error}:r.includes("video")?{type:"VIDEO",color:Re.semantic.error}:r.includes("audio")?{type:"AUDIO",color:Re.semantic.debug}:r.includes("form")?{type:"FORM",color:Re.semantic.info}:{type:"OTHER",color:Me.color.textTertiary}}function ou(e){switch(e){case"JSON":return Kd;case"HTML":case"XML":case"TEXT":return Yd;case"IMAGE":return Zd;case"VIDEO":return Gd;case"AUDIO":return Qd;default:return _i}}function nu(e){switch(e){case"GET":return Re.semantic.success;case"POST":return Re.semantic.info;case"PUT":return Re.semantic.warning;case"DELETE":return Re.semantic.error;case"PATCH":return Re.semantic.success;default:return Me.color.textTertiary}}function iu({events:e,filter:t,onFilterChange:r,ignoredPatterns:o=[],onRemovePattern:n=()=>{},isTeamPattern:i=ru,onAddPattern:s=()=>{},onTogglePatternMode:l=()=>{}}){let[a,u]=tu("contains"),d=rt(()=>{let v=new Map;for(let c of o)v.set(c.value,c.mode);return v},[o]),g=rt(()=>new Set(o.map(v=>v.value)),[o]),x=Gr(v=>{s({value:v,mode:a})},[s,a]),y=Gr(v=>{if(i(v)){let S=Me.color.accent;return ut(m,{accessibilityLabel:"Set by your team on buoy.gg",style:[Ue.modeBadge,{borderColor:`${S}60`,backgroundColor:`${S}15`}],children:ut(b,{style:[Ue.modeBadgeText,{color:S}],children:"TEAM"})})}let c=d.get(v)??"contains",p=c==="exact",f=p?Me.color.warning:Me.color.info;return ut(F,{accessibilityRole:"button",accessibilityLabel:`Match mode: ${c}. Tap to toggle.`,onPress:()=>l(v),style:[Ue.modeBadge,{borderColor:`${f}60`,backgroundColor:`${f}15`}],hitSlop:{top:6,bottom:6,left:6,right:6},children:ut(b,{style:[Ue.modeBadgeText,{color:f}],children:p?"EXACT":"CONTAINS"})})},[d,l,i]),R=Gr(()=>{let v=[{label:"Contains",value:"contains",hint:"substring"},{label:"Exact",value:"exact",hint:"whole path/host/url"}];return Xi(m,{style:Ue.modeToggleRow,children:[ut(b,{style:Ue.modeToggleLabel,children:"Match:"}),ut(m,{style:Ue.modeToggleGroup,children:v.map(c=>{let p=a===c.value;return Xi(F,{onPress:()=>u(c.value),style:[Ue.modeToggleButton,p&&Ue.modeToggleButtonActive],accessibilityRole:"button",accessibilityState:{selected:p},children:[ut(b,{style:[Ue.modeToggleButtonText,p&&Ue.modeToggleButtonTextActive],children:c.label}),ut(b,{style:Ue.modeToggleButtonHint,children:c.hint})]},c.value)})})]})},[a]),h=rt(()=>{let v={all:e.length,success:0,error:0,pending:0};return e.forEach(c=>{if(c.error||c.status&&c.status>=400){v.error+=1;return}if(c.status&&c.status>=200&&c.status<300){v.success+=1;return}!c.status&&!c.error&&(v.pending+=1)}),v},[e]),C=rt(()=>e.reduce((v,c)=>(c.method&&(v[c.method]=(v[c.method]||0)+1),v),{}),[e]),k=rt(()=>e.reduce((v,c)=>{let{type:p}=un(c);return v[p]=(v[p]||0)+1,v},{}),[e]),w=rt(()=>{let v=new Set;return e.forEach(c=>{if(c.host){v.add(c.host);return}try{if(c.url){let p=new URL(c.url),f=String(p.host||"");f&&v.add(f)}}catch{}}),Array.from(v).filter(c=>c&&c!=="").sort((c,p)=>c.localeCompare(p))},[e]),I=rt(()=>{let v=new Set;return e.forEach(c=>{if(c.url)try{let p=new URL(c.url),f=String(p.origin||""),S=String(p.pathname||""),D=`${f}${S}`;v.add(D)}catch{v.add(c.url)}}),Array.from(v).filter(c=>c&&c!=="").sort((c,p)=>c.localeCompare(p))},[e]),z=rt(()=>{let v=w.slice(0,30),c=I.slice(0,30);return[...v,...c]},[w,I]),$=Gr((v,c)=>{let[p]=v.split("::");if(p==="status"){r({...t,status:c==="all"?void 0:c});return}if(p==="method"){let f=String(c),S=t.method||[],D=S.includes(f)?S.filter(H=>H!==f):[f];r({...t,method:D.length>0?D:void 0});return}if(p==="contentType"){let f=String(c),S=t.contentType||[],D=S.includes(f)?S.filter(H=>H!==f):[f];r({...t,contentType:D.length>0?D:void 0})}},[t,r]),P=rt(()=>{let v=[];v.push({id:"status",title:"Status",type:"status",data:["all","success","error","pending"].map(f=>({id:`status::${f}`,label:f.charAt(0).toUpperCase()+f.slice(1),count:h[f],icon:f==="success"?_d:f==="error"?eu:f==="pending"?Xd:_i,color:f==="success"?Re.semantic.success:f==="error"?Re.semantic.error:f==="pending"?Re.semantic.warning:Re.semantic.info,isActive:t.status===f||!t.status&&f==="all",value:f}))});let c=Object.entries(C);c.length>0&&v.push({id:"method",title:"Method",type:"method",data:c.map(([f,S])=>({id:`method::${f}`,label:f,count:S,color:nu(f),isActive:t.method?.includes(f)??false,value:f}))});let p=Object.entries(k);return p.length>0&&v.push({id:"contentType",title:"Content Type",type:"contentType",data:p.map(([f,S])=>{let D=e.find(V=>un(V).type===f),{color:H}=D?un(D):{color:Me.color.textTertiary};return{id:`contentType::${f}`,label:f,count:S,icon:ou(f),color:H,isActive:t.contentType?.includes(f)??false,value:f}})}),v},[k,e,t.contentType,t.method,t.status,C,h]),A=rt(()=>({sections:P,addFilterSection:{enabled:true,placeholder:"Enter domain or URL pattern...",title:"ACTIVE FILTERS",icon:Ui,renderExtra:R},availableItemsSection:{enabled:true,title:"AVAILABLE DOMAINS & URLS",emptyMessage:"No network events captured yet. Domains and URLs will appear here.",items:z},howItWorksSection:{enabled:true,title:"HOW NETWORK FILTERS WORK",description:"Patterns hide matching requests from the network event list. Each pattern has a match mode you can toggle on its badge: CONTAINS hides any URL containing the text; EXACT hides only an exact path/host/url match.",examples:["\u2022 example.com (CONTAINS) \u2192 any request whose URL contains example.com","\u2022 example.com (EXACT) \u2192 only requests served by that exact host","\u2022 /v1 (CONTAINS) \u2192 any URL containing /v1 (e.g. /v1, /v1/users)","\u2022 /v1 (EXACT) \u2192 only requests whose pathname is exactly /v1"],icon:Ui},onFilterChange:$,onPatternAdd:x,onPatternToggle:n,activePatterns:g,renderPatternMeta:y}),[g,P,$,x,n,R,y,z]);return ut(Jd,{...A})}var Ue=ve.create({modeBadge:{paddingHorizontal:8,paddingVertical:3,borderRadius:6,borderWidth:1},modeBadgeText:{fontSize:9,fontFamily:dn,fontWeight:"700",letterSpacing:.5},modeToggleRow:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:8},modeToggleLabel:{fontSize:11,fontWeight:"600",color:Me.color.textSecondary,fontFamily:dn,letterSpacing:.3},modeToggleGroup:{flexDirection:"row",gap:6,flex:1},modeToggleButton:{flex:1,paddingVertical:6,paddingHorizontal:10,borderRadius:8,borderWidth:1,borderColor:Me.color.border,backgroundColor:Me.color.buttonSurface,alignItems:"center"},modeToggleButtonActive:{borderColor:Me.color.accentBorderStrong,backgroundColor:Me.color.accentSoft},modeToggleButtonText:{fontSize:11,fontWeight:"700",color:Me.color.textSecondary,fontFamily:dn,letterSpacing:.3},modeToggleButtonTextActive:{color:Me.color.accent},modeToggleButtonHint:{fontSize:9,color:Me.color.textTertiary,marginTop:1}});O();import{TickProvider as cn}from"@buoy-gg/shared-ui/web";import{useTick as su}from"@buoy-gg/shared-ui/web";function hn(){return su()??Date.now()}O();Se();import{useState as yr,useEffect as Ji,useMemo as au,memo as lu}from"react";import{Clock as pn,Upload as Gi,Download as Ki,AlertCircle as du,ChevronDown as Yi,ChevronUp as Zi,Lock as uu,Unlock as cu,FileJson as Kr,Filter as hu,Globe as pu,Link as fu,Copy as Qi,FlaskConical as yu,InlineCopyButton as es,macOSColors as Yr,night as q,useFeatureGate as gu,UpgradeModal as mu,monoFont as Yt}from"@buoy-gg/shared-ui/web";O();import{formatBytes as ct,formatDuration as Zr,formatHttpStatus as ts,getMethodColor as ty}from"@buoy-gg/shared-ui/web";import{formatRelativeTime as bu}from"@buoy-gg/shared-ui/web";import{DataViewer as gr}from"@buoy-gg/shared-ui/web/dataViewer";O();function fn(e,t=30){if(e==null)return null;if(typeof e=="boolean"||typeof e=="number")return String(e);if(typeof e=="string")return e.length>t?e.substring(0,t-1)+"\u2026":e;if(Array.isArray(e))return e.length===0?null:e.length===1?fn(e[0],t):`${e.length} items`;if(typeof e=="object"){let r=Object.entries(e);if(r.length===0)return null;for(let[o,n]of r){let i=fn(n,t);if(i)return i}return null}return null}function vu(e,t=3){if(!e||typeof e!="object")return null;let r=[];for(let[o,n]of Object.entries(e)){let i=fn(n);if(i&&r.push(i),r.length>=t)break}return r.length>0?r:null}function rs(e,t){let r=vu(t);return!r||r.length===0?e:[e,...r].join(" \u203A ")}function os(e,t){if(!e||typeof e!="object")return false;for(let r of Object.values(e))if(yn(r,t))return true;return false}function yn(e,t){return typeof e=="string"?e.toLowerCase().includes(t):typeof e=="number"||typeof e=="boolean"?String(e).includes(t):Array.isArray(e)?e.some(r=>yn(r,t)):typeof e=="object"&&e!==null?Object.values(e).some(r=>yn(r,t)):false}O();import{createContext as Su,useContext as wu}from"react";import{jsx as xu}from"react/jsx-runtime";var ns=Su(null);function Cu({resolver:e,children:t}){return xu(ns.Provider,{value:e,children:t})}function ku(){return wu(ns)}import{Fragment as gn,jsx as T,jsxs as Q}from"react/jsx-runtime";var Qr=q.color.accent,Tu=new Set,Ru=()=>{},Eu=({timings:e,total:t})=>{let r=Math.max(1,t),o=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:e.ttfb,color:Yr.semantic.warning},{label:"Content download",hint:void 0,value:e.download,color:Yr.semantic.success}];return T(m,{style:E.phaseList,children:o.map(n=>Q(m,{style:E.phaseRow,children:[Q(m,{style:E.phaseLabelGroup,children:[T(b,{style:E.phaseLabel,children:n.label}),n.hint?T(b,{style:E.phaseHint,children:n.hint}):null]}),T(m,{style:E.phaseTrack,children:T(m,{style:[E.phaseBar,{backgroundColor:n.color,width:`${Math.min(100,Math.max(1,n.value/r*100))}%`}]})}),T(b,{style:E.phaseValue,children:Zr(n.value)})]},n.label))})},is=()=>T(m,{style:E.bodyDeferred}),At=({title:e,icon:t,children:r,defaultOpen:o=false,count:n})=>{let[i,s]=yr(o);return Q(m,{style:E.collapsibleSection,children:[Q(F,{style:E.collapsibleHeader,onPress:()=>s(!i),testID:`buoy-network-section-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,children:[Q(m,{style:E.collapsibleTitle,children:[t,T(b,{style:E.collapsibleTitleText,children:e}),n!==void 0?T(b,{style:E.collapsibleCount,children:n}):null]}),i?T(Zi,{size:16,color:q.color.textSecondary}):T(Yi,{size:16,color:q.color.textSecondary})]}),i?T(m,{style:E.collapsibleContent,children:r}):null]})},Iu=({url:e,requestData:t,operationName:r,graphqlVariables:o,requestClient:n,isPro:i=false,onUpgradePress:s})=>{let l=g=>{try{let x=new URL(g),y=String(x.protocol||""),R=String(x.host||""),h=y==="https:",C=String(x.pathname||"");if(n==="graphql"&&r){let I=rs(r,o);C=`${C} (${I})`}else r&&(C=`${C} (${r})`);let k={},w=x.searchParams;return w&&typeof w.forEach=="function"&&w.forEach((I,z)=>{k[z]=I}),{protocol:y.replace(":",""),host:R,pathname:C,params:Object.keys(k).length>0?k:null,isSecure:h}}catch{return{protocol:"",host:e,pathname:"",params:null,isSecure:false}}},a=au(()=>l(e),[e,n,r,o]),[u,d]=yr(false);return Q(m,{style:E.urlBreakdown,children:[Q(m,{style:E.urlRow,children:[a.isSecure?T(uu,{size:12,color:Yr.semantic.success}):T(cu,{size:12,color:Yr.semantic.warning}),T(b,{style:E.urlDomain,children:a.host}),Q(b,{style:E.urlProtocol,children:["(",a.protocol.toUpperCase(),")"]}),i?T(es,{value:e,buttonStyle:E.copyButton}):T(F,{style:E.copyButton,onPress:s,activeOpacity:.7,children:T(Qi,{size:14,color:q.color.textSecondary})})]}),T(m,{style:E.urlPathRow,children:Q(b,{style:E.urlPath,numberOfLines:2,children:[a.pathname,a.params?Q(b,{style:E.urlQueryString,children:["?",new URLSearchParams(a.params).toString()]}):null]})}),a.params?Q(m,{style:E.queryParamsCollapsible,children:[Q(F,{style:E.queryParamsToggle,onPress:()=>d(!u),activeOpacity:.7,children:[T(b,{style:E.queryParamsToggleText,children:"Query Parameters"}),T(b,{style:E.collapsibleCount,children:Object.keys(a.params).length}),u?T(Zi,{size:14,color:q.color.textSecondary}):T(Yi,{size:14,color:q.color.textSecondary})]}),u?T(gr,{title:"",data:a.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})},ss=lu(function({event:e,ignoredPatterns:t=Tu,onTogglePattern:r=Ru,showBodies:o=true}){let n=e.status?ts(e.status):null,i=!e.status&&!e.error,{isPro:s}=gu(),[l,a]=yr(false);Ji(()=>{l&&s&&a(false)},[l,s]);let u=ku(),d=e.requestData===void 0&&(e.requestBodyOmitted===true||(e.requestSize??0)>0),g=e.responseData===void 0&&(e.responseBodyOmitted===true||(e.responseSize??0)>0),x=e.headersOmitted===true,[y,R]=yr(null),[h,C]=yr(false);Ji(()=>{if(R(null),!u||!d&&!g&&!x){C(false);return}let P=false;return C(true),u(e.id).then(A=>{P||R(A)}).catch(()=>{}).finally(()=>{P||C(false)}),()=>{P=true}},[e.id,u,d,g,x]);let k=e.requestData??y?.requestData??void 0,w=e.responseData??y?.responseData??void 0,I=(x?y?.requestHeaders:void 0)??e.requestHeaders,z=(x?y?.responseHeaders:void 0)??e.responseHeaders,$=()=>{let P={method:e.method,url:e.url,status:e.status,statusText:e.statusText,timestamp:new Date(e.timestamp).toISOString(),duration:e.duration?`${e.duration}ms`:"N/A",requestHeaders:I,requestData:k,responseHeaders:z,responseData:w,requestSize:e.requestSize?ct(e.requestSize):"N/A",responseSize:e.responseSize?ct(e.responseSize):"N/A",error:e.error,client:e.requestClient};return`# Network Request Details
8
+ ... [truncated, ${this.formatBytes(s)} omitted]`,size:n,truncated:true,json:false}}try{return{body:JSON.parse(o),size:n,truncated:false,json:true}}catch{return{body:o,size:n,truncated:false,json:false}}}catch{return{body:"~~~ unable to read body ~~~",json:false,unread:true,size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";let t=1024,r=["B","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,o)*100)/100} ${r[o]}`}handleXHRResponse(e,t,r,o,n,i,s,d,a=false,l="xhr",c,y){let w=d?fe()-d:0,p=e._buoyTtfb,C=p===void 0?void 0:{ttfb:p,download:Math.max(0,w-p)};if(a||e.status===0){this.emit({type:"error",timestamp:new Date,duration:w,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:l},error:{message:a?"Request failed":"Network error or request aborted"},override:c,condition:y});return}let u,R=false,h=false,m=0;try{let I=e.response;if(e.responseType==="json"){let B=e.status===204||e.status===205||e.status===304||o.toUpperCase()==="HEAD"||e.getResponseHeader?.("content-length")==="0";I===null?(u=void 0,h=!B,m=0):(u=I,R=true,m=JSON.stringify(I).length)}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){m=e.responseText.length;try{u=JSON.parse(e.responseText),R=true}catch{u=e.responseText}}}else if(e.responseType==="arraybuffer")if(I)try{let B=new TextDecoder("utf-8").decode(I);m=B.length;try{u=JSON.parse(B),R=true}catch{u=B}}catch{u=`[arraybuffer response - ${I.byteLength||0} bytes]`,h=true,m=I.byteLength||0}else u="[arraybuffer response - no data]",h=true,m=0;else if(e.responseType==="blob")if(I instanceof Blob)u=`[blob response - ${I.size} bytes, type: ${I.type||"unknown"}]`,h=true,m=I.size;else if(I)try{u=typeof I=="string"?JSON.parse(I):I,m=JSON.stringify(u).length}catch{u="[blob response - unable to parse]",h=true,m=0}else u="[blob response - no data]",h=true,m=0;else if(I)if(typeof I=="string"){u=I,m=I.length;try{u=JSON.parse(I),R=true}catch{}}else typeof I=="object"?(u=I,m=JSON.stringify(I).length):(u=String(I),m=String(I).length)}catch{u="~~~ unable to read body ~~~",h=true}if(y?.downloadBytesPerSecond&&(!e.responseType||e.responseType==="text"||e.responseType==="json")){let I=e._response;typeof I=="string"&&(m=En(I))}let x={};try{let I=e.getAllResponseHeaders();I&&I.split(`\r
9
+ `).forEach(B=>{if(B){let E=B.indexOf(": ");if(E>0){let D=B.substring(0,E).toLowerCase(),k=B.substring(E+2);x[D]=k}}})}catch{}Bc(e.status)==="response"?this.emit({type:"response",timestamp:new Date,duration:w,timings:C,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:l},response:{status:e.status,statusText:Lc(e.status,e.statusText),headers:x,body:u,size:m,json:R,unread:h||void 0},override:c,condition:y}):this.emit({type:"error",timestamp:new Date,duration:w,request:{id:t||"unknown",url:r,method:o,headers:n,data:i,params:s||void 0,client:l},response:{status:e.status,statusText:e.statusText,headers:x,body:u,size:m},error:{message:"Network Error"},override:c,condition:y})}isFetchInterceptionLive(){return globalThis.fetch[zs]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[Os]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){let e=this.isListening&&this.isFetchInterceptionLive(),t=this.isListening&&this.isXhrInterceptionLive();e&&t||(e||this.installFetchInterceptor(),t||this.installXhrInterceptor(),this.isListening=true)}installFetchInterceptor(){let e=this,t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let r=++this.fetchGeneration,o=async(n,i)=>{let s=wo(typeof n=="string"?n:n instanceof URL?n.href:n.url);if(r!==e.fetchGeneration)return t(n,i);if(i?.__buoyInternal||e.shouldIgnoreUrl(s)){let g=Zt;Zt=true;try{return t(n,i)}finally{Zt=g}}let d=fe(),a=So("fetch"),l=typeof n=="object"&&"method"in n?n:void 0,c=i?.method??l?.method??"GET",y=i?.signal!==void 0?i.signal:l?.signal;Et(y);let w=Ns(s),p=w?.uploadBytesPerSecond?{...w,uploadCap:Gd(n,i)}:w,{url:C,params:u}=e.parseUrl(s),R={},h=i?.headers??l?.headers;h&&(h instanceof Headers?h.forEach((g,v)=>{R[v]=g}):Array.isArray(h)?h.forEach(([g,v])=>{R[g]=v}):R={...h}),Object.assign(R,Ls(s));let m;if(i?.body)if(typeof i.body=="string")try{m=JSON.parse(i.body)}catch{m=i.body}else m=i.body;let x=R["X-Request-Client"]||R["x-request-client"]||"fetch";p?.profile!=="offline"&&On()&&await Es();let I=typeof i?.body=="string"?i.body:void 0;if(I===void 0&&i?.body===void 0&&l&&!l.bodyUsed&&c!=="GET"&&c!=="HEAD"&&xc())try{I=(await e.readStreamedBody(l.clone())).body}catch{}let B=p?.profile!=="offline"&&On()?Pc(s,c,R,I):null;B&&await B;let E=p?.profile!=="offline"&&On()?Bs(s,c,R,I):null,D=E?Ps(E):void 0;e.emit({type:"request",timestamp:new Date,request:{id:a||"unknown",url:C,method:c,headers:R,data:m,params:u||void 0,client:x},override:D,condition:p});let k=g=>{try{m=JSON.parse(g)}catch{m=g}e.emit({type:"request-body",timestamp:new Date,request:{id:a||"unknown",url:C,method:c,data:m,client:x}})};if(i?.body===void 0&&l&&typeof I=="string")k(I);else if(!p?.uploadBytesPerSecond&&i?.body===void 0&&l&&!l.bodyUsed&&c!=="GET"&&c!=="HEAD")try{let g=l.clone();e.readStreamedBody(g).then(({body:v})=>{v&&k(v)}).catch(()=>{})}catch{}try{if((p||E)&&await Pn((p?.delayMs??0)+(E?.delayMs??0),y),Et(y),p?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(E?.kind==="fail")throw lc(E);p?.uploadBytesPerSecond&&(await vo(p.uploadCap?.knownBytes??0,p.uploadBytesPerSecond,y),Et(y));let g;if(E?.kind==="respond")g=ac(s,E);else{let ee=Zt;Zt=true;let Z;try{Z=t(n,i)}finally{Zt=ee}g=await Z}if(p?.downloadBytesPerSecond){let ee={};g.headers.forEach((De,Ce)=>{ee[Ce.toLowerCase()]=De});let Z=0,Y=0,Oe=[],Xe=(De,Ce)=>{let Ke=new Uint8Array(Y),ut=0;for(let ho of Oe)Ke.set(ho,ut),ut+=ho.byteLength;let Or=De?new TextDecoder().decode(Ke):Nn,co=false;if(De&&ee["content-type"]?.includes("json"))try{Or=JSON.parse(Or),co=true}catch{}let uo=Z>Y,qr=!De||Ce!==void 0;e.emit({type:Ce!==void 0?"error":"response",timestamp:new Date,duration:fe()-d,request:{id:a,url:C,method:c,headers:R,data:m,params:u||void 0,client:x},response:{status:g.status,statusText:g.statusText,headers:ee,body:Or,size:Z,json:co&&!uo&&!qr,truncated:uo&&!qr,...qr?{unread:true}:{}},...Ce!==void 0?{error:{message:Ce instanceof Error?Ce.message:String(Ce)}}:{},override:D,condition:p})};return Xe(false),fs(g,p.downloadBytesPerSecond,y,(De,Ce)=>{if(De){Z+=De.byteLength;let Ke=Math.min(De.byteLength,65536-Y);Ke>0&&(Oe.push(De.slice(0,Ke)),Y+=Ke)}else Xe(true,Ce)},c.toUpperCase()==="HEAD")}let v=fe()-d,f=typeof g.body?.getReader=="function"||qs(g.headers?.get?.("content-type")),T=g.clone(),{body:M,size:P,json:A,truncated:_,unread:F}=f?{body:Nn,size:0,json:false,truncated:false,unread:true}:await e.processResponseBody(T),L=fe()-d,H=Math.max(0,L-v),j=H>0?{ttfb:v,download:H}:void 0,J={};if(g.headers.forEach((ee,Z)=>{J[Z.toLowerCase()]=ee}),e.emit({type:"response",timestamp:new Date,duration:L,timings:j,request:{id:a||"unknown",url:C,method:c,headers:R,data:m,params:u||void 0,client:x},response:{status:g.status,statusText:g.statusText,headers:J,body:M,size:P,json:A,truncated:_||void 0,unread:F||void 0},override:D,condition:p}),f){let ee=g.headers?.get?.("content-type");e.readStreamedBody(T,qs(ee)?void 0:1024*1024).then(Z=>{let Y=Z.body,Oe=false;if(ee?.toLowerCase().includes("json"))try{Y=JSON.parse(Z.body),Oe=true}catch{}e.emit({type:"response",timestamp:new Date,duration:fe()-d,timings:j,request:{id:a||"unknown",url:C,method:c,headers:R,data:m,params:u||void 0,client:x},response:{status:g.status,statusText:g.statusText,headers:J,body:Y,size:Z.size,json:Oe,truncated:Z.truncated},override:D,condition:p})}).catch(()=>{})}return g}catch(g){let v=fe()-d;throw e.emit({type:"error",timestamp:new Date,duration:v,request:{id:a||"unknown",url:C,method:c,headers:R,data:m,params:u||void 0,client:x},error:{message:g instanceof Error?g.message:"Network error",stack:g instanceof Error?g.stack:void 0},override:D,condition:p}),g}};o[zs]=true,this.patchedFetch=o,globalThis.fetch=this.patchedFetch}installXhrInterceptor(){let e=this,t=XMLHttpRequest.prototype.open,r=XMLHttpRequest.prototype.send,o=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t,this.originalXHRSend=r,this.originalXHRSetRequestHeader=o;let n=++this.xhrGeneration,i=new WeakMap,s=function(l,c,y,w,p){let C=t.call(this,l,c,y??true,w,p);if(n===e.xhrGeneration){i.get(this)?.();let u=this;u._buoyRequestId=So("xhr"),u._method=l,u._url=wo(c),u._buoyStartTime=fe(),u._requestHeaders={},u._buoyAsync=y!==false,u._buoyRestoreAbort?.(),u._buoyWaitedForRules=false,u._buoyHeldSend=false,u._buoyOpenSeq=(u._buoyOpenSeq??0)+1}return C},d=function(l,c){let y=this;return n===e.xhrGeneration&&y._requestHeaders&&(y._requestHeaders[l]=c),o.call(this,l,c)},a=function(l){if(n!==e.xhrGeneration||Zt)return r.call(this,l);if(rc(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent)return r.call(this,l);let c=this;if(c._buoyHeldSend)throw new DOMException("The request has already been sent.","InvalidStateError");if(!kc()&&c._buoyAsync!==false&&!c._buoyWaitedForRules){c._buoyWaitedForRules=true,c._buoyHeldSend=true;let L=c._buoyOpenSeq,H=false,j=Object.prototype.hasOwnProperty.call(this,"abort")?this.abort:void 0,J=()=>{c._buoyRestoreAbort===J&&(c._buoyRestoreAbort=void 0,j?this.abort=j:delete this.abort)};c._buoyRestoreAbort=J;let ee=j??Object.getPrototypeOf(this).abort;this.abort=function(){return H=true,c._buoyHeldSend=false,J(),ee.call(this)};let Z=()=>{J(),!(H||c._buoyOpenSeq!==L)&&(c._buoyHeldSend=false,this.readyState===1&&!this._sent&&a.call(this,l))};Es().then(Z,Z);return}let y=c._buoyRequestId,w=c._method||"GET",p=c._url||"",C=fe();c._buoyStartTime=C,c._buoyTtfb=void 0;let u=c._requestHeaders||{};if(Object.assign(u,Ls(p)),e.shouldIgnoreUrl(p))return r.call(this,l);let{url:R,params:h}=e.parseUrl(p),m;if(l)if(typeof l=="string")try{m=JSON.parse(l)}catch{m=l}else m=l;let x=u["X-Request-Client"]||u["x-request-client"],I=u.Accept||u.accept||"",B=I.includes("application/json")&&I.includes("text/plain")&&I.includes("*/*")&&!Ac(),E=x||(B?"axios":"xhr"),D=Ns(p),k=D?.uploadBytesPerSecond?{...D,uploadCap:Bn(l)}:D,g=k?.profile==="offline"?null:Bs(p,w,u,typeof l=="string"?l:void 0),v=g?Ps(g):void 0;e.emit({type:"request",timestamp:new Date,request:{id:y||"unknown",url:R,method:w,headers:u,data:m,params:h||void 0,client:E},override:v,condition:k});let f=false,T=(L=false)=>{f||(f=true,e.handleXHRResponse(this,y||"unknown",R,w,u,m,h,C||0,L,E,v,k),M())},M=()=>{i.delete(this),this.removeEventListener("load",P),this.removeEventListener("error",A),this.removeEventListener("abort",_),this.removeEventListener("readystatechange",F)};i.set(this,M);let P=()=>{T(false)},A=()=>{T(true)},_=()=>{T(true)},F=()=>{if(this.readyState===2){let L=this;L._buoyTtfb===void 0&&L._buoyStartTime&&(L._buoyTtfb=fe()-L._buoyStartTime)}this.readyState===4&&!f&&T(false)};if(this.addEventListener("load",P),this.addEventListener("error",A),this.addEventListener("abort",_),this.addEventListener("readystatechange",F),k){ic(this,p,k,g,()=>r.call(this,l),l);return}if(!(g&&ks(this,p,g,()=>r.call(this,l))))return r.call(this,l)};a[Os]=true,this.patchedXHROpen=s,this.patchedXHRSend=a,this.patchedXHRSetRequestHeader=d,XMLHttpRequest.prototype.open=this.patchedXHROpen,XMLHttpRequest.prototype.send=this.patchedXHRSend,XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){this.isListening&&(this.fetchGeneration++,this.xhrGeneration++,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.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader),this.patchedFetch=null,this.patchedXHROpen=null,this.patchedXHRSend=null,this.patchedXHRSetRequestHeader=null,this.isListening=false)}adoptEarlyRequests(){let e=globalThis,t=e[Oc]??e.__BUOY_EARLY_NETWORK__;if(t?.version===1)for(let r of t.adopt())try{r.kind==="fetch"?this.adoptEarlyFetch(r):this.adoptEarlyXhr(r)}catch{}}adoptEarlyFetch(e){let{input:t,init:r}=e,o=typeof t=="object"&&"method"in t?t:void 0,n=wo(typeof t=="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(n))return;let i=So("fetch"),s=r?.method??o?.method??"GET",{url:d,params:a}=this.parseUrl(n),l=qc(r?.headers??o?.headers),c=r?.body;if(typeof c=="string")try{c=JSON.parse(c)}catch{}let y=l["X-Request-Client"]||l["x-request-client"]||"fetch",w=()=>({id:i,url:d,method:s,headers:l,data:c,params:a||void 0,client:y});this.emit({type:"request",timestamp:new Date(e.start),request:w()}),e.requestCopy&&this.readStreamedBody(e.requestCopy).then(({body:p})=>{try{c=JSON.parse(p)}catch{c=p}this.emit({type:"request-body",timestamp:new Date,request:{id:i,url:d,method:s,data:c,client:y}})}).catch(()=>{}),e.settled.then(async({response:p,clone:C,error:u,headersAt:R})=>{if(!p){this.emit({type:"error",timestamp:new Date,duration:R-e.start,request:w(),error:{message:u instanceof Error?u.message:"Network error",stack:u instanceof Error?u.stack:void 0}});return}let{body:h,size:m,json:x,truncated:I,unread:B}=C?await this.processResponseBody(C):{body:Nn,size:0,json:false,truncated:false,unread:true},E=Math.max(0,fe()-e.start),D=R-e.start,k={};p.headers.forEach((g,v)=>{k[v.toLowerCase()]=g}),this.emit({type:"response",timestamp:new Date,duration:E,timings:E>D?{ttfb:D,download:E-D}:void 0,request:w(),response:{status:p.status,statusText:p.statusText,headers:k,body:h,size:m,json:x,truncated:I||void 0,unread:B||void 0}})})}adoptEarlyXhr(e){let t=wo(e.url);if(this.shouldIgnoreUrl(t))return;let r=So("xhr"),o=e.method.toUpperCase(),{url:n,params:i}=this.parseUrl(t),s=e.body;if(typeof s=="string")try{s=JSON.parse(s)}catch{}let d=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:r,url:n,method:o,headers:e.headers,data:s,params:i||void 0,client:d}});let a=e.xhr,l=()=>{let c=(a._buoyEarlyEnd??fe())-e.start;this.handleXHRResponse(a,r,n,o,e.headers,s,i,fe()-c,false,d)};a.readyState===4?l():a.addEventListener("loadend",l,{once:true})}addListener(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}},Mt=null,$n=()=>(Mt||(Mt=new $c),Mt),Co=$n,Ds=()=>$n().startListening(),jr=()=>Mt?.stopListening(),Fr=e=>$n().addListener(e),Hc=()=>Mt?.removeAllListeners(),As=()=>Mt?.isActive??false,er=()=>Mt?.listenerCount??0,jc=()=>Mt?.isInterceptionLive()??false;q();var $t={normal:{label:"Normal",delayMs:0},offline:{label:"Offline (requests)",delayMs:0},slow:{label:"Slow (+500 ms)",delayMs:500},verySlow:{label:"Very slow (+2000 ms)",delayMs:2e3},slow3g:{label:"Slow 3G",delayMs:2e3,downloadBytesPerSecond:5e4,uploadBytesPerSecond:5e4},slow4g:{label:"Slow 4G",delayMs:562.5,downloadBytesPerSecond:18e4,uploadBytesPerSecond:84375},fast4g:{label:"Fast 4G",delayMs:165,downloadBytesPerSecond:1012500,uploadBytesPerSecond:168750}},Fc=["auto","real","offline","wifi","cellular","noInternet"],Wc={download:"Paces bytes to the app in JS. The socket stays at its real speed.",upload:"Waits before send for known body bytes. Unknown sizes pass through with latency only. Multipart overhead is not counted. Each call marks a partial or skipped cap. Upload time is simulated; the socket is not paced.",transports:"Affects global fetch and RN XHR. Offline also drops WebSockets; speeds don't slow them. Native images, native SDKs and file transfers are not affected."};var Hn={netInfo:{supported:false,reason:"Load the NetInfo hook before app code."},expoNetwork:{supported:false,reason:"Load the Expo Network hook before app code."}},Ht="auto",jn=0,_c=()=>Ht,tr=()=>jn,Vc=()=>Lt()?Ht==="auto"?pt==="offline"?"offline":"real":Ht:"real",Fn=()=>pt!=="normal"||!["auto","real"].includes(Ht);function rr(){let e=$t[pt];return{version:2,runtimeId:Uc,revision:jn,profile:pt,connection:Ht,available:Lt(),active:Fn(),delayMs:e.delayMs,downloadBytesPerSecond:e.downloadBytesPerSecond??null,uploadBytesPerSecond:e.uploadBytesPerSecond??null,capabilities:{...Hn,fetch:"JS body delivery",xhr:"RN progress and body delivery",upload:"time-simulated",webSocket:"offline only",nativeImages:false,nativeModules:false},scope:Wc}}function To(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Choose a speed or link state.");let t=e;if(Object.keys(t).some(i=>i!=="profile"&&i!=="connection")||!("profile"in t)&&!("connection"in t))throw new Error("Choose a speed or link state.");let r="profile"in t?t.profile:pt,o="connection"in t?t.connection:r==="normal"&&"profile"in t?"auto":Ht;if(typeof r!="string"||!Object.prototype.hasOwnProperty.call($t,r))throw new Error("Choose a valid speed profile.");if(!Fc.includes(o))throw new Error("Choose a valid link state.");if((r!=="normal"||!["auto","real"].includes(o))&&!Lt())throw new Error("Use a signed-in account and a dev build.");if(!["auto","real"].includes(o)&&!Hn.netInfo.supported&&!Hn.expoNetwork.supported)throw new Error("Load a link hook before app code.");if(r===pt&&o===Ht)return rr();let n=r!=="normal";return n&&!Ro&&(Ds(),Ro=Fr(()=>{})),n||(Ro?.(),Ro=void 0,er()===0&&jr()),pt=r,Ht=o,jn++,Io.forEach(i=>i()),rr()}var Uc=`${Date.now()}-${Math.random().toString(36).slice(2)}`,pt="normal",Ro,Io=new Set,Lt=()=>typeof we<"u"&&we&&cs(),jt=()=>pt,ft=e=>(Io.add(e),()=>{Io.delete(e)});function Po(e){return To({profile:e}).profile}function Ns(e){if(pt==="normal"||!Lt()||!/^https?:\/\//i.test(e))return;let{label:t,...r}=$t[pt];return Object.freeze({profile:pt,...r})}Jd(()=>{cs()||Po("normal"),Io.forEach(e=>e())});import{jsx as Wn,jsxs as Jc}from"react/jsx-runtime";function Gc({size:e}){ds(ft,tr,tr);let t=Fn(),r=ds(ft,jt,jt);return Jc(S,{accessibilityLabel:r==="normal"?"Network":`Network: ${$t[r].label}`,children:[Wn(Ud,{size:e}),t&&Wn(S,{pointerEvents:"none",style:{position:"absolute",top:-6,right:-8,width:48,alignItems:"flex-end"},children:Wn(b,{testID:"buoy-network-condition-indicator",numberOfLines:1,style:{color:"#FFCC66",fontSize:10,fontWeight:"700"},children:r==="normal"?"LINK":r==="offline"?"OFF":`+${$t[r].delayMs}`})})]})}import{createToolFactory as Xc,defineToolPreset as Kc}from"@buoy-gg/shared-ui/web";q();q();he();import{useEffect as _n,useRef as Vn,useState as Un,useSyncExternalStore as Eo}from"react";import{FloatingTool as Qc,night as Ve,openFloatingTool as Yc,persistentStorage as Zc,registerPersistentFloatingTool as eu}from"@buoy-gg/shared-ui/web";q();he();import{useEffect as Ms,useRef as Jn,useState as Bo,useSyncExternalStore as Gn}from"react";import{ChevronDown as tu,Check as ru,night as pe}from"@buoy-gg/shared-ui/web";import{jsx as Ie,jsxs as or}from"react/jsx-runtime";var $s=[{profile:"normal",label:"No throttling"},{profile:"slow",label:"Slow"},{profile:"verySlow",label:"Very slow"},{profile:"offline",label:"Offline"},{profile:"slow3g",label:"Slow 3G"},{profile:"slow4g",label:"Slow 4G"},{profile:"fast4g",label:"Fast 4G"}],Hs={normal:"No added delay",slow:"+500 ms before each new request",verySlow:"+2 seconds before each new request",offline:"New requests fail before sending",slow3g:"50 KB/s down, 50 KB/s up; +2000 ms",slow4g:"180 KB/s down, 84.375 KB/s up; +562.5 ms",fast4g:"1012.5 KB/s down, 168.75 KB/s up; +165 ms"};function ou({remote:e,compact:t=false}){Gn(ft,tr,tr);let r=e?e.state:rr(),[o,n]=Bo(false),i=Gn(ft,jt,jt),s=Gn(ft,Lt,Lt),[d,a]=Bo(false),[l,c]=Bo(),[y,w]=Bo(false),p=Jn(false),C=Jn(true),u=Jn(0);Ms(()=>{u.current++,p.current=false,w(false),c(void 0)},[e?.targetId]),Ms(()=>(C.current=true,()=>{C.current=false}),[]);let R=e?e.profile:i,h=e?e.available:s,m=r?.active??(R!==null&&R!=="normal"),x=R==="offline"?pe.color.danger:m?pe.color.warning:pe.color.accent;async function I(k){if(!h||p.current)return;if(k===R&&(k!=="normal"||!r?.active)){a(false);return}let g=++u.current;p.current=true,w(true),c(void 0);try{e?await e.onChange(k):Po(k),C.current&&u.current===g&&a(false)}catch(v){C.current&&u.current===g&&c(v instanceof Error?v.message:String(v))}finally{u.current===g&&(p.current=false,C.current&&w(false))}}let B=[["auto","Follow speed"],["real","Real link"],["offline","Offline"],["wifi","Wi-Fi"],["cellular","Cellular"],["noInternet","No internet"]],E=(!e||!!e.onConnectionChange)&&(r?.capabilities.netInfo.supported||r?.capabilities.expoNetwork.supported),D=$s.find(k=>k.profile===R)?.label??"Unavailable";return or(S,{style:ce.container,testID:"buoy-network-throttling-screen",children:[Ie(b,{style:ce.heading,children:"Connection profile"}),or(W,{testID:"buoy-network-conditions",accessibilityRole:"button",accessibilityLabel:`Network throttling: ${D}`,accessibilityState:{expanded:d,disabled:!h||y},disabled:!h||y,onPress:()=>a(k=>!k),style:[ce.dropdown,d&&ce.dropdownOpen,!h&&ce.disabled],children:[Ie(b,{style:[ce.value,m&&{color:x}],children:D}),y?Ie(yo,{size:"small",color:pe.color.textSecondary}):Ie(tu,{size:16,color:pe.color.textSecondary})]}),d&&Ie(S,{accessibilityRole:"radiogroup",accessibilityLabel:"Connection profile",style:ce.options,children:$s.map(k=>{let g=R===k.profile;return or(W,{testID:`buoy-network-condition-${k.profile}`,accessibilityRole:"radio",accessibilityLabel:k.label,accessibilityState:{checked:g,disabled:!h||y},disabled:!h||y,onPress:()=>void I(k.profile),style:[ce.option,g&&ce.selected],children:[or(S,{style:ce.optionBody,children:[Ie(b,{style:[ce.optionTitle,g&&{color:x}],children:k.label}),Ie(b,{style:ce.caption,children:Hs[k.profile]})]}),g&&Ie(ru,{size:16,color:x})]},k.profile)})}),Ie(b,{style:ce.caption,accessibilityLiveRegion:"polite",children:y?"Applying to device\u2026":h?R?Hs[R]:"Waiting for device status":e?"Conditions unavailable on this device":"Requires a signed-in account and a development build"}),!!l&&Ie(b,{accessibilityRole:"alert",style:ce.error,children:l}),Ie(W,{testID:"buoy-network-link-state",accessibilityRole:"button",accessibilityLabel:"App link state",disabled:!h||y||!E,onPress:()=>n(k=>!k),style:ce.dropdown,children:or(b,{style:ce.value,children:["App link: ",B.find(([k])=>k===r?.connection)?.[1]??"Unavailable"]})}),o&&B.map(([k,g])=>Ie(W,{testID:`buoy-network-link-${k}`,accessibilityRole:"radio",accessibilityState:{checked:r?.connection===k,disabled:y||!h},disabled:y||!h,style:ce.option,onPress:async()=>{if(p.current)return;let v=++u.current;p.current=true,w(true),c(void 0);try{e?await e.onConnectionChange?.(k):To({connection:k}),C.current&&u.current===v&&n(false)}catch(f){C.current&&u.current===v&&c(f instanceof Error?f.message:String(f))}finally{u.current===v&&(p.current=false,C.current&&w(false))}},children:Ie(b,{style:ce.optionTitle,children:g})},k)),!E&&Ie(b,{style:ce.caption,children:r?.capabilities.netInfo.reason??"This device has no link hook."}),!t&&or(S,{style:ce.help,children:[Ie(b,{style:ce.heading,children:"How it works"}),r&&or(b,{style:ce.caption,children:["NetInfo: ",r.capabilities.netInfo.supported?"Hook on":r.capabilities.netInfo.reason??"No hook",". Expo Network: ",r.capabilities.expoNetwork.supported?"Hook on":r.capabilities.expoNetwork.reason??"No hook","."]}),Ie(b,{style:ce.caption,children:"Down caps pace bytes to the app in JS. The socket stays at its real speed."}),Ie(b,{style:ce.caption,children:"Up caps wait before send for known bytes. Upload time is simulated. The socket is not paced. Unknown sizes pass through with latency only. Each call shows any cap gap."}),Ie(b,{style:ce.caption,children:"Caps apply per call through global fetch and RN XHR. Offline also drops WebSockets; speeds don't slow them. Native images, native SDKs and file transfers are not affected."}),Ie(b,{style:ce.caption,children:"Link state changes what NetInfo and Expo Network report. It does not change the radio or web calls."}),Ie(b,{style:ce.caption,children:"Stays on when this tool closes or capture pauses. No throttling clears both controls. App reload clears them too."})]})]})}var ce=se.create({container:{padding:pe.gutter,gap:10},heading:{fontSize:pe.font.caption,fontWeight:"600",color:pe.color.textSecondary},dropdown:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingHorizontal:12,paddingVertical:10,borderRadius:pe.radius.segment,borderWidth:1,borderColor:pe.color.separator,backgroundColor:pe.color.surfaceElevated},dropdownOpen:{borderColor:pe.color.accentBorderStrong},value:{flex:1,fontSize:pe.font.body,color:pe.color.text},options:{padding:4,borderRadius:pe.radius.row,borderWidth:1,borderColor:pe.color.border,backgroundColor:pe.color.surface},option:{flexDirection:"row",alignItems:"center",gap:12,minHeight:54,padding:10,borderRadius:pe.radius.segment},optionBody:{flex:1,gap:4},optionTitle:{fontSize:pe.font.caption,fontWeight:"600",color:pe.color.text},selected:{backgroundColor:pe.color.surfaceElevated},disabled:{opacity:.45},caption:{fontSize:pe.font.caption,lineHeight:19,color:pe.color.textSecondary},help:{marginTop:14,paddingTop:16,gap:10,borderTopWidth:1,borderTopColor:pe.color.separator},error:{fontSize:pe.font.caption,lineHeight:18,color:pe.color.danger}});import{jsx as qe,jsxs as Lo}from"react/jsx-runtime";function nu(){let e,t=new Set;return{getSnapshot:()=>e,subscribe:r=>(t.add(r),()=>{t.delete(r)}),update(r){e=r,t.forEach(o=>o())}}}var iu=()=>()=>{},js=()=>{},zo=[{id:"normal",label:"No throttling",detail:"No added delay"},{id:"slow",label:"Slow",detail:"+500 ms before sending"},{id:"verySlow",label:"Very slow",detail:"+2 seconds before sending"},{id:"offline",label:"Offline",detail:"New requests fail"}],su={id:"network-throttling",render:e=>qe(_s,{...e})};function Fs(){return typeof we>"u"||!we?()=>{}:eu(su,Zc)}typeof we<"u"&&we&&typeof navigator<"u"&&navigator.product==="ReactNative"&&Fs();function Ws(e,t=false){Yc({id:"network-throttling",render:r=>qe(_s,{...r,source:e,showControls:t})})}function _s({id:e,revealToken:t,dismiss:r,source:o,showControls:n=false}){Eo(ft,tr,tr);let i=rr(),s=Eo(ft,jt,jt),d=Eo(ft,Lt,Lt),a=Eo(o?.subscribe??iu,o?.getSnapshot??js,js),l=o?a?.profile??null:s,c=o?a?.available===true:d,[y,w]=Un(n);_n(()=>{w(n)},[n,t]);let[p,C]=Un(false),[u,R]=Un(),h=Vn(false),m=Vn(0),x=Vn(true),{width:I,height:B}=Xi();_n(()=>(x.current=true,()=>{x.current=false}),[]),_n(()=>{m.current+=1,h.current=false,C(false),R(void 0)},[o,a?.targetId]);let E=o?a?.state?.active??(l!==null&&l!=="normal"):i.active,D=l??"normal",k=zo.find(P=>P.id===D)??{label:$t[D].label},g=zo[(zo.findIndex(P=>P.id===D)+1)%zo.length],v=!c||D==="offline"?0:D==="verySlow"?1:D==="slow"?2:4,f=p?"Applying\u2026":c?D==="normal"?E?"Link set":"0 ms":D==="slow"?"+500 ms":D==="verySlow"?"+2000 ms":D==="offline"?"Blocked":`${Math.round(($t[D].downloadBytesPerSecond??0)/1e3)} kB/s`:"Unavailable";async function T(P,A=false){if(h.current)return;let _=++m.current;h.current=true,C(true),R(void 0);let F=o?.getSnapshot();try{if(o){if(!F?.available)throw new Error("Device unavailable. Open Network again to reconnect these controls.");await F.onChange(P)}else Po(P);x.current&&m.current===_&&A&&r()}catch(L){x.current&&m.current===_&&R(L instanceof Error?L.message:String(L))}finally{m.current===_&&(h.current=false,x.current&&C(false))}}let M=u||y?Lo(S,{style:Ue.menu,children:[!!u&&qe(b,{accessibilityRole:"alert",style:Ue.error,children:u}),y&&qe(ht,{testID:"throttling-controls-scroll",style:{maxHeight:Math.min(420,B-180)},children:qe(ou,{remote:o?a??{profile:null,available:false,onChange:async()=>{throw new Error("Device unavailable.")}}:void 0})})]}):void 0;return qe(Qc,{id:e,revealToken:t,variant:"strip",dragFromSurface:fo.OS!=="android"||!y,accessibilityLabel:`Move or hide network throttling. ${E?"Active":"Off"}`,accessory:fo.OS==="android"?void 0:M,children:Lo(S,{style:{width:Math.max(220,Math.min(336,I-64))},children:[Lo(S,{style:[Ue.row,{width:Math.max(220,Math.min(336,I-64))}],children:[qe(W,{testID:"throttling-cycle",accessibilityRole:"button",accessibilityLabel:`Network: ${k.label}. Switch to ${g.label}`,accessibilityState:{disabled:p||!c},disabled:p||!c,onPress:()=>void T(g.id),style:Ue.signalButton,children:p?qe(yo,{size:"small",color:Ve.color.accent}):Lo(S,{testID:`throttling-signal-${D}`,style:Ue.signal,children:[[7,12,18,24].map((P,A)=>qe(S,{style:{width:4,height:P,borderRadius:2,backgroundColor:A<v?D==="offline"?Ve.color.danger:Ve.color.accent:Ve.color.fillTertiary}},P)),D==="offline"&&qe(S,{style:Ue.slash})]})}),qe(S,{style:Ue.profile,children:qe(b,{testID:"throttling-profile",accessibilityLabel:`Connection profile: ${k.label}`,accessibilityLiveRegion:"polite",numberOfLines:1,style:Ue.profileLabel,children:k.label})}),qe(b,{testID:"throttling-status",numberOfLines:1,accessibilityLiveRegion:"polite",style:Ue.status,children:f}),qe(W,{testID:"throttling-edit",accessibilityRole:"button",accessibilityLabel:y?"Hide speed and link controls":"Edit speed and link state",onPress:()=>w(P=>!P),style:Ue.action,children:qe(b,{style:Ue.actionText,children:y?"Done":"Edit"})}),qe(S,{style:Ue.separator}),qe(W,{testID:"throttling-close",accessibilityRole:"button",accessibilityLabel:"Close and turn off throttling",disabled:p,accessibilityState:{disabled:p},onPress:()=>{E?T("normal",true):r()},style:[Ue.action,p&&Ue.disabled],children:qe(b,{style:Ue.actionText,children:"Close"})})]}),fo.OS==="android"&&M]})})}var Ue=se.create({row:{flexDirection:"row",alignItems:"center",gap:6,paddingVertical:4,minHeight:48},signalButton:{width:36,minHeight:44,alignItems:"center",justifyContent:"center"},signal:{flexDirection:"row",alignItems:"flex-end",gap:3,height:24},slash:{position:"absolute",width:30,height:2,backgroundColor:Ve.color.danger,top:11,left:-2,transform:[{rotate:"-45deg"}]},separator:{height:20,width:1,backgroundColor:Ve.color.separator,marginHorizontal:2},status:{color:Ve.color.textSecondary,fontSize:10,lineHeight:15,flexShrink:1},profile:{flex:1,flexDirection:"row",alignItems:"center",gap:6,minHeight:44},profileLabel:{color:Ve.color.text,fontSize:13,fontWeight:"500",flexShrink:1},action:{minHeight:36,minWidth:52,borderRadius:Ve.radius.input,borderWidth:1,borderColor:Ve.color.accentBorderStrong,alignItems:"center",justifyContent:"center",paddingHorizontal:10},actionText:{color:Ve.color.accent,fontSize:12,fontWeight:"600"},disabled:{opacity:.4},menu:{marginVertical:8,padding:6,borderRadius:Ve.radius.card,borderWidth:1,borderColor:Ve.color.separator,backgroundColor:Ve.color.surface,shadowColor:"#000",shadowOffset:{width:0,height:6},shadowOpacity:.25,shadowRadius:16,elevation:8},error:{color:Ve.color.danger,fontSize:12,lineHeight:18,padding:10}});he();import{useState as Be,useRef as Wr,useEffect as nr,useCallback as Xn}from"react";import{Search as au,Wifi as Vs,Filter as lu,Bookmark as du,Activity as cu,JsModal as uu,ModalHeader as Te,devToolsStorageKeys as Oo,macOSColors as hu,night as gt,persistentStorage as Us,NightSegmented as pu,useFeatureGate as fu,UpgradeModal as gu,PowerToggleButton as yu,useIgnoredPatterns as mu,windowDragProps as bu}from"@buoy-gg/shared-ui/web";q();he();import{CheckCircle as vu,Clock as wu,DynamicFilterView as Su,Film as ku,FileJson as xu,FileText as Cu,Filter as Js,Globe as Gs,Image as Tu,macOSColors as Ae,night as Ye,Music as Ru,XCircle as Iu,monoFont as Kn}from"@buoy-gg/shared-ui/web";import{useCallback as qo,useMemo as St,useState as Pu}from"react";import{jsx as zt,jsxs as Xs}from"react/jsx-runtime";var Eu=()=>false;function Qn(e){let t=e.responseHeaders||e.requestHeaders,r=t?.["content-type"]||t?.["Content-Type"]||"";return r.includes("json")?{type:"JSON",color:Ae.semantic.info}:r.includes("xml")?{type:"XML",color:Ae.semantic.success}:r.includes("html")?{type:"HTML",color:Ae.semantic.warning}:r.includes("text")?{type:"TEXT",color:Ae.semantic.success}:r.includes("image")?{type:"IMAGE",color:Ae.semantic.error}:r.includes("video")?{type:"VIDEO",color:Ae.semantic.error}:r.includes("audio")?{type:"AUDIO",color:Ae.semantic.debug}:r.includes("form")?{type:"FORM",color:Ae.semantic.info}:{type:"OTHER",color:Ye.color.textTertiary}}function Bu(e){switch(e){case"JSON":return xu;case"HTML":case"XML":case"TEXT":return Cu;case"IMAGE":return Tu;case"VIDEO":return ku;case"AUDIO":return Ru;default:return Gs}}function Lu(e){switch(e){case"GET":return Ae.semantic.success;case"POST":return Ae.semantic.info;case"PUT":return Ae.semantic.warning;case"DELETE":return Ae.semantic.error;case"PATCH":return Ae.semantic.success;default:return Ye.color.textTertiary}}function zu({events:e,filter:t,onFilterChange:r,ignoredPatterns:o=[],onRemovePattern:n=()=>{},isTeamPattern:i=Eu,onAddPattern:s=()=>{},onTogglePatternMode:d=()=>{}}){let[a,l]=Pu("contains"),c=St(()=>{let k=new Map;for(let g of o)k.set(g.value,g.mode);return k},[o]),y=St(()=>new Set(o.map(k=>k.value)),[o]),w=qo(k=>{s({value:k,mode:a})},[s,a]),p=qo(k=>{if(i(k)){let T=Ye.color.accent;return zt(S,{accessibilityLabel:"Set by your team on buoy.gg",style:[lt.modeBadge,{borderColor:`${T}60`,backgroundColor:`${T}15`}],children:zt(b,{style:[lt.modeBadgeText,{color:T}],children:"TEAM"})})}let g=c.get(k)??"contains",v=g==="exact",f=v?Ye.color.warning:Ye.color.info;return zt(W,{accessibilityRole:"button",accessibilityLabel:`Match mode: ${g}. Tap to toggle.`,onPress:()=>d(k),style:[lt.modeBadge,{borderColor:`${f}60`,backgroundColor:`${f}15`}],hitSlop:{top:6,bottom:6,left:6,right:6},children:zt(b,{style:[lt.modeBadgeText,{color:f}],children:v?"EXACT":"CONTAINS"})})},[c,d,i]),C=qo(()=>{let k=[{label:"Contains",value:"contains",hint:"substring"},{label:"Exact",value:"exact",hint:"whole path/host/url"}];return Xs(S,{style:lt.modeToggleRow,children:[zt(b,{style:lt.modeToggleLabel,children:"Match:"}),zt(S,{style:lt.modeToggleGroup,children:k.map(g=>{let v=a===g.value;return Xs(W,{onPress:()=>l(g.value),style:[lt.modeToggleButton,v&&lt.modeToggleButtonActive],accessibilityRole:"button",accessibilityState:{selected:v},children:[zt(b,{style:[lt.modeToggleButtonText,v&&lt.modeToggleButtonTextActive],children:g.label}),zt(b,{style:lt.modeToggleButtonHint,children:g.hint})]},g.value)})})]})},[a]),u=St(()=>{let k={all:e.length,success:0,error:0,pending:0};return e.forEach(g=>{if(g.error||g.status&&g.status>=400){k.error+=1;return}if(g.status&&g.status>=200&&g.status<300){k.success+=1;return}!g.status&&!g.error&&(k.pending+=1)}),k},[e]),R=St(()=>e.reduce((k,g)=>(g.method&&(k[g.method]=(k[g.method]||0)+1),k),{}),[e]),h=St(()=>e.reduce((k,g)=>{let{type:v}=Qn(g);return k[v]=(k[v]||0)+1,k},{}),[e]),m=St(()=>{let k=new Set;return e.forEach(g=>{if(g.host){k.add(g.host);return}try{if(g.url){let v=new URL(g.url),f=String(v.host||"");f&&k.add(f)}}catch{}}),Array.from(k).filter(g=>g&&g!=="").sort((g,v)=>g.localeCompare(v))},[e]),x=St(()=>{let k=new Set;return e.forEach(g=>{if(g.url)try{let v=new URL(g.url),f=String(v.origin||""),T=String(v.pathname||""),M=`${f}${T}`;k.add(M)}catch{k.add(g.url)}}),Array.from(k).filter(g=>g&&g!=="").sort((g,v)=>g.localeCompare(v))},[e]),I=St(()=>{let k=m.slice(0,30),g=x.slice(0,30);return[...k,...g]},[m,x]),B=qo((k,g)=>{let[v]=k.split("::");if(v==="status"){r({...t,status:g==="all"?void 0:g});return}if(v==="method"){let f=String(g),T=t.method||[],M=T.includes(f)?T.filter(P=>P!==f):[f];r({...t,method:M.length>0?M:void 0});return}if(v==="contentType"){let f=String(g),T=t.contentType||[],M=T.includes(f)?T.filter(P=>P!==f):[f];r({...t,contentType:M.length>0?M:void 0})}},[t,r]),E=St(()=>{let k=[];k.push({id:"status",title:"Status",type:"status",data:["all","success","error","pending"].map(f=>({id:`status::${f}`,label:f.charAt(0).toUpperCase()+f.slice(1),count:u[f],icon:f==="success"?vu:f==="error"?Iu:f==="pending"?wu:Gs,color:f==="success"?Ae.semantic.success:f==="error"?Ae.semantic.error:f==="pending"?Ae.semantic.warning:Ae.semantic.info,isActive:t.status===f||!t.status&&f==="all",value:f}))});let g=Object.entries(R);g.length>0&&k.push({id:"method",title:"Method",type:"method",data:g.map(([f,T])=>({id:`method::${f}`,label:f,count:T,color:Lu(f),isActive:t.method?.includes(f)??false,value:f}))});let v=Object.entries(h);return v.length>0&&k.push({id:"contentType",title:"Content Type",type:"contentType",data:v.map(([f,T])=>{let M=e.find(A=>Qn(A).type===f),{color:P}=M?Qn(M):{color:Ye.color.textTertiary};return{id:`contentType::${f}`,label:f,count:T,icon:Bu(f),color:P,isActive:t.contentType?.includes(f)??false,value:f}})}),k},[h,e,t.contentType,t.method,t.status,R,u]),D=St(()=>({sections:E,addFilterSection:{enabled:true,placeholder:"Enter domain or URL pattern...",title:"ACTIVE FILTERS",icon:Js,renderExtra:C},availableItemsSection:{enabled:true,title:"AVAILABLE DOMAINS & URLS",emptyMessage:"No network events captured yet. Domains and URLs will appear here.",items:I},howItWorksSection:{enabled:true,title:"HOW NETWORK FILTERS WORK",description:"Patterns hide matching requests from the network event list. Each pattern has a match mode you can toggle on its badge: CONTAINS hides any URL containing the text; EXACT hides only an exact path/host/url match.",examples:["\u2022 example.com (CONTAINS) \u2192 any request whose URL contains example.com","\u2022 example.com (EXACT) \u2192 only requests served by that exact host","\u2022 /v1 (CONTAINS) \u2192 any URL containing /v1 (e.g. /v1, /v1/users)","\u2022 /v1 (EXACT) \u2192 only requests whose pathname is exactly /v1"],icon:Js},onFilterChange:B,onPatternAdd:w,onPatternToggle:n,activePatterns:y,renderPatternMeta:p}),[y,E,B,w,n,C,p,I]);return zt(Su,{...D})}var lt=se.create({modeBadge:{paddingHorizontal:8,paddingVertical:3,borderRadius:6,borderWidth:1},modeBadgeText:{fontSize:9,fontFamily:Kn,fontWeight:"700",letterSpacing:.5},modeToggleRow:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:8},modeToggleLabel:{fontSize:11,fontWeight:"600",color:Ye.color.textSecondary,fontFamily:Kn,letterSpacing:.3},modeToggleGroup:{flexDirection:"row",gap:6,flex:1},modeToggleButton:{flex:1,paddingVertical:6,paddingHorizontal:10,borderRadius:8,borderWidth:1,borderColor:Ye.color.border,backgroundColor:Ye.color.buttonSurface,alignItems:"center"},modeToggleButtonActive:{borderColor:Ye.color.accentBorderStrong,backgroundColor:Ye.color.accentSoft},modeToggleButtonText:{fontSize:11,fontWeight:"700",color:Ye.color.textSecondary,fontFamily:Kn,letterSpacing:.3},modeToggleButtonTextActive:{color:Ye.color.accent},modeToggleButtonHint:{fontSize:9,color:Ye.color.textTertiary,marginTop:1}});q();import{TickProvider as Yn}from"@buoy-gg/shared-ui/web";import{useTick as Ou}from"@buoy-gg/shared-ui/web";function Zn(){return Ou()??Date.now()}q();he();import{useState as _r,useEffect as Ks,useMemo as qu,memo as Du}from"react";import{Clock as ei,Upload as Qs,Download as Ys,AlertCircle as Au,ChevronDown as Zs,ChevronUp as ea,Lock as Nu,Unlock as Mu,FileJson as Do,Filter as $u,Globe as Hu,Link as ju,Copy as ta,FlaskConical as Fu,InlineCopyButton as ra,macOSColors as Ao,night as $,useFeatureGate as Wu,UpgradeModal as _u,monoFont as Sr}from"@buoy-gg/shared-ui/web";q();import{formatBytes as Ot,formatDuration as No,formatHttpStatus as oa,getMethodColor as mb}from"@buoy-gg/shared-ui/web";import{formatRelativeTime as Vu}from"@buoy-gg/shared-ui/web";import{DataViewer as Vr}from"@buoy-gg/shared-ui/web/dataViewer";q();function ti(e,t=30){if(e==null)return null;if(typeof e=="boolean"||typeof e=="number")return String(e);if(typeof e=="string")return e.length>t?e.substring(0,t-1)+"\u2026":e;if(Array.isArray(e))return e.length===0?null:e.length===1?ti(e[0],t):`${e.length} items`;if(typeof e=="object"){let r=Object.entries(e);if(r.length===0)return null;for(let[o,n]of r){let i=ti(n,t);if(i)return i}return null}return null}function Uu(e,t=3){if(!e||typeof e!="object")return null;let r=[];for(let[o,n]of Object.entries(e)){let i=ti(n);if(i&&r.push(i),r.length>=t)break}return r.length>0?r:null}function na(e,t){let r=Uu(t);return!r||r.length===0?e:[e,...r].join(" \u203A ")}function ia(e,t){if(!e||typeof e!="object")return false;for(let r of Object.values(e))if(ri(r,t))return true;return false}function ri(e,t){return typeof e=="string"?e.toLowerCase().includes(t):typeof e=="number"||typeof e=="boolean"?String(e).includes(t):Array.isArray(e)?e.some(r=>ri(r,t)):typeof e=="object"&&e!==null?Object.values(e).some(r=>ri(r,t)):false}q();import{createContext as Ju,useContext as Gu}from"react";import{jsx as Xu}from"react/jsx-runtime";var sa=Ju(null);function Ku({resolver:e,children:t}){return Xu(sa.Provider,{value:e,children:t})}function Qu(){return Gu(sa)}import{Fragment as oi,jsx as z,jsxs as te}from"react/jsx-runtime";var Mo=$.color.accent,Yu=new Set,Zu=()=>{},eh=({timings:e,total:t})=>{let r=Math.max(1,t),o=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:e.ttfb,color:Ao.semantic.warning},{label:"Content download",hint:void 0,value:e.download,color:Ao.semantic.success}];return z(S,{style:O.phaseList,children:o.map(n=>te(S,{style:O.phaseRow,children:[te(S,{style:O.phaseLabelGroup,children:[z(b,{style:O.phaseLabel,children:n.label}),n.hint?z(b,{style:O.phaseHint,children:n.hint}):null]}),z(S,{style:O.phaseTrack,children:z(S,{style:[O.phaseBar,{backgroundColor:n.color,width:`${Math.min(100,Math.max(1,n.value/r*100))}%`}]})}),z(b,{style:O.phaseValue,children:No(n.value)})]},n.label))})},aa=()=>z(S,{style:O.bodyDeferred}),ir=({title:e,icon:t,children:r,defaultOpen:o=false,count:n})=>{let[i,s]=_r(o);return te(S,{style:O.collapsibleSection,children:[te(W,{style:O.collapsibleHeader,onPress:()=>s(!i),testID:`buoy-network-section-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,children:[te(S,{style:O.collapsibleTitle,children:[t,z(b,{style:O.collapsibleTitleText,children:e}),n!==void 0?z(b,{style:O.collapsibleCount,children:n}):null]}),i?z(ea,{size:16,color:$.color.textSecondary}):z(Zs,{size:16,color:$.color.textSecondary})]}),i?z(S,{style:O.collapsibleContent,children:r}):null]})},th=({url:e,requestData:t,operationName:r,graphqlVariables:o,requestClient:n,isPro:i=false,onUpgradePress:s})=>{let d=y=>{try{let w=new URL(y),p=String(w.protocol||""),C=String(w.host||""),u=p==="https:",R=String(w.pathname||"");if(n==="graphql"&&r){let x=na(r,o);R=`${R} (${x})`}else r&&(R=`${R} (${r})`);let h={},m=w.searchParams;return m&&typeof m.forEach=="function"&&m.forEach((x,I)=>{h[I]=x}),{protocol:p.replace(":",""),host:C,pathname:R,params:Object.keys(h).length>0?h:null,isSecure:u}}catch{return{protocol:"",host:e,pathname:"",params:null,isSecure:false}}},a=qu(()=>d(e),[e,n,r,o]),[l,c]=_r(false);return te(S,{style:O.urlBreakdown,children:[te(S,{style:O.urlRow,children:[a.isSecure?z(Nu,{size:12,color:Ao.semantic.success}):z(Mu,{size:12,color:Ao.semantic.warning}),z(b,{style:O.urlDomain,children:a.host}),te(b,{style:O.urlProtocol,children:["(",a.protocol.toUpperCase(),")"]}),i?z(ra,{value:e,buttonStyle:O.copyButton}):z(W,{style:O.copyButton,onPress:s,activeOpacity:.7,children:z(ta,{size:14,color:$.color.textSecondary})})]}),z(S,{style:O.urlPathRow,children:te(b,{style:O.urlPath,numberOfLines:2,children:[a.pathname,a.params?te(b,{style:O.urlQueryString,children:["?",new URLSearchParams(a.params).toString()]}):null]})}),a.params?te(S,{style:O.queryParamsCollapsible,children:[te(W,{style:O.queryParamsToggle,onPress:()=>c(!l),activeOpacity:.7,children:[z(b,{style:O.queryParamsToggleText,children:"Query Parameters"}),z(b,{style:O.collapsibleCount,children:Object.keys(a.params).length}),l?z(ea,{size:14,color:$.color.textSecondary}):z(Zs,{size:14,color:$.color.textSecondary})]}),l?z(Vr,{title:"",data:a.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})},la=Du(function({event:e,ignoredPatterns:t=Yu,onTogglePattern:r=Zu,showBodies:o=true}){let n=e.status?oa(e.status):null,i=!e.status&&!e.error,{isPro:s}=Wu(),[d,a]=_r(false);Ks(()=>{d&&s&&a(false)},[d,s]);let l=Qu(),c=e.requestData===void 0&&(e.requestBodyOmitted===true||(e.requestSize??0)>0),y=e.responseData===void 0&&(e.responseBodyOmitted===true||(e.responseSize??0)>0),w=e.headersOmitted===true,[p,C]=_r(null),[u,R]=_r(false);Ks(()=>{if(C(null),!l||!c&&!y&&!w){R(false);return}let E=false;return R(true),l(e.id).then(D=>{E||C(D)}).catch(()=>{}).finally(()=>{E||R(false)}),()=>{E=true}},[e.id,l,c,y,w]);let h=e.requestData??p?.requestData??void 0,m=e.responseData!==void 0?e.responseData:p?.responseData,x=(w?p?.requestHeaders:void 0)??e.requestHeaders,I=(w?p?.responseHeaders:void 0)??e.responseHeaders,B=()=>{let E={method:e.method,url:e.url,status:e.status,statusText:e.statusText,timestamp:new Date(e.timestamp).toISOString(),duration:e.duration?`${e.duration}ms`:"N/A",requestHeaders:x,requestData:h,responseHeaders:I,responseData:m,requestSize:e.requestSize?Ot(e.requestSize):"N/A",responseSize:e.responseSize?Ot(e.responseSize):"N/A",error:e.error,client:e.requestClient};return`# Network Request Details
10
10
 
11
11
  ## Request
12
- - **Method:** ${P.method}
13
- - **URL:** ${P.url}
14
- - **Client:** ${P.client||"N/A"}
15
- - **Timestamp:** ${P.timestamp}
12
+ - **Method:** ${E.method}
13
+ - **URL:** ${E.url}
14
+ - **Client:** ${E.client||"N/A"}
15
+ - **Timestamp:** ${E.timestamp}
16
16
 
17
17
  ## Response
18
- - **Status:** ${P.status||"Pending"}${P.statusText?` (${P.statusText})`:""}
19
- - **Duration:** ${P.duration}
20
- - **Request Size:** ${P.requestSize}
21
- - **Response Size:** ${P.responseSize}
22
- ${P.error?`- **Error:** ${P.error}`:""}
18
+ - **Status:** ${E.status||"Pending"}${E.statusText?` (${E.statusText})`:""}
19
+ - **Duration:** ${E.duration}
20
+ - **Request Size:** ${E.requestSize}
21
+ - **Response Size:** ${E.responseSize}
22
+ ${E.error?`- **Error:** ${E.error}`:""}
23
23
 
24
24
  ## Request Headers
25
25
  \`\`\`json
26
- ${JSON.stringify(P.requestHeaders,null,2)}
26
+ ${JSON.stringify(E.requestHeaders,null,2)}
27
27
  \`\`\`
28
28
 
29
29
  ## Request Data
30
30
  \`\`\`json
31
- ${JSON.stringify(P.requestData,null,2)}
31
+ ${JSON.stringify(E.requestData,null,2)}
32
32
  \`\`\`
33
33
 
34
34
  ## Response Headers
35
35
  \`\`\`json
36
- ${JSON.stringify(P.responseHeaders,null,2)}
36
+ ${JSON.stringify(E.responseHeaders,null,2)}
37
37
  \`\`\`
38
38
 
39
39
  ## Response Data
40
40
  \`\`\`json
41
- ${JSON.stringify(P.responseData,null,2)}
41
+ ${JSON.stringify(E.responseData,null,2)}
42
42
  \`\`\`
43
- `};return Q(gn,{children:[Q(yt,{keyboardShouldPersistTaps:"handled",testID:"buoy-network-detail-scroll",style:E.container,children:[Q(m,{style:E.requestDetailsSection,children:[Q(m,{style:E.httpHeader,children:[T(m,{style:E.httpMethodBadge,children:T(b,{style:E.httpMethod,children:e.method})}),e.status?T(m,{style:[E.httpStatusBadge,{backgroundColor:`${n?.color}20`}],children:Q(b,{style:[E.httpStatusText,{color:n?.color}],children:[n?.text," ",n?.meaning]})}):i?Q(m,{style:E.pendingBadge,children:[T(pn,{size:10,color:q.color.warning}),T(b,{style:E.pendingBadgeText,children:"Pending"})]}):null,e.condition&&Q(b,{style:{color:"#FFCC66"},children:["Conditions: ",e.condition.profile," (+",e.condition.delayMs," ms)"]}),e.condition?.uploadCap?.note&&T(b,{testID:"buoy-network-upload-cap-detail",style:{color:"#FFCC66"},children:e.condition.uploadCap.note}),e.duration?Q(m,{style:E.httpDuration,children:[T(pn,{size:10,color:q.color.textTertiary}),T(b,{style:E.httpDurationText,children:Zr(e.duration)})]}):null,e.override?Q(m,{style:E.overrideBadge,children:[T(yu,{size:10,color:q.color.warning}),T(b,{style:E.overrideBadgeText,children:e.override.ruleName||"Overridden"})]}):null,s?T(es,{value:$,buttonStyle:E.copyFullButton}):T(F,{style:E.copyFullButton,onPress:()=>a(true),activeOpacity:.7,children:T(Qi,{size:14,color:q.color.textSecondary})})]}),T(Iu,{url:e.url,requestData:k,operationName:e.operationName,graphqlVariables:e.graphqlVariables,requestClient:e.requestClient,isPro:s,onUpgradePress:()=>a(true)}),e.error?Q(m,{style:E.errorBox,children:[T(du,{size:12,color:q.color.danger}),T(b,{style:E.errorText,children:e.error})]}):null]}),Q(m,{style:E.timingSection,children:[Q(m,{style:E.timingRow,children:[T(pn,{size:12,color:q.color.textSecondary}),T(b,{style:E.timingLabel,children:"Started:"}),T(b,{style:E.timingValue,children:bu(e.timestamp)}),Q(b,{style:E.timingExact,children:["(",new Date(e.timestamp).toLocaleTimeString(),")"]}),e.requestSize||e.responseSize?Q(m,{style:E.sizeRow,children:[e.requestSize!==void 0?Q(m,{style:E.sizeItem,children:[T(Gi,{size:10,color:q.color.info}),T(b,{style:E.sizeLabel,children:"Sent:"}),T(b,{style:E.sizeValue,children:ct(e.requestSize)})]}):null,e.responseSize!==void 0?Q(m,{style:E.sizeItem,children:[T(Ki,{size:10,color:Qr}),T(b,{style:E.sizeLabel,children:"Received:"}),T(b,{style:E.sizeValue,children:ct(e.responseSize)})]}):null]}):null]}),e.timings?Q(gn,{children:[T(m,{style:E.phaseDivider}),T(Eu,{timings:e.timings,total:e.duration??e.timings.ttfb+e.timings.download})]}):null]}),T(At,{title:"Request Headers",icon:T(Gi,{size:14,color:q.color.info}),defaultOpen:false,count:Object.keys(I).length,children:Object.keys(I).length>0?T(m,{style:E.dataViewerContainer,children:T(gr,{title:"",data:I,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s})}):T(b,{style:E.emptyText,children:"No request headers"})}),T(At,{title:"Response Headers",icon:T(Ki,{size:14,color:Qr}),defaultOpen:false,count:Object.keys(z).length,children:Object.keys(z).length>0?T(m,{style:E.dataViewerContainer,children:T(gr,{title:"",data:z,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s})}):T(b,{style:E.emptyText,children:"No response headers yet"})}),k!==void 0?T(At,{title:"Request Body",icon:T(Kr,{size:14,color:q.color.accent}),defaultOpen:false,children:T(m,{style:E.dataViewerContainer,children:o?T(gr,{title:"",data:k,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s}):T(is,{})})}):d?T(At,{title:"Request Body",icon:T(Kr,{size:14,color:q.color.accent}),defaultOpen:true,children:T(b,{style:E.emptyText,children:h?`Loading request body (${ct(e.requestSize??0)})\u2026`:"Request body unavailable"})}):null,w!==void 0?T(At,{title:"Response Body",icon:T(Kr,{size:14,color:Qr}),defaultOpen:true,children:T(m,{style:E.dataViewerContainer,children:o?T(gr,{title:"",data:w,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s}):T(is,{})})}):g?T(At,{title:"Response Body",icon:T(Kr,{size:14,color:Qr}),defaultOpen:true,children:T(b,{style:E.emptyText,children:h?`Loading response body (${ct(e.responseSize??0)})\u2026`:"Response body unavailable"})}):null,T(At,{title:"Filter Options",icon:T(hu,{size:14,color:q.color.warning}),defaultOpen:false,children:T(m,{style:E.filterOptionsContainer,children:(()=>{let P="",A="";try{let p=new URL(e.url);P=p.hostname,A=p.pathname}catch{A=e.url}let v=t.has(P),c=t.has(A);return Q(gn,{children:[Q(F,{style:[E.filterOption,v&&E.filterOptionActive],onPress:()=>P&&r(P),children:[Q(m,{style:E.filterOptionLeft,children:[T(pu,{size:16,color:v?q.color.warning:q.color.textTertiary}),Q(m,{style:E.filterOptionContent,children:[T(b,{style:E.filterOptionLabel,children:"Ignore Domain"}),T(b,{style:E.filterOptionValue,children:P||"N/A"})]})]}),T(m,{style:[E.filterToggle,v&&E.filterToggleActive],children:T(b,{style:[E.filterToggleText,v&&E.filterToggleTextActive],children:v?"IGNORED":"IGNORE"})})]}),Q(F,{style:[E.filterOption,c&&E.filterOptionActive],onPress:()=>A&&r(A),children:[Q(m,{style:E.filterOptionLeft,children:[T(fu,{size:16,color:c?q.color.warning:q.color.textTertiary}),Q(m,{style:E.filterOptionContent,children:[T(b,{style:E.filterOptionLabel,children:"Ignore URL Pattern"}),T(b,{style:E.filterOptionValue,numberOfLines:1,children:A||"N/A"})]})]}),T(m,{style:[E.filterToggle,c&&E.filterToggleActive],children:T(b,{style:[E.filterToggleText,c&&E.filterToggleTextActive],children:c?"IGNORED":"IGNORE"})})]}),T(m,{style:E.filterInfoBox,children:T(b,{style:E.filterInfoText,children:"Ignored requests will be hidden from the network list. You can manage filters in the Filters tab."})})]})})()})})]}),T(mu,{visible:l,onClose:()=>a(false),featureName:"Copy Request Details",description:"Copy network request details to share or debug issues.",benefits:["Copy full request details including headers and body","Export to JSON, Markdown, or plain text","Share request data with teammates","Feed data to AI assistants for debugging"]})]})}),E=ve.create({container:{flex:1,backgroundColor:"transparent"},requestDetailsSection:{marginHorizontal:12,marginTop:12,backgroundColor:q.color.surface,borderRadius:8,borderWidth:1,borderColor:q.color.border,padding:12},httpHeader:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:12,flexWrap:"nowrap"},httpMethodBadge:{backgroundColor:q.color.infoSoft,paddingHorizontal:8,paddingVertical:4,borderRadius:4},httpMethod:{color:q.color.info,fontSize:11,fontWeight:"700",letterSpacing:.5},httpStatusBadge:{paddingHorizontal:8,paddingVertical:4,borderRadius:4},httpStatusText:{fontSize:11,fontWeight:"600"},pendingBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:q.color.warningSoft,paddingHorizontal:8,paddingVertical:4,borderRadius:4},pendingBadgeText:{color:q.color.warning,fontSize:11,fontWeight:"600"},httpDuration:{flexDirection:"row",alignItems:"center",gap:4},httpDurationText:{color:q.color.textSecondary,fontSize:11},overrideBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:6,paddingVertical:3,borderRadius:4,backgroundColor:q.color.warningSoft},overrideBadgeText:{color:q.color.warning,fontSize:10,fontWeight:"700"},copyFullButton:{marginLeft:"auto",flexShrink:0,padding:4},urlBreakdown:{backgroundColor:q.color.bg,borderRadius:4,padding:8},urlRow:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},urlDomain:{color:q.color.text,fontSize:12,fontWeight:"600",flex:1},urlProtocol:{color:q.color.textTertiary,fontSize:10},copyButton:{padding:4},urlPathRow:{paddingLeft:18},urlPath:{color:q.color.textSecondary,fontSize:11,fontFamily:Yt},urlQueryString:{color:q.color.info,fontSize:11,fontFamily:Yt},queryParamsCollapsible:{marginTop:8},queryParamsToggle:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:12,paddingVertical:10,backgroundColor:q.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:q.color.border,marginBottom:8},queryParamsToggleText:{flexGrow:0,color:q.color.text,fontSize:12,fontWeight:"600",letterSpacing:.3},timingSection:{marginHorizontal:12,marginTop:8,backgroundColor:q.color.surface,borderRadius:8,borderWidth:1,borderColor:q.color.border,padding:12},timingRow:{flexDirection:"row",alignItems:"center",gap:6,flexWrap:"wrap"},timingLabel:{color:q.color.textSecondary,fontSize:11},timingValue:{color:q.color.text,fontSize:11,fontWeight:"600"},timingExact:{color:q.color.textTertiary,fontSize:10,marginLeft:4},sizeRow:{flexDirection:"row",alignItems:"center",gap:16,marginLeft:"auto"},sizeItem:{flexDirection:"row",alignItems:"center",gap:4},sizeLabel:{color:q.color.textTertiary,fontSize:10},sizeValue:{color:q.color.info,fontSize:10,fontFamily:Yt,fontWeight:"600"},phaseDivider:{height:1,backgroundColor:q.color.border,marginTop:12,marginBottom:12},phaseList:{gap:8},phaseRow:{flexDirection:"row",alignItems:"center",gap:14},phaseLabelGroup:{width:150},phaseLabel:{fontSize:12,color:q.color.textSecondary},phaseHint:{fontSize:10,color:q.color.textTertiary},phaseTrack:{flex:1,height:7,borderRadius:4,backgroundColor:q.color.surfaceElevated,justifyContent:"center",overflow:"hidden"},phaseBar:{height:7,borderRadius:4},phaseValue:{width:72,textAlign:"right",fontSize:12,fontFamily:Yt,color:q.color.text},collapsibleSection:{marginHorizontal:12,marginTop:8,backgroundColor:q.color.surface,borderRadius:8,borderWidth:1,borderColor:q.color.border,overflow:"hidden"},collapsibleHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",padding:12,backgroundColor:q.color.surfaceElevated},collapsibleTitle:{flexDirection:"row",alignItems:"center",gap:8},collapsibleTitleText:{color:q.color.text,fontSize:13,fontWeight:"600"},collapsibleCount:{color:q.color.textTertiary,fontSize:11.5,fontFamily:Yt},collapsibleContent:{padding:12},dataViewerContainer:{marginTop:-12,marginHorizontal:-12,marginBottom:-12},bodyDeferred:{height:120},errorBox:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:q.color.dangerSoft,padding:8,borderRadius:4,marginTop:8},errorText:{color:q.color.danger,fontSize:11,flex:1},emptyText:{color:q.color.textTertiary,fontSize:12,fontStyle:"italic",textAlign:"center"},filterOptionsContainer:{gap:12},filterOption:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",backgroundColor:q.color.surfaceElevated,borderRadius:8,padding:12,borderWidth:1,borderColor:q.color.border},filterOptionActive:{backgroundColor:q.color.warningSoft,borderColor:q.color.warning+"33"},filterOptionLeft:{flexDirection:"row",alignItems:"center",gap:12,flex:1},filterOptionContent:{flex:1},filterOptionLabel:{color:q.color.textSecondary,fontSize:11,marginBottom:2,textTransform:"uppercase",letterSpacing:.5},filterOptionValue:{color:q.color.text,fontSize:13,fontFamily:Yt},filterToggle:{paddingHorizontal:10,paddingVertical:6,borderRadius:4,backgroundColor:q.color.bg,borderWidth:1,borderColor:q.color.border},filterToggleActive:{backgroundColor:q.color.warningSoft,borderColor:q.color.warning+"4D"},filterToggleText:{fontSize:10,fontWeight:"600",color:q.color.textTertiary,letterSpacing:.5},filterToggleTextActive:{color:q.color.warning},filterInfoBox:{backgroundColor:q.color.infoSoft,borderRadius:6,padding:10,borderWidth:1,borderColor:q.color.info+"33"},filterInfoText:{color:q.color.textSecondary,fontSize:11,lineHeight:16}});O();Se();import{DynamicFilterView as as,macOSColors as Ge,FileText as ls,FileCode as ds,Link as Pu,Zap as Lu,Settings as Bu,Hash as qu,Eye as Ou,ToolbarCopyButton as zu,formatRelativeTime as Du,useFeatureGate as Au,ProFeatureBanner as Hu,ExportPreview as Mu,monoFont as us}from"@buoy-gg/shared-ui/web";import{DataViewer as Nu}from"@buoy-gg/shared-ui/web/dataViewer";import{useCallback as ot,useMemo as Ht,useState as $u}from"react";import{Fragment as Fu,jsx as _e,jsxs as cs}from"react/jsx-runtime";var ju={includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:10,format:"markdown",filterMode:"all"},mr={urls:{includeMethod:true,includeStatus:false,includeDuration:false,includeTimestamp:false,includeClient:false,includeSizes:false,includeErrors:false,includeRequestHeaders:false,includeResponseHeaders:false,includeRequestBody:false,includeResponseBody:false,bodySizeThreshold:10,format:"plaintext",filterMode:"all"},llm:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:10,format:"markdown",filterMode:"all"},json:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:-1,format:"json",filterMode:"all"},full:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:-1,format:"markdown",filterMode:"all"}};function Wu(e){for(let[t,r]of Object.entries(mr))if(Object.keys(r).every(o=>r[o]===e[o]))return t;return null}var Vu=100*1024,Uu=500*1024;function _u(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Xu({settings:e,onSettingsChange:t,events:r=[]}){let{isPro:o}=Au(),n=hn(),[i,s]=$u(false),l=r.length>0,a=Ht(()=>{if(!l)return null;let c=r.map(p=>typeof p.timestamp=="number"?p.timestamp:new Date(p.timestamp).getTime());return Math.max(...c)},[r,l]),u=Ht(()=>Wu(e),[e]),d=ot(()=>{t(mr.urls)},[t]),g=ot(()=>{t(mr.llm)},[t]),x=ot(()=>{t(mr.json)},[t]),y=ot(()=>{t(mr.full)},[t]),R=ot((c,p)=>{let[f,S]=c.split("::");if(f==="preset"){switch(S){case"urls":d();break;case"llm":g();break;case"json":x();break;case"full":y();break}return}if(f==="requestInfo"){t({...e,[S]:!e[S]});return}if(f==="headers"){t({...e,[S]:!e[S]});return}if(f==="body"){t(S==="bodySizeThreshold"?{...e,bodySizeThreshold:p}:{...e,[S]:!e[S]});return}if(f==="format"){t({...e,format:p});return}f==="filter"&&t({...e,filterMode:p})},[e,t,d,g,x,y]),h=Ht(()=>({method:"POST",url:"https://api.example.com/v1/users",status:201,duration:342,timestamp:new Date().toISOString(),requestHeaders:{"Content-Type":"application/json",Authorization:"Bearer ***"},responseHeaders:{"Content-Type":"application/json","X-Request-ID":"abc123"},requestBody:{name:"John Doe",email:"john@example.com"},responseBody:{id:"user_123",name:"John Doe",email:"john@example.com",createdAt:"2025-01-10T12:00:00Z"}}),[]),C=Ht(()=>l?r:[h],[l,r,h]),k=Ht(()=>{let c=l?r:[h],p=0;for(let f of c){if(e.includeMethod&&(p+=(f.url?.length||0)+10),e.includeStatus&&(p+=30),e.includeTimestamp&&(p+=30),e.includeRequestHeaders)try{p+=JSON.stringify(f.requestHeaders||{}).length}catch{p+=100}if(e.includeRequestBody){let S="requestBody"in f?f.requestBody:f.requestData;try{p+=JSON.stringify(S||{}).length}catch{p+=100}}if(e.includeResponseBody){let S="responseBody"in f?f.responseBody:f.responseData;try{p+=JSON.stringify(S||{}).length}catch{p+=100}}}return p},[l,r,h,e]),w=Ht(()=>k>=Uu?"danger":k>=Vu?"warning":"none",[k]),I=ot(()=>{let c=l?r:[h],{format:p,includeMethod:f,includeStatus:S,includeTimestamp:D,includeRequestHeaders:H,includeRequestBody:V,includeResponseBody:Z}=e,Y=L=>{let M={};return f&&(M.method=L.method,M.url=L.url),S&&(M.status=L.status,M.duration=L.duration),D&&(M.timestamp=L.timestamp),H&&(M.requestHeaders=L.requestHeaders),V&&(M.requestBody="requestBody"in L?L.requestBody:L.requestData),Z&&(M.responseBody="responseBody"in L?L.responseBody:L.responseData),M};if(p==="json"){let L=c.map(Y);return JSON.stringify(L,null,2)}return p==="markdown"?c.map((L,M)=>{let N=[];N.push(`# Request ${M+1}`),f&&N.push(`
44
- **${L.method}** ${L.url}`);let J=[];if(S&&(J.push(`**Status:** ${L.status}`),J.push(`**Duration:** ${L.duration}ms`)),D&&J.push(`**Timestamp:** ${L.timestamp}`),J.length>0&&N.push(`
43
+ `};return te(oi,{children:[te(ht,{keyboardShouldPersistTaps:"handled",testID:"buoy-network-detail-scroll",style:O.container,children:[te(S,{style:O.requestDetailsSection,children:[te(S,{style:O.httpHeader,children:[z(S,{style:O.httpMethodBadge,children:z(b,{style:O.httpMethod,children:e.method})}),e.status?z(S,{style:[O.httpStatusBadge,{backgroundColor:`${n?.color}20`}],children:te(b,{style:[O.httpStatusText,{color:n?.color}],children:[n?.text," ",n?.meaning]})}):i?te(S,{style:O.pendingBadge,children:[z(ei,{size:10,color:$.color.warning}),z(b,{style:O.pendingBadgeText,children:"Pending"})]}):null,e.condition&&te(b,{style:{color:"#FFCC66"},children:["Conditions: ",e.condition.profile," (+",e.condition.delayMs," ms)"]}),e.condition?.uploadCap?.note&&z(b,{testID:"buoy-network-upload-cap-detail",style:{color:"#FFCC66"},children:e.condition.uploadCap.note}),e.duration?te(S,{style:O.httpDuration,children:[z(ei,{size:10,color:$.color.textTertiary}),z(b,{style:O.httpDurationText,children:No(e.duration)})]}):null,e.override?te(S,{style:O.overrideBadge,children:[z(Fu,{size:10,color:$.color.warning}),z(b,{style:O.overrideBadgeText,children:e.override.ruleName||"Overridden"})]}):null,s?z(ra,{value:B,buttonStyle:O.copyFullButton}):z(W,{style:O.copyFullButton,onPress:()=>a(true),activeOpacity:.7,children:z(ta,{size:14,color:$.color.textSecondary})})]}),z(th,{url:e.url,requestData:h,operationName:e.operationName,graphqlVariables:e.graphqlVariables,requestClient:e.requestClient,isPro:s,onUpgradePress:()=>a(true)}),e.error?te(S,{style:O.errorBox,children:[z(Au,{size:12,color:$.color.danger}),z(b,{style:O.errorText,children:e.error})]}):null]}),te(S,{style:O.timingSection,children:[te(S,{style:O.timingRow,children:[z(ei,{size:12,color:$.color.textSecondary}),z(b,{style:O.timingLabel,children:"Started:"}),z(b,{style:O.timingValue,children:Vu(e.timestamp)}),te(b,{style:O.timingExact,children:["(",new Date(e.timestamp).toLocaleTimeString(),")"]}),e.requestSize||e.responseSize?te(S,{style:O.sizeRow,children:[e.requestSize!==void 0?te(S,{style:O.sizeItem,children:[z(Qs,{size:10,color:$.color.info}),z(b,{style:O.sizeLabel,children:"Sent:"}),z(b,{style:O.sizeValue,children:Ot(e.requestSize)})]}):null,e.responseSize!==void 0?te(S,{style:O.sizeItem,children:[z(Ys,{size:10,color:Mo}),z(b,{style:O.sizeLabel,children:"Received:"}),z(b,{style:O.sizeValue,children:Ot(e.responseSize)})]}):null]}):null]}),e.timings?te(oi,{children:[z(S,{style:O.phaseDivider}),z(eh,{timings:e.timings,total:e.duration??e.timings.ttfb+e.timings.download})]}):null]}),z(ir,{title:"Request Headers",icon:z(Qs,{size:14,color:$.color.info}),defaultOpen:false,count:Object.keys(x).length,children:Object.keys(x).length>0?z(S,{style:O.dataViewerContainer,children:z(Vr,{title:"",data:x,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s})}):z(b,{style:O.emptyText,children:"No request headers"})}),z(ir,{title:"Response Headers",icon:z(Ys,{size:14,color:Mo}),defaultOpen:false,count:Object.keys(I).length,children:Object.keys(I).length>0?z(S,{style:O.dataViewerContainer,children:z(Vr,{title:"",data:I,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s})}):z(b,{style:O.emptyText,children:"No response headers yet"})}),h!==void 0?z(ir,{title:"Request Body",icon:z(Do,{size:14,color:$.color.accent}),defaultOpen:false,children:z(S,{style:O.dataViewerContainer,children:o?z(Vr,{title:"",data:h,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s}):z(aa,{})})}):c?z(ir,{title:"Request Body",icon:z(Do,{size:14,color:$.color.accent}),defaultOpen:true,children:z(b,{style:O.emptyText,children:u?`Loading request body (${Ot(e.requestSize??0)})\u2026`:"Request body unavailable"})}):null,m!==void 0?z(ir,{title:"Response Body",icon:z(Do,{size:14,color:Mo}),defaultOpen:true,children:z(S,{style:O.dataViewerContainer,children:o?z(Vr,{title:"",data:m,showTypeFilter:true,rawMode:true,initialExpanded:true,disableCopy:!s}):z(aa,{})})}):y?z(ir,{title:"Response Body",icon:z(Do,{size:14,color:Mo}),defaultOpen:true,children:z(b,{style:O.emptyText,children:u?`Loading response body (${Ot(e.responseSize??0)})\u2026`:"Response body unavailable"})}):null,z(ir,{title:"Filter Options",icon:z($u,{size:14,color:$.color.warning}),defaultOpen:false,children:z(S,{style:O.filterOptionsContainer,children:(()=>{let E="",D="";try{let v=new URL(e.url);E=v.hostname,D=v.pathname}catch{D=e.url}let k=t.has(E),g=t.has(D);return te(oi,{children:[te(W,{style:[O.filterOption,k&&O.filterOptionActive],onPress:()=>E&&r(E),children:[te(S,{style:O.filterOptionLeft,children:[z(Hu,{size:16,color:k?$.color.warning:$.color.textTertiary}),te(S,{style:O.filterOptionContent,children:[z(b,{style:O.filterOptionLabel,children:"Ignore Domain"}),z(b,{style:O.filterOptionValue,children:E||"N/A"})]})]}),z(S,{style:[O.filterToggle,k&&O.filterToggleActive],children:z(b,{style:[O.filterToggleText,k&&O.filterToggleTextActive],children:k?"IGNORED":"IGNORE"})})]}),te(W,{style:[O.filterOption,g&&O.filterOptionActive],onPress:()=>D&&r(D),children:[te(S,{style:O.filterOptionLeft,children:[z(ju,{size:16,color:g?$.color.warning:$.color.textTertiary}),te(S,{style:O.filterOptionContent,children:[z(b,{style:O.filterOptionLabel,children:"Ignore URL Pattern"}),z(b,{style:O.filterOptionValue,numberOfLines:1,children:D||"N/A"})]})]}),z(S,{style:[O.filterToggle,g&&O.filterToggleActive],children:z(b,{style:[O.filterToggleText,g&&O.filterToggleTextActive],children:g?"IGNORED":"IGNORE"})})]}),z(S,{style:O.filterInfoBox,children:z(b,{style:O.filterInfoText,children:"Ignored requests will be hidden from the network list. You can manage filters in the Filters tab."})})]})})()})})]}),z(_u,{visible:d,onClose:()=>a(false),featureName:"Copy Request Details",description:"Copy network request details to share or debug issues.",benefits:["Copy full request details including headers and body","Export to JSON, Markdown, or plain text","Share request data with teammates","Feed data to AI assistants for debugging"]})]})}),O=se.create({container:{flex:1,backgroundColor:"transparent"},requestDetailsSection:{marginHorizontal:12,marginTop:12,backgroundColor:$.color.surface,borderRadius:8,borderWidth:1,borderColor:$.color.border,padding:12},httpHeader:{flexDirection:"row",alignItems:"center",gap:8,marginBottom:12,flexWrap:"nowrap"},httpMethodBadge:{backgroundColor:$.color.infoSoft,paddingHorizontal:8,paddingVertical:4,borderRadius:4},httpMethod:{color:$.color.info,fontSize:11,fontWeight:"700",letterSpacing:.5},httpStatusBadge:{paddingHorizontal:8,paddingVertical:4,borderRadius:4},httpStatusText:{fontSize:11,fontWeight:"600"},pendingBadge:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:$.color.warningSoft,paddingHorizontal:8,paddingVertical:4,borderRadius:4},pendingBadgeText:{color:$.color.warning,fontSize:11,fontWeight:"600"},httpDuration:{flexDirection:"row",alignItems:"center",gap:4},httpDurationText:{color:$.color.textSecondary,fontSize:11},overrideBadge:{flexDirection:"row",alignItems:"center",gap:4,paddingHorizontal:6,paddingVertical:3,borderRadius:4,backgroundColor:$.color.warningSoft},overrideBadgeText:{color:$.color.warning,fontSize:10,fontWeight:"700"},copyFullButton:{marginLeft:"auto",flexShrink:0,padding:4},urlBreakdown:{backgroundColor:$.color.bg,borderRadius:4,padding:8},urlRow:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},urlDomain:{color:$.color.text,fontSize:12,fontWeight:"600",flex:1},urlProtocol:{color:$.color.textTertiary,fontSize:10},copyButton:{padding:4},urlPathRow:{paddingLeft:18},urlPath:{color:$.color.textSecondary,fontSize:11,fontFamily:Sr},urlQueryString:{color:$.color.info,fontSize:11,fontFamily:Sr},queryParamsCollapsible:{marginTop:8},queryParamsToggle:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:12,paddingVertical:10,backgroundColor:$.color.surfaceElevated,borderRadius:8,borderWidth:1,borderColor:$.color.border,marginBottom:8},queryParamsToggleText:{flexGrow:0,color:$.color.text,fontSize:12,fontWeight:"600",letterSpacing:.3},timingSection:{marginHorizontal:12,marginTop:8,backgroundColor:$.color.surface,borderRadius:8,borderWidth:1,borderColor:$.color.border,padding:12},timingRow:{flexDirection:"row",alignItems:"center",gap:6,flexWrap:"wrap"},timingLabel:{color:$.color.textSecondary,fontSize:11},timingValue:{color:$.color.text,fontSize:11,fontWeight:"600"},timingExact:{color:$.color.textTertiary,fontSize:10,marginLeft:4},sizeRow:{flexDirection:"row",alignItems:"center",gap:16,marginLeft:"auto"},sizeItem:{flexDirection:"row",alignItems:"center",gap:4},sizeLabel:{color:$.color.textTertiary,fontSize:10},sizeValue:{color:$.color.info,fontSize:10,fontFamily:Sr,fontWeight:"600"},phaseDivider:{height:1,backgroundColor:$.color.border,marginTop:12,marginBottom:12},phaseList:{gap:8},phaseRow:{flexDirection:"row",alignItems:"center",gap:14},phaseLabelGroup:{width:150},phaseLabel:{fontSize:12,color:$.color.textSecondary},phaseHint:{fontSize:10,color:$.color.textTertiary},phaseTrack:{flex:1,height:7,borderRadius:4,backgroundColor:$.color.surfaceElevated,justifyContent:"center",overflow:"hidden"},phaseBar:{height:7,borderRadius:4},phaseValue:{width:72,textAlign:"right",fontSize:12,fontFamily:Sr,color:$.color.text},collapsibleSection:{marginHorizontal:12,marginTop:8,backgroundColor:$.color.surface,borderRadius:8,borderWidth:1,borderColor:$.color.border,overflow:"hidden"},collapsibleHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",padding:12,backgroundColor:$.color.surfaceElevated},collapsibleTitle:{flexDirection:"row",alignItems:"center",gap:8},collapsibleTitleText:{color:$.color.text,fontSize:13,fontWeight:"600"},collapsibleCount:{color:$.color.textTertiary,fontSize:11.5,fontFamily:Sr},collapsibleContent:{padding:12},dataViewerContainer:{marginTop:-12,marginHorizontal:-12,marginBottom:-12},bodyDeferred:{height:120},errorBox:{flexDirection:"row",alignItems:"center",gap:6,backgroundColor:$.color.dangerSoft,padding:8,borderRadius:4,marginTop:8},errorText:{color:$.color.danger,fontSize:11,flex:1},emptyText:{color:$.color.textTertiary,fontSize:12,fontStyle:"italic",textAlign:"center"},filterOptionsContainer:{gap:12},filterOption:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",backgroundColor:$.color.surfaceElevated,borderRadius:8,padding:12,borderWidth:1,borderColor:$.color.border},filterOptionActive:{backgroundColor:$.color.warningSoft,borderColor:$.color.warning+"33"},filterOptionLeft:{flexDirection:"row",alignItems:"center",gap:12,flex:1},filterOptionContent:{flex:1},filterOptionLabel:{color:$.color.textSecondary,fontSize:11,marginBottom:2,textTransform:"uppercase",letterSpacing:.5},filterOptionValue:{color:$.color.text,fontSize:13,fontFamily:Sr},filterToggle:{paddingHorizontal:10,paddingVertical:6,borderRadius:4,backgroundColor:$.color.bg,borderWidth:1,borderColor:$.color.border},filterToggleActive:{backgroundColor:$.color.warningSoft,borderColor:$.color.warning+"4D"},filterToggleText:{fontSize:10,fontWeight:"600",color:$.color.textTertiary,letterSpacing:.5},filterToggleTextActive:{color:$.color.warning},filterInfoBox:{backgroundColor:$.color.infoSoft,borderRadius:6,padding:10,borderWidth:1,borderColor:$.color.info+"33"},filterInfoText:{color:$.color.textSecondary,fontSize:11,lineHeight:16}});q();he();import{DynamicFilterView as da,macOSColors as yt,FileText as ca,FileCode as ua,Link as rh,Zap as oh,Settings as nh,Hash as ih,Eye as sh,ToolbarCopyButton as ah,formatRelativeTime as lh,useFeatureGate as dh,ProFeatureBanner as ch,ExportPreview as uh,monoFont as ha}from"@buoy-gg/shared-ui/web";import{DataViewer as hh}from"@buoy-gg/shared-ui/web/dataViewer";import{useCallback as kt,useMemo as sr,useState as ph}from"react";import{Fragment as fh,jsx as dt,jsxs as pa}from"react/jsx-runtime";var gh={includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:10,format:"markdown",filterMode:"all"},Ur={urls:{includeMethod:true,includeStatus:false,includeDuration:false,includeTimestamp:false,includeClient:false,includeSizes:false,includeErrors:false,includeRequestHeaders:false,includeResponseHeaders:false,includeRequestBody:false,includeResponseBody:false,bodySizeThreshold:10,format:"plaintext",filterMode:"all"},llm:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:10,format:"markdown",filterMode:"all"},json:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:-1,format:"json",filterMode:"all"},full:{includeMethod:true,includeStatus:true,includeDuration:true,includeTimestamp:true,includeClient:true,includeSizes:true,includeErrors:true,includeRequestHeaders:true,includeResponseHeaders:true,includeRequestBody:true,includeResponseBody:true,bodySizeThreshold:-1,format:"markdown",filterMode:"all"}};function yh(e){for(let[t,r]of Object.entries(Ur))if(Object.keys(r).every(o=>r[o]===e[o]))return t;return null}var mh=100*1024,bh=500*1024;function vh(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wh({settings:e,onSettingsChange:t,events:r=[]}){let{isPro:o}=dh(),n=Zn(),[i,s]=ph(false),d=r.length>0,a=sr(()=>{if(!d)return null;let g=r.map(v=>typeof v.timestamp=="number"?v.timestamp:new Date(v.timestamp).getTime());return Math.max(...g)},[r,d]),l=sr(()=>yh(e),[e]),c=kt(()=>{t(Ur.urls)},[t]),y=kt(()=>{t(Ur.llm)},[t]),w=kt(()=>{t(Ur.json)},[t]),p=kt(()=>{t(Ur.full)},[t]),C=kt((g,v)=>{let[f,T]=g.split("::");if(f==="preset"){switch(T){case"urls":c();break;case"llm":y();break;case"json":w();break;case"full":p();break}return}if(f==="requestInfo"){t({...e,[T]:!e[T]});return}if(f==="headers"){t({...e,[T]:!e[T]});return}if(f==="body"){t(T==="bodySizeThreshold"?{...e,bodySizeThreshold:v}:{...e,[T]:!e[T]});return}if(f==="format"){t({...e,format:v});return}f==="filter"&&t({...e,filterMode:v})},[e,t,c,y,w,p]),u=sr(()=>({method:"POST",url:"https://api.example.com/v1/users",status:201,duration:342,timestamp:new Date().toISOString(),requestHeaders:{"Content-Type":"application/json",Authorization:"Bearer ***"},responseHeaders:{"Content-Type":"application/json","X-Request-ID":"abc123"},requestBody:{name:"John Doe",email:"john@example.com"},responseBody:{id:"user_123",name:"John Doe",email:"john@example.com",createdAt:"2025-01-10T12:00:00Z"}}),[]),R=sr(()=>d?r:[u],[d,r,u]),h=sr(()=>{let g=d?r:[u],v=0;for(let f of g){if(e.includeMethod&&(v+=(f.url?.length||0)+10),e.includeStatus&&(v+=30),e.includeTimestamp&&(v+=30),e.includeRequestHeaders)try{v+=JSON.stringify(f.requestHeaders||{}).length}catch{v+=100}if(e.includeRequestBody){let T="requestBody"in f?f.requestBody:f.requestData;try{v+=JSON.stringify(T||{}).length}catch{v+=100}}if(e.includeResponseBody){let T="responseBody"in f?f.responseBody:f.responseData;try{v+=JSON.stringify(T||{}).length}catch{v+=100}}}return v},[d,r,u,e]),m=sr(()=>h>=bh?"danger":h>=mh?"warning":"none",[h]),x=kt(()=>{let g=d?r:[u],{format:v,includeMethod:f,includeStatus:T,includeTimestamp:M,includeRequestHeaders:P,includeRequestBody:A,includeResponseBody:_}=e,F=L=>{let H={};return f&&(H.method=L.method,H.url=L.url),T&&(H.status=L.status,H.duration=L.duration),M&&(H.timestamp=L.timestamp),P&&(H.requestHeaders=L.requestHeaders),A&&(H.requestBody="requestBody"in L?L.requestBody:L.requestData),_&&(H.responseBody="responseBody"in L?L.responseBody:L.responseData),H};if(v==="json"){let L=g.map(F);return JSON.stringify(L,null,2)}return v==="markdown"?g.map((L,H)=>{let j=[];j.push(`# Request ${H+1}`),f&&j.push(`
44
+ **${L.method}** ${L.url}`);let J=[];if(T&&(J.push(`**Status:** ${L.status}`),J.push(`**Duration:** ${L.duration}ms`)),M&&J.push(`**Timestamp:** ${L.timestamp}`),J.length>0&&j.push(`
45
45
  `+J.join(`
46
- `)),H){let le=L.requestHeaders||{};N.push(`
46
+ `)),P){let ee=L.requestHeaders||{};j.push(`
47
47
  ## Request Headers
48
48
  \`\`\`json
49
- ${JSON.stringify(le,null,2)}
50
- \`\`\``)}if(V){let le="requestBody"in L?L.requestBody:L.requestData;N.push(`
49
+ ${JSON.stringify(ee,null,2)}
50
+ \`\`\``)}if(A){let ee="requestBody"in L?L.requestBody:L.requestData;j.push(`
51
51
  ## Request Body
52
52
  \`\`\`json
53
- ${JSON.stringify(le||{},null,2)}
54
- \`\`\``)}if(Z){let le="responseBody"in L?L.responseBody:L.responseData;N.push(`
53
+ ${JSON.stringify(ee||{},null,2)}
54
+ \`\`\``)}if(_){let ee="responseBody"in L?L.responseBody:L.responseData;j.push(`
55
55
  ## Response Body
56
56
  \`\`\`json
57
- ${JSON.stringify(le||{},null,2)}
58
- \`\`\``)}return N.join(`
57
+ ${JSON.stringify(ee||{},null,2)}
58
+ \`\`\``)}return j.join(`
59
59
  `)}).join(`
60
60
 
61
61
  ---
62
62
 
63
- `)||"No data included":c.map((L,M)=>{let N=[];if(N.push(`Request ${M+1}:`),f&&N.push(`${L.method} ${L.url}`),S&&(N.push(`Status: ${L.status}`),N.push(`Duration: ${L.duration}ms`)),D&&N.push(`Timestamp: ${L.timestamp}`),V){let J="requestBody"in L?L.requestBody:L.requestData;N.push(`
64
- Request:`),N.push(JSON.stringify(J||{},null,2))}if(Z){let J="responseBody"in L?L.responseBody:L.responseData;N.push(`
65
- Response:`),N.push(JSON.stringify(J||{},null,2))}return N.join(`
63
+ `)||"No data included":g.map((L,H)=>{let j=[];if(j.push(`Request ${H+1}:`),f&&j.push(`${L.method} ${L.url}`),T&&(j.push(`Status: ${L.status}`),j.push(`Duration: ${L.duration}ms`)),M&&j.push(`Timestamp: ${L.timestamp}`),A){let J="requestBody"in L?L.requestBody:L.requestData;j.push(`
64
+ Request:`),j.push(JSON.stringify(J||{},null,2))}if(_){let J="responseBody"in L?L.responseBody:L.responseData;j.push(`
65
+ Response:`),j.push(JSON.stringify(J||{},null,2))}return j.join(`
66
66
  `)}).join(`
67
67
 
68
68
  ---
69
69
 
70
- `)||"No data included"},[l,r,h,e]),z=ot(()=>{let c=l?r:[h],{format:p,includeMethod:f,includeStatus:S,includeTimestamp:D,includeRequestHeaders:H,includeRequestBody:V,includeResponseBody:Z}=e,Y=M=>{let N={};return f&&(N.method=M.method,N.url=M.url),S&&(N.status=M.status,N.duration=M.duration),D&&(N.timestamp=M.timestamp),H&&(N.requestHeaders=M.requestHeaders),V&&(N.requestBody="requestBody"in M?M.requestBody:M.requestData),Z&&(N.responseBody="responseBody"in M?M.responseBody:M.responseData),N};if(p==="json"){let M=c.map(Y);return _e(Nu,{data:M,title:"",showTypeFilter:false})}if(p==="markdown"){let M=c.map((N,J)=>{let le=[];le.push(`# Request ${J+1}`),f&&le.push(`
71
- **${N.method}** ${N.url}`);let ne=[];if(S&&(ne.push(`**Status:** ${N.status}`),ne.push(`**Duration:** ${N.duration}ms`)),D&&ne.push(`**Timestamp:** ${N.timestamp}`),ne.length>0&&le.push(`
72
- `+ne.join(`
73
- `)),H){let K=N.requestHeaders||{};le.push(`
70
+ `)||"No data included"},[d,r,u,e]),I=kt(()=>{let g=d?r:[u],{format:v,includeMethod:f,includeStatus:T,includeTimestamp:M,includeRequestHeaders:P,includeRequestBody:A,includeResponseBody:_}=e,F=H=>{let j={};return f&&(j.method=H.method,j.url=H.url),T&&(j.status=H.status,j.duration=H.duration),M&&(j.timestamp=H.timestamp),P&&(j.requestHeaders=H.requestHeaders),A&&(j.requestBody="requestBody"in H?H.requestBody:H.requestData),_&&(j.responseBody="responseBody"in H?H.responseBody:H.responseData),j};if(v==="json"){let H=g.map(F);return dt(hh,{data:H,title:"",showTypeFilter:false})}if(v==="markdown"){let H=g.map((j,J)=>{let ee=[];ee.push(`# Request ${J+1}`),f&&ee.push(`
71
+ **${j.method}** ${j.url}`);let Z=[];if(T&&(Z.push(`**Status:** ${j.status}`),Z.push(`**Duration:** ${j.duration}ms`)),M&&Z.push(`**Timestamp:** ${j.timestamp}`),Z.length>0&&ee.push(`
72
+ `+Z.join(`
73
+ `)),P){let Y=j.requestHeaders||{};ee.push(`
74
74
  ## Request Headers
75
75
  \`\`\`json
76
- ${JSON.stringify(K,null,2)}
77
- \`\`\``)}if(V){let K="requestBody"in N?N.requestBody:N.requestData;le.push(`
76
+ ${JSON.stringify(Y,null,2)}
77
+ \`\`\``)}if(A){let Y="requestBody"in j?j.requestBody:j.requestData;ee.push(`
78
78
  ## Request Body
79
79
  \`\`\`json
80
- ${JSON.stringify(K||{},null,2)}
81
- \`\`\``)}if(Z){let K="responseBody"in N?N.responseBody:N.responseData;le.push(`
80
+ ${JSON.stringify(Y||{},null,2)}
81
+ \`\`\``)}if(_){let Y="responseBody"in j?j.responseBody:j.responseData;ee.push(`
82
82
  ## Response Body
83
83
  \`\`\`json
84
- ${JSON.stringify(K||{},null,2)}
85
- \`\`\``)}return le.join(`
84
+ ${JSON.stringify(Y||{},null,2)}
85
+ \`\`\``)}return ee.join(`
86
86
  `)}).join(`
87
87
 
88
88
  ---
89
89
 
90
- `);return _e(yt,{keyboardShouldPersistTaps:"handled",style:Mt.previewScroll,nestedScrollEnabled:true,children:_e(b,{style:Mt.markdownText,selectable:o,children:M||"No data included"})})}let L=c.map((M,N)=>{let J=[];if(J.push(`Request ${N+1}:`),f&&J.push(`${M.method} ${M.url}`),S&&(J.push(`Status: ${M.status}`),J.push(`Duration: ${M.duration}ms`)),D&&J.push(`Timestamp: ${M.timestamp}`),V){let le="requestBody"in M?M.requestBody:M.requestData;J.push(`
91
- Request:`),J.push(JSON.stringify(le||{},null,2))}if(Z){let le="responseBody"in M?M.responseBody:M.responseData;J.push(`
92
- Response:`),J.push(JSON.stringify(le||{},null,2))}return J.join(`
90
+ `);return dt(ht,{keyboardShouldPersistTaps:"handled",style:ar.previewScroll,nestedScrollEnabled:true,children:dt(b,{style:ar.markdownText,selectable:o,children:H||"No data included"})})}let L=g.map((H,j)=>{let J=[];if(J.push(`Request ${j+1}:`),f&&J.push(`${H.method} ${H.url}`),T&&(J.push(`Status: ${H.status}`),J.push(`Duration: ${H.duration}ms`)),M&&J.push(`Timestamp: ${H.timestamp}`),A){let ee="requestBody"in H?H.requestBody:H.requestData;J.push(`
91
+ Request:`),J.push(JSON.stringify(ee||{},null,2))}if(_){let ee="responseBody"in H?H.responseBody:H.responseData;J.push(`
92
+ Response:`),J.push(JSON.stringify(ee||{},null,2))}return J.join(`
93
93
  `)}).join(`
94
94
 
95
95
  ---
96
96
 
97
- `);return _e(yt,{keyboardShouldPersistTaps:"handled",style:Mt.previewScroll,nestedScrollEnabled:true,children:_e(b,{style:Mt.plaintextText,selectable:o,children:L||"No data included"})})},[e,l,r,h,o]),$=ot(()=>{let c=(l?r:[h]).length;return _e(Mu,{expanded:i,onExpandedChange:s,summary:`${c} request${c!==1?"s":""} \u2022 ~${_u(k)}`,warningLevel:w,warningText:{warning:"Large payload - preview may be slow",danger:"Very large payload - may cause performance issues"},renderBody:z})},[e,l,r,h,i,k,w,z]),P=ot(()=>{let c=l&&a?`Live data \u2022 Updated ${Du(a,n)}`:"Mock data (no events captured)";return cs(Fu,{children:[_e(b,{style:Mt.statusLabel,children:c}),_e(zu,{value:I()})]})},[l,a,n,I]),A=ot(()=>$(),[$]),v=Ht(()=>({sections:[{id:"presets",title:"Presets",type:"custom",data:[{id:"preset::urls",label:"URLs",icon:Pu,color:Ge.semantic.info,value:"urls",isActive:u==="urls"},{id:"preset::llm",label:"LLM",icon:Lu,color:Ge.semantic.success,value:"llm",isActive:u==="llm"},{id:"preset::json",label:"JSON",icon:ds,color:Ge.semantic.warning,value:"json",isActive:u==="json"},{id:"preset::full",label:"Full",icon:ls,color:Ge.semantic.info,value:"full",isActive:u==="full"},{id:"preset::custom",label:"Custom",icon:Bu,color:Ge.text.secondary,value:"custom",isActive:u===null}]},{id:"include",title:"Include",type:"custom",data:[{id:"requestInfo::includeMethod",label:"URL",value:"includeMethod",isActive:e.includeMethod},{id:"requestInfo::includeStatus",label:"Status",value:"includeStatus",isActive:e.includeStatus},{id:"requestInfo::includeTimestamp",label:"Time",value:"includeTimestamp",isActive:e.includeTimestamp},{id:"headers::includeRequestHeaders",label:"Headers",value:"includeRequestHeaders",isActive:e.includeRequestHeaders},{id:"body::includeRequestBody",label:"Req Body",value:"includeRequestBody",isActive:e.includeRequestBody},{id:"body::includeResponseBody",label:"Res Body",value:"includeResponseBody",isActive:e.includeResponseBody},{id:"requestInfo::includeErrors",label:"Errors",value:"includeErrors",isActive:e.includeErrors}]},{id:"format",title:"Format",type:"custom",data:[{id:"format::markdown",label:"Markdown",icon:ls,color:Ge.semantic.info,value:"markdown",isActive:e.format==="markdown"},{id:"format::json",label:"JSON",icon:ds,color:Ge.semantic.warning,value:"json",isActive:e.format==="json"},{id:"format::plaintext",label:"Text",icon:qu,color:Ge.text.secondary,value:"plaintext",isActive:e.format==="plaintext"}]}],previewSection:{enabled:true,title:"PREVIEW",icon:Ou,content:A,headerActions:P},onFilterChange:R}),[e,R,A,P,u]);return o?_e(as,{...v}):cs(m,{style:Mt.gatedContainer,children:[_e(Hu,{featureName:"Network Export",description:"Export network requests to share with your team, debug APIs, or feed into AI tools.",benefits:["Export to JSON, Markdown, or plain text","Customizable copy presets (URLs only, LLM-ready, full data)","Share request details with teammates","Feed network data directly to AI assistants"]}),_e(m,{style:Mt.gatedPreview,children:_e(as,{...v})})]})}var Mt=ve.create({previewScroll:{maxHeight:300},markdownText:{fontFamily:us,fontSize:11,color:Ge.text.primary,lineHeight:18},plaintextText:{fontFamily:us,fontSize:11,color:Ge.text.primary,lineHeight:18},statusLabel:{fontSize:11,fontWeight:"600",color:Ge.text.muted,marginRight:8},gatedContainer:{flex:1,padding:12},gatedPreview:{flex:1}});O();Se();import{Bookmark as hs,CheckCircle as Ju,XCircle as Gu,Clock as Ku,Copy as Yu,Pin as Zu,Trash2 as Qu,CopyButton as ec,macOSColors as bt,night as ae,useLimit as tc,monoFont as ps}from"@buoy-gg/shared-ui/web";O();import{isBuoyRequest as fs,getAccountAccess as ys}from"@buoy-gg/shared-ui/web";import{BaseEventStore as rc}from"@buoy-gg/shared-ui/web";O();function gs(e){if(!e||typeof e!="object")return null;if("operationName"in e&&e.operationName){let t=e.operationName;if(typeof t=="string"&&t.trim().length>0)return t.trim()}if("query"in e&&typeof e.query=="string"){let t=e.query.match(/(?:query|mutation|subscription)\s+(\w+)/);if(t&&t[1])return t[1]}return null}O();import{isBuoyRequest as oc,devToolsStorageKeys as ms,persistentStorage as bs}from"@buoy-gg/shared-ui/web";import{TIER_LIMITS as nc}from"@buoy-gg/shared-ui/web";var mn=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,eo=25,vt=50,vs=nc["network.saved"].free,St=16*1024,Ss=512*1024;function bn(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.id=="string"&&typeof t.url=="string"&&!oc(t.url)}var ic=800;function to(e,t){if(!t)return{pinned:false,saved:false};let r=e.pinnedLiveIds.has(t),o=e.savedLiveIds.has(t);if(r||o)return{pinned:r,saved:o};let n=e.records.find(i=>i.event.id===t);return n?{pinned:n.pinned,saved:n.saved}:{pinned:false,saved:false}}var sc={records:[],pinnedEvents:[],savedRecords:[],pinnedLiveIds:new Set,savedLiveIds:new Set};function ws(e){if(e==null)return{value:e,truncated:false};if(typeof e=="string")return e.length<=St?{value:e,truncated:false}:{value:`${e.slice(0,St)}
97
+ `);return dt(ht,{keyboardShouldPersistTaps:"handled",style:ar.previewScroll,nestedScrollEnabled:true,children:dt(b,{style:ar.plaintextText,selectable:o,children:L||"No data included"})})},[e,d,r,u,o]),B=kt(()=>{let g=(d?r:[u]).length;return dt(uh,{expanded:i,onExpandedChange:s,summary:`${g} request${g!==1?"s":""} \u2022 ~${vh(h)}`,warningLevel:m,warningText:{warning:"Large payload - preview may be slow",danger:"Very large payload - may cause performance issues"},renderBody:I})},[e,d,r,u,i,h,m,I]),E=kt(()=>{let g=d&&a?`Live data \u2022 Updated ${lh(a,n)}`:"Mock data (no events captured)";return pa(fh,{children:[dt(b,{style:ar.statusLabel,children:g}),dt(ah,{value:x()})]})},[d,a,n,x]),D=kt(()=>B(),[B]),k=sr(()=>({sections:[{id:"presets",title:"Presets",type:"custom",data:[{id:"preset::urls",label:"URLs",icon:rh,color:yt.semantic.info,value:"urls",isActive:l==="urls"},{id:"preset::llm",label:"LLM",icon:oh,color:yt.semantic.success,value:"llm",isActive:l==="llm"},{id:"preset::json",label:"JSON",icon:ua,color:yt.semantic.warning,value:"json",isActive:l==="json"},{id:"preset::full",label:"Full",icon:ca,color:yt.semantic.info,value:"full",isActive:l==="full"},{id:"preset::custom",label:"Custom",icon:nh,color:yt.text.secondary,value:"custom",isActive:l===null}]},{id:"include",title:"Include",type:"custom",data:[{id:"requestInfo::includeMethod",label:"URL",value:"includeMethod",isActive:e.includeMethod},{id:"requestInfo::includeStatus",label:"Status",value:"includeStatus",isActive:e.includeStatus},{id:"requestInfo::includeTimestamp",label:"Time",value:"includeTimestamp",isActive:e.includeTimestamp},{id:"headers::includeRequestHeaders",label:"Headers",value:"includeRequestHeaders",isActive:e.includeRequestHeaders},{id:"body::includeRequestBody",label:"Req Body",value:"includeRequestBody",isActive:e.includeRequestBody},{id:"body::includeResponseBody",label:"Res Body",value:"includeResponseBody",isActive:e.includeResponseBody},{id:"requestInfo::includeErrors",label:"Errors",value:"includeErrors",isActive:e.includeErrors}]},{id:"format",title:"Format",type:"custom",data:[{id:"format::markdown",label:"Markdown",icon:ca,color:yt.semantic.info,value:"markdown",isActive:e.format==="markdown"},{id:"format::json",label:"JSON",icon:ua,color:yt.semantic.warning,value:"json",isActive:e.format==="json"},{id:"format::plaintext",label:"Text",icon:ih,color:yt.text.secondary,value:"plaintext",isActive:e.format==="plaintext"}]}],previewSection:{enabled:true,title:"PREVIEW",icon:sh,content:D,headerActions:E},onFilterChange:C}),[e,C,D,E,l]);return o?dt(da,{...k}):pa(S,{style:ar.gatedContainer,children:[dt(ch,{featureName:"Network Export",description:"Export network requests to share with your team, debug APIs, or feed into AI tools.",benefits:["Export to JSON, Markdown, or plain text","Customizable copy presets (URLs only, LLM-ready, full data)","Share request details with teammates","Feed network data directly to AI assistants"]}),dt(S,{style:ar.gatedPreview,children:dt(da,{...k})})]})}var ar=se.create({previewScroll:{maxHeight:300},markdownText:{fontFamily:ha,fontSize:11,color:yt.text.primary,lineHeight:18},plaintextText:{fontFamily:ha,fontSize:11,color:yt.text.primary,lineHeight:18},statusLabel:{fontSize:11,fontWeight:"600",color:yt.text.muted,marginRight:8},gatedContainer:{flex:1,padding:12},gatedPreview:{flex:1}});q();he();import{Bookmark as fa,CheckCircle as Sh,XCircle as kh,Clock as xh,Copy as Ch,Pin as Th,Trash2 as Rh,CopyButton as Ih,macOSColors as Ft,night as ue,useLimit as Ph,monoFont as ga}from"@buoy-gg/shared-ui/web";q();import{isBuoyRequest as ya,getAccountAccess as ma}from"@buoy-gg/shared-ui/web";import{BaseEventStore as Eh}from"@buoy-gg/shared-ui/web";q();function ba(e){if(!e||typeof e!="object")return null;if("operationName"in e&&e.operationName){let t=e.operationName;if(typeof t=="string"&&t.trim().length>0)return t.trim()}if("query"in e&&typeof e.query=="string"){let t=e.query.match(/(?:query|mutation|subscription)\s+(\w+)/);if(t&&t[1])return t[1]}return null}q();import{isBuoyRequest as Bh,devToolsStorageKeys as va,persistentStorage as wa}from"@buoy-gg/shared-ui/web";import{TIER_LIMITS as Lh}from"@buoy-gg/shared-ui/web";var ni=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,$o=25,Wt=50,Sa=Lh["network.saved"].free,_t=16*1024,ka=512*1024;function ii(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.id=="string"&&typeof t.url=="string"&&!Bh(t.url)}var zh=800;function Ho(e,t){if(!t)return{pinned:false,saved:false};let r=e.pinnedLiveIds.has(t),o=e.savedLiveIds.has(t);if(r||o)return{pinned:r,saved:o};let n=e.records.find(i=>i.event.id===t);return n?{pinned:n.pinned,saved:n.saved}:{pinned:false,saved:false}}var Oh={records:[],pinnedEvents:[],savedRecords:[],pinnedLiveIds:new Set,savedLiveIds:new Set};function xa(e){if(e==null)return{value:e,truncated:false};if(typeof e=="string")return e.length<=_t?{value:e,truncated:false}:{value:`${e.slice(0,_t)}
98
98
 
99
- \u2026 truncated by Buoy (body exceeded ${St} bytes)`,truncated:true};try{let t=JSON.stringify(e);return t===void 0?{value:void 0,truncated:false}:t.length<=St?{value:e,truncated:false}:{value:`${t.slice(0,St)}
99
+ \u2026 truncated by Buoy (body exceeded ${_t} bytes)`,truncated:true};try{let t=JSON.stringify(e);return t===void 0?{value:void 0,truncated:false}:t.length<=_t?{value:e,truncated:false}:{value:`${t.slice(0,_t)}
100
100
 
101
- \u2026 truncated by Buoy (body exceeded ${St} bytes)`,truncated:true}}catch{return{value:"[unserializable body]",truncated:true}}}function xs(e){let t=ws(e.requestData),r=ws(e.responseData);return!t.truncated&&!r.truncated?{event:{...e},bodyTruncated:false}:{event:{...e,requestData:t.value,responseData:r.value},bodyTruncated:true}}function Cs(e){let t=0;return e.requestData!=null&&(t+=Math.min(e.requestSize??0,St)),e.responseData!=null&&(t+=Math.min(e.responseSize??0,St)),t}function ac(e){let t=0;for(let i of e)t+=Cs(i.event);if(t<=Ss)return e;let r=[...e].sort((i,s)=>i.pinned!==s.pinned?i.pinned?-1:1:s.savedAt-i.savedAt),o=new Set,n=0;for(let i of r){let s=Cs(i.event);n+s<=Ss?n+=s:o.add(i.key)}return o.size===0?e:e.map(i=>o.has(i.key)?{...i,event:{...i.event,requestData:void 0,responseData:void 0},bodyTruncated:true}:i)}function lc(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let o=r;typeof o.key=="string"&&bn(o.event)&&(!o.pinned&&!o.saved||t.push({key:o.key,event:{...o.event,id:`saved:${o.key}`},pinned:!!o.pinned,saved:!!o.saved,savedAt:typeof o.savedAt=="number"?o.savedAt:0,sessionId:typeof o.sessionId=="string"?o.sessionId:"unknown",liveId:typeof o.liveId=="string"?o.liveId:"",bodyTruncated:!!o.bodyTruncated}))}return t}var dc=class{constructor(){this.records=[];this.listeners=new Set;this.loaded=false;this.loadPromise=null;this.dirty=false;this.keyCounter=0;this.trackedLiveIds=new Set;this.state=sc;this.remote=null;this.remoteEchoUntil=0}getState(){return this.state}enableRemoteMode(e){this.remote=e}disableRemoteMode(){this.remote=null}replaceRecords(e,t=false){this.remote&&(!t&&Date.now()<this.remoteEchoUntil||(this.records=e.filter(r=>bn(r.event)),this.rebuild(),this.emit()))}sessionMatches(e){return this.remote!==null||e.sessionId===mn}getRecords(){return this.records}subscribe(e){return this.listeners.add(e),this.ensureLoaded(),()=>{this.listeners.delete(e)}}getEventById(e){for(let t of this.records)if(t.event.id===e)return t.event;return null}isPinned(e){return this.state.pinnedLiveIds.has(e)}isSaved(e){return this.state.savedLiveIds.has(e)}syncFromLive(e){if(this.trackedLiveIds.size===0||!this.trackedLiveIds.has(e.id))return;let t=this.records.findIndex(o=>this.sessionMatches(o)&&o.liveId===e.id);if(t===-1)return;let r=xs(e);this.commit(this.records.map((o,n)=>n===t?{...o,event:r.event,bodyTruncated:r.bodyTruncated}:o))}togglePin(e){return this.setFlag(e,"pinned")}toggleSave(e){return this.setFlag(e,"saved")}remove(e){this.records.some(t=>t.key===e)&&(this.remote?.removeRecord(e),this.commit(this.records.filter(t=>t.key!==e)))}clearSaved(){this.records.some(e=>e.saved)&&(this.remote?.clearSaved(),this.commit(this.records.filter(e=>e.pinned).map(e=>({...e,saved:false}))))}clearPinned(){this.records.some(e=>e.pinned)&&(this.remote?.clearPinned(),this.commit(this.records.filter(e=>e.saved).map(e=>({...e,pinned:false}))))}setFlag(e,t){if(!bn(e))return{ok:false,reason:"invalid-event"};let r=this.findRecordFor(e);if(this.remote){let s=r?!r[t]:true;t==="pinned"?this.remote.setPinned(e.id,s):this.remote.setSaved(e.id,s),this.remoteEchoUntil=Date.now()+ic}if(r){let s=!r[t];if(s&&!this.hasRoomFor(t,r.key))return{ok:false,reason:t==="pinned"?"pin-cap":"saved-cap"};let l={...r,[t]:s};return this.commit(l.pinned||l.saved?this.records.map(a=>a.key===r.key?l:a):this.records.filter(a=>a.key!==r.key)),{ok:true,active:s}}if(!this.hasRoomFor(t,null))return{ok:false,reason:t==="pinned"?"pin-cap":"saved-cap"};let o=Date.now(),n=xs(e),i={key:`${mn}_${++this.keyCounter}`,event:n.event,pinned:t==="pinned",saved:t==="saved",savedAt:o,sessionId:mn,liveId:e.id,bodyTruncated:n.bodyTruncated};return this.commit(this.evictIfNeeded([i,...this.records])),{ok:true,active:true}}findRecordFor(e){return this.records.find(t=>t.event.id===e.id||this.sessionMatches(t)&&t.liveId===e.id)}hasRoomFor(e,t){let r=e==="pinned"?eo:vt;return this.records.filter(o=>o[e]&&o.key!==t).length<r}evictIfNeeded(e){let t=e.filter(n=>n.saved);if(t.length<=vt)return e;let r=t.filter(n=>!n.pinned).sort((n,i)=>n.savedAt-i.savedAt).slice(0,t.length-vt);if(r.length===0)return e;let o=new Set(r.map(n=>n.key));return e.filter(n=>!o.has(n.key))}ensureLoaded(){return this.remote||this.loaded?Promise.resolve():this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{let e=await bs.getItem(ms.network.saved());e&&!this.dirty&&(this.records=lc(JSON.parse(e)),this.rebuild())}catch{}finally{this.loaded=true,this.emit()}})(),this.loadPromise)}persist(){this.remote||bs.setItem(ms.network.saved(),JSON.stringify(this.records)).catch(()=>{})}commit(e){this.dirty=true,this.records=ac(e),this.rebuild(),this.emit(),this.persist()}rebuild(){let e=[],t=[],r=new Set,o=new Set,n=new Set;for(let i of this.records)i.pinned&&e.push(i),i.saved&&t.push(i),!(!this.sessionMatches(i)||!i.liveId)&&(n.add(i.liveId),i.pinned&&r.add(i.liveId),i.saved&&o.add(i.liveId));this.trackedLiveIds=n,this.state={records:this.records,pinnedEvents:e.map(i=>i.event),savedRecords:t,pinnedLiveIds:r,savedLiveIds:o}}emit(){this.listeners.forEach(e=>e())}},fe=new dc;var uc=200,cc=class extends rc{constructor(){super({storeName:"network",maxEvents:500});this.pendingRequests=new Map;this.rawListenerUnsubscribe=null;this.bootBuffer=[];this.bootBufferUnsubscribe=null;this.mirrorMode=false}replaceEvents(e){super.replaceEvents(e.filter(t=>!fs(t.url)))}startBootCapture(){if(ys().status==="locked"||this.mirrorMode||this.bootBufferUnsubscribe||this.isCapturing())return;let e=Mr();e.isActive||e.startListening(),this.bootBufferUnsubscribe=fr(t=>{this.bootBuffer.push(t),this.bootBuffer.length>uc&&this.bootBuffer.shift()})}takeBootBuffer(){this.bootBufferUnsubscribe&&(this.bootBufferUnsubscribe(),this.bootBufferUnsubscribe=null);let e=this.bootBuffer;return this.bootBuffer=[],e}startCapturing(){let e=Mr();e.isActive||e.startListening();for(let t of this.takeBootBuffer())this.processNetworkEvent(t);this.rawListenerUnsubscribe||(this.rawListenerUnsubscribe=fr(t=>{this.processNetworkEvent(t)})),e.adoptEarlyRequests()}stopCapturing(){this.takeBootBuffer(),this.rawListenerUnsubscribe&&(this.rawListenerUnsubscribe(),this.rawListenerUnsubscribe=null),Pt()===0&&pr()}disableCapture(){this.mirrorMode=true,this.takeBootBuffer(),Pt()===0&&pr(),super.disableCapture()}isCapturing(){return this.rawListenerUnsubscribe!==null}ensureInterception(){this.isCapturing()&&Mr().startListening()}subscribeToEvents(e){let t=super.subscribeToEvents(e);return this.ensureInterception(),t}processNetworkEvent(e){if(ys().status==="locked")return;let{request:t}=e;if(!fs(t.url)){if(e.type==="request"){if(this.events.some(l=>l.id===t.id))return;let r=t.params?`?${new URLSearchParams(t.params).toString()}`:"",o=`${t.url}${r}`,n,i;t.client==="graphql"&&(n=gs(t.data)||void 0,t.data&&typeof t.data=="object"&&"variables"in t.data&&t.data.variables&&typeof t.data.variables=="object"&&(i=t.data.variables));let s={id:t.id,method:t.method,url:o,host:this.extractHost(t.url),path:this.extractPath(t.url),query:r,timestamp:e.timestamp.getTime(),requestHeaders:t.headers||{},requestData:t.data,requestSize:this.getDataSize(t.data),responseHeaders:{},requestClient:t.client,operationName:n,graphqlVariables:i,override:e.override,condition:e.condition};this.pendingRequests.set(t.id,s),this.events=[s,...this.events].slice(0,this.maxEvents),this.notify(s),this.notifyArrayListeners()}else if(e.type==="request-body"){let r=this.events.find(n=>n.id===t.id);if(!r)return;let o={...r,requestData:t.data,requestSize:this.getDataSize(t.data)};if(t.client==="graphql"){o.operationName=gs(t.data)||void 0;let n=t.data?.variables;n&&typeof n=="object"&&(o.graphqlVariables=n)}this.events=this.events.map(n=>n.id===t.id?o:n),this.pendingRequests.has(t.id)&&this.pendingRequests.set(t.id,o),fe.syncFromLive(o),this.notify(o),this.notifyArrayListeners()}else if(e.type==="response"||e.type==="error"){let r=this.events.findIndex(o=>o.id===t.id);if(r!==-1){let o={...this.events[r],duration:e.duration,timings:e.timings};e.response&&(o.status=e.response.status,o.statusText=e.response.statusText,o.responseHeaders=e.response.headers||{},o.responseData=e.response.body,o.responseSize=e.response.size||0,o.responseType=e.response.headers?.["content-type"]),e.error&&(o.error=e.error.message,o.status=o.status||0),e.override&&(o.override=e.override),this.events=this.events.map((n,i)=>i===r?o:n),this.pendingRequests.delete(t.id),fe.syncFromLive(o),this.notify(o),this.notifyArrayListeners()}}}}extractHost(e){try{return new URL(e).hostname}catch{return""}}extractPath(e){try{return new URL(e).pathname}catch{return e}}getDataSize(e){if(!e)return 0;if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return 0}}getEventById(e){return this.events.find(t=>t.id===e)}clearEvents(){super.clearEvents(),this.pendingRequests.clear()}onEvent(e,t=true){let r=this.subscribe(e);if(t&&this.events.length>0){let o=[...this.events].reverse();for(let n of o)try{e(n)}catch{}}return r}getStats(){let e=this.events.length,t=this.events.filter(a=>a.status&&a.status>=200&&a.status<300).length,r=this.events.filter(a=>a.error||a.status&&a.status>=400).length,o=this.events.filter(a=>!a.status&&!a.error).length,n=this.events.filter(a=>a.duration).map(a=>a.duration),i=n.length>0?n.reduce((a,u)=>a+u,0)/n.length:0,s=this.events.reduce((a,u)=>a+(u.requestSize||0),0),l=this.events.reduce((a,u)=>a+(u.responseSize||0),0);return{totalRequests:e,successfulRequests:t,failedRequests:r,pendingRequests:o,totalDataSent:s,totalDataReceived:l,averageDuration:Math.round(i)}}filterEvents(e){let t=[...this.events];if(e.method&&(t=t.filter(r=>r.method===e.method)),e.status)switch(e.status){case"success":t=t.filter(r=>r.status&&r.status>=200&&r.status<300);break;case"error":t=t.filter(r=>r.error||r.status&&r.status>=400);break;case"pending":t=t.filter(r=>!r.status&&!r.error);break}if(e.searchText){let r=e.searchText.toLowerCase();t=t.filter(o=>o.url.toLowerCase().includes(r)||o.method.toLowerCase().includes(r)||o.error&&o.error.toLowerCase().includes(r))}return e.host&&(t=t.filter(r=>r.host===e.host)),t}},te=new cc;O();import{useEffect as hc,useState as pc}from"react";var fc=e=>fe.togglePin(e),yc=e=>fe.toggleSave(e),gc=e=>fe.remove(e),mc=()=>fe.clearSaved(),bc=()=>fe.clearPinned();function Zt(){let[e,t]=pc(()=>fe.getState());return hc(()=>fe.subscribe(()=>{t(fe.getState())}),[]),{...e,togglePin:fc,toggleSave:yc,remove:gc,clearSaved:mc,clearPinned:bc}}O();import{useSyncExternalStore as br}from"react";O();var vc=120,Sc=class{constructor(){this.ids=[];this.index=-1;this.selectedId=null;this.bodyId=null;this.renderedId=null;this.settleMs=120;this.settleTimer=null;this.subscribers=new Set;this.snapshot=this.buildSnapshot()}buildSnapshot(){return{ids:this.ids,index:this.index,selectedId:this.selectedId,bodyId:this.bodyId,renderedId:this.renderedId}}emit(){this.snapshot=this.buildSnapshot();for(let e of this.subscribers)e(this.snapshot)}getState(){return this.snapshot}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}setIds(e){e.length===this.ids.length&&e.every((t,r)=>t===this.ids[r])||(this.ids=e,this.index=this.selectedId==null?-1:e.indexOf(this.selectedId),this.emit())}select(e){e!==this.selectedId&&(this.selectedId=e,this.index=e==null?-1:this.ids.indexOf(e),this.scheduleBody(e),this.emit())}clear(){this.select(null)}step(e){if(this.index<0)return null;let t=this.index+e;if(t<0||t>=this.ids.length)return null;let r=this.ids[t];return this.selectedId=r,this.index=t,this.scheduleBody(r),this.emit(),r}scheduleBody(e){if(this.settleTimer!=null&&(clearTimeout(this.settleTimer),this.settleTimer=null),e==null||this.bodyId==null||this.settleMs<=0){this.bodyId=e;return}this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.bodyId!==this.selectedId&&(this.bodyId=this.selectedId,this.emit())},this.settleMs)}setSettleMs(e){this.settleMs=Math.max(0,e)}getSettleMs(){return this.settleMs}reportRendered(e){e!==this.renderedId&&(this.renderedId=e,this.emit())}reset(){this.settleTimer!=null&&clearTimeout(this.settleTimer),this.settleTimer=null,this.ids=[],this.index=-1,this.selectedId=null,this.bodyId=null,this.renderedId=null,this.emit()}},nt=new Sc;function wc(e){return e.map(t=>t.id)}var vr=e=>nt.subscribe(e),it=()=>nt.getState();function xc(){return br(vr,()=>it().selectedId!=null,()=>it().selectedId!=null)}function vn(){return br(vr,()=>it().selectedId,()=>it().selectedId)}function Cc(){return br(vr,()=>it().bodyId,()=>it().bodyId)}function kc(){let e=br(vr,()=>it().index,()=>it().index),t=br(vr,()=>it().ids.length,()=>it().ids.length);return{index:e,total:t}}O();import{useEffect as ks,useState as Tc}from"react";O();import{urlMatchesIgnoredPattern as Rc}from"@buoy-gg/shared-ui/web";function Sr(e,t){let r=t.searchText?t.searchText.toLowerCase():null,o=t.method&&t.method.length>0?new Set(t.method):null,n=t.contentType&&t.contentType.length>0?new Set(t.contentType):null,i=[...e];if(o&&(i=i.filter(s=>o.has(s.method))),t.status&&t.status!=="all")switch(t.status){case"success":i=i.filter(s=>s.status&&s.status>=200&&s.status<300);break;case"error":i=i.filter(s=>s.error||s.status&&s.status>=400);break;case"pending":i=i.filter(s=>!s.status&&!s.error);break}return r&&(i=i.filter(s=>s.url.toLowerCase().includes(r)||s.method.toLowerCase().includes(r)||s.path?.toLowerCase().includes(r)||s.host?.toLowerCase().includes(r)||s.error&&s.error.toLowerCase().includes(r)||s.operationName&&s.operationName.toLowerCase().includes(r)||os(s.graphqlVariables,r))),t.host&&(i=i.filter(s=>s.host===t.host)),n&&(i=i.filter(s=>{let l=s.responseHeaders||s.requestHeaders,a=l?.["content-type"]||l?.["Content-Type"]||"";for(let u of n)switch(u){case"JSON":if(a.includes("json"))return true;break;case"XML":if(a.includes("xml"))return true;break;case"HTML":if(a.includes("html"))return true;break;case"TEXT":if(a.includes("text"))return true;break;case"IMAGE":if(a.includes("image"))return true;break;case"VIDEO":if(a.includes("video"))return true;break;case"AUDIO":if(a.includes("audio"))return true;break;case"FORM":if(a.includes("form"))return true;break;case"OTHER":if(!a||!a.includes("json")&&!a.includes("xml")&&!a.includes("html")&&!a.includes("text")&&!a.includes("image")&&!a.includes("video")&&!a.includes("audio")&&!a.includes("form"))return true;break}return false})),i}function wr(e,t){return t.length===0?e:e.filter(r=>!t.some(o=>Rc(r.url,o)))}function Ts(e,t){let r=0,o=0,n=0;for(let i of wr(e,t))i.status&&i.status>=200&&i.status<300?r++:i.error||i.status&&i.status>=400?o++:!i.status&&!i.error&&n++;return{successful:r,failed:o,pending:n,total:e.length}}function Ec(e,t){return e.successful===t.successful&&e.failed===t.failed&&e.pending===t.pending&&e.total===t.total}function Rs(e){let{ignoredPatterns:t,paused:r}=e,[o,n]=Tc(()=>Ts(te.getEvents(),t));return ks(()=>{if(r)return;let i=null,s=null,l=te.subscribeToEvents(a=>{s=a,i==null&&(i=requestAnimationFrame(()=>{if(i=null,!s)return;let u=Ts(s,t);s=null,n(d=>Ec(d,u)?d:u)}))});return()=>{l(),i!=null&&cancelAnimationFrame(i)}},[r,t]),ks(()=>te.onClear(()=>{n({successful:0,failed:0,pending:0,total:0})}),[]),o}O();import{useEffect as ro,useState as Es}from"react";function Ic(e){let{paused:t}=e,[r,o]=Es(()=>te.getEvents().length>0);return ro(()=>{if(!t)return te.subscribeToEvents(n=>{let i=n.length>0;o(s=>s===i?s:i)})},[t]),ro(()=>te.onClear(()=>o(false)),[]),r}function Pc(e){let{filter:t,ignoredPatterns:r,paused:o}=e,[n,i]=Es(()=>Sr(wr(te.getEvents(),r),t).length>0);return ro(()=>{if(!o)return te.subscribeToEvents(s=>{let l=Sr(wr(s,r),t).length>0;i(a=>a===l?a:l)})},[o,t,r]),ro(()=>te.onClear(()=>i(false)),[]),n}O();function oo(e){if(e==null)return"N/A";if(e===0)return"0 B";let t=1024,r=["B","KB","MB","GB","TB"],o=Math.floor(Math.log(e)/Math.log(t));return`${(e/Math.pow(t,o)).toFixed(1)} ${r[o]}`}function no(e,t){if(t===-1||!e)return true;try{return JSON.stringify(e).length<t*1024}catch{return false}}function Is(e,t){let r=e;if(t.filterMode==="failed"?r=r.filter(n=>n.error||n.status&&n.status>=400):t.filterMode==="success"&&(r=r.filter(n=>n.status&&n.status>=200&&n.status<300)),r.length===0)return"No requests to copy";if(t.format==="plaintext")return r.map(n=>`${n.method} ${n.url}`).join(`
102
- `);if(t.format==="json"){let n=r.map(i=>{let s={};return t.includeMethod&&(s.method=i.method,s.url=i.url),t.includeStatus&&(s.status=i.status,s.statusText=i.statusText),t.includeDuration&&(s.duration=i.duration),i.condition&&(s.condition=i.condition),t.includeTimestamp&&(s.timestamp=i.timestamp),t.includeClient&&(s.requestClient=i.requestClient),t.includeSizes&&(s.requestSize=i.requestSize,s.responseSize=i.responseSize),t.includeErrors&&i.error&&(s.error=i.error),t.includeRequestHeaders&&(s.requestHeaders=i.requestHeaders),t.includeResponseHeaders&&(s.responseHeaders=i.responseHeaders),t.includeRequestBody&&no(i.requestData,t.bodySizeThreshold)&&(s.requestData=i.requestData),t.includeResponseBody&&no(i.responseData,t.bodySizeThreshold)&&(s.responseData=i.responseData),s});return JSON.stringify(n,null,2)}let o=r.map((n,i)=>{let s=`# Request ${i+1}
101
+ \u2026 truncated by Buoy (body exceeded ${_t} bytes)`,truncated:true}}catch{return{value:"[unserializable body]",truncated:true}}}function Ca(e){let t=xa(e.requestData),r=xa(e.responseData);return!t.truncated&&!r.truncated?{event:{...e},bodyTruncated:false}:{event:{...e,requestData:t.value,responseData:r.value},bodyTruncated:true}}function Ta(e){let t=0;return e.requestData!=null&&(t+=Math.min(e.requestSize??0,_t)),e.responseData!=null&&(t+=Math.min(e.responseSize??0,_t)),t}function qh(e){let t=0;for(let i of e)t+=Ta(i.event);if(t<=ka)return e;let r=[...e].sort((i,s)=>i.pinned!==s.pinned?i.pinned?-1:1:s.savedAt-i.savedAt),o=new Set,n=0;for(let i of r){let s=Ta(i.event);n+s<=ka?n+=s:o.add(i.key)}return o.size===0?e:e.map(i=>o.has(i.key)?{...i,event:{...i.event,requestData:void 0,responseData:void 0},bodyTruncated:true}:i)}function Dh(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let o=r;typeof o.key=="string"&&ii(o.event)&&(!o.pinned&&!o.saved||t.push({key:o.key,event:{...o.event,id:`saved:${o.key}`},pinned:!!o.pinned,saved:!!o.saved,savedAt:typeof o.savedAt=="number"?o.savedAt:0,sessionId:typeof o.sessionId=="string"?o.sessionId:"unknown",liveId:typeof o.liveId=="string"?o.liveId:"",bodyTruncated:!!o.bodyTruncated}))}return t}var Ah=class{constructor(){this.records=[];this.listeners=new Set;this.loaded=false;this.loadPromise=null;this.dirty=false;this.keyCounter=0;this.trackedLiveIds=new Set;this.state=Oh;this.remote=null;this.remoteEchoUntil=0}getState(){return this.state}enableRemoteMode(e){this.remote=e}disableRemoteMode(){this.remote=null}replaceRecords(e,t=false){this.remote&&(!t&&Date.now()<this.remoteEchoUntil||(this.records=e.filter(r=>ii(r.event)),this.rebuild(),this.emit()))}sessionMatches(e){return this.remote!==null||e.sessionId===ni}getRecords(){return this.records}subscribe(e){return this.listeners.add(e),this.ensureLoaded(),()=>{this.listeners.delete(e)}}getEventById(e){for(let t of this.records)if(t.event.id===e)return t.event;return null}isPinned(e){return this.state.pinnedLiveIds.has(e)}isSaved(e){return this.state.savedLiveIds.has(e)}syncFromLive(e){if(this.trackedLiveIds.size===0||!this.trackedLiveIds.has(e.id))return;let t=this.records.findIndex(o=>this.sessionMatches(o)&&o.liveId===e.id);if(t===-1)return;let r=Ca(e);this.commit(this.records.map((o,n)=>n===t?{...o,event:r.event,bodyTruncated:r.bodyTruncated}:o))}togglePin(e){return this.setFlag(e,"pinned")}toggleSave(e){return this.setFlag(e,"saved")}remove(e){this.records.some(t=>t.key===e)&&(this.remote?.removeRecord(e),this.commit(this.records.filter(t=>t.key!==e)))}clearSaved(){this.records.some(e=>e.saved)&&(this.remote?.clearSaved(),this.commit(this.records.filter(e=>e.pinned).map(e=>({...e,saved:false}))))}clearPinned(){this.records.some(e=>e.pinned)&&(this.remote?.clearPinned(),this.commit(this.records.filter(e=>e.saved).map(e=>({...e,pinned:false}))))}setFlag(e,t){if(!ii(e))return{ok:false,reason:"invalid-event"};let r=this.findRecordFor(e);if(this.remote){let s=r?!r[t]:true;t==="pinned"?this.remote.setPinned(e.id,s):this.remote.setSaved(e.id,s),this.remoteEchoUntil=Date.now()+zh}if(r){let s=!r[t];if(s&&!this.hasRoomFor(t,r.key))return{ok:false,reason:t==="pinned"?"pin-cap":"saved-cap"};let d={...r,[t]:s};return this.commit(d.pinned||d.saved?this.records.map(a=>a.key===r.key?d:a):this.records.filter(a=>a.key!==r.key)),{ok:true,active:s}}if(!this.hasRoomFor(t,null))return{ok:false,reason:t==="pinned"?"pin-cap":"saved-cap"};let o=Date.now(),n=Ca(e),i={key:`${ni}_${++this.keyCounter}`,event:n.event,pinned:t==="pinned",saved:t==="saved",savedAt:o,sessionId:ni,liveId:e.id,bodyTruncated:n.bodyTruncated};return this.commit(this.evictIfNeeded([i,...this.records])),{ok:true,active:true}}findRecordFor(e){return this.records.find(t=>t.event.id===e.id||this.sessionMatches(t)&&t.liveId===e.id)}hasRoomFor(e,t){let r=e==="pinned"?$o:Wt;return this.records.filter(o=>o[e]&&o.key!==t).length<r}evictIfNeeded(e){let t=e.filter(n=>n.saved);if(t.length<=Wt)return e;let r=t.filter(n=>!n.pinned).sort((n,i)=>n.savedAt-i.savedAt).slice(0,t.length-Wt);if(r.length===0)return e;let o=new Set(r.map(n=>n.key));return e.filter(n=>!o.has(n.key))}ensureLoaded(){return this.remote||this.loaded?Promise.resolve():this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{try{let e=await wa.getItem(va.network.saved());e&&!this.dirty&&(this.records=Dh(JSON.parse(e)),this.rebuild())}catch{}finally{this.loaded=true,this.emit()}})(),this.loadPromise)}persist(){this.remote||wa.setItem(va.network.saved(),JSON.stringify(this.records)).catch(()=>{})}commit(e){this.dirty=true,this.records=qh(e),this.rebuild(),this.emit(),this.persist()}rebuild(){let e=[],t=[],r=new Set,o=new Set,n=new Set;for(let i of this.records)i.pinned&&e.push(i),i.saved&&t.push(i),!(!this.sessionMatches(i)||!i.liveId)&&(n.add(i.liveId),i.pinned&&r.add(i.liveId),i.saved&&o.add(i.liveId));this.trackedLiveIds=n,this.state={records:this.records,pinnedEvents:e.map(i=>i.event),savedRecords:t,pinnedLiveIds:r,savedLiveIds:o}}emit(){this.listeners.forEach(e=>e())}},me=new Ah;var Nh=200,Mh=class extends Eh{constructor(){super({storeName:"network",maxEvents:500});this.pendingRequests=new Map;this.rawListenerUnsubscribe=null;this.bootBuffer=[];this.bootBufferUnsubscribe=null;this.mirrorMode=false}replaceEvents(e){super.replaceEvents(e.filter(t=>!ya(t.url)))}startBootCapture(){if(ma().status==="locked"||this.mirrorMode||this.bootBufferUnsubscribe||this.isCapturing())return;let e=Co();e.isActive||e.startListening(),this.bootBufferUnsubscribe=Fr(t=>{this.bootBuffer.push(t),this.bootBuffer.length>Nh&&this.bootBuffer.shift()})}takeBootBuffer(){this.bootBufferUnsubscribe&&(this.bootBufferUnsubscribe(),this.bootBufferUnsubscribe=null);let e=this.bootBuffer;return this.bootBuffer=[],e}startCapturing(){let e=Co();e.isActive||e.startListening();for(let t of this.takeBootBuffer())this.processNetworkEvent(t);this.rawListenerUnsubscribe||(this.rawListenerUnsubscribe=Fr(t=>{this.processNetworkEvent(t)})),e.adoptEarlyRequests()}stopCapturing(){this.takeBootBuffer(),this.rawListenerUnsubscribe&&(this.rawListenerUnsubscribe(),this.rawListenerUnsubscribe=null),er()===0&&jr()}disableCapture(){this.mirrorMode=true,this.takeBootBuffer(),er()===0&&jr(),super.disableCapture()}isCapturing(){return this.rawListenerUnsubscribe!==null}ensureInterception(){this.isCapturing()&&Co().startListening()}subscribeToEvents(e){let t=super.subscribeToEvents(e);return this.ensureInterception(),t}processNetworkEvent(e){if(ma().status==="locked")return;let{request:t}=e;if(!ya(t.url)){if(e.type==="request"){if(this.events.some(d=>d.id===t.id))return;let r=t.params?`?${new URLSearchParams(t.params).toString()}`:"",o=`${t.url}${r}`,n,i;t.client==="graphql"&&(n=ba(t.data)||void 0,t.data&&typeof t.data=="object"&&"variables"in t.data&&t.data.variables&&typeof t.data.variables=="object"&&(i=t.data.variables));let s={id:t.id,method:t.method,url:o,host:this.extractHost(t.url),path:this.extractPath(t.url),query:r,timestamp:e.timestamp.getTime(),requestHeaders:t.headers||{},requestData:t.data,requestSize:this.getDataSize(t.data),responseHeaders:{},requestClient:t.client,operationName:n,graphqlVariables:i,override:e.override,condition:e.condition};this.pendingRequests.set(t.id,s),this.events=[s,...this.events].slice(0,this.maxEvents),this.notify(s),this.notifyArrayListeners()}else if(e.type==="request-body"){let r=this.events.find(n=>n.id===t.id);if(!r)return;let o={...r,requestData:t.data,requestSize:this.getDataSize(t.data)};if(t.client==="graphql"){o.operationName=ba(t.data)||void 0;let n=t.data?.variables;n&&typeof n=="object"&&(o.graphqlVariables=n)}this.events=this.events.map(n=>n.id===t.id?o:n),this.pendingRequests.has(t.id)&&this.pendingRequests.set(t.id,o),me.syncFromLive(o),this.notify(o),this.notifyArrayListeners()}else if(e.type==="response"||e.type==="error"){let r=this.events.findIndex(o=>o.id===t.id);if(r!==-1){let o={...this.events[r],duration:e.duration,timings:e.timings};e.response&&(o.status=e.response.status,o.statusText=e.response.statusText,o.responseHeaders=e.response.headers||{},o.responseData=e.response.body,o.responseJson=typeof e.response.json=="boolean"?e.response.json:void 0,o.responseTruncated=e.response.truncated===true||void 0,o.responseUnread=e.response.unread===true||void 0,o.responseSize=e.response.size||0,o.responseType=e.response.headers?.["content-type"]),e.error&&(o.error=e.error.message,o.status=o.status||0),e.override&&(o.override=e.override),this.events=this.events.map((n,i)=>i===r?o:n),this.pendingRequests.delete(t.id),me.syncFromLive(o),this.notify(o),this.notifyArrayListeners()}}}}extractHost(e){try{return new URL(e).hostname}catch{return""}}extractPath(e){try{return new URL(e).pathname}catch{return e}}getDataSize(e){if(!e)return 0;if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return 0}}getEventById(e){return this.events.find(t=>t.id===e)}clearEvents(){super.clearEvents(),this.pendingRequests.clear()}onEvent(e,t=true){let r=this.subscribe(e);if(t&&this.events.length>0){let o=[...this.events].reverse();for(let n of o)try{e(n)}catch{}}return r}getStats(){let e=this.events.length,t=this.events.filter(a=>a.status&&a.status>=200&&a.status<300).length,r=this.events.filter(a=>a.error||a.status&&a.status>=400).length,o=this.events.filter(a=>!a.status&&!a.error).length,n=this.events.filter(a=>a.duration).map(a=>a.duration),i=n.length>0?n.reduce((a,l)=>a+l,0)/n.length:0,s=this.events.reduce((a,l)=>a+(l.requestSize||0),0),d=this.events.reduce((a,l)=>a+(l.responseSize||0),0);return{totalRequests:e,successfulRequests:t,failedRequests:r,pendingRequests:o,totalDataSent:s,totalDataReceived:d,averageDuration:Math.round(i)}}filterEvents(e){let t=[...this.events];if(e.method&&(t=t.filter(r=>r.method===e.method)),e.status)switch(e.status){case"success":t=t.filter(r=>r.status&&r.status>=200&&r.status<300);break;case"error":t=t.filter(r=>r.error||r.status&&r.status>=400);break;case"pending":t=t.filter(r=>!r.status&&!r.error);break}if(e.searchText){let r=e.searchText.toLowerCase();t=t.filter(o=>o.url.toLowerCase().includes(r)||o.method.toLowerCase().includes(r)||o.error&&o.error.toLowerCase().includes(r))}return e.host&&(t=t.filter(r=>r.host===e.host)),t}},ne=new Mh;q();import{useEffect as $h,useState as Hh}from"react";var jh=e=>me.togglePin(e),Fh=e=>me.toggleSave(e),Wh=e=>me.remove(e),_h=()=>me.clearSaved(),Vh=()=>me.clearPinned();function kr(){let[e,t]=Hh(()=>me.getState());return $h(()=>me.subscribe(()=>{t(me.getState())}),[]),{...e,togglePin:jh,toggleSave:Fh,remove:Wh,clearSaved:_h,clearPinned:Vh}}q();import{useSyncExternalStore as Jr}from"react";q();var Uh=120,Jh=class{constructor(){this.ids=[];this.index=-1;this.selectedId=null;this.bodyId=null;this.renderedId=null;this.settleMs=120;this.settleTimer=null;this.subscribers=new Set;this.snapshot=this.buildSnapshot()}buildSnapshot(){return{ids:this.ids,index:this.index,selectedId:this.selectedId,bodyId:this.bodyId,renderedId:this.renderedId}}emit(){this.snapshot=this.buildSnapshot();for(let e of this.subscribers)e(this.snapshot)}getState(){return this.snapshot}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}setIds(e){e.length===this.ids.length&&e.every((t,r)=>t===this.ids[r])||(this.ids=e,this.index=this.selectedId==null?-1:e.indexOf(this.selectedId),this.emit())}select(e){e!==this.selectedId&&(this.selectedId=e,this.index=e==null?-1:this.ids.indexOf(e),this.scheduleBody(e),this.emit())}clear(){this.select(null)}step(e){if(this.index<0)return null;let t=this.index+e;if(t<0||t>=this.ids.length)return null;let r=this.ids[t];return this.selectedId=r,this.index=t,this.scheduleBody(r),this.emit(),r}scheduleBody(e){if(this.settleTimer!=null&&(clearTimeout(this.settleTimer),this.settleTimer=null),e==null||this.bodyId==null||this.settleMs<=0){this.bodyId=e;return}this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.bodyId!==this.selectedId&&(this.bodyId=this.selectedId,this.emit())},this.settleMs)}setSettleMs(e){this.settleMs=Math.max(0,e)}getSettleMs(){return this.settleMs}reportRendered(e){e!==this.renderedId&&(this.renderedId=e,this.emit())}reset(){this.settleTimer!=null&&clearTimeout(this.settleTimer),this.settleTimer=null,this.ids=[],this.index=-1,this.selectedId=null,this.bodyId=null,this.renderedId=null,this.emit()}},xt=new Jh;function Gh(e){return e.map(t=>t.id)}var Gr=e=>xt.subscribe(e),Ct=()=>xt.getState();function Xh(){return Jr(Gr,()=>Ct().selectedId!=null,()=>Ct().selectedId!=null)}function si(){return Jr(Gr,()=>Ct().selectedId,()=>Ct().selectedId)}function Kh(){return Jr(Gr,()=>Ct().bodyId,()=>Ct().bodyId)}function Qh(){let e=Jr(Gr,()=>Ct().index,()=>Ct().index),t=Jr(Gr,()=>Ct().ids.length,()=>Ct().ids.length);return{index:e,total:t}}q();import{useEffect as Ra,useState as Yh}from"react";q();import{urlMatchesIgnoredPattern as Zh}from"@buoy-gg/shared-ui/web";function Xr(e,t){let r=t.searchText?t.searchText.toLowerCase():null,o=t.method&&t.method.length>0?new Set(t.method):null,n=t.contentType&&t.contentType.length>0?new Set(t.contentType):null,i=[...e];if(o&&(i=i.filter(s=>o.has(s.method))),t.status&&t.status!=="all")switch(t.status){case"success":i=i.filter(s=>s.status&&s.status>=200&&s.status<300);break;case"error":i=i.filter(s=>s.error||s.status&&s.status>=400);break;case"pending":i=i.filter(s=>!s.status&&!s.error);break}return r&&(i=i.filter(s=>s.url.toLowerCase().includes(r)||s.method.toLowerCase().includes(r)||s.path?.toLowerCase().includes(r)||s.host?.toLowerCase().includes(r)||s.error&&s.error.toLowerCase().includes(r)||s.operationName&&s.operationName.toLowerCase().includes(r)||ia(s.graphqlVariables,r))),t.host&&(i=i.filter(s=>s.host===t.host)),n&&(i=i.filter(s=>{let d=s.responseHeaders||s.requestHeaders,a=d?.["content-type"]||d?.["Content-Type"]||"";for(let l of n)switch(l){case"JSON":if(a.includes("json"))return true;break;case"XML":if(a.includes("xml"))return true;break;case"HTML":if(a.includes("html"))return true;break;case"TEXT":if(a.includes("text"))return true;break;case"IMAGE":if(a.includes("image"))return true;break;case"VIDEO":if(a.includes("video"))return true;break;case"AUDIO":if(a.includes("audio"))return true;break;case"FORM":if(a.includes("form"))return true;break;case"OTHER":if(!a||!a.includes("json")&&!a.includes("xml")&&!a.includes("html")&&!a.includes("text")&&!a.includes("image")&&!a.includes("video")&&!a.includes("audio")&&!a.includes("form"))return true;break}return false})),i}function Kr(e,t){return t.length===0?e:e.filter(r=>!t.some(o=>Zh(r.url,o)))}function Ia(e,t){let r=0,o=0,n=0;for(let i of Kr(e,t))i.status&&i.status>=200&&i.status<300?r++:i.error||i.status&&i.status>=400?o++:!i.status&&!i.error&&n++;return{successful:r,failed:o,pending:n,total:e.length}}function ep(e,t){return e.successful===t.successful&&e.failed===t.failed&&e.pending===t.pending&&e.total===t.total}function Pa(e){let{ignoredPatterns:t,paused:r}=e,[o,n]=Yh(()=>Ia(ne.getEvents(),t));return Ra(()=>{if(r)return;let i=null,s=null,d=ne.subscribeToEvents(a=>{s=a,i==null&&(i=requestAnimationFrame(()=>{if(i=null,!s)return;let l=Ia(s,t);s=null,n(c=>ep(c,l)?c:l)}))});return()=>{d(),i!=null&&cancelAnimationFrame(i)}},[r,t]),Ra(()=>ne.onClear(()=>{n({successful:0,failed:0,pending:0,total:0})}),[]),o}q();import{useEffect as jo,useState as Ea}from"react";function tp(e){let{paused:t}=e,[r,o]=Ea(()=>ne.getEvents().length>0);return jo(()=>{if(!t)return ne.subscribeToEvents(n=>{let i=n.length>0;o(s=>s===i?s:i)})},[t]),jo(()=>ne.onClear(()=>o(false)),[]),r}function rp(e){let{filter:t,ignoredPatterns:r,paused:o}=e,[n,i]=Ea(()=>Xr(Kr(ne.getEvents(),r),t).length>0);return jo(()=>{if(!o)return ne.subscribeToEvents(s=>{let d=Xr(Kr(s,r),t).length>0;i(a=>a===d?a:d)})},[o,t,r]),jo(()=>ne.onClear(()=>i(false)),[]),n}q();function Fo(e){if(e==null)return"N/A";if(e===0)return"0 B";let t=1024,r=["B","KB","MB","GB","TB"],o=Math.floor(Math.log(e)/Math.log(t));return`${(e/Math.pow(t,o)).toFixed(1)} ${r[o]}`}function Wo(e,t){if(t===-1||!e)return true;try{return JSON.stringify(e).length<t*1024}catch{return false}}function Ba(e,t){let r=e;if(t.filterMode==="failed"?r=r.filter(n=>n.error||n.status&&n.status>=400):t.filterMode==="success"&&(r=r.filter(n=>n.status&&n.status>=200&&n.status<300)),r.length===0)return"No requests to copy";if(t.format==="plaintext")return r.map(n=>`${n.method} ${n.url}`).join(`
102
+ `);if(t.format==="json"){let n=r.map(i=>{let s={};return t.includeMethod&&(s.method=i.method,s.url=i.url),t.includeStatus&&(s.status=i.status,s.statusText=i.statusText),t.includeDuration&&(s.duration=i.duration),i.condition&&(s.condition=i.condition),t.includeTimestamp&&(s.timestamp=i.timestamp),t.includeClient&&(s.requestClient=i.requestClient),t.includeSizes&&(s.requestSize=i.requestSize,s.responseSize=i.responseSize),t.includeErrors&&i.error&&(s.error=i.error),t.includeRequestHeaders&&(s.requestHeaders=i.requestHeaders),t.includeResponseHeaders&&(s.responseHeaders=i.responseHeaders),t.includeRequestBody&&Wo(i.requestData,t.bodySizeThreshold)&&(s.requestData=i.requestData),t.includeResponseBody&&Wo(i.responseData,t.bodySizeThreshold)&&(s.responseData=i.responseData),s});return JSON.stringify(n,null,2)}let o=r.map((n,i)=>{let s=`# Request ${i+1}
103
103
 
104
104
  `;if(t.includeMethod&&(s+=`**Method:** ${n.method}
105
105
  `,s+=`**URL:** ${n.url}
106
- `),t.includeStatus){let l=n.status||"Pending";s+=`**Status:** ${l}${n.statusText?` (${n.statusText})`:""}
106
+ `),t.includeStatus){let d=n.status||"Pending";s+=`**Status:** ${d}${n.statusText?` (${n.statusText})`:""}
107
107
  `}if(t.includeClient&&n.requestClient&&(s+=`**Client:** ${n.requestClient}
108
108
  `),n.condition&&(s+=`Conditions: ${n.condition.profile} (+${n.condition.delayMs} ms)
109
109
  `),n.condition?.uploadCap?.note&&(s+=`${n.condition.uploadCap.note}
110
110
  `),t.includeDuration&&n.duration&&(s+=`**Duration:** ${n.duration}ms
111
111
  `),t.includeTimestamp&&(s+=`**Timestamp:** ${new Date(n.timestamp).toISOString()}
112
- `),t.includeSizes){let l=n.requestSize?oo(n.requestSize):"N/A",a=n.responseSize?oo(n.responseSize):"N/A";s+=`**Request Size:** ${l}
112
+ `),t.includeSizes){let d=n.requestSize?Fo(n.requestSize):"N/A",a=n.responseSize?Fo(n.responseSize):"N/A";s+=`**Request Size:** ${d}
113
113
  `,s+=`**Response Size:** ${a}
114
114
  `}if(t.includeErrors&&n.error&&(s+=`**Error:** ${n.error}
115
115
  `),t.includeRequestHeaders&&Object.keys(n.requestHeaders).length>0&&(s+=`
@@ -119,10 +119,10 @@ ${JSON.stringify(n.requestHeaders,null,2)}
119
119
  \`\`\`
120
120
  `),t.includeRequestBody)if(s+=`
121
121
  ## Request Data
122
- `,no(n.requestData,t.bodySizeThreshold))s+=`\`\`\`json
122
+ `,Wo(n.requestData,t.bodySizeThreshold))s+=`\`\`\`json
123
123
  ${JSON.stringify(n.requestData,null,2)}
124
124
  \`\`\`
125
- `;else{let l=n.requestSize?oo(n.requestSize):"Unknown size";s+=`_Payload omitted (${l}). Exceeds ${t.bodySizeThreshold}KB threshold._
125
+ `;else{let d=n.requestSize?Fo(n.requestSize):"Unknown size";s+=`_Payload omitted (${d}). Exceeds ${t.bodySizeThreshold}KB threshold._
126
126
  `}if(t.includeResponseHeaders&&Object.keys(n.responseHeaders).length>0&&(s+=`
127
127
  ## Response Headers
128
128
  \`\`\`json
@@ -130,17 +130,17 @@ ${JSON.stringify(n.responseHeaders,null,2)}
130
130
  \`\`\`
131
131
  `),t.includeResponseBody)if(s+=`
132
132
  ## Response Data
133
- `,no(n.responseData,t.bodySizeThreshold))s+=`\`\`\`json
133
+ `,Wo(n.responseData,t.bodySizeThreshold))s+=`\`\`\`json
134
134
  ${JSON.stringify(n.responseData,null,2)}
135
135
  \`\`\`
136
- `;else{let l=n.responseSize?oo(n.responseSize):"Unknown size";s+=`_Payload omitted (${l}). Exceeds ${t.bodySizeThreshold}KB threshold._
136
+ `;else{let d=n.responseSize?Fo(n.responseSize):"Unknown size";s+=`_Payload omitted (${d}). Exceeds ${t.bodySizeThreshold}KB threshold._
137
137
  `}return s+=`
138
138
  ---
139
139
  `,s}).join(`
140
140
  `);return`# Network Requests (${r.length} total)
141
141
 
142
- `+o}import{Fragment as Lc,jsx as xe,jsxs as Nt}from"react/jsx-runtime";function Bc({activeStatus:e,onToggleStatus:t,ignoredPatterns:r,paused:o}){let n=Rs({ignoredPatterns:r,paused:o});return xe(Ps,{counts:n,activeStatus:e,onToggleStatus:t})}function Ps({counts:e,activeStatus:t,onToggleStatus:r}){return Nt(m,{style:ie.headerChipRow,children:[Nt(F,{style:[ie.headerChip,t==="success"&&ie.headerChipActive],onPress:()=>r("success"),children:[xe(Ju,{size:12,color:bt.semantic.success}),xe(b,{style:[ie.headerChipValue,{color:bt.semantic.success}],children:e.successful})]}),Nt(F,{style:[ie.headerChip,t==="error"&&ie.headerChipActive],onPress:()=>r("error"),children:[xe(Gu,{size:12,color:bt.semantic.error}),xe(b,{style:[ie.headerChipValue,{color:bt.semantic.error}],children:e.failed})]}),Nt(F,{style:[ie.headerChip,t==="pending"&&ie.headerChipActive],onPress:()=>r("pending"),children:[xe(Ku,{size:12,color:bt.semantic.warning}),xe(b,{style:[ie.headerChipValue,{color:bt.semantic.warning}],children:e.pending})]})]})}function qc({paused:e}){let t=Ic({paused:e});return xe(F,{"sentry-label":"ignore clear events",testID:"buoy-network-clear",accessibilityLabel:"Clear network requests",accessibilityRole:"button",onPress:()=>te.clearEvents(),style:[ie.headerActionButton,!t&&ie.headerActionButtonDisabled],disabled:!t,children:xe(Qu,{size:14,color:t?ae.color.textSecondary:ae.color.textTertiary})})}function Oc({onPress:e}){let{savedRecords:t}=Zt(),r=t.length;return Nt(F,{"sentry-label":"ignore open saved",onPress:e,accessibilityLabel:"Saved requests",style:ie.headerActionButton,children:[xe(hs,{size:14,color:r>0?ae.color.accent:ae.color.textSecondary}),r>0?xe(m,{style:ie.savedBadge,children:xe(b,{style:ie.savedBadgeText,children:r>99?"99+":r})}):null]})}function Ls({isPro:e,onUpgradePress:t}){let r=vn(),o=Zt(),{pinned:n,saved:i}=to(o,r),s=tc("network.saved"),l=!n&&o.pinnedEvents.length>=eo,a=!i&&o.savedRecords.length>=s,u=()=>r?te.getEvents().find(x=>x.id===r)??fe.getEventById(r):null,d=()=>{let x=u();x&&o.togglePin(x)},g=()=>{if(a&&!e){t();return}let x=u();x&&o.toggleSave(x)};return Nt(Lc,{children:[xe(F,{"sentry-label":"ignore pin request",onPress:d,disabled:l,testID:"buoy-network-pin",accessibilityRole:"button",accessibilityLabel:n?"Unpin request":"Pin request",accessibilityHint:l?`Pin limit reached (${eo})`:void 0,style:[ie.headerActionButton,n&&ie.headerActionButtonActive,l&&ie.headerActionButtonDisabled],children:xe(Zu,{size:14,active:n,color:n?ae.color.accent:l?ae.color.textTertiary:ae.color.textSecondary})}),xe(F,{"sentry-label":"ignore save request",onPress:g,disabled:a&&e,testID:"buoy-network-save",accessibilityRole:"button",accessibilityLabel:i?"Remove from saved":"Save request",accessibilityHint:a&&e?`Saved limit reached (${vt})`:void 0,style:[ie.headerActionButton,i&&ie.headerActionButtonSaved,a&&e&&ie.headerActionButtonDisabled],children:xe(hs,{size:14,color:i?ae.color.accent:a&&e?ae.color.textTertiary:ae.color.textSecondary})})]})}function zc({isPro:e,filter:t,ignoredPatterns:r,copySettings:o,paused:n,onUpgradePress:i,label:s}){let l=Pc({filter:t,ignoredPatterns:r,paused:n});return e?xe(ec,{value:()=>Is(Sr(wr(te.getEvents(),r),t),o),size:14,label:s,buttonStyle:s?ie.copyMenuRow:ie.headerActionButton,labelStyle:ie.copyMenuLabel,colors:{idle:l?ae.color.textSecondary:ae.color.textTertiary,success:bt.semantic.success,error:bt.semantic.error},disabled:!l}):Nt(F,{"sentry-label":"ignore copy pro",onPress:i,style:[s?ie.copyMenuRow:ie.headerActionButton,!l&&ie.headerActionButtonDisabled],disabled:!l,children:[xe(Yu,{size:14,color:l?ae.color.textSecondary:ae.color.textTertiary}),s?xe(b,{style:ie.copyMenuLabel,children:s}):null]})}var ie=ve.create({copyMenuRow:{flexDirection:"row",alignItems:"center",gap:10,paddingHorizontal:6,paddingVertical:11,justifyContent:"flex-start"},copyMenuLabel:{fontSize:13,fontWeight:"600",color:ae.color.text},headerChipRow:{flexDirection:"row",alignItems:"center",gap:8},headerChip:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:ae.color.buttonSurface,paddingHorizontal:10,paddingVertical:5,borderRadius:12,borderWidth:1,borderColor:ae.color.border},headerChipActive:{backgroundColor:ae.color.accentSoft,borderColor:ae.color.accentBorderStrong},headerChipValue:{fontSize:12,fontWeight:"600",fontFamily:ps},headerActionButton:{width:32,height:32,borderRadius:8,backgroundColor:ae.color.buttonSurface,borderWidth:1,borderColor:ae.color.border,alignItems:"center",justifyContent:"center"},headerActionButtonDisabled:{opacity:.55},headerActionButtonActive:{backgroundColor:ae.color.accentSoft,borderColor:ae.color.accentBorderStrong},headerActionButtonSaved:{backgroundColor:ae.color.accentSoft,borderColor:ae.color.accentBorderStrong},savedBadge:{position:"absolute",top:-3,right:-3,minWidth:14,height:14,paddingHorizontal:3,borderRadius:7,backgroundColor:ae.color.accent,alignItems:"center",justifyContent:"center"},savedBadgeText:{color:ae.color.onAccent,fontSize:9,fontWeight:"700",fontFamily:ps}});O();Se();import{useCallback as Dc}from"react";import{FlaskConical as Ac,Pin as Hc,Power as Mc,macOSColors as Ee,ToolEmptyState as Nc,resolveListEmptyState as $c,EVENT_LIST_PRESET as Fc,monoFont as jc}from"@buoy-gg/shared-ui/web";O();Se();import{memo as Wc}from"react";import{ChevronRight as Vc,Upload as Uc,Download as _c,Clock as Xc,AlertCircle as Jc,Bookmark as Gc,FlaskConical as Kc,Pin as Yc,DevToolsCard as Zc,MethodBadge as Qc,TypeBadge as eh,night as Ie,macOSColors as Qt,monoFont as Sn}from"@buoy-gg/shared-ui/web";import{formatRelativeTime as th}from"@buoy-gg/shared-ui/web";import{jsx as ce,jsxs as Ke}from"react/jsx-runtime";function rh(e,t){return t?Qt.semantic.error:e?e>=200&&e<300?Qt.semantic.success:e>=300&&e<400?Qt.semantic.info:e>=400?Qt.semantic.error:Qt.text.muted:Qt.semantic.warning}function oh(e){let t=e?.["content-type"]||e?.["Content-Type"]||"";return t.includes("json")?"JSON":t.includes("xml")?"XML":t.includes("html")?"HTML":t.includes("text")?"TEXT":t.includes("image")?"IMG":t.includes("video")?"VIDEO":t.includes("audio")?"AUDIO":t.includes("form")?"FORM":null}function Bs(e){switch(e){case"fetch":return{backgroundColor:"rgba(74, 144, 226, 0.15)",color:"#4A90E2"};case"graphql":return{backgroundColor:"rgba(229, 53, 171, 0.15)",color:"#E535AB"};case"grpc-web":return{backgroundColor:"rgba(16, 185, 129, 0.15)",color:"#10B981"};case"xhr":return{backgroundColor:"rgba(245, 158, 11, 0.15)",color:"#F59E0B"};default:return{backgroundColor:"rgba(147, 51, 234, 0.15)",color:"#9333EA"}}}function nh({event:e,isPending:t,statusColor:r}){return t?Ke(m,{style:ye.pendingBadge,children:[ce(Xc,{size:10,color:Ie.color.warning}),ce(b,{style:ye.pendingText,children:"..."})]}):e.error?Ke(m,{style:ye.errorBadge,children:[ce(Jc,{size:10,color:Ie.color.danger}),ce(b,{style:ye.errorText,children:"ERR"})]}):ce(m,{style:ye.statusBadge,children:ce(b,{style:[ye.statusText,{color:r}],children:String(e.status)})})}function ih({requestSize:e,responseSize:t}){return!e&&!t?null:Ke(m,{style:ye.sizeRow,children:[e?Ke(m,{style:ye.sizeItem,children:[ce(Uc,{size:8,color:Ie.color.info}),ce(b,{style:ye.sizeText,children:ct(e)})]}):null,t?Ke(m,{style:ye.sizeItem,children:[ce(_c,{size:8,color:Ie.color.accent}),ce(b,{style:ye.sizeText,children:ct(t)})]}):null]})}function sh({timestamp:e,duration:t}){let r=hn(),o=th(e,r);return t?Ke(b,{style:ye.bottomRightText,children:[Zr(t)," ",o]}):ce(b,{style:ye.bottomRightText,children:o})}var er=Wc(function({event:e,onPress:t,pinned:r=false,saved:o=false,overridden:n=false,onLongPress:i}){let s=rh(e.status,e.error),l=!e.status&&!e.error,a=oh(e.responseHeaders),u=e.path||e.url.replace(/^https?:\/\/[^/]+/,"");return e.requestClient==="graphql"?e.operationName?u=rs(e.operationName,e.graphqlVariables):u=u.replace(/\/graphql[^?]*/,"/graphql"):e.operationName&&(u=`${u}
143
- (${e.operationName})`),Ke(Zc,{onPress:()=>t(e),onLongPress:i?()=>i(e):void 0,style:ye.cardWrapper,contentStyle:[ye.container,{borderLeftColor:s}],testID:`buoy-network-row-${e.id}`,accessibilityLabel:`${e.method} ${e.path||e.url}`,children:[Ke(m,{style:ye.topRightContainer,children:[r?ce(Yc,{size:10,active:true,color:Ie.color.info}):null,o?ce(Gc,{size:10,color:Ie.color.accent}):null,n||e.override?ce(Kc,{size:10,color:Ie.color.warning}):null,ce(nh,{event:e,isPending:l,statusColor:s}),e.requestClient?ce(m,{style:[ye.topRightBadge,{backgroundColor:Bs(e.requestClient).backgroundColor}],children:ce(b,{style:[ye.clientText,{color:Bs(e.requestClient).color}],children:e.requestClient==="graphql"?"GQL":e.requestClient==="grpc-web"?"gRPC":e.requestClient==="xhr"?"XHR":e.requestClient})}):null]}),Ke(m,{style:ye.leftSection,children:[ce(Qc,{method:e.method,size:"small"}),ce(ih,{requestSize:e.requestSize,responseSize:e.responseSize})]}),Ke(m,{style:ye.middleSection,children:[ce(b,{style:ye.urlText,numberOfLines:2,children:u}),e.condition?.uploadCap?.note&&ce(b,{testID:`buoy-network-upload-cap-${e.id}`,style:{color:Ie.color.warning,fontSize:10},children:e.condition.uploadCap.note})]}),Ke(m,{style:ye.rightSection,children:[a?ce(eh,{type:a,size:"small"}):null,ce(Vc,{size:14,color:Ie.color.textTertiary})]}),ce(m,{style:ye.bottomRightContainer,children:ce(sh,{timestamp:e.timestamp,duration:e.duration})})]})});er.displayName="NetworkEventItemCompact";var ye=ve.create({cardWrapper:{marginHorizontal:8},container:{flexDirection:"row",alignItems:"center",backgroundColor:"rgba(12, 12, 12, 0.9)",borderLeftWidth:3,borderLeftColor:"transparent",borderBottomWidth:1},leftSection:{marginRight:8,alignItems:"flex-start"},topRightContainer:{position:"absolute",top:1,right:1,flexDirection:"row",alignItems:"center",gap:4},topRightBadge:{paddingHorizontal:4,paddingVertical:2,borderRadius:4},middleSection:{flex:1,justifyContent:"center",paddingRight:8},urlText:{fontSize:12,color:Ie.color.text,lineHeight:16,fontFamily:Sn},rightSection:{flexDirection:"row",alignItems:"center",gap:6},bottomRightContainer:{position:"absolute",bottom:4,right:8},bottomRightText:{fontSize:9,color:Ie.color.textTertiary,fontFamily:Sn},statusBadge:{paddingHorizontal:4,paddingVertical:1,borderRadius:3},statusText:{fontSize:10,fontWeight:"600"},pendingBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:Ie.color.warningSoft,borderRadius:3},pendingText:{fontSize:10,color:Ie.color.warning,fontWeight:"600"},errorBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:Ie.color.dangerSoft,borderRadius:3},errorText:{fontSize:10,color:Ie.color.danger,fontWeight:"600"},durationText:{fontSize:9,color:Ie.color.textSecondary},sizeRow:{flexDirection:"row",gap:4,marginTop:4},sizeItem:{flexDirection:"row",alignItems:"center",gap:2},sizeText:{fontSize:8,color:Ie.color.textSecondary,fontFamily:Sn},clientText:{fontSize:8,fontWeight:"700",letterSpacing:.3,textTransform:"uppercase"}});O();Se();import{ProBadge as ah,Zap as lh,buoyColors as xr}from"@buoy-gg/shared-ui/web";import{jsx as io,jsxs as wn}from"react/jsx-runtime";function qs({title:e,subtitle:t,onPress:r}){return wn(F,{style:Cr.banner,onPress:r,activeOpacity:.8,children:[wn(m,{style:Cr.content,children:[wn(m,{style:Cr.left,children:[io(lh,{size:16,color:xr.primary}),io(b,{style:Cr.title,children:e})]}),io(ah,{})]}),io(b,{style:Cr.subtitle,children:t})]})}var Cr=ve.create({banner:{backgroundColor:xr.card,borderRadius:10,borderWidth:1,borderColor:xr.primary+"40",padding:12,marginHorizontal:12,marginTop:12,marginBottom:34},content:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",marginBottom:4},left:{flexDirection:"row",alignItems:"center",gap:8},title:{color:xr.text,fontSize:13,fontWeight:"600"},subtitle:{color:xr.textMuted,fontSize:11}});O();import{useEffect as Os,useMemo as so,useState as dh}from"react";import{useLimit as uh}from"@buoy-gg/shared-ui/web";function kr(e){let{filter:t,ignoredPatterns:r,paused:o,visible:n=true,isPro:i}=e,s=uh("network.requests"),l=i?1/0:s,[a,u]=dh(()=>te.getEvents());Os(()=>{if(!n)return;if(o){u(te.getEvents());return}let h=null,C=null,k=te.subscribeToEvents(w=>{C=w,h==null&&(h=requestAnimationFrame(()=>{h=null,C&&u(C),C=null}))});return()=>{k(),h!=null&&cancelAnimationFrame(h)}},[o,n]),Os(()=>te.onClear(()=>{u([])}),[]);let d=so(()=>wr(a,r),[a,r]),g=so(()=>Sr(d,t),[d,t]),x=so(()=>{let h=new Set;return a.slice(l).forEach(C=>{h.add(C.id)}),h},[a,l]),y=so(()=>x.size===0?g:g.filter(h=>!x.has(h.id)),[g,x]),R=g.length-y.length;return{events:g,visibleEvents:y,hasLockedEvents:R>0,lockedEventCount:R,totalEvents:d.length}}O();import{useCallback as tr,useSyncExternalStore as ch}from"react";O();import{devToolsStorageKeys as ao,persistentStorage as zs}from"@buoy-gg/shared-ui/web";var hh=800,ph=3;function fh(){let e=`${ao.network.overrides()}_launch`;try{let t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(e))return true;t.setItem(e,"1")}catch{}return false}var Ds=Object.freeze([]),yh=250,gh=["respond","fail","delay"];function As(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let o=r;if(typeof o.id!="string"||typeof o.urlPattern!="string"||!o.urlPattern)continue;let n=gh.includes(o.kind)?o.kind:"respond";t.push({id:o.id,enabled:o.enabled!==false,name:typeof o.name=="string"?o.name:void 0,urlPattern:o.urlPattern,methods:Array.isArray(o.methods)?o.methods.filter(i=>typeof i=="string"):void 0,requireHeader:typeof o.requireHeader=="string"&&o.requireHeader?o.requireHeader:void 0,bodyIncludes:typeof o.bodyIncludes=="string"&&o.bodyIncludes?o.bodyIncludes:void 0,graphqlOperation:typeof o.graphqlOperation=="string"&&o.graphqlOperation?o.graphqlOperation:void 0,graphqlVariables:typeof o.graphqlVariables=="string"?o.graphqlVariables:void 0,sandbox:o.sandbox===true?true:void 0,kind:n,status:typeof o.status=="number"?Math.min(hr,Math.max(cr,o.status)):void 0,statusText:typeof o.statusText=="string"?o.statusText:void 0,headers:o.headers&&typeof o.headers=="object"?o.headers:void 0,body:typeof o.body=="string"?o.body:void 0,failKind:o.failKind==="timeout"?"timeout":void 0,delayMs:typeof o.delayMs=="number"?o.delayMs:void 0,times:typeof o.times=="number"?o.times:null,alternate:o.alternate===true,hits:0,seen:0,createdAt:typeof o.createdAt=="number"?o.createdAt:0})}return t.slice(0,Ze)}var mh=class{constructor(){this.rules=[];this.enabled=true;this.listeners=new Set;this.loaded=false;this.loadPromise=null;this.dirty=false;this.idCounter=0;this.state={enabled:true,rules:[],autoPaused:false};this.launchStreak=0;this.autoPaused=false;this.keepAlive=null;this.hitEmitTimer=null;this.engineDisabled=false;this.remote=null;this.remoteEchoUntil=0;this.sandboxCache=null}enableRemoteMode(e){this.remote=e,this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(e,t=false){this.remote&&(!t&&ue()<this.remoteEchoUntil||(this.enabled=e.enabled,this.rules=e.rules,this.rebuild(),this.emit()))}markLocalEdit(){this.remote&&(this.remoteEchoUntil=ue()+hh)}disableEngine(){this.engineDisabled=true,this.keepAlive&&(this.keepAlive(),this.keepAlive=null,Pt()===0&&pr())}getState(){return this.state}getRules(){return this.engineDisabled?Ds:this.enabled?this.rules:this.sandboxOnly()}sandboxOnly(){if(this.sandboxCache?.from!==this.rules){let e=this.rules.filter(t=>t.sandbox===true);this.sandboxCache={from:this.rules,rules:e.length?e:Ds}}return this.sandboxCache.rules}async fetchRuleBody(e){let t=this.rules.find(r=>r.id===e);if(!t)return null;if(!t.bodyOmitted)return t.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(e)}catch{return null}}activeCount(){return(this.enabled?this.rules:this.sandboxOnly()).filter(e=>e.enabled&&!Xo(e)).length}subscribe(e){return this.listeners.add(e),this.ensureLoaded(),()=>{this.listeners.delete(e)}}setEnabled(e){this.enabled!==e&&(this.remote?.setEnabled(e),this.markLocalEdit(),this.markTouched(),this.enabled=e,this.commit(this.rules))}addRule(e){if(this.rules.length>=Ze)return null;let t={...e,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};return this.commit([t,...this.rules]),t}upsertRule(e){this.remote?.upsertRule(e),this.markLocalEdit(),this.markTouched();let{id:t,...r}=e;return t&&this.rules.some(o=>o.id===t)?(this.updateRule(t,r),this.rules.find(o=>o.id===t)??null):this.addRule(r)}replaceAllRules(e,t){if(this.remote)return null;this.markTouched();let r=e.map(o=>o&&typeof o=="object"&&typeof o.id=="string"?o:{...o,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});return this.enabled=t,this.commit(As(r)),this.rules.slice()}updateRule(e,t){let r=this.rules.findIndex(n=>n.id===e);if(r===-1)return;let o=[...this.rules];o[r]={...o[r],...t,hits:0,seen:0},this.commit(o)}setRuleEnabled(e,t){let r=this.rules.findIndex(n=>n.id===e);if(r===-1||this.rules[r].enabled===t)return;this.remote?.setRuleEnabled(e,t),this.markLocalEdit(),this.markTouched();let o=[...this.rules];o[r]={...o[r],enabled:t,hits:t?0:o[r].hits,seen:t?0:o[r].seen},this.commit(o)}removeRule(e){let t=this.rules.filter(r=>r.id!==e);t.length!==this.rules.length&&(this.remote?.removeRule(e),this.markLocalEdit(),this.markTouched(),this.commit(t))}clearRules(){this.rules.length!==0&&(this.remote?.clearRules(),this.markLocalEdit(),this.markTouched(),this.commit([]))}recordMatch(e){let t=this.rules.findIndex(o=>o.id===e);if(t===-1)return;let r=[...this.rules];r[t]={...r[t],seen:r[t].seen+1},this.rules=r,this.rebuild()}recordHit(e){let t=this.rules.findIndex(s=>s.id===e);if(t===-1)return;let r=this.rules[t],o=r.hits+1,n=typeof r.times=="number"&&o>=r.times,i=[...this.rules];if(i[t]={...r,hits:o,enabled:n?false:r.enabled},n){this.commit(i);return}this.rules=i,this.rebuild(),this.scheduleHitEmit()}isLoaded(){return!!this.remote||this.loaded}ensureLoaded(){return this.remote||this.loaded?Promise.resolve():this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{let e=null;try{e=await zs.getItem(ao.network.overrides())}catch{}this.hydrate(e)})(),this.loadPromise)}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let e;try{e=globalThis.localStorage?.getItem(ao.network.overrides())??null}catch{return}e!==null&&this.hydrate(e)}hydrate(e){try{if(e&&!this.dirty){let t=JSON.parse(e);this.enabled=t?.enabled!==false,this.rules=As(t?.rules),this.launchStreak=typeof t?.launchStreak=="number"?t.launchStreak:0,this.autoPaused=t?.autoPaused===true&&!this.enabled,this.applyLaunchGuard(),this.rebuild()}}catch{}finally{this.loaded=true,this.syncKeepAlive(),this.emit()}}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0||this.rules.some(e=>e.enabled&&e.sandbox)){this.launchStreak=0;return}fh()||(this.launchStreak+=1,this.launchStreak>=ph&&(this.enabled=false,this.autoPaused=true,this.launchStreak=0),this.persist())}syncKeepAlive(){let e=!this.engineDisabled&&this.activeCount()>0;if(e&&!this.keepAlive){Oi(),this.keepAlive=fr(()=>{});return}!e&&this.keepAlive&&(this.keepAlive(),this.keepAlive=null,Pt()===0&&pr())}scheduleHitEmit(){this.hitEmitTimer===null&&(this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null,this.emit()},yh))}commit(e){this.dirty=true,this.rules=e.slice(0,Ze),this.rebuild(),this.syncKeepAlive(),this.emit(),this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0,this.autoPaused=false}noteHealthyLaunch(){this.launchStreak===0&&!this.autoPaused||(this.markTouched(),this.persist(),this.rebuild(),this.emit())}persist(){this.remote||zs.setItem(ao.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})).catch(()=>{})}emit(){this.listeners.forEach(e=>e())}},_=new mh;Kl({getRules:()=>_.getRules(),ready:()=>_.ensureLoaded(),isReady:()=>_.isLoaded(),recordHit:e=>_.recordHit(e),recordMatch:e=>_.recordMatch(e)});typeof window<"u"&&typeof document<"u"&&!(typeof navigator<"u"&&navigator.product==="ReactNative")&&_.loadNow();function lo(){let e=ch(tr(s=>_.subscribe(s),[]),()=>_.getState(),()=>_.getState()),t=tr(s=>_.setEnabled(s),[]),r=tr(s=>_.upsertRule(s),[]),o=tr((s,l)=>_.setRuleEnabled(s,l),[]),n=tr(s=>_.removeRule(s),[]),i=tr(()=>_.clearRules(),[]);return{enabled:e.enabled,rules:e.rules,autoPaused:e.autoPaused,activeCount:_.activeCount(),setEnabled:t,upsertRule:r,setRuleEnabled:o,removeRule:n,clearRules:i,isRuleSpent:Xo}}O();function bh(e,t){if(t.length===0)return[];let r=new Set(t.map(n=>n.id)),o=new Set;for(let n of t){let i;for(let s of e){if(s.override&&r.has(s.override.ruleId)){o.add(s.id);continue}_o(n,s.url,String(s.method||"GET"),s.requestHeaders)&&(s.timestamp>=n.createdAt?o.add(s.id):(!i||s.timestamp>i.timestamp)&&(i=s))}i&&o.add(i.id)}return e.filter(n=>o.has(n.id))}O();var vh=[];function xn(e,t,r){return t.length===0?{pinned:vh,rest:e}:{pinned:t,rest:r.size===0?e:e.filter(o=>!r.has(o.id))}}import{jsx as Pe,jsxs as $t}from"react/jsx-runtime";var Sh=e=>e.id;function wh({events:e,onEventPress:t,onLongPress:r,savedLiveIds:o,onClearPinned:n}){return e.length===0?null:$t(m,{style:Le.pinnedSection,children:[$t(m,{style:Le.pinnedHeader,children:[Pe(Hc,{size:11,active:true,color:Ee.semantic.info}),$t(b,{style:Le.pinnedTitle,children:["PINNED \xB7 ",e.length]}),Pe(F,{onPress:n,"sentry-label":"ignore unpin all",style:Le.pinnedClear,children:Pe(b,{style:Le.pinnedClearText,children:"Unpin all"})})]}),e.map(i=>Pe(er,{event:i,onPress:t,onLongPress:r,pinned:true,saved:o.has(i.id)},i.id))]})}function xh({events:e,onEventPress:t,onLongPress:r,savedLiveIds:o,paused:n,onTogglePaused:i}){return e.length===0?null:$t(m,{style:[Le.overriddenSection,n&&Le.overriddenSectionOff],children:[$t(m,{style:Le.overriddenHeader,children:[Pe(Ac,{size:11,color:n?Ee.text.muted:Ee.semantic.warning}),Pe(b,{testID:"buoy-network-overridden-strip",style:[Le.overriddenTitle,n&&Le.overriddenTitleOff],children:n?`PAUSED \xB7 ${e.length}`:`OVERRIDDEN \xB7 ${e.length}`}),Pe(F,{onPress:i,"sentry-label":"ignore pause overrides",style:Le.overriddenManage,children:Pe(b,{style:[Le.overriddenManageText,n&&Le.overriddenTitleOff],children:n?"Resume":"Pause"})})]}),e.map(s=>Pe(er,{event:s,onPress:t,onLongPress:r,overridden:true,saved:o.has(s.id)},s.id))]})}function Ch({visible:e,paused:t,filter:r,ignoredPatterns:o,isPro:n,searchText:i,onEventPress:s,onUpgradePress:l}){let{visibleEvents:a,hasLockedEvents:u,lockedEventCount:d,totalEvents:g}=kr({filter:r,ignoredPatterns:o,paused:t,visible:e,isPro:n}),{pinnedEvents:x,pinnedLiveIds:y,savedLiveIds:R,togglePin:h,clearPinned:C}=Zt(),{rules:k,enabled:w,setEnabled:I,isRuleSpent:z}=lo(),$=Dc(Y=>{h(Y)},[h]);if(!e)return null;let{pinned:P,rest:A}=xn(a,x,y),v=k.filter(Y=>Y.enabled&&!z(Y)),c=bh([...P,...A],v),p=new Set(c.map(Y=>Y.id)),f=P.filter(Y=>!p.has(Y.id)),S=p.size?A.filter(Y=>!p.has(Y.id)):A,D=!t,H=({item:Y})=>Pe(er,{event:Y,onPress:s,onLongPress:$,saved:R.has(Y.id)}),V=()=>f.length>0||c.length>0?null:Pe(Nc,{testID:"buoy-network-empty",...$c({subject:"requests",search:i,total:g,capturing:D,waiting:{otto:"fishing",title:"No network events",message:"Network requests will appear here"},paused:{title:"No network events",message:"Enable interception to start capturing"}})}),Z=()=>{if(!u)return null;let Y=i.length>0,L=Y?`${d} matching ${d===1?"request":"requests"} in locked history`:`${d} requests locked`;return Pe(qs,{title:L,subtitle:Y?"Upgrade to Pro to search your full request history":"Upgrade to Pro to unlock full request history",onPress:l})};return $t(m,{style:Le.root,children:[D?null:$t(m,{style:Le.disabledBanner,children:[Pe(Mc,{size:14,color:Ee.semantic.warning}),Pe(b,{style:Le.disabledText,children:"Network interception is disabled"})]}),Pe(xh,{events:c,onEventPress:s,onLongPress:$,savedLiveIds:R,paused:!w,onTogglePaused:()=>I(!w)}),Pe(wh,{events:f,onEventPress:s,onLongPress:$,savedLiveIds:R,onClearPinned:C}),S.length>0||u?Pe(Ao,{keyboardShouldPersistTaps:"handled",testID:"buoy-network-list",data:S,renderItem:H,keyExtractor:Sh,contentContainerStyle:Le.listContent,showsVerticalScrollIndicator:true,onEndReachedThreshold:.8,scrollEnabled:true,...Fc,extraData:R,"sentry-label":"ignore network events list",ListFooterComponent:Z}):V()]})}var Le=ve.create({root:{flex:1,minHeight:0},overriddenSection:{borderBottomWidth:1,borderBottomColor:Ee.semantic.warning+"44",backgroundColor:Ee.semantic.warningBackground},overriddenSectionOff:{borderBottomColor:Ee.border.default,backgroundColor:Ee.background.card},overriddenTitleOff:{color:Ee.text.muted},overriddenHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingTop:8,paddingBottom:4},overriddenTitle:{flex:1,fontSize:10,fontWeight:"700",letterSpacing:.8,color:Ee.semantic.warning},overriddenManage:{paddingHorizontal:6,paddingVertical:2},overriddenManageText:{fontSize:10,fontWeight:"600",color:Ee.semantic.warning},pinnedSection:{borderBottomWidth:1,borderBottomColor:Ee.border.default,paddingBottom:4},pinnedHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:20,paddingTop:10,paddingBottom:6},pinnedTitle:{flex:1,color:Ee.semantic.info,fontSize:10,fontWeight:"700",letterSpacing:.6,fontFamily:jc},pinnedClear:{paddingHorizontal:6,paddingVertical:2},pinnedClearText:{color:Ee.text.muted,fontSize:10},disabledBanner:{flexDirection:"row",alignItems:"center",gap:8,padding:10,marginHorizontal:12,marginTop:8,backgroundColor:Ee.semantic.warningBackground,borderRadius:8,borderWidth:1,borderColor:Ee.semantic.warning+"20"},disabledText:{color:Ee.semantic.warning,fontSize:11,flex:1},listContent:{paddingTop:8}});O();Se();import{useState as kh}from"react";import{Bookmark as Th,CopyButton as Rh,Search as Eh,macOSColors as Xe,useLimit as Ih,ToolEmptyState as Ph,resolveListEmptyState as Lh,EVENT_LIST_PRESET as Bh,monoFont as qh}from"@buoy-gg/shared-ui/web";O();function Hs(e,t,r){let o=e.slice(0,Math.min(t,vt)),n=o.map(i=>i.event);return{events:r?Sr(n,{searchText:r}):n,lockedCount:e.length-o.length}}import{jsx as st,jsxs as uo}from"react/jsx-runtime";var Oh=e=>e.id;function Ms({visible:e,isPro:t,copySettings:r,search:o,onSearchChange:n,onEventPress:i,onUpgradePress:s}){let{savedRecords:l,pinnedLiveIds:a,toggleSave:u,clearSaved:d}=Zt(),g=Ih("network.saved"),[x,y]=kh(""),R=o!=null&&n!=null,h=R?o:x,C=R?n:y;if(!e)return null;let{events:k,lockedCount:w}=Hs(l,g,h),I=P=>{u(P)},z=({item:P})=>st(er,{event:P,onPress:i,onLongPress:I,saved:true,pinned:a.has(P.id)}),$=()=>w===0?null:st(qs,{title:`${w} saved ${w===1?"request":"requests"} locked`,subtitle:`Your plan keeps ${g}. Upgrade to Pro to unlock the rest.`,onPress:s});return uo(m,{style:at.root,children:[uo(m,{style:at.toolbar,children:[st(Th,{size:11,color:Xe.semantic.debug}),uo(b,{style:at.toolbarTitle,children:["SAVED \xB7 ",l.length,g>=vt?"":`/${g}`]}),t?st(Rh,{value:()=>Is(k,r),size:13,buttonStyle:at.toolbarButton,colors:{idle:Xe.text.secondary,success:Xe.semantic.success,error:Xe.semantic.error},disabled:k.length===0}):null,st(F,{onPress:d,"sentry-label":"ignore clear saved",style:at.toolbarClear,disabled:l.length===0,children:st(b,{style:[at.toolbarClearText,l.length===0&&at.toolbarClearTextDisabled],children:"Clear all"})})]}),l.length>0?uo(m,{style:at.searchRow,children:[st(Eh,{size:13,color:Xe.text.secondary}),st(Jt,{style:at.searchInput,placeholder:"Search saved requests\u2026",placeholderTextColor:Xe.text.muted,value:h,onChangeText:C,"sentry-label":"ignore saved search",accessibilityLabel:"Search saved requests",autoCapitalize:"none",autoCorrect:false,returnKeyType:"search"})]}):null,l.length===0||h.trim().length>0&&k.length===0&&w===0?st(Ph,{testID:"buoy-network-saved-empty",...Lh({subject:"saved requests",verb:"kept",search:l.length===0?"":h,total:l.length,waiting:{otto:"empty",title:"No saved requests",message:"Open a request and tap the bookmark to keep it here \u2014 saved requests survive Clear and app restarts."}})}):st(Ao,{keyboardShouldPersistTaps:"handled",data:k,renderItem:z,keyExtractor:Oh,contentContainerStyle:at.listContent,showsVerticalScrollIndicator:true,scrollEnabled:true,...Bh,extraData:a,"sentry-label":"ignore saved requests list",ListFooterComponent:$})]})}var at=ve.create({root:{flex:1,minHeight:0},toolbar:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:20,paddingTop:10,paddingBottom:6},toolbarTitle:{flex:1,color:Xe.semantic.debug,fontSize:10,fontWeight:"700",letterSpacing:.6,fontFamily:qh},toolbarButton:{width:26,height:26,borderRadius:6,alignItems:"center",justifyContent:"center"},toolbarClear:{paddingHorizontal:6,paddingVertical:2},toolbarClearText:{color:Xe.text.muted,fontSize:10},toolbarClearTextDisabled:{color:Xe.text.disabled},searchRow:{flexDirection:"row",alignItems:"center",gap:6,marginHorizontal:12,marginBottom:8,paddingHorizontal:10,paddingVertical:5,backgroundColor:Xe.background.input,borderRadius:10,borderWidth:1,borderColor:Xe.border.default},searchInput:{flex:1,color:Xe.text.primary,fontSize:13,paddingVertical:2},listContent:{paddingTop:4}});O();Se();import{useCallback as zh,useEffect as co,useState as Dh}from"react";import{AlertCircle as Ah,AlertTriangle as Hh,DevToolsCard as Mh,EmptyState as Nh,MethodBadge as $h,Plus as Fh,Trash2 as jh,macOSColors as oe,useLimit as Wh,monoFont as Vh}from"@buoy-gg/shared-ui/web";O();Se();import{useMemo as Ns,useState as ho}from"react";import{ChevronDown as Uh,ChevronRight as _h,macOSColors as G,useSafeAreaInsets as Xh,monoFont as Jh}from"@buoy-gg/shared-ui/web";O();Se();import{useState as po,useMemo as fo,useCallback as Tr,useRef as Cn,useEffect as Gh,memo as yo}from"react";import{displayValue as Kh,buoyColors as B,monoFont as Fe}from"@buoy-gg/shared-ui/web";import{CopyButton as Yh}from"@buoy-gg/shared-ui/web";import{ChevronRight as Zh,ChevronDown as Qh,Trash as $s}from"@buoy-gg/shared-ui/web";import{CyberpunkInput as ep}from"@buoy-gg/shared-ui/web/dataViewer";O();var Ft=(e,t,r)=>{if(t.length===0)return r;if(e instanceof Map){let o=new Map(e);if(t.length===1)return o.set(t[0],r),o;let[n,...i]=t,s=o.get(n);return o.set(n,Ft(s??null,i,r)),o}if(e instanceof Set){let o=Ft(Array.from(e),t,r);return new Set(Array.isArray(o)?o:[])}if(Array.isArray(e)){let o=[...e];if(t.length===1)return o[t[0]]=r,o;let[n,...i]=t;return o[n]=Ft(o[n],i,r),o}if(e instanceof Object){let o={...e};if(t.length===1)return o[t[0]]=r,o;let[n,...i]=t;return o[n]=Ft(o[n],i,r),o}return e};O();var jt=(e,t)=>{if(e instanceof Map){let r=new Map(e);if(t.length===1)return r.delete(t[0]),r;let[o,...n]=t;return r.set(o,jt(r.get(o),n)),r}if(e instanceof Set){let r=jt(Array.from(e),t);return new Set(r)}if(Array.isArray(e)){let r=[...e];if(t.length===1)return r.filter((i,s)=>s.toString()!==t[0]);let[o,...n]=t;return r[o]=jt(r[o],n),r}if(e instanceof Object){let r={...e};if(t.length===1)return delete r[t[0]],r;let[o,...n]=t;return r[o]=jt(r[o],n),r}return e};O();import{createContext as tp,useContext as rp}from"react";var Fs=tp(null);function go(){return rp(Fs)}import{Fragment as mo,jsx as ee,jsxs as Ne}from"react/jsx-runtime";var Rr=100,rr={top:8,bottom:8,left:8,right:8},js=12,op=(e,t=Rr)=>{if(t<1||e.length===0)return[];let r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r},kn=yo(({expanded:e,isFocused:t=false,isMain:r=false})=>ee(m,{style:[U.expanderIcon,r&&U.expanderIconMain,e?U.expanded:U.collapsed],children:e?ee(Qh,{size:r?14:js,color:t?B.primary:r?B.text:B.textSecondary,strokeWidth:2.5}):ee(Zh,{size:r?14:js,color:t?B.primary:r?B.text:B.textSecondary,strokeWidth:2.5})}));kn.displayName="Expander";var Ws=yo(({value:e,isFocused:t=false})=>ee(Yh,{value:e,isFocused:t,buttonStyle:t?{...U.buttonStyle,...U.buttonStyleFocused}:U.buttonStyle}));Ws.displayName="CopyButton";var Tn=yo(({dataPath:e,isFocused:t=false})=>{let r=go(),o=Tr(()=>{r&&r.onChange(jt(r.root,e))},[r,e]);return r?ee(F,{"sentry-label":"ignore devtools explorer delete button",onPress:o,style:[U.deleteButton,t&&U.deleteButtonFocused],accessibilityLabel:"Delete item",hitSlop:rr,activeOpacity:.7,children:ee($s,{size:14,strokeWidth:2,color:t?B.error:B.error+"CC"})}):null});Tn.displayName="DeleteItemButton";var Vs=yo(({dataPath:e,isFocused:t=false})=>{let r=go(),o=Tr(()=>{r&&r.onChange(Ft(r.root,e,[]))},[r,e]);return r?ee(F,{"sentry-label":"ignore devtools explorer clear button",style:[U.clearButton,t&&U.clearButtonFocused],"aria-label":"Remove all items",onPress:o,hitSlop:rr,activeOpacity:.7,children:ee(b,{style:[U.clearButtonText,{color:t?B.warning:B.warning+"CC"}],children:"[]"})}):null});Vs.displayName="ClearArrayButton";function np({dataPath:e,value:t,itemsDeletable:r}){let o=go(),n=Tr(()=>{if(!o)return;let a=typeof t=="boolean"?t:false;o.onChange(Ft(o.root,e,!a))},[o,e,t]),i=Tr(()=>{o&&o.onChange(jt(o.root,e))},[o,e]);if(!o)return null;let s=t?U.toggleBadgeTrue:U.toggleBadgeFalse,l=t?U.toggleTextTrue:U.toggleTextFalse;return Ne(F,{"sentry-label":"ignore devtools explorer toggle button",style:U.modernToggleButton,onPress:n,hitSlop:rr,activeOpacity:.8,children:[ee(m,{style:[U.toggleBadge,s],children:ee(b,{style:[U.toggleBadgeText,l],children:t?"TRUE":"FALSE"})}),r&&ee(F,{"sentry-label":"ignore devtools explorer delete button in toggle",onPress:i,style:U.deleteButtonInToggle,accessibilityLabel:"Delete item",hitSlop:rr,activeOpacity:.7,children:ee($s,{size:14,strokeWidth:2,color:B.error+"CC"})})]})}function Rn({editable:e,label:t,value:r,defaultExpanded:o,dataPath:n,itemsDeletable:i,dataVersion:s=0}){let l=go(),[a,u]=po(false),[d,g]=po("");Gh(()=>{if(r!=null&&(typeof r=="string"||typeof r=="number")){let p=r.toString();g(p)}},[r,t,s]);let x=fo(()=>{let p=t.toUpperCase();return["DATA","QUERY","QUERYKEY","TYPES","STATS","OPTIONS","OBSERVERS"].includes(p)},[t]),[y,R]=po((o||[]).includes(t)),h=()=>R(p=>!p),[C,k]=po([]),w=fo(()=>r==null||typeof r!="object"?[]:Array.isArray(r)?(r.length>1e3?r.slice(0,1e3):r).map((p,f)=>({label:f.toString(),value:p})):r instanceof Map?Array.from(r.entries()).slice(0,1e3).map(([p,f])=>({label:p.toString(),value:f})):r instanceof Set?Array.from(r).slice(0,1e3).map((p,f)=>({label:f.toString(),value:p})):Object.entries(r).slice(0,1e3).map(([p,f])=>({label:p,value:f})),[r]),I=fo(()=>Array.isArray(r)?"array":r===null||typeof r!="object"?typeof r:r instanceof Map||r instanceof Set?"Iterable":"object",[r]),z=fo(()=>op(w,Rr),[w]),$=n??[],P=Cn(l),A=Cn($),v=Cn(I);P.current=l,A.current=$,v.current=I;let c=Tr((p,f)=>{g(f);let S=P.current;if(!S||p&&isNaN(Number(f)))return;let D=v.current==="number"?Number(f):f;S.onChange(Ft(S.root,A.current,D))},[g]);return ee(m,{style:U.minWidthWrapper,children:Ne(m,{style:U.fullWidthMarginRight,children:[z.length>0&&Ne(mo,{children:[Ne(m,{style:[U.flexRowItemsCenterGap,x&&U.flexRowItemsCenterGapMain],children:[Ne(F,{"sentry-label":"ignore devtools explorer expander button",style:U.expanderButton,onPress:h,hitSlop:rr,activeOpacity:.6,children:[ee(kn,{expanded:y,isFocused:a,isMain:x}),ee(b,{style:[U.labelText,a&&U.labelTextFocused,x&&U.labelTextMain],children:t}),ee(b,{style:U.textGray500,children:`${String(I).toLowerCase()==="iterable"?"(Iterable) ":""}${w.length} ${w.length>1?"items":"item"}`})]}),e&&Ne(m,{style:U.flexRowGapItemsCenter,children:[ee(Ws,{value:r,isFocused:a}),i&&l!==null&&ee(Tn,{dataPath:$,isFocused:a}),I==="array"&&l!==null&&ee(Vs,{dataPath:$,isFocused:a})]})]}),y&&Ne(mo,{children:[z.length===1&&ee(m,{style:[U.singleEntryContainer,x&&U.singleEntryContainerMain],children:w.map((p,f)=>ee(Rn,{defaultExpanded:o,label:p.label,value:p.value,editable:e,dataPath:[...$,p.label],itemsDeletable:I==="array"||I==="Iterable"||I==="object",dataVersion:s},p.label+f))}),z.length>1&&ee(m,{style:U.multiEntryContainer,children:z.map((p,f)=>ee(m,{children:Ne(m,{style:U.relativeOutlineNone,children:[Ne(F,{"sentry-label":"ignore devtools explorer page toggle",onPress:()=>k(S=>S.includes(f)?S.filter(D=>D!==f):[...S,f]),style:U.pageExpanderButton,hitSlop:rr,children:[ee(kn,{expanded:C.includes(f)}),Ne(b,{style:U.pageRangeText,children:["[",f*Rr,"...",f*Rr+Rr-1,"]"]})]}),C.includes(f)&&ee(m,{style:U.entriesContainer,children:p.map(S=>ee(Rn,{defaultExpanded:o,label:S.label,value:S.value,editable:e,dataPath:[...$,S.label],dataVersion:s},S.label))})]})},f))})]})]}),z.length===0&&Ne(m,{style:U.flexRowGapFullWidth,children:[e&&l!==null&&(I==="string"||I==="number"||I==="boolean")?Ne(mo,{children:[e&&l&&(I==="string"||I==="number")&&ee(m,{style:U.nebulaInputWrapper,children:ee(ep,{label:t,accessibilityLabel:"Data input field for editing values",style:[I==="number"?U.textNumber:U.textString],keyboardType:I==="number"?"numeric":"default",value:d,onChangeText:p=>c(I==="number",p),onFocus:()=>u(true),onBlur:()=>u(false),showNumberControls:I==="number",onIncrement:()=>{let p=Number(d)||0;c(true,String(p+1))},onDecrement:()=>{let p=Number(d)||0;c(true,String(p-1))},showDeleteButton:i,onDelete:()=>{l.onChange(jt(l.root,$))}})}),I==="boolean"&&Ne(m,{style:U.booleanRowContainer,children:[ee(b,{style:U.booleanLabel,children:t}),ee(m,{style:U.booleanToggleWrapper,children:ee(np,{dataPath:$,value:r,itemsDeletable:i})})]})]}):Ne(mo,{children:[ee(b,{style:U.text344054,children:t}),ee(b,{style:U.displayValueText,children:Kh(r)})]}),e&&i&&l!==null&&I!=="string"&&I!=="number"&&I!=="boolean"&&ee(Tn,{dataPath:$,isFocused:a})]})]})})}var U=ve.create({buttonStyle:{backgroundColor:B.card+"E6",borderWidth:1,borderColor:B.textSecondary+"33",borderRadius:6,flexDirection:"row",alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",shadowColor:"#000",shadowOffset:{width:0,height:1},shadowOpacity:.2,shadowRadius:2},buttonStyleFocused:{borderColor:B.primary+"CC",backgroundColor:B.primary+"26",shadowColor:B.primary,shadowOpacity:.3,shadowRadius:4},deleteButton:{backgroundColor:B.error+"1A",borderColor:B.error+"4D",borderWidth:1,borderRadius:6,padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",shadowColor:B.error,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},deleteButtonFocused:{borderColor:B.error+"CC",backgroundColor:B.error+"33",shadowOpacity:.3,shadowRadius:5},deleteButtonInToggle:{backgroundColor:B.error+"1A",borderColor:B.error+"4D",borderWidth:1,borderRadius:6,padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,shadowColor:B.error,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},clearButton:{backgroundColor:B.warning+"1A",borderWidth:1,borderColor:B.warning+"4D",borderRadius:6,flexDirection:"row",padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",zIndex:10,shadowColor:B.warning,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},clearButtonFocused:{borderColor:B.warning+"CC",backgroundColor:B.warning+"33",shadowOpacity:.3,shadowRadius:5},clearButtonText:{fontSize:12,fontWeight:"700",fontFamily:Fe},expanderIcon:{width:18,height:18,alignItems:"center",justifyContent:"center",marginRight:1,backgroundColor:B.textSecondary+"14",borderRadius:3},expanderIconMain:{backgroundColor:B.textSecondary+"1A",width:20,height:20,borderRadius:4,borderWidth:.5,borderColor:B.textSecondary+"33"},expanded:{transform:[{rotate:"0deg"}]},collapsed:{transform:[{rotate:"0deg"}]},minWidthWrapper:{minWidth:180,fontSize:11,flexDirection:"row",flexWrap:"wrap",width:"100%",marginVertical:.5},fullWidthMarginRight:{position:"relative",width:"100%",marginRight:1},flexRowItemsCenterGap:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:3,paddingHorizontal:6,marginVertical:1,borderRadius:4,backgroundColor:B.card+"66",borderWidth:.5,borderColor:B.textSecondary+"1A"},flexRowItemsCenterGapMain:{backgroundColor:B.card+"E6",borderLeftWidth:2.5,borderLeftColor:B.textSecondary+"80",borderColor:B.textSecondary+"26",paddingVertical:5,paddingHorizontal:8,marginBottom:3,borderWidth:1,shadowColor:"#000",shadowOffset:{width:0,height:0},shadowOpacity:.08,shadowRadius:3},expanderButton:{flexDirection:"row",alignItems:"center",backgroundColor:"transparent",paddingVertical:1,paddingHorizontal:2,gap:6,borderWidth:0,minHeight:24,flex:1},labelText:{color:B.textSecondary,fontSize:10,fontWeight:"600",marginRight:4,fontFamily:Fe,letterSpacing:.4},labelTextFocused:{color:B.text},labelTextMain:{color:B.text,fontSize:11,fontWeight:"700",letterSpacing:.6},textGray500:{color:B.textMuted,fontSize:10,fontWeight:"400",fontFamily:Fe,opacity:.7},pageRangeText:{color:B.textSecondary,fontSize:10,fontWeight:"600",fontFamily:Fe},flexRowGapItemsCenter:{flexDirection:"row",alignItems:"center",gap:4,paddingLeft:2},singleEntryContainer:{marginLeft:2,marginTop:2,paddingLeft:8,borderLeftWidth:1.5,borderLeftColor:B.textSecondary+"40"},singleEntryContainerMain:{borderLeftColor:B.textSecondary+"4D",marginLeft:4,paddingLeft:10},multiEntryContainer:{marginLeft:2,marginTop:2,paddingLeft:8,borderLeftWidth:1.5,borderLeftColor:B.textSecondary+"40"},multiEntryContainerMain:{borderLeftColor:B.textSecondary+"4D",marginLeft:4,paddingLeft:10},relativeOutlineNone:{position:"relative"},pageExpanderButton:{flexDirection:"row",alignItems:"center",backgroundColor:B.card+"66",paddingVertical:3,paddingHorizontal:6,gap:6,borderRadius:4,borderWidth:.5,borderColor:B.textSecondary+"1A",marginBottom:2,minHeight:24},entriesContainer:{marginLeft:2,paddingLeft:8,marginTop:2,borderLeftWidth:1.5,borderLeftColor:B.textSecondary+"40"},textNumber:{color:B.text,fontWeight:"600",fontFamily:Fe},textString:{color:B.text,fontFamily:Fe},flexRowGapFullWidth:{flexDirection:"row",width:"100%",alignItems:"center",marginVertical:1,gap:6,paddingHorizontal:4,paddingVertical:2,borderRadius:3},text344054:{color:B.textSecondary,fontWeight:"600",fontSize:9,minWidth:50,fontFamily:Fe,letterSpacing:.4,opacity:.8},numberInputButtons:{position:"absolute",right:8,top:"50%",transform:[{translateY:-18}],flexDirection:"row",gap:4,zIndex:10},touchableButton:{width:32,height:32,borderRadius:6,backgroundColor:B.card+"E6",borderWidth:1,borderColor:B.textSecondary+"33",alignItems:"center",justifyContent:"center",marginLeft:2,shadowColor:"#000",shadowOffset:{width:0,height:1},shadowOpacity:.2,shadowRadius:2},touchableButtonFocused:{borderColor:B.primary+"CC",backgroundColor:B.primary+"26",shadowColor:B.primary,shadowOffset:{width:0,height:0},shadowOpacity:.3,shadowRadius:4,elevation:3},nebulaInputWrapper:{flex:1,width:"100%",position:"relative"},displayValueText:{flex:1,color:B.text,fontWeight:"400",fontFamily:Fe,fontSize:12,paddingVertical:6,paddingHorizontal:10,borderRadius:6,borderWidth:1,borderColor:B.textMuted+"66",minHeight:34},dataRow:{flexDirection:"row",alignItems:"center",paddingVertical:4,paddingHorizontal:8,minHeight:44,gap:12},dataLabel:{color:B.textSecondary,fontSize:13,fontWeight:"500",minWidth:80,flexShrink:0},dataValueContainer:{flex:1,flexDirection:"row",alignItems:"center"},inputWithActions:{flex:1,position:"relative"},numberControls:{position:"absolute",right:8,top:"50%",transform:[{translateY:-16}],flexDirection:"column",gap:2},numberButton:{width:32,height:16,borderRadius:4,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:B.primary+"0F"},readOnlyValue:{color:B.text,fontSize:13,fontFamily:Fe,paddingVertical:8,paddingHorizontal:12,borderRadius:6,borderWidth:1,borderColor:B.textMuted+"33",flex:1},actionButtons:{flexDirection:"row",gap:6,paddingLeft:8},booleanContainer:{flexDirection:"row",alignItems:"center",padding:8,borderRadius:6,borderWidth:1,borderColor:B.textMuted+"4D",flex:1},booleanText:{marginLeft:8,color:B.warning,fontWeight:"500",fontFamily:Fe},modernToggleButton:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:6,borderWidth:1,borderColor:B.textMuted+"99",paddingHorizontal:8,paddingVertical:6,marginVertical:2,minHeight:34,gap:8},toggleIconContainer:{marginRight:6},toggleIcon:{padding:8,borderRadius:8,alignItems:"center",justifyContent:"center",width:32,height:32},toggleIconSmall:{width:8,height:8,borderRadius:4},toggleContent:{flex:1,minWidth:0},toggleLabel:{color:"#E5E7EB",fontSize:11,fontWeight:"600",fontFamily:Fe,letterSpacing:.3},toggleStatus:{color:"#9CA3AF",fontSize:11},toggleBadge:{marginLeft:6,paddingHorizontal:6,paddingVertical:3,borderRadius:4,borderWidth:1},toggleBadgeText:{fontSize:9,fontWeight:"700",textTransform:"uppercase",letterSpacing:.8,fontFamily:Fe},toggleIconTrue:{backgroundColor:B.primary},toggleIconFalse:{backgroundColor:B.textMuted},toggleBadgeTrue:{backgroundColor:B.primary+"1A",borderColor:B.primary+"4D"},toggleBadgeFalse:{backgroundColor:B.textMuted+"1A",borderColor:B.textMuted+"4D"},toggleTextTrue:{color:B.primary,fontWeight:"600"},toggleTextFalse:{color:B.textSecondary,fontWeight:"500"},booleanRowContainer:{flexDirection:"row",alignItems:"center",width:"100%",gap:8,paddingVertical:2},booleanLabel:{color:B.textSecondary,fontSize:10,fontWeight:"600",fontFamily:Fe,letterSpacing:.4,minWidth:60,flexShrink:0},booleanToggleWrapper:{flex:1}});O();Se();import{useState as ip}from"react";import{absoluteFill as Us,macOSColors as $e}from"@buoy-gg/shared-ui/web";import{jsx as wt,jsxs as En}from"react/jsx-runtime";function In({title:e,hint:t,value:r,placeholder:o="Number",min:n,max:i,onSubmit:s,onCancel:l}){let[a,u]=ip(r!=null?String(r):""),d=()=>{let g=a.trim();if(!g){s(null);return}let x=Number(g);if(!Number.isFinite(x)){s(null);return}let y=x;n!=null&&(y=Math.max(n,y)),i!=null&&(y=Math.min(i,y)),s(y)};return En(m,{style:je.overlay,children:[wt(F,{style:je.backdrop,activeOpacity:1,onPress:l,"sentry-label":"ignore dismiss number prompt"}),En(m,{style:je.panel,children:[wt(b,{style:je.title,children:e}),wt(Jt,{style:je.input,value:a,onChangeText:u,placeholder:o,placeholderTextColor:$e.text.muted,keyboardType:"number-pad",autoFocus:true,selectTextOnFocus:true,onSubmitEditing:d,returnKeyType:"done","sentry-label":"ignore number prompt input",accessibilityLabel:e}),t?wt(b,{style:je.hint,children:t}):null,En(m,{style:je.actions,children:[wt(F,{onPress:l,"sentry-label":"ignore cancel number prompt",style:[je.button,je.cancelButton],children:wt(b,{style:je.cancelText,children:"Cancel"})}),wt(F,{onPress:d,"sentry-label":"ignore save number prompt",style:[je.button,je.saveButton],children:wt(b,{style:je.saveText,children:"Set"})})]})]})]})}var je=ve.create({overlay:{...Us,zIndex:40},backdrop:{...Us,backgroundColor:"rgba(0,0,0,0.6)"},panel:{marginHorizontal:12,marginTop:12,padding:14,borderRadius:10,borderWidth:1,borderColor:$e.border.hover,backgroundColor:$e.background.card,gap:10},title:{fontSize:13,fontWeight:"700",color:$e.text.primary},input:{backgroundColor:$e.background.input,borderWidth:1,borderColor:$e.border.input,borderRadius:6,paddingHorizontal:12,paddingVertical:10,fontSize:16,fontWeight:"700",color:$e.text.primary},hint:{fontSize:10,color:$e.text.muted},actions:{flexDirection:"row",gap:8},button:{flex:1,paddingVertical:10,borderRadius:6,alignItems:"center",borderWidth:1},cancelButton:{borderColor:$e.border.default,backgroundColor:$e.background.base},cancelText:{fontSize:12,fontWeight:"600",color:$e.text.secondary},saveButton:{borderColor:$e.semantic.info,backgroundColor:`${$e.semantic.info}22`},saveText:{fontSize:12,fontWeight:"700",color:$e.semantic.info}});import{Fragment as _s,jsx as X,jsxs as qe}from"react/jsx-runtime";var sp=["GET","POST","PUT","PATCH","DELETE"],Xs=[0,500,1e3,3e3,1e4],Js=[{id:"500",label:"Server error",code:"500",danger:true,patch:{kind:"respond",status:500,statusText:"Internal Server Error"}},{id:"401",label:"Unauthorized",code:"401",danger:true,patch:{kind:"respond",status:401,statusText:"Unauthorized"}},{id:"404",label:"Not found",code:"404",danger:true,patch:{kind:"respond",status:404,statusText:"Not Found"}},{id:"403",label:"Forbidden",code:"403",danger:true,patch:{kind:"respond",status:403,statusText:"Forbidden"}},{id:"429",label:"Rate limited",code:"429",danger:true,patch:{kind:"respond",status:429,statusText:"Too Many Requests"}},{id:"503",label:"Unavailable",code:"503",danger:true,patch:{kind:"respond",status:503,statusText:"Service Unavailable"}},{id:"400",label:"Bad request",code:"400",danger:true,patch:{kind:"respond",status:400,statusText:"Bad Request"}},{id:"200",label:"Success",code:"200",patch:{kind:"respond",status:200,statusText:"OK"}},{id:"offline",label:"Offline",danger:true,patch:{kind:"fail",failKind:"network"}},{id:"timeout",label:"Timeout",danger:true,patch:{kind:"fail",failKind:"timeout"}},{id:"passthrough",label:"Real response",patch:{kind:"delay"}}];function ap(e){return e.kind==="delay"?"passthrough":e.kind==="fail"?e.failKind==="timeout"?"timeout":"offline":String(e.status??200)}function lp({outcome:e,active:t,onPress:r}){let o=e.danger?G.semantic.error:G.semantic.info;return qe(F,{onPress:r,"sentry-label":"ignore override outcome",testID:`buoy-network-outcome-${e.label.toLowerCase().replace(/\s+/g,"-")}${e.code?`-${e.code}`:""}`,accessibilityRole:"button",accessibilityLabel:`${e.label}${e.code?` ${e.code}`:""}`,style:[j.outcome,t&&{borderColor:o,backgroundColor:`${o}1F`}],children:[X(b,{style:[j.outcomeLabel,t&&{color:o}],children:e.label}),e.code?X(b,{style:[j.outcomeCode,t&&{color:o}],children:e.code}):null]})}function Gs({title:e,summary:t,open:r,onToggle:o,children:n}){return qe(m,{style:j.disclosure,children:[qe(F,{onPress:o,"sentry-label":"ignore override disclosure",testID:`buoy-network-disclosure-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,style:j.disclosureHeader,children:[r?X(Uh,{size:12,color:G.text.muted}):X(_h,{size:12,color:G.text.muted}),X(b,{style:j.disclosureTitle,children:e}),t&&!r?X(b,{style:j.disclosureSummary,numberOfLines:1,children:t}):null]}),r?X(m,{style:j.disclosureBody,children:n}):null]})}function or({label:e,active:t,onPress:r}){return X(F,{onPress:r,"sentry-label":"ignore override chip",testID:`buoy-network-chip-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,style:[j.chip,t&&j.chipActive],children:X(b,{style:[j.chipText,t&&j.chipTextActive],children:e})})}function dp({draft:e,onChange:t,onSave:r,onCancel:o,saveLabel:n="Save",applySafeAreaInset:i=false}){let s=Xh({minBottom:16}),l=i?s.bottom:0,a=S=>t({...e,...S}),[u,d]=ho(!e.urlPattern.trim()),[g,x]=ho(false),[y,R]=ho(null),[h,C]=ho(null),k=ap(e),w=e.kind==="respond"&&typeof e.status=="number"&&!Js.some(S=>S.code===String(e.status)),I=e.kind==="respond",z=e.methods?.[0],$=`${z??"Any"} ${e.urlPattern||"No URL yet"}`,P=Ns(()=>{let S=(e.body??"").trim();if(!S)return"Empty";let D=S.split(`
144
- `).length;return`${D} line${D===1?"":"s"}`},[e.body]),A=Ns(()=>{let S=(e.body??"").trim();if(!S)return null;try{return JSON.parse(S)}catch{return null}},[e.body]),v=(e.body??"").trim().length>0&&!A,c=e.delayMs??0,p=c>0&&!Xs.includes(c),f=!e.alternate&&typeof e.times=="number"&&e.times!==1;return qe(m,{style:j.root,children:[qe(yt,{testID:"buoy-network-editor-scroll",style:j.scroll,contentContainerStyle:j.scrollContent,keyboardShouldPersistTaps:"handled",children:[qe(Gs,{title:"Applies to",summary:$,open:u,onToggle:()=>d(S=>!S),children:[X(Jt,{style:j.input,value:e.urlPattern,onChangeText:S=>a({urlPattern:S}),testID:"buoy-network-override-pattern",accessibilityLabel:"Override URL pattern",placeholder:"https://api.example.com/v1/users*",placeholderTextColor:G.text.muted,autoCapitalize:"none",autoCorrect:false,multiline:true,"sentry-label":"ignore override url pattern"}),qe(m,{style:j.chipRow,children:[X(or,{label:"Any",active:!z,onPress:()=>a({methods:void 0})}),sp.map(S=>X(or,{label:S,active:z===S,onPress:()=>a({methods:[S]})},S))]})]}),qe(m,{style:j.outcomeGrid,children:[Js.map(S=>X(lp,{outcome:S,active:k===S.id,onPress:()=>a(S.patch)},S.id)),X(F,{onPress:()=>C("status"),"sentry-label":"ignore custom status",accessibilityLabel:"Custom status code",style:[j.customField,w&&j.customFieldActive],children:X(b,{style:[j.customValue,w&&j.customInputActive],children:w?String(e.status):"Custom"})})]}),I?X(Gs,{title:"Response body",summary:P,open:g,onToggle:()=>x(S=>!S),children:y!==null?qe(_s,{children:[X(Jt,{style:[j.input,j.bodyInput],value:y,onChangeText:R,placeholder:"Paste a new body\u2026",placeholderTextColor:G.text.muted,autoCapitalize:"none",autoCorrect:false,autoFocus:true,multiline:true,"sentry-label":"ignore override body paste"}),qe(m,{style:j.inlineActions,children:[X(F,{onPress:()=>R(null),"sentry-label":"ignore cancel body paste",style:j.textButton,children:X(b,{style:j.textButtonMuted,children:"Cancel"})}),X(F,{onPress:()=>{let S=y.trim();try{a({body:JSON.stringify(JSON.parse(S),null,2)})}catch{a({body:S})}R(null)},disabled:!y.trim(),"sentry-label":"ignore apply body paste",style:j.textButton,children:X(b,{style:[j.textButtonLabel,!y.trim()&&j.textButtonDisabled],children:"Replace"})})]})]}):qe(_s,{children:[A!==null?X(Fs.Provider,{value:{root:A,onChange:S=>a({body:JSON.stringify(S,null,2)})},children:X(Rn,{editable:true,label:"",value:A,defaultExpanded:[""]})}):X(b,{style:j.emptyBody,children:v?"This body isn't JSON, so there's no tree to show.":"No body yet."}),X(F,{onPress:()=>R(""),"sentry-label":"ignore edit all body",style:j.textButton,children:X(b,{style:j.textButtonLabel,children:"Edit all"})})]})}):null,qe(m,{style:j.field,children:[X(b,{style:j.subLabel,children:"Delay"}),qe(m,{style:j.chipRow,children:[Xs.map(S=>X(or,{label:S===0?"None":`${S/1e3}s`,active:c===S,onPress:()=>a({delayMs:S})},S)),X(F,{onPress:()=>C("delay"),"sentry-label":"ignore custom delay",accessibilityLabel:"Custom delay in seconds",style:[j.customField,p&&j.customFieldActive],children:X(b,{style:[j.customValue,p&&j.customInputActive],children:p?`${c/1e3}s`:"Custom"})})]})]}),qe(m,{style:j.field,children:[X(b,{style:j.subLabel,children:"Fires"}),X(b,{style:j.subHint,children:"A limited rule switches itself off once it's used up. Every other alternates forever \u2014 the first request through, the next overridden."}),qe(m,{style:j.chipRow,children:[X(or,{label:"Always",active:!e.alternate&&e.times==null,onPress:()=>a({alternate:false,times:null})}),X(or,{label:"Once",active:!e.alternate&&e.times===1,onPress:()=>a({alternate:false,times:1})}),X(or,{label:"Every other",active:e.alternate===true,onPress:()=>a({alternate:true,times:null})}),X(F,{onPress:()=>{a({alternate:false}),C("times")},"sentry-label":"ignore custom times",accessibilityLabel:"Custom number of times",style:[j.customField,f&&j.customFieldActive],children:X(b,{style:[j.customValue,f&&j.customInputActive],children:f?`${e.times}\xD7`:"Custom"})})]})]})]}),h==="status"?X(In,{title:"Custom status code",hint:`${cr}\u2013${hr}`,value:w?e.status:void 0,min:cr,max:hr,onSubmit:S=>{a({kind:"respond",status:S??void 0,statusText:void 0}),C(null)},onCancel:()=>C(null)}):null,h==="delay"?X(In,{title:"Custom delay",hint:"Seconds",value:p?c/1e3:void 0,min:0,onSubmit:S=>{a({delayMs:S!=null?Math.round(S*1e3):0}),C(null)},onCancel:()=>C(null)}):null,h==="times"?X(In,{title:"Fires how many times",hint:"Leave empty for always",value:f?e.times:void 0,min:1,onSubmit:S=>{a({alternate:false,times:S&&S>0?S:null}),C(null)},onCancel:()=>C(null)}):null,qe(m,{style:[j.footer,{paddingBottom:12+l}],children:[X(F,{onPress:o,"sentry-label":"ignore cancel override",testID:"buoy-network-editor-cancel",accessibilityRole:"button",accessibilityLabel:"Cancel",style:[j.footerButton,j.cancelButton],children:X(b,{style:j.cancelText,children:"Cancel"})}),X(F,{onPress:r,disabled:!e.urlPattern.trim(),"sentry-label":"ignore save override",testID:"buoy-network-editor-save",accessibilityRole:"button",accessibilityLabel:n,style:[j.footerButton,j.saveButton,!e.urlPattern.trim()&&j.saveButtonDisabled],children:X(b,{style:j.saveText,children:n})})]})]})}var j=ve.create({root:{flex:1},scroll:{flex:1},scrollContent:{padding:12,paddingBottom:24,gap:4},field:{gap:8,paddingVertical:6},outcomeGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,paddingVertical:10},outcome:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:9,borderRadius:6,borderWidth:1,borderColor:G.border.default,backgroundColor:G.background.card},outcomeLabel:{fontSize:12,fontWeight:"600",color:G.text.primary},outcomeCode:{fontSize:10,fontWeight:"700",color:G.text.muted},disclosure:{borderRadius:6,borderWidth:1,borderColor:G.border.default,backgroundColor:G.background.card,overflow:"hidden"},disclosureHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:10},disclosureTitle:{fontSize:12,fontWeight:"600",color:G.text.primary},disclosureSummary:{flex:1,textAlign:"right",fontSize:11,color:G.text.muted},disclosureBody:{paddingHorizontal:10,paddingBottom:10,gap:8},input:{backgroundColor:G.background.input,borderWidth:1,borderColor:G.border.input,borderRadius:6,paddingHorizontal:10,paddingVertical:8,color:G.text.primary,fontSize:12,fontFamily:Jh,minHeight:40},bodyInput:{minHeight:140,textAlignVertical:"top"},chipRow:{flexDirection:"row",flexWrap:"wrap",gap:6},chip:{paddingHorizontal:10,paddingVertical:6,borderRadius:5,borderWidth:1,borderColor:G.border.default,backgroundColor:G.background.base},chipActive:{borderColor:G.semantic.info,backgroundColor:`${G.semantic.info}1F`},chipText:{fontSize:11,fontWeight:"600",color:G.text.secondary},chipTextActive:{color:G.semantic.info},customField:{flexDirection:"row",alignItems:"center",paddingHorizontal:8,borderRadius:5,borderWidth:1,borderColor:G.border.default,backgroundColor:G.background.base},customFieldActive:{borderColor:G.semantic.info,backgroundColor:`${G.semantic.info}1F`},customValue:{paddingVertical:6,fontSize:11,fontWeight:"600",color:G.text.secondary},customInputActive:{color:G.semantic.info},subHint:{fontSize:10,lineHeight:14,color:G.text.muted,marginTop:-2},subLabel:{fontSize:10,fontWeight:"700",letterSpacing:.6,color:G.text.muted,textTransform:"uppercase"},textButton:{alignSelf:"flex-start",paddingVertical:4},textButtonLabel:{fontSize:11,fontWeight:"600",color:G.semantic.info},textButtonMuted:{fontSize:11,fontWeight:"600",color:G.text.secondary},textButtonDisabled:{opacity:.4},inlineActions:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},emptyBody:{fontSize:11,color:G.text.muted,paddingVertical:6},footer:{flexDirection:"row",gap:8,padding:12,borderTopWidth:1,borderTopColor:G.border.default,backgroundColor:G.background.base},footerButton:{flex:1,paddingVertical:11,borderRadius:6,alignItems:"center",borderWidth:1},cancelButton:{borderColor:G.border.default,backgroundColor:G.background.card},cancelText:{fontSize:12,fontWeight:"600",color:G.text.secondary},saveButton:{borderColor:G.semantic.info,backgroundColor:`${G.semantic.info}22`},saveButtonDisabled:{opacity:.4},saveText:{fontSize:12,fontWeight:"700",color:G.semantic.info}});import{jsx as ge,jsxs as Wt}from"react/jsx-runtime";function up(){return{enabled:true,urlPattern:"",kind:"respond",status:500,body:"",times:null}}function cp(e){let{id:t,hits:r,seen:o,createdAt:n,...i}=e;return i}function hp(e){let t=e.urlPattern,r=t.indexOf("://");if(r===-1)return t;let o=t.indexOf("/",r+3);return o===-1?t.slice(r+3):t.slice(o)}function pp(e){let t=[];return e.delayMs&&t.push(`${e.delayMs/1e3}s delay`),e.alternate?t.push("every other"):e.times===1?t.push("once"):typeof e.times=="number"&&t.push(`${e.times}\xD7`),t.join(" \xB7 ")}function fp(e){if(e.kind==="fail")return oe.semantic.error;if(e.kind==="delay")return oe.semantic.info;let t=e.status??200;return t>=200&&t<300?oe.semantic.success:t>=300&&t<400?oe.semantic.info:oe.semantic.error}function yp({rule:e,spent:t,onEdit:r,onDelete:o}){let n=e.enabled&&!t,i=fp(e),s=pp(e),l=e.methods?.length?e.methods.join("/"):"ANY";return Wt(Mh,{onPress:r,style:he.cardWrapper,contentStyle:[he.card,{borderLeftColor:n?i:"transparent"}],children:[ge($h,{method:l,size:"small"}),Wt(m,{style:he.cardMiddle,children:[ge(b,{style:[he.urlText,!n&&he.urlTextOff],numberOfLines:2,children:hp(e)}),s?ge(b,{style:he.extrasText,children:s}):null]}),e.hits>0?ge(b,{style:he.rowHits,children:e.hits}):null,e.kind==="fail"?Wt(m,{style:he.failBadge,children:[ge(Ah,{size:10,color:oe.semantic.error}),ge(b,{style:he.failText,children:e.failKind==="timeout"?"TIMEOUT":"OFFLINE"})]}):ge(b,{style:[he.statusText,{color:i}],children:e.kind==="delay"?"PASS":String(e.status??200)}),ge(F,{onPress:o,"sentry-label":"ignore delete override rule",testID:"buoy-network-rule-delete",accessibilityRole:"button",accessibilityLabel:"Delete rule",hitSlop:{top:8,bottom:8,left:4,right:4},style:he.rowDelete,children:ge(jh,{size:13,color:oe.text.muted})})]})}function gp(e){return e.visible?ge(mp,{...e}):null}function mp({isPro:e,onUpgradePress:t,pendingDraft:r,onPendingConsumed:o,backHandlerRef:n,applySafeAreaInset:i}){let s=Wh("network.overrideRules"),l=e?Ze:s,{enabled:a,autoPaused:u,rules:d,activeCount:g,setEnabled:x,upsertRule:y,setRuleEnabled:R,removeRule:h,isRuleSpent:C}=lo(),[k,w]=Dh(null);co(()=>{_.noteHealthyLaunch()},[]),co(()=>{if(n)return n.current=k?()=>(w(null),true):null,()=>{n.current=null}},[n,k]);let I=zh(v=>{_.fetchRuleBody(v).then(c=>{c!=null&&w(p=>p?.id===v?{...p,draft:{...p.draft,body:c,bodyOmitted:void 0}}:p)})},[]);co(()=>{if(!r)return;let{id:v,...c}=r;w({id:v,draft:c}),v&&c.bodyOmitted&&I(v),o?.()},[r,o,I]),co(()=>{k?.id&&(d.some(v=>v.id===k.id)||w(null))},[k?.id,d]);let z=v=>{w({id:v.id,draft:cp(v)}),v.bodyOmitted&&I(v.id)},$=v=>{d.filter(c=>c.enabled&&!C(c)).length<=l||d.filter(c=>c.enabled&&!C(c)&&c.id!==v).forEach(c=>R(c.id,false))},P=()=>{if(!k)return;let v={...k.draft,enabled:true,urlPattern:k.draft.urlPattern.trim()};if(!v.urlPattern)return;let c=y({...v,id:k.id});$(c?.id??k.id),x(true),w(null)};if(k)return ge(dp,{draft:k.draft,onChange:v=>w({...k,draft:v}),onSave:P,onCancel:()=>w(null),saveLabel:k.id?"Save":"Add",applySafeAreaInset:i});let A=d.length>0;return Wt(m,{style:he.root,children:[A?Wt(m,{style:[he.bar,a&&g>0&&he.barOn],children:[a&&g>0?ge(Hh,{size:12,color:oe.semantic.warning}):null,ge(b,{style:[he.barText,a&&g>0&&he.barTextOn],numberOfLines:2,children:u?"Overrides paused \u2014 they'd been on for 3 launches":a&&g>0?`${g} override${g===1?" is":"s are"} on`:"Overrides are off"}),ge(F,{onPress:()=>x(!(a&&g>0)),"sentry-label":"ignore toggle overrides master",testID:"buoy-network-overrides-master",accessibilityRole:"button",style:he.barButton,children:ge(b,{style:he.barButtonText,children:a&&g>0?"Turn all off":u?"Turn back on":"Turn on"})})]}):null,Wt(m,{style:he.listHeader,children:[ge(b,{style:he.listHeaderText,children:A?`${d.length} rule${d.length===1?"":"s"}`:""}),ge(F,{onPress:()=>w({draft:up()}),"sentry-label":"ignore new override rule",accessibilityLabel:"New override rule",style:he.newButton,children:ge(Fh,{size:14,color:oe.semantic.info})})]}),A?Wt(yt,{style:he.list,contentContainerStyle:he.listContent,keyboardShouldPersistTaps:"handled",children:[d.map(v=>ge(yp,{rule:v,spent:C(v),onEdit:()=>z(v),onDelete:()=>h(v.id)},v.id)),l<Ze?ge(b,{style:he.footNote,children:`Your plan: ${l} override at a time. Pro: up to ${Ze}.`}):null]}):ge(m,{style:he.emptyWrap,children:ge(Nh,{otto:"empty",iconSize:32,title:"Nothing overridden",description:"Open any request and tap Override, or + to write a rule."})})]})}var he=ve.create({root:{flex:1},bar:{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:12,paddingVertical:10,borderBottomWidth:1,borderBottomColor:oe.border.default,backgroundColor:oe.background.card},barOn:{borderBottomColor:oe.semantic.warning+"44",backgroundColor:oe.semantic.warningBackground},barText:{flex:1,fontSize:12,fontWeight:"600",color:oe.text.secondary},barTextOn:{color:oe.semantic.warning},barButton:{paddingHorizontal:10,paddingVertical:6,borderRadius:5,borderWidth:1,borderColor:oe.border.hover,backgroundColor:oe.background.base},barButtonText:{fontSize:11,fontWeight:"700",color:oe.text.primary},listHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:12,paddingTop:10,paddingBottom:4},listHeaderText:{fontSize:10,fontWeight:"700",letterSpacing:.6,color:oe.text.muted,textTransform:"uppercase"},newButton:{padding:6,borderRadius:5,borderWidth:1,borderColor:oe.border.default,backgroundColor:oe.background.card},emptyWrap:{flex:1,justifyContent:"center"},list:{flex:1},listContent:{padding:10,gap:6},cardWrapper:{marginHorizontal:0,marginVertical:0},card:{flexDirection:"row",alignItems:"center",gap:8,borderLeftWidth:3,borderLeftColor:"transparent"},cardMiddle:{flex:1},urlText:{fontSize:12,color:oe.text.primary,lineHeight:16,fontFamily:Vh},urlTextOff:{color:oe.text.muted},extrasText:{fontSize:10,color:oe.text.secondary,marginTop:2},statusText:{fontSize:11,fontWeight:"600"},failBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:oe.semantic.error+"26",borderRadius:3},failText:{fontSize:10,color:oe.semantic.error,fontWeight:"600"},rowHits:{fontSize:11,fontWeight:"700",color:oe.semantic.warning},rowDelete:{padding:5,borderRadius:5,borderWidth:1,borderColor:oe.border.default,backgroundColor:oe.background.base},footNote:{fontSize:10,lineHeight:14,color:oe.text.muted,paddingHorizontal:4,paddingTop:8}});O();Se();import{FlaskConical as bp,night as Vt}from"@buoy-gg/shared-ui/web";import{jsx as Pn,jsxs as vp}from"react/jsx-runtime";function Sp({onPress:e}){let{activeCount:t}=lo(),r=t>0;return vp(F,{onPress:e,"sentry-label":"ignore open overrides",testID:"buoy-network-overrides",accessibilityRole:"button",style:[bo.button,r&&bo.buttonActive],accessibilityLabel:r?`Response overrides \u2014 ${t} active`:"Response overrides",children:[Pn(bp,{size:14,color:r?Vt.color.warning:Vt.color.textSecondary}),r?Pn(m,{style:bo.badge,children:Pn(b,{style:bo.badgeText,children:t})}):null]})}var bo=ve.create({button:{width:32,height:32,borderRadius:8,alignItems:"center",justifyContent:"center",backgroundColor:Vt.color.buttonSurface,borderWidth:1,borderColor:Vt.color.border},buttonActive:{backgroundColor:Vt.color.warningSoft,borderColor:Vt.color.warning+"77"},badge:{position:"absolute",top:1,right:1,minWidth:12,height:12,borderRadius:6,paddingHorizontal:3,alignItems:"center",justifyContent:"center",backgroundColor:Vt.color.warning},badgeText:{fontSize:8,fontWeight:"800",color:"#000000"}});O();Se();import{night as nr}from"@buoy-gg/shared-ui/web";O();function wp(e){let t=e.indexOf("?");return t===-1?e:`${e.slice(0,t)}*`}function xp(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return""}}function Ln(e){return{enabled:true,name:void 0,urlPattern:wp(e.url),methods:[String(e.method||"GET").toUpperCase()],kind:"respond",status:e.status&&e.status>=200?e.status:200,statusText:e.statusText,body:xp(e.responseData),times:null}}import{jsx as Ks}from"react/jsx-runtime";function Cp({onOpen:e}){let t=vn(),{rules:r,isRuleSpent:o}=lo(),n=t?te.getEvents().find(l=>l.id===t)??fe.getEventById(t):null,i=n?r.find(l=>l.enabled&&!o(l)&&_o(l,n.url,String(n.method||"GET")))??null:null,s=i!==null;return Ks(F,{onPress:()=>{if(n){if(i){let{id:l,hits:a,seen:u,createdAt:d,...g}=i;e(g,l);return}e(Ln(n))}},"sentry-label":"ignore open overrides",testID:"buoy-network-override-request",accessibilityRole:"button",accessibilityLabel:s?"Edit the override on this request":"Override this request",style:[vo.button,s&&vo.buttonActive],children:Ks(b,{style:[vo.label,s&&vo.labelActive],children:"Override"})})}var vo=ve.create({button:{paddingHorizontal:10,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:nr.color.border,backgroundColor:nr.color.buttonSurface},buttonActive:{borderColor:nr.color.warning+"77",backgroundColor:nr.color.warningSoft},label:{fontSize:11,fontWeight:"700",color:nr.color.accent},labelActive:{color:nr.color.warning}});O();Se();import{absoluteFill as Ys,night as xt}from"@buoy-gg/shared-ui/web";import{jsx as ht,jsxs as So}from"react/jsx-runtime";function kp({onPress:e,isOpen:t,hasIndicator:r}){return So(F,{onPress:e,"sentry-label":"ignore toggle header menu",testID:"buoy-network-menu",accessibilityRole:"button",accessibilityLabel:t?"Close menu":"More actions",style:[Be.button,t&&Be.buttonOpen],children:[So(m,{style:Be.dots,children:[ht(m,{style:[Be.dot,t&&Be.dotOpen]}),ht(m,{style:[Be.dot,t&&Be.dotOpen]}),ht(m,{style:[Be.dot,t&&Be.dotOpen]})]}),r?ht(m,{style:Be.indicator}):null]})}function Tp({onClose:e,children:t}){return So(m,{style:Be.overlay,children:[ht(F,{style:Be.backdrop,activeOpacity:1,onPress:e,"sentry-label":"ignore dismiss header menu"}),ht(m,{style:Be.panel,children:t})]})}function wo({icon:e,label:t,detail:r,testID:o,onPress:n}){return So(F,{onPress:n,"sentry-label":"ignore header menu item",testID:o,accessibilityRole:"button",accessibilityLabel:t,style:Be.item,children:[ht(m,{style:Be.itemIcon,children:e}),ht(b,{style:Be.itemLabel,children:t}),r?ht(b,{style:Be.itemDetail,children:r}):null]})}var Be=ve.create({button:{width:32,height:32,borderRadius:8,alignItems:"center",justifyContent:"center"},buttonOpen:{backgroundColor:xt.color.surfaceElevated},dots:{flexDirection:"column",gap:2.5,alignItems:"center"},dot:{width:3,height:3,borderRadius:2,backgroundColor:xt.color.textSecondary},dotOpen:{backgroundColor:xt.color.text},indicator:{position:"absolute",top:6,right:8,width:6,height:6,borderRadius:3,backgroundColor:xt.color.accent},overlay:{...Ys,zIndex:50},backdrop:{...Ys,backgroundColor:"rgba(0,0,0,0.5)"},panel:{position:"absolute",top:6,right:8,minWidth:196,paddingVertical:4,borderRadius:10,borderWidth:1,borderColor:xt.color.border,backgroundColor:xt.color.surface},item:{flexDirection:"row",alignItems:"center",gap:10,paddingHorizontal:12,paddingVertical:11},itemIcon:{width:16,alignItems:"center"},itemLabel:{flex:1,fontSize:13,fontWeight:"600",color:xt.color.text},itemDetail:{fontSize:11,color:xt.color.textTertiary}});O();import{memo as Rp,useEffect as Ep,useMemo as Ip}from"react";import{EventStepperFooter as Pp,useLimit as Lp}from"@buoy-gg/shared-ui/web";import{jsx as Bp}from"react/jsx-runtime";var qp=()=>nt.step(-1),Op=()=>nt.step(1),zp=Rp(function({paused:e,filter:t,ignoredPatterns:r,isPro:o,fromSaved:n,savedSearch:i,applySafeAreaInset:s}){let{visibleEvents:l}=kr({filter:t,ignoredPatterns:r,paused:e,isPro:o}),{pinnedEvents:a,pinnedLiveIds:u,savedRecords:d}=Zt(),g=Lp("network.saved"),x=Ip(()=>{if(n)return Hs(d,g,i).events;let{pinned:h,rest:C}=xn(l,a,u);return h.length===0?C:[...h,...C]},[n,d,i,o,l,a,u]);Ep(()=>{nt.setIds(wc(x))},[x]);let{index:y,total:R}=kc();return y<0?null:Bp(Pp,{currentIndex:y,totalItems:R,itemLabel:"Request",applySafeAreaInset:s,onPrevious:qp,onNext:Op,variant:"night"})});O();import{useEffect as Dp,useState as Ap}from"react";function Hp(e){return te.getEvents().find(t=>t.id===e)??fe.getEventById(e)}function Zs(e,t={}){let{paused:r=false}=t,[o,n]=Ap(null);return Dp(()=>{if(!(!e||r))return te.subscribeToEvents(i=>{let s=i.find(l=>l.id===e);s&&n(l=>l&&l.id===e&&l.event===s?l:{id:e,event:s})})},[e,r]),e?o&&o.id===e?o.event:Hp(e):null}import{Fragment as Mp,jsx as W,jsxs as Je}from"react/jsx-runtime";function Np({visible:e,paused:t,ignoredPatternValues:r,onTogglePattern:o,isPro:n,filter:i,ignoredPatterns:s,fromSaved:l,savedSearch:a,applySafeAreaInset:u}){let d=vn(),g=Cc(),x=d!=null&&d===g,y=Zs(d,{paused:t||!e});return Dt(()=>{e&&y&&x&&nt.reportRendered(y.id)},[e,y,x]),e?Je(m,{style:Ut.detailRoot,children:[y?W(ss,{event:y,ignoredPatterns:r,onTogglePattern:o,showBodies:x}):W(m,{style:Ut.detailBodyFallback}),W(zp,{paused:t,filter:i,ignoredPatterns:s,isPro:n,fromSaved:l,savedSearch:a,applySafeAreaInset:u})]}):null}function $p({visible:e,paused:t,isPro:r,filter:o,onFilterChange:n,ignoredPatterns:i,onRemovePattern:s,onAddPattern:l,onTogglePatternMode:a,isTeamPattern:u}){let{events:d}=kr({filter:o,ignoredPatterns:i,paused:t,visible:e,isPro:r});return e?W(iu,{events:d,filter:o,onFilterChange:n,ignoredPatterns:i,onRemovePattern:s,onAddPattern:l,onTogglePatternMode:a,isTeamPattern:u}):null}function Fp({visible:e,paused:t,isPro:r,filter:o,ignoredPatterns:n,settings:i,onSettingsChange:s}){let{events:l}=kr({filter:o,ignoredPatterns:n,paused:t,visible:e,isPro:r});return e?W(Xu,{settings:i,onSettingsChange:s,events:l}):null}function Qs({visible:e,onClose:t,onBack:r,onMinimize:o,enableSharedModalDimensions:n=false,inline:i=false,paused:s,onPausedChange:l,remoteConditions:a}){let{isPro:u}=Fd(),[d,g]=Te(false),x=s!=null&&l!=null,y=x?s:d,R=re=>{let We=typeof re=="function"?re(y):re;x?l(We):g(We)},[h,C]=Te({}),k=xc(),[w,I]=Te(false),[z,$]=Te(false),[P,A]=Te(false),[v,c]=Te(false),[p,f]=Te(0),[S]=Te(qd);Dt(()=>{S.update(a)},[S,a]),Dt(()=>()=>S.update(void 0),[S]);let D=true,[H,V]=Te(null),[Z,Y]=Te("filters"),[L,M]=Te(""),[N,J]=Te(false),le=Xr(false),[ne,K]=Te(""),be=Xr(null),{patterns:pe,values:ft,add:Ae,remove:Ye,toggle:Eo,toggleMode:da,isTeamOnly:ua}=Vd(),[sr,Nn]=Te(ju),Io=Xr(false),[Po,Lo]=Te(false),[_t,ca]=Te("export"),ar=re=>{ca(re),Lo(true)};Dt(()=>{Po&&u&&Lo(false)},[Po,u]),Dt(()=>{if(!e||Io.current)return;(async()=>{try{let re=await Vi.getItem(Jr.network.copyOptions());if(re){let We=JSON.parse(re);Nn(We)}}catch{}finally{Io.current=true}})()},[e]),Dt(()=>{if(!Io.current)return;(async()=>{try{await Vi.setItem(Jr.network.copyOptions(),JSON.stringify(sr))}catch{}})()},[sr]);let ha=()=>{nt.clear()},$n=ln(re=>{nt.select(re.id)},[]),pa=ln((re,We)=>{V(We?{...re,id:We}:re),A(true),nt.clear()},[]),fa=ln(()=>V(null),[]),Fn=Xr(null),jn=re=>{M(re),C(We=>({...We,searchText:re}))},ya=re=>{C(We=>({...We,status:We.status===re?void 0:re}))},[Wn,ga]=Te("bottomSheet"),ma=re=>{ga(re)};Dt(()=>{N&&requestAnimationFrame(()=>{be.current?.focus()})},[N]);let Vn=()=>w?Je(ke,{children:[W(ke.Navigation,{onBack:()=>I(false)}),W(ke.Content,{title:"",noMargin:true,children:W($d,{size:"sm",tabs:[{key:"filters",label:"Filters"},{key:"copy",label:"Copy"}],activeKey:Z,onChange:re=>Y(re)})})]}):k?Je(ke,{children:[W(ke.Navigation,{onBack:ha}),W(ke.Content,{title:"Request Details",centered:true}),Je(ke.Actions,{children:[D?W(Cp,{onOpen:pa}):null,W(Ls,{isPro:u,onUpgradePress:()=>ar("saved")})]})]}):P&&D?Je(ke,{children:[W(ke.Navigation,{onBack:()=>{Fn.current?.()||(A(false),V(null))}}),W(ke.Content,{title:"Response Overrides",centered:true})]}):z?Je(ke,{children:[W(ke.Navigation,{onBack:()=>$(false)}),W(ke.Content,{title:"Saved Requests",centered:true})]}):Je(ke,{children:[r&&W(ke.Navigation,{onBack:r}),W(ke.Content,{title:"",children:N?W(ke.Search,{value:L,onChangeText:jn,onCancel:()=>{jn(""),J(false)},onDismiss:()=>J(false),dismissOnBlur:true,clearOnlyWhenText:true,placeholder:"Search URL, method, operation, error...",accessibilityLabel:"Search network requests",iconSize:14,testID:"buoy-network-search-input",clearTestID:"buoy-network-search-clear",inputProps:{"sentry-label":"ignore network search header"}}):W(Bc,{activeStatus:h.status,onToggleStatus:ya,ignoredPatterns:pe,paused:y})}),Je(ke.Actions,{children:[W(F,{"sentry-label":"ignore open search",testID:"buoy-network-search-open",accessibilityLabel:"Open search",accessibilityRole:"button",onPress:()=>J(true),style:Ut.headerActionButton,children:W(Dd,{size:14,color:tt.color.textSecondary})}),D?W(Sp,{onPress:()=>A(true)}):null,W(Wd,{isEnabled:!y,onToggle:()=>R(re=>!re),accessibilityLabel:y?"Resume network capture":"Pause network capture",testID:"buoy-network-power"}),W(qc,{paused:y}),W(kp,{onPress:()=>c(re=>!re),isOpen:v,hasIndicator:Bo})]})]}),Bo=!!(h.status||h.method||h.contentType),ba=n?Jr.modal.root():Jr.network.modal();if(!e)return null;let va=k||!w,Un=Je(Mp,{children:[Je(m,{style:Ut.container,children:[W(Np,{visible:k,paused:y,ignoredPatternValues:ft,onTogglePattern:Eo,isPro:u,filter:h,ignoredPatterns:pe,fromSaved:z,savedSearch:ne,applySafeAreaInset:!i&&Wn==="bottomSheet"}),W($p,{visible:w&&Z==="filters"&&!k,paused:y,isPro:u,filter:h,onFilterChange:C,ignoredPatterns:pe,onRemovePattern:Ye,onAddPattern:Ae,onTogglePatternMode:da,isTeamPattern:ua}),W(Fp,{visible:w&&Z==="copy"&&!k,paused:y,isPro:u,filter:h,ignoredPatterns:pe,settings:sr,onSettingsChange:Nn}),W(gp,{visible:D&&P&&!k&&!w,isPro:u,onUpgradePress:()=>ar("overrides"),pendingDraft:H,onPendingConsumed:fa,backHandlerRef:Fn,applySafeAreaInset:!i&&Wn==="bottomSheet"}),W(Ms,{visible:z&&!k&&!w&&!(P&&D),isPro:u,copySettings:sr,search:ne,onSearchChange:K,onEventPress:$n,onUpgradePress:()=>ar("saved")}),W(Ch,{visible:!k&&!w&&!z&&!(P&&D),paused:y,filter:h,ignoredPatterns:pe,isPro:u,searchText:L,onEventPress:$n,onUpgradePress:()=>ar("export")})]}),v?Je(Tp,{onClose:()=>c(false),children:[W(wo,{icon:W(Wi,{size:14,color:tt.color.textSecondary}),label:"Network throttling",testID:"buoy-network-menu-throttling",onPress:()=>{c(false),Fi(a?S:void 0),i||f(re=>re+1)}}),W(wo,{icon:W(Wi,{size:14,color:tt.color.textSecondary}),label:"Speed and link state",testID:"buoy-network-menu-conditions",onPress:()=>{c(false),Fi(a?S:void 0,true),i||f(re=>re+1)}}),W(wo,{icon:W(Ad,{size:14,color:Bo?tt.color.accent:tt.color.textSecondary}),label:"Filters",detail:Bo?"Active":void 0,onPress:()=>{c(false),Y("filters"),I(true)}}),W(wo,{icon:W(Hd,{size:14,color:tt.color.textSecondary}),label:"Saved requests",onPress:()=>{c(false),$(true)}}),W(m,{style:Ut.menuCopyRow,children:W(zc,{isPro:u,filter:h,ignoredPatterns:pe,copySettings:sr,paused:y,onUpgradePress:()=>{c(false),ar("export")},label:"Copy requests"})})]}):null,W(jd,{visible:Po,onClose:()=>Lo(false),featureName:_t==="saved"?"Saved Requests":_t==="overrides"?"Response Overrides":"Network Export",description:_t==="saved"?"Keep the requests that matter. Saved requests survive Clear, app restarts, and the 500-request history cap.":_t==="overrides"?"Force any endpoint to fail, stall or return something else \u2014 no backend changes, no code changes. Free keeps one active rule.":"Export network requests to share with your team, debug APIs, or feed into AI tools.",benefits:_t==="overrides"?[`Run ${Ze} rules at once (free keeps ${Ti})`,"Force a 500, a 401 or an empty list in one tap","Simulate offline, timeouts and slow connections","Rules survive an app reload, so you can test the boot path"]:_t==="saved"?[`Save up to ${vt} requests (free keeps ${vs})`,"Failed requests stay put through a Clear","Snapshots survive an app restart","Export saved requests to teammates or AI assistants"]:["Export to JSON, Markdown, or plain text","Customizable copy presets (URLs only, LLM-ready, full data)","Share request details with teammates","Feed network data directly to AI assistants"]})]});return i?Je(m,{style:Ut.inlineRoot,children:[W(m,{style:Ut.inlineHeader,...Ud,children:Vn()}),Un]}):W(Md,{visible:e,onClose:t,onMinimize:o,minimizeRequest:p,persistenceKey:ba,variant:"night",header:{showToggleButton:true,customContent:Vn()},onModeChange:ma,enablePersistence:true,initialMode:"bottomSheet",enableGlitchEffects:true,disableScrollWrapper:va,styles:{},children:Un})}var Ut=ve.create({container:{flex:1,backgroundColor:"transparent"},detailRoot:{flex:1,minHeight:0},detailBodyFallback:{flex:1},inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:Nd.border.default,backgroundColor:"transparent"},menuCopyRow:{paddingHorizontal:6},headerActionButton:{width:32,height:32,borderRadius:8,backgroundColor:tt.color.buttonSurface,borderWidth:1,borderColor:tt.color.border,alignItems:"center",justifyContent:"center"},activeFilterButton:{backgroundColor:tt.color.accentSoft,borderColor:tt.color.accentBorderStrong}});function ea(e){return W(cn,{children:W(Qs,{...e})})}function jp(e={}){return W(cn,{children:W(Qs,{...e,inline:true,visible:true,onClose:Wp})})}var Wp=()=>{};import{jsx as Vp}from"react/jsx-runtime";var ta=typeof navigator<"u"&&navigator.product==="ReactNative";ta&&_.ensureLoaded();ta&&typeof me<"u"&&me&&te.startBootCapture();var ra=kd({id:"network",name:"NET",description:"Network request logger",slot:"both",icon:({size:e})=>Vp(xd,{size:e}),component:ea,props:{enableSharedModalDimensions:false}}),Up=Cd(ra,e=>({enableSharedModalDimensions:e.enableSharedModalDimensions??false}));O();function _p(){let e=typeof navigator<"u"&&navigator.product==="ReactNative";if(!e&&(typeof window>"u"||typeof document>"u"))return()=>{};_.ensureLoaded();let t=e?()=>{}:$i(),r=te.subscribeToEvents(()=>{}),o=false;return()=>{o||(o=true,t(),r())}}O();import{useState as Bn,useEffect as Xp,useCallback as xo,useMemo as pt,useRef as Jp}from"react";import{useLimit as Gp,TIER_LIMITS as Kp}from"@buoy-gg/shared-ui/web";var fg=Kp["network.requests"].free;function Yp(e={}){let{isPro:t=false}=e,r=Gp("network.requests"),o=t?1/0:r,[n,i]=Bn([]),[s,l]=Bn({}),[a,u]=Bn(true),d=Jp(null);Xp(()=>(a&&(d.current=te.subscribeToEvents(i)),()=>{d.current&&(d.current(),d.current=null)}),[a]);let g=xo(()=>{te.clearEvents(),i([])},[]),x=xo(()=>{u(false)},[]),y=xo(()=>{u(true)},[]),R=pt(()=>s.searchText?s.searchText.toLowerCase():null,[s.searchText]),h=pt(()=>s.method&&s.method.length>0?new Set(s.method):null,[s.method]),C=pt(()=>s.contentType&&s.contentType.length>0?new Set(s.contentType):null,[s.contentType]),k=pt(()=>{let p=[...n];if(h&&(p=p.filter(f=>h.has(f.method))),s.status&&s.status!=="all")switch(s.status){case"success":p=p.filter(f=>f.status&&f.status>=200&&f.status<300);break;case"error":p=p.filter(f=>f.error||f.status&&f.status>=400);break;case"pending":p=p.filter(f=>!f.status&&!f.error);break}return R&&(p=p.filter(f=>f.url.toLowerCase().includes(R)||f.method.toLowerCase().includes(R)||f.path?.toLowerCase().includes(R)||f.host?.toLowerCase().includes(R)||f.error&&f.error.toLowerCase().includes(R)||f.operationName&&f.operationName.toLowerCase().includes(R)||os(f.graphqlVariables,R))),s.host&&(p=p.filter(f=>f.host===s.host)),C&&(p=p.filter(f=>{let S=f.responseHeaders||f.requestHeaders,D=S?.["content-type"]||S?.["Content-Type"]||"";for(let H of C)switch(H){case"JSON":if(D.includes("json"))return true;break;case"XML":if(D.includes("xml"))return true;break;case"HTML":if(D.includes("html"))return true;break;case"TEXT":if(D.includes("text"))return true;break;case"IMAGE":if(D.includes("image"))return true;break;case"VIDEO":if(D.includes("video"))return true;break;case"AUDIO":if(D.includes("audio"))return true;break;case"FORM":if(D.includes("form"))return true;break;case"OTHER":if(!D||!D.includes("json")&&!D.includes("xml")&&!D.includes("html")&&!D.includes("text")&&!D.includes("image")&&!D.includes("video")&&!D.includes("audio")&&!D.includes("form"))return true;break}return false})),p},[n,s,R,h,C]),w=pt(()=>{let p=new Set;return n.slice(o).forEach(f=>{p.add(f.id)}),p},[n,o]),I=pt(()=>k.filter(p=>w.has(p.id)),[k,w]),z=I.length>0,$=I.length,P=xo(p=>w.has(p),[w]),A=pt(()=>{let p=0,f=0,S=0,D=0,H=0,V=0,Z=0;for(let L of n)L.status&&L.status>=200&&L.status<300?p++:L.error||L.status&&L.status>=400?f++:!L.status&&!L.error&&S++,D+=L.requestSize||0,H+=L.responseSize||0,L.duration&&(V+=L.duration,Z++);let Y=Z>0?V/Z:0;return{totalRequests:n.length,successfulRequests:p,failedRequests:f,pendingRequests:S,totalDataSent:D,totalDataReceived:H,averageDuration:Math.round(Y)}},[n]),v=pt(()=>{let p=new Set;for(let f of n)f.host&&p.add(f.host);return Array.from(p)},[n]),c=pt(()=>{let p=new Set;for(let f of n)p.add(f.method);return Array.from(p)},[n]);return{events:k,allEvents:n,stats:A,filter:s,setFilter:l,clearEvents:g,isCapturing:a,pauseCapturing:x,resumeCapturing:y,hosts:v,methods:c,hasLockedEvents:z,lockedEventCount:$,isEventLocked:P,requestLimit:o,getSubscriberCounts:()=>te.getSubscriberCounts()}}import{useIgnoredPatterns as Zp,ignoredPatternsStore as Qp,urlMatchesIgnoredPattern as ef,isUrlIgnored as tf}from"@buoy-gg/shared-ui/web";O();import{approxJsonSize as qn,isOverWireBudget as rf}from"@buoy-gg/shared-ui/web";import{expandKeyedArrays as of,patchFromPath as nf,refusalText as sf,shapeKind as oa,suggestedPatch as af,typedEditViolations as lf}from"@buoy-gg/shared-ui/web";var On=16*1024,Co=1.25*1024*1024;function zn(e,t){return e===void 0?false:(t??0)>On?true:rf(e,On)}var na=new WeakMap,ia=new WeakMap;function Dn(e){let t=na.get(e);if(t)return t;let r;try{r=uf(e)}catch{r=df(e)}return na.set(e,r),r}function df(e){let t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0},r=1024;try{r=qn(t,Co).bytes}catch{}return{event:t,bytes:r}}function uf(e){let t=zn(e.requestData,e.requestSize),r=zn(e.responseData,e.responseSize),o=sa(e.graphqlVariables),n=aa(e.requestHeaders),i=aa(e.responseHeaders),s=t||r||o!==e.graphqlVariables||n!==e.requestHeaders||i!==e.responseHeaders,l=e;return s&&(l={...e},t&&(l.requestData=void 0,l.requestBodyOmitted=true),r&&(l.responseData=void 0,l.responseBodyOmitted=true),o!==e.graphqlVariables&&(l.graphqlVariables=o),n!==e.requestHeaders&&(l.requestHeaders=n,l.headersOmitted=true),i!==e.responseHeaders&&(l.responseHeaders=i,l.headersOmitted=true)),{event:l,bytes:qn(l,Co).bytes}}function cf(e){let t=ia.get(e);if(t)return t;let{event:r}=Dn(e),o={...r};o.requestData!==void 0&&(o.requestData=void 0,o.requestBodyOmitted=true),o.responseData!==void 0&&(o.responseData=void 0,o.responseBodyOmitted=true),o.graphqlVariables!==void 0&&(o.graphqlVariables=sa(o.graphqlVariables,true));let n={event:o,bytes:qn(o,Co).bytes};return ia.set(e,n),n}function hf(e){let t=new Array(e.length),r=0;for(let o=0;o<e.length;o++){let n=Dn(e[o]);if(r+n.bytes<=Co)t[o]=n.event,r+=n.bytes;else{let i=cf(e[o]);t[o]=i.event,r+=i.bytes}}return t}function sa(e,t=false){if(!e||!t&&!zn(e,void 0))return e;let r={};for(let[o,n]of Object.entries(e))(typeof n=="string"&&n.length<=64||typeof n=="number"||typeof n=="boolean")&&(r[o]=n);return Object.keys(r).length>0?r:void 0}var An=64;function aa(e){if(!e)return e;let t=false,r={};for(let[o,n]of Object.entries(e))typeof n=="string"&&(n.length<=An?r[o]=n:(r[o]=`${n.slice(0,An)}\u2026 [${n.length-An} more]`,t=true));return t?r:e}var pf=e=>{let t=false,r=e.rules.map(o=>!o.body||o.body.length<=On?o:(t=true,{...o,body:void 0,bodyOmitted:true}));return t?{...e,rules:r}:e},ko=e=>te.getEventById(e)??fe.getEventById(e),ir=e=>e&&typeof e=="object"?e.id:void 0,To=(e,t)=>!!(e&&typeof e=="object"&&e[t]),Ro=()=>Ql()?{}:{active:false,inactiveReason:ed},ff=["respond","fail","delay"];function yf(e,t){if(!e||typeof e!="object")return null;let r=e.rule??e;if(!r||typeof r!="object")return null;let o=r,n=typeof o.urlPattern=="string"&&o.urlPattern.trim()?o.urlPattern.trim():t?.urlPattern??"";if(!n)return null;let i=ff.includes(o.kind)?o.kind:t?.kind??"respond";return{id:typeof o.id=="string"?o.id:void 0,enabled:o.enabled!==false,name:typeof o.name=="string"?o.name:t?.name,urlPattern:n,methods:Array.isArray(o.methods)?o.methods.filter(s=>typeof s=="string").map(s=>s.toUpperCase()):t?.methods,requireHeader:typeof o.requireHeader=="string"&&o.requireHeader.trim()?o.requireHeader.trim():void 0,bodyIncludes:typeof o.bodyIncludes=="string"&&o.bodyIncludes?o.bodyIncludes.slice(0,4096):t?.bodyIncludes,graphqlOperation:typeof o.graphqlOperation=="string"&&o.graphqlOperation?o.graphqlOperation.slice(0,200):t?.graphqlOperation,graphqlVariables:typeof o.graphqlVariables=="string"?o.graphqlVariables.slice(0,4096):t?.graphqlVariables,sandbox:o.sandbox===true?true:void 0,kind:i,status:typeof o.status=="number"?o.status:t?.status,statusText:typeof o.statusText=="string"?o.statusText:t?.statusText,headers:o.headers&&typeof o.headers=="object"?o.headers:t?.headers,body:mf(o,t),failKind:o.failKind==="timeout"?"timeout":void 0,delayMs:typeof o.delayMs=="number"?o.delayMs:void 0,times:typeof o.times=="number"?o.times:null,alternate:o.alternate===true}}var Hn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Er=e=>Hn(e)||Array.isArray(e);function la(e,t,r="",o={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t))return t.length>0&&t.length<e.length&&o.shrunk.push({path:r||"(root)",have:e.length,sent:t.length}),t;if(!Hn(e)||!Hn(t))return t;let n={...e};for(let[i,s]of Object.entries(t)){let l=r?`${r}.${i}`:i;if(i in e){let a=oa(e[i]),u=oa(s);(a==="array"||a==="object")&&a!==u&&o.breaks.push({path:l,from:a,to:u}),n[i]=la(e[i],s,l,o)}else n[i]=s}return n}function gf(e,t){if(e.body!=null||!Er(e.bodyPatch)||typeof t!="string")return[];try{return lf(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function mf(e,t){if(typeof e.body=="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);let r=t?.body??(Er(e.bodyPatch)&&typeof e.id=="string"?_.getState().rules.find(o=>o.id===e.id)?.body:void 0);if(Er(e.bodyPatch)&&typeof r=="string")try{return JSON.stringify(la(JSON.parse(r),e.bodyPatch),null,2)}catch{return r}return r}function bf(e){if(!e||typeof e!="object")return null;let t=e.rule??e;if(!t||typeof t!="object")return null;let r=t.id;if(typeof r!="string")return null;let o=_.getState().rules.find(n=>n.id===r);return o?{...o}:null}function vf(e){if(!e||typeof e!="object")return null;let t=e.rule??e;if(!t||typeof t!="object")return null;let r=t;if(r.bodyOmitted!==true||typeof r.id!="string")return null;let o=_.getState().rules.find(n=>n.id===r.id);return o?{body:o.body}:null}function Sf(e){if(!e||typeof e!="object")return null;let t=e.fromRequestId;if(typeof t!="string"||!t)return null;let r=ko(t);return r?Ln(r):null}var wf={dispose:()=>{_.setEnabled(false)},version:6,getSnapshot:()=>(te.ensureInterception(),{conditions:Bt(),events:hf(te.getEvents()),overrides:pf(_.getState()),saved:fe.getRecords().map(e=>({...e,event:Dn(e.event).event}))}),subscribe:e=>{let t=te.subscribeToEvents(e),r=et(e),o=fe.subscribe(e),n=_.subscribe(e);return()=>{r(),t(),o(),n()}},actions:{getNetworkConditions:Bt,setNetworkConditions:Nr,clearEvents:()=>{te.clearEvents()},getEventBody:e=>{let t=ir(e);if(!t)return null;let r=ko(t);return r?{url:r.url??null,method:r.method??null,status:r.status??null,override:r.override??null,condition:r.condition??null,requestData:r.requestData??null,responseData:r.responseData??null,requestHeaders:r.requestHeaders??null,responseHeaders:r.responseHeaders??null}:null},setPinned:e=>{let t=ir(e);if(!t)return null;let r=ko(t);if(!r)return null;let o=To(e,"pinned");return to(fe.getState(),t).pinned===o?{ok:true}:fe.togglePin(r)},setSaved:e=>{let t=ir(e);if(!t)return null;let r=ko(t);if(!r)return null;let o=To(e,"saved");return to(fe.getState(),t).saved===o?{ok:true}:fe.toggleSave(r)},removeSavedRecord:e=>{let t=e&&typeof e=="object"?e.key:void 0;return t?(fe.remove(t),{ok:true}):null},clearSavedRequests:()=>(fe.clearSaved(),{ok:true}),clearPinnedRequests:()=>(fe.clearPinned(),{ok:true}),setOverridesEnabled:e=>(_.setEnabled(To(e,"enabled")),{ok:true,enabled:_.getState().enabled,...Ro()}),upsertOverrideRule:e=>{let t=e?.rule??e,r=!!t&&t.body==null&&(Er(t.bodyPatch)||typeof t.bodyPath=="string"),o=Sf(e)??vf(e)??(r?bf(e):null);if(t&&typeof t.bodyPath=="string"&&t.body==null){let s=o?.body??(typeof t.id=="string"?_.getState().rules.find(u=>u.id===t.id)?.body:void 0);if(typeof s!="string")return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."};if(t.bodyValue===void 0)return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${t.bodyPath}" to.`};let l;try{l=JSON.parse(s)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}let a=nf(l,t.bodyPath,t.bodyValue);if(!a.ok)return{ok:false,error:`Refused: ${a.error}`};t.bodyPatch=a.patch,delete t.bodyPath,delete t.bodyValue}if(t&&Er(t.bodyPatch)&&t.body==null){let s=o?.body??(typeof t.id=="string"?_.getState().rules.find(a=>a.id===t.id)?.body:void 0);if(typeof s!="string")return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."};let l;try{let a=of(JSON.parse(s),t.bodyPatch);l=a.error,a.notes.length&&(t.bodyPatch=a.patch)}catch{}if(l)return{ok:false,error:`Refused: ${l}`};if(t.force!==true){let a=gf(t,s);if(a.length>0)return{ok:false,error:sf(a,"response body",af(t.bodyPatch,a)),violations:a}}}let n=yf(e,o);if(!n){let s=e?.fromRequestId;return{ok:false,error:s?`No captured request \`${s}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}let i=_.upsertRule(n);return i?(i.enabled&&_.setEnabled(true),{ok:true,rule:{id:i.id,urlPattern:i.urlPattern,enabled:i.enabled,kind:i.kind,status:i.status,times:i.times,bodySize:i.body?i.body.length:0},...i.times===void 0||i.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${i.id}\`). If you meant only the next one, set times:1.`}:{},...Ro()}):{ok:false,error:"Override rule limit reached."}},setOverrideRuleEnabled:e=>{let t=ir(e);return t?(_.setRuleEnabled(t,To(e,"enabled")),{ok:true,...Ro()}):{ok:false,error:"Missing rule id."}},deleteOverrideRule:e=>{let t=ir(e);return t?(_.removeRule(t),{ok:true}):{ok:false,error:"Missing rule id."}},clearOverrideRules:()=>(_.clearRules(),{ok:true}),replaceOverrideRules:async e=>{let t=e??{};if(!Array.isArray(t.rules))return{ok:false,error:"replaceOverrideRules needs `rules`: an array of rules, first match first."};if(t.rules.length>Ze)return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${Ze}.`};await _.ensureLoaded();let r=_.replaceAllRules(t.rules,t.enabled!==false);return r?{ok:true,count:r.length,enabled:_.getState().enabled,...Ro()}:{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."}},listOverrideRules:async()=>(await _.ensureLoaded(),_.getState()),getOverrideRuleBody:e=>{let t=ir(e);if(!t)return null;let r=_.getState().rules.find(o=>o.id===t);return r?{body:r.body??null}:null},getCaptureStatus:()=>{let e=te.getSubscriberCounts().total,t=null,r=null;try{t=zi(),r=Pt()}catch{}let o=null;try{o=gd()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:o,listenerCount:r,eventCount:te.getEvents().length}},debugOverrides:e=>{let{url:t,method:r}=e&&typeof e=="object"?e:{},o=typeof t=="string"?t:"https://example.com/",n=typeof r=="string"&&r.trim()?r.trim().toUpperCase():"GET";return{tested:{url:o,method:n},interceptorInstalled:zi(),listenerCount:Pt(),engine:td(o,n),store:{enabled:_.getState().enabled,autoPaused:_.getState().autoPaused,ruleCount:_.getState().rules.length,rulesVisibleToEngine:_.getRules().length}}}}};O();var xf=new Set(["content-length","host","connection","accept-encoding"]);function Mn(e){return`'${e.replace(/'/g,"'\\''")}'`}function Cf(e){if(e==null)return null;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return null}}function kf(e){let t=(e.method||"GET").toUpperCase(),r=Cf(e.requestData),o=[];t!=="GET"&&!(t==="POST"&&r!==null)&&o.push(`-X ${t}`);for(let[i,s]of Object.entries(e.requestHeaders||{}))xf.has(i.toLowerCase())||o.push(`-H ${Mn(`${i}: ${s}`)}`);r!==null&&o.push(`--data-raw ${Mn(r)}`);let n=`curl ${Mn(e.url)}`;return o.length===0?n:`${n} \\
142
+ `+o}import{Fragment as op,jsx as Le,jsxs as lr}from"react/jsx-runtime";function np({activeStatus:e,onToggleStatus:t,ignoredPatterns:r,paused:o}){let n=Pa({ignoredPatterns:r,paused:o});return Le(La,{counts:n,activeStatus:e,onToggleStatus:t})}function La({counts:e,activeStatus:t,onToggleStatus:r}){return lr(S,{style:le.headerChipRow,children:[lr(W,{style:[le.headerChip,t==="success"&&le.headerChipActive],onPress:()=>r("success"),children:[Le(Sh,{size:12,color:Ft.semantic.success}),Le(b,{style:[le.headerChipValue,{color:Ft.semantic.success}],children:e.successful})]}),lr(W,{style:[le.headerChip,t==="error"&&le.headerChipActive],onPress:()=>r("error"),children:[Le(kh,{size:12,color:Ft.semantic.error}),Le(b,{style:[le.headerChipValue,{color:Ft.semantic.error}],children:e.failed})]}),lr(W,{style:[le.headerChip,t==="pending"&&le.headerChipActive],onPress:()=>r("pending"),children:[Le(xh,{size:12,color:Ft.semantic.warning}),Le(b,{style:[le.headerChipValue,{color:Ft.semantic.warning}],children:e.pending})]})]})}function ip({paused:e}){let t=tp({paused:e});return Le(W,{"sentry-label":"ignore clear events",testID:"buoy-network-clear",accessibilityLabel:"Clear network requests",accessibilityRole:"button",onPress:()=>ne.clearEvents(),style:[le.headerActionButton,!t&&le.headerActionButtonDisabled],disabled:!t,children:Le(Rh,{size:14,color:t?ue.color.textSecondary:ue.color.textTertiary})})}function sp({onPress:e}){let{savedRecords:t}=kr(),r=t.length;return lr(W,{"sentry-label":"ignore open saved",onPress:e,accessibilityLabel:"Saved requests",style:le.headerActionButton,children:[Le(fa,{size:14,color:r>0?ue.color.accent:ue.color.textSecondary}),r>0?Le(S,{style:le.savedBadge,children:Le(b,{style:le.savedBadgeText,children:r>99?"99+":r})}):null]})}function za({isPro:e,onUpgradePress:t}){let r=si(),o=kr(),{pinned:n,saved:i}=Ho(o,r),s=Ph("network.saved"),d=!n&&o.pinnedEvents.length>=$o,a=!i&&o.savedRecords.length>=s,l=()=>r?ne.getEvents().find(w=>w.id===r)??me.getEventById(r):null,c=()=>{let w=l();w&&o.togglePin(w)},y=()=>{if(a&&!e){t();return}let w=l();w&&o.toggleSave(w)};return lr(op,{children:[Le(W,{"sentry-label":"ignore pin request",onPress:c,disabled:d,testID:"buoy-network-pin",accessibilityRole:"button",accessibilityLabel:n?"Unpin request":"Pin request",accessibilityHint:d?`Pin limit reached (${$o})`:void 0,style:[le.headerActionButton,n&&le.headerActionButtonActive,d&&le.headerActionButtonDisabled],children:Le(Th,{size:14,active:n,color:n?ue.color.accent:d?ue.color.textTertiary:ue.color.textSecondary})}),Le(W,{"sentry-label":"ignore save request",onPress:y,disabled:a&&e,testID:"buoy-network-save",accessibilityRole:"button",accessibilityLabel:i?"Remove from saved":"Save request",accessibilityHint:a&&e?`Saved limit reached (${Wt})`:void 0,style:[le.headerActionButton,i&&le.headerActionButtonSaved,a&&e&&le.headerActionButtonDisabled],children:Le(fa,{size:14,color:i?ue.color.accent:a&&e?ue.color.textTertiary:ue.color.textSecondary})})]})}function ap({isPro:e,filter:t,ignoredPatterns:r,copySettings:o,paused:n,onUpgradePress:i,label:s}){let d=rp({filter:t,ignoredPatterns:r,paused:n});return e?Le(Ih,{value:()=>Ba(Xr(Kr(ne.getEvents(),r),t),o),size:14,label:s,buttonStyle:s?le.copyMenuRow:le.headerActionButton,labelStyle:le.copyMenuLabel,colors:{idle:d?ue.color.textSecondary:ue.color.textTertiary,success:Ft.semantic.success,error:Ft.semantic.error},disabled:!d}):lr(W,{"sentry-label":"ignore copy pro",onPress:i,style:[s?le.copyMenuRow:le.headerActionButton,!d&&le.headerActionButtonDisabled],disabled:!d,children:[Le(Ch,{size:14,color:d?ue.color.textSecondary:ue.color.textTertiary}),s?Le(b,{style:le.copyMenuLabel,children:s}):null]})}var le=se.create({copyMenuRow:{flexDirection:"row",alignItems:"center",gap:10,paddingHorizontal:6,paddingVertical:11,justifyContent:"flex-start"},copyMenuLabel:{fontSize:13,fontWeight:"600",color:ue.color.text},headerChipRow:{flexDirection:"row",alignItems:"center",gap:8},headerChip:{flexDirection:"row",alignItems:"center",gap:4,backgroundColor:ue.color.buttonSurface,paddingHorizontal:10,paddingVertical:5,borderRadius:12,borderWidth:1,borderColor:ue.color.border},headerChipActive:{backgroundColor:ue.color.accentSoft,borderColor:ue.color.accentBorderStrong},headerChipValue:{fontSize:12,fontWeight:"600",fontFamily:ga},headerActionButton:{width:32,height:32,borderRadius:8,backgroundColor:ue.color.buttonSurface,borderWidth:1,borderColor:ue.color.border,alignItems:"center",justifyContent:"center"},headerActionButtonDisabled:{opacity:.55},headerActionButtonActive:{backgroundColor:ue.color.accentSoft,borderColor:ue.color.accentBorderStrong},headerActionButtonSaved:{backgroundColor:ue.color.accentSoft,borderColor:ue.color.accentBorderStrong},savedBadge:{position:"absolute",top:-3,right:-3,minWidth:14,height:14,paddingHorizontal:3,borderRadius:7,backgroundColor:ue.color.accent,alignItems:"center",justifyContent:"center"},savedBadgeText:{color:ue.color.onAccent,fontSize:9,fontWeight:"700",fontFamily:ga}});q();he();import{useCallback as lp}from"react";import{FlaskConical as dp,Pin as cp,Power as up,macOSColors as Ne,ToolEmptyState as hp,resolveListEmptyState as pp,EVENT_LIST_PRESET as fp,monoFont as gp}from"@buoy-gg/shared-ui/web";q();he();import{memo as yp}from"react";import{ChevronRight as mp,Upload as bp,Download as vp,Clock as wp,AlertCircle as Sp,Bookmark as kp,FlaskConical as xp,Pin as Cp,DevToolsCard as Tp,MethodBadge as Rp,TypeBadge as Ip,night as Me,macOSColors as xr,monoFont as ai}from"@buoy-gg/shared-ui/web";import{formatRelativeTime as Pp}from"@buoy-gg/shared-ui/web";import{jsx as ge,jsxs as mt}from"react/jsx-runtime";function Ep(e,t){return t?xr.semantic.error:e?e>=200&&e<300?xr.semantic.success:e>=300&&e<400?xr.semantic.info:e>=400?xr.semantic.error:xr.text.muted:xr.semantic.warning}function Bp(e){let t=e?.["content-type"]||e?.["Content-Type"]||"";return t.includes("json")?"JSON":t.includes("xml")?"XML":t.includes("html")?"HTML":t.includes("text")?"TEXT":t.includes("image")?"IMG":t.includes("video")?"VIDEO":t.includes("audio")?"AUDIO":t.includes("form")?"FORM":null}function Oa(e){switch(e){case"fetch":return{backgroundColor:"rgba(74, 144, 226, 0.15)",color:"#4A90E2"};case"graphql":return{backgroundColor:"rgba(229, 53, 171, 0.15)",color:"#E535AB"};case"grpc-web":return{backgroundColor:"rgba(16, 185, 129, 0.15)",color:"#10B981"};case"xhr":return{backgroundColor:"rgba(245, 158, 11, 0.15)",color:"#F59E0B"};default:return{backgroundColor:"rgba(147, 51, 234, 0.15)",color:"#9333EA"}}}function Lp({event:e,isPending:t,statusColor:r}){return t?mt(S,{style:Se.pendingBadge,children:[ge(wp,{size:10,color:Me.color.warning}),ge(b,{style:Se.pendingText,children:"..."})]}):e.error?mt(S,{style:Se.errorBadge,children:[ge(Sp,{size:10,color:Me.color.danger}),ge(b,{style:Se.errorText,children:"ERR"})]}):ge(S,{style:Se.statusBadge,children:ge(b,{style:[Se.statusText,{color:r}],children:String(e.status)})})}function zp({requestSize:e,responseSize:t}){return!e&&!t?null:mt(S,{style:Se.sizeRow,children:[e?mt(S,{style:Se.sizeItem,children:[ge(bp,{size:8,color:Me.color.info}),ge(b,{style:Se.sizeText,children:Ot(e)})]}):null,t?mt(S,{style:Se.sizeItem,children:[ge(vp,{size:8,color:Me.color.accent}),ge(b,{style:Se.sizeText,children:Ot(t)})]}):null]})}function Op({timestamp:e,duration:t}){let r=Zn(),o=Pp(e,r);return t?mt(b,{style:Se.bottomRightText,children:[No(t)," ",o]}):ge(b,{style:Se.bottomRightText,children:o})}var Cr=yp(function({event:e,onPress:t,pinned:r=false,saved:o=false,overridden:n=false,onLongPress:i}){let s=Ep(e.status,e.error),d=!e.status&&!e.error,a=Bp(e.responseHeaders),l=e.path||e.url.replace(/^https?:\/\/[^/]+/,"");return e.requestClient==="graphql"?e.operationName?l=na(e.operationName,e.graphqlVariables):l=l.replace(/\/graphql[^?]*/,"/graphql"):e.operationName&&(l=`${l}
143
+ (${e.operationName})`),mt(Tp,{onPress:()=>t(e),onLongPress:i?()=>i(e):void 0,style:Se.cardWrapper,contentStyle:[Se.container,{borderLeftColor:s}],testID:`buoy-network-row-${e.id}`,accessibilityLabel:`${e.method} ${e.path||e.url}`,children:[mt(S,{style:Se.topRightContainer,children:[r?ge(Cp,{size:10,active:true,color:Me.color.info}):null,o?ge(kp,{size:10,color:Me.color.accent}):null,n||e.override?ge(xp,{size:10,color:Me.color.warning}):null,ge(Lp,{event:e,isPending:d,statusColor:s}),e.requestClient?ge(S,{style:[Se.topRightBadge,{backgroundColor:Oa(e.requestClient).backgroundColor}],children:ge(b,{style:[Se.clientText,{color:Oa(e.requestClient).color}],children:e.requestClient==="graphql"?"GQL":e.requestClient==="grpc-web"?"gRPC":e.requestClient==="xhr"?"XHR":e.requestClient})}):null]}),mt(S,{style:Se.leftSection,children:[ge(Rp,{method:e.method,size:"small"}),ge(zp,{requestSize:e.requestSize,responseSize:e.responseSize})]}),mt(S,{style:Se.middleSection,children:[ge(b,{style:Se.urlText,numberOfLines:2,children:l}),e.condition?.uploadCap?.note&&ge(b,{testID:`buoy-network-upload-cap-${e.id}`,style:{color:Me.color.warning,fontSize:10},children:e.condition.uploadCap.note})]}),mt(S,{style:Se.rightSection,children:[a?ge(Ip,{type:a,size:"small"}):null,ge(mp,{size:14,color:Me.color.textTertiary})]}),ge(S,{style:Se.bottomRightContainer,children:ge(Op,{timestamp:e.timestamp,duration:e.duration})})]})});Cr.displayName="NetworkEventItemCompact";var Se=se.create({cardWrapper:{marginHorizontal:8},container:{flexDirection:"row",alignItems:"center",backgroundColor:"rgba(12, 12, 12, 0.9)",borderLeftWidth:3,borderLeftColor:"transparent",borderBottomWidth:1},leftSection:{marginRight:8,alignItems:"flex-start"},topRightContainer:{position:"absolute",top:1,right:1,flexDirection:"row",alignItems:"center",gap:4},topRightBadge:{paddingHorizontal:4,paddingVertical:2,borderRadius:4},middleSection:{flex:1,justifyContent:"center",paddingRight:8},urlText:{fontSize:12,color:Me.color.text,lineHeight:16,fontFamily:ai},rightSection:{flexDirection:"row",alignItems:"center",gap:6},bottomRightContainer:{position:"absolute",bottom:4,right:8},bottomRightText:{fontSize:9,color:Me.color.textTertiary,fontFamily:ai},statusBadge:{paddingHorizontal:4,paddingVertical:1,borderRadius:3},statusText:{fontSize:10,fontWeight:"600"},pendingBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:Me.color.warningSoft,borderRadius:3},pendingText:{fontSize:10,color:Me.color.warning,fontWeight:"600"},errorBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:Me.color.dangerSoft,borderRadius:3},errorText:{fontSize:10,color:Me.color.danger,fontWeight:"600"},durationText:{fontSize:9,color:Me.color.textSecondary},sizeRow:{flexDirection:"row",gap:4,marginTop:4},sizeItem:{flexDirection:"row",alignItems:"center",gap:2},sizeText:{fontSize:8,color:Me.color.textSecondary,fontFamily:ai},clientText:{fontSize:8,fontWeight:"700",letterSpacing:.3,textTransform:"uppercase"}});q();he();import{ProBadge as qp,Zap as Dp,buoyColors as Qr}from"@buoy-gg/shared-ui/web";import{jsx as _o,jsxs as li}from"react/jsx-runtime";function qa({title:e,subtitle:t,onPress:r}){return li(W,{style:Yr.banner,onPress:r,activeOpacity:.8,children:[li(S,{style:Yr.content,children:[li(S,{style:Yr.left,children:[_o(Dp,{size:16,color:Qr.primary}),_o(b,{style:Yr.title,children:e})]}),_o(qp,{})]}),_o(b,{style:Yr.subtitle,children:t})]})}var Yr=se.create({banner:{backgroundColor:Qr.card,borderRadius:10,borderWidth:1,borderColor:Qr.primary+"40",padding:12,marginHorizontal:12,marginTop:12,marginBottom:34},content:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",marginBottom:4},left:{flexDirection:"row",alignItems:"center",gap:8},title:{color:Qr.text,fontSize:13,fontWeight:"600"},subtitle:{color:Qr.textMuted,fontSize:11}});q();import{useEffect as Da,useMemo as Vo,useState as Ap}from"react";import{useLimit as Np}from"@buoy-gg/shared-ui/web";function Zr(e){let{filter:t,ignoredPatterns:r,paused:o,visible:n=true,isPro:i}=e,s=Np("network.requests"),d=i?1/0:s,[a,l]=Ap(()=>ne.getEvents());Da(()=>{if(!n)return;if(o){l(ne.getEvents());return}let u=null,R=null,h=ne.subscribeToEvents(m=>{R=m,u==null&&(u=requestAnimationFrame(()=>{u=null,R&&l(R),R=null}))});return()=>{h(),u!=null&&cancelAnimationFrame(u)}},[o,n]),Da(()=>ne.onClear(()=>{l([])}),[]);let c=Vo(()=>Kr(a,r),[a,r]),y=Vo(()=>Xr(c,t),[c,t]),w=Vo(()=>{let u=new Set;return a.slice(d).forEach(R=>{u.add(R.id)}),u},[a,d]),p=Vo(()=>w.size===0?y:y.filter(u=>!w.has(u.id)),[y,w]),C=y.length-p.length;return{events:y,visibleEvents:p,hasLockedEvents:C>0,lockedEventCount:C,totalEvents:c.length}}q();import{useCallback as Tr,useSyncExternalStore as Mp}from"react";q();import{devToolsStorageKeys as Rr,persistentStorage as Aa,setItemChecked as $p}from"@buoy-gg/shared-ui/web";var Hp=800,jp=3;function Fp(){let e=`${Rr.network.overrides()}_launch`;try{let t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(e))return true;t.setItem(e,"1")}catch{}return false}var Na=Object.freeze([]),Ma=()=>`${Rr.base}_bug_links_loaded`;function $a(){if(typeof navigator<"u"&&navigator.product==="ReactNative")return null;try{return globalThis.localStorage??null}catch{return null}}var di={raw:null,blocks:false};function Wp(){let e;try{e=$a()?.getItem(Ma())??null}catch{return false}return e===di.raw||(di={raw:e,blocks:_p(e)}),di.blocks}function _p(e){try{if(!e)return false;let t=JSON.parse(e);return t.block===void 0?t.options?.replay!==false&&t.report?.replay?.active===true:t.block===true}catch{return true}}var Vp=5e3,Up=Object.freeze([Object.freeze({id:"bug-case-other-tab",name:"Bug case (loaded in another tab)",enabled:true,sandbox:true,urlPattern:"*",kind:"fail",failKind:"network"})]),Jp=250,Gp=["respond","fail","delay"];function Ha(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let o=r;if(typeof o.id!="string"||typeof o.urlPattern!="string"||!o.urlPattern)continue;let n=Gp.includes(o.kind)?o.kind:"respond";t.push({id:o.id,enabled:o.enabled!==false,name:typeof o.name=="string"?o.name:void 0,urlPattern:o.urlPattern,methods:Array.isArray(o.methods)?o.methods.filter(i=>typeof i=="string"):void 0,requireHeader:typeof o.requireHeader=="string"&&o.requireHeader?o.requireHeader:void 0,bodyIncludes:typeof o.bodyIncludes=="string"&&o.bodyIncludes?o.bodyIncludes:void 0,graphqlOperation:typeof o.graphqlOperation=="string"&&o.graphqlOperation?o.graphqlOperation:void 0,graphqlVariables:typeof o.graphqlVariables=="string"?o.graphqlVariables:void 0,bodyJson:typeof o.bodyJson=="string"?o.bodyJson:void 0,graphqlSingle:o.graphqlSingle===true?true:void 0,sandbox:o.sandbox===true?true:void 0,kind:n,status:typeof o.status=="number"?Math.min(Hr,Math.max($r,o.status)):void 0,statusText:typeof o.statusText=="string"?o.statusText:void 0,headers:o.headers&&typeof o.headers=="object"?o.headers:void 0,body:typeof o.body=="string"?o.body:void 0,failKind:o.failKind==="timeout"?"timeout":void 0,delayMs:typeof o.delayMs=="number"?o.delayMs:void 0,times:typeof o.times=="number"?o.times:null,alternate:o.alternate===true,hits:0,seen:0,createdAt:typeof o.createdAt=="number"?o.createdAt:0})}return t.slice(0,wt)}var Xp=class{constructor(){this.rules=[];this.enabled=true;this.listeners=new Set;this.loaded=false;this.loadPromise=null;this.dirty=false;this.idCounter=0;this.state={enabled:true,rules:[],autoPaused:false};this.launchStreak=0;this.autoPaused=false;this.keepAlive=null;this.hitEmitTimer=null;this.engineDisabled=false;this.remote=null;this.remoteEchoUntil=0;this.sandboxCache=null;this.writes=Promise.resolve()}enableRemoteMode(e){this.remote=e,this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(e,t=false){this.remote&&(!t&&fe()<this.remoteEchoUntil||(this.enabled=e.enabled,this.rules=e.rules,this.rebuild(),this.emit()))}markLocalEdit(){this.remote&&(this.remoteEchoUntil=fe()+Hp)}disableEngine(){this.engineDisabled=true,this.keepAlive&&(this.keepAlive(),this.keepAlive=null,er()===0&&jr())}getState(){return this.state}getRules(){return this.engineDisabled?Na:this.otherTabCase()?Up:this.enabled?this.rules:this.sandboxOnly()}otherTabCase(){return this.remote||this.sandboxOnly().length||!$a()?false:Wp()}caseLockChanged(){this.syncKeepAlive(),this.emit()}sandboxOnly(){if(this.sandboxCache?.from!==this.rules){let e=this.rules.filter(t=>t.sandbox===true);this.sandboxCache={from:this.rules,rules:e.length?e:Na}}return this.sandboxCache.rules}async fetchRuleBody(e){let t=this.rules.find(r=>r.id===e);if(!t)return null;if(!t.bodyOmitted)return t.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(e)}catch{return null}}activeCount(){return(this.enabled?this.rules:this.sandboxOnly()).filter(e=>e.enabled&&!Dn(e)).length}subscribe(e){return this.listeners.add(e),this.ensureLoaded(),()=>{this.listeners.delete(e)}}setEnabled(e){this.enabled!==e&&(this.remote?.setEnabled(e),this.markLocalEdit(),this.markTouched(),this.enabled=e,this.commit(this.rules))}addRule(e){if(this.rules.length>=wt)return null;let t={...e,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};return this.commit([t,...this.rules]),t}upsertRule(e){this.remote?.upsertRule(e),this.markLocalEdit(),this.markTouched();let{id:t,...r}=e;return t&&this.rules.some(o=>o.id===t)?(this.updateRule(t,r),this.rules.find(o=>o.id===t)??null):this.addRule(r)}replaceAllRules(e,t){if(this.remote)return null;this.markTouched();let r=e.map(o=>o&&typeof o=="object"&&typeof o.id=="string"?o:{...o,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});return this.enabled=t,this.commit(Ha(r)),this.rules.slice()}updateRule(e,t){let r=this.rules.findIndex(n=>n.id===e);if(r===-1)return;let o=[...this.rules];o[r]={...o[r],...t,hits:0,seen:0},this.commit(o)}setRuleEnabled(e,t){let r=this.rules.findIndex(n=>n.id===e);if(r===-1||this.rules[r].enabled===t)return;this.remote?.setRuleEnabled(e,t),this.markLocalEdit(),this.markTouched();let o=[...this.rules];o[r]={...o[r],enabled:t,hits:t?0:o[r].hits,seen:t?0:o[r].seen},this.commit(o)}removeRule(e){let t=this.rules.filter(r=>r.id!==e);t.length!==this.rules.length&&(this.remote?.removeRule(e),this.markLocalEdit(),this.markTouched(),this.commit(t))}clearRules(){this.rules.length!==0&&(this.remote?.clearRules(),this.markLocalEdit(),this.markTouched(),this.commit([]))}recordMatch(e){let t=this.rules.findIndex(o=>o.id===e);if(t===-1)return;let r=[...this.rules];r[t]={...r[t],seen:r[t].seen+1},this.rules=r,this.rebuild()}recordHit(e){let t=this.rules.findIndex(s=>s.id===e);if(t===-1)return;let r=this.rules[t],o=r.hits+1,n=typeof r.times=="number"&&o>=r.times,i=[...this.rules];if(i[t]={...r,hits:o,enabled:n?false:r.enabled},n){this.commit(i);return}this.rules=i,this.rebuild(),this.scheduleHitEmit()}isLoaded(){return!!this.remote||this.loaded}ensureLoaded(){return this.remote||this.loaded?Promise.resolve():this.loadPromise?this.loadPromise:(this.loadPromise=(async()=>{let e=null;try{e=await Aa.getItem(Rr.network.overrides())}catch{}this.hydrate(e)})(),this.loadPromise)}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let e;try{e=globalThis.localStorage?.getItem(Rr.network.overrides())??null}catch{return}e!==null&&this.hydrate(e)}hydrate(e){try{if(e&&!this.dirty){let t=JSON.parse(e);this.enabled=t?.enabled!==false,this.rules=Ha(t?.rules),this.launchStreak=typeof t?.launchStreak=="number"?t.launchStreak:0,this.autoPaused=t?.autoPaused===true&&!this.enabled,this.applyLaunchGuard(),this.rebuild()}}catch{}finally{this.loaded=true,this.syncKeepAlive(),this.emit()}}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0||this.rules.some(e=>e.enabled&&e.sandbox)){this.launchStreak=0;return}Fp()||(this.launchStreak+=1,this.launchStreak>=jp&&(this.enabled=false,this.autoPaused=true,this.launchStreak=0),this.persist())}syncKeepAlive(){let e=!this.engineDisabled&&(this.activeCount()>0||this.otherTabCase());if(e&&!this.keepAlive){Ds(),this.keepAlive=Fr(()=>{});return}!e&&this.keepAlive&&(this.keepAlive(),this.keepAlive=null,er()===0&&jr())}scheduleHitEmit(){this.hitEmitTimer===null&&(this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null,this.emit()},Jp))}commit(e){this.dirty=true,this.rules=e.slice(0,wt),this.rebuild(),this.syncKeepAlive(),this.emit(),this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0,this.autoPaused=false}noteHealthyLaunch(){this.launchStreak===0&&!this.autoPaused||(this.markTouched(),this.persist(),this.rebuild(),this.emit())}persisted(){return JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})}persist(){if(this.remote)return;let e=this.persisted();this.writes=this.writes.then(()=>Aa.setItem(Rr.network.overrides(),e)).catch(()=>{})}async saveChecked(){if(this.remote)return false;let e=this.persisted(),t=this.writes.then(()=>$p(Rr.network.overrides(),e));this.writes=t.catch(()=>{});let r,o=new Promise(n=>{r=setTimeout(()=>n(false),Vp)});return Promise.race([t.catch(()=>false),o]).finally(()=>clearTimeout(r))}emit(){this.listeners.forEach(e=>e())}},G=new Xp;Sc({getRules:()=>G.getRules(),ready:()=>G.ensureLoaded(),isReady:()=>G.isLoaded(),recordHit:e=>G.recordHit(e),recordMatch:e=>G.recordMatch(e)});typeof window<"u"&&typeof document<"u"&&!(typeof navigator<"u"&&navigator.product==="ReactNative")&&(G.loadNow(),G.caseLockChanged(),window.addEventListener?.("storage",e=>{(e.key===null||e.key===Ma())&&G.caseLockChanged()}));function Uo(){let e=Mp(Tr(s=>G.subscribe(s),[]),()=>G.getState(),()=>G.getState()),t=Tr(s=>G.setEnabled(s),[]),r=Tr(s=>G.upsertRule(s),[]),o=Tr((s,d)=>G.setRuleEnabled(s,d),[]),n=Tr(s=>G.removeRule(s),[]),i=Tr(()=>G.clearRules(),[]);return{enabled:e.enabled,rules:e.rules,autoPaused:e.autoPaused,activeCount:G.activeCount(),setEnabled:t,upsertRule:r,setRuleEnabled:o,removeRule:n,clearRules:i,isRuleSpent:Dn}}q();function Kp(e,t){if(t.length===0)return[];let r=new Set(t.map(n=>n.id)),o=new Set;for(let n of t){let i;for(let s of e){if(s.override&&r.has(s.override.ruleId)){o.add(s.id);continue}qn(n,s.url,String(s.method||"GET"),s.requestHeaders)&&(s.timestamp>=n.createdAt?o.add(s.id):(!i||s.timestamp>i.timestamp)&&(i=s))}i&&o.add(i.id)}return e.filter(n=>o.has(n.id))}q();var Qp=[];function ci(e,t,r){return t.length===0?{pinned:Qp,rest:e}:{pinned:t,rest:r.size===0?e:e.filter(o=>!r.has(o.id))}}import{jsx as $e,jsxs as dr}from"react/jsx-runtime";var Yp=e=>e.id;function Zp({events:e,onEventPress:t,onLongPress:r,savedLiveIds:o,onClearPinned:n}){return e.length===0?null:dr(S,{style:He.pinnedSection,children:[dr(S,{style:He.pinnedHeader,children:[$e(cp,{size:11,active:true,color:Ne.semantic.info}),dr(b,{style:He.pinnedTitle,children:["PINNED \xB7 ",e.length]}),$e(W,{onPress:n,"sentry-label":"ignore unpin all",style:He.pinnedClear,children:$e(b,{style:He.pinnedClearText,children:"Unpin all"})})]}),e.map(i=>$e(Cr,{event:i,onPress:t,onLongPress:r,pinned:true,saved:o.has(i.id)},i.id))]})}function ef({events:e,onEventPress:t,onLongPress:r,savedLiveIds:o,paused:n,onTogglePaused:i}){return e.length===0?null:dr(S,{style:[He.overriddenSection,n&&He.overriddenSectionOff],children:[dr(S,{style:He.overriddenHeader,children:[$e(dp,{size:11,color:n?Ne.text.muted:Ne.semantic.warning}),$e(b,{testID:"buoy-network-overridden-strip",style:[He.overriddenTitle,n&&He.overriddenTitleOff],children:n?`PAUSED \xB7 ${e.length}`:`OVERRIDDEN \xB7 ${e.length}`}),$e(W,{onPress:i,"sentry-label":"ignore pause overrides",style:He.overriddenManage,children:$e(b,{style:[He.overriddenManageText,n&&He.overriddenTitleOff],children:n?"Resume":"Pause"})})]}),e.map(s=>$e(Cr,{event:s,onPress:t,onLongPress:r,overridden:true,saved:o.has(s.id)},s.id))]})}function tf({visible:e,paused:t,filter:r,ignoredPatterns:o,isPro:n,searchText:i,onEventPress:s,onUpgradePress:d}){let{visibleEvents:a,hasLockedEvents:l,lockedEventCount:c,totalEvents:y}=Zr({filter:r,ignoredPatterns:o,paused:t,visible:e,isPro:n}),{pinnedEvents:w,pinnedLiveIds:p,savedLiveIds:C,togglePin:u,clearPinned:R}=kr(),{rules:h,enabled:m,setEnabled:x,isRuleSpent:I}=Uo(),B=lp(F=>{u(F)},[u]);if(!e)return null;let{pinned:E,rest:D}=ci(a,w,p),k=h.filter(F=>F.enabled&&!I(F)),g=Kp([...E,...D],k),v=new Set(g.map(F=>F.id)),f=E.filter(F=>!v.has(F.id)),T=v.size?D.filter(F=>!v.has(F.id)):D,M=!t,P=({item:F})=>$e(Cr,{event:F,onPress:s,onLongPress:B,saved:C.has(F.id)}),A=()=>f.length>0||g.length>0?null:$e(hp,{testID:"buoy-network-empty",...pp({subject:"requests",search:i,total:y,capturing:M,waiting:{otto:"fishing",title:"No network events",message:"Network requests will appear here"},paused:{title:"No network events",message:"Enable interception to start capturing"}})}),_=()=>{if(!l)return null;let F=i.length>0,L=F?`${c} matching ${c===1?"request":"requests"} in locked history`:`${c} requests locked`;return $e(qa,{title:L,subtitle:F?"Upgrade to Pro to search your full request history":"Upgrade to Pro to unlock full request history",onPress:d})};return dr(S,{style:He.root,children:[M?null:dr(S,{style:He.disabledBanner,children:[$e(up,{size:14,color:Ne.semantic.warning}),$e(b,{style:He.disabledText,children:"Network interception is disabled"})]}),$e(ef,{events:g,onEventPress:s,onLongPress:B,savedLiveIds:C,paused:!m,onTogglePaused:()=>x(!m)}),$e(Zp,{events:f,onEventPress:s,onLongPress:B,savedLiveIds:C,onClearPinned:R}),T.length>0||l?$e(go,{keyboardShouldPersistTaps:"handled",testID:"buoy-network-list",data:T,renderItem:P,keyExtractor:Yp,contentContainerStyle:He.listContent,showsVerticalScrollIndicator:true,onEndReachedThreshold:.8,scrollEnabled:true,...fp,extraData:C,"sentry-label":"ignore network events list",ListFooterComponent:_}):A()]})}var He=se.create({root:{flex:1,minHeight:0},overriddenSection:{borderBottomWidth:1,borderBottomColor:Ne.semantic.warning+"44",backgroundColor:Ne.semantic.warningBackground},overriddenSectionOff:{borderBottomColor:Ne.border.default,backgroundColor:Ne.background.card},overriddenTitleOff:{color:Ne.text.muted},overriddenHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:12,paddingTop:8,paddingBottom:4},overriddenTitle:{flex:1,fontSize:10,fontWeight:"700",letterSpacing:.8,color:Ne.semantic.warning},overriddenManage:{paddingHorizontal:6,paddingVertical:2},overriddenManageText:{fontSize:10,fontWeight:"600",color:Ne.semantic.warning},pinnedSection:{borderBottomWidth:1,borderBottomColor:Ne.border.default,paddingBottom:4},pinnedHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:20,paddingTop:10,paddingBottom:6},pinnedTitle:{flex:1,color:Ne.semantic.info,fontSize:10,fontWeight:"700",letterSpacing:.6,fontFamily:gp},pinnedClear:{paddingHorizontal:6,paddingVertical:2},pinnedClearText:{color:Ne.text.muted,fontSize:10},disabledBanner:{flexDirection:"row",alignItems:"center",gap:8,padding:10,marginHorizontal:12,marginTop:8,backgroundColor:Ne.semantic.warningBackground,borderRadius:8,borderWidth:1,borderColor:Ne.semantic.warning+"20"},disabledText:{color:Ne.semantic.warning,fontSize:11,flex:1},listContent:{paddingTop:8}});q();he();import{useState as rf}from"react";import{Bookmark as of,CopyButton as nf,Search as sf,macOSColors as ct,useLimit as af,ToolEmptyState as lf,resolveListEmptyState as df,EVENT_LIST_PRESET as cf,monoFont as uf}from"@buoy-gg/shared-ui/web";q();function ja(e,t,r){let o=e.slice(0,Math.min(t,Wt)),n=o.map(i=>i.event);return{events:r?Xr(n,{searchText:r}):n,lockedCount:e.length-o.length}}import{jsx as Tt,jsxs as Jo}from"react/jsx-runtime";var hf=e=>e.id;function Fa({visible:e,isPro:t,copySettings:r,search:o,onSearchChange:n,onEventPress:i,onUpgradePress:s}){let{savedRecords:d,pinnedLiveIds:a,toggleSave:l,clearSaved:c}=kr(),y=af("network.saved"),[w,p]=rf(""),C=o!=null&&n!=null,u=C?o:w,R=C?n:p;if(!e)return null;let{events:h,lockedCount:m}=ja(d,y,u),x=E=>{l(E)},I=({item:E})=>Tt(Cr,{event:E,onPress:i,onLongPress:x,saved:true,pinned:a.has(E.id)}),B=()=>m===0?null:Tt(qa,{title:`${m} saved ${m===1?"request":"requests"} locked`,subtitle:`Your plan keeps ${y}. Upgrade to Pro to unlock the rest.`,onPress:s});return Jo(S,{style:Rt.root,children:[Jo(S,{style:Rt.toolbar,children:[Tt(of,{size:11,color:ct.semantic.debug}),Jo(b,{style:Rt.toolbarTitle,children:["SAVED \xB7 ",d.length,y>=Wt?"":`/${y}`]}),t?Tt(nf,{value:()=>Ba(h,r),size:13,buttonStyle:Rt.toolbarButton,colors:{idle:ct.text.secondary,success:ct.semantic.success,error:ct.semantic.error},disabled:h.length===0}):null,Tt(W,{onPress:c,"sentry-label":"ignore clear saved",style:Rt.toolbarClear,disabled:d.length===0,children:Tt(b,{style:[Rt.toolbarClearText,d.length===0&&Rt.toolbarClearTextDisabled],children:"Clear all"})})]}),d.length>0?Jo(S,{style:Rt.searchRow,children:[Tt(sf,{size:13,color:ct.text.secondary}),Tt(Xt,{style:Rt.searchInput,placeholder:"Search saved requests\u2026",placeholderTextColor:ct.text.muted,value:u,onChangeText:R,"sentry-label":"ignore saved search",accessibilityLabel:"Search saved requests",autoCapitalize:"none",autoCorrect:false,returnKeyType:"search"})]}):null,d.length===0||u.trim().length>0&&h.length===0&&m===0?Tt(lf,{testID:"buoy-network-saved-empty",...df({subject:"saved requests",verb:"kept",search:d.length===0?"":u,total:d.length,waiting:{otto:"empty",title:"No saved requests",message:"Open a request and tap the bookmark to keep it here \u2014 saved requests survive Clear and app restarts."}})}):Tt(go,{keyboardShouldPersistTaps:"handled",data:h,renderItem:I,keyExtractor:hf,contentContainerStyle:Rt.listContent,showsVerticalScrollIndicator:true,scrollEnabled:true,...cf,extraData:a,"sentry-label":"ignore saved requests list",ListFooterComponent:B})]})}var Rt=se.create({root:{flex:1,minHeight:0},toolbar:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:20,paddingTop:10,paddingBottom:6},toolbarTitle:{flex:1,color:ct.semantic.debug,fontSize:10,fontWeight:"700",letterSpacing:.6,fontFamily:uf},toolbarButton:{width:26,height:26,borderRadius:6,alignItems:"center",justifyContent:"center"},toolbarClear:{paddingHorizontal:6,paddingVertical:2},toolbarClearText:{color:ct.text.muted,fontSize:10},toolbarClearTextDisabled:{color:ct.text.disabled},searchRow:{flexDirection:"row",alignItems:"center",gap:6,marginHorizontal:12,marginBottom:8,paddingHorizontal:10,paddingVertical:5,backgroundColor:ct.background.input,borderRadius:10,borderWidth:1,borderColor:ct.border.default},searchInput:{flex:1,color:ct.text.primary,fontSize:13,paddingVertical:2},listContent:{paddingTop:4}});q();he();import{useCallback as pf,useEffect as Go,useState as ff}from"react";import{AlertCircle as gf,AlertTriangle as yf,DevToolsCard as mf,EmptyState as bf,MethodBadge as vf,Plus as wf,Trash2 as Sf,macOSColors as ae,useLimit as kf,monoFont as xf}from"@buoy-gg/shared-ui/web";q();he();import{useMemo as Wa,useState as Xo}from"react";import{ChevronDown as Cf,ChevronRight as Tf,macOSColors as Q,useSafeAreaInsets as Rf,monoFont as If}from"@buoy-gg/shared-ui/web";q();he();import{useState as Ko,useMemo as Qo,useCallback as eo,useRef as ui,useEffect as Pf,memo as Yo}from"react";import{displayValue as Ef,buoyColors as N,monoFont as tt}from"@buoy-gg/shared-ui/web";import{CopyButton as Bf}from"@buoy-gg/shared-ui/web";import{ChevronRight as Lf,ChevronDown as zf,Trash as _a}from"@buoy-gg/shared-ui/web";import{CyberpunkInput as Of}from"@buoy-gg/shared-ui/web/dataViewer";q();var cr=(e,t,r)=>{if(t.length===0)return r;if(e instanceof Map){let o=new Map(e);if(t.length===1)return o.set(t[0],r),o;let[n,...i]=t,s=o.get(n);return o.set(n,cr(s??null,i,r)),o}if(e instanceof Set){let o=cr(Array.from(e),t,r);return new Set(Array.isArray(o)?o:[])}if(Array.isArray(e)){let o=[...e];if(t.length===1)return o[t[0]]=r,o;let[n,...i]=t;return o[n]=cr(o[n],i,r),o}if(e instanceof Object){let o={...e};if(t.length===1)return o[t[0]]=r,o;let[n,...i]=t;return o[n]=cr(o[n],i,r),o}return e};q();var ur=(e,t)=>{if(e instanceof Map){let r=new Map(e);if(t.length===1)return r.delete(t[0]),r;let[o,...n]=t;return r.set(o,ur(r.get(o),n)),r}if(e instanceof Set){let r=ur(Array.from(e),t);return new Set(r)}if(Array.isArray(e)){let r=[...e];if(t.length===1)return r.filter((i,s)=>s.toString()!==t[0]);let[o,...n]=t;return r[o]=ur(r[o],n),r}if(e instanceof Object){let r={...e};if(t.length===1)return delete r[t[0]],r;let[o,...n]=t;return r[o]=ur(r[o],n),r}return e};q();import{createContext as qf,useContext as Df}from"react";var Va=qf(null);function Zo(){return Df(Va)}import{Fragment as en,jsx as re,jsxs as Ze}from"react/jsx-runtime";var to=100,Ir={top:8,bottom:8,left:8,right:8},Ua=12,Af=(e,t=to)=>{if(t<1||e.length===0)return[];let r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r},hi=Yo(({expanded:e,isFocused:t=false,isMain:r=false})=>re(S,{style:[X.expanderIcon,r&&X.expanderIconMain,e?X.expanded:X.collapsed],children:e?re(zf,{size:r?14:Ua,color:t?N.primary:r?N.text:N.textSecondary,strokeWidth:2.5}):re(Lf,{size:r?14:Ua,color:t?N.primary:r?N.text:N.textSecondary,strokeWidth:2.5})}));hi.displayName="Expander";var Ja=Yo(({value:e,isFocused:t=false})=>re(Bf,{value:e,isFocused:t,buttonStyle:t?{...X.buttonStyle,...X.buttonStyleFocused}:X.buttonStyle}));Ja.displayName="CopyButton";var pi=Yo(({dataPath:e,isFocused:t=false})=>{let r=Zo(),o=eo(()=>{r&&r.onChange(ur(r.root,e))},[r,e]);return r?re(W,{"sentry-label":"ignore devtools explorer delete button",onPress:o,style:[X.deleteButton,t&&X.deleteButtonFocused],accessibilityLabel:"Delete item",hitSlop:Ir,activeOpacity:.7,children:re(_a,{size:14,strokeWidth:2,color:t?N.error:N.error+"CC"})}):null});pi.displayName="DeleteItemButton";var Ga=Yo(({dataPath:e,isFocused:t=false})=>{let r=Zo(),o=eo(()=>{r&&r.onChange(cr(r.root,e,[]))},[r,e]);return r?re(W,{"sentry-label":"ignore devtools explorer clear button",style:[X.clearButton,t&&X.clearButtonFocused],"aria-label":"Remove all items",onPress:o,hitSlop:Ir,activeOpacity:.7,children:re(b,{style:[X.clearButtonText,{color:t?N.warning:N.warning+"CC"}],children:"[]"})}):null});Ga.displayName="ClearArrayButton";function Nf({dataPath:e,value:t,itemsDeletable:r}){let o=Zo(),n=eo(()=>{if(!o)return;let a=typeof t=="boolean"?t:false;o.onChange(cr(o.root,e,!a))},[o,e,t]),i=eo(()=>{o&&o.onChange(ur(o.root,e))},[o,e]);if(!o)return null;let s=t?X.toggleBadgeTrue:X.toggleBadgeFalse,d=t?X.toggleTextTrue:X.toggleTextFalse;return Ze(W,{"sentry-label":"ignore devtools explorer toggle button",style:X.modernToggleButton,onPress:n,hitSlop:Ir,activeOpacity:.8,children:[re(S,{style:[X.toggleBadge,s],children:re(b,{style:[X.toggleBadgeText,d],children:t?"TRUE":"FALSE"})}),r&&re(W,{"sentry-label":"ignore devtools explorer delete button in toggle",onPress:i,style:X.deleteButtonInToggle,accessibilityLabel:"Delete item",hitSlop:Ir,activeOpacity:.7,children:re(_a,{size:14,strokeWidth:2,color:N.error+"CC"})})]})}function fi({editable:e,label:t,value:r,defaultExpanded:o,dataPath:n,itemsDeletable:i,dataVersion:s=0}){let d=Zo(),[a,l]=Ko(false),[c,y]=Ko("");Pf(()=>{if(r!=null&&(typeof r=="string"||typeof r=="number")){let v=r.toString();y(v)}},[r,t,s]);let w=Qo(()=>{let v=t.toUpperCase();return["DATA","QUERY","QUERYKEY","TYPES","STATS","OPTIONS","OBSERVERS"].includes(v)},[t]),[p,C]=Ko((o||[]).includes(t)),u=()=>C(v=>!v),[R,h]=Ko([]),m=Qo(()=>r==null||typeof r!="object"?[]:Array.isArray(r)?(r.length>1e3?r.slice(0,1e3):r).map((v,f)=>({label:f.toString(),value:v})):r instanceof Map?Array.from(r.entries()).slice(0,1e3).map(([v,f])=>({label:v.toString(),value:f})):r instanceof Set?Array.from(r).slice(0,1e3).map((v,f)=>({label:f.toString(),value:v})):Object.entries(r).slice(0,1e3).map(([v,f])=>({label:v,value:f})),[r]),x=Qo(()=>Array.isArray(r)?"array":r===null||typeof r!="object"?typeof r:r instanceof Map||r instanceof Set?"Iterable":"object",[r]),I=Qo(()=>Af(m,to),[m]),B=n??[],E=ui(d),D=ui(B),k=ui(x);E.current=d,D.current=B,k.current=x;let g=eo((v,f)=>{y(f);let T=E.current;if(!T||v&&isNaN(Number(f)))return;let M=k.current==="number"?Number(f):f;T.onChange(cr(T.root,D.current,M))},[y]);return re(S,{style:X.minWidthWrapper,children:Ze(S,{style:X.fullWidthMarginRight,children:[I.length>0&&Ze(en,{children:[Ze(S,{style:[X.flexRowItemsCenterGap,w&&X.flexRowItemsCenterGapMain],children:[Ze(W,{"sentry-label":"ignore devtools explorer expander button",style:X.expanderButton,onPress:u,hitSlop:Ir,activeOpacity:.6,children:[re(hi,{expanded:p,isFocused:a,isMain:w}),re(b,{style:[X.labelText,a&&X.labelTextFocused,w&&X.labelTextMain],children:t}),re(b,{style:X.textGray500,children:`${String(x).toLowerCase()==="iterable"?"(Iterable) ":""}${m.length} ${m.length>1?"items":"item"}`})]}),e&&Ze(S,{style:X.flexRowGapItemsCenter,children:[re(Ja,{value:r,isFocused:a}),i&&d!==null&&re(pi,{dataPath:B,isFocused:a}),x==="array"&&d!==null&&re(Ga,{dataPath:B,isFocused:a})]})]}),p&&Ze(en,{children:[I.length===1&&re(S,{style:[X.singleEntryContainer,w&&X.singleEntryContainerMain],children:m.map((v,f)=>re(fi,{defaultExpanded:o,label:v.label,value:v.value,editable:e,dataPath:[...B,v.label],itemsDeletable:x==="array"||x==="Iterable"||x==="object",dataVersion:s},v.label+f))}),I.length>1&&re(S,{style:X.multiEntryContainer,children:I.map((v,f)=>re(S,{children:Ze(S,{style:X.relativeOutlineNone,children:[Ze(W,{"sentry-label":"ignore devtools explorer page toggle",onPress:()=>h(T=>T.includes(f)?T.filter(M=>M!==f):[...T,f]),style:X.pageExpanderButton,hitSlop:Ir,children:[re(hi,{expanded:R.includes(f)}),Ze(b,{style:X.pageRangeText,children:["[",f*to,"...",f*to+to-1,"]"]})]}),R.includes(f)&&re(S,{style:X.entriesContainer,children:v.map(T=>re(fi,{defaultExpanded:o,label:T.label,value:T.value,editable:e,dataPath:[...B,T.label],dataVersion:s},T.label))})]})},f))})]})]}),I.length===0&&Ze(S,{style:X.flexRowGapFullWidth,children:[e&&d!==null&&(x==="string"||x==="number"||x==="boolean")?Ze(en,{children:[e&&d&&(x==="string"||x==="number")&&re(S,{style:X.nebulaInputWrapper,children:re(Of,{label:t,accessibilityLabel:"Data input field for editing values",style:[x==="number"?X.textNumber:X.textString],keyboardType:x==="number"?"numeric":"default",value:c,onChangeText:v=>g(x==="number",v),onFocus:()=>l(true),onBlur:()=>l(false),showNumberControls:x==="number",onIncrement:()=>{let v=Number(c)||0;g(true,String(v+1))},onDecrement:()=>{let v=Number(c)||0;g(true,String(v-1))},showDeleteButton:i,onDelete:()=>{d.onChange(ur(d.root,B))}})}),x==="boolean"&&Ze(S,{style:X.booleanRowContainer,children:[re(b,{style:X.booleanLabel,children:t}),re(S,{style:X.booleanToggleWrapper,children:re(Nf,{dataPath:B,value:r,itemsDeletable:i})})]})]}):Ze(en,{children:[re(b,{style:X.text344054,children:t}),re(b,{style:X.displayValueText,children:Ef(r)})]}),e&&i&&d!==null&&x!=="string"&&x!=="number"&&x!=="boolean"&&re(pi,{dataPath:B,isFocused:a})]})]})})}var X=se.create({buttonStyle:{backgroundColor:N.card+"E6",borderWidth:1,borderColor:N.textSecondary+"33",borderRadius:6,flexDirection:"row",alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",shadowColor:"#000",shadowOffset:{width:0,height:1},shadowOpacity:.2,shadowRadius:2},buttonStyleFocused:{borderColor:N.primary+"CC",backgroundColor:N.primary+"26",shadowColor:N.primary,shadowOpacity:.3,shadowRadius:4},deleteButton:{backgroundColor:N.error+"1A",borderColor:N.error+"4D",borderWidth:1,borderRadius:6,padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",shadowColor:N.error,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},deleteButtonFocused:{borderColor:N.error+"CC",backgroundColor:N.error+"33",shadowOpacity:.3,shadowRadius:5},deleteButtonInToggle:{backgroundColor:N.error+"1A",borderColor:N.error+"4D",borderWidth:1,borderRadius:6,padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,shadowColor:N.error,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},clearButton:{backgroundColor:N.warning+"1A",borderWidth:1,borderColor:N.warning+"4D",borderRadius:6,flexDirection:"row",padding:0,alignItems:"center",justifyContent:"center",width:28,height:28,position:"relative",zIndex:10,shadowColor:N.warning,shadowOffset:{width:0,height:0},shadowOpacity:.15,shadowRadius:3},clearButtonFocused:{borderColor:N.warning+"CC",backgroundColor:N.warning+"33",shadowOpacity:.3,shadowRadius:5},clearButtonText:{fontSize:12,fontWeight:"700",fontFamily:tt},expanderIcon:{width:18,height:18,alignItems:"center",justifyContent:"center",marginRight:1,backgroundColor:N.textSecondary+"14",borderRadius:3},expanderIconMain:{backgroundColor:N.textSecondary+"1A",width:20,height:20,borderRadius:4,borderWidth:.5,borderColor:N.textSecondary+"33"},expanded:{transform:[{rotate:"0deg"}]},collapsed:{transform:[{rotate:"0deg"}]},minWidthWrapper:{minWidth:180,fontSize:11,flexDirection:"row",flexWrap:"wrap",width:"100%",marginVertical:.5},fullWidthMarginRight:{position:"relative",width:"100%",marginRight:1},flexRowItemsCenterGap:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingVertical:3,paddingHorizontal:6,marginVertical:1,borderRadius:4,backgroundColor:N.card+"66",borderWidth:.5,borderColor:N.textSecondary+"1A"},flexRowItemsCenterGapMain:{backgroundColor:N.card+"E6",borderLeftWidth:2.5,borderLeftColor:N.textSecondary+"80",borderColor:N.textSecondary+"26",paddingVertical:5,paddingHorizontal:8,marginBottom:3,borderWidth:1,shadowColor:"#000",shadowOffset:{width:0,height:0},shadowOpacity:.08,shadowRadius:3},expanderButton:{flexDirection:"row",alignItems:"center",backgroundColor:"transparent",paddingVertical:1,paddingHorizontal:2,gap:6,borderWidth:0,minHeight:24,flex:1},labelText:{color:N.textSecondary,fontSize:10,fontWeight:"600",marginRight:4,fontFamily:tt,letterSpacing:.4},labelTextFocused:{color:N.text},labelTextMain:{color:N.text,fontSize:11,fontWeight:"700",letterSpacing:.6},textGray500:{color:N.textMuted,fontSize:10,fontWeight:"400",fontFamily:tt,opacity:.7},pageRangeText:{color:N.textSecondary,fontSize:10,fontWeight:"600",fontFamily:tt},flexRowGapItemsCenter:{flexDirection:"row",alignItems:"center",gap:4,paddingLeft:2},singleEntryContainer:{marginLeft:2,marginTop:2,paddingLeft:8,borderLeftWidth:1.5,borderLeftColor:N.textSecondary+"40"},singleEntryContainerMain:{borderLeftColor:N.textSecondary+"4D",marginLeft:4,paddingLeft:10},multiEntryContainer:{marginLeft:2,marginTop:2,paddingLeft:8,borderLeftWidth:1.5,borderLeftColor:N.textSecondary+"40"},multiEntryContainerMain:{borderLeftColor:N.textSecondary+"4D",marginLeft:4,paddingLeft:10},relativeOutlineNone:{position:"relative"},pageExpanderButton:{flexDirection:"row",alignItems:"center",backgroundColor:N.card+"66",paddingVertical:3,paddingHorizontal:6,gap:6,borderRadius:4,borderWidth:.5,borderColor:N.textSecondary+"1A",marginBottom:2,minHeight:24},entriesContainer:{marginLeft:2,paddingLeft:8,marginTop:2,borderLeftWidth:1.5,borderLeftColor:N.textSecondary+"40"},textNumber:{color:N.text,fontWeight:"600",fontFamily:tt},textString:{color:N.text,fontFamily:tt},flexRowGapFullWidth:{flexDirection:"row",width:"100%",alignItems:"center",marginVertical:1,gap:6,paddingHorizontal:4,paddingVertical:2,borderRadius:3},text344054:{color:N.textSecondary,fontWeight:"600",fontSize:9,minWidth:50,fontFamily:tt,letterSpacing:.4,opacity:.8},numberInputButtons:{position:"absolute",right:8,top:"50%",transform:[{translateY:-18}],flexDirection:"row",gap:4,zIndex:10},touchableButton:{width:32,height:32,borderRadius:6,backgroundColor:N.card+"E6",borderWidth:1,borderColor:N.textSecondary+"33",alignItems:"center",justifyContent:"center",marginLeft:2,shadowColor:"#000",shadowOffset:{width:0,height:1},shadowOpacity:.2,shadowRadius:2},touchableButtonFocused:{borderColor:N.primary+"CC",backgroundColor:N.primary+"26",shadowColor:N.primary,shadowOffset:{width:0,height:0},shadowOpacity:.3,shadowRadius:4,elevation:3},nebulaInputWrapper:{flex:1,width:"100%",position:"relative"},displayValueText:{flex:1,color:N.text,fontWeight:"400",fontFamily:tt,fontSize:12,paddingVertical:6,paddingHorizontal:10,borderRadius:6,borderWidth:1,borderColor:N.textMuted+"66",minHeight:34},dataRow:{flexDirection:"row",alignItems:"center",paddingVertical:4,paddingHorizontal:8,minHeight:44,gap:12},dataLabel:{color:N.textSecondary,fontSize:13,fontWeight:"500",minWidth:80,flexShrink:0},dataValueContainer:{flex:1,flexDirection:"row",alignItems:"center"},inputWithActions:{flex:1,position:"relative"},numberControls:{position:"absolute",right:8,top:"50%",transform:[{translateY:-16}],flexDirection:"column",gap:2},numberButton:{width:32,height:16,borderRadius:4,alignItems:"center",justifyContent:"center",borderWidth:1,borderColor:N.primary+"0F"},readOnlyValue:{color:N.text,fontSize:13,fontFamily:tt,paddingVertical:8,paddingHorizontal:12,borderRadius:6,borderWidth:1,borderColor:N.textMuted+"33",flex:1},actionButtons:{flexDirection:"row",gap:6,paddingLeft:8},booleanContainer:{flexDirection:"row",alignItems:"center",padding:8,borderRadius:6,borderWidth:1,borderColor:N.textMuted+"4D",flex:1},booleanText:{marginLeft:8,color:N.warning,fontWeight:"500",fontFamily:tt},modernToggleButton:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:6,borderWidth:1,borderColor:N.textMuted+"99",paddingHorizontal:8,paddingVertical:6,marginVertical:2,minHeight:34,gap:8},toggleIconContainer:{marginRight:6},toggleIcon:{padding:8,borderRadius:8,alignItems:"center",justifyContent:"center",width:32,height:32},toggleIconSmall:{width:8,height:8,borderRadius:4},toggleContent:{flex:1,minWidth:0},toggleLabel:{color:"#E5E7EB",fontSize:11,fontWeight:"600",fontFamily:tt,letterSpacing:.3},toggleStatus:{color:"#9CA3AF",fontSize:11},toggleBadge:{marginLeft:6,paddingHorizontal:6,paddingVertical:3,borderRadius:4,borderWidth:1},toggleBadgeText:{fontSize:9,fontWeight:"700",textTransform:"uppercase",letterSpacing:.8,fontFamily:tt},toggleIconTrue:{backgroundColor:N.primary},toggleIconFalse:{backgroundColor:N.textMuted},toggleBadgeTrue:{backgroundColor:N.primary+"1A",borderColor:N.primary+"4D"},toggleBadgeFalse:{backgroundColor:N.textMuted+"1A",borderColor:N.textMuted+"4D"},toggleTextTrue:{color:N.primary,fontWeight:"600"},toggleTextFalse:{color:N.textSecondary,fontWeight:"500"},booleanRowContainer:{flexDirection:"row",alignItems:"center",width:"100%",gap:8,paddingVertical:2},booleanLabel:{color:N.textSecondary,fontSize:10,fontWeight:"600",fontFamily:tt,letterSpacing:.4,minWidth:60,flexShrink:0},booleanToggleWrapper:{flex:1}});q();he();import{useState as Mf}from"react";import{absoluteFill as Xa,macOSColors as et}from"@buoy-gg/shared-ui/web";import{jsx as Vt,jsxs as gi}from"react/jsx-runtime";function yi({title:e,hint:t,value:r,placeholder:o="Number",min:n,max:i,onSubmit:s,onCancel:d}){let[a,l]=Mf(r!=null?String(r):""),c=()=>{let y=a.trim();if(!y){s(null);return}let w=Number(y);if(!Number.isFinite(w)){s(null);return}let p=w;n!=null&&(p=Math.max(n,p)),i!=null&&(p=Math.min(i,p)),s(p)};return gi(S,{style:rt.overlay,children:[Vt(W,{style:rt.backdrop,activeOpacity:1,onPress:d,"sentry-label":"ignore dismiss number prompt"}),gi(S,{style:rt.panel,children:[Vt(b,{style:rt.title,children:e}),Vt(Xt,{style:rt.input,value:a,onChangeText:l,placeholder:o,placeholderTextColor:et.text.muted,keyboardType:"number-pad",autoFocus:true,selectTextOnFocus:true,onSubmitEditing:c,returnKeyType:"done","sentry-label":"ignore number prompt input",accessibilityLabel:e}),t?Vt(b,{style:rt.hint,children:t}):null,gi(S,{style:rt.actions,children:[Vt(W,{onPress:d,"sentry-label":"ignore cancel number prompt",style:[rt.button,rt.cancelButton],children:Vt(b,{style:rt.cancelText,children:"Cancel"})}),Vt(W,{onPress:c,"sentry-label":"ignore save number prompt",style:[rt.button,rt.saveButton],children:Vt(b,{style:rt.saveText,children:"Set"})})]})]})]})}var rt=se.create({overlay:{...Xa,zIndex:40},backdrop:{...Xa,backgroundColor:"rgba(0,0,0,0.6)"},panel:{marginHorizontal:12,marginTop:12,padding:14,borderRadius:10,borderWidth:1,borderColor:et.border.hover,backgroundColor:et.background.card,gap:10},title:{fontSize:13,fontWeight:"700",color:et.text.primary},input:{backgroundColor:et.background.input,borderWidth:1,borderColor:et.border.input,borderRadius:6,paddingHorizontal:12,paddingVertical:10,fontSize:16,fontWeight:"700",color:et.text.primary},hint:{fontSize:10,color:et.text.muted},actions:{flexDirection:"row",gap:8},button:{flex:1,paddingVertical:10,borderRadius:6,alignItems:"center",borderWidth:1},cancelButton:{borderColor:et.border.default,backgroundColor:et.background.base},cancelText:{fontSize:12,fontWeight:"600",color:et.text.secondary},saveButton:{borderColor:et.semantic.info,backgroundColor:`${et.semantic.info}22`},saveText:{fontSize:12,fontWeight:"700",color:et.semantic.info}});import{Fragment as Ka,jsx as K,jsxs as We}from"react/jsx-runtime";var $f=["GET","POST","PUT","PATCH","DELETE"],Qa=[0,500,1e3,3e3,1e4],Ya=[{id:"500",label:"Server error",code:"500",danger:true,patch:{kind:"respond",status:500,statusText:"Internal Server Error"}},{id:"401",label:"Unauthorized",code:"401",danger:true,patch:{kind:"respond",status:401,statusText:"Unauthorized"}},{id:"404",label:"Not found",code:"404",danger:true,patch:{kind:"respond",status:404,statusText:"Not Found"}},{id:"403",label:"Forbidden",code:"403",danger:true,patch:{kind:"respond",status:403,statusText:"Forbidden"}},{id:"429",label:"Rate limited",code:"429",danger:true,patch:{kind:"respond",status:429,statusText:"Too Many Requests"}},{id:"503",label:"Unavailable",code:"503",danger:true,patch:{kind:"respond",status:503,statusText:"Service Unavailable"}},{id:"400",label:"Bad request",code:"400",danger:true,patch:{kind:"respond",status:400,statusText:"Bad Request"}},{id:"200",label:"Success",code:"200",patch:{kind:"respond",status:200,statusText:"OK"}},{id:"offline",label:"Offline",danger:true,patch:{kind:"fail",failKind:"network"}},{id:"timeout",label:"Timeout",danger:true,patch:{kind:"fail",failKind:"timeout"}},{id:"passthrough",label:"Real response",patch:{kind:"delay"}}];function Hf(e){return e.kind==="delay"?"passthrough":e.kind==="fail"?e.failKind==="timeout"?"timeout":"offline":String(e.status??200)}function jf({outcome:e,active:t,onPress:r}){let o=e.danger?Q.semantic.error:Q.semantic.info;return We(W,{onPress:r,"sentry-label":"ignore override outcome",testID:`buoy-network-outcome-${e.label.toLowerCase().replace(/\s+/g,"-")}${e.code?`-${e.code}`:""}`,accessibilityRole:"button",accessibilityLabel:`${e.label}${e.code?` ${e.code}`:""}`,style:[V.outcome,t&&{borderColor:o,backgroundColor:`${o}1F`}],children:[K(b,{style:[V.outcomeLabel,t&&{color:o}],children:e.label}),e.code?K(b,{style:[V.outcomeCode,t&&{color:o}],children:e.code}):null]})}function Za({title:e,summary:t,open:r,onToggle:o,children:n}){return We(S,{style:V.disclosure,children:[We(W,{onPress:o,"sentry-label":"ignore override disclosure",testID:`buoy-network-disclosure-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,style:V.disclosureHeader,children:[r?K(Cf,{size:12,color:Q.text.muted}):K(Tf,{size:12,color:Q.text.muted}),K(b,{style:V.disclosureTitle,children:e}),t&&!r?K(b,{style:V.disclosureSummary,numberOfLines:1,children:t}):null]}),r?K(S,{style:V.disclosureBody,children:n}):null]})}function Pr({label:e,active:t,onPress:r}){return K(W,{onPress:r,"sentry-label":"ignore override chip",testID:`buoy-network-chip-${e.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:e,style:[V.chip,t&&V.chipActive],children:K(b,{style:[V.chipText,t&&V.chipTextActive],children:e})})}function Ff({draft:e,onChange:t,onSave:r,onCancel:o,saveLabel:n="Save",applySafeAreaInset:i=false}){let s=Rf({minBottom:16}),d=i?s.bottom:0,a=T=>t({...e,...T}),[l,c]=Xo(!e.urlPattern.trim()),[y,w]=Xo(false),[p,C]=Xo(null),[u,R]=Xo(null),h=Hf(e),m=e.kind==="respond"&&typeof e.status=="number"&&!Ya.some(T=>T.code===String(e.status)),x=e.kind==="respond",I=e.methods?.[0],B=`${I??"Any"} ${e.urlPattern||"No URL yet"}`,E=Wa(()=>{let T=(e.body??"").trim();if(!T)return"Empty";let M=T.split(`
144
+ `).length;return`${M} line${M===1?"":"s"}`},[e.body]),D=Wa(()=>{let T=(e.body??"").trim();if(!T)return null;try{return JSON.parse(T)}catch{return null}},[e.body]),k=(e.body??"").trim().length>0&&!D,g=e.delayMs??0,v=g>0&&!Qa.includes(g),f=!e.alternate&&typeof e.times=="number"&&e.times!==1;return We(S,{style:V.root,children:[We(ht,{testID:"buoy-network-editor-scroll",style:V.scroll,contentContainerStyle:V.scrollContent,keyboardShouldPersistTaps:"handled",children:[We(Za,{title:"Applies to",summary:B,open:l,onToggle:()=>c(T=>!T),children:[K(Xt,{style:V.input,value:e.urlPattern,onChangeText:T=>a({urlPattern:T}),testID:"buoy-network-override-pattern",accessibilityLabel:"Override URL pattern",placeholder:"https://api.example.com/v1/users*",placeholderTextColor:Q.text.muted,autoCapitalize:"none",autoCorrect:false,multiline:true,"sentry-label":"ignore override url pattern"}),We(S,{style:V.chipRow,children:[K(Pr,{label:"Any",active:!I,onPress:()=>a({methods:void 0})}),$f.map(T=>K(Pr,{label:T,active:I===T,onPress:()=>a({methods:[T]})},T))]})]}),We(S,{style:V.outcomeGrid,children:[Ya.map(T=>K(jf,{outcome:T,active:h===T.id,onPress:()=>a(T.patch)},T.id)),K(W,{onPress:()=>R("status"),"sentry-label":"ignore custom status",accessibilityLabel:"Custom status code",style:[V.customField,m&&V.customFieldActive],children:K(b,{style:[V.customValue,m&&V.customInputActive],children:m?String(e.status):"Custom"})})]}),x?K(Za,{title:"Response body",summary:E,open:y,onToggle:()=>w(T=>!T),children:p!==null?We(Ka,{children:[K(Xt,{style:[V.input,V.bodyInput],value:p,onChangeText:C,placeholder:"Paste a new body\u2026",placeholderTextColor:Q.text.muted,autoCapitalize:"none",autoCorrect:false,autoFocus:true,multiline:true,"sentry-label":"ignore override body paste"}),We(S,{style:V.inlineActions,children:[K(W,{onPress:()=>C(null),"sentry-label":"ignore cancel body paste",style:V.textButton,children:K(b,{style:V.textButtonMuted,children:"Cancel"})}),K(W,{onPress:()=>{let T=p.trim();try{a({body:JSON.stringify(JSON.parse(T),null,2)})}catch{a({body:T})}C(null)},disabled:!p.trim(),"sentry-label":"ignore apply body paste",style:V.textButton,children:K(b,{style:[V.textButtonLabel,!p.trim()&&V.textButtonDisabled],children:"Replace"})})]})]}):We(Ka,{children:[D!==null?K(Va.Provider,{value:{root:D,onChange:T=>a({body:JSON.stringify(T,null,2)})},children:K(fi,{editable:true,label:"",value:D,defaultExpanded:[""]})}):K(b,{style:V.emptyBody,children:k?"This body isn't JSON, so there's no tree to show.":"No body yet."}),K(W,{onPress:()=>C(""),"sentry-label":"ignore edit all body",style:V.textButton,children:K(b,{style:V.textButtonLabel,children:"Edit all"})})]})}):null,We(S,{style:V.field,children:[K(b,{style:V.subLabel,children:"Delay"}),We(S,{style:V.chipRow,children:[Qa.map(T=>K(Pr,{label:T===0?"None":`${T/1e3}s`,active:g===T,onPress:()=>a({delayMs:T})},T)),K(W,{onPress:()=>R("delay"),"sentry-label":"ignore custom delay",accessibilityLabel:"Custom delay in seconds",style:[V.customField,v&&V.customFieldActive],children:K(b,{style:[V.customValue,v&&V.customInputActive],children:v?`${g/1e3}s`:"Custom"})})]})]}),We(S,{style:V.field,children:[K(b,{style:V.subLabel,children:"Fires"}),K(b,{style:V.subHint,children:"A limited rule switches itself off once it's used up. Every other alternates forever \u2014 the first request through, the next overridden."}),We(S,{style:V.chipRow,children:[K(Pr,{label:"Always",active:!e.alternate&&e.times==null,onPress:()=>a({alternate:false,times:null})}),K(Pr,{label:"Once",active:!e.alternate&&e.times===1,onPress:()=>a({alternate:false,times:1})}),K(Pr,{label:"Every other",active:e.alternate===true,onPress:()=>a({alternate:true,times:null})}),K(W,{onPress:()=>{a({alternate:false}),R("times")},"sentry-label":"ignore custom times",accessibilityLabel:"Custom number of times",style:[V.customField,f&&V.customFieldActive],children:K(b,{style:[V.customValue,f&&V.customInputActive],children:f?`${e.times}\xD7`:"Custom"})})]})]})]}),u==="status"?K(yi,{title:"Custom status code",hint:`${$r}\u2013${Hr}`,value:m?e.status:void 0,min:$r,max:Hr,onSubmit:T=>{a({kind:"respond",status:T??void 0,statusText:void 0}),R(null)},onCancel:()=>R(null)}):null,u==="delay"?K(yi,{title:"Custom delay",hint:"Seconds",value:v?g/1e3:void 0,min:0,onSubmit:T=>{a({delayMs:T!=null?Math.round(T*1e3):0}),R(null)},onCancel:()=>R(null)}):null,u==="times"?K(yi,{title:"Fires how many times",hint:"Leave empty for always",value:f?e.times:void 0,min:1,onSubmit:T=>{a({alternate:false,times:T&&T>0?T:null}),R(null)},onCancel:()=>R(null)}):null,We(S,{style:[V.footer,{paddingBottom:12+d}],children:[K(W,{onPress:o,"sentry-label":"ignore cancel override",testID:"buoy-network-editor-cancel",accessibilityRole:"button",accessibilityLabel:"Cancel",style:[V.footerButton,V.cancelButton],children:K(b,{style:V.cancelText,children:"Cancel"})}),K(W,{onPress:r,disabled:!e.urlPattern.trim(),"sentry-label":"ignore save override",testID:"buoy-network-editor-save",accessibilityRole:"button",accessibilityLabel:n,style:[V.footerButton,V.saveButton,!e.urlPattern.trim()&&V.saveButtonDisabled],children:K(b,{style:V.saveText,children:n})})]})]})}var V=se.create({root:{flex:1},scroll:{flex:1},scrollContent:{padding:12,paddingBottom:24,gap:4},field:{gap:8,paddingVertical:6},outcomeGrid:{flexDirection:"row",flexWrap:"wrap",gap:6,paddingVertical:10},outcome:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:9,borderRadius:6,borderWidth:1,borderColor:Q.border.default,backgroundColor:Q.background.card},outcomeLabel:{fontSize:12,fontWeight:"600",color:Q.text.primary},outcomeCode:{fontSize:10,fontWeight:"700",color:Q.text.muted},disclosure:{borderRadius:6,borderWidth:1,borderColor:Q.border.default,backgroundColor:Q.background.card,overflow:"hidden"},disclosureHeader:{flexDirection:"row",alignItems:"center",gap:6,paddingHorizontal:10,paddingVertical:10},disclosureTitle:{fontSize:12,fontWeight:"600",color:Q.text.primary},disclosureSummary:{flex:1,textAlign:"right",fontSize:11,color:Q.text.muted},disclosureBody:{paddingHorizontal:10,paddingBottom:10,gap:8},input:{backgroundColor:Q.background.input,borderWidth:1,borderColor:Q.border.input,borderRadius:6,paddingHorizontal:10,paddingVertical:8,color:Q.text.primary,fontSize:12,fontFamily:If,minHeight:40},bodyInput:{minHeight:140,textAlignVertical:"top"},chipRow:{flexDirection:"row",flexWrap:"wrap",gap:6},chip:{paddingHorizontal:10,paddingVertical:6,borderRadius:5,borderWidth:1,borderColor:Q.border.default,backgroundColor:Q.background.base},chipActive:{borderColor:Q.semantic.info,backgroundColor:`${Q.semantic.info}1F`},chipText:{fontSize:11,fontWeight:"600",color:Q.text.secondary},chipTextActive:{color:Q.semantic.info},customField:{flexDirection:"row",alignItems:"center",paddingHorizontal:8,borderRadius:5,borderWidth:1,borderColor:Q.border.default,backgroundColor:Q.background.base},customFieldActive:{borderColor:Q.semantic.info,backgroundColor:`${Q.semantic.info}1F`},customValue:{paddingVertical:6,fontSize:11,fontWeight:"600",color:Q.text.secondary},customInputActive:{color:Q.semantic.info},subHint:{fontSize:10,lineHeight:14,color:Q.text.muted,marginTop:-2},subLabel:{fontSize:10,fontWeight:"700",letterSpacing:.6,color:Q.text.muted,textTransform:"uppercase"},textButton:{alignSelf:"flex-start",paddingVertical:4},textButtonLabel:{fontSize:11,fontWeight:"600",color:Q.semantic.info},textButtonMuted:{fontSize:11,fontWeight:"600",color:Q.text.secondary},textButtonDisabled:{opacity:.4},inlineActions:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},emptyBody:{fontSize:11,color:Q.text.muted,paddingVertical:6},footer:{flexDirection:"row",gap:8,padding:12,borderTopWidth:1,borderTopColor:Q.border.default,backgroundColor:Q.background.base},footerButton:{flex:1,paddingVertical:11,borderRadius:6,alignItems:"center",borderWidth:1},cancelButton:{borderColor:Q.border.default,backgroundColor:Q.background.card},cancelText:{fontSize:12,fontWeight:"600",color:Q.text.secondary},saveButton:{borderColor:Q.semantic.info,backgroundColor:`${Q.semantic.info}22`},saveButtonDisabled:{opacity:.4},saveText:{fontSize:12,fontWeight:"700",color:Q.semantic.info}});import{jsx as ke,jsxs as hr}from"react/jsx-runtime";function Wf(){return{enabled:true,urlPattern:"",kind:"respond",status:500,body:"",times:null}}function _f(e){let{id:t,hits:r,seen:o,createdAt:n,...i}=e;return i}function Vf(e){let t=e.urlPattern,r=t.indexOf("://");if(r===-1)return t;let o=t.indexOf("/",r+3);return o===-1?t.slice(r+3):t.slice(o)}function Uf(e){let t=[];return e.delayMs&&t.push(`${e.delayMs/1e3}s delay`),e.alternate?t.push("every other"):e.times===1?t.push("once"):typeof e.times=="number"&&t.push(`${e.times}\xD7`),t.join(" \xB7 ")}function Jf(e){if(e.kind==="fail")return ae.semantic.error;if(e.kind==="delay")return ae.semantic.info;let t=e.status??200;return t>=200&&t<300?ae.semantic.success:t>=300&&t<400?ae.semantic.info:ae.semantic.error}function Gf({rule:e,spent:t,onEdit:r,onDelete:o}){let n=e.enabled&&!t,i=Jf(e),s=Uf(e),d=e.methods?.length?e.methods.join("/"):"ANY";return hr(mf,{onPress:r,style:ye.cardWrapper,contentStyle:[ye.card,{borderLeftColor:n?i:"transparent"}],children:[ke(vf,{method:d,size:"small"}),hr(S,{style:ye.cardMiddle,children:[ke(b,{style:[ye.urlText,!n&&ye.urlTextOff],numberOfLines:2,children:Vf(e)}),s?ke(b,{style:ye.extrasText,children:s}):null]}),e.hits>0?ke(b,{style:ye.rowHits,children:e.hits}):null,e.kind==="fail"?hr(S,{style:ye.failBadge,children:[ke(gf,{size:10,color:ae.semantic.error}),ke(b,{style:ye.failText,children:e.failKind==="timeout"?"TIMEOUT":"OFFLINE"})]}):ke(b,{style:[ye.statusText,{color:i}],children:e.kind==="delay"?"PASS":String(e.status??200)}),ke(W,{onPress:o,"sentry-label":"ignore delete override rule",testID:"buoy-network-rule-delete",accessibilityRole:"button",accessibilityLabel:"Delete rule",hitSlop:{top:8,bottom:8,left:4,right:4},style:ye.rowDelete,children:ke(Sf,{size:13,color:ae.text.muted})})]})}function Xf(e){return e.visible?ke(Kf,{...e}):null}function Kf({isPro:e,onUpgradePress:t,pendingDraft:r,onPendingConsumed:o,backHandlerRef:n,applySafeAreaInset:i}){let s=kf("network.overrideRules"),d=e?wt:s,{enabled:a,autoPaused:l,rules:c,activeCount:y,setEnabled:w,upsertRule:p,setRuleEnabled:C,removeRule:u,isRuleSpent:R}=Uo(),[h,m]=ff(null);Go(()=>{G.noteHealthyLaunch()},[]),Go(()=>{if(n)return n.current=h?()=>(m(null),true):null,()=>{n.current=null}},[n,h]);let x=pf(k=>{G.fetchRuleBody(k).then(g=>{g!=null&&m(v=>v?.id===k?{...v,draft:{...v.draft,body:g,bodyOmitted:void 0}}:v)})},[]);Go(()=>{if(!r)return;let{id:k,...g}=r;m({id:k,draft:g}),k&&g.bodyOmitted&&x(k),o?.()},[r,o,x]),Go(()=>{h?.id&&(c.some(k=>k.id===h.id)||m(null))},[h?.id,c]);let I=k=>{m({id:k.id,draft:_f(k)}),k.bodyOmitted&&x(k.id)},B=k=>{c.filter(g=>g.enabled&&!R(g)).length<=d||c.filter(g=>g.enabled&&!R(g)&&g.id!==k).forEach(g=>C(g.id,false))},E=()=>{if(!h)return;let k={...h.draft,enabled:true,urlPattern:h.draft.urlPattern.trim()};if(!k.urlPattern)return;let g=p({...k,id:h.id});B(g?.id??h.id),w(true),m(null)};if(h)return ke(Ff,{draft:h.draft,onChange:k=>m({...h,draft:k}),onSave:E,onCancel:()=>m(null),saveLabel:h.id?"Save":"Add",applySafeAreaInset:i});let D=c.length>0;return hr(S,{style:ye.root,children:[D?hr(S,{style:[ye.bar,a&&y>0&&ye.barOn],children:[a&&y>0?ke(yf,{size:12,color:ae.semantic.warning}):null,ke(b,{style:[ye.barText,a&&y>0&&ye.barTextOn],numberOfLines:2,children:l?"Overrides paused \u2014 they'd been on for 3 launches":a&&y>0?`${y} override${y===1?" is":"s are"} on`:"Overrides are off"}),ke(W,{onPress:()=>w(!(a&&y>0)),"sentry-label":"ignore toggle overrides master",testID:"buoy-network-overrides-master",accessibilityRole:"button",style:ye.barButton,children:ke(b,{style:ye.barButtonText,children:a&&y>0?"Turn all off":l?"Turn back on":"Turn on"})})]}):null,hr(S,{style:ye.listHeader,children:[ke(b,{style:ye.listHeaderText,children:D?`${c.length} rule${c.length===1?"":"s"}`:""}),ke(W,{onPress:()=>m({draft:Wf()}),"sentry-label":"ignore new override rule",accessibilityLabel:"New override rule",style:ye.newButton,children:ke(wf,{size:14,color:ae.semantic.info})})]}),D?hr(ht,{style:ye.list,contentContainerStyle:ye.listContent,keyboardShouldPersistTaps:"handled",children:[c.map(k=>ke(Gf,{rule:k,spent:R(k),onEdit:()=>I(k),onDelete:()=>u(k.id)},k.id)),d<wt?ke(b,{style:ye.footNote,children:`Your plan: ${d} override at a time. Pro: up to ${wt}.`}):null]}):ke(S,{style:ye.emptyWrap,children:ke(bf,{otto:"empty",iconSize:32,title:"Nothing overridden",description:"Open any request and tap Override, or + to write a rule."})})]})}var ye=se.create({root:{flex:1},bar:{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:12,paddingVertical:10,borderBottomWidth:1,borderBottomColor:ae.border.default,backgroundColor:ae.background.card},barOn:{borderBottomColor:ae.semantic.warning+"44",backgroundColor:ae.semantic.warningBackground},barText:{flex:1,fontSize:12,fontWeight:"600",color:ae.text.secondary},barTextOn:{color:ae.semantic.warning},barButton:{paddingHorizontal:10,paddingVertical:6,borderRadius:5,borderWidth:1,borderColor:ae.border.hover,backgroundColor:ae.background.base},barButtonText:{fontSize:11,fontWeight:"700",color:ae.text.primary},listHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:12,paddingTop:10,paddingBottom:4},listHeaderText:{fontSize:10,fontWeight:"700",letterSpacing:.6,color:ae.text.muted,textTransform:"uppercase"},newButton:{padding:6,borderRadius:5,borderWidth:1,borderColor:ae.border.default,backgroundColor:ae.background.card},emptyWrap:{flex:1,justifyContent:"center"},list:{flex:1},listContent:{padding:10,gap:6},cardWrapper:{marginHorizontal:0,marginVertical:0},card:{flexDirection:"row",alignItems:"center",gap:8,borderLeftWidth:3,borderLeftColor:"transparent"},cardMiddle:{flex:1},urlText:{fontSize:12,color:ae.text.primary,lineHeight:16,fontFamily:xf},urlTextOff:{color:ae.text.muted},extrasText:{fontSize:10,color:ae.text.secondary,marginTop:2},statusText:{fontSize:11,fontWeight:"600"},failBadge:{flexDirection:"row",alignItems:"center",gap:2,paddingHorizontal:4,paddingVertical:1,backgroundColor:ae.semantic.error+"26",borderRadius:3},failText:{fontSize:10,color:ae.semantic.error,fontWeight:"600"},rowHits:{fontSize:11,fontWeight:"700",color:ae.semantic.warning},rowDelete:{padding:5,borderRadius:5,borderWidth:1,borderColor:ae.border.default,backgroundColor:ae.background.base},footNote:{fontSize:10,lineHeight:14,color:ae.text.muted,paddingHorizontal:4,paddingTop:8}});q();he();import{FlaskConical as Qf,night as pr}from"@buoy-gg/shared-ui/web";import{jsx as mi,jsxs as Yf}from"react/jsx-runtime";function Zf({onPress:e}){let{activeCount:t}=Uo(),r=t>0;return Yf(W,{onPress:e,"sentry-label":"ignore open overrides",testID:"buoy-network-overrides",accessibilityRole:"button",style:[tn.button,r&&tn.buttonActive],accessibilityLabel:r?`Response overrides \u2014 ${t} active`:"Response overrides",children:[mi(Qf,{size:14,color:r?pr.color.warning:pr.color.textSecondary}),r?mi(S,{style:tn.badge,children:mi(b,{style:tn.badgeText,children:t})}):null]})}var tn=se.create({button:{width:32,height:32,borderRadius:8,alignItems:"center",justifyContent:"center",backgroundColor:pr.color.buttonSurface,borderWidth:1,borderColor:pr.color.border},buttonActive:{backgroundColor:pr.color.warningSoft,borderColor:pr.color.warning+"77"},badge:{position:"absolute",top:1,right:1,minWidth:12,height:12,borderRadius:6,paddingHorizontal:3,alignItems:"center",justifyContent:"center",backgroundColor:pr.color.warning},badgeText:{fontSize:8,fontWeight:"800",color:"#000000"}});q();he();import{night as Er}from"@buoy-gg/shared-ui/web";q();function eg(e){let t=e.indexOf("?");return t===-1?e:`${e.slice(0,t)}*`}function tg(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return""}}function bi(e){return{enabled:true,name:void 0,urlPattern:eg(e.url),methods:[String(e.method||"GET").toUpperCase()],kind:"respond",status:e.status&&e.status>=200?e.status:200,statusText:e.statusText,body:tg(e.responseData),times:null}}import{jsx as el}from"react/jsx-runtime";function rg({onOpen:e}){let t=si(),{rules:r,isRuleSpent:o}=Uo(),n=t?ne.getEvents().find(d=>d.id===t)??me.getEventById(t):null,i=n?r.find(d=>d.enabled&&!o(d)&&qn(d,n.url,String(n.method||"GET")))??null:null,s=i!==null;return el(W,{onPress:()=>{if(n){if(i){let{id:d,hits:a,seen:l,createdAt:c,...y}=i;e(y,d);return}e(bi(n))}},"sentry-label":"ignore open overrides",testID:"buoy-network-override-request",accessibilityRole:"button",accessibilityLabel:s?"Edit the override on this request":"Override this request",style:[rn.button,s&&rn.buttonActive],children:el(b,{style:[rn.label,s&&rn.labelActive],children:"Override"})})}var rn=se.create({button:{paddingHorizontal:10,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:Er.color.border,backgroundColor:Er.color.buttonSurface},buttonActive:{borderColor:Er.color.warning+"77",backgroundColor:Er.color.warningSoft},label:{fontSize:11,fontWeight:"700",color:Er.color.accent},labelActive:{color:Er.color.warning}});q();he();import{Activity as og,night as It}from"@buoy-gg/shared-ui/web";q();import{useEffect as ng,useState as ig}from"react";q();import{BaseEventStore as sg,getAccountAccess as on,isBuoyRequest as ag,subscribeAccountAccess as lg}from"@buoy-gg/shared-ui/web";q();q();import{classifyKey as vi}from"@buoy-gg/shared-ui/web";var wi=64*1024,Je="[hidden]",dg=["type","event","op","action","method"],cg=["requestId","request_id","correlationId","correlation_id","ref","id"],ug=["success","ok","result","error","status"],hg=/^(ping|pong|heartbeat|hb|keep-?alive)$/i,pg=new Set(["2","3","ping","pong","heartbeat","primus::ping","primus::pong"]),tl=/^(auth|authenticate|authorize|login|sign-?in|connection_init)$/i,ro=/\beyJ[\w-]{6,}\.[\w-]{6,}\.[\w-]*/g,fg=/^4[0-6](?:\/[^,]*,)?(\d*)([[{].*)$/s,gg=256*1024,yg=/("?)([\w.-]{2,64})\1(\s*[:=]\s*)("(?:[^"\\]|\\.)*(?:"|$)|(?:(?:Bearer|Basic|Token)\s+)?[^\s,;&}\]"]+)/gi,mg=/\b(Bearer|Basic|Token)\s+[\w.~+/=-]{8,}/g,bg=/("payload"\s*:\s*)("(?:[^"\\]|\\.)*(?:"|$)|[^\s,}\]]+)/,vg=/"(?:type|event|op|action|method)"\s*:\s*"([^"\\]{1,80})"/;function wg(e){return typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))?e.byteLength:typeof Blob<"u"&&e instanceof Blob?e.size:null}function Sg(e){try{let t=e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null;if(!t)return"";let r=Array.from(t.subarray(0,32),o=>o.toString(16).padStart(2,"0")).join(" ");return t.byteLength>32?`${r} \u2026`:r}catch{return""}}function oo(e,t=0){if(t>20)return e!==null&&typeof e=="object"?Je:typeof e=="string"?e.replace(ro,Je):e;if(typeof e=="string")return e.replace(ro,Je);if(Array.isArray(e))return e.map(r=>oo(r,t+1));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=vi(o)==="secret"&&n!=null&&n!==""?Je:oo(n,t+1);return r}return e}function Br(e,t=0){return e.replace(yg,(r,o,n,i,s)=>{if(vi(n)==="secret")return`${o}${n}${o}${i}${s.startsWith('"')?`"${Je}"`:Je}`;if(s.startsWith('"')&&s.length>2&&t<3){let d=s.endsWith('"')&&s.length>1,a=s.slice(1,d?-1:void 0);return`${o}${n}${o}${i}"${Br(a,t+1)}${d?'"':""}`}return r}).replace(mg,`$1 ${Je}`).replace(ro,Je)}function kg(e){let t=e.replace(/^([a-z][\w+.-]*:\/\/[^/@:?#]*):[^/@?#]*@/i,`$1:${Je}@`),r=t.indexOf("?");if(r===-1)return t.replace(ro,Je);let o=t.slice(r+1).split("&").map(n=>{let i=n.indexOf("=");if(i===-1)return n;let s=n.slice(0,i);try{s=decodeURIComponent(s)}catch{}return vi(s)==="secret"?`${n.slice(0,i)}=${Je}`:n}).join("&");return`${t.slice(0,r)}?${o}`.replace(ro,Je)}function bt(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function rl(e,t){for(let r of t){let o=e[r];if(typeof o=="string"&&o)return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}var ol="phx_reply";function xg(e){let t=rl(e,dg);return{type:t,correlationId:rl(e,cg),replyShaped:t===ol||ug.some(r=>r in e)}}function Cg(e){if(e.length!==5||typeof e[2]!="string"||typeof e[3]!="string")return null;let t=e[1];return{type:e[3],correlationId:typeof t=="string"||typeof t=="number"?String(t):void 0,replyShaped:e[3]===ol}}function Tg(e){let t=wg(e);if(t!==null){let C=Sg(e);return{data:`[binary, ${t} bytes]${C?` ${C}`:""}`,size:t,binary:true}}let r=typeof e=="string"?e:String(e),o=r.length;if(o>gg){let C=r.slice(0,wi),u=C.trimStart()[0],R=vg.exec(C.slice(0,4096))?.[1],h=R?Br(R):void 0,m=R&&tl.test(R)?C.replace(bg,`$1"${Je}"`):C;return{data:Br(m).replace(/\beyJ[\w-]{6,}(?:\.[\w-]*)?$/,Je),size:o,truncated:true,...u==="{"||u==="["?{json:true}:{},...h?{type:h}:{}}}let n=r.trim();if(pg.has(n.toLowerCase()))return{data:r,size:o,ping:true,type:n};let i,s=false,d,a=fg.exec(n);try{a?(i=JSON.parse(a[2]),d=a[1]||void 0):(n.startsWith("{")||n.startsWith("["))&&(i=JSON.parse(n),s=true)}catch{i=void 0}let l={},c=false,y;if(a&&i&&typeof i=="object"){let C=n[1]==="3"||n[1]==="6";Array.isArray(i)&&(l=C?{correlationId:d,replyShaped:true}:{type:typeof i[0]=="string"?i[0]:void 0,correlationId:d}),y=`${n.slice(0,n.length-a[2].length)}${JSON.stringify(oo(i))}`}else if(i&&typeof i=="object"&&!Array.isArray(i)){let C=i;l=xg(C);let u=oo(C);l.type&&tl.test(l.type)&&"payload"in u&&u.payload!=null&&(u={...u,payload:Je}),y=JSON.stringify(u)}else s?(Array.isArray(i)&&(l=Cg(i)??{},c=l.type!==void 0&&i[2]==="phoenix"),y=JSON.stringify(oo(i))):y=Br(r);l.correlationId&&(l.correlationId=Br(l.correlationId)),l.type&&(l.type=Br(l.type));let w=c||!!l.type&&hg.test(l.type),p=y.length>wi;return{data:p?y.slice(0,wi):y,size:o,...p?{truncated:p}:{},...s||a?{json:true}:{},...l,...w?{ping:w}:{}}}var nn=1e4,Rg=3,Ig=15e3,Pg=3,Eg=3,Bg=12e4,Lg=3e4,zg=1008,Og=/(^|[._:-])(auth[._:-]?(expired|fail(ed|ure)?|error|invalid|rejected)|unauthori[sz]ed|token[._:-]?expired)$/i;function qg(e,t){let r=new Map(e.map(n=>[n.id,n])),o=new Map;for(let n of e){if(!n.replyTo)continue;let i=r.get(n.replyTo),s=t.get(n.socketId);if(!i?.type||!s)continue;let d=bt(s.url),a=o.get(d);a||o.set(d,a=new Set),a.add(i.type)}return o}function nl(e,t,r){let o=[...e].sort((s,d)=>s.at-d.at),n=0,i=null;for(let s=0;s<o.length;s++){for(;o[s].at-o[n].at>r;)n++;let d=s-n+1;d>t&&d>(i?.length??0)&&(i=o.slice(n,s+1))}return i}var il=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function Dg(e,t,r,o){let n=[],i=new Map(t.map(h=>[h.id,h])),s=qg(e,i);if(o)for(let[h,m]of o){let x=s.get(h)??new Set;m.forEach(I=>x.add(I)),s.set(h,x)}let d=new Map;for(let h of e)h.kind==="message"&&h.direction==="in"&&h.held&&d.set(h.socketId,[...d.get(h.socketId)??[],h.timestamp]);for(let h of e){if(h.kind!=="message"||h.direction!=="out"||h.held||h.ping||h.sentWhileClosed||!h.type||!h.correlationId||h.replyId)continue;let m=i.get(h.socketId);!m||!s.get(bt(m.url))?.has(h.type)||m.frozen||d.get(h.socketId)?.some(x=>x>=h.timestamp)||(m.closedAt!==void 0&&m.closedAt>=h.timestamp?m.closedAt:r)-h.timestamp<nn||n.push({kind:"no-reply",message:`${h.type} got no reply after ${nn/1e3}s`,socketId:h.socketId,url:m.url,frameIds:[h.id],at:h.timestamp})}let a=new Map;for(let h of[...t].sort((m,x)=>m.createdAt-x.createdAt)){let m=bt(h.url);a.set(m,[...a.get(m)??[],h])}let l=new Set;for(let h of a.values())for(let m=1;m<h.length;m++){let x=h[m-1];x.closedByBuoy&&x.closedAt!==void 0&&h[m].createdAt>=x.closedAt&&l.add(h[m].id)}let c=new Map,y=new Map;for(let h of e){let m=i.get(h.socketId);if(!m)continue;let x=bt(m.url);h.kind==="open"&&!l.has(m.id)&&c.set(x,[...c.get(x)??[],{at:h.timestamp,id:h.id}]);let I=h.kind==="close"&&h.code===zg&&!h.byBuoy,B=h.kind==="message"&&h.direction==="in"&&!h.fake&&!!h.type&&Og.test(h.type);if(!I&&!B)continue;let E=y.get(h.socketId);(!E||h.timestamp<E.at)&&y.set(h.socketId,{at:h.timestamp,id:h.id,url:x})}let w=new Map;for(let h of y.values())w.set(h.url,[...w.get(h.url)??[],{at:h.at,id:h.id}]);for(let[h,m]of c){let x=nl(m,Rg,Ig);if(!x)continue;let I=Math.max(1,Math.round((x[x.length-1].at-x[0].at)/1e3));n.push({kind:"reconnect-storm",message:`Opened ${x.length} times in ${I}s`,url:h,frameIds:x.map(B=>B.id),at:x[x.length-1].at})}for(let[h,m]of w){let x=-1/0;for(let B of a.get(h)??[]){if(B.openedAt===void 0)continue;let E=y.get(B.id)?.at??B.closedAt??r;E-B.openedAt>=Lg&&(x=Math.max(x,E))}let I=nl(m.filter(B=>B.at>x),Eg-1,Bg);I&&n.push({kind:"auth-loop",message:`Sign-in failed ${il(I.length,"time")} in a row`,url:h,frameIds:I.map(B=>B.id),at:I[I.length-1].at})}let p=new Map,C=new Map;for(let h of[...t].sort((m,x)=>m.createdAt-x.createdAt)){if(h.state!=="closed"&&h.openedAt===void 0)continue;let m=bt(h.url);if(!(h.state==="closed"&&h.openedAt===void 0&&!h.closedByBuoy)){p.set(m,[]),C.delete(m);continue}let x=[...p.get(m)??[],h];p.set(m,x),x.length>=Pg&&C.set(m,x)}for(let[h,m]of C){let x=new Set(m.map(B=>B.id)),I=e.filter(B=>B.kind==="close"&&x.has(B.socketId));n.push({kind:"cant-connect",message:`Couldn't connect: ${m.length} tries in a row failed`,url:h,frameIds:I.map(B=>B.id),at:Math.max(...m.map(B=>B.closedAt??B.createdAt))})}let u=new Map;for(let h of t){if(h.state!=="open")continue;let m=bt(h.url);u.set(m,[...u.get(m)??[],h])}for(let[h,m]of u)m.length<2||n.push({kind:"two-sockets",message:`${m.length} sockets open to the same URL`,url:h,frameIds:[],at:Math.max(...m.map(x=>x.openedAt??x.createdAt))});let R=new Map;for(let h of e)h.sentWhileClosed&&R.set(h.socketId,[...R.get(h.socketId)??[],h]);for(let[h,m]of R){let x=[...m].sort((I,B)=>I.timestamp-B.timestamp);n.push({kind:"sent-while-closed",message:`Sent ${il(x.length,"message")} while the socket was not open`,socketId:h,url:i.get(h)?.url,frameIds:x.map(I=>I.id),at:x[0].timestamp})}return n.sort((h,m)=>m.at-h.at)}q();var sl=["open","message","close","error"];var al=Symbol.for("buoy.websocket.patched"),Ag=4999;function Ng(e,t,r){try{typeof t=="function"?t.call(e,r):t&&typeof t.handleEvent=="function"&&t.handleEvent(r)}catch(o){let n=globalThis.reportError;typeof n=="function"?n(o):console.error(o)}}function ze(e){try{return e()}catch(t){typeof we<"u"&&we&&console.warn("[Buoy] Couldn't record a socket event:",t);return}}function Si(e,t,r){return{type:e,target:t,currentTarget:t,isTrusted:false,timeStamp:Date.now(),defaultPrevented:false,preventDefault(){},stopPropagation(){},stopImmediatePropagation(){},...r}}function Mg(e){var t,r;let o=globalThis,n=o.WebSocket;if(typeof n!="function"||n[al])return false;let i=n.prototype,s=i.send,d=i.close,a=i.addEventListener,l=i.removeEventListener;class c extends(r=n,t=al,r){constructor(w,p,...C){super(w,p,...C);let u=this,R={open:[],message:[],close:[],error:[]},h=false,m=false,x=null,I=Object.getOwnPropertyDescriptor(u,"readyState"),B=I&&"value"in I?I.value:void 0,E=()=>I&&"value"in I?B:Reflect.get(i,"readyState",u);Object.defineProperty(u,"readyState",{configurable:true,enumerable:true,get:()=>h?3:m?0:E(),set:P=>{B=P}});let D=()=>{let P=h;h=false;try{d.call(u,Ag,"Closed by Buoy")}catch{}finally{h=P}},k=(P,A)=>{let _=R[P],F=false,L=A,H=L?.stopImmediatePropagation;if(L&&typeof H=="function")try{L.stopImmediatePropagation=()=>{F=true,H.call(L)}}catch{}for(let j of[..._]){if(F)break;let J=_.indexOf(j);J!==-1&&(j.once&&_.splice(J,1),Ng(u,j.listener,A))}};for(let P of sl)Object.defineProperty(u,`on${P}`,{configurable:true,enumerable:true,get:()=>R[P].find(A=>A.attr)?.listener??null,set:A=>{let _=R[P],F=_.find(L=>L.attr);typeof A=="function"?F?F.listener=A:_.push({listener:A,once:false,capture:false,attr:true}):F&&_.splice(_.indexOf(F),1)}});let g=P=>typeof P=="boolean"?P:!!P?.capture;u.__buoyAdd=(P,A,_)=>{let F=R[P];if(!F)return false;let L=g(_);if(!A||F.some(J=>!J.attr&&J.listener===A&&J.capture===L))return true;let H=typeof _=="object"?_:void 0;if(H?.signal?.aborted)return true;let j={listener:A,once:!!H?.once,capture:L};return F.push(j),H?.signal?.addEventListener?.("abort",()=>{let J=F.indexOf(j);J!==-1&&F.splice(J,1)},{once:true}),true},u.__buoyRemove=(P,A,_)=>{let F=R[P];if(!F)return false;let L=g(_),H=F.findIndex(j=>!j.attr&&j.listener===A&&j.capture===L);return H!==-1&&F.splice(H,1),true},u.__buoySend=P=>{if(!x)return s.call(u,P);if(h){ze(()=>e.message(x,"out",P,{sentWhileClosed:true,held:true}));return}if(m){ze(()=>e.message(x,"out",P,{sentWhileClosed:true,held:true}));let A=globalThis.DOMException;throw typeof A=="function"?new A("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.","InvalidStateError"):new Error("INVALID_STATE_ERR")}if(E()!==1)return ze(()=>e.message(x,"out",P,{sentWhileClosed:true})),s.call(u,P);if(ze(()=>e.cutOff()!==null||e.isFrozen(x))===true){ze(()=>e.message(x,"out",P,{held:true}));return}return ze(()=>e.message(x,"out",P)),s.call(u,P)};let v={inject(P){if(!x)return;let A=ze(()=>e.message(x,"in",P,{fake:"inject"}));return k("message",Si("message",u,{data:P,origin:"",lastEventId:"",ports:[]})),A},send(P){if(!x)return;let A=h||E()!==1||ze(()=>e.cutOff()!==null||e.isFrozen(x))===true,_=ze(()=>e.message(x,"out",P,A?{fake:"send",held:A}:{fake:"send"}));return A||s.call(u,P),_},fakeClose(P,A){h||(h=true,x&&P===1006&&ze(()=>e.error(x)),x&&ze(()=>e.close(x,P,A,true)),P===1006&&k("error",Si("error",u,{message:A})),k("close",Si("close",u,{code:P,reason:A,wasClean:P!==1006})),D())},isOpen:()=>!h&&E()===1},f=typeof w=="string"?w:String(w),T=p==null?void 0:Array.isArray(p)?p:[p];x=ze(()=>e.register(f,T,v))??null;for(let P of sl)a.call(u,P,A=>{if(h||m){P==="open"&&D();return}if(x){let _=x,F=P==="open"?ze(()=>e.cutOff()):null;if(F)return v.fakeClose(1006,F);if(P==="open")ze(()=>e.open(_));else if(P==="close")ze(()=>e.close(_,A?.code,A?.reason,false));else if(P==="error")ze(()=>e.error(_));else{let L=ze(()=>e.cutOff()!==null||e.isFrozen(_))===true;if(ze(()=>e.message(_,"in",A?.data,L?{held:L}:void 0)),L)return}}k(P,A)});let M=x?ze(()=>e.cutOff()):null;M&&(m=true,D(),setTimeout(()=>v.fakeClose(1006,M),0))}addEventListener(w,p,C){if(!this.__buoyAdd?.(w,p,C))return a.call(this,w,p,C)}removeEventListener(w,p,C){if(!this.__buoyRemove?.(w,p,C))return l.call(this,w,p,C)}send(w){let p=this;return p.__buoySend?p.__buoySend(w):s.call(p,w)}}return c[t]=true,o.WebSocket=c,true}var sn=2*6e4,$g=1e3,ll=50,Hg=50,jg=200,Fg=3e4,Wg=/\/(hot|message|inspector\/(device|debug)|debugger-proxy|__expo[^/?]*)(?:[/?]|$)/,_g=/^wss?:\/\/[^/]+:8097(?:\/|$)/;function Vg(e){return ag(e)||Wg.test(e)||_g.test(e)}var Ug=class extends sg{constructor(){super({storeName:"sockets",maxEvents:$g});this.connections=new Map;this.controls=new Map;this.pending=new Map;this.answered=new Map;this.socketSeq=0;this.frameSeq=0;this.blocked=false;this.offline=false;this.installed=false;this.mirror=false;this.remote=null;this.capturingSince=null;this.mirrored=null;this.cache=null;this.version=0;this.recheck=null;this.retryOnAccess=null}install(){return this.installed||this.mirror?this.installed:on().status==="locked"?(this.retryOnAccess??(this.retryOnAccess=lg(()=>{on().status!=="locked"&&this.install()&&(this.retryOnAccess?.(),this.retryOnAccess=null)})),false):(this.installed=Mg(this),this.installed&&(this.capturingSince=Date.now(),ft(()=>this.syncOffline()),this.syncOffline()),this.installed)}startCapturing(){this.install()}stopCapturing(){}isCapturing(){return this.installed}disableCapture(){this.mirror=true,super.disableCapture()}bump(){this.notifyArrayListeners()}nextFrameId(){return`f${++this.frameSeq}`}setConnection(e,t){let r=this.connections.get(e);r&&this.connections.set(e,{...r,...t})}push(e){this.addEvent(e)}register(e,t,r){if(this.mirror||Vg(e)||on().status==="locked")return null;let o=`s${++this.socketSeq}`,n=kg(e),i=bt(n),s;for(let l of this.connections.values())bt(l.url)===i&&(s=l);let d=s?.openedAt!==void 0&&(s.closedAt??Date.now())-s.openedAt>=Fg,a=s?.state==="closed"&&s.closeCode!==1e3&&!d?s.attempt+1:1;return this.connections.set(o,{id:o,url:n,...t?.length?{protocols:t}:{},attempt:a,state:"connecting",createdAt:Date.now(),sent:0,received:0,bytesSent:0,bytesReceived:0,pings:0}),this.controls.set(o,r),this.trimConnections(),this.bump(),o}trimConnections(){if(!(this.connections.size<=ll))for(let e of this.connections.values()){if(this.connections.size<=ll)break;e.state==="closed"&&(this.connections.delete(e.id),this.controls.delete(e.id),this.pending.delete(e.id))}}open(e){let t=Date.now();this.setConnection(e,{state:"open",openedAt:t}),this.push({id:this.nextFrameId(),socketId:e,kind:"open",timestamp:t})}close(e,t,r,o){let n=this.connections.get(e);if(!n||n.state==="closed")return;let i=Date.now();this.setConnection(e,{state:"closed",closedAt:i,closeCode:t,closeReason:r||void 0,...o?{closedByBuoy:true}:{},frozen:false}),this.controls.delete(e),this.pending.delete(e),this.trimConnections(),this.push({id:this.nextFrameId(),socketId:e,kind:"close",timestamp:i,...t!==void 0?{code:t}:{},...r?{reason:r}:{},...o?{byBuoy:o}:{},...n.openedAt===void 0?{neverOpened:true}:{}})}error(e){this.push({id:this.nextFrameId(),socketId:e,kind:"error",timestamp:Date.now()})}message(e,t,r,o){let n=this.connections.get(e);if(!n||on().status==="locked")return;let i=Tg(r),s=Date.now(),d=this.nextFrameId(),a={id:d,socketId:e,kind:"message",direction:t,timestamp:s,data:i.data,size:i.size,...i.binary?{binary:true}:{},...i.truncated?{truncated:true}:{},...i.json?{json:true}:{},...i.type?{type:i.type}:{},...i.correlationId?{correlationId:i.correlationId}:{},...i.ping?{ping:true}:{},...o?.fake?{fake:o.fake}:{},...o?.held?{held:true}:{},...o?.sentWhileClosed?{sentWhileClosed:true}:{}},l=t==="out";if(this.setConnection(e,{lastMessageAt:s,...i.ping?{pings:n.pings+1}:l?{sent:n.sent+1,bytesSent:n.bytesSent+i.size}:{received:n.received+1,bytesReceived:n.bytesReceived+i.size}}),i.correlationId&&!o?.held&&!(l&&o?.sentWhileClosed)){let c=this.pending.get(e);if(l)c||this.pending.set(e,c=new Map),c.set(i.correlationId,{frameId:d,at:s}),this.scheduleRecheck();else{let y=c?.get(i.correlationId);y&&s-y.at>sn&&c.delete(i.correlationId);let w=y&&s-y.at<=sn?y.frameId:void 0,p=w?this.events.find(C=>C.id===w):void 0;if(p&&(i.replyShaped||i.type&&i.type===p.type)){c.delete(i.correlationId),a.replyTo=p.id;let C=s-p.timestamp;this.events=this.events.map(u=>u.id===p.id?{...u,replyId:d,replyMs:C}:u),p.type&&this.rememberAnswered(bt(n.url),p.type)}}}return this.push(a),d}rememberAnswered(e,t){let r=this.answered.get(e);for(r?this.answered.delete(e):r=new Set,this.answered.set(e,r),r.delete(t),r.add(t);r.size>jg;)r.delete(r.values().next().value);for(;this.answered.size>Hg;)this.answered.delete(this.answered.keys().next().value)}scheduleRecheck(){this.recheck&&clearTimeout(this.recheck),this.recheck=null;let e=Date.now(),t=1/0;for(let[r,o]of this.pending){for(let[n,i]of o){let s=e-i.at;s>sn?o.delete(n):t=Math.min(t,s<nn?i.at+nn:i.at+sn+1)}o.size===0&&this.pending.delete(r)}t!==1/0&&(this.recheck=setTimeout(()=>{this.recheck=null,this.bump(),this.scheduleRecheck()},Math.max(0,t-e)+100))}cutOff(){return this.offline?"Offline (Buoy)":this.blocked?"Blocked by Buoy":null}isFrozen(e){return this.connections.get(e)?.frozen===true}syncOffline(){let e=Lt()&&(jt()==="offline"||["offline","noInternet"].includes(Vc()));if(e!==this.offline){if(this.offline=e,e)for(let t of[...this.controls.values()])t.fakeClose(1006,"Offline (Buoy)");this.bump()}}getState(){if(this.mirrored)return this.mirrored;if(this.cache?.version===this.version&&this.cache.state.frames===this.events)return this.cache.state;let e=[...this.connections.values()].reverse(),t=this.getEvents(),r={connections:e,frames:t,problems:Dg(t,e,Date.now(),this.answered),tests:{blocked:this.blocked,offline:this.offline,frozen:e.filter(o=>o.frozen).map(o=>o.id)},capturingSince:this.capturingSince};return this.cache={version:this.version,state:r},r}getFrame(e){return this.getState().frames.find(t=>t.id===e)}subscribeState(e){return this.subscribeToEvents(()=>e())}setRemote(e){this.remote=e}async loadFrame(e){if(this.remote)return this.remote.getFrame(e);let t=this.getFrame(e);if(!t)return null;let r=t.replyId??t.replyTo;return{frame:t,partner:r?this.getFrame(r)??null:null}}applySnapshot(e){this.mirrored=e,this.notifyArrayListeners()}async act(e){return this.remote?this.remote.act(e):this.actLocal(e)}actLocal(e){let t="socketId"in e?this.controls.get(e.socketId):void 0,r=o=>({ok:false,message:this.connections.has(o)?`Socket ${o} is closed.`:`No socket ${o}. Read get_sockets for ids.`});switch(e.action){case"inject":return t?{ok:true,frameId:t.inject(e.data),message:`Pushed the message into the app on ${e.socketId}, as if the server sent it.`}:r(e.socketId);case"send":{if(!t)return r(e.socketId);let o=this.connections.get(e.socketId)?.state==="connecting",n=t.send(e.data);return(n?this.getFrame(n)?.held:false)?{ok:false,frameId:n,message:o?`Held back: ${e.socketId} is still connecting, so the server did not get it. Try again once it's open.`:`Held back: ${e.socketId} is frozen, blocked or offline, so the server did not get it.`}:{ok:true,frameId:n,message:`Sent to the server on ${e.socketId}.`}}case"close":{if(!t)return r(e.socketId);let o=e.code??1006;if(!Number.isInteger(o)||o<1e3||o>4999)return{ok:false,message:`Close code ${o} isn't a WebSocket close code. Use 1000-4999, like 1006, 1008 or 1001.`};let n=e.reason??(o===1006?"Dropped by Buoy":"Closed by Buoy");return t.fakeClose(o,n),{ok:true,message:`Closed ${e.socketId} with code ${o}. The app got the close; watch for its reconnect.`}}case"freeze":return t?(this.setConnection(e.socketId,{frozen:e.frozen}),this.bump(),{ok:true,message:e.frozen?`Froze ${e.socketId}: it still looks open, but no messages get through either way.`:`Unfroze ${e.socketId}. Messages held while frozen are lost.`}):r(e.socketId);case"block":{if(this.blocked=e.blocked,e.blocked)for(let o of[...this.controls.values()])o.fakeClose(1006,"Blocked by Buoy");return this.bump(),{ok:true,message:e.blocked?"Blocked: open sockets dropped, and every new one fails until you unblock.":"Unblocked: new sockets can connect again."}}case"reset":{this.blocked=false;for(let o of this.connections.values())o.frozen&&this.setConnection(o.id,{frozen:false});return this.bump(),{ok:true,message:"Reset: no socket is frozen or blocked. The app reconnects on its own schedule."}}case"clear":return this.clearEvents(),{ok:true,message:"Cleared the message list."}}}clearEvents(){for(let[e,t]of this.connections)t.state==="closed"&&this.connections.delete(e);this.pending.clear(),this.answered.clear(),super.clearEvents()}notifyArrayListeners(){this.version++,super.notifyArrayListeners()}},Pe=new Ug;var Jg=100;function an(e=false){let[t,r]=ig(()=>Pe.getState());return ng(()=>{if(e)return;r(Pe.getState());let o=null,n=0,i=()=>{o=null,n=Date.now(),r(Pe.getState())},s=Pe.subscribeState(()=>{if(o)return;let d=Math.max(0,Jg-(Date.now()-n));o=setTimeout(i,d)});return()=>{s(),o&&clearTimeout(o)}},[e]),t}import{jsx as ki,jsxs as Gg}from"react/jsx-runtime";function Xg({onPress:e,paused:t}){let r=an(t);if(r.connections.length===0)return null;let o=r.connections.some(d=>d.state==="open"),n=r.tests.blocked||r.tests.offline||r.tests.frozen.length>0,i=r.problems.length,s=n?It.color.warning:o?It.color.accent:It.color.textSecondary;return Gg(W,{onPress:e,"sentry-label":"ignore open sockets",testID:"buoy-network-sockets",accessibilityRole:"button",accessibilityLabel:`Sockets${o?", one open":""}${i?`, ${i} ${i===1?"problem":"problems"}`:""}${n?", a trick is on":""}`,style:[no.button,n?no.testing:o?no.open:null],children:[ki(og,{size:14,color:s}),i>0?ki(S,{style:no.badge,children:ki(b,{style:no.badgeText,children:i})}):null]})}var no=se.create({button:{width:32,height:32,borderRadius:8,alignItems:"center",justifyContent:"center",backgroundColor:It.color.buttonSurface,borderWidth:1,borderColor:It.color.border},open:{backgroundColor:It.color.accentSoft,borderColor:It.color.accentBorder},testing:{backgroundColor:It.color.warningSoft,borderColor:It.color.warning+"77"},badge:{position:"absolute",top:1,right:1,minWidth:12,height:12,borderRadius:6,paddingHorizontal:3,alignItems:"center",justifyContent:"center",backgroundColor:It.color.danger},badgeText:{fontSize:8,fontWeight:"800",color:"#FFFFFF"}});q();he();import{useEffect as xi,useState as dl}from"react";q();he();import{useEffect as cl,useState as Ci}from"react";import{InlineCopyButton as Kg,NightBadge as qt,NightButton as ul,monoFont as io,night as ot}from"@buoy-gg/shared-ui/web";q();function ln(e){let t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(r=>String(r).padStart(2,"0")).join(":")}function dn(e){if(e<1e3)return`${Math.max(0,Math.round(e))}ms`;if(e<1e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let r=Math.floor(t/60);return r<60?`${r}m ${t%60}s`:`${Math.floor(r/60)}h ${r%60}m`}function Ti(e){return e.replace(/^wss?:\/\//,"")}var Qg={1e3:"normal",1001:"going away",1006:"lost connection",1008:"rejected",1011:"server error",1012:"server restart",4999:"Buoy"};function Ri(e,t=false){if(e===void 0)return"Closed";let r=e===1006&&t?"couldn't connect":Qg[e];return r?`Closed ${e} \xB7 ${r}`:`Closed ${e}`}function hl(e,t){switch(e.state){case"connecting":return"Connecting";case"open":return`Open ${dn(t-(e.openedAt??e.createdAt))}`;case"closing":return"Closing";case"closed":return`${Ri(e.closeCode,e.openedAt===void 0)}${e.closedByBuoy?" (Buoy)":""}`}}var Yg=["payload","data","body","d"],Zg=["content","text","message","body"];function ey(e){if(!(!e||typeof e!="object"||Array.isArray(e)))for(let t of Zg){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim().slice(0,80)}}function ty(e){if(e.binary)return e.data??"[binary]";let t=(e.data??"").replace(/\s+/g," ").trim();if(!e.json||!e.type)return t;try{let r=JSON.parse(e.data??"");if(r&&typeof r=="object"&&!Array.isArray(r)){let{type:o,event:n,op:i,action:s,method:d,...a}=r;for(let p of["requestId","request_id","correlationId","correlation_id","ref","id"])String(a[p])===e.correlationId&&delete a[p];let l=Object.keys(a),c=l.length===1&&Yg.includes(l[0])?a[l[0]]:void 0,y=c&&typeof c=="object"?c:a,w=ey(y);return`${w?`"${w}" \xB7 `:""}${JSON.stringify(y)}`}}catch{}return t}function ry(e){if(!e.json||!e.data)return e.data??"";try{return JSON.stringify(JSON.parse(e.data),null,2)}catch{return e.data}}import{jsx as de,jsxs as fr}from"react/jsx-runtime";function pl({frame:e,label:t}){let r=ry(e);return fr(S,{style:Re.box,children:[fr(S,{style:Re.boxHead,children:[de(b,{style:Re.boxLabel,children:t}),de(b,{style:Re.boxTime,children:ln(e.timestamp)}),de(Kg,{value:r})]}),de(b,{selectable:true,style:Re.code,testID:`buoy-socket-data-${e.id}`,children:r||"(empty)"}),e.truncated?de(b,{style:Re.boxNote,children:"Cut at 64 KB. The rest was not kept."}):null]})}function oy({visible:e}){return e?de(S,{style:Re.missing,children:de(b,{style:Re.note,children:"This message is gone. It was cleared or pushed out by newer ones."})}):null}function ny({loaded:e,isPro:t,onUpgradePress:r,onEdit:o}){let[n,i]=Ci(null),s=e?.frame;if(cl(()=>i(null),[s?.id]),!s)return null;let d=s.direction==="out",a=e?.partner??null,l=s.replyTo?a:s,c=s.replyTo?s:a,y=Pe.getState().problems.find(p=>p.frameIds.includes(s.id)),w=async()=>{if(!t)return r();let p=s.data??"",C=await Pe.act(d?{action:"send",socketId:s.socketId,data:p}:{action:"inject",socketId:s.socketId,data:p});i(C.message)};return fr(ht,{contentContainerStyle:Re.content,testID:"buoy-socket-detail",children:[fr(S,{style:Re.titleRow,children:[de(b,{style:[Re.dir,d?Re.up:Re.down],children:d?"\u2191":"\u2193"}),de(b,{style:Re.title,numberOfLines:2,children:s.type??"message"})]}),fr(S,{style:Re.badges,children:[y?de(qt,{label:y.kind==="no-reply"?"No reply":"Problem",tone:"danger"}):null,l?.replyMs!==void 0?de(qt,{label:`Reply in ${dn(l.replyMs)}`,tone:"accent"}):null,s.correlationId?de(qt,{label:`id ${s.correlationId}`,tone:"info"}):null,de(qt,{label:`Socket ${s.socketId}`}),s.size!==void 0?de(qt,{label:`${s.size} B`}):null,s.fake==="inject"?de(qt,{label:"Fake: pushed by Buoy",tone:"info"}):null,s.fake==="send"?de(qt,{label:"Sent by Buoy",tone:"info"}):null,s.held?de(qt,{label:"Held back",tone:"warning"}):null,s.sentWhileClosed?de(qt,{label:"Sent while closed",tone:"danger"}):null]}),l?de(pl,{frame:l,label:l.direction==="out"?"\u2191 Sent":"\u2193 Got"}):null,l&&c?de(b,{style:Re.gap,children:dn(c.timestamp-l.timestamp)}):null,c?de(pl,{frame:c,label:"\u2193 Reply"}):null,fr(S,{style:Re.buttons,children:[de(ul,{label:d?"Send again":"Push to app again",variant:"primary",onPress:w,testID:"buoy-socket-replay"}),de(ul,{label:"Edit in Tricks",onPress:()=>t?o(s):r(),testID:"buoy-socket-edit"})]}),y?de(b,{style:Re.problem,children:y.message}):null,n?de(b,{style:Re.result,children:n}):null,s.data?.includes("[hidden]")?de(b,{style:Re.note,children:"Buoy hid secrets in this message. Sending it again sends the word [hidden] in their place."}):null]})}function iy({visible:e,frameId:t,isPro:r,onUpgradePress:o,onEdit:n}){let[i,s]=Ci(null),[d,a]=Ci(false);if(cl(()=>{if(s(null),a(false),!e||!t)return;let y=true;return Pe.loadFrame(t).then(w=>{y&&(s(w),a(true))}),()=>{y=false}},[e,t]),!e)return null;let l=t?Pe.getFrame(t):void 0,c=i??(l?{frame:l,partner:null}:null);return fr(S,{style:Re.fill,children:[de(oy,{visible:d&&!c}),de(ny,{loaded:c,isPro:r,onUpgradePress:o,onEdit:n})]})}var Re=se.create({fill:{flex:1},content:{padding:12,gap:10,paddingBottom:32},missing:{padding:24},titleRow:{flexDirection:"row",alignItems:"center",gap:8},dir:{fontSize:16,fontWeight:"700",fontFamily:io},up:{color:"#6EA1FF"},down:{color:ot.color.accent},title:{flexShrink:1,fontSize:15,fontWeight:"600",color:ot.color.text,fontFamily:io},badges:{flexDirection:"row",flexWrap:"wrap",gap:6},box:{borderWidth:1,borderColor:ot.color.border,borderRadius:8,backgroundColor:ot.color.surface,overflow:"hidden"},boxHead:{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:9,paddingVertical:6,borderBottomWidth:1,borderBottomColor:ot.color.separator},boxLabel:{flex:1,fontSize:10,fontWeight:"700",color:ot.color.textSecondary,letterSpacing:.4},boxTime:{fontSize:10,color:ot.color.textTertiary,fontFamily:io},boxNote:{paddingHorizontal:9,paddingBottom:8,fontSize:11,color:ot.color.textTertiary},code:{padding:9,fontSize:11,lineHeight:16,color:ot.color.text,fontFamily:io},gap:{textAlign:"center",fontSize:11,color:ot.color.textSecondary,fontFamily:io},buttons:{flexDirection:"row",flexWrap:"wrap",gap:8},result:{fontSize:12,color:ot.color.textSecondary},problem:{fontSize:12,color:ot.color.danger,fontWeight:"600"},note:{fontSize:11,color:ot.color.textTertiary}});q();he();import{useEffect as sy,useState as so}from"react";import{EVENT_LIST_PRESET as ay,NightChip as Lr,ToolEmptyState as ly,Zap as dy,monoFont as cy,night as Ge,resolveListEmptyState as uy}from"@buoy-gg/shared-ui/web";q();function hy(e,t,r){if(t.socketId&&e.socketId!==t.socketId||e.ping&&!t.showPings)return false;let o=t.filter??{kind:"all"};if(o.kind==="problems"&&!r.has(e.id)||o.kind==="direction"&&e.direction!==o.direction||o.kind==="type"&&!fl(e.type,o.prefix))return false;if(t.search){let n=t.search.toLowerCase();if(!`${e.type??""} ${e.data??""} ${e.reason??""}`.toLowerCase().includes(n))return false}return true}function py(e,t={}){let r=new Map;for(let i of e.problems)for(let s of i.frameIds)r.has(s)||r.set(s,i);let o=[];for(let i of e.frames){if(!hy(i,t,r))continue;let s=r.get(i.id),d=o[o.length-1],a=d?.frames[d.frames.length-1];a&&!s&&!d.problem&&i.kind==="message"&&a.kind==="message"&&!i.fake&&!a.fake&&!i.replyId&&!a.replyId&&i.type!==void 0&&i.type===a.type&&i.direction===a.direction&&i.socketId===a.socketId&&a.timestamp-i.timestamp<=1500?d.frames.push(i):o.push({frames:[i],...s?{problem:s}:{}})}let n=[];for(let i of o){let s=i.frames[i.frames.length-1].id;if(i.frames.length>=3&&!t.expanded?.has(s)){n.push({frame:i.frames[0],count:i.frames.length,foldKey:s});continue}for(let d of i.frames)n.push({frame:d,count:1,...i.problem?{problem:i.problem}:{}})}return n}function fl(e,t){return e?e.startsWith(t)||/[.:/]$/.test(t)&&e===t.slice(0,-1):false}function fy(e,t=4){let r=new Map;for(let o of e){if(o.kind!=="message"||o.ping||!o.type)continue;let n=o.type.search(/[.:/]/),i=n>0?`${o.type.slice(0,n+1)}`:o.type;r.set(i,(r.get(i)??0)+1)}for(let[o,n]of[...r]){let i=[".",":","/"].map(s=>o+s).find(s=>r.has(s));i&&(r.set(i,r.get(i)+n),r.delete(o))}return[...r.entries()].sort((o,n)=>n[1]-o[1]).slice(0,t).map(([o])=>o)}q();he();import{monoFont as cn,night as Ee}from"@buoy-gg/shared-ui/web";import{jsx as vt,jsxs as gr}from"react/jsx-runtime";var gl="#6EA1FF";function yl({label:e,tone:t}){return vt(S,{style:[je.tag,bl[t].box],children:vt(b,{style:[je.tagText,bl[t].text],numberOfLines:1,children:e})})}function gy(e){let t=e.frame,r=[];return e.problem&&r.push({label:ml[e.problem.kind],tone:"bad"}),t.replyMs!==void 0&&r.push({label:`\u2713 ${dn(t.replyMs)}`,tone:"ok"}),t.fake==="inject"&&r.push({label:"Fake",tone:"info"}),t.fake==="send"&&r.push({label:"Buoy sent",tone:"info"}),t.held&&r.push({label:"Held",tone:"warn"}),t.sentWhileClosed&&r.push({label:"Closed",tone:"bad"}),r}var ml={"no-reply":"No reply","reconnect-storm":"Storm","auth-loop":"Sign-in loop","cant-connect":"Can't connect","two-sockets":"Two sockets","sent-while-closed":"Sent while closed"};function yy({row:e,onOpen:t,onExpand:r}){let o=e.frame,n=o.direction==="out",i=o.type??(o.binary?"binary":"message"),s=e.count>1&&e.foldKey!==void 0;return gr(W,{activeOpacity:.7,onPress:()=>s?r(e.foldKey):t(o),"sentry-label":"ignore open socket message",testID:`buoy-socket-row-${o.id}`,accessibilityRole:"button",accessibilityLabel:s?`${e.count} ${i} messages, tap to show each`:`${n?"Sent":"Got"} ${i}`,style:[je.row,e.problem?je.rowProblem:null],children:[vt(b,{style:[je.dir,{color:n?gl:Ee.color.accent}],children:n?"\u2191":"\u2193"}),gr(S,{style:je.middle,children:[gr(S,{style:je.titleLine,children:[vt(b,{style:je.type,numberOfLines:1,children:i}),e.count>1?vt(yl,{label:`\xD7${e.count}`,tone:"plain"}):null]}),gr(b,{style:je.preview,numberOfLines:1,children:[o.correlationId?`${o.correlationId} \xB7 `:"",ty(o)]})]}),gr(S,{style:je.right,children:[vt(S,{style:je.tags,children:gy(e).slice(0,2).map(d=>vt(yl,{label:d.label,tone:d.tone},d.label))}),vt(b,{style:je.time,children:ln(o.timestamp)})]})]})}function my({row:e,attempt:t}){let r=e.frame,o=r.kind==="open"?`Open${t&&t>1?` #${t}`:""}`:r.kind==="error"?"Error":Ri(r.code,r.neverOpened),n=r.byBuoy&&!/buoy/i.test(r.reason??"")?"by Buoy":null,i=[e.problem?`\u26A0 ${ml[e.problem.kind]}`:null,r.kind==="close"?r.reason:null,r.kind==="close"?n:null].filter(Boolean).join(" \xB7 "),s=e.problem||r.kind==="error"?Ee.color.danger:r.kind==="open"?Ee.color.accent:Ee.color.warning;return gr(S,{style:je.life,testID:`buoy-socket-life-${r.id}`,children:[vt(S,{style:je.lifeLine}),gr(b,{style:je.lifeText,numberOfLines:1,children:[vt(b,{style:[je.lifeLabel,{color:s}],children:o}),i?` \xB7 ${i}`:""," \xB7 ",ln(r.timestamp)]}),vt(S,{style:je.lifeLine})]})}var bl={ok:se.create({box:{backgroundColor:Ee.color.accentSoft},text:{color:Ee.color.accent}}),bad:se.create({box:{backgroundColor:Ee.color.dangerSoft},text:{color:Ee.color.danger}}),warn:se.create({box:{backgroundColor:Ee.color.warningSoft},text:{color:Ee.color.warning}}),info:se.create({box:{backgroundColor:Ee.color.infoSoft},text:{color:gl}}),plain:se.create({box:{backgroundColor:Ee.color.fill},text:{color:Ee.color.textSecondary}})},je=se.create({row:{flexDirection:"row",alignItems:"center",gap:8,paddingVertical:7,paddingHorizontal:10,marginHorizontal:8,backgroundColor:"rgba(12, 12, 12, 0.9)",borderBottomWidth:1,borderBottomColor:Ee.color.separator,borderLeftWidth:3,borderLeftColor:"transparent"},rowProblem:{borderLeftColor:Ee.color.danger,backgroundColor:"rgba(40, 12, 12, 0.9)"},dir:{width:14,fontSize:13,fontWeight:"700",fontFamily:cn,textAlign:"center"},middle:{flex:1,minWidth:0,gap:1},titleLine:{flexDirection:"row",alignItems:"center",gap:6},type:{flexShrink:1,fontSize:12,fontWeight:"600",color:Ee.color.text,fontFamily:cn},preview:{fontSize:10,color:Ee.color.textTertiary,fontFamily:cn},right:{alignItems:"flex-end",gap:3},tags:{flexDirection:"row",gap:4},tag:{paddingHorizontal:5,paddingVertical:1,borderRadius:4},tagText:{fontSize:9.5,fontWeight:"700"},time:{fontSize:9,color:Ee.color.textTertiary,fontFamily:cn},life:{flexDirection:"row",alignItems:"center",gap:8,paddingVertical:6,paddingHorizontal:12},lifeLine:{flex:1,height:1,backgroundColor:Ee.color.separator},lifeText:{fontSize:10.5,color:Ee.color.textSecondary,flexShrink:1},lifeLabel:{fontWeight:"700"}});import{jsx as xe,jsxs as Dt}from"react/jsx-runtime";var by=2,vy=2*6e4,wy=e=>e.frame.id;function Sy(e){let[t,r]=so(Date.now);return sy(()=>{if(!e)return;r(Date.now());let o=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(o)},[e]),t}function ky({conn:e,selected:t,onPress:r,showPings:o,onTogglePings:n}){let i=e.state==="open",s=Sy(i),d=i?oe.pillOk:e.state==="closed"?oe.pillWarn:oe.pillPlain,a=i?oe.pillOkText:e.state==="closed"?oe.pillWarnText:oe.pillPlainText;return Dt(W,{activeOpacity:.8,onPress:r,"sentry-label":"ignore pick socket",testID:`buoy-socket-card-${e.id}`,accessibilityRole:"button",accessibilityLabel:`Socket ${e.id}, ${hl(e,s)}`,style:[oe.card,t?oe.cardSelected:null],children:[xe(b,{style:oe.cardUrl,numberOfLines:1,children:Ti(e.url)}),Dt(S,{style:oe.pills,children:[xe(S,{style:[oe.pill,d],children:Dt(b,{style:[oe.pillText,a],children:[i?"\u25CF ":"",hl(e,s)]})}),e.frozen?xe(S,{style:[oe.pill,oe.pillWarn],children:xe(b,{style:[oe.pillText,oe.pillWarnText],children:"Frozen"})}):null,e.attempt>1?xe(S,{style:[oe.pill,oe.pillPlain],children:Dt(b,{style:[oe.pillText,oe.pillPlainText],children:["Try #",e.attempt]})}):null,xe(S,{style:[oe.pill,oe.pillPlain],children:Dt(b,{style:[oe.pillText,oe.pillPlainText],children:["\u2191",e.sent," \u2193",e.received]})}),e.pings>0?xe(W,{onPress:n,"sentry-label":"ignore toggle socket pings",testID:`buoy-socket-pings-${e.id}`,style:[oe.pill,oe.pillPlain],children:Dt(b,{style:[oe.pillText,oe.pillPlainText],children:["\u2665 ",e.pings," ",e.pings===1?"heartbeat":"heartbeats"," ",o?"shown":"hidden"]})}):null]})]})}function xy({problems:e}){let t=Date.now(),r=e.filter(o=>t-o.at<vy&&(o.frameIds.length===0||o.kind==="reconnect-storm"||o.kind==="auth-loop"||o.kind==="cant-connect"));return r.length===0?null:xe(S,{style:oe.banner,testID:"buoy-socket-problems",children:r.slice(0,3).map(o=>Dt(b,{style:oe.bannerText,numberOfLines:2,children:["\u26A0 ",o.message," \xB7 ",ln(o.at)]},`${o.kind}-${o.at}`))})}function Cy({visible:e,paused:t,search:r,onOpenFrame:o,onOpenTricks:n}){let i=an(t||!e),[s,d]=so(null),[a,l]=so({kind:"all"}),[c,y]=so(false),[w,p]=so(()=>new Set);if(!e)return null;let C=i.connections.filter(f=>f.state!=="closed"),u=i.connections.find(f=>f.id===s&&f.state==="closed"),R=C.length?C:i.connections.filter(f=>f.state==="closed").slice(0,1),h=[...u&&!R.includes(u)?[u]:[],...R].slice(0,by),m=py(i,{socketId:s,filter:a,showPings:c,search:r,expanded:w}),x=f=>p(new Set(w).add(f)),I=new Map(i.connections.map(f=>[f.id,f.attempt])),B=fy(i.frames),E=new Set(i.problems.flatMap(f=>f.frameIds)).size,D=f=>JSON.stringify(f)===JSON.stringify(a),k=f=>l(D(f)?{kind:"all"}:f),g=({item:f})=>f.frame.kind==="message"?xe(yy,{row:f,onOpen:o,onExpand:x}):xe(my,{row:f,attempt:I.get(f.frame.socketId)}),v=Dt(S,{style:oe.header,children:[h.map(f=>xe(ky,{conn:f,selected:s===f.id,onPress:()=>d(s===f.id?null:f.id),showPings:c,onTogglePings:()=>y(!c)},f.id)),xe(xy,{problems:i.problems}),Dt(ht,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:oe.chips,children:[xe(Lr,{label:"Tricks",icon:xe(dy,{size:11,color:Ge.color.warning}),onPress:()=>n(s??i.connections.find(f=>f.state==="open")?.id??null),testID:"buoy-socket-tricks"}),xe(Lr,{label:`All ${i.frames.length}`,selected:a.kind==="all",onPress:()=>l({kind:"all"}),testID:"buoy-socket-chip-all"}),E>0?xe(Lr,{label:`Problems ${E}`,selected:a.kind==="problems",onPress:()=>k({kind:"problems"}),testID:"buoy-socket-chip-problems"}):null,xe(Lr,{label:"\u2191 Sent",selected:D({kind:"direction",direction:"out"}),onPress:()=>k({kind:"direction",direction:"out"}),testID:"buoy-socket-chip-sent"}),xe(Lr,{label:"\u2193 Got",selected:D({kind:"direction",direction:"in"}),onPress:()=>k({kind:"direction",direction:"in"}),testID:"buoy-socket-chip-got"}),B.map(f=>xe(Lr,{label:f.match(/[.:/]$/)?`${f}*`:f,selected:D({kind:"type",prefix:f}),onPress:()=>k({kind:"type",prefix:f}),testID:`buoy-socket-chip-type-${f}`},f))]}),i.tests.blocked||i.tests.offline||i.tests.frozen.length>0?xe(b,{style:oe.testNote,numberOfLines:1,children:i.tests.offline?"Offline mode is on":i.tests.blocked?"New sockets are blocked":"A socket is frozen"}):null]});return xe(go,{...ay,testID:"buoy-socket-list",accessibilityLabel:"Socket messages",data:m,renderItem:g,keyExtractor:wy,ListHeaderComponent:v,ListEmptyComponent:xe(ly,{testID:"buoy-socket-empty",...uy({subject:"messages",search:r,total:i.frames.length,capturing:i.capturingSince!==null||i.connections.length>0,waiting:{otto:"fishing",title:"No socket messages",message:"Messages show here when your app opens a WebSocket."},paused:{title:"Not watching sockets",message:"Buoy watches sockets in dev builds once the Network tool loads."}})}),contentContainerStyle:oe.listContent,keyboardShouldPersistTaps:"handled",showsVerticalScrollIndicator:true})}var oe=se.create({listContent:{paddingBottom:24},header:{gap:6,paddingTop:8,paddingBottom:4},card:{marginHorizontal:10,padding:9,gap:6,borderRadius:10,borderWidth:1,borderColor:Ge.color.border,backgroundColor:Ge.color.surface},cardSelected:{borderColor:Ge.color.accentBorderStrong,backgroundColor:Ge.color.accentSoft},cardUrl:{fontSize:11,color:Ge.color.text,fontFamily:cy},pills:{flexDirection:"row",flexWrap:"wrap",gap:5},pill:{paddingHorizontal:6,paddingVertical:2,borderRadius:5},pillText:{fontSize:10,fontWeight:"600"},pillOk:{backgroundColor:Ge.color.accentSoft},pillOkText:{color:Ge.color.accent},pillWarn:{backgroundColor:Ge.color.warningSoft},pillWarnText:{color:Ge.color.warning},pillPlain:{backgroundColor:Ge.color.fill},pillPlainText:{color:Ge.color.textSecondary},banner:{marginHorizontal:10,padding:8,gap:3,borderRadius:8,backgroundColor:Ge.color.dangerSoft,borderWidth:1,borderColor:"rgba(255,59,48,0.3)"},bannerText:{fontSize:11,color:Ge.color.danger,fontWeight:"600"},chips:{gap:6,paddingHorizontal:10},testNote:{paddingHorizontal:12,fontSize:11,color:Ge.color.warning,fontWeight:"600"}});q();he();import{useEffect as Ty,useState as Ii}from"react";import{NightButton as Pi,NightChip as Ry,NightSectionLabel as Ei,NightSwitch as vl,monoFont as Iy,night as nt}from"@buoy-gg/shared-ui/web";import{jsx as be,jsxs as yr}from"react/jsx-runtime";var Py=[{code:1006,title:"Drop it",detail:"1006 \xB7 like lost signal",testID:"buoy-socket-drop"},{code:1008,title:"Kick out",detail:"1008 \xB7 like a bad token",testID:"buoy-socket-kick"},{code:1001,title:"Server going away",detail:"1001 \xB7 like a deploy",testID:"buoy-socket-going-away"}];function Ey({visible:e,draft:t,isPro:r,onUpgradePress:o}){let n=an(!e),[i,s]=Ii(null),[d,a]=Ii(""),[l,c]=Ii(null);if(Ty(()=>{!e||!t||(s(t.socketId),a(t.data),c(null))},[e,t]),!e)return null;let y=n.connections.filter(u=>u.state==="open"||u.state==="connecting"),w=y.find(u=>u.id===i)??y[0]??null,p=async u=>{if(!r)return o();c(await Pe.act(u))},C=n.tests.blocked||n.tests.frozen.length>0;return yr(ht,{contentContainerStyle:ve.content,keyboardShouldPersistTaps:"handled",testID:"buoy-socket-tricks-screen",children:[be(b,{style:ve.lede,children:"Make the socket misbehave on purpose. Your app's real code handles each one."}),be(Ei,{children:"Socket"}),y.length===0?be(b,{style:ve.note,children:"No socket is open. Open one in your app, or turn Block off."}):null,y.length>0?be(S,{style:ve.chips,children:y.map(u=>be(Ry,{label:`${u.id} \xB7 ${Ti(u.url)}`,selected:w?.id===u.id,onPress:()=>s(u.id),testID:`buoy-socket-target-${u.id}`},u.id))}):null,be(Ei,{children:"Message"}),be(Xt,{value:d,onChangeText:a,multiline:true,autoCapitalize:"none",autoCorrect:false,placeholder:'{"type":"chat.message","payload":{"text":"hi"}}',placeholderTextColor:nt.color.placeholder,style:ve.input,testID:"buoy-socket-message-input",accessibilityLabel:"Message to push or send"}),yr(S,{style:ve.row,children:[be(Pi,{label:"Push to app",variant:"primary",disabled:!w||!d.trim(),onPress:()=>w&&p({action:"inject",socketId:w.id,data:d}),testID:"buoy-socket-inject"}),be(Pi,{label:"Send to server",disabled:!w||!d.trim(),onPress:()=>w&&p({action:"send",socketId:w.id,data:d}),testID:"buoy-socket-send"})]}),be(Ei,{children:"Break the socket"}),be(S,{style:ve.grid,children:Py.map(u=>yr(W,{disabled:!w,onPress:()=>w&&p({action:"close",socketId:w.id,code:u.code}),"sentry-label":"ignore socket break",testID:u.testID,accessibilityRole:"button",style:[ve.cell,w?null:ve.cellOff],children:[be(b,{style:ve.cellTitle,children:u.title}),be(b,{style:ve.cellDetail,children:u.detail})]},u.code))}),be(b,{style:ve.note,children:'On iOS, a real lost link often closes as 1001 "Stream end encountered", not 1006. Check for both.'}),yr(S,{style:ve.switchRow,children:[yr(S,{style:ve.switchText,children:[be(b,{style:ve.switchTitle,children:"Freeze"}),be(b,{style:ve.cellDetail,children:"Looks open, but nothing gets through. Tests your app's ping check."})]}),be(vl,{value:!!w?.frozen,disabled:!w,onValueChange:u=>w&&p({action:"freeze",socketId:w.id,frozen:u}),testID:"buoy-socket-freeze"})]}),yr(S,{style:ve.switchRow,children:[yr(S,{style:ve.switchText,children:[be(b,{style:ve.switchTitle,children:"Block"}),be(b,{style:ve.cellDetail,children:"Drops open sockets, and every new one fails. Tests your backoff."})]}),be(vl,{value:n.tests.blocked,onValueChange:u=>p({action:"block",blocked:u}),testID:"buoy-socket-block"})]}),n.tests.offline?be(b,{style:ve.warn,children:"Network's offline mode is on, so sockets act offline too."}):null,be(S,{style:ve.row,children:be(Pi,{label:"Reset all",variant:"tertiary",disabled:!C,onPress:()=>p({action:"reset"}),testID:"buoy-socket-reset"})}),l?be(b,{style:[ve.result,l.ok?null:ve.warn],testID:"buoy-socket-result",children:l.message}):null]})}var ve=se.create({content:{padding:12,gap:10,paddingBottom:40},lede:{fontSize:12,color:nt.color.textSecondary},note:{fontSize:12,color:nt.color.textTertiary},chips:{flexDirection:"row",flexWrap:"wrap",gap:6},input:{minHeight:96,padding:10,borderRadius:8,borderWidth:1,borderColor:nt.color.border,backgroundColor:nt.color.surface,color:nt.color.text,fontFamily:Iy,fontSize:12,textAlignVertical:"top"},row:{flexDirection:"row",flexWrap:"wrap",gap:8},grid:{flexDirection:"row",flexWrap:"wrap",gap:8},cell:{flexGrow:1,flexBasis:"45%",padding:9,gap:2,borderRadius:8,borderWidth:1,borderColor:nt.color.border,backgroundColor:nt.color.surface},cellOff:{opacity:.4},cellTitle:{fontSize:12,fontWeight:"700",color:nt.color.text},cellDetail:{fontSize:10.5,color:nt.color.textTertiary},switchRow:{flexDirection:"row",alignItems:"center",gap:10},switchText:{flex:1,gap:2},switchTitle:{fontSize:13,fontWeight:"600",color:nt.color.text},warn:{fontSize:12,color:nt.color.warning,fontWeight:"600"},result:{fontSize:12,color:nt.color.textSecondary}});import{jsx as Bi,jsxs as By}from"react/jsx-runtime";function wl({visible:e,paused:t,isPro:r,onUpgradePress:o,backHandlerRef:n,onTitleChange:i}){let[s,d]=dl(null),[a,l]=dl(null),c=a?"Tricks":s?"Message":"Sockets";xi(()=>{i?.(c)},[i,c]),xi(()=>{if(n)return n.current=a||s?()=>(a?l(null):d(null),true):null,()=>{n.current=null}},[n,a,s]),xi(()=>{e||(d(null),l(null))},[e]);let y=p=>{if(!r)return o();l({socketId:p,data:""})},w=p=>l({socketId:p.socketId,data:p.data??""});return e?By(S,{style:Ly.container,children:[Bi(Cy,{visible:!a&&!s,paused:t,search:"",onOpenFrame:p=>d(p.id),onOpenTricks:y}),Bi(iy,{visible:!a&&!!s,frameId:s,isPro:r,onUpgradePress:o,onEdit:w}),Bi(Ey,{visible:!!a,draft:a,isPro:r,onUpgradePress:o})]}):null}var Ly=se.create({container:{flex:1}});q();he();import{absoluteFill as Sl,night as Ut}from"@buoy-gg/shared-ui/web";import{jsx as At,jsxs as un}from"react/jsx-runtime";function zy({onPress:e,isOpen:t,hasIndicator:r}){return un(W,{onPress:e,"sentry-label":"ignore toggle header menu",testID:"buoy-network-menu",accessibilityRole:"button",accessibilityLabel:t?"Close menu":"More actions",style:[Fe.button,t&&Fe.buttonOpen],children:[un(S,{style:Fe.dots,children:[At(S,{style:[Fe.dot,t&&Fe.dotOpen]}),At(S,{style:[Fe.dot,t&&Fe.dotOpen]}),At(S,{style:[Fe.dot,t&&Fe.dotOpen]})]}),r?At(S,{style:Fe.indicator}):null]})}function Oy({onClose:e,children:t}){return un(S,{style:Fe.overlay,children:[At(W,{style:Fe.backdrop,activeOpacity:1,onPress:e,"sentry-label":"ignore dismiss header menu"}),At(S,{style:Fe.panel,children:t})]})}function ao({icon:e,label:t,detail:r,testID:o,onPress:n}){return un(W,{onPress:n,"sentry-label":"ignore header menu item",testID:o,accessibilityRole:"button",accessibilityLabel:t,style:Fe.item,children:[At(S,{style:Fe.itemIcon,children:e}),At(b,{style:Fe.itemLabel,children:t}),r?At(b,{style:Fe.itemDetail,children:r}):null]})}var Fe=se.create({button:{width:32,height:32,borderRadius:8,alignItems:"center",justifyContent:"center"},buttonOpen:{backgroundColor:Ut.color.surfaceElevated},dots:{flexDirection:"column",gap:2.5,alignItems:"center"},dot:{width:3,height:3,borderRadius:2,backgroundColor:Ut.color.textSecondary},dotOpen:{backgroundColor:Ut.color.text},indicator:{position:"absolute",top:6,right:8,width:6,height:6,borderRadius:3,backgroundColor:Ut.color.accent},overlay:{...Sl,zIndex:50},backdrop:{...Sl,backgroundColor:"rgba(0,0,0,0.5)"},panel:{position:"absolute",top:6,right:8,minWidth:196,paddingVertical:4,borderRadius:10,borderWidth:1,borderColor:Ut.color.border,backgroundColor:Ut.color.surface},item:{flexDirection:"row",alignItems:"center",gap:10,paddingHorizontal:12,paddingVertical:11},itemIcon:{width:16,alignItems:"center"},itemLabel:{flex:1,fontSize:13,fontWeight:"600",color:Ut.color.text},itemDetail:{fontSize:11,color:Ut.color.textTertiary}});q();import{memo as qy,useEffect as Dy,useMemo as Ay}from"react";import{EventStepperFooter as Ny,useLimit as My}from"@buoy-gg/shared-ui/web";import{jsx as $y}from"react/jsx-runtime";var Hy=()=>xt.step(-1),jy=()=>xt.step(1),Fy=qy(function({paused:e,filter:t,ignoredPatterns:r,isPro:o,fromSaved:n,savedSearch:i,applySafeAreaInset:s}){let{visibleEvents:d}=Zr({filter:t,ignoredPatterns:r,paused:e,isPro:o}),{pinnedEvents:a,pinnedLiveIds:l,savedRecords:c}=kr(),y=My("network.saved"),w=Ay(()=>{if(n)return ja(c,y,i).events;let{pinned:u,rest:R}=ci(d,a,l);return u.length===0?R:[...u,...R]},[n,c,i,o,d,a,l]);Dy(()=>{xt.setIds(Gh(w))},[w]);let{index:p,total:C}=Qh();return p<0?null:$y(Ny,{currentIndex:p,totalItems:C,itemLabel:"Request",applySafeAreaInset:s,onPrevious:Hy,onNext:jy,variant:"night"})});q();import{useEffect as Wy,useState as _y}from"react";function Vy(e){return ne.getEvents().find(t=>t.id===e)??me.getEventById(e)}function kl(e,t={}){let{paused:r=false}=t,[o,n]=_y(null);return Wy(()=>{if(!(!e||r))return ne.subscribeToEvents(i=>{let s=i.find(d=>d.id===e);s&&n(d=>d&&d.id===e&&d.event===s?d:{id:e,event:s})})},[e,r]),e?o&&o.id===e?o.event:Vy(e):null}import{Fragment as Uy,jsx as U,jsxs as it}from"react/jsx-runtime";function Jy({visible:e,paused:t,ignoredPatternValues:r,onTogglePattern:o,isPro:n,filter:i,ignoredPatterns:s,fromSaved:d,savedSearch:a,applySafeAreaInset:l}){let c=si(),y=Kh(),w=c!=null&&c===y,p=kl(c,{paused:t||!e});return nr(()=>{e&&p&&w&&xt.reportRendered(p.id)},[e,p,w]),e?it(S,{style:mr.detailRoot,children:[p?U(la,{event:p,ignoredPatterns:r,onTogglePattern:o,showBodies:w}):U(S,{style:mr.detailBodyFallback}),U(Fy,{paused:t,filter:i,ignoredPatterns:s,isPro:n,fromSaved:d,savedSearch:a,applySafeAreaInset:l})]}):null}function Gy({visible:e,paused:t,isPro:r,filter:o,onFilterChange:n,ignoredPatterns:i,onRemovePattern:s,onAddPattern:d,onTogglePatternMode:a,isTeamPattern:l}){let{events:c}=Zr({filter:o,ignoredPatterns:i,paused:t,visible:e,isPro:r});return e?U(zu,{events:c,filter:o,onFilterChange:n,ignoredPatterns:i,onRemovePattern:s,onAddPattern:d,onTogglePatternMode:a,isTeamPattern:l}):null}function Xy({visible:e,paused:t,isPro:r,filter:o,ignoredPatterns:n,settings:i,onSettingsChange:s}){let{events:d}=Zr({filter:o,ignoredPatterns:n,paused:t,visible:e,isPro:r});return e?U(wh,{settings:i,onSettingsChange:s,events:d}):null}function xl({visible:e,onClose:t,onBack:r,onMinimize:o,enableSharedModalDimensions:n=false,inline:i=false,paused:s,onPausedChange:d,remoteConditions:a}){let{isPro:l}=fu(),[c,y]=Be(false),w=s!=null&&d!=null,p=w?s:c,C=ie=>{let st=typeof ie=="function"?ie(p):ie;w?d(st):y(st)},[u,R]=Be({}),h=Xh(),[m,x]=Be(false),[I,B]=Be(false),[E,D]=Be(false),[k,g]=Be(false),[v,f]=Be("Sockets"),[T,M]=Be(false),[P,A]=Be(0),[_]=Be(nu);nr(()=>{_.update(a)},[_,a]),nr(()=>()=>_.update(void 0),[_]);let F=true,[L,H]=Be(null),[j,J]=Be("filters"),[ee,Z]=Be(""),[Y,Oe]=Be(false),Xe=Wr(false),[De,Ce]=Be(""),Ke=Wr(null),{patterns:ut,values:Or,add:co,remove:uo,toggle:qr,toggleMode:ho,isTeamOnly:Dl}=mu(),[Dr,$i]=Be(gh),mn=Wr(false),[bn,vn]=Be(false),[Pt,Al]=Be("export"),br=ie=>{Al(ie),vn(true)};nr(()=>{bn&&l&&vn(false)},[bn,l]),nr(()=>{if(!e||mn.current)return;(async()=>{try{let ie=await Us.getItem(Oo.network.copyOptions());if(ie){let st=JSON.parse(ie);$i(st)}}catch{}finally{mn.current=true}})()},[e]),nr(()=>{if(!mn.current)return;(async()=>{try{await Us.setItem(Oo.network.copyOptions(),JSON.stringify(Dr))}catch{}})()},[Dr]);let Nl=()=>{xt.clear()},Hi=Xn(ie=>{xt.select(ie.id)},[]),Ml=Xn((ie,st)=>{H(st?{...ie,id:st}:ie),D(true),xt.clear()},[]),$l=Xn(()=>H(null),[]),ji=Wr(null),Fi=Wr(null),Wi=ie=>{Z(ie),R(st=>({...st,searchText:ie}))},Hl=ie=>{R(st=>({...st,status:st.status===ie?void 0:ie}))},[_i,jl]=Be("bottomSheet"),Fl=ie=>{jl(ie)};nr(()=>{Y&&requestAnimationFrame(()=>{Ke.current?.focus()})},[Y]);let Vi=()=>m?it(Te,{children:[U(Te.Navigation,{onBack:()=>x(false)}),U(Te.Content,{title:"",noMargin:true,children:U(pu,{size:"sm",tabs:[{key:"filters",label:"Filters"},{key:"copy",label:"Copy"}],activeKey:j,onChange:ie=>J(ie)})})]}):h?it(Te,{children:[U(Te.Navigation,{onBack:Nl}),U(Te.Content,{title:"Request Details",centered:true}),it(Te.Actions,{children:[F?U(rg,{onOpen:Ml}):null,U(za,{isPro:l,onUpgradePress:()=>br("saved")})]})]}):k?it(Te,{children:[U(Te.Navigation,{onBack:()=>{Fi.current?.()||g(false)}}),U(Te.Content,{title:v,centered:true})]}):E&&F?it(Te,{children:[U(Te.Navigation,{onBack:()=>{ji.current?.()||(D(false),H(null))}}),U(Te.Content,{title:"Response Overrides",centered:true})]}):I?it(Te,{children:[U(Te.Navigation,{onBack:()=>B(false)}),U(Te.Content,{title:"Saved Requests",centered:true})]}):it(Te,{children:[r&&U(Te.Navigation,{onBack:r}),U(Te.Content,{title:"",children:Y?U(Te.Search,{value:ee,onChangeText:Wi,onCancel:()=>{Wi(""),Oe(false)},onDismiss:()=>Oe(false),dismissOnBlur:true,clearOnlyWhenText:true,placeholder:"Search URL, method, operation, error...",accessibilityLabel:"Search network requests",iconSize:14,testID:"buoy-network-search-input",clearTestID:"buoy-network-search-clear",inputProps:{"sentry-label":"ignore network search header"}}):U(np,{activeStatus:u.status,onToggleStatus:Hl,ignoredPatterns:ut,paused:p})}),it(Te.Actions,{children:[U(W,{"sentry-label":"ignore open search",testID:"buoy-network-search-open",accessibilityLabel:"Open search",accessibilityRole:"button",onPress:()=>Oe(true),style:mr.headerActionButton,children:U(au,{size:14,color:gt.color.textSecondary})}),U(Xg,{paused:p,onPress:()=>g(true)}),F?U(Zf,{onPress:()=>D(true)}):null,U(yu,{isEnabled:!p,onToggle:()=>C(ie=>!ie),accessibilityLabel:p?"Resume network capture":"Pause network capture",testID:"buoy-network-power"}),U(ip,{paused:p}),U(zy,{onPress:()=>M(ie=>!ie),isOpen:T,hasIndicator:wn})]})]}),wn=!!(u.status||u.method||u.contentType),Wl=n?Oo.modal.root():Oo.network.modal();if(!e)return null;let _l=h||!m,Ui=it(Uy,{children:[it(S,{style:mr.container,children:[U(Jy,{visible:h,paused:p,ignoredPatternValues:Or,onTogglePattern:qr,isPro:l,filter:u,ignoredPatterns:ut,fromSaved:I,savedSearch:De,applySafeAreaInset:!i&&_i==="bottomSheet"}),U(Gy,{visible:m&&j==="filters"&&!h,paused:p,isPro:l,filter:u,onFilterChange:R,ignoredPatterns:ut,onRemovePattern:uo,onAddPattern:co,onTogglePatternMode:ho,isTeamPattern:Dl}),U(Xy,{visible:m&&j==="copy"&&!h,paused:p,isPro:l,filter:u,ignoredPatterns:ut,settings:Dr,onSettingsChange:$i}),U(Xf,{visible:F&&E&&!h&&!m&&!k,isPro:l,onUpgradePress:()=>br("overrides"),pendingDraft:L,onPendingConsumed:$l,backHandlerRef:ji,applySafeAreaInset:!i&&_i==="bottomSheet"}),U(wl,{visible:k&&!h&&!m,paused:p,isPro:l,onUpgradePress:()=>br("sockets"),backHandlerRef:Fi,onTitleChange:f}),U(Fa,{visible:I&&!h&&!m&&!k&&!(E&&F),isPro:l,copySettings:Dr,search:De,onSearchChange:Ce,onEventPress:Hi,onUpgradePress:()=>br("saved")}),U(tf,{visible:!h&&!m&&!I&&!k&&!(E&&F),paused:p,filter:u,ignoredPatterns:ut,isPro:l,searchText:ee,onEventPress:Hi,onUpgradePress:()=>br("export")})]}),T?it(Oy,{onClose:()=>M(false),children:[U(ao,{icon:U(Vs,{size:14,color:gt.color.textSecondary}),label:"Network throttling",testID:"buoy-network-menu-throttling",onPress:()=>{M(false),Ws(a?_:void 0),i||A(ie=>ie+1)}}),U(ao,{icon:U(Vs,{size:14,color:gt.color.textSecondary}),label:"Speed and link state",testID:"buoy-network-menu-conditions",onPress:()=>{M(false),Ws(a?_:void 0,true),i||A(ie=>ie+1)}}),U(ao,{icon:U(lu,{size:14,color:wn?gt.color.accent:gt.color.textSecondary}),label:"Filters",detail:wn?"Active":void 0,onPress:()=>{M(false),J("filters"),x(true)}}),U(ao,{icon:U(du,{size:14,color:gt.color.textSecondary}),label:"Saved requests",onPress:()=>{M(false),B(true)}}),U(ao,{icon:U(cu,{size:14,color:gt.color.textSecondary}),label:"Sockets",testID:"buoy-network-menu-sockets",onPress:()=>{M(false),g(true)}}),U(S,{style:mr.menuCopyRow,children:U(ap,{isPro:l,filter:u,ignoredPatterns:ut,copySettings:Dr,paused:p,onUpgradePress:()=>{M(false),br("export")},label:"Copy requests"})})]}):null,U(gu,{visible:bn,onClose:()=>vn(false),featureName:Pt==="saved"?"Saved Requests":Pt==="overrides"?"Response Overrides":Pt==="sockets"?"Socket Tricks":"Network Export",description:Pt==="saved"?"Keep the requests that matter. Saved requests survive Clear, app restarts, and the 500-request history cap.":Pt==="overrides"?"Force any endpoint to fail, stall or return something else \u2014 no backend changes, no code changes. Free keeps one active rule.":Pt==="sockets"?"Push fake server messages into your app, and drop, freeze or block its sockets. Your app's real code handles each one.":"Export network requests to share with your team, debug APIs, or feed into AI tools.",benefits:Pt==="sockets"?["Push a fake message, like auth.expired, in one tap","Drop a socket with 1006 or kick it out with 1008","Freeze a socket to test your ping check","Block every reconnect to test your backoff"]:Pt==="overrides"?[`Run ${wt} rules at once (free keeps ${Is})`,"Force a 500, a 401 or an empty list in one tap","Simulate offline, timeouts and slow connections","Rules survive an app reload, so you can test the boot path"]:Pt==="saved"?[`Save up to ${Wt} requests (free keeps ${Sa})`,"Failed requests stay put through a Clear","Snapshots survive an app restart","Export saved requests to teammates or AI assistants"]:["Export to JSON, Markdown, or plain text","Customizable copy presets (URLs only, LLM-ready, full data)","Share request details with teammates","Feed network data directly to AI assistants"]})]});return i?it(S,{style:mr.inlineRoot,children:[U(S,{style:mr.inlineHeader,...bu,children:Vi()}),Ui]}):U(uu,{visible:e,onClose:t,onMinimize:o,minimizeRequest:P,persistenceKey:Wl,variant:"night",header:{showToggleButton:true,customContent:Vi()},onModeChange:Fl,enablePersistence:true,initialMode:"bottomSheet",enableGlitchEffects:true,disableScrollWrapper:_l,styles:{},children:Ui})}var mr=se.create({container:{flex:1,backgroundColor:"transparent"},detailRoot:{flex:1,minHeight:0},detailBodyFallback:{flex:1},inlineRoot:{flex:1,minHeight:0,backgroundColor:"transparent"},inlineHeader:{paddingHorizontal:12,paddingVertical:8,borderBottomWidth:1,borderBottomColor:hu.border.default,backgroundColor:"transparent"},menuCopyRow:{paddingHorizontal:6},headerActionButton:{width:32,height:32,borderRadius:8,backgroundColor:gt.color.buttonSurface,borderWidth:1,borderColor:gt.color.border,alignItems:"center",justifyContent:"center"},activeFilterButton:{backgroundColor:gt.color.accentSoft,borderColor:gt.color.accentBorderStrong}});function Cl(e){return U(Yn,{children:U(xl,{...e})})}function Ky(e={}){return U(Yn,{children:U(xl,{...e,inline:true,visible:true,onClose:Qy})})}var Qy=()=>{};import{jsx as Yy}from"react/jsx-runtime";var Tl=typeof navigator<"u"&&navigator.product==="ReactNative";Tl&&G.ensureLoaded();Tl&&typeof we<"u"&&we&&(ne.startBootCapture(),Pe.install());var Rl=Kc({id:"network",name:"NET",description:"Network request logger",slot:"both",icon:({size:e})=>Yy(Gc,{size:e}),component:Cl,props:{enableSharedModalDimensions:false}}),Zy=Xc(Rl,e=>({enableSharedModalDimensions:e.enableSharedModalDimensions??false}));q();function em(){let e=typeof navigator<"u"&&navigator.product==="ReactNative";if(!e&&(typeof window>"u"||typeof document>"u"))return()=>{};G.ensureLoaded(),Pe.install();let t=e?()=>{}:Fs(),r=ne.subscribeToEvents(()=>{}),o=false;return()=>{o||(o=true,t(),r())}}q();import{useState as Li,useEffect as tm,useCallback as hn,useMemo as Nt,useRef as rm}from"react";import{useLimit as om,TIER_LIMITS as nm}from"@buoy-gg/shared-ui/web";var G0=nm["network.requests"].free;function im(e={}){let{isPro:t=false}=e,r=om("network.requests"),o=t?1/0:r,[n,i]=Li([]),[s,d]=Li({}),[a,l]=Li(true),c=rm(null);tm(()=>(a&&(c.current=ne.subscribeToEvents(i)),()=>{c.current&&(c.current(),c.current=null)}),[a]);let y=hn(()=>{ne.clearEvents(),i([])},[]),w=hn(()=>{l(false)},[]),p=hn(()=>{l(true)},[]),C=Nt(()=>s.searchText?s.searchText.toLowerCase():null,[s.searchText]),u=Nt(()=>s.method&&s.method.length>0?new Set(s.method):null,[s.method]),R=Nt(()=>s.contentType&&s.contentType.length>0?new Set(s.contentType):null,[s.contentType]),h=Nt(()=>{let v=[...n];if(u&&(v=v.filter(f=>u.has(f.method))),s.status&&s.status!=="all")switch(s.status){case"success":v=v.filter(f=>f.status&&f.status>=200&&f.status<300);break;case"error":v=v.filter(f=>f.error||f.status&&f.status>=400);break;case"pending":v=v.filter(f=>!f.status&&!f.error);break}return C&&(v=v.filter(f=>f.url.toLowerCase().includes(C)||f.method.toLowerCase().includes(C)||f.path?.toLowerCase().includes(C)||f.host?.toLowerCase().includes(C)||f.error&&f.error.toLowerCase().includes(C)||f.operationName&&f.operationName.toLowerCase().includes(C)||ia(f.graphqlVariables,C))),s.host&&(v=v.filter(f=>f.host===s.host)),R&&(v=v.filter(f=>{let T=f.responseHeaders||f.requestHeaders,M=T?.["content-type"]||T?.["Content-Type"]||"";for(let P of R)switch(P){case"JSON":if(M.includes("json"))return true;break;case"XML":if(M.includes("xml"))return true;break;case"HTML":if(M.includes("html"))return true;break;case"TEXT":if(M.includes("text"))return true;break;case"IMAGE":if(M.includes("image"))return true;break;case"VIDEO":if(M.includes("video"))return true;break;case"AUDIO":if(M.includes("audio"))return true;break;case"FORM":if(M.includes("form"))return true;break;case"OTHER":if(!M||!M.includes("json")&&!M.includes("xml")&&!M.includes("html")&&!M.includes("text")&&!M.includes("image")&&!M.includes("video")&&!M.includes("audio")&&!M.includes("form"))return true;break}return false})),v},[n,s,C,u,R]),m=Nt(()=>{let v=new Set;return n.slice(o).forEach(f=>{v.add(f.id)}),v},[n,o]),x=Nt(()=>h.filter(v=>m.has(v.id)),[h,m]),I=x.length>0,B=x.length,E=hn(v=>m.has(v),[m]),D=Nt(()=>{let v=0,f=0,T=0,M=0,P=0,A=0,_=0;for(let L of n)L.status&&L.status>=200&&L.status<300?v++:L.error||L.status&&L.status>=400?f++:!L.status&&!L.error&&T++,M+=L.requestSize||0,P+=L.responseSize||0,L.duration&&(A+=L.duration,_++);let F=_>0?A/_:0;return{totalRequests:n.length,successfulRequests:v,failedRequests:f,pendingRequests:T,totalDataSent:M,totalDataReceived:P,averageDuration:Math.round(F)}},[n]),k=Nt(()=>{let v=new Set;for(let f of n)f.host&&v.add(f.host);return Array.from(v)},[n]),g=Nt(()=>{let v=new Set;for(let f of n)v.add(f.method);return Array.from(v)},[n]);return{events:h,allEvents:n,stats:D,filter:s,setFilter:d,clearEvents:y,isCapturing:a,pauseCapturing:w,resumeCapturing:p,hosts:k,methods:g,hasLockedEvents:I,lockedEventCount:B,isEventLocked:E,requestLimit:o,getSubscriberCounts:()=>ne.getSubscriberCounts()}}import{useIgnoredPatterns as sm,ignoredPatternsStore as am,urlMatchesIgnoredPattern as lm,isUrlIgnored as dm}from"@buoy-gg/shared-ui/web";q();var cm=300,um=1e3,hm=200,pm=4e3;function Il(e,t){return!e.data||e.data.length<=t?e:{...e,data:e.data.slice(0,t),dataCut:true}}function fm(e,t){if(!e)return false;let r=t.toLowerCase(),o=e.toLowerCase();return r.endsWith("*")?fl(o,r.slice(0,-1)):o.includes(r)}function Pl(e,t={}){let r=new Set(e.problems.flatMap(l=>l.frameIds)),o=e.frames;t.frameId&&(o=o.filter(l=>l.id===t.frameId||l.replyTo===t.frameId||l.replyId===t.frameId)),t.socketId&&(o=o.filter(l=>l.socketId===t.socketId)),!t.includePings&&!t.frameId&&(o=o.filter(l=>!l.ping)),t.type&&(o=o.filter(l=>fm(l.type,t.type))),t.direction==="lifecycle"?o=o.filter(l=>l.kind!=="message"):t.direction&&(o=o.filter(l=>l.direction===t.direction)),t.problems&&(o=o.filter(l=>r.has(l.id))),t.since&&(o=o.filter(l=>l.timestamp>=t.since));let n=o.length,i=typeof t.limit=="number"&&t.limit>=0?Math.min(t.limit,500):50,s=o.slice(0,i).map(l=>t.frameId?l:Il(l,t.includeBodies?pm:hm)),d=t.socketId?e.connections.find(l=>l.id===t.socketId):void 0,a=d?bt(d.url):void 0;return{connections:t.socketId?e.connections.filter(l=>l.id===t.socketId):e.connections,problems:t.socketId?e.problems.filter(l=>l.socketId?l.socketId===t.socketId:!!l.url&&bt(l.url)===a):e.problems,tests:e.tests,capturingSince:e.capturingSince,frames:s,total:n,flagged:[...r]}}function gm(e){if(!e||typeof e!="object")return null;let t=e,r=typeof t.socketId=="string"?t.socketId:"",o=typeof t.data=="string"?t.data:t.data!==void 0?JSON.stringify(t.data):void 0;switch(t.action){case"inject":case"send":return r&&o!==void 0?{action:t.action,socketId:r,data:o}:null;case"close":return r?{action:"close",socketId:r,...typeof t.code=="number"?{code:t.code}:{},...typeof t.reason=="string"?{reason:t.reason}:{}}:null;case"freeze":return r?{action:"freeze",socketId:r,frozen:t.frozen!==false}:null;case"block":return{action:"block",blocked:t.blocked!==false};case"reset":case"clear":return{action:t.action};default:return null}}var ym={version:1,getSnapshot:()=>{let e=Pe.getState();return{...e,frames:e.frames.slice(0,cm).map(t=>Il(t,um))}},subscribe:e=>Pe.subscribeState(e),actions:{getFrame:e=>{let t=e&&typeof e=="object"?e.id:void 0;if(typeof t!="string")return null;let r=Pe.getFrame(t);if(!r)return null;let o=r.replyId??r.replyTo;return{frame:r,partner:o?Pe.getFrame(o)??null:null}},query:e=>Pl(Pe.getState(),e??{}),act:e=>{let t=gm(e);return t?Pe.actLocal(t):{ok:false,message:"Unknown or incomplete action. inject/send need socketId and data; close/freeze need socketId."}}}};q();function mm(e,t){let r={id:`socket-${e.id}`,source:"socket",timestamp:e.timestamp,subtitle:Ti(t),originalEvent:e,correlationId:e.socketId};switch(e.kind){case"open":return{...r,title:"Socket opened",status:"success"};case"error":return{...r,title:"Socket error",status:"error"};case"close":return{...r,title:`Socket ${Ri(e.code,e.neverOpened).toLowerCase()}${e.byBuoy?" (Buoy)":""}`,status:e.code===1e3||e.code===1001?"neutral":"error"};case"message":return e.fake!=="inject"?null:{...r,title:`Buoy pushed ${e.type??"a message"}`,status:"neutral"}}}function bm(e){return Pe.onEvent(t=>{let r=Pe.getState().connections.find(n=>n.id===t.socketId),o=mm(t,r?.url??"");o&&e(o)})}q();import{approxJsonSize as zi,isOverWireBudget as vm}from"@buoy-gg/shared-ui/web";import{expandKeyedArrays as wm,patchFromPath as Sm,refusalText as km,shapeKind as El,suggestedPatch as xm,typedEditViolations as Cm}from"@buoy-gg/shared-ui/web";var Oi=16*1024,pn=1.25*1024*1024;function qi(e,t){return e===void 0?false:(t??0)>Oi?true:vm(e,Oi)}var Bl=new WeakMap,Ll=new WeakMap;function Di(e){let t=Bl.get(e);if(t)return t;let r;try{r=Rm(e)}catch{r=Tm(e)}return Bl.set(e,r),r}function Tm(e){let t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0},r=1024;try{r=zi(t,pn).bytes}catch{}return{event:t,bytes:r}}function Rm(e){let t=qi(e.requestData,e.requestSize),r=qi(e.responseData,e.responseSize),o=zl(e.graphqlVariables),n=Ol(e.requestHeaders),i=Ol(e.responseHeaders),s=t||r||o!==e.graphqlVariables||n!==e.requestHeaders||i!==e.responseHeaders,d=e;return s&&(d={...e},t&&(d.requestData=void 0,d.requestBodyOmitted=true),r&&(d.responseData=void 0,d.responseBodyOmitted=true),o!==e.graphqlVariables&&(d.graphqlVariables=o),n!==e.requestHeaders&&(d.requestHeaders=n,d.headersOmitted=true),i!==e.responseHeaders&&(d.responseHeaders=i,d.headersOmitted=true)),{event:d,bytes:zi(d,pn).bytes}}function Im(e){let t=Ll.get(e);if(t)return t;let{event:r}=Di(e),o={...r};o.requestData!==void 0&&(o.requestData=void 0,o.requestBodyOmitted=true),o.responseData!==void 0&&(o.responseData=void 0,o.responseBodyOmitted=true),o.graphqlVariables!==void 0&&(o.graphqlVariables=zl(o.graphqlVariables,true));let n={event:o,bytes:zi(o,pn).bytes};return Ll.set(e,n),n}function Pm(e){let t=new Array(e.length),r=0;for(let o=0;o<e.length;o++){let n=Di(e[o]);if(r+n.bytes<=pn)t[o]=n.event,r+=n.bytes;else{let i=Im(e[o]);t[o]=i.event,r+=i.bytes}}return t}function zl(e,t=false){if(!e||!t&&!qi(e,void 0))return e;let r={};for(let[o,n]of Object.entries(e))(typeof n=="string"&&n.length<=64||typeof n=="number"||typeof n=="boolean")&&(r[o]=n);return Object.keys(r).length>0?r:void 0}var Ai=64;function Ol(e){if(!e)return e;let t=false,r={};for(let[o,n]of Object.entries(e))typeof n=="string"&&(n.length<=Ai?r[o]=n:(r[o]=`${n.slice(0,Ai)}\u2026 [${n.length-Ai} more]`,t=true));return t?r:e}var Em=e=>{let t=false,r=e.rules.map(o=>!o.body||o.body.length<=Oi?o:(t=true,{...o,body:void 0,bodyOmitted:true}));return t?{...e,rules:r}:e},fn=e=>ne.getEventById(e)??me.getEventById(e),zr=e=>e&&typeof e=="object"?e.id:void 0,gn=(e,t)=>!!(e&&typeof e=="object"&&e[t]),yn=()=>Cc()?{}:{active:false,inactiveReason:Tc},Bm=["respond","fail","delay"];function Lm(e,t){if(!e||typeof e!="object")return null;let r=e.rule??e;if(!r||typeof r!="object")return null;let o=r,n=typeof o.urlPattern=="string"&&o.urlPattern.trim()?o.urlPattern.trim():t?.urlPattern??"";if(!n)return null;let i=Bm.includes(o.kind)?o.kind:t?.kind??"respond";return{id:typeof o.id=="string"?o.id:void 0,enabled:o.enabled!==false,name:typeof o.name=="string"?o.name:t?.name,urlPattern:n,methods:Array.isArray(o.methods)?o.methods.filter(s=>typeof s=="string").map(s=>s.toUpperCase()):t?.methods,requireHeader:typeof o.requireHeader=="string"&&o.requireHeader.trim()?o.requireHeader.trim():void 0,bodyIncludes:typeof o.bodyIncludes=="string"&&o.bodyIncludes?o.bodyIncludes.slice(0,4096):t?.bodyIncludes,graphqlOperation:typeof o.graphqlOperation=="string"&&o.graphqlOperation?o.graphqlOperation.slice(0,200):t?.graphqlOperation,graphqlVariables:typeof o.graphqlVariables=="string"?o.graphqlVariables.slice(0,4096):t?.graphqlVariables,bodyJson:typeof o.bodyJson=="string"&&o.bodyJson.length<=4096?o.bodyJson:t?.bodyJson,graphqlSingle:o.graphqlSingle===true?true:t?.graphqlSingle,sandbox:o.sandbox===true?true:void 0,kind:i,status:typeof o.status=="number"?o.status:t?.status,statusText:typeof o.statusText=="string"?o.statusText:t?.statusText,headers:o.headers&&typeof o.headers=="object"?o.headers:t?.headers,body:Om(o,t),failKind:o.failKind==="timeout"?"timeout":void 0,delayMs:typeof o.delayMs=="number"?o.delayMs:void 0,times:typeof o.times=="number"?o.times:null,alternate:o.alternate===true}}var Ni=e=>!!e&&typeof e=="object"&&!Array.isArray(e),lo=e=>Ni(e)||Array.isArray(e);function ql(e,t,r="",o={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t))return t.length>0&&t.length<e.length&&o.shrunk.push({path:r||"(root)",have:e.length,sent:t.length}),t;if(!Ni(e)||!Ni(t))return t;let n={...e};for(let[i,s]of Object.entries(t)){let d=r?`${r}.${i}`:i;if(i in e){let a=El(e[i]),l=El(s);(a==="array"||a==="object")&&a!==l&&o.breaks.push({path:d,from:a,to:l}),n[i]=ql(e[i],s,d,o)}else n[i]=s}return n}function zm(e,t){if(e.body!=null||!lo(e.bodyPatch)||typeof t!="string")return[];try{return Cm(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function Om(e,t){if(typeof e.body=="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);let r=t?.body??(lo(e.bodyPatch)&&typeof e.id=="string"?G.getState().rules.find(o=>o.id===e.id)?.body:void 0);if(lo(e.bodyPatch)&&typeof r=="string")try{return JSON.stringify(ql(JSON.parse(r),e.bodyPatch),null,2)}catch{return r}return r}function qm(e){if(!e||typeof e!="object")return null;let t=e.rule??e;if(!t||typeof t!="object")return null;let r=t.id;if(typeof r!="string")return null;let o=G.getState().rules.find(n=>n.id===r);return o?{...o}:null}function Dm(e){if(!e||typeof e!="object")return null;let t=e.rule??e;if(!t||typeof t!="object")return null;let r=t;if(r.bodyOmitted!==true||typeof r.id!="string")return null;let o=G.getState().rules.find(n=>n.id===r.id);return o?{body:o.body}:null}function Am(e){if(!e||typeof e!="object")return null;let t=e.fromRequestId;if(typeof t!="string"||!t)return null;let r=fn(t);return r?bi(r):null}var Nm={dispose:()=>{G.setEnabled(false)},version:6,getSnapshot:()=>(ne.ensureInterception(),{conditions:rr(),events:Pm(ne.getEvents()),overrides:Em(G.getState()),saved:me.getRecords().map(e=>({...e,event:Di(e.event).event}))}),subscribe:e=>{let t=ne.subscribeToEvents(e),r=ft(e),o=me.subscribe(e),n=G.subscribe(e);return()=>{r(),t(),o(),n()}},actions:{getNetworkConditions:rr,setNetworkConditions:To,clearEvents:()=>{ne.clearEvents()},getEventBody:e=>{let t=zr(e);if(!t)return null;let r=fn(t);return r?{url:r.url??null,method:r.method??null,status:r.status??null,override:r.override??null,condition:r.condition??null,requestData:r.requestData??null,responseData:r.responseData??null,requestHeaders:r.requestHeaders??null,responseHeaders:r.responseHeaders??null}:null},setPinned:e=>{let t=zr(e);if(!t)return null;let r=fn(t);if(!r)return null;let o=gn(e,"pinned");return Ho(me.getState(),t).pinned===o?{ok:true}:me.togglePin(r)},setSaved:e=>{let t=zr(e);if(!t)return null;let r=fn(t);if(!r)return null;let o=gn(e,"saved");return Ho(me.getState(),t).saved===o?{ok:true}:me.toggleSave(r)},removeSavedRecord:e=>{let t=e&&typeof e=="object"?e.key:void 0;return t?(me.remove(t),{ok:true}):null},clearSavedRequests:()=>(me.clearSaved(),{ok:true}),clearPinnedRequests:()=>(me.clearPinned(),{ok:true}),setOverridesEnabled:e=>(G.setEnabled(gn(e,"enabled")),{ok:true,enabled:G.getState().enabled,...yn()}),upsertOverrideRule:e=>{let t=e?.rule??e,r=!!t&&t.body==null&&(lo(t.bodyPatch)||typeof t.bodyPath=="string"),o=Am(e)??Dm(e)??(r?qm(e):null);if(t&&typeof t.bodyPath=="string"&&t.body==null){let s=o?.body??(typeof t.id=="string"?G.getState().rules.find(l=>l.id===t.id)?.body:void 0);if(typeof s!="string")return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."};if(t.bodyValue===void 0)return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${t.bodyPath}" to.`};let d;try{d=JSON.parse(s)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}let a=Sm(d,t.bodyPath,t.bodyValue);if(!a.ok)return{ok:false,error:`Refused: ${a.error}`};t.bodyPatch=a.patch,delete t.bodyPath,delete t.bodyValue}if(t&&lo(t.bodyPatch)&&t.body==null){let s=o?.body??(typeof t.id=="string"?G.getState().rules.find(a=>a.id===t.id)?.body:void 0);if(typeof s!="string")return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."};let d;try{let a=wm(JSON.parse(s),t.bodyPatch);d=a.error,a.notes.length&&(t.bodyPatch=a.patch)}catch{}if(d)return{ok:false,error:`Refused: ${d}`};if(t.force!==true){let a=zm(t,s);if(a.length>0)return{ok:false,error:km(a,"response body",xm(t.bodyPatch,a)),violations:a}}}let n=Lm(e,o);if(!n){let s=e?.fromRequestId;return{ok:false,error:s?`No captured request \`${s}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}let i=G.upsertRule(n);return i?(i.enabled&&G.setEnabled(true),{ok:true,rule:{id:i.id,urlPattern:i.urlPattern,enabled:i.enabled,kind:i.kind,status:i.status,times:i.times,bodySize:i.body?i.body.length:0},...i.times===void 0||i.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${i.id}\`). If you meant only the next one, set times:1.`}:{},...yn()}):{ok:false,error:"Override rule limit reached."}},setOverrideRuleEnabled:e=>{let t=zr(e);return t?(G.setRuleEnabled(t,gn(e,"enabled")),{ok:true,...yn()}):{ok:false,error:"Missing rule id."}},deleteOverrideRule:e=>{let t=zr(e);return t?(G.removeRule(t),{ok:true}):{ok:false,error:"Missing rule id."}},clearOverrideRules:()=>(G.clearRules(),{ok:true}),replaceOverrideRules:async e=>{let t=e??{};if(!Array.isArray(t.rules))return{ok:false,error:"replaceOverrideRules needs `rules`: an array of rules, first match first."};if(t.rules.length>wt)return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${wt}.`};await G.ensureLoaded();let r=G.replaceAllRules(t.rules,t.enabled!==false);if(!r)return{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."};let o=await G.saveChecked();return{ok:true,count:r.length,enabled:G.getState().enabled,saved:o,...yn()}},listOverrideRules:async()=>(await G.ensureLoaded(),G.getState()),getOverrideRuleBody:e=>{let t=zr(e);if(!t)return null;let r=G.getState().rules.find(o=>o.id===t);return r?{body:r.body??null}:null},getCaptureStatus:()=>{let e=ne.getSubscriberCounts().total,t=null,r=null;try{t=As(),r=er()}catch{}let o=null;try{o=jc()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:o,listenerCount:r,eventCount:ne.getEvents().length}},debugOverrides:e=>{let{url:t,method:r}=e&&typeof e=="object"?e:{},o=typeof t=="string"?t:"https://example.com/",n=typeof r=="string"&&r.trim()?r.trim().toUpperCase():"GET";return{tested:{url:o,method:n},interceptorInstalled:As(),listenerCount:er(),engine:Rc(o,n),store:{enabled:G.getState().enabled,autoPaused:G.getState().autoPaused,ruleCount:G.getState().rules.length,rulesVisibleToEngine:G.getRules().length}}}}};q();var Mm=new Set(["content-length","host","connection","accept-encoding"]);function Mi(e){return`'${e.replace(/'/g,"'\\''")}'`}function $m(e){if(e==null)return null;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return null}}function Hm(e){let t=(e.method||"GET").toUpperCase(),r=$m(e.requestData),o=[];t!=="GET"&&!(t==="POST"&&r!==null)&&o.push(`-X ${t}`);for(let[i,s]of Object.entries(e.requestHeaders||{}))Mm.has(i.toLowerCase())||o.push(`-H ${Mi(`${i}: ${s}`)}`);r!==null&&o.push(`--data-raw ${Mi(r)}`);let n=`curl ${Mi(e.url)}`;return o.length===0?n:`${n} \\
145
145
  ${o.join(` \\
146
- `)}`}O();function Tf(e,t){return e?!t||t.runtimeId!==e.runtimeId||t.revision<e.revision?e:t:null}export{vc as DEFAULT_SETTLE_MS,Ti as FREE_TIER_OVERRIDE_LIMIT,vs as FREE_TIER_SAVED_LIMIT,Ze as MAX_OVERRIDE_RULES,eo as MAX_PINNED,vt as MAX_SAVED,mt as NETWORK_CONDITIONS,Cu as NetworkBodyResolverProvider,Ls as NetworkDetailPinActions,ss as NetworkEventDetailView,er as NetworkEventItemCompact,Ps as NetworkHeaderBadgesView,ea as NetworkModal,Oc as NetworkSavedButton,Ms as NetworkSavedScreen,jp as NetworkToolView,hr as OVERRIDE_STATUS_MAX,cr as OVERRIDE_STATUS_MIN,cn as TickProvider,fr as addNetworkListener,Tf as chooseConditionsSnapshot,Up as createNetworkTool,Ln as draftFromEvent,to as flagsForEventId,ct as formatBytes,Zr as formatDuration,ts as formatHttpStatus,kf as generateCurl,Lt as getConditionsRevision,Ot as getNetworkCondition,Bt as getNetworkConditions,vd as getNetworkConnection,Qp as ignoredPatternsStore,tf as isUrlIgnored,en as networkConditionsActive,te as networkEventStore,Mr as networkListener,fe as networkSavedStore,nt as networkSelectionStore,wf as networkSyncAdapter,ra as networkToolPreset,_ as overrideRulesStore,yd as removeAllNetworkListeners,jr as setNetworkCondition,Nr as setNetworkConditions,xn as splitPinned,_p as startNetworkCapture,et as subscribeNetworkConditions,ef as urlMatchesIgnoredPattern,Zp as useIgnoredPatterns,Zs as useLiveNetworkEvent,Rs as useNetworkBadgeCounts,kr as useNetworkEventList,Yp as useNetworkEvents,Zt as useNetworkSaved,hn as useTickEveryMinute};
146
+ `)}`}q();function jm(e,t){return e?!t||t.runtimeId!==e.runtimeId||t.revision<e.revision?e:t:null}export{Uh as DEFAULT_SETTLE_MS,Is as FREE_TIER_OVERRIDE_LIMIT,Sa as FREE_TIER_SAVED_LIMIT,wt as MAX_OVERRIDE_RULES,$o as MAX_PINNED,Wt as MAX_SAVED,$t as NETWORK_CONDITIONS,Ku as NetworkBodyResolverProvider,za as NetworkDetailPinActions,la as NetworkEventDetailView,Cr as NetworkEventItemCompact,La as NetworkHeaderBadgesView,Cl as NetworkModal,sp as NetworkSavedButton,Fa as NetworkSavedScreen,wl as NetworkSocketsScreen,Ky as NetworkToolView,Hr as OVERRIDE_STATUS_MAX,$r as OVERRIDE_STATUS_MIN,Yn as TickProvider,Fr as addNetworkListener,jm as chooseConditionsSnapshot,Zy as createNetworkTool,bi as draftFromEvent,Ho as flagsForEventId,Ot as formatBytes,No as formatDuration,oa as formatHttpStatus,Hm as generateCurl,tr as getConditionsRevision,jt as getNetworkCondition,rr as getNetworkConditions,_c as getNetworkConnection,am as ignoredPatternsStore,dm as isUrlIgnored,Fn as networkConditionsActive,ne as networkEventStore,Co as networkListener,me as networkSavedStore,xt as networkSelectionStore,Nm as networkSyncAdapter,Rl as networkToolPreset,bm as onSocketMoment,G as overrideRulesStore,Pl as querySockets,Hc as removeAllNetworkListeners,Po as setNetworkCondition,To as setNetworkConditions,Pe as socketStore,ym as socketsSyncAdapter,ci as splitPinned,em as startNetworkCapture,ft as subscribeNetworkConditions,lm as urlMatchesIgnoredPattern,sm as useIgnoredPatterns,kl as useLiveNetworkEvent,Pa as useNetworkBadgeCounts,Zr as useNetworkEventList,im as useNetworkEvents,kr as useNetworkSaved,an as useSocketsState,Zn as useTickEveryMinute};