@joai/warps 4.25.2 → 4.26.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.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1260,6 +1260,7 @@ type ExecutionHandlers = {
|
|
|
1260
1260
|
meta: Record<string, any>;
|
|
1261
1261
|
delay: number;
|
|
1262
1262
|
}) => void;
|
|
1263
|
+
onActionProcessing?: (action: WarpAction) => void;
|
|
1263
1264
|
onActionExecuted?: (params: {
|
|
1264
1265
|
action: WarpActionIndex;
|
|
1265
1266
|
chain: WarpChainInfo | null;
|
package/dist/index.d.ts
CHANGED
|
@@ -1260,6 +1260,7 @@ type ExecutionHandlers = {
|
|
|
1260
1260
|
meta: Record<string, any>;
|
|
1261
1261
|
delay: number;
|
|
1262
1262
|
}) => void;
|
|
1263
|
+
onActionProcessing?: (action: WarpAction) => void;
|
|
1263
1264
|
onActionExecuted?: (params: {
|
|
1264
1265
|
action: WarpActionIndex;
|
|
1265
1266
|
chain: WarpChainInfo | null;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Qe=Object.create;var At=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var tr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Ye.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return r};var J=(r,t,e)=>(e=r!=null?Qe(Ze(r)):{},ge(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),er=r=>ge(At({},"__esModule",{value:!0}),r);var Pn={};tr(Pn,{BrowserCryptoProvider:()=>wt,CLOUD_WALLET_PROVIDERS:()=>dr,CacheTtl:()=>ie,EvmWalletChainNames:()=>cr,MultiversxWalletChainNames:()=>ur,NodeCryptoProvider:()=>It,WARP_LANGUAGES:()=>br,WarpAssets:()=>S,WarpBrandBuilder:()=>ee,WarpBuilder:()=>ut,WarpCache:()=>ft,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>we,WarpChainName:()=>Ae,WarpChainResolver:()=>rt,WarpClient:()=>le,WarpCompositeResolver:()=>nt,WarpConfig:()=>L,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>G,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>R,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>vt,WarpLogger:()=>C,WarpPlatformName:()=>Ft,WarpPlatforms:()=>Ht,WarpProtocolVersions:()=>k,WarpSerializer:()=>I,WarpTypeRegistry:()=>pe,WarpValidator:()=>ct,address:()=>on,applyOutputToMessages:()=>Et,asset:()=>te,biguint:()=>an,bool:()=>sn,buildGeneratedFallbackWarpIdentifier:()=>Fe,buildGeneratedSourceWarpIdentifier:()=>Gr,buildInputsContext:()=>pt,buildMappedOutput:()=>_,buildNestedPayload:()=>Ee,bytesToBase64:()=>xr,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Zr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>Nt,createAuthMessage:()=>Rt,createCryptoProvider:()=>Cr,createDefaultWalletProvider:()=>Xr,createHttpAuthHeaders:()=>kr,createSignableMessage:()=>Be,createWarpI18nText:()=>Er,createWarpIdentifier:()=>bt,doesWarpRequireWallet:()=>Sr,evaluateOutputCommon:()=>Kt,evaluateWhenCondition:()=>K,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractPromptOutput:()=>Xt,extractQueryStringFromIdentifier:()=>_t,extractQueryStringFromUrl:()=>zt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>wr,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>fr,getChainLogo:()=>hr,getCryptoProvider:()=>jt,getGeneratedSourceWarpName:()=>Oe,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>Yt,getNextInfo:()=>ot,getNextInfoForStatus:()=>lt,getProviderConfig:()=>jr,getRandomBytes:()=>kt,getRandomHex:()=>Mt,getRequiredAssetIds:()=>He,getWalletFromConfigOrFail:()=>rr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>mr,getWarpChainAssetLogoUrl:()=>yr,getWarpChainInfoLogoUrl:()=>Wr,getWarpIdentifierWithQuery:()=>Br,getWarpInfoFromIdentifier:()=>F,getWarpInputAction:()=>N,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>ar,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>ir,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>nr,hasInputPrefix:()=>Or,hex:()=>ln,initializeWalletCache:()=>Kr,isEqualWarpIdentifier:()=>Tr,isGeneratedSourcePrivateIdentifier:()=>Qr,isPlatformValue:()=>$e,isWarpActionAutoExecute:()=>St,isWarpI18nText:()=>Pr,isWarpWalletReadOnly:()=>sr,matchesTrigger:()=>Sn,mergeNestedPayload:()=>Qt,normalizeAndValidateMnemonic:()=>pr,normalizeMnemonic:()=>ve,option:()=>pn,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>qr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>$r,removeWarpWalletFromConfig:()=>lr,replacePlaceholders:()=>j,replacePlaceholdersInWhenExpression:()=>Q,resolveInputs:()=>bn,resolveNextString:()=>Vr,resolveNextStrings:()=>Tt,resolvePath:()=>ce,resolvePlatformValue:()=>Zt,resolveWarpText:()=>st,safeWindow:()=>Ut,setCryptoProvider:()=>vr,setWarpWalletInConfig:()=>or,shiftBigintBy:()=>at,splitInput:()=>Pt,stampGeneratedWarpMeta:()=>Jr,string:()=>Yr,struct:()=>un,testCryptoAvailability:()=>Ar,toInputPayloadValue:()=>Te,toPreviewText:()=>qt,tuple:()=>cn,uint16:()=>en,uint32:()=>rn,uint64:()=>nn,uint8:()=>tn,validateMnemonicLength:()=>xe,validateSignedMessage:()=>Mr,vector:()=>dn,withAdapterFallback:()=>gr});module.exports=er(Pn);var rt=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 nt=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 rr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,nr=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,ir=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,ar=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},sr=r=>typeof r=="string",or=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},lr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},xe=(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`)},pr=(r,t=24)=>{let e=ve(r);return xe(e,t),e};var Ae=(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))(Ae||{}),Ft=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Ft||{}),Ht=Object.values(Ft),cr=["ethereum","base","arbitrum","polygon","somnia","tempo"],ur=["multiversx","claws"],dr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(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:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={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"},Ut=typeof window<"u"?window:{open:()=>{}};var k={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},L={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${k.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${k.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","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 gr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ce={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"},fr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),we={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")}},hr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Dt=(r,t)=>r[t]??r.default??Object.values(r)[0],mr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Dt(r.logo,e)},yr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Dt(r.logoUrl,e)},Wr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Dt(r.logoUrl,e)};var wt=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}},It=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"}`)}}},M=null;function jt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new wt,M;if(typeof process<"u"&&process.versions?.node)return M=new It,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function vr(r){M=r}async function kt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||jt()).getRandomBytes(r)}function Ie(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 xr(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 Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await kt(r/2,t);return Ie(e)}async function Ar(){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 kt(16),r.randomBytes=!0}catch{}return r}function Cr(){return jt()}var wr=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 W=(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},it=r=>{if(r==="warp")return`warp:${k.Warp}`;if(r==="brand")return`brand:${k.Brand}`;if(r==="abi")return`abi:${k.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],Ir=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Ir.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,at=(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 l=s.slice(0,-a)||"0";return BigInt(l)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},j=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Q=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Sr=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}},K=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var br={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"},st=(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""},Pr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Er=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Tr=(r,t)=>!r||!t?!1:X(r)===X(t),bt=(r,t,e)=>{let n=X(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},F=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=Se(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,l]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let p=e.includes("?")?l+e.substring(e.indexOf("?")):l;return{chain:a,type:s,identifier:p,identifierBase:l}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:l,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s,p=Rr(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:p,identifier:l,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},Z=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 F(i)},Rr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Nr=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=Nr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},zt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},_t=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},Gt=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},$r=r=>{let t=F(r);return(t?t.identifierBase:X(r)).trim()},Br=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 Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Or=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};var be=J(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}build(t,e,n){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,l=a.chainInfo.name+u.IdentifierParamSeparator+s,p=encodeURIComponent(l);return L.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${u.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=F(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return L.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(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",l="#23F7DD"){let p=W(t,this.adapters),o=this.build(p.chainInfo.name,e,n);return new be.default({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(l)}" 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 Lr="https://",Tt=(r,t)=>{if(!r)return null;if(typeof r=="string")return t==="success"?[r]:null;if(Array.isArray(r))return t==="success"?r:null;let e=r[t];return e?Array.isArray(e)?e:[e]:null},Vr=(r,t)=>Tt(r,t)?.[0]??null,Pe=(r,t,e,n,i)=>{if(n.startsWith(Lr))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let g=j(a,{...e.vars,...i});return[{identifier:g,url:Jt(t,g,r)}]}let l=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let g=j(s,{...e.vars,...i}),f=g?`${a}?${g}`:a;return[{identifier:f,url:Jt(t,f,r)}]}let p=l[0];if(!p)return[];let o=p.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=l.filter(g=>g.includes(`{{${c}[]`)).map(g=>{let f=g.match(/\[\](\.[^}]+)?}}/),y=f&&f[1]||"";return{placeholder:g,field:y?y.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(g=>{let f=s;for(let{regex:v,field:x}of h){let w=x?Fr(g,x):g;if(w==null)return null;f=f.replace(v,w)}if(f.includes("{{")||f.includes("}}"))return null;let y=f?`${a}?${f}`:a;return{identifier:y,url:Jt(t,y,r)}}).filter(g=>g!==null)},ot=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=Tt(a,"success");if(!s)return null;let l=s.flatMap(p=>Pe(r,t,e,p,i));return l.length>0?l:null},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",l=T(e,n)?.next||e.next||null,p=Tt(l,s);if(!p)return null;let o=p.flatMap(c=>Pe(r,t,e,c,i));return o.length>0?o:null},Jt=(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((l,p)=>s.searchParams.set(p,l)),s.toString().replace(/\/\?/,"?")},Fr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var z=class z{static debug(...t){z.isTestEnv||console.debug(...t)}static info(...t){z.isTestEnv||console.info(...t)}static warn(...t){z.isTestEnv||console.warn(...t)}static error(...t){z.isTestEnv||console.error(...t)}};z.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=z;function Ee(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 Qt(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]=Qt(e[n],t[n]):e[n]=t[n]}),e}function Te(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 B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function _(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Te(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ee(n.input.position,i,a);e=Qt(e,s)}else e[i]=a}),e}function pt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=l=>{if(!l?.value)return;let p=l.input.as||l.input.name,[,o]=t.stringToNative(l.value);if(i[p]=o,l.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[`${p}.token`]=d,i[`${p}.identifier`]=d,i[`${p}.amount`]=String(c.amount)}};for(let l=0;l<a;l++)s(r[l]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,l]of Object.entries(r.output)){if(l.startsWith(u.Transform.Prefix))continue;let p=Ne(l);if(p!==null&&p!==t){a[s]=null;continue}let[o,...c]=l.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]=l}return{stringValues:n,nativeValues:i,output:a}},Y=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,f)=>g&&g[f]!==void 0?g[f]:null,d),l=d=>d.length===0?t:s(t,d),{stringValues:p,nativeValues:o,output:c}=Re(r,e,l);return{values:{string:p,native:o,mapped:_(n,i)},output:await Kt(r,c,t,e,n,i,a)}},Kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let l={...t};return l=Hr(l,r,n,i,a),l=await Ur(r,l,e,i,a,s.transform?.runner||null),l},Hr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[l,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("in.")){let o=p.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[l]=d?i.stringToNative(d)[1]:null}return a},Ur=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},l=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(l.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 p={...s,out:Dr(e),inputs:pt(n,i)};for(let{key:o,code:c}of l)try{s[o]=await a.run(c,p),p[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,p[o]=null}return s},Dr=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},Xt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:l,nativeValues:p,output:o}=Re(r,e,s),c=await Kt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:l,native:p,mapped:_(n,i)},output:c}},Ne=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 $e=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ht.some(t=>t in r),Zt=(r,t)=>{if(!$e(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 jr=(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 Be(r,t,e,n=5){let i=await Mt(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 Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Be(r,i,e,5)}function Nt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function kr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),l=await t(i);return Nt(r,l,a,s)}function Mr(r){let t=new Date(r).getTime();return Date.now()<t}function qr(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 Oe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",zr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Le=(r,t=24)=>{let e=zr(r);return e?e.slice(0,t):"action"},Ve=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)},_r=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()}},Gr=(r,t,e)=>{let n=Le((e||t||"").trim()||"action"),i=`${r.type}|${_r(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Ve(i);return`private_src_${n}_${a}`},Fe=r=>{let t=Oe(r),e=Le(t),n=Ve(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Jr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Fe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Qr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Kr(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 Xr(r,t,e){return null}var He=(r,t)=>{let e=null;try{e=N(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]:[]},Zr=async(r,t,e,n)=>{try{let i=W(e,n),a=He(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),l=new Map(s.map(p=>[p.identifier,p.amount??0n]));return a.every(p=>(l.get(p)??0n)>0n)}catch{return!0}};var $t=require("mppx/client");async function Yt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return C.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),$t.Mppx.create({methods:[(0,$t.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,t===m.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===m.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(l=>l!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(l=>{let[p,o]=this.getTypeAndValue(n[l]);return`(${l}${u.ArgParamsSeparator}${p})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&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[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(p=>{let o=p.indexOf(u.ArgParamsSeparator),c=p.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),l=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(l)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.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+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=Ue[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),l=i.substring(a+1),p=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(l?l.split(p):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),l=i.split(u.ArgCompositeSeparator).map((p,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${p}`)[1]);return[n,l]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let l={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(p=>{let o=p.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;l[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${h}`)[1]}}),[n,l]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),l={identifier:a,amount:BigInt(s)};return[n,l]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let l=a.stringToNative(i);return[n,l]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[l,p]=this.stringToNative(`${s}:${i}`);return[n,p]}}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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Yr=r=>new I().nativeToString(m.String,r),tn=r=>new I().nativeToString(m.Uint8,r),en=r=>new I().nativeToString(m.Uint16,r),rn=r=>new I().nativeToString(m.Uint32,r),nn=r=>new I().nativeToString(m.Uint64,r),an=r=>new I().nativeToString(m.Biguint,r),sn=r=>new I().nativeToString(m.Bool,r),on=r=>new I().nativeToString(m.Address,r),te=r=>new I().nativeToString(m.Asset,r),ln=r=>new I().nativeToString(m.Hex,r),pn=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},cn=(...r)=>new I().nativeToString(m.Tuple,r),un=r=>new I().nativeToString(m.Struct,r),dn=r=>new I().nativeToString(m.Vector,r);var De=J(require("ajv"),1);var ee=class{constructor(t){this.pendingBrand={protocol:it("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||L.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var je=J(require("ajv"),1);var gn=new Set(["POST","PUT","PATCH","DELETE"]),fn=/^[A-Z][A-Z0-9_]*$/,ct=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}=N(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 l=a.destination;if(!l||typeof l=="string"||!l.url)continue;let p=this.extractUrlPlaceholders(l.url);if(p.length!==0)for(let o of p)n.has(o)||fn.test(o)||i.has(o)||e.push(`URL "${l.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||!gn.has(a))continue;let s=n.inputs??[];for(let l of s)if(l.position?.startsWith("arg:")){let p=l.as??l.name??"(unnamed)";e.push(`Input "${p}" has position "${l.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||L.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new je.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ut=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("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 qt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var E=require("fs"),et=require("path");var re="$bigint:",Bt=(r,t)=>typeof t=="bigint"?re+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var Ot=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,E.existsSync)(this.cacheDir)||(0,E.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,E.existsSync)(e))return null;let n=(0,E.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,E.unlinkSync)(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);(0,E.writeFileSync)(a,JSON.stringify(i,Bt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,E.existsSync)(e)&&(0,E.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,E.readdirSync)(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{(0,E.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,E.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var dt=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,tt);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,Bt))}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 H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var gt=H;var ke=require("fs"),ne=require("path");var Lt=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,ke.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return C.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},ht={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}`},ft=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new dt(t,e):e?.type==="memory"?new gt(t,e):e?.type==="static"?new Lt(t,e):e?.type==="filesystem"?new Ot(t,e):typeof window<"u"&&window.localStorage?new dt(t,e):new gt(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 mt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(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)},oe=r=>{try{return JSON.parse(r)}catch{return null}},hn=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:p,nonce:o,expiresAt:c}=await Rt(n,`${e.chain.name}-adapter`),d=await a({message:p,chain:e.chain});d&&Object.entries(Nt(n,d,o,c)).forEach(([h,g])=>s.set(h,g))}let l=se(e.resolvedInputs,mt.Headers,i);if(l){let p=oe(l);p&&typeof p=="object"&&Object.entries(p).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([p,o])=>{s.set(p,r.applyInputs(o,e.resolvedInputs,i))});return s},mn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,mt.Queries,i);if(s){let l=oe(s);if(l&&typeof l=="object"){let p=new URL(a);Object.entries(l).forEach(([o,c])=>c!=null&&p.searchParams.set(o,String(c))),a=p.toString()}}}return a},yn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,mt.Payload,n);if(a&&oe(a)!==null)return a;let{[mt.Payload]:s,[mt.Queries]:l,...p}=e;return JSON.stringify({...p,...i})},Me=async(r,t,e,n,i,a,s,l)=>{let p=t.method||ae.Get,o=await hn(r,t,e,n,a,l),c=mn(r,t,e,p,a),d=yn(p,e,i,a,s);return{url:c,method:p,headers:o,body:d}};var R=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=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Wn(i)}\\}\\}`,"g"),s)}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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,l)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([s,l])=>{if(typeof l!="string")a(s,l);else if(l.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Query.length+1),[o,c]=p.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(l.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Env.length+1),[o,c]=p.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else l===u.Source.UserWallet&&n?a(s,n):a(s,l)}),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 j(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 l=s.Accessor(i);l!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),l.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,l)=>{let p=l.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(p,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}},Wn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var vn=["collect","compute","mcp","state","mount","unmount"],xn=new Set(Object.values(m)),An=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:xn.has(r.slice(0,t))},G=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 I,this.cache=new ft(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return B(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ht.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),l=W(s.name,this.adapters),p=new R(this.config,l,this.adapters),o=await p.apply(t,i),c=T(o,e),{action:d,index:h}=N(o),g=[],f=[];if(h===e-1){let b=this.getStringTypedInputs(d,n);g=await this.getResolvedInputs(s.name,d,b,p,i.queries),f=await this.getModifiedInputs(g)}else c.inputs&&c.inputs.length>0&&(g=await this.resolveActionInputs(s.name,c,n,p,i.queries),f=await this.getModifiedInputs(g));let y=f.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,v=this.getDestinationFromAction(c),x=y?this.serializer.stringToNative(y)[1]:v;if(x&&(x=p.applyInputs(x,f,this.serializer)),!x&&!vn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let w=this.getPreparedArgs(c,f);w=w.map(b=>p.applyInputs(b,f,this.serializer));let V=f.find(b=>b.input.position==="value")?.value||null,A="value"in c?c.value:null,O=V?.split(u.ArgParamsSeparator)[1]||A||"0",U=p.applyInputs(O,f,this.serializer),$=BigInt(U),D=f.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),qe=[...("transfers"in c?c.transfers:[])||[],...D||[]].map(b=>{let Vt=p.applyInputs(b,f,this.serializer),Je=Vt.startsWith(`asset${u.ArgParamsSeparator}`)?Vt:`asset${u.ArgParamsSeparator}${Vt}`;return this.serializer.stringToNative(Je)[1]}),ze=f.find(b=>b.input.position==="data")?.value,_e="data"in c?c.data||"":null,ue=ze||_e||null,Ge=ue?p.applyInputs(ue,f,this.serializer):null,de={adapter:l,warp:o,chain:s,action:e,destination:x,args:w,value:$,transfers:qe,data:Ge,resolvedInputs:f};return await this.cache.set(ht.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return W(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||An(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],l=n.map(c=>i.applyInputs(c,[],this.serializer)),p=await Promise.all(l.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(c.source==="hidden"){if(c.default===void 0)return null;let v=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,v)}if(p[d])return p[d];let h=c.as||c.name,g=a?.[h],f=this.url.searchParams.get(h),y=g||f;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),g=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(g!==void 0?this.serializer.nativeToString(c.type,g):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),l=new R(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],l,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 l=i.value?.split(":")[1];if(!l)throw new Error("WarpActionExecutor: Scalable value not found");let p=at(l,+s);e.push({...i,value:`${i.input.type}:${p}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let l=at(s,+a);e.push({...i,value:`${i.input.type}:${l}`})}}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 l=pt(t,this.serializer,n,i),p=await s.run(a,l);if(p==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),l=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,p=l?.value?this.serializer.stringToNative(l.value)[1]??null:null;if(p){let c=await(await fetch(p)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(g=>g.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]=Pt(e),a=W(t,this.adapters);if(n==="asset"){let[s,l,p]=i.split(u.ArgCompositeSeparator);if(p)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=at(l,o.decimals);return te({...o,amount:c})}else return e}catch(n){throw C.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[l,p]=this.serializer.stringToNative(s),o=p;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 l=Number(a.position.split(":")[1])-1;i.push({index:l,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(p=>p.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.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 W(s,this.adapters).chainInfo}};var yt=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.handlers=n,this.factory=new G(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],l=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},{index:h}=N(t);for(let g=1;g<=t.actions.length;g++){let f=T(t,g);if(!St(f))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:v,chain:x,immediateExecution:w,executable:V}=await this.executeAction(t,g,e,y);if(v&&i.push(v),x&&(a=x),w&&s.push(w),w?.output){let{_DATA:A,...O}=w.output;Object.assign(d,O)}w?.values?.mapped&&Object.assign(d,w.values.mapped),V&&g===h+1&&V.resolvedInputs&&(l=B(V.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:l}}async executeAction(t,e,n,i={}){let a=T(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):Ut.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=Q(a.when,o);if(!K(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 y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};let d={...this.config.vars,...i.envs||{},...i.queries||{}};Object.entries(d).filter(([,y])=>typeof y!="string").forEach(([y,v])=>console.log("[warp:inline] non-string bag value",{key:y,type:typeof v,value:v}));let h={};for(let[y,v]of Object.entries(c.meta?.query||{}))h[y]=v.replace(/\{\{(.+?)\}\}/g,(x,w)=>String(d[w.trim()]??""));c.meta={...c.meta,query:h};let{immediateExecutions:g}=await this.execute(c,[],i),f=g[0];return f?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:f,tx:null})),{tx:null,chain:null,immediateExecution:f,executable:null}):{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);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 l=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await l.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 l.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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,l)=>{if(!St(s)||s.type!=="transfer"&&s.type!=="contract")return null;let p=e[l],o=l+1;if(!p){let g=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),f={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:g};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:f})),f}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let g=t.meta?.query;g&&Object.keys(g).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,g))}let d=await i.output.getActionExecution(t,o,p.tx,c),h=Cn(c,d.output);return d.next=lt(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:p})):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(l=>l.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=_(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:l,output:p}=await Y(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",l,p)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=_(t.resolvedInputs,n),{values:a,output:s}=await Y(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){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:p,method:o,headers:c,body:d}=await Me(s,e,t,n,i,l,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:p,method:o,headers:c,body:d});try{let h={method:o,headers:c,body:d},f=await(await Yt(this.adapters))(p,h);C.debug("Collect response status",{status:f.status});let y=await f.json();C.debug("Collect response content",{content:y});let{values:v,output:x}=await Y(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),f.ok?"success":"error",v,x,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=B(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:h},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=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let g=B(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let f=B(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:f}}let l=this.factory.getSerializer(),p=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=p.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,f])=>{let y=p.applyInputs(f,t.resolvedInputs,this.factory.getSerializer());h[g]=y}),C.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let g=new s(new URL(c),{requestInit:{headers:h}}),f=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await f.connect(g);let y={};t.resolvedInputs.forEach(({input:A,value:O})=>{if(O&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let U=A.position.replace("payload:",""),[$,D]=l.stringToNative(O);if($==="string")y[U]=String(D);else if($==="bool")y[U]=!!D;else if($==="uint8"||$==="uint16"||$==="uint32"||$==="uint64"||$==="uint128"||$==="uint256"||$==="biguint"){let xt=Number(D);y[U]=(Number.isInteger(xt),xt)}else y[U]=D}}),e&&Object.assign(y,e);let v=await f.callTool({name:d,arguments:y});await f.close();let x;if(v.content&&v.content.length>0){let A=v.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=v;let{values:w,output:V}=await Y(t.warp,x,t.action,t.resolvedInputs,l,this.config);return this.buildCollectResult(t,n,"success",w,V,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let f=B(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}buildCollectResult(t,e,n,i,a,s){let l=lt(this.config,this.adapters,t.warp,t.action,a,n),p=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:l,values:i,output:s?{...a,_DATA:s}:a,messages:Et(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}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,p=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},g=Q(s.when,h);try{if(!K(g)){this.loopIterations.delete(p);continue}}catch{this.loopIterations.delete(p);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(p)??0)+1;if(c>o){this.loopIterations.delete(p),C.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(p,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 p=i.envs||{},o=Q(e.when,p);if(!K(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),l=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let p=await a.get(l)??{},o=e.keys??Object.keys(p),c={};for(let h of o)p[h]!==void 0&&p[h]!==null&&(c[`state.${h}`]=p[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 p=await a.get(l)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let g=h.replace(/\{\{([^}]+)\}\}/g,(f,y)=>{let v=o[y.trim()];return v!=null?String(v):h});c[d]=wn(g)}else c[d]=h;await a.set(l,{...p,...c})}return e.op==="clear"&&await a.delete(l),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),l=W(s.name,this.adapters),p=new R(this.config,l,this.adapters),o=await p.apply(t,a),c=T(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),O=await this.factory.getResolvedInputs(s.name,e,A,p,a.queries);d=await this.factory.getModifiedInputs(O)}else{let{action:A}=N(o),O=this.factory.getStringTypedInputs(A,i),U=await this.factory.getResolvedInputs(s.name,A,O,p,a.queries);d=await this.factory.getModifiedInputs(U)}let h=Zt(c.prompt,this.config.platform),g=p.applyInputs(h,d,this.factory.getSerializer()),f=B(d),y=P(this.config,s.name),v=this.factory.getSerializer(),{values:x,output:w}=await Xt(o,g,n,d,v,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(g,c.expect);A&&(w.MESSAGE=A)}let V=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,w),values:x,output:w,messages:Et(o,{...x.mapped,...w},this.config),destination:V,resolvedInputs:f}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:lt(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 l=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),p=W(l.name,this.adapters),o=new R(this.config,p,this.adapters),c;if(a)c=a;else{let f=await this.factory.getResolvedInputs(l.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(f)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},g=Q(e.when,h);return K(g)}},Cn=(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}},wn=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Wt=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 C.error("WarpIndex: Error searching for warps: ",i),i}}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(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),l=s.length>0,p=s.map(o=>({url:o.url,warp:o.warp}));return{match:l,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?Z(t):F(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,l=null,p=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?zt(t):_t(i.identifier);if(this.resolver){let f=null;if(a==="hash")f=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;f=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}f&&(l=f.warp,p=f.registryInfo,o=f.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let f=W(i.chain,this.adapters);if(a==="hash"){l=await f.builder().createFromTransactionHash(s,e);let y=await f.registry.getInfoByHash(s,e);p=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await f.registry.getInfoByAlias(s,e);p=y.registryInfo,o=y.brand,y.registryInfo&&(l=await f.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(l&&l.meta&&(In(l,i.chain,p,i.identifier),l.meta.query=c?Gt(c):null),!l)return n;let d=l.chain||i.chain||null,h=d?this.adapters.find(f=>f.chainInfo.name.toLowerCase()===d.toLowerCase()):null,g=h?await new R(this.config,h,this.adapters).apply(l):l;return{match:!0,url:t,warp:g,chain:d,registryInfo:p,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},In=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?bt(null,"alias",e.alias):bt(t,"hash",e?.hash??n))};var le=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 rt(e));return new nt(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 yt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new vt(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"),l=a?t:null;if(!l&&s){let f=await fetch(t);if(!f.ok)throw new Error("WarpClient: executeWarp - invalid url");l=await f.json()}if(l||(l=(await this.detectWarp(t,i.cache)).warp),!l)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await p.execute(l,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async f=>{await p.evaluateOutput(l,f)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=F(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??N(e).index+1,l=await W(t,this.chains).output.getActionExecution(e,a,n);return l.next=ot(this.config,this.chains,e,a,l.output),l}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ut(this.config)}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return st(t,this.config)}};var pe=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 Sn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function bn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpInputAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolveNextStrings,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
|
1
|
+
"use strict";var Qe=Object.create;var At=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var tr=(r,t)=>{for(var e in t)At(r,e,{get:t[e],enumerable:!0})},ge=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xe(t))!Ye.call(r,i)&&i!==e&&At(r,i,{get:()=>t[i],enumerable:!(n=Ke(t,i))||n.enumerable});return r};var J=(r,t,e)=>(e=r!=null?Qe(Ze(r)):{},ge(t||!r||!r.__esModule?At(e,"default",{value:r,enumerable:!0}):e,r)),er=r=>ge(At({},"__esModule",{value:!0}),r);var Pn={};tr(Pn,{BrowserCryptoProvider:()=>wt,CLOUD_WALLET_PROVIDERS:()=>dr,CacheTtl:()=>ie,EvmWalletChainNames:()=>cr,MultiversxWalletChainNames:()=>ur,NodeCryptoProvider:()=>It,WARP_LANGUAGES:()=>br,WarpAssets:()=>S,WarpBrandBuilder:()=>ee,WarpBuilder:()=>ut,WarpCache:()=>ft,WarpCacheKey:()=>ht,WarpChainDisplayNames:()=>Ce,WarpChainLogos:()=>we,WarpChainName:()=>Ae,WarpChainResolver:()=>rt,WarpClient:()=>le,WarpCompositeResolver:()=>nt,WarpConfig:()=>L,WarpConstants:()=>u,WarpExecutor:()=>yt,WarpFactory:()=>G,WarpIndex:()=>Wt,WarpInputTypes:()=>m,WarpInterpolator:()=>R,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>vt,WarpLogger:()=>C,WarpPlatformName:()=>Vt,WarpPlatforms:()=>Ft,WarpProtocolVersions:()=>j,WarpSerializer:()=>I,WarpTypeRegistry:()=>pe,WarpValidator:()=>ct,address:()=>on,applyOutputToMessages:()=>Et,asset:()=>te,biguint:()=>an,bool:()=>sn,buildGeneratedFallbackWarpIdentifier:()=>Ve,buildGeneratedSourceWarpIdentifier:()=>Gr,buildInputsContext:()=>pt,buildMappedOutput:()=>_,buildNestedPayload:()=>Ee,bytesToBase64:()=>xr,bytesToHex:()=>Ie,checkWarpAssetBalance:()=>Zr,cleanWarpIdentifier:()=>X,createAuthHeaders:()=>Nt,createAuthMessage:()=>Rt,createCryptoProvider:()=>Cr,createDefaultWalletProvider:()=>Xr,createHttpAuthHeaders:()=>jr,createSignableMessage:()=>Be,createWarpI18nText:()=>Er,createWarpIdentifier:()=>bt,doesWarpRequireWallet:()=>Sr,evaluateOutputCommon:()=>Kt,evaluateWhenCondition:()=>K,extractCollectOutput:()=>Y,extractIdentifierInfoFromUrl:()=>Z,extractPromptOutput:()=>Xt,extractQueryStringFromIdentifier:()=>_t,extractQueryStringFromUrl:()=>zt,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>wr,findWarpAdapterForChain:()=>W,getChainDisplayName:()=>fr,getChainLogo:()=>hr,getCryptoProvider:()=>kt,getGeneratedSourceWarpName:()=>Oe,getLatestProtocolIdentifier:()=>it,getMppFetch:()=>Yt,getNextInfo:()=>ot,getNextInfoForStatus:()=>lt,getProviderConfig:()=>kr,getRandomBytes:()=>jt,getRandomHex:()=>Mt,getRequiredAssetIds:()=>Fe,getWalletFromConfigOrFail:()=>rr,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>mr,getWarpChainAssetLogoUrl:()=>yr,getWarpChainInfoLogoUrl:()=>Wr,getWarpIdentifierWithQuery:()=>Br,getWarpInfoFromIdentifier:()=>V,getWarpInputAction:()=>N,getWarpWalletAddress:()=>fe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ye,getWarpWalletExternalIdFromConfig:()=>We,getWarpWalletExternalIdFromConfigOrFail:()=>ar,getWarpWalletMnemonic:()=>me,getWarpWalletMnemonicFromConfig:()=>ir,getWarpWalletPrivateKey:()=>he,getWarpWalletPrivateKeyFromConfig:()=>nr,hasInputPrefix:()=>Or,hex:()=>ln,initializeWalletCache:()=>Kr,isEqualWarpIdentifier:()=>Tr,isGeneratedSourcePrivateIdentifier:()=>Qr,isPlatformValue:()=>$e,isWarpActionAutoExecute:()=>St,isWarpI18nText:()=>Pr,isWarpWalletReadOnly:()=>sr,matchesTrigger:()=>Sn,mergeNestedPayload:()=>Qt,normalizeAndValidateMnemonic:()=>pr,normalizeMnemonic:()=>ve,option:()=>pn,parseOutputOutIndex:()=>Ne,parseSignedMessage:()=>qr,parseWarpQueryStringToObject:()=>Gt,removeWarpChainPrefix:()=>$r,removeWarpWalletFromConfig:()=>lr,replacePlaceholders:()=>k,replacePlaceholdersInWhenExpression:()=>Q,resolveInputs:()=>bn,resolveNextString:()=>Hr,resolveNextStrings:()=>Tt,resolvePath:()=>ce,resolvePlatformValue:()=>Zt,resolveWarpText:()=>st,safeWindow:()=>Ut,setCryptoProvider:()=>vr,setWarpWalletInConfig:()=>or,shiftBigintBy:()=>at,splitInput:()=>Pt,stampGeneratedWarpMeta:()=>Jr,string:()=>Yr,struct:()=>un,testCryptoAvailability:()=>Ar,toInputPayloadValue:()=>Te,toPreviewText:()=>qt,tuple:()=>cn,uint16:()=>en,uint32:()=>rn,uint64:()=>nn,uint8:()=>tn,validateMnemonicLength:()=>xe,validateSignedMessage:()=>Mr,vector:()=>dn,withAdapterFallback:()=>gr});module.exports=er(Pn);var rt=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 nt=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 rr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},fe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>fe(r.user?.wallets?.[t]||null),he=r=>r?typeof r=="string"?r:r.privateKey||null:null,me=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ye=r=>r?typeof r=="string"?r:r.externalId||null:null,nr=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,ir=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,ar=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},sr=r=>typeof r=="string",or=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},lr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},xe=(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`)},pr=(r,t=24)=>{let e=ve(r);return xe(e,t),e};var Ae=(f=>(f.Multiversx="multiversx",f.Claws="claws",f.Sui="sui",f.Ethereum="ethereum",f.Base="base",f.Arbitrum="arbitrum",f.Polygon="polygon",f.Somnia="somnia",f.Tempo="tempo",f.Fastset="fastset",f.Solana="solana",f.Near="near",f))(Ae||{}),Vt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Vt||{}),Ft=Object.values(Vt),cr=["ethereum","base","arbitrum","polygon","somnia","tempo"],ur=["multiversx","claws"],dr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(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:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={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"},Ut=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},L={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","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 gr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ct="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",S={baseUrl:Ct,chainLogo:r=>`${Ct}/chains/logos/${r}`,tokenLogo:r=>`${Ct}/tokens/logos/${r}`,walletLogo:r=>`${Ct}/wallets/logos/${r}`},Ce={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"},fr=r=>Ce[r]??r.charAt(0).toUpperCase()+r.slice(1),we={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")}},hr=(r,t="dark")=>{let e=we[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var Dt=(r,t)=>r[t]??r.default??Object.values(r)[0],mr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:Dt(r.logo,e)},yr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Dt(r.logoUrl,e)},Wr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return Dt(r.logoUrl,e)};var wt=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}},It=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"}`)}}},M=null;function kt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new wt,M;if(typeof process<"u"&&process.versions?.node)return M=new It,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function vr(r){M=r}async function jt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||kt()).getRandomBytes(r)}function Ie(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 xr(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 Mt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await jt(r/2,t);return Ie(e)}async function Ar(){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 jt(16),r.randomBytes=!0}catch{}return r}function Cr(){return kt()}var wr=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 W=(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},it=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}`)},T=(r,t)=>r?.actions[t-1],Ir=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Ir.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,at=(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 l=s.slice(0,-a)||"0";return BigInt(l)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},qt=(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},k=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),Q=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Sr=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}},K=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var br={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"},st=(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""},Pr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Er=r=>r;var X=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,Tr=(r,t)=>!r||!t?!1:X(r)===X(t),bt=(r,t,e)=>{let n=X(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},V=r=>{let t=decodeURIComponent(r).trim(),e=X(t),n=e.split("?")[0],i=Se(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,l]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let p=e.includes("?")?l+e.substring(e.indexOf("?")):l;return{chain:a,type:s,identifier:p,identifierBase:l}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:l,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s,p=Rr(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:p,identifier:l,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},Z=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 V(i)},Rr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Nr=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Se=r=>{let t=Nr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Se(a);return[i,...s]},zt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},_t=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},Gt=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},$r=r=>{let t=V(r);return(t?t.identifierBase:X(r)).trim()},Br=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 Pt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Or=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Pt(r)[0];return t.has(e)};var Et=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=st(a,e);return[i,k(s,t)]});return Object.fromEntries(n)};var be=J(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(t):!1}build(t,e,n){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,l=a.chainInfo.name+u.IdentifierParamSeparator+s,p=encodeURIComponent(l);return L.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${u.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=V(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return L.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(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",l="#23F7DD"){let p=W(t,this.adapters),o=this.build(p.chainInfo.name,e,n);return new be.default({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(l)}" 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 Lr="https://",Tt=(r,t)=>{if(!r)return null;if(typeof r=="string")return t==="success"?[r]:null;if(Array.isArray(r))return t==="success"?r:null;let e=r[t];return e?Array.isArray(e)?e:[e]:null},Hr=(r,t)=>Tt(r,t)?.[0]??null,Pe=(r,t,e,n,i)=>{if(n.startsWith(Lr))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let h=k(a,{...e.vars,...i});return[{identifier:h,url:Jt(t,h,r)}]}let l=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let h=k(s,{...e.vars,...i}),g=h?`${a}?${h}`:a;return[{identifier:g,url:Jt(t,g,r)}]}let p=l[0];if(!p)return[];let o=p.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 f=l.filter(h=>h.includes(`{{${c}[]`)).map(h=>{let g=h.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:h,field:y?y.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(h=>{let g=s;for(let{regex:v,field:x}of f){let w=x?Vr(h,x):h;if(w==null)return null;g=g.replace(v,w)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Jt(t,y,r)}}).filter(h=>h!==null)},ot=(r,t,e,n,i)=>{let a=T(e,n)?.next||e.next||null,s=Tt(a,"success");if(!s)return null;let l=s.flatMap(p=>Pe(r,t,e,p,i));return l.length>0?l:null},lt=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",l=T(e,n)?.next||e.next||null,p=Tt(l,s);if(!p)return null;let o=p.flatMap(c=>Pe(r,t,e,c,i));return o.length>0?o:null},Jt=(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((l,p)=>s.searchParams.set(p,l)),s.toString().replace(/\/\?/,"?")},Vr=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var z=class z{static debug(...t){z.isTestEnv||console.debug(...t)}static info(...t){z.isTestEnv||console.info(...t)}static warn(...t){z.isTestEnv||console.warn(...t)}static error(...t){z.isTestEnv||console.error(...t)}};z.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=z;function Ee(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 Qt(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]=Qt(e[n],t[n]):e[n]=t[n]}),e}function Te(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 B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function _(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Te(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=Ee(n.input.position,i,a);e=Qt(e,s)}else e[i]=a}),e}function pt(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=l=>{if(!l?.value)return;let p=l.input.as||l.input.name,[,o]=t.stringToNative(l.value);if(i[p]=o,l.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[`${p}.token`]=d,i[`${p}.identifier`]=d,i[`${p}.amount`]=String(c.amount)}};for(let l=0;l<a;l++)s(r[l]);return s(n),i}var Re=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,l]of Object.entries(r.output)){if(l.startsWith(u.Transform.Prefix))continue;let p=Ne(l);if(p!==null&&p!==t){a[s]=null;continue}let[o,...c]=l.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]=l}return{stringValues:n,nativeValues:i,output:a}},Y=async(r,t,e,n,i,a)=>{let s=(f,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,f),l=f=>f.length===0?t:s(t,f),{stringValues:p,nativeValues:o,output:c}=Re(r,e,l),d=_(n,i);for(let f of n)if(f.input.position==="local"){let h=f.input.as||f.input.name;if(h&&f.value){let[,g]=i.stringToNative(f.value);d[h]=g}}return{values:{string:p,native:o,mapped:d},output:await Kt(r,c,t,e,n,i,a)}},Kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let l={...t};return l=Fr(l,r,n,i,a),l=await Ur(r,l,e,i,a,s.transform?.runner||null),l},Fr=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[l,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("in.")){let o=p.split(".")[1],c=s.findIndex(f=>f.as===o||f.name===o),d=c!==-1?n[c]?.value:null;a[l]=d?i.stringToNative(d)[1]:null}return a},Ur=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},l=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(l.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 p={...s,out:Dr(e),inputs:pt(n,i)};for(let{key:o,code:c}of l)try{s[o]=await a.run(c,p),p[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,p[o]=null}return s},Dr=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},Xt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:l,nativeValues:p,output:o}=Re(r,e,s),c=await Kt(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:l,native:p,mapped:_(n,i)},output:c}},Ne=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 $e=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ft.some(t=>t in r),Zt=(r,t)=>{if(!$e(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 kr=(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 Be(r,t,e,n=5){let i=await Mt(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 Rt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Be(r,i,e,5)}function Nt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function jr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Rt(r,e,n),l=await t(i);return Nt(r,l,a,s)}function Mr(r){let t=new Date(r).getTime();return Date.now()<t}function qr(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 Oe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",zr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Le=(r,t=24)=>{let e=zr(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)},_r=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()}},Gr=(r,t,e)=>{let n=Le((e||t||"").trim()||"action"),i=`${r.type}|${_r(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=He(i);return`private_src_${n}_${a}`},Ve=r=>{let t=Oe(r),e=Le(t),n=He(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Jr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ve(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Qr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Kr(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 Xr(r,t,e){return null}var Fe=(r,t)=>{let e=null;try{e=N(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]:[]},Zr=async(r,t,e,n)=>{try{let i=W(e,n),a=Fe(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),l=new Map(s.map(p=>[p.identifier,p.amount??0n]));return a.every(p=>(l.get(p)??0n)>0n)}catch{return!0}};var $t=require("mppx/client");async function Yt(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return C.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),$t.Mppx.create({methods:[(0,$t.tempo)({account:e})],polyfill:!1}).fetch}return fetch}var Ue={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=Ue[t]??t,t===m.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===m.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(l=>l!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(l=>{let[p,o]=this.getTypeAndValue(n[l]);return`(${l}${u.ArgParamsSeparator}${p})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&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[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(p=>{let o=p.indexOf(u.ArgParamsSeparator),c=p.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),l=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(l)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.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+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=Ue[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),l=i.substring(a+1),p=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(l?l.split(p):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),l=i.split(u.ArgCompositeSeparator).map((p,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${p}`)[1]);return[n,l]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let l={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(p=>{let o=p.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,f]=o;l[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${f}`)[1]}}),[n,l]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),l={identifier:a,amount:BigInt(s)};return[n,l]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let l=a.stringToNative(i);return[n,l]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[l,p]=this.stringToNative(`${s}:${i}`);return[n,p]}}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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var Yr=r=>new I().nativeToString(m.String,r),tn=r=>new I().nativeToString(m.Uint8,r),en=r=>new I().nativeToString(m.Uint16,r),rn=r=>new I().nativeToString(m.Uint32,r),nn=r=>new I().nativeToString(m.Uint64,r),an=r=>new I().nativeToString(m.Biguint,r),sn=r=>new I().nativeToString(m.Bool,r),on=r=>new I().nativeToString(m.Address,r),te=r=>new I().nativeToString(m.Asset,r),ln=r=>new I().nativeToString(m.Hex,r),pn=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},cn=(...r)=>new I().nativeToString(m.Tuple,r),un=r=>new I().nativeToString(m.Struct,r),dn=r=>new I().nativeToString(m.Vector,r);var De=J(require("ajv"),1);var ee=class{constructor(t){this.pendingBrand={protocol:it("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||L.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new De.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var ke=J(require("ajv"),1);var gn=new Set(["POST","PUT","PATCH","DELETE"]),fn=/^[A-Z][A-Z0-9_]*$/,ct=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}=N(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 l=a.destination;if(!l||typeof l=="string"||!l.url)continue;let p=this.extractUrlPlaceholders(l.url);if(p.length!==0)for(let o of p)n.has(o)||fn.test(o)||i.has(o)||e.push(`URL "${l.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||!gn.has(a))continue;let s=n.inputs??[];for(let l of s)if(l.position?.startsWith("arg:")){let p=l.as??l.name??"(unnamed)";e.push(`Input "${p}" has position "${l.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||L.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ke.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var ut=class{constructor(t){this.config=t;this.pendingWarp={protocol:it("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 qt(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 ct(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var E=require("fs"),et=require("path");var re="$bigint:",Bt=(r,t)=>typeof t=="bigint"?re+t.toString():t,tt=(r,t)=>typeof t=="string"&&t.startsWith(re)?BigInt(t.slice(re.length)):t;var Ot=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,et.resolve)(n):(0,et.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,E.existsSync)(this.cacheDir)||(0,E.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,et.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,E.existsSync)(e))return null;let n=(0,E.readFileSync)(e,"utf-8"),i=JSON.parse(n,tt);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,E.unlinkSync)(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);(0,E.writeFileSync)(a,JSON.stringify(i,Bt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,E.existsSync)(e)&&(0,E.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,E.readdirSync)(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{(0,E.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,E.unlinkSync)((0,et.join)(this.cacheDir,e))})}catch{}}};var dt=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,tt);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,Bt))}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 F=class F{constructor(t,e){}async get(t){let e=F.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;F.cache.set(t,{value:e,expiresAt:i})}async delete(t){F.cache.delete(t)}async keys(t){let e=Array.from(F.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){F.cache.clear()}};F.cache=new Map;var gt=F;var je=require("fs"),ne=require("path");var Lt=class{constructor(t,e){let n=e?.path?(0,ne.resolve)(e.path):(0,ne.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,je.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,tt)))}catch(e){return C.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},ht={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}`},ft=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new dt(t,e):e?.type==="memory"?new gt(t,e):e?.type==="static"?new Lt(t,e):e?.type==="filesystem"?new Ot(t,e):typeof window<"u"&&window.localStorage?new dt(t,e):new gt(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 mt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ae={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},se=(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)},oe=r=>{try{return JSON.parse(r)}catch{return null}},hn=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:p,nonce:o,expiresAt:c}=await Rt(n,`${e.chain.name}-adapter`),d=await a({message:p,chain:e.chain});d&&Object.entries(Nt(n,d,o,c)).forEach(([f,h])=>s.set(f,h))}let l=se(e.resolvedInputs,mt.Headers,i);if(l){let p=oe(l);p&&typeof p=="object"&&Object.entries(p).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([p,o])=>{s.set(p,r.applyInputs(o,e.resolvedInputs,i))});return s},mn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ae.Get){let s=se(e.resolvedInputs,mt.Queries,i);if(s){let l=oe(s);if(l&&typeof l=="object"){let p=new URL(a);Object.entries(l).forEach(([o,c])=>c!=null&&p.searchParams.set(o,String(c))),a=p.toString()}}}return a},yn=(r,t,e,n,i)=>{if(r===ae.Get)return;let a=se(t.resolvedInputs,mt.Payload,n);if(a&&oe(a)!==null)return a;let{[mt.Payload]:s,[mt.Queries]:l,...p}=e;return JSON.stringify({...p,...i})},Me=async(r,t,e,n,i,a,s,l)=>{let p=t.method||ae.Get,o=await hn(r,t,e,n,a,l),c=mn(r,t,e,p,a),d=yn(p,e,i,a,s);return{url:c,method:p,headers:o,body:d}};var R=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=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${Wn(i)}\\}\\}`,"g"),s)}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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,l)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([s,l])=>{if(typeof l!="string")a(s,l);else if(l.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Query.length+1),[o,c]=p.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}else if(l.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Env.length+1),[o,c]=p.split(u.ArgCompositeSeparator),f={...this.config.vars,...e.envs}?.[o];f!=null&&a(s,f)}else l===u.Source.UserWallet&&n?a(s,n):a(s,l)}),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 k(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 l=s.Accessor(i);l!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),l.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,l)=>{let p=l.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(p,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}},Wn=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var vn=["collect","compute","mcp","state","mount","unmount"],xn=new Set(Object.values(m)),An=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:xn.has(r.slice(0,t))},G=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 I,this.cache=new ft(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(ht.WarpExecutable(t,e||"",n))||[];return B(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(ht.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),l=W(s.name,this.adapters),p=new R(this.config,l,this.adapters),o=await p.apply(t,i),c=T(o,e),{action:d,index:f}=N(o),h=[],g=[];if(f===e-1){let b=this.getStringTypedInputs(d,n);h=await this.getResolvedInputs(s.name,d,b,p,i.queries),g=await this.getModifiedInputs(h)}else c.inputs&&c.inputs.length>0&&(h=await this.resolveActionInputs(s.name,c,n,p,i.queries),g=await this.getModifiedInputs(h));let y=g.find(b=>b.input.position==="receiver"||b.input.position==="destination")?.value,v=this.getDestinationFromAction(c),x=y?this.serializer.stringToNative(y)[1]:v;if(x&&(x=p.applyInputs(x,g,this.serializer)),!x&&!vn.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let w=this.getPreparedArgs(c,g);w=w.map(b=>p.applyInputs(b,g,this.serializer));let H=g.find(b=>b.input.position==="value")?.value||null,A="value"in c?c.value:null,O=H?.split(u.ArgParamsSeparator)[1]||A||"0",U=p.applyInputs(O,g,this.serializer),$=BigInt(U),D=g.filter(b=>b.input.position==="transfer"&&b.value).map(b=>b.value),qe=[...("transfers"in c?c.transfers:[])||[],...D||[]].map(b=>{let Ht=p.applyInputs(b,g,this.serializer),Je=Ht.startsWith(`asset${u.ArgParamsSeparator}`)?Ht:`asset${u.ArgParamsSeparator}${Ht}`;return this.serializer.stringToNative(Je)[1]}),ze=g.find(b=>b.input.position==="data")?.value,_e="data"in c?c.data||"":null,ue=ze||_e||null,Ge=ue?p.applyInputs(ue,g,this.serializer):null,de={adapter:l,warp:o,chain:s,action:e,destination:x,args:w,value:$,transfers:qe,data:Ge,resolvedInputs:g};return await this.cache.set(ht.WarpExecutable(this.config.env,o.meta?.hash||"",e),de.resolvedInputs,ie.OneWeek),de}async getChainInfoForWarp(t,e){if(t.chain)return W(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||An(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],l=n.map(c=>i.applyInputs(c,[],this.serializer)),p=await Promise.all(l.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(c.source==="hidden"){if(c.default===void 0)return null;let v=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,v)}if(p[d])return p[d];let f=c.as||c.name,h=a?.[f],g=this.url.searchParams.get(f),y=h||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let f=o(c,d),h=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:f||(h!==void 0?this.serializer.nativeToString(c.type,h):null)}})}async resolveInputsFromQuery(t,e,n){let i=T(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),l=new R(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],l,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 l=i.value?.split(":")[1];if(!l)throw new Error("WarpActionExecutor: Scalable value not found");let p=at(l,+s);e.push({...i,value:`${i.input.type}:${p}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let l=at(s,+a);e.push({...i,value:`${i.input.type}:${l}`})}}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 l=pt(t,this.serializer,n,i),p=await s.run(a,l);if(p==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),l=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,p=l?.value?this.serializer.stringToNative(l.value)[1]??null:null;if(p){let c=await(await fetch(p)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),f=Array.from(new Uint8Array(d)).map(h=>h.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",f)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Pt(e),a=W(t,this.adapters);if(n==="asset"){let[s,l,p]=i.split(u.ArgCompositeSeparator);if(p)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=at(l,o.decimals);return te({...o,amount:c})}else return e}catch(n){throw C.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[l,p]=this.serializer.stringToNative(s),o=p;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 l=Number(a.position.split(":")[1])-1;i.push({index:l,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(p=>p.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.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 W(s,this.adapters).chainInfo}};var yt=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.handlers=n,this.factory=new G(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],l=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let h=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(h){let g=await new R(this.config,h,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:f}=N(t);for(let h=1;h<=t.actions.length;h++){let g=T(t,h);if(!St(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:v,chain:x,immediateExecution:w,executable:H}=await this.executeAction(t,h,e,y);if(v&&i.push(v),x&&(a=x),w&&s.push(w),w?.output){let{_DATA:A,...O}=w.output;Object.assign(d,O)}w?.values?.mapped&&Object.assign(d,w.values.mapped),H&&h===f+1&&H.resolvedInputs&&(l=B(H.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:l}}async executeAction(t,e,n,i={}){let a=T(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):Ut.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=Q(a.when,o);if(!K(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 y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},f={};for(let[y,v]of Object.entries(c.meta?.query||{}))f[y]=v.replace(/\{\{(.+?)\}\}/g,(x,w)=>String(d[w.trim()]??""));c.meta={...c.meta,query:f};let{immediateExecutions:h}=await this.execute(c,[],i),g=h[0];return g?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),{tx:null,chain:null,immediateExecution:g,executable:null}):{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);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 l=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await l.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 l.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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,l)=>{if(!St(s)||s.type!=="transfer"&&s.type!=="contract")return null;let p=e[l],o=l+1;if(!p){let h=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:h};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 h=t.meta?.query;h&&Object.keys(h).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,h))}let d=await i.output.getActionExecution(t,o,p.tx,c),f=Cn(c,d.output);return d.next=lt(this.config,this.adapters,t,o,f,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:p})):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(l=>l.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=_(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:l,output:p}=await Y(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",l,p)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=_(t.resolvedInputs,n),{values:a,output:s}=await Y(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){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:p,method:o,headers:c,body:d}=await Me(s,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));C.debug("WarpExecutor: Executing HTTP collect",{url:p,method:o,headers:c,body:d});try{let f={method:o,headers:c,body:d},g=await(await Yt(this.adapters))(p,f);C.debug("Collect response status",{status:g.status});let y=await g.json();C.debug("Collect response content",{content:y});let{values:v,output:x}=await Y(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",v,x,y)}catch(f){C.error("WarpActionExecutor: Error executing collect",f);let h=B(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:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let h=B(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:h}}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=B(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 l=this.factory.getSerializer(),p=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=p.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),f={};o.headers&&Object.entries(o.headers).forEach(([h,g])=>{let y=p.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());f[h]=y}),C.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:f});try{let h=new s(new URL(c),{requestInit:{headers:f}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(h);let y={};t.resolvedInputs.forEach(({input:A,value:O})=>{if(O&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let U=A.position.replace("payload:",""),[$,D]=l.stringToNative(O);if($==="string")y[U]=String(D);else if($==="bool")y[U]=!!D;else if($==="uint8"||$==="uint16"||$==="uint32"||$==="uint64"||$==="uint128"||$==="uint256"||$==="biguint"){let xt=Number(D);y[U]=(Number.isInteger(xt),xt)}else y[U]=D}}),e&&Object.assign(y,e);let v=await g.callTool({name:d,arguments:y});await g.close();let x;if(v.content&&v.content.length>0){let A=v.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=v;let{values:w,output:H}=await Y(t.warp,x,t.action,t.resolvedInputs,l,this.config);return this.buildCollectResult(t,n,"success",w,H,v)}catch(h){C.error("WarpExecutor: Error executing MCP",h);let g=B(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let l=lt(this.config,this.adapters,t.warp,t.action,a,n),p=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:l,values:i,output:s?{...a,_DATA:s}:a,messages:Et(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}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,p=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let f={...n.envs,...i},h=Q(s.when,f);try{if(!K(h)){this.loopIterations.delete(p);continue}}catch{this.loopIterations.delete(p);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(p)??0)+1;if(c>o){this.loopIterations.delete(p),C.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(p,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 p=i.envs||{},o=Q(e.when,p);if(!K(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),l=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let p=await a.get(l)??{},o=e.keys??Object.keys(p),c={};for(let f of o)p[f]!==void 0&&p[f]!==null&&(c[`state.${f}`]=p[f]);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 p=await a.get(l)??{},o=i.envs||{},c={};for(let[d,f]of Object.entries(e.data))if(typeof f=="string"){let h=f.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let v=o[y.trim()];return v!=null?String(v):f});c[d]=wn(h)}else c[d]=f;await a.set(l,{...p,...c})}return e.op==="clear"&&await a.delete(l),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),l=W(s.name,this.adapters),p=new R(this.config,l,this.adapters),o=await p.apply(t,a),c=T(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),O=await this.factory.getResolvedInputs(s.name,e,A,p,a.queries);d=await this.factory.getModifiedInputs(O)}else{let{action:A}=N(o),O=this.factory.getStringTypedInputs(A,i),U=await this.factory.getResolvedInputs(s.name,A,O,p,a.queries);d=await this.factory.getModifiedInputs(U)}let f=Zt(c.prompt,this.config.platform),h=p.applyInputs(f,d,this.factory.getSerializer()),g=B(d),y=P(this.config,s.name),v=this.factory.getSerializer(),{values:x,output:w}=await Xt(o,h,n,d,v,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(h,c.expect);A&&(w.MESSAGE=A)}let H=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:ot(this.config,this.adapters,o,n,w),values:x,output:w,messages:Et(o,{...x.mapped,...w},this.config),destination:H,resolvedInputs:g}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:lt(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 l=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),p=W(l.name,this.adapters),o=new R(this.config,p,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(l.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),f={...i.envs??{},...d},h=Q(e.when,f);return K(h)}},Cn=(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}},wn=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var Wt=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 C.error("WarpIndex: Error searching for warps: ",i),i}}};var vt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!Z(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),l=s.length>0,p=s.map(o=>({url:o.url,warp:o.warp}));return{match:l,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?Z(t):V(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,l=null,p=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?zt(t):_t(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(l=g.warp,p=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){l=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);p=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);p=y.registryInfo,o=y.brand,y.registryInfo&&(l=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(l&&l.meta&&(In(l,i.chain,p,i.identifier),l.meta.query=c?Gt(c):null),!l)return n;let d=l.chain||i.chain||null,f=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,h=f?await new R(this.config,f,this.adapters).apply(l):l;return{match:!0,url:t,warp:h,chain:d,registryInfo:p,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},In=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?bt(null,"alias",e.alias):bt(t,"hash",e?.hash??n))};var le=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 rt(e));return new nt(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 yt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new vt(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"),l=a?t:null;if(!l&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");l=await g.json()}if(l||(l=(await this.detectWarp(t,i.cache)).warp),!l)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:f}=await p.execute(l,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await p.evaluateOutput(l,g)},resolvedInputs:f}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=V(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??N(e).index+1,l=await W(t,this.chains).output.getActionExecution(e,a,n);return l.next=ot(this.config,this.chains,e,a,l.output),l}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new Wt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new ut(this.config)}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return st(t,this.config)}};var pe=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 Sn(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ce(t,n)!==i)return!1;return!0}function bn(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ce(t,i):i;return e}function ce(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}0&&(module.exports={BrowserCryptoProvider,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,MultiversxWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpAssets,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainDisplayNames,WarpChainLogos,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getChainDisplayName,getChainLogo,getCryptoProvider,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getMppFetch,getNextInfo,getNextInfoForStatus,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpInputAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,matchesTrigger,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveInputs,resolveNextString,resolveNextStrings,resolvePath,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var nt=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 it=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 Ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Se=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Se(r.user?.wallets?.[t]||null),be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ee=r=>r?typeof r=="string"?r:r.externalId||null:null,Sr=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,br=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Pr=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Er=r=>typeof r=="string",Tr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Rr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Re=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ne=(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`)},Nr=(r,t=24)=>{let e=Re(r);return Ne(e,t),e};var $e=(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))($e||{}),kt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(kt||{}),Mt=Object.values(kt),Or=["ethereum","base","arbitrum","polygon","somnia","tempo"],Lr=["multiversx","claws"],Vr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(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:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={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"},qt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},L={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${M.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","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 Dr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var at="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",b={baseUrl:at,chainLogo:r=>`${at}/chains/logos/${r}`,tokenLogo:r=>`${at}/tokens/logos/${r}`,walletLogo:r=>`${at}/wallets/logos/${r}`},Be={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"},kr=r=>Be[r]??r.charAt(0).toUpperCase()+r.slice(1),Oe={ethereum:{light:b.chainLogo("ethereum-white.svg"),dark:b.chainLogo("ethereum-black.svg")},base:{light:b.chainLogo("base-white.svg"),dark:b.chainLogo("base-black.svg")},arbitrum:b.chainLogo("arbitrum.svg"),polygon:b.chainLogo("polygon.svg"),somnia:b.chainLogo("somnia.png"),tempo:{light:b.chainLogo("tempo-white.svg"),dark:b.chainLogo("tempo-black.svg")},multiversx:b.chainLogo("multiversx.svg"),claws:b.chainLogo("claws.png"),sui:b.chainLogo("sui.svg"),solana:b.chainLogo("solana.svg"),near:{light:b.chainLogo("near-white.svg"),dark:b.chainLogo("near-black.svg")},fastset:{light:b.chainLogo("fastset-white.svg"),dark:b.chainLogo("fastset-black.svg")}},Mr=(r,t="dark")=>{let e=Oe[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var wt=(r,t)=>r[t]??r.default??Object.values(r)[0],zr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:wt(r.logo,e)},_r=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)},Gr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)};var It=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}},St=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"}`)}}},D=null;function zt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new It,D;if(typeof process<"u"&&process.versions?.node)return D=new St,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Qr(r){D=r}async function _t(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||zt()).getRandomBytes(r)}function Le(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 Kr(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 Gt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await _t(r/2,t);return Le(e)}async function Xr(){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 _t(16),r.randomBytes=!0}catch{}return r}function Zr(){return zt()}var en=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 W=(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},st=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],Ve=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!Ve.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},bt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,ot=(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 l=s.slice(0,-a)||"0";return BigInt(l)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Jt=(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},j=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),J=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),on=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}},Q=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var pn={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"},lt=(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""},cn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,un=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,hn=(r,t)=>!r||!t?!1:K(r)===K(t),Pt=(r,t,e)=>{let n=K(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},U=r=>{let t=decodeURIComponent(r).trim(),e=K(t),n=e.split("?")[0],i=Qt(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,l]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let p=e.includes("?")?l+e.substring(e.indexOf("?")):l;return{chain:a,type:s,identifier:p,identifierBase:l}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:l,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s,p=Fe(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:p,identifier:l,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},X=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 U(i)},Fe=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,He=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Qt=r=>{let t=He(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Qt(a);return[i,...s]},Kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Xt=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},Zt=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},mn=r=>{let t=U(r);return(t?t.identifierBase:K(r)).trim()},yn=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 Et=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},xn=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Et(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=lt(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};import Ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}build(t,e,n){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,l=a.chainInfo.name+u.IdentifierParamSeparator+s,p=encodeURIComponent(l);return L.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${u.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=U(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return L.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(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",l="#23F7DD"){let p=W(t,this.adapters),o=this.build(p.chainInfo.name,e,n);return new Ue({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(l)}" 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 De="https://",Nt=(r,t)=>{if(!r)return null;if(typeof r=="string")return t==="success"?[r]:null;if(Array.isArray(r))return t==="success"?r:null;let e=r[t];return e?Array.isArray(e)?e:[e]:null},On=(r,t)=>Nt(r,t)?.[0]??null,Yt=(r,t,e,n,i)=>{if(n.startsWith(De))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let g=j(a,{...e.vars,...i});return[{identifier:g,url:Rt(t,g,r)}]}let l=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let g=j(s,{...e.vars,...i}),f=g?`${a}?${g}`:a;return[{identifier:f,url:Rt(t,f,r)}]}let p=l[0];if(!p)return[];let o=p.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=l.filter(g=>g.includes(`{{${c}[]`)).map(g=>{let f=g.match(/\[\](\.[^}]+)?}}/),y=f&&f[1]||"";return{placeholder:g,field:y?y.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(g=>{let f=s;for(let{regex:v,field:x}of h){let C=x?je(g,x):g;if(C==null)return null;f=f.replace(v,C)}if(f.includes("{{")||f.includes("}}"))return null;let y=f?`${a}?${f}`:a;return{identifier:y,url:Rt(t,y,r)}}).filter(g=>g!==null)},pt=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Nt(a,"success");if(!s)return null;let l=s.flatMap(p=>Yt(r,t,e,p,i));return l.length>0?l:null},ct=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",l=E(e,n)?.next||e.next||null,p=Nt(l,s);if(!p)return null;let o=p.flatMap(c=>Yt(r,t,e,c,i));return o.length>0?o:null},Rt=(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((l,p)=>s.searchParams.set(p,l)),s.toString().replace(/\/\?/,"?")},je=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var k=class k{static debug(...t){k.isTestEnv||console.debug(...t)}static info(...t){k.isTestEnv||console.info(...t)}static warn(...t){k.isTestEnv||console.warn(...t)}static error(...t){k.isTestEnv||console.error(...t)}};k.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=k;function ke(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 te(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]=te(e[n],t[n]):e[n]=t[n]}),e}function Me(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 B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function z(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Me(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=ke(n.input.position,i,a);e=te(e,s)}else e[i]=a}),e}function ut(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=l=>{if(!l?.value)return;let p=l.input.as||l.input.name,[,o]=t.stringToNative(l.value);if(i[p]=o,l.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[`${p}.token`]=d,i[`${p}.identifier`]=d,i[`${p}.amount`]=String(c.amount)}};for(let l=0;l<a;l++)s(r[l]);return s(n),i}var ee=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,l]of Object.entries(r.output)){if(l.startsWith(u.Transform.Prefix))continue;let p=Ge(l);if(p!==null&&p!==t){a[s]=null;continue}let[o,...c]=l.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]=l}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,f)=>g&&g[f]!==void 0?g[f]:null,d),l=d=>d.length===0?t:s(t,d),{stringValues:p,nativeValues:o,output:c}=ee(r,e,l);return{values:{string:p,native:o,mapped:z(n,i)},output:await re(r,c,t,e,n,i,a)}},re=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let l={...t};return l=qe(l,r,n,i,a),l=await ze(r,l,e,i,a,s.transform?.runner||null),l},qe=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[l,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("in.")){let o=p.split(".")[1],c=s.findIndex(h=>h.as===o||h.name===o),d=c!==-1?n[c]?.value:null;a[l]=d?i.stringToNative(d)[1]:null}return a},ze=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},l=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(l.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 p={...s,out:_e(e),inputs:ut(n,i)};for(let{key:o,code:c}of l)try{s[o]=await a.run(c,p),p[o]=s[o]}catch(d){w.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,p[o]=null}return s},_e=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},ne=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:l,nativeValues:p,output:o}=ee(r,e,s),c=await re(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:l,native:p,mapped:z(n,i)},output:c}},Ge=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 Je=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Mt.some(t=>t in r),ie=(r,t)=>{if(!Je(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 Gn=(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 Qe(r,t,e,n=5){let i=await Gt(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 $t(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Qe(r,i,e,5)}function Bt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Xn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await $t(r,e,n),l=await t(i);return Bt(r,l,a,s)}function Zn(r){let t=new Date(r).getTime();return Date.now()<t}function Yn(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 Ke=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Xe=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ae=(r,t=24)=>{let e=Xe(r);return e?e.slice(0,t):"action"},se=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)},Ze=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()}},ei=(r,t,e)=>{let n=ae((e||t||"").trim()||"action"),i=`${r.type}|${Ze(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=se(i);return`private_src_${n}_${a}`},Ye=r=>{let t=Ke(r),e=ae(t),n=se(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ri=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ye(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ni=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ai(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 oi(r,t,e){return null}var tr=(r,t)=>{let e=null;try{e=N(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=W(e,n),a=tr(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),l=new Map(s.map(p=>[p.identifier,p.amount??0n]));return a.every(p=>(l.get(p)??0n)>0n)}catch{return!0}};import{Mppx as er,tempo as rr}from"mppx/client";async function oe(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return w.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),er.create({methods:[rr({account:e})],polyfill:!1}).fetch}return fetch}var le={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=le[t]??t,t===m.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===m.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(l=>l!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(l=>{let[p,o]=this.getTypeAndValue(n[l]);return`(${l}${u.ArgParamsSeparator}${p})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&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[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(p=>{let o=p.indexOf(u.ArgParamsSeparator),c=p.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),l=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(l)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.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+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=le[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),l=i.substring(a+1),p=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(l?l.split(p):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),l=i.split(u.ArgCompositeSeparator).map((p,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${p}`)[1]);return[n,l]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let l={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(p=>{let o=p.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,h]=o;l[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${h}`)[1]}}),[n,l]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),l={identifier:a,amount:BigInt(s)};return[n,l]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let l=a.stringToNative(i);return[n,l]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[l,p]=this.stringToNative(`${s}:${i}`);return[n,p]}}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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var vi=r=>new I().nativeToString(m.String,r),xi=r=>new I().nativeToString(m.Uint8,r),Ai=r=>new I().nativeToString(m.Uint16,r),Ci=r=>new I().nativeToString(m.Uint32,r),wi=r=>new I().nativeToString(m.Uint64,r),Ii=r=>new I().nativeToString(m.Biguint,r),Si=r=>new I().nativeToString(m.Bool,r),bi=r=>new I().nativeToString(m.Address,r),pe=r=>new I().nativeToString(m.Asset,r),Pi=r=>new I().nativeToString(m.Hex,r),Ei=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Ti=(...r)=>new I().nativeToString(m.Tuple,r),Ri=r=>new I().nativeToString(m.Struct,r),Ni=r=>new I().nativeToString(m.Vector,r);import nr from"ajv";var ce=class{constructor(t){this.pendingBrand={protocol:st("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||L.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new nr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import ir from"ajv";var ar=new Set(["POST","PUT","PATCH","DELETE"]),sr=/^[A-Z][A-Z0-9_]*$/,dt=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}=N(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 l=a.destination;if(!l||typeof l=="string"||!l.url)continue;let p=this.extractUrlPlaceholders(l.url);if(p.length!==0)for(let o of p)n.has(o)||sr.test(o)||i.has(o)||e.push(`URL "${l.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||!ar.has(a))continue;let s=n.inputs??[];for(let l of s)if(l.position?.startsWith("arg:")){let p=l.as??l.name??"(unnamed)";e.push(`Input "${p}" has position "${l.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||L.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ir({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var gt=class{constructor(t){this.config=t;this.pendingWarp={protocol:st("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 Jt(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 dt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};import{existsSync as Lt,mkdirSync as or,readdirSync as ue,readFileSync as lr,unlinkSync as Vt,writeFileSync as pr}from"fs";import{join as de,resolve as ge}from"path";var Ot="$bigint:",ft=(r,t)=>typeof t=="bigint"?Ot+t.toString():t,_=(r,t)=>typeof t=="string"&&t.startsWith(Ot)?BigInt(t.slice(Ot.length)):t;var ht=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ge(n):ge(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Lt(this.cacheDir)||or(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return de(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Lt(e))return null;let n=lr(e,"utf-8"),i=JSON.parse(n,_);return i.expiresAt!==null&&Date.now()>i.expiresAt?(Vt(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);pr(a,JSON.stringify(i,ft),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Lt(e)&&Vt(e)}catch{}}async keys(t){try{let e=ue(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{ue(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Vt(de(this.cacheDir,e))})}catch{}}};var Y=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,_);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,ft))}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 V=class V{constructor(t,e){}async get(t){let e=V.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(V.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;V.cache.set(t,{value:e,expiresAt:i})}async delete(t){V.cache.delete(t)}async keys(t){let e=Array.from(V.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){V.cache.clear()}};V.cache=new Map;var tt=V;import{readFileSync as cr}from"fs";import{resolve as fe}from"path";var mt=class{constructor(t,e){let n=e?.path?fe(e.path):fe(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=cr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,_)))}catch(e){return w.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 he={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={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}`},yt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new mt(t,e):e?.type==="filesystem"?new ht(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(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 et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Ft={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ht=(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)},Ut=r=>{try{return JSON.parse(r)}catch{return null}},ur=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:p,nonce:o,expiresAt:c}=await $t(n,`${e.chain.name}-adapter`),d=await a({message:p,chain:e.chain});d&&Object.entries(Bt(n,d,o,c)).forEach(([h,g])=>s.set(h,g))}let l=Ht(e.resolvedInputs,et.Headers,i);if(l){let p=Ut(l);p&&typeof p=="object"&&Object.entries(p).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([p,o])=>{s.set(p,r.applyInputs(o,e.resolvedInputs,i))});return s},dr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Ft.Get){let s=Ht(e.resolvedInputs,et.Queries,i);if(s){let l=Ut(s);if(l&&typeof l=="object"){let p=new URL(a);Object.entries(l).forEach(([o,c])=>c!=null&&p.searchParams.set(o,String(c))),a=p.toString()}}}return a},gr=(r,t,e,n,i)=>{if(r===Ft.Get)return;let a=Ht(t.resolvedInputs,et.Payload,n);if(a&&Ut(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:l,...p}=e;return JSON.stringify({...p,...i})},me=async(r,t,e,n,i,a,s,l)=>{let p=t.method||Ft.Get,o=await ur(r,t,e,n,a,l),c=dr(r,t,e,p,a),d=gr(p,e,i,a,s);return{url:c,method:p,headers:o,body:d}};var T=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=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${fr(i)}\\}\\}`,"g"),s)}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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,l)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([s,l])=>{if(typeof l!="string")a(s,l);else if(l.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Query.length+1),[o,c]=p.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(l.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Env.length+1),[o,c]=p.split(u.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else l===u.Source.UserWallet&&n?a(s,n):a(s,l)}),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 j(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 l=s.Accessor(i);l!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),l.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,l)=>{let p=l.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(p,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}},fr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var hr=["collect","compute","mcp","state","mount","unmount"],mr=new Set(Object.values(m)),yr=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:mr.has(r.slice(0,t))},G=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 I,this.cache=new yt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return B(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),l=W(s.name,this.adapters),p=new T(this.config,l,this.adapters),o=await p.apply(t,i),c=E(o,e),{action:d,index:h}=N(o),g=[],f=[];if(h===e-1){let S=this.getStringTypedInputs(d,n);g=await this.getResolvedInputs(s.name,d,S,p,i.queries),f=await this.getModifiedInputs(g)}else c.inputs&&c.inputs.length>0&&(g=await this.resolveActionInputs(s.name,c,n,p,i.queries),f=await this.getModifiedInputs(g));let y=f.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,v=this.getDestinationFromAction(c),x=y?this.serializer.stringToNative(y)[1]:v;if(x&&(x=p.applyInputs(x,f,this.serializer)),!x&&!hr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let C=this.getPreparedArgs(c,f);C=C.map(S=>p.applyInputs(S,f,this.serializer));let O=f.find(S=>S.input.position==="value")?.value||null,A="value"in c?c.value:null,$=O?.split(u.ArgParamsSeparator)[1]||A||"0",F=p.applyInputs($,f,this.serializer),R=BigInt(F),H=f.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),xe=[...("transfers"in c?c.transfers:[])||[],...H||[]].map(S=>{let Ct=p.applyInputs(S,f,this.serializer),Ie=Ct.startsWith(`asset${u.ArgParamsSeparator}`)?Ct:`asset${u.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Ie)[1]}),Ae=f.find(S=>S.input.position==="data")?.value,Ce="data"in c?c.data||"":null,Dt=Ae||Ce||null,we=Dt?p.applyInputs(Dt,f,this.serializer):null,jt={adapter:l,warp:o,chain:s,action:e,destination:x,args:C,value:R,transfers:xe,data:we,resolvedInputs:f};return await this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),jt.resolvedInputs,he.OneWeek),jt}async getChainInfoForWarp(t,e){if(t.chain)return W(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||yr(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],l=n.map(c=>i.applyInputs(c,[],this.serializer)),p=await Promise.all(l.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(c.source==="hidden"){if(c.default===void 0)return null;let v=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,v)}if(p[d])return p[d];let h=c.as||c.name,g=a?.[h],f=this.url.searchParams.get(h),y=g||f;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let h=o(c,d),g=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:h||(g!==void 0?this.serializer.nativeToString(c.type,g):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),l=new T(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],l,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 l=i.value?.split(":")[1];if(!l)throw new Error("WarpActionExecutor: Scalable value not found");let p=ot(l,+s);e.push({...i,value:`${i.input.type}:${p}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let l=ot(s,+a);e.push({...i,value:`${i.input.type}:${l}`})}}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 l=ut(t,this.serializer,n,i),p=await s.run(a,l);if(p==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),l=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,p=l?.value?this.serializer.stringToNative(l.value)[1]??null:null;if(p){let c=await(await fetch(p)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),h=Array.from(new Uint8Array(d)).map(g=>g.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]=Et(e),a=W(t,this.adapters);if(n==="asset"){let[s,l,p]=i.split(u.ArgCompositeSeparator);if(p)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=ot(l,o.decimals);return pe({...o,amount:c})}else return e}catch(n){throw w.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[l,p]=this.serializer.stringToNative(s),o=p;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 l=Number(a.position.split(":")[1])-1;i.push({index:l,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(p=>p.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.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 W(s,this.adapters).chainInfo}};var vt=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.handlers=n,this.factory=new G(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],l=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={},{index:h}=N(t);for(let g=1;g<=t.actions.length;g++){let f=E(t,g);if(!bt(f))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:v,chain:x,immediateExecution:C,executable:O}=await this.executeAction(t,g,e,y);if(v&&i.push(v),x&&(a=x),C&&s.push(C),C?.output){let{_DATA:A,...$}=C.output;Object.assign(d,$)}C?.values?.mapped&&Object.assign(d,C.values.mapped),O&&g===h+1&&O.resolvedInputs&&(l=B(O.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 g=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(g))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:l}}async executeAction(t,e,n,i={}){let a=E(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):qt.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=J(a.when,o);if(!Q(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 y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};let d={...this.config.vars,...i.envs||{},...i.queries||{}};Object.entries(d).filter(([,y])=>typeof y!="string").forEach(([y,v])=>console.log("[warp:inline] non-string bag value",{key:y,type:typeof v,value:v}));let h={};for(let[y,v]of Object.entries(c.meta?.query||{}))h[y]=v.replace(/\{\{(.+?)\}\}/g,(x,C)=>String(d[C.trim()]??""));c.meta={...c.meta,query:h};let{immediateExecutions:g}=await this.execute(c,[],i),f=g[0];return f?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:f,tx:null})),{tx:null,chain:null,immediateExecution:f,executable:null}):{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);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 l=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await l.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 l.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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,l)=>{if(!bt(s)||s.type!=="transfer"&&s.type!=="contract")return null;let p=e[l],o=l+1;if(!p){let g=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),f={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:g};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:f})),f}let c=await this.factory.getRawResolvedInputsFromCache(this.config.env,t.meta?.hash,o);if(c.length===0){let g=t.meta?.query;g&&Object.keys(g).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,g))}let d=await i.output.getActionExecution(t,o,p.tx,c),h=Wr(c,d.output);return d.next=ct(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:p})):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(l=>l.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=z(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:l,output:p}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",l,p)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=z(t.resolvedInputs,n),{values:a,output:s}=await Z(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){let s=new T(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:p,method:o,headers:c,body:d}=await me(s,e,t,n,i,l,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));w.debug("WarpExecutor: Executing HTTP collect",{url:p,method:o,headers:c,body:d});try{let h={method:o,headers:c,body:d},f=await(await oe(this.adapters))(p,h);w.debug("Collect response status",{status:f.status});let y=await f.json();w.debug("Collect response content",{content:y});let{values:v,output:x}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),f.ok?"success":"error",v,x,y)}catch(h){w.error("WarpActionExecutor: Error executing collect",h);let g=B(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:h},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=P(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=B(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:g}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let f=B(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:f}}let l=this.factory.getSerializer(),p=new T(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=p.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,f])=>{let y=p.applyInputs(f,t.resolvedInputs,this.factory.getSerializer());h[g]=y}),w.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:h});try{let g=new s(new URL(c),{requestInit:{headers:h}}),f=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await f.connect(g);let y={};t.resolvedInputs.forEach(({input:A,value:$})=>{if($&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let F=A.position.replace("payload:",""),[R,H]=l.stringToNative($);if(R==="string")y[F]=String(H);else if(R==="bool")y[F]=!!H;else if(R==="uint8"||R==="uint16"||R==="uint32"||R==="uint64"||R==="uint128"||R==="uint256"||R==="biguint"){let rt=Number(H);y[F]=(Number.isInteger(rt),rt)}else y[F]=H}}),e&&Object.assign(y,e);let v=await f.callTool({name:d,arguments:y});await f.close();let x;if(v.content&&v.content.length>0){let A=v.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=v;let{values:C,output:O}=await Z(t.warp,x,t.action,t.resolvedInputs,l,this.config);return this.buildCollectResult(t,n,"success",C,O,v)}catch(g){w.error("WarpExecutor: Error executing MCP",g);let f=B(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:g},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:f}}}buildCollectResult(t,e,n,i,a,s){let l=ct(this.config,this.adapters,t.warp,t.action,a,n),p=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:l,values:i,output:s?{...a,_DATA:s}:a,messages:Tt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}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,p=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let h={...n.envs,...i},g=J(s.when,h);try{if(!Q(g)){this.loopIterations.delete(p);continue}}catch{this.loopIterations.delete(p);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(p)??0)+1;if(c>o){this.loopIterations.delete(p),w.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(p,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 p=i.envs||{},o=J(e.when,p);if(!Q(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),l=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let p=await a.get(l)??{},o=e.keys??Object.keys(p),c={};for(let h of o)p[h]!==void 0&&p[h]!==null&&(c[`state.${h}`]=p[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 p=await a.get(l)??{},o=i.envs||{},c={};for(let[d,h]of Object.entries(e.data))if(typeof h=="string"){let g=h.replace(/\{\{([^}]+)\}\}/g,(f,y)=>{let v=o[y.trim()];return v!=null?String(v):h});c[d]=vr(g)}else c[d]=h;await a.set(l,{...p,...c})}return e.op==="clear"&&await a.delete(l),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),l=W(s.name,this.adapters),p=new T(this.config,l,this.adapters),o=await p.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),$=await this.factory.getResolvedInputs(s.name,e,A,p,a.queries);d=await this.factory.getModifiedInputs($)}else{let{action:A}=N(o),$=this.factory.getStringTypedInputs(A,i),F=await this.factory.getResolvedInputs(s.name,A,$,p,a.queries);d=await this.factory.getModifiedInputs(F)}let h=ie(c.prompt,this.config.platform),g=p.applyInputs(h,d,this.factory.getSerializer()),f=B(d),y=P(this.config,s.name),v=this.factory.getSerializer(),{values:x,output:C}=await ne(o,g,n,d,v,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(g,c.expect);A&&(C.MESSAGE=A)}let O=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:pt(this.config,this.adapters,o,n,C),values:x,output:C,messages:Tt(o,{...x.mapped,...C},this.config),destination:O,resolvedInputs:f}}catch(s){return w.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:ct(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 l=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),p=W(l.name,this.adapters),o=new T(this.config,p,this.adapters),c;if(a)c=a;else{let f=await this.factory.getResolvedInputs(l.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(f)}let d=o.buildInputBag(c,this.factory.getSerializer()),h={...i.envs??{},...d},g=J(e.when,h);return Q(g)}},Wr=(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}},vr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var xt=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 w.error("WarpIndex: Error searching for warps: ",i),i}}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(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),l=s.length>0,p=s.map(o=>({url:o.url,warp:o.warp}));return{match:l,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?X(t):U(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,l=null,p=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Kt(t):Xt(i.identifier);if(this.resolver){let f=null;if(a==="hash")f=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;f=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}f&&(l=f.warp,p=f.registryInfo,o=f.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let f=W(i.chain,this.adapters);if(a==="hash"){l=await f.builder().createFromTransactionHash(s,e);let y=await f.registry.getInfoByHash(s,e);p=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await f.registry.getInfoByAlias(s,e);p=y.registryInfo,o=y.brand,y.registryInfo&&(l=await f.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(l&&l.meta&&(xr(l,i.chain,p,i.identifier),l.meta.query=c?Zt(c):null),!l)return n;let d=l.chain||i.chain||null,h=d?this.adapters.find(f=>f.chainInfo.name.toLowerCase()===d.toLowerCase()):null,g=h?await new T(this.config,h,this.adapters).apply(l):l;return{match:!0,url:t,warp:g,chain:d,registryInfo:p,brand:o}}catch(a){return w.error("Error detecting warp link",a),n}}},xr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Pt(null,"alias",e.alias):Pt(t,"hash",e?.hash??n))};var ye=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 nt(e));return new it(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 vt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new At(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"),l=a?t:null;if(!l&&s){let f=await fetch(t);if(!f.ok)throw new Error("WarpClient: executeWarp - invalid url");l=await f.json()}if(l||(l=(await this.detectWarp(t,i.cache)).warp),!l)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:h}=await p.execute(l,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async f=>{await p.evaluateOutput(l,f)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=U(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??N(e).index+1,l=await W(t,this.chains).output.getActionExecution(e,a,n);return l.next=pt(this.config,this.chains,e,a,l.output),l}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new xt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new gt(this.config)}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return lt(t,this.config)}};var We=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 os(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ve(t,n)!==i)return!1;return!0}function ls(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ve(t,i):i;return e}function ve(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{It as BrowserCryptoProvider,Vr as CLOUD_WALLET_PROVIDERS,he as CacheTtl,Or as EvmWalletChainNames,Lr as MultiversxWalletChainNames,St as NodeCryptoProvider,pn as WARP_LANGUAGES,b as WarpAssets,ce as WarpBrandBuilder,gt as WarpBuilder,yt as WarpCache,Wt as WarpCacheKey,Be as WarpChainDisplayNames,Oe as WarpChainLogos,$e as WarpChainName,nt as WarpChainResolver,ye as WarpClient,it as WarpCompositeResolver,L as WarpConfig,u as WarpConstants,vt as WarpExecutor,G as WarpFactory,xt as WarpIndex,m as WarpInputTypes,T as WarpInterpolator,q as WarpLinkBuilder,At as WarpLinkDetecter,w as WarpLogger,kt as WarpPlatformName,Mt as WarpPlatforms,M as WarpProtocolVersions,I as WarpSerializer,We as WarpTypeRegistry,dt as WarpValidator,bi as address,Tt as applyOutputToMessages,pe as asset,Ii as biguint,Si as bool,Ye as buildGeneratedFallbackWarpIdentifier,ei as buildGeneratedSourceWarpIdentifier,ut as buildInputsContext,z as buildMappedOutput,ke as buildNestedPayload,Kr as bytesToBase64,Le as bytesToHex,ci as checkWarpAssetBalance,K as cleanWarpIdentifier,Bt as createAuthHeaders,$t as createAuthMessage,Zr as createCryptoProvider,oi as createDefaultWalletProvider,Xn as createHttpAuthHeaders,Qe as createSignableMessage,un as createWarpI18nText,Pt as createWarpIdentifier,on as doesWarpRequireWallet,re as evaluateOutputCommon,Q as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,ne as extractPromptOutput,Xt as extractQueryStringFromIdentifier,Kt as extractQueryStringFromUrl,B as extractResolvedInputValues,en as extractWarpSecrets,W as findWarpAdapterForChain,kr as getChainDisplayName,Mr as getChainLogo,zt as getCryptoProvider,Ke as getGeneratedSourceWarpName,st as getLatestProtocolIdentifier,oe as getMppFetch,pt as getNextInfo,ct as getNextInfoForStatus,Gn as getProviderConfig,_t as getRandomBytes,Gt as getRandomHex,tr as getRequiredAssetIds,Ir as getWalletFromConfigOrFail,E as getWarpActionByIndex,zr as getWarpBrandLogoUrl,_r as getWarpChainAssetLogoUrl,Gr as getWarpChainInfoLogoUrl,yn as getWarpIdentifierWithQuery,U as getWarpInfoFromIdentifier,N as getWarpInputAction,Se as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ee as getWarpWalletExternalId,Te as getWarpWalletExternalIdFromConfig,Pr as getWarpWalletExternalIdFromConfigOrFail,Pe as getWarpWalletMnemonic,br as getWarpWalletMnemonicFromConfig,be as getWarpWalletPrivateKey,Sr as getWarpWalletPrivateKeyFromConfig,xn as hasInputPrefix,Pi as hex,ai as initializeWalletCache,hn as isEqualWarpIdentifier,ni as isGeneratedSourcePrivateIdentifier,Je as isPlatformValue,bt as isWarpActionAutoExecute,cn as isWarpI18nText,Er as isWarpWalletReadOnly,os as matchesTrigger,te as mergeNestedPayload,Nr as normalizeAndValidateMnemonic,Re as normalizeMnemonic,Ei as option,Ge as parseOutputOutIndex,Yn as parseSignedMessage,Zt as parseWarpQueryStringToObject,mn as removeWarpChainPrefix,Rr as removeWarpWalletFromConfig,j as replacePlaceholders,J as replacePlaceholdersInWhenExpression,ls as resolveInputs,On as resolveNextString,Nt as resolveNextStrings,ve as resolvePath,ie as resolvePlatformValue,lt as resolveWarpText,qt as safeWindow,Qr as setCryptoProvider,Tr as setWarpWalletInConfig,ot as shiftBigintBy,Et as splitInput,ri as stampGeneratedWarpMeta,vi as string,Ri as struct,Xr as testCryptoAvailability,Me as toInputPayloadValue,Jt as toPreviewText,Ti as tuple,Ai as uint16,Ci as uint32,wi as uint64,xi as uint8,Ne as validateMnemonicLength,Zn as validateSignedMessage,Ni as vector,Dr as withAdapterFallback};
|
|
1
|
+
var nt=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 it=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 Ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Se=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Se(r.user?.wallets?.[t]||null),be=r=>r?typeof r=="string"?r:r.privateKey||null:null,Pe=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ee=r=>r?typeof r=="string"?r:r.externalId||null:null,Sr=(r,t)=>be(r.user?.wallets?.[t]||null)?.trim()||null,br=(r,t)=>Pe(r.user?.wallets?.[t]||null)?.trim()||null,Te=(r,t)=>Ee(r.user?.wallets?.[t]||null)?.trim()||null,Pr=(r,t)=>{let e=Te(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Er=r=>typeof r=="string",Tr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Rr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Re=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ne=(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`)},Nr=(r,t=24)=>{let e=Re(r);return Ne(e,t),e};var $e=(f=>(f.Multiversx="multiversx",f.Claws="claws",f.Sui="sui",f.Ethereum="ethereum",f.Base="base",f.Arbitrum="arbitrum",f.Polygon="polygon",f.Somnia="somnia",f.Tempo="tempo",f.Fastset="fastset",f.Solana="solana",f.Near="near",f))($e||{}),jt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(jt||{}),Mt=Object.values(jt),Or=["ethereum","base","arbitrum","polygon","somnia","tempo"],Lr=["multiversx","claws"],Hr=["coinbase","privy","gaupa"],u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(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:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},m={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"},qt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},L={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${M.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","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 Dr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var at="https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main",b={baseUrl:at,chainLogo:r=>`${at}/chains/logos/${r}`,tokenLogo:r=>`${at}/tokens/logos/${r}`,walletLogo:r=>`${at}/wallets/logos/${r}`},Be={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"},jr=r=>Be[r]??r.charAt(0).toUpperCase()+r.slice(1),Oe={ethereum:{light:b.chainLogo("ethereum-white.svg"),dark:b.chainLogo("ethereum-black.svg")},base:{light:b.chainLogo("base-white.svg"),dark:b.chainLogo("base-black.svg")},arbitrum:b.chainLogo("arbitrum.svg"),polygon:b.chainLogo("polygon.svg"),somnia:b.chainLogo("somnia.png"),tempo:{light:b.chainLogo("tempo-white.svg"),dark:b.chainLogo("tempo-black.svg")},multiversx:b.chainLogo("multiversx.svg"),claws:b.chainLogo("claws.png"),sui:b.chainLogo("sui.svg"),solana:b.chainLogo("solana.svg"),near:{light:b.chainLogo("near-white.svg"),dark:b.chainLogo("near-black.svg")},fastset:{light:b.chainLogo("fastset-white.svg"),dark:b.chainLogo("fastset-black.svg")}},Mr=(r,t="dark")=>{let e=Oe[r];return typeof e=="string"?e:t==="dark"?e.light:e.dark};var wt=(r,t)=>r[t]??r.default??Object.values(r)[0],zr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:wt(r.logo,e)},_r=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)},Gr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return wt(r.logoUrl,e)};var It=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}},St=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"}`)}}},D=null;function zt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new It,D;if(typeof process<"u"&&process.versions?.node)return D=new St,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Qr(r){D=r}async function _t(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||zt()).getRandomBytes(r)}function Le(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 Kr(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 Gt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await _t(r/2,t);return Le(e)}async function Xr(){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 _t(16),r.randomBytes=!0}catch{}return r}function Zr(){return zt()}var en=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 W=(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},st=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],He=["state","mount","unmount","loop"],N=r=>{if(r.actions.length===0)throw new Error(`Warp has no actions: ${r.meta?.identifier}`);let t=r.actions.find(e=>!He.includes(e.type));return t?{action:t,index:r.actions.indexOf(t)}:{action:r.actions[0],index:0}},bt=r=>r.auto===!1?!1:r.type==="link"?r.auto===!0:!0,ot=(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 l=s.slice(0,-a)||"0";return BigInt(l)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Jt=(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},k=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":String(i)}),J=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),on=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}},Q=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var pn={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"},lt=(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""},cn=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,un=r=>r;var K=r=>r.startsWith(u.IdentifierAliasMarker)?r.replace(u.IdentifierAliasMarker,""):r,hn=(r,t)=>!r||!t?!1:K(r)===K(t),Pt=(r,t,e)=>{let n=K(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},U=r=>{let t=decodeURIComponent(r).trim(),e=K(t),n=e.split("?")[0],i=Qt(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,l]=i;if(s===u.IdentifierType.Alias||s===u.IdentifierType.Hash){let p=e.includes("?")?l+e.substring(e.indexOf("?")):l;return{chain:a,type:s,identifier:p,identifierBase:l}}}if(i.length===2){let[a,s]=i;if(a===u.IdentifierType.Alias||a===u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:null,type:a,identifier:l,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==u.IdentifierType.Alias&&a!==u.IdentifierType.Hash){let l=e.includes("?")?s+e.substring(e.indexOf("?")):s,p=Ve(s,a)?u.IdentifierType.Hash:u.IdentifierType.Alias;return{chain:a,type:p,identifier:l,identifierBase:s}}}return{chain:null,type:u.IdentifierType.Alias,identifier:e,identifierBase:n}},X=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 U(i)},Ve=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Fe=r=>{let t=u.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Qt=r=>{let t=Fe(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Qt(a);return[i,...s]},Kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(u.IdentifierParamName),e.toString()||null}catch{return null}},Xt=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},Zt=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},mn=r=>{let t=U(r);return(t?t.identifierBase:K(r)).trim()},yn=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 Et=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},xn=r=>{let t=new Set(Object.values(m));if(!r.includes(u.ArgParamsSeparator))return!1;let e=Et(r)[0];return t.has(e)};var Tt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=lt(a,e);return[i,k(s,t)]});return Object.fromEntries(n)};import Ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(t):!1}build(t,e,n){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===u.IdentifierType.Alias?n:e+u.IdentifierParamSeparator+n,l=a.chainInfo.name+u.IdentifierParamSeparator+s,p=encodeURIComponent(l);return L.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${u.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let e=U(t);if(!e)return null;if(!e.chain){let i=this.config.clientUrl||L.DefaultClientUrl(this.config.env),a=u.IdentifierAliasMarker+e.identifierBase;return L.SuperClientUrls.includes(i)?`${i}/${encodeURIComponent(a)}`:`${i}?${u.IdentifierParamName}=${encodeURIComponent(a)}`}let n=W(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",l="#23F7DD"){let p=W(t,this.adapters),o=this.build(p.chainInfo.name,e,n);return new Ue({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(l)}" 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 De="https://",Nt=(r,t)=>{if(!r)return null;if(typeof r=="string")return t==="success"?[r]:null;if(Array.isArray(r))return t==="success"?r:null;let e=r[t];return e?Array.isArray(e)?e:[e]:null},On=(r,t)=>Nt(r,t)?.[0]??null,Yt=(r,t,e,n,i)=>{if(n.startsWith(De))return[{identifier:null,url:n}];let[a,s]=n.split("?");if(!s){let h=k(a,{...e.vars,...i});return[{identifier:h,url:Rt(t,h,r)}]}let l=s.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let h=k(s,{...e.vars,...i}),g=h?`${a}?${h}`:a;return[{identifier:g,url:Rt(t,g,r)}]}let p=l[0];if(!p)return[];let o=p.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 f=l.filter(h=>h.includes(`{{${c}[]`)).map(h=>{let g=h.match(/\[\](\.[^}]+)?}}/),y=g&&g[1]||"";return{placeholder:h,field:y?y.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return d.map(h=>{let g=s;for(let{regex:v,field:x}of f){let C=x?ke(h,x):h;if(C==null)return null;g=g.replace(v,C)}if(g.includes("{{")||g.includes("}}"))return null;let y=g?`${a}?${g}`:a;return{identifier:y,url:Rt(t,y,r)}}).filter(h=>h!==null)},pt=(r,t,e,n,i)=>{let a=E(e,n)?.next||e.next||null,s=Nt(a,"success");if(!s)return null;let l=s.flatMap(p=>Yt(r,t,e,p,i));return l.length>0?l:null},ct=(r,t,e,n,i,a)=>{let s=a==="error"?"error":"success",l=E(e,n)?.next||e.next||null,p=Nt(l,s);if(!p)return null;let o=p.flatMap(c=>Yt(r,t,e,c,i));return o.length>0?o:null},Rt=(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((l,p)=>s.searchParams.set(p,l)),s.toString().replace(/\/\?/,"?")},ke=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var j=class j{static debug(...t){j.isTestEnv||console.debug(...t)}static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var w=j;function je(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 te(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]=te(e[n],t[n]):e[n]=t[n]}),e}function Me(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 B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function z(r,t){let e={};return r.forEach(n=>{if(n.input.position==="local")return;let i=n.input.as||n.input.name,a=Me(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(u.Position.Payload)){let s=je(n.input.position,i,a);e=te(e,s)}else e[i]=a}),e}function ut(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=l=>{if(!l?.value)return;let p=l.input.as||l.input.name,[,o]=t.stringToNative(l.value);if(i[p]=o,l.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[`${p}.token`]=d,i[`${p}.identifier`]=d,i[`${p}.amount`]=String(c.amount)}};for(let l=0;l<a;l++)s(r[l]);return s(n),i}var ee=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,l]of Object.entries(r.output)){if(l.startsWith(u.Transform.Prefix))continue;let p=Ge(l);if(p!==null&&p!==t){a[s]=null;continue}let[o,...c]=l.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]=l}return{stringValues:n,nativeValues:i,output:a}},Z=async(r,t,e,n,i,a)=>{let s=(f,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,f),l=f=>f.length===0?t:s(t,f),{stringValues:p,nativeValues:o,output:c}=ee(r,e,l),d=z(n,i);for(let f of n)if(f.input.position==="local"){let h=f.input.as||f.input.name;if(h&&f.value){let[,g]=i.stringToNative(f.value);d[h]=g}}return{values:{string:p,native:o,mapped:d},output:await re(r,c,t,e,n,i,a)}},re=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let l={...t};return l=qe(l,r,n,i,a),l=await ze(r,l,e,i,a,s.transform?.runner||null),l},qe=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[l,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("in.")){let o=p.split(".")[1],c=s.findIndex(f=>f.as===o||f.name===o),d=c!==-1?n[c]?.value:null;a[l]=d?i.stringToNative(d)[1]:null}return a},ze=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},l=Object.entries(r.output).filter(([,o])=>o.startsWith(u.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(u.Transform.Prefix.length)}));if(l.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 p={...s,out:_e(e),inputs:ut(n,i)};for(let{key:o,code:c}of l)try{s[o]=await a.run(c,p),p[o]=s[o]}catch(d){w.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,p[o]=null}return s},_e=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},ne=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:l,nativeValues:p,output:o}=ee(r,e,s),c=await re(r,o,t,e,n,i,a);return"PROMPT"in c||(c.PROMPT=t),{values:{string:l,native:p,mapped:z(n,i)},output:c}},Ge=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 Je=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Mt.some(t=>t in r),ie=(r,t)=>{if(!Je(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 Gn=(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 Qe(r,t,e,n=5){let i=await Gt(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 $t(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Qe(r,i,e,5)}function Bt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Xn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await $t(r,e,n),l=await t(i);return Bt(r,l,a,s)}function Zn(r){let t=new Date(r).getTime();return Date.now()<t}function Yn(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 Ke=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Xe=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),ae=(r,t=24)=>{let e=Xe(r);return e?e.slice(0,t):"action"},se=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)},Ze=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()}},ei=(r,t,e)=>{let n=ae((e||t||"").trim()||"action"),i=`${r.type}|${Ze(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=se(i);return`private_src_${n}_${a}`},Ye=r=>{let t=Ke(r),e=ae(t),n=se(t.trim().toLowerCase());return`private_gen_${e}_${n}`},ri=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ye(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},ni=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function ai(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 oi(r,t,e){return null}var tr=(r,t)=>{let e=null;try{e=N(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=W(e,n),a=tr(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),l=new Map(s.map(p=>[p.identifier,p.amount??0n]));return a.every(p=>(l.get(p)??0n)>0n)}catch{return!0}};import{Mppx as er,tempo as rr}from"mppx/client";async function oe(r){for(let t of r){if(!t.wallet.getMppAccount)continue;let e=await t.wallet.getMppAccount().catch(()=>null);if(!e)continue;return w.debug("WarpExecutor: Using mppx fetch for MPP auto-payment"),er.create({methods:[rr({account:e})],polyfill:!1}).fetch}return fetch}var le={boolean:m.Bool,integer:m.Uint32,int:m.Uint32,number:m.Uint64},I=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t=le[t]??t,t===m.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===m.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(l=>l!=="_name");if(a.length===0)return`${t}(${i})${u.ArgParamsSeparator}`;let s=a.map(l=>{let[p,o]=this.getTypeAndValue(n[l]);return`(${l}${u.ArgParamsSeparator}${p})${o}`});return`${t}(${i})${u.ArgParamsSeparator}${s.join(u.ArgListSeparator)}`}if(t===m.Vector&&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[0],i=n.indexOf(u.ArgParamsSeparator),a=n.substring(0,i),s=e.map(p=>{let o=p.indexOf(u.ArgParamsSeparator),c=p.substring(o+1);return a.startsWith(m.Tuple)?c.replace(u.ArgListSeparator,u.ArgCompositeSeparator):c}),l=a.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return t+u.ArgParamsSeparator+a+u.ArgParamsSeparator+s.join(l)}return t+u.ArgParamsSeparator+e.join(u.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+u.ArgParamsSeparator+e.identifier+u.ArgCompositeSeparator+String(e.amount)+u.ArgCompositeSeparator+String(e.decimals):m.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+u.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(u.ArgParamsSeparator),n=le[e[0]]??e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(u.ArgParamsSeparator);return[m.Option+u.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(u.ArgParamsSeparator),s=i.substring(0,a),l=i.substring(a+1),p=s.startsWith(m.Struct)?u.ArgStructSeparator:u.ArgListSeparator,c=(l?l.split(p):[]).map(d=>this.stringToNative(s+u.ArgParamsSeparator+d)[1]);return[m.Vector+u.ArgParamsSeparator+s,c]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),l=i.split(u.ArgCompositeSeparator).map((p,o)=>this.stringToNative(`${a[o]}${u.IdentifierParamSeparator}${p}`)[1]);return[n,l]}else if(n.startsWith(m.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let l={_name:a[1]};return i&&i.split(u.ArgListSeparator).forEach(p=>{let o=p.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,c,d,f]=o;l[c]=this.stringToNative(`${d}${u.IdentifierParamSeparator}${f}`)[1]}}),[n,l]}else{if(n===m.String)return[n,i];if(n===m.Uint8||n===m.Uint16||n===m.Uint32)return[n,Number(i)];if(n===m.Uint64||n===m.Uint128||n===m.Uint256||n===m.Biguint)return[n,BigInt(i||0)];if(n===m.Bool)return[n,i==="true"];if(n===m.Address)return[n,i];if(n===m.Hex)return[n,i];if(n===m.Datetime)return[n,i];if(n===m.Asset){let[a,s]=i.split(u.ArgCompositeSeparator),l={identifier:a,amount:BigInt(s)};return[n,l]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let l=a.stringToNative(i);return[n,l]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[l,p]=this.stringToNative(`${s}:${i}`);return[n,p]}}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"?[m.Uint32,t]:typeof t=="bigint"?[m.Uint64,t]:typeof t=="boolean"?[m.Bool,t]:[typeof t,t]}};var vi=r=>new I().nativeToString(m.String,r),xi=r=>new I().nativeToString(m.Uint8,r),Ai=r=>new I().nativeToString(m.Uint16,r),Ci=r=>new I().nativeToString(m.Uint32,r),wi=r=>new I().nativeToString(m.Uint64,r),Ii=r=>new I().nativeToString(m.Biguint,r),Si=r=>new I().nativeToString(m.Bool,r),bi=r=>new I().nativeToString(m.Address,r),pe=r=>new I().nativeToString(m.Asset,r),Pi=r=>new I().nativeToString(m.Hex,r),Ei=(r,t)=>{if(t===null)return m.Option+u.ArgParamsSeparator;let e=r(t),n=e.indexOf(u.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+u.ArgParamsSeparator+i+u.ArgParamsSeparator+a},Ti=(...r)=>new I().nativeToString(m.Tuple,r),Ri=r=>new I().nativeToString(m.Struct,r),Ni=r=>new I().nativeToString(m.Vector,r);import nr from"ajv";var ce=class{constructor(t){this.pendingBrand={protocol:st("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||L.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new nr,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import ir from"ajv";var ar=new Set(["POST","PUT","PATCH","DELETE"]),sr=/^[A-Z][A-Z0-9_]*$/,dt=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}=N(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 l=a.destination;if(!l||typeof l=="string"||!l.url)continue;let p=this.extractUrlPlaceholders(l.url);if(p.length!==0)for(let o of p)n.has(o)||sr.test(o)||i.has(o)||e.push(`URL "${l.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||!ar.has(a))continue;let s=n.inputs??[];for(let l of s)if(l.position?.startsWith("arg:")){let p=l.as??l.name??"(unnamed)";e.push(`Input "${p}" has position "${l.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||L.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new ir({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var gt=class{constructor(t){this.config=t;this.pendingWarp={protocol:st("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 Jt(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 dt(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};import{existsSync as Lt,mkdirSync as or,readdirSync as ue,readFileSync as lr,unlinkSync as Ht,writeFileSync as pr}from"fs";import{join as de,resolve as ge}from"path";var Ot="$bigint:",ft=(r,t)=>typeof t=="bigint"?Ot+t.toString():t,_=(r,t)=>typeof t=="string"&&t.startsWith(Ot)?BigInt(t.slice(Ot.length)):t;var ht=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ge(n):ge(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Lt(this.cacheDir)||or(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return de(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!Lt(e))return null;let n=lr(e,"utf-8"),i=JSON.parse(n,_);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);pr(a,JSON.stringify(i,ft),"utf-8")}async delete(t){try{let e=this.getFilePath(t);Lt(e)&&Ht(e)}catch{}}async keys(t){try{let e=ue(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{ue(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Ht(de(this.cacheDir,e))})}catch{}}};var Y=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,_);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,ft))}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 H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var tt=H;import{readFileSync as cr}from"fs";import{resolve as fe}from"path";var mt=class{constructor(t,e){let n=e?.path?fe(e.path):fe(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=cr(t,"utf-8");return new Map(Object.entries(JSON.parse(e,_)))}catch(e){return w.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 he={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wt={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}`},yt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new Y(t,e):e?.type==="memory"?new tt(t,e):e?.type==="static"?new mt(t,e):e?.type==="filesystem"?new ht(t,e):typeof window<"u"&&window.localStorage?new Y(t,e):new tt(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 et={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Vt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Ft=(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)},Ut=r=>{try{return JSON.parse(r)}catch{return null}},ur=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:p,nonce:o,expiresAt:c}=await $t(n,`${e.chain.name}-adapter`),d=await a({message:p,chain:e.chain});d&&Object.entries(Bt(n,d,o,c)).forEach(([f,h])=>s.set(f,h))}let l=Ft(e.resolvedInputs,et.Headers,i);if(l){let p=Ut(l);p&&typeof p=="object"&&Object.entries(p).forEach(([o,c])=>typeof c=="string"&&s.set(o,c))}else t.headers&&Object.entries(t.headers).forEach(([p,o])=>{s.set(p,r.applyInputs(o,e.resolvedInputs,i))});return s},dr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Vt.Get){let s=Ft(e.resolvedInputs,et.Queries,i);if(s){let l=Ut(s);if(l&&typeof l=="object"){let p=new URL(a);Object.entries(l).forEach(([o,c])=>c!=null&&p.searchParams.set(o,String(c))),a=p.toString()}}}return a},gr=(r,t,e,n,i)=>{if(r===Vt.Get)return;let a=Ft(t.resolvedInputs,et.Payload,n);if(a&&Ut(a)!==null)return a;let{[et.Payload]:s,[et.Queries]:l,...p}=e;return JSON.stringify({...p,...i})},me=async(r,t,e,n,i,a,s,l)=>{let p=t.method||Vt.Get,o=await ur(r,t,e,n,a,l),c=dr(r,t,e,p,a),d=gr(p,e,i,a,s);return{url:c,method:p,headers:o,body:d}};var T=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=JSON.stringify(String(a)).slice(1,-1);n=n.replace(new RegExp(`\\{\\{${fr(i)}\\}\\}`,"g"),s)}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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,l)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(t.vars).forEach(([s,l])=>{if(typeof l!="string")a(s,l);else if(l.startsWith(u.Vars.Query+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Query.length+1),[o,c]=p.split(u.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,h=e.queries?.[o]??null??d;h!=null&&a(s,h)}else if(l.startsWith(u.Vars.Env+u.ArgParamsSeparator)){let p=l.slice(u.Vars.Env.length+1),[o,c]=p.split(u.ArgCompositeSeparator),f={...this.config.vars,...e.envs}?.[o];f!=null&&a(s,f)}else l===u.Source.UserWallet&&n?a(s,n):a(s,l)}),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 k(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 l=s.Accessor(i);l!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),l.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,l)=>{let p=l.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(p,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}},fr=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var hr=["collect","compute","mcp","state","mount","unmount"],mr=new Set(Object.values(m)),yr=r=>{let t=r.indexOf(u.ArgParamsSeparator);return t===-1?!1:mr.has(r.slice(0,t))},G=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 I,this.cache=new yt(t.env,t.cache)}getSerializer(){return this.serializer}getCache(){return this.cache}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[];return B(i)}async getRawResolvedInputsFromCache(t,e,n){return await this.cache.get(Wt.WarpExecutable(t,e||"",n))||[]}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),l=W(s.name,this.adapters),p=new T(this.config,l,this.adapters),o=await p.apply(t,i),c=E(o,e),{action:d,index:f}=N(o),h=[],g=[];if(f===e-1){let S=this.getStringTypedInputs(d,n);h=await this.getResolvedInputs(s.name,d,S,p,i.queries),g=await this.getModifiedInputs(h)}else c.inputs&&c.inputs.length>0&&(h=await this.resolveActionInputs(s.name,c,n,p,i.queries),g=await this.getModifiedInputs(h));let y=g.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,v=this.getDestinationFromAction(c),x=y?this.serializer.stringToNative(y)[1]:v;if(x&&(x=p.applyInputs(x,g,this.serializer)),!x&&!hr.includes(a.type))throw new Error("WarpActionExecutor: Destination/Receiver not provided");let C=this.getPreparedArgs(c,g);C=C.map(S=>p.applyInputs(S,g,this.serializer));let O=g.find(S=>S.input.position==="value")?.value||null,A="value"in c?c.value:null,$=O?.split(u.ArgParamsSeparator)[1]||A||"0",V=p.applyInputs($,g,this.serializer),R=BigInt(V),F=g.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),xe=[...("transfers"in c?c.transfers:[])||[],...F||[]].map(S=>{let Ct=p.applyInputs(S,g,this.serializer),Ie=Ct.startsWith(`asset${u.ArgParamsSeparator}`)?Ct:`asset${u.ArgParamsSeparator}${Ct}`;return this.serializer.stringToNative(Ie)[1]}),Ae=g.find(S=>S.input.position==="data")?.value,Ce="data"in c?c.data||"":null,Dt=Ae||Ce||null,we=Dt?p.applyInputs(Dt,g,this.serializer):null,kt={adapter:l,warp:o,chain:s,action:e,destination:x,args:C,value:R,transfers:xe,data:we,resolvedInputs:g};return await this.cache.set(Wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),kt.resolvedInputs,he.OneWeek),kt}async getChainInfoForWarp(t,e){if(t.chain)return W(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||yr(i)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],l=n.map(c=>i.applyInputs(c,[],this.serializer)),p=await Promise.all(l.map(c=>this.preprocessInput(t,c))),o=(c,d)=>{if(c.source===u.Source.UserWallet){let v=P(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(c.source==="hidden"){if(c.default===void 0)return null;let v=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,v)}if(p[d])return p[d];let f=c.as||c.name,h=a?.[f],g=this.url.searchParams.get(f),y=h||g;return y?this.serializer.nativeToString(c.type,String(y)):null};return s.map((c,d)=>{let f=o(c,d),h=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:f||(h!==void 0?this.serializer.nativeToString(c.type,h):null)}})}async resolveInputsFromQuery(t,e,n){let i=E(t,e);if(!i||!i.inputs?.length)return[];let a=await this.getChainInfoForWarp(t),s=W(a.name,this.adapters),l=new T(this.config,s,this.adapters);return this.getResolvedInputs(a.name,i,[],l,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 l=i.value?.split(":")[1];if(!l)throw new Error("WarpActionExecutor: Scalable value not found");let p=ot(l,+s);e.push({...i,value:`${i.input.type}:${p}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let l=ot(s,+a);e.push({...i,value:`${i.input.type}:${l}`})}}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 l=ut(t,this.serializer,n,i),p=await s.run(a,l);if(p==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,p);e.push({...i,value:o})}}else if(i.input.modifier?.startsWith("crypto:")){let[,a,s]=i.input.modifier.split(":"),l=a==="sha256"&&s?t.find(o=>(o.input.as||o.input.name)===s):null,p=l?.value?this.serializer.stringToNative(l.value)[1]??null:null;if(p){let c=await(await fetch(p)).arrayBuffer(),d=await globalThis.crypto.subtle.digest("SHA-256",c),f=Array.from(new Uint8Array(d)).map(h=>h.toString(16).padStart(2,"0")).join("");e.push({...i,value:this.serializer.nativeToString("string",f)})}else e.push(i)}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=Et(e),a=W(t,this.adapters);if(n==="asset"){let[s,l,p]=i.split(u.ArgCompositeSeparator);if(p)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=ot(l,o.decimals);return pe({...o,amount:c})}else return e}catch(n){throw w.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[l,p]=this.serializer.stringToNative(s),o=p;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 l=Number(a.position.split(":")[1])-1;i.push({index:l,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(p=>p.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(p=>p.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 W(s,this.adapters).chainInfo}};var vt=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.handlers=n,this.factory=new G(t,e)}setWarpResolver(t){this.warpResolver=t}stop(){this.active=!1,this.loopIterations.clear()}async execute(t,e,n={}){let i=[],a=null,s=[],l=[],o={...t.meta?.query??{},...n.queries},c={...n,queries:o},d={};if(t.vars)try{let h=this.adapters?.find(g=>g.chainInfo.name===(t.chain||this.adapters[0]?.chainInfo?.name));if(h){let g=await new T(this.config,h,this.adapters).apply(t,c);g?.actions&&(t.actions=g.actions),g?.meta&&(t.meta=g.meta)}}catch{}let{index:f}=N(t);for(let h=1;h<=t.actions.length;h++){let g=E(t,h);if(!bt(g))continue;let y=Object.keys(d).length>0?{...c,envs:{...c.envs,...d}}:c,{tx:v,chain:x,immediateExecution:C,executable:O}=await this.executeAction(t,h,e,y);if(v&&i.push(v),x&&(a=x),C&&s.push(C),C?.output){let{_DATA:A,...$}=C.output;Object.assign(d,$)}C?.values?.mapped&&Object.assign(d,C.values.mapped),O&&h===f+1&&O.resolvedInputs&&(l=B(O.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 h=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(h))}return this.scheduleLoops(t,e,c,d),{txs:i,chain:a,immediateExecutions:s,resolvedInputs:l}}async executeAction(t,e,n,i={}){let a=E(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):qt.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=J(a.when,o);if(!Q(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 y=this.adapters[0]?.chainInfo.name||"";if(!await this.evaluateWhenCondition(t,a,n,i,[],y))return{tx:null,chain:null,immediateExecution:null,executable:null}}let o=a,c=await this.warpResolver(o.warp);if(!c)return{tx:null,chain:null,immediateExecution:null,executable:null};await this.callHandler(()=>this.handlers?.onActionProcessing?.(a));let d={...this.config.vars,...i.envs||{},...i.queries||{}},f={};for(let[y,v]of Object.entries(c.meta?.query||{}))f[y]=v.replace(/\{\{(.+?)\}\}/g,(x,C)=>String(d[C.trim()]??""));c.meta={...c.meta,query:f};let{immediateExecutions:h}=await this.execute(c,[],i),g=h[0];return g?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:g,tx:null})),{tx:null,chain:null,immediateExecution:g,executable:null}):{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);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 l=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await l.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 l.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=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,l)=>{if(!bt(s)||s.type!=="transfer"&&s.type!=="contract")return null;let p=e[l],o=l+1;if(!p){let h=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),g={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:h};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 h=t.meta?.query;h&&Object.keys(h).length>0&&(c=await this.factory.resolveInputsFromQuery(t,o,h))}let d=await i.output.getActionExecution(t,o,p.tx,c),f=Wr(c,d.output);return d.next=ct(this.config,this.adapters,t,o,f,d.status),d.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:d,tx:p})):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(l=>l.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=z(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:l,output:p}=await Z(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",l,p)}async executeCompute(t){let e=P(this.config,t.chain.name),n=this.factory.getSerializer(),i=z(t.resolvedInputs,n),{values:a,output:s}=await Z(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){let s=new T(this.config,W(t.chain.name,this.adapters),this.adapters),l=this.factory.getSerializer(),{url:p,method:o,headers:c,body:d}=await me(s,e,t,n,i,l,a,async f=>await this.callHandler(()=>this.handlers?.onSignRequest?.(f)));w.debug("WarpExecutor: Executing HTTP collect",{url:p,method:o,headers:c,body:d});try{let f={method:o,headers:c,body:d},g=await(await oe(this.adapters))(p,f);w.debug("Collect response status",{status:g.status});let y=await g.json();w.debug("Collect response content",{content:y});let{values:v,output:x}=await Z(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",v,x,y)}catch(f){w.error("WarpActionExecutor: Error executing collect",f);let h=B(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:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let h=B(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:h}}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=B(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 l=this.factory.getSerializer(),p=new T(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,c=p.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=p.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),f={};o.headers&&Object.entries(o.headers).forEach(([h,g])=>{let y=p.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());f[h]=y}),w.debug("WarpExecutor: Executing MCP",{url:c,tool:d,headers:f});try{let h=new s(new URL(c),{requestInit:{headers:f}}),g=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await g.connect(h);let y={};t.resolvedInputs.forEach(({input:A,value:$})=>{if($&&A.position&&typeof A.position=="string"&&A.position.startsWith("payload:")){let V=A.position.replace("payload:",""),[R,F]=l.stringToNative($);if(R==="string")y[V]=String(F);else if(R==="bool")y[V]=!!F;else if(R==="uint8"||R==="uint16"||R==="uint32"||R==="uint64"||R==="uint128"||R==="uint256"||R==="biguint"){let rt=Number(F);y[V]=(Number.isInteger(rt),rt)}else y[V]=F}}),e&&Object.assign(y,e);let v=await g.callTool({name:d,arguments:y});await g.close();let x;if(v.content&&v.content.length>0){let A=v.content[0];if(A.type==="text")try{x=JSON.parse(A.text)}catch{x=A.text}else A.type,x=A}else x=v;let{values:C,output:O}=await Z(t.warp,x,t.action,t.resolvedInputs,l,this.config);return this.buildCollectResult(t,n,"success",C,O,v)}catch(h){w.error("WarpExecutor: Error executing MCP",h);let g=B(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:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}buildCollectResult(t,e,n,i,a,s){let l=ct(this.config,this.adapters,t.warp,t.action,a,n),p=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:l,values:i,output:s?{...a,_DATA:s}:a,messages:Tt(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}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,p=`loop:${n.scope||"default"}:${t.meta?.identifier||t.name}`;if(s.when){let f={...n.envs,...i},h=J(s.when,f);try{if(!Q(h)){this.loopIterations.delete(p);continue}}catch{this.loopIterations.delete(p);continue}}let o=s.maxIterations??1e4,c=(this.loopIterations.get(p)??0)+1;if(c>o){this.loopIterations.delete(p),w.debug(`Loop maxIterations (${o}) reached for warp ${t.meta?.identifier}`);continue}if(this.loopIterations.set(p,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 p=i.envs||{},o=J(e.when,p);if(!Q(o))return{tx:null,chain:null,immediateExecution:null,executable:null}}let a=this.factory.getCache(),l=`state:${i.scope||"default"}:${e.store}`;if(e.op==="read"){let p=await a.get(l)??{},o=e.keys??Object.keys(p),c={};for(let f of o)p[f]!==void 0&&p[f]!==null&&(c[`state.${f}`]=p[f]);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 p=await a.get(l)??{},o=i.envs||{},c={};for(let[d,f]of Object.entries(e.data))if(typeof f=="string"){let h=f.replace(/\{\{([^}]+)\}\}/g,(g,y)=>{let v=o[y.trim()];return v!=null?String(v):f});c[d]=vr(h)}else c[d]=f;await a.set(l,{...p,...c})}return e.op==="clear"&&await a.delete(l),{tx:null,chain:null,immediateExecution:null,executable:null}}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),l=W(s.name,this.adapters),p=new T(this.config,l,this.adapters),o=await p.apply(t,a),c=E(o,n),d=[];if(e.inputs&&e.inputs.length>0){let A=this.factory.getStringTypedInputs(e,i),$=await this.factory.getResolvedInputs(s.name,e,A,p,a.queries);d=await this.factory.getModifiedInputs($)}else{let{action:A}=N(o),$=this.factory.getStringTypedInputs(A,i),V=await this.factory.getResolvedInputs(s.name,A,$,p,a.queries);d=await this.factory.getModifiedInputs(V)}let f=ie(c.prompt,this.config.platform),h=p.applyInputs(f,d,this.factory.getSerializer()),g=B(d),y=P(this.config,s.name),v=this.factory.getSerializer(),{values:x,output:C}=await ne(o,h,n,d,v,this.config);if(this.handlers?.onPromptGenerate){let A=await this.handlers.onPromptGenerate(h,c.expect);A&&(C.MESSAGE=A)}let O=d.find(A=>A.input.position==="destination")?.value||null;return{status:"success",warp:o,action:n,user:y,txHash:null,tx:null,next:pt(this.config,this.adapters,o,n,C),values:x,output:C,messages:Tt(o,{...x.mapped,...C},this.config),destination:O,resolvedInputs:g}}catch(s){return w.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:ct(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 l=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),p=W(l.name,this.adapters),o=new T(this.config,p,this.adapters),c;if(a)c=a;else{let g=await this.factory.getResolvedInputs(l.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);c=await this.factory.getModifiedInputs(g)}let d=o.buildInputBag(c,this.factory.getSerializer()),f={...i.envs??{},...d},h=J(e.when,f);return Q(h)}},Wr=(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}},vr=r=>{if(r==="true")return!0;if(r==="false")return!1;let t=Number(r);return!isNaN(t)&&r.trim()!==""?t:r};var xt=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 w.error("WarpIndex: Error searching for warps: ",i),i}}};var At=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!X(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),l=s.length>0,p=s.map(o=>({url:o.url,warp:o.warp}));return{match:l,output:p}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(u.HttpProtocolPrefix)?X(t):U(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,l=null,p=null,o=null,c=t.startsWith(u.HttpProtocolPrefix)?Kt(t):Xt(i.identifier);if(this.resolver){let g=null;if(a==="hash")g=await this.resolver.getByHash(s,e);else if(a==="alias"){let y=`${i.chain}:${s}`;g=await this.resolver.getByAlias(y,e)||await this.resolver.getByAlias(s,e)}g&&(l=g.warp,p=g.registryInfo,o=g.brand)}else{if(!i.chain)throw new Error(`WarpLinkDetecter: chain is required for identifier ${i.identifier}`);let g=W(i.chain,this.adapters);if(a==="hash"){l=await g.builder().createFromTransactionHash(s,e);let y=await g.registry.getInfoByHash(s,e);p=y.registryInfo,o=y.brand}else if(a==="alias"){let y=await g.registry.getInfoByAlias(s,e);p=y.registryInfo,o=y.brand,y.registryInfo&&(l=await g.builder().createFromTransactionHash(y.registryInfo.hash,e))}}if(l&&l.meta&&(xr(l,i.chain,p,i.identifier),l.meta.query=c?Zt(c):null),!l)return n;let d=l.chain||i.chain||null,f=d?this.adapters.find(g=>g.chainInfo.name.toLowerCase()===d.toLowerCase()):null,h=f?await new T(this.config,f,this.adapters).apply(l):l;return{match:!0,url:t,warp:h,chain:d,registryInfo:p,brand:o}}catch(a){return w.error("Error detecting warp link",a),n}}},xr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?Pt(null,"alias",e.alias):Pt(t,"hash",e?.hash??n))};var ye=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 nt(e));return new it(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 vt(this.config,this.chains,t);return e.setWarpResolver(async n=>(await this.detectWarp(n)).warp??null),e}async detectWarp(t,e){return new At(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"),l=a?t:null;if(!l&&s){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");l=await g.json()}if(l||(l=(await this.detectWarp(t,i.cache)).warp),!l)throw new Error("Warp not found");let p=this.createExecutor(n),{txs:o,chain:c,immediateExecutions:d,resolvedInputs:f}=await p.execute(l,e,{queries:i.queries});return{txs:o,chain:c,immediateExecutions:d,evaluateOutput:async g=>{await p.evaluateOutput(l,g)},resolvedInputs:f}}async createInscriptionTransaction(t,e){return await W(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return W(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=U(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");if(!n.chain)throw new Error("WarpClient: createFromTransactionHash - chain is required");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(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 W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??N(e).index+1,l=await W(t,this.chains).output.getActionExecution(e,a,n);return l.next=pt(this.config,this.chains,e,a,l.output),l}async getRegistry(t){let e=W(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return W(t,this.chains).dataLoader}getWallet(t){return W(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new xt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return t?W(t,this.chains).builder():new gt(this.config)}createAbiBuilder(t){return W(t,this.chains).abiBuilder()}createBrandBuilder(t){return W(t,this.chains).brandBuilder()}createSerializer(t){return W(t,this.chains).serializer}resolveText(t){return lt(t,this.config)}};var We=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 os(r,t){let e=r.match??{};for(let[n,i]of Object.entries(e))if(ve(t,n)!==i)return!1;return!0}function ls(r,t){let e={};for(let[n,i]of Object.entries(r.inputs??{}))e[n]=i.includes(".")?ve(t,i):i;return e}function ve(r,t){return t.split(".").reduce((e,n)=>e?.[n],r)}export{It as BrowserCryptoProvider,Hr as CLOUD_WALLET_PROVIDERS,he as CacheTtl,Or as EvmWalletChainNames,Lr as MultiversxWalletChainNames,St as NodeCryptoProvider,pn as WARP_LANGUAGES,b as WarpAssets,ce as WarpBrandBuilder,gt as WarpBuilder,yt as WarpCache,Wt as WarpCacheKey,Be as WarpChainDisplayNames,Oe as WarpChainLogos,$e as WarpChainName,nt as WarpChainResolver,ye as WarpClient,it as WarpCompositeResolver,L as WarpConfig,u as WarpConstants,vt as WarpExecutor,G as WarpFactory,xt as WarpIndex,m as WarpInputTypes,T as WarpInterpolator,q as WarpLinkBuilder,At as WarpLinkDetecter,w as WarpLogger,jt as WarpPlatformName,Mt as WarpPlatforms,M as WarpProtocolVersions,I as WarpSerializer,We as WarpTypeRegistry,dt as WarpValidator,bi as address,Tt as applyOutputToMessages,pe as asset,Ii as biguint,Si as bool,Ye as buildGeneratedFallbackWarpIdentifier,ei as buildGeneratedSourceWarpIdentifier,ut as buildInputsContext,z as buildMappedOutput,je as buildNestedPayload,Kr as bytesToBase64,Le as bytesToHex,ci as checkWarpAssetBalance,K as cleanWarpIdentifier,Bt as createAuthHeaders,$t as createAuthMessage,Zr as createCryptoProvider,oi as createDefaultWalletProvider,Xn as createHttpAuthHeaders,Qe as createSignableMessage,un as createWarpI18nText,Pt as createWarpIdentifier,on as doesWarpRequireWallet,re as evaluateOutputCommon,Q as evaluateWhenCondition,Z as extractCollectOutput,X as extractIdentifierInfoFromUrl,ne as extractPromptOutput,Xt as extractQueryStringFromIdentifier,Kt as extractQueryStringFromUrl,B as extractResolvedInputValues,en as extractWarpSecrets,W as findWarpAdapterForChain,jr as getChainDisplayName,Mr as getChainLogo,zt as getCryptoProvider,Ke as getGeneratedSourceWarpName,st as getLatestProtocolIdentifier,oe as getMppFetch,pt as getNextInfo,ct as getNextInfoForStatus,Gn as getProviderConfig,_t as getRandomBytes,Gt as getRandomHex,tr as getRequiredAssetIds,Ir as getWalletFromConfigOrFail,E as getWarpActionByIndex,zr as getWarpBrandLogoUrl,_r as getWarpChainAssetLogoUrl,Gr as getWarpChainInfoLogoUrl,yn as getWarpIdentifierWithQuery,U as getWarpInfoFromIdentifier,N as getWarpInputAction,Se as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ee as getWarpWalletExternalId,Te as getWarpWalletExternalIdFromConfig,Pr as getWarpWalletExternalIdFromConfigOrFail,Pe as getWarpWalletMnemonic,br as getWarpWalletMnemonicFromConfig,be as getWarpWalletPrivateKey,Sr as getWarpWalletPrivateKeyFromConfig,xn as hasInputPrefix,Pi as hex,ai as initializeWalletCache,hn as isEqualWarpIdentifier,ni as isGeneratedSourcePrivateIdentifier,Je as isPlatformValue,bt as isWarpActionAutoExecute,cn as isWarpI18nText,Er as isWarpWalletReadOnly,os as matchesTrigger,te as mergeNestedPayload,Nr as normalizeAndValidateMnemonic,Re as normalizeMnemonic,Ei as option,Ge as parseOutputOutIndex,Yn as parseSignedMessage,Zt as parseWarpQueryStringToObject,mn as removeWarpChainPrefix,Rr as removeWarpWalletFromConfig,k as replacePlaceholders,J as replacePlaceholdersInWhenExpression,ls as resolveInputs,On as resolveNextString,Nt as resolveNextStrings,ve as resolvePath,ie as resolvePlatformValue,lt as resolveWarpText,qt as safeWindow,Qr as setCryptoProvider,Tr as setWarpWalletInConfig,ot as shiftBigintBy,Et as splitInput,ri as stampGeneratedWarpMeta,vi as string,Ri as struct,Xr as testCryptoAvailability,Me as toInputPayloadValue,Jt as toPreviewText,Ti as tuple,Ai as uint16,Ci as uint32,wi as uint64,xi as uint8,Ne as validateMnemonicLength,Zn as validateSignedMessage,Ni as vector,Dr as withAdapterFallback};
|