import{k as P,t as F}from"./chunk-5T3OVTF5.js";import{a as N}from"./chunk-Q7BOSHWX.js";import{a as T}from"./chunk-H7PNMMDO.js";import{M as H,O as q,o as $,va as d,xa as h}from"./chunk-2HZMOK4U.js";import{a as x}from"./chunk-J3KRY2SD.js";import{P as v,x as I,y as L}from"./chunk-E24W34C4.js";import{d as l}from"./chunk-ELIH6GCC.js";import{Fb as C,Hb as U,Pb as c}from"./chunk-EYDNSYYE.js";import{u as O}from"./chunk-JCNRQYRP.js";import{g as p}from"./chunk-VKWPEFWQ.js";p();p();function D(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e.replaceTemplates??[]))t.append(`replace_templates[${r}]`,o);for(let[r,o]of Object.entries(e.replaceExtensionTemplates??[])){let n=r.split("/")[0];t.append(`replace_extension_templates[${n}][${r}]`,o)}return t.append("_method",e.method),t}function w(){return{"User-Agent":`Shopify CLI; v=${x}`}}function k(e){return delete e.cookie,delete e.authorization,e}p();function S(e){let t={};return e.split(";").forEach(r=>{let o=r.match(/(.*?)=(.*)$/)??[],n=o[1]?.trim(),s=o[2]?.trim()??"";n&&(t[n]=s)}),t}function E(e){return Object.entries(e).map(([t,r])=>`${t}=${r}`).join("; ")}var y=class extends l{};async function Re(e){return F(e)}async function be(e,t,r){let o=M(t),n=new URLSearchParams;n.append("form_type","storefront_password"),n.append("utf8","\u2713"),n.append("password",e??""),h("theme-service:storefront-session:check-storefront-password");let s={"cache-control":"no-cache","content-type":"application/x-www-form-urlencoded",...r},a=await $(`${o}/password`,{headers:s,body:n.toString(),method:"POST",redirect:"manual"});if(a.status===429)throw d(new l(`Too many incorrect password attempts. Please try again after ${a.headers.get("retry-after")} seconds.`));return B(a,o)}async function j(e,t,r,o,n={}){let s={},a=await G(e,r,n),i=M(t);if(s._shopify_essential=a,h(`theme-service:storefront-session:is-password-protected:${!!o}`),!o)return s;let u=await ee(a,e,i,o,n);return{...s,...u}}async function G(e,t,r,o=1){let n=new URLSearchParams({preview_theme_id:t,_fd:"0",pb:"0"}),s=`${e}?${n}`;h("theme-service:storefront-session:get-session-essential-cookie");let a={...r,...w()},i=await $(s,{method:"HEAD",redirect:"manual",headers:a}),u=i.headers.raw()["set-cookie"]??[],f=_(u,"_shopify_essential");if(!f){if(c(`Failed to obtain _shopify_essential cookie.

       -Request ID: ${i.headers.get("x-request-id")??"unknown"}

       -Body: ${await i.text()}

       -Status: ${i.status}
`),o>3)throw d(new y('Your development session could not be created because the "_shopify_essential" could not be defined. Please, check your internet connection.'));return c("Retrying to obtain the _shopify_essential cookie..."),await v(o),G(e,t,r,o+1)}return f}async function ee(e,t,r,o,n){let s=new URLSearchParams({password:o}),a={...n,...w(),Cookie:E({_shopify_essential:e})},i=await $(`${t}/password`,{method:"POST",redirect:"manual",body:s,headers:a});if(!B(i,r))throw d(new l("Your development session could not be created because the store password is invalid. Please, retry with a different password."));let u=i.headers.raw()["set-cookie"]??[],f=_(u,"storefront_digest"),m=_(u,"_shopify_essential"),g={};return f&&(g.storefront_digest=f),m&&(g._shopify_essential=m),g}function B(e,t){let r=e.headers.get("location")??"",o;try{o=new URL(r,t)}catch(s){if(s instanceof TypeError)return!1;throw s}let n=new URL(t).origin;return e.status===302&&o.origin===n}function _(e,t){let r=e.find(n=>S(n)[t]);return r?S(r)[t]:void 0}function M(e){return`https://${e}`}p();p();function te(e,t){d(t),t instanceof l?(t.message=`${e}
${t.message}`,L(t)):(I({headline:e,body:t.message}),c(`${e}
${t.stack??t.message}`))}function Oe(e,t){let r={delete:`Failed to delete file "${e}" from remote theme.`,upload:`Failed to upload file "${e}" to remote theme.`,default:e}[t??"default"]??e;return o=>{te(r,o)}}function R(e,t){return N({status:e.status??502,statusText:e.statusText??"Bad Gateway",cause:e,data:{url:(t??e.url)?.toString(),requestId:e.headers?.get("x-request-id")??void 0}})}function Ue(e,t="Unexpected error during fetch"){let r=e,o=r.statusCode??502,n=r.statusMessage??"Bad Gateway",s=`${t.replace(/\.$/,"")} with status ${o} (${n}).`;r.data?.requestId&&(s+=`
Request ID: ${r.data.requestId}`),r.data?.url&&(s+=`
URL: ${r.data.url}`);let a=r.cause??e;return{headline:s,body:a.stack??r.stack??r.message??n,status:o,statusText:n,cause:a,requestId:r.data?.requestId,url:r.data?.url}}async function ze(e,t){let r=se(e,t),n={...await re(e,t),...w()},s,a=Object.keys({...t.replaceTemplates,...t.replaceExtensionTemplates});if(a.length>0){c(`\u2192 Rendering ${r} (with ${a})...`);let m=D(t);s=await fetch(r,{method:"POST",body:m,redirect:"manual",headers:n}).catch(g=>{throw R(d(g),r)})}else c(`\u2192 Rendering ${r}...`),s=await fetch(r,{method:t.method,redirect:"manual",headers:n}).catch(m=>{throw R(d(m),r)});let i=s.headers.get("x-request-id");c(`\u2190 ${s.status} (request_id: ${i})`);let f=s.headers.get("Content-Type")?.includes("application/json");return s=new Response(s.body,s),f||s.headers.delete("Content-Type"),s}async function re(e,t){return W(e)?ne(e,t):oe(e,t)}async function oe(e,t){let r=await z(e,t),o=e.storefrontToken;return k({...t.headers,...e.crawlerSignatureHeaders,Authorization:`Bearer ${o}`,Cookie:r})}async function ne(e,t){let r=await z(e,t),o=e.storefrontToken,n={},s=["ACCEPT","CONTENT-TYPE","CONTENT-LENGTH"];for(let[a,i]of Object.entries(t.headers))s.includes(a.toUpperCase())&&(n[a]=i);return k({...n,...ae(e),...e.crawlerSignatureHeaders,Authorization:`Bearer ${o}`,Cookie:r})}function z(e,t){let r=S(t.headers.cookie??t.headers.Cookie??""),o=e.sessionCookies??{};return E({...r,...o})}function se(e,{path:t,sectionId:r,appBlockId:o,query:n}){let a=`${b(e)}${t}`,i=new URLSearchParams({_fd:"0",pb:"0"});for(let[u,f]of n)i.append(u,f);return r?i.append("section_id",r):o&&i.append("app_block_id",o),`${a}?${i}`}function b(e){return W(e)?`https://${O()}/cli/sfr`:`https://${e.storeFqdn}`}function W(e){return e.token.startsWith("shptka_")}function ae(e){return{"X-Shopify-Shop":e.storeFqdn,"X-Shopify-Access-Token":e.token}}p();var A="Shopify CLI",ie=720*60*60,V=["Signature","Signature-Input","Signature-Agent"],X="unstable",ce=`
  query StorefrontCrawlerSignatures($first: Int!, $expired: Boolean, $cli: Boolean, $domain: String) {
    storefrontCrawlerSignatures(first: $first, expired: $expired, cli: $cli, domain: $domain) {
      edges {
        node {
          id
          name
          domainHost
          signature
          signatureInput
          signatureAgent
          expiresAt
        }
      }
    }
  }
`,ue=`
  mutation StorefrontCrawlerSignatureGenerate($timeToLive: Int!, $name: String!, $domainHost: String!, $cli: Boolean) {
    storefrontCrawlerSignatureGenerate(timeToLive: $timeToLive, name: $name, domainHost: $domainHost, cli: $cli) {
      id
      signature
      signatureInput
      signatureAgent
      name
      expiresAt
      domainHost
      userErrors {
        field
        message
        code
      }
    }
  }
`;async function Q(e,t=e.storeFqdn){try{let o=(await T(ce,e,{first:1,expired:!1,cli:!0,domain:t},X)).storefrontCrawlerSignatures;if(!o)throw d(new l("Could not fetch Shopify CLI crawler signatures."));let n=o.edges[0]?.node;if(n){h("theme-service:crawler-signature:reused");let u=K(n);return c(`Reusing crawler signature "${A}" for ${n.domainHost} (${Y(u)}).`),u}let a=(await T(ue,e,{timeToLive:ie,name:A,domainHost:t,cli:!0},X)).storefrontCrawlerSignatureGenerate;if(!a)throw d(new l("Could not create a Shopify CLI crawler signature."));if(a.userErrors.length>0){let u=a.userErrors.map(f=>{let m=f.field?.join(".");return m?`${m}: ${f.message}`:f.message}).join(`
`);throw d(new l("Could not create a Shopify CLI crawler signature.",u))}h("theme-service:crawler-signature:created");let i=K(a);return c(`Created crawler signature "${A}" for ${a.domainHost} expiring at ${a.expiresAt} (${Y(i)}).`),i}catch(r){let o=r instanceof Error?r.message:String(r);c(`Could not obtain crawler signature headers; continuing without them. ${o}`);return}}function Y(e){let t=Object.keys(e),r=V.filter(n=>t.some(s=>s.toLowerCase()===n.toLowerCase())),o=V.filter(n=>!r.includes(n));return`present: ${r.join(", ")||"none"}; missing: ${o.join(", ")||"none"}`}function K(e){if(!e.signature||!e.signatureInput||!e.signatureAgent)throw d(new l("The Shopify CLI crawler signature response did not include all required headers."));return{Signature:e.signature,"Signature-Input":e.signatureInput,"Signature-Agent":e.signatureAgent}}p();var de=1800*1e3,J=["layout/theme.liquid","config/settings_schema.json"];async function ct(e,t,r,o,n){let s=await Z(e,t,r,o,n);return s.refresh=async()=>{c("Refreshing theme session...");let a=await Z(e,t,r,o,s.crawlerSignatureHeaders);return h("theme-service:session:refreshed"),Object.assign(s,a),a},setInterval(()=>{s.refresh&&s.refresh().then(()=>c("Refreshed theme session via auto-refresher...")).catch(()=>c("Session could not be refreshed."))},de),s}async function Z(e,t,r,o,n){let s=b(t),a=n??await Q(t),i=await q(t.storeFqdn,r,[],{forceRefresh:!1,noPrompt:!0}),u=await H([],r,{forceRefresh:!1,noPrompt:!0}),f=await fe(s,e,t,u,o,a);return{...i,sessionCookies:f,storefrontToken:u,crawlerSignatureHeaders:a}}async function fe(e,t,r,o,n,s){try{return await j(e,r.storeFqdn,t,n,{"X-Shopify-Shop":r.storeFqdn,"X-Shopify-Access-Token":r.token,Authorization:`Bearer ${o}`,...s})}catch(a){throw a instanceof y&&await pe(t,r),a}}async function pe(e,t){if(c(`Verifying if theme with id ${e} has required files...`),(await P(Number(e),J,t)).length!==J.length)throw d(new l(U`Theme ${C.cyan(e)} is missing required files. Run ${C.cyan(`shopify theme delete -t ${e}`)} to delete it, then try your command again.`.value));c(`Theme with id ${e} has required files.`)}export{w as a,k as b,Re as c,be as d,te as e,Oe as f,R as g,Ue as h,ze as i,re as j,z as k,b as l,Q as m,ct as n,Z as o};
