#!/usr/bin/env node var me=Object.defineProperty;var n=(t,e)=>me(t,"name",{value:e,configurable:!0});import{createHash as Ue}from"crypto";import{chmodSync as Ve,closeSync as we,lstatSync as Fe,mkdirSync as Me,openSync as $e,readdirSync as He,rmSync as Be,statSync as Ke}from"fs";import{tmpdir as Ge}from"os";import{join as k}from"path";import{parseArgs as Ye}from"util";var b="assistant-first-turn-complete",C=["up","down","mixed"],f=["worked","partial","failed","not_used"];function h(t){return typeof t=="string"&&t.length>0?t:void 0}n(h,"nonEmpty");function S(){let t=[process.env.CLAUDE_SESSION_ID,process.env.CLAUDE_CODE_SESSION_ID,process.env.CURSOR_SESSION_ID,process.env.COPILOT_SESSION_ID];for(let e of t)if(typeof e=="string"&&e.length>0)return e}n(S,"readHostSessionId");function U(t){let e=n(a=>`${a}:${t.trigger}:1`,"key"),r=h(t.sessionId);if(r)return{feedbackId:e(r),feedbackIdSource:"session"};let i=h(t.conversationId);if(i)return{feedbackId:e(i),feedbackIdSource:"conversation"};let s=h(t.toolUseId);if(s)return{feedbackId:e(s),feedbackIdSource:"tool-use"};let o=h(t.fallbackId);if(o)return{feedbackId:e(o),feedbackIdSource:"random"}}n(U,"deriveFeedbackId");import{readFileSync as ge,statSync as _e}from"node:fs";import{homedir as Ee}from"node:os";import{join as m}from"node:path";var I="shopify-ai-toolkit",O="opt-out",he="SHOPIFY_AI_TOOLKIT_OPT_OUT_FILE",Se=new Set(["false","0","no","off"]);function V(t){return{env:t?.env??process.env,platform:t?.platform??process.platform,homeDir:t&&"homeDir"in t?t.homeDir:Ie(t?.env??process.env)}}n(V,"resolveContext");function Ie(t){let e=t.HOME?.trim()||t.USERPROFILE?.trim();if(e)return e;try{return Ee()||void 0}catch{return}}n(Ie,"resolveHomeDir");function Oe(t){let{env:e,platform:r,homeDir:i}=V(t),s=[],o=e[he]?.trim();o&&s.push(o);let a=e.XDG_CONFIG_HOME?.trim();if(a&&s.push(m(a,I,O)),i&&(s.push(m(i,".config",I,O)),r==="darwin"&&s.push(m(i,"Library","Application Support",I,O))),r==="win32"){let c=e.APPDATA?.trim()||(i?m(i,"AppData","Roaming"):void 0);c&&s.push(m(c,I,O))}return[...new Set(s.filter(c=>!!c))]}n(Oe,"telemetryOptOutFileCandidates");function ve(t){if(t.OPT_OUT_INSTRUMENTATION?.trim().toLowerCase()==="true")return!0;let e=t.DO_NOT_TRACK?.trim().toLowerCase();return e==="1"||e==="true"}n(ve,"envSaysOptOut");function ye(t){try{if(!_e(t).isFile())return!1}catch{return!1}try{let e=ge(t,"utf8").trim().toLowerCase();return!Se.has(e)}catch{return!0}}n(ye,"fileSaysOptOut");function v(t){try{let e=V(t);return ve(e.env)?!0:Oe(e).some(ye)}catch{return!1}}n(v,"isTelemetryOptedOut");function w(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>{let{description:i,valueName:s,choices:o,...a}=r;return[e,a]}))}n(w,"toParseArgsOptions");var y={model:{type:"string",valueName:"name",description:"Agent model name"},"client-name":{type:"string",valueName:"name",description:"Agent client name"},"client-version":{type:"string",valueName:"version",description:"Agent client version"}},g={"user-prompt-base64":{type:"string",valueName:"base64",description:"Base64-encoded triggering prompt"},"session-id":{type:"string",valueName:"id",description:"Agent session identifier"},"tool-use-id":{type:"string",valueName:"id",description:"Agent tool-use identifier"}},ct={"artifact-id":{type:"string",valueName:"id",description:"Stable artifact identifier"},revision:{type:"string",valueName:"number",description:"Positive artifact revision"},...y,...g,json:{type:"boolean",description:"Emit machine-readable JSON"}},F={help:{type:"boolean",short:"h",description:"Show this help"}};function M(t,e){let r=new Set([...Object.keys(y),...Object.keys(g),"artifact-id","revision"]),i=Object.entries(e).filter(([o])=>!0).map(([o,a])=>{let c=a.type==="string"?a.valueName||a.choices?.join("|")||"value":void 0,u=`--${o}${c?` <${c}>`:""}`;return[a.short?`-${a.short}, ${u}`:u,a.description]}),s=Math.max(...i.map(([o])=>o.length));return["Usage:",...t.map(o=>` ${o}`),"","Options:",...i.map(([o,a])=>` ${o.padEnd(s)} ${a}`)].join(` `)}n(M,"formatCliHelp");import{isIP as Re}from"node:net";var Ne="https://shopify.dev/",Le="https://shopify-dev.shop.dev/";function $(t){return`https://shopify-dev-staging${t}.shopifycloud.com/`}n($,"stagingHost");var De="SHOPIFY_DEV_SUPPORT_CORE_MCP_DOMAIN",T="SHOPIFY_DEV_LOCAL_SERVER_URL";function be(t){let e;try{e=new URL(t)}catch{throw new Error(`${T} must identify a local Shopify.dev origin`)}let r=e.hostname==="localhost"||e.hostname==="[::1]"||Re(e.hostname)===4&&e.hostname.startsWith("127."),i=/^shopify-dev-[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.shop\.dev$/u.test(e.hostname);if(!r&&!i||r&&!e.port||i&&e.protocol!=="https:"||r&&e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||e.pathname!==""&&e.pathname!=="/"||e.search||e.hash)throw new Error(`${T} must identify a local Shopify.dev origin`);return`${e.origin}/`}n(be,"normalizeLocalShopifyDevUrl");function A(t){let e=t?.env??process.env,r=e.SHOPIFY_DEV_STAGING_SERVER_NUMBER?.trim(),i=e[T]?.trim();if(i&&t?.allowLocalServer){if(r||e.DEV&&e.DEV!=="false"||e[De]?.trim())throw new Error(`${T} cannot be combined with staging, DEV, or Support Core routing overrides`);return{url:be(i),headers:{}}}if(r){if(!/^\d+$/.test(r))throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${r}"`);let o=Number(r);if(!Number.isSafeInteger(o)||o<=0)throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${r}"`);let a=e.MINERVA_TOKEN;if(!a){let c=$(o).replace(/\/$/,"");throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER=${o} is set but no Minerva token is available. Staging servers are behind Minerva. Get a token via: export MINERVA_TOKEN=$(devx minerva-auth --client-id 0oa1bphetnkOusboI0x8 --audience ${c})`)}return{url:$(o),headers:{Cookie:`MINERVA_TOKEN=${a}`}}}let s=e.SHOPIFY_DEV_INSTRUMENTATION_URL?.trim();return s&&t?.uri?.startsWith("/mcp/usage")?{url:s,headers:{}}:e.DEV&&e.DEV!=="false"?{url:Le,headers:{}}:{url:Ne,headers:{}}}n(A,"resolveShopifyDevBaseUrl");async function H(t,e){let r,i={};if(t.startsWith("http://")||t.startsWith("https://"))r=new URL(t);else{let o=A({uri:t,allowLocalServer:e?.allowLocalServer});r=new URL(t,o.url),i=o.headers}e?.parameters&&Object.entries(e.parameters).forEach(([o,a])=>{r.searchParams.append(o,a)});let s=await fetch(r.toString(),{method:e?.method||"GET",...e?.redirect&&{redirect:e.redirect},headers:{Accept:"application/json","Cache-Control":"no-cache","X-Shopify-Surface":"mcp","X-Shopify-MCP-Version":e?.instrumentation?.packageVersion||"","X-Shopify-Timestamp":e?.instrumentation?.timestamp||"",...i,...e?.headers},...e?.body&&{body:e.body}});if(!s.ok){let o;try{o=await s.text()}catch{}throw new Error(o?`HTTP ${s.status}: ${o}`:`HTTP error! status: ${s.status}`)}return await s.text()}n(H,"shopifyDevFetch");function B(t){return{...t?.api&&{api:t.api},...t?.api_version&&{api_version:t.api_version},...t?.resolve_api_version&&{resolve_api_version:t.resolve_api_version}}}n(B,"nonEmptyUsageMetadata");var Ce={ucp:"ucp"},Ae="functions_",ke="shopify-";function K(t){if(t)return t.startsWith(Ae)?"shopify-functions":Ce[t]??`${ke}${t}`}n(K,"legacySkillName");function Pe(){return v()}n(Pe,"isInstrumentationDisabled");function G(t){if(!(typeof t!="string"||t.length===0))try{let e=Buffer.from(t,"base64").toString("utf8");return e.length>0?e:void 0}catch{return}}n(G,"decodeUserPrompt");async function Y(t,e,r,i){if(!!0||Pe())return;let{model:s,clientName:o,clientVersion:a,user_prompt:c,sessionId:u,toolUseId:E,topic:L,...ae}=r??{},D=typeof L=="string"&&L.length>0?L:void 0,ce=n((...p)=>{for(let l of p)if(typeof l=="string"&&l.length>0)return l},"firstApi")(i?.api,(r??{}).api),de=K(D??ce??"")??"shopify",P=typeof u=="string"&&u.length>0?u:S(),x=typeof c=="string"&&c.length>0?c.slice(0,2e3):void 0;try{let p={"Content-Type":"application/json","X-Shopify-Surface":"skills"};o&&(p["X-Shopify-Client-Name"]=String(o)),a&&(p["X-Shopify-Client-Version"]=String(a)),s&&(p["X-Shopify-Client-Model"]=String(s));let l=JSON.stringify({tool:t,parameters:{skill:de,skillBundle:"shopify",skillVersion:"1.19.0",...D!==void 0&&{topic:D},...x!==void 0&&{user_prompt:x},...P!==void 0&&{sessionId:P},...typeof E=="string"&&E.length>0&&{toolUseId:E},...ae},result:e,...B(i)});if(process.env.SKILL_TELEMETRY_TEST_MODE==="1"){let{url:pe}=A({uri:"/mcp/usage"}),ue=new URL("/mcp/usage",pe).toString();process.stderr.write([`[TEST_TELEMETRY_ENDPOINT] ${ue}`,...Object.entries(p).map(([le,fe])=>`[TEST_TELEMETRY_HEADER] ${le}: ${fe}`),`[TEST_TELEMETRY_BODY] ${l}`,""].join(` `));return}await H("/mcp/usage",{method:"POST",headers:p,body:l,instrumentation:{packageVersion:"1.19.0",timestamp:new Date().toISOString()}})}catch{}}n(Y,"reportValidation");var J=".feedback",je=1440*60*1e3;function Xe(){let t=process.getuid?.()??0;return k(Ge(),`shopify-ai-toolkit-telemetry-${t}`)}n(Xe,"markerDir");function Je(t,e){let r=Ue("sha256").update(e).digest("hex").slice(0,32);return k(t,`${r}${J}`)}n(Je,"markerPath");function We(t){try{let e=Date.now()-je;for(let r of He(t)){if(!r.endsWith(J))continue;let i=k(t,r);try{Ke(i).mtimeMs0?t:void 0}n(W,"nonEmptyFlag");function R(t){return{type:"string",choices:f,description:t}}n(R,"verdictOption");var z={overall:{type:"string",choices:C,description:"Overall toolkit verdict for this turn"},"docs-context":R("Verdict for docs/search context"),"schema-validation":R("Verdict for schema/code validation"),"api-version":R("Verdict for API version targeting"),codegen:R("Verdict for generated code"),"comment-base64":{type:"string",valueName:"base64",description:`Base64-encoded rationale, decoded and truncated to ${500} chars (base64 keeps arbitrary text inert in the shell)`},"session-id":g["session-id"],"tool-use-id":g["tool-use-id"],...y,...F},qe=[M(["scripts/log_feedback.mjs --overall --docs-context "," --schema-validation --api-version --codegen "," --comment-base64 [--session-id ] [--tool-use-id ]"," [--model ] [--client-name ] [--client-version ]"],z),"","Each is one of: worked | partial | failed | not_used.","Run once per turn. Without a session id or tool-use id there is no dedupe","key, so nothing is sent."].join(` `);function q(){console.error("Usage: scripts/log_feedback.mjs --overall --docs-context --schema-validation --api-version --codegen --comment-base64 [options] (run with --help for details)"),process.exit(1)}n(q,"exitWithUsageHint");var Q=(()=>{try{return Ye({options:w(z),allowPositionals:!0})}catch{return}})();Q||q();var{values:d}=Q;d.help&&(console.log(qe),process.exit(0));v()&&process.exit(0);var Z=_(C,d.overall),ee=_(f,d["docs-context"]),te=_(f,d["schema-validation"]),re=_(f,d["api-version"]),ne=_(f,d.codegen),j=d["comment-base64"],Qe=j===""?"":G(j),oe=Qe?.slice(0,500);(!Z||!ee||!te||!re||!ne||oe===void 0)&&q();var ie=W(d["session-id"])??S(),se=W(d["tool-use-id"]),N=U({trigger:b,sessionId:ie,toolUseId:se});N&&ze(N.feedbackId)&&await Y("feedback","ok",{model:d.model,clientName:d["client-name"],clientVersion:d["client-version"],sessionId:ie,toolUseId:se,feedbackVersion:1,feedbackId:N.feedbackId,feedbackIdSource:N.feedbackIdSource,trigger:b,overall:Z,docsContext:ee,schemaValidation:te,apiVersion:re,codegen:ne,comment:oe});process.exit(0);