{"_id":"@oppulence/core","_rev":"2-937be6a85367fff98d1b4701996d362f","name":"@oppulence/core","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.0":{"name":"@oppulence/core","version":"1.0.0","keywords":["logger","tryCatch","utilities"],"author":"","license":"ISC","_id":"@oppulence/core@1.0.0","maintainers":[{"name":"solomonai","email":"yoanyomba@solomon-ai.co"}],"homepage":"https://github.com/Oppulence-Engineering/design-system#readme","bugs":{"url":"https://github.com/Oppulence-Engineering/design-system/issues"},"dist":{"shasum":"e34eb5e1b7eb1494bfc6fa6668ce51448d5863c9","tarball":"https://registry.npmjs.org/@oppulence/core/-/core-1.0.0.tgz","fileCount":62,"integrity":"sha512-NOLZ97xB9mnmAq+qTFp8hCUP083SiQ7KYMBKBRunAOJbfn9I8sz+YuBZ4JKpw6mlbojHOUhE1pxFDPF4J1069w==","signatures":[{"sig":"MEUCIH7bxOgkVM+pv9PV/9Ytap1YSF2MndHJIlamkOImhrf5AiEAwKl6wD4rtsyvsA4Q+Go690V5N4lvZ27T1JSQrcthHYI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@oppulence%2fcore@1.0.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":820420},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"},"./collaboration":{"types":"./dist/collaboration.d.ts","import":"./dist/collaboration.js","default":"./dist/collaboration.js"}},"gitHead":"6720617a739cf6283c1b1340c195a27fa3073a67","scripts":{"lint":"prettier --check \"src/**/*.{ts,tsx}\"","test":"bun test src","build":"tsc && bun build src/index.ts src/collaboration.ts --root src --outdir dist --target node --format esm --packages=external","clean":"rm -rf dist","format":"prettier --write \"src/**/*.{ts,tsx}\"","typecheck":"tsc --noEmit --emitDeclarationOnly false","prepublishOnly":"bun run clean && bun run build"},"_npmUser":{"name":"solomonai","email":"yoanyomba@solomon-ai.co"},"repository":{"url":"git+https://github.com/Oppulence-Engineering/design-system.git","type":"git","directory":"packages/core"},"_npmVersion":"10.8.2","description":"Core utilities for Revenue Cloud packages","directories":{},"_nodeVersion":"20.20.2","dependencies":{"ai":"^6.0.175","zod":"^4.3.5","tslib":"^2.8.1","std-env":"^3.9.0","uncrypto":"^0.1.3","socket.io":"^4.8.1","socket.io-client":"^4.8.1","humanize-duration":"^3.33.0","@opentelemetry/api":"^1.9.1","zod-validation-error":"^5.0.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.9.3","@types/node":"^20.0.0","@types/humanize-duration":"^3.27.4"},"_npmOperationalInternal":{"tmp":"tmp/core_1.0.0_1784906467100_0.8229329920294193","host":"s3://npm-registry-packages-npm-production"}},"1.1.0":{"name":"@oppulence/core","version":"1.1.0","description":"Core utilities for Revenue Cloud packages","type":"module","main":"./dist/index.js","module":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"},"./collaboration":{"types":"./dist/collaboration.d.ts","import":"./dist/collaboration.js","default":"./dist/collaboration.js"}},"scripts":{"build":"tsc && bun build src/index.ts src/collaboration.ts --root src --outdir dist --target node --format esm --packages=external","clean":"rm -rf dist","format":"prettier --write \"src/**/*.{ts,tsx}\"","lint":"prettier --check \"src/**/*.{ts,tsx}\"","prepublishOnly":"bun run clean && bun run build","test":"bun test src","typecheck":"tsc --noEmit --emitDeclarationOnly false"},"keywords":["logger","tryCatch","utilities"],"author":"","license":"ISC","publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/Oppulence-Engineering/design-system.git","directory":"packages/core"},"devDependencies":{"@types/humanize-duration":"^3.27.4","@types/node":"^20.0.0","typescript":"^5.9.3"},"dependencies":{"@opentelemetry/api":"^1.9.1","ai":"^6.0.175","tslib":"^2.8.1","humanize-duration":"^3.33.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1","std-env":"^3.9.0","uncrypto":"^0.1.3","zod":"^4.3.5","zod-validation-error":"^5.0.0"},"_id":"@oppulence/core@1.1.0","gitHead":"d8845e79ad66c5f6e29448488fab5f9fc485ec46","bugs":{"url":"https://github.com/Oppulence-Engineering/design-system/issues"},"homepage":"https://github.com/Oppulence-Engineering/design-system#readme","_nodeVersion":"20.20.2","_npmVersion":"10.8.2","dist":{"integrity":"sha512-DqjZmRssBpENsS9XnQA4CEbaShPfy9L3bOFTNm2ULZTIeHVda2j3oSmadZpGbcjE2rAHQbN6TF93/ccYPz066g==","shasum":"54719dceebf38956d96d5aad145bdaf7da261c02","tarball":"https://registry.npmjs.org/@oppulence/core/-/core-1.1.0.tgz","fileCount":62,"unpackedSize":850451,"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@oppulence%2fcore@1.1.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDb6CNWzV3ensFoxVrrQhgWuHD000pZXzWkJ98nr0kEQwIgPZDMRgbSA0mY5mVCjkUnDtJ5WJtCNjmwkURTuqEgGdI="}]},"_npmUser":{"name":"solomonai","email":"yoanyomba@solomon-ai.co"},"directories":{},"maintainers":[{"name":"solomonai","email":"yoanyomba@solomon-ai.co"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/core_1.1.0_1785649223637_0.046688217958874345"},"_hasShrinkwrap":false}},"time":{"created":"2026-07-24T15:21:06.851Z","modified":"2026-08-02T05:40:24.152Z","1.0.0":"2026-07-24T15:21:07.262Z","1.1.0":"2026-08-02T05:40:23.798Z"},"bugs":{"url":"https://github.com/Oppulence-Engineering/design-system/issues"},"license":"ISC","homepage":"https://github.com/Oppulence-Engineering/design-system#readme","keywords":["logger","tryCatch","utilities"],"repository":{"type":"git","url":"git+https://github.com/Oppulence-Engineering/design-system.git","directory":"packages/core"},"description":"Core utilities for Revenue Cloud packages","maintainers":[{"name":"solomonai","email":"yoanyomba@solomon-ai.co"}],"readme":"# @oppulence/core\n\nCore utilities for the Solomon AI platform providing essential functionality for logging, error handling, cryptography, async context management, and system operations.\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Error Handling (Result Types)](#error-handling-result-types)\n- [Logging](#logging)\n- [Cryptography](#cryptography)\n- [Async Context (AsyncLocalStorage)](#async-context-asynclocalstorage)\n- [Shutdown Management](#shutdown-management)\n- [Utility Functions](#utility-functions)\n- [Type Utilities](#type-utilities)\n- [Schemas](#schemas)\n- [API Reference](#api-reference)\n\n## Installation\n\n```bash\nbun add @oppulence/core\n# or\nnpm install @oppulence/core\n# or\npnpm add @oppulence/core\n```\n\n## Quick Start\n\n```typescript\nimport {\n  // Error handling\n  tryCatch,\n  tryCatchSync,\n  mapResult,\n  isSuccess,\n\n  // Logging\n  Logger,\n  createLogger,\n\n  // Utilities\n  debounce,\n  throttle,\n  memoize,\n  sleep,\n  deepMerge,\n\n  // Crypto\n  digestSHA256,\n  hmacSHA256,\n  generateRandomHex,\n\n  // Shutdown\n  shutdownManager,\n\n  // Async context\n  SafeAsyncLocalStorage,\n} from \"@oppulence/core\";\n```\n\n## Error Handling (Result Types)\n\nGo-style error handling using Result tuples `[Error | null, Data | null]`. This pattern makes error handling explicit and prevents unhandled exceptions.\n\n### Basic Usage\n\n```typescript\nimport { tryCatch, tryCatchSync, Result } from \"@oppulence/core\";\n\n// Async operations\nconst [error, data] = await tryCatch(fetch(\"/api/users\"));\nif (error) {\n  console.error(\"Request failed:\", error.message);\n  return;\n}\nconsole.log(\"Users:\", data);\n\n// Sync operations\nconst [parseError, json] = tryCatchSync(() => JSON.parse(rawString));\nif (parseError) {\n  console.error(\"Invalid JSON\");\n  return;\n}\n```\n\n### With Timeout\n\n```typescript\nimport { tryCatchWithTimeout } from \"@oppulence/core\";\n\n// Automatically fails if operation takes longer than 5 seconds\nconst [error, data] = await tryCatchWithTimeout(\n  fetch(\"/api/slow-endpoint\"),\n  5000, // timeout in ms\n  new Error(\"Request timed out\") // optional custom error\n);\n```\n\n### With Abort Controller\n\n```typescript\nimport { tryCatchWithAbort } from \"@oppulence/core\";\n\nconst controller = new AbortController();\n\n// Cancel after 10 seconds\nsetTimeout(() => controller.abort(), 10000);\n\nconst [error, data] = await tryCatchWithAbort(\n  fetch(\"/api/data\", { signal: controller.signal }),\n  controller.signal\n);\n\nif (error?.name === \"AbortError\") {\n  console.log(\"Request was cancelled\");\n}\n```\n\n### Result Utilities\n\n```typescript\nimport {\n  mapResult,\n  flatMapResult,\n  isSuccess,\n  isFailure,\n  unwrapResult,\n  unwrapResultOr,\n  combineResults,\n} from \"@oppulence/core\";\n\n// Transform success values\nconst userResult = await tryCatch(fetchUser(id));\nconst nameResult = mapResult(userResult, (user) => user.name);\n\n// Chain Result-returning operations\nconst profileResult = flatMapResult(userResult, (user) =>\n  tryCatchSync(() => parseProfile(user.rawProfile))\n);\n\n// Type guards\nif (isSuccess(result)) {\n  console.log(\"Data:\", result[1]); // TypeScript knows result[1] is not null\n}\n\n// Extract values\nconst user = unwrapResult(userResult); // throws if error\nconst userOrDefault = unwrapResultOr(userResult, defaultUser); // returns default if error\n\n// Combine multiple results\nconst results = await Promise.all([\n  tryCatch(fetchUser(1)),\n  tryCatch(fetchUser(2)),\n  tryCatch(fetchUser(3)),\n]);\nconst [error, users] = combineResults(results);\nif (error) {\n  console.error(\"At least one fetch failed\");\n} else {\n  console.log(\"All users:\", users); // users is User[]\n}\n```\n\n## Logging\n\nStructured JSON logging with configurable levels, key masking, batching, and OpenTelemetry trace context support.\n\n### Basic Usage\n\n```typescript\nimport { Logger, createLogger } from \"@oppulence/core\";\n\n// Create a logger\nconst logger = new Logger(\"my-service\");\n// or\nconst logger = createLogger(\"my-service\");\n\n// Log at different levels\nlogger.log(\"General message\");\nlogger.info(\"Informational message\", { userId: \"123\" });\nlogger.warn(\"Warning message\", { threshold: 80 });\nlogger.error(\"Error occurred\", { error: err });\nlogger.debug(\"Debug info\", { query: sql });\nlogger.verbose(\"Verbose output\", { trace: stack });\n```\n\n### Key Masking\n\nAutomatically mask sensitive data in logs:\n\n```typescript\nconst logger = new Logger(\"auth\", \"info\", [\"password\", \"token\", \"apiKey\"]);\n\nlogger.info(\"User login\", {\n  username: \"john\",\n  password: \"secret123\",\n  token: \"abc123\",\n});\n// Output: {\"username\":\"john\",\"password\":\"[FILTERED]\",\"token\":\"[FILTERED]\",...}\n```\n\n### Child Loggers\n\nCreate loggers with inherited context:\n\n```typescript\nconst requestLogger = logger.child({\n  requestId: \"req-123\",\n  userId: \"user-456\",\n});\n\n// All logs include requestId and userId\nrequestLogger.info(\"Processing request\");\nrequestLogger.info(\"Request complete\", { duration: 150 });\n```\n\n### OpenTelemetry Trace Context\n\n```typescript\nimport { trace } from \"@opentelemetry/api\";\n\nconst span = trace.getActiveSpan();\nif (span) {\n  const tracedLogger = logger.withTraceContext(span.spanContext());\n  tracedLogger.info(\"Traced operation\"); // Includes traceId, spanId\n}\n```\n\n### Log Batching (High-Throughput)\n\nFor high-throughput scenarios, batch logs to reduce I/O overhead:\n\n```typescript\nconst logger = new Logger(\"high-throughput\");\n\nlogger.enableBatching({\n  maxSize: 100, // Flush after 100 logs\n  flushInterval: 1000, // Or flush every 1 second\n});\n\n// Logs are batched and written together\nfor (let i = 0; i < 1000; i++) {\n  logger.info(\"Processing item\", { index: i });\n}\n\n// Manually flush when needed\nawait logger.flush();\n\n// Disable batching\nlogger.disableBatching();\n```\n\n## Cryptography\n\nSecure cryptographic utilities with module caching for optimal performance.\n\n### Hashing\n\n```typescript\nimport { digestSHA256, digestSHA512 } from \"@oppulence/core\";\n\nconst hash256 = await digestSHA256(\"Hello, World!\");\n// Returns 64-character hex string\n\nconst hash512 = await digestSHA512(\"Hello, World!\");\n// Returns 128-character hex string\n```\n\n### HMAC Signing\n\n```typescript\nimport { hmacSHA256, hmacSHA512 } from \"@oppulence/core\";\n\n// Sign data with a secret key\nconst signature = await hmacSHA256(\"secret-key\", \"data-to-sign\");\n\n// Verify webhook signatures\nconst expectedSig = await hmacSHA256(webhookSecret, requestBody);\nif (expectedSig === receivedSignature) {\n  // Valid signature\n}\n```\n\n### Random Generation\n\n```typescript\nimport {\n  generateRandomBytes,\n  generateRandomHex,\n  generateId,\n} from \"@oppulence/core\";\n\nconst bytes = await generateRandomBytes(32); // Uint8Array\nconst hex = await generateRandomHex(16); // 32-character hex string\nconst id = await generateId(12); // URL-safe random ID\n```\n\n### Encoding Utilities\n\n```typescript\nimport {\n  bufferToHex,\n  hexToBuffer,\n  base64Encode,\n  base64Decode,\n  base64UrlEncode,\n  base64UrlDecode,\n} from \"@oppulence/core\";\n\n// Hex encoding\nconst hex = bufferToHex(buffer);\nconst buffer = hexToBuffer(hex);\n\n// Base64 encoding\nconst encoded = base64Encode(\"Hello\");\nconst decoded = base64Decode(encoded);\n\n// URL-safe Base64 (no padding, URL-safe chars)\nconst urlSafe = base64UrlEncode(\"Hello\");\nconst original = base64UrlDecode(urlSafe);\n```\n\n### Secure Comparison\n\n```typescript\nimport { constantTimeCompare } from \"@oppulence/core\";\n\n// Timing-safe string comparison (prevents timing attacks)\nif (constantTimeCompare(providedToken, storedToken)) {\n  // Tokens match\n}\n```\n\n## Async Context (AsyncLocalStorage)\n\nSafe wrapper around Node.js AsyncLocalStorage for request-scoped context.\n\n### Basic Usage\n\n```typescript\nimport { SafeAsyncLocalStorage, createAsyncLocalStorage } from \"@oppulence/core\";\n\ninterface RequestContext {\n  requestId: string;\n  userId?: string;\n  startTime: number;\n}\n\nconst requestContext = new SafeAsyncLocalStorage<RequestContext>();\n// or\nconst requestContext = createAsyncLocalStorage<RequestContext>();\n\n// Set context for a scope\nrequestContext.runWith(\n  { requestId: \"req-123\", startTime: Date.now() },\n  async () => {\n    // Context is available in all async operations\n    await handleRequest();\n  }\n);\n\n// Access context anywhere in the call chain\nfunction logMessage(msg: string) {\n  const ctx = requestContext.getStore();\n  if (ctx) {\n    console.log(`[${ctx.requestId}] ${msg}`);\n  }\n}\n```\n\n### Safe Access Methods\n\n```typescript\n// Get with default value\nconst ctx = requestContext.getStoreOrDefault({\n  requestId: \"unknown\",\n  startTime: 0,\n});\n\n// Get or throw (for required context)\ntry {\n  const ctx = requestContext.getStoreOrThrow(\"Context required\");\n} catch (e) {\n  // Handle missing context\n}\n\n// Check if context exists\nif (requestContext.hasStore()) {\n  const ctx = requestContext.getStore()!;\n}\n```\n\n### Update Context\n\n```typescript\nrequestContext.runWith(\n  { requestId: \"req-123\", startTime: Date.now() },\n  async () => {\n    // Later, after authentication\n    requestContext.update({ userId: \"user-456\" });\n\n    // Context now has both requestId and userId\n    const ctx = requestContext.getStore();\n    // { requestId: 'req-123', startTime: ..., userId: 'user-456' }\n  }\n);\n```\n\n### Middleware Helper\n\n```typescript\n// Create middleware for Express/Koa-like frameworks\nconst withContext = requestContext.middleware((req: Request) => ({\n  requestId: (req.headers[\"x-request-id\"] as string) || generateId(),\n  startTime: Date.now(),\n}));\n\n// Wrap handlers\napp.get(\n  \"/api/users\",\n  withContext(async (req, res) => {\n    const ctx = requestContext.getStore();\n    // Context is automatically set\n  })\n);\n```\n\n### Exit Context\n\n```typescript\nrequestContext.runWith({ requestId: \"req-123\" }, () => {\n  console.log(requestContext.getStore()); // { requestId: 'req-123' }\n\n  // Run code outside the context\n  requestContext.exit(() => {\n    console.log(requestContext.getStore()); // undefined\n  });\n\n  console.log(requestContext.getStore()); // { requestId: 'req-123' }\n});\n```\n\n## Shutdown Management\n\nGraceful shutdown handling with priority ordering and timeouts.\n\n### Basic Usage\n\n```typescript\nimport { shutdownManager, ShutdownManager } from \"@oppulence/core\";\n\n// Register cleanup handlers\nshutdownManager.register(\"database\", async (signal) => {\n  console.log(`Closing database (${signal})`);\n  await database.close();\n});\n\nshutdownManager.register(\"cache\", async () => {\n  await cache.flush();\n});\n\n// Handlers run automatically on SIGTERM/SIGINT\n```\n\n### Priority and Timeout\n\n```typescript\n// Lower priority runs first\nshutdownManager.register(\n  \"critical-cleanup\",\n  async () => {\n    await flushLogs();\n  },\n  {\n    priority: 0, // Runs first\n    timeout: 5000, // 5 second timeout\n  }\n);\n\nshutdownManager.register(\n  \"database\",\n  async () => {\n    await database.close();\n  },\n  {\n    priority: 10, // Runs after priority 0\n    timeout: 10000, // 10 second timeout\n  }\n);\n\nshutdownManager.register(\n  \"optional-cleanup\",\n  async () => {\n    await sendMetrics();\n  },\n  {\n    priority: 100, // Runs last\n    timeout: 2000,\n    signals: [\"SIGTERM\"], // Only on SIGTERM, not SIGINT\n  }\n);\n```\n\n### Manual Shutdown\n\n```typescript\n// Trigger shutdown manually\nawait shutdownManager.shutdown(\"SIGTERM\");\n\n// With options\nawait shutdownManager.shutdown(\"SIGTERM\", {\n  timeout: 30000, // Global timeout\n  skipExit: true, // Don't call process.exit (useful for testing)\n});\n```\n\n## Utility Functions\n\n### Debounce\n\nCollapse multiple calls into one:\n\n```typescript\nimport { debounce } from \"@oppulence/core\";\n\nconst debouncedSave = debounce(saveDocument, 1000, {\n  leading: false, // Don't execute on leading edge\n  trailing: true, // Execute on trailing edge (default)\n  maxWait: 5000, // Maximum time to wait\n});\n\n// Multiple rapid calls\ndebouncedSave(doc);\ndebouncedSave(doc);\ndebouncedSave(doc); // Only this executes after 1 second\n\n// Control methods\ndebouncedSave.cancel(); // Cancel pending execution\ndebouncedSave.flush(); // Execute immediately\ndebouncedSave.pending(); // Check if execution is pending\n```\n\n### Throttle\n\nRate-limit function calls:\n\n```typescript\nimport { throttle } from \"@oppulence/core\";\n\nconst throttledScroll = throttle(handleScroll, 100, {\n  leading: true, // Execute on leading edge\n  trailing: true, // Execute on trailing edge\n});\n\nwindow.addEventListener(\"scroll\", throttledScroll);\n// Executes at most once per 100ms\n```\n\n### Memoize\n\nCache function results:\n\n```typescript\nimport { memoize, memoizeAsync } from \"@oppulence/core\";\n\n// Sync memoization\nconst expensiveCalc = memoize(\n  (n: number) => {\n    // Complex calculation\n    return fibonacci(n);\n  },\n  {\n    maxSize: 100, // LRU cache size\n    ttl: 60000, // Cache TTL in ms\n  }\n);\n\n// Async memoization\nconst fetchUser = memoizeAsync(\n  async (id: string) => {\n    return await api.getUser(id);\n  },\n  {\n    maxSize: 50,\n    ttl: 300000, // 5 minutes\n    resolver: (id) => id, // Custom cache key\n  }\n);\n\n// Methods\nexpensiveCalc.clear(); // Clear cache\n```\n\n### Sleep\n\n```typescript\nimport { sleep, sleepWithSignal, delay } from \"@oppulence/core\";\n\n// Simple delay\nawait sleep(1000); // Wait 1 second\n\n// Cancellable delay\nconst controller = new AbortController();\nsetTimeout(() => controller.abort(), 500);\n\ntry {\n  await sleepWithSignal(1000, controller.signal);\n} catch (e) {\n  console.log(\"Sleep was cancelled\");\n}\n\n// Delay with cleanup\nconst { promise, cancel } = delay(1000);\nsetTimeout(cancel, 500); // Cancel after 500ms\ntry {\n  await promise;\n} catch (e) {\n  console.log(\"Delay was cancelled\");\n}\n```\n\n### Retry\n\n```typescript\nimport { retry } from \"@oppulence/core\";\n\nconst result = await retry(\n  async () => {\n    const response = await fetch(\"/api/data\");\n    if (!response.ok) throw new Error(\"Request failed\");\n    return response.json();\n  },\n  {\n    maxAttempts: 3,\n    initialDelay: 1000,\n    maxDelay: 10000,\n    backoffFactor: 2, // Exponential backoff\n    shouldRetry: (error, attempt) => {\n      // Custom retry logic\n      return attempt < 3 && error.message !== \"Not Found\";\n    },\n  }\n);\n```\n\n### Deep Merge\n\n```typescript\nimport { deepMerge, deepMergeWithOptions, deepFreeze } from \"@oppulence/core\";\n\nconst defaults = {\n  server: { host: \"localhost\", port: 3000 },\n  logging: { level: \"info\" },\n};\n\nconst overrides = {\n  server: { port: 8080 },\n  logging: { format: \"json\" },\n};\n\nconst config = deepMerge(defaults, overrides);\n// {\n//   server: { host: 'localhost', port: 8080 },\n//   logging: { level: 'info', format: 'json' }\n// }\n\n// With options\nconst merged = deepMergeWithOptions(defaults, overrides, {\n  arrayMerge: \"replace\", // 'replace' | 'concat' | 'unique'\n  clone: true, // Clone objects instead of mutating\n});\n\n// Deep freeze for immutability\nconst frozen = deepFreeze(config);\nfrozen.server.port = 9000; // TypeError in strict mode\n```\n\n### Deep Get/Set\n\n```typescript\nimport { getDeep, setDeep } from \"@oppulence/core\";\n\nconst obj = { user: { profile: { name: \"John\" } } };\n\n// Get nested value\nconst name = getDeep(obj, \"user.profile.name\"); // 'John'\nconst missing = getDeep(obj, \"user.profile.age\", 0); // 0 (default)\n\n// Set nested value (returns new object)\nconst updated = setDeep(obj, \"user.profile.age\", 30);\n// { user: { profile: { name: 'John', age: 30 } } }\n```\n\n### Pick and Omit\n\n```typescript\nimport { pick, pickBy, omit } from \"@oppulence/core\";\n\nconst user = { id: 1, name: \"John\", password: \"secret\", role: \"admin\" };\n\n// Pick specific keys\nconst public = pick(user, [\"id\", \"name\"]);\n// { id: 1, name: 'John' }\n\n// Pick by predicate\nconst strings = pickBy(user, (value) => typeof value === \"string\");\n// { name: 'John', password: 'secret', role: 'admin' }\n\n// Omit keys\nconst safe = omit(user, [\"password\"]);\n// { id: 1, name: 'John', role: 'admin' }\n```\n\n### Singleton Pattern\n\n```typescript\nimport { singleton } from \"@oppulence/core\";\n\n// Create or retrieve singleton instance\nconst cache = singleton(\"app-cache\", () => new Map());\nconst sameCache = singleton(\"app-cache\", () => new Map());\n\nconsole.log(cache === sameCache); // true\n```\n\n## Type Utilities\n\n### Branded Types\n\nPrevent mixing up values with the same underlying type:\n\n```typescript\nimport { Brand, brand, UserId, TeamId, Email } from '@oppulence/core';\n\n// Pre-defined branded types\nconst userId: UserId = brand<UserId>('user_123');\nconst teamId: TeamId = brand<TeamId>('team_456');\nconst email: Email = brand<Email>('john@example.com');\n\n// Custom branded types\ntype OrderId = Brand<string, 'OrderId'>;\ntype SKU = Brand<string, 'SKU'>;\n\nfunction getOrder(id: OrderId): Order { ... }\n\nconst orderId = brand<OrderId>('order_789');\ngetOrder(orderId); // OK\ngetOrder(userId);  // Type error!\n```\n\n### Deep Utility Types\n\n```typescript\nimport {\n  DeepPartial,\n  DeepReadonly,\n  DeepRequired,\n  DeepMutable,\n} from \"@oppulence/core\";\n\ninterface Config {\n  server: {\n    host: string;\n    port: number;\n    ssl: {\n      enabled: boolean;\n      cert: string;\n    };\n  };\n}\n\n// All nested properties optional\ntype PartialConfig = DeepPartial<Config>;\n\n// All nested properties readonly\ntype ImmutableConfig = DeepReadonly<Config>;\n\n// All nested properties required\ntype FullConfig = DeepRequired<Config>;\n\n// Remove readonly from all nested properties\ntype MutableConfig = DeepMutable<ImmutableConfig>;\n```\n\n### Other Utility Types\n\n```typescript\nimport {\n  RequireKeys,\n  PartialKeys,\n  Prettify,\n  Awaitable,\n  MaybeArray,\n  AsyncReturnType,\n  KeysOfType,\n  PickByType,\n  OmitByType,\n  JsonValue,\n  Jsonify,\n} from \"@oppulence/core\";\n\n// Make specific keys required\ntype UserCreate = RequireKeys<User, \"email\" | \"name\">;\n\n// Make specific keys optional\ntype UserUpdate = PartialKeys<User, \"name\" | \"avatar\">;\n\n// Expand complex types for readability\ntype Expanded = Prettify<SomeComplexIntersection>;\n\n// Value or Promise of value\ntype Handler = (req: Request) => Awaitable<Response>;\n\n// Single or array\ntype Input = MaybeArray<string>; // string | string[]\n\n// Get return type of async function\ntype UserData = AsyncReturnType<typeof fetchUser>;\n\n// Get keys by value type\ntype StringKeys = KeysOfType<User, string>; // 'name' | 'email'\n\n// JSON serialization type\ntype ApiResponse = Jsonify<InternalUser>; // Converts Date to string, removes functions\n```\n\n## Schemas\n\nZod schemas for common patterns:\n\n```typescript\nimport {\n  RetryOptionsSchema,\n  RateLimitOptionsSchema,\n  // ... other schemas\n} from \"@oppulence/core\";\n\n// Validate configuration\nconst config = RetryOptionsSchema.parse({\n  maxAttempts: 3,\n  initialDelay: 1000,\n});\n```\n\n## API Reference\n\n### Error Handling\n\n| Function                                         | Description                          |\n| ------------------------------------------------ | ------------------------------------ |\n| `tryCatch<T, E>(promise)`                        | Wrap async operation in Result tuple |\n| `tryCatchSync<T, E>(fn)`                         | Wrap sync operation in Result tuple  |\n| `tryCatchWithTimeout<T, E>(promise, ms, error?)` | With timeout                         |\n| `tryCatchWithAbort<T, E>(promise, signal)`       | With abort signal                    |\n| `mapResult<T, U, E>(result, fn)`                 | Transform success value              |\n| `flatMapResult<T, U, E>(result, fn)`             | Chain Result operations              |\n| `isSuccess<T, E>(result)`                        | Type guard for success               |\n| `isFailure<T, E>(result)`                        | Type guard for failure               |\n| `unwrapResult<T, E>(result)`                     | Extract value or throw               |\n| `unwrapResultOr<T, E>(result, default)`          | Extract value or default             |\n| `combineResults<T, E>(results)`                  | Combine array of Results             |\n\n### Logging\n\n| Method                                                 | Description         |\n| ------------------------------------------------------ | ------------------- |\n| `new Logger(name, level?, maskedKeys?, replacer?)`     | Create logger       |\n| `logger.log/info/warn/error/debug/verbose(msg, data?)` | Log at level        |\n| `logger.child(context)`                                | Create child logger |\n| `logger.withTraceContext(spanContext)`                 | Add trace context   |\n| `logger.enableBatching(options)`                       | Enable log batching |\n| `logger.disableBatching()`                             | Disable batching    |\n| `logger.flush()`                                       | Flush batched logs  |\n\n### Cryptography\n\n| Function                        | Description         |\n| ------------------------------- | ------------------- |\n| `digestSHA256(data)`            | SHA-256 hash        |\n| `digestSHA512(data)`            | SHA-512 hash        |\n| `hmacSHA256(key, data)`         | HMAC-SHA256         |\n| `hmacSHA512(key, data)`         | HMAC-SHA512         |\n| `generateRandomBytes(length)`   | Random bytes        |\n| `generateRandomHex(length)`     | Random hex string   |\n| `generateId(length?)`           | Random URL-safe ID  |\n| `constantTimeCompare(a, b)`     | Timing-safe compare |\n| `base64Encode/Decode(data)`     | Base64 encoding     |\n| `base64UrlEncode/Decode(data)`  | URL-safe Base64     |\n| `bufferToHex/hexToBuffer(data)` | Hex encoding        |\n\n### Utilities\n\n| Function                       | Description            |\n| ------------------------------ | ---------------------- |\n| `debounce(fn, wait, options?)` | Debounce function      |\n| `throttle(fn, wait, options?)` | Throttle function      |\n| `memoize(fn, options?)`        | Memoize sync function  |\n| `memoizeAsync(fn, options?)`   | Memoize async function |\n| `sleep(ms)`                    | Promise-based delay    |\n| `sleepWithSignal(ms, signal)`  | Cancellable delay      |\n| `retry(fn, options?)`          | Retry with backoff     |\n| `delay(ms)`                    | Delay with cancel      |\n| `deepMerge(...objects)`        | Deep merge objects     |\n| `deepFreeze(obj)`              | Deep freeze object     |\n| `getDeep(obj, path, default?)` | Get nested value       |\n| `setDeep(obj, path, value)`    | Set nested value       |\n| `pick(obj, keys)`              | Pick object keys       |\n| `pickBy(obj, predicate)`       | Pick by predicate      |\n| `omit(obj, keys)`              | Omit object keys       |\n| `singleton(key, factory)`      | Get/create singleton   |\n\n### AsyncLocalStorage\n\n| Method                       | Description          |\n| ---------------------------- | -------------------- |\n| `runWith(context, fn)`       | Run with context     |\n| `run(context, fn)`           | Alias for runWith    |\n| `enterWith(context)`         | Set context directly |\n| `exit(fn)`                   | Run outside context  |\n| `getStore()`                 | Get current context  |\n| `getStoreOrDefault(default)` | Get or default       |\n| `getStoreOrThrow(message?)`  | Get or throw         |\n| `hasStore()`                 | Check if context set |\n| `update(partial)`            | Update context       |\n| `middleware(getContext)`     | Create middleware    |\n| `disable()`                  | Disable storage      |\n\n### Shutdown Manager\n\n| Method                              | Description      |\n| ----------------------------------- | ---------------- |\n| `register(name, handler, options?)` | Register handler |\n| `shutdown(signal, options?)`        | Trigger shutdown |\n\n## Environment Variables\n\n| Variable            | Description        |\n| ------------------- | ------------------ |\n| `TRIGGER_LOG_LEVEL` | Override log level |\n| `NODE_ENV`          | Environment mode   |\n\n## License\n\nISC\n","readmeFilename":"README.md"}