@joai/warps 4.5.0 → 4.6.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 CHANGED
@@ -484,6 +484,7 @@ type Warp = {
484
484
  bot?: string;
485
485
  preview?: string;
486
486
  vars?: Record<WarpVarPlaceholder, string>;
487
+ trigger?: WarpTrigger;
487
488
  actions: WarpAction[];
488
489
  next?: string;
489
490
  output?: Record<WarpOutputName, WarpResulutionPath>;
@@ -502,9 +503,49 @@ type WarpMeta = {
502
503
  creator: string;
503
504
  createdAt: string;
504
505
  };
505
- type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction;
506
+ type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction;
506
507
  type WarpActionIndex = number;
507
- type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt';
508
+ type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount';
509
+ type WarpTrigger = {
510
+ type: 'message';
511
+ pattern: string;
512
+ };
513
+ type WarpStateAction = {
514
+ type: 'state';
515
+ label: WarpText;
516
+ description?: WarpText | null;
517
+ op: 'read' | 'write' | 'clear';
518
+ store: string;
519
+ keys?: string[];
520
+ data?: Record<string, any>;
521
+ inputs?: WarpActionInput[];
522
+ primary?: boolean;
523
+ auto?: boolean;
524
+ next?: string;
525
+ when?: string;
526
+ };
527
+ type WarpMountAction = {
528
+ type: 'mount';
529
+ label: WarpText;
530
+ description?: WarpText | null;
531
+ warp: string;
532
+ inputs?: WarpActionInput[];
533
+ primary?: boolean;
534
+ auto?: boolean;
535
+ next?: string;
536
+ when?: string;
537
+ };
538
+ type WarpUnmountAction = {
539
+ type: 'unmount';
540
+ label: WarpText;
541
+ description?: WarpText | null;
542
+ warp: string;
543
+ inputs?: WarpActionInput[];
544
+ primary?: boolean;
545
+ auto?: boolean;
546
+ next?: string;
547
+ when?: string;
548
+ };
508
549
  type WarpTransferAction = {
509
550
  type: WarpActionType;
510
551
  label: WarpText;
@@ -1012,6 +1053,9 @@ declare function initializeWalletCache(provider: WalletProvider | null): Promise
1012
1053
 
1013
1054
  declare function createDefaultWalletProvider(config: WarpClientConfig, chain: WarpChainInfo, rpcProvider?: any): WalletProvider | null;
1014
1055
 
1056
+ declare const getRequiredAssetIds: (warp: Warp, chainInfo: WarpChainInfo) => string[];
1057
+ declare const checkWarpAssetBalance: (warp: Warp, walletAddress: string, walletChain: WarpChainName, adapters: ChainAdapter[]) => Promise<boolean>;
1058
+
1015
1059
  declare function handleX402Payment(response: Response, url: string, method: string, body: string | undefined, adapters: ChainAdapter[]): Promise<Response>;
1016
1060
 
1017
1061
  type CodecFunc<T extends WarpNativeValue = WarpNativeValue> = (value: T) => string;
@@ -1325,4 +1369,4 @@ declare class WarpValidator {
1325
1369
  private validateSchema;
1326
1370
  }
1327
1371
 
1328
- 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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, 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 WarpCacheAdapter, 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, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, 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, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, 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, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1372
+ 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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, 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 WarpCacheAdapter, 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, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, 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 WarpMountAction, type WarpNativeValue, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.d.ts CHANGED
@@ -484,6 +484,7 @@ type Warp = {
484
484
  bot?: string;
485
485
  preview?: string;
486
486
  vars?: Record<WarpVarPlaceholder, string>;
487
+ trigger?: WarpTrigger;
487
488
  actions: WarpAction[];
488
489
  next?: string;
489
490
  output?: Record<WarpOutputName, WarpResulutionPath>;
@@ -502,9 +503,49 @@ type WarpMeta = {
502
503
  creator: string;
503
504
  createdAt: string;
504
505
  };
505
- type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction;
506
+ type WarpAction = WarpTransferAction | WarpContractAction | WarpQueryAction | WarpCollectAction | WarpLinkAction | WarpMcpAction | WarpPromptAction | WarpStateAction | WarpMountAction | WarpUnmountAction;
506
507
  type WarpActionIndex = number;
507
- type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt';
508
+ type WarpActionType = 'transfer' | 'contract' | 'query' | 'collect' | 'link' | 'mcp' | 'prompt' | 'state' | 'mount' | 'unmount';
509
+ type WarpTrigger = {
510
+ type: 'message';
511
+ pattern: string;
512
+ };
513
+ type WarpStateAction = {
514
+ type: 'state';
515
+ label: WarpText;
516
+ description?: WarpText | null;
517
+ op: 'read' | 'write' | 'clear';
518
+ store: string;
519
+ keys?: string[];
520
+ data?: Record<string, any>;
521
+ inputs?: WarpActionInput[];
522
+ primary?: boolean;
523
+ auto?: boolean;
524
+ next?: string;
525
+ when?: string;
526
+ };
527
+ type WarpMountAction = {
528
+ type: 'mount';
529
+ label: WarpText;
530
+ description?: WarpText | null;
531
+ warp: string;
532
+ inputs?: WarpActionInput[];
533
+ primary?: boolean;
534
+ auto?: boolean;
535
+ next?: string;
536
+ when?: string;
537
+ };
538
+ type WarpUnmountAction = {
539
+ type: 'unmount';
540
+ label: WarpText;
541
+ description?: WarpText | null;
542
+ warp: string;
543
+ inputs?: WarpActionInput[];
544
+ primary?: boolean;
545
+ auto?: boolean;
546
+ next?: string;
547
+ when?: string;
548
+ };
508
549
  type WarpTransferAction = {
509
550
  type: WarpActionType;
510
551
  label: WarpText;
@@ -1012,6 +1053,9 @@ declare function initializeWalletCache(provider: WalletProvider | null): Promise
1012
1053
 
1013
1054
  declare function createDefaultWalletProvider(config: WarpClientConfig, chain: WarpChainInfo, rpcProvider?: any): WalletProvider | null;
1014
1055
 
1056
+ declare const getRequiredAssetIds: (warp: Warp, chainInfo: WarpChainInfo) => string[];
1057
+ declare const checkWarpAssetBalance: (warp: Warp, walletAddress: string, walletChain: WarpChainName, adapters: ChainAdapter[]) => Promise<boolean>;
1058
+
1015
1059
  declare function handleX402Payment(response: Response, url: string, method: string, body: string | undefined, adapters: ChainAdapter[]): Promise<Response>;
1016
1060
 
1017
1061
  type CodecFunc<T extends WarpNativeValue = WarpNativeValue> = (value: T) => string;
@@ -1325,4 +1369,4 @@ declare class WarpValidator {
1325
1369
  private validateSchema;
1326
1370
  }
1327
1371
 
1328
- 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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, 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 WarpCacheAdapter, 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, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, 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, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, 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, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
1372
+ 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, type BuiltInWarpWalletProvider, CLOUD_WALLET_PROVIDERS, CacheTtl, type ChainAdapter, type ChainAdapterFactory, type ClientCacheConfig, 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 WarpCacheAdapter, 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, WarpChainResolver, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpCompositeResolver, 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 WarpMountAction, type WarpNativeValue, type WarpOutputName, WarpPlatformName, type WarpPlatformValue, WarpPlatforms, type WarpPromptAction, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResolver, type WarpResolverResult, type WarpResulutionPath, type WarpSchedule, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStateAction, type WarpStructValue, type WarpText, type WarpTheme, type WarpTransferAction, type WarpTrigger, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUnmountAction, type WarpUser, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, type WarpWalletProvider, address, applyOutputToMessages, asset, biguint, bool, buildGeneratedFallbackWarpIdentifier, buildGeneratedSourceWarpIdentifier, buildInputsContext, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, checkWarpAssetBalance, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createDefaultWalletProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, doesWarpRequireWallet, evaluateOutputCommon, evaluateWhenCondition, extractCollectOutput, extractIdentifierInfoFromUrl, extractPromptOutput, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractResolvedInputValues, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getGeneratedSourceWarpName, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getRequiredAssetIds, getWalletFromConfigOrFail, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpChainAssetLogoUrl, getWarpChainInfoLogoUrl, getWarpIdentifierWithQuery, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletExternalId, getWarpWalletExternalIdFromConfig, getWarpWalletExternalIdFromConfigOrFail, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, handleX402Payment, hasInputPrefix, hex, initializeWalletCache, isEqualWarpIdentifier, isGeneratedSourcePrivateIdentifier, isPlatformValue, isWarpActionAutoExecute, isWarpI18nText, isWarpWalletReadOnly, mergeNestedPayload, normalizeAndValidateMnemonic, normalizeMnemonic, option, parseOutputOutIndex, parseSignedMessage, parseWarpQueryStringToObject, removeWarpChainPrefix, removeWarpWalletFromConfig, replacePlaceholders, replacePlaceholdersInWhenExpression, resolvePlatformValue, resolveWarpText, safeWindow, setCryptoProvider, setWarpWalletInConfig, shiftBigintBy, splitInput, stampGeneratedWarpMeta, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateMnemonicLength, validateSignedMessage, vector, withAdapterFallback };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var je=Object.create;var ht=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var Ge=(r,t)=>{for(var e in t)ht(r,e,{get:t[e],enumerable:!0})},pe=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of qe(t))!ze.call(r,i)&&i!==e&&ht(r,i,{get:()=>t[i],enumerable:!(n=Me(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?je(ke(r)):{},pe(t||!r||!r.__esModule?ht(e,"default",{value:r,enumerable:!0}):e,r)),_e=r=>pe(ht({},"__esModule",{value:!0}),r);var sn={};Ge(sn,{BrowserCryptoProvider:()=>mt,CLOUD_WALLET_PROVIDERS:()=>nr,CacheTtl:()=>te,EvmWalletChainNames:()=>rr,NodeCryptoProvider:()=>yt,WARP_LANGUAGES:()=>hr,WarpBrandBuilder:()=>Kt,WarpBuilder:()=>Xt,WarpCache:()=>ct,WarpCacheKey:()=>bt,WarpChainName:()=>me,WarpChainResolver:()=>tt,WarpClient:()=>ie,WarpCompositeResolver:()=>et,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>dt,WarpFactory:()=>G,WarpIndex:()=>ft,WarpInputTypes:()=>h,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>gt,WarpLogger:()=>C,WarpPlatformName:()=>Et,WarpPlatforms:()=>Rt,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>ae,WarpValidator:()=>ot,address:()=>Qr,applyOutputToMessages:()=>Ct,asset:()=>Qt,biguint:()=>_r,bool:()=>Jr,buildGeneratedFallbackWarpIdentifier:()=>Ee,buildGeneratedSourceWarpIdentifier:()=>Hr,buildInputsContext:()=>at,buildMappedOutput:()=>K,buildNestedPayload:()=>Ae,bytesToBase64:()=>cr,bytesToHex:()=>ye,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>wt,createAuthMessage:()=>xt,createCryptoProvider:()=>dr,createDefaultWalletProvider:()=>Dr,createHttpAuthHeaders:()=>Rr,createSignableMessage:()=>Pe,createWarpI18nText:()=>yr,createWarpIdentifier:()=>vt,doesWarpRequireWallet:()=>gr,evaluateOutputCommon:()=>qt,evaluateWhenCondition:()=>Ot,extractCollectOutput:()=>st,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>kt,extractQueryStringFromIdentifier:()=>Dt,extractQueryStringFromUrl:()=>Ut,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>fr,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Bt,getEventNameFromWarp:()=>ar,getGeneratedSourceWarpName:()=>Se,getLatestProtocolIdentifier:()=>rt,getNextInfo:()=>k,getProviderConfig:()=>Er,getRandomBytes:()=>$t,getRandomHex:()=>Vt,getWalletFromConfigOrFail:()=>Je,getWarpActionByIndex:()=>E,getWarpBrandLogoUrl:()=>sr,getWarpChainAssetLogoUrl:()=>or,getWarpChainInfoLogoUrl:()=>pr,getWarpIdentifierWithQuery:()=>xr,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>R,getWarpWalletAddress:()=>le,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>de,getWarpWalletExternalIdFromConfig:()=>fe,getWarpWalletExternalIdFromConfigOrFail:()=>Xe,getWarpWalletMnemonic:()=>ue,getWarpWalletMnemonicFromConfig:()=>Ke,getWarpWalletPrivateKey:()=>ce,getWarpWalletPrivateKeyFromConfig:()=>Qe,handleX402Payment:()=>Jt,hasInputPrefix:()=>wr,hex:()=>Kr,initializeWalletCache:()=>Ur,isEqualWarpIdentifier:()=>Wr,isGeneratedSourcePrivateIdentifier:()=>Or,isPlatformValue:()=>Ie,isWarpActionAutoExecute:()=>Wt,isWarpI18nText:()=>mr,isWarpWalletReadOnly:()=>Ze,mergeNestedPayload:()=>Mt,normalizeAndValidateMnemonic:()=>er,normalizeMnemonic:()=>ge,option:()=>Xr,parseOutputOutIndex:()=>we,parseSignedMessage:()=>Br,parseWarpQueryStringToObject:()=>Lt,removeWarpChainPrefix:()=>Cr,removeWarpWalletFromConfig:()=>tr,replacePlaceholders:()=>L,replacePlaceholdersInWhenExpression:()=>Ft,resolvePlatformValue:()=>zt,resolveWarpText:()=>it,safeWindow:()=>Nt,setCryptoProvider:()=>lr,setWarpWalletInConfig:()=>Ye,shiftBigintBy:()=>nt,splitInput:()=>At,stampGeneratedWarpMeta:()=>Fr,string:()=>Mr,struct:()=>Yr,testCryptoAvailability:()=>ur,toInputPayloadValue:()=>Ce,toPreviewText:()=>Ht,tuple:()=>Zr,uint16:()=>kr,uint32:()=>zr,uint64:()=>Gr,uint8:()=>qr,validateMnemonicLength:()=>he,validateSignedMessage:()=>Nr,vector:()=>tn,withAdapterFallback:()=>ir});module.exports=_e(sn);var tt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var et=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Je=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},le=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>le(r.user?.wallets?.[t]||null),ce=r=>r?typeof r=="string"?r:r.privateKey||null:null,ue=r=>r?typeof r=="string"?r:r.mnemonic||null:null,de=r=>r?typeof r=="string"?r:r.externalId||null:null,Qe=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,Ke=(r,t)=>ue(r.user?.wallets?.[t]||null)?.trim()||null,fe=(r,t)=>de(r.user?.wallets?.[t]||null)?.trim()||null,Xe=(r,t)=>{let e=fe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ze=r=>typeof r=="string",Ye=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},tr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ge=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},he=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},er=(r,t=24)=>{let e=ge(r);return he(e,t),e};var me=(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))(me||{}),Et=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Et||{}),Rt=Object.values(Et),rr=["ethereum","base","arbitrum","polygon","somnia"],nr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},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"},Nt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={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",c.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 ir=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var ar=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var sr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},or=(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]},pr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var mt=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}},yt=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 mt,M;if(typeof process<"u"&&process.versions?.node)return M=new yt,M;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function lr(r){M=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 ye(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 cr(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 Vt(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 ye(e)}async function ur(){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 dr(){return Bt()}var fr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.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},rt=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}},Wt=(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},nt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Ht=(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)=>{let i=t[n];return i==null?"":String(i)}),Ft=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),gr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Ot=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 hr={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"},it=(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""},mr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,yr=r=>r;var J=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Wr=(r,t)=>!r||!t?!1:J(r)===J(t),vt=(r,t,e)=>{let n=J(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=We(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.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[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=vr(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return B(a,t)},vr=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ar=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},We=r=>{let t=Ar(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=We(a);return[i,...s]},Ut=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Dt=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},Cr=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()},xr=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var At=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},wr=r=>{let t=new Set(Object.values(h));if(!r.includes(c.ArgParamsSeparator))return!1;let e=At(r)[0];return t.has(e)};var Ct=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=it(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};var ve=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}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",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new ve.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ir="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ir))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:jt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:jt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.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=l.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=p;for(let{regex:T,field:O}of g){let x=O?Pr(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:jt(t,A,r)}}).filter(f=>f!==null)},jt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:c.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 p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},Pr=(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 Ae(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.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 Ce(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=Ce(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Ae(n.input.position,i,a);e=Mt(e,s)}else e[i]=a}),e}function at(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var xe=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=we(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},st=async(r,t,e,n,i,a)=>{let s=(d,m)=>m.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=xe(r,e,p);return{values:{string:l,native:o,mapped:K(n,i)},output:await qt(r,u,t,e,n,i,a)}},qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Sr(p,r,n,i,a),p=await br(r,p,e,i,a,s.transform?.runner||null),p},Sr=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(m=>m.as===o||m.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},br=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Tr(e),inputs:at(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Tr=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=xe(r,e,s),u=await qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:u}},we=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 Ie=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Rt.some(t=>t in r),zt=(r,t)=>{if(!Ie(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Er=(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 Pe(r,t,e,n=5){let i=await Vt(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 xt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Pe(r,i,e,5)}function wt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Rr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await xt(r,e,n),p=await t(i);return wt(r,p,a,s)}function Nr(r){let t=new Date(r).getTime();return Date.now()<t}function Br(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 Se=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",$r=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),be=(r,t=24)=>{let e=$r(r);return e?e.slice(0,t):"action"},Te=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)},Vr=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()}},Hr=(r,t,e)=>{let n=be((e||t||"").trim()||"action"),i=`${r.type}|${Vr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Te(i);return`private_src_${n}_${a}`},Ee=r=>{let t=Se(r),e=be(t),n=Te(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Fr=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ee(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Or=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Ur(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 Dr(r,t,e){return null}var Gt=require("@x402/core/client"),_t=require("@x402/core/http");async function Jt(r,t,e,n,i){let a=await Lr(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(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Lr=async(r,t)=>{let e=await jr(r),i=new _t.x402HTTPClient(new Gt.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 Gt.x402Client,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(m=>m?.network&&p[m.network]);if(!l?.network)continue;p[l.network]();let o=new _t.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},jr=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+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.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(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(h.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(h.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):h.Asset+c.ArgParamsSeparator+e.identifier+c.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+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[h.Option+c.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(h.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[h.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}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 p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,m]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${m}`)[1]}}),[n,p]}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(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.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 Mr=r=>new w().nativeToString(h.String,r),qr=r=>new w().nativeToString(h.Uint8,r),kr=r=>new w().nativeToString(h.Uint16,r),zr=r=>new w().nativeToString(h.Uint32,r),Gr=r=>new w().nativeToString(h.Uint64,r),_r=r=>new w().nativeToString(h.Biguint,r),Jr=r=>new w().nativeToString(h.Bool,r),Qr=r=>new w().nativeToString(h.Address,r),Qt=r=>new w().nativeToString(h.Asset,r),Kr=r=>new w().nativeToString(h.Hex,r),Xr=(r,t)=>{if(t===null)return h.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},Zr=(...r)=>new w().nativeToString(h.Tuple,r),Yr=r=>new w().nativeToString(h.Struct,r),tn=r=>new w().nativeToString(h.Vector,r);var Re=_(require("ajv"),1);var Kt=class{constructor(t){this.pendingBrand={protocol:rt("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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Re.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Ne=_(require("ajv"),1);var ot=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||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ne.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 Xt=class{constructor(t){this.config=t;this.pendingWarp={protocol:rt("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 Ht(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 ot(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var I=require("fs"),Z=require("path");var Zt="$bigint:",It=(r,t)=>typeof t=="bigint"?Zt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Zt)?BigInt(t.slice(Zt.length)):t;var Pt=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,I.existsSync)(this.cacheDir)||(0,I.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,I.existsSync)(e))return null;let n=(0,I.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,I.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,I.writeFileSync)(a,JSON.stringify(i,It),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,I.existsSync)(e)&&(0,I.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,I.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,I.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,I.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var pt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,It))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}async get(t){let e=F.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;F.cache.set(t,{value:e,expiresAt:i})}async delete(t){F.cache.delete(t)}async keys(t){let e=Array.from(F.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){F.cache.clear()}};F.cache=new Map;var lt=F;var Be=require("fs"),Yt=require("path");var St=class{constructor(t,e){let n=e?.path?(0,Yt.resolve)(e.path):(0,Yt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,Be.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}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var te={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},bt={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}`},ct=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new pt(t,e):e?.type==="memory"?new lt(t,e):e?.type==="static"?new St(t,e):e?.type==="filesystem"?new Pt(t,e):typeof window<"u"&&window.localStorage?new pt(t,e):new lt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var ut={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ee={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},re=(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)},ne=r=>{try{return JSON.parse(r)}catch{return null}},en=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await xt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(wt(n,d,o,u)).forEach(([m,g])=>s.set(m,g))}let p=re(e.resolvedInputs,ut.Headers,i);if(p){let l=ne(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},rn=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ee.Get){let s=re(e.resolvedInputs,ut.Queries,i);if(s){let p=ne(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},nn=(r,t,e,n,i)=>{if(r===ee.Get)return;let a=re(t.resolvedInputs,ut.Payload,n);if(a&&ne(a)!==null)return a;let{[ut.Payload]:s,[ut.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},$e=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ee.Get,o=await en(r,t,e,n,a,p),u=rn(r,t,e,l,a),d=nn(l,e,i,a,s);return{url:u,method:l,headers:o,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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),m={...this.config.vars,...e.envs}?.[o];m!=null&&a(s,m)}else p===c.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.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(c.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(c.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(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),u={config:this.config,adapter:o},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,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.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 ct(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(bt.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),p=W(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,i),u=E(o,e),{action:d,index:m}=R(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,l,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,l,i.queries),A=await this.getModifiedInputs(v));let T=A.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:O;if(x&&(x=l.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let U=this.getPreparedArgs(u,A);U=U.map(S=>l.applyInputs(S,A,this.serializer,f));let V=A.find(S=>S.input.position==="value")?.value||null,b="value"in u?u.value:null,H=V?.split(c.ArgParamsSeparator)[1]||b||"0",Y=l.applyInputs(H,A,this.serializer,f),Ve=BigInt(Y),He=A.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),Fe=[...("transfers"in u?u.transfers:[])||[],...He||[]].map(S=>{let Tt=l.applyInputs(S,A,this.serializer,f),Le=Tt.startsWith(`asset${c.ArgParamsSeparator}`)?Tt:`asset${c.ArgParamsSeparator}${Tt}`;return this.serializer.stringToNative(Le)[1]}),Oe=A.find(S=>S.input.position==="data")?.value,Ue="data"in u?u.data||"":null,se=Oe||Ue||null,De=se?l.applyInputs(se,A,this.serializer,f):null,oe={adapter:p,warp:o,chain:s,action:e,destination:x,args:U,value:Ve,transfers:Fe,data:De,resolvedInputs:A};return await this.cache.set(bt.WarpExecutable(this.config.env,o.meta?.hash||"",e),oe.resolvedInputs,te.OneWeek),oe}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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(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(l[d])return l[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=o(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(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=nt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=nt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=at(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=At(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=nt(p,o.decimals);return Qt({...o,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[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let 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",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var dt=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=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:m}=R(t);for(let g=1;g<=t.actions.length;g++){let y=E(t,g);if(!Wt(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&&(p=$(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:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Nt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),m={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:m})),m}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=k(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):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(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=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:p,output:l}=await st(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await $e(s,e,t,n,i,p,a,async m=>await this.callHandler(()=>this.handlers?.onSignRequest?.(m)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Jt(g,l,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await st(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",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=P(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 p=this.factory.getSerializer(),l=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),m={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=l.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:U})=>{if(U&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[b,H]=p.stringToNative(U);if(b==="string")f[V]=String(H);else if(b==="bool")f[V]=!!H;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let Y=Number(H);f[V]=(Number.isInteger(Y),Y)}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 st(t.warp,A,t.action,t.resolvedInputs,p,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 p=k(this.config,this.adapters,t.warp,t.action,a),l=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Ct(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,a),u=E(o,n),{action:d}=R(o),m=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,m,l,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let b=this.factory.getStringTypedInputs(e,i),H=await this.factory.getResolvedInputs(s.name,e,b,l,a.queries);f=await this.factory.getModifiedInputs(H)}let v=zt(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),y),T=$(f),O=P(this.config,s.name),x=this.factory.getSerializer(),{values:U,output:V}=await kt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:O,txHash:null,tx:null,next:k(this.config,this.adapters,o,n,V),values:U,output:V,messages:Ct(o,V,this.config),destination:null,resolvedInputs:T}}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 p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new N(this.config,l,this.adapters),{action:u}=R(t),d=this.factory.getStringTypedInputs(u,n),m=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(m),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Ft(e.when,f);return Ot(v)}};var ft=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 gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.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(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;C.info("Warp detect parse",{input:t,chain:i.chain,type:i.type,identifier:i.identifier,identifierBase:i.identifierBase});try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?Ut(t):Dt(i.identifier);if(this.resolver){let y=null;if(a==="hash")y=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;y=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}y&&(p=y.warp,l=y.registryInfo,o=y.brand)}else{let y=W(i.chain,this.adapters);if(a==="hash"){p=await y.builder().createFromTransactionHash(s,e);let f=await y.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await y.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await y.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(an(p,i.chain,l,i.identifier),p.meta.query=u?Lt(u):null),!p)return n;let d=p.chain||i.chain,m=W(d,this.adapters),g=await new N(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:g,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},an=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?vt(null,"alias",e.alias):vt(t,"hash",e?.hash??n))};var ie=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new tt(e));return new et(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new dt(this.config,this.chains,t)}async detectWarp(t,e){return new gt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:m}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await l.evaluateOutput(p,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(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??R(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=k(this.config,this.chains,e,a,p.output),p}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 ft(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 it(t,this.config)}};var ae=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,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
1
+ "use strict";var Me=Object.create;var ht=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var _e=(r,t)=>{for(var e in t)ht(r,e,{get:t[e],enumerable:!0})},pe=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ke(t))!Ge.call(r,i)&&i!==e&&ht(r,i,{get:()=>t[i],enumerable:!(n=qe(t,i))||n.enumerable});return r};var _=(r,t,e)=>(e=r!=null?Me(ze(r)):{},pe(t||!r||!r.__esModule?ht(e,"default",{value:r,enumerable:!0}):e,r)),Je=r=>pe(ht({},"__esModule",{value:!0}),r);var pn={};_e(pn,{BrowserCryptoProvider:()=>mt,CLOUD_WALLET_PROVIDERS:()=>ir,CacheTtl:()=>te,EvmWalletChainNames:()=>nr,NodeCryptoProvider:()=>yt,WARP_LANGUAGES:()=>mr,WarpBrandBuilder:()=>Kt,WarpBuilder:()=>Xt,WarpCache:()=>ct,WarpCacheKey:()=>bt,WarpChainName:()=>me,WarpChainResolver:()=>tt,WarpClient:()=>ie,WarpCompositeResolver:()=>et,WarpConfig:()=>D,WarpConstants:()=>c,WarpExecutor:()=>dt,WarpFactory:()=>G,WarpIndex:()=>ft,WarpInputTypes:()=>h,WarpInterpolator:()=>N,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>gt,WarpLogger:()=>C,WarpPlatformName:()=>Et,WarpPlatforms:()=>Rt,WarpProtocolVersions:()=>j,WarpSerializer:()=>w,WarpTypeRegistry:()=>ae,WarpValidator:()=>ot,address:()=>Xr,applyOutputToMessages:()=>Ct,asset:()=>Qt,biguint:()=>Qr,bool:()=>Kr,buildGeneratedFallbackWarpIdentifier:()=>Ee,buildGeneratedSourceWarpIdentifier:()=>Fr,buildInputsContext:()=>at,buildMappedOutput:()=>K,buildNestedPayload:()=>Ae,bytesToBase64:()=>ur,bytesToHex:()=>ye,checkWarpAssetBalance:()=>jr,cleanWarpIdentifier:()=>J,createAuthHeaders:()=>wt,createAuthMessage:()=>xt,createCryptoProvider:()=>fr,createDefaultWalletProvider:()=>Lr,createHttpAuthHeaders:()=>Nr,createSignableMessage:()=>Pe,createWarpI18nText:()=>Wr,createWarpIdentifier:()=>vt,doesWarpRequireWallet:()=>hr,evaluateOutputCommon:()=>qt,evaluateWhenCondition:()=>Ot,extractCollectOutput:()=>st,extractIdentifierInfoFromUrl:()=>Q,extractPromptOutput:()=>kt,extractQueryStringFromIdentifier:()=>Dt,extractQueryStringFromUrl:()=>Ut,extractResolvedInputValues:()=>$,extractWarpSecrets:()=>gr,findWarpAdapterForChain:()=>W,getCryptoProvider:()=>Bt,getEventNameFromWarp:()=>sr,getGeneratedSourceWarpName:()=>Se,getLatestProtocolIdentifier:()=>rt,getNextInfo:()=>k,getProviderConfig:()=>Rr,getRandomBytes:()=>$t,getRandomHex:()=>Vt,getRequiredAssetIds:()=>Re,getWalletFromConfigOrFail:()=>Qe,getWarpActionByIndex:()=>R,getWarpBrandLogoUrl:()=>or,getWarpChainAssetLogoUrl:()=>pr,getWarpChainInfoLogoUrl:()=>lr,getWarpIdentifierWithQuery:()=>wr,getWarpInfoFromIdentifier:()=>B,getWarpPrimaryAction:()=>b,getWarpWalletAddress:()=>le,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>de,getWarpWalletExternalIdFromConfig:()=>fe,getWarpWalletExternalIdFromConfigOrFail:()=>Ze,getWarpWalletMnemonic:()=>ue,getWarpWalletMnemonicFromConfig:()=>Xe,getWarpWalletPrivateKey:()=>ce,getWarpWalletPrivateKeyFromConfig:()=>Ke,handleX402Payment:()=>Jt,hasInputPrefix:()=>Ir,hex:()=>Zr,initializeWalletCache:()=>Dr,isEqualWarpIdentifier:()=>vr,isGeneratedSourcePrivateIdentifier:()=>Ur,isPlatformValue:()=>Ie,isWarpActionAutoExecute:()=>Wt,isWarpI18nText:()=>yr,isWarpWalletReadOnly:()=>Ye,mergeNestedPayload:()=>Mt,normalizeAndValidateMnemonic:()=>rr,normalizeMnemonic:()=>ge,option:()=>Yr,parseOutputOutIndex:()=>we,parseSignedMessage:()=>$r,parseWarpQueryStringToObject:()=>Lt,removeWarpChainPrefix:()=>xr,removeWarpWalletFromConfig:()=>er,replacePlaceholders:()=>L,replacePlaceholdersInWhenExpression:()=>Ft,resolvePlatformValue:()=>zt,resolveWarpText:()=>it,safeWindow:()=>Nt,setCryptoProvider:()=>cr,setWarpWalletInConfig:()=>tr,shiftBigintBy:()=>nt,splitInput:()=>At,stampGeneratedWarpMeta:()=>Or,string:()=>kr,struct:()=>en,testCryptoAvailability:()=>dr,toInputPayloadValue:()=>Ce,toPreviewText:()=>Ht,tuple:()=>tn,uint16:()=>Gr,uint32:()=>_r,uint64:()=>Jr,uint8:()=>zr,validateMnemonicLength:()=>he,validateSignedMessage:()=>Br,vector:()=>rn,withAdapterFallback:()=>ar});module.exports=Je(pn);var tt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var et=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var Qe=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},le=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>le(r.user?.wallets?.[t]||null),ce=r=>r?typeof r=="string"?r:r.privateKey||null:null,ue=r=>r?typeof r=="string"?r:r.mnemonic||null:null,de=r=>r?typeof r=="string"?r:r.externalId||null:null,Ke=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,Xe=(r,t)=>ue(r.user?.wallets?.[t]||null)?.trim()||null,fe=(r,t)=>de(r.user?.wallets?.[t]||null)?.trim()||null,Ze=(r,t)=>{let e=fe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},Ye=r=>typeof r=="string",tr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},er=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},ge=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},he=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},rr=(r,t=24)=>{let e=ge(r);return he(e,t),e};var me=(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))(me||{}),Et=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Et||{}),Rt=Object.values(Et),nr=["ethereum","base","arbitrum","polygon","somnia"],ir=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},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"},Nt=typeof window<"u"?window:{open:()=>{}};var j={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},D={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",c.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 ar=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var sr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var or=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},pr=(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]},lr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var mt=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}},yt=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 mt,M;if(typeof process<"u"&&process.versions?.node)return M=new yt,M;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){M=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 ye(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 ur(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 Vt(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 ye(e)}async function dr(){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 fr(){return Bt()}var gr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.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},rt=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}`)},R=(r,t)=>r?.actions[t-1],b=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}},Wt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=b(t);return r===e}return!0},nt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Ht=(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)=>{let i=t[n];return i==null?"":String(i)}),Ft=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),hr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Ot=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 mr={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"},it=(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""},yr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Wr=r=>r;var J=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,vr=(r,t)=>!r||!t?!1:J(r)===J(t),vt=(r,t,e)=>{let n=J(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},B=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=We(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.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[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Ar(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.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,Cr=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},We=r=>{let t=Cr(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=We(a);return[i,...s]},Ut=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},Dt=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},xr=(r,t)=>{let e=B(r,t);return(e?e.identifierBase:J(r)).trim()},wr=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var At=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Ir=r=>{let t=new Set(Object.values(h));if(!r.includes(c.ArgParamsSeparator))return!1;let e=At(r)[0];return t.has(e)};var Ct=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=it(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};var ve=_(require("qr-code-styling"),1);var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!Q(t,this.config.defaultChain):!1}build(t,e,n){let i=this.config.clientUrl||D.DefaultClientUrl(this.config.env),a=W(t,this.adapters),s=e===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return D.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}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",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new ve.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Pr="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Pr))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:jt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:jt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.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=l.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=p;for(let{regex:E,field:O}of g){let x=O?Sr(f,O):f;if(x==null)return null;v=v.replace(E,x)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${s}?${v}`:s;return{identifier:A,url:jt(t,A,r)}}).filter(f=>f!==null)},jt=(r,t,e)=>{let[n,i]=t.split("?"),a=B(n,e.defaultChain)||{chain:c.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 p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},Sr=(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 Ae(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.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 Ce(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=Ce(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=Ae(n.input.position,i,a);e=Mt(e,s)}else e[i]=a}),e}function at(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var xe=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=we(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},st=async(r,t,e,n,i,a)=>{let s=(d,m)=>m.reduce((g,y)=>g&&g[y]!==void 0?g[y]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=xe(r,e,p);return{values:{string:l,native:o,mapped:K(n,i)},output:await qt(r,u,t,e,n,i,a)}},qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=br(p,r,n,i,a),p=await Tr(r,p,e,i,a,s.transform?.runner||null),p},br=(r,t,e,n,i)=>{let a={...r},s=R(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(m=>m.as===o||m.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Tr=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:Er(e),inputs:at(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},Er=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=xe(r,e,s),u=await qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:u}},we=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 Ie=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Rt.some(t=>t in r),zt=(r,t)=>{if(!Ie(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Rr=(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 Pe(r,t,e,n=5){let i=await Vt(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 xt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Pe(r,i,e,5)}function wt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Nr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await xt(r,e,n),p=await t(i);return wt(r,p,a,s)}function Br(r){let t=new Date(r).getTime();return Date.now()<t}function $r(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 Se=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",Vr=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),be=(r,t=24)=>{let e=Vr(r);return e?e.slice(0,t):"action"},Te=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)},Hr=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()}},Fr=(r,t,e)=>{let n=be((e||t||"").trim()||"action"),i=`${r.type}|${Hr(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Te(i);return`private_src_${n}_${a}`},Ee=r=>{let t=Se(r),e=be(t),n=Te(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Or=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ee(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},Ur=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Dr(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 Lr(r,t,e){return null}var Re=(r,t)=>{let e=null;try{e=b(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},jr=async(r,t,e,n)=>{try{let i=W(e,n),a=Re(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};var Gt=require("@x402/core/client"),_t=require("@x402/core/http");async function Jt(r,t,e,n,i){let a=await Mr(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(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Mr=async(r,t)=>{let e=await qr(r),i=new _t.x402HTTPClient(new Gt.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 Gt.x402Client,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(m=>m?.network&&p[m.network]);if(!l?.network)continue;p[l.network]();let o=new _t.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},qr=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+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.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(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===h.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(h.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(h.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===h.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?h.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):h.Asset+c.ArgParamsSeparator+e.identifier+c.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+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===h.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[h.Option+c.ArgParamsSeparator+a,s||null]}if(n===h.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(h.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[h.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(h.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}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 p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,m]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${m}`)[1]}}),[n,p]}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(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.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 kr=r=>new w().nativeToString(h.String,r),zr=r=>new w().nativeToString(h.Uint8,r),Gr=r=>new w().nativeToString(h.Uint16,r),_r=r=>new w().nativeToString(h.Uint32,r),Jr=r=>new w().nativeToString(h.Uint64,r),Qr=r=>new w().nativeToString(h.Biguint,r),Kr=r=>new w().nativeToString(h.Bool,r),Xr=r=>new w().nativeToString(h.Address,r),Qt=r=>new w().nativeToString(h.Asset,r),Zr=r=>new w().nativeToString(h.Hex,r),Yr=(r,t)=>{if(t===null)return h.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return h.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},tn=(...r)=>new w().nativeToString(h.Tuple,r),en=r=>new w().nativeToString(h.Struct,r),rn=r=>new w().nativeToString(h.Vector,r);var Ne=_(require("ajv"),1);var Kt=class{constructor(t){this.pendingBrand={protocol:rt("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||D.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Ne.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var Be=_(require("ajv"),1);var ot=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}=b(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||D.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Be.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 Xt=class{constructor(t){this.config=t;this.pendingWarp={protocol:rt("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 Ht(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 ot(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var I=require("fs"),Z=require("path");var Zt="$bigint:",It=(r,t)=>typeof t=="bigint"?Zt+t.toString():t,X=(r,t)=>typeof t=="string"&&t.startsWith(Zt)?BigInt(t.slice(Zt.length)):t;var Pt=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,I.existsSync)(this.cacheDir)||(0,I.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,Z.join)(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!(0,I.existsSync)(e))return null;let n=(0,I.readFileSync)(e,"utf-8"),i=JSON.parse(n,X);return i.expiresAt!==null&&Date.now()>i.expiresAt?((0,I.unlinkSync)(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);(0,I.writeFileSync)(a,JSON.stringify(i,It),"utf-8")}async delete(t){try{let e=this.getFilePath(t);(0,I.existsSync)(e)&&(0,I.unlinkSync)(e)}catch{}}async keys(t){try{let e=(0,I.readdirSync)(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{(0,I.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,I.unlinkSync)((0,Z.join)(this.cacheDir,e))})}catch{}}};var pt=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,X);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,It))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var F=class F{constructor(t,e){}async get(t){let e=F.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(F.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;F.cache.set(t,{value:e,expiresAt:i})}async delete(t){F.cache.delete(t)}async keys(t){let e=Array.from(F.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){F.cache.clear()}};F.cache=new Map;var lt=F;var $e=require("fs"),Yt=require("path");var St=class{constructor(t,e){let n=e?.path?(0,Yt.resolve)(e.path):(0,Yt.resolve)(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=(0,$e.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}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var te={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},bt={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}`},ct=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new pt(t,e):e?.type==="memory"?new lt(t,e):e?.type==="static"?new St(t,e):e?.type==="filesystem"?new Pt(t,e):typeof window<"u"&&window.localStorage?new pt(t,e):new lt(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var ut={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},ee={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},re=(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)},ne=r=>{try{return JSON.parse(r)}catch{return null}},nn=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await xt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(wt(n,d,o,u)).forEach(([m,g])=>s.set(m,g))}let p=re(e.resolvedInputs,ut.Headers,i);if(p){let l=ne(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},an=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===ee.Get){let s=re(e.resolvedInputs,ut.Queries,i);if(s){let p=ne(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},sn=(r,t,e,n,i)=>{if(r===ee.Get)return;let a=re(t.resolvedInputs,ut.Payload,n);if(a&&ne(a)!==null)return a;let{[ut.Payload]:s,[ut.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},Ve=async(r,t,e,n,i,a,s,p)=>{let l=t.method||ee.Get,o=await nn(r,t,e,n,a,p),u=an(r,t,e,l,a),d=sn(l,e,i,a,s);return{url:u,method:l,headers:o,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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),m={...this.config.vars,...e.envs}?.[o];m!=null&&a(s,m)}else p===c.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.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(c.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(c.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(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),u={config:this.config,adapter:o},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,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.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 ct(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(bt.WarpExecutable(t,e||"",n))||[];return $(i)}async createExecutable(t,e,n,i={}){let a=R(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=W(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,i),u=R(o,e),{action:d,index:m}=b(o),g=this.getStringTypedInputs(d,n),y=await this.getResolvedInputs(s.name,d,g,l,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,l,i.queries),A=await this.getModifiedInputs(v));let E=A.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,O=this.getDestinationFromAction(u),x=E?this.serializer.stringToNative(E)[1]:O;if(x&&(x=l.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let U=this.getPreparedArgs(u,A);U=U.map(S=>l.applyInputs(S,A,this.serializer,f));let V=A.find(S=>S.input.position==="value")?.value||null,T="value"in u?u.value:null,H=V?.split(c.ArgParamsSeparator)[1]||T||"0",Y=l.applyInputs(H,A,this.serializer,f),He=BigInt(Y),Fe=A.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),Oe=[...("transfers"in u?u.transfers:[])||[],...Fe||[]].map(S=>{let Tt=l.applyInputs(S,A,this.serializer,f),je=Tt.startsWith(`asset${c.ArgParamsSeparator}`)?Tt:`asset${c.ArgParamsSeparator}${Tt}`;return this.serializer.stringToNative(je)[1]}),Ue=A.find(S=>S.input.position==="data")?.value,De="data"in u?u.data||"":null,se=Ue||De||null,Le=se?l.applyInputs(se,A,this.serializer,f):null,oe={adapter:p,warp:o,chain:s,action:e,destination:x,args:U,value:He,transfers:Oe,data:Le,resolvedInputs:A};return await this.cache.set(bt.WarpExecutable(this.config.env,o.meta?.hash||"",e),oe.resolvedInputs,te.OneWeek),oe}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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(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(l[d])return l[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=o(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(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=nt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=nt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=at(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=At(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=nt(p,o.decimals);return Qt({...o,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[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let 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",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var dt=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=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:m}=b(t);for(let g=1;g<=t.actions.length;g++){let y=R(t,g);if(!Wt(y,t))continue;let{tx:f,chain:v,immediateExecution:A,executable:E}=await this.executeAction(t,g,e,u);f&&i.push(f),v&&(a=v),A&&s.push(A),E&&g===m+1&&E.resolvedInputs&&(p=$(E.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:p}}async executeAction(t,e,n,i={}){let a=R(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Nt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),m={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:m})),m}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=k(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):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(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=R(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:p,output:l}=await st(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,a){let s=new N(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await Ve(s,e,t,n,i,p,a,async m=>await this.callHandler(()=>this.handlers?.onSignRequest?.(m)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await Jt(g,l,o,d,this.adapters));let y=await g.json();C.debug("Collect response content",{content:y});let{values:f,output:v}=await st(t.warp,y,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",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=P(this.config,t.chain.name),i=R(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 p=this.factory.getSerializer(),l=new N(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),m={};o.headers&&Object.entries(o.headers).forEach(([g,y])=>{let f=l.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:U})=>{if(U&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let V=x.position.replace("payload:",""),[T,H]=p.stringToNative(U);if(T==="string")f[V]=String(H);else if(T==="bool")f[V]=!!H;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let Y=Number(H);f[V]=(Number.isInteger(Y),Y)}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:E,output:O}=await st(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",E,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 p=k(this.config,this.adapters,t.warp,t.action,a),l=$(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Ct(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new N(this.config,p,this.adapters),o=await l.apply(t,a),u=R(o,n),{action:d}=b(o),m=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,m,l,a.queries),y=await this.factory.getModifiedInputs(g),f=y;if(e.inputs&&e.inputs.length>0){let T=this.factory.getStringTypedInputs(e,i),H=await this.factory.getResolvedInputs(s.name,e,T,l,a.queries);f=await this.factory.getModifiedInputs(H)}let v=zt(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),y),E=$(f),O=P(this.config,s.name),x=this.factory.getSerializer(),{values:U,output:V}=await kt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:O,txHash:null,tx:null,next:k(this.config,this.adapters,o,n,V),values:U,output:V,messages:Ct(o,V,this.config),destination:null,resolvedInputs:E}}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 p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new N(this.config,l,this.adapters),{action:u}=b(t),d=this.factory.getStringTypedInputs(u,n),m=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(m),y;if(a)y=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);y=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(y,this.factory.getSerializer(),g),v=Ft(e.when,f);return Ot(v)}};var ft=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 gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.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(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?Q(t,this.config.defaultChain):B(t,this.config.defaultChain);if(!i)return n;C.info("Warp detect parse",{input:t,chain:i.chain,type:i.type,identifier:i.identifier,identifierBase:i.identifierBase});try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?Ut(t):Dt(i.identifier);if(this.resolver){let y=null;if(a==="hash")y=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;y=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}y&&(p=y.warp,l=y.registryInfo,o=y.brand)}else{let y=W(i.chain,this.adapters);if(a==="hash"){p=await y.builder().createFromTransactionHash(s,e);let f=await y.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await y.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await y.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(on(p,i.chain,l,i.identifier),p.meta.query=u?Lt(u):null),!p)return n;let d=p.chain||i.chain,m=W(d,this.adapters),g=await new N(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:g,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},on=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?vt(null,"alias",e.alias):vt(t,"hash",e?.hash??n))};var ie=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new tt(e));return new et(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new dt(this.config,this.chains,t)}async detectWarp(t,e){return new gt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await y.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:m}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async y=>{await l.evaluateOutput(p,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(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??b(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=k(this.config,this.chains,e,a,p.output),p}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 ft(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 it(t,this.config)}};var ae=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,CLOUD_WALLET_PROVIDERS,CacheTtl,EvmWalletChainNames,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpChainResolver,WarpClient,WarpCompositeResolver,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpPlatformName,WarpPlatforms,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildGeneratedFallbackWarpIdentifier,buildGeneratedSourceWarpIdentifier,buildInputsContext,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,checkWarpAssetBalance,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,doesWarpRequireWallet,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractPromptOutput,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getGeneratedSourceWarpName,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getRequiredAssetIds,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpIdentifierWithQuery,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isGeneratedSourcePrivateIdentifier,isPlatformValue,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,parseWarpQueryStringToObject,removeWarpChainPrefix,removeWarpWalletFromConfig,replacePlaceholders,replacePlaceholdersInWhenExpression,resolvePlatformValue,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,stampGeneratedWarpMeta,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var tt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var et=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var lr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Ce=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Ce(r.user?.wallets?.[t]||null),xe=r=>r?typeof r=="string"?r:r.privateKey||null:null,we=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ie=r=>r?typeof r=="string"?r:r.externalId||null:null,cr=(r,t)=>xe(r.user?.wallets?.[t]||null)?.trim()||null,ur=(r,t)=>we(r.user?.wallets?.[t]||null)?.trim()||null,Pe=(r,t)=>Ie(r.user?.wallets?.[t]||null)?.trim()||null,dr=(r,t)=>{let e=Pe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},fr=r=>typeof r=="string",gr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},hr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Se=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},be=(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`)},mr=(r,t=24)=>{let e=Se(r);return be(e,t),e};var Te=(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))(Te||{}),Vt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Vt||{}),Ht=Object.values(Vt),vr=["ethereum","base","arbitrum","polygon","somnia"],Ar=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},y={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Ft=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",c.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 Ir=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var br=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Er=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Rr=(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]},Nr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var mt=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}},yt=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 Ot(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new mt,D;if(typeof process<"u"&&process.versions?.node)return D=new yt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function $r(r){D=r}async function Ut(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Ot()).getRandomBytes(r)}function Ee(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 Vr(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 Dt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ut(r/2,t);return Ee(e)}async function Hr(){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 Ut(16),r.randomBytes=!0}catch{}return r}function Fr(){return Ot()}var Dr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.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},rt=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}},Wt=(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},nt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Lt=(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)=>{let i=t[n];return i==null?"":String(i)}),jt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),kr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Mt=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 Gr={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"},it=(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""},_r=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Jr=r=>r;var J=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Zr=(r,t)=>!r||!t?!1:J(r)===J(t),vt=(r,t,e)=>{let n=J(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},$=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=qt(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.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[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Re(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return $(a,t)},Re=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ne=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},qt=r=>{let t=Ne(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=qt(a);return[i,...s]},kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},zt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},Yr=(r,t)=>{let e=$(r,t);return(e?e.identifierBase:J(r)).trim()},tn=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var At=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},nn=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=At(r)[0];return t.has(e)};var Ct=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=it(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Be from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.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===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=$(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",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Be({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var $e="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith($e))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:xt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:xt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.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=l.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=p;for(let{regex:b,field:F}of g){let x=F?Ve(f,F):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:xt(t,A,r)}}).filter(f=>f!==null)},xt=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n,e.defaultChain)||{chain:c.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 p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},Ve=(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 He(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function _t(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]=_t(e[n],t[n]):e[n]=t[n]}),e}function Fe(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 V(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=Fe(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=He(n.input.position,i,a);e=_t(e,s)}else e[i]=a}),e}function at(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Jt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=Le(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},st=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,m)=>g&&g[m]!==void 0?g[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Jt(r,e,p);return{values:{string:l,native:o,mapped:K(n,i)},output:await Qt(r,u,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Oe(p,r,n,i,a),p=await Ue(r,p,e,i,a,s.transform?.runner||null),p},Oe=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ue=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:De(e),inputs:at(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},De=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Jt(r,e,s),u=await Qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:u}},Le=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var je=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ht.some(t=>t in r),Xt=(r,t)=>{if(!je(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var $n=(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 Me(r,t,e,n=5){let i=await Dt(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 wt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Me(r,i,e,5)}function It(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function On(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await wt(r,e,n),p=await t(i);return It(r,p,a,s)}function Un(r){let t=new Date(r).getTime();return Date.now()<t}function Dn(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 qe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",ke=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Zt=(r,t=24)=>{let e=ke(r);return e?e.slice(0,t):"action"},Yt=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},ze=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},jn=(r,t,e)=>{let n=Zt((e||t||"").trim()||"action"),i=`${r.type}|${ze(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Yt(i);return`private_src_${n}_${a}`},Ge=r=>{let t=qe(r),e=Zt(t),n=Yt(t.trim().toLowerCase());return`private_gen_${e}_${n}`},Mn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ge(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},qn=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function zn(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 _n(r,t,e){return null}import{x402Client as te}from"@x402/core/client";import{x402HTTPClient as ee}from"@x402/core/http";async function re(r,t,e,n,i){let a=await _e(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(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var _e=async(r,t)=>{let e=await Je(r),i=new ee(new te).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 te,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(h=>h?.network&&p[h.network]);if(!l?.network)continue;p[l.network]();let o=new ee(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},Je=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===y.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===y.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===y.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.Asset+c.ArgParamsSeparator+e.identifier+c.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+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(y.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var ni=r=>new w().nativeToString(y.String,r),ii=r=>new w().nativeToString(y.Uint8,r),ai=r=>new w().nativeToString(y.Uint16,r),si=r=>new w().nativeToString(y.Uint32,r),oi=r=>new w().nativeToString(y.Uint64,r),pi=r=>new w().nativeToString(y.Biguint,r),li=r=>new w().nativeToString(y.Bool,r),ci=r=>new w().nativeToString(y.Address,r),ne=r=>new w().nativeToString(y.Asset,r),ui=r=>new w().nativeToString(y.Hex,r),di=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},fi=(...r)=>new w().nativeToString(y.Tuple,r),gi=r=>new w().nativeToString(y.Struct,r),hi=r=>new w().nativeToString(y.Vector,r);import Qe from"ajv";var ie=class{constructor(t){this.pendingBrand={protocol:rt("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 Qe,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Ke from"ajv";var ot=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 Ke({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 ae=class{constructor(t){this.config=t;this.pendingWarp={protocol:rt("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 Lt(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 ot(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as St,mkdirSync as Xe,readdirSync as se,readFileSync as Ze,unlinkSync as bt,writeFileSync as Ye}from"fs";import{join as oe,resolve as pe}from"path";var Pt="$bigint:",pt=(r,t)=>typeof t=="bigint"?Pt+t.toString():t,z=(r,t)=>typeof t=="string"&&t.startsWith(Pt)?BigInt(t.slice(Pt.length)):t;var lt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?pe(n):pe(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){St(this.cacheDir)||Xe(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return oe(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!St(e))return null;let n=Ze(e,"utf-8"),i=JSON.parse(n,z);return i.expiresAt!==null&&Date.now()>i.expiresAt?(bt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);Ye(a,JSON.stringify(i,pt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);St(e)&&bt(e)}catch{}}async keys(t){try{let e=se(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{se(this.cacheDir).forEach(e=>{e.endsWith(".json")&&bt(oe(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,z);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,pt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var Z=H;import{readFileSync as tr}from"fs";import{resolve as le}from"path";var ct=class{constructor(t,e){let n=e?.path?le(e.path):le(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=tr(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}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ce={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Tt={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}`},ut=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new ct(t,e):e?.type==="filesystem"?new lt(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Et={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Rt=(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)},Nt=r=>{try{return JSON.parse(r)}catch{return null}},er=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await wt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(It(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=Rt(e.resolvedInputs,Y.Headers,i);if(p){let l=Nt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},rr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Et.Get){let s=Rt(e.resolvedInputs,Y.Queries,i);if(s){let p=Nt(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},nr=(r,t,e,n,i)=>{if(r===Et.Get)return;let a=Rt(t.resolvedInputs,Y.Payload,n);if(a&&Nt(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},ue=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Et.Get,o=await er(r,t,e,n,a,p),u=rr(r,t,e,l,a),d=nr(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===c.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.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(c.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(c.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(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),u={config:this.config,adapter:o},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,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.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 ut(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Tt.WarpExecutable(t,e||"",n))||[];return V(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),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),u=T(o,e),{action:d,index:h}=E(o),g=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,g,l,i.queries),f=await this.getModifiedInputs(m),v=[],A=[];h===e-1?(v=m,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),A=await this.getModifiedInputs(v));let b=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,F=this.getDestinationFromAction(u),x=b?this.serializer.stringToNative(b)[1]:F;if(x&&(x=l.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(I=>l.applyInputs(I,A,this.serializer,f));let N=A.find(I=>I.input.position==="value")?.value||null,S="value"in u?u.value:null,B=N?.split(c.ArgParamsSeparator)[1]||S||"0",_=l.applyInputs(B,A,this.serializer,f),ge=BigInt(_),he=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),me=[...("transfers"in u?u.transfers:[])||[],...he||[]].map(I=>{let ht=l.applyInputs(I,A,this.serializer,f),Ae=ht.startsWith(`asset${c.ArgParamsSeparator}`)?ht:`asset${c.ArgParamsSeparator}${ht}`;return this.serializer.stringToNative(Ae)[1]}),ye=A.find(I=>I.input.position==="data")?.value,We="data"in u?u.data||"":null,Bt=ye||We||null,ve=Bt?l.applyInputs(Bt,A,this.serializer,f):null,$t={adapter:p,warp:o,chain:s,action:e,destination:x,args:O,value:ge,transfers:me,data:ve,resolvedInputs:A};return await this.cache.set(Tt.WarpExecutable(this.config.env,o.meta?.hash||"",e),$t.resolvedInputs,ce.OneWeek),$t}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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(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(l[d])return l[d];let h=u.as||u.name,g=a?.[h],m=this.url.searchParams.get(h),f=g||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(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(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=nt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=nt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=at(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=At(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=nt(p,o.decimals);return ne({...o,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[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let 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",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var dt=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=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=E(t);for(let g=1;g<=t.actions.length;g++){let m=T(t,g);if(!Wt(m,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&&(p=V(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:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Ft.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=k(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):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(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=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:p,output:l}=await st(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await ue(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await re(g,l,o,d,this.adapters));let m=await g.json();C.debug("Collect response content",{content:m});let{values:f,output:v}=await st(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",f,v,m)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=V(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let g=V(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 m=V(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:m}}let p=this.factory.getSerializer(),l=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,m])=>{let f=l.applyInputs(m,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}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:O})=>{if(O&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let N=x.position.replace("payload:",""),[S,B]=p.stringToNative(O);if(S==="string")f[N]=String(B);else if(S==="bool")f[N]=!!B;else if(S==="uint8"||S==="uint16"||S==="uint32"||S==="uint64"||S==="uint128"||S==="uint256"||S==="biguint"){let _=Number(B);f[N]=(Number.isInteger(_),_)}else f[N]=B}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.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:F}=await st(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,F,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let m=V(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:m}}}buildCollectResult(t,e,n,i,a,s){let p=k(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Ct(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,a),u=T(o,n),{action:d}=E(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,l,a.queries),m=await this.factory.getModifiedInputs(g),f=m;if(e.inputs&&e.inputs.length>0){let S=this.factory.getStringTypedInputs(e,i),B=await this.factory.getResolvedInputs(s.name,e,S,l,a.queries);f=await this.factory.getModifiedInputs(B)}let v=Xt(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),m),b=V(f),F=P(this.config,s.name),x=this.factory.getSerializer(),{values:O,output:N}=await Kt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:F,txHash:null,tx:null,next:k(this.config,this.adapters,o,n,N),values:O,output:N,messages:Ct(o,N,this.config),destination:null,resolvedInputs:b}}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 p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new R(this.config,l,this.adapters),{action:u}=E(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),m;if(a)m=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(m,this.factory.getSerializer(),g),v=jt(e.when,f);return Mt(v)}};var ft=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 gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.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(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?Q(t,this.config.defaultChain):$(t,this.config.defaultChain);if(!i)return n;C.info("Warp detect parse",{input:t,chain:i.chain,type:i.type,identifier:i.identifier,identifierBase:i.identifierBase});try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?kt(t):zt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(ir(p,i.chain,l,i.identifier),p.meta.query=u?Gt(u):null),!p)return n;let d=p.chain||i.chain,h=W(d,this.adapters),g=await new R(this.config,h,this.adapters).apply(p);return{match:!0,url:t,warp:g,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},ir=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?vt(null,"alias",e.alias):vt(t,"hash",e?.hash??n))};var de=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new tt(e));return new et(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new dt(this.config,this.chains,t)}async detectWarp(t,e){return new gt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async m=>{await l.evaluateOutput(p,m)},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=$(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(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??E(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=k(this.config,this.chains,e,a,p.output),p}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 ft(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 it(t,this.config)}};var fe=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{mt as BrowserCryptoProvider,Ar as CLOUD_WALLET_PROVIDERS,ce as CacheTtl,vr as EvmWalletChainNames,yt as NodeCryptoProvider,Gr as WARP_LANGUAGES,ie as WarpBrandBuilder,ae as WarpBuilder,ut as WarpCache,Tt as WarpCacheKey,Te as WarpChainName,tt as WarpChainResolver,de as WarpClient,et as WarpCompositeResolver,U as WarpConfig,c as WarpConstants,dt as WarpExecutor,G as WarpFactory,ft as WarpIndex,y as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,gt as WarpLinkDetecter,C as WarpLogger,Vt as WarpPlatformName,Ht as WarpPlatforms,M as WarpProtocolVersions,w as WarpSerializer,fe as WarpTypeRegistry,ot as WarpValidator,ci as address,Ct as applyOutputToMessages,ne as asset,pi as biguint,li as bool,Ge as buildGeneratedFallbackWarpIdentifier,jn as buildGeneratedSourceWarpIdentifier,at as buildInputsContext,K as buildMappedOutput,He as buildNestedPayload,Vr as bytesToBase64,Ee as bytesToHex,J as cleanWarpIdentifier,It as createAuthHeaders,wt as createAuthMessage,Fr as createCryptoProvider,_n as createDefaultWalletProvider,On as createHttpAuthHeaders,Me as createSignableMessage,Jr as createWarpI18nText,vt as createWarpIdentifier,kr as doesWarpRequireWallet,Qt as evaluateOutputCommon,Mt as evaluateWhenCondition,st as extractCollectOutput,Q as extractIdentifierInfoFromUrl,Kt as extractPromptOutput,zt as extractQueryStringFromIdentifier,kt as extractQueryStringFromUrl,V as extractResolvedInputValues,Dr as extractWarpSecrets,W as findWarpAdapterForChain,Ot as getCryptoProvider,br as getEventNameFromWarp,qe as getGeneratedSourceWarpName,rt as getLatestProtocolIdentifier,k as getNextInfo,$n as getProviderConfig,Ut as getRandomBytes,Dt as getRandomHex,lr as getWalletFromConfigOrFail,T as getWarpActionByIndex,Er as getWarpBrandLogoUrl,Rr as getWarpChainAssetLogoUrl,Nr as getWarpChainInfoLogoUrl,tn as getWarpIdentifierWithQuery,$ as getWarpInfoFromIdentifier,E as getWarpPrimaryAction,Ce as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ie as getWarpWalletExternalId,Pe as getWarpWalletExternalIdFromConfig,dr as getWarpWalletExternalIdFromConfigOrFail,we as getWarpWalletMnemonic,ur as getWarpWalletMnemonicFromConfig,xe as getWarpWalletPrivateKey,cr as getWarpWalletPrivateKeyFromConfig,re as handleX402Payment,nn as hasInputPrefix,ui as hex,zn as initializeWalletCache,Zr as isEqualWarpIdentifier,qn as isGeneratedSourcePrivateIdentifier,je as isPlatformValue,Wt as isWarpActionAutoExecute,_r as isWarpI18nText,fr as isWarpWalletReadOnly,_t as mergeNestedPayload,mr as normalizeAndValidateMnemonic,Se as normalizeMnemonic,di as option,Le as parseOutputOutIndex,Dn as parseSignedMessage,Gt as parseWarpQueryStringToObject,Yr as removeWarpChainPrefix,hr as removeWarpWalletFromConfig,L as replacePlaceholders,jt as replacePlaceholdersInWhenExpression,Xt as resolvePlatformValue,it as resolveWarpText,Ft as safeWindow,$r as setCryptoProvider,gr as setWarpWalletInConfig,nt as shiftBigintBy,At as splitInput,Mn as stampGeneratedWarpMeta,ni as string,gi as struct,Hr as testCryptoAvailability,Fe as toInputPayloadValue,Lt as toPreviewText,fi as tuple,ai as uint16,si as uint32,oi as uint64,ii as uint8,be as validateMnemonicLength,Un as validateSignedMessage,hi as vector,Ir as withAdapterFallback};
1
+ var tt=class{constructor(t){this.adapter=t}async getByAlias(t,e){try{let{registryInfo:n,brand:i}=await this.adapter.registry.getInfoByAlias(t,e);if(!n)return null;let a=await this.adapter.builder().createFromTransactionHash(n.hash,e);return a?{warp:a,brand:i,registryInfo:n}:null}catch{return null}}async getByHash(t,e){try{let n=await this.adapter.builder().createFromTransactionHash(t,e);if(!n)return null;let{registryInfo:i,brand:a}=await this.adapter.registry.getInfoByHash(t,e);return{warp:n,brand:a,registryInfo:i}}catch{return null}}};var et=class{constructor(t){this.resolvers=t}async getByAlias(t,e){for(let n of this.resolvers){let i=await n.getByAlias(t,e);if(i)return i}return null}async getByHash(t,e){for(let n of this.resolvers){let i=await n.getByHash(t,e);if(i)return i}return null}};var cr=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Ce=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>Ce(r.user?.wallets?.[t]||null),xe=r=>r?typeof r=="string"?r:r.privateKey||null:null,we=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ie=r=>r?typeof r=="string"?r:r.externalId||null:null,ur=(r,t)=>xe(r.user?.wallets?.[t]||null)?.trim()||null,dr=(r,t)=>we(r.user?.wallets?.[t]||null)?.trim()||null,Pe=(r,t)=>Ie(r.user?.wallets?.[t]||null)?.trim()||null,fr=(r,t)=>{let e=Pe(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},gr=r=>typeof r=="string",hr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},mr=(r,t)=>{r.user?.wallets&&delete r.user.wallets[t]},Se=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},be=(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`)},yr=(r,t=24)=>{let e=Se(r);return be(e,t),e};var Te=(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))(Te||{}),Vt=(n=>(n.Macos="macos",n.Linux="linux",n.Windows="windows",n))(Vt||{}),Ht=Object.values(Vt),Ar=["ethereum","base","arbitrum","polygon","somnia"],Cr=["coinbase","privy","gaupa"],c={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>P(r.config,r.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},y={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Ft=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",c.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 Pr=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Tr=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Rr=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Nr=(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]},Br=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var mt=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}},yt=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 Ot(){if(D)return D;if(typeof window<"u"&&window.crypto)return D=new mt,D;if(typeof process<"u"&&process.versions?.node)return D=new yt,D;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Vr(r){D=r}async function Ut(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Ot()).getRandomBytes(r)}function Ee(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 Hr(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 Dt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Ut(r/2,t);return Ee(e)}async function Fr(){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 Ut(16),r.randomBytes=!0}catch{}return r}function Or(){return Ot()}var Lr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let e=t.replace(`${c.Vars.Env}:`,"").trim(),[n,i]=e.split(c.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},rt=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],b=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}},Wt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=b(t);return r===e}return!0},nt=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Lt=(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)=>{let i=t[n];return i==null?"":String(i)}),jt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),zr=r=>{let t=r.actions.some(e=>["transfer","contract"].includes(e.type)?!0:(e.inputs??[]).some(n=>n.source===c.Source.UserWallet||n.default===`{{${c.Globals.UserWallet.Placeholder}}}`||n.default===`{{${c.Globals.UserWalletPublicKey.Placeholder}}}`));return{required:t,chain:t?r.chain??null:null}},Mt=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 _r={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"},it=(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""},Jr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,Qr=r=>r;var J=r=>r.startsWith(c.IdentifierAliasMarker)?r.replace(c.IdentifierAliasMarker,""):r,Yr=(r,t)=>!r||!t?!1:J(r)===J(t),vt=(r,t,e)=>{let n=J(e);if(t===c.IdentifierType.Alias)return c.IdentifierAliasMarker+n;if(!r)throw new Error("Chain is required for hash warp identifiers");return r+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+n},$=(r,t)=>{let e=t||c.IdentifierChainDefault,n=decodeURIComponent(r).trim(),i=J(n),a=i.split("?")[0],s=qt(a);if(a.length===64&&/^[a-fA-F0-9]+$/.test(a))return{chain:e,type:c.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[p,l,o]=s;if(l===c.IdentifierType.Alias||l===c.IdentifierType.Hash){let u=i.includes("?")?o+i.substring(i.indexOf("?")):o;return{chain:p,type:l,identifier:u,identifierBase:o}}}if(s.length===2){let[p,l]=s;if(p===c.IdentifierType.Alias||p===c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l;return{chain:e,type:p,identifier:o,identifierBase:l}}}if(s.length===2){let[p,l]=s;if(p!==c.IdentifierType.Alias&&p!==c.IdentifierType.Hash){let o=i.includes("?")?l+i.substring(i.indexOf("?")):l,u=Re(l,p)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:p,type:u,identifier:o,identifierBase:l}}}return{chain:e,type:c.IdentifierType.Alias,identifier:i,identifierBase:a}},Q=(r,t)=>{let e=new URL(r),i=e.searchParams.get(c.IdentifierParamName);if(i||(i=e.pathname.split("/")[1]),!i)return null;let a=decodeURIComponent(i);return $(a,t)},Re=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Ne=r=>{let t=c.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},qt=r=>{let t=Ne(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=qt(a);return[i,...s]},kt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(c.IdentifierParamName),e.toString()||null}catch{return null}},zt=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null},Gt=r=>{if(!r)return{};let t=r.startsWith("?")?r.slice(1):r;if(!t)return{};let e=new URLSearchParams(t),n={};return e.forEach((i,a)=>{n[a]=i}),n},tn=(r,t)=>{let e=$(r,t);return(e?e.identifierBase:J(r)).trim()},en=r=>{let t=r.meta?.identifier;if(!t)return"";let e=r.meta?.query;if(e&&typeof e=="object"&&Object.keys(e).length>0){let n=new URLSearchParams(e);return`${t}?${n.toString()}`}return t};var At=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},an=r=>{let t=new Set(Object.values(y));if(!r.includes(c.ArgParamsSeparator))return!1;let e=At(r)[0];return t.has(e)};var Ct=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=it(a,e);return[i,L(s,t)]});return Object.fromEntries(n)};import Be from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(c.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===c.IdentifierType.Alias?n:e+c.IdentifierParamSeparator+n,p=a.chainInfo.name+c.IdentifierParamSeparator+s,l=encodeURIComponent(p);return U.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${c.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let e=$(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",p="#23F7DD"){let l=W(t,this.adapters),o=this.build(l.chainInfo.name,e,n);return new Be({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var $e="https://",k=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith($e))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=L(s,{...e.vars,...i});return[{identifier:f,url:xt(t,f,r)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let f=L(p,{...e.vars,...i}),v=f?`${s}?${f}`:s;return[{identifier:v,url:xt(t,v,r)}]}let o=l[0];if(!o)return[];let u=o.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=l.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=p;for(let{regex:T,field:F}of g){let x=F?Ve(f,F):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:xt(t,A,r)}}).filter(f=>f!==null)},xt=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n,e.defaultChain)||{chain:c.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 p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((o,u)=>l.searchParams.set(u,o)),l.toString().replace(/\/\?/,"?")},Ve=(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 He(r,t,e){return r.startsWith(c.Position.Payload)?r.slice(c.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function _t(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]=_t(e[n],t[n]):e[n]=t[n]}),e}function Fe(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 V(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=Fe(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(c.Position.Payload)){let s=He(n.input.position,i,a);e=_t(e,s)}else e[i]=a}),e}function at(r,t,e,n){let i={},a=e!==void 0?e:r.length,s=p=>{if(!p?.value)return;let l=p.input.as||p.input.name,[,o]=t.stringToNative(p.value);if(i[l]=o,p.input.type!=="asset"||typeof o!="object"||o===null)return;let u=o;if("identifier"in u&&"amount"in u){let d=String(u.identifier);i[`${l}.token`]=d,i[`${l}.identifier`]=d,i[`${l}.amount`]=String(u.amount)}};for(let p=0;p<a;p++)s(r[p]);return s(n),i}var Jt=(r,t,e)=>{let n=[],i=[],a={};if(r.output)for(let[s,p]of Object.entries(r.output)){if(p.startsWith(c.Transform.Prefix))continue;let l=Le(p);if(l!==null&&l!==t){a[s]=null;continue}let[o,...u]=p.split(".");if(o==="out"||o.startsWith("out[")||o==="$"){let d=e(u);n.push(String(d)),i.push(d),a[s]=d}else a[s]=p}return{stringValues:n,nativeValues:i,output:a}},st=async(r,t,e,n,i,a)=>{let s=(d,h)=>h.reduce((g,m)=>g&&g[m]!==void 0?g[m]:null,d),p=d=>d.length===0?t:s(t,d),{stringValues:l,nativeValues:o,output:u}=Jt(r,e,p);return{values:{string:l,native:o,mapped:K(n,i)},output:await Qt(r,u,t,e,n,i,a)}},Qt=async(r,t,e,n,i,a,s)=>{if(!r.output)return t;let p={...t};return p=Oe(p,r,n,i,a),p=await Ue(r,p,e,i,a,s.transform?.runner||null),p},Oe=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("in.")){let o=l.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ue=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t},p=Object.entries(r.output).filter(([,o])=>o.startsWith(c.Transform.Prefix)).map(([o,u])=>({key:o,code:u.substring(c.Transform.Prefix.length)}));if(p.length>0&&(!a||typeof a.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let l={...s,out:De(e),inputs:at(n,i)};for(let{key:o,code:u}of p)try{s[o]=await a.run(u,l),l[o]=s[o]}catch(d){C.error(`Transform error for Warp '${r.name}' with output '${o}':`,d),s[o]=null,l[o]=null}return s},De=r=>{if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))return r;let t=[...r.data];return t.data=r.data,t},Kt=async(r,t,e,n,i,a)=>{let s=d=>d.length===0?t:null,{stringValues:p,nativeValues:l,output:o}=Jt(r,e,s),u=await Qt(r,o,t,e,n,i,a);return"PROMPT"in u||(u.PROMPT=t),{values:{string:p,native:l,mapped:K(n,i)},output:u}},Le=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var je=r=>r==null||typeof r!="object"||Array.isArray(r)?!1:Ht.some(t=>t in r),Xt=(r,t)=>{if(!je(r))return r;if(!t)throw new Error("Platform-specific value requires platform in client config");let e=r[t];if(e===void 0)throw new Error(`Warp does not support platform: ${t}`);return e};var Vn=(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 Me(r,t,e,n=5){let i=await Dt(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 wt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Me(r,i,e,5)}function It(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Un(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await wt(r,e,n),p=await t(i);return It(r,p,a,s)}function Dn(r){let t=new Date(r).getTime();return Date.now()<t}function Ln(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 qe=r=>typeof r.name=="string"&&r.name.trim()?r.name.trim():typeof r.title=="string"&&r.title.trim()?r.title.trim():"generated-warp",ke=r=>r.normalize("NFKD").replace(/[^\w\s-]/g,"").toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),Zt=(r,t=24)=>{let e=ke(r);return e?e.slice(0,t):"action"},Yt=r=>{let t=3735928559^r.length,e=1103547991^r.length;for(let a=0;a<r.length;a++){let s=r.charCodeAt(a);t=Math.imul(t^s,2654435761),e=Math.imul(e^s,1597334677)}t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909);let n=(e>>>0).toString(16).padStart(8,"0"),i=(t>>>0).toString(16).padStart(8,"0");return`${n}${i}`.slice(0,12)},ze=r=>{let t=(r||"").trim();if(!t)return"";try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"").toLowerCase()||"/";return`${e.origin.toLowerCase()}${n}`}catch{return t.toLowerCase()}},Mn=(r,t,e)=>{let n=Zt((e||t||"").trim()||"action"),i=`${r.type}|${ze(r.url)}|${(r.contract||"").trim().toLowerCase()}|${t.trim().toLowerCase()}`,a=Yt(i);return`private_src_${n}_${a}`},Ge=r=>{let t=qe(r),e=Zt(t),n=Yt(t.trim().toLowerCase());return`private_gen_${e}_${n}`},qn=(r,t,e,n)=>{(!r.name||!r.name.trim())&&n&&(r.name=n);let i=r.chain||t;r.meta={chain:i,identifier:e||Ge(r),hash:r.meta?.hash||"",creator:r.meta?.creator||"",createdAt:r.meta?.createdAt||"",query:r.meta?.query||null}},kn=r=>!!r&&(r.startsWith("private_src_")||r.startsWith("private_gen_"));async function Gn(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 Jn(r,t,e){return null}var _e=(r,t)=>{let e=null;try{e=b(r)}catch{return[]}let n=e?.action;return!n||n.type!=="contract"&&n.type!=="transfer"?[]:(n.inputs??[]).some(s=>s.position==="value"||s.position==="transfer"||s.type==="asset")?[t.nativeToken.identifier]:[]},Xn=async(r,t,e,n)=>{try{let i=W(e,n),a=_e(r,i.chainInfo);if(!a.length)return!0;let s=await i.dataLoader.getAccountAssets(t),p=new Map(s.map(l=>[l.identifier,l.amount??0n]));return a.every(l=>(p.get(l)??0n)>0n)}catch{return!0}};import{x402Client as te}from"@x402/core/client";import{x402HTTPClient as ee}from"@x402/core/http";async function re(r,t,e,n,i){let a=await Je(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(([l,o])=>{s.set(l,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Je=async(r,t)=>{let e=await Qe(r),i=new ee(new te).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 te,p=await a.wallet.registerX402Handlers(s),l=i.accepts.find(h=>h?.network&&p[h.network]);if(!l?.network)continue;p[l.network]();let o=new ee(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${l.network} scheme`),d}catch{continue}return null},Qe=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===y.Tuple&&Array.isArray(e)){if(e.length===0)return t+c.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===y.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let s=a.map(p=>{let[l,o]=this.getTypeAndValue(n[p]);return`(${p}${c.ArgParamsSeparator}${l})${o}`});return`${t}(${i})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}if(t===y.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${c.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(c.ArgParamsSeparator))){let n=e[0],i=n.indexOf(c.ArgParamsSeparator),a=n.substring(0,i),s=e.map(l=>{let o=l.indexOf(c.ArgParamsSeparator),u=l.substring(o+1);return a.startsWith(y.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),p=a.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+a+c.ArgParamsSeparator+s.join(p)}return t+c.ArgParamsSeparator+e.join(c.ArgListSeparator)}if(t===y.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?y.Asset+c.ArgParamsSeparator+e.identifier+c.ArgCompositeSeparator+String(e.amount)+c.ArgCompositeSeparator+String(e.decimals):y.Asset+c.ArgParamsSeparator+e.identifier+c.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+c.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(c.ArgParamsSeparator),n=e[0],i=e.slice(1).join(c.ArgParamsSeparator);if(n==="null")return[n,null];if(n===y.Option){let[a,s]=i.split(c.ArgParamsSeparator);return[y.Option+c.ArgParamsSeparator+a,s||null]}if(n===y.Vector){let a=i.indexOf(c.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),l=s.startsWith(y.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(p?p.split(l):[]).map(d=>this.stringToNative(s+c.ArgParamsSeparator+d)[1]);return[y.Vector+c.ArgParamsSeparator+s,u]}else if(n.startsWith(y.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),p=i.split(c.ArgCompositeSeparator).map((l,o)=>this.stringToNative(`${a[o]}${c.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(y.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(c.ArgListSeparator).forEach(l=>{let o=l.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${c.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===y.String)return[n,i];if(n===y.Uint8||n===y.Uint16||n===y.Uint32)return[n,Number(i)];if(n===y.Uint64||n===y.Uint128||n===y.Uint256||n===y.Biguint)return[n,BigInt(i||0)];if(n===y.Bool)return[n,i==="true"];if(n===y.Address)return[n,i];if(n===y.Hex)return[n,i];if(n===y.Asset){let[a,s]=i.split(c.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,l]=this.stringToNative(`${s}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[e,n]=t.split(c.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[y.Uint32,t]:typeof t=="bigint"?[y.Uint64,t]:typeof t=="boolean"?[y.Bool,t]:[typeof t,t]}};var oi=r=>new w().nativeToString(y.String,r),pi=r=>new w().nativeToString(y.Uint8,r),li=r=>new w().nativeToString(y.Uint16,r),ci=r=>new w().nativeToString(y.Uint32,r),ui=r=>new w().nativeToString(y.Uint64,r),di=r=>new w().nativeToString(y.Biguint,r),fi=r=>new w().nativeToString(y.Bool,r),gi=r=>new w().nativeToString(y.Address,r),ne=r=>new w().nativeToString(y.Asset,r),hi=r=>new w().nativeToString(y.Hex,r),mi=(r,t)=>{if(t===null)return y.Option+c.ArgParamsSeparator;let e=r(t),n=e.indexOf(c.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return y.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+a},yi=(...r)=>new w().nativeToString(y.Tuple,r),Wi=r=>new w().nativeToString(y.Struct,r),vi=r=>new w().nativeToString(y.Vector,r);import Ke from"ajv";var ie=class{constructor(t){this.pendingBrand={protocol:rt("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 Ke,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Xe from"ajv";var ot=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}=b(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 Xe({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 ae=class{constructor(t){this.config=t;this.pendingWarp={protocol:rt("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 Lt(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 ot(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};import{existsSync as St,mkdirSync as Ze,readdirSync as se,readFileSync as Ye,unlinkSync as bt,writeFileSync as tr}from"fs";import{join as oe,resolve as pe}from"path";var Pt="$bigint:",pt=(r,t)=>typeof t=="bigint"?Pt+t.toString():t,z=(r,t)=>typeof t=="string"&&t.startsWith(Pt)?BigInt(t.slice(Pt.length)):t;var lt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?pe(n):pe(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){St(this.cacheDir)||Ze(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return oe(this.cacheDir,`${e}.json`)}async get(t){try{let e=this.getFilePath(t);if(!St(e))return null;let n=Ye(e,"utf-8"),i=JSON.parse(n,z);return i.expiresAt!==null&&Date.now()>i.expiresAt?(bt(e),null):i.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null},a=this.getFilePath(t);tr(a,JSON.stringify(i,pt),"utf-8")}async delete(t){try{let e=this.getFilePath(t);St(e)&&bt(e)}catch{}}async keys(t){try{let e=se(this.cacheDir).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5));if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}catch{return[]}}async clear(){try{se(this.cacheDir).forEach(e=>{e.endsWith(".json")&&bt(oe(this.cacheDir,e))})}catch{}}};var X=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}async get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,z);return n.expiresAt!==null&&Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}async set(t,e,n){let i={value:e,expiresAt:n?Date.now()+n*1e3:null};localStorage.setItem(this.getKey(t),JSON.stringify(i,pt))}async delete(t){localStorage.removeItem(this.getKey(t))}async keys(t){let e=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a?.startsWith(this.prefix+":")&&e.push(a.slice(this.prefix.length+1))}if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var H=class H{constructor(t,e){}async get(t){let e=H.cache.get(t);return e?e.expiresAt!==null&&Date.now()>e.expiresAt?(H.cache.delete(t),null):e.value:null}async set(t,e,n){let i=n?Date.now()+n*1e3:null;H.cache.set(t,{value:e,expiresAt:i})}async delete(t){H.cache.delete(t)}async keys(t){let e=Array.from(H.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){H.cache.clear()}};H.cache=new Map;var Z=H;import{readFileSync as er}from"fs";import{resolve as le}from"path";var ct=class{constructor(t,e){let n=e?.path?le(e.path):le(process.cwd(),`warps-manifest-${t}.json`);this.cache=this.loadManifest(n)}loadManifest(t){try{let e=er(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}}async get(t){let e=this.cache.get(t);return!e||e.expiresAt!==null&&Date.now()>e.expiresAt?(e&&this.cache.delete(t),null):e.value}async set(t,e,n){let i=n?Date.now()+n*1e3:null,a={value:e,expiresAt:i};this.cache.set(t,a)}async delete(t){this.cache.delete(t)}async keys(t){let e=Array.from(this.cache.keys());if(!t)return e;let n=new RegExp("^"+t.replace(/\*/g,".*")+"$");return e.filter(i=>n.test(i))}async clear(){this.cache.clear()}};var ce={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Tt={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}`},ut=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.adapter?e.adapter:e?.type==="localStorage"?new X(t,e):e?.type==="memory"?new Z(t,e):e?.type==="static"?new ct(t,e):e?.type==="filesystem"?new lt(t,e):typeof window<"u"&&window.localStorage?new X(t,e):new Z(t,e)}async set(t,e,n){await this.strategy.set(t,e,n)}async get(t){return await this.strategy.get(t)}async delete(t){await this.strategy.delete(t)}async keys(t){return await this.strategy.keys(t)}async clear(){await this.strategy.clear()}};var Y={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},Et={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Rt=(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)},Nt=r=>{try{return JSON.parse(r)}catch{return null}},rr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:l,nonce:o,expiresAt:u}=await wt(n,`${e.chain.name}-adapter`),d=await a({message:l,chain:e.chain});d&&Object.entries(It(n,d,o,u)).forEach(([h,g])=>s.set(h,g))}let p=Rt(e.resolvedInputs,Y.Headers,i);if(p){let l=Nt(p);l&&typeof l=="object"&&Object.entries(l).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([l,o])=>{s.set(l,r.applyInputs(o,e.resolvedInputs,i))});return s},nr=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===Et.Get){let s=Rt(e.resolvedInputs,Y.Queries,i);if(s){let p=Nt(s);if(p&&typeof p=="object"){let l=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&l.searchParams.set(o,String(u))),a=l.toString()}}}return a},ir=(r,t,e,n,i)=>{if(r===Et.Get)return;let a=Rt(t.resolvedInputs,Y.Payload,n);if(a&&Nt(a)!==null)return a;let{[Y.Payload]:s,[Y.Queries]:p,...l}=e;return JSON.stringify({...l,...i})},ue=async(r,t,e,n,i,a,s,p)=>{let l=t.method||Et.Get,o=await rr(r,t,e,n,a,p),u=nr(r,t,e,l,a),d=ir(l,e,i,a,s);return{url:u,method:l,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);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=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[o,u]=l.split(c.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,g=e.queries?.[o]??null??d;g!=null&&a(s,g)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[o,u]=l.split(c.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h!=null&&a(s,h)}else p===c.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(c.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(c.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(c.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(c.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let l=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=W(l,this.adapters),u={config:this.config,adapter:o},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,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let l=p;l&&typeof l=="object"&&"identifier"in l&&"amount"in l&&(i[`primary.${s}.token`]=String(l.identifier),i[`primary.${s}.amount`]=String(l.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 ut(t.env,t.cache)}getSerializer(){return this.serializer}async getResolvedInputsFromCache(t,e,n){let i=await this.cache.get(Tt.WarpExecutable(t,e||"",n))||[];return V(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),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,i),u=E(o,e),{action:d,index:h}=b(o),g=this.getStringTypedInputs(d,n),m=await this.getResolvedInputs(s.name,d,g,l,i.queries),f=await this.getModifiedInputs(m),v=[],A=[];h===e-1?(v=m,A=f):this.requiresPayloadInputs(u)&&(v=await this.resolveActionInputs(s.name,u,n,l,i.queries),A=await this.getModifiedInputs(v));let T=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,F=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:F;if(x&&(x=l.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(I=>l.applyInputs(I,A,this.serializer,f));let N=A.find(I=>I.input.position==="value")?.value||null,S="value"in u?u.value:null,B=N?.split(c.ArgParamsSeparator)[1]||S||"0",_=l.applyInputs(B,A,this.serializer,f),ge=BigInt(_),he=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),me=[...("transfers"in u?u.transfers:[])||[],...he||[]].map(I=>{let ht=l.applyInputs(I,A,this.serializer,f),Ae=ht.startsWith(`asset${c.ArgParamsSeparator}`)?ht:`asset${c.ArgParamsSeparator}${ht}`;return this.serializer.stringToNative(Ae)[1]}),ye=A.find(I=>I.input.position==="data")?.value,We="data"in u?u.data||"":null,Bt=ye||We||null,ve=Bt?l.applyInputs(Bt,A,this.serializer,f):null,$t={adapter:p,warp:o,chain:s,action:e,destination:x,args:O,value:ge,transfers:me,data:ve,resolvedInputs:A};return await this.cache.set(Tt.WarpExecutable(this.config.env,o.meta?.hash||"",e),$t.resolvedInputs,ce.OneWeek),$t}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(c.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i,a){let s=e.inputs||[],p=n.map(u=>i.applyInputs(u,[],this.serializer)),l=await Promise.all(p.map(u=>this.preprocessInput(t,u))),o=(u,d)=>{if(u.source===c.Source.UserWallet){let v=P(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(l[d])return l[d];let h=u.as||u.name,g=a?.[h],m=this.url.searchParams.get(h),f=g||m;return f?this.serializer.nativeToString(u.type,String(f)):null};return s.map((u,d)=>{let h=o(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(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let l=nt(p,+s);e.push({...i,value:`${i.input.type}:${l}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=nt(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let a=i.input.modifier.substring(c.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=at(t,this.serializer,n,i),l=await s.run(a,p);if(l==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,l);e.push({...i,value:o})}}else e.push(i)}return e}async preprocessInput(t,e){try{let[n,i]=At(e),a=W(t,this.adapters);if(n==="asset"){let[s,p,l]=i.split(c.ArgCompositeSeparator);if(l)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=nt(p,o.decimals);return ne({...o,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[p,l]=this.serializer.stringToNative(s),o=l;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let 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",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(l=>l.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return W(s,this.adapters).chainInfo}};var dt=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=[],p=[],o={...t.meta?.query??{},...n.queries},u={...n,queries:o},{action:d,index:h}=b(t);for(let g=1;g<=t.actions.length;g++){let m=E(t,g);if(!Wt(m,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&&(p=V(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:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Ft.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=W(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=W(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!Wt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let l=e[p],o=p+1;if(!l){let d=await this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,l.tx);return u.next=k(this.config,this.adapters,t,o,u.output),u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:l})):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(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=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:p,output:l}=await st(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,W(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:l,method:o,headers:u,body:d}=await ue(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:l,method:o,headers:u,body:d});try{let g=await fetch(l,{method:o,headers:u,body:d});C.debug("Collect response status",{status:g.status}),g.status===402&&(g=await re(g,l,o,d,this.adapters));let m=await g.json();C.debug("Collect response content",{content:m});let{values:f,output:v}=await st(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),g.ok?"success":"error",f,v,m)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let g=V(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let g=V(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 m=V(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:m}}let p=this.factory.getSerializer(),l=new R(this.config,W(t.chain.name,this.adapters),this.adapters),o=i.destination,u=l.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=l.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([g,m])=>{let f=l.applyInputs(m,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}}),m=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await m.connect(g);let f={};t.resolvedInputs.forEach(({input:x,value:O})=>{if(O&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let N=x.position.replace("payload:",""),[S,B]=p.stringToNative(O);if(S==="string")f[N]=String(B);else if(S==="bool")f[N]=!!B;else if(S==="uint8"||S==="uint16"||S==="uint32"||S==="uint64"||S==="uint128"||S==="uint256"||S==="biguint"){let _=Number(B);f[N]=(Number.isInteger(_),_)}else f[N]=B}}),e&&Object.assign(f,e);let v=await m.callTool({name:d,arguments:f});await m.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:F}=await st(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,F,v)}catch(g){C.error("WarpExecutor: Error executing MCP",g);let m=V(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:m}}}buildCollectResult(t,e,n,i,a,s){let p=k(this.config,this.adapters,t.warp,t.action,a),l=V(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Ct(t.warp,{...i.mapped,...a},this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:l}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=W(s.name,this.adapters),l=new R(this.config,p,this.adapters),o=await l.apply(t,a),u=E(o,n),{action:d}=b(o),h=this.factory.getStringTypedInputs(d,i),g=await this.factory.getResolvedInputs(s.name,d,h,l,a.queries),m=await this.factory.getModifiedInputs(g),f=m;if(e.inputs&&e.inputs.length>0){let S=this.factory.getStringTypedInputs(e,i),B=await this.factory.getResolvedInputs(s.name,e,S,l,a.queries);f=await this.factory.getModifiedInputs(B)}let v=Xt(u.prompt,this.config.platform),A=l.applyInputs(v,f,this.factory.getSerializer(),m),T=V(f),F=P(this.config,s.name),x=this.factory.getSerializer(),{values:O,output:N}=await Kt(o,A,n,f,x,this.config);return{status:"success",warp:o,action:n,user:F,txHash:null,tx:null,next:k(this.config,this.adapters,o,n,N),values:O,output:N,messages:Ct(o,N,this.config),destination:null,resolvedInputs:T}}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 p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),l=W(p.name,this.adapters),o=new R(this.config,l,this.adapters),{action:u}=b(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o,i.queries),g=await this.factory.getModifiedInputs(h),m;if(a)m=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o,i.queries);m=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(m,this.factory.getSerializer(),g),v=jt(e.when,f);return Mt(v)}};var ft=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 gt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.resolver=n}isValid(t){return t.startsWith(c.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(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,l=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:l}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?Q(t,this.config.defaultChain):$(t,this.config.defaultChain);if(!i)return n;C.info("Warp detect parse",{input:t,chain:i.chain,type:i.type,identifier:i.identifier,identifierBase:i.identifierBase});try{let{type:a,identifierBase:s}=i,p=null,l=null,o=null,u=t.startsWith(c.HttpProtocolPrefix)?kt(t):zt(i.identifier);if(this.resolver){let m=null;if(a==="hash")m=await this.resolver.getByHash(s,e);else if(a==="alias"){let f=`${i.chain}:${s}`;m=await this.resolver.getByAlias(f,e)||await this.resolver.getByAlias(s,e)}m&&(p=m.warp,l=m.registryInfo,o=m.brand)}else{let m=W(i.chain,this.adapters);if(a==="hash"){p=await m.builder().createFromTransactionHash(s,e);let f=await m.registry.getInfoByHash(s,e);l=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await m.registry.getInfoByAlias(s,e);l=f.registryInfo,o=f.brand,f.registryInfo&&(p=await m.builder().createFromTransactionHash(f.registryInfo.hash,e))}}if(p&&p.meta&&(ar(p,i.chain,l,i.identifier),p.meta.query=u?Gt(u):null),!p)return n;let d=p.chain||i.chain,h=W(d,this.adapters),g=await new R(this.config,h,this.adapters).apply(p);return{match:!0,url:t,warp:g,chain:d,registryInfo:l,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},ar=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?vt(null,"alias",e.alias):vt(t,"hash",e?.hash??n))};var de=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config)),this.resolver=e.resolver??this.buildDefaultResolver()}buildDefaultResolver(){let t=this.chains.map(e=>new tt(e));return new et(t)}getConfig(){return this.config}getResolver(){return this.resolver}createExecutor(t){return new dt(this.config,this.chains,t)}async detectWarp(t,e){return new gt(this.config,this.chains,this.resolver).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let m=await fetch(t);if(!m.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await m.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await l.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async m=>{await l.evaluateOutput(p,m)},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=$(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(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return W(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return W(t,this.chains).explorer}getOutput(t){return W(t,this.chains).output}async getActionExecution(t,e,n,i){let a=i??b(e).index+1,p=await W(t,this.chains).output.getActionExecution(e,a,n);return p.next=k(this.config,this.chains,e,a,p.output),p}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 ft(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 it(t,this.config)}};var fe=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{mt as BrowserCryptoProvider,Cr as CLOUD_WALLET_PROVIDERS,ce as CacheTtl,Ar as EvmWalletChainNames,yt as NodeCryptoProvider,_r as WARP_LANGUAGES,ie as WarpBrandBuilder,ae as WarpBuilder,ut as WarpCache,Tt as WarpCacheKey,Te as WarpChainName,tt as WarpChainResolver,de as WarpClient,et as WarpCompositeResolver,U as WarpConfig,c as WarpConstants,dt as WarpExecutor,G as WarpFactory,ft as WarpIndex,y as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,gt as WarpLinkDetecter,C as WarpLogger,Vt as WarpPlatformName,Ht as WarpPlatforms,M as WarpProtocolVersions,w as WarpSerializer,fe as WarpTypeRegistry,ot as WarpValidator,gi as address,Ct as applyOutputToMessages,ne as asset,di as biguint,fi as bool,Ge as buildGeneratedFallbackWarpIdentifier,Mn as buildGeneratedSourceWarpIdentifier,at as buildInputsContext,K as buildMappedOutput,He as buildNestedPayload,Hr as bytesToBase64,Ee as bytesToHex,Xn as checkWarpAssetBalance,J as cleanWarpIdentifier,It as createAuthHeaders,wt as createAuthMessage,Or as createCryptoProvider,Jn as createDefaultWalletProvider,Un as createHttpAuthHeaders,Me as createSignableMessage,Qr as createWarpI18nText,vt as createWarpIdentifier,zr as doesWarpRequireWallet,Qt as evaluateOutputCommon,Mt as evaluateWhenCondition,st as extractCollectOutput,Q as extractIdentifierInfoFromUrl,Kt as extractPromptOutput,zt as extractQueryStringFromIdentifier,kt as extractQueryStringFromUrl,V as extractResolvedInputValues,Lr as extractWarpSecrets,W as findWarpAdapterForChain,Ot as getCryptoProvider,Tr as getEventNameFromWarp,qe as getGeneratedSourceWarpName,rt as getLatestProtocolIdentifier,k as getNextInfo,Vn as getProviderConfig,Ut as getRandomBytes,Dt as getRandomHex,_e as getRequiredAssetIds,cr as getWalletFromConfigOrFail,E as getWarpActionByIndex,Rr as getWarpBrandLogoUrl,Nr as getWarpChainAssetLogoUrl,Br as getWarpChainInfoLogoUrl,en as getWarpIdentifierWithQuery,$ as getWarpInfoFromIdentifier,b as getWarpPrimaryAction,Ce as getWarpWalletAddress,P as getWarpWalletAddressFromConfig,Ie as getWarpWalletExternalId,Pe as getWarpWalletExternalIdFromConfig,fr as getWarpWalletExternalIdFromConfigOrFail,we as getWarpWalletMnemonic,dr as getWarpWalletMnemonicFromConfig,xe as getWarpWalletPrivateKey,ur as getWarpWalletPrivateKeyFromConfig,re as handleX402Payment,an as hasInputPrefix,hi as hex,Gn as initializeWalletCache,Yr as isEqualWarpIdentifier,kn as isGeneratedSourcePrivateIdentifier,je as isPlatformValue,Wt as isWarpActionAutoExecute,Jr as isWarpI18nText,gr as isWarpWalletReadOnly,_t as mergeNestedPayload,yr as normalizeAndValidateMnemonic,Se as normalizeMnemonic,mi as option,Le as parseOutputOutIndex,Ln as parseSignedMessage,Gt as parseWarpQueryStringToObject,tn as removeWarpChainPrefix,mr as removeWarpWalletFromConfig,L as replacePlaceholders,jt as replacePlaceholdersInWhenExpression,Xt as resolvePlatformValue,it as resolveWarpText,Ft as safeWindow,Vr as setCryptoProvider,hr as setWarpWalletInConfig,nt as shiftBigintBy,At as splitInput,qn as stampGeneratedWarpMeta,oi as string,Wi as struct,Fr as testCryptoAvailability,Fe as toInputPayloadValue,Lt as toPreviewText,yi as tuple,li as uint16,ci as uint32,ui as uint64,pi as uint8,be as validateMnemonicLength,Dn as validateSignedMessage,vi as vector,Pr as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps",
3
- "version": "4.5.0",
3
+ "version": "4.6.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",