@shopify/cli
Version:
A CLI tool to build for the Shopify platform
111 lines (107 loc) • 583 kB
JavaScript
import{a as Na}from"./chunk-FFQ5EWII.js";import{a as Sa,b as Tm}from"./chunk-PAP22IQO.js";import"./chunk-OLZHWPZP.js";import"./chunk-JXW374CL.js";import{a as Hm}from"./chunk-ZTMSBSYD.js";import{a as lm,b as pm,c as _x,d as hm,e as bx,f as Sx,g as ba,h as jm,i as Bm,j as zm,k as Wl,l as Hl,m as Wm}from"./chunk-HUIJMGVJ.js";import{a as $d}from"./chunk-AKML26N3.js";import"./chunk-URZPVSJZ.js";import{a as km,b as wm,c as _m}from"./chunk-EQU4MUQJ.js";import{a as pt,b as Bl}from"./chunk-6SF3ZETE.js";import"./chunk-3VZEETAV.js";import{a as dm,b as um,c as jl,d as cr,e as mm,f as pr,h as fm,l as dr,m as ya,n as Ze,s as Re,u as va,v as ka,w as wa}from"./chunk-IX5ICOBV.js";import{a as cm}from"./chunk-SXTMSGUE.js";import"./chunk-QFWIDATO.js";import{b as sm,g as ga,j as ql}from"./chunk-CBXSPL4W.js";import"./chunk-UJVH7FZS.js";import{b as Nm,c as Am}from"./chunk-E3EMHAJB.js";import"./chunk-UWJ73J4B.js";import{a as go,b as _i}from"./chunk-WFXRSKRK.js";import"./chunk-YOZNRLFC.js";import"./chunk-XEFQQPL4.js";import{a as mr,b as yo}from"./chunk-6WL4GA2M.js";import{a as vm,c as _a}from"./chunk-TYZXGSHO.js";import{a as bm,b as Sm}from"./chunk-ULFWK45W.js";import"./chunk-KHTV6PBV.js";import"./chunk-NKQBEFPS.js";import{a as Cm}from"./chunk-WDC3KIZT.js";import{a as im}from"./chunk-7NH7CHVI.js";import{a as Yu}from"./chunk-SIMFNECG.js";import{a as xa,b as Ex,c as Cx,d as Fm,e as Pm,f as Im,g as zl,h as Dm,i as Rm,j as Qt,k as ho,l as Nx,m as Ea,n as qm}from"./chunk-GZS44BUW.js";import"./chunk-K2WUCOQJ.js";import{a as Em,b as ur}from"./chunk-7QIOUDCX.js";import{b as xm,o as xx}from"./chunk-7MUKLZOL.js";import{a as ym}from"./chunk-VBUZWRUL.js";import{a as Um,b as Om,c as Lm,d as Mm,e as $m,f as Vm}from"./chunk-DCPBRWVC.js";import{a as gm}from"./chunk-KR6QDE7D.js";import{aa as wx}from"./chunk-UXVZ2P63.js";import"./chunk-QSTEVZFQ.js";import"./chunk-5Y7GIF2W.js";import{a as om,b as Xe,c as rm,d as am,e as Yt}from"./chunk-EKXY5COY.js";import{a as vx,b as lr,c as _e}from"./chunk-4DCQNGUV.js";import{a as Hu}from"./chunk-6ITDI2SD.js";import{a as zu}from"./chunk-2GK56X53.js";import"./chunk-KHSYW7I4.js";import"./chunk-4ZGSSQC6.js";import{a as Wu}from"./chunk-MCVRONUY.js";import"./chunk-2AJ5FI2K.js";import{a as Zu}from"./chunk-KZOBF55B.js";import{a as Xu}from"./chunk-C7BTJ32Z.js";import"./chunk-NMBBTTIH.js";import{a as tm}from"./chunk-M2ZHFKPN.js";import{a as nm}from"./chunk-6RE2SNCU.js";import"./chunk-OCOY5MV2.js";import{a as Lu}from"./chunk-67MH4AXG.js";import{a as qu}from"./chunk-4IC626OL.js";import{a as Vu}from"./chunk-UJXUSRQK.js";import{a as em}from"./chunk-DRFGABEB.js";import{a as ju}from"./chunk-MWY3A7O3.js";import{a as Qu}from"./chunk-Q4T2T2QE.js";import{a as Gu}from"./chunk-KN3WTTHZ.js";import{a as Bu}from"./chunk-76R52ODR.js";import"./chunk-M2D7USAX.js";import{a as Gm}from"./chunk-T542UQBY.js";import{a as Km}from"./chunk-XXVEHDVO.js";import{a as Q}from"./chunk-QA23HIH4.js";import{a as Px}from"./chunk-7ZT57XT7.js";import{d as Fx}from"./chunk-UYXEA3Y6.js";import{a as Ju}from"./chunk-5WVAHE5E.js";import{a as Mu}from"./chunk-6CYMJ76C.js";import{a as $u}from"./chunk-Q33IBIVJ.js";import"./chunk-ZGK3LGCH.js";import{c as tu}from"./chunk-QBSKKQBN.js";import{a as Ou}from"./chunk-FQWB2F75.js";import{$ as wn,A as Fl,G as ra,H as ao,I as so,K as Pl,L as Il,N as aa,R as gi,Z as rt,_ as kn,a as zd,aa as Jd,b as Wd,ba as Oe,c as Hd,ca as Xd,da as yi,e as Nl,ea as Zd,fa as rr,g as Al,ga as eu,h as na,j as R,ja as fu,ka as hu,l as Gd,la as gu,m as Kd,n as Ae,na as Rl,o as ia,oa as yu,p as Yd,pa,q as Qd,r as u,t as fi,ta as ku,u as oa,x as Tl,z as K}from"./chunk-XONFGLJQ.js";import"./chunk-4LNCYIS3.js";import{B as pu,C as du,D as uu,E as mu,f as sa,g as ou,i as ru,m as la,n as au,o as su,p as ar,s as lu,t as cu,w as vi,x as ca,y as Dl}from"./chunk-L2MGAEV3.js";import"./chunk-PRKBO42R.js";import"./chunk-ZSBA6VIC.js";import{a as Pt}from"./chunk-F2QU6WWX.js";import{a as Ht,b as hi}from"./chunk-XULPJ6UG.js";import{a as kx}from"./chunk-6HBRBQAN.js";import{a as Ku,b as T,c as Fe}from"./chunk-XR6GMMEU.js";import"./chunk-3TNEIDOD.js";import{c as Aa,d as Tx}from"./chunk-BS3BKORT.js";import{b as Gt}from"./chunk-MHWV5RQV.js";import{b as fo}from"./chunk-XOTA6JTZ.js";import"./chunk-MOA33ZFO.js";import{a as ut,c as yn,d as vn}from"./chunk-JUVAGMIH.js";import{A as De,B as Ge,C as co,D as xe,E as Me,F as Kt,G as Eu,H as Cu,I as wi,J as Rt,O as Ke,P as Nt,Q as Ml,R as fa,T as Tu,a as gn,b as Bd,f as vu,g as da,i as ki,j as lo,k as Le,l as je,m as ua,n as Ol,o as bu,p as _n,s as Su,t as ma,u as oe,v as j,w as He,x as Te,y as xu,z as Je}from"./chunk-6G6TMKXF.js";import"./chunk-P6XE4MH5.js";import"./chunk-KLMDWDT2.js";import"./chunk-5CH3B62S.js";import{a as yx}from"./chunk-QUTQDXSL.js";import{d as mt,e as wu,f as Ul}from"./chunk-WSDN25F5.js";import{b as Ll,c as Nu,d as g,f as de,g as M,l as Au}from"./chunk-M56NDIMD.js";import{a as vo,b as Ax}from"./chunk-7UYZQN4V.js";import"./chunk-Z35BTAM6.js";import"./chunk-75VPUOC5.js";import"./chunk-HZA6IAA4.js";import"./chunk-PD5ZHJWI.js";import{r as ke}from"./chunk-LDGAHMS7.js";import"./chunk-ZR76GGZ6.js";import"./chunk-EENHXSWU.js";import"./chunk-FUOIGXI4.js";import"./chunk-6M3ZYNGO.js";import"./chunk-QYR5VPQA.js";import{a as Ca}from"./chunk-S6EJHWJL.js";import{a as _u}from"./chunk-OBEWZXOQ.js";import{$ as Ct,$a as qe,Ab as nu,Ba as Pd,Bb as iu,Ca as Wt,Ea as Dt,Ga as oo,Gb as b,Hb as Be,Ib as w,Ja as Id,Ka as Dd,L as zt,La as Rd,Mb as J,N as Jr,Na as ea,Nb as q,O as bl,Oa as un,Ob as sr,P as Sl,Pa as Ud,Pb as po,Q as xl,Qb as S,Rb as se,Sb as uo,Ta as C,Tb as Sn,U as Nd,Ua as Se,Ub as Du,Va as Od,W as tr,Wa as re,Wb as mo,Xa as Ld,Xb as Ru,Y as te,Yb as Uu,Z as nr,ba as Xr,bb as mn,ca as ir,cb as Md,da as Zr,db as ta,ea as Ad,eb as ot,fa as no,fb as V,ga as Td,gb as N,ha as El,ib as Vd,jb as fn,ka as It,kb as hn,ma as P,mb as qd,na as ct,nb as jd,oa as or,pa as it,qa as dn,sa as Cl,tb as ve,ua as ie,ub as ro,va as Fd,wa as ae,ya as io}from"./chunk-N5PQPIBF.js";import"./chunk-CERXUPGC.js";import"./chunk-T4M5CWAO.js";import"./chunk-PRVQAHWI.js";import{a as Fu,d as Pu,e as ha,f as ft,j as bn,l as $l,m as Vl,n as Iu}from"./chunk-YTNDFQJT.js";import{a as Bt}from"./chunk-ULQG3XQS.js";import{d as k,e as Ne,f as he,g as z,h as Qr,i as H,j as $,k as pn,l as Ed,n as eo,p as mi,q as to,s as Cd,t as _l}from"./chunk-IU2ZQ6TE.js";import"./chunk-PIBY5DDZ.js";import{a as xd,e as O,g as l}from"./chunk-VPRTJUIN.js";l();var gx=O(kx(),1);l();l();l();l();var xn="7e9cb568cfd431c538f36d1ad3f2b4f6";var Ta="/auth/callback";function Ym(e){return`http://127.0.0.1:${e}${Ta}`}function fr(e){return`${xn}::${e}`}function ht(e){return e.length<=10?"***":`${e.slice(0,10)}***`}l();var Gl;function Kl(){return Gl??(Gl=new Gt({projectName:"shopify-cli-store"})),Gl}function gt(e){return typeof e=="string"}function Qm(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.id=="number")return{id:t.id,...gt(t.email)?{email:t.email}:{},...gt(t.firstName)?{firstName:t.firstName}:{},...gt(t.lastName)?{lastName:t.lastName}:{},...typeof t.accountOwner=="boolean"?{accountOwner:t.accountOwner}:{}}}function Ix(e){if(!e||typeof e!="object")return;let t=e;if(!(!gt(t.store)||!gt(t.clientId)||!gt(t.userId)||!gt(t.accessToken)||!Array.isArray(t.scopes)||!t.scopes.every(gt)||!gt(t.acquiredAt)))return{store:t.store,clientId:t.clientId,userId:t.userId,accessToken:t.accessToken,scopes:t.scopes,acquiredAt:t.acquiredAt,...gt(t.refreshToken)?{refreshToken:t.refreshToken}:{},...gt(t.expiresAt)?{expiresAt:t.expiresAt}:{},...gt(t.refreshTokenExpiresAt)?{refreshTokenExpiresAt:t.refreshTokenExpiresAt}:{},...Qm(t.associatedUser)?{associatedUser:Qm(t.associatedUser)}:{}}}function Yl(e,t){let n=fr(e),i=t.get(n);if(!i||typeof i!="object")return;let{sessionsByUserId:o,currentUserId:r}=i;if(!o||typeof o!="object"||Array.isArray(o)||typeof r!="string"){t.delete(n);return}let a=Object.fromEntries(Object.entries(o).flatMap(([s,c])=>{let d=Ix(c);return d?[[s,d]]:[]}));if(Object.keys(a).length!==Object.keys(o).length)if(a[r])t.set(n,{currentUserId:r,sessionsByUserId:a});else{t.delete(n);return}return{currentUserId:r,sessionsByUserId:a}}function Fa(e,t=Kl()){let n=Yl(e,t);if(!n)return;let i=n.sessionsByUserId[n.currentUserId];if(!i){t.delete(fr(e));return}return i}function Pa(e,t=Kl()){let n=fr(e.store),i=Yl(e.store,t),o={currentUserId:e.userId,sessionsByUserId:{...i?.sessionsByUserId??{},[e.userId]:e}};t.set(n,o)}function hr(e,t,n){let i=typeof t=="string"?t:void 0,o=(typeof t=="string"?n:t)??Kl(),r=fr(e);if(!i){o.delete(r);return}let a=Yl(e,o);if(!a)return;let{[i]:s,...c}=a.sessionsByUserId,d=Object.keys(c);if(d.length===0){o.delete(r);return}o.set(r,{currentUserId:a.currentUserId===i?d[0]:a.currentUserId,sessionsByUserId:c})}l();function Jm(e,t=300){return e.slice(0,t)}async function Xm(e){let t=`https://${e.store}/admin/oauth/access_token`;S(w`Exchanging authorization code for token at ${b.raw(t)}`);let n=await Ae(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:xn,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}),i=await n.text();if(!n.ok)throw S(w`Token exchange failed with HTTP ${b.raw(String(n.status))}: ${b.raw(Jm(i||n.statusText))}`),new g(`Failed to exchange OAuth code for an access token (HTTP ${n.status}).`,i||n.statusText);let o;try{o=JSON.parse(i)}catch{throw new g("Received an invalid token response from Shopify.")}return S(w`Token exchange succeeded: access_token=${b.raw(ht(o.access_token))}, refresh_token=${b.raw(o.refresh_token?ht(o.refresh_token):"none")}, expires_in=${b.raw(String(o.expires_in??"unknown"))}s, user=${b.raw(String(o.associated_user?.id??"unknown"))} (${b.raw(o.associated_user?.email??"no email")})`),o}async function Zm(e){let t=`https://${e.store}/admin/oauth/access_token`;S(w`Refreshing access token for ${b.raw(e.store)} using refresh_token=${b.raw(ht(e.refreshToken))}`);let n=await Ae(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:xn,grant_type:"refresh_token",refresh_token:e.refreshToken})}),i=await n.text();if(!n.ok)throw S(w`Token refresh failed with HTTP ${b.raw(String(n.status))}: ${b.raw(Jm(i||n.statusText))}`),new g(`Token refresh failed for ${e.store} (HTTP ${n.status}).`);let o;try{o=JSON.parse(i)}catch{throw new g("Received an invalid refresh response from Shopify.")}if(!o.access_token)throw new g(`Token refresh returned an invalid response for ${e.store}.`);return{accessToken:o.access_token,refreshToken:o.refresh_token,expiresIn:o.expires_in,refreshTokenExpiresIn:o.refresh_token_expires_in}}var Dx=`#graphql
query CurrentAppInstallationAccessScopes {
currentAppInstallation {
accessScopes {
handle
}
}
}
`;async function ef(e){S(w`Fetching current app installation scopes for ${b.raw(e.store)} using token ${b.raw(ht(e.accessToken))}`);let t=await rr({query:Dx,api:"Admin",url:Yt(e.store,"unstable"),token:e.accessToken,responseOptions:{handleErrors:!1}});if(!Array.isArray(t.currentAppInstallation?.accessScopes))throw new Error("Shopify did not return currentAppInstallation.accessScopes.");return t.currentAppInstallation.accessScopes.flatMap(n=>typeof n.handle=="string"?[n.handle]:[])}l();l();function Rx(e,t){return{command:`shopify store auth --store ${e} --scopes ${t}`}}function Ql(e,t){return[[Rx(e,t)]]}function tf(e){throw new g(`No stored app authentication found for ${e}.`,"To create stored auth for this store, run:",Ql(e,"<comma-separated-scopes>"))}function bi(e,t,n){throw new g(e,"To re-authenticate, run:",Ql(t,n))}function nf(e){return new g("OAuth callback store does not match the requested store.",`Shopify returned ${e} during authentication. Re-run using the permanent store domain:`,Ql(e,"<comma-separated-scopes>"))}import{timingSafeEqual as Ux}from"crypto";import{createServer as Ox}from"http";function of(e,t){let n=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),i=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${n}</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
background-color: rgb(10, 19, 20);
color: rgb(32, 34, 35);
}
body {
background: radial-gradient(53.91% 53.91% at 50% 22.36%, rgb(10, 19, 20) 50%, rgb(2, 9, 10) 100%);
min-height: 100vh;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 20px;
-webkit-font-smoothing: antialiased;
}
.page-main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.header {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.card {
background: #fff;
border-radius: 24px;
box-shadow: rgba(26, 26, 26, 0.24) 0px 12px 20px -8px,
rgba(204, 204, 204, 0.5) 0px 1px 0px 0px inset,
rgba(0, 0, 0, 0.17) 0px -1px 0px 0px inset,
rgba(0, 0, 0, 0.13) -1px 0px 0px 0px inset,
rgba(0, 0, 0, 0.13) 1px 0px 0px 0px inset;
max-width: 476px;
width: calc(100% - 2rem);
margin-top: 28px;
padding: 40px;
}
h1 {
font-size: 24px;
font-weight: 600;
line-height: 28.8px;
color: rgb(32, 34, 35);
margin-bottom: 12px;
}
p {
font-size: 14px;
line-height: 20px;
color: rgb(109, 113, 117);
}
</style>
</head>
<body>
<div class="page-main">
<header class="header"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 28" width="80" height="90"><path fill="#95BF47" fill-rule="evenodd" d="M17.836 27.059l-.062-23.736c-.16-.16-.472-.112-.594-.076l-.813.252a5.675 5.675 0 00-.39-.957c-.576-1.1-1.42-1.682-2.44-1.683h-.003c-.068 0-.136.006-.204.012h-.008a2.234 2.234 0 00-.092-.105C12.786.29 12.216.059 11.533.079c-1.318.038-2.63.99-3.693 2.679-.75 1.19-1.318 2.683-1.48 3.84L3.767 7.4c-.764.24-.788.263-.888.982C2.803 8.928.806 24.377.806 24.377l16.743 2.895.287-.213zM12.35 1.163a1.347 1.347 0 00-.792-.208c-2.033.06-3.807 3.235-4.26 5.352l1.949-.604.347-.107c.255-1.344.896-2.738 1.733-3.636a3.821 3.821 0 011.023-.797zm-1.793 4.135l2.796-.866c.009-.728-.07-1.805-.435-2.565-.388.16-.715.44-.95.691-.628.675-1.14 1.705-1.41 2.74zM14.23 4.16l1.299-.403c-.208-.674-.7-1.805-1.7-1.994.311.802.391 1.73.4 2.397z" clip-rule="evenodd"/><path fill="#5E8E3E" d="M21.587 5.088c-.099-.008-2.035-.037-2.035-.037s-1.619-1.573-1.778-1.733a.399.399 0 00-.225-.103v24.053l7.256-1.804S21.844 5.447 21.825 5.31a.263.263 0 00-.238-.222z"/><path fill="#fff" d="M13.528 8.824l-.843 3.153s-.94-.429-2.054-.358c-1.635.103-1.652 1.134-1.636 1.392.09 1.41 3.799 1.718 4.008 5.021.163 2.599-1.379 4.376-3.601 4.516-2.667.169-4.135-1.405-4.135-1.405l.565-2.404s1.478 1.115 2.66 1.04c.773-.048 1.05-.677 1.021-1.121-.116-1.84-3.137-1.731-3.328-4.754-.16-2.544 1.51-5.12 5.196-5.353 1.42-.09 2.147.273 2.147.273"/></svg></header>
<main class="card">
<h1>${n}</h1>
<p>${i}</p>
</main>
</div>
</body>
</html>`}async function rf({store:e,state:t,port:n,timeoutMs:i=300*1e3,onListening:o}){let r=K(e);return new Promise((a,s)=>{let c=!1,d=!1,p=setTimeout(()=>{y(new g("Timed out waiting for OAuth callback."))},i),m=Ox((f,v)=>{let _=new URL(f.url??"/",`http://127.0.0.1:${n}`);if(_.pathname!==Ta){v.statusCode=404,v.end("Not found");return}let{searchParams:x}=_,E=(be,U)=>{let we=typeof be=="string"?new g(be,U):be;v.statusCode=400,v.setHeader("Content-Type","text/html"),v.setHeader("Connection","close"),v.once("finish",()=>y(we)),v.end(of("Authentication failed",we.message))},A=x.get("shop");if(S(w`Received OAuth callback for shop ${b.raw(A??"unknown")}`),!A){E("OAuth callback store doesn't match the requested store");return}let F=K(A);if(F!==r){E(nf(F));return}let W=x.get("state");if(!W||!Lx(W,t)){E("OAuth callback state doesn't match the original request");return}let ee=x.get("error");if(ee){E(`Shopify returned an OAuth error: ${ee}`);return}let ne=x.get("code");if(!ne){E("OAuth callback didn't include an authorization code");return}S(w`Received authorization code ${b.raw(ht(ne))}`),v.statusCode=200,v.setHeader("Content-Type","text/html"),v.setHeader("Connection","close"),v.once("finish",()=>h(()=>a(ne))),v.end(of("Authentication succeeded","Close this window and return to the terminal"))}),h=f=>{if(c)return;c=!0,clearTimeout(p);let v=()=>{f()};if(!d){v();return}m.close(()=>{d=!1,v()}),m.closeIdleConnections?.()},y=f=>{h(()=>s(f))};m.on("error",f=>{if(f.code==="EADDRINUSE"){y(new g(`Port ${n} is already in use.`,`Free port ${n} and re-run ${b.genericShellCommand(`shopify store auth --store ${e} --scopes <comma-separated-scopes>`).value}. Ensure that redirect URI is allowed in the app configuration.`));return}y(f)}),m.listen(n,"127.0.0.1",()=>{d=!0,S(w`PKCE callback server listening on http://127.0.0.1:${b.raw(String(n))}${b.raw(Ta)}`),o&&Promise.resolve(o()).catch(f=>{y(f instanceof Error?f:new Error(String(f)))})})})}function Lx(e,t){return e.length!==t.length?!1:Ux(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}l();import{createHash as $x,randomBytes as Vx}from"crypto";function qx(){return Vx(32).toString("base64url")}function jx(e){return $x("sha256").update(e).digest("base64url")}function Bx(e){let t=new URLSearchParams;return t.set("client_id",xn),t.set("scope",e.scopes.join(",")),t.set("redirect_uri",e.redirectUri),t.set("state",e.state),t.set("response_type","code"),t.set("code_challenge",e.codeChallenge),t.set("code_challenge_method","S256"),`https://${e.store}/admin/oauth/authorize?${t.toString()}`}function af(e){let{store:t,scopes:n,exchangeCodeForToken:i}=e,o=13387,r=yn(),a=Ym(o),s=qx(),c=jx(s),d=Bx({store:t,scopes:n,state:r,redirectUri:a,codeChallenge:c});return S(w`Starting PKCE auth for ${b.raw(t)} with scopes ${b.raw(n.join(","))} (redirect_uri=${b.raw(a)})`),{authorization:{store:t,scopes:n,state:r,port:o,redirectUri:a,authorizationUrl:d,codeVerifier:s},waitForAuthCodeOptions:{store:t,state:r,port:o},exchangeCodeForToken:p=>i({store:t,code:p,codeVerifier:s,redirectUri:a})}}l();function Xl(e){let t=e.split(/[ ,]+/).filter(Boolean);if(t.length===0)throw new g("At least one scope is required.","Pass --scopes as a comma-separated list.");return[...new Set(t)]}function Jl(e){let t=new Set(e);for(let n of e){let i=n.match(/^(unauthenticated_)?write_(.*)$/);i&&t.add(`${i[1]??""}read_${i[2]}`)}return t}function sf(e,t){let n=[...t],i=Jl(t);for(let o of e)if(!i.has(o)){n.push(o);for(let r of Jl([o]))i.add(r)}return n}function lf(e,t){if(!e.scope)return S(w`Token response did not include scope; falling back to requested scopes`),t;let n=Xl(e.scope),i=Jl(n),o=t.filter(r=>!i.has(r));if(o.length>0)throw new g("Shopify granted fewer scopes than were requested.",`Missing scopes: ${o.join(", ")}.`,["Update the app or store installation scopes.","See https://shopify.dev/app/scopes","Re-run shopify store auth."]);return n}l();l();var zx=240*1e3;function Wx(e){if(!e.expiresAt)return!1;let t=new Date(e.expiresAt).getTime();return Number.isNaN(t)?!0:t-zx<Date.now()}function Hx(e,t){let n=Date.now(),i=t.expiresIn?new Date(n+t.expiresIn*1e3).toISOString():e.expiresAt;return{...e,accessToken:t.accessToken,refreshToken:t.refreshToken??e.refreshToken,expiresAt:i,refreshTokenExpiresAt:t.refreshTokenExpiresIn?new Date(n+t.refreshTokenExpiresIn*1e3).toISOString():e.refreshTokenExpiresAt,acquiredAt:new Date(n).toISOString()}}async function Ia(e){let t=Fa(e);if(t||tf(e),S(w`Loaded stored session for ${b.raw(e)}: token=${b.raw(ht(t.accessToken))}, expires=${b.raw(t.expiresAt??"unknown")}`),!Wx(t))return t;t.refreshToken||bi(`No refresh token stored for ${t.store}.`,t.store,t.scopes.join(",")),S(w`Refreshing expired token for ${b.raw(t.store)} (expired at ${b.raw(t.expiresAt??"unknown")}, refresh_token=${b.raw(ht(t.refreshToken))})`);let n=t.accessToken,i;try{i=await Zm({store:t.store,refreshToken:t.refreshToken})}catch(o){throw hr(t.store,t.userId),o instanceof g&&o.message.startsWith(`Token refresh failed for ${t.store} (HTTP `)&&bi(o.message,t.store,t.scopes.join(",")),o instanceof g&&o.message===`Token refresh returned an invalid response for ${t.store}.`&&bi(o.message,t.store,t.scopes.join(",")),o instanceof g&&o.message==="Received an invalid refresh response from Shopify.",o}return t=Hx(t,i),S(w`Token refresh succeeded for ${b.raw(t.store)}: ${b.raw(ht(n))} → ${b.raw(ht(t.accessToken))}, new expiry ${b.raw(t.expiresAt??"unknown")}`),Pa(t),t}function cf(e,t=300){return e.slice(0,t)}function Gx(e){if(e&&typeof e=="object"&&"response"in e){let t=e.response,n=t?.status,i=t?.errors;if(typeof n=="number"){let o=typeof i=="string"?i:JSON.stringify(i);return cf(o?`HTTP ${n}: ${o}`:`HTTP ${n}`)}}return cf(e instanceof Error?e.message:String(e))}async function pf(e){let t=K(e),n=Fa(t);if(!n)return{scopes:[],authoritative:!0};try{let i=await Ia(t),o=await ef({store:i.store,accessToken:i.accessToken});return S(w`Resolved current remote scopes for ${b.raw(t)}: ${b.raw(o.join(",")||"none")}`),{scopes:o,authoritative:!0}}catch(i){if(i instanceof Error)return S(w`Falling back to locally stored scopes for ${b.raw(t)} after remote scope lookup failed: ${b.raw(Gx(i))}`),{scopes:n.scopes,authoritative:!1};throw i}}l();function Kx(e){return JSON.stringify(e,null,2)}function Yx(e){return{completed:["Logged in.",`Authenticated${e.associatedUser?.email?` as ${e.associatedUser.email}`:""} against ${e.store}.`],info:["","To verify that authentication worked, run:",`shopify store execute --store ${e.store} --query 'query { shop { name id } }'`]}}function Qx(){q("Shopify CLI will open the app authorization page in your browser."),q("")}function Jx(e){q("Browser did not open automatically. Open this URL manually:"),q(w`${b.link(e)}`),q("")}function Xx(e,t="text"){if(t==="json"){J(Kx(e));return}let n=Yx(e);n.completed.forEach(i=>po(i)),n.info.forEach(i=>q(i))}function Da(e="text"){return{openingBrowser:Qx,manualAuthUrl:Jx,success(t){Xx(t,e)}}}l();async function Si(e,t){await wu(()=>({store_fqdn:e})),await mt(()=>({store_fqdn_hash:ut(e),store_fqdn_validated:t}))}var Zx={openURL:Rt,waitForStoreAuthCode:rf,exchangeStoreAuthCodeForToken:Xm,resolveExistingScopes:pf,presenter:Da("text")};async function df(e,t={}){let n={...Zx,...t},i=K(e.store);await Si(i,!1);let o=Xl(e.scopes),r=await n.resolveExistingScopes(i),a=sf(o,r.scopes),s=r.authoritative?a:o;r.scopes.length>0&&S(w`Merged requested scopes ${b.raw(o.join(","))} with existing scopes ${b.raw(r.scopes.join(","))} for ${b.raw(i)}`);let c=af({store:i,scopes:a,exchangeCodeForToken:n.exchangeStoreAuthCodeForToken}),{authorization:{authorizationUrl:d}}=c;n.presenter.openingBrowser();let p=await n.waitForStoreAuthCode({...c.waitForAuthCodeOptions,onListening:async()=>{await n.openURL(d)||n.presenter.manualAuthUrl(d)}}),m=await c.exchangeCodeForToken(p);await Si(i,!0);let h=m.associated_user?.id?.toString();if(!h)throw new g("Shopify did not return associated user information for the online access token.");ra(h);let y=Date.now(),f=m.expires_in?new Date(y+m.expires_in*1e3).toISOString():void 0,v={store:i,userId:h,scopes:lf(m,s),acquiredAt:new Date(y).toISOString(),expiresAt:f,refreshTokenExpiresAt:m.refresh_token_expires_in?new Date(y+m.refresh_token_expires_in*1e3).toISOString():void 0,hasRefreshToken:!!m.refresh_token,associatedUser:m.associated_user?{id:m.associated_user.id,email:m.associated_user.email,firstName:m.associated_user.first_name,lastName:m.associated_user.last_name,accountOwner:m.associated_user.account_owner}:void 0};return Pa({store:i,clientId:xn,userId:h,accessToken:m.access_token,refreshToken:m.refresh_token,scopes:v.scopes,acquiredAt:v.acquiredAt,expiresAt:f,refreshTokenExpiresAt:v.refreshTokenExpiresAt,associatedUser:v.associatedUser}),S(w`Session persisted for ${b.raw(i)} (user ${b.raw(h)}, expires ${b.raw(f??"unknown")})`),n.presenter.success(v),v}l();var xi=class extends fo{};var Zl=O(ke(),1),ec,Jt=class extends xi{async run(){let{flags:t}=await this.parse(ec);await df({store:t.store,scopes:t.scopes},{presenter:Da(t.json?"json":"text")})}};ec=Jt;Jt.summary="Authenticate an app against a store for store commands.";Jt.descriptionWithMarkdown=`Authenticates the app against the specified store for store commands and stores an online access token for later reuse.
Re-run this command if the stored token is missing, expires, or no longer has the scopes you need.`;Jt.description=ec.descriptionWithoutMarkdown();Jt.examples=["<%= config.bin %> <%= command.id %> --store shop.myshopify.com --scopes read_products,write_products","<%= config.bin %> <%= command.id %> --store shop.myshopify.com --scopes read_products,write_products --json"];Jt.flags={...T,...Fe,store:Zl.Flags.string({char:"s",description:"The myshopify.com domain of the store to authenticate against.",env:"SHOPIFY_FLAG_STORE",parse:async e=>K(e),required:!0}),scopes:Zl.Flags.string({description:"Comma-separated Admin API scopes to request for the app.",env:"SHOPIFY_FLAG_SCOPES",required:!0})};var uf=Jt;l();l();l();var mf=O(Al(),1);async function eE(e){if(e.query!==void 0){if(!e.query.trim())throw new g("The --query flag value is empty. Please provide a valid GraphQL query or mutation.");return e.query}if(e.queryFile){if(!await C(e.queryFile))throw new g(w`Query file not found at ${b.path(e.queryFile)}. Please check the path and try again.`);let t=await P(e.queryFile,{encoding:"utf8"});if(!t.trim())throw new g(w`Query file at ${b.path(e.queryFile)} is empty. Please provide a valid GraphQL query or mutation.`);return t}throw new M("Query should have been provided via --query or --query-file flags due to exactlyOne constraint. This indicates the oclif flag validation failed.")}async function tE(e,t){if(e)try{return JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw new g(w`Invalid JSON in ${b.yellow("--variables")} flag: ${i}`,"Please provide valid JSON format.")}else if(t){if(!await C(t))throw new g(w`Variable file not found at ${b.path(t)}. Please check the path and try again.`);let n=await P(t,{encoding:"utf8"});try{return JSON.parse(n)}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw new g(w`Invalid JSON in variable file ${b.path(t)}: ${o}`,"Please provide valid JSON format.")}}}function nE(e){let t;try{t=(0,mf.parse)(e)}catch(i){throw i instanceof Error?new g(`Invalid GraphQL syntax: ${i.message}`):i}let n=t.definitions.filter(i=>i.kind==="OperationDefinition");if(n.length!==1)throw new g("GraphQL document must contain exactly one operation definition. Multiple operations are not supported.");return{operationDefinition:n[0]}}function iE(e){return e.operationDefinition.operation==="mutation"}function oE(e,t=!1){if(iE(e)&&!t)throw new g("Mutations are disabled by default for shopify store execute.","Re-run with --allow-mutations if you intend to modify store data.")}async function ff(e){let t=await eE({query:e.query,queryFile:e.queryFile}),n=nE(t);oE(n,e.allowMutations);let i=await tE(e.variables,e.variableFile);return{query:t,parsedOperation:n,parsedVariables:i,requestedVersion:e.version}}l();l();l();var rE=`
query StoreExecutePublicApiVersions {
publicApiVersions {
handle
supported
}
}
`;async function hf(e){try{return(await rr({query:rE,api:"Admin",url:Yt(e.adminSession.storeFqdn,"unstable",e.adminSession),token:e.adminSession.token,responseOptions:{handleErrors:!1}})).publicApiVersions}catch(t){let n=yf(t);(n===401||n===404)&&(hr(e.session.store,e.session.userId),bi(`Stored app authentication for ${e.session.store} is no longer valid.`,e.session.store,e.session.scopes.join(",")));let i=vf(t,e.adminSession.storeFqdn);throw i||t}}async function gf(e){try{return await Me({title:w`Executing GraphQL operation`,task:async()=>rr({query:e.request.query,api:"Admin",url:Yt(e.context.adminSession.storeFqdn,e.context.version,e.context.adminSession),token:e.context.adminSession.token,variables:e.request.parsedVariables,responseOptions:{handleErrors:!1}}),renderOptions:{stdout:process.stderr}})}catch(t){tc(t)&&t.response.status===401&&(hr(e.context.session.store,e.context.session.userId),bi(`Stored app authentication for ${e.context.session.store} is no longer valid.`,e.context.session.store,e.context.session.scopes.join(",")));let n=vf(t,e.context.adminSession.storeFqdn);throw n||(tc(t)&&t.response.errors?new g("GraphQL operation failed.",JSON.stringify({errors:t.response.errors},null,2)):t)}}function tc(e){if(!e||typeof e!="object"||!("response"in e))return!1;let t=e.response;return!!t&&typeof t=="object"}function yf(e){if(!tc(e))return;let t=e.response.status;return typeof t=="number"?t:void 0}var aE=["the user aborted a request","the operation was aborted"];function sE(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;let t=e.message.toLowerCase();return aE.some(n=>t.includes(n))}function vf(e,t){if(yf(e)===402)return new g(`The store ${t} is currently unavailable.`,"Check the store in the Shopify admin and try again once it is reactivated.");if(sE(e))return new g(`Request to ${t} was aborted before it completed.`)}async function lE(e){let{session:t,adminSession:n,userSpecifiedVersion:i}=e;if(i==="unstable")return i;let o=await hf({adminSession:n,session:t});if(!i)return o.filter(s=>s.supported).map(s=>s.handle).sort().reverse()[0];let r=o.map(a=>a.handle);if(r.includes(i))return i;throw new g(`Invalid API version: ${i}`,`Allowed versions: ${r.join(", ")}`)}async function kf(e){let t=await Ia(e.store);await Si(t.store,!0),ra(t.userId);let n={token:t.accessToken,storeFqdn:t.store},i=await lE({session:t,adminSession:n,userSpecifiedVersion:e.userSpecifiedVersion});return{adminSession:n,version:i,session:t}}var cE={id:"admin",prepareContext:async({store:e,requestedVersion:t})=>kf({store:e,userSpecifiedVersion:t}),execute:async({context:e,request:t})=>gf({context:e,request:t})};function wf(e){if(e==="admin")return cE;throw new M(`Unsupported store GraphQL API target: ${e}`)}async function _f(e){await Si(e.store,!1);let t=wf(e.api??"admin"),n=await ff({query:e.query,queryFile:e.queryFile,variables:e.variables,variableFile:e.variableFile,version:e.version,allowMutations:e.allowMutations}),i=await Me({title:w`Loading stored store auth`,task:async()=>t.prepareContext({store:e.store,requestedVersion:n.requestedVersion}),renderOptions:{stdout:process.stderr}});return t.execute({context:i,request:n})}l();function pE(e){return JSON.stringify(e,null,2)}function bf(e){if(e){j({headline:"Operation succeeded.",body:`Results written to ${e}`});return}j({headline:"Operation succeeded."})}async function Sf(e,t,n="text"){let i=pE(e);if(t){await ie(t,i),n==="text"&&bf(t);return}n==="text"&&bf(),J(i)}var Xt=O(ke(),1),nc,Zt=class extends xi{async run(){let{flags:t}=await this.parse(nc),n=await _f({store:t.store,query:t.query,queryFile:t["query-file"],variables:t.variables,variableFile:t["variable-file"],version:t.version,allowMutations:t["allow-mutations"]});await Sf(n,t["output-file"],t.json?"json":"text")}};nc=Zt;Zt.summary="Execute GraphQL queries and mutations on a store.";Zt.descriptionWithMarkdown="Executes an Admin API GraphQL query or mutation on the specified store using previously stored app authentication.\n\nRun `shopify store auth` first to create stored auth for the store.\n\nMutations are disabled by default. Re-run with `--allow-mutations` if you intend to modify store data.";Zt.description=nc.descriptionWithoutMarkdown();Zt.examples=['<%= config.bin %> <%= command.id %> --store shop.myshopify.com --query "query { shop { name } }"',`<%= config.bin %> <%= command.id %> --store shop.myshopify.com --query-file ./operation.graphql --variables '{"id":"gid://shopify/Product/1"}'`,'<%= config.bin %> <%= command.id %> --store shop.myshopify.com --query "mutation { shop { id } }" --allow-mutations','<%= config.bin %> <%= command.id %> --store shop.myshopify.com --query "query { shop { name } }" --json'];Zt.flags={...T,...Fe,query:Xt.Flags.string({char:"q",description:"The GraphQL query or mutation, as a string.",env:"SHOPIFY_FLAG_QUERY",required:!1,exactlyOne:["query","query-file"]}),"query-file":Xt.Flags.string({description:"Path to a file containing the GraphQL query or mutation. Can't be used with --query.",env:"SHOPIFY_FLAG_QUERY_FILE",parse:async e=>he(e),exactlyOne:["query","query-file"]}),variables:Xt.Flags.string({char:"v",description:"The values for any GraphQL variables in your query or mutation, in JSON format.",env:"SHOPIFY_FLAG_VARIABLES",exclusive:["variable-file"]}),"variable-file":Xt.Flags.string({description:"Path to a file containing GraphQL variables in JSON format. Can't be used with --variables.",env:"SHOPIFY_FLAG_VARIABLE_FILE",parse:async e=>he(e),exclusive:["variables"]}),store:Xt.Flags.string({char:"s",description:"The myshopify.com domain of the store to execute against.",env:"SHOPIFY_FLAG_STORE",parse:async e=>K(e),required:!0}),version:Xt.Flags.string({description:"The API version to use for the query or mutation. Defaults to the latest stable version.",env:"SHOPIFY_FLAG_VERSION"}),"output-file":Xt.Flags.string({description:"The file name where results should be written, instead of STDOUT.",env:"SHOPIFY_FLAG_OUTPUT_FILE",parse:async e=>he(e)}),"allow-mutations":Xt.Flags.boolean({description:"Allow GraphQL mutations to run against the target store.",env:"SHOPIFY_FLAG_ALLOW_MUTATIONS",default:!1})};var xf=Zt;var dE={"store:auth":uf,"store:execute":xf},Ra=dE;l();l();l();var Pe=O(ke(),1);var I={path:Pe.Flags.string({description:"The path to your app directory.",parse:async e=>he(e),default:async()=>to(),noCacheDefault:!0,env:"SHOPIFY_FLAG_PATH"}),config:Pe.Flags.string({hidden:!1,char:"c",description:"The name of the app configuration.",env:"SHOPIFY_FLAG_APP_CONFIG"}),"client-id":Pe.Flags.string({hidden:!1,description:"The Client ID of your app.",env:"SHOPIFY_FLAG_CLIENT_ID",exclusive:["config"]}),reset:Pe.Flags.boolean({hidden:!1,description:"Reset all your settings.",env:"SHOPIFY_FLAG_RESET",default:!1,exclusive:["config"]})},Ef={query:Pe.Flags.string({char:"q",description:"The GraphQL query or mutation to run as a bulk operation.",env:"SHOPIFY_FLAG_QUERY",required:!1,exactlyOne:["query","query-file"]}),"query-file":Pe.Flags.string({description:"Path to a file containing the GraphQL query or mutation. Can't be used with --query.",env:"SHOPIFY_FLAG_QUERY_FILE",parse:async e=>he(e),exactlyOne:["query","query-file"]}),variables:Pe.Flags.string({char:"v",description:"The values for any GraphQL variables in your mutation, in JSON format. Can be specified multiple times.",env:"SHOPIFY_FLAG_VARIABLES",multiple:!0,exclusive:["variable-file"]}),"variable-file":Pe.Flags.string({description:"Path to a file containing GraphQL variables in JSONL format (one JSON object per line). Can't be used with --variables.",env:"SHOPIFY_FLAG_VARIABLE_FILE",parse:async e=>he(e),exclusive:["variables"]}),store:Pe.Flags.string({char:"s",description:"The store domain. Must be an existing dev store.",env:"SHOPIFY_FLAG_STORE",parse:async e=>K(e)}),watch:Pe.Flags.boolean({description:"Wait for bulk operation results before exiting. Defaults to false.",env:"SHOPIFY_FLAG_WATCH"}),"output-file":Pe.Flags.string({description:"The file path where results should be written if --watch is specified. If not specified, results will be written to STDOUT.",env:"SHOPIFY_FLAG_OUTPUT_FILE",dependsOn:["watch"]}),version:Pe.Flags.string({description:"The API version to use for the bulk operation. If not specified, uses the latest stable version.",env:"SHOPIFY_FLAG_VERSION"})},Cf={query:Pe.Flags.string({char:"q",description:"The GraphQL query or mutation, as a string.",env:"SHOPIFY_FLAG_QUERY",required:!1,exactlyOne:["query","query-file"]}),"query-file":Pe.Flags.string({description:"Path to a file containing the GraphQL query or mutation. Can't be used with --query.",env:"SHOPIFY_FLAG_QUERY_FILE",parse:async e=>he(e),exactlyOne:["query","query-file"]}),variables:Pe.Flags.string({char:"v",description:"The values for any GraphQL variables in your query or mutation, in JSON format.",env:"SHOPIFY_FLAG_VARIABLES",exclusive:["variable-file"]}),"variable-file":Pe.Flags.string({description:"Path to a file containing GraphQL variables in JSON format. Can't be used with --variables.",env:"SHOPIFY_FLAG_VARIABLE_FILE",parse:async e=>he(e),exclusive:["variables"]}),store:Pe.Flags.string({char:"s",description:"The myshopify.com domain of the store to execute against. The app must be installed on the store. If not specified, you will be prompted to select a store.",env:"SHOPIFY_FLAG_STORE",parse:async e=>K(e)}),version:Pe.Flags.string({description:"The API version to use for the query or mutation. Defaults to the latest stable version.",env:"SHOPIFY_FLAG_VERSION"}),"output-file":Pe.Flags.string({description:"The file name where results should be written, instead of STDOUT.",env:"SHOPIFY_FLAG_OUTPUT_FILE"})};l();l();async function ic(e,{web:t,stdout:n,stderr:i,signal:o,env:r={}}){let a=t.configuration.commands[e];if(!a)return;let[s,...c]=a.split(" ");await Ke(s,c,{cwd:t.directory,stdout:n,stderr:i,signal:o,env:r}),n.write("Web successfully built.")}l();async function Ua(e){await xe([{title:"Installing dependencies",task:async()=>{await su({packageManager:e.packageManager,directory:e.directory,deep:3})}}])}l();l();import{pipeline as uE}from"stream/promises";import Nf from"node:stream/promises";import*as Af from"node:zlib";import{fileURLToPath as sc}from"node:url";var Tf="9.1.2",Ff="7.0.1",Pf="3",mE="123.0.0",If="1.0.2",Df="2.0.1";function Rf(e){return e==="0"||e==="1"?{functionRunner:"7.0.1",javy:"4.0.0",javyPlugin:"1"}:e==="2"?{functionRunner:Tf,javy:Ff,javyPlugin:Pf}:null}var gr=class{constructor(t,n,i,o,r=`v${n}`){this.name=t,this.version=n,this.release=r,this.supportsWindowsOnArm=o;let a;a=`${t}-${n}`,a=process.platform==="win32"?`${a}.exe`:a,this.path=k(H(sc(import.meta.url)),"..","bin",a),this.gitHubRepo=i}downloadUrl(t,n){let i,o;switch(t.toLowerCase()){case"darwin":i="macos";break;case"linux":i="linux";break;case"win32":i="windows";break;default:throw Error(`Unsupported platform ${t}`)}switch(n.toLowerCase()){case"arm":case"arm64":o="arm";break;case"ia32":case"x64":o="x86_64";break;default:throw Error(`Unsupported architecture ${n}`)}let r=`${o}-${i}`,a=["arm-linux","arm-macos","x86_64-macos","x86_64-windows","x86_64-linux"];if(this.supportsWindowsOnArm&&a.push("arm-windows"),!a.includes(r))throw Error(`Unsupported platform/architecture combination ${t}/${n}`);return`https://github.com/${this.gitHubRepo}/releases/download/${this.release}/${this.name}-${r}-v${this.version}.gz`}async processResponse(t,n){return hE(t,n)}},rc=class{constructor(t){this.name=`shopify_functions_javy_v${t}`,this.version=t,this.path=k(H(sc(import.meta.url)),"..","bin",`shopify_functions_javy_v${t}.wasm`)}downloadUrl(t,n){return`https://cdn.shopify.com/shopifycloud/shopify-functions-javy-plugin/shopify_functions_javy_v${this.version}.wasm`}async processResponse(t,n){return uE(t,n)}},ac=class{constructor(t,n){this.name=t,this.version=n,this.path=k(H(sc(import.meta.url)),"..","bin",t)}downloadUrl(t,n){return`https://cdn.jsdelivr.net/npm/binaryen@${this.version}/bin/wasm-opt`}async processResponse(t,n){await Nf.pipeline(t,n)}},oc;function lc(e=Ff){return new gr("javy",e,"bytecodealliance/javy",vi(e,">=7.0.0"))}function cc(e=Pf){return new rc(e)}function yr(e=Tf){return new gr("function-runner",e,"Shopify/function-runner",vi(e,">=9.1.1"))}function vr(){return oc||(oc=new ac("wasm-opt.cjs",mE)),oc}function Uf(e){return new gr("shopify-function-trampoline",e,"Shopify/shopify-function-wasm-api",vi(e,">=2.0.1"),`shopify_function_trampoline/v${e}`)}var Oa=new Map;async function At(e){if(await C(e.path)&&!Oa.has(e.path))return;let n=Oa.get(e.path);if(n){await n;return}let i=fE(e);Oa.set(e.path,i);try{await i}finally{Oa.delete(e.path)}}async function fE(e){let t=e.downloadUrl(process.platform,process.arch);S(`Downloading ${e.name} ${e.version} from ${t} to ${e.path}`);let n=H(e.path);await C(n)||await ae(n),await xa(async()=>{let i=await Ae(t,void 0,"slow-request");if(i.status!==200)throw new Error(`Downloading ${e.name} failed with status code of ${i.status}`);let o=i.body;if(o===null)throw new Error(`Downloading ${e.name} failed with empty response body`);await It(async r=>{let a=k(r,"binary"),s=Rd(a);await e.processResponse(o,s),await Ud(a,509),await un(a,e.path,{overwrite:!0})})},async()=>{},2)}async function hE(e,t){let n=Af.createGunzip();await Nf.pipeline(e,n,t)}l();var en={skipEsbuildReactDedeuplication:"SHOPIFY_CLI_SKIP_ESBUILD_REACT_DEDUPLICATION",disableGraphiQLExplorer:"SHOPIFY_CLI_DISABLE_GRAPHIQL",useDynamicConfigSpecifications:"SHOPIFY_CLI_DYNAMIC_CONFIG",enableAppLogPolling:"SHOPIFY_CLI_ENABLE_APP_LOG_POLLING",templatesJsonPath:"SHOPIFY_CLI_APP_TEMPLATES_JSON_PATH",mkcertBinaryPath:"SHOPIFY_CLI_MKCERT_BINARY",disableMinificationOnDev:"SHOPIFY_CLI_DISABLE_MINIFICATION_ON_DEV"},me={app:"shopify.app.toml",web:"shopify.web.toml",appEnvironments:"shopify.environments.toml",lockFile:".shopify.lock",hiddenConfig:"project.json",hiddenFolder:".shopify"},ko={production:".env"},Of={reactTypes:"17.0.30"},wo={extensions:{directoryName:"extensions",defaultRegistrationLimit:1},web:{directoryName:"web",configurationName:me.web}},kr={graphiql:3457,localhost:3458},La=/^([a-zA-Z_$])([a-zA-Z0-9_$])*$/;import{build as Mf}from"esbuild";var dc="2",wr=class extends g{constructor(t){super(t,w`Make sure you have a compatible version of the ${b.yellow("@shopify/shopify_function")} library installed.`,[w`Add ${b.green(`"@shopify/shopify_function": "~${dc}.0.0"`)} to the dependencies section of the package.json file in your function's directory, if not already present.`.value,"Run your package manager's install command to update dependencies."])}};async function $f(e,t){let n=_E(e),i=n.length===0?wE:new pc(n),o=await Ma(e);return t.useTasks?yE(e,t,i,o):gE(e,t,i,o)}async function gE(e,t,n,i){t.signal?.aborted||(t.stdout.write(`Building function ${e.localIdentifier}...`),t.stdout.write(`Building GraphQL types...
`),await tn(e,t)),t.signal?.aborted||(t.stdout.write(`Bundling JS function...
`),await n.bundle(e,t)),t.signal?.aborted||(t.stdout.write(`Running javy...
`),await n.compile(e,t,i)),t.signal?.aborted||t.stdout.write(`Done!
`)}async function yE(e,t,n,i){await xe([{title:"Building GraphQL types",task:async()=>{await tn(e,t)}},{title:"Bundling JS function",task:async()=>{await n.bundle(e,t)}},{title:"Running javy",task:async()=>{await n.compile(e,t,i)}}])}async function tn(e,t){if(e.typegenCommand){let i=e.typegenCommand.split(" ");return Ul("cmd_all_timing_network_ms")(async()=>Ke(i[0],i.slice(1),{cwd:e.directory,stdout:t.stdout,stderr:t.stderr,signal:t.signal}))}if(!e.isJavaScript)throw new g("No typegen_command specified. Set build.typegen_command in your function extension TOML to generate GraphQL types for non-JavaScript functions.");let n=await au(e.directory,"graphql-code-generator","--config","package.json");return Ul("cmd_all_timing_network_ms")(async()=>Ke(n.command,n.args,{cwd:e.directory,stderr:t.stderr,signal:t.signal}))}async function Vf(e){let t=await qe("node_modules/@shopify/shopify_function/index.ts",{type:"file",cwd:e.directory}),n=await qe("node_modules/@shopify/shopify_function/run.ts",{type:"file",cwd:e.directory});if(!t||!n)throw new wr("Could not find the Shopify Functions JavaScript library.");if(!e.entrySourceFilePath)throw new g("Could not find your function entry point. It must be in src/index.js or src/index.ts");return t}async function Ma(e){let t=await qe("node_modules/@shopify/shopify_function/package.json",{type:"file",cwd:e.directory});if(!t)throw new wr("Could not find the Shopify Functions JavaScript library.");let i=JSON.parse(await P(t)).version.split(".")[0],o=Rf(i);if(o===null)throw new wr("The installed version of the Shopify Functions JavaScript library is not compatible with this version of Shopify CLI.");return o}async function vE(e,t,n=process.env){let i=await Vf(e),o={...qf(e.directory,e.entrySourceFilePath,t.app.dotenv?.variables??{},n),entryPoints:[i]};return Mf(o)}function qf(e,t,n,i=process.env){let o=kn(i,(c,d)=>La.test(d)&&c),r={...n,...o},a=Object.keys(r||{}).reduce((c,d)=>({...c,[`process.env.${d}`]:JSON.stringify(r[d])}),{});return{outfile:k(e,"dist/function.js"),alias:{"user-function":t},define:a,logLevel:"silent",bundle:!0,legalComments:"none",target:"es2022",format:"esm"}}async function jf(e){let t=vr();await At(t);let n=H(vr().path),i="node",o=[vr().name,e,"-Oz","--enable-bulk-memory","--enable-multimemory","--enable-nontrapping-float-to-int","--strip-debug","-o",e];S(`Wasm binary: ${vr().name}`),S("Optimizing this wasm binary using wasm-opt."),await Ke(i,o,{cwd:n})}async function Bf(e){let t,n=await kE(e);if(n.includes("shopify_function_v1")?t=If:n.includes("shopify_function_v2")&&(t=Df),!t)return;let i=Uf(t);await At(i);let o=i.path,r=["-i",e,"-o",e];S(`Applying trampoline to the wasm binary with command: ${o} ${r.join(" ")}`),await Ke(o,r)}async function kE(e){let t=new Uint8Array(ct(e));if(!WebAssembly.validate(t))return[];let i=new WebAssembly.Module(t),o=WebAssembly.Module.imports(i);return[...new Set(o.map(r=>r.module))]}async function zf(e,t,n,i=[]){let o=lc(n.javy),r=cc(n.javyPlugin);await Promise.all([At(o),At(r)]);let a=["build","-C","dynamic","-C",`plugin=${r.path}`,...i,"-o",e.outputPath,"dist/function.js"];return Ke(o.path,a,{cwd:e.directory,stdout:"inherit",stderr:"inherit",signal:t.signal})}async function _o(e){let n=e.allExtensions.filter(s=>s.features.includes("function")&&s.isJavaScript).map(s=>Ma(s)),i=await Promise.all(n),o=new Set,r=new Set;i.forEach(s=>{o.add(s.javy),r.add(s.javyPlugin)});let a=[];o.forEach(s=>{a.push(At(lc(s)))}),r.forEach(s=>{a.push(At(cc(s)))}),await Promise.all(a)}var wE={async bundle(e,t){return vE(e,t)},async compile(e,t,n){return zf(e,t,n)}},Lf="shopify-function",pc=class{constructor(t){this.exports=t}async bundle(t,n,i=process.env){await Vf(t);let o=this.entrypointContents;S("Generating dist/function.js using generated module:"),S(o);let r={...qf(t.directory,t.entrySourceFilePath,n.app.dotenv?.variables??{},i),stdin:{contents:o,loader:"ts",resolveDir:t.directory}};return Mf(r)}async compile(t,n,i){let o=this.wit;return S("Generating world to use with Javy:"),S(o),It(async r=>{let a=k(r,"javy-world.wit");return await ie(a,o),zf(t,n,i,["-C",`wit=${a}`,"-C",`wit-world=${Lf}`])})}get wit(){let t=this.exports.map(n=>`export %${Ct(n)}: func();`);return`package function:impl;
world ${Lf} {
${t.join(`
`)}
}`}get entrypointContents(){let t=`
import __runFunction from "@shopify/shopify_function/run"`,n=this.exports.map(i=>{let o=nr(i),r=nr(`run-${i}`);return`
import { ${o} as ${r} } from "user-function"
export function ${o}() { return __runFunction(${r}) }`});return`${t}
${n.join(`
`)}`}};function _E(e){let t=e.configuration.targeting??[],n=t.filter(r=>!r.export),i=t.filter(r=>!!r.export);if(t.length>1&&n.length>0)throw new Error(`Can't infer export name for targets:
${n.map(({target:r})=>`- '${r}'`).join(`
`)}
All targets must have an export when multiple targets are present.`);let o=i.filter(r=>!r.export.match(/^[a-z0-9-]+$/));if(o.length>0){let r=[],a=o.map(s=>`'${s.export}'`);throw r.push(`Invalid export names: ${a.join(", ")}.
The TOML's exports must be kebab-case (lowercase, hyphen or numbers) to comply with WebAssembly's Component Model.
JavaScript exports with camelCase names are automatically mapped to kebab-case Wasm exports.
`),r.push("Suggested TOML changes:"),o.forEach(s=>{let c=s.export;r.push(`- Change export for '${s.target}' to '${Ct(c)}'.`)}),new Error(r.join(`
`))}return i.map(r=>r.export)}async function bE(e){!e.skipDependenciesInstallation&&!e.project.usesWorkspaces&&await Ua(e.project);let t={};e.apiKey&&(t.SHOPIFY_API_KEY=e.apiKey),await _o(e.app),await ma({processes:[...e.app.webs.map(n=>({prefix:["web",...n.configuration.roles].join("-"),action:async(i,o,r)=>{await ic("build",{web:n,stdout:i,stderr:o,signal:r,env:t})}})),...e.app.allExtensions.map(n=>({prefix:n.localIdentifier,action:async(i,o,r)=>{await n.build({stdout:i,stderr:o,signal:r,app:e.app,environment:"production"})}}))],showTimestamps:!1}),j({headline:[{userInput:e.app.name},"built!"]})}var Wf=bE;l();l();l();l();function $a(e,t){return async n=>{let i=await e.appsForOrg(t,n);return{apps:i.apps,hasMorePages:i.hasMorePages}}}l();l();l();l();l();function _r(e,{httpsOnly:t=!1,message:n="Invalid URL"}={}){return e.refine(i=>Gf(i,t),{message:n}).refine(i=>!i.includes(`
`),{message:n})}function Hf(e,{message:t="URL must be HTTPS URL or start with /"}={}){return e.refine(n=>n.startsWith("/")||Gf(n,!0),{message:t})}function Gf(e,t){try{let n=new URL(e);return t?n.protocol==="https:":["http:","https:"].includes(n.protocol)}catch{return!1}}function uc(e){return typeof e=="string"&&!e.startsWith("/")?`/${e}`:e}var Va=30;function Kf(e){return e.length<=Va}l();l();l();var Ee=50,qa=250,nn=u.object({namespace:u.string(),key:u.string()}),SE=u.object({sms_marketing:u.boolean().optional(),customer_privacy:u.boolean().optional()}),xE=u.object({sources:u.array(u.string()).optional()}),EE=u.object({network_access:u.boolean().optional(),block_progress:u.boolean().optional(),api_access:u.boolean().optional(),collect_buyer_consent:SE.optional(),iframe:xE.optional()}),CE=u.object({runs_offline:u.boolean().optional()}),Yf=u.object({type:u.string().optional(),extensions:u.array(u.any()).optional()}),NE=u.object({allow_direct_linking:u.boolean().optional()}),AE=u.object({module:u.string()}),TE=u.object({target:u.string(),module:u.string(),should_render:AE.optional(