/** * @frontmcp/utils * * Shared utility functions for the FrontMCP ecosystem. * Provides generic, protocol-neutral utilities for string manipulation, * URI handling, path operations, content processing, and more. */ // Naming utilities export { splitWords, toCase, sepFor, shortHash, ensureMaxLen, idFromString } from './naming'; export type { NameCase } from './naming'; // URI utilities export { isValidMcpUri, extractUriScheme, isValidMcpUriTemplate, parseUriTemplate, matchUriTemplate, expandUriTemplate, extractTemplateParams, isUriTemplate, } from './uri'; export type { ParsedUriTemplate } from './uri'; // Path utilities export { trimSlashes, joinPath, pathResolve, pathJoin, basename, dirname, extname, isAbsolute, pathToFileURL, sep, } from './path'; // Content utilities export { sanitizeToJson, inferMimeType, findNonFiniteNumber, findDroppedKeys } from './content'; // HTTP utilities export { validateBaseUrl, buildSetCookie, parseCookies, getCookie, isLocalhost, isSecureRequest, readBodyWithLimit, readTextWithLimit, ResponseTooLargeError, } from './http'; export type { CookieOptions, SecureDetectionRequest, LimitedBodySource } from './http'; // Network utilities (IP-literal classification for SSRF guards, redirect detection, SSRF-hardened outbound requests) export { classifyIpAddress, expandIpv6, extractEmbeddedIpv4, isGloballyRoutableIp, parseIpv4, isRedirectResponse, pinnedFetch, validateOutboundUrl, sendOutboundRequest, outboundFailureCategory, OUTBOUND_TIMEOUT_MS, OUTBOUND_MAX_REQUEST_BYTES, } from './net'; export type { IpAddressClassification, IpAddressRange, SpecialPurposeIpRange, RedirectCandidate, PinnedFetch, PinnedRequestInit, OutboundTargetOptions, OutboundUrlCheck, OutboundUrlProblem, OutboundRequest, OutboundAnswer, OutboundFailure, OutboundFailureReason, OutboundFailureCategory, OutboundResult, } from './net'; // File system utilities (Node.js only) export { readFile, readFileSync, readFileBuffer, writeFile, appendFile, mkdir, rename, unlink, stat, lstat, chmod, copyFile, cp, readdir, readdirSync, realpath, rm, mkdtemp, symlink, access, fileExists, fileExistsSync, readJSON, writeJSON, ensureDir, ensureDirSync, isDirEmpty, runCmd, watchFile, watchFiles, getSpawnFn, } from './fs'; export type { FileWatcherHandle, FileWatchEvent, FileWatchEventType, WatchFilesOptions } from './fs'; // Process supervision (Node.js only): process trees, owned children, orphan reaping, parent and path watchers export { processTreeSpawnOptions, signalProcessTree, isProcessTreeAlive, stopProcessTree, spawnOwned, reapOrphans, OwnedProcessError, watchParent, watchPath, } from './process'; export type { ProcessTreeDeps, SpawnOwnedOptions, OwnedProcess, ReapOrphansOptions, ParentGoneReason, ProcessWatcher, WatchParentOptions, WatchPathOptions, } from './process'; // The stdio bridge (Node.js only): a newline-delimited JSON-RPC framer, an upstream MCP client, and the state // machine that buffers a client's requests while its server starts or restarts export { DEV_BUFFER_FULL, DEV_ERROR_MESSAGE, DEV_RELOAD_DEADLINE, DEV_SERVER_UNREACHABLE, makeDevError, listChangedNotifications, createBridgeStateMachine, createStdioFramer, createHttpUpstream, createPipeUpstream, } from './stdio-bridge'; export type { BridgeState, BridgeStateMachine, BridgeStateMachineOptions, InflightRequest, JsonRpcFrame, StdioFramer, StdioFramerOptions, BridgeLogger, HttpUpstreamClient, HttpUpstreamOptions, PipeUpstreamOptions, UpstreamClient, UpstreamClientOptions, } from './stdio-bridge'; // Redaction of sensitive fields in log entries and recorded calls export { redactFields, redactJson } from './redaction'; export type { RedactedFields } from './redaction'; // Escape utilities (HTML, JS, XSS prevention, control characters in text output) export { escapeHtml, escapeHtmlAttr, escapeJsString, escapeScriptClose, safeJsonForScript, escapeControlCharacters, } from './escape'; // Class identity across two copies of a package in one process (`instanceof` by brand) export { brandClass, isBrandedInstance } from './class-brand'; // Optional packages a bundle hands over, for runtimes where `require()` cannot reach them export { registerOptionalModule, requireOptionalModule } from './optional-module'; // Serialization utilities export { safeStringify, canonicalJson } from './serialization'; // Crypto utilities (cross-platform: Node.js and browser) // Includes: core crypto, encrypted blobs, PKCE (RFC 7636), secret persistence export { // Core crypto getCrypto, rsaVerify, rsaVerifySync, pemToPublicJwk, generateRsaKeyPair, rsaSignBase64Url, type RsaJwk, type RsaKeyPair, jwtAlgToNodeAlg, isRsaPssAlg, randomUUID, randomBytes, sha256, sha256Hex, sha256Base64url, hmacSha256, hkdfSha256, encryptAesGcm, decryptAesGcm, timingSafeEqual, bytesToHex, base64urlEncode, base64urlDecode, base64Encode, base64Decode, isNode, isBrowser, assertNode, // Encrypted blob helpers EncryptedBlobError, encryptValue, decryptValue, tryDecryptValue, serializeBlob, deserializeBlob, tryDeserializeBlob, isValidEncryptedBlob, encryptAndSerialize, deserializeAndDecrypt, tryDeserializeAndDecrypt, // PKCE utilities (RFC 7636) generateCodeVerifier, generateCodeChallenge, verifyCodeChallenge, generatePkcePair, isValidCodeVerifier, isValidCodeChallenge, MIN_CODE_VERIFIER_LENGTH, MAX_CODE_VERIFIER_LENGTH, DEFAULT_CODE_VERIFIER_LENGTH, PkceError, type PkcePair, // Secret persistence utilities (legacy) type SecretData, type SecretPersistenceOptions, type SecretValidationResult, secretDataSchema, validateSecretData, parseSecretData, isSecretPersistenceEnabled, resolveSecretPath, loadSecret, saveSecret, deleteSecret, generateSecret, createSecretData, getOrCreateSecret, clearCachedSecret, isSecretCached, // HMAC signing utilities type SignedData, type HmacSigningConfig, signData, verifyData, isSignedData, verifyOrParseData, // Standard Webhooks signing and verification WEBHOOK_ID_HEADER, WEBHOOK_TIMESTAMP_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, signingKeyOf, isStandardWebhookSecret, generateStandardWebhookSecret, generateWebhookMessageId, signWebhookMessage, webhookSignatureHeaders, verifyWebhookSignature, type WebhookMessage, type SignedWebhookMessage, type WebhookSignatureCheck, // Unified key persistence (recommended) type BaseKeyData, type SecretKeyData, type AsymmetricKeyData, type AnyKeyData, type KeyPersistenceOptions, type CreateKeyPersistenceOptions, type CreateSecretOptions, type CreateAsymmetricOptions, type KeyValidationResult, asymmetricAlgSchema, secretKeyDataSchema, asymmetricKeyDataSchema, anyKeyDataSchema, validateKeyData, parseKeyData, isSecretKeyData, isAsymmetricKeyData, KeyPersistence, createKeyPersistence, createKeyPersistenceWithStorage, LocalStorageKeyLostError, LocalStorageKeyRequiredError, LocalStorageKeyUnavailableError, UnreadableKeyRecordError, } from './crypto'; export type { CryptoProvider, EncBlob, EncryptedBlob } from './crypto'; // Async context (cross-platform AsyncLocalStorage; the browser build runs requests one at a time // unless the runtime has AsyncContext) export { AsyncContextOverlapError, AsyncLocalStorage, awaitOutsideRequest, getAsyncContextMode, runRequestExclusive, type AsyncContextMode, } from './async-context'; // Event emitter (cross-platform) export { EventEmitter } from './event-emitter'; // Environment utilities (cross-platform) export { getEnv, getNodeEnv, getCwd, isProduction, isDevelopment, getEnvFlag, isDebug, setEnv, isEdgeRuntime, isServerless, supportsAnsi, // Runtime context detection and entry availability matching getRuntimeContext, resetRuntimeContext, detectRuntimeContext, isEntryAvailable, checkEntryAvailability, entryAvailabilitySchema, } from './env'; export type { RuntimeContext, EntryAvailability } from './env'; // Safe regex utilities (ReDoS prevention) export { // Core safe regex functions analyzePattern, isPatternSafe, createSafeRegExp, safeTest, safeMatch, safeReplace, safeExec, isInputLengthSafe, DEFAULT_MAX_INPUT_LENGTH, REDOS_THRESHOLDS, // Pre-built safe pattern utilities trimLeading, trimTrailing, trimBoth, trimChars, extractBracedParams, expandTemplate, hasTemplatePlaceholders, collapseChar, collapseWhitespace, // Types type SafeRegexOptions, type PatternAnalysisResult, } from './regex'; // Storage utilities (unified key-value storage with pluggable backends) export { // Factory createStorage, createMemoryStorage, getDetectedStorageType, // Change feed createChangeFeed, DEFAULT_CHANGE_FEED_COALESCE_MS, DEFAULT_CHANGE_FEED_POLL_INTERVAL_MS, // Namespace NamespacedStorageImpl, createRootStorage, createNamespacedStorage, buildPrefix, NAMESPACE_SEPARATOR, // Errors StorageError, StorageConnectionError, StorageOperationError, StorageNotSupportedError, StorageConfigError, StorageTTLError, StoragePatternError, StorageNotConnectedError, EncryptedStorageError, // Adapters BaseStorageAdapter, MemoryStorageAdapter, RedisStorageAdapter, createRedisClient, VercelKvStorageAdapter, createVercelKvClient, type VercelKvConnection, UpstashStorageAdapter, FileSystemStorageAdapter, type FileSystemAdapterOptions, // TypedStorage (type-safe JSON wrapper) TypedStorage, type TypedStorageOptions, type TypedSetOptions, type TypedSetEntry, // EncryptedTypedStorage (encrypted storage with key rotation) EncryptedTypedStorage, type EncryptedTypedStorageOptions, type EncryptedSetOptions, type EncryptedSetEntry, type EncryptionKey, type StoredEncryptedBlob, type ClientKeyBinding, // Utilities createGlobMatcher, globToRegex, matchesPattern, validatePattern, escapeGlob, MAX_TTL_SECONDS, validateTTL, validateOptionalTTL, ttlToExpiresAt, expiresAtToTTL, isExpired, normalizeTTL, attachRedisErrorListener, DEFAULT_REDIS_ERROR_LOG_INTERVAL_MS, mergeRedisUrlFields, describeRedisUrlConflicts, } from './storage'; export type { StorageAdapter, NamespacedStorage, RootStorage, SetOptions, SetEntry, MessageHandler, Unsubscribe, MemoryAdapterOptions, RedisAdapterOptions, RedisHostConnectionConfig, RedisUrlConnectionConfig, RedisUrlFillInConfig, VercelKvAdapterOptions, UpstashAdapterOptions, SqliteAdapterOptions, StorageType, StorageConfig, RedisErrorListenerOptions, RedisUrlConnection, RedisUrlMerge, RedisUrlSiblingFields, CreateRedisClientOptions, ErrorEmitterClient, ChangeFeed, ChangeFeedKind, ChangeFeedOptions, PublishOptions, } from './storage'; // LLM platform tool call processing (cross-platform: Node.js and browser) export { processPlatformToolCalls } from './llm'; export type { CallToolFn, OpenAIToolCallItem, OpenAIToolResponse, ClaudeToolUseBlock, ClaudeToolResultBlock, VercelToolCallInfo, PlatformToolCallsInput, PlatformToolCallsOutput, SupportedPlatform, } from './llm'; // Machine ID (deployment-aware node identity) export { getHostname, getMachineId, setMachineIdOverride } from './machine-id';