@joai/warps 3.2.6 → 3.3.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 +17 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -915,6 +915,22 @@ declare function validateSignedMessage(expiresAt: string): boolean;
|
|
|
915
915
|
*/
|
|
916
916
|
declare function parseSignedMessage(message: string): SignableMessage;
|
|
917
917
|
|
|
918
|
+
type GeneratedSourceType = 'abi' | 'openapi';
|
|
919
|
+
type GeneratedSourceInfo = {
|
|
920
|
+
type: GeneratedSourceType;
|
|
921
|
+
url?: string | null;
|
|
922
|
+
contract?: string | null;
|
|
923
|
+
};
|
|
924
|
+
type GeneratedWarpNameLike = {
|
|
925
|
+
name?: unknown;
|
|
926
|
+
title?: unknown;
|
|
927
|
+
};
|
|
928
|
+
declare const getGeneratedSourceWarpName: (warp: GeneratedWarpNameLike) => string;
|
|
929
|
+
declare const buildGeneratedSourceWarpIdentifier: (source: GeneratedSourceInfo, operationKey: string, displayName?: string) => string;
|
|
930
|
+
declare const buildGeneratedFallbackWarpIdentifier: (warp: GeneratedWarpNameLike) => string;
|
|
931
|
+
declare const stampGeneratedWarpMeta: (warp: Warp, defaultChain: WarpChainName, identifier?: string, fallbackName?: string) => void;
|
|
932
|
+
declare const isGeneratedSourcePrivateIdentifier: (identifier?: string | null) => boolean;
|
|
933
|
+
|
|
918
934
|
declare const getWalletFromConfigOrFail: (config: WarpClientConfig, chain: WarpChainName) => string | WarpWalletDetails;
|
|
919
935
|
declare const getWarpWalletAddress: (wallet: WarpWalletDetails | string | null | undefined) => string | null;
|
|
920
936
|
declare const getWarpWalletAddressFromConfig: (config: WarpClientConfig, chain: WarpChainName) => string | null;
|
|
@@ -1279,4 +1295,4 @@ declare class WarpValidator {
|
|
|
1279
1295
|
private validateSchema;
|
|
1280
1296
|
}
|
|
1281
1297
|
|
|
1282
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1298
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.d.ts
CHANGED
|
@@ -915,6 +915,22 @@ declare function validateSignedMessage(expiresAt: string): boolean;
|
|
|
915
915
|
*/
|
|
916
916
|
declare function parseSignedMessage(message: string): SignableMessage;
|
|
917
917
|
|
|
918
|
+
type GeneratedSourceType = 'abi' | 'openapi';
|
|
919
|
+
type GeneratedSourceInfo = {
|
|
920
|
+
type: GeneratedSourceType;
|
|
921
|
+
url?: string | null;
|
|
922
|
+
contract?: string | null;
|
|
923
|
+
};
|
|
924
|
+
type GeneratedWarpNameLike = {
|
|
925
|
+
name?: unknown;
|
|
926
|
+
title?: unknown;
|
|
927
|
+
};
|
|
928
|
+
declare const getGeneratedSourceWarpName: (warp: GeneratedWarpNameLike) => string;
|
|
929
|
+
declare const buildGeneratedSourceWarpIdentifier: (source: GeneratedSourceInfo, operationKey: string, displayName?: string) => string;
|
|
930
|
+
declare const buildGeneratedFallbackWarpIdentifier: (warp: GeneratedWarpNameLike) => string;
|
|
931
|
+
declare const stampGeneratedWarpMeta: (warp: Warp, defaultChain: WarpChainName, identifier?: string, fallbackName?: string) => void;
|
|
932
|
+
declare const isGeneratedSourcePrivateIdentifier: (identifier?: string | null) => boolean;
|
|
933
|
+
|
|
918
934
|
declare const getWalletFromConfigOrFail: (config: WarpClientConfig, chain: WarpChainName) => string | WarpWalletDetails;
|
|
919
935
|
declare const getWarpWalletAddress: (wallet: WarpWalletDetails | string | null | undefined) => string | null;
|
|
920
936
|
declare const getWarpWalletAddressFromConfig: (config: WarpClientConfig, chain: WarpChainName) => string | null;
|
|
@@ -1279,4 +1295,4 @@ declare class WarpValidator {
|
|
|
1279
1295
|
private validateSchema;
|
|
1280
1296
|
}
|
|
1281
1297
|
|
|
1282
|
-
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
|
1298
|
+
export { type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, EvmWalletChainNames, type ExecutionHandlers, type GeneratedSourceInfo, type GeneratedSourceType, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type WalletCache, type WalletProvider, type WalletProviderFactory, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetLogo, type WarpChainAssetLogoThemed, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, type WarpChainInfoLogo, type WarpChainInfoLogoThemed, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMcpAction, type WarpMcpDestination, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, replacePlaceholders, replacePlaceholdersInWhenExpression, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Re=Object.create;var dt=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Ve=(r,t)=>{for(var e in t)dt(r,e,{get:t[e],enumerable:!0})},re=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Be(t))!Oe.call(r,i)&&i!==e&&dt(r,i,{get:()=>t[i],enumerable:!(n=Ne(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?Re($e(r)):{},re(t||!r||!r.__esModule?dt(e,"default",{value:r,enumerable:!0}):e,r)),He=r=>re(dt({},"__esModule",{value:!0}),r);var Ur={};Ve(Ur,{BrowserCryptoProvider:()=>ft,CacheTtl:()=>Jt,EvmWalletChainNames:()=>ze,NodeCryptoProvider:()=>gt,WARP_LANGUAGES:()=>er,WarpBrandBuilder:()=>zt,WarpBuilder:()=>kt,WarpCache:()=>ot,WarpCacheKey:()=>It,WarpChainName:()=>le,WarpClient:()=>Zt,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>ct,WarpFactory:()=>G,WarpIndex:()=>lt,WarpInputTypes:()=>h,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>ut,WarpLogger:()=>C,WarpProtocolVersions:()=>L,WarpSerializer:()=>w,WarpTypeRegistry:()=>Yt,WarpValidator:()=>it,address:()=>br,applyOutputToMessages:()=>Wt,asset:()=>qt,biguint:()=>Pr,bool:()=>Tr,buildMappedOutput:()=>K,buildNestedPayload:()=>ge,bytesToBase64:()=>Xe,bytesToHex:()=>ue,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>At,createAuthMessage:()=>vt,createCryptoProvider:()=>Ye,createDefaultWalletProvider:()=>Wr,createHttpAuthHeaders:()=>gr,createSignableMessage:()=>We,createWarpI18nText:()=>nr,createWarpIdentifier:()=>mt,evaluateOutputCommon:()=>Ut,evaluateWhenCondition:()=>Bt,extractCollectOutput:()=>nt,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>Dt,extractQueryStringFromIdentifier:()=>Ot,extractQueryStringFromUrl:()=>$t,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>tr,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Tt,getEventNameFromWarp:()=>Ge,getLatestProtocolIdentifier:()=>tt,getNextInfo:()=>z,getProviderConfig:()=>fr,getRandomBytes:()=>bt,getRandomHex:()=>Et,getWalletFromConfigOrFail:()=>Fe,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>_e,getWarpChainAssetLogoUrl:()=>Je,getWarpChainInfoLogoUrl:()=>Qe,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>ne,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>se,getWarpWalletExternalIdFromConfig:()=>oe,getWarpWalletExternalIdFromConfigOrFail:()=>je,getWarpWalletMnemonic:()=>ae,getWarpWalletMnemonicFromConfig:()=>De,getWarpWalletPrivateKey:()=>ie,getWarpWalletPrivateKeyFromConfig:()=>Ue,handleX402Payment:()=>Mt,hasInputPrefix:()=>pr,hex:()=>Er,initializeWalletCache:()=>yr,isEqualWarpIdentifier:()=>ir,isWarpActionAutoExecute:()=>ht,isWarpI18nText:()=>rr,isWarpWalletReadOnly:()=>Le,mergeNestedPayload:()=>Ft,normalizeAndValidateMnemonic:()=>qe,normalizeMnemonic:()=>pe,option:()=>Rr,parseOutputOutIndex:()=>ye,parseSignedMessage:()=>mr,parseWarpQueryStringToObject:()=>Vt,removeWarpChainPrefix:()=>or,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Nt,resolveWarpText:()=>rt,safeWindow:()=>Pt,setCryptoProvider:()=>Ke,setWarpWalletInConfig:()=>Me,shiftBigintBy:()=>et,splitInput:()=>yt,string:()=>Cr,struct:()=>Br,testCryptoAvailability:()=>Ze,toInputPayloadValue:()=>he,toPreviewText:()=>Rt,tuple:()=>Nr,uint16:()=>wr,uint32:()=>Ir,uint64:()=>Sr,uint8:()=>xr,validateMnemonicLength:()=>ce,validateSignedMessage:()=>hr,vector:()=>$r,withAdapterFallback:()=>ke});module.exports=He(Ur);var Fe=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ne=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>ne(r.user?.wallets?.[t]||null),ie=r=>r?typeof r=="string"?r:r.privateKey||null:null,ae=r=>r?typeof r=="string"?r:r.mnemonic||null:null,se=r=>r?typeof r=="string"?r:r.externalId||null:null,Ue=(r,t)=>ie(r.user?.wallets?.[t]||null)?.trim()||null,De=(r,t)=>ae(r.user?.wallets?.[t]||null)?.trim()||null,oe=(r,t)=>se(r.user?.wallets?.[t]||null)?.trim()||null,je=(r,t)=>{let e=oe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Le=r=>typeof r=="string",Me=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},pe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ce=(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`)},qe=(r,t=24)=>{let e=pe(r);return ce(e,t),e};var le=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(le||{}),ze=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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:"},Alerts:{TriggerEventPrefix:"event"}},h={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"},Pt=typeof window<"u"?window:{open:()=>{}};var L={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/v${L.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/JoAiHQ/warps-specs/refs/heads/main/schemas/brand/v${L.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.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 ke=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ge=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var _e=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Je=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Qe=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ft=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}},gt=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 Tt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new ft,M;if(typeof process<"u"&&process.versions?.node)return M=new gt,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ke(r){M=r}async function bt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Tt()).getRandomBytes(r)}function ue(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 Xe(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 Et(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await bt(r/2,t);return ue(e)}async function Ze(){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 bt(16),r.randomBytes=!0}catch{}return r}function Ye(){return Tt()}var tr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=r=>{if(r==="warp")return`warp:${L.Warp}`;if(r==="brand")return`brand:${L.Brand}`;if(r==="abi")return`abi:${L.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ht=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},et=(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 o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Rt=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Nt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Bt=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 er={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"},rt=(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""},rr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,nr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,ir=(r,t)=>!r||!t?!1:J(r)===J(t),mt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=de(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[o,c,p]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?p+i.substring(i.indexOf("?")):p;return{chain:o,type:c,identifier:u,identifierBase:p}}}if(s.length===2){let[o,c]=s;if(o===l.IdentifierType.Alias||o===l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:o,identifier:p,identifierBase:c}}}if(s.length===2){let[o,c]=s;if(o!==l.IdentifierType.Alias&&o!==l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=ar(c,o)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:o,type:u,identifier:p,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},ar=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,sr=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},de=r=>{let t=sr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=de(a);return[i,...s]},$t=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ot=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},Vt=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},or=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()};var yt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},pr=r=>{let t=new Set(Object.values(h));if(!r.includes(l.ArgParamsSeparator))return!1;let e=yt(r)[0];return t.has(e)};var Wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var fe=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,o=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(o);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(t,this.config.defaultChain);if(!e)return null;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",o="#23F7DD"){let c=W(t,this.adapters),p=this.build(c.chainInfo.name,e,n);return new fe.default({type:"svg",width:i,height:i,data:String(p),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(o)}" 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 cr="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(cr))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o){let f=D(s,{...e.vars,...i});return[{identifier:f,url:Ht(t,f,r)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=D(o,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:Ht(t,v,r)}]}let p=c[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let m=Array.isArray(i[d])?i[d]:[i[d]];if(m.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(f=>{let v=o;for(let{regex:b,field:V}of g){let x=V?lr(f,V):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:Ht(t,A,r)}}).filter(f=>f!==null)},Ht=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let o=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((p,u)=>c.searchParams.set(u,p)),c.toString().replace(/\/\?/,"?")},lr=(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 C=k;function ge(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ft(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]=Ft(e[n],t[n]):e[n]=t[n]}),e}function he(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=he(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ge(n.input.position,i,a);e=Ft(e,s)}else e[i]=a}),e}var me=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,o]of Object.entries(r.output)){if(o.startsWith(l.Transform.Prefix))continue;let c=ye(o);if(c!==null&&c!==t){a[s]=null;continue}let[p,...u]=o.split(".");if(p==="out"||p.startsWith("out[")||p==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=o}return{stringValues:n,nativeValues:i,output:a}},nt=async(r,t,e,n,i,a)=>{let s=(d,m)=>m.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),o=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:p,output:u}=me(r,e,o);return{values:{string:c,native:p,mapped:K(n,i)},output:await Ut(r,u,t,e,n,i,a)}},Ut=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let o={...t};return o=ur(o,r,n,i,a),o=await dr(r,o,e,s.transform?.runner||null),o},ur=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let p=c.split(".")[1],u=s.findIndex(m=>m.as===p||m.name===p),d=u!==-1?n[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},dr=async(r,t,e,n)=>{if(!r.output)return t;let i={...t},a=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(l.Transform.Prefix.length)}));if(a.length>0&&(!n||typeof n.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let s={...i,out:e};for(let{key:o,code:c}of a)try{i[o]=await n.run(c,s),s[o]=i[o]}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,p),i[o]=null,s[o]=null}return i},Dt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:o,nativeValues:c,output:p}=me(r,e,s),u=await Ut(r,p,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:o,native:c,mapped:K(n,i)},output:u}},ye=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 fr=(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 We(r,t,e,n=5){let i=await Et(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return We(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function gr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),o=await t(i);return At(r,o,a,s)}function hr(r){let t=new Date(r).getTime();return Date.now()<t}function mr(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"}`)}}async function yr(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 Wr(r,t,e){return null}var jt=require("@x402/core/client"),Lt=require("@x402/core/http");async function Mt(r,t,e,n,i){let a=await vr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,p])=>{s.set(c,p)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var vr=async(r,t)=>{let e=await Ar(r),i=new Lt.x402HTTPClient(new jt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new jt.x402Client,o=await a.wallet.registerX402Handlers(s),c=i.accepts.find(m=>m?.network&&o[m.network]);if(!c?.network)continue;o[c.network]();let p=new Lt.x402HTTPClient(s),u=await p.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=p.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Ar=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===h.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.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(o=>o!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(o=>{let[c,p]=this.getTypeAndValue(n[o]);return`(${o}${l.ArgParamsSeparator}${c})${p}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let p=c.indexOf(l.ArgParamsSeparator),u=c.substring(p+1);return a.startsWith(h.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=a.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(o)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):h.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[h.Option+l.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),o=i.substring(a+1),c=s.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[h.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,o]}else if(n.startsWith(h.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let p=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,m]=p;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${m}`)[1]}}),[n,o]}else{if(n===h.String)return[n,i];if(n===h.Uint8||n===h.Uint16||n===h.Uint32)return[n,Number(i)];if(n===h.Uint64||n===h.Uint128||n===h.Uint256||n===h.Biguint)return[n,BigInt(i||0)];if(n===h.Bool)return[n,i==="true"];if(n===h.Address)return[n,i];if(n===h.Hex)return[n,i];if(n===h.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),o={identifier:a,amount:BigInt(s)};return[n,o]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let o=a.stringToNative(i);return[n,o]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[o,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[h.Uint32,t]:typeof t=="bigint"?[h.Uint64,t]:typeof t=="boolean"?[h.Bool,t]:[typeof t,t]}};var Cr=r=>new w().nativeToString(h.String,r),xr=r=>new w().nativeToString(h.Uint8,r),wr=r=>new w().nativeToString(h.Uint16,r),Ir=r=>new w().nativeToString(h.Uint32,r),Sr=r=>new w().nativeToString(h.Uint64,r),Pr=r=>new w().nativeToString(h.Biguint,r),Tr=r=>new w().nativeToString(h.Bool,r),br=r=>new w().nativeToString(h.Address,r),qt=r=>new w().nativeToString(h.Asset,r),Er=r=>new w().nativeToString(h.Hex,r),Rr=(r,t)=>{if(t===null)return h.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Nr=(...r)=>new w().nativeToString(h.Tuple,r),Br=r=>new w().nativeToString(h.Struct,r),$r=r=>new w().nativeToString(h.Vector,r);var ve=_(require("ajv"),1);var zt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new ve.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Ae=_(require("ajv"),1);var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=R(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ae.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 kt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Rt(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 it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};var S=require("fs"),Z=require("path");var Gt="$bigint:",Ct=(r,t)=>typeof t=="bigint"?Gt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Gt)?BigInt(t.slice(Gt.length)):t;var xt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,Z.resolve)(n):(0,Z.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,Ct),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var at=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ct))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var j=class j{constructor(t,e){}get(t){let e=j.cache.get(t);return e?Date.now()>e.expiresAt?(j.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;j.cache.set(t,{value:e,expiresAt:i})}forget(t){j.cache.delete(t)}clear(){j.cache.clear()}};j.cache=new Map;var st=j;var Ce=require("fs"),_t=require("path");var wt=class{constructor(t,e){let n=e?.path?(0,_t.resolve)(e.path):(0,_t.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Ce.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Jt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={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}`},ot=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new at(t,e):e?.type==="memory"?new st(t,e):e?.type==="static"?new wt(t,e):e?.type==="filesystem"?new xt(t,e):typeof window<"u"&&window.localStorage?new at(t,e):new st(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var pt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Qt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Kt=(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)},Xt=r=>{try{return JSON.parse(r)}catch{return null}},Or=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:c,nonce:p,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,p,u)).forEach(([m,g])=>s.set(m,g))}let o=Kt(e.resolvedInputs,pt.Headers,i);if(o){let c=Xt(o);c&&typeof c=="object"&&Object.entries(c).forEach(([p,u])=>typeof u=="string"&&s.set(p,u))}else t.headers&&Object.entries(t.headers).forEach(([c,p])=>{s.set(c,r.applyInputs(p,e.resolvedInputs,i))});return s},Vr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Qt.Get){let s=Kt(e.resolvedInputs,pt.Queries,i);if(s){let o=Xt(s);if(o&&typeof o=="object"){let c=new URL(a);Object.entries(o).forEach(([p,u])=>u!=null&&c.searchParams.set(p,String(u))),a=c.toString()}}}return a},Hr=(r,t,e,n,i)=>{if(r===Qt.Get)return;let a=Kt(t.resolvedInputs,pt.Payload,n);if(a&&Xt(a)!==null)return a;let{[pt.Payload]:s,[pt.Queries]:o,...c}=e;return JSON.stringify({...c,...i})},xe=async(r,t,e,n,i,a,s,o)=>{let c=t.method||Qt.Get,p=await Or(r,t,e,n,a,o),u=Vr(r,t,e,c,a),d=Hr(c,e,i,a,s);return{url:u,method:c,headers:p,body:d}};var N=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(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=I(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,o)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o!="string")a(s,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Query.length+1),[p,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,g=e.queries?.[p]||null||d;g&&a(s,g)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Env.length+1),[p,u]=c.split(l.ArgCompositeSeparator),m={...this.config.vars,...e.envs}?.[p];m&&a(s,m)}else o===l.Source.UserWallet&&n?a(s,n):a(s,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.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,o)=>{let c=o.trim().toLowerCase();if(!this.adapters)return s;try{let p=W(c,this.adapters),u={config:this.config,adapter:p},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);i[s]=String(o)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(o),a.input.type==="asset"&&typeof a.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var 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 w,this.cache=new ot(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(It.WarpExecutable(t,e||"",n))||[];return $(i)}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),o=W(s.name,this.adapters),c=new N(this.config,o,this.adapters),p=await c.apply(t,i),u=E(p,e),{action:d,index:m}=R(p),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];m===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let b=A.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,V=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:V;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let O=this.getPreparedArgs(u,A);O=O.map(P=>c.applyInputs(P,A,this.serializer,f));let H=A.find(P=>P.input.position==="value")?.value||null,T="value"in u?u.value:null,F=H?.split(l.ArgParamsSeparator)[1]||T||"0",Y=c.applyInputs(F,A,this.serializer,f),we=BigInt(Y),Ie=A.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Se=[...("transfers"in u?u.transfers:[])||[],...Ie||[]].map(P=>{let St=c.applyInputs(P,A,this.serializer,f),Ee=St.startsWith(`asset${l.ArgParamsSeparator}`)?St:`asset${l.ArgParamsSeparator}${St}`;return this.serializer.stringToNative(Ee)[1]}),Pe=A.find(P=>P.input.position==="data")?.value,Te="data"in u?u.data||"":null,te=Pe||Te||null,be=te?c.applyInputs(te,A,this.serializer,f):null,ee={adapter:o,warp:p,chain:s,action:e,destination:x,args:O,value:we,transfers:Se,data:be,resolvedInputs:A};return this.cache.set(It.WarpExecutable(this.config.env,p.meta?.hash||"",e),ee.resolvedInputs,Jt.OneWeek),ee}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||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],o=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(o.map(u=>this.preprocessInput(t,u))),p=(u,d)=>{if(u.source===l.Source.UserWallet){let v=I(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let m=u.as||u.name,g=a?.[m],y=this.url.searchParams.get(m),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let m=p(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:m||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=et(o,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=et(s,+a);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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 o=this.buildInputContext(t,n,i),c=await s.run(a,o);if(c==null)e.push(i);else{let p=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:p})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let o=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[o]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let p=c;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let o=s;"identifier"in o&&"amount"in o&&(i[`${a}.token`]=String(o.identifier),i[`${a}.amount`]=String(o.amount),i[`${a}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=yt(e),a=W(t,this.adapters);if(n==="asset"){let[s,o,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let p=await a.dataLoader.getAsset(s);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=et(o,p.decimals);return qt({...p,amount:u})}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[o,c]=this.serializer.stringToNative(s),p=c;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.amount)})}else if(a.position.startsWith("arg:")){let o=Number(a.position.split(":")[1])-1;i.push({index:o,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(c=>c.inputs?.some(p=>p.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 ct=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],o=[],p={...t.meta?.query??{},...n.queries},u={...n,queries:p},{action:d,index:m}=R(t);for(let g=1;g<=t.actions.length;g++){let y=E(t,g);if(!ht(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:b}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),b&&g===m+1&&b.resolvedInputs&&(o=$(b.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{txs:i,chain:a,immediateExecutions:s,resolvedInputs:o}}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 p=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):Pt.open(p,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let p=await this.executePrompt(t,a,e,n,i);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:null};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,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 p=await this.executeCollect(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let p=await this.executeMcp(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,executable:s}}}let o=W(s.chain.name,this.adapters);if(a.type==="query"){let p=await o.executor.executeQuery(s);if(p.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:p,tx:null}));else{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:s.chain,immediateExecution:p,executable:s}}return{tx:await o.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,o)=>{if(!ht(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[o],p=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),m={status:"error",warp:t,action:p,user:I(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${p} failed: Transaction not found`,result:m})),m}let u=await i.output.getActionExecution(t,p,c.tx);return u.next=z(this.config,this.adapters,t,p,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=I(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:o,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",o,c)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=this.factory.getSerializer(),{url:c,method:p,headers:u,body:d}=await xe(s,e,t,n,i,o,a,async m=>await this.callHandler(()=>this.handlers?.onSignRequest?.(m)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:p,headers:u,body:d});try{let g=await fetch(c,{method:p,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Mt(g,c,p,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await nt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(m){C.error("WarpActionExecutor: Error executing collect",m);let g=$(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:m},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=I(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=$(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 y=$(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:y}}let o=this.factory.getSerializer(),c=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=i.destination,u=c.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),m={};p.headers&&Object.entries(p.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());m[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:m});try{let g=new s(new URL(u),{requestInit:{headers:m}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:O})=>{if(O&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[T,F]=o.stringToNative(O);if(T==="string")f[H]=String(F);else if(T==="bool")f[H]=!!F;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let Y=Number(F);f[H]=(Number.isInteger(Y),Y)}else f[H]=F}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:V}=await nt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",b,V,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let o=z(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:s?{...a,_DATA:s}:a,messages:Wt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),o=W(s.name,this.adapters),c=new N(this.config,o,this.adapters),p=await c.apply(t,a),u=E(p,n),{action:d}=R(p),m=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,m,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let H=this.factory.getStringTypedInputs(e,i),T=await this.factory.getResolvedInputs(s.name,e,H,c,a.queries);f=await this.factory.getModifiedInputs(T)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),b=I(this.config,s.name),V=this.factory.getSerializer(),{values:x,output:O}=await Dt(p,v,n,f,V,this.config);return{status:"success",warp:p,action:n,user:b,txHash:null,tx:null,next:z(this.config,this.adapters,p,n,O),values:x,output:O,messages:Wt(p,O,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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 o=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=W(o.name,this.adapters),p=new N(this.config,c,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),m=await this.factory.getResolvedInputs(o.name,u,d,p,i.queries),g=await this.factory.getModifiedInputs(m),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),p,i.queries);y=await this.factory.getModifiedInputs(A)}let f=p.buildInputBag(y,this.factory.getSerializer(),g),v=Nt(e.when,f);return Bt(v)}};var lt=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 ut=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,o=null,c=null,p=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?$t(t):Ot(i.identifier);if(a==="hash"){o=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,p=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,p=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(Fr(o,u.chainInfo.name,c,i.identifier),o.meta.query=d?Vt(d):null),!o)return n;let m=o.chain||u.chainInfo.name,g=W(m,this.adapters),y=await new N(this.config,g,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:m,registryInfo:c,brand:p}}catch(a){return C.error("Error detecting warp link",a),n}}},Fr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?mt(t,"alias",e.alias):mt(t,"hash",e?.hash??n))};var Zt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new ct(this.config,this.chains,t)}async detectWarp(t,e){return new ut(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),o=a?t:null;if(!o&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:m}=await c.execute(o,e,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(o,y)},resolvedInputs:m}}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=B(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!I(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??R(e).index+1,o=await W(t,this.chains).output.getActionExecution(e,a,n);return o.next=z(this.config,this.chains,e,a,o.output),o}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 lt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}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 rt(t,this.config)}};var Yt=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()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
|
|
1
|
+
"use strict";var Oe=Object.create;var dt=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Fe=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var De=(r,t)=>{for(var e in t)dt(r,e,{get:t[e],enumerable:!0})},re=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of He(t))!Ue.call(r,i)&&i!==e&&dt(r,i,{get:()=>t[i],enumerable:!(n=Ve(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?Oe(Fe(r)):{},re(t||!r||!r.__esModule?dt(e,"default",{value:r,enumerable:!0}):e,r)),Le=r=>re(dt({},"__esModule",{value:!0}),r);var _r={};De(_r,{BrowserCryptoProvider:()=>ft,CacheTtl:()=>Jt,EvmWalletChainNames:()=>Je,NodeCryptoProvider:()=>gt,WARP_LANGUAGES:()=>ar,WarpBrandBuilder:()=>kt,WarpBuilder:()=>zt,WarpCache:()=>ot,WarpCacheKey:()=>It,WarpChainName:()=>le,WarpClient:()=>Zt,WarpConfig:()=>U,WarpConstants:()=>l,WarpExecutor:()=>ct,WarpFactory:()=>G,WarpIndex:()=>lt,WarpInputTypes:()=>h,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>ut,WarpLogger:()=>C,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>Yt,WarpValidator:()=>it,address:()=>Fr,applyOutputToMessages:()=>Wt,asset:()=>qt,biguint:()=>Vr,bool:()=>Hr,buildGeneratedFallbackWarpIdentifier:()=>xe,buildGeneratedSourceWarpIdentifier:()=>wr,buildMappedOutput:()=>K,buildNestedPayload:()=>ge,bytesToBase64:()=>er,bytesToHex:()=>ue,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>At,createAuthMessage:()=>vt,createCryptoProvider:()=>nr,createDefaultWalletProvider:()=>br,createHttpAuthHeaders:()=>Wr,createSignableMessage:()=>We,createWarpI18nText:()=>or,createWarpIdentifier:()=>mt,evaluateOutputCommon:()=>Ut,evaluateWhenCondition:()=>Bt,extractCollectOutput:()=>nt,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>Dt,extractQueryStringFromIdentifier:()=>Ot,extractQueryStringFromUrl:()=>$t,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>ir,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>bt,getEventNameFromWarp:()=>Ke,getGeneratedSourceWarpName:()=>ve,getLatestProtocolIdentifier:()=>tt,getNextInfo:()=>k,getProviderConfig:()=>yr,getRandomBytes:()=>Tt,getRandomHex:()=>Et,getWalletFromConfigOrFail:()=>je,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>Xe,getWarpChainAssetLogoUrl:()=>Ze,getWarpChainInfoLogoUrl:()=>Ye,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>ne,getWarpWalletAddressFromConfig:()=>I,getWarpWalletExternalId:()=>se,getWarpWalletExternalIdFromConfig:()=>oe,getWarpWalletExternalIdFromConfigOrFail:()=>ke,getWarpWalletMnemonic:()=>ae,getWarpWalletMnemonicFromConfig:()=>qe,getWarpWalletPrivateKey:()=>ie,getWarpWalletPrivateKeyFromConfig:()=>Me,handleX402Payment:()=>Mt,hasInputPrefix:()=>dr,hex:()=>Ur,initializeWalletCache:()=>Pr,isEqualWarpIdentifier:()=>pr,isGeneratedSourcePrivateIdentifier:()=>Sr,isWarpActionAutoExecute:()=>ht,isWarpI18nText:()=>sr,isWarpWalletReadOnly:()=>ze,mergeNestedPayload:()=>Ft,normalizeAndValidateMnemonic:()=>_e,normalizeMnemonic:()=>pe,option:()=>Dr,parseOutputOutIndex:()=>ye,parseSignedMessage:()=>Ar,parseWarpQueryStringToObject:()=>Vt,removeWarpChainPrefix:()=>ur,replacePlaceholders:()=>D,replacePlaceholdersInWhenExpression:()=>Nt,resolveWarpText:()=>rt,safeWindow:()=>Pt,setCryptoProvider:()=>tr,setWarpWalletInConfig:()=>Ge,shiftBigintBy:()=>et,splitInput:()=>yt,stampGeneratedWarpMeta:()=>Ir,string:()=>Rr,struct:()=>jr,testCryptoAvailability:()=>rr,toInputPayloadValue:()=>he,toPreviewText:()=>Rt,tuple:()=>Lr,uint16:()=>Br,uint32:()=>$r,uint64:()=>Or,uint8:()=>Nr,validateMnemonicLength:()=>ce,validateSignedMessage:()=>vr,vector:()=>Mr,withAdapterFallback:()=>Qe});module.exports=Le(_r);var je=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ne=r=>r?typeof r=="string"?r:r.address:null,I=(r,t)=>ne(r.user?.wallets?.[t]||null),ie=r=>r?typeof r=="string"?r:r.privateKey||null:null,ae=r=>r?typeof r=="string"?r:r.mnemonic||null:null,se=r=>r?typeof r=="string"?r:r.externalId||null:null,Me=(r,t)=>ie(r.user?.wallets?.[t]||null)?.trim()||null,qe=(r,t)=>ae(r.user?.wallets?.[t]||null)?.trim()||null,oe=(r,t)=>se(r.user?.wallets?.[t]||null)?.trim()||null,ke=(r,t)=>{let e=oe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},ze=r=>typeof r=="string",Ge=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},pe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ce=(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`)},_e=(r,t=24)=>{let e=pe(r);return ce(e,t),e};var le=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(le||{}),Je=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>I(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:"},Alerts:{TriggerEventPrefix:"event"}},h={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"},Pt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.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 Qe=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ke=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Xe=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Ze=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Ye=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ft=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}},gt=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 bt(){if(M)return M;if(typeof window<"u"&&window.crypto)return M=new ft,M;if(typeof process<"u"&&process.versions?.node)return M=new gt,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function tr(r){M=r}async function Tt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||bt()).getRandomBytes(r)}function ue(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 er(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 Et(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Tt(r/2,t);return ue(e)}async function rr(){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 Tt(16),r.randomBytes=!0}catch{}return r}function nr(){return bt()}var ir=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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}`)},E=(r,t)=>r?.actions[t-1],R=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ht=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=R(t);return r===e}return!0},et=(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 o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Rt=(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},D=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Nt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Bt=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 ar={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"},rt=(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""},sr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,or=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,pr=(r,t)=>!r||!t?!1:J(r)===J(t),mt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=de(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[o,c,p]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?p+i.substring(i.indexOf("?")):p;return{chain:o,type:c,identifier:u,identifierBase:p}}}if(s.length===2){let[o,c]=s;if(o===l.IdentifierType.Alias||o===l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:o,identifier:p,identifierBase:c}}}if(s.length===2){let[o,c]=s;if(o!==l.IdentifierType.Alias&&o!==l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=cr(c,o)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:o,type:u,identifier:p,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},cr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,lr=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},de=r=>{let t=lr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=de(a);return[i,...s]},$t=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ot=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},Vt=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},ur=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()};var yt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},dr=r=>{let t=new Set(Object.values(h));if(!r.includes(l.ArgParamsSeparator))return!1;let e=yt(r)[0];return t.has(e)};var Wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,D(s,t)]});return Object.fromEntries(n)};var fe=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,o=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(o);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(t,this.config.defaultChain);if(!e)return null;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",o="#23F7DD"){let c=W(t,this.adapters),p=this.build(c.chainInfo.name,e,n);return new fe.default({type:"svg",width:i,height:i,data:String(p),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(o)}" 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 fr="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(fr))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o){let f=D(s,{...e.vars,...i});return[{identifier:f,url:Ht(t,f,r)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=D(o,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:Ht(t,v,r)}]}let p=c[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let m=Array.isArray(i[d])?i[d]:[i[d]];if(m.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(f=>{let v=o;for(let{regex:T,field:V}of g){let x=V?gr(f,V):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:Ht(t,A,r)}}).filter(f=>f!==null)},Ht=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let o=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((p,u)=>c.searchParams.set(u,p)),c.toString().replace(/\/\?/,"?")},gr=(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 ge(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ft(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]=Ft(e[n],t[n]):e[n]=t[n]}),e}function he(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=he(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ge(n.input.position,i,a);e=Ft(e,s)}else e[i]=a}),e}var me=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,o]of Object.entries(r.output)){if(o.startsWith(l.Transform.Prefix))continue;let c=ye(o);if(c!==null&&c!==t){a[s]=null;continue}let[p,...u]=o.split(".");if(p==="out"||p.startsWith("out[")||p==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=o}return{stringValues:n,nativeValues:i,output:a}},nt=async(r,t,e,n,i,a)=>{let s=(d,m)=>m.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),o=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:p,output:u}=me(r,e,o);return{values:{string:c,native:p,mapped:K(n,i)},output:await Ut(r,u,t,e,n,i,a)}},Ut=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let o={...t};return o=hr(o,r,n,i,a),o=await mr(r,o,e,s.transform?.runner||null),o},hr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let p=c.split(".")[1],u=s.findIndex(m=>m.as===p||m.name===p),d=u!==-1?n[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},mr=async(r,t,e,n)=>{if(!r.output)return t;let i={...t},a=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(l.Transform.Prefix.length)}));if(a.length>0&&(!n||typeof n.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let s={...i,out:e};for(let{key:o,code:c}of a)try{i[o]=await n.run(c,s),s[o]=i[o]}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,p),i[o]=null,s[o]=null}return i},Dt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:o,nativeValues:c,output:p}=me(r,e,s),u=await Ut(r,p,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:o,native:c,mapped:K(n,i)},output:u}},ye=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 yr=(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 We(r,t,e,n=5){let i=await Et(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 vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return We(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Wr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),o=await t(i);return At(r,o,a,s)}function vr(r){let t=new Date(r).getTime();return Date.now()<t}function Ar(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 ve=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Cr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Ae=(r,t=24)=>{let e=Cr(r);return e?e.slice(0,t):"action"},Ce=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)},xr=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()}},wr=(r,t,e)=>{let n=Ae((e||t||"").trim()||"action"),i=`${r.type}|${xr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Ce(i);return`private_src_${n}_${a}`},xe=r=>{let t=ve(r),e=Ae(t),n=Ce(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Ir=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||xe(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Sr=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Pr(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 br(r,t,e){return null}var Lt=require("@x402/core/client"),jt=require("@x402/core/http");async function Mt(r,t,e,n,i){let a=await Tr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,p])=>{s.set(c,p)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var Tr=async(r,t)=>{let e=await Er(r),i=new jt.x402HTTPClient(new Lt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Lt.x402Client,o=await a.wallet.registerX402Handlers(s),c=i.accepts.find(m=>m?.network&&o[m.network]);if(!c?.network)continue;o[c.network]();let p=new jt.x402HTTPClient(s),u=await p.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=p.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Er=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===h.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.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(o=>o!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(o=>{let[c,p]=this.getTypeAndValue(n[o]);return`(${o}${l.ArgParamsSeparator}${c})${p}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let p=c.indexOf(l.ArgParamsSeparator),u=c.substring(p+1);return a.startsWith(h.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=a.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(o)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):h.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[h.Option+l.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),o=i.substring(a+1),c=s.startsWith(h.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[h.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,o]}else if(n.startsWith(h.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let p=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,m]=p;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${m}`)[1]}}),[n,o]}else{if(n===h.String)return[n,i];if(n===h.Uint8||n===h.Uint16||n===h.Uint32)return[n,Number(i)];if(n===h.Uint64||n===h.Uint128||n===h.Uint256||n===h.Biguint)return[n,BigInt(i||0)];if(n===h.Bool)return[n,i==="true"];if(n===h.Address)return[n,i];if(n===h.Hex)return[n,i];if(n===h.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),o={identifier:a,amount:BigInt(s)};return[n,o]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let o=a.stringToNative(i);return[n,o]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[o,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[h.Uint32,t]:typeof t=="bigint"?[h.Uint64,t]:typeof t=="boolean"?[h.Bool,t]:[typeof t,t]}};var Rr=r=>new w().nativeToString(h.String,r),Nr=r=>new w().nativeToString(h.Uint8,r),Br=r=>new w().nativeToString(h.Uint16,r),$r=r=>new w().nativeToString(h.Uint32,r),Or=r=>new w().nativeToString(h.Uint64,r),Vr=r=>new w().nativeToString(h.Biguint,r),Hr=r=>new w().nativeToString(h.Bool,r),Fr=r=>new w().nativeToString(h.Address,r),qt=r=>new w().nativeToString(h.Asset,r),Ur=r=>new w().nativeToString(h.Hex,r),Dr=(r,t)=>{if(t===null)return h.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Lr=(...r)=>new w().nativeToString(h.Tuple,r),jr=r=>new w().nativeToString(h.Struct,r),Mr=r=>new w().nativeToString(h.Vector,r);var we=_(require("ajv"),1);var kt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new we.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Ie=_(require("ajv"),1);var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=R(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ie.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 zt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Rt(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 it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};var S=require("fs"),Z=require("path");var Gt="$bigint:",Ct=(r,t)=>typeof t=="bigint"?Gt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Gt)?BigInt(t.slice(Gt.length)):t;var xt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,Z.resolve)(n):(0,Z.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,S.existsSync)(this.cacheDir)||(0,S.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,S.existsSync)(e))return null;let n=(0,S.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return Date.now()>i.expiresAt?((0,S.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,S.writeFileSync)(a,JSON.stringify(i,Ct),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,S.existsSync)(e)&&(0,S.unlinkSync)(e)}catch{}}clear(){try{(0,S.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,S.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var at=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Ct))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{constructor(t,e){}get(t){let e=L.cache.get(t);return e?Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;L.cache.set(t,{value:e,expiresAt:i})}forget(t){L.cache.delete(t)}clear(){L.cache.clear()}};L.cache=new Map;var st=L;var Se=require("fs"),_t=require("path");var wt=class{constructor(t,e){let n=e?.path?(0,_t.resolve)(e.path):(0,_t.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Se.readFileSync)(t,"utf-8");return new Map(Object.entries(JSON.parse(e,X)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var Jt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={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}`},ot=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new at(t,e):e?.type==="memory"?new st(t,e):e?.type==="static"?new wt(t,e):e?.type==="filesystem"?new xt(t,e):typeof window<"u"&&window.localStorage?new at(t,e):new st(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var pt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Qt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Kt=(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)},Xt=r=>{try{return JSON.parse(r)}catch{return null}},qr=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:c,nonce:p,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,p,u)).forEach(([m,g])=>s.set(m,g))}let o=Kt(e.resolvedInputs,pt.Headers,i);if(o){let c=Xt(o);c&&typeof c=="object"&&Object.entries(c).forEach(([p,u])=>typeof u=="string"&&s.set(p,u))}else t.headers&&Object.entries(t.headers).forEach(([c,p])=>{s.set(c,r.applyInputs(p,e.resolvedInputs,i))});return s},kr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Qt.Get){let s=Kt(e.resolvedInputs,pt.Queries,i);if(s){let o=Xt(s);if(o&&typeof o=="object"){let c=new URL(a);Object.entries(o).forEach(([p,u])=>u!=null&&c.searchParams.set(p,String(u))),a=c.toString()}}}return a},zr=(r,t,e,n,i)=>{if(r===Qt.Get)return;let a=Kt(t.resolvedInputs,pt.Payload,n);if(a&&Xt(a)!==null)return a;let{[pt.Payload]:s,[pt.Queries]:o,...c}=e;return JSON.stringify({...c,...i})},Pe=async(r,t,e,n,i,a,s,o)=>{let c=t.method||Qt.Get,p=await qr(r,t,e,n,a,o),u=kr(r,t,e,c,a),d=zr(c,e,i,a,s);return{url:u,method:c,headers:p,body:d}};var N=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(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=I(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,o)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o!="string")a(s,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Query.length+1),[p,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,g=e.queries?.[p]||null||d;g&&a(s,g)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Env.length+1),[p,u]=c.split(l.ArgCompositeSeparator),m={...this.config.vars,...e.envs}?.[p];m&&a(s,m)}else o===l.Source.UserWallet&&n?a(s,n):a(s,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return D(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.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,o)=>{let c=o.trim().toLowerCase();if(!this.adapters)return s;try{let p=W(c,this.adapters),u={config:this.config,adapter:p},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);i[s]=String(o)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(o),a.input.type==="asset"&&typeof a.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var 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 w,this.cache=new ot(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(It.WarpExecutable(t,e||"",n))||[];return $(i)}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),o=W(s.name,this.adapters),c=new N(this.config,o,this.adapters),p=await c.apply(t,i),u=E(p,e),{action:d,index:m}=R(p),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];m===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let T=A.find(P=>P.input.position==="receiver"||P.input.position==="destination")?.value,V=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:V;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let O=this.getPreparedArgs(u,A);O=O.map(P=>c.applyInputs(P,A,this.serializer,f));let H=A.find(P=>P.input.position==="value")?.value||null,b="value"in u?u.value:null,F=H?.split(l.ArgParamsSeparator)[1]||b||"0",Y=c.applyInputs(F,A,this.serializer,f),be=BigInt(Y),Te=A.filter(P=>P.input.position==="transfer"&&P.value).map(P=>P.value),Ee=[...("transfers"in u?u.transfers:[])||[],...Te||[]].map(P=>{let St=c.applyInputs(P,A,this.serializer,f),$e=St.startsWith(`asset${l.ArgParamsSeparator}`)?St:`asset${l.ArgParamsSeparator}${St}`;return this.serializer.stringToNative($e)[1]}),Re=A.find(P=>P.input.position==="data")?.value,Ne="data"in u?u.data||"":null,te=Re||Ne||null,Be=te?c.applyInputs(te,A,this.serializer,f):null,ee={adapter:o,warp:p,chain:s,action:e,destination:x,args:O,value:be,transfers:Ee,data:Be,resolvedInputs:A};return this.cache.set(It.WarpExecutable(this.config.env,p.meta?.hash||"",e),ee.resolvedInputs,Jt.OneWeek),ee}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||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],o=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(o.map(u=>this.preprocessInput(t,u))),p=(u,d)=>{if(u.source===l.Source.UserWallet){let v=I(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let m=u.as||u.name,g=a?.[m],y=this.url.searchParams.get(m),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let m=p(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:m||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=et(o,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=et(s,+a);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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 o=this.buildInputContext(t,n,i),c=await s.run(a,o);if(c==null)e.push(i);else{let p=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:p})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let o=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[o]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let p=c;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let o=s;"identifier"in o&&"amount"in o&&(i[`${a}.token`]=String(o.identifier),i[`${a}.amount`]=String(o.amount),i[`${a}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=yt(e),a=W(t,this.adapters);if(n==="asset"){let[s,o,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let p=await a.dataLoader.getAsset(s);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=et(o,p.decimals);return qt({...p,amount:u})}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[o,c]=this.serializer.stringToNative(s),p=c;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.amount)})}else if(a.position.startsWith("arg:")){let o=Number(a.position.split(":")[1])-1;i.push({index:o,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(c=>c.inputs?.some(p=>p.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 ct=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],o=[],p={...t.meta?.query??{},...n.queries},u={...n,queries:p},{action:d,index:m}=R(t);for(let g=1;g<=t.actions.length;g++){let y=E(t,g);if(!ht(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:T}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),T&&g===m+1&&T.resolvedInputs&&(o=$(T.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{txs:i,chain:a,immediateExecutions:s,resolvedInputs:o}}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 p=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):Pt.open(p,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let p=await this.executePrompt(t,a,e,n,i);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:null};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,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 p=await this.executeCollect(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let p=await this.executeMcp(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,executable:s}}}let o=W(s.chain.name,this.adapters);if(a.type==="query"){let p=await o.executor.executeQuery(s);if(p.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:p,tx:null}));else{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:s.chain,immediateExecution:p,executable:s}}return{tx:await o.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,o)=>{if(!ht(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[o],p=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),m={status:"error",warp:t,action:p,user:I(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${p} failed: Transaction not found`,result:m})),m}let u=await i.output.getActionExecution(t,p,c.tx);return u.next=k(this.config,this.adapters,t,p,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=I(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:o,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",o,c)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=this.factory.getSerializer(),{url:c,method:p,headers:u,body:d}=await Pe(s,e,t,n,i,o,a,async m=>await this.callHandler(()=>this.handlers?.onSignRequest?.(m)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:p,headers:u,body:d});try{let g=await fetch(c,{method:p,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Mt(g,c,p,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await nt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,I(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(m){C.error("WarpActionExecutor: Error executing collect",m);let g=$(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:m},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=I(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=$(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 y=$(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:y}}let o=this.factory.getSerializer(),c=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=i.destination,u=c.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),m={};p.headers&&Object.entries(p.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());m[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:m});try{let g=new s(new URL(u),{requestInit:{headers:m}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:O})=>{if(O&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let H=x.position.replace("payload:",""),[b,F]=o.stringToNative(O);if(b==="string")f[H]=String(F);else if(b==="bool")f[H]=!!F;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let Y=Number(F);f[H]=(Number.isInteger(Y),Y)}else f[H]=F}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:V}=await nt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",T,V,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let o=k(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||I(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:s?{...a,_DATA:s}:a,messages:Wt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),o=W(s.name,this.adapters),c=new N(this.config,o,this.adapters),p=await c.apply(t,a),u=E(p,n),{action:d}=R(p),m=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,m,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let H=this.factory.getStringTypedInputs(e,i),b=await this.factory.getResolvedInputs(s.name,e,H,c,a.queries);f=await this.factory.getModifiedInputs(b)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),T=I(this.config,s.name),V=this.factory.getSerializer(),{values:x,output:O}=await Dt(p,v,n,f,V,this.config);return{status:"success",warp:p,action:n,user:T,txHash:null,tx:null,next:k(this.config,this.adapters,p,n,O),values:x,output:O,messages:Wt(p,O,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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 o=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=W(o.name,this.adapters),p=new N(this.config,c,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),m=await this.factory.getResolvedInputs(o.name,u,d,p,i.queries),g=await this.factory.getModifiedInputs(m),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),p,i.queries);y=await this.factory.getModifiedInputs(A)}let f=p.buildInputBag(y,this.factory.getSerializer(),g),v=Nt(e.when,f);return Bt(v)}};var lt=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 ut=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,o=null,c=null,p=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?$t(t):Ot(i.identifier);if(a==="hash"){o=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,p=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,p=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(Gr(o,u.chainInfo.name,c,i.identifier),o.meta.query=d?Vt(d):null),!o)return n;let m=o.chain||u.chainInfo.name,g=W(m,this.adapters),y=await new N(this.config,g,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:m,registryInfo:c,brand:p}}catch(a){return C.error("Error detecting warp link",a),n}}},Gr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?mt(t,"alias",e.alias):mt(t,"hash",e?.hash??n))};var Zt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new ct(this.config,this.chains,t)}async detectWarp(t,e){return new ut(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),o=a?t:null;if(!o&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:m}=await c.execute(o,e,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(o,y)},resolvedInputs:m}}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=B(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!I(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??R(e).index+1,o=await W(t,this.chains).output.getActionExecution(e,a,n);return o.next=k(this.config,this.chains,e,a,o.output),o}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 lt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}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 rt(t,this.config)}};var Yt=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()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,replacePlaceholders,replacePlaceholdersInWhenExpression,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 _e=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},de=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>de(r.user?.wallets?.[t]||null),fe=r=>r?typeof r=="string"?r:r.privateKey||null:null,ge=r=>r?typeof r=="string"?r:r.mnemonic||null:null,he=r=>r?typeof r=="string"?r:r.externalId||null:null,Je=(r,t)=>fe(r.user?.wallets?.[t]||null)?.trim()||null,Qe=(r,t)=>ge(r.user?.wallets?.[t]||null)?.trim()||null,me=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,Ke=(r,t)=>{let e=me(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Xe=r=>typeof r=="string",Ze=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ye=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},We=(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`)},Ye=(r,t=24)=>{let e=ye(r);return We(e,t),e};var ve=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(ve||{}),rr=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},Nt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.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 sr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var cr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var ur=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},dr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},fr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ft=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}},gt=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 Bt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new ft,D;if(typeof process<"u"&&process.versions?.node)return D=new gt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function hr(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||Bt()).getRandomBytes(r)}function Ae(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 mr(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 Ot(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 Ae(e)}async function yr(){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 Wr(){return Bt()}var Cr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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}`)},b=(r,t)=>r?.actions[t-1],E=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ht=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},et=(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 o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Vt=(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)=>t[n]||""),Ht=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ft=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 Sr={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"},rt=(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,Tr=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Nr=(r,t)=>!r||!t?!1:J(r)===J(t),mt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=Ut(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[o,c,p]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?p+i.substring(i.indexOf("?")):p;return{chain:o,type:c,identifier:u,identifierBase:p}}}if(s.length===2){let[o,c]=s;if(o===l.IdentifierType.Alias||o===l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:o,identifier:p,identifierBase:c}}}if(s.length===2){let[o,c]=s;if(o!==l.IdentifierType.Alias&&o!==l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=Ce(c,o)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:o,type:u,identifier:p,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},Ce=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,xe=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ut=r=>{let t=xe(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Ut(a);return[i,...s]},Dt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},jt=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},Lt=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},Br=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()};var yt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Vr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=yt(r)[0];return t.has(e)};var Wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,j(s,t)]});return Object.fromEntries(n)};import we from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,o=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(o);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(t,this.config.defaultChain);if(!e)return null;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",o="#23F7DD"){let c=W(t,this.adapters),p=this.build(c.chainInfo.name,e,n);return new we({type:"svg",width:i,height:i,data:String(p),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(o)}" 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 Ie="https://",z=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ie))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o){let f=j(s,{...e.vars,...i});return[{identifier:f,url:vt(t,f,r)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=j(o,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:vt(t,v,r)}]}let p=c[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:T,field:O}of g){let x=O?Se(f,O):f;if(x==null)return null;v=v.replace(T,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:vt(t,A,r)}}).filter(f=>f!==null)},vt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let o=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((p,u)=>c.searchParams.set(u,p)),c.toString().replace(/\/\?/,"?")},Se=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;function Pe(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Mt(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]=Mt(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{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(l.Position.Payload)){let s=Pe(n.input.position,i,a);e=Mt(e,s)}else e[i]=a}),e}var qt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,o]of Object.entries(r.output)){if(o.startsWith(l.Transform.Prefix))continue;let c=Re(o);if(c!==null&&c!==t){a[s]=null;continue}let[p,...u]=o.split(".");if(p==="out"||p.startsWith("out[")||p==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=o}return{stringValues:n,nativeValues:i,output:a}},nt=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),o=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:p,output:u}=qt(r,e,o);return{values:{string:c,native:p,mapped:K(n,i)},output:await zt(r,u,t,e,n,i,a)}},zt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let o={...t};return o=be(o,r,n,i,a),o=await Ee(r,o,e,s.transform?.runner||null),o},be=(r,t,e,n,i)=>{let a={...r},s=b(t,e)?.inputs||[];for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let p=c.split(".")[1],u=s.findIndex(h=>h.as===p||h.name===p),d=u!==-1?n[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},Ee=async(r,t,e,n)=>{if(!r.output)return t;let i={...t},a=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(l.Transform.Prefix.length)}));if(a.length>0&&(!n||typeof n.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let s={...i,out:e};for(let{key:o,code:c}of a)try{i[o]=await n.run(c,s),s[o]=i[o]}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,p),i[o]=null,s[o]=null}return i},kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:o,nativeValues:c,output:p}=qt(r,e,s),u=await zt(r,p,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:o,native:c,mapped:K(n,i)},output:u}},Re=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 pn=(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 Ne(r,t,e,n=5){let i=await Ot(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 At(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ne(r,i,e,5)}function Ct(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function dn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await At(r,e,n),o=await t(i);return Ct(r,o,a,s)}function fn(r){let t=new Date(r).getTime();return Date.now()<t}function gn(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"}`)}}async function mn(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 Wn(r,t,e){return null}import{x402Client as Gt}from"@x402/core/client";import{x402HTTPClient as _t}from"@x402/core/http";async function Jt(r,t,e,n,i){let a=await Be(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,p])=>{s.set(c,p)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var Be=async(r,t)=>{let e=await $e(r),i=new _t(new Gt).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Gt,o=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&o[h.network]);if(!c?.network)continue;o[c.network]();let p=new _t(s),u=await p.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=p.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},$e=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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(o=>o!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(o=>{let[c,p]=this.getTypeAndValue(n[o]);return`(${o}${l.ArgParamsSeparator}${c})${p}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let p=c.indexOf(l.ArgParamsSeparator),u=c.substring(p+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(o)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),o=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,o]}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 o={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let p=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,h]=p;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,o]}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.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),o={identifier:a,amount:BigInt(s)};return[n,o]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let o=a.stringToNative(i);return[n,o]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[o,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 bn=r=>new w().nativeToString(m.String,r),En=r=>new w().nativeToString(m.Uint8,r),Rn=r=>new w().nativeToString(m.Uint16,r),Nn=r=>new w().nativeToString(m.Uint32,r),Bn=r=>new w().nativeToString(m.Uint64,r),$n=r=>new w().nativeToString(m.Biguint,r),On=r=>new w().nativeToString(m.Bool,r),Vn=r=>new w().nativeToString(m.Address,r),Qt=r=>new w().nativeToString(m.Asset,r),Hn=r=>new w().nativeToString(m.Hex,r),Fn=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Un=(...r)=>new w().nativeToString(m.Tuple,r),Dn=r=>new w().nativeToString(m.Struct,r),jn=r=>new w().nativeToString(m.Vector,r);import Oe from"ajv";var Kt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Oe,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Ve from"ajv";var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ve({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 Xt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Vt(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 it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
-
`))}};import{existsSync as wt,mkdirSync as He,readdirSync as Fe,readFileSync as Ue,unlinkSync as It,writeFileSync as De}from"fs";import{join as Zt,resolve as Yt}from"path";var xt="$bigint:",at=(r,t)=>typeof t=="bigint"?xt+t.toString():t,k=(r,t)=>typeof t=="string"&&t.startsWith(xt)?BigInt(t.slice(xt.length)):t;var st=class{constructor(t,e){let n=e?.path;this.cacheDir=n?Yt(n):Yt(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){wt(this.cacheDir)||He(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Zt(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!wt(e))return null;let n=Ue(e,"utf-8"),i=JSON.parse(n,k);return Date.now()>i.expiresAt?(It(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);De(a,JSON.stringify(i,at),"utf-8")}forget(t){try{let e=this.getFilePath(t);wt(e)&&It(e)}catch{}}clear(){try{Fe(this.cacheDir).forEach(e=>{e.endsWith(".json")&&It(Zt(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,k);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,at))}forget(t){localStorage.removeItem(this.getKey(t))}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){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var Z=F;import{readFileSync as je}from"fs";import{resolve as te}from"path";var ot=class{constructor(t,e){let n=e?.path?te(e.path):te(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=je(t,"utf-8");return new Map(Object.entries(JSON.parse(e,k)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var ee={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},St={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}`},pt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new ot(t,e):e?.type==="filesystem"?new st(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Pt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Tt=(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)},bt=r=>{try{return JSON.parse(r)}catch{return null}},Le=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:c,nonce:p,expiresAt:u}=await At(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(Ct(n,d,p,u)).forEach(([h,g])=>s.set(h,g))}let o=Tt(e.resolvedInputs,Y.Headers,i);if(o){let c=bt(o);c&&typeof c=="object"&&Object.entries(c).forEach(([p,u])=>typeof u=="string"&&s.set(p,u))}else t.headers&&Object.entries(t.headers).forEach(([c,p])=>{s.set(c,r.applyInputs(p,e.resolvedInputs,i))});return s},Me=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Pt.Get){let s=Tt(e.resolvedInputs,Y.Queries,i);if(s){let o=bt(s);if(o&&typeof o=="object"){let c=new URL(a);Object.entries(o).forEach(([p,u])=>u!=null&&c.searchParams.set(p,String(u))),a=c.toString()}}}return a},qe=(r,t,e,n,i)=>{if(r===Pt.Get)return;let a=Tt(t.resolvedInputs,Y.Payload,n);if(a&&bt(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:o,...c}=e;return JSON.stringify({...c,...i})},re=async(r,t,e,n,i,a,s,o)=>{let c=t.method||Pt.Get,p=await Le(r,t,e,n,a,o),u=Me(r,t,e,c,a),d=qe(c,e,i,a,s);return{url:u,method:c,headers:p,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);return await this.applyGlobals(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=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,o)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o!="string")a(s,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Query.length+1),[p,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,g=e.queries?.[p]||null||d;g&&a(s,g)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Env.length+1),[p,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[p];h&&a(s,h)}else o===l.Source.UserWallet&&n?a(s,n):a(s,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return j(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.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,o)=>{let c=o.trim().toLowerCase();if(!this.adapters)return s;try{let p=W(c,this.adapters),u={config:this.config,adapter:p},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);i[s]=String(o)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(o),a.input.type==="asset"&&typeof a.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var 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 w,this.cache=new pt(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(St.WarpExecutable(t,e||"",n))||[];return $(i)}async createExecutable(t,e,n,i={}){let a=b(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),o=W(s.name,this.adapters),c=new R(this.config,o,this.adapters),p=await c.apply(t,i),u=b(p,e),{action:d,index:h}=E(p),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let T=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:O;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,A);N=N.map(I=>c.applyInputs(I,A,this.serializer,f));let V=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,H=V?.split(l.ArgParamsSeparator)[1]||P||"0",_=c.applyInputs(H,A,this.serializer,f),ae=BigInt(_),se=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),oe=[...("transfers"in u?u.transfers:[])||[],...se||[]].map(I=>{let dt=c.applyInputs(I,A,this.serializer,f),ue=dt.startsWith(`asset${l.ArgParamsSeparator}`)?dt:`asset${l.ArgParamsSeparator}${dt}`;return this.serializer.stringToNative(ue)[1]}),pe=A.find(I=>I.input.position==="data")?.value,ce="data"in u?u.data||"":null,Et=pe||ce||null,le=Et?c.applyInputs(Et,A,this.serializer,f):null,Rt={adapter:o,warp:p,chain:s,action:e,destination:x,args:N,value:ae,transfers:oe,data:le,resolvedInputs:A};return this.cache.set(St.WarpExecutable(this.config.env,p.meta?.hash||"",e),Rt.resolvedInputs,ee.OneWeek),Rt}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||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],o=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(o.map(u=>this.preprocessInput(t,u))),p=(u,d)=>{if(u.source===l.Source.UserWallet){let v=S(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=p(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=et(o,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=et(s,+a);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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 o=this.buildInputContext(t,n,i),c=await s.run(a,o);if(c==null)e.push(i);else{let p=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:p})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let o=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[o]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let p=c;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let o=s;"identifier"in o&&"amount"in o&&(i[`${a}.token`]=String(o.identifier),i[`${a}.amount`]=String(o.amount),i[`${a}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=yt(e),a=W(t,this.adapters);if(n==="asset"){let[s,o,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let p=await a.dataLoader.getAsset(s);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=et(o,p.decimals);return Qt({...p,amount:u})}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[o,c]=this.serializer.stringToNative(s),p=c;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.amount)})}else if(a.position.startsWith("arg:")){let o=Number(a.position.split(":")[1])-1;i.push({index:o,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(c=>c.inputs?.some(p=>p.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 ct=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],o=[],p={...t.meta?.query??{},...n.queries},u={...n,queries:p},{action:d,index:h}=E(t);for(let g=1;g<=t.actions.length;g++){let y=b(t,g);if(!ht(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:T}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),T&&g===h+1&&T.resolvedInputs&&(o=$(T.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{txs:i,chain:a,immediateExecutions:s,resolvedInputs:o}}async executeAction(t,e,n,i={}){let a=b(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 p=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):Nt.open(p,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let p=await this.executePrompt(t,a,e,n,i);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:null};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,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 p=await this.executeCollect(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let p=await this.executeMcp(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,executable:s}}}let o=W(s.chain.name,this.adapters);if(a.type==="query"){let p=await o.executor.executeQuery(s);if(p.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:p,tx:null}));else{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:s.chain,immediateExecution:p,executable:s}}return{tx:await o.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,o)=>{if(!ht(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[o],p=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),h={status:"error",warp:t,action:p,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${p} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,p,c.tx);return u.next=z(this.config,this.adapters,t,p,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=b(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:o,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",o,c)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=this.factory.getSerializer(),{url:c,method:p,headers:u,body:d}=await re(s,e,t,n,i,o,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:p,headers:u,body:d});try{let g=await fetch(c,{method:p,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Jt(g,c,p,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await nt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=$(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=S(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let g=$(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 y=$(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:y}}let o=this.factory.getSerializer(),c=new R(this.config,W(t.chain.name,this.adapters),this.adapters),p=i.destination,u=c.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),h={};p.headers&&Object.entries(p.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[P,H]=o.stringToNative(N);if(P==="string")f[V]=String(H);else if(P==="bool")f[V]=!!H;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let _=Number(H);f[V]=(Number.isInteger(_),_)}else f[V]=H}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:T,output:O}=await nt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",T,O,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let o=z(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:s?{...a,_DATA:s}:a,messages:Wt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),o=W(s.name,this.adapters),c=new R(this.config,o,this.adapters),p=await c.apply(t,a),u=b(p,n),{action:d}=E(p),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let V=this.factory.getStringTypedInputs(e,i),P=await this.factory.getResolvedInputs(s.name,e,V,c,a.queries);f=await this.factory.getModifiedInputs(P)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),T=S(this.config,s.name),O=this.factory.getSerializer(),{values:x,output:N}=await kt(p,v,n,f,O,this.config);return{status:"success",warp:p,action:n,user:T,txHash:null,tx:null,next:z(this.config,this.adapters,p,n,N),values:x,output:N,messages:Wt(p,N,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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 o=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=W(o.name,this.adapters),p=new R(this.config,c,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(o.name,u,d,p,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),p,i.queries);y=await this.factory.getModifiedInputs(A)}let f=p.buildInputBag(y,this.factory.getSerializer(),g),v=Ht(e.when,f);return Ft(v)}};var lt=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 ut=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,o=null,c=null,p=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Dt(t):jt(i.identifier);if(a==="hash"){o=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,p=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,p=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(ze(o,u.chainInfo.name,c,i.identifier),o.meta.query=d?Lt(d):null),!o)return n;let h=o.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new R(this.config,g,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:p}}catch(a){return C.error("Error detecting warp link",a),n}}},ze=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?mt(t,"alias",e.alias):mt(t,"hash",e?.hash??n))};var ne=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new ct(this.config,this.chains,t)}async detectWarp(t,e){return new ut(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),o=a?t:null;if(!o&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(o,e,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(o,y)},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=B(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(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??E(e).index+1,o=await W(t,this.chains).output.getActionExecution(e,a,n);return o.next=z(this.config,this.chains,e,a,o.output),o}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 lt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}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 rt(t,this.config)}};var ie=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()]))}};export{ft as BrowserCryptoProvider,ee as CacheTtl,rr as EvmWalletChainNames,gt as NodeCryptoProvider,Sr as WARP_LANGUAGES,Kt as WarpBrandBuilder,Xt as WarpBuilder,pt as WarpCache,St as WarpCacheKey,ve as WarpChainName,ne as WarpClient,U as WarpConfig,l as WarpConstants,ct as WarpExecutor,G as WarpFactory,lt as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,ut as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,ie as WarpTypeRegistry,it as WarpValidator,Vn as address,Wt as applyOutputToMessages,Qt as asset,$n as biguint,On as bool,K as buildMappedOutput,Pe as buildNestedPayload,mr as bytesToBase64,Ae as bytesToHex,J as cleanWarpIdentifier,Ct as createAuthHeaders,At as createAuthMessage,Wr as createCryptoProvider,Wn as createDefaultWalletProvider,dn as createHttpAuthHeaders,Ne as createSignableMessage,Tr as createWarpI18nText,mt as createWarpIdentifier,zt as evaluateOutputCommon,Ft as evaluateWhenCondition,nt as extractCollectOutput,Q as extractIdentifierInfoFromUrl,kt as extractPromptOutput,jt as extractQueryStringFromIdentifier,Dt as extractQueryStringFromUrl,$ as extractResolvedInputValues,Cr as extractWarpSecrets,W as findWarpAdapterForChain,Bt as getCryptoProvider,cr as getEventNameFromWarp,tt as getLatestProtocolIdentifier,z as getNextInfo,pn as getProviderConfig,$t as getRandomBytes,Ot as getRandomHex,_e as getWalletFromConfigOrFail,b as getWarpActionByIndex,ur as getWarpBrandLogoUrl,dr as getWarpChainAssetLogoUrl,fr as getWarpChainInfoLogoUrl,B as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,de as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,he as getWarpWalletExternalId,me as getWarpWalletExternalIdFromConfig,Ke as getWarpWalletExternalIdFromConfigOrFail,ge as getWarpWalletMnemonic,Qe as getWarpWalletMnemonicFromConfig,fe as getWarpWalletPrivateKey,Je as getWarpWalletPrivateKeyFromConfig,Jt as handleX402Payment,Vr as hasInputPrefix,Hn as hex,mn as initializeWalletCache,Nr as isEqualWarpIdentifier,ht as isWarpActionAutoExecute,Pr as isWarpI18nText,Xe as isWarpWalletReadOnly,Mt as mergeNestedPayload,Ye as normalizeAndValidateMnemonic,ye as normalizeMnemonic,Fn as option,Re as parseOutputOutIndex,gn as parseSignedMessage,Lt as parseWarpQueryStringToObject,Br as removeWarpChainPrefix,j as replacePlaceholders,Ht as replacePlaceholdersInWhenExpression,rt as resolveWarpText,Nt as safeWindow,hr as setCryptoProvider,Ze as setWarpWalletInConfig,et as shiftBigintBy,yt as splitInput,bn as string,Dn as struct,yr as testCryptoAvailability,Te as toInputPayloadValue,Vt as toPreviewText,Un as tuple,Rn as uint16,Nn as uint32,Bn as uint64,En as uint8,We as validateMnemonicLength,fn as validateSignedMessage,jn as vector,sr as withAdapterFallback};
|
|
1
|
+
var Ye=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},ge=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>ge(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,tr=(r,t)=>he(r.user?.wallets?.[t]||null)?.trim()||null,er=(r,t)=>me(r.user?.wallets?.[t]||null)?.trim()||null,We=(r,t)=>ye(r.user?.wallets?.[t]||null)?.trim()||null,rr=(r,t)=>{let e=We(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},nr=r=>typeof r=="string",ir=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},ve=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Ae=(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`)},ar=(r,t=24)=>{let e=ve(r);return Ae(e,t),e};var Ce=(d=>(d.Multiversx="multiversx",d.Claws="claws",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(Ce||{}),pr=["ethereum","base","arbitrum","polygon","somnia"],l={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>S(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:"},Alerts:{TriggerEventPrefix:"event"}},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"},Nt=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},U={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.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.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 hr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var yr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Wr=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},vr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ft=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}},gt=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 Bt(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new ft,D;if(typeof process<"u"&&process.versions?.node)return D=new gt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Cr(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||Bt()).getRandomBytes(r)}function xe(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 Ot(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 xe(e)}async function wr(){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 Ir(){return Bt()}var br=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.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},tt=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}`)},T=(r,t)=>r?.actions[t-1],E=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ht=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=E(t);return r===e}return!0},et=(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 o=s.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Vt=(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},L=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Ht=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ft=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 Nr={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"},rt=(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""},Br=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,$r=r=>r;var J=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Fr=(r,t)=>!r||!t?!1:J(r)===J(t),mt=(r,t,e)=>{let n=J(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||l.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=Ut(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:l.IdentifierType.Hash,identifier:i,identifierBase:a};if(s.length===2&&/^[a-zA-Z0-9]{62}$/.test(s[0])&&/^[a-zA-Z0-9]{2}$/.test(s[1]))return null;if(s.length===3){let[o,c,p]=s;if(c===l.IdentifierType.Alias||c===l.IdentifierType.Hash){let u=i.includes("?")?p+i.substring(i.indexOf("?")):p;return{chain:o,type:c,identifier:u,identifierBase:p}}}if(s.length===2){let[o,c]=s;if(o===l.IdentifierType.Alias||o===l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c;return{chain:e,type:o,identifier:p,identifierBase:c}}}if(s.length===2){let[o,c]=s;if(o!==l.IdentifierType.Alias&&o!==l.IdentifierType.Hash){let p=i.includes("?")?c+i.substring(i.indexOf("?")):c,u=we(c,o)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:o,type:u,identifier:p,identifierBase:c}}}return{chain:e,type:l.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(l.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},we=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ie=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ut=r=>{let t=Ie(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Ut(a);return[i,...s]},Dt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Lt=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},jt=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},Ur=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()};var yt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},jr=r=>{let t=new Set(Object.values(m));if(!r.includes(l.ArgParamsSeparator))return!1;let e=yt(r)[0];return t.has(e)};var Wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=rt(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Se from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||U.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,o=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(o);return U.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=B(t,this.config.defaultChain);if(!e)return null;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",o="#23F7DD"){let c=W(t,this.adapters),p=this.build(c.chainInfo.name,e,n);return new Se({type:"svg",width:i,height:i,data:String(p),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(o)}" 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 Pe="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Pe))return[{identifier:null,url:a}];let[s,o]=a.split("?");if(!o){let f=L(s,{...e.vars,...i});return[{identifier:f,url:vt(t,f,r)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=L(o,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:vt(t,v,r)}]}let p=c[0];if(!p)return[];let u=p.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let g=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let v=f.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let v=o;for(let{regex:b,field:O}of g){let x=O?be(f,O):f;if(x==null)return null;v=v.replace(b,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:vt(t,A,r)}}).filter(f=>f!==null)},vt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=W(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let o=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((p,u)=>c.searchParams.set(u,p)),c.toString().replace(/\/\?/,"?")},be=(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 C=j;function Te(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Mt(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]=Mt(e[n],t[n]):e[n]=t[n]}),e}function Ee(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 $(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function K(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=Ee(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=Te(n.input.position,i,a);e=Mt(e,s)}else e[i]=a}),e}var qt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,o]of Object.entries(r.output)){if(o.startsWith(l.Transform.Prefix))continue;let c=Be(o);if(c!==null&&c!==t){a[s]=null;continue}let[p,...u]=o.split(".");if(p==="out"||p.startsWith("out[")||p==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=o}return{stringValues:n,nativeValues:i,output:a}},nt=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),o=d=>d.length===0?t:s(t,d),{stringValues:c,nativeValues:p,output:u}=qt(r,e,o);return{values:{string:c,native:p,mapped:K(n,i)},output:await kt(r,u,t,e,n,i,a)}},kt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let o={...t};return o=Re(o,r,n,i,a),o=await Ne(r,o,e,s.transform?.runner||null),o},Re=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let p=c.split(".")[1],u=s.findIndex(h=>h.as===p||h.name===p),d=u!==-1?n[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},Ne=async(r,t,e,n)=>{if(!r.output)return t;let i={...t},a=Object.entries(r.output).filter(([,o])=>o.startsWith(l.Transform.Prefix)).map(([o,c])=>({key:o,code:c.substring(l.Transform.Prefix.length)}));if(a.length>0&&(!n||typeof n.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let s={...i,out:e};for(let{key:o,code:c}of a)try{i[o]=await n.run(c,s),s[o]=i[o]}catch(p){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,p),i[o]=null,s[o]=null}return i},zt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:o,nativeValues:c,output:p}=qt(r,e,s),u=await kt(r,p,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:o,native:c,mapped:K(n,i)},output:u}},Be=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 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 $e(r,t,e,n=5){let i=await Ot(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 At(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return $e(r,i,e,5)}function Ct(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Wn(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await At(r,e,n),o=await t(i);return Ct(r,o,a,s)}function vn(r){let t=new Date(r).getTime();return Date.now()<t}function An(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",Ve=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Gt=(r,t=24)=>{let e=Ve(r);return e?e.slice(0,t):"action"},_t=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)},He=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()}},xn=(r,t,e)=>{let n=Gt((e||t||"").trim()||"action"),i=`${r.type}|${He(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=_t(i);return`private_src_${n}_${a}`},Fe=r=>{let t=Oe(r),e=Gt(t),n=_t(t.trim().toLowerCase());return`private_gen_${e}_${n}`},wn=(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}},In=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Pn(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 Tn(r,t,e){return null}import{x402Client as Jt}from"@x402/core/client";import{x402HTTPClient as Qt}from"@x402/core/http";async function Kt(r,t,e,n,i){let a=await Ue(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,p])=>{s.set(c,p)}),C.debug("WarpExecutor: Retrying request with payment headers");let o=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:o.status}),o}var Ue=async(r,t)=>{let e=await De(r),i=new Qt(new Jt).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Jt,o=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&o[h.network]);if(!c?.network)continue;o[c.network]();let p=new Qt(s),u=await p.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=p.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},De=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===m.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.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(o=>o!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(o=>{let[c,p]=this.getTypeAndValue(n[o]);return`(${o}${l.ArgParamsSeparator}${c})${p}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===m.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let p=c.indexOf(l.ArgParamsSeparator),u=c.substring(p+1);return a.startsWith(m.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),o=a.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(o)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===m.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?m.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):m.Asset+l.ArgParamsSeparator+e.identifier+l.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+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===m.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[m.Option+l.ArgParamsSeparator+a,s||null]}if(n===m.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),o=i.substring(a+1),c=s.startsWith(m.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(o?o.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[m.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(m.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,o]}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 o={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let p=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(p){let[,u,d,h]=p;o[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,o]}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.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),o={identifier:a,amount:BigInt(s)};return[n,o]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let o=a.stringToNative(i);return[n,o]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[o,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.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 Un=r=>new w().nativeToString(m.String,r),Dn=r=>new w().nativeToString(m.Uint8,r),Ln=r=>new w().nativeToString(m.Uint16,r),jn=r=>new w().nativeToString(m.Uint32,r),Mn=r=>new w().nativeToString(m.Uint64,r),qn=r=>new w().nativeToString(m.Biguint,r),kn=r=>new w().nativeToString(m.Bool,r),zn=r=>new w().nativeToString(m.Address,r),Xt=r=>new w().nativeToString(m.Asset,r),Gn=r=>new w().nativeToString(m.Hex,r),_n=(r,t)=>{if(t===null)return m.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return m.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Jn=(...r)=>new w().nativeToString(m.Tuple,r),Qn=r=>new w().nativeToString(m.Struct,r),Kn=r=>new w().nativeToString(m.Vector,r);import Le from"ajv";var Zt=class{constructor(t){this.pendingBrand={protocol:tt("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||U.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Le,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import je from"ajv";var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=E(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}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"),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"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||U.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new je({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 Yt=class{constructor(t){this.config=t;this.pendingWarp={protocol:tt("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 Vt(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 it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
|
|
2
|
+
`))}};import{existsSync as wt,mkdirSync as Me,readdirSync as qe,readFileSync as ke,unlinkSync as It,writeFileSync as ze}from"fs";import{join as te,resolve as ee}from"path";var xt="$bigint:",at=(r,t)=>typeof t=="bigint"?xt+t.toString():t,z=(r,t)=>typeof t=="string"&&t.startsWith(xt)?BigInt(t.slice(xt.length)):t;var st=class{constructor(t,e){let n=e?.path;this.cacheDir=n?ee(n):ee(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){wt(this.cacheDir)||Me(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return te(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!wt(e))return null;let n=ke(e,"utf-8"),i=JSON.parse(n,z);return Date.now()>i.expiresAt?(It(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);ze(a,JSON.stringify(i,at),"utf-8")}forget(t){try{let e=this.getFilePath(t);wt(e)&&It(e)}catch{}}clear(){try{qe(this.cacheDir).forEach(e=>{e.endsWith(".json")&&It(te(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,z);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,at))}forget(t){localStorage.removeItem(this.getKey(t))}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){}get(t){let e=F.cache.get(t);return e?Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;F.cache.set(t,{value:e,expiresAt:i})}forget(t){F.cache.delete(t)}clear(){F.cache.clear()}};F.cache=new Map;var Z=F;import{readFileSync as Ge}from"fs";import{resolve as re}from"path";var ot=class{constructor(t,e){let n=e?.path?re(e.path):re(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=Ge(t,"utf-8");return new Map(Object.entries(JSON.parse(e,z)))}catch(e){return C.warn(`StaticCacheStrategy (loadManifest): Failed to load manifest from ${t}:`,e),new Map}}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a)}forget(t){this.cache.delete(t)}clear(){this.cache.clear()}};var ne={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},St={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}`},pt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new ot(t,e):e?.type==="filesystem"?new st(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Pt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},bt=(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)},Tt=r=>{try{return JSON.parse(r)}catch{return null}},_e=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:c,nonce:p,expiresAt:u}=await At(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(Ct(n,d,p,u)).forEach(([h,g])=>s.set(h,g))}let o=bt(e.resolvedInputs,Y.Headers,i);if(o){let c=Tt(o);c&&typeof c=="object"&&Object.entries(c).forEach(([p,u])=>typeof u=="string"&&s.set(p,u))}else t.headers&&Object.entries(t.headers).forEach(([c,p])=>{s.set(c,r.applyInputs(p,e.resolvedInputs,i))});return s},Je=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Pt.Get){let s=bt(e.resolvedInputs,Y.Queries,i);if(s){let o=Tt(s);if(o&&typeof o=="object"){let c=new URL(a);Object.entries(o).forEach(([p,u])=>u!=null&&c.searchParams.set(p,String(u))),a=c.toString()}}}return a},Qe=(r,t,e,n,i)=>{if(r===Pt.Get)return;let a=bt(t.resolvedInputs,Y.Payload,n);if(a&&Tt(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:o,...c}=e;return JSON.stringify({...c,...i})},ie=async(r,t,e,n,i,a,s,o)=>{let c=t.method||Pt.Get,p=await _e(r,t,e,n,a,o),u=Je(r,t,e,c,a),d=Qe(c,e,i,a,s);return{url:u,method:c,headers:p,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);return await this.applyGlobals(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=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,o)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o!="string")a(s,o);else if(o.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Query.length+1),[p,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(p):null,g=e.queries?.[p]||null||d;g&&a(s,g)}else if(o.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=o.slice(l.Vars.Env.length+1),[p,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[p];h&&a(s,h)}else o===l.Source.UserWallet&&n?a(s,n):a(s,o)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.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(l.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,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return L(a,s)}applyGlobalsToText(t){if(!Object.values(l.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(l.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.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,o)=>{let c=o.trim().toLowerCase();if(!this.adapters)return s;try{let p=W(c,this.adapters),u={config:this.config,adapter:p},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);i[s]=String(o)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,o]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(o),a.input.type==="asset"&&typeof a.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var 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 w,this.cache=new pt(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(St.WarpExecutable(t,e||"",n))||[];return $(i)}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),o=W(s.name,this.adapters),c=new R(this.config,o,this.adapters),p=await c.apply(t,i),u=T(p,e),{action:d,index:h}=E(p),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,c,i.queries),f=await this.getModifiedInputs(y),v=[],A=[];h===e-1?(v=y,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,c,i.queries),A=await this.getModifiedInputs(v));let b=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:O;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let N=this.getPreparedArgs(u,A);N=N.map(I=>c.applyInputs(I,A,this.serializer,f));let V=A.find(I=>I.input.position==="value")?.value||null,P="value"in u?u.value:null,H=V?.split(l.ArgParamsSeparator)[1]||P||"0",_=c.applyInputs(H,A,this.serializer,f),oe=BigInt(_),pe=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),ce=[...("transfers"in u?u.transfers:[])||[],...pe||[]].map(I=>{let dt=c.applyInputs(I,A,this.serializer,f),fe=dt.startsWith(`asset${l.ArgParamsSeparator}`)?dt:`asset${l.ArgParamsSeparator}${dt}`;return this.serializer.stringToNative(fe)[1]}),le=A.find(I=>I.input.position==="data")?.value,ue="data"in u?u.data||"":null,Et=le||ue||null,de=Et?c.applyInputs(Et,A,this.serializer,f):null,Rt={adapter:o,warp:p,chain:s,action:e,destination:x,args:N,value:oe,transfers:ce,data:de,resolvedInputs:A};return this.cache.set(St.WarpExecutable(this.config.env,p.meta?.hash||"",e),Rt.resolvedInputs,ne.OneWeek),Rt}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||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],o=n.map(u=>i.applyInputs(u,[],this.serializer)),c=await Promise.all(o.map(u=>this.preprocessInput(t,u))),p=(u,d)=>{if(u.source===l.Source.UserWallet){let v=S(this.config,t);return v?this.serializer.nativeToString("address",v):null}if(u.source==="hidden"){if(u.default===void 0)return null;let v=i?i.applyInputs(String(u.default),[],this.serializer):String(u.default);return this.serializer.nativeToString(u.type,v)}if(c[d])return c[d];let h=u.as||u.name,g=a?.[h],y=this.url.searchParams.get(h),f=g||y;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=p(u,d),g=u.default!==void 0?i?i.applyInputs(String(u.default),[],this.serializer):String(u.default):void 0;return{input:u,value:h||(g!==void 0?this.serializer.nativeToString(u.type,g):null)}})}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(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=et(o,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=et(s,+a);e.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.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 o=this.buildInputContext(t,n,i),c=await s.run(a,o);if(c==null)e.push(i);else{let p=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:p})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let o=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[o]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let p=c;"identifier"in p&&"amount"in p&&(i[`${o}.token`]=String(p.identifier),i[`${o}.amount`]=String(p.amount),i[`${o}.identifier`]=String(p.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let o=s;"identifier"in o&&"amount"in o&&(i[`${a}.token`]=String(o.identifier),i[`${a}.amount`]=String(o.amount),i[`${a}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=yt(e),a=W(t,this.adapters);if(n==="asset"){let[s,o,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let p=await a.dataLoader.getAsset(s);if(!p)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof p.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=et(o,p.decimals);return Xt({...p,amount:u})}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[o,c]=this.serializer.stringToNative(s),p=c;if(!p||typeof p!="object"||!("identifier"in p)||!("amount"in p))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",p.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",p.amount)})}else if(a.position.startsWith("arg:")){let o=Number(a.position.split(":")[1])-1;i.push({index:o,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(c=>c.inputs?.some(p=>p.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.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 ct=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],o=[],p={...t.meta?.query??{},...n.queries},u={...n,queries:p},{action:d,index:h}=E(t);for(let g=1;g<=t.actions.length;g++){let y=T(t,g);if(!ht(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:b}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),b&&g===h+1&&b.resolvedInputs&&(o=$(b.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{txs:i,chain:a,immediateExecutions:s,resolvedInputs:o}}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 p=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(p):Nt.open(p,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let p=await this.executePrompt(t,a,e,n,i);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:null};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,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 p=await this.executeCollect(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let p=await this.executeMcp(s);if(p.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};if(p.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:p,tx:null})),{tx:null,chain:null,immediateExecution:p,executable:s};{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);return this.handlers?.onError?.({message:u,result:p}),{tx:null,chain:null,immediateExecution:p,executable:s}}}let o=W(s.chain.name,this.adapters);if(a.type==="query"){let p=await o.executor.executeQuery(s);if(p.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:p,tx:null}));else{let u=p.output._DATA instanceof Error?p.output._DATA.message:JSON.stringify(p.output._DATA);this.handlers?.onError?.({message:u,result:p})}return{tx:null,chain:s.chain,immediateExecution:p,executable:s}}return{tx:await o.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,o)=>{if(!ht(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[o],p=o+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,p),h={status:"error",warp:t,action:p,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${p} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,p,c.tx);return u.next=k(this.config,this.adapters,t,p,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:p,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).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(o=>o.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=K(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:o,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",o,c)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=this.factory.getSerializer(),{url:c,method:p,headers:u,body:d}=await ie(s,e,t,n,i,o,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:p,headers:u,body:d});try{let g=await fetch(c,{method:p,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Kt(g,c,p,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await nt(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),g.ok?"success":"error",f,v,y)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=$(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=S(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let g=$(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 y=$(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:y}}let o=this.factory.getSerializer(),c=new R(this.config,W(t.chain.name,this.adapters),this.adapters),p=i.destination,u=c.applyInputs(p.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(p.tool,t.resolvedInputs,this.factory.getSerializer()),h={};p.headers&&Object.entries(p.headers).forEach(([g,y])=>{let f=c.applyInputs(y,t.resolvedInputs,this.factory.getSerializer());h[g]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let g=new s(new URL(u),{requestInit:{headers:h}}),y=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await y.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:N})=>{if(N&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[P,H]=o.stringToNative(N);if(P==="string")f[V]=String(H);else if(P==="bool")f[V]=!!H;else if(P==="uint8"||P==="uint16"||P==="uint32"||P==="uint64"||P==="uint128"||P==="uint256"||P==="biguint"){let _=Number(H);f[V]=(Number.isInteger(_),_)}else f[V]=H}}),e&&Object.assign(f,e);let v=await y.callTool({name:d,arguments:f});await y.close();let A;if(v.content&&v.content.length>0){let x=v.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=v;let{values:b,output:O}=await nt(t.warp,A,t.action,t.resolvedInputs,o,this.config);return this.buildCollectResult(t,n,"success",b,O,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let y=$(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:y}}}buildCollectResult(t,e,n,i,a,s){let o=k(this.config,this.adapters,t.warp,t.action,a),c=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:s?{...a,_DATA:s}:a,messages:Wt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),o=W(s.name,this.adapters),c=new R(this.config,o,this.adapters),p=await c.apply(t,a),u=T(p,n),{action:d}=E(p),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,c,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let V=this.factory.getStringTypedInputs(e,i),P=await this.factory.getResolvedInputs(s.name,e,V,c,a.queries);f=await this.factory.getModifiedInputs(P)}let v=c.applyInputs(u.prompt,f,this.factory.getSerializer(),y),A=$(f),b=S(this.config,s.name),O=this.factory.getSerializer(),{values:x,output:N}=await zt(p,v,n,f,O,this.config);return{status:"success",warp:p,action:n,user:b,txHash:null,tx:null,next:k(this.config,this.adapters,p,n,N),values:x,output:N,messages:Wt(p,N,this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,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 o=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=W(o.name,this.adapters),p=new R(this.config,c,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(o.name,u,d,p,i.queries),g=await this.factory.getModifiedInputs(h),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(o.name,e,this.factory.getStringTypedInputs(e,n),p,i.queries);y=await this.factory.getModifiedInputs(A)}let f=p.buildInputBag(y,this.factory.getSerializer(),g),v=Ht(e.when,f);return Ft(v)}};var lt=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 ut=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;try{let{type:a,identifierBase:s}=i,o=null,c=null,p=null,u=W(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Dt(t):Lt(i.identifier);if(a==="hash"){o=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,p=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,p=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(o&&o.meta&&(Ke(o,u.chainInfo.name,c,i.identifier),o.meta.query=d?jt(d):null),!o)return n;let h=o.chain||u.chainInfo.name,g=W(h,this.adapters),y=await new R(this.config,g,this.adapters).apply(o);return{match:!0,url:t,warp:y,chain:h,registryInfo:c,brand:p}}catch(a){return C.error("Error detecting warp link",a),n}}},Ke=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?mt(t,"alias",e.alias):mt(t,"hash",e?.hash??n))};var ae=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new ct(this.config,this.chains,t)}async detectWarp(t,e){return new ut(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),o=a?t:null;if(!o&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:p,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(o,e,{queries:i.queries});return{txs:p,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await c.evaluateOutput(o,y)},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=B(t,this.config.defaultChain);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return W(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(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??E(e).index+1,o=await W(t,this.chains).output.getActionExecution(e,a,n);return o.next=k(this.config,this.chains,e,a,o.output),o}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 lt(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return W(t,this.chains).builder()}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 rt(t,this.config)}};var se=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{ft as BrowserCryptoProvider,ne as CacheTtl,pr as EvmWalletChainNames,gt as NodeCryptoProvider,Nr as WARP_LANGUAGES,Zt as WarpBrandBuilder,Yt as WarpBuilder,pt as WarpCache,St as WarpCacheKey,Ce as WarpChainName,ae as WarpClient,U as WarpConfig,l as WarpConstants,ct as WarpExecutor,G as WarpFactory,lt as WarpIndex,m as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,ut as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,se as WarpTypeRegistry,it as WarpValidator,zn as address,Wt as applyOutputToMessages,Xt as asset,qn as biguint,kn as bool,Fe as buildGeneratedFallbackWarpIdentifier,xn as buildGeneratedSourceWarpIdentifier,K as buildMappedOutput,Te as buildNestedPayload,xr as bytesToBase64,xe as bytesToHex,J as cleanWarpIdentifier,Ct as createAuthHeaders,At as createAuthMessage,Ir as createCryptoProvider,Tn as createDefaultWalletProvider,Wn as createHttpAuthHeaders,$e as createSignableMessage,$r as createWarpI18nText,mt as createWarpIdentifier,kt as evaluateOutputCommon,Ft as evaluateWhenCondition,nt as extractCollectOutput,Q as extractIdentifierInfoFromUrl,zt as extractPromptOutput,Lt as extractQueryStringFromIdentifier,Dt as extractQueryStringFromUrl,$ as extractResolvedInputValues,br as extractWarpSecrets,W as findWarpAdapterForChain,Bt as getCryptoProvider,hr as getEventNameFromWarp,Oe as getGeneratedSourceWarpName,tt as getLatestProtocolIdentifier,k as getNextInfo,gn as getProviderConfig,$t as getRandomBytes,Ot as getRandomHex,Ye as getWalletFromConfigOrFail,T as getWarpActionByIndex,yr as getWarpBrandLogoUrl,Wr as getWarpChainAssetLogoUrl,vr as getWarpChainInfoLogoUrl,B as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,ge as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,ye as getWarpWalletExternalId,We as getWarpWalletExternalIdFromConfig,rr as getWarpWalletExternalIdFromConfigOrFail,me as getWarpWalletMnemonic,er as getWarpWalletMnemonicFromConfig,he as getWarpWalletPrivateKey,tr as getWarpWalletPrivateKeyFromConfig,Kt as handleX402Payment,jr as hasInputPrefix,Gn as hex,Pn as initializeWalletCache,Fr as isEqualWarpIdentifier,In as isGeneratedSourcePrivateIdentifier,ht as isWarpActionAutoExecute,Br as isWarpI18nText,nr as isWarpWalletReadOnly,Mt as mergeNestedPayload,ar as normalizeAndValidateMnemonic,ve as normalizeMnemonic,_n as option,Be as parseOutputOutIndex,An as parseSignedMessage,jt as parseWarpQueryStringToObject,Ur as removeWarpChainPrefix,L as replacePlaceholders,Ht as replacePlaceholdersInWhenExpression,rt as resolveWarpText,Nt as safeWindow,Cr as setCryptoProvider,ir as setWarpWalletInConfig,et as shiftBigintBy,yt as splitInput,wn as stampGeneratedWarpMeta,Un as string,Qn as struct,wr as testCryptoAvailability,Ee as toInputPayloadValue,Vt as toPreviewText,Jn as tuple,Ln as uint16,jn as uint32,Mn as uint64,Dn as uint8,Ae as validateMnemonicLength,vn as validateSignedMessage,Kn as vector,dr as withAdapterFallback};
|