@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
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.overrideRulesStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _networkListener=require("../utils/networkListener");var _engine=require("./engine");var _resolveOverride=require("./resolveOverride");var _types=require("./types");var _realNow=require("../utils/realNow");const REMOTE_ECHO_GRACE_MS=800;const MAX_UNTOUCHED_LAUNCHES=3;function countedThisTab(){const r=`${_sharedUi.devToolsStorageKeys.network.overrides()}_launch`;try{const t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(r))return true;t.setItem(r,"1")}catch{}return false}const EMPTY_RULES=Object.freeze([]);const HIT_EMIT_COALESCE_MS=250;const VALID_KINDS=["respond","fail","delay"];function parseRules(r){if(!Array.isArray(r))return[];const t=[];for(const s of r){if(!s||typeof s!=="object")continue;const e=s;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const i=VALID_KINDS.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(n=>typeof n==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,bodyIncludes:typeof e.bodyIncludes==="string"&&e.bodyIncludes?e.bodyIncludes:void 0,graphqlOperation:typeof e.graphqlOperation==="string"&&e.graphqlOperation?e.graphqlOperation:void 0,graphqlVariables:typeof e.graphqlVariables==="string"?e.graphqlVariables:void 0,sandbox:e.sandbox===true?true:void 0,kind:i,status:typeof e.status==="number"?Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,_types.MAX_RULES)}class OverrideRulesStore{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,s=false){if(!this.remote)return;if(!s&&(0,_realNow.realNow)()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=(0,_realNow.realNow)()+REMOTE_ECHO_GRACE_MS}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}getState(){return this.state}getRules(){if(this.engineDisabled)return EMPTY_RULES;if(!this.enabled)return this.sandboxOnly();return this.rules}sandboxCache=null;sandboxOnly(){if(this.sandboxCache?.from!==this.rules){const t=this.rules.filter(s=>s.sandbox===true);this.sandboxCache={from:this.rules,rules:t.length?t:EMPTY_RULES}}return this.sandboxCache.rules}async fetchRuleBody(t){const s=this.rules.find(e=>e.id===t);if(!s)return null;if(!s.bodyOmitted)return s.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){return(this.enabled?this.rules:this.sandboxOnly()).filter(t=>t.enabled&&!(0,_resolveOverride.isSpent)(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=_types.MAX_RULES)return null;const s={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([s,...this.rules]);return s}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:s,...e}=t;if(s&&this.rules.some(i=>i.id===s)){this.updateRule(s,e);return this.rules.find(i=>i.id===s)??null}return this.addRule(e)}replaceAllRules(t,s){if(this.remote)return null;this.markTouched();const e=t.map(i=>i&&typeof i==="object"&&typeof i.id==="string"?i:{...i,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});this.enabled=s;this.commit(parseRules(e));return this.rules.slice()}updateRule(t,s){const e=this.rules.findIndex(n=>n.id===t);if(e===-1)return;const i=[...this.rules];i[e]={...i[e],...s,hits:0,seen:0};this.commit(i)}setRuleEnabled(t,s){const e=this.rules.findIndex(n=>n.id===t);if(e===-1||this.rules[e].enabled===s)return;this.remote?.setRuleEnabled(t,s);this.markLocalEdit();this.markTouched();const i=[...this.rules];i[e]={...i[e],enabled:s,hits:s?0:i[e].hits,seen:s?0:i[e].seen};this.commit(i)}removeRule(t){const s=this.rules.filter(e=>e.id!==t);if(s.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(s)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const s=this.rules.findIndex(i=>i.id===t);if(s===-1)return;const e=[...this.rules];e[s]={...e[s],seen:e[s].seen+1};this.rules=e;this.rebuild()}recordHit(t){const s=this.rules.findIndex(l=>l.id===t);if(s===-1)return;const e=this.rules[s];const i=e.hits+1;const n=typeof e.times==="number"&&i>=e.times;const a=[...this.rules];a[s]={...e,hits:i,enabled:n?false:e.enabled};if(n){this.commit(a);return}this.rules=a;this.rebuild();this.scheduleHitEmit()}isLoaded(){return!!this.remote||this.loaded}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{let t=null;try{t=await _sharedUi.persistentStorage.getItem(_sharedUi.devToolsStorageKeys.network.overrides())}catch{}this.hydrate(t)})();return this.loadPromise}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let t;try{t=globalThis.localStorage?.getItem(_sharedUi.devToolsStorageKeys.network.overrides())??null}catch{return}if(t===null)return;this.hydrate(t)}hydrate(t){try{if(t&&!this.dirty){const s=JSON.parse(t);this.enabled=s?.enabled!==false;this.rules=parseRules(s?.rules);this.launchStreak=typeof s?.launchStreak==="number"?s.launchStreak:0;this.autoPaused=s?.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(t=>t.enabled&&t.sandbox)){this.launchStreak=0;return}if(countedThisTab())return;this.launchStreak+=1;if(this.launchStreak>=MAX_UNTOUCHED_LAUNCHES){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&this.activeCount()>0;if(t&&!this.keepAlive){(0,_networkListener.startNetworkListener)();this.keepAlive=(0,_networkListener.addNetworkListener)(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},HIT_EMIT_COALESCE_MS)}commit(t){this.dirty=true;this.rules=t.slice(0,_types.MAX_RULES);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(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persist(){if(this.remote)return;_sharedUi.persistentStorage.setItem(_sharedUi.devToolsStorageKeys.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})).catch(()=>{})}emit(){this.listeners.forEach(t=>t())}}const overrideRulesStore=exports.overrideRulesStore=new OverrideRulesStore;(0,_engine.setOverrideHooks)({getRules:()=>overrideRulesStore.getRules(),ready:()=>overrideRulesStore.ensureLoaded(),isReady:()=>overrideRulesStore.isLoaded(),recordHit:r=>overrideRulesStore.recordHit(r),recordMatch:r=>overrideRulesStore.recordMatch(r)});if(typeof window!=="undefined"&&typeof document!=="undefined"&&!(typeof navigator!=="undefined"&&navigator.product==="ReactNative")){overrideRulesStore.loadNow()}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.overrideRulesStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _networkListener=require("../utils/networkListener");var _engine=require("./engine");var _resolveOverride=require("./resolveOverride");var _types=require("./types");var _realNow=require("../utils/realNow");const REMOTE_ECHO_GRACE_MS=800;const MAX_UNTOUCHED_LAUNCHES=3;function countedThisTab(){const i=`${_sharedUi.devToolsStorageKeys.network.overrides()}_launch`;try{const t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(i))return true;t.setItem(i,"1")}catch{}return false}const EMPTY_RULES=Object.freeze([]);const caseRecordKey=()=>`${_sharedUi.devToolsStorageKeys.base}_bug_links_loaded`;function browserStorage(){if(typeof navigator!=="undefined"&&navigator.product==="ReactNative")return null;try{return globalThis.localStorage??null}catch{return null}}let lastRecord={raw:null,blocks:false};function caseRecordBlocks(){let i;try{i=browserStorage()?.getItem(caseRecordKey())??null}catch{return false}if(i===lastRecord.raw)return lastRecord.blocks;lastRecord={raw:i,blocks:parseRecordBlocks(i)};return lastRecord.blocks}function parseRecordBlocks(i){try{if(!i)return false;const t=JSON.parse(i);if(t.block===void 0)return t.options?.replay!==false&&t.report?.replay?.active===true;return t.block===true}catch{return true}}const SAVE_CHECK_MS=5e3;const OTHER_TAB_BLOCK=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"})]);const HIT_EMIT_COALESCE_MS=250;const VALID_KINDS=["respond","fail","delay"];function parseRules(i){if(!Array.isArray(i))return[];const t=[];for(const s of i){if(!s||typeof s!=="object")continue;const e=s;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const r=VALID_KINDS.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(n=>typeof n==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,bodyIncludes:typeof e.bodyIncludes==="string"&&e.bodyIncludes?e.bodyIncludes:void 0,graphqlOperation:typeof e.graphqlOperation==="string"&&e.graphqlOperation?e.graphqlOperation:void 0,graphqlVariables:typeof e.graphqlVariables==="string"?e.graphqlVariables:void 0,bodyJson:typeof e.bodyJson==="string"?e.bodyJson:void 0,graphqlSingle:e.graphqlSingle===true?true:void 0,sandbox:e.sandbox===true?true:void 0,kind:r,status:typeof e.status==="number"?Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,_types.MAX_RULES)}class OverrideRulesStore{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,s=false){if(!this.remote)return;if(!s&&(0,_realNow.realNow)()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=(0,_realNow.realNow)()+REMOTE_ECHO_GRACE_MS}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}getState(){return this.state}getRules(){if(this.engineDisabled)return EMPTY_RULES;if(this.otherTabCase())return OTHER_TAB_BLOCK;if(!this.enabled)return this.sandboxOnly();return this.rules}otherTabCase(){if(this.remote||this.sandboxOnly().length)return false;if(!browserStorage())return false;return caseRecordBlocks()}caseLockChanged(){this.syncKeepAlive();this.emit()}sandboxCache=null;sandboxOnly(){if(this.sandboxCache?.from!==this.rules){const t=this.rules.filter(s=>s.sandbox===true);this.sandboxCache={from:this.rules,rules:t.length?t:EMPTY_RULES}}return this.sandboxCache.rules}async fetchRuleBody(t){const s=this.rules.find(e=>e.id===t);if(!s)return null;if(!s.bodyOmitted)return s.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){return(this.enabled?this.rules:this.sandboxOnly()).filter(t=>t.enabled&&!(0,_resolveOverride.isSpent)(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=_types.MAX_RULES)return null;const s={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([s,...this.rules]);return s}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:s,...e}=t;if(s&&this.rules.some(r=>r.id===s)){this.updateRule(s,e);return this.rules.find(r=>r.id===s)??null}return this.addRule(e)}replaceAllRules(t,s){if(this.remote)return null;this.markTouched();const e=t.map(r=>r&&typeof r==="object"&&typeof r.id==="string"?r:{...r,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});this.enabled=s;this.commit(parseRules(e));return this.rules.slice()}updateRule(t,s){const e=this.rules.findIndex(n=>n.id===t);if(e===-1)return;const r=[...this.rules];r[e]={...r[e],...s,hits:0,seen:0};this.commit(r)}setRuleEnabled(t,s){const e=this.rules.findIndex(n=>n.id===t);if(e===-1||this.rules[e].enabled===s)return;this.remote?.setRuleEnabled(t,s);this.markLocalEdit();this.markTouched();const r=[...this.rules];r[e]={...r[e],enabled:s,hits:s?0:r[e].hits,seen:s?0:r[e].seen};this.commit(r)}removeRule(t){const s=this.rules.filter(e=>e.id!==t);if(s.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(s)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const s=this.rules.findIndex(r=>r.id===t);if(s===-1)return;const e=[...this.rules];e[s]={...e[s],seen:e[s].seen+1};this.rules=e;this.rebuild()}recordHit(t){const s=this.rules.findIndex(o=>o.id===t);if(s===-1)return;const e=this.rules[s];const r=e.hits+1;const n=typeof e.times==="number"&&r>=e.times;const a=[...this.rules];a[s]={...e,hits:r,enabled:n?false:e.enabled};if(n){this.commit(a);return}this.rules=a;this.rebuild();this.scheduleHitEmit()}isLoaded(){return!!this.remote||this.loaded}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{let t=null;try{t=await _sharedUi.persistentStorage.getItem(_sharedUi.devToolsStorageKeys.network.overrides())}catch{}this.hydrate(t)})();return this.loadPromise}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let t;try{t=globalThis.localStorage?.getItem(_sharedUi.devToolsStorageKeys.network.overrides())??null}catch{return}if(t===null)return;this.hydrate(t)}hydrate(t){try{if(t&&!this.dirty){const s=JSON.parse(t);this.enabled=s?.enabled!==false;this.rules=parseRules(s?.rules);this.launchStreak=typeof s?.launchStreak==="number"?s.launchStreak:0;this.autoPaused=s?.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(t=>t.enabled&&t.sandbox)){this.launchStreak=0;return}if(countedThisTab())return;this.launchStreak+=1;if(this.launchStreak>=MAX_UNTOUCHED_LAUNCHES){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&(this.activeCount()>0||this.otherTabCase());if(t&&!this.keepAlive){(0,_networkListener.startNetworkListener)();this.keepAlive=(0,_networkListener.addNetworkListener)(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},HIT_EMIT_COALESCE_MS)}commit(t){this.dirty=true;this.rules=t.slice(0,_types.MAX_RULES);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(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persisted(){return JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})}writes=Promise.resolve();persist(){if(this.remote)return;const t=this.persisted();this.writes=this.writes.then(()=>_sharedUi.persistentStorage.setItem(_sharedUi.devToolsStorageKeys.network.overrides(),t)).catch(()=>{})}async saveChecked(){if(this.remote)return false;const t=this.persisted();const s=this.writes.then(()=>(0,_sharedUi.setItemChecked)(_sharedUi.devToolsStorageKeys.network.overrides(),t));this.writes=s.catch(()=>{});let e;const r=new Promise(n=>{e=setTimeout(()=>n(false),SAVE_CHECK_MS)});return Promise.race([s.catch(()=>false),r]).finally(()=>clearTimeout(e))}emit(){this.listeners.forEach(t=>t())}}const overrideRulesStore=exports.overrideRulesStore=new OverrideRulesStore;(0,_engine.setOverrideHooks)({getRules:()=>overrideRulesStore.getRules(),ready:()=>overrideRulesStore.ensureLoaded(),isReady:()=>overrideRulesStore.isLoaded(),recordHit:i=>overrideRulesStore.recordHit(i),recordMatch:i=>overrideRulesStore.recordMatch(i)});if(typeof window!=="undefined"&&typeof document!=="undefined"&&!(typeof navigator!=="undefined"&&navigator.product==="ReactNative")){overrideRulesStore.loadNow();overrideRulesStore.caseLockChanged();window.addEventListener?.("storage",i=>{if(i.key===null||i.key===caseRecordKey())overrideRulesStore.caseLockChanged()})}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.STORM_WINDOW_MS=exports.STORM_OPENS=exports.SIGNED_IN_MS=exports.REPLY_TIMEOUT_MS=exports.CANT_CONNECT_TRIES=exports.AUTH_WINDOW_MS=exports.AUTH_FAILURES=void 0;exports.answeredTypes=answeredTypes;exports.findProblems=findProblems;var _readMessage=require("./readMessage");const REPLY_TIMEOUT_MS=exports.REPLY_TIMEOUT_MS=1e4;const STORM_OPENS=exports.STORM_OPENS=3;const STORM_WINDOW_MS=exports.STORM_WINDOW_MS=15e3;const CANT_CONNECT_TRIES=exports.CANT_CONNECT_TRIES=3;const AUTH_FAILURES=exports.AUTH_FAILURES=3;const AUTH_WINDOW_MS=exports.AUTH_WINDOW_MS=12e4;const SIGNED_IN_MS=exports.SIGNED_IN_MS=3e4;const CLOSE_POLICY=1008;const AUTH_FAIL_TYPE=/(^|[._:-])(auth[._:-]?(expired|fail(ed|ure)?|error|invalid|rejected)|unauthori[sz]ed|token[._:-]?expired)$/i;function answeredTypes(i,f){const u=new Map(i.map(c=>[c.id,c]));const r=new Map;for(const c of i){if(!c.replyTo)continue;const d=u.get(c.replyTo);const a=f.get(c.socketId);if(!d?.type||!a)continue;const l=(0,_readMessage.socketKey)(a.url);let p=r.get(l);if(!p)r.set(l,p=new Set);p.add(d.type)}return r}function burst(i,f,u){const r=[...i].sort((a,l)=>a.at-l.at);let c=0;let d=null;for(let a=0;a<r.length;a++){while(r[a].at-r[c].at>u)c++;const l=a-c+1;if(l>f&&l>(d?.length??0))d=r.slice(c,a+1)}return d}const plural=(i,f)=>`${i} ${f}${i===1?"":"s"}`;function findProblems(i,f,u,r){const c=[];const d=new Map(f.map(e=>[e.id,e]));const a=answeredTypes(i,d);if(r){for(const[e,t]of r){const o=a.get(e)??new Set;t.forEach(n=>o.add(n));a.set(e,o)}}const l=new Map;for(const e of i){if(e.kind==="message"&&e.direction==="in"&&e.held){l.set(e.socketId,[...l.get(e.socketId)??[],e.timestamp])}}for(const e of i){if(e.kind!=="message"||e.direction!=="out"||e.held||e.ping)continue;if(e.sentWhileClosed)continue;if(!e.type||!e.correlationId||e.replyId)continue;const t=d.get(e.socketId);if(!t||!a.get((0,_readMessage.socketKey)(t.url))?.has(e.type))continue;if(t.frozen||l.get(e.socketId)?.some(n=>n>=e.timestamp))continue;const o=t.closedAt!==void 0&&t.closedAt>=e.timestamp?t.closedAt:u;if(o-e.timestamp<REPLY_TIMEOUT_MS)continue;c.push({kind:"no-reply",message:`${e.type} got no reply after ${REPLY_TIMEOUT_MS/1e3}s`,socketId:e.socketId,url:t.url,frameIds:[e.id],at:e.timestamp})}const p=new Map;for(const e of[...f].sort((t,o)=>t.createdAt-o.createdAt)){const t=(0,_readMessage.socketKey)(e.url);p.set(t,[...p.get(t)??[],e])}const S=new Set;for(const e of p.values()){for(let t=1;t<e.length;t++){const o=e[t-1];if(o.closedByBuoy&&o.closedAt!==void 0&&e[t].createdAt>=o.closedAt)S.add(e[t].id)}}const g=new Map;const _=new Map;for(const e of i){const t=d.get(e.socketId);if(!t)continue;const o=(0,_readMessage.socketKey)(t.url);if(e.kind==="open"&&!S.has(t.id)){g.set(o,[...g.get(o)??[],{at:e.timestamp,id:e.id}])}const n=e.kind==="close"&&e.code===CLOSE_POLICY&&!e.byBuoy;const s=e.kind==="message"&&e.direction==="in"&&!e.fake&&!!e.type&&AUTH_FAIL_TYPE.test(e.type);if(!n&&!s)continue;const m=_.get(e.socketId);if(!m||e.timestamp<m.at)_.set(e.socketId,{at:e.timestamp,id:e.id,url:o})}const I=new Map;for(const e of _.values())I.set(e.url,[...I.get(e.url)??[],{at:e.at,id:e.id}]);for(const[e,t]of g){const o=burst(t,STORM_OPENS,STORM_WINDOW_MS);if(!o)continue;const n=Math.max(1,Math.round((o[o.length-1].at-o[0].at)/1e3));c.push({kind:"reconnect-storm",message:`Opened ${o.length} times in ${n}s`,url:e,frameIds:o.map(s=>s.id),at:o[o.length-1].at})}for(const[e,t]of I){let o=-Infinity;for(const s of p.get(e)??[]){if(s.openedAt===void 0)continue;const m=_.get(s.id)?.at??s.closedAt??u;if(m-s.openedAt>=SIGNED_IN_MS)o=Math.max(o,m)}const n=burst(t.filter(s=>s.at>o),AUTH_FAILURES-1,AUTH_WINDOW_MS);if(!n)continue;c.push({kind:"auth-loop",message:`Sign-in failed ${plural(n.length,"time")} in a row`,url:e,frameIds:n.map(s=>s.id),at:n[n.length-1].at})}const h=new Map;const k=new Map;for(const e of[...f].sort((t,o)=>t.createdAt-o.createdAt)){if(e.state!=="closed"&&e.openedAt===void 0)continue;const t=(0,_readMessage.socketKey)(e.url);const o=e.state==="closed"&&e.openedAt===void 0&&!e.closedByBuoy;if(!o){h.set(t,[]);k.delete(t);continue}const n=[...h.get(t)??[],e];h.set(t,n);if(n.length>=CANT_CONNECT_TRIES)k.set(t,n)}for(const[e,t]of k){const o=new Set(t.map(s=>s.id));const n=i.filter(s=>s.kind==="close"&&o.has(s.socketId));c.push({kind:"cant-connect",message:`Couldn't connect: ${t.length} tries in a row failed`,url:e,frameIds:n.map(s=>s.id),at:Math.max(...t.map(s=>s.closedAt??s.createdAt))})}const M=new Map;for(const e of f){if(e.state!=="open")continue;const t=(0,_readMessage.socketKey)(e.url);M.set(t,[...M.get(t)??[],e])}for(const[e,t]of M){if(t.length<2)continue;c.push({kind:"two-sockets",message:`${t.length} sockets open to the same URL`,url:e,frameIds:[],at:Math.max(...t.map(o=>o.openedAt??o.createdAt))})}const y=new Map;for(const e of i){if(!e.sentWhileClosed)continue;y.set(e.socketId,[...y.get(e.socketId)??[],e])}for(const[e,t]of y){const o=[...t].sort((n,s)=>n.timestamp-s.timestamp);c.push({kind:"sent-while-closed",message:`Sent ${plural(o.length,"message")} while the socket was not open`,socketId:e,url:d.get(e)?.url,frameIds:o.map(n=>n.id),at:o[0].timestamp})}return c.sort((e,t)=>t.at-e.at)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FOLD_MIN=exports.BURST_GAP_MS=void 0;exports.foldFrames=foldFrames;exports.matchesPrefix=matchesPrefix;exports.topTypePrefixes=topTypePrefixes;const BURST_GAP_MS=exports.BURST_GAP_MS=1500;const FOLD_MIN=exports.FOLD_MIN=3;function keep(s,o,r){if(o.socketId&&s.socketId!==o.socketId)return false;if(s.ping&&!o.showPings)return false;const t=o.filter??{kind:"all"};if(t.kind==="problems"&&!r.has(s.id))return false;if(t.kind==="direction"&&s.direction!==t.direction)return false;if(t.kind==="type"&&!matchesPrefix(s.type,t.prefix))return false;if(o.search){const i=o.search.toLowerCase();if(!`${s.type??""} ${s.data??""} ${s.reason??""}`.toLowerCase().includes(i))return false}return true}function foldFrames(s,o={}){const r=new Map;for(const e of s.problems)for(const n of e.frameIds)if(!r.has(n))r.set(n,e);const t=[];for(const e of s.frames){if(!keep(e,o,r))continue;const n=r.get(e.id);const c=t[t.length-1];const f=c?.frames[c.frames.length-1];const a=f&&!n&&!c.problem&&e.kind==="message"&&f.kind==="message"&&!e.fake&&!f.fake&&!e.replyId&&!f.replyId&&e.type!==void 0&&e.type===f.type&&e.direction===f.direction&&e.socketId===f.socketId&&f.timestamp-e.timestamp<=BURST_GAP_MS;if(a)c.frames.push(e);else t.push({frames:[e],...n?{problem:n}:{}})}const i=[];for(const e of t){const n=e.frames[e.frames.length-1].id;if(e.frames.length>=FOLD_MIN&&!o.expanded?.has(n)){i.push({frame:e.frames[0],count:e.frames.length,foldKey:n});continue}for(const c of e.frames)i.push({frame:c,count:1,...e.problem?{problem:e.problem}:{}})}return i}function matchesPrefix(s,o){if(!s)return false;return s.startsWith(o)||/[.:/]$/.test(o)&&s===o.slice(0,-1)}function topTypePrefixes(s,o=4){const r=new Map;for(const t of s){if(t.kind!=="message"||t.ping||!t.type)continue;const i=t.type.search(/[.:/]/);const e=i>0?`${t.type.slice(0,i+1)}`:t.type;r.set(e,(r.get(e)??0)+1)}for(const[t,i]of[...r]){const e=[".",":","/"].map(n=>t+n).find(n=>r.has(n));if(!e)continue;r.set(e,r.get(e)+i);r.delete(t)}return[...r.entries()].sort((t,i)=>i[1]-t[1]).slice(0,o).map(([t])=>t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.clockTime=clockTime;exports.closeLabel=closeLabel;exports.connectionStatus=connectionStatus;exports.prettyData=prettyData;exports.previewText=previewText;exports.shortDuration=shortDuration;exports.shortUrl=shortUrl;function clockTime(t){const r=new Date(t);return[r.getHours(),r.getMinutes(),r.getSeconds()].map(e=>String(e).padStart(2,"0")).join(":")}function shortDuration(t){if(t<1e3)return`${Math.max(0,Math.round(t))}ms`;if(t<1e4)return`${(t/1e3).toFixed(1)}s`;const r=Math.round(t/1e3);if(r<60)return`${r}s`;const e=Math.floor(r/60);if(e<60)return`${e}m ${r%60}s`;return`${Math.floor(e/60)}h ${e%60}m`}function shortUrl(t){return t.replace(/^wss?:\/\//,"")}const CLOSE_NAMES={1e3:"normal",1001:"going away",1006:"lost connection",1008:"rejected",1011:"server error",1012:"server restart",4999:"Buoy"};function closeLabel(t,r=false){if(t===void 0)return"Closed";const e=t===1006&&r?"couldn't connect":CLOSE_NAMES[t];return e?`Closed ${t} \xB7 ${e}`:`Closed ${t}`}function connectionStatus(t,r){switch(t.state){case"connecting":return"Connecting";case"open":return`Open ${shortDuration(r-(t.openedAt??t.createdAt))}`;case"closing":return"Closing";case"closed":return`${closeLabel(t.closeCode,t.openedAt===void 0)}${t.closedByBuoy?" (Buoy)":""}`}}const WRAPPER_KEYS=["payload","data","body","d"];const TEXT_KEYS=["content","text","message","body"];function said(t){if(!t||typeof t!=="object"||Array.isArray(t))return void 0;for(const r of TEXT_KEYS){const e=t[r];if(typeof e==="string"&&e.trim())return e.trim().slice(0,80)}return void 0}function previewText(t){if(t.binary)return t.data??"[binary]";const r=(t.data??"").replace(/\s+/g," ").trim();if(!t.json||!t.type)return r;try{const e=JSON.parse(t.data??"");if(e&&typeof e==="object"&&!Array.isArray(e)){const{type:u,event:d,op:l,action:p,method:y,...n}=e;for(const a of["requestId","request_id","correlationId","correlation_id","ref","id"]){if(String(n[a])===t.correlationId)delete n[a]}const o=Object.keys(n);const s=o.length===1&&WRAPPER_KEYS.includes(o[0])?n[o[0]]:void 0;const i=s&&typeof s==="object"?s:n;const c=said(i);return`${c?`"${c}" \xB7 `:""}${JSON.stringify(i)}`}}catch{}return r}function prettyData(t){if(!t.json||!t.data)return t.data??"";try{return JSON.stringify(JSON.parse(t.data),null,2)}catch{return t.data}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_PARSE_CHARS=exports.MAX_FRAME_CHARS=exports.HIDDEN=void 0;exports.hideSecrets=hideSecrets;exports.hideUrlSecrets=hideUrlSecrets;exports.readMessage=readMessage;exports.scrubText=scrubText;exports.socketKey=socketKey;var _sharedUi=require("@buoy-gg/shared-ui");const MAX_FRAME_CHARS=exports.MAX_FRAME_CHARS=64*1024;const HIDDEN=exports.HIDDEN="[hidden]";const TYPE_KEYS=["type","event","op","action","method"];const CORRELATION_KEYS=["requestId","request_id","correlationId","correlation_id","ref","id"];const REPLY_KEYS=["success","ok","result","error","status"];const PING_TYPE=/^(ping|pong|heartbeat|hb|keep-?alive)$/i;const PING_TEXT=new Set(["2","3","ping","pong","heartbeat","primus::ping","primus::pong"]);const AUTH_TYPE=/^(auth|authenticate|authorize|login|sign-?in|connection_init)$/i;const JWT=/\beyJ[\w-]{6,}\.[\w-]{6,}\.[\w-]*/g;const SOCKET_IO=/^4[0-6](?:\/[^,]*,)?(\d*)([[{].*)$/s;const MAX_PARSE_CHARS=exports.MAX_PARSE_CHARS=256*1024;const KEY_VALUE=/("?)([\w.-]{2,64})\1(\s*[:=]\s*)("(?:[^"\\]|\\.)*(?:"|$)|(?:(?:Bearer|Basic|Token)\s+)?[^\s,;&}\]"]+)/gi;const AUTH_SCHEME=/\b(Bearer|Basic|Token)\s+[\w.~+/=-]{8,}/g;const AUTH_PAYLOAD=/("payload"\s*:\s*)("(?:[^"\\]|\\.)*(?:"|$)|[^\s,}\]]+)/;const TYPE_IN_TEXT=/"(?:type|event|op|action|method)"\s*:\s*"([^"\\]{1,80})"/;function binarySize(e){if(typeof ArrayBuffer!=="undefined"){if(e instanceof ArrayBuffer)return e.byteLength;if(ArrayBuffer.isView(e))return e.byteLength}if(typeof Blob!=="undefined"&&e instanceof Blob)return e.size;return null}function hexPreview(e){try{const t=e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null;if(!t)return"";const s=Array.from(t.subarray(0,32),i=>i.toString(16).padStart(2,"0")).join(" ");return t.byteLength>32?`${s} \u2026`:s}catch{return""}}function hideSecrets(e,t=0){if(t>20)return e!==null&&typeof e==="object"?HIDDEN:typeof e==="string"?e.replace(JWT,HIDDEN):e;if(typeof e==="string")return e.replace(JWT,HIDDEN);if(Array.isArray(e))return e.map(s=>hideSecrets(s,t+1));if(e&&typeof e==="object"){const s={};for(const[i,n]of Object.entries(e)){s[i]=(0,_sharedUi.classifyKey)(i)==="secret"&&n!=null&&n!==""?HIDDEN:hideSecrets(n,t+1)}return s}return e}function scrubText(e,t=0){return e.replace(KEY_VALUE,(s,i,n,r,c)=>{if((0,_sharedUi.classifyKey)(n)==="secret")return`${i}${n}${i}${r}${c.startsWith('"')?`"${HIDDEN}"`:HIDDEN}`;if(c.startsWith('"')&&c.length>2&&t<3){const u=c.endsWith('"')&&c.length>1;const y=c.slice(1,u?-1:void 0);return`${i}${n}${i}${r}"${scrubText(y,t+1)}${u?'"':""}`}return s}).replace(AUTH_SCHEME,`$1 ${HIDDEN}`).replace(JWT,HIDDEN)}function hideUrlSecrets(e){const t=e.replace(/^([a-z][\w+.-]*:\/\/[^/@:?#]*):[^/@?#]*@/i,`$1:${HIDDEN}@`);const s=t.indexOf("?");if(s===-1)return t.replace(JWT,HIDDEN);const i=t.slice(s+1).split("&").map(n=>{const r=n.indexOf("=");if(r===-1)return n;let c=n.slice(0,r);try{c=decodeURIComponent(c)}catch{}return(0,_sharedUi.classifyKey)(c)==="secret"?`${n.slice(0,r)}=${HIDDEN}`:n}).join("&");return`${t.slice(0,s)}?${i}`.replace(JWT,HIDDEN)}function socketKey(e){const t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}function pick(e,t){for(const s of t){const i=e[s];if(typeof i==="string"&&i)return i;if(typeof i==="number"&&Number.isFinite(i))return String(i)}return void 0}const PHOENIX_REPLY="phx_reply";function readObject(e){const t=pick(e,TYPE_KEYS);return{type:t,correlationId:pick(e,CORRELATION_KEYS),replyShaped:t===PHOENIX_REPLY||REPLY_KEYS.some(s=>s in e)}}function readPhoenix(e){if(e.length!==5||typeof e[2]!=="string"||typeof e[3]!=="string")return null;const t=e[1];return{type:e[3],correlationId:typeof t==="string"||typeof t==="number"?String(t):void 0,replyShaped:e[3]===PHOENIX_REPLY}}function readMessage(e){const t=binarySize(e);if(t!==null){const f=hexPreview(e);return{data:`[binary, ${t} bytes]${f?` ${f}`:""}`,size:t,binary:true}}const s=typeof e==="string"?e:String(e);const i=s.length;if(i>MAX_PARSE_CHARS){const f=s.slice(0,MAX_FRAME_CHARS);const p=f.trimStart()[0];const d=TYPE_IN_TEXT.exec(f.slice(0,4096))?.[1];const A=d?scrubText(d):void 0;const S=d&&AUTH_TYPE.test(d)?f.replace(AUTH_PAYLOAD,`$1"${HIDDEN}"`):f;return{data:scrubText(S).replace(/\beyJ[\w-]{6,}(?:\.[\w-]*)?$/,HIDDEN),size:i,truncated:true,...p==="{"||p==="["?{json:true}:{},...A?{type:A}:{}}}const n=s.trim();if(PING_TEXT.has(n.toLowerCase()))return{data:s,size:i,ping:true,type:n};let r;let c=false;let u;const y=SOCKET_IO.exec(n);try{if(y){r=JSON.parse(y[2]);u=y[1]||void 0}else if(n.startsWith("{")||n.startsWith("[")){r=JSON.parse(n);c=true}}catch{r=void 0}let o={};let h=false;let a;if(y&&r&&typeof r==="object"){const f=n[1]==="3"||n[1]==="6";if(Array.isArray(r)){o=f?{correlationId:u,replyShaped:true}:{type:typeof r[0]==="string"?r[0]:void 0,correlationId:u}}a=`${n.slice(0,n.length-y[2].length)}${JSON.stringify(hideSecrets(r))}`}else if(r&&typeof r==="object"&&!Array.isArray(r)){const f=r;o=readObject(f);let p=hideSecrets(f);if(o.type&&AUTH_TYPE.test(o.type)&&"payload"in p&&p.payload!=null){p={...p,payload:HIDDEN}}a=JSON.stringify(p)}else if(c){if(Array.isArray(r)){o=readPhoenix(r)??{};h=o.type!==void 0&&r[2]==="phoenix"}a=JSON.stringify(hideSecrets(r))}else{a=scrubText(s)}if(o.correlationId)o.correlationId=scrubText(o.correlationId);if(o.type)o.type=scrubText(o.type);const g=h||!!o.type&&PING_TYPE.test(o.type);const l=a.length>MAX_FRAME_CHARS;return{data:l?a.slice(0,MAX_FRAME_CHARS):a,size:i,...l?{truncated:l}:{},...c||y?{json:true}:{},...o,...g?{ping:g}:{}}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.onSocketMoment=onSocketMoment;exports.toSocketMoment=toSocketMoment;var _format=require("./format");var _socketStore=require("./socketStore");function toSocketMoment(e,o){const t={id:`socket-${e.id}`,source:"socket",timestamp:e.timestamp,subtitle:(0,_format.shortUrl)(o),originalEvent:e,correlationId:e.socketId};switch(e.kind){case"open":return{...t,title:"Socket opened",status:"success"};case"error":return{...t,title:"Socket error",status:"error"};case"close":return{...t,title:`Socket ${(0,_format.closeLabel)(e.code,e.neverOpened).toLowerCase()}${e.byBuoy?" (Buoy)":""}`,status:e.code===1e3||e.code===1001?"neutral":"error"};case"message":if(e.fake!=="inject")return null;return{...t,title:`Buoy pushed ${e.type??"a message"}`,status:"neutral"}}}function onSocketMoment(e){return _socketStore.socketStore.onEvent(o=>{const t=_socketStore.socketStore.getState().connections.find(r=>r.id===o.socketId);const s=toSocketMoment(o,t?.url??"");if(s)e(s)})}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isToolingSocket=isToolingSocket;exports.socketStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _store=require("../conditions/store");var _findProblems=require("./findProblems");var _readMessage=require("./readMessage");var _webSocketPatch=require("./webSocketPatch");const LATE_REPLY_MS=2*6e4;const MAX_FRAMES=1e3;const MAX_CONNECTIONS=50;const MAX_ANSWERED_URLS=50;const MAX_ANSWERED_TYPES=200;const HEALTHY_MS=3e4;const TOOLING_PATH=/\/(hot|message|inspector\/(device|debug)|debugger-proxy|__expo[^/?]*)(?:[/?]|$)/;const TOOLING_PORT=/^wss?:\/\/[^/]+:8097(?:\/|$)/;function isToolingSocket(u){return(0,_sharedUi.isBuoyRequest)(u)||TOOLING_PATH.test(u)||TOOLING_PORT.test(u)}class SocketStore extends _sharedUi.BaseEventStore{connections=new Map;controls=new Map;pending=new Map;answered=new Map;socketSeq=0;frameSeq=0;blocked=false;offline=false;installed=false;mirror=false;remote=null;capturingSince=null;mirrored=null;cache=null;version=0;recheck=null;retryOnAccess=null;constructor(){super({storeName:"sockets",maxEvents:MAX_FRAMES})}install(){if(this.installed||this.mirror)return this.installed;if((0,_sharedUi.getAccountAccess)().status==="locked"){this.retryOnAccess??=(0,_sharedUi.subscribeAccountAccess)(()=>{if((0,_sharedUi.getAccountAccess)().status!=="locked"&&this.install()){this.retryOnAccess?.();this.retryOnAccess=null}});return false}this.installed=(0,_webSocketPatch.installWebSocketPatch)(this);if(this.installed){this.capturingSince=Date.now();(0,_store.subscribeNetworkConditions)(()=>this.syncOffline());this.syncOffline()}return 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){const n=this.connections.get(e);if(n)this.connections.set(e,{...n,...t})}push(e){this.addEvent(e)}register(e,t,n){if(this.mirror||isToolingSocket(e)||(0,_sharedUi.getAccountAccess)().status==="locked")return null;const s=`s${++this.socketSeq}`;const i=(0,_readMessage.hideUrlSecrets)(e);const o=(0,_readMessage.socketKey)(i);let r;for(const c of this.connections.values())if((0,_readMessage.socketKey)(c.url)===o)r=c;const a=r?.openedAt!==void 0&&(r.closedAt??Date.now())-r.openedAt>=HEALTHY_MS;const f=r?.state==="closed"&&r.closeCode!==1e3&&!a;const d=f?r.attempt+1:1;this.connections.set(s,{id:s,url:i,...t?.length?{protocols:t}:{},attempt:d,state:"connecting",createdAt:Date.now(),sent:0,received:0,bytesSent:0,bytesReceived:0,pings:0});this.controls.set(s,n);this.trimConnections();this.bump();return s}trimConnections(){if(this.connections.size<=MAX_CONNECTIONS)return;for(const e of this.connections.values()){if(this.connections.size<=MAX_CONNECTIONS)break;if(e.state!=="closed")continue;this.connections.delete(e.id);this.controls.delete(e.id);this.pending.delete(e.id)}}open(e){const t=Date.now();this.setConnection(e,{state:"open",openedAt:t});this.push({id:this.nextFrameId(),socketId:e,kind:"open",timestamp:t})}close(e,t,n,s){const i=this.connections.get(e);if(!i||i.state==="closed")return;const o=Date.now();this.setConnection(e,{state:"closed",closedAt:o,closeCode:t,closeReason:n||void 0,...s?{closedByBuoy:true}:{},frozen:false});this.controls.delete(e);this.pending.delete(e);this.trimConnections();this.push({id:this.nextFrameId(),socketId:e,kind:"close",timestamp:o,...t!==void 0?{code:t}:{},...n?{reason:n}:{},...s?{byBuoy:s}:{},...i.openedAt===void 0?{neverOpened:true}:{}})}error(e){this.push({id:this.nextFrameId(),socketId:e,kind:"error",timestamp:Date.now()})}message(e,t,n,s){const i=this.connections.get(e);if(!i||(0,_sharedUi.getAccountAccess)().status==="locked")return void 0;const o=(0,_readMessage.readMessage)(n);const r=Date.now();const a=this.nextFrameId();const f={id:a,socketId:e,kind:"message",direction:t,timestamp:r,data:o.data,size:o.size,...o.binary?{binary:true}:{},...o.truncated?{truncated:true}:{},...o.json?{json:true}:{},...o.type?{type:o.type}:{},...o.correlationId?{correlationId:o.correlationId}:{},...o.ping?{ping:true}:{},...s?.fake?{fake:s.fake}:{},...s?.held?{held:true}:{},...s?.sentWhileClosed?{sentWhileClosed:true}:{}};const d=t==="out";this.setConnection(e,{lastMessageAt:r,...o.ping?{pings:i.pings+1}:d?{sent:i.sent+1,bytesSent:i.bytesSent+o.size}:{received:i.received+1,bytesReceived:i.bytesReceived+o.size}});if(o.correlationId&&!s?.held&&!(d&&s?.sentWhileClosed)){let c=this.pending.get(e);if(d){if(!c)this.pending.set(e,c=new Map);c.set(o.correlationId,{frameId:a,at:r});this.scheduleRecheck()}else{const h=c?.get(o.correlationId);if(h&&r-h.at>LATE_REPLY_MS)c.delete(o.correlationId);const k=h&&r-h.at<=LATE_REPLY_MS?h.frameId:void 0;const l=k?this.events.find(p=>p.id===k):void 0;if(l&&(o.replyShaped||o.type&&o.type===l.type)){c.delete(o.correlationId);f.replyTo=l.id;const p=r-l.timestamp;this.events=this.events.map(m=>m.id===l.id?{...m,replyId:a,replyMs:p}:m);if(l.type)this.rememberAnswered((0,_readMessage.socketKey)(i.url),l.type)}}}this.push(f);return a}rememberAnswered(e,t){let n=this.answered.get(e);if(n)this.answered.delete(e);else n=new Set;this.answered.set(e,n);n.delete(t);n.add(t);while(n.size>MAX_ANSWERED_TYPES)n.delete(n.values().next().value);while(this.answered.size>MAX_ANSWERED_URLS)this.answered.delete(this.answered.keys().next().value)}scheduleRecheck(){if(this.recheck)clearTimeout(this.recheck);this.recheck=null;const e=Date.now();let t=Infinity;for(const[n,s]of this.pending){for(const[i,o]of s){const r=e-o.at;if(r>LATE_REPLY_MS)s.delete(i);else t=Math.min(t,r<_findProblems.REPLY_TIMEOUT_MS?o.at+_findProblems.REPLY_TIMEOUT_MS:o.at+LATE_REPLY_MS+1)}if(s.size===0)this.pending.delete(n)}if(t===Infinity)return;this.recheck=setTimeout(()=>{this.recheck=null;this.bump();this.scheduleRecheck()},Math.max(0,t-e)+100)}cutOff(){if(this.offline)return"Offline (Buoy)";return this.blocked?"Blocked by Buoy":null}isFrozen(e){return this.connections.get(e)?.frozen===true}syncOffline(){const e=(0,_store.conditionsCanApply)()&&((0,_store.getNetworkCondition)()==="offline"||["offline","noInternet"].includes((0,_store.getEffectiveNetworkConnection)()));if(e===this.offline)return;this.offline=e;if(e){for(const 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;const e=[...this.connections.values()].reverse();const t=this.getEvents();const n={connections:e,frames:t,problems:(0,_findProblems.findProblems)(t,e,Date.now(),this.answered),tests:{blocked:this.blocked,offline:this.offline,frozen:e.filter(s=>s.frozen).map(s=>s.id)},capturingSince:this.capturingSince};this.cache={version:this.version,state:n};return n}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);const t=this.getFrame(e);if(!t)return null;const n=t.replyId??t.replyTo;return{frame:t,partner:n?this.getFrame(n)??null:null}}applySnapshot(e){this.mirrored=e;this.notifyArrayListeners()}async act(e){if(this.remote)return this.remote.act(e);return this.actLocal(e)}actLocal(e){const t="socketId"in e?this.controls.get(e.socketId):void 0;const n=s=>({ok:false,message:this.connections.has(s)?`Socket ${s} is closed.`:`No socket ${s}. Read get_sockets for ids.`});switch(e.action){case"inject":{if(!t)return n(e.socketId);const s=t.inject(e.data);return{ok:true,frameId:s,message:`Pushed the message into the app on ${e.socketId}, as if the server sent it.`}}case"send":{if(!t)return n(e.socketId);const s=this.connections.get(e.socketId)?.state==="connecting";const i=t.send(e.data);const o=i?this.getFrame(i)?.held:false;return o?{ok:false,frameId:i,message:s?`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:i,message:`Sent to the server on ${e.socketId}.`}}case"close":{if(!t)return n(e.socketId);const s=e.code??1006;if(!Number.isInteger(s)||s<1e3||s>4999){return{ok:false,message:`Close code ${s} isn't a WebSocket close code. Use 1000-4999, like 1006, 1008 or 1001.`}}const i=e.reason??(s===1006?"Dropped by Buoy":"Closed by Buoy");t.fakeClose(s,i);return{ok:true,message:`Closed ${e.socketId} with code ${s}. The app got the close; watch for its reconnect.`}}case"freeze":{if(!t)return n(e.socketId);this.setConnection(e.socketId,{frozen:e.frozen});this.bump();return{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.`}}case"block":{this.blocked=e.blocked;if(e.blocked)for(const s of[...this.controls.values()])s.fakeClose(1006,"Blocked by Buoy");this.bump();return{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(const s of this.connections.values())if(s.frozen)this.setConnection(s.id,{frozen:false});this.bump();return{ok:true,message:"Reset: no socket is frozen or blocked. The app reconnects on its own schedule."}}case"clear":{this.clearEvents();return{ok:true,message:"Cleared the message list."}}}}clearEvents(){for(const[e,t]of this.connections)if(t.state==="closed")this.connections.delete(e);this.pending.clear();this.answered.clear();super.clearEvents()}notifyArrayListeners(){this.version++;super.notifyArrayListeners()}}const socketStore=exports.socketStore=new SocketStore;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SNAPSHOT_TEXT=exports.SNAPSHOT_FRAMES=exports.LIST_BODY_TEXT=void 0;exports.matchesType=matchesType;exports.querySockets=querySockets;exports.socketsSyncAdapter=void 0;var _foldFrames=require("./foldFrames");var _readMessage=require("./readMessage");var _socketStore=require("./socketStore");const SNAPSHOT_FRAMES=exports.SNAPSHOT_FRAMES=300;const SNAPSHOT_TEXT=exports.SNAPSHOT_TEXT=1e3;const PREVIEW_TEXT=200;const LIST_BODY_TEXT=exports.LIST_BODY_TEXT=4e3;function cut(t,e){if(!t.data||t.data.length<=e)return t;return{...t,data:t.data.slice(0,e),dataCut:true}}function matchesType(t,e){if(!t)return false;const r=e.toLowerCase();const n=t.toLowerCase();return r.endsWith("*")?(0,_foldFrames.matchesPrefix)(n,r.slice(0,-1)):n.includes(r)}function querySockets(t,e={}){const r=new Set(t.problems.flatMap(o=>o.frameIds));let n=t.frames;if(e.frameId)n=n.filter(o=>o.id===e.frameId||o.replyTo===e.frameId||o.replyId===e.frameId);if(e.socketId)n=n.filter(o=>o.socketId===e.socketId);if(!e.includePings&&!e.frameId)n=n.filter(o=>!o.ping);if(e.type)n=n.filter(o=>matchesType(o.type,e.type));if(e.direction==="lifecycle")n=n.filter(o=>o.kind!=="message");else if(e.direction)n=n.filter(o=>o.direction===e.direction);if(e.problems)n=n.filter(o=>r.has(o.id));if(e.since)n=n.filter(o=>o.timestamp>=e.since);const c=n.length;const i=typeof e.limit==="number"&&e.limit>=0?Math.min(e.limit,500):50;const d=n.slice(0,i).map(o=>e.frameId?o:cut(o,e.includeBodies?LIST_BODY_TEXT:PREVIEW_TEXT));const s=e.socketId?t.connections.find(o=>o.id===e.socketId):void 0;const a=s?(0,_readMessage.socketKey)(s.url):void 0;return{connections:e.socketId?t.connections.filter(o=>o.id===e.socketId):t.connections,problems:e.socketId?t.problems.filter(o=>o.socketId?o.socketId===e.socketId:!!o.url&&(0,_readMessage.socketKey)(o.url)===a):t.problems,tests:t.tests,capturingSince:t.capturingSince,frames:d,total:c,flagged:[...r]}}function readAction(t){if(!t||typeof t!=="object")return null;const e=t;const r=typeof e.socketId==="string"?e.socketId:"";const n=typeof e.data==="string"?e.data:e.data!==void 0?JSON.stringify(e.data):void 0;switch(e.action){case"inject":case"send":return r&&n!==void 0?{action:e.action,socketId:r,data:n}:null;case"close":return r?{action:"close",socketId:r,...typeof e.code==="number"?{code:e.code}:{},...typeof e.reason==="string"?{reason:e.reason}:{}}:null;case"freeze":return r?{action:"freeze",socketId:r,frozen:e.frozen!==false}:null;case"block":return{action:"block",blocked:e.blocked!==false};case"reset":case"clear":return{action:e.action};default:return null}}const socketsSyncAdapter=exports.socketsSyncAdapter={version:1,getSnapshot:()=>{const t=_socketStore.socketStore.getState();return{...t,frames:t.frames.slice(0,SNAPSHOT_FRAMES).map(e=>cut(e,SNAPSHOT_TEXT))}},subscribe:t=>_socketStore.socketStore.subscribeState(t),actions:{getFrame:t=>{const e=t&&typeof t==="object"?t.id:void 0;if(typeof e!=="string")return null;const r=_socketStore.socketStore.getFrame(e);if(!r)return null;const n=r.replyId??r.replyTo;return{frame:r,partner:n?_socketStore.socketStore.getFrame(n)??null:null}},query:t=>querySockets(_socketStore.socketStore.getState(),t??{}),act:t=>{const e=readAction(t);if(!e){return{ok:false,message:"Unknown or incomplete action. inject/send need socketId and data; close/freeze need socketId."}}return _socketStore.socketStore.actLocal(e)}}};
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.installWebSocketPatch=installWebSocketPatch;exports.isWebSocketPatched=isWebSocketPatched;const EVENT_TYPES=["open","message","close","error"];const CONNECTING=0;const OPEN=1;const CLOSED=3;const PATCHED=Symbol.for("buoy.websocket.patched");const BUOY_CLOSE_CODE=4999;function call(n,f,d){try{if(typeof f==="function")f.call(n,d);else if(f&&typeof f.handleEvent==="function"){f.handleEvent(d)}}catch(g){const h=globalThis.reportError;if(typeof h==="function")h(g);else console.error(g)}}function safe(n){try{return n()}catch(f){if(typeof __DEV__!=="undefined"&&__DEV__)console.warn("[Buoy] Couldn't record a socket event:",f);return void 0}}function fakeEvent(n,f,d){return{type:n,target:f,currentTarget:f,isTrusted:false,timeStamp:Date.now(),defaultPrevented:false,preventDefault(){},stopPropagation(){},stopImmediatePropagation(){},...d}}function isWebSocketPatched(){const n=globalThis.WebSocket;return typeof n==="function"&&n[PATCHED]===true}function installWebSocketPatch(n){const f=globalThis;const d=f.WebSocket;if(typeof d!=="function"||d[PATCHED])return false;const g=d.prototype;const h=g.send;const x=g.close;const P=g.addEventListener;const D=g.removeEventListener;class I extends d{static[PATCHED]=true;constructor(c,i,...m){super(c,i,...m);const l=this;const _={open:[],message:[],close:[],error:[]};let a=false;let S=false;let o=null;const E=Object.getOwnPropertyDescriptor(l,"readyState");let T=E&&"value"in E?E.value:void 0;const O=()=>E&&"value"in E?T:Reflect.get(g,"readyState",l);Object.defineProperty(l,"readyState",{configurable:true,enumerable:true,get:()=>a?CLOSED:S?CONNECTING:O(),set:e=>{T=e}});const v=()=>{const e=a;a=false;try{x.call(l,BUOY_CLOSE_CODE,"Closed by Buoy")}catch{}finally{a=e}};const k=(e,t)=>{const s=_[e];let r=false;const u=t;const y=u?.stopImmediatePropagation;if(u&&typeof y==="function"){try{u.stopImmediatePropagation=()=>{r=true;y.call(u)}}catch{}}for(const p of[...s]){if(r)break;const b=s.indexOf(p);if(b===-1)continue;if(p.once)s.splice(b,1);call(l,p.listener,t)}};for(const e of EVENT_TYPES){Object.defineProperty(l,`on${e}`,{configurable:true,enumerable:true,get:()=>_[e].find(t=>t.attr)?.listener??null,set:t=>{const s=_[e];const r=s.find(u=>u.attr);if(typeof t==="function"){if(r)r.listener=t;else s.push({listener:t,once:false,capture:false,attr:true})}else if(r){s.splice(s.indexOf(r),1)}}})}const W=e=>typeof e==="boolean"?e:!!e?.capture;l.__buoyAdd=(e,t,s)=>{const r=_[e];if(!r)return false;const u=W(s);if(!t||r.some(b=>!b.attr&&b.listener===t&&b.capture===u))return true;const y=typeof s==="object"?s:void 0;if(y?.signal?.aborted)return true;const p={listener:t,once:!!y?.once,capture:u};r.push(p);y?.signal?.addEventListener?.("abort",()=>{const b=r.indexOf(p);if(b!==-1)r.splice(b,1)},{once:true});return true};l.__buoyRemove=(e,t,s)=>{const r=_[e];if(!r)return false;const u=W(s);const y=r.findIndex(p=>!p.attr&&p.listener===t&&p.capture===u);if(y!==-1)r.splice(y,1);return true};l.__buoySend=e=>{if(!o)return h.call(l,e);if(a){safe(()=>n.message(o,"out",e,{sentWhileClosed:true,held:true}));return}if(S){safe(()=>n.message(o,"out",e,{sentWhileClosed:true,held:true}));const t=globalThis.DOMException;throw typeof t==="function"?new t("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.","InvalidStateError"):new Error("INVALID_STATE_ERR")}if(O()!==OPEN){safe(()=>n.message(o,"out",e,{sentWhileClosed:true}));return h.call(l,e)}if(safe(()=>n.cutOff()!==null||n.isFrozen(o))===true){safe(()=>n.message(o,"out",e,{held:true}));return}safe(()=>n.message(o,"out",e));return h.call(l,e)};const C={inject(e){if(!o)return void 0;const t=safe(()=>n.message(o,"in",e,{fake:"inject"}));k("message",fakeEvent("message",l,{data:e,origin:"",lastEventId:"",ports:[]}));return t},send(e){if(!o)return void 0;const t=a||O()!==OPEN||safe(()=>n.cutOff()!==null||n.isFrozen(o))===true;const s=safe(()=>n.message(o,"out",e,t?{fake:"send",held:t}:{fake:"send"}));if(!t)h.call(l,e);return s},fakeClose(e,t){if(a)return;a=true;if(o&&e===1006)safe(()=>n.error(o));if(o)safe(()=>n.close(o,e,t,true));if(e===1006)k("error",fakeEvent("error",l,{message:t}));k("close",fakeEvent("close",l,{code:e,reason:t,wasClean:e!==1006}));v()},isOpen:()=>!a&&O()===OPEN};const N=typeof c==="string"?c:String(c);const A=i==null?void 0:Array.isArray(i)?i:[i];o=safe(()=>n.register(N,A,C))??null;for(const e of EVENT_TYPES){P.call(l,e,t=>{if(a||S){if(e==="open")v();return}if(o){const s=o;const r=e==="open"?safe(()=>n.cutOff()):null;if(r)return C.fakeClose(1006,r);if(e==="open")safe(()=>n.open(s));else if(e==="close")safe(()=>n.close(s,t?.code,t?.reason,false));else if(e==="error")safe(()=>n.error(s));else{const u=safe(()=>n.cutOff()!==null||n.isFrozen(s))===true;safe(()=>n.message(s,"in",t?.data,u?{held:u}:void 0));if(u)return}}k(e,t)})}const w=o?safe(()=>n.cutOff()):null;if(w){S=true;v();setTimeout(()=>C.fakeClose(1006,w),0)}}addEventListener(c,i,m){if(this.__buoyAdd?.(c,i,m))return;return P.call(this,c,i,m)}removeEventListener(c,i,m){if(this.__buoyRemove?.(c,i,m))return;return D.call(this,c,i,m)}send(c){const i=this;return i.__buoySend?i.__buoySend(c):h.call(i,c)}}f.WebSocket=I;return true}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkSyncAdapter=exports.SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_BODY_INLINE_LIMIT=void 0;var _store=require("../conditions/store");var _networkEventStore=require("../utils/networkEventStore");var _networkSavedStore=require("../utils/networkSavedStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _presets=require("../overrides/presets");var _engine=require("../overrides/engine");var _networkListener=require("../utils/networkListener");var _types=require("../overrides/types");var _sharedUi=require("@buoy-gg/shared-ui");const SNAPSHOT_BODY_INLINE_LIMIT=exports.SNAPSHOT_BODY_INLINE_LIMIT=16*1024;const SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function shouldStripBody(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_BODY_INLINE_LIMIT)}const wireCache=new WeakMap;const strippedCache=new WeakMap;function toWireEvent(e){const t=wireCache.get(e);if(t)return t;let n;try{n=buildWireEvent(e)}catch{n=buildMetadataOnly(e)}wireCache.set(e,n);return n}function buildMetadataOnly(e){const 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};let n=1024;try{n=(0,_sharedUi.approxJsonSize)(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:n}}function buildWireEvent(e){const t=shouldStripBody(e.requestData,e.requestSize);const n=shouldStripBody(e.responseData,e.responseSize);const r=toWireGraphqlVariables(e.graphqlVariables);const o=toWireHeaders(e.requestHeaders);const s=toWireHeaders(e.responseHeaders);const d=t||n||r!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let i=e;if(d){i={...e};if(t){i.requestData=void 0;i.requestBodyOmitted=true}if(n){i.responseData=void 0;i.responseBodyOmitted=true}if(r!==e.graphqlVariables){i.graphqlVariables=r}if(o!==e.requestHeaders){i.requestHeaders=o;i.headersOmitted=true}if(s!==e.responseHeaders){i.responseHeaders=s;i.headersOmitted=true}}return{event:i,bytes:(0,_sharedUi.approxJsonSize)(i,SNAPSHOT_EVENTS_BUDGET).bytes}}function toStrippedEvent(e){const t=strippedCache.get(e);if(t)return t;const{event:n}=toWireEvent(e);const r={...n};if(r.requestData!==void 0){r.requestData=void 0;r.requestBodyOmitted=true}if(r.responseData!==void 0){r.responseData=void 0;r.responseBodyOmitted=true}if(r.graphqlVariables!==void 0){r.graphqlVariables=toWireGraphqlVariables(r.graphqlVariables,true)}const o={event:r,bytes:(0,_sharedUi.approxJsonSize)(r,SNAPSHOT_EVENTS_BUDGET).bytes};strippedCache.set(e,o);return o}function fitEventsToBudget(e){const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++){const o=toWireEvent(e[r]);if(n+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[r]=o.event;n+=o.bytes}else{const s=toStrippedEvent(e[r]);t[r]=s.event;n+=s.bytes}}return t}function toWireGraphqlVariables(e,t=false){if(!e)return e;if(!t&&!shouldStripBody(e,void 0))return e;const n={};for(const[r,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)n[r]=o;else if(typeof o==="number"||typeof o==="boolean"){n[r]=o}}return Object.keys(n).length>0?n:void 0}const SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_HEADER_VALUE_LIMIT=64;function toWireHeaders(e){if(!e)return e;let t=false;const n={};for(const[r,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){n[r]=o}else{n[r]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?n:e}const stripLargeRuleBodies=e=>{let t=false;const n=e.rules.map(r=>{if(!r.body||r.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return r}t=true;return{...r,body:void 0,bodyOmitted:true}});return t?{...e,rules:n}:e};const resolveEvent=e=>_networkEventStore.networkEventStore.getEventById(e)??_networkSavedStore.networkSavedStore.getEventById(e);const readId=e=>e&&typeof e==="object"?e.id:void 0;const readBool=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const inactiveStamp=()=>(0,_engine.overridesCanApply)()?{}:{active:false,inactiveReason:_engine.OVERRIDES_INACTIVE_REASON};const VALID_KINDS=["respond","fail","delay"];function readRuleDraft(e,t){if(!e||typeof e!=="object")return null;const n=e.rule??e;if(!n||typeof n!=="object")return null;const r=n;const o=typeof r.urlPattern==="string"&&r.urlPattern.trim()?r.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=VALID_KINDS.includes(r.kind)?r.kind:t?.kind??"respond";return{id:typeof r.id==="string"?r.id:void 0,enabled:r.enabled!==false,name:typeof r.name==="string"?r.name:t?.name,urlPattern:o,methods:Array.isArray(r.methods)?r.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof r.requireHeader==="string"&&r.requireHeader.trim()?r.requireHeader.trim():void 0,bodyIncludes:typeof r.bodyIncludes==="string"&&r.bodyIncludes?r.bodyIncludes.slice(0,4096):t?.bodyIncludes,graphqlOperation:typeof r.graphqlOperation==="string"&&r.graphqlOperation?r.graphqlOperation.slice(0,200):t?.graphqlOperation,graphqlVariables:typeof r.graphqlVariables==="string"?r.graphqlVariables.slice(0,4096):t?.graphqlVariables,sandbox:r.sandbox===true?true:void 0,kind:s,status:typeof r.status==="number"?r.status:t?.status,statusText:typeof r.statusText==="string"?r.statusText:t?.statusText,headers:r.headers&&typeof r.headers==="object"?r.headers:t?.headers,body:patchedBody(r,t),failKind:r.failKind==="timeout"?"timeout":void 0,delayMs:typeof r.delayMs==="number"?r.delayMs:void 0,times:typeof r.times==="number"?r.times:null,alternate:r.alternate===true}}const isPlainObject=e=>!!e&&typeof e==="object"&&!Array.isArray(e);const isBodyPatch=e=>isPlainObject(e)||Array.isArray(e);function deepMerge(e,t,n="",r={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){r.shrunk.push({path:n||"(root)",have:e.length,sent:t.length})}return t}if(!isPlainObject(e)||!isPlainObject(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const i=n?`${n}.${s}`:s;if(s in e){const u=(0,_sharedUi.shapeKind)(e[s]);const l=(0,_sharedUi.shapeKind)(d);if((u==="array"||u==="object")&&u!==l){r.breaks.push({path:i,from:u,to:l})}o[s]=deepMerge(e[s],d,i,r)}else{o[s]=d}}return o}function patchViolations(e,t){if(e.body!=null||!isBodyPatch(e.bodyPatch)||typeof t!=="string")return[];try{return(0,_sharedUi.typedEditViolations)(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function patchedBody(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const n=t?.body??(isBodyPatch(e.bodyPatch)&&typeof e.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===e.id)?.body:void 0);if(isBodyPatch(e.bodyPatch)&&typeof n==="string"){try{return JSON.stringify(deepMerge(JSON.parse(n),e.bodyPatch),null,2)}catch{return n}}return n}function existingRule(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t.id;if(typeof n!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n);return r?{...r}:null}function preservedBody(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t;if(n.bodyOmitted!==true||typeof n.id!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n.id);return r?{body:r.body}:null}function baseFromRequest(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const n=resolveEvent(t);return n?(0,_presets.draftFromEvent)(n):null}const networkSyncAdapter=exports.networkSyncAdapter={dispose:()=>{_overrideRulesStore.overrideRulesStore.setEnabled(false)},version:6,getSnapshot:()=>{_networkEventStore.networkEventStore.ensureInterception();return{conditions:(0,_store.getNetworkConditions)(),events:fitEventsToBudget(_networkEventStore.networkEventStore.getEvents()),overrides:stripLargeRuleBodies(_overrideRulesStore.overrideRulesStore.getState()),saved:_networkSavedStore.networkSavedStore.getRecords().map(e=>({...e,event:toWireEvent(e.event).event}))}},subscribe:e=>{const t=_networkEventStore.networkEventStore.subscribeToEvents(e);const n=(0,_store.subscribeNetworkConditions)(e);const r=_networkSavedStore.networkSavedStore.subscribe(e);const o=_overrideRulesStore.overrideRulesStore.subscribe(e);return()=>{n();t();r();o()}},actions:{getNetworkConditions:_store.getNetworkConditions,setNetworkConditions:_store.setNetworkConditions,clearEvents:()=>{_networkEventStore.networkEventStore.clearEvents()},getEventBody:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;return{url:n.url??null,method:n.method??null,status:n.status??null,override:n.override??null,condition:n.condition??null,requestData:n.requestData??null,responseData:n.responseData??null,requestHeaders:n.requestHeaders??null,responseHeaders:n.responseHeaders??null}},setPinned:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"pinned");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).pinned;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.togglePin(n)},setSaved:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"saved");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).saved;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.toggleSave(n)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;_networkSavedStore.networkSavedStore.remove(t);return{ok:true}},clearSavedRequests:()=>{_networkSavedStore.networkSavedStore.clearSaved();return{ok:true}},clearPinnedRequests:()=>{_networkSavedStore.networkSavedStore.clearPinned();return{ok:true}},setOverridesEnabled:e=>{_overrideRulesStore.overrideRulesStore.setEnabled(readBool(e,"enabled"));return{ok:true,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},upsertOverrideRule:e=>{const t=e?.rule??e;const n=!!t&&t.body==null&&(isBodyPatch(t.bodyPatch)||typeof t.bodyPath==="string");const r=baseFromRequest(e)??preservedBody(e)??(n?existingRule(e):null);if(t&&typeof t.bodyPath==="string"&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(l=>l.id===t.id)?.body:void 0);if(typeof d!=="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 i;try{i=JSON.parse(d)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const u=(0,_sharedUi.patchFromPath)(i,t.bodyPath,t.bodyValue);if(!u.ok)return{ok:false,error:`Refused: ${u.error}`};t.bodyPatch=u.patch;delete t.bodyPath;delete t.bodyValue}if(t&&isBodyPatch(t.bodyPatch)&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(u=>u.id===t.id)?.body:void 0);if(typeof d!=="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 i;try{const u=(0,_sharedUi.expandKeyedArrays)(JSON.parse(d),t.bodyPatch);i=u.error;if(u.notes.length)t.bodyPatch=u.patch}catch{}if(i){return{ok:false,error:`Refused: ${i}`}}if(t.force!==true){const u=patchViolations(t,d);if(u.length>0){return{ok:false,error:(0,_sharedUi.refusalText)(u,"response body",(0,_sharedUi.suggestedPatch)(t.bodyPatch,u)),violations:u}}}}const o=readRuleDraft(e,r);if(!o){const d=e?.fromRequestId;return{ok:false,error:d?`No captured request \`${d}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const s=_overrideRulesStore.overrideRulesStore.upsertRule(o);if(!s)return{ok:false,error:"Override rule limit reached."};if(s.enabled)_overrideRulesStore.overrideRulesStore.setEnabled(true);return{ok:true,rule:{id:s.id,urlPattern:s.urlPattern,enabled:s.enabled,kind:s.kind,status:s.status,times:s.times,bodySize:s.body?s.body.length:0},...s.times===void 0||s.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${s.id}\`). If you meant only the next one, set times:1.`}:{},...inactiveStamp()}},setOverrideRuleEnabled:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.setRuleEnabled(t,readBool(e,"enabled"));return{ok:true,...inactiveStamp()}},deleteOverrideRule:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.removeRule(t);return{ok:true}},clearOverrideRules:()=>{_overrideRulesStore.overrideRulesStore.clearRules();return{ok:true}},replaceOverrideRules:async e=>{const 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>_types.MAX_RULES){return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${_types.MAX_RULES}.`}}await _overrideRulesStore.overrideRulesStore.ensureLoaded();const n=_overrideRulesStore.overrideRulesStore.replaceAllRules(t.rules,t.enabled!==false);if(!n)return{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."};return{ok:true,count:n.length,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},listOverrideRules:async()=>{await _overrideRulesStore.overrideRulesStore.ensureLoaded();return _overrideRulesStore.overrideRulesStore.getState()},getOverrideRuleBody:e=>{const t=readId(e);if(!t)return null;const n=_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===t);if(!n)return null;return{body:n.body??null}},getCaptureStatus:()=>{const e=_networkEventStore.networkEventStore.getSubscriberCounts().total;let t=null;let n=null;try{t=(0,_networkListener.isNetworkListening)();n=(0,_networkListener.getNetworkListenerCount)()}catch{}let r=null;try{r=(0,_networkListener.isNetworkInterceptionLive)()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:r,listenerCount:n,eventCount:_networkEventStore.networkEventStore.getEvents().length}},debugOverrides:e=>{const{url:t,method:n}=e&&typeof e==="object"?e:{};const r=typeof t==="string"?t:"https://example.com/";const o=typeof n==="string"&&n.trim()?n.trim().toUpperCase():"GET";return{tested:{url:r,method:o},interceptorInstalled:(0,_networkListener.isNetworkListening)(),listenerCount:(0,_networkListener.getNetworkListenerCount)(),engine:(0,_engine.inspectEngine)(r,o),store:{enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,autoPaused:_overrideRulesStore.overrideRulesStore.getState().autoPaused,ruleCount:_overrideRulesStore.overrideRulesStore.getState().rules.length,rulesVisibleToEngine:_overrideRulesStore.overrideRulesStore.getRules().length}}}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkSyncAdapter=exports.SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_BODY_INLINE_LIMIT=void 0;var _store=require("../conditions/store");var _networkEventStore=require("../utils/networkEventStore");var _networkSavedStore=require("../utils/networkSavedStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _presets=require("../overrides/presets");var _engine=require("../overrides/engine");var _networkListener=require("../utils/networkListener");var _types=require("../overrides/types");var _sharedUi=require("@buoy-gg/shared-ui");const SNAPSHOT_BODY_INLINE_LIMIT=exports.SNAPSHOT_BODY_INLINE_LIMIT=16*1024;const SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function shouldStripBody(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_BODY_INLINE_LIMIT)}const wireCache=new WeakMap;const strippedCache=new WeakMap;function toWireEvent(e){const t=wireCache.get(e);if(t)return t;let n;try{n=buildWireEvent(e)}catch{n=buildMetadataOnly(e)}wireCache.set(e,n);return n}function buildMetadataOnly(e){const 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};let n=1024;try{n=(0,_sharedUi.approxJsonSize)(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:n}}function buildWireEvent(e){const t=shouldStripBody(e.requestData,e.requestSize);const n=shouldStripBody(e.responseData,e.responseSize);const r=toWireGraphqlVariables(e.graphqlVariables);const o=toWireHeaders(e.requestHeaders);const s=toWireHeaders(e.responseHeaders);const d=t||n||r!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let i=e;if(d){i={...e};if(t){i.requestData=void 0;i.requestBodyOmitted=true}if(n){i.responseData=void 0;i.responseBodyOmitted=true}if(r!==e.graphqlVariables){i.graphqlVariables=r}if(o!==e.requestHeaders){i.requestHeaders=o;i.headersOmitted=true}if(s!==e.responseHeaders){i.responseHeaders=s;i.headersOmitted=true}}return{event:i,bytes:(0,_sharedUi.approxJsonSize)(i,SNAPSHOT_EVENTS_BUDGET).bytes}}function toStrippedEvent(e){const t=strippedCache.get(e);if(t)return t;const{event:n}=toWireEvent(e);const r={...n};if(r.requestData!==void 0){r.requestData=void 0;r.requestBodyOmitted=true}if(r.responseData!==void 0){r.responseData=void 0;r.responseBodyOmitted=true}if(r.graphqlVariables!==void 0){r.graphqlVariables=toWireGraphqlVariables(r.graphqlVariables,true)}const o={event:r,bytes:(0,_sharedUi.approxJsonSize)(r,SNAPSHOT_EVENTS_BUDGET).bytes};strippedCache.set(e,o);return o}function fitEventsToBudget(e){const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++){const o=toWireEvent(e[r]);if(n+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[r]=o.event;n+=o.bytes}else{const s=toStrippedEvent(e[r]);t[r]=s.event;n+=s.bytes}}return t}function toWireGraphqlVariables(e,t=false){if(!e)return e;if(!t&&!shouldStripBody(e,void 0))return e;const n={};for(const[r,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)n[r]=o;else if(typeof o==="number"||typeof o==="boolean"){n[r]=o}}return Object.keys(n).length>0?n:void 0}const SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_HEADER_VALUE_LIMIT=64;function toWireHeaders(e){if(!e)return e;let t=false;const n={};for(const[r,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){n[r]=o}else{n[r]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?n:e}const stripLargeRuleBodies=e=>{let t=false;const n=e.rules.map(r=>{if(!r.body||r.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return r}t=true;return{...r,body:void 0,bodyOmitted:true}});return t?{...e,rules:n}:e};const resolveEvent=e=>_networkEventStore.networkEventStore.getEventById(e)??_networkSavedStore.networkSavedStore.getEventById(e);const readId=e=>e&&typeof e==="object"?e.id:void 0;const readBool=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const inactiveStamp=()=>(0,_engine.overridesCanApply)()?{}:{active:false,inactiveReason:_engine.OVERRIDES_INACTIVE_REASON};const VALID_KINDS=["respond","fail","delay"];function readRuleDraft(e,t){if(!e||typeof e!=="object")return null;const n=e.rule??e;if(!n||typeof n!=="object")return null;const r=n;const o=typeof r.urlPattern==="string"&&r.urlPattern.trim()?r.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=VALID_KINDS.includes(r.kind)?r.kind:t?.kind??"respond";return{id:typeof r.id==="string"?r.id:void 0,enabled:r.enabled!==false,name:typeof r.name==="string"?r.name:t?.name,urlPattern:o,methods:Array.isArray(r.methods)?r.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof r.requireHeader==="string"&&r.requireHeader.trim()?r.requireHeader.trim():void 0,bodyIncludes:typeof r.bodyIncludes==="string"&&r.bodyIncludes?r.bodyIncludes.slice(0,4096):t?.bodyIncludes,graphqlOperation:typeof r.graphqlOperation==="string"&&r.graphqlOperation?r.graphqlOperation.slice(0,200):t?.graphqlOperation,graphqlVariables:typeof r.graphqlVariables==="string"?r.graphqlVariables.slice(0,4096):t?.graphqlVariables,bodyJson:typeof r.bodyJson==="string"&&r.bodyJson.length<=4096?r.bodyJson:t?.bodyJson,graphqlSingle:r.graphqlSingle===true?true:t?.graphqlSingle,sandbox:r.sandbox===true?true:void 0,kind:s,status:typeof r.status==="number"?r.status:t?.status,statusText:typeof r.statusText==="string"?r.statusText:t?.statusText,headers:r.headers&&typeof r.headers==="object"?r.headers:t?.headers,body:patchedBody(r,t),failKind:r.failKind==="timeout"?"timeout":void 0,delayMs:typeof r.delayMs==="number"?r.delayMs:void 0,times:typeof r.times==="number"?r.times:null,alternate:r.alternate===true}}const isPlainObject=e=>!!e&&typeof e==="object"&&!Array.isArray(e);const isBodyPatch=e=>isPlainObject(e)||Array.isArray(e);function deepMerge(e,t,n="",r={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){r.shrunk.push({path:n||"(root)",have:e.length,sent:t.length})}return t}if(!isPlainObject(e)||!isPlainObject(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const i=n?`${n}.${s}`:s;if(s in e){const u=(0,_sharedUi.shapeKind)(e[s]);const l=(0,_sharedUi.shapeKind)(d);if((u==="array"||u==="object")&&u!==l){r.breaks.push({path:i,from:u,to:l})}o[s]=deepMerge(e[s],d,i,r)}else{o[s]=d}}return o}function patchViolations(e,t){if(e.body!=null||!isBodyPatch(e.bodyPatch)||typeof t!=="string")return[];try{return(0,_sharedUi.typedEditViolations)(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function patchedBody(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const n=t?.body??(isBodyPatch(e.bodyPatch)&&typeof e.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===e.id)?.body:void 0);if(isBodyPatch(e.bodyPatch)&&typeof n==="string"){try{return JSON.stringify(deepMerge(JSON.parse(n),e.bodyPatch),null,2)}catch{return n}}return n}function existingRule(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t.id;if(typeof n!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n);return r?{...r}:null}function preservedBody(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t;if(n.bodyOmitted!==true||typeof n.id!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n.id);return r?{body:r.body}:null}function baseFromRequest(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const n=resolveEvent(t);return n?(0,_presets.draftFromEvent)(n):null}const networkSyncAdapter=exports.networkSyncAdapter={dispose:()=>{_overrideRulesStore.overrideRulesStore.setEnabled(false)},version:6,getSnapshot:()=>{_networkEventStore.networkEventStore.ensureInterception();return{conditions:(0,_store.getNetworkConditions)(),events:fitEventsToBudget(_networkEventStore.networkEventStore.getEvents()),overrides:stripLargeRuleBodies(_overrideRulesStore.overrideRulesStore.getState()),saved:_networkSavedStore.networkSavedStore.getRecords().map(e=>({...e,event:toWireEvent(e.event).event}))}},subscribe:e=>{const t=_networkEventStore.networkEventStore.subscribeToEvents(e);const n=(0,_store.subscribeNetworkConditions)(e);const r=_networkSavedStore.networkSavedStore.subscribe(e);const o=_overrideRulesStore.overrideRulesStore.subscribe(e);return()=>{n();t();r();o()}},actions:{getNetworkConditions:_store.getNetworkConditions,setNetworkConditions:_store.setNetworkConditions,clearEvents:()=>{_networkEventStore.networkEventStore.clearEvents()},getEventBody:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;return{url:n.url??null,method:n.method??null,status:n.status??null,override:n.override??null,condition:n.condition??null,requestData:n.requestData??null,responseData:n.responseData??null,requestHeaders:n.requestHeaders??null,responseHeaders:n.responseHeaders??null}},setPinned:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"pinned");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).pinned;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.togglePin(n)},setSaved:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"saved");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).saved;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.toggleSave(n)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;_networkSavedStore.networkSavedStore.remove(t);return{ok:true}},clearSavedRequests:()=>{_networkSavedStore.networkSavedStore.clearSaved();return{ok:true}},clearPinnedRequests:()=>{_networkSavedStore.networkSavedStore.clearPinned();return{ok:true}},setOverridesEnabled:e=>{_overrideRulesStore.overrideRulesStore.setEnabled(readBool(e,"enabled"));return{ok:true,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},upsertOverrideRule:e=>{const t=e?.rule??e;const n=!!t&&t.body==null&&(isBodyPatch(t.bodyPatch)||typeof t.bodyPath==="string");const r=baseFromRequest(e)??preservedBody(e)??(n?existingRule(e):null);if(t&&typeof t.bodyPath==="string"&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(l=>l.id===t.id)?.body:void 0);if(typeof d!=="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 i;try{i=JSON.parse(d)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const u=(0,_sharedUi.patchFromPath)(i,t.bodyPath,t.bodyValue);if(!u.ok)return{ok:false,error:`Refused: ${u.error}`};t.bodyPatch=u.patch;delete t.bodyPath;delete t.bodyValue}if(t&&isBodyPatch(t.bodyPatch)&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(u=>u.id===t.id)?.body:void 0);if(typeof d!=="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 i;try{const u=(0,_sharedUi.expandKeyedArrays)(JSON.parse(d),t.bodyPatch);i=u.error;if(u.notes.length)t.bodyPatch=u.patch}catch{}if(i){return{ok:false,error:`Refused: ${i}`}}if(t.force!==true){const u=patchViolations(t,d);if(u.length>0){return{ok:false,error:(0,_sharedUi.refusalText)(u,"response body",(0,_sharedUi.suggestedPatch)(t.bodyPatch,u)),violations:u}}}}const o=readRuleDraft(e,r);if(!o){const d=e?.fromRequestId;return{ok:false,error:d?`No captured request \`${d}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const s=_overrideRulesStore.overrideRulesStore.upsertRule(o);if(!s)return{ok:false,error:"Override rule limit reached."};if(s.enabled)_overrideRulesStore.overrideRulesStore.setEnabled(true);return{ok:true,rule:{id:s.id,urlPattern:s.urlPattern,enabled:s.enabled,kind:s.kind,status:s.status,times:s.times,bodySize:s.body?s.body.length:0},...s.times===void 0||s.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${s.id}\`). If you meant only the next one, set times:1.`}:{},...inactiveStamp()}},setOverrideRuleEnabled:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.setRuleEnabled(t,readBool(e,"enabled"));return{ok:true,...inactiveStamp()}},deleteOverrideRule:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.removeRule(t);return{ok:true}},clearOverrideRules:()=>{_overrideRulesStore.overrideRulesStore.clearRules();return{ok:true}},replaceOverrideRules:async e=>{const 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>_types.MAX_RULES){return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${_types.MAX_RULES}.`}}await _overrideRulesStore.overrideRulesStore.ensureLoaded();const n=_overrideRulesStore.overrideRulesStore.replaceAllRules(t.rules,t.enabled!==false);if(!n)return{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."};const r=await _overrideRulesStore.overrideRulesStore.saveChecked();return{ok:true,count:n.length,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,saved:r,...inactiveStamp()}},listOverrideRules:async()=>{await _overrideRulesStore.overrideRulesStore.ensureLoaded();return _overrideRulesStore.overrideRulesStore.getState()},getOverrideRuleBody:e=>{const t=readId(e);if(!t)return null;const n=_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===t);if(!n)return null;return{body:n.body??null}},getCaptureStatus:()=>{const e=_networkEventStore.networkEventStore.getSubscriberCounts().total;let t=null;let n=null;try{t=(0,_networkListener.isNetworkListening)();n=(0,_networkListener.getNetworkListenerCount)()}catch{}let r=null;try{r=(0,_networkListener.isNetworkInterceptionLive)()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:r,listenerCount:n,eventCount:_networkEventStore.networkEventStore.getEvents().length}},debugOverrides:e=>{const{url:t,method:n}=e&&typeof e==="object"?e:{};const r=typeof t==="string"?t:"https://example.com/";const o=typeof n==="string"&&n.trim()?n.trim().toUpperCase():"GET";return{tested:{url:r,method:o},interceptorInstalled:(0,_networkListener.isNetworkListening)(),listenerCount:(0,_networkListener.getNetworkListenerCount)(),engine:(0,_engine.inspectEngine)(r,o),store:{enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,autoPaused:_overrideRulesStore.overrideRulesStore.getState().autoPaused,ruleCount:_overrideRulesStore.overrideRulesStore.getState().rules.length,rulesVisibleToEngine:_overrideRulesStore.overrideRulesStore.getRules().length}}}}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkEventStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _extractOperationName=require("./extractOperationName");var _networkListener=require("./networkListener");var _networkSavedStore=require("./networkSavedStore");const BOOT_BUFFER_MAX=200;class NetworkEventStore extends _sharedUi.BaseEventStore{replaceEvents(t){super.replaceEvents(t.filter(e=>!(0,_sharedUi.isBuoyRequest)(e.url)))}pendingRequests=new Map;rawListenerUnsubscribe=null;bootBuffer=[];bootBufferUnsubscribe=null;mirrorMode=false;constructor(){super({storeName:"network",maxEvents:500})}startBootCapture(){if((0,_sharedUi.getAccountAccess)().status==="locked")return;if(this.mirrorMode||this.bootBufferUnsubscribe||this.isCapturing()){return}const t=(0,_networkListener.networkListener)();if(!t.isActive){t.startListening()}this.bootBufferUnsubscribe=(0,_networkListener.addNetworkListener)(e=>{this.bootBuffer.push(e);if(this.bootBuffer.length>BOOT_BUFFER_MAX)this.bootBuffer.shift()})}takeBootBuffer(){if(this.bootBufferUnsubscribe){this.bootBufferUnsubscribe();this.bootBufferUnsubscribe=null}const t=this.bootBuffer;this.bootBuffer=[];return t}startCapturing(){const t=(0,_networkListener.networkListener)();if(!t.isActive){t.startListening()}for(const e of this.takeBootBuffer()){this.processNetworkEvent(e)}if(!this.rawListenerUnsubscribe){this.rawListenerUnsubscribe=(0,_networkListener.addNetworkListener)(e=>{this.processNetworkEvent(e)})}t.adoptEarlyRequests()}stopCapturing(){this.takeBootBuffer();if(this.rawListenerUnsubscribe){this.rawListenerUnsubscribe();this.rawListenerUnsubscribe=null}if((0,_networkListener.getNetworkListenerCount)()===0){(0,_networkListener.stopNetworkListener)()}}disableCapture(){this.mirrorMode=true;this.takeBootBuffer();if((0,_networkListener.getNetworkListenerCount)()===0){(0,_networkListener.stopNetworkListener)()}super.disableCapture()}isCapturing(){return this.rawListenerUnsubscribe!==null}ensureInterception(){if(!this.isCapturing())return;(0,_networkListener.networkListener)().startListening()}subscribeToEvents(t){const e=super.subscribeToEvents(t);this.ensureInterception();return e}processNetworkEvent(t){if((0,_sharedUi.getAccountAccess)().status==="locked")return;const{request:e}=t;if((0,_sharedUi.isBuoyRequest)(e.url))return;if(t.type==="request"){if(this.events.some(u=>u.id===e.id))return;const r=e.params?`?${new URLSearchParams(e.params).toString()}`:"";const s=`${e.url}${r}`;let n;let o;if(e.client==="graphql"){const u=(0,_extractOperationName.extractOperationName)(e.data);n=u||void 0;if(e.data&&typeof e.data==="object"&&"variables"in e.data&&e.data.variables&&typeof e.data.variables==="object"){o=e.data.variables}}const a={id:e.id,method:e.method,url:s,host:this.extractHost(e.url),path:this.extractPath(e.url),query:r,timestamp:t.timestamp.getTime(),requestHeaders:e.headers||{},requestData:e.data,requestSize:this.getDataSize(e.data),responseHeaders:{},requestClient:e.client,operationName:n,graphqlVariables:o,override:t.override,condition:t.condition};this.pendingRequests.set(e.id,a);this.events=[a,...this.events].slice(0,this.maxEvents);this.notify(a);this.notifyArrayListeners()}else if(t.type==="request-body"){const r=this.events.find(n=>n.id===e.id);if(!r)return;const s={...r,requestData:e.data,requestSize:this.getDataSize(e.data)};if(e.client==="graphql"){s.operationName=(0,_extractOperationName.extractOperationName)(e.data)||void 0;const n=e.data?.variables;if(n&&typeof n==="object")s.graphqlVariables=n}this.events=this.events.map(n=>n.id===e.id?s:n);if(this.pendingRequests.has(e.id))this.pendingRequests.set(e.id,s);_networkSavedStore.networkSavedStore.syncFromLive(s);this.notify(s);this.notifyArrayListeners()}else if(t.type==="response"||t.type==="error"){const r=this.events.findIndex(s=>s.id===e.id);if(r!==-1){const s={...this.events[r],duration:t.duration,timings:t.timings};if(t.response){s.status=t.response.status;s.statusText=t.response.statusText;s.responseHeaders=t.response.headers||{};s.responseData=t.response.body;s.responseSize=t.response.size||0;s.responseType=t.response.headers?.["content-type"]}if(t.error){s.error=t.error.message;s.status=s.status||0}if(t.override)s.override=t.override;this.events=this.events.map((n,o)=>o===r?s:n);this.pendingRequests.delete(e.id);_networkSavedStore.networkSavedStore.syncFromLive(s);this.notify(s);this.notifyArrayListeners()}}}extractHost(t){try{const e=new URL(t);return e.hostname}catch{return""}}extractPath(t){try{const e=new URL(t);return e.pathname}catch{return t}}getDataSize(t){if(!t)return 0;if(typeof t==="string")return t.length;try{return JSON.stringify(t).length}catch{return 0}}getEventById(t){return this.events.find(e=>e.id===t)}clearEvents(){super.clearEvents();this.pendingRequests.clear()}onEvent(t,e=true){const r=this.subscribe(t);if(e&&this.events.length>0){const s=[...this.events].reverse();for(const n of s){try{t(n)}catch{}}}return r}getStats(){const t=this.events.length;const e=this.events.filter(i=>i.status&&i.status>=200&&i.status<300).length;const r=this.events.filter(i=>i.error||i.status&&i.status>=400).length;const s=this.events.filter(i=>!i.status&&!i.error).length;const n=this.events.filter(i=>i.duration).map(i=>i.duration);const o=n.length>0?n.reduce((i,c)=>i+c,0)/n.length:0;const a=this.events.reduce((i,c)=>i+(c.requestSize||0),0);const u=this.events.reduce((i,c)=>i+(c.responseSize||0),0);return{totalRequests:t,successfulRequests:e,failedRequests:r,pendingRequests:s,totalDataSent:a,totalDataReceived:u,averageDuration:Math.round(o)}}filterEvents(t){let e=[...this.events];if(t.method){e=e.filter(r=>r.method===t.method)}if(t.status){switch(t.status){case"success":e=e.filter(r=>r.status&&r.status>=200&&r.status<300);break;case"error":e=e.filter(r=>r.error||r.status&&r.status>=400);break;case"pending":e=e.filter(r=>!r.status&&!r.error);break}}if(t.searchText){const r=t.searchText.toLowerCase();e=e.filter(s=>s.url.toLowerCase().includes(r)||s.method.toLowerCase().includes(r)||s.error&&s.error.toLowerCase().includes(r))}if(t.host){e=e.filter(r=>r.host===t.host)}return e}}const networkEventStore=exports.networkEventStore=new NetworkEventStore;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkEventStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _extractOperationName=require("./extractOperationName");var _networkListener=require("./networkListener");var _networkSavedStore=require("./networkSavedStore");const BOOT_BUFFER_MAX=200;class NetworkEventStore extends _sharedUi.BaseEventStore{replaceEvents(t){super.replaceEvents(t.filter(e=>!(0,_sharedUi.isBuoyRequest)(e.url)))}pendingRequests=new Map;rawListenerUnsubscribe=null;bootBuffer=[];bootBufferUnsubscribe=null;mirrorMode=false;constructor(){super({storeName:"network",maxEvents:500})}startBootCapture(){if((0,_sharedUi.getAccountAccess)().status==="locked")return;if(this.mirrorMode||this.bootBufferUnsubscribe||this.isCapturing()){return}const t=(0,_networkListener.networkListener)();if(!t.isActive){t.startListening()}this.bootBufferUnsubscribe=(0,_networkListener.addNetworkListener)(e=>{this.bootBuffer.push(e);if(this.bootBuffer.length>BOOT_BUFFER_MAX)this.bootBuffer.shift()})}takeBootBuffer(){if(this.bootBufferUnsubscribe){this.bootBufferUnsubscribe();this.bootBufferUnsubscribe=null}const t=this.bootBuffer;this.bootBuffer=[];return t}startCapturing(){const t=(0,_networkListener.networkListener)();if(!t.isActive){t.startListening()}for(const e of this.takeBootBuffer()){this.processNetworkEvent(e)}if(!this.rawListenerUnsubscribe){this.rawListenerUnsubscribe=(0,_networkListener.addNetworkListener)(e=>{this.processNetworkEvent(e)})}t.adoptEarlyRequests()}stopCapturing(){this.takeBootBuffer();if(this.rawListenerUnsubscribe){this.rawListenerUnsubscribe();this.rawListenerUnsubscribe=null}if((0,_networkListener.getNetworkListenerCount)()===0){(0,_networkListener.stopNetworkListener)()}}disableCapture(){this.mirrorMode=true;this.takeBootBuffer();if((0,_networkListener.getNetworkListenerCount)()===0){(0,_networkListener.stopNetworkListener)()}super.disableCapture()}isCapturing(){return this.rawListenerUnsubscribe!==null}ensureInterception(){if(!this.isCapturing())return;(0,_networkListener.networkListener)().startListening()}subscribeToEvents(t){const e=super.subscribeToEvents(t);this.ensureInterception();return e}processNetworkEvent(t){if((0,_sharedUi.getAccountAccess)().status==="locked")return;const{request:e}=t;if((0,_sharedUi.isBuoyRequest)(e.url))return;if(t.type==="request"){if(this.events.some(u=>u.id===e.id))return;const r=e.params?`?${new URLSearchParams(e.params).toString()}`:"";const s=`${e.url}${r}`;let n;let o;if(e.client==="graphql"){const u=(0,_extractOperationName.extractOperationName)(e.data);n=u||void 0;if(e.data&&typeof e.data==="object"&&"variables"in e.data&&e.data.variables&&typeof e.data.variables==="object"){o=e.data.variables}}const a={id:e.id,method:e.method,url:s,host:this.extractHost(e.url),path:this.extractPath(e.url),query:r,timestamp:t.timestamp.getTime(),requestHeaders:e.headers||{},requestData:e.data,requestSize:this.getDataSize(e.data),responseHeaders:{},requestClient:e.client,operationName:n,graphqlVariables:o,override:t.override,condition:t.condition};this.pendingRequests.set(e.id,a);this.events=[a,...this.events].slice(0,this.maxEvents);this.notify(a);this.notifyArrayListeners()}else if(t.type==="request-body"){const r=this.events.find(n=>n.id===e.id);if(!r)return;const s={...r,requestData:e.data,requestSize:this.getDataSize(e.data)};if(e.client==="graphql"){s.operationName=(0,_extractOperationName.extractOperationName)(e.data)||void 0;const n=e.data?.variables;if(n&&typeof n==="object")s.graphqlVariables=n}this.events=this.events.map(n=>n.id===e.id?s:n);if(this.pendingRequests.has(e.id))this.pendingRequests.set(e.id,s);_networkSavedStore.networkSavedStore.syncFromLive(s);this.notify(s);this.notifyArrayListeners()}else if(t.type==="response"||t.type==="error"){const r=this.events.findIndex(s=>s.id===e.id);if(r!==-1){const s={...this.events[r],duration:t.duration,timings:t.timings};if(t.response){s.status=t.response.status;s.statusText=t.response.statusText;s.responseHeaders=t.response.headers||{};s.responseData=t.response.body;s.responseJson=typeof t.response.json==="boolean"?t.response.json:void 0;s.responseTruncated=t.response.truncated===true||void 0;s.responseUnread=t.response.unread===true||void 0;s.responseSize=t.response.size||0;s.responseType=t.response.headers?.["content-type"]}if(t.error){s.error=t.error.message;s.status=s.status||0}if(t.override)s.override=t.override;this.events=this.events.map((n,o)=>o===r?s:n);this.pendingRequests.delete(e.id);_networkSavedStore.networkSavedStore.syncFromLive(s);this.notify(s);this.notifyArrayListeners()}}}extractHost(t){try{const e=new URL(t);return e.hostname}catch{return""}}extractPath(t){try{const e=new URL(t);return e.pathname}catch{return t}}getDataSize(t){if(!t)return 0;if(typeof t==="string")return t.length;try{return JSON.stringify(t).length}catch{return 0}}getEventById(t){return this.events.find(e=>e.id===t)}clearEvents(){super.clearEvents();this.pendingRequests.clear()}onEvent(t,e=true){const r=this.subscribe(t);if(e&&this.events.length>0){const s=[...this.events].reverse();for(const n of s){try{t(n)}catch{}}}return r}getStats(){const t=this.events.length;const e=this.events.filter(i=>i.status&&i.status>=200&&i.status<300).length;const r=this.events.filter(i=>i.error||i.status&&i.status>=400).length;const s=this.events.filter(i=>!i.status&&!i.error).length;const n=this.events.filter(i=>i.duration).map(i=>i.duration);const o=n.length>0?n.reduce((i,c)=>i+c,0)/n.length:0;const a=this.events.reduce((i,c)=>i+(c.requestSize||0),0);const u=this.events.reduce((i,c)=>i+(c.responseSize||0),0);return{totalRequests:t,successfulRequests:e,failedRequests:r,pendingRequests:s,totalDataSent:a,totalDataReceived:u,averageDuration:Math.round(o)}}filterEvents(t){let e=[...this.events];if(t.method){e=e.filter(r=>r.method===t.method)}if(t.status){switch(t.status){case"success":e=e.filter(r=>r.status&&r.status>=200&&r.status<300);break;case"error":e=e.filter(r=>r.error||r.status&&r.status>=400);break;case"pending":e=e.filter(r=>!r.status&&!r.error);break}}if(t.searchText){const r=t.searchText.toLowerCase();e=e.filter(s=>s.url.toLowerCase().includes(r)||s.method.toLowerCase().includes(r)||s.error&&s.error.toLowerCase().includes(r))}if(t.host){e=e.filter(r=>r.host===t.host)}return e}}const networkEventStore=exports.networkEventStore=new NetworkEventStore;
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stopNetworkListener=exports.startNetworkListener=exports.removeAllNetworkListeners=exports.networkListener=exports.isNetworkListening=exports.isNetworkInterceptionLive=exports.getNetworkListenerCount=exports.addNetworkListener=exports.BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG=void 0;var _pacer=require("../conditions/pacer");var _sharedUi=require("@buoy-gg/shared-ui");var _resolveRequestUrl=require("./resolveRequestUrl");var _requestId=require("./requestId");var _xhr=require("../conditions/xhr");var _store=require("../conditions/store");var _wait=require("../conditions/wait");var _engine=require("../overrides/engine");var _applyToXhr=require("../overrides/applyToXhr");var _applyToFetch=require("../overrides/applyToFetch");var _types=require("../overrides/types");var _httpCompletion=require("./httpCompletion");var _realNow=require("./realNow");let devOrigin;function injectedHeaders(b){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const s of e){try{const l=s(b);if(l)t={...t,...l}}catch{}}return t}function devServerOrigin(){if(devOrigin!==void 0)return devOrigin;devOrigin=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return devOrigin;const b=require("react-native");const e=b?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const s=new URL(t);devOrigin=`${s.protocol}//${s.host}`}}catch{devOrigin=null}return devOrigin}let insideFetchHandoff=false;const EARLY_NETWORK_KEY=Symbol.for("buoy.earlyNetwork");function headersToRecord(b){const e={};if(!b)return e;if(typeof Headers!=="undefined"&&b instanceof Headers)b.forEach((t,s)=>{e[s]=t});else if(Array.isArray(b))for(const[t,s]of b)e[t]=s;else Object.assign(e,b);return e}const BUOY_FETCH_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";const BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const STREAMED_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"];const STREAMING_PLACEHOLDER="[streaming\u2026]";let angularPageSeen=false;function isAngularPage(){if(angularPageSeen)return true;const b=globalThis.document;angularPageSeen=!!b?.querySelector?.("[ng-version]");return angularPageSeen}function isStreamedContentType(b){if(!b)return false;const e=b.toLowerCase();return STREAMED_CONTENT_TYPES.some(t=>e.includes(t))}const INTERNAL_HOSTS_KEY="__BUOY_INTERNAL_HOSTS__";function isInternalBuoyHost(b){const e=globalThis[INTERNAL_HOSTS_KEY];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(b).host.toLowerCase()}catch{return false}for(const s of e){if(typeof s==="string"&&s&&t===s.toLowerCase())return true}return false}class NetworkListener{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if((0,_sharedUi.isBuoyRequest)(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(s&&["8081","8802"].includes(t.port))return true;const l=devServerOrigin();if(l&&`${t.protocol}//${t.host}`===l)return true}catch{return false}return isInternalBuoyHost(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(s){}})}parseUrl(e){let t=null;const s=e.indexOf("?");if(s>-1){t={};e.substring(s+1).split("&").forEach(l=>{const[u,i]=l.split("=");if(u&&i!==void 0){t[u]=decodeURIComponent(i.replace(/\+/g," "))}})}return{url:s>-1?e.substring(0,s):e,params:t}}async readStreamedBody(e,t=256*1024){const s=e.body;if(!s||typeof s.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stopNetworkListener=exports.startNetworkListener=exports.removeAllNetworkListeners=exports.networkListener=exports.isNetworkListening=exports.isNetworkInterceptionLive=exports.getNetworkListenerCount=exports.addNetworkListener=exports.BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG=void 0;var _pacer=require("../conditions/pacer");var _sharedUi=require("@buoy-gg/shared-ui");var _resolveRequestUrl=require("./resolveRequestUrl");var _requestId=require("./requestId");var _xhr=require("../conditions/xhr");var _store=require("../conditions/store");var _wait=require("../conditions/wait");var _engine=require("../overrides/engine");var _applyToXhr=require("../overrides/applyToXhr");var _applyToFetch=require("../overrides/applyToFetch");var _types=require("../overrides/types");var _httpCompletion=require("./httpCompletion");var _realNow=require("./realNow");let devOrigin;function injectedHeaders(R){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const s of e){try{const l=s(R);if(l)t={...t,...l}}catch{}}return t}function devServerOrigin(){if(devOrigin!==void 0)return devOrigin;devOrigin=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return devOrigin;const R=require("react-native");const e=R?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const s=new URL(t);devOrigin=`${s.protocol}//${s.host}`}}catch{devOrigin=null}return devOrigin}let insideFetchHandoff=false;const EARLY_NETWORK_KEY=Symbol.for("buoy.earlyNetwork");function headersToRecord(R){const e={};if(!R)return e;if(typeof Headers!=="undefined"&&R instanceof Headers)R.forEach((t,s)=>{e[s]=t});else if(Array.isArray(R))for(const[t,s]of R)e[t]=s;else Object.assign(e,R);return e}const BUOY_FETCH_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";const BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const STREAMED_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"];const STREAMING_PLACEHOLDER="[streaming\u2026]";let angularPageSeen=false;function isAngularPage(){if(angularPageSeen)return true;const R=globalThis.document;angularPageSeen=!!R?.querySelector?.("[ng-version]");return angularPageSeen}function isStreamedContentType(R){if(!R)return false;const e=R.toLowerCase();return STREAMED_CONTENT_TYPES.some(t=>e.includes(t))}const INTERNAL_HOSTS_KEY="__BUOY_INTERNAL_HOSTS__";function isInternalBuoyHost(R){const e=globalThis[INTERNAL_HOSTS_KEY];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(R).host.toLowerCase()}catch{return false}for(const s of e){if(typeof s==="string"&&s&&t===s.toLowerCase())return true}return false}class NetworkListener{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if((0,_sharedUi.isBuoyRequest)(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(s&&["8081","8802"].includes(t.port))return true;const l=devServerOrigin();if(l&&`${t.protocol}//${t.host}`===l)return true}catch{return false}return isInternalBuoyHost(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(s){}})}parseUrl(e){let t=null;const s=e.indexOf("?");if(s>-1){t={};e.substring(s+1).split("&").forEach(l=>{const[c,o]=l.split("=");if(c&&o!==void 0){t[c]=decodeURIComponent(o.replace(/\+/g," "))}})}return{url:s>-1?e.substring(0,s):e,params:t}}async readStreamedBody(e,t=256*1024){const s=e.body;if(!s||typeof s.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
2
2
 
3
- ... [truncated]`,size:f.length}:{body:f,size:f.length}}const l=s.getReader();const u=new TextDecoder;let i="";let h=0;let R=false;try{for(;;){const{done:f,value:a}=await l.read();if(f)break;h+=a?.byteLength??0;if(!R){i+=u.decode(a,{stream:true});if(h>=t){i=`${i.slice(0,t)}
3
+ ... [truncated]`,size:f.length,truncated:true}:{body:f,size:f.length}}const l=s.getReader();const c=new TextDecoder;let o="";let h=0;let b=false;try{for(;;){const{done:f,value:i}=await l.read();if(f)break;h+=i?.byteLength??0;if(!b){o+=c.decode(i,{stream:true});if(h>=t){o=`${o.slice(0,t)}
4
4
 
5
- ... [truncated]`;R=true;break}}}if(!R)i+=u.decode()}finally{try{void Promise.resolve(l.cancel()).catch(()=>{})}catch{}try{l.releaseLock()}catch{}}return{body:i,size:h}}async processResponseBody(e,t=1024*1024){try{const s=e.headers.get("content-length");if(s){const i=parseInt(s,10);if(!isNaN(i)&&i>t){return{body:`[Response too large: ${this.formatBytes(i)}]`,size:i,truncated:true}}}const l=await e.text();const u=l.length;if(u>t){const i=l.substring(0,t);const h=u-t;return{body:`${i}
5
+ ... [truncated]`;b=true;break}}}if(!b)o+=c.decode()}finally{try{void Promise.resolve(l.cancel()).catch(()=>{})}catch{}try{l.releaseLock()}catch{}}return{body:o,size:h,truncated:b||void 0}}async processResponseBody(e,t=1024*1024){try{const s=e.headers.get("content-length");if(s){const o=parseInt(s,10);if(!isNaN(o)&&o>t){return{body:`[Response too large: ${this.formatBytes(o)}]`,size:o,truncated:true,json:false}}}const l=await e.text();const c=l.length;if(c>t){const o=l.substring(0,t);const h=c-t;return{body:`${o}
6
6
 
7
- ... [truncated, ${this.formatBytes(h)} omitted]`,size:u,truncated:true}}try{return{body:JSON.parse(l),size:u,truncated:false}}catch{return{body:l,size:u,truncated:false}}}catch(s){return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const s=["B","KB","MB","GB"];const l=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,l)*100)/100} ${s[l]}`}handleXHRResponse(e,t,s,l,u,i,h,R,f=false,a="xhr",r,y){const m=R?(0,_realNow.realNow)()-R:0;const c=e._buoyTtfb;const L=c===void 0?void 0:{ttfb:c,download:Math.max(0,m-c)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:m,request:{id:t||"unknown",url:s,method:l,headers:u,data:i,params:h||void 0,client:a},error:{message:f?"Request failed":"Network error or request aborted"},override:r,condition:y});return}let o;let p=0;try{const n=e.response;if(e.responseType==="json"&&n){o=n;p=JSON.stringify(n).length}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{o=JSON.parse(e.responseText)}catch{o=e.responseText}}}else if(e.responseType==="arraybuffer"){if(n){try{const g=new TextDecoder("utf-8").decode(n);p=g.length;try{o=JSON.parse(g)}catch{o=g}}catch(g){o=`[arraybuffer response - ${n.byteLength||0} bytes]`;p=n.byteLength||0}}else{o=`[arraybuffer response - no data]`;p=0}}else if(e.responseType==="blob"){if(n instanceof Blob){o=`[blob response - ${n.size} bytes, type: ${n.type||"unknown"}]`;p=n.size}else if(n){try{o=typeof n==="string"?JSON.parse(n):n;p=JSON.stringify(o).length}catch{o=`[blob response - unable to parse]`;p=0}}else{o=`[blob response - no data]`;p=0}}else if(n){if(typeof n==="string"){o=n;p=n.length;try{o=JSON.parse(n)}catch{}}else if(typeof n==="object"){o=n;p=JSON.stringify(n).length}else{o=String(n);p=String(n).length}}}catch(n){o="~~~ unable to read body ~~~"}if(y?.downloadBytesPerSecond&&(!e.responseType||e.responseType==="text"||e.responseType==="json")){const n=e._response;if(typeof n==="string")p=(0,_pacer.utf8Length)(n)}const _={};try{const n=e.getAllResponseHeaders();if(n){n.split("\r\n").forEach(g=>{if(g){const w=g.indexOf(": ");if(w>0){const k=g.substring(0,w).toLowerCase();const q=g.substring(w+2);_[k]=q}}})}}catch{}if((0,_httpCompletion.xhrCompletionKind)(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:m,timings:L,request:{id:t||"unknown",url:s,method:l,headers:u,data:i,params:h||void 0,client:a},response:{status:e.status,statusText:(0,_httpCompletion.httpStatusText)(e.status,e.statusText),headers:_,body:o,size:p},override:r,condition:y})}else{this.emit({type:"error",timestamp:new Date,duration:m,request:{id:t||"unknown",url:s,method:l,headers:u,data:i,params:h||void 0,client:a},response:{status:e.status,statusText:e.statusText,headers:_,body:o,size:p},error:{message:"Network Error"},override:r,condition:y})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const s=++this.fetchGeneration;const l=async(u,i)=>{const h=(0,_resolveRequestUrl.resolveRequestUrl)(typeof u==="string"?u:u instanceof URL?u.href:u.url);if(s!==e.fetchGeneration){return t(u,i)}if(i?.__buoyInternal||e.shouldIgnoreUrl(h)){const d=insideFetchHandoff;insideFetchHandoff=true;try{return t(u,i)}finally{insideFetchHandoff=d}}const R=(0,_realNow.realNow)();const f=(0,_requestId.nextRequestId)("fetch");const a=typeof u==="object"&&"method"in u?u:void 0;const r=i?.method??a?.method??"GET";const y=i?.signal!==void 0?i.signal:a?.signal;(0,_wait.throwIfAborted)(y);const m=(0,_store.snapshotNetworkCondition)(h);const c=m?.uploadBytesPerSecond?{...m,uploadCap:(0,_pacer.uploadBodySize)(u,i)}:m;const{url:L,params:o}=e.parseUrl(h);let p={};const _=i?.headers??a?.headers;if(_){if(_ instanceof Headers){_.forEach((d,S)=>{p[S]=d})}else if(Array.isArray(_)){_.forEach(([d,S])=>{p[d]=S})}else{p={..._}}}Object.assign(p,injectedHeaders(h));let n;if(i?.body){if(typeof i.body==="string"){try{n=JSON.parse(i.body)}catch{n=i.body}}else{n=i.body}}const g=p["X-Request-Client"]||p["x-request-client"]||"fetch";if(c?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)())await(0,_engine.overrideRulesReady)();let w=typeof i?.body==="string"?i.body:void 0;if(w===void 0&&i?.body===void 0&&a&&!a.bodyUsed&&r!=="GET"&&r!=="HEAD"&&(0,_engine.overrideRulesNeedBody)()){try{w=(await e.readStreamedBody(a.clone())).body}catch{}}const k=c?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.accountCheckFor)(h,r,p,w):null;if(k)await k;const q=c?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.overrideForRequest)(h,r,p,w):null;const N=q?(0,_types.markForOutcome)(q):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:L,method:r,headers:p,data:n,params:o||void 0,client:g},override:N,condition:c});const X=d=>{try{n=JSON.parse(d)}catch{n=d}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:L,method:r,data:n,client:g}})};if(i?.body===void 0&&a&&typeof w==="string"){X(w)}else if(!c?.uploadBytesPerSecond&&i?.body===void 0&&a&&!a.bodyUsed&&r!=="GET"&&r!=="HEAD"){try{const d=a.clone();void e.readStreamedBody(d).then(({body:S})=>{if(S)X(S)}).catch(()=>{})}catch{}}try{if(c||q)await(0,_wait.waitBeforeDispatch)((c?.delayMs??0)+(q?.delayMs??0),y);(0,_wait.throwIfAborted)(y);if(c?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(q?.kind==="fail")throw(0,_applyToFetch.synthesizeFetchError)(q);if(c?.uploadBytesPerSecond){await(0,_pacer.paceByteCount)(c.uploadCap?.knownBytes??0,c.uploadBytesPerSecond,y);(0,_wait.throwIfAborted)(y)}let d;if(q?.kind==="respond"){d=(0,_applyToFetch.synthesizeResponse)(h,q)}else{const T=insideFetchHandoff;insideFetchHandoff=true;let H;try{H=t(u,i)}finally{insideFetchHandoff=T}d=await H}if(c?.downloadBytesPerSecond){const T={};d.headers.forEach((O,x)=>{T[x.toLowerCase()]=O});let H=0;let E=0;const z=[];const M=(O,x)=>{const B=new Uint8Array(E);let j=0;for(const J of z){B.set(J,j);j+=J.byteLength}let G=O?new TextDecoder().decode(B):STREAMING_PLACEHOLDER;if(O&&T["content-type"]?.includes("json")){try{G=JSON.parse(G)}catch{}}e.emit({type:x!==void 0?"error":"response",timestamp:new Date,duration:(0,_realNow.realNow)()-R,request:{id:f,url:L,method:r,headers:p,data:n,params:o||void 0,client:g},response:{status:d.status,statusText:d.statusText,headers:T,body:G,size:H},...x!==void 0?{error:{message:x instanceof Error?x.message:String(x)}}:{},override:N,condition:c})};M(false);return(0,_pacer.paceResponse)(d,c.downloadBytesPerSecond,y,(O,x)=>{if(O){H+=O.byteLength;const B=Math.min(O.byteLength,65536-E);if(B>0){z.push(O.slice(0,B));E+=B}}else M(true,x)},r.toUpperCase()==="HEAD")}const S=(0,_realNow.realNow)()-R;const I=typeof d.body?.getReader==="function"||isStreamedContentType(d.headers?.get?.("content-type"));const C=d.clone();const{body:D,size:P}=I?{body:STREAMING_PLACEHOLDER,size:0}:await e.processResponseBody(C);const A=(0,_realNow.realNow)()-R;const F=Math.max(0,A-S);const U=F>0?{ttfb:S,download:F}:void 0;const v={};d.headers.forEach((T,H)=>{v[H.toLowerCase()]=T});e.emit({type:"response",timestamp:new Date,duration:A,timings:U,request:{id:f||"unknown",url:L,method:r,headers:p,data:n,params:o||void 0,client:g},response:{status:d.status,statusText:d.statusText,headers:v,body:D,size:P},override:N,condition:c});if(I){const T=d.headers?.get?.("content-type");void e.readStreamedBody(C,isStreamedContentType(T)?void 0:1024*1024).then(H=>{let E=H.body;if(T?.includes("json")){try{E=JSON.parse(H.body)}catch{}}e.emit({type:"response",timestamp:new Date,duration:(0,_realNow.realNow)()-R,timings:U,request:{id:f||"unknown",url:L,method:r,headers:p,data:n,params:o||void 0,client:g},response:{status:d.status,statusText:d.statusText,headers:v,body:E,size:H.size},override:N,condition:c})}).catch(()=>{})}return d}catch(d){const S=(0,_realNow.realNow)()-R;e.emit({type:"error",timestamp:new Date,duration:S,request:{id:f||"unknown",url:L,method:r,headers:p,data:n,params:o||void 0,client:g},error:{message:d instanceof Error?d.message:"Network error",stack:d instanceof Error?d.stack:void 0},override:N,condition:c});throw d}};l[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=l;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const s=XMLHttpRequest.prototype.send;const l=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=s;this.originalXHRSetRequestHeader=l;const u=++this.xhrGeneration;const i=new WeakMap;const h=function(a,r,y,m,c){const L=t.call(this,a,r,y??true,m,c);if(u===e.xhrGeneration){i.get(this)?.();const o=this;o._buoyRequestId=(0,_requestId.nextRequestId)("xhr");o._method=a;o._url=(0,_resolveRequestUrl.resolveRequestUrl)(r);o._buoyStartTime=(0,_realNow.realNow)();o._requestHeaders={};o._buoyAsync=y!==false;o._buoyRestoreAbort?.();o._buoyWaitedForRules=false;o._buoyHeldSend=false;o._buoyOpenSeq=(o._buoyOpenSeq??0)+1}return L};const R=function(a,r){const y=this;if(u===e.xhrGeneration&&y._requestHeaders){y._requestHeaders[a]=r}return l.call(this,a,r)};const f=function(a){if(u!==e.xhrGeneration||insideFetchHandoff){return s.call(this,a)}if((0,_applyToXhr.hasPendingStandardRequest)(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return s.call(this,a)}const r=this;if(r._buoyHeldSend)throw new DOMException("The request has already been sent.","InvalidStateError");if(!(0,_engine.overrideRulesLoaded)()&&r._buoyAsync!==false&&!r._buoyWaitedForRules){r._buoyWaitedForRules=true;r._buoyHeldSend=true;const v=r._buoyOpenSeq;let T=false;const H=Object.prototype.hasOwnProperty.call(this,"abort")?this.abort:void 0;const E=()=>{if(r._buoyRestoreAbort!==E)return;r._buoyRestoreAbort=void 0;if(H)this.abort=H;else delete this.abort};r._buoyRestoreAbort=E;const z=H??Object.getPrototypeOf(this).abort;this.abort=function(){T=true;r._buoyHeldSend=false;E();return z.call(this)};const M=()=>{E();if(T||r._buoyOpenSeq!==v)return;r._buoyHeldSend=false;if(this.readyState===1&&!this._sent)f.call(this,a)};void(0,_engine.overrideRulesReady)().then(M,M);return}const y=r._buoyRequestId;const m=r._method||"GET";const c=r._url||"";const L=(0,_realNow.realNow)();r._buoyStartTime=L;r._buoyTtfb=void 0;const o=r._requestHeaders||{};Object.assign(o,injectedHeaders(c));if(e.shouldIgnoreUrl(c)){return s.call(this,a)}const{url:p,params:_}=e.parseUrl(c);let n;if(a){if(typeof a==="string"){try{n=JSON.parse(a)}catch{n=a}}else{n=a}}const g=o["X-Request-Client"]||o["x-request-client"];const w=o["Accept"]||o["accept"]||"";const k=w.includes("application/json")&&w.includes("text/plain")&&w.includes("*/*")&&!isAngularPage();const q=g||(k?"axios":"xhr");const N=(0,_store.snapshotNetworkCondition)(c);const X=N?.uploadBytesPerSecond?{...N,uploadCap:(0,_pacer.uploadSize)(a)}:N;const d=X?.profile==="offline"?null:(0,_engine.overrideForRequest)(c,m,o,typeof a==="string"?a:void 0);const S=d?(0,_types.markForOutcome)(d):void 0;e.emit({type:"request",timestamp:new Date,request:{id:y||"unknown",url:p,method:m,headers:o,data:n,params:_||void 0,client:q},override:S,condition:X});let I=false;const C=(v=false)=>{if(I)return;I=true;e.handleXHRResponse(this,y||"unknown",p,m,o,n,_,L||0,v,q,S,X);D()};const D=()=>{i.delete(this);this.removeEventListener("load",P);this.removeEventListener("error",A);this.removeEventListener("abort",F);this.removeEventListener("readystatechange",U)};i.set(this,D);const P=()=>{C(false)};const A=()=>{C(true)};const F=()=>{C(true)};const U=()=>{if(this.readyState===2){const v=this;if(v._buoyTtfb===void 0&&v._buoyStartTime){v._buoyTtfb=(0,_realNow.realNow)()-v._buoyStartTime}}if(this.readyState===4&&!I){C(false)}};this.addEventListener("load",P);this.addEventListener("error",A);this.addEventListener("abort",F);this.addEventListener("readystatechange",U);if(X){(0,_xhr.runConditionXhr)(this,c,X,d,()=>s.call(this,a),a);return}if(d){const v=(0,_applyToXhr.runOverride)(this,c,d,()=>s.call(this,a));if(v)return}return s.call(this,a)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=h;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=R;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(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;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis;const t=e[EARLY_NETWORK_KEY]??e.__BUOY_EARLY_NETWORK__;if(t?.version!==1)return;for(const s of t.adopt()){try{if(s.kind==="fetch")this.adoptEarlyFetch(s);else this.adoptEarlyXhr(s)}catch{}}}adoptEarlyFetch(e){const{input:t,init:s}=e;const l=typeof t==="object"&&"method"in t?t:void 0;const u=(0,_resolveRequestUrl.resolveRequestUrl)(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(u))return;const i=(0,_requestId.nextRequestId)("fetch");const h=s?.method??l?.method??"GET";const{url:R,params:f}=this.parseUrl(u);const a=headersToRecord(s?.headers??l?.headers);let r=s?.body;if(typeof r==="string"){try{r=JSON.parse(r)}catch{}}const y=a["X-Request-Client"]||a["x-request-client"]||"fetch";const m=()=>({id:i,url:R,method:h,headers:a,data:r,params:f||void 0,client:y});this.emit({type:"request",timestamp:new Date(e.start),request:m()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:c})=>{try{r=JSON.parse(c)}catch{r=c}this.emit({type:"request-body",timestamp:new Date,request:{id:i,url:R,method:h,data:r,client:y}})}).catch(()=>{})}void e.settled.then(async({response:c,clone:L,error:o,headersAt:p})=>{if(!c){this.emit({type:"error",timestamp:new Date,duration:p-e.start,request:m(),error:{message:o instanceof Error?o.message:"Network error",stack:o instanceof Error?o.stack:void 0}});return}const{body:_,size:n}=L?await this.processResponseBody(L):{body:STREAMING_PLACEHOLDER,size:0};const g=Math.max(0,(0,_realNow.realNow)()-e.start);const w=p-e.start;const k={};c.headers.forEach((q,N)=>{k[N.toLowerCase()]=q});this.emit({type:"response",timestamp:new Date,duration:g,timings:g>w?{ttfb:w,download:g-w}:void 0,request:m(),response:{status:c.status,statusText:c.statusText,headers:k,body:_,size:n}})})}adoptEarlyXhr(e){const t=(0,_resolveRequestUrl.resolveRequestUrl)(e.url);if(this.shouldIgnoreUrl(t))return;const s=(0,_requestId.nextRequestId)("xhr");const l=e.method.toUpperCase();const{url:u,params:i}=this.parseUrl(t);let h=e.body;if(typeof h==="string"){try{h=JSON.parse(h)}catch{}}const R=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:s,url:u,method:l,headers:e.headers,data:h,params:i||void 0,client:R}});const f=e.xhr;const a=()=>{const r=(f._buoyEarlyEnd??(0,_realNow.realNow)())-e.start;this.handleXHRResponse(f,s,u,l,e.headers,h,i,(0,_realNow.realNow)()-r,false,R)};if(f.readyState===4)a();else f.addEventListener("loadend",a,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let _networkListener=null;const getNetworkListener=()=>{if(!_networkListener){_networkListener=new NetworkListener}return _networkListener};const networkListener=exports.networkListener=getNetworkListener;const startNetworkListener=()=>getNetworkListener().startListening();exports.startNetworkListener=startNetworkListener;const stopNetworkListener=()=>_networkListener?.stopListening();exports.stopNetworkListener=stopNetworkListener;const addNetworkListener=b=>getNetworkListener().addListener(b);exports.addNetworkListener=addNetworkListener;const removeAllNetworkListeners=()=>_networkListener?.removeAllListeners();exports.removeAllNetworkListeners=removeAllNetworkListeners;const isNetworkListening=()=>_networkListener?.isActive??false;exports.isNetworkListening=isNetworkListening;const getNetworkListenerCount=()=>_networkListener?.listenerCount??0;exports.getNetworkListenerCount=getNetworkListenerCount;const isNetworkInterceptionLive=()=>_networkListener?.isInterceptionLive()??false;exports.isNetworkInterceptionLive=isNetworkInterceptionLive;
7
+ ... [truncated, ${this.formatBytes(h)} omitted]`,size:c,truncated:true,json:false}}try{return{body:JSON.parse(l),size:c,truncated:false,json:true}}catch{return{body:l,size:c,truncated:false,json:false}}}catch(s){return{body:"~~~ unable to read body ~~~",json:false,unread:true,size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const s=["B","KB","MB","GB"];const l=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,l)*100)/100} ${s[l]}`}handleXHRResponse(e,t,s,l,c,o,h,b,f=false,i="xhr",r,g){const L=b?(0,_realNow.realNow)()-b:0;const u=e._buoyTtfb;const q=u===void 0?void 0:{ttfb:u,download:Math.max(0,L-u)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:L,request:{id:t||"unknown",url:s,method:l,headers:c,data:o,params:h||void 0,client:i},error:{message:f?"Request failed":"Network error or request aborted"},override:r,condition:g});return}let n;let y=false;let w=false;let p=0;try{const a=e.response;if(e.responseType==="json"){const _=e.status===204||e.status===205||e.status===304||l.toUpperCase()==="HEAD"||e.getResponseHeader?.("content-length")==="0";if(a===null){n=void 0;w=!_;p=0}else{n=a;y=true;p=JSON.stringify(a).length}}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{n=JSON.parse(e.responseText);y=true}catch{n=e.responseText}}}else if(e.responseType==="arraybuffer"){if(a){try{const _=new TextDecoder("utf-8").decode(a);p=_.length;try{n=JSON.parse(_);y=true}catch{n=_}}catch(_){n=`[arraybuffer response - ${a.byteLength||0} bytes]`;w=true;p=a.byteLength||0}}else{n=`[arraybuffer response - no data]`;w=true;p=0}}else if(e.responseType==="blob"){if(a instanceof Blob){n=`[blob response - ${a.size} bytes, type: ${a.type||"unknown"}]`;w=true;p=a.size}else if(a){try{n=typeof a==="string"?JSON.parse(a):a;p=JSON.stringify(n).length}catch{n=`[blob response - unable to parse]`;w=true;p=0}}else{n=`[blob response - no data]`;w=true;p=0}}else if(a){if(typeof a==="string"){n=a;p=a.length;try{n=JSON.parse(a);y=true}catch{}}else if(typeof a==="object"){n=a;p=JSON.stringify(a).length}else{n=String(a);p=String(a).length}}}catch(a){n="~~~ unable to read body ~~~";w=true}if(g?.downloadBytesPerSecond&&(!e.responseType||e.responseType==="text"||e.responseType==="json")){const a=e._response;if(typeof a==="string")p=(0,_pacer.utf8Length)(a)}const T={};try{const a=e.getAllResponseHeaders();if(a){a.split("\r\n").forEach(_=>{if(_){const m=_.indexOf(": ");if(m>0){const v=_.substring(0,m).toLowerCase();const N=_.substring(m+2);T[v]=N}}})}}catch{}if((0,_httpCompletion.xhrCompletionKind)(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:L,timings:q,request:{id:t||"unknown",url:s,method:l,headers:c,data:o,params:h||void 0,client:i},response:{status:e.status,statusText:(0,_httpCompletion.httpStatusText)(e.status,e.statusText),headers:T,body:n,size:p,json:y,unread:w||void 0},override:r,condition:g})}else{this.emit({type:"error",timestamp:new Date,duration:L,request:{id:t||"unknown",url:s,method:l,headers:c,data:o,params:h||void 0,client:i},response:{status:e.status,statusText:e.statusText,headers:T,body:n,size:p},error:{message:"Network Error"},override:r,condition:g})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const s=++this.fetchGeneration;const l=async(c,o)=>{const h=(0,_resolveRequestUrl.resolveRequestUrl)(typeof c==="string"?c:c instanceof URL?c.href:c.url);if(s!==e.fetchGeneration){return t(c,o)}if(o?.__buoyInternal||e.shouldIgnoreUrl(h)){const d=insideFetchHandoff;insideFetchHandoff=true;try{return t(c,o)}finally{insideFetchHandoff=d}}const b=(0,_realNow.realNow)();const f=(0,_requestId.nextRequestId)("fetch");const i=typeof c==="object"&&"method"in c?c:void 0;const r=o?.method??i?.method??"GET";const g=o?.signal!==void 0?o.signal:i?.signal;(0,_wait.throwIfAborted)(g);const L=(0,_store.snapshotNetworkCondition)(h);const u=L?.uploadBytesPerSecond?{...L,uploadCap:(0,_pacer.uploadBodySize)(c,o)}:L;const{url:q,params:n}=e.parseUrl(h);let y={};const w=o?.headers??i?.headers;if(w){if(w instanceof Headers){w.forEach((d,H)=>{y[H]=d})}else if(Array.isArray(w)){w.forEach(([d,H])=>{y[d]=H})}else{y={...w}}}Object.assign(y,injectedHeaders(h));let p;if(o?.body){if(typeof o.body==="string"){try{p=JSON.parse(o.body)}catch{p=o.body}}else{p=o.body}}const T=y["X-Request-Client"]||y["x-request-client"]||"fetch";if(u?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)())await(0,_engine.overrideRulesReady)();let a=typeof o?.body==="string"?o.body:void 0;if(a===void 0&&o?.body===void 0&&i&&!i.bodyUsed&&r!=="GET"&&r!=="HEAD"&&(0,_engine.overrideRulesNeedBody)()){try{a=(await e.readStreamedBody(i.clone())).body}catch{}}const _=u?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.accountCheckFor)(h,r,y,a):null;if(_)await _;const m=u?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.overrideForRequest)(h,r,y,a):null;const v=m?(0,_types.markForOutcome)(m):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:q,method:r,headers:y,data:p,params:n||void 0,client:T},override:v,condition:u});const N=d=>{try{p=JSON.parse(d)}catch{p=d}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:q,method:r,data:p,client:T}})};if(o?.body===void 0&&i&&typeof a==="string"){N(a)}else if(!u?.uploadBytesPerSecond&&o?.body===void 0&&i&&!i.bodyUsed&&r!=="GET"&&r!=="HEAD"){try{const d=i.clone();void e.readStreamedBody(d).then(({body:H})=>{if(H)N(H)}).catch(()=>{})}catch{}}try{if(u||m)await(0,_wait.waitBeforeDispatch)((u?.delayMs??0)+(m?.delayMs??0),g);(0,_wait.throwIfAborted)(g);if(u?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(m?.kind==="fail")throw(0,_applyToFetch.synthesizeFetchError)(m);if(u?.uploadBytesPerSecond){await(0,_pacer.paceByteCount)(u.uploadCap?.knownBytes??0,u.uploadBytesPerSecond,g);(0,_wait.throwIfAborted)(g)}let d;if(m?.kind==="respond"){d=(0,_applyToFetch.synthesizeResponse)(h,m)}else{const k=insideFetchHandoff;insideFetchHandoff=true;let S;try{S=t(c,o)}finally{insideFetchHandoff=k}d=await S}if(u?.downloadBytesPerSecond){const k={};d.headers.forEach((O,X)=>{k[X.toLowerCase()]=O});let S=0;let I=0;const M=[];const Y=(O,X)=>{const U=new Uint8Array(I);let W=0;for(const Q of M){U.set(Q,W);W+=Q.byteLength}let J=O?new TextDecoder().decode(U):STREAMING_PLACEHOLDER;let K=false;if(O&&k["content-type"]?.includes("json")){try{J=JSON.parse(J);K=true}catch{}}const V=S>I;const $=!O||X!==void 0;e.emit({type:X!==void 0?"error":"response",timestamp:new Date,duration:(0,_realNow.realNow)()-b,request:{id:f,url:q,method:r,headers:y,data:p,params:n||void 0,client:T},response:{status:d.status,statusText:d.statusText,headers:k,body:J,size:S,json:K&&!V&&!$,truncated:V&&!$,...$?{unread:true}:{}},...X!==void 0?{error:{message:X instanceof Error?X.message:String(X)}}:{},override:v,condition:u})};Y(false);return(0,_pacer.paceResponse)(d,u.downloadBytesPerSecond,g,(O,X)=>{if(O){S+=O.byteLength;const U=Math.min(O.byteLength,65536-I);if(U>0){M.push(O.slice(0,U));I+=U}}else Y(true,X)},r.toUpperCase()==="HEAD")}const H=(0,_realNow.realNow)()-b;const B=typeof d.body?.getReader==="function"||isStreamedContentType(d.headers?.get?.("content-type"));const C=d.clone();const{body:j,size:D,json:P,truncated:z,unread:G}=B?{body:STREAMING_PLACEHOLDER,size:0,json:false,truncated:false,unread:true}:await e.processResponseBody(C);const E=(0,_realNow.realNow)()-b;const F=Math.max(0,E-H);const A=F>0?{ttfb:H,download:F}:void 0;const x={};d.headers.forEach((k,S)=>{x[S.toLowerCase()]=k});e.emit({type:"response",timestamp:new Date,duration:E,timings:A,request:{id:f||"unknown",url:q,method:r,headers:y,data:p,params:n||void 0,client:T},response:{status:d.status,statusText:d.statusText,headers:x,body:j,size:D,json:P,truncated:z||void 0,unread:G||void 0},override:v,condition:u});if(B){const k=d.headers?.get?.("content-type");void e.readStreamedBody(C,isStreamedContentType(k)?void 0:1024*1024).then(S=>{let I=S.body;let M=false;if(k?.toLowerCase().includes("json")){try{I=JSON.parse(S.body);M=true}catch{}}e.emit({type:"response",timestamp:new Date,duration:(0,_realNow.realNow)()-b,timings:A,request:{id:f||"unknown",url:q,method:r,headers:y,data:p,params:n||void 0,client:T},response:{status:d.status,statusText:d.statusText,headers:x,body:I,size:S.size,json:M,truncated:S.truncated},override:v,condition:u})}).catch(()=>{})}return d}catch(d){const H=(0,_realNow.realNow)()-b;e.emit({type:"error",timestamp:new Date,duration:H,request:{id:f||"unknown",url:q,method:r,headers:y,data:p,params:n||void 0,client:T},error:{message:d instanceof Error?d.message:"Network error",stack:d instanceof Error?d.stack:void 0},override:v,condition:u});throw d}};l[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=l;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const s=XMLHttpRequest.prototype.send;const l=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=s;this.originalXHRSetRequestHeader=l;const c=++this.xhrGeneration;const o=new WeakMap;const h=function(i,r,g,L,u){const q=t.call(this,i,r,g??true,L,u);if(c===e.xhrGeneration){o.get(this)?.();const n=this;n._buoyRequestId=(0,_requestId.nextRequestId)("xhr");n._method=i;n._url=(0,_resolveRequestUrl.resolveRequestUrl)(r);n._buoyStartTime=(0,_realNow.realNow)();n._requestHeaders={};n._buoyAsync=g!==false;n._buoyRestoreAbort?.();n._buoyWaitedForRules=false;n._buoyHeldSend=false;n._buoyOpenSeq=(n._buoyOpenSeq??0)+1}return q};const b=function(i,r){const g=this;if(c===e.xhrGeneration&&g._requestHeaders){g._requestHeaders[i]=r}return l.call(this,i,r)};const f=function(i){if(c!==e.xhrGeneration||insideFetchHandoff){return s.call(this,i)}if((0,_applyToXhr.hasPendingStandardRequest)(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return s.call(this,i)}const r=this;if(r._buoyHeldSend)throw new DOMException("The request has already been sent.","InvalidStateError");if(!(0,_engine.overrideRulesLoaded)()&&r._buoyAsync!==false&&!r._buoyWaitedForRules){r._buoyWaitedForRules=true;r._buoyHeldSend=true;const E=r._buoyOpenSeq;let F=false;const A=Object.prototype.hasOwnProperty.call(this,"abort")?this.abort:void 0;const x=()=>{if(r._buoyRestoreAbort!==x)return;r._buoyRestoreAbort=void 0;if(A)this.abort=A;else delete this.abort};r._buoyRestoreAbort=x;const k=A??Object.getPrototypeOf(this).abort;this.abort=function(){F=true;r._buoyHeldSend=false;x();return k.call(this)};const S=()=>{x();if(F||r._buoyOpenSeq!==E)return;r._buoyHeldSend=false;if(this.readyState===1&&!this._sent)f.call(this,i)};void(0,_engine.overrideRulesReady)().then(S,S);return}const g=r._buoyRequestId;const L=r._method||"GET";const u=r._url||"";const q=(0,_realNow.realNow)();r._buoyStartTime=q;r._buoyTtfb=void 0;const n=r._requestHeaders||{};Object.assign(n,injectedHeaders(u));if(e.shouldIgnoreUrl(u)){return s.call(this,i)}const{url:y,params:w}=e.parseUrl(u);let p;if(i){if(typeof i==="string"){try{p=JSON.parse(i)}catch{p=i}}else{p=i}}const T=n["X-Request-Client"]||n["x-request-client"];const a=n["Accept"]||n["accept"]||"";const _=a.includes("application/json")&&a.includes("text/plain")&&a.includes("*/*")&&!isAngularPage();const m=T||(_?"axios":"xhr");const v=(0,_store.snapshotNetworkCondition)(u);const N=v?.uploadBytesPerSecond?{...v,uploadCap:(0,_pacer.uploadSize)(i)}:v;const d=N?.profile==="offline"?null:(0,_engine.overrideForRequest)(u,L,n,typeof i==="string"?i:void 0);const H=d?(0,_types.markForOutcome)(d):void 0;e.emit({type:"request",timestamp:new Date,request:{id:g||"unknown",url:y,method:L,headers:n,data:p,params:w||void 0,client:m},override:H,condition:N});let B=false;const C=(E=false)=>{if(B)return;B=true;e.handleXHRResponse(this,g||"unknown",y,L,n,p,w,q||0,E,m,H,N);j()};const j=()=>{o.delete(this);this.removeEventListener("load",D);this.removeEventListener("error",P);this.removeEventListener("abort",z);this.removeEventListener("readystatechange",G)};o.set(this,j);const D=()=>{C(false)};const P=()=>{C(true)};const z=()=>{C(true)};const G=()=>{if(this.readyState===2){const E=this;if(E._buoyTtfb===void 0&&E._buoyStartTime){E._buoyTtfb=(0,_realNow.realNow)()-E._buoyStartTime}}if(this.readyState===4&&!B){C(false)}};this.addEventListener("load",D);this.addEventListener("error",P);this.addEventListener("abort",z);this.addEventListener("readystatechange",G);if(N){(0,_xhr.runConditionXhr)(this,u,N,d,()=>s.call(this,i),i);return}if(d){const E=(0,_applyToXhr.runOverride)(this,u,d,()=>s.call(this,i));if(E)return}return s.call(this,i)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=h;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=b;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(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;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis;const t=e[EARLY_NETWORK_KEY]??e.__BUOY_EARLY_NETWORK__;if(t?.version!==1)return;for(const s of t.adopt()){try{if(s.kind==="fetch")this.adoptEarlyFetch(s);else this.adoptEarlyXhr(s)}catch{}}}adoptEarlyFetch(e){const{input:t,init:s}=e;const l=typeof t==="object"&&"method"in t?t:void 0;const c=(0,_resolveRequestUrl.resolveRequestUrl)(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(c))return;const o=(0,_requestId.nextRequestId)("fetch");const h=s?.method??l?.method??"GET";const{url:b,params:f}=this.parseUrl(c);const i=headersToRecord(s?.headers??l?.headers);let r=s?.body;if(typeof r==="string"){try{r=JSON.parse(r)}catch{}}const g=i["X-Request-Client"]||i["x-request-client"]||"fetch";const L=()=>({id:o,url:b,method:h,headers:i,data:r,params:f||void 0,client:g});this.emit({type:"request",timestamp:new Date(e.start),request:L()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:u})=>{try{r=JSON.parse(u)}catch{r=u}this.emit({type:"request-body",timestamp:new Date,request:{id:o,url:b,method:h,data:r,client:g}})}).catch(()=>{})}void e.settled.then(async({response:u,clone:q,error:n,headersAt:y})=>{if(!u){this.emit({type:"error",timestamp:new Date,duration:y-e.start,request:L(),error:{message:n instanceof Error?n.message:"Network error",stack:n instanceof Error?n.stack:void 0}});return}const{body:w,size:p,json:T,truncated:a,unread:_}=q?await this.processResponseBody(q):{body:STREAMING_PLACEHOLDER,size:0,json:false,truncated:false,unread:true};const m=Math.max(0,(0,_realNow.realNow)()-e.start);const v=y-e.start;const N={};u.headers.forEach((d,H)=>{N[H.toLowerCase()]=d});this.emit({type:"response",timestamp:new Date,duration:m,timings:m>v?{ttfb:v,download:m-v}:void 0,request:L(),response:{status:u.status,statusText:u.statusText,headers:N,body:w,size:p,json:T,truncated:a||void 0,unread:_||void 0}})})}adoptEarlyXhr(e){const t=(0,_resolveRequestUrl.resolveRequestUrl)(e.url);if(this.shouldIgnoreUrl(t))return;const s=(0,_requestId.nextRequestId)("xhr");const l=e.method.toUpperCase();const{url:c,params:o}=this.parseUrl(t);let h=e.body;if(typeof h==="string"){try{h=JSON.parse(h)}catch{}}const b=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:s,url:c,method:l,headers:e.headers,data:h,params:o||void 0,client:b}});const f=e.xhr;const i=()=>{const r=(f._buoyEarlyEnd??(0,_realNow.realNow)())-e.start;this.handleXHRResponse(f,s,c,l,e.headers,h,o,(0,_realNow.realNow)()-r,false,b)};if(f.readyState===4)i();else f.addEventListener("loadend",i,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let _networkListener=null;const getNetworkListener=()=>{if(!_networkListener){_networkListener=new NetworkListener}return _networkListener};const networkListener=exports.networkListener=getNetworkListener;const startNetworkListener=()=>getNetworkListener().startListening();exports.startNetworkListener=startNetworkListener;const stopNetworkListener=()=>_networkListener?.stopListening();exports.stopNetworkListener=stopNetworkListener;const addNetworkListener=R=>getNetworkListener().addListener(R);exports.addNetworkListener=addNetworkListener;const removeAllNetworkListeners=()=>_networkListener?.removeAllListeners();exports.removeAllNetworkListeners=removeAllNetworkListeners;const isNetworkListening=()=>_networkListener?.isActive??false;exports.isNetworkListening=isNetworkListening;const getNetworkListenerCount=()=>_networkListener?.listenerCount??0;exports.getNetworkListenerCount=getNetworkListenerCount;const isNetworkInterceptionLive=()=>_networkListener?.isInterceptionLive()??false;exports.isNetworkInterceptionLive=isNetworkInterceptionLive;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.startNetworkCapture=startNetworkCapture;var _networkEventStore=require("./networkEventStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _NetworkFloatingTool=require("../conditions/NetworkFloatingTool");function startNetworkCapture(){const e=typeof navigator!=="undefined"&&navigator.product==="ReactNative";if(!e&&(typeof window==="undefined"||typeof document==="undefined"))return()=>{};void _overrideRulesStore.overrideRulesStore.ensureLoaded();const r=e?()=>{}:(0,_NetworkFloatingTool.registerLocalNetworkFloatingTool)();const o=_networkEventStore.networkEventStore.subscribeToEvents(()=>{});let t=false;return()=>{if(t)return;t=true;r();o()}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.startNetworkCapture=startNetworkCapture;var _networkEventStore=require("./networkEventStore");var _socketStore=require("../sockets/socketStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _NetworkFloatingTool=require("../conditions/NetworkFloatingTool");function startNetworkCapture(){const e=typeof navigator!=="undefined"&&navigator.product==="ReactNative";if(!e&&(typeof window==="undefined"||typeof document==="undefined"))return()=>{};void _overrideRulesStore.overrideRulesStore.ensureLoaded();_socketStore.socketStore.install();const r=e?()=>{}:(0,_NetworkFloatingTool.registerLocalNetworkFloatingTool)();const o=_networkEventStore.networkEventStore.subscribeToEvents(()=>{});let t=false;return()=>{if(t)return;t=true;r();o()}}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkToolPreset=exports.createNetworkTool=void 0;var _NetworkConditionsIcon=require("./network/conditions/NetworkConditionsIcon");var _sharedUi=require("@buoy-gg/shared-ui");var _NetworkModal=require("./network/components/NetworkModal");var _overrideRulesStore=require("./network/overrides/overrideRulesStore");var _networkEventStore=require("./network/utils/networkEventStore");var _jsxRuntime=require("react/jsx-runtime");const isReactNativeRuntime=typeof navigator!=="undefined"&&navigator.product==="ReactNative";if(isReactNativeRuntime)void _overrideRulesStore.overrideRulesStore.ensureLoaded();if(isReactNativeRuntime&&typeof __DEV__!=="undefined"&&__DEV__){_networkEventStore.networkEventStore.startBootCapture()}const networkToolPreset=exports.networkToolPreset=(0,_sharedUi.defineToolPreset)({id:"network",name:"NET",description:"Network request logger",slot:"both",icon:({size:e})=>(0,_jsxRuntime.jsx)(_NetworkConditionsIcon.NetworkConditionsIcon,{size:e}),component:_NetworkModal.NetworkModal,props:{enableSharedModalDimensions:false}});const createNetworkTool=exports.createNetworkTool=(0,_sharedUi.createToolFactory)(networkToolPreset,e=>({enableSharedModalDimensions:e.enableSharedModalDimensions??false}));
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkToolPreset=exports.createNetworkTool=void 0;var _NetworkConditionsIcon=require("./network/conditions/NetworkConditionsIcon");var _sharedUi=require("@buoy-gg/shared-ui");var _NetworkModal=require("./network/components/NetworkModal");var _overrideRulesStore=require("./network/overrides/overrideRulesStore");var _networkEventStore=require("./network/utils/networkEventStore");var _socketStore=require("./network/sockets/socketStore");var _jsxRuntime=require("react/jsx-runtime");const isReactNativeRuntime=typeof navigator!=="undefined"&&navigator.product==="ReactNative";if(isReactNativeRuntime)void _overrideRulesStore.overrideRulesStore.ensureLoaded();if(isReactNativeRuntime&&typeof __DEV__!=="undefined"&&__DEV__){_networkEventStore.networkEventStore.startBootCapture();_socketStore.socketStore.install()}const networkToolPreset=exports.networkToolPreset=(0,_sharedUi.defineToolPreset)({id:"network",name:"NET",description:"Network request logger",slot:"both",icon:({size:e})=>(0,_jsxRuntime.jsx)(_NetworkConditionsIcon.NetworkConditionsIcon,{size:e}),component:_NetworkModal.NetworkModal,props:{enableSharedModalDimensions:false}});const createNetworkTool=exports.createNetworkTool=(0,_sharedUi.createToolFactory)(networkToolPreset,e=>({enableSharedModalDimensions:e.enableSharedModalDimensions??false}));
@@ -1 +1 @@
1
- "use strict";export{networkToolPreset,createNetworkTool}from"./preset";export{startNetworkCapture}from"./network/utils/startNetworkCapture";export{NetworkModal,NetworkToolView}from"./network/components/NetworkModal";export{NetworkEventDetailView}from"./network/components/NetworkEventDetailView";export{NetworkEventItemCompact}from"./network/components/NetworkEventItemCompact";export{NetworkSavedScreen}from"./network/components/NetworkSavedScreen";export{NetworkSavedButton,NetworkDetailPinActions,NetworkHeaderBadgesView}from"./network/components/NetworkHeaderLive";export{useNetworkEvents}from"./network/hooks/useNetworkEvents";export{useNetworkEventList}from"./network/hooks/useNetworkEventList";export{useLiveNetworkEvent}from"./network/hooks/useLiveNetworkEvent";export{useNetworkBadgeCounts}from"./network/hooks/useNetworkBadgeCounts";export{useNetworkSaved}from"./network/hooks/useNetworkSaved";export{splitPinned}from"./network/utils/withPinnedFirst";export{networkSelectionStore,DEFAULT_SETTLE_MS}from"./network/utils/networkSelectionStore";export{TickProvider,useTickEveryMinute}from"./network/hooks/useTickEveryMinute";export{formatBytes,formatDuration,formatHttpStatus}from"./network/utils/formatting";export{overrideRulesStore}from"./network/overrides/overrideRulesStore";export{draftFromEvent}from"./network/overrides/presets";export{MAX_RULES as MAX_OVERRIDE_RULES,FREE_TIER_RULE_LIMIT as FREE_TIER_OVERRIDE_LIMIT,STATUS_MIN as OVERRIDE_STATUS_MIN,STATUS_MAX as OVERRIDE_STATUS_MAX}from"./network/overrides/types";export{useIgnoredPatterns,ignoredPatternsStore,urlMatchesIgnoredPattern,isUrlIgnored}from"@buoy-gg/shared-ui";export{networkSyncAdapter}from"./network/sync/networkSyncAdapter";export{NetworkBodyResolverProvider}from"./network/sync/networkBodyResolver";export{networkEventStore}from"./network/utils/networkEventStore";export{networkSavedStore,flagsForEventId,FREE_TIER_SAVED_LIMIT,MAX_PINNED,MAX_SAVED}from"./network/utils/networkSavedStore";export{generateCurl}from"./network/utils/generateCurl";export{networkListener,addNetworkListener,removeAllNetworkListeners}from"./network/utils/networkListener";export{NETWORK_CONDITIONS,getNetworkCondition,setNetworkCondition,subscribeNetworkConditions,getNetworkConditions,setNetworkConditions,getNetworkConnection,getConditionsRevision,networkConditionsActive}from"./network/conditions/store";export{chooseConditionsSnapshot}from"./network/conditions/remoteState";
1
+ "use strict";export{networkToolPreset,createNetworkTool}from"./preset";export{startNetworkCapture}from"./network/utils/startNetworkCapture";export{NetworkModal,NetworkToolView}from"./network/components/NetworkModal";export{NetworkEventDetailView}from"./network/components/NetworkEventDetailView";export{NetworkEventItemCompact}from"./network/components/NetworkEventItemCompact";export{NetworkSavedScreen}from"./network/components/NetworkSavedScreen";export{NetworkSavedButton,NetworkDetailPinActions,NetworkHeaderBadgesView}from"./network/components/NetworkHeaderLive";export{useNetworkEvents}from"./network/hooks/useNetworkEvents";export{useNetworkEventList}from"./network/hooks/useNetworkEventList";export{useLiveNetworkEvent}from"./network/hooks/useLiveNetworkEvent";export{useNetworkBadgeCounts}from"./network/hooks/useNetworkBadgeCounts";export{useNetworkSaved}from"./network/hooks/useNetworkSaved";export{splitPinned}from"./network/utils/withPinnedFirst";export{networkSelectionStore,DEFAULT_SETTLE_MS}from"./network/utils/networkSelectionStore";export{TickProvider,useTickEveryMinute}from"./network/hooks/useTickEveryMinute";export{formatBytes,formatDuration,formatHttpStatus}from"./network/utils/formatting";export{overrideRulesStore}from"./network/overrides/overrideRulesStore";export{draftFromEvent}from"./network/overrides/presets";export{MAX_RULES as MAX_OVERRIDE_RULES,FREE_TIER_RULE_LIMIT as FREE_TIER_OVERRIDE_LIMIT,STATUS_MIN as OVERRIDE_STATUS_MIN,STATUS_MAX as OVERRIDE_STATUS_MAX}from"./network/overrides/types";export{useIgnoredPatterns,ignoredPatternsStore,urlMatchesIgnoredPattern,isUrlIgnored}from"@buoy-gg/shared-ui";export{NetworkSocketsScreen}from"./network/components/sockets/NetworkSocketsScreen";export{useSocketsState}from"./network/hooks/useSocketsState";export{socketsSyncAdapter,querySockets}from"./network/sockets/socketsSyncAdapter";export{socketStore}from"./network/sockets/socketStore";export{onSocketMoment}from"./network/sockets/socketMoments";export{networkSyncAdapter}from"./network/sync/networkSyncAdapter";export{NetworkBodyResolverProvider}from"./network/sync/networkBodyResolver";export{networkEventStore}from"./network/utils/networkEventStore";export{networkSavedStore,flagsForEventId,FREE_TIER_SAVED_LIMIT,MAX_PINNED,MAX_SAVED}from"./network/utils/networkSavedStore";export{generateCurl}from"./network/utils/generateCurl";export{networkListener,addNetworkListener,removeAllNetworkListeners}from"./network/utils/networkListener";export{NETWORK_CONDITIONS,getNetworkCondition,setNetworkCondition,subscribeNetworkConditions,getNetworkConditions,setNetworkConditions,getNetworkConnection,getConditionsRevision,networkConditionsActive}from"./network/conditions/store";export{chooseConditionsSnapshot}from"./network/conditions/remoteState";
@@ -1 +1 @@
1
- "use strict";export{networkListener,startNetworkListener,stopNetworkListener,addNetworkListener,removeAllNetworkListeners,isNetworkListening}from"./network/utils/networkListener";export{networkEventStore}from"./network/utils/networkEventStore";export{networkSavedStore,flagsForEventId}from"./network/utils/networkSavedStore";export{useNetworkEvents,FREE_TIER_REQUEST_LIMIT}from"./network/hooks/useNetworkEvents";export{useNetworkEventList}from"./network/hooks/useNetworkEventList";export{useLiveNetworkEvent}from"./network/hooks/useLiveNetworkEvent";export{useNetworkBadgeCounts}from"./network/hooks/useNetworkBadgeCounts";export{useHasNetworkSelection,useSelectedNetworkEventId,useNetworkBodyEventId,useNetworkCursor}from"./network/hooks/useNetworkSelection";export{networkSelectionStore,toSelectionIds}from"./network/utils/networkSelectionStore";export{NetworkListScreen}from"./network/components/NetworkListScreen.web";export{NetworkEventItemCompact}from"./network/components/NetworkEventItemCompact.web";export{NetworkHeaderBadges,NetworkClearButton,NetworkSavedButton,NetworkDetailPinActions,NetworkHeaderCopyButton}from"./network/components/NetworkHeaderLive.web";export{NetworkEventDetailView}from"./network/components/NetworkEventDetailView.web";export{NetworkDetailStepper}from"./network/components/NetworkDetailStepper.web";export{NetworkDetailScreen}from"./network/components/NetworkDetailScreen.web";export{NetworkFilterViewV3}from"./network/components/NetworkFilterViewV3.web";export{NetworkFilterScreen}from"./network/components/NetworkFilterScreen.web";export{NetworkSavedScreen}from"./network/components/NetworkSavedScreen.web";export{NetworkCopySettingsView,DEFAULT_COPY_SETTINGS}from"./network/components/NetworkCopySettingsView.web";export{NetworkCopyScreen}from"./network/components/NetworkCopyScreen.web";export{generateNetworkCopyText}from"./network/utils/generateNetworkCopyText";export{selectSavedEvents}from"./network/utils/selectSavedEvents";export{FREE_TIER_SAVED_LIMIT,MAX_SAVED}from"./network/utils/networkSavedStore";export{NetworkOverridesScreen}from"./network/components/NetworkOverridesScreen.web";export{NetworkOverrideEditor}from"./network/components/NetworkOverrideEditor.web";export{NetworkNumberPrompt}from"./network/components/NetworkNumberPrompt.web";export{NetworkOverridesButton}from"./network/components/NetworkOverridesButton.web";export{NetworkOverrideHeaderButton}from"./network/components/NetworkOverrideHeaderButton.web";export{useOverrideRules}from"./network/hooks/useOverrideRules";export{overrideRulesStore}from"./network/overrides/overrideRulesStore";export{draftFromEvent,patternForUrl}from"./network/overrides/presets";export{FREE_TIER_RULE_LIMIT,MAX_RULES,STATUS_MAX,STATUS_MIN}from"./network/overrides/types";export{ruleMatches}from"./network/overrides/matchRule";export{filterNetworkEvents,applyIgnoredPatterns}from"./network/utils/filterNetworkEvents";export{splitPinned}from"./network/utils/withPinnedFirst";export{extractOperationName}from"./network/utils/extractOperationName";export{generateCurl}from"./network/utils/generateCurl";export{NETWORK_CONDITIONS,getNetworkCondition,setNetworkCondition,subscribeNetworkConditions,getNetworkConditions,setNetworkConditions,getNetworkConnection,getConditionsRevision,networkConditionsActive}from"./network/conditions/store";export{chooseConditionsSnapshot}from"./network/conditions/remoteState";
1
+ "use strict";export{networkListener,startNetworkListener,stopNetworkListener,addNetworkListener,removeAllNetworkListeners,isNetworkListening}from"./network/utils/networkListener";export{networkEventStore}from"./network/utils/networkEventStore";export{networkSavedStore,flagsForEventId}from"./network/utils/networkSavedStore";export{socketStore}from"./network/sockets/socketStore";export{socketsSyncAdapter,querySockets}from"./network/sockets/socketsSyncAdapter";export{onSocketMoment}from"./network/sockets/socketMoments";export{useNetworkEvents,FREE_TIER_REQUEST_LIMIT}from"./network/hooks/useNetworkEvents";export{useNetworkEventList}from"./network/hooks/useNetworkEventList";export{useLiveNetworkEvent}from"./network/hooks/useLiveNetworkEvent";export{useNetworkBadgeCounts}from"./network/hooks/useNetworkBadgeCounts";export{useHasNetworkSelection,useSelectedNetworkEventId,useNetworkBodyEventId,useNetworkCursor}from"./network/hooks/useNetworkSelection";export{networkSelectionStore,toSelectionIds}from"./network/utils/networkSelectionStore";export{NetworkListScreen}from"./network/components/NetworkListScreen.web";export{NetworkEventItemCompact}from"./network/components/NetworkEventItemCompact.web";export{NetworkHeaderBadges,NetworkClearButton,NetworkSavedButton,NetworkDetailPinActions,NetworkHeaderCopyButton}from"./network/components/NetworkHeaderLive.web";export{NetworkEventDetailView}from"./network/components/NetworkEventDetailView.web";export{NetworkDetailStepper}from"./network/components/NetworkDetailStepper.web";export{NetworkDetailScreen}from"./network/components/NetworkDetailScreen.web";export{NetworkFilterViewV3}from"./network/components/NetworkFilterViewV3.web";export{NetworkFilterScreen}from"./network/components/NetworkFilterScreen.web";export{NetworkSavedScreen}from"./network/components/NetworkSavedScreen.web";export{NetworkCopySettingsView,DEFAULT_COPY_SETTINGS}from"./network/components/NetworkCopySettingsView.web";export{NetworkCopyScreen}from"./network/components/NetworkCopyScreen.web";export{generateNetworkCopyText}from"./network/utils/generateNetworkCopyText";export{selectSavedEvents}from"./network/utils/selectSavedEvents";export{FREE_TIER_SAVED_LIMIT,MAX_SAVED}from"./network/utils/networkSavedStore";export{NetworkOverridesScreen}from"./network/components/NetworkOverridesScreen.web";export{NetworkOverrideEditor}from"./network/components/NetworkOverrideEditor.web";export{NetworkNumberPrompt}from"./network/components/NetworkNumberPrompt.web";export{NetworkOverridesButton}from"./network/components/NetworkOverridesButton.web";export{NetworkOverrideHeaderButton}from"./network/components/NetworkOverrideHeaderButton.web";export{useOverrideRules}from"./network/hooks/useOverrideRules";export{overrideRulesStore}from"./network/overrides/overrideRulesStore";export{draftFromEvent,patternForUrl}from"./network/overrides/presets";export{FREE_TIER_RULE_LIMIT,MAX_RULES,STATUS_MAX,STATUS_MIN}from"./network/overrides/types";export{ruleMatches}from"./network/overrides/matchRule";export{filterNetworkEvents,applyIgnoredPatterns}from"./network/utils/filterNetworkEvents";export{splitPinned}from"./network/utils/withPinnedFirst";export{extractOperationName}from"./network/utils/extractOperationName";export{generateCurl}from"./network/utils/generateCurl";export{NETWORK_CONDITIONS,getNetworkCondition,setNetworkCondition,subscribeNetworkConditions,getNetworkConditions,setNetworkConditions,getNetworkConnection,getConditionsRevision,networkConditionsActive}from"./network/conditions/store";export{chooseConditionsSnapshot}from"./network/conditions/remoteState";
@@ -1,4 +1,4 @@
1
- "use strict";import{useState as F,useEffect as U,useMemo as ee,memo as oe}from"react";import{View as l,Text as i,StyleSheet as te,ScrollView as re,TouchableOpacity as O}from"react-native";import{Clock as M,Upload as G,Download as J,AlertCircle as le,ChevronDown as _,ChevronUp as Q,Lock as ie,Unlock as ne,FileJson as E,Filter as ae,Globe as se,Link as ce,Copy as Y,FlaskConical as de,InlineCopyButton as K,macOSColors as N,night as t,useFeatureGate as ue,UpgradeModal as pe,monoFont as R}from"@buoy-gg/shared-ui";import{formatBytes as q,formatDuration as X,formatHttpStatus as ge}from"../utils/formatting";import{formatRelativeTime as he}from"@buoy-gg/shared-ui";import{DataViewer as H}from"@buoy-gg/shared-ui/dataViewer";import{formatGraphQLDisplay as fe}from"../utils/formatGraphQLVariables";import{useNetworkBodyResolver as ye}from"../sync/networkBodyResolver";import{jsx as e,jsxs as n,Fragment as W}from"react/jsx-runtime";const A=t.color.accent;const me=new Set;const be=()=>{};const Se=({timings:d,total:r})=>{const u=Math.max(1,r);const h=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:d.ttfb,color:N.semantic.warning},{label:"Content download",hint:void 0,value:d.download,color:N.semantic.success}];return e(l,{style:o.phaseList,children:h.map(s=>n(l,{style:o.phaseRow,children:[n(l,{style:o.phaseLabelGroup,children:[e(i,{style:o.phaseLabel,children:s.label}),s.hint?e(i,{style:o.phaseHint,children:s.hint}):null]}),e(l,{style:o.phaseTrack,children:e(l,{style:[o.phaseBar,{backgroundColor:s.color,width:`${Math.min(100,Math.max(1,s.value/u*100))}%`}]})}),e(i,{style:o.phaseValue,children:X(s.value)})]},s.label))})};const Z=()=>e(l,{style:o.bodyDeferred});const T=({title:d,icon:r,children:u,defaultOpen:h=false,count:s})=>{const[p,B]=F(h);return n(l,{style:o.collapsibleSection,children:[n(O,{style:o.collapsibleHeader,onPress:()=>B(!p),testID:`buoy-network-section-${d.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:d,children:[n(l,{style:o.collapsibleTitle,children:[r,e(i,{style:o.collapsibleTitleText,children:d}),s!==void 0?e(i,{style:o.collapsibleCount,children:s}):null]}),p?e(Q,{size:16,color:t.color.textSecondary}):e(_,{size:16,color:t.color.textSecondary})]}),p?e(l,{style:o.collapsibleContent,children:u}):null]})};const xe=({url:d,requestData:r,operationName:u,graphqlVariables:h,requestClient:s,isPro:p=false,onUpgradePress:B})=>{const g=I=>{try{const y=new URL(I);const x=String(y.protocol||"");const C=String(y.host||"");const V=x==="https:";let m=String(y.pathname||"");if(s==="graphql"&&u){const z=fe(u,h);m=`${m} (${z})`}else if(u){m=`${m} (${u})`}const w={};const b=y.searchParams;if(b&&typeof b.forEach==="function"){b.forEach((z,D)=>{w[D]=z})}return{protocol:x.replace(":",""),host:C,pathname:m,params:Object.keys(w).length>0?w:null,isSecure:V}}catch{return{protocol:"",host:d,pathname:"",params:null,isSecure:false}}};const c=ee(()=>g(d),[d,s,u,h]);const[f,k]=F(false);return n(l,{style:o.urlBreakdown,children:[n(l,{style:o.urlRow,children:[c.isSecure?e(ie,{size:12,color:N.semantic.success}):e(ne,{size:12,color:N.semantic.warning}),e(i,{style:o.urlDomain,children:c.host}),n(i,{style:o.urlProtocol,children:["(",c.protocol.toUpperCase(),")"]}),p?e(K,{value:d,buttonStyle:o.copyButton}):e(O,{style:o.copyButton,onPress:B,activeOpacity:.7,children:e(Y,{size:14,color:t.color.textSecondary})})]}),e(l,{style:o.urlPathRow,children:n(i,{style:o.urlPath,numberOfLines:2,children:[c.pathname,c.params?n(i,{style:o.urlQueryString,children:["?",new URLSearchParams(c.params).toString()]}):null]})}),c.params?n(l,{style:o.queryParamsCollapsible,children:[n(O,{style:o.queryParamsToggle,onPress:()=>k(!f),activeOpacity:.7,children:[e(i,{style:o.queryParamsToggleText,children:"Query Parameters"}),e(i,{style:o.collapsibleCount,children:Object.keys(c.params).length}),f?e(Q,{size:14,color:t.color.textSecondary}):e(_,{size:14,color:t.color.textSecondary})]}),f?e(H,{title:"",data:c.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})};export const NetworkEventDetailView=oe(function d({event:r,ignoredPatterns:u=me,onTogglePattern:h=be,showBodies:s=true}){const p=r.status?ge(r.status):null;const B=!r.status&&!r.error;const{isPro:g}=ue();const[c,f]=F(false);U(()=>{if(c&&g){f(false)}},[c,g]);const k=ye();const I=r.requestData===void 0&&(r.requestBodyOmitted===true||(r.requestSize??0)>0);const y=r.responseData===void 0&&(r.responseBodyOmitted===true||(r.responseSize??0)>0);const x=r.headersOmitted===true;const[C,V]=F(null);const[m,w]=F(false);U(()=>{V(null);if(!k||!I&&!y&&!x){w(false);return}let a=false;w(true);k(r.id).then(S=>{if(!a)V(S)}).catch(()=>{}).finally(()=>{if(!a)w(false)});return()=>{a=true}},[r.id,k,I,y,x]);const b=r.requestData??C?.requestData??void 0;const z=r.responseData??C?.responseData??void 0;const D=(x?C?.requestHeaders:void 0)??r.requestHeaders;const $=(x?C?.responseHeaders:void 0)??r.responseHeaders;const v=()=>{const a={method:r.method,url:r.url,status:r.status,statusText:r.statusText,timestamp:new Date(r.timestamp).toISOString(),duration:r.duration?`${r.duration}ms`:"N/A",requestHeaders:D,requestData:b,responseHeaders:$,responseData:z,requestSize:r.requestSize?q(r.requestSize):"N/A",responseSize:r.responseSize?q(r.responseSize):"N/A",error:r.error,client:r.requestClient};return`# Network Request Details
1
+ "use strict";import{useState as F,useEffect as U,useMemo as ee,memo as oe}from"react";import{View as l,Text as i,StyleSheet as te,ScrollView as re,TouchableOpacity as O}from"react-native";import{Clock as M,Upload as G,Download as J,AlertCircle as le,ChevronDown as _,ChevronUp as Q,Lock as ie,Unlock as ne,FileJson as E,Filter as ae,Globe as se,Link as ce,Copy as Y,FlaskConical as de,InlineCopyButton as K,macOSColors as N,night as t,useFeatureGate as ue,UpgradeModal as pe,monoFont as R}from"@buoy-gg/shared-ui";import{formatBytes as q,formatDuration as X,formatHttpStatus as ge}from"../utils/formatting";import{formatRelativeTime as he}from"@buoy-gg/shared-ui";import{DataViewer as H}from"@buoy-gg/shared-ui/dataViewer";import{formatGraphQLDisplay as fe}from"../utils/formatGraphQLVariables";import{useNetworkBodyResolver as ye}from"../sync/networkBodyResolver";import{jsx as e,jsxs as n,Fragment as W}from"react/jsx-runtime";const A=t.color.accent;const me=new Set;const be=()=>{};const Se=({timings:d,total:r})=>{const u=Math.max(1,r);const h=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:d.ttfb,color:N.semantic.warning},{label:"Content download",hint:void 0,value:d.download,color:N.semantic.success}];return e(l,{style:o.phaseList,children:h.map(s=>n(l,{style:o.phaseRow,children:[n(l,{style:o.phaseLabelGroup,children:[e(i,{style:o.phaseLabel,children:s.label}),s.hint?e(i,{style:o.phaseHint,children:s.hint}):null]}),e(l,{style:o.phaseTrack,children:e(l,{style:[o.phaseBar,{backgroundColor:s.color,width:`${Math.min(100,Math.max(1,s.value/u*100))}%`}]})}),e(i,{style:o.phaseValue,children:X(s.value)})]},s.label))})};const Z=()=>e(l,{style:o.bodyDeferred});const T=({title:d,icon:r,children:u,defaultOpen:h=false,count:s})=>{const[p,B]=F(h);return n(l,{style:o.collapsibleSection,children:[n(O,{style:o.collapsibleHeader,onPress:()=>B(!p),testID:`buoy-network-section-${d.toLowerCase().replace(/\s+/g,"-")}`,accessibilityRole:"button",accessibilityLabel:d,children:[n(l,{style:o.collapsibleTitle,children:[r,e(i,{style:o.collapsibleTitleText,children:d}),s!==void 0?e(i,{style:o.collapsibleCount,children:s}):null]}),p?e(Q,{size:16,color:t.color.textSecondary}):e(_,{size:16,color:t.color.textSecondary})]}),p?e(l,{style:o.collapsibleContent,children:u}):null]})};const xe=({url:d,requestData:r,operationName:u,graphqlVariables:h,requestClient:s,isPro:p=false,onUpgradePress:B})=>{const g=I=>{try{const y=new URL(I);const x=String(y.protocol||"");const C=String(y.host||"");const V=x==="https:";let m=String(y.pathname||"");if(s==="graphql"&&u){const z=fe(u,h);m=`${m} (${z})`}else if(u){m=`${m} (${u})`}const w={};const b=y.searchParams;if(b&&typeof b.forEach==="function"){b.forEach((z,D)=>{w[D]=z})}return{protocol:x.replace(":",""),host:C,pathname:m,params:Object.keys(w).length>0?w:null,isSecure:V}}catch{return{protocol:"",host:d,pathname:"",params:null,isSecure:false}}};const c=ee(()=>g(d),[d,s,u,h]);const[f,k]=F(false);return n(l,{style:o.urlBreakdown,children:[n(l,{style:o.urlRow,children:[c.isSecure?e(ie,{size:12,color:N.semantic.success}):e(ne,{size:12,color:N.semantic.warning}),e(i,{style:o.urlDomain,children:c.host}),n(i,{style:o.urlProtocol,children:["(",c.protocol.toUpperCase(),")"]}),p?e(K,{value:d,buttonStyle:o.copyButton}):e(O,{style:o.copyButton,onPress:B,activeOpacity:.7,children:e(Y,{size:14,color:t.color.textSecondary})})]}),e(l,{style:o.urlPathRow,children:n(i,{style:o.urlPath,numberOfLines:2,children:[c.pathname,c.params?n(i,{style:o.urlQueryString,children:["?",new URLSearchParams(c.params).toString()]}):null]})}),c.params?n(l,{style:o.queryParamsCollapsible,children:[n(O,{style:o.queryParamsToggle,onPress:()=>k(!f),activeOpacity:.7,children:[e(i,{style:o.queryParamsToggleText,children:"Query Parameters"}),e(i,{style:o.collapsibleCount,children:Object.keys(c.params).length}),f?e(Q,{size:14,color:t.color.textSecondary}):e(_,{size:14,color:t.color.textSecondary})]}),f?e(H,{title:"",data:c.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})};export const NetworkEventDetailView=oe(function d({event:r,ignoredPatterns:u=me,onTogglePattern:h=be,showBodies:s=true}){const p=r.status?ge(r.status):null;const B=!r.status&&!r.error;const{isPro:g}=ue();const[c,f]=F(false);U(()=>{if(c&&g){f(false)}},[c,g]);const k=ye();const I=r.requestData===void 0&&(r.requestBodyOmitted===true||(r.requestSize??0)>0);const y=r.responseData===void 0&&(r.responseBodyOmitted===true||(r.responseSize??0)>0);const x=r.headersOmitted===true;const[C,V]=F(null);const[m,w]=F(false);U(()=>{V(null);if(!k||!I&&!y&&!x){w(false);return}let a=false;w(true);k(r.id).then(S=>{if(!a)V(S)}).catch(()=>{}).finally(()=>{if(!a)w(false)});return()=>{a=true}},[r.id,k,I,y,x]);const b=r.requestData??C?.requestData??void 0;const z=r.responseData!==void 0?r.responseData:C?.responseData;const D=(x?C?.requestHeaders:void 0)??r.requestHeaders;const $=(x?C?.responseHeaders:void 0)??r.responseHeaders;const v=()=>{const a={method:r.method,url:r.url,status:r.status,statusText:r.statusText,timestamp:new Date(r.timestamp).toISOString(),duration:r.duration?`${r.duration}ms`:"N/A",requestHeaders:D,requestData:b,responseHeaders:$,responseData:z,requestSize:r.requestSize?q(r.requestSize):"N/A",responseSize:r.responseSize?q(r.responseSize):"N/A",error:r.error,client:r.requestClient};return`# Network Request Details
2
2
 
3
3
  ## Request
4
4
  - **Method:** ${a.method}
@@ -1,4 +1,4 @@
1
- "use strict";import{memo as U,useEffect as G,useMemo as J,useState as q}from"react";import{formatGraphQLDisplay as _}from"../utils/formatGraphQLVariables";import{useNetworkBodyResolver as Q}from"../sync/networkBodyResolver";import{DataViewer as R,InlineCopyButton as F}from"./DataViewer.web";import{jsx as e,jsxs as o,Fragment as A}from"react/jsx-runtime";const r={background:{base:"#0A0A0C",card:"#1A1A1C",hover:"#1D1D1F",input:"#26262A"},border:{default:"#2D2D2F"},text:{primary:"#F5F5F7",secondary:"#A1A1A6",muted:"#8E8E93"},semantic:{success:"#34C759",error:"#FF453A",errorBackground:"rgba(255, 69, 58, 0.15)",warning:"#FFEB3B",warningBackground:"rgba(255, 235, 59, 0.15)",info:"#00B8E6",infoBackground:"rgba(0, 184, 230, 0.1)"}};const $=r.semantic.success;function k(i){if(i===void 0||i===null)return"N/A";if(i===0)return"0 B";const t=1024;const c=["B","KB","MB","GB","TB"];const d=Math.floor(Math.log(i)/Math.log(t));return`${(i/Math.pow(t,d)).toFixed(1)} ${c[d]}`}function N(i){if(i===void 0||i===null)return"N/A";if(i<1e3)return`${i}ms`;if(i<6e4)return`${(i/1e3).toFixed(1)}s`;if(i<36e5){const d=Math.floor(i/6e4);const s=Math.floor(i%6e4/1e3);return s>0?`${d}m ${s}s`:`${d}m`}const t=Math.floor(i/36e5);const c=Math.floor(i%36e5/6e4);return c>0?`${t}h ${c}m`:`${t}h`}function Y(i,t=Date.now()){const c=i instanceof Date?i.getTime():i;const d=Math.floor((t-c)/1e3);if(d<0)return"just now";if(d<60)return d===0?"just now":`${d}s ago`;const s=Math.floor(d/60);if(s<60)return`${s}m ago`;const a=Math.floor(s/60);if(a<24)return`${a}h ago`;const u=Math.floor(a/24);return`${u}d ago`}function K(i){if(i>=100&&i<200){return{text:String(i),color:r.semantic.info,meaning:"Informational"}}if(i>=200&&i<300){const t={200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content"};return{text:String(i),color:r.semantic.success,meaning:t[i]||"Success"}}if(i>=300&&i<400){const t={301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect"};return{text:String(i),color:r.semantic.warning,meaning:t[i]||"Redirect"}}if(i>=400&&i<500){const t={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests"};return{text:String(i),color:r.semantic.error,meaning:t[i]||"Client Error"}}if(i>=500){const t={500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"};return{text:String(i),color:r.semantic.error,meaning:t[i]||"Server Error"}}return{text:String(i),color:r.text.muted,meaning:"Unknown"}}function p({size:i=14,color:t="currentColor",children:c}){return e("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},children:c})}const L=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("polyline",{points:"12 6 12 12 16 14"})]});const P=i=>o(p,{...i,children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"17 8 12 3 7 8"}),e("line",{x1:"12",x2:"12",y1:"3",y2:"15"})]});const E=i=>o(p,{...i,children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"7 10 12 15 17 10"}),e("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]});const Z=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),e("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]});const H=i=>e(p,{...i,children:e("path",{d:"m6 9 6 6 6-6"})});const W=i=>e(p,{...i,children:e("path",{d:"m18 15-6-6-6 6"})});const X=i=>o(p,{...i,children:[e("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),e("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]});const ee=i=>o(p,{...i,children:[e("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),e("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]});const v=i=>o(p,{...i,children:[e("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),e("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),e("path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1"}),e("path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1"})]});const te=i=>e(p,{...i,children:e("polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"})});const ne=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),e("path",{d:"M2 12h20"})]});const re=i=>o(p,{...i,children:[e("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),e("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]});const ie=i=>o(p,{...i,children:[e("path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2"}),e("path",{d:"M8.5 2h7"}),e("path",{d:"M7 16h10"})]});const oe=new Set;const le=()=>{};const ae=({timings:i,total:t})=>{const c=Math.max(1,t);const d=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:i.ttfb,color:r.semantic.warning},{label:"Content download",hint:void 0,value:i.download,color:r.semantic.success}];return e("div",{style:n.phaseList,children:d.map(s=>o("div",{style:n.phaseRow,children:[o("div",{style:n.phaseLabelGroup,children:[e("div",{style:n.phaseLabel,children:s.label}),s.hint?e("div",{style:n.phaseHint,children:s.hint}):null]}),e("div",{style:n.phaseTrack,children:e("div",{style:{...n.phaseBar,backgroundColor:s.color,width:`${Math.min(100,Math.max(1,s.value/c*100))}%`}})}),e("span",{style:n.phaseValue,children:N(s.value)})]},s.label))})};const V=()=>e("div",{style:n.bodyDeferred});const w=({title:i,icon:t,children:c,defaultOpen:d=false,count:s})=>{const[a,u]=q(d);return o("div",{style:n.collapsibleSection,children:[o("button",{type:"button",style:n.collapsibleHeader,onClick:()=>u(!a),"aria-expanded":a,children:[o("span",{style:n.collapsibleTitle,children:[t,e("span",{style:n.collapsibleTitleText,children:i}),s!==void 0?e("span",{style:n.collapsibleCount,children:s}):null]}),a?e(W,{size:16,color:r.text.secondary}):e(H,{size:16,color:r.text.secondary})]}),a?e("div",{style:n.collapsibleContent,children:c}):null]})};const se=({url:i,operationName:t,graphqlVariables:c,requestClient:d})=>{const s=C=>{try{const h=new URL(C);const y=String(h.protocol||"");const S=String(h.host||"");const O=y==="https:";let f=String(h.pathname||"");if(d==="graphql"&&t){const b=_(t,c);f=`${f} (${b})`}else if(t){f=`${f} (${t})`}const x={};const g=h.searchParams;if(g&&typeof g.forEach==="function"){g.forEach((b,z)=>{x[z]=b})}return{protocol:y.replace(":",""),host:S,pathname:f,params:Object.keys(x).length>0?x:null,isSecure:O}}catch{return{protocol:"",host:i,pathname:"",params:null,isSecure:false}}};const a=J(()=>s(i),[i,d,t,c]);const[u,T]=q(false);return o("div",{style:n.urlBreakdown,children:[o("div",{style:n.urlRow,children:[a.isSecure?e(X,{size:12,color:r.semantic.success}):e(ee,{size:12,color:r.semantic.warning}),e("span",{style:n.urlDomain,children:a.host}),o("span",{style:n.urlProtocol,children:["(",a.protocol.toUpperCase(),")"]}),e(F,{value:i,buttonStyle:n.copyButton})]}),e("div",{style:n.urlPathRow,children:o("span",{style:n.urlPath,children:[a.pathname,a.params?o("span",{style:n.urlQueryString,children:["?",new URLSearchParams(a.params).toString()]}):null]})}),a.params?o("div",{style:n.queryParamsCollapsible,children:[o("button",{type:"button",style:n.queryParamsToggle,onClick:()=>T(!u),"aria-expanded":u,children:[e("span",{style:n.queryParamsToggleText,children:"Query Parameters"}),e("span",{style:{...n.collapsibleCount,flex:1,textAlign:"left"},children:Object.keys(a.params).length}),u?e(W,{size:14,color:r.text.secondary}):e(H,{size:14,color:r.text.secondary})]}),u?e(R,{title:"",data:a.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})};export const NetworkEventDetailView=U(function i({event:t,ignoredPatterns:c=oe,onTogglePattern:d=le,showBodies:s=true}){const a=t.status?K(t.status):null;const u=!t.status&&!t.error;const T=Q();const C=t.requestData===void 0&&(t.requestBodyOmitted===true||(t.requestSize??0)>0);const h=t.responseData===void 0&&(t.responseBodyOmitted===true||(t.responseSize??0)>0);const y=t.headersOmitted===true;const[S,O]=q(null);const[f,x]=q(false);G(()=>{O(null);if(!T||!C&&!h&&!y){x(false);return}let l=false;x(true);T(t.id).then(m=>{if(!l)O(m)}).catch(()=>{}).finally(()=>{if(!l)x(false)});return()=>{l=true}},[t.id,T,C,h,y]);const g=t.requestData??S?.requestData??void 0;const b=t.responseData??S?.responseData??void 0;const z=(y?S?.requestHeaders:void 0)??t.requestHeaders;const M=(y?S?.responseHeaders:void 0)??t.responseHeaders;const j=()=>{const l={method:t.method,url:t.url,status:t.status,statusText:t.statusText,timestamp:new Date(t.timestamp).toISOString(),duration:t.duration?`${t.duration}ms`:"N/A",requestHeaders:z,requestData:g,responseHeaders:M,responseData:b,requestSize:t.requestSize?k(t.requestSize):"N/A",responseSize:t.responseSize?k(t.responseSize):"N/A",error:t.error,client:t.requestClient};return`# Network Request Details
1
+ "use strict";import{memo as U,useEffect as G,useMemo as J,useState as q}from"react";import{formatGraphQLDisplay as _}from"../utils/formatGraphQLVariables";import{useNetworkBodyResolver as Q}from"../sync/networkBodyResolver";import{DataViewer as R,InlineCopyButton as F}from"./DataViewer.web";import{jsx as e,jsxs as o,Fragment as A}from"react/jsx-runtime";const r={background:{base:"#0A0A0C",card:"#1A1A1C",hover:"#1D1D1F",input:"#26262A"},border:{default:"#2D2D2F"},text:{primary:"#F5F5F7",secondary:"#A1A1A6",muted:"#8E8E93"},semantic:{success:"#34C759",error:"#FF453A",errorBackground:"rgba(255, 69, 58, 0.15)",warning:"#FFEB3B",warningBackground:"rgba(255, 235, 59, 0.15)",info:"#00B8E6",infoBackground:"rgba(0, 184, 230, 0.1)"}};const $=r.semantic.success;function k(i){if(i===void 0||i===null)return"N/A";if(i===0)return"0 B";const t=1024;const c=["B","KB","MB","GB","TB"];const d=Math.floor(Math.log(i)/Math.log(t));return`${(i/Math.pow(t,d)).toFixed(1)} ${c[d]}`}function N(i){if(i===void 0||i===null)return"N/A";if(i<1e3)return`${i}ms`;if(i<6e4)return`${(i/1e3).toFixed(1)}s`;if(i<36e5){const d=Math.floor(i/6e4);const s=Math.floor(i%6e4/1e3);return s>0?`${d}m ${s}s`:`${d}m`}const t=Math.floor(i/36e5);const c=Math.floor(i%36e5/6e4);return c>0?`${t}h ${c}m`:`${t}h`}function Y(i,t=Date.now()){const c=i instanceof Date?i.getTime():i;const d=Math.floor((t-c)/1e3);if(d<0)return"just now";if(d<60)return d===0?"just now":`${d}s ago`;const s=Math.floor(d/60);if(s<60)return`${s}m ago`;const a=Math.floor(s/60);if(a<24)return`${a}h ago`;const u=Math.floor(a/24);return`${u}d ago`}function K(i){if(i>=100&&i<200){return{text:String(i),color:r.semantic.info,meaning:"Informational"}}if(i>=200&&i<300){const t={200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content"};return{text:String(i),color:r.semantic.success,meaning:t[i]||"Success"}}if(i>=300&&i<400){const t={301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect"};return{text:String(i),color:r.semantic.warning,meaning:t[i]||"Redirect"}}if(i>=400&&i<500){const t={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",408:"Request Timeout",409:"Conflict",410:"Gone",422:"Unprocessable Entity",429:"Too Many Requests"};return{text:String(i),color:r.semantic.error,meaning:t[i]||"Client Error"}}if(i>=500){const t={500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"};return{text:String(i),color:r.semantic.error,meaning:t[i]||"Server Error"}}return{text:String(i),color:r.text.muted,meaning:"Unknown"}}function p({size:i=14,color:t="currentColor",children:c}){return e("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},children:c})}const L=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("polyline",{points:"12 6 12 12 16 14"})]});const P=i=>o(p,{...i,children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"17 8 12 3 7 8"}),e("line",{x1:"12",x2:"12",y1:"3",y2:"15"})]});const E=i=>o(p,{...i,children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"7 10 12 15 17 10"}),e("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]});const Z=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),e("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]});const H=i=>e(p,{...i,children:e("path",{d:"m6 9 6 6 6-6"})});const W=i=>e(p,{...i,children:e("path",{d:"m18 15-6-6-6 6"})});const X=i=>o(p,{...i,children:[e("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),e("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]});const ee=i=>o(p,{...i,children:[e("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),e("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]});const v=i=>o(p,{...i,children:[e("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),e("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),e("path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1"}),e("path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1"})]});const te=i=>e(p,{...i,children:e("polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"})});const ne=i=>o(p,{...i,children:[e("circle",{cx:"12",cy:"12",r:"10"}),e("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),e("path",{d:"M2 12h20"})]});const re=i=>o(p,{...i,children:[e("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),e("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]});const ie=i=>o(p,{...i,children:[e("path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2"}),e("path",{d:"M8.5 2h7"}),e("path",{d:"M7 16h10"})]});const oe=new Set;const le=()=>{};const ae=({timings:i,total:t})=>{const c=Math.max(1,t);const d=[{label:"Waiting (TTFB)",hint:"incl. queue, DNS, TLS",value:i.ttfb,color:r.semantic.warning},{label:"Content download",hint:void 0,value:i.download,color:r.semantic.success}];return e("div",{style:n.phaseList,children:d.map(s=>o("div",{style:n.phaseRow,children:[o("div",{style:n.phaseLabelGroup,children:[e("div",{style:n.phaseLabel,children:s.label}),s.hint?e("div",{style:n.phaseHint,children:s.hint}):null]}),e("div",{style:n.phaseTrack,children:e("div",{style:{...n.phaseBar,backgroundColor:s.color,width:`${Math.min(100,Math.max(1,s.value/c*100))}%`}})}),e("span",{style:n.phaseValue,children:N(s.value)})]},s.label))})};const V=()=>e("div",{style:n.bodyDeferred});const w=({title:i,icon:t,children:c,defaultOpen:d=false,count:s})=>{const[a,u]=q(d);return o("div",{style:n.collapsibleSection,children:[o("button",{type:"button",style:n.collapsibleHeader,onClick:()=>u(!a),"aria-expanded":a,children:[o("span",{style:n.collapsibleTitle,children:[t,e("span",{style:n.collapsibleTitleText,children:i}),s!==void 0?e("span",{style:n.collapsibleCount,children:s}):null]}),a?e(W,{size:16,color:r.text.secondary}):e(H,{size:16,color:r.text.secondary})]}),a?e("div",{style:n.collapsibleContent,children:c}):null]})};const se=({url:i,operationName:t,graphqlVariables:c,requestClient:d})=>{const s=C=>{try{const h=new URL(C);const y=String(h.protocol||"");const S=String(h.host||"");const O=y==="https:";let f=String(h.pathname||"");if(d==="graphql"&&t){const b=_(t,c);f=`${f} (${b})`}else if(t){f=`${f} (${t})`}const x={};const g=h.searchParams;if(g&&typeof g.forEach==="function"){g.forEach((b,z)=>{x[z]=b})}return{protocol:y.replace(":",""),host:S,pathname:f,params:Object.keys(x).length>0?x:null,isSecure:O}}catch{return{protocol:"",host:i,pathname:"",params:null,isSecure:false}}};const a=J(()=>s(i),[i,d,t,c]);const[u,T]=q(false);return o("div",{style:n.urlBreakdown,children:[o("div",{style:n.urlRow,children:[a.isSecure?e(X,{size:12,color:r.semantic.success}):e(ee,{size:12,color:r.semantic.warning}),e("span",{style:n.urlDomain,children:a.host}),o("span",{style:n.urlProtocol,children:["(",a.protocol.toUpperCase(),")"]}),e(F,{value:i,buttonStyle:n.copyButton})]}),e("div",{style:n.urlPathRow,children:o("span",{style:n.urlPath,children:[a.pathname,a.params?o("span",{style:n.urlQueryString,children:["?",new URLSearchParams(a.params).toString()]}):null]})}),a.params?o("div",{style:n.queryParamsCollapsible,children:[o("button",{type:"button",style:n.queryParamsToggle,onClick:()=>T(!u),"aria-expanded":u,children:[e("span",{style:n.queryParamsToggleText,children:"Query Parameters"}),e("span",{style:{...n.collapsibleCount,flex:1,textAlign:"left"},children:Object.keys(a.params).length}),u?e(W,{size:14,color:r.text.secondary}):e(H,{size:14,color:r.text.secondary})]}),u?e(R,{title:"",data:a.params,showTypeFilter:true,rawMode:true,initialExpanded:true}):null]}):null]})};export const NetworkEventDetailView=U(function i({event:t,ignoredPatterns:c=oe,onTogglePattern:d=le,showBodies:s=true}){const a=t.status?K(t.status):null;const u=!t.status&&!t.error;const T=Q();const C=t.requestData===void 0&&(t.requestBodyOmitted===true||(t.requestSize??0)>0);const h=t.responseData===void 0&&(t.responseBodyOmitted===true||(t.responseSize??0)>0);const y=t.headersOmitted===true;const[S,O]=q(null);const[f,x]=q(false);G(()=>{O(null);if(!T||!C&&!h&&!y){x(false);return}let l=false;x(true);T(t.id).then(m=>{if(!l)O(m)}).catch(()=>{}).finally(()=>{if(!l)x(false)});return()=>{l=true}},[t.id,T,C,h,y]);const g=t.requestData??S?.requestData??void 0;const b=t.responseData!==void 0?t.responseData:S?.responseData;const z=(y?S?.requestHeaders:void 0)??t.requestHeaders;const M=(y?S?.responseHeaders:void 0)??t.responseHeaders;const j=()=>{const l={method:t.method,url:t.url,status:t.status,statusText:t.statusText,timestamp:new Date(t.timestamp).toISOString(),duration:t.duration?`${t.duration}ms`:"N/A",requestHeaders:z,requestData:g,responseHeaders:M,responseData:b,requestSize:t.requestSize?k(t.requestSize):"N/A",responseSize:t.responseSize?k(t.responseSize):"N/A",error:t.error,client:t.requestClient};return`# Network Request Details
2
2
 
3
3
  ## Request
4
4
  - **Method:** ${l.method}