@joai/warps 4.38.0 → 4.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var at=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var st=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var jr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Oe=r=>r?typeof r=="string"?r:r.address:null,R=(r,t)=>Oe(r.user?.wallets?.[t]||null),je=r=>r?typeof r=="string"?r:r.privateKey||null:null,Be=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Le=r=>r?typeof r=="string"?r:r.externalId||null:null,Br=(r,t)=>je(r.user?.wallets?.[t]||null)?.trim()||null,Lr=(r,t)=>Be(r.user?.wallets?.[t]||null)?.trim()||null,Ve=(r,t)=>Le(r.user?.wallets?.[t]||null)?.trim()||null,Vr=(r,t)=>{let e=Ve(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},kr=r=>typeof r=="string",Hr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Fr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ke=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},He=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Ur=(r,t=24)=>{let e=ke(r);return He(e,t),e};var Fe=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(Fe||{}),zt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(zt||{}),_t=Object.values(zt),qr=["ethereum","base","arbitrum","polygon","somnia","tempo"],zr=["multiversx","claws"],_r=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>R(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Append:{Prefix:"append:"},Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},y={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},Gt=typeof window<"u"?window:{open:()=>{}};var J={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},q={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${J.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${J.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Kr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var ot="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:ot,chainLogo:r=>`${ot}/chains/logos/${r}`,tokenLogo:r=>`${ot}/tokens/logos/${r}`,walletLogo:r=>`${ot}/wallets/logos/${r}`},Ue={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Zr=r=>Ue[r]??r.charAt(0).toUpperCase()+r.slice(1),De={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},Yr=(r,t="dark")=>{let e=De[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Pt=(r,t)=>r[t]??r.default??Object.values(r)[0],en=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Pt(r.logo,e)},rn=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Pt(r.logoUrl,e)},nn=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Pt(r.logoUrl,e)};var Tt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},Et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},z=null;function Jt(){if(z)return z;if(typeof window<"u"&&window.crypto)return z=new Tt,z;if(typeof process<"u"&&process.versions?.node)return z=new Et,z;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function sn(r){z=r}async function Qt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Jt()).getRandomBytes(r)}function Me(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function on(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Kt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Qt(r/2,t);return Me(e)}async function pn(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await Qt(16),r.randomBytes=!0}catch{}return r}function ln(){return Jt()}var dn=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var x=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},pt=r=>{if(r==="warp")return`warp:${J.Warp}`;if(r==="brand")return`brand:${J.Brand}`;if(r==="abi")return`abi:${J.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},N=(r,t)=>r?.actions[t-1],qe=["state","mount","unmount","loop"],k=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!qe.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},St=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,lt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Xt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),_=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),yn=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},G=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){if(t instanceof SyntaxError)return!1;throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var xn={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},ct=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},vn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,An=r=>r;var Y=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,In=(r,t)=>!r||!t?!1:Y(r)===Y(t),Rt=(r,t,e)=>{let n=Y(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},D=r=>{let t=decodeURIComponent(r).trim(),e=Y(t),n=e.split("?")[0],i=Zt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=ze(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},tt=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return D(i)},ze=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,_e=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Zt=r=>{let t=_e(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Zt(a);return[i,...s]},Yt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},te=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},ee=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Pn=r=>{let t=D(r);return(t?t.identifierBase:Y(r)).trim()},Tn=r=>{let t=r.indexOf("?");if(t===-1)return r;let e=new URLSearchParams(r.slice(t+1)),n=Array.from(e.entries()).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return r.slice(0,t)+"?"+n},En=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var $t=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},re=r=>{if(typeof r!="string")return!1;let t=new Set(Object.values(y));if(!r.includes(u.ArgParamsSeparator))return!1;let e=$t(r)[0],n=e.endsWith("[]")?e.slice(0,-2):e;return t.has(n)};var Nt=(r,t,e)=>ne(r.messages,t,e),jn=(r,t,e)=>!("messages"in r)||!r.messages?{}:ne(r.messages,t,e),ne=(r,t,e)=>{if(!r)return{};let n=Object.entries(r).map(([i,a])=>{let s=ct(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};import Ge from"qr-code-styling";var Q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!tt(t):!1}build(t,e,n){let i=this.config.clientUrl||q.DefaultClientUrl(this.config.env),a=x(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return q.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=D(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||q.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return q.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=x(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=x(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Ge({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Je="https://",Qe=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=_(r.when,t);if(!G(e))return null}return r.identifier},Ke=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),jt=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(Ke(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=Qe(a,e);s!==null&&i.push(s)}return i.length>0?i:null},zn=(r,t,e)=>jt(r,t,e)?.[0]??null,ie=(r,t,e,n,i)=>{if(n.startsWith(Je))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=V(a,{...e.vars,...i});return[{identifier:f,url:Ot(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=V(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Ot(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),W=g&&g[1]||"";return{placeholder:f,field:W?W.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:A,field:C}of h){let m=C?Xe(f,C):f;if(m==null)return null;g=g.replace(A,m)}if(g.includes("{{")||g.includes("}}"))return null;let W=g?`${a}?${g}`:a;return{identifier:W,url:Ot(t,W,r)}}).filter(f=>f!==null)},ut=(r,t,e,n,i)=>{let a=N(e,n)?.next||e.next||null,s=jt(a,"success",i);if(!s)return null;let p=s.flatMap(l=>ie(r,t,e,l,i));return p.length>0?p:null},dt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=N(e,n)?.next||e.next||null,l=jt(p,s,i);if(!l)return null;let o=l.flatMap(c=>ie(r,t,e,c,i));return o.length>0?o:null},Ot=(r,t,e)=>{let[n,i]=t.split("?"),a=new Q(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},_n=(r,t)=>{let e=[];for(let n of r){let i=typeof n=="string"?n:n.identifier,a=V(i,t);a&&e.push(a)}return e},Xe=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var ae={debug:0,info:1,warning:2,error:3},se="error",H=class H{static setLevel(t){se=t}static shouldLog(t){return ae[t]>=ae[se]}static debug(...t){!H.isTestEnv&&H.shouldLog("debug")&&console.debug(...t)}static info(...t){!H.isTestEnv&&H.shouldLog("info")&&console.info(...t)}static warn(...t){!H.isTestEnv&&H.shouldLog("warning")&&console.warn(...t)}static error(...t){!H.isTestEnv&&H.shouldLog("error")&&console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=H;function Ze(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function oe(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=oe(e[n],t[n]):e[n]=t[n]}),e}function Ye(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function F(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Ye(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ze(n.input.position,i,a);e=oe(e,s)}else e[i]=a}),e}function ft(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var pe=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=ir(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},et=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,W)=>g&&g[W]!==void 0?g[W]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=pe(r,e,p),d=K(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await le(r,c,t,e,n,i,a)}},le=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=tr(p,r,n,i,a),p=await er(r,p,e,i,a,s.transform?.runner||null),p},tr=(r,t,e,n,i)=>{let a={...r},s=N(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},er=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:rr(e),inputs:ft(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){v.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},rr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},ce=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=pe(r,e,s),c=await le(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:c}},nr=(r,t)=>{let e=r.split(".");return e[0]!=="out"?r:e.length===1?t:e.slice(1).reduce((n,i)=>n&&n[i]!==void 0?n[i]:null,t)},ue=(r,t,e)=>{if(!r.output)return t.output;let n={...t.output||{},...t.values?.mapped||{}},i={};for(let[a,s]of Object.entries(r.output)){let p=s.startsWith(u.Append.Prefix),l=p?s.slice(u.Append.Prefix.length):s,o=nr(l,n);if(p){let c=e?.[a],d=Array.isArray(c)?c:c!==void 0?[c]:[];i[a]=[...d,o]}else i[a]=o}return{...t.output,...i}},ir=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var ar=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:_t.some(t=>t in r),de=(r,t)=>{if(!ar(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var ai=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function sr(r,t,e,n=5){let i=await Kt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Bt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return sr(r,i,e,5)}function Lt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function li(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Bt(r,e,n),p=await t(i);return Lt(r,p,a,s)}function ci(r){let t=new Date(r).getTime();return Date.now()<t}function ui(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var or=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",pr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),fe=(r,t=24)=>{let e=pr(r);return e?e.slice(0,t):"action"},ge=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},lr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},fi=(r,t,e)=>{let n=fe((e||t||"").trim()||"action"),i=`${r.type}|${lr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=ge(i);return`private_src_${n}_${a}`},cr=r=>{let t=or(r),e=fe(t),n=ge(t.trim().toLowerCase());return`private_gen_${e}_${n}`},gi=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||cr(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},hi=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function yi(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function xi(r,t,e){return null}var ur=(r,t)=>{let e=null;try{e=k(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Ci=async(r,t,e,n)=>{try{let i=x(e,n),a=ur(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as dr,tempo as fr}from"mppx/client";async function he(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return v.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),dr.create({methods:[fr({account:e})],polyfill:!1}).fetch}return fetch}var gr=r=>{try{return JSON.parse(r)}catch{return null}},me=/^(.+)\[\]$/,ye={boolean:y.Bool,integer:y.Uint32,int:y.Uint32,number:y.Uint64},P=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=ye[t]??t,me.test(t)){let n=typeof e=="string"?gr(e):null;return t+u.ArgParamsSeparator+JSON.stringify(n??e)}if(t===y.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===y.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(y.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(y.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(y.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):y.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=ye[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(me.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===y.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[y.Option+u.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[y.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(y.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(y.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.Datetime)return[n,i];if(n===y.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var $i=r=>new P().nativeToString(y.String,r),Ni=r=>new P().nativeToString(y.Uint8,r),Oi=r=>new P().nativeToString(y.Uint16,r),ji=r=>new P().nativeToString(y.Uint32,r),Bi=r=>new P().nativeToString(y.Uint64,r),Li=r=>new P().nativeToString(y.Biguint,r),Vi=r=>new P().nativeToString(y.Bool,r),ki=r=>new P().nativeToString(y.Address,r),We=r=>new P().nativeToString(y.Asset,r),Hi=r=>new P().nativeToString(y.Hex,r),Fi=(r,t)=>{if(t===null)return y.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Ui=(...r)=>new P().nativeToString(y.Tuple,r),Di=r=>new P().nativeToString(y.Struct,r),Mi=r=>new P().nativeToString(y.Vector,r);import hr from"ajv";var xe=class{constructor(t){this.pendingBrand={protocol:pt("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||q.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new hr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import yr from"ajv";var ve={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{$ref:"#/definitions/WarpRelatedEntry"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},output:{additionalProperties:{type:"string"},type:"object"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpRelatedEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{bot:{type:"string"},identifier:{type:"string"}},required:["identifier"],type:"object"}]},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var Wr=new Set(["POST","PUT","PATCH","DELETE"]),xr=/^[A-Z][A-Z0-9_]*$/,gt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=k(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||xr.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!Wr.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():ve,n=new yr({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ht=class{constructor(t){this.config=t;this.pendingWarp={protocol:pt("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Xt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new gt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as kt,mkdirSync as vr,readdirSync as Ae,readFileSync as Ar,unlinkSync as Ht,writeFileSync as Cr}from"fs";import{join as Ce,resolve as be}from"path";var Vt="$bigint:",mt=(r,t)=>typeof t=="bigint"?Vt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Vt)?BigInt(t.slice(Vt.length)):t;var yt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?be(n):be(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){kt(this.cacheDir)||vr(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Ce(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!kt(e))return null;let n=Ar(e,"utf-8"),i=JSON.parse(n,X);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Ht(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);Cr(a,JSON.stringify(i,mt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);kt(e)&&Ht(e)}catch{}}async keys(t){try{let e=Ae(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{Ae(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Ht(Ce(this.cacheDir,e))})}catch{}}};var rt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,mt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{constructor(t,e){}async get(t){let e=U.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;U.cache.set(t,{value:e,expiresAt:i})}async delete(t){U.cache.delete(t)}async keys(t){let e=Array.from(U.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){U.cache.clear()}};U.cache=new Map;var nt=U;import{readFileSync as br}from"fs";import{resolve as we}from"path";var Wt=class{constructor(t,e){let n=e?.path?we(e.path):we(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=br(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return v.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var Ie={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},vt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},xt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new rt(t,e):e?.type==="memory"?new nt(t,e):e?.type==="static"?new Wt(t,e):e?.type==="filesystem"?new yt(t,e):typeof window<"u"&&window.localStorage?new rt(t,e):new nt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var it={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Ft={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ut=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Dt=r=>{try{return JSON.parse(r)}catch{return null}},wr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Bt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Lt(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=Ut(e.resolvedInputs,it.Headers,i);if(p){let l=Dt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},Ir=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Ft.Get){let s=Ut(e.resolvedInputs,it.Queries,i);if(s){let p=Dt(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},Pr=(r,t,e,n,i)=>{if(r===Ft.Get)return;let a=Ut(t.resolvedInputs,it.Payload,n);if(a&&Dt(a)!==null)return a;let{[it.Payload]:s,[it.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Pe=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Ft.Get,o=await wr(r,t,e,n,a,p),c=Ir(r,t,e,l,a),d=Pr(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var B=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Tr(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=R(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return V(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=x(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},Tr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var Er=["collect","compute","mcp","state","mount","unmount"],Z=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new P,this.cache=new xt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(vt.WarpExecutable(t,e||"",n))||[];return F(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(vt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=N(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=x(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),c=N(o,e),{action:d,index:h}=k(o),f=[],g=[];if(h===e-1){let E=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,E,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let W=g.find(E=>E.input.position==="receiver"||E.input.position==="destination")?.value,A=this.getDestinationFromAction(c),C=W?this.serializer.stringToNative(W)[1]:A;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!Er.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(c,g);m=m.map(E=>l.applyInputs(E,g,this.serializer));let w=g.find(E=>E.input.position==="value")?.value||null,b="value"in c?c.value:null,j=w?.split(u.ArgParamsSeparator)[1]||b||"0",T=l.applyInputs(j,g,this.serializer),I=BigInt(T),$=g.filter(E=>E.input.position==="transfer"&&E.value).map(E=>E.value),M=[...("transfers"in c?c.transfers:[])||[],...$||[]].map(E=>{let It=l.applyInputs(E,g,this.serializer),Ne=It.startsWith(`asset${u.ArgParamsSeparator}`)?It:`asset${u.ArgParamsSeparator}${It}`;return this.serializer.stringToNative(Ne)[1]}),wt=g.find(E=>E.input.position==="data")?.value,Re="data"in c?c.data||"":null,Mt=wt||Re||null,$e=Mt?l.applyInputs(Mt,g,this.serializer):null,qt={adapter:p,warp:o,chain:s,action:e,destination:C,args:m,value:I,transfers:M,data:$e,resolvedInputs:g};return await this.cache.set(vt.WarpExecutable(this.config.env,o.meta?.hash||"",e),qt.resolvedInputs,Ie.OneWeek),qt}async getChainInfoForWarp(t,e){if(t.chain)return x(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||re(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let A=R(this.config,t);return A?this.serializer.nativeToString("address",A):null}if(c.source==="hidden"){if(c.default===void 0)return null;let A=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,A)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),W=f||g;return W?this.serializer.nativeToString(c.type,String(W)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=N(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=x(a.name,this.adapters),p=new B(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=lt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=lt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ft(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=$t(e),a=x(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=lt(p,o.decimals);return We({...o,amount:c})}else return e}catch(n){throw v.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return x(s,this.adapters).chainInfo}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this._checkpointIndex=null;this.handlers=n,this.factory=new Z(t,e),t.logLevel&&v.setLevel(t.logLevel)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},h=n.scope||"default",f=t.meta?.identifier||"",g=`warp-checkpoint:${h}:${f}`,W=await this.factory.getCache().get(g),A=W?.identifier===f?W:void 0;if(A&&Object.assign(d,A.outputs),t.vars)try{let m=this.adapters?.find(w=>w.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(m){let w=await new B(this.config,m,this.adapters).apply(t,c);w?.actions&&(t.actions=w.actions),w?.meta&&(t.meta=w.meta)}}catch{}let{index:C}=k(t);for(let m=1;m<=t.actions.length;m++){let w=N(t,m);if(!St(w))continue;if(A&&m<=A.actionIndex){v.debug(`[WarpExecutor] skipping action ${m} (checkpoint resume)`);continue}let b=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c;v.debug(`[WarpExecutor] action ${m}/${t.actions.length}:`,{type:w.type,label:w.label||w.as||"",when:w.when||null}),this._checkpointIndex=null;let{tx:j,chain:T,immediateExecution:I,executable:$}=await this.executeAction(t,m,e,b);if(this._checkpointIndex!==null){let L={identifier:f,actionIndex:this._checkpointIndex,outputs:{...d}};return await this.factory.getCache().set(g,L),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p,outputs:{...d},checkpoint:L}}if(I?.output){let{_DATA:L,...O}=I.output,M=Object.keys(O);v.debug(`[WarpExecutor] action ${m} output keys:`,M.length>0?M:"(empty)"),Object.assign(d,O)}else v.debug(`[WarpExecutor] action ${m}: no output`);if(I?.values?.mapped){let L=Object.keys(I.values.mapped);v.debug(`[WarpExecutor] action ${m} mapped keys:`,L),Object.assign(d,I.values.mapped)}if($?.resolvedInputs){let L=$.resolvedInputs.filter(O=>O.input.as).map(O=>[O.input.as,O.value]);v.debug(`[WarpExecutor] action ${m} resolved inputs:`,Object.fromEntries(L));for(let O of $.resolvedInputs){let M=O.input.as;if(M&&O.value!==null&&O.value!==void 0){let[,wt]=this.factory.getSerializer().stringToNative(O.value);d[M]=wt??O.value}}}v.debug(`[WarpExecutor] action ${m} outputBag keys:`,Object.keys(d)),I&&(I.envs={...b.envs,...d},s.push(I)),j&&i.push(j),T&&(a=T),$&&m===C+1&&$.resolvedInputs&&(p=F($.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let m=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(m))}return this.scheduleLoops(t,e,c,d),A&&(await this.factory.getCache().get(g))?.identifier===f&&await this.factory.getCache().delete(g),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p,outputs:{...d}}}async executeAction(t,e,n,i={}){let a=N(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Gt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=_(a.when,o);if(!G(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let m=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],m))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a;v.debug("[WarpExecutor] resolving inline warp:",{identifier:o.warp,query:o.warp?.split("?")[1]});let c=await this.warpResolver(o.warp);if(!c)return v.debug("[WarpExecutor] inline warp not found:",{identifier:o.warp}),{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[m,w]of Object.entries(c.meta?.query||{}))h[m]=w.replace(/\{\{(.+?)\}\}/g,(b,j)=>{let T=d[j.trim()];return T==null?"":typeof T=="object"?JSON.stringify(T):String(T)});c.meta={...c.meta,query:h};let f=new Set(Object.keys(h)),g=c.actions?.flatMap(m=>m.inputs||[]).filter(m=>m.source==="field"&&m.required&&!f.has(m.as||m.name))||[];if(g.length>0&&this.handlers?.onInputRequest){let m=Object.fromEntries(Object.entries(h).map(([w,b])=>[w,String(b)]));return this._checkpointIndex=e,await this.handlers.onInputRequest(c,g,m),{tx:null,chain:null,immediateExecution:null,executable:null}}let W=this.handlers?.onActionExecuted;o.silent&&(this.handlers.onActionExecuted=void 0);let{immediateExecutions:A}=await this.execute(c,[],i);o.silent&&(this.handlers.onActionExecuted=W);let C=A[0];if(v.debug("[WarpExecutor] inline warp result:",{identifier:o.warp,hasOutput:!!C?.output,outputKeys:C?.output?Object.keys(C.output).filter(m=>m!=="_DATA"):[],status:C?.status}),C){if(o.silent||await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:C,tx:null})),o.output){let m=ue(o,C,i.envs);return{tx:null,chain:null,immediateExecution:{...C,output:m},executable:null}}return{tx:null,chain:null,immediateExecution:C,executable:null}}return{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=x(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=x(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!St(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:R(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=Sr(c,d.output);return d.next=dt(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=R(this.config,t.chain.name),a=N(t.warp,t.action),s=this.factory.getSerializer(),p=K(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await et(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=R(this.config,t.chain.name),n=this.factory.getSerializer(),i=K(t.resolvedInputs,n),{values:a,output:s}=await et(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new B(this.config,x(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await Pe(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));if(s){o=V(o,s);for(let[f,g]of d.entries())d.set(f,V(g,s))}v.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},W=await(await he(this.adapters))(o,f);v.debug("Collect response status",{status:W.status});let A=await W.json();v.debug("Collect response content",{content:A});let{values:C,output:m}=await et(t.warp,A,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,R(this.config,t.chain.name),W.ok?"success":"error",C,m,A)}catch(f){v.error("WarpActionExecutor: Error executing collect",f);let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=R(this.config,t.chain.name),i=N(t.warp,t.action);if(!i.destination){let f=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}let p=this.factory.getSerializer(),l=new B(this.config,x(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let W=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=W}),v.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let W={};t.resolvedInputs.forEach(({input:b,value:j})=>{if(j&&b.position&&typeof b.position=="string"&&b.position.startsWith("payload:")){let T=b.position.replace("payload:",""),[I,$]=p.stringToNative(j);if(I==="string")W[T]=String($);else if(I==="bool")W[T]=!!$;else if(I==="uint8"||I==="uint16"||I==="uint32"||I==="uint64"||I==="uint128"||I==="uint256"||I==="biguint"){let L=Number($);W[T]=(Number.isInteger(L),L)}else W[T]=$}}),e&&Object.assign(W,e);let A=await g.callTool({name:d,arguments:W});await g.close();let C;if(A.content&&A.content.length>0){let b=A.content[0];if(b.type==="text")try{C=JSON.parse(b.text)}catch{C=b.text}else b.type,C=b}else C=A;let{values:m,output:w}=await et(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",m,w,A)}catch(f){v.error("WarpExecutor: Error executing MCP",f);let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=dt(this.config,this.adapters,t.warp,t.action,a,n),l=F(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||R(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Nt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=_(s.when,h);try{if(!G(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),v.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=_(e.when,l);if(!G(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,W)=>{let A=o[W.trim()];return A!=null?String(A):h});c[d]=Rr(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=x(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),c=N(o,n),d=[];if(e.inputs&&e.inputs.length>0){let b=this.factory.getStringTypedInputs(e,i),j=await this.factory.getResolvedInputs(s.name,e,b,l,a.queries);d=await this.factory.getModifiedInputs(j)}else{let{action:b}=k(o),j=this.factory.getStringTypedInputs(b,i),T=await this.factory.getResolvedInputs(s.name,b,j,l,a.queries);d=await this.factory.getModifiedInputs(T)}let h=de(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=V(f,a.envs));let g=F(d),W=R(this.config,s.name),A=this.factory.getSerializer(),{values:C,output:m}=await ce(o,f,n,d,A,this.config);if(this.handlers?.onPromptGenerate){let b=await this.handlers.onPromptGenerate(f,c.expect);b&&(m.MESSAGE=b,c.as&&(m[c.as]=b))}let w=d.find(b=>b.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:W,txHash:null,tx:null,next:ut(this.config,this.adapters,o,n,m),values:C,output:m,messages:Nt(o,{...C.mapped,...m},this.config),destination:w,resolvedInputs:g}}catch(s){return v.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:dt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=x(p.name,this.adapters),o=new B(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=_(e.when,h);return v.debug("[WarpExecutor] when condition:",{action:e.label||e.type,expression:e.when,interpolated:f,mergedBag:h}),G(f)}},Sr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},Rr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Ct=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw v.error("WarpIndex: Error searching for warps: ",i),i}}};var bt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!tt(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?tt(t):D(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Yt(t):te(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let W=`${i.chain}:${s}`;g=await this.resolver.getByAlias(W,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=x(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let W=await g.registry.getInfoByHash(s,e);l=W.registryInfo,o=W.brand}else if(a==="alias"){let W=await g.registry.getInfoByAlias(s,e);l=W.registryInfo,o=W.brand,W.registryInfo&&(p=await g.builder().createFromTransactionHash(W.registryInfo.hash,e))}}if(p&&p.meta&&($r(p,i.chain,l,i.identifier),p.meta.query=c?ee(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new B(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return v.error("Error detecting warp link",a),n}}},$r=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Rt(null,"alias",e.alias):Rt(t,"hash",e?.hash??n))};var Te=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new at(e));return new st(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new At(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new bt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await x(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return x(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=D(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return x(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!R(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return x(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return x(t,this.chains).explorer}getOutput(t){return x(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??k(e).index+1,p=await x(t,this.chains).output.getActionExecution(e,a,n);return p.next=ut(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=x(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return x(t,this.chains).dataLoader}getWallet(t){return x(t,this.chains).wallet}get factory(){return new Z(this.config,this.chains)}get index(){return new Ct(this.config)}get linkBuilder(){return new Q(this.config,this.chains)}createBuilder(t){return t?x(t,this.chains).builder():new ht(this.config)}createAbiBuilder(t){return x(t,this.chains).abiBuilder()}createBrandBuilder(t){return x(t,this.chains).brandBuilder()}createSerializer(t){return x(t,this.chains).serializer}resolveText(t){return ct(t,this.config)}};var Ee=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function As(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(Se(t,n)!==i)return!1;return!0}function Cs(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?Se(t,i):i;return e}function Se(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{Tt as BrowserCryptoProvider,_r as CLOUD_WALLET_PROVIDERS,Ie as CacheTtl,qr as EvmWalletChainNames,zr as MultiversxWalletChainNames,Et as NodeCryptoProvider,xn as WARP_LANGUAGES,S as WarpAssets,xe as WarpBrandBuilder,ht as WarpBuilder,xt as WarpCache,vt as WarpCacheKey,Ue as WarpChainDisplayNames,De as WarpChainLogos,Fe as WarpChainName,at as WarpChainResolver,Te as WarpClient,st as WarpCompositeResolver,q as WarpConfig,u as WarpConstants,At as WarpExecutor,Z as WarpFactory,Ct as WarpIndex,y as WarpInputTypes,B as WarpInterpolator,Q as WarpLinkBuilder,bt as WarpLinkDetecter,v as WarpLogger,zt as WarpPlatformName,_t as WarpPlatforms,J as WarpProtocolVersions,P as WarpSerializer,Ee as WarpTypeRegistry,gt as WarpValidator,ki as address,Nt as applyOutputToMessages,We as asset,Li as biguint,Vi as bool,cr as buildGeneratedFallbackWarpIdentifier,fi as buildGeneratedSourceWarpIdentifier,ft as buildInputsContext,K as buildMappedOutput,Ze as buildNestedPayload,on as bytesToBase64,Me as bytesToHex,Ci as checkWarpAssetBalance,Y as cleanWarpIdentifier,Lt as createAuthHeaders,Bt as createAuthMessage,ln as createCryptoProvider,xi as createDefaultWalletProvider,li as createHttpAuthHeaders,sr as createSignableMessage,An as createWarpI18nText,Rt as createWarpIdentifier,yn as doesWarpRequireWallet,Tn as encodeQueryValues,le as evaluateOutputCommon,G as evaluateWhenCondition,et as extractCollectOutput,tt as extractIdentifierInfoFromUrl,ue as extractInlineOutput,ce as extractPromptOutput,te as extractQueryStringFromIdentifier,Yt as extractQueryStringFromUrl,F as extractResolvedInputValues,dn as extractWarpSecrets,x as findWarpAdapterForChain,Zr as getChainDisplayName,Yr as getChainLogo,Jt as getCryptoProvider,or as getGeneratedSourceWarpName,pt as getLatestProtocolIdentifier,he as getMppFetch,ut as getNextInfo,dt as getNextInfoForStatus,ai as getProviderConfig,Qt as getRandomBytes,Kt as getRandomHex,ur as getRequiredAssetIds,jr as getWalletFromConfigOrFail,N as getWarpActionByIndex,en as getWarpBrandLogoUrl,rn as getWarpChainAssetLogoUrl,nn as getWarpChainInfoLogoUrl,En as getWarpIdentifierWithQuery,D as getWarpInfoFromIdentifier,k as getWarpInputAction,Oe as getWarpWalletAddress,R as getWarpWalletAddressFromConfig,Le as getWarpWalletExternalId,Ve as getWarpWalletExternalIdFromConfig,Vr as getWarpWalletExternalIdFromConfigOrFail,Be as getWarpWalletMnemonic,Lr as getWarpWalletMnemonicFromConfig,je as getWarpWalletPrivateKey,Br as getWarpWalletPrivateKeyFromConfig,re as hasInputPrefix,Hi as hex,yi as initializeWalletCache,In as isEqualWarpIdentifier,hi as isGeneratedSourcePrivateIdentifier,ar as isPlatformValue,St as isWarpActionAutoExecute,vn as isWarpI18nText,kr as isWarpWalletReadOnly,As as matchesTrigger,oe as mergeNestedPayload,Ur as normalizeAndValidateMnemonic,ke as normalizeMnemonic,Fi as option,ir as parseOutputOutIndex,ui as parseSignedMessage,ee as parseWarpQueryStringToObject,Pn as removeWarpChainPrefix,Fr as removeWarpWalletFromConfig,V as replacePlaceholders,_ as replacePlaceholdersInWhenExpression,jn as resolveActionMessages,Cs as resolveInputs,zn as resolveNextString,jt as resolveNextStrings,Se as resolvePath,de as resolvePlatformValue,_n as resolveRelatedEntries,ct as resolveWarpText,Gt as safeWindow,sn as setCryptoProvider,Hr as setWarpWalletInConfig,lt as shiftBigintBy,$t as splitInput,gi as stampGeneratedWarpMeta,$i as string,Di as struct,pn as testCryptoAvailability,Ye as toInputPayloadValue,Xt as toPreviewText,Ui as tuple,Oi as uint16,ji as uint32,Bi as uint64,Ni as uint8,He as validateMnemonicLength,ci as validateSignedMessage,Mi as vector,Kr as withAdapterFallback};
1
+ var at=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var st=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Br=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},je=r=>r?typeof r=="string"?r:r.address:null,R=(r,t)=>je(r.user?.wallets?.[t]||null),Be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Le=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ve=r=>r?typeof r=="string"?r:r.externalId||null:null,Lr=(r,t)=>Be(r.user?.wallets?.[t]||null)?.trim()||null,Vr=(r,t)=>Le(r.user?.wallets?.[t]||null)?.trim()||null,ke=(r,t)=>Ve(r.user?.wallets?.[t]||null)?.trim()||null,kr=(r,t)=>{let e=ke(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Hr=r=>typeof r=="string",Fr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Ur=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},He=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Fe=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},Dr=(r,t=24)=>{let e=He(r);return Fe(e,t),e};var Ue=(h=>(h.Multiversx="multiversx",h.Claws="claws",h.Sui="sui",h.Ethereum="ethereum",h.Base="base",h.Arbitrum="arbitrum",h.Polygon="polygon",h.Somnia="somnia",h.Tempo="tempo",h.Fastset="fastset",h.Solana="solana",h.Near="near",h))(Ue||{}),zt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(zt||{}),_t=Object.values(zt),zr=["ethereum","base","arbitrum","polygon","somnia","tempo"],_r=["multiversx","claws"],Gr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>R(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Append:{Prefix:"append:"},Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},y={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex",Datetime:"datetime",Email:"email",Textarea:"textarea",File:"file"},Gt=typeof window<"u"?window:{open:()=>{}};var J={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},q={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${J.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${J.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.joai.ai":r==="testnet"?"https://testnet.joai.ai":"https://joai.ai",SuperClientUrls:["https://joai.ai","https://devnet.joai.ai","https://testnet.joai.ai","https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",u.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","string[]","json","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Xr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var ot="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:ot,chainLogo:r=>`${ot}/chains/logos/${r}`,tokenLogo:r=>`${ot}/tokens/logos/${r}`,walletLogo:r=>`${ot}/wallets/logos/${r}`},De={multiversx:"MultiversX",claws:"Claws Network",sui:"Sui",ethereum:"Ethereum",base:"Base",arbitrum:"Arbitrum",polygon:"Polygon",somnia:"Somnia",tempo:"Tempo",fastset:"Fastset",solana:"Solana",near:"NEAR"},Yr=r=>De[r]??r.charAt(0).toUpperCase()+r.slice(1),Me={ethereum:{light:S.chainLogo("ethereum-white.svg"),dark:S.chainLogo("ethereum-black.svg")},base:{light:S.chainLogo("base-white.svg"),dark:S.chainLogo("base-black.svg")},arbitrum:S.chainLogo("arbitrum.svg"),polygon:S.chainLogo("polygon.svg"),somnia:S.chainLogo("somnia.png"),tempo:{light:S.chainLogo("tempo-white.svg"),dark:S.chainLogo("tempo-black.svg")},multiversx:S.chainLogo("multiversx.svg"),claws:S.chainLogo("claws.png"),sui:S.chainLogo("sui.svg"),solana:S.chainLogo("solana.svg"),near:{light:S.chainLogo("near-white.svg"),dark:S.chainLogo("near-black.svg")},fastset:{light:S.chainLogo("fastset-white.svg"),dark:S.chainLogo("fastset-black.svg")}},tn=(r,t="dark")=>{let e=Me[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Pt=(r,t)=>r[t]??r.default??Object.values(r)[0],rn=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Pt(r.logo,e)},nn=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Pt(r.logoUrl,e)},an=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Pt(r.logoUrl,e)};var Tt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},Et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},z=null;function Jt(){if(z)return z;if(typeof window<"u"&&window.crypto)return z=new Tt,z;if(typeof process<"u"&&process.versions?.node)return z=new Et,z;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function on(r){z=r}async function Qt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Jt()).getRandomBytes(r)}function qe(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function pn(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Kt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Qt(r/2,t);return qe(e)}async function ln(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await Qt(16),r.randomBytes=!0}catch{}return r}function cn(){return Jt()}var fn=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${u.Vars.Env}:`)).map(t=>{let e=t.replace(`${u.Vars.Env}:`,"").trim(),[n,i]=e.split(u.ArgCompositeSeparator);return{key:n,description:i||null}});var x=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},pt=r=>{if(r==="warp")return`warp:${J.Warp}`;if(r==="brand")return`brand:${J.Brand}`;if(r==="abi")return`abi:${J.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},N=(r,t)=>r?.actions[t-1],ze=["state","mount","unmount","loop"],k=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!ze.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},St=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,lt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Xt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="object"&&i!==null?JSON.stringify(i):String(i)}),_=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`:typeof i=="object"&&i!==null?`'${JSON.stringify(i).replace(/'/g,"\\'")}'`:String(i)}),Wn=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===u.Source.UserWallet||n.default===`{{${u.Globals.UserWallet.Placeholder}}}`||n.default===`{{${u.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},G=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){if(t instanceof SyntaxError)return!1;throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var vn={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},ct=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},An=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Cn=r=>r;var Y=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Zt=r=>{let t=r.indexOf("?");return t===-1?r:r.slice(0,t)},Pn=(r,t)=>!r||!t?!1:Zt(Y(r))===Zt(Y(t)),Rt=(r,t,e)=>{let n=Y(e);if(t===u.IdentifierType.Alias)return u.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+u.IdentifierParamSeparator+t+u.IdentifierParamSeparator+n},D=r=>{let t=decodeURIComponent(r).trim(),e=Y(t),n=e.split("?")[0],i=Yt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:null,type:u.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let l=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:l,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,l=_e(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:l,identifier:p,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},tt=r=>{let t=new URL(r),n=t.searchParams.get(u.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return D(i)},_e=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ge=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Yt=r=>{let t=Ge(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Yt(a);return[i,...s]},te=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},ee=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},re=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Tn=r=>{let t=D(r);return(t?t.identifierBase:Y(r)).trim()},En=r=>{let t=r.indexOf("?");if(t===-1)return r;let e=new URLSearchParams(r.slice(t+1)),n=Array.from(e.entries()).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return r.slice(0,t)+"?"+n},Sn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var $t=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},ne=r=>{if(typeof r!="string")return!1;let t=new Set(Object.values(y));if(!r.includes(u.ArgParamsSeparator))return!1;let e=$t(r)[0],n=e.endsWith("[]")?e.slice(0,-2):e;return t.has(n)};var Nt=(r,t,e)=>ie(r.messages,t,e),Bn=(r,t,e)=>!("messages"in r)||!r.messages?{}:ie(r.messages,t,e),ie=(r,t,e)=>{if(!r)return{};let n=Object.entries(r).map(([i,a])=>{let s=ct(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};import Je from"qr-code-styling";var Q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!tt(t):!1}build(t,e,n){let i=this.config.clientUrl||q.DefaultClientUrl(this.config.env),a=x(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,p=a.chainInfo.name+u.IdentifierParamSeparator+s,l=encodeURIComponent(p);return q.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${u.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=D(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||q.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return q.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=x(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let l=x(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Je({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Qe="https://",Ke=(r,t)=>{if(typeof r=="string")return r;if(r.when&&t){let e=_(r.when,t);if(!G(e))return null}return r.identifier},Xe=r=>typeof r=="object"&&!Array.isArray(r)&&!("identifier"in r),jt=(r,t,e)=>{if(!r)return null;let n;if(typeof r=="string")n=t==="success"?[r]:[];else if(Array.isArray(r))n=t==="success"?r:[];else if(Xe(r)){let a=r[t];n=a?Array.isArray(a)?a:[a]:[]}else n=t==="success"?[r]:[];if(n.length===0)return null;let i=[];for(let a of n){let s=Ke(a,e);s!==null&&i.push(s)}return i.length>0?i:null},_n=(r,t,e)=>jt(r,t,e)?.[0]??null,ae=(r,t,e,n,i)=>{if(n.startsWith(Qe))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let f=V(a,{...e.vars,...i});return[{identifier:f,url:Ot(t,f,r)}]}let p=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let f=V(s,{...e.vars,...i}),g=f?`${a}?${f}`:a;return[{identifier:g,url:Ot(t,g,r)}]}let l=p[0];if(!l)return[];let o=l.match(/{{([^[]+)\[\]/),c=o?o[1]:null;if(!c||i[c]===void 0)return[];let d=Array.isArray(i[c])?i[c]:[i[c]];if(d.length===0)return[];let h=p.filter(f=>f.includes(`{{${c}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),W=g&&g[1]||"";return{placeholder:f,field:W?W.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(f=>{let g=s;for(let{regex:A,field:C}of h){let m=C?Ze(f,C):f;if(m==null)return null;g=g.replace(A,m)}if(g.includes("{{")||g.includes("}}"))return null;let W=g?`${a}?${g}`:a;return{identifier:W,url:Ot(t,W,r)}}).filter(f=>f!==null)},ut=(r,t,e,n,i)=>{let a=N(e,n)?.next||e.next||null,s=jt(a,"success",i);if(!s)return null;let p=s.flatMap(l=>ae(r,t,e,l,i));return p.length>0?p:null},dt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",p=N(e,n)?.next||e.next||null,l=jt(p,s,i);if(!l)return null;let o=l.flatMap(c=>ae(r,t,e,c,i));return o.length>0?o:null},Ot=(r,t,e)=>{let[n,i]=t.split("?"),a=new Q(e,r).buildFromPrefixedIdentifier(n);if(!a)throw new Error(`Cannot build URL for identifier: ${n}`);if(!i)return a;let s=new URL(a);return new URLSearchParams(i).forEach((p,l)=>s.searchParams.set(l,p)),s.toString().replace(/\/\?/,"?")},Gn=(r,t)=>{let e=[];for(let n of r){let i=typeof n=="string"?n:n.identifier,a=V(i,t);a&&e.push(a)}return e},Ze=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var se={debug:0,info:1,warning:2,error:3},oe="error",H=class H{static setLevel(t){oe=t}static shouldLog(t){return se[t]>=se[oe]}static debug(...t){!H.isTestEnv&&H.shouldLog("debug")&&console.debug(...t)}static info(...t){!H.isTestEnv&&H.shouldLog("info")&&console.info(...t)}static warn(...t){!H.isTestEnv&&H.shouldLog("warning")&&console.warn(...t)}static error(...t){!H.isTestEnv&&H.shouldLog("error")&&console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=H;function Ye(r,t,e){return r.startsWith(u.Position.Payload)?r.slice(u.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function pe(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=pe(e[n],t[n]):e[n]=t[n]}),e}function tr(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function F(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=tr(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ye(n.input.position,i,a);e=pe(e,s)}else e[i]=a}),e}function ft(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let c=o;if("identifier"in c&&"amount"in c){let d=String(c.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(c.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var le=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(u.Transform.Prefix))continue;let l=ar(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...c]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(c);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},et=async(r,t,e,n,i,a)=>{let s=(h,f)=>f.reduce((g,W)=>g&&g[W]!==void 0?g[W]:null,h),p=h=>h.length===0?t:s(t,h),{stringValues:l,nativeValues:o,output:c}=le(r,e,p),d=K(n,i);for(let h of n)if(h.input.position==="local"){let f=h.input.as||h.input.name;if(f&&h.value){let[,g]=i.stringToNative(h.value);d[f]=g}}return{values:{string:l,native:o,mapped:d},output:await ce(r,c,t,e,n,i,a)}},ce=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=er(p,r,n,i,a),p=await rr(r,p,e,i,a,s.transform?.runner||null),p},er=(r,t,e,n,i)=>{let a={...r},s=N(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},rr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:nr(e),inputs:ft(n,i)};for(let{key:o,code:c}of p)try{s[o]=await a.run(c,l),l[o]=s[o]}catch(d){v.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},nr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},ue=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=le(r,e,s),c=await ce(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:c}},ir=(r,t)=>{let e=r.split(".");return e[0]!=="out"?r:e.length===1?t:e.slice(1).reduce((n,i)=>n&&n[i]!==void 0?n[i]:null,t)},de=(r,t,e)=>{if(!r.output)return t.output;let n={...t.output||{},...t.values?.mapped||{}},i={};for(let[a,s]of Object.entries(r.output)){let p=s.startsWith(u.Append.Prefix),l=p?s.slice(u.Append.Prefix.length):s,o=ir(l,n);if(p){let c=e?.[a],d=Array.isArray(c)?c:c!==void 0?[c]:[];i[a]=[...d,o]}else i[a]=o}return{...t.output,...i}},ar=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var sr=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:_t.some(t=>t in r),fe=(r,t)=>{if(!sr(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var si=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function or(r,t,e,n=5){let i=await Kt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Bt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return or(r,i,e,5)}function Lt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function ci(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Bt(r,e,n),p=await t(i);return Lt(r,p,a,s)}function ui(r){let t=new Date(r).getTime();return Date.now()<t}function di(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var pr=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",lr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ge=(r,t=24)=>{let e=lr(r);return e?e.slice(0,t):"action"},he=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},cr=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},gi=(r,t,e)=>{let n=ge((e||t||"").trim()||"action"),i=`${r.type}|${cr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=he(i);return`private_src_${n}_${a}`},ur=r=>{let t=pr(r),e=ge(t),n=he(t.trim().toLowerCase());return`private_gen_${e}_${n}`},hi=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||ur(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},mi=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Wi(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function vi(r,t,e){return null}var dr=(r,t)=>{let e=null;try{e=k(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},bi=async(r,t,e,n)=>{try{let i=x(e,n),a=dr(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{Mppx as fr,tempo as gr}from"mppx/client";async function me(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return v.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),fr.create({methods:[gr({account:e})],polyfill:!1}).fetch}return fetch}var hr=r=>{try{return JSON.parse(r)}catch{return null}},ye=/^(.+)\[\]$/,We={boolean:y.Bool,integer:y.Uint32,int:y.Uint32,number:y.Uint64},P=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=We[t]??t,ye.test(t)){let n=typeof e=="string"?hr(e):null;return t+u.ArgParamsSeparator+JSON.stringify(n??e)}if(t===y.Tuple&&Array.isArray(e)){if(e.length===0)return t+u.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(u.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(u.ArgCompositeSeparator)})${u.ArgParamsSeparator}${a.join(u.ArgListSeparator)}`}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===y.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${u.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t.startsWith(y.Vector)&&Array.isArray(e)){if(e.length===0)return`${t}${u.ArgParamsSeparator}`;let i=t.includes(u.IdentifierParamSeparator)?t.split(u.IdentifierParamSeparator)[1]:typeof e[0]=="string"&&e[0].includes(u.ArgParamsSeparator)?e[0].substring(0,e[0].indexOf(u.ArgParamsSeparator)):null;if(!i)return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator);let a=e.map(p=>{if(typeof p=="string"&&p.includes(u.ArgParamsSeparator)){let l=p.indexOf(u.ArgParamsSeparator),o=p.substring(l+1);return i.startsWith(y.Tuple)?o.replace(u.ArgListSeparator,u.ArgCompositeSeparator):o}return String(p)}),s=i.startsWith(y.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a.join(s)}if(t===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):y.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t==="json"?t+u.ArgParamsSeparator+JSON.stringify(e):t+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=We[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(ye.test(n)){if(!i)return[n,[]];try{return[n,JSON.parse(i)]}catch{return[n,i]}}if(n==="null")return[n,null];if(n===y.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[y.Option+u.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(p?p.split(l):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[y.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(y.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),p=i.split(u.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(y.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;p[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.Datetime)return[n,i];if(n===y.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}if(n==="json")try{return[n,JSON.parse(i)]}catch{return[n,i]}if(n==="chain"||n==="nft"||n==="email"||n==="textarea"||n==="file")return[n,i];throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(u.ArgParamsSeparator)){let[e,n]=t.split(u.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var Ni=r=>new P().nativeToString(y.String,r),Oi=r=>new P().nativeToString(y.Uint8,r),ji=r=>new P().nativeToString(y.Uint16,r),Bi=r=>new P().nativeToString(y.Uint32,r),Li=r=>new P().nativeToString(y.Uint64,r),Vi=r=>new P().nativeToString(y.Biguint,r),ki=r=>new P().nativeToString(y.Bool,r),Hi=r=>new P().nativeToString(y.Address,r),xe=r=>new P().nativeToString(y.Asset,r),Fi=r=>new P().nativeToString(y.Hex,r),Ui=(r,t)=>{if(t===null)return y.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Di=(...r)=>new P().nativeToString(y.Tuple,r),Mi=r=>new P().nativeToString(y.Struct,r),qi=r=>new P().nativeToString(y.Vector,r);import mr from"ajv";var ve=class{constructor(t){this.pendingBrand={protocol:pt("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||q.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new mr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Wr from"ajv";var Ae={$ref:"#/definitions/Warp",$schema:"http://json-schema.org/draft-07/schema#",definitions:{Warp:{additionalProperties:!1,properties:{actions:{items:{$ref:"#/definitions/WarpAction"},type:"array"},bot:{type:"string"},chain:{$ref:"#/definitions/WarpChainName"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},meta:{$ref:"#/definitions/WarpMeta"},name:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},output:{additionalProperties:{$ref:"#/definitions/WarpResulutionPath"},type:"object"},preview:{type:"string"},protocol:{type:"string"},related:{items:{$ref:"#/definitions/WarpRelatedEntry"},type:"array"},schedule:{$ref:"#/definitions/WarpSchedule"},sections:{items:{$ref:"#/definitions/WarpSection"},type:"array"},title:{$ref:"#/definitions/WarpText"},trigger:{$ref:"#/definitions/WarpTrigger"},ui:{type:"string"},vars:{additionalProperties:{type:"string"},type:"object"}},required:["protocol","name","title","description","actions"],type:"object"},WarpAction:{anyOf:[{$ref:"#/definitions/WarpTransferAction"},{$ref:"#/definitions/WarpContractAction"},{$ref:"#/definitions/WarpQueryAction"},{$ref:"#/definitions/WarpCollectAction"},{$ref:"#/definitions/WarpComputeAction"},{$ref:"#/definitions/WarpLinkAction"},{$ref:"#/definitions/WarpMcpAction"},{$ref:"#/definitions/WarpPromptAction"},{$ref:"#/definitions/WarpStateAction"},{$ref:"#/definitions/WarpMountAction"},{$ref:"#/definitions/WarpUnmountAction"},{$ref:"#/definitions/WarpLoopAction"},{$ref:"#/definitions/WarpInlineAction"}]},WarpActionInput:{additionalProperties:!1,properties:{as:{type:"string"},bot:{type:"string"},default:{type:["string","number","boolean"]},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},label:{$ref:"#/definitions/WarpText"},max:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},min:{anyOf:[{type:"number"},{$ref:"#/definitions/WarpVarPlaceholder"}]},modifier:{type:"string"},name:{type:"string"},options:{anyOf:[{items:{type:"string"},type:"array"},{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"}]},pattern:{type:"string"},patternDescription:{$ref:"#/definitions/WarpText"},position:{$ref:"#/definitions/WarpActionInputPosition"},required:{type:"boolean"},source:{$ref:"#/definitions/WarpActionInputSource"},type:{$ref:"#/definitions/WarpActionInputType"}},required:["name","type","source"],type:"object"},WarpActionInputPosition:{anyOf:[{const:"receiver",type:"string"},{const:"value",type:"string"},{const:"transfer",type:"string"},{const:"arg:1",type:"string"},{const:"arg:2",type:"string"},{const:"arg:3",type:"string"},{const:"arg:4",type:"string"},{const:"arg:5",type:"string"},{const:"arg:6",type:"string"},{const:"arg:7",type:"string"},{const:"arg:8",type:"string"},{const:"arg:9",type:"string"},{const:"arg:10",type:"string"},{const:"data",type:"string"},{const:"chain",type:"string"},{type:"string"},{const:"destination",type:"string"},{const:"local",type:"string"},{$ref:"#/definitions/WarpActionInputPositionAssetObject"}]},WarpActionInputPositionAssetObject:{additionalProperties:!1,properties:{amount:{type:"string"},token:{type:"string"}},required:["token","amount"],type:"object"},WarpActionInputSource:{enum:["field","query","user:wallet","hidden"],type:"string"},WarpActionInputType:{type:"string"},WarpActionType:{enum:["transfer","contract","query","collect","compute","link","mcp","prompt","state","mount","unmount","loop","inline"],type:"string"},WarpChainName:{enum:["multiversx","claws","sui","ethereum","base","arbitrum","polygon","somnia","tempo","fastset","solana","near"],type:"string"},WarpCollectAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpCollectDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpCollectDestination:{anyOf:[{$ref:"#/definitions/WarpCollectDestinationHttp"},{type:"string"}]},WarpCollectDestinationHttp:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},method:{enum:["GET","POST","PUT","DELETE"],type:"string"},url:{type:"string"}},required:["url"],type:"object"},WarpComputeAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"compute",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpContractAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:["string","null"]},gasLimit:{type:"number"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label","gasLimit"],type:"object"},WarpI18nText:{additionalProperties:{type:"string"},type:"object"},WarpInlineAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},output:{additionalProperties:{type:"string"},type:"object"},silent:{type:"boolean"},type:{const:"inline",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpLinkAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},type:{$ref:"#/definitions/WarpActionType"},url:{type:"string"},when:{type:"string"}},required:["type","label","url"],type:"object"},WarpLoopAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},delay:{type:"number"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},maxIterations:{type:"number"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"loop",type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},destination:{$ref:"#/definitions/WarpMcpDestination"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpMcpDestination:{additionalProperties:!1,properties:{headers:{additionalProperties:{type:"string"},type:"object"},tool:{type:"string"},url:{type:"string"}},required:["url","tool"],type:"object"},WarpMeta:{additionalProperties:!1,properties:{chain:{anyOf:[{$ref:"#/definitions/WarpChainName"},{type:"null"}]},createdAt:{type:"string"},creator:{type:"string"},hash:{type:"string"},identifier:{type:"string"},query:{anyOf:[{type:"object"},{type:"null"}]}},required:["chain","identifier","query","hash","creator","createdAt"],type:"object"},WarpMountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"mount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpNextConfig:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"},{additionalProperties:!1,properties:{error:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]},success:{anyOf:[{$ref:"#/definitions/WarpNextEntry"},{items:{$ref:"#/definitions/WarpNextEntry"},type:"array"}]}},type:"object"}]},WarpNextEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{identifier:{type:"string"},when:{type:"string"}},required:["identifier"],type:"object"}]},"WarpPlatformValue<string>":{anyOf:[{type:"string"},{additionalProperties:!1,properties:{linux:{type:"string"},macos:{type:"string"},windows:{type:"string"}},type:"object"}]},WarpPromptAction:{additionalProperties:!1,properties:{as:{type:"string"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},expect:{anyOf:[{type:"string"},{type:"object"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},model:{type:"string"},next:{$ref:"#/definitions/WarpNextConfig"},prompt:{$ref:"#/definitions/WarpPlatformValue%3Cstring%3E"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label","prompt"],type:"object"},WarpQueryAction:{additionalProperties:!1,properties:{abi:{type:"string"},address:{type:"string"},args:{items:{type:"string"},type:"array"},auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},func:{type:"string"},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{$ref:"#/definitions/WarpActionType"},when:{type:"string"}},required:["type","label"],type:"object"},WarpRelatedEntry:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{bot:{type:"string"},identifier:{type:"string"}},required:["identifier"],type:"object"}]},WarpResulutionPath:{type:"string"},WarpSchedule:{enum:["minutely","hourly","daily","weekly","monthly","yearly"],type:"string"},WarpSection:{additionalProperties:!1,properties:{description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{type:"string"},type:"array"},title:{$ref:"#/definitions/WarpText"}},required:["title","inputs"],type:"object"},WarpStateAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},data:{type:"object"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},keys:{items:{type:"string"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},op:{enum:["read","write","clear"],type:"string"},store:{type:"string"},type:{const:"state",type:"string"},when:{type:"string"}},required:["type","label","op","store"],type:"object"},WarpText:{anyOf:[{type:"string"},{$ref:"#/definitions/WarpI18nText"}]},WarpTransferAction:{additionalProperties:!1,properties:{address:{type:"string"},auto:{type:"boolean"},data:{type:"string"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},transfers:{items:{type:"string"},type:"array"},type:{$ref:"#/definitions/WarpActionType"},value:{type:"string"},when:{type:"string"}},required:["type","label"],type:"object"},WarpTrigger:{anyOf:[{additionalProperties:!1,properties:{pattern:{type:"string"},type:{const:"message",type:"string"}},required:["type","pattern"],type:"object"},{additionalProperties:!1,properties:{body:{$ref:"#/definitions/WarpText"},inputs:{additionalProperties:{type:"string"},type:"object"},label:{$ref:"#/definitions/WarpText"},match:{additionalProperties:{type:["string","number","boolean"]},type:"object"},source:{type:"string"},subject:{$ref:"#/definitions/WarpText"},type:{const:"webhook",type:"string"}},required:["type","source"],type:"object"}]},WarpUnmountAction:{additionalProperties:!1,properties:{auto:{type:"boolean"},description:{anyOf:[{$ref:"#/definitions/WarpText"},{type:"null"}]},inputs:{items:{$ref:"#/definitions/WarpActionInput"},type:"array"},label:{$ref:"#/definitions/WarpText"},messages:{additionalProperties:{$ref:"#/definitions/WarpText"},type:"object"},next:{$ref:"#/definitions/WarpNextConfig"},type:{const:"unmount",type:"string"},warp:{type:"string"},when:{type:"string"}},required:["type","label","warp"],type:"object"},WarpVarPlaceholder:{type:"string"}}};var xr=new Set(["POST","PUT","PATCH","DELETE"]),vr=/^[A-Z][A-Z0-9_]*$/,gt=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateHasActions(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...this.validateUrlPlaceholdersHaveInputs(t)),e.push(...this.validateNoArgPositionsOnHttpActions(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateHasActions(t){try{let{action:e}=k(t);return e?[]:["Warp must have at least one action"]}catch(e){return[e instanceof Error?e.message:"Warp must have at least one action"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),t.trigger?.type==="webhook"&&t.trigger.inputs&&n(t.trigger.inputs,"Webhook trigger input"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}validateUrlPlaceholdersHaveInputs(t){let e=[],n=new Set(Object.keys(t.vars??{})),i=new Set;for(let a of t.actions){let s=a.inputs??[];for(let o of s)typeof o.position=="string"&&o.position.startsWith("url:")&&i.add(o.position.slice(4));let p=a.destination;if(!p||typeof p=="string"||!p.url)continue;let l=this.extractUrlPlaceholders(p.url);if(l.length!==0)for(let o of l)n.has(o)||vr.test(o)||i.has(o)||e.push(`URL "${p.url}" contains {{${o}}} but no input has position "url:${o}" (and it is not declared in vars)`)}return e}validateNoArgPositionsOnHttpActions(t){let e=[];for(let n of t.actions){let i=n.destination;if(!i||typeof i=="string")continue;let a=i.method?.toUpperCase();if(!a||!xr.has(a))continue;let s=n.inputs??[];for(let p of s)if(p.position?.startsWith("arg:")){let l=p.as??p.name??"(unnamed)";e.push(`Input "${l}" has position "${p.position}" on HTTP ${a} action \u2014 CLI arg positions are not sent in the JSON body. Remove the position (defaults to body) or use "payload:X" / "url:X" explicitly.`)}}return e}extractUrlPlaceholders(t){let n=t.split("?")[0].match(/\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\}/g);return n?n.map(i=>i.slice(2,-2)):[]}async validateSchema(t){try{let e=this.config.schema?.warp?await(await fetch(this.config.schema.warp)).json():Ae,n=new Wr({strict:!1}),i=n.compile(e);return i(t)?[]:[`Schema validation failed: ${n.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ht=class{constructor(t){this.config=t;this.pendingWarp={protocol:pt("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Xt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new gt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};import{existsSync as kt,mkdirSync as Ar,readdirSync as Ce,readFileSync as Cr,unlinkSync as Ht,writeFileSync as br}from"fs";import{join as be,resolve as we}from"path";var Vt="$bigint:",mt=(r,t)=>typeof t=="bigint"?Vt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Vt)?BigInt(t.slice(Vt.length)):t;var yt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?we(n):we(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){kt(this.cacheDir)||Ar(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return be(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!kt(e))return null;let n=Cr(e,"utf-8"),i=JSON.parse(n,X);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Ht(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);br(a,JSON.stringify(i,mt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);kt(e)&&Ht(e)}catch{}}async keys(t){try{let e=Ce(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{Ce(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Ht(be(this.cacheDir,e))})}catch{}}};var rt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,mt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{constructor(t,e){}async get(t){let e=U.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;U.cache.set(t,{value:e,expiresAt:i})}async delete(t){U.cache.delete(t)}async keys(t){let e=Array.from(U.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){U.cache.clear()}};U.cache=new Map;var nt=U;import{readFileSync as wr}from"fs";import{resolve as Ie}from"path";var Wt=class{constructor(t,e){let n=e?.path?Ie(e.path):Ie(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=wr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return v.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var Pe={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},vt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`,AccountNfts:(r,t,e,n,i)=>`account-nfts:${r}:${t}:${e}:${n}:${i}`},xt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new rt(t,e):e?.type==="memory"?new nt(t,e):e?.type==="static"?new Wt(t,e):e?.type==="filesystem"?new yt(t,e):typeof window<"u"&&window.localStorage?new rt(t,e):new nt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var it={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Ft={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ut=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Dt=r=>{try{return JSON.parse(r)}catch{return null}},Ir=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:c}=await Bt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(Lt(n,d,o,c)).forEach(([h,f])=>s.set(h,f))}let p=Ut(e.resolvedInputs,it.Headers,i);if(p){let l=Dt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},Pr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Ft.Get){let s=Ut(e.resolvedInputs,it.Queries,i);if(s){let p=Dt(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,c])=>c!=null&&l.searchParams.set(o,String(c))),a=l.toString()}}}return a},Tr=(r,t,e,n,i)=>{if(r===Ft.Get)return;let a=Ut(t.resolvedInputs,it.Payload,n);if(a&&Dt(a)!==null)return a;let{[it.Payload]:s,[it.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Te=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Ft.Get,o=await Ir(r,t,e,n,a,p),c=Pr(r,t,e,l,a),d=Tr(l,e,i,a,s);return{url:c,method:l,headers:o,body:d}};var B=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e),i=await this.applyGlobals(n);return e.envs?this.applyEnvs(i,e.envs):i}applyEnvs(t,e){if(!e||Object.keys(e).length===0)return t;let n=JSON.stringify(t);for(let[i,a]of Object.entries(e)){if(a==null)continue;let s=typeof a=="object"?JSON.stringify(a):String(a),p=JSON.stringify(s).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Er(i)}\\}\\}`,"g"),p)}return JSON.parse(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=R(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Query.length+1),[o,c]=l.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,f=e.queries?.[o]??null??d;f!=null&&a(s,f)}else if(p.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let l=p.slice(u.Vars.Env.length+1),[o,c]=l.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===u.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(u.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n){if(!t||typeof t!="string"||!t.includes("{{"))return t;let i=this.applyGlobalsToText(t),a=this.buildInputBag(e,n);return V(i,a)}applyGlobalsToText(t){if(!Object.values(u.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(u.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=x(l,this.adapters),c={config:this.config,adapter:o},d=i(c);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e){let n={};return t.forEach(i=>{if(!i.value)return;let a=i.input.as||i.input.name,[,s]=e.stringToNative(i.value);n[a]=String(s)}),n}},Er=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var Sr=["collect","compute","mcp","state","mount","unmount"],Z=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new P,this.cache=new xt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(vt.WarpExecutable(t,e||"",n))||[];return F(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(vt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=N(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=x(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,i),c=N(o,e),{action:d,index:h}=k(o),f=[],g=[];if(h===e-1){let E=this.getStringTypedInputs(d,n);f=await this.getResolvedInputs(s.name,d,E,l,i.queries),g=await this.getModifiedInputs(f)}else c.inputs&&c.inputs.length>0&&(f=await this.resolveActionInputs(s.name,c,n,l,i.queries),g=await this.getModifiedInputs(f));let W=g.find(E=>E.input.position==="receiver"||E.input.position==="destination")?.value,A=this.getDestinationFromAction(c),C=W?this.serializer.stringToNative(W)[1]:A;if(C&&(C=l.applyInputs(C,g,this.serializer)),!C&&!Sr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=this.getPreparedArgs(c,g);m=m.map(E=>l.applyInputs(E,g,this.serializer));let w=g.find(E=>E.input.position==="value")?.value||null,b="value"in c?c.value:null,j=w?.split(u.ArgParamsSeparator)[1]||b||"0",T=l.applyInputs(j,g,this.serializer),I=BigInt(T),$=g.filter(E=>E.input.position==="transfer"&&E.value).map(E=>E.value),M=[...("transfers"in c?c.transfers:[])||[],...$||[]].map(E=>{let It=l.applyInputs(E,g,this.serializer),Oe=It.startsWith(`asset${u.ArgParamsSeparator}`)?It:`asset${u.ArgParamsSeparator}${It}`;return this.serializer.stringToNative(Oe)[1]}),wt=g.find(E=>E.input.position==="data")?.value,$e="data"in c?c.data||"":null,Mt=wt||$e||null,Ne=Mt?l.applyInputs(Mt,g,this.serializer):null,qt={adapter:p,warp:o,chain:s,action:e,destination:C,args:m,value:I,transfers:M,data:Ne,resolvedInputs:g};return await this.cache.set(vt.WarpExecutable(this.config.env,o.meta?.hash||"",e),qt.resolvedInputs,Pe.OneWeek),qt}async getChainInfoForWarp(t,e){if(t.chain)return x(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||ne(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(c=>i.applyInputs(c,[],this.serializer)),l=await Promise.all(p.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let A=R(this.config,t);return A?this.serializer.nativeToString("address",A):null}if(c.source==="hidden"){if(c.default===void 0)return null;let A=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,A)}if(l[d])return l[d];let h=c.as||c.name,f=a?.[h],g=this.url.searchParams.get(h),W=f||g;return W?this.serializer.nativeToString(c.type,String(W)):null};return s.map((c,d)=>{let h=o(c,d),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async resolveInputsFromQuery(t,e,n){let i=N(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=x(a.name,this.adapters),p=new B(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],p,n)}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i,a){let s=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,s,i,a)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=lt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=lt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(u.Transform.Prefix)){let a=i.input.modifier.substring(u.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=ft(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),p=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,l=p?.value?this.serializer.stringToNative(p.value)[1]??null:null;if(l){let c=await(await fetch(l)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(f=>f.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",h)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=$t(e),a=x(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(u.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let c=lt(p,o.decimals);return xe({...o,amount:c})}else return e}catch(n){throw v.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let c=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:c,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return x(s,this.adapters).chainInfo}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.loopIterations=new Map;this.active=!0;this.warpResolver=null;this._checkpointIndex=null;this.handlers=n,this.factory=new Z(t,e),t.logLevel&&v.setLevel(t.logLevel)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},h=n.scope||"default",f=t.meta?.identifier||"",g=`warp-checkpoint:${h}:${f}`,W=await this.factory.getCache().get(g),A=W?.identifier===f?W:void 0;if(A&&Object.assign(d,A.outputs),t.vars)try{let m=this.adapters?.find(w=>w.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(m){let w=await new B(this.config,m,this.adapters).apply(t,c);w?.actions&&(t.actions=w.actions),w?.meta&&(t.meta=w.meta)}}catch{}let{index:C}=k(t);for(let m=1;m<=t.actions.length;m++){let w=N(t,m);if(!St(w))continue;if(A&&m<=A.actionIndex){v.debug(`[WarpExecutor] skipping action ${m} (checkpoint resume)`);continue}let b=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c;v.debug(`[WarpExecutor] action ${m}/${t.actions.length}:`,{type:w.type,label:w.label||w.as||"",when:w.when||null}),this._checkpointIndex=null;let{tx:j,chain:T,immediateExecution:I,executable:$}=await this.executeAction(t,m,e,b);if(this._checkpointIndex!==null){let L={identifier:f,actionIndex:this._checkpointIndex,outputs:{...d}};return await this.factory.getCache().set(g,L),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p,outputs:{...d},checkpoint:L}}if(I?.output){let{_DATA:L,...O}=I.output,M=Object.keys(O);v.debug(`[WarpExecutor] action ${m} output keys:`,M.length>0?M:"(empty)"),Object.assign(d,O)}else v.debug(`[WarpExecutor] action ${m}: no output`);if(I?.values?.mapped){let L=Object.keys(I.values.mapped);v.debug(`[WarpExecutor] action ${m} mapped keys:`,L),Object.assign(d,I.values.mapped)}if($?.resolvedInputs){let L=$.resolvedInputs.filter(O=>O.input.as).map(O=>[O.input.as,O.value]);v.debug(`[WarpExecutor] action ${m} resolved inputs:`,Object.fromEntries(L));for(let O of $.resolvedInputs){let M=O.input.as;if(M&&O.value!==null&&O.value!==void 0){let[,wt]=this.factory.getSerializer().stringToNative(O.value);d[M]=wt??O.value}}}v.debug(`[WarpExecutor] action ${m} outputBag keys:`,Object.keys(d)),I&&(I.envs={...b.envs,...d},s.push(I)),j&&i.push(j),T&&(a=T),$&&m===C+1&&$.resolvedInputs&&(p=F($.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let m=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(m))}return this.scheduleLoops(t,e,c,d),A&&(await this.factory.getCache().get(g))?.identifier===f&&await this.factory.getCache().delete(g),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p,outputs:{...d}}}async executeAction(t,e,n,i={}){let a=N(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Gt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}if(a.type==="loop")return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="state")return this.executeState(t,a,e,i);if(a.type==="mount"||a.type==="unmount"){if(a.when){let o=i.envs||{},c=_(a.when,o);if(!G(c))return{tx:null,chain:null,immediateExecution:null,executable:null}}return await this.handlers?.onMountAction?.({action:a,actionIndex:e,warp:t}),{tx:null,chain:null,immediateExecution:null,executable:null}}if(a.type==="inline"){if(!this.warpResolver)return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.when){let m=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],m))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a;v.debug("[WarpExecutor] resolving inline warp:",{identifier:o.warp,query:o.warp?.split("?")[1]});let c=await this.warpResolver(o.warp);if(!c)return v.debug("[WarpExecutor] inline warp not found:",{identifier:o.warp}),{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},h={};for(let[m,w]of Object.entries(c.meta?.query||{}))h[m]=w.replace(/\{\{(.+?)\}\}/g,(b,j)=>{let T=d[j.trim()];return T==null?"":typeof T=="object"?JSON.stringify(T):String(T)});c.meta={...c.meta,query:h};let f=new Set(Object.keys(h)),g=c.actions?.flatMap(m=>m.inputs||[]).filter(m=>m.source==="field"&&m.required&&!f.has(m.as||m.name))||[];if(g.length>0&&this.handlers?.onInputRequest){let m=Object.fromEntries(Object.entries(h).map(([w,b])=>[w,String(b)]));return this._checkpointIndex=e,await this.handlers.onInputRequest(c,g,m),{tx:null,chain:null,immediateExecution:null,executable:null}}let W=this.handlers?.onActionExecuted;o.silent&&(this.handlers.onActionExecuted=void 0);let{immediateExecutions:A}=await this.execute(c,[],i);o.silent&&(this.handlers.onActionExecuted=W);let C=A[0];if(v.debug("[WarpExecutor] inline warp result:",{identifier:o.warp,hasOutput:!!C?.output,outputKeys:C?.output?Object.keys(C.output).filter(m=>m!=="_DATA"):[],status:C?.status}),C){if(o.silent||await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:C,tx:null})),o.output){let m=de(o,C,i.envs);return{tx:null,chain:null,immediateExecution:{...C,output:m},executable:null}}return{tx:null,chain:null,immediateExecution:C,executable:null}}return{tx:null,chain:null,immediateExecution:null,executable:null}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s,void 0,i.envs);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="compute"){let o=await this.executeCompute(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:c,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=x(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let c=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:c,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=x(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!St(s)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let f=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:R(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:g})),g}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let f=t.meta?.query;f&&Object.keys(f).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,f))}let d=await i.output.getActionExecution(t,o,l.tx,c),h=Rr(c,d.output);return d.next=dt(this.config,this.adapters,t,o,h,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:l})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(d.values),result:d})),d}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e,n){let i=R(this.config,t.chain.name),a=N(t.warp,t.action),s=this.factory.getSerializer(),p=K(t.resolvedInputs,s);if(a.destination&&typeof a.destination=="object"&&"url"in a.destination)return await this.doHttpRequest(t,a.destination,i,p,e,n);let{values:l,output:o}=await et(t.warp,p,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,i,"unhandled",l,o)}async executeCompute(t){let e=R(this.config,t.chain.name),n=this.factory.getSerializer(),i=K(t.resolvedInputs,n),{values:a,output:s}=await et(t.warp,i,t.action,t.resolvedInputs,n,this.config);return this.buildCollectResult(t,e,"success",a,s)}async doHttpRequest(t,e,n,i,a,s){let p=new B(this.config,x(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:o,method:c,headers:d,body:h}=await Te(p,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));if(s){o=V(o,s);for(let[f,g]of d.entries())d.set(f,V(g,s))}v.debug("WarpExecutor: Executing HTTP collect",{url:o,method:c,headers:d,body:h});try{let f={method:c,headers:d,body:h},W=await(await me(this.adapters))(o,f);v.debug("Collect response status",{status:W.status});let A=await W.json();v.debug("Collect response content",{content:A});let{values:C,output:m}=await et(t.warp,A,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,R(this.config,t.chain.name),W.ok?"success":"error",C,m,A)}catch(f){v.error("WarpActionExecutor: Error executing collect",f);let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=R(this.config,t.chain.name),i=N(t.warp,t.action);if(!i.destination){let f=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}let p=this.factory.getSerializer(),l=new B(this.config,x(t.chain.name,this.adapters),this.adapters),o=i.destination,c=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([f,g])=>{let W=l.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());h[f]=W}),v.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let f=new s(new URL(c),{requestInit:{headers:h}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(f);let W={};t.resolvedInputs.forEach(({input:b,value:j})=>{if(j&&b.position&&typeof b.position=="string"&&b.position.startsWith("payload:")){let T=b.position.replace("payload:",""),[I,$]=p.stringToNative(j);if(I==="string")W[T]=String($);else if(I==="bool")W[T]=!!$;else if(I==="uint8"||I==="uint16"||I==="uint32"||I==="uint64"||I==="uint128"||I==="uint256"||I==="biguint"){let L=Number($);W[T]=(Number.isInteger(L),L)}else W[T]=$}}),e&&Object.assign(W,e);let A=await g.callTool({name:d,arguments:W});await g.close();let C;if(A.content&&A.content.length>0){let b=A.content[0];if(b.type==="text")try{C=JSON.parse(b.text)}catch{C=b.text}else b.type,C=b}else C=A;let{values:m,output:w}=await et(t.warp,C,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",m,w,A)}catch(f){v.error("WarpExecutor: Error executing MCP",f);let g=F(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let p=dt(this.config,this.adapters,t.warp,t.action,a,n),l=F(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||R(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Nt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}scheduleLoops(t,e,n,i){if(this.active)for(let a of t.actions){if(a.type!=="loop"||a.auto===!1)continue;let s=a,l=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},f=_(s.when,h);try{if(!G(f)){this.loopIterations.delete(l);continue}}catch{this.loopIterations.delete(l);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(l)??0)+1;if(c>o){this.loopIterations.delete(l),v.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(l,c),!this.handlers?.onLoop)continue;let d=s.delay??0;this.handlers.onLoop({warp:t,inputs:e,meta:n,delay:d})}}async executeState(t,e,n,i){if(e.when){let l=i.envs||{},o=_(e.when,l);if(!G(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),p=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let l=await a.get(p)??{},o=e.keys??Object.keys(l),c={};for(let h of o)l[h]!==void 0&&l[h]!==null&&(c[`state.${h}`]=l[h]);let d={status:"success",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:c,messages:{},destination:null,resolvedInputs:[]};return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:n,chain:null,execution:d,tx:null})),{tx:null,chain:null,immediateExecution:d,executable:null}}if(e.op==="write"&&e.data){let l=await a.get(p)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let f=h.replace(/\{\{([^}]+)\}\}/g,(g,W)=>{let A=o[W.trim()];return A!=null?String(A):h});c[d]=$r(f)}else c[d]=h;await a.set(p,{...l,...c})}return e.op==="clear"&&await a.delete(p),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=x(s.name,this.adapters),l=new B(this.config,p,this.adapters),o=await l.apply(t,a),c=N(o,n),d=[];if(e.inputs&&e.inputs.length>0){let b=this.factory.getStringTypedInputs(e,i),j=await this.factory.getResolvedInputs(s.name,e,b,l,a.queries);d=await this.factory.getModifiedInputs(j)}else{let{action:b}=k(o),j=this.factory.getStringTypedInputs(b,i),T=await this.factory.getResolvedInputs(s.name,b,j,l,a.queries);d=await this.factory.getModifiedInputs(T)}let h=fe(c.prompt,this.config.platform),f=l.applyInputs(h,d,this.factory.getSerializer());a.envs&&(f=V(f,a.envs));let g=F(d),W=R(this.config,s.name),A=this.factory.getSerializer(),{values:C,output:m}=await ue(o,f,n,d,A,this.config);if(this.handlers?.onPromptGenerate){let b=await this.handlers.onPromptGenerate(f,c.expect,c.model);b&&(m.MESSAGE=b,c.as&&(m[c.as]=b))}let w=d.find(b=>b.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:W,txHash:null,tx:null,next:ut(this.config,this.adapters,o,n,m),values:C,output:m,messages:Nt(o,{...C.mapped,...m},this.config),destination:w,resolvedInputs:g}}catch(s){return v.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:dt(this.config,this.adapters,t,n,{},"error"),values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=x(p.name,this.adapters),o=new B(this.config,l,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},f=_(e.when,h);return v.debug("[WarpExecutor] when condition:",{action:e.label||e.type,expression:e.when,interpolated:f,mergedBag:h}),G(f)}},Rr=(r,t)=>{let e=Object.fromEntries((r??[]).flatMap(i=>{let a=i.input.as||i.input.name;return a?[[a,i.value]]:[]})),n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!=null));return{...e,...n}},$r=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Ct=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw v.error("WarpIndex: Error searching for warps: ",i),i}}};var bt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!tt(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?tt(t):D(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?te(t):ee(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let W=`${i.chain}:${s}`;g=await this.resolver.getByAlias(W,e)||await this.resolver.getByAlias(s,e)}g&&(p=g.warp,l=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=x(i.chain,this.adapters);if(a==="hash"){p=await g.builder().createFromTransactionHash(s,e);let W=await g.registry.getInfoByHash(s,e);l=W.registryInfo,o=W.brand}else if(a==="alias"){let W=await g.registry.getInfoByAlias(s,e);l=W.registryInfo,o=W.brand,W.registryInfo&&(p=await g.builder().createFromTransactionHash(W.registryInfo.hash,e))}}if(p&&p.meta&&(Nr(p,i.chain,l,i.identifier),p.meta.query=c?re(c):null),!p)return n;let d=p.chain||i.chain||null,h=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,f=h?await new B(this.config,h,this.adapters).apply(p):p;return{match:!0,url:t,warp:f,chain:d,registryInfo:l,brand:o}}catch(a){return v.error("Error detecting warp link",a),n}}},Nr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Rt(null,"alias",e.alias):Rt(t,"hash",e?.hash??n))};var Ee=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new at(e));return new st(t)}getConfig(){return this.config}mergeVars(t){this.config={...this.config,vars:{...this.config.vars,...t}}}getResolver(){return this.resolver}createExecutor(t){let e=new At(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new bt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await l.evaluateOutput(p,g)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await x(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return x(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=D(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return x(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!R(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return x(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return x(t,this.chains).explorer}getOutput(t){return x(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??k(e).index+1,p=await x(t,this.chains).output.getActionExecution(e,a,n);return p.next=ut(this.config,this.chains,e,a,p.output),p}async getRegistry(t){let e=x(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return x(t,this.chains).dataLoader}getWallet(t){return x(t,this.chains).wallet}get factory(){return new Z(this.config,this.chains)}get index(){return new Ct(this.config)}get linkBuilder(){return new Q(this.config,this.chains)}createBuilder(t){return t?x(t,this.chains).builder():new ht(this.config)}createAbiBuilder(t){return x(t,this.chains).abiBuilder()}createBrandBuilder(t){return x(t,this.chains).brandBuilder()}createSerializer(t){return x(t,this.chains).serializer}resolveText(t){return ct(t,this.config)}};var Se=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};function Cs(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(Re(t,n)!==i)return!1;return!0}function bs(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?Re(t,i):i;return e}function Re(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{Tt as BrowserCryptoProvider,Gr as CLOUD_WALLET_PROVIDERS,Pe as CacheTtl,zr as EvmWalletChainNames,_r as MultiversxWalletChainNames,Et as NodeCryptoProvider,vn as WARP_LANGUAGES,S as WarpAssets,ve as WarpBrandBuilder,ht as WarpBuilder,xt as WarpCache,vt as WarpCacheKey,De as WarpChainDisplayNames,Me as WarpChainLogos,Ue as WarpChainName,at as WarpChainResolver,Ee as WarpClient,st as WarpCompositeResolver,q as WarpConfig,u as WarpConstants,At as WarpExecutor,Z as WarpFactory,Ct as WarpIndex,y as WarpInputTypes,B as WarpInterpolator,Q as WarpLinkBuilder,bt as WarpLinkDetecter,v as WarpLogger,zt as WarpPlatformName,_t as WarpPlatforms,J as WarpProtocolVersions,P as WarpSerializer,Se as WarpTypeRegistry,gt as WarpValidator,Hi as address,Nt as applyOutputToMessages,xe as asset,Vi as biguint,ki as bool,ur as buildGeneratedFallbackWarpIdentifier,gi as buildGeneratedSourceWarpIdentifier,ft as buildInputsContext,K as buildMappedOutput,Ye as buildNestedPayload,pn as bytesToBase64,qe as bytesToHex,bi as checkWarpAssetBalance,Y as cleanWarpIdentifier,Lt as createAuthHeaders,Bt as createAuthMessage,cn as createCryptoProvider,vi as createDefaultWalletProvider,ci as createHttpAuthHeaders,or as createSignableMessage,Cn as createWarpI18nText,Rt as createWarpIdentifier,Wn as doesWarpRequireWallet,En as encodeQueryValues,ce as evaluateOutputCommon,G as evaluateWhenCondition,et as extractCollectOutput,tt as extractIdentifierInfoFromUrl,de as extractInlineOutput,ue as extractPromptOutput,ee as extractQueryStringFromIdentifier,te as extractQueryStringFromUrl,F as extractResolvedInputValues,fn as extractWarpSecrets,x as findWarpAdapterForChain,Yr as getChainDisplayName,tn as getChainLogo,Jt as getCryptoProvider,pr as getGeneratedSourceWarpName,pt as getLatestProtocolIdentifier,me as getMppFetch,ut as getNextInfo,dt as getNextInfoForStatus,si as getProviderConfig,Qt as getRandomBytes,Kt as getRandomHex,dr as getRequiredAssetIds,Br as getWalletFromConfigOrFail,N as getWarpActionByIndex,rn as getWarpBrandLogoUrl,nn as getWarpChainAssetLogoUrl,an as getWarpChainInfoLogoUrl,Sn as getWarpIdentifierWithQuery,D as getWarpInfoFromIdentifier,k as getWarpInputAction,je as getWarpWalletAddress,R as getWarpWalletAddressFromConfig,Ve as getWarpWalletExternalId,ke as getWarpWalletExternalIdFromConfig,kr as getWarpWalletExternalIdFromConfigOrFail,Le as getWarpWalletMnemonic,Vr as getWarpWalletMnemonicFromConfig,Be as getWarpWalletPrivateKey,Lr as getWarpWalletPrivateKeyFromConfig,ne as hasInputPrefix,Fi as hex,Wi as initializeWalletCache,Pn as isEqualWarpIdentifier,mi as isGeneratedSourcePrivateIdentifier,sr as isPlatformValue,St as isWarpActionAutoExecute,An as isWarpI18nText,Hr as isWarpWalletReadOnly,Cs as matchesTrigger,pe as mergeNestedPayload,Dr as normalizeAndValidateMnemonic,He as normalizeMnemonic,Ui as option,ar as parseOutputOutIndex,di as parseSignedMessage,re as parseWarpQueryStringToObject,Tn as removeWarpChainPrefix,Ur as removeWarpWalletFromConfig,V as replacePlaceholders,_ as replacePlaceholdersInWhenExpression,Bn as resolveActionMessages,bs as resolveInputs,_n as resolveNextString,jt as resolveNextStrings,Re as resolvePath,fe as resolvePlatformValue,Gn as resolveRelatedEntries,ct as resolveWarpText,Gt as safeWindow,on as setCryptoProvider,Fr as setWarpWalletInConfig,lt as shiftBigintBy,$t as splitInput,hi as stampGeneratedWarpMeta,Ni as string,Zt as stripWarpQuery,Mi as struct,ln as testCryptoAvailability,tr as toInputPayloadValue,Xt as toPreviewText,Di as tuple,ji as uint16,Bi as uint32,Li as uint64,Oi as uint8,Fe as validateMnemonicLength,ui as validateSignedMessage,qi as vector,Xr as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "4.38.0",
3
+ "version": "4.39.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",