import*as Common from"../../../core/common/common.js";import*as Host from"../../../core/host/host.js";import*as i18n from"../../../core/i18n/i18n.js";import*as Platform from"../../../core/platform/platform.js";import*as Root from"../../../core/root/root.js";import*as SDK from"../../../core/sdk/sdk.js";import*as Persistence from"../../../models/persistence/persistence.js";import*as Workspace from"../../../models/workspace/workspace.js";import*as NetworkForward from"../../../panels/network/forward/forward.js";import*as Buttons from"../../../ui/components/buttons/buttons.js";import*as ComponentHelpers from"../../../ui/components/helpers/helpers.js";import*as IconButton from"../../../ui/components/icon_button/icon_button.js";import*as Input from"../../../ui/components/input/input.js";import*as LegacyWrapper from"../../../ui/components/legacy_wrapper/legacy_wrapper.js";import*as UI from"../../../ui/legacy/legacy.js";import*as LitHtml from"../../../ui/lit-html/lit-html.js";import*as Sources from"../../sources/sources.js";import{RequestHeaderSection}from"./RequestHeaderSection.js";import{ResponseHeaderSection,RESPONSE_HEADER_SECTION_DATA_KEY}from"./ResponseHeaderSection.js";import requestHeadersViewStyles from"./RequestHeadersView.css.js";const RAW_HEADER_CUTOFF=3e3,{render:render,html:html}=LitHtml,UIStrings={fromDiskCache:"(from disk cache)",fromMemoryCache:"(from memory cache)",fromPrefetchCache:"(from prefetch cache)",fromServiceWorker:"(from `service worker`)",fromSignedexchange:"(from signed-exchange)",fromWebBundle:"(from Web Bundle)",general:"General",raw:"Raw",referrerPolicy:"Referrer Policy",remoteAddress:"Remote Address",requestHeaders:"Request Headers",requestMethod:"Request Method",requestUrl:"Request URL",responseHeaders:"Response Headers",revealHeaderOverrides:"Reveal header override definitions",showMore:"Show more",statusCode:"Status Code"},str_=i18n.i18n.registerUIStrings("panels/network/components/RequestHeadersView.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class RequestHeadersView extends LegacyWrapper.LegacyWrapper.WrappableComponent{#e;static litTagName=LitHtml.literal`devtools-request-headers`;#t=this.attachShadow({mode:"open"});#s=!1;#r=!1;#o=!1;#i=!1;#n=void 0;#a=Workspace.Workspace.WorkspaceImpl.instance();constructor(e){super(),this.#e=e}wasShown(){this.#e.addEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this.#d,this),this.#e.addEventListener(SDK.NetworkRequest.Events.FinishedLoading,this.#d,this),this.#e.addEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this.#d,this),this.#e.addEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this.#h,this),this.#n=void 0,this.#d()}willHide(){this.#e.removeEventListener(SDK.NetworkRequest.Events.RemoteAddressChanged,this.#d,this),this.#e.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading,this.#d,this),this.#e.removeEventListener(SDK.NetworkRequest.Events.RequestHeadersChanged,this.#d,this),this.#e.removeEventListener(SDK.NetworkRequest.Events.ResponseHeadersChanged,this.#h,this)}#h(){this.#e.deleteAssociatedData(RESPONSE_HEADER_SECTION_DATA_KEY),this.render()}#d(){this.render()}revealHeader(e,t){this.#n={section:e,header:t},this.render()}connectedCallback(){this.#t.adoptedStyleSheets=[requestHeadersViewStyles],this.#a.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this.#l,this),this.#a.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this.#l,this),Common.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled").addChangeListener(this.render,this)}disconnectedCallback(){this.#a.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded,this.#l,this),this.#a.removeEventListener(Workspace.Workspace.Events.UISourceCodeRemoved,this.#l,this),Common.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled").removeChangeListener(this.render,this)}#l(e){this.#c()===e.data.url()&&this.render()}async render(){this.#e&&render(html`
      ${this.#u()}
      ${this.#m()}
      ${this.#g()}
    `,this.#t,{host:this})}#m(){if(!this.#e)return LitHtml.nothing;return html`
      <${Category.litTagName}
        @togglerawevent=${()=>{this.#s=!this.#s,this.render()}}
        .data=${{name:"responseHeaders",title:i18nString(UIStrings.responseHeaders),headerCount:this.#e.sortedResponseHeaders.length,checked:this.#e.responseHeadersText?this.#s:void 0,additionalContent:this.#p(),forceOpen:this.#n?.section===NetworkForward.UIRequestLocation.UIHeaderSection.Response}}
        aria-label=${i18nString(UIStrings.responseHeaders)}
      >
        ${this.#s?this.#S(this.#e.responseHeadersText,!0):html`
          <${ResponseHeaderSection.litTagName} .data=${{request:this.#e,toReveal:this.#n}}></${ResponseHeaderSection.litTagName}>
        `}
      </${Category.litTagName}>
    `}#p(){if(!Root.Runtime.experiments.isEnabled(Root.Runtime.ExperimentName.HEADER_OVERRIDES)||!this.#a.uiSourceCodeForURL(this.#c()))return LitHtml.nothing;const e=Common.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled"),t=html`
      <${IconButton.Icon.Icon.litTagName} class=${e.get()?"inline-icon dot purple":"inline-icon"} .data=${{iconName:"document",color:"var(--icon-default)",width:"16px",height:"16px"}}>
      </${IconButton.Icon.Icon.litTagName}>`;return html`
      <x-link href="https://goo.gle/devtools-override" class="link devtools-link">
        <${IconButton.Icon.Icon.litTagName} class="inline-icon" .data=${{iconName:"help",color:"var(--icon-link)",width:"16px",height:"16px"}}>
        </${IconButton.Icon.Icon.litTagName}
      ></x-link>
      <x-link @click=${e=>{e.preventDefault();const t=this.#a.uiSourceCodeForURL(this.#c());t&&(Sources.SourcesPanel.SourcesPanel.instance().showUISourceCode(t),Sources.SourcesPanel.SourcesPanel.instance().revealInNavigator(t))}} class="link devtools-link" title=${UIStrings.revealHeaderOverrides}>
        ${t}${Persistence.NetworkPersistenceManager.HEADERS_FILENAME}
      </x-link>
    `}#c(){if(!this.#e)return Platform.DevToolsPath.EmptyUrlString;const e=Persistence.NetworkPersistenceManager.NetworkPersistenceManager.instance().fileUrlFromNetworkUrl(this.#e.url(),!0);return e.substring(0,e.lastIndexOf("/"))+"/"+Persistence.NetworkPersistenceManager.HEADERS_FILENAME}#g(){if(!this.#e)return LitHtml.nothing;const e=this.#e.requestHeadersText();return html`
      <${Category.litTagName}
        @togglerawevent=${()=>{this.#r=!this.#r,this.render()}}
        .data=${{name:"requestHeaders",title:i18nString(UIStrings.requestHeaders),headerCount:this.#e.requestHeaders().length,checked:e?this.#r:void 0,forceOpen:this.#n?.section===NetworkForward.UIRequestLocation.UIHeaderSection.Request}}
        aria-label=${i18nString(UIStrings.requestHeaders)}
      >
        ${this.#r&&e?this.#S(e,!1):html`
          <${RequestHeaderSection.litTagName} .data=${{request:this.#e,toReveal:this.#n}}></${RequestHeaderSection.litTagName}>
        `}
      </${Category.litTagName}>
    `}#S(e,t){const s=e.trim(),r=!(t?this.#o:this.#i)&&s.length>3e3,o=()=>{t?this.#o=!0:this.#i=!0,this.render()},i=e=>{if(!(t?this.#o:this.#i)){const t=new UI.ContextMenu.ContextMenu(e);t.newSection().appendItem(i18nString(UIStrings.showMore),o),t.show()}};return html`
      <div class="row raw-headers-row" on-render=${ComponentHelpers.Directives.nodeRenderedCallback((e=>{r&&e.addEventListener("contextmenu",i)}))}>
        <div class="raw-headers">${r?s.substring(0,3e3):s}</div>
        ${r?html`
          <${Buttons.Button.Button.litTagName}
            .size=${"SMALL"}
            .variant=${"secondary"}
            @click=${o}
          >${i18nString(UIStrings.showMore)}</${Buttons.Button.Button.litTagName}>
        `:LitHtml.nothing}
      </div>
    `}#u(){if(!this.#e)return LitHtml.nothing;const e=["status"];this.#e.statusCode<300||304===this.#e.statusCode?e.push("green-circle"):this.#e.statusCode<400?e.push("yellow-circle"):e.push("red-circle");let t="";this.#e.cachedInMemory()?t=i18nString(UIStrings.fromMemoryCache):this.#e.fetchedViaServiceWorker?t=i18nString(UIStrings.fromServiceWorker):this.#e.redirectSourceSignedExchangeInfoHasNoErrors()?t=i18nString(UIStrings.fromSignedexchange):this.#e.webBundleInnerRequestInfo()?t=i18nString(UIStrings.fromWebBundle):this.#e.fromPrefetchCache()?t=i18nString(UIStrings.fromPrefetchCache):this.#e.cached()&&(t=i18nString(UIStrings.fromDiskCache)),t&&e.push("status-with-comment");const s=[this.#e.statusCode,this.#e.statusText,t].join(" ");return html`
      <${Category.litTagName}
        .data=${{name:"general",title:i18nString(UIStrings.general),forceOpen:this.#n?.section===NetworkForward.UIRequestLocation.UIHeaderSection.General}}
        aria-label=${i18nString(UIStrings.general)}
      >
        ${this.#w(i18nString(UIStrings.requestUrl),this.#e.url())}
        ${this.#e.statusCode?this.#w(i18nString(UIStrings.requestMethod),this.#e.requestMethod):LitHtml.nothing}
        ${this.#e.statusCode?this.#w(i18nString(UIStrings.statusCode),s,e):LitHtml.nothing}
        ${this.#e.remoteAddress()?this.#w(i18nString(UIStrings.remoteAddress),this.#e.remoteAddress()):LitHtml.nothing}
        ${this.#e.referrerPolicy()?this.#w(i18nString(UIStrings.referrerPolicy),String(this.#e.referrerPolicy())):LitHtml.nothing}
      </${Category.litTagName}>
    `}#w(e,t,s){const r=this.#n?.section===NetworkForward.UIRequestLocation.UIHeaderSection.General&&e.toLowerCase()===this.#n?.header?.toLowerCase();return html`
      <div class="row ${r?"header-highlight":""}">
        <div class="header-name">${e}:</div>
        <div
          class="header-value ${s?.join(" ")}"
          @copy=${()=>Host.userMetrics.actionTaken(Host.UserMetrics.Action.NetworkPanelCopyValue)}
        >${t}</div>
      </div>
    `}}export class ToggleRawHeadersEvent extends Event{static eventName="togglerawevent";constructor(){super(ToggleRawHeadersEvent.eventName,{})}}export class Category extends HTMLElement{static litTagName=LitHtml.literal`devtools-request-headers-category`;#t=this.attachShadow({mode:"open"});#v;#R=Common.UIString.LocalizedEmptyString;#H=void 0;#q=void 0;#f=void 0;#k=void 0;connectedCallback(){this.#t.adoptedStyleSheets=[requestHeadersViewStyles,Input.checkboxStyles]}set data(e){this.#R=e.title,this.#v=Common.Settings.Settings.instance().createSetting("request-info-"+e.name+"-category-expanded",!0),this.#H=e.headerCount,this.#q=e.checked,this.#f=e.additionalContent,this.#k=e.forceOpen,this.#C()}#E(){this.dispatchEvent(new ToggleRawHeadersEvent)}#C(){const e=!this.#v||this.#v.get()||this.#k;render(html`
      <details ?open=${e} @toggle=${this.#I}>
        <summary class="header" @keydown=${this.#$}>
          <div class="header-grid-container">
            <div>
              ${this.#R}${void 0!==this.#H?html`<span class="header-count"> (${this.#H})</span>`:LitHtml.nothing}
            </div>
            <div class="hide-when-closed">
              ${void 0!==this.#q?html`
                <label><input type="checkbox" .checked=${this.#q} @change=${this.#E} />${i18nString(UIStrings.raw)}</label>
              `:LitHtml.nothing}
            </div>
            <div class="hide-when-closed">${this.#f}</div>
        </summary>
        <slot></slot>
      </details>
    `,this.#t,{host:this})}#$(e){if(!e.target)return;const t=e.target.parentElement;if(!t)throw new Error("<details> element is not found for a <summary> element");switch(e.key){case"ArrowLeft":t.open=!1;break;case"ArrowRight":t.open=!0}}#I(e){this.#v?.set(e.target.open)}}ComponentHelpers.CustomElements.defineComponent("devtools-request-headers",RequestHeadersView),ComponentHelpers.CustomElements.defineComponent("devtools-request-headers-category",Category);