@shopify/cli
Version:
A CLI tool to build for the Shopify platform
104 lines (100 loc) • 32.8 kB
JavaScript
import{a as dt,b as pt,f as we,g as ie,h as H,i as oe,k as mt}from"./chunk-K6CTUBFC.js";import{n as ne,o as re}from"./chunk-XITQULK4.js";import{a as O,b as lt}from"./chunk-3VZEETAV.js";import{a as ee,b as te,e as tt,g as st,i as nt,j as rt,k as it,n as ot,p as at,q as ct,r as se,s as I}from"./chunk-IX5ICOBV.js";import{a as J,l as Ke,m as et}from"./chunk-CBXSPL4W.js";import{aa as Qe}from"./chunk-UXVZ2P63.js";import{va as C,xa as q}from"./chunk-XONFGLJQ.js";import{b as Ve}from"./chunk-JUVAGMIH.js";import{u as Xe,w as b,x as X,y as Ze}from"./chunk-6G6TMKXF.js";import{d as Z}from"./chunk-M56NDIMD.js";import{Gb as $,Ib as Q,Nb as K,O as Ge,Qb as R,Rb as j,Ta as F,Wa as L,_ as Re,bb as Pe,ma as k,ua as Fe,wa as ze,ya as Ye}from"./chunk-N5PQPIBF.js";import{d as E,g as Se,j as Je,k as A}from"./chunk-IU2ZQ6TE.js";import{e as Ue,g as u}from"./chunk-VPRTJUIN.js";u();u();u();var qt=".shopifyignore",ht=/templates\/\*(\.(json|liquid))?$/,ut=new Set;function be(e,t={}){let s=t.ignoreFromFile??[],n=t.ignore??[],r=t.only??[],[i=[],o=[]]=ke(s),[a=[],m=[]]=ke(n),[p=[],h=[]]=ke(r),l=e.filter(N(i,".shopifyignore"));return l=l.filter(N(a,"--ignore")),l=l.filter(N(p,"--only",!0)),o.length>0&&(l=l.concat(e.filter(N(o,".shopifyignore",!0)))),m.length>0&&(l=l.concat(e.filter(N(m,"--ignore",!0)))),h.length>0&&(l=l.filter(N(h,"--only"))),Ge(l,f=>f.key)}function N(e,t,s=!1){return({key:n})=>{if(e.length===0)return!0;let r=e.some(o=>jt(n,o)||Wt(o)&&Nt(n,Mt(o)));return(s?!r:r)?(R(`Ignoring theme file ${n} via ${t}...`),!1):!0}}async function ft(e){let t=E(e,qt);return await F(t)?(await k(t,{encoding:"utf8"})).split(/(\r\n|\r|\n)/).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")):[]}function ke(e){let t=e.filter(n=>n.startsWith("!")).map(n=>n.slice(1));return[e.filter(n=>!n.startsWith("!")),t]}function jt(e,t){let s={matchBase:!0,noglobstar:!0};return Pe(e,t,s)?!0:(!t.includes("*")&&t.endsWith("/")&&!ut.has(t)&&(ut.add(t),b({headline:"Directory pattern may be misleading.",body:`For more reliable matching, consider using "${t}*" or "${t}*.<file_extension>" instead.`})),Ot(t)?Pe(e,t.replace(ht,"templates/**/*$1"),s):!1)}function Ot(e){return ht.test(e)}function Nt(e,t){return t.test(e)}function Wt(e){return e.startsWith("/")&&e.endsWith("/")}function Mt(e){return new RegExp(e.slice(1,-1))}u();import gt from"fs/promises";var ae=class{constructor(t){this.notifyPath=t,this.isValidUrl=this.validateUrl(t),this.notifyPath===""&&j("Notification skipped: notifyPath is an empty string")}async notify(t){if(this.notifyPath!=="")try{R(`Notifying filechange listener at ${this.notifyPath}...`),this.isValidUrl?await this.notifyUrl(t):await this.notifyFile(t)}catch(s){C(s);let n=`Failed to notify filechange listener at ${this.notifyPath}`;s instanceof Error&&(n=n.concat(`: ${s.message}`)),j(n)}}async notifyUrl(t){let s=await fetch(this.notifyPath,{method:"POST",body:JSON.stringify({files:[t]}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(s.statusText)}async notifyFile(t){await gt.writeFile(this.notifyPath,t),await gt.utimes(this.notifyPath,new Date,new Date)}validateUrl(t){try{let s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"}catch{return!1}}};u();u();u();u();u();var Bt="https://unpkg.com/@shopify/polaris@13.9.2/build/esm/styles.css";function yt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Et(e){return(0,String.raw)`<!DOCTYPE html>
<html>
<head>
<title>${e.title}</title>
<link rel="stylesheet" href="${Bt}" />
</head>
<body>
<div style="display: flex; justify-content: center; padding-top: 2rem;">
<div style="width: 80%;">
<div class="Polaris-Banner Polaris-Banner--withinPage" tabindex="0" role="alert" aria-live="polite">
<div class="Polaris-Box" style="--pc-box-width:100%">
<div
class="Polaris-BlockStack"
style="--pc-block-stack-align:space-between;--pc-block-stack-order:column"
>
<div
class="Polaris-Box"
style="--pc-box-color: var(--p-color-text-critical-on-bg-fill); --pc-box-background: var(--p-color-bg-fill-critical); --pc-box-padding-block-start-xs: var(--p-space-300); --pc-box-padding-block-end-xs: var(--p-space-300); --pc-box-padding-inline-start-xs: var(--p-space-300); --pc-box-padding-inline-end-xs: var(--p-space-300); --pc-box-border-start-start-radius: var(--p-border-radius-300); --pc-box-border-start-end-radius: var(--p-border-radius-300);"
>
<div
class="Polaris-InlineStack"
style="--pc-inline-stack-align:space-between;--pc-inline-stack-block-align:center;--pc-inline-stack-wrap:nowrap;--pc-inline-stack-gap-xs:var(--p-space-200);--pc-inline-stack-flex-direction-xs:row"
>
<div
class="Polaris-InlineStack"
style="--pc-inline-stack-wrap:nowrap;--pc-inline-stack-gap-xs:var(--p-space-100);--pc-inline-stack-flex-direction-xs:row"
>
<span class="Polaris-Banner--textCriticalOnBgFill">
<span class="Polaris-Icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M10 6a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5a.75.75 0 0 1 .75-.75Z" />
<path d="M11 13a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z" />
<path
fill-rule="evenodd"
d="M17 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0Zm-1.5 0a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0Z"
/>
</svg>
</span>
</span>
<h2 class="Polaris-Text--root Polaris-Text--headingSm Polaris-Text--break">
${e.header}
</h2>
</div>
</div>
</div>
<div
class="Polaris-Box"
style="--pc-box-padding-block-start-xs:var(--p-space-300);--pc-box-padding-block-end-xs:var(--p-space-300);--pc-box-padding-block-end-md:var(--p-space-400);--pc-box-padding-inline-start-xs:var(--p-space-300);--pc-box-padding-inline-start-md:var(--p-space-400);--pc-box-padding-inline-end-xs:var(--p-space-300);--pc-box-padding-inline-end-md:var(--p-space-400)"
>
<div
class="Polaris-BlockStack"
style="--pc-block-stack-order:column;--pc-block-stack-gap-xs:var(--p-space-300)"
>
${e.errors.map(s=>`
<div>
<span class="Polaris-Text--root Polaris-Text--headingSm">${yt(s.message)}</span>
<ul class="Polaris-List">
<li class="Polaris-List__Item">${yt(s.code)}</li>
</ul>
</div>`).join("")}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>`}u();u();var Tt=80;function G(e,t,s){if(!Ut(e)||s.type==="theme-extension")return;let n=e.path.length>Tt?`${e.path.substring(0,Tt)}...`:e.path,i=t.headers.get("server-timing")?.match(/cfRequestDuration;dur=([\d.]+)/)?.[1],o=i?`${Math.round(Number(i))}ms`:"",a=Jt(t.status),m=e.method.padStart(6);K(Q`• ${ne.format(new Date)} Request ${$.raw("\xBB")} ${m} ${a(String(t.status))} ${n} ${$.gray(o)}`)}function Ut(e){let t=[M,W,"/checkouts","/payments"],s=[".js",".css",".json",".map"];if(t.some(i=>e.path.startsWith(i)))return!1;let[n]=e.path.split("?"),r=A(n);return!s.includes(r)}function Jt(e){return e<300?$.green:e<400?$.yellow:$.errorText}var W="/cdn/",M="/ext/cdn/",$e="/api/collect",Gt=/^\/cart\//,vt=/^\/checkouts\/(?!internal\/)/,zt=/^\/account(\/login\/multipass(\/[^/]+)?|\/logout)?\/?$/,Yt=new RegExp(`^${W}`),Vt=new RegExp(`^${M}`),Xt=/^\/api\/(unstable|\d{4}-\d{2})\/graphql\.json/,Zt=["/.well-known","/shopify/monorail","/mini-profiler-resources","/web-pixels-manager","/web-pixels@","/wpm","/services/",$e,"/cdn-cgi/challenge-platform"],xt="_shopify_essential",Qt=new RegExp(`${xt}=([^;]*)(;|$)`);function Kt(e,t){return I(async s=>{if(Zt.some(n=>s.path.startsWith(n)))return null;if(es(s)){let n=s.path.split("?")[0]??"";return De(s,t).then(async r=>{if(G(s,r,t),r.ok){let i=n.split("/").at(-1)??"";if(t.localThemeFileSystem.files.has(`assets/${i}.liquid`)){let o=z(await r.text(),t);return new Response(o,r)}}return r}).catch(async r=>{let{status:i,statusText:o,...a}=H(r,`Failed to proxy request to ${n}`);return i>=500&&!n.endsWith(".js.map")&&b(a),new Response(r.message,{status:i,statusText:o})})}})}function es(e){if(e.method!=="GET"||e.path.match(Gt)||e.path.match(vt)||e.path.match(zt)||e.path.match(Yt)||e.path.match(Vt))return!0;let[t]=e.path.split("?"),s=A(t),n=e.headers.get("accept")??"*/*";return s===".html"||n.includes("text/html")?!1:!!s||n!=="*/*"}function ce(e){return e.session.storeFqdn.replace(/\\/g,"\\\\").replace(/\./g,"\\.")}function ts(e){return Xt.test(e.path)}function z(e,t){let s=e,n=`(data-shs-beacon-endpoint=["'])https://${ce(t)}${$e}`,r=new RegExp(n,"g");s=s.replace(r,`$1${$e}`);let i=new RegExp(`(https?:)?//${ce(t)}${W}`,"g");s=s.replace(i,W);let o=/(?:https?:)?\/\/cdn\.shopify\.com\/(.*?\/(assets\/[^?#"'`>\s]+))/g,a=h=>h.startsWith("assets/"),m=new Set([...t.localThemeFileSystem.files.keys()].filter(a)),p=new Set([...t.localThemeExtensionFileSystem.files.keys()].filter(a));return s=s.replace(o,(h,l,d)=>{let f=d&&m.has(d),P=d&&p.has(d)&&l.startsWith("extensions/");return O(d).startsWith("image/")?h:P?`${M}${l}`:f?`${W}${l}`:h}),s}function ss(e,t){let s=`http://${t.options.host}:${t.options.port}`,n=new RegExp(`data-base-url=["']((?:https?:)?//${ce(t)})[^"']*?["']`,"g");return e.replace(n,(r,i)=>r.replace(i,s))}function ns(e,t){let s=new RegExp(`Domain=${ce(t)};\\s*`,"gi");return e.map(n=>n.replace(s,""))}async function le(e,t,s){if(t.status>=300&&t.status<400)return t;let n=Rt(e,t);t.headers.get("content-type")?.includes("application/json")||n.headers.set("content-type","text/html; charset=utf-8");let o=await n.text();return o=z(o,e),o=ss(o,e),s&&(o=s(o)??o),new Response(o,n)}var St=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","expect","content-security-policy","host"];function Rt(e,t){let s=new Response(t.body,t);s.headers.delete("content-length"),s.headers.delete("content-encoding");for(let o of St)s.headers.delete(o);s.headers.delete("access-control-allow-origin"),s.headers.delete("access-control-allow-credentials"),s.headers.delete("access-control-allow-methods"),s.headers.delete("access-control-allow-headers"),s.headers.delete("access-control-expose-headers"),s.headers.delete("access-control-max-age");let n=s.headers.get("Link");n&&s.headers.set("Link",z(n,e));let r=s.headers.get("Location");if(r){let o=new URL(r,"https://shopify.dev");vt.test(o.pathname)||(o.searchParams.delete("_fd"),o.searchParams.delete("pb"),s.headers.set("Location",o.href.replace(o.origin,"")))}let i=s.headers.getSetCookie();if(i?.length){s.headers.set("Set-Cookie",ns(i,e).join(","));let o=i.join(",").match(Qt)?.[1];o&&(e.session.sessionCookies[xt]=o)}return s}function Ie(e){let t=tt(e);for(let n of St)delete t[n];delete t["upgrade-insecure-requests"];let s=st(e);return s&&(t["X-Forwarded-For"]=s),t}function De(e,t){let s=e.path.replace(new RegExp(M,"g"),"/"),n=e.path.startsWith(M)?"cdn.shopify.com":t.session.storeFqdn,r=new URL(s,`https://${n}`);if(r.hostname!==n)return Promise.reject(new Error(`Request failed: Hostname mismatch. Expected host: ${n}. Resulting URL hostname: ${r.hostname}`));let i=nt(e),o=Ie(e);return ts(e)||(/\/assets\/[^/]+\.(css|js)$/.test(r.pathname)&&/\?\d+$/.test(r.search)&&(r.search=`?v=${Date.now()}`),r.searchParams.set("_fd","0"),r.searchParams.set("pb","0"),o=pt({...o,...dt(),referer:r.origin,Cookie:mt(t.session,{headers:o}),...t.type==="theme"?{Authorization:`Bearer ${t.session.storefrontToken}`}:{}})),fetch(r,{method:e.method,body:i,duplex:i?"half":void 0,redirect:"manual",headers:o}).then(a=>Rt(t,a)).catch(a=>{throw ie(C(a),r)})}var Ae=0,rs=5;function is(e,t){return I(s=>{let[n="/",r=""]=s.path.split("?");return as(s)&&(t.lastRequestedPath=s.path),t.options.errorOverlay!=="silent"&&t.localThemeFileSystem.uploadErrors.size>0?Ft(t,{status:500,statusText:"Internal Server Error"},{title:"Failed to Upload Theme Files",header:"Upload Errors",errors:Array.from(t.localThemeFileSystem.uploadErrors.entries()).map(([o,a])=>({message:o,code:a.join(`
`)}))}):oe(t.session,{method:s.method,path:n,query:[...new URLSearchParams(r)],themeId:String(e.id),sectionId:"",headers:Ie(s),replaceExtensionTemplates:pe(t),replaceTemplates:He(t,n,rt(s,"localization")?.toLowerCase())}).then(async o=>{if(o.status>=400&&o.status<500&&!os(s)){let a=await cs(s,t,o);if(a)return G(s,a,t),a}return G(s,o,t),le(t,o,a=>(ls(o,a,String(e.id)),Ae=0,Le(a,t)))}).catch(async o=>{if(o instanceof de&&(R(`Theme ID mismatch: expected ${o.getExpectedThemeId()} but got ${o.getActualThemeId()}; refreshing session...`),q("theme-service:error-page:theme-id-mismatch"),t.session.refresh)){Ae++,Ae>rs&&(Ze(new Z(o.getMessage())),process.exit(1)),await t.session.refresh();let f=new URLSearchParams(r),P=new URLSearchParams([...f].filter(([ve])=>!ve.startsWith("__sfr"))),D=n+(P.toString()?`?${P}`:"");return new Response(null,{status:302,headers:{Location:D}})}let{status:a,statusText:m,cause:p,...h}=H(o,"Failed to render storefront"),[l,...d]=h.headline.split(`
`);return X(h),Ft(t,{status:a,statusText:m},{title:l,header:l,errors:[{message:[...d,p.message].join("<br>"),code:p.stack?.replace(`${p.message}
`,"")??""}]})})})}function Ft(e,t,s){let n=Le(Et(s),e);return q("theme-service:error-page:rendered"),new Response(n,{...t,headers:t.headers??{"Content-Type":"text/html; charset=utf-8"}})}function os(e){let t=new URLSearchParams(e.path.split("?")[1]);return["section_id","sections","app_block_id"].some(s=>t.has(s))}function as(e){return e.headers.get("sec-fetch-mode")==="navigate"}async function cs(e,t,s){R(`Render failed for ${e.path} with ${s.status} (x-request-id: ${s.headers.get("x-request-id")}), trying proxy...`);let n=await De(e,t).catch(r=>new Response(null,H(r)));if(n.status<400)return R(`Proxy status: ${n.status}. Returning proxy response.`),n;R(`Proxy status: ${n.status}. Returning render error.`)}function ls(e,t,s){let n=t.match(/Shopify\.theme\s*=\s*{[^}]+?"id":\s*"?(\d+)"?(}|,)/)?.[1];if(n&&n!==s)throw new de(s,n,e)}var de=class extends Error{constructor(t,s,n){super([`Theme ID mismatch: expected ${t} but got ${s}.`,`Request ID: ${n.headers.get("x-request-id")}`,`URL: ${n.url}`,"This is likely related to an issue in upstream Shopify APIs.","Please try again in a few minutes and report this issue:","https://community.shopify.dev/c/shopify-cli-libraries/14"].join(`
`)),this.response=n,this.expectedThemeId=t,this.actualThemeId=s}getMessage(){return this.message}getResponse(){return this.response}getExpectedThemeId(){return this.expectedThemeId}getActualThemeId(){return this.actualThemeId}};u();u();function me(e,t){let s=new RegExp(`{%-?\\s*${t}\\s*-?%}`),n=new RegExp(`{%-?\\s*end${t}\\s*-?%}`),r=s.exec(e);if(!r)return;let i=r.index+r[0].length;n.lastIndex=i;let o=n.exec(e);if(!o)return;let a=o.index;return e.slice(i,a)}u();function ue(e){let{pathname:t,search:s,searchParams:n}=new URL(e.path,"http://e.c");return{pathname:t,search:s,searchParams:n}}var ds={stylesheet:new Map,javascript:new Map};function ps(e,t){return I(async s=>{if(s.method!=="GET")return;if(us(s,t))return hs(s,t);let{file:n,fileKey:r,isUnsynced:i}=ms(s,t);if(!r)return;let o=O(r);if(o.startsWith("image/")&&s.path.includes("&")&&!i)return;if(ot(s,"X-Local-Asset","true"),!n){i&&te(s,ee({statusCode:404,statusMessage:"Not found"}));return}let a=n.value?Buffer.from(z(n.value,t)):Buffer.from(n.attachment??"","base64");return se(s,{getContents:()=>a,getMeta:()=>({type:o,size:a.length,mtime:n.stats?.mtime})})})}function ms(e,t){let s=(n,r)=>{let i=e.path.match(n)?.[1];if(i){let o=E("assets",i),a=r.files.get(o),m=r.unsyncedFileKeys.has(o);if(a||m)return{file:a,isUnsynced:m,fileKey:o}}};return s(/^(?:\/cdn\/.*?)?\/assets\/([^?]+)/,t.localThemeFileSystem)??s(/^(?:\/ext\/cdn\/extensions\/.*?)?\/assets\/([^?]+)/,t.localThemeExtensionFileSystem)??{isUnsynced:!1,fileKey:void 0,file:void 0}}function us(e,t){return t.type==="theme"&&e.path.includes("/compiled_assets")}function hs(e,t){switch(ue(e).pathname.split("/").at(-1)){case"styles.css":return fs(t,e);case"block-scripts.js":return qe(t,e,"block");case"snippet-scripts.js":return qe(t,e,"snippet");case"scripts.js":return qe(t,e,"section");case void 0:break;default:break}}function fs(e,t){let s=he(e,"section"),n=he(e,"block"),r=he(e,"snippet"),i=[`/*** GENERATED LOCALLY ***/
`];for(let[,a]of[...s,...n,...r]){let m=Pt(a,"stylesheet");m&&i.push(m)}let o=i.join(`
`);return se(t,{getContents:()=>o,getMeta:()=>({type:"text/css",size:Buffer.byteLength(o),mtime:new Date})})}function qe(e,t,s){let n=he(e,s),r=`${s}s`,i=[`
/*** GENERATED LOCALLY ***/
(function () {
var __${r}__ = {};
(function () {
var element = document.getElementById("${r}-script");
var attribute = element ? element.getAttribute("data-${r}") : "";
var ${r} = attribute.split(",").filter(Boolean);
for (var i = 0; i < ${r}.length; i++) {
__${r}__[${r}[i]] = true;
}
})();`];for(let[a,m]of n){let p=a.split("/").pop()?.replace(".liquid",""),h=Pt(m,"javascript")??"";p&&h&&i.push(`
(function () {
if (!__${r}__["${p}"] && !Shopify.designMode) return;
try {
${h}
} catch (e) {
console.error(e);
}
})();`)}i.push("})();");let o=i.join(`
`);return se(t,{getContents:()=>o,getMeta:()=>({type:"text/javascript",size:Buffer.byteLength(o),mtime:new Date})})}function he(e,t){return[...e.localThemeFileSystem.files.entries()].filter(([s])=>s.endsWith(".liquid")&&s.startsWith(`${t}s/`)).sort(([s],[n])=>s.localeCompare(n))}function Pt(e,t){let s=ds[t],n=s.get(e.key);if(n?.checksum===e.checksum)return n.content;if(s.delete(e.key),!e.value)return;let r=[`/* ${e.key} */`],i=me(e.value??"",t);if(i&&r.push(i),r.length>1){let o=r.join(`
`);return s.set(e.key,{checksum:e.checksum,content:o}),o}}u();function Qn(){return gs()}function gs(){return{root:"",files:new Map,unsyncedFileKeys:new Set,uploadErrors:new Map,ready:()=>Promise.resolve(),delete:async e=>{},read:async e=>"",write:async e=>{},stat:async e=>({mtime:new Date,size:1}),addEventListener:()=>{},startWatcher:async()=>{}}}function pe(e){let t={},s=e.localThemeExtensionFileSystem;for(let n of s.unsyncedFileKeys){let r=s.files.get(n),i=r?.value??r?.attachment;i&&(t[n]=i)}return t}var ye=Ue(Qe(),1);import Es from"node:events";var Oe=new Map,Y=new Map;function wt(e,t){let s=(0,ye.parseJSON)(t,null,!0);if(!s)return;let n=s?.sections;n&&!e.startsWith("locales/")?Y.set(e,Object.entries(n||{}).map(([r,{type:i}])=>[i,r])):Y.delete(e)}function Ne(e){return!e.startsWith("assets/")&&[".liquid",".json"].includes(A(e))}function He(e,t,s){let n={},r=/^templates\/.+\.json$/,i=t?`${E("templates",t.replace(/^\//,"").replace(/\.html$/,"")||"index")}.json`:"",o=!!t&&e.localThemeFileSystem.files.has(i),a=/^locales\/.+\.json$/,m=!!s&&(e.localThemeFileSystem.files.has(`locales/${s}.json`)||e.localThemeFileSystem.files.has(`locales/${s}.default.json`));for(let p of e.localThemeFileSystem.unsyncedFileKeys)if(Ne(p)){if(o&&r.test(p)){if(p!==i)continue}else if(a.test(p)){if(m){if(!p.startsWith(`locales/${s}.`))continue}else if(!p.includes(".default."))continue}n[p]=e.localThemeFileSystem.files.get(p)?.value??""}return n}function wr(e,t){let s=({fileKey:r,onContent:i,onSync:o})=>{let a=A(r);i(m=>{!Rs(r)&&Ne(r)&&a===".json"&&wt(r,m),je(e,t,o,{type:"update",key:r,payload:xs(r,t)})})},n=({fileKey:r,onSync:i})=>{Y.delete(r),je(e,t,i,{type:"delete",key:r})};return t.localThemeFileSystem.addEventListener("add",s),t.localThemeFileSystem.addEventListener("change",s),t.localThemeFileSystem.addEventListener("unlink",n),t.localThemeFileSystem.ready().then(async()=>{let r=[...t.localThemeFileSystem.files];return Promise.allSettled(r.map(async([i,o])=>{if(i.endsWith(".json")){let a=o.value??await t.localThemeFileSystem.read(i);a&&typeof a=="string"&&wt(i,a)}else i.endsWith(".liquid")&&Ct(o)}))})}var Ts="1",bt=new Es;function ge(e){bt.emit("hot-reload",{...e,version:Ts})}function ys(e,t){return I(s=>{let n=s.headers.get("accept")==="text/event-stream",r=ue(s).searchParams;if(n){let i=ct(s);return bt.on("hot-reload",o=>{i.push(JSON.stringify(o)).catch(a=>{b({headline:"Failed to send HotReload event.",body:a.stack})})}),ge({type:"open",pid:String(process.pid),themeId:String(e.id)}),i.send().then(()=>i.flush())}if(r.has("hr-log")){let i=(0,ye.parseJSON)(r.get("hr-log")??"",null);return i&&(i.headline=`[HotReload] ${i.headline}`,i.type==="error"?X(i):i.type==="warn"?b(i):i.type==="info"?Xe(i):b({headline:`Unknown HotReload log type: ${i.type}`})),null}if(s.path===_t)return k(Ee()).then(i=>it(s,i,"application/javascript")).catch(i=>te(s,ee({cause:i})));if(r.has("section_id")||r.has("app_block_id")){let i=r.get("section_key")??"",o=r.get("section_id")??"",a=r.get("app_block_id")??"",m=s.path.split("?")[0]??"",p=new URLSearchParams(r);if(p.delete("section_key"),p.delete("section_id"),p.delete("app_block_id"),p.delete("_fd"),p.delete("pb"),o===""&&a==="")return;let h={};if(o){let l=t.localThemeFileSystem.unsyncedFileKeys;if(l.has(i)){let d=t.localThemeFileSystem.files.get(i)?.value;if(!d)return"";h[i]=d}for(let d of l)if(d.endsWith(".json")){for(let[f,P]of Y.get(d)??[])if(o.endsWith(`__${P}`)){let D=t.localThemeFileSystem.files.get(d)?.value;D&&(h[d]=D);continue}}}return oe(t.session,{method:s.method,path:m??"/",query:[...p.entries()],themeId:String(e.id),sectionId:o,appBlockId:a,replaceTemplates:h,headers:at(s),replaceExtensionTemplates:pe(t)}).then(async l=>{if(!l.ok)throw q("theme-service:hot-reload:section:render-failed"),ie(l);return le(t,l)}).catch(async l=>{let{status:d,statusText:f,...P}=H(C(l),"Failed to render section on Hot Reload");return q("theme-service:hot-reload:section:render-error"),a||b(P),new Response(null,{status:d,statusText:f})})}})}var V=(e,t)=>ge({themeId:String(e),type:"full",key:t});function je(e,t,s,n){let r=()=>V(e.id,n.key);if(t.options.liveReload==="off")return;if(t.options.liveReload==="full-page"){s(r);return}let i=String(e.id);ge({sync:"local",themeId:i,...n}),s(()=>ge({sync:"remote",themeId:i,...n}),r)}function vs(e,t){let s=new Set;if(e.endsWith(".json")){let n=t.localThemeFileSystem.files.get(e)?.value;if(n){let r=(0,ye.parseJSON)(n,null,!0)?.sections;for(let i of Object.keys(r??{}))s.add(i)}}else{let n=e.match(/^sections\/(.+)\.liquid$/)?.[1];if(n)for(let[r,i]of Y)for(let[o,a]of i)o===n&&s.add(a)}return[...s]}function xs(e,t){let[s]=e.split("/"),n=t.localThemeFileSystem.files.get(e);return{sectionNames:s==="sections"?vs(e,t):[],replaceTemplates:Ne(e)?He(t):{},updatedFileParts:n&&Ct(n)}}var fe="hot-reload-client",Ss="/cdn/shopifycloud/theme-hot-reload/theme-hot-reload.js",kt=new RegExp(`<script id="${fe}"[^>]*>[^<]*</script>`),_t="/@shopify/theme-hot-reload";function Le(e,t){return t.options.liveReload==="off"?e.replace(kt,""):process.env.SHOPIFY_CLI_LOCAL_HOT_RELOAD?e.replace(kt,"").replace(/<\/head>/,`<script id="${fe}" src="${_t}" defer></script></head>`):e.includes(`<script id="${fe}"`)?e:e.replace(/<\/head>/,`<script id="${fe}" src="${Ss}" defer></script></head>`)}function Rs(e){return e.startsWith("assets/")}function Ct(e){if(!(["sections/","snippets/","blocks/"].some(h=>e.key.startsWith(h))&&e.key.endsWith(".liquid")))return;let n={stylesheetTag:!1,javascriptTag:!1,schemaTag:!1,liquid:!1},r={checksum:e.checksum,liquid:"",stylesheetTag:"",javascriptTag:"",schemaTag:""},i=Oe.get(e.key);if(i?.checksum===e.checksum||(Oe.delete(e.key),!e.value))return n;let o=["stylesheet","javascript","schema"],a=h=>h?.replace(/\s+/g," ").trim(),m=e.value,p=(h,l)=>{m=m.replace(l,"");let d=a(l),f=`${h}Tag`;n[f]=!i||d!==i[f],r[f]=d};for(let h of o){let l=me(e.value??"",h);l&&p(h,l)}return m=a(m.replace(/<!--[\s\S]*?-->/g,"").replace(/{%\s*comment\s*%}[\s\S]*?{%\s*endcomment\s*%}/g,"").replace(/{%\s*doc\s*%}[\s\S]*?{%\s*enddoc\s*%}/g,"")),r.liquid=m,n.liquid=!i||m!==i.liquid,Oe.set(e.key,r),n}u();var $t=Ue(Qe(),1);function Fs(e){return(e.startsWith("templates/")||e.startsWith("sections/"))&&e.endsWith(".json")}async function It(e,t,s){if(Fs(s)){let n=E(e,"listings",t,s);if(await F(n))return n}}async function Dt(e,t){let s=E(e,"config","settings_data.json"),n=await k(s,{encoding:"utf8"}),r=(0,$t.parseJSON)(n,null,!0);return r?(r.current=Re(t),JSON.stringify(r,null,2)):n}async function Dr(e,t){let s=E(e,"listings"),n=E(s,t);if(await F(n))return;let i=[];await F(s)&&(i=await L("*",{cwd:s,onlyDirectories:!0,deep:1}));let o=i.length>0?`Available presets: ${i.map(a=>`"${Re(a)}"`).join(", ")}`:'No presets found under "listings/"';throw new Z(`Listing preset "${t}" was not found. ${o}.`,`Add the preset to config/settings_data.json and its corresponding "listings/${t}" folder, or remove the --listing flag to use the default theme settings.`)}import Ps from"node:events";import{fileURLToPath as ws}from"node:url";var ks=250,At=["assets/**/*.*","config/**/*.json","layout/**/*.liquid","locales/**/*.json","sections/**/*.{liquid,json}","blocks/**/*.liquid","snippets/**/*.liquid","templates/**/*.{liquid,json}","templates/customers/**/*.{liquid,json}"],w={layoutLiquidRegex:/^layout\/.+\.liquid$/,sectionLiquidRegex:/^sections\/.+\.liquid$/,blockLiquidRegex:/^blocks\/.+\.liquid$/,configSchemaRegex:/^config\/settings_schema\.json$/,configDataRegex:/^config\/settings_data\.json$/,sectionJsonRegex:/^sections\/.+\.json$/,templateJsonRegex:/^templates\/.+\.json$/,jsonRegex:/^(?!config\/).*\.json$/,contextualizedJsonRegex:/\.context\.[^.]+\.json$/i,staticAssetRegex:/^assets\/(?!.*\.liquid$)/};function Kr(e,t){let s=new Map,n=new Map,r=new Set,i={ignoreFromFile:[],ignore:t?.filters?.ignore??[],only:t?.filters?.only??[]},o=new Ps,a=(c,g)=>{o.emit(c,g)},m=t?.notify?new ae(t.notify):void 0,p=async c=>{let g=t?.listing?await _s(e,c,t.listing):await Ce(e,c),y=_e(c,g);return s.set(c,J({key:c,checksum:y,value:typeof g=="string"?g:"",attachment:Buffer.isBuffer(g)?g.toString("base64"):""})),g},h=L(At,{cwd:e,deep:3,ignore:re}).then(c=>Promise.all([ft(e),...c.map(p)])).then(([c])=>{Array.isArray(c)&&i.ignoreFromFile.push(...c)}),l=c=>Se(e,c),d=c=>be([{key:c}],i).length===0;function f(c,g,y,T){if(process.env.SHOPIFY_CLI_LOCAL_HOT_RELOAD&&T===Ee()){V(g,T);return}let x=l(T);if(t?.listing&&x.startsWith(`listings/${t.listing}/`)){let v=x.replace(`listings/${t.listing}/`,"");if(v.startsWith("templates/")||v.startsWith("sections/"))x=v;else return}P(x).then(()=>{switch(c){case"add":case"change":return D(c,g,y,x);case"unlink":return ve(g,y,x,n)}}).catch(v=>{j(`Error handling file event for ${x}: ${v}`)})}function P(c){return m?.notify(c)??Promise.resolve()}let D=(c,g,y,T)=>{if(d(T))return;let x=s.get(T)?.checksum,v=p(T).then(async()=>{let S=s.get(T);if(S)return S.checksum!==x&&r.add(T),{value:S.value||void 0,attachment:S.attachment}}),_=v.then(S=>{if(S)return bs(r,n,T,g,y)(S)}).catch(we(T,"upload"));a(c,{fileKey:T,onContent:S=>{v.then(B=>{r.has(T)&&S(B?.value??B?.attachment??"")}).catch(()=>{})},onSync:(S,B)=>{_.then(U=>{U?S():B?.()}).catch(()=>{})}})},ve=(c,g,y,T)=>{if(d(y))return;T.delete(y),s.delete(y),r.add(y);let x=t?.noDelete?Promise.resolve():Ke(Number(c),[y],g).then(async v=>{if(!v[0]?.success)throw new Error(`Failed to delete file "${y}" from remote theme.`);return r.delete(y),Ht("delete",y),!0}).catch(v=>(we(y,"delete")(v),!1));a("unlink",{fileKey:y,onSync:v=>{x.then(_=>{_&&v()}).catch(()=>{})}})},xe=new Set(At.map(c=>E(e,c.split("/").shift()??"")));return t?.listing&&xe.add(E(e,"listings",t.listing)),process.env.SHOPIFY_CLI_LOCAL_HOT_RELOAD&&xe.add(Ee()),{root:e,files:s,unsyncedFileKeys:r,uploadErrors:n,ready:()=>h,delete:async c=>{s.delete(c),await Cs(e,c)},write:async c=>{let g=(c.key.startsWith("templates/")||c.key.startsWith("sections/"))&&c.key.endsWith(".json");if(t?.listing&&g){let y=E("listings",t.listing,c.key),T=E(e,y),x=await F(T);s.set(c.key,J({key:c.key,checksum:c.checksum,value:c.value??"",attachment:c.attachment??""})),x?await We(e,{...c,key:y}):await We(e,c);return}s.set(c.key,J({key:c.key,checksum:c.checksum,value:c.value??"",attachment:c.attachment??""})),await We(e,c)},read:p,applyIgnoreFilters:c=>be(c,i),addEventListener:(c,g)=>{o.on(c,g)},startWatcher:async(c,g)=>{let{default:y}=await import("./chokidar-G4ONJSK4.js"),T=y.watch([...xe],{ignored:re,persistent:!process.env.SHOPIFY_UNIT_TEST,ignoreInitial:!0}),x=new Map,v=(_,S)=>{let U=`${l(S)}:${_}`,Be=x.get(U);Be&&clearTimeout(Be);let Lt=setTimeout(()=>{x.delete(U),f(_,c,g,S)},ks);x.set(U,Lt)};T.on("add",v.bind(null,"add")).on("change",v.bind(null,"change")).on("unlink",v.bind(null,"unlink")).on("error",_=>{j(`File watcher error: ${_}`),C("theme-service:file-watcher:error")})}}}function bs(e,t,s,n,r){return async i=>{if(!e.has(s))return!1;let[o]=await et(Number(n),[{key:s,...i}],r);if(!o?.success){let a=o?.errors?.asset??["Response was not successful."];throw t.set(s,a),V(n,s),new Error(a.join(`
`))}return t.delete(s)&&V(n,s),e.delete(s),Ht("update",s),!0}}async function We(e,{key:t,attachment:s,value:n}){let r=E(e,t);if(await $s(r),s){let i=Buffer.from(s,"base64");await Fe(r,i,{encoding:"base64"})}else await Fe(r,n??"")}async function Ce(e,t){let s=Te(t)?{encoding:"utf8"}:{},n=E(e,t);if(!await F(n)){R(`File ${n} can't be read because it doesn't exist...`);return}return k(n,s)}async function _s(e,t,s){if(t==="config/settings_data.json")return Dt(e,s);let n=await It(e,s,t);if(n){let r=Te(t)?{encoding:"utf8"}:{};return k(n,r)}return Ce(e,t)}async function Cs(e,t){let s=E(e,t);if(!await F(s)){R(`File ${s} can't be removed because it doesn't exist...`);return}await Ye(s)}function ei(e){let t=[],s=[],n=[],r=[],i=[],o=[],a=[],m=[],p=[],h=[],l=[];return e.forEach(d=>{let f=d.key;f.endsWith(".liquid")?w.sectionLiquidRegex.test(f)?t.push(d):w.blockLiquidRegex.test(f)?h.push(d):w.layoutLiquidRegex.test(f)?l.push(d):s.push(d):w.configSchemaRegex.test(f)?a.push(d):w.configDataRegex.test(f)?m.push(d):w.jsonRegex.test(f)?w.contextualizedJsonRegex.test(f)?o.push(d):w.sectionJsonRegex.test(f)?n.push(d):w.templateJsonRegex.test(f)?r.push(d):i.push(d):w.staticAssetRegex.test(f)&&p.push(d)}),{sectionLiquidFiles:t,otherLiquidFiles:s,sectionJsonFiles:n,templateJsonFiles:r,contextualizedJsonFiles:o,otherJsonFiles:i,configSchemaFile:a,configDataFile:m,staticAssetFiles:p,blockLiquidFiles:h,layoutFiles:l}}function Te(e){return lt({liquid:"application/liquid",sass:"text/x-sass",scss:"text/x-scss"}),["application/javascript","application/json","application/liquid","text/css","text/x-sass","text/x-scss","image/svg+xml"].includes(O(e))}async function ti(e){let t=new Set(await L("*",{cwd:e,deep:1,onlyDirectories:!0}));return["config","layout","sections","templates"].every(n=>t.has(n))}async function $s(e){let t=Is(e);await F(t)||await ze(t)}function Is(e){let t=Je(e),s=e.lastIndexOf(t);return e.substring(0,s)}function Ht(e,t){K(Q`• ${ne.format(new Date)} Synced ${$.raw("\xBB")} ${e} ${t}`)}function Ee(){let e=process.env.SHOPIFY_CLI_LOCAL_HOT_RELOAD;return!e||e==="true"?E(ws(import.meta.url.split("/cli/")[0]??""),"theme-hot-reload/dist/theme-hot-reload.js"):e}function _e(e,t){return t?Buffer.isBuffer(t)?Me(t):Ls(e)?Ds(t):As(e,t):""}function Ds(e){let t=e;return t=t.replace(/\r\n/g,`
`),t=t.replace(/\/\*[\s\S]*?\*\//,""),t=Hs(t),Me(t)}function As(e,t){let s=t;return Te(e)&&(s=s.replace(/\r\n/g,`
`)),Me(s)}function Hs(e){let t=!1,s=!1,n="";for(let r of e)r==='"'&&!s&&(t=!t),!(!t&&(r===" "||r===`
`))&&(n+=r,s=r==="\\"&&!s);return n}function Me(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return Ve(t)}function oi(e){let t=new Set(e.filter(({key:s})=>s.startsWith("assets/")&&s.endsWith(".liquid")).map(({key:s})=>s));return e.filter(({key:s})=>s.startsWith("assets/")?!t.has(`${s}.liquid`):!0)}function Ls(e){return e.endsWith("/settings_data.json")}export{oi as a,Kt as b,is as c,ps as d,Qn as e,wr as f,ys as g,V as h,Dr as i,Kr as j,ei as k,ti as l};