/**
 * @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 } from './content';

// HTTP utilities
export { validateBaseUrl, buildSetCookie, parseCookies, getCookie, isLocalhost, isSecureRequest } from './http';
export type { CookieOptions, SecureDetectionRequest } from './http';

// File system utilities (Node.js only)
export {
  readFile,
  readFileSync,
  readFileBuffer,
  writeFile,
  mkdir,
  rename,
  unlink,
  stat,
  copyFile,
  cp,
  readdir,
  readdirSync,
  realpath,
  rm,
  mkdtemp,
  symlink,
  access,
  fileExists,
  readJSON,
  writeJSON,
  ensureDir,
  ensureDirSync,
  isDirEmpty,
  runCmd,
  watchFile,
  getSpawnFn,
} from './fs';
export type { FileWatcherHandle } from './fs';

// Escape utilities (HTML, JS, XSS prevention)
export { escapeHtml, escapeHtmlAttr, escapeJsString, escapeScriptClose, safeJsonForScript } from './escape';

// Serialization utilities
export { safeStringify } 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,
  // 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,
} from './crypto';
export type { CryptoProvider, EncBlob, EncryptedBlob } from './crypto';

// Async context (cross-platform AsyncLocalStorage)
export { AsyncLocalStorage } from './async-context';

// Event emitter (cross-platform)
export { EventEmitter } from './event-emitter';

// Environment utilities (cross-platform)
export {
  getEnv,
  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,
  // Namespace
  NamespacedStorageImpl,
  createRootStorage,
  createNamespacedStorage,
  buildPrefix,
  NAMESPACE_SEPARATOR,
  // Errors
  StorageError,
  StorageConnectionError,
  StorageOperationError,
  StorageNotSupportedError,
  StorageConfigError,
  StorageTTLError,
  StoragePatternError,
  StorageNotConnectedError,
  EncryptedStorageError,
  // Adapters
  BaseStorageAdapter,
  MemoryStorageAdapter,
  RedisStorageAdapter,
  VercelKvStorageAdapter,
  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
  globToRegex,
  matchesPattern,
  validatePattern,
  escapeGlob,
  MAX_TTL_SECONDS,
  validateTTL,
  validateOptionalTTL,
  ttlToExpiresAt,
  expiresAtToTTL,
  isExpired,
  normalizeTTL,
} from './storage';
export type {
  StorageAdapter,
  NamespacedStorage,
  RootStorage,
  SetOptions,
  SetEntry,
  MessageHandler,
  Unsubscribe,
  MemoryAdapterOptions,
  RedisAdapterOptions,
  VercelKvAdapterOptions,
  UpstashAdapterOptions,
  StorageType,
  StorageConfig,
} 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 { getMachineId, setMachineIdOverride } from './machine-id';
