@mks2508/coolify-mks-cli-mcp 0.6.2 → 0.8.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.
Files changed (60) hide show
  1. package/dist/cli/coolify-state.d.ts +92 -4
  2. package/dist/cli/coolify-state.d.ts.map +1 -1
  3. package/dist/cli/index.js +22228 -11529
  4. package/dist/cli/ui/highlighter.d.ts +28 -0
  5. package/dist/cli/ui/highlighter.d.ts.map +1 -0
  6. package/dist/cli/ui/index.d.ts +9 -0
  7. package/dist/cli/ui/index.d.ts.map +1 -0
  8. package/dist/cli/ui/spinners.d.ts +100 -0
  9. package/dist/cli/ui/spinners.d.ts.map +1 -0
  10. package/dist/cli/ui/tables.d.ts +103 -0
  11. package/dist/cli/ui/tables.d.ts.map +1 -0
  12. package/dist/coolify/index.d.ts +22 -3
  13. package/dist/coolify/index.d.ts.map +1 -1
  14. package/dist/coolify/types.d.ts +99 -1
  15. package/dist/coolify/types.d.ts.map +1 -1
  16. package/dist/examples/demo-ui.d.ts +8 -0
  17. package/dist/examples/demo-ui.d.ts.map +1 -0
  18. package/dist/index.cjs +322 -12
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.js +322 -12
  21. package/dist/index.js.map +1 -1
  22. package/dist/sdk.d.ts +41 -0
  23. package/dist/sdk.d.ts.map +1 -1
  24. package/dist/server/stdio.js +258 -9
  25. package/package.json +19 -4
  26. package/src/cli/actions.ts +9 -2
  27. package/src/cli/commands/create.ts +71 -5
  28. package/src/cli/commands/db.ts +37 -0
  29. package/src/cli/commands/delete.ts +6 -2
  30. package/src/cli/commands/deploy.ts +347 -49
  31. package/src/cli/commands/deployments.ts +6 -2
  32. package/src/cli/commands/diagnose.ts +3 -3
  33. package/src/cli/commands/env.ts +121 -22
  34. package/src/cli/commands/exec.ts +6 -2
  35. package/src/cli/commands/init.ts +937 -0
  36. package/src/cli/commands/logs.ts +224 -24
  37. package/src/cli/commands/main-menu.ts +21 -0
  38. package/src/cli/commands/projects.ts +312 -29
  39. package/src/cli/commands/restart.ts +6 -2
  40. package/src/cli/commands/service-logs.ts +14 -0
  41. package/src/cli/commands/show.ts +6 -2
  42. package/src/cli/commands/start.ts +6 -2
  43. package/src/cli/commands/status.ts +538 -0
  44. package/src/cli/commands/stop.ts +6 -2
  45. package/src/cli/commands/update.ts +27 -2
  46. package/src/cli/coolify-state.ts +164 -11
  47. package/src/cli/index.ts +91 -10
  48. package/src/cli/name-resolver.ts +228 -0
  49. package/src/cli/ui/banner.ts +276 -0
  50. package/src/cli/ui/highlighter.ts +176 -0
  51. package/src/cli/ui/index.ts +9 -0
  52. package/src/cli/ui/prompts.ts +155 -0
  53. package/src/cli/ui/screen.ts +606 -0
  54. package/src/cli/ui/select.ts +280 -0
  55. package/src/cli/ui/spinners.ts +256 -0
  56. package/src/cli/ui/tables.ts +407 -0
  57. package/src/coolify/index.ts +257 -12
  58. package/src/coolify/types.ts +103 -1
  59. package/src/examples/demo-ui.ts +78 -0
  60. package/src/sdk.ts +162 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["DEFAULT_CONFIG","DEFAULT_CONFIG","err","index","DEFAULT_CONFIG$1","endpoint: string","options: RequestInit","data: T | undefined","options: ICoolifyDeployOptions","onProgress?: IProgressCallback","options: ICoolifyAppOptions","endpointMap: Record<string, string>","body: Record<string, unknown>","appUuid: string","envVars: Record<string, string>","key: string","value: string","_isBuildTime: boolean","page?: number","perPage?: number","serverUuid: string","name: string","description?: string","projectUuid: string","teamId?: string","projectId?: string","options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n }","options: ICoolifyUpdateOptions","options: ICoolifyLogsOptions","logsArray: string[]","l: string","command: string","envVars: Array<{\n key: string;\n value: string;\n is_preview?: boolean;\n }>","options?: { force?: boolean; instantDeploy?: boolean }","uuid: string","dbType: string","data: Record<string, unknown>","databaseUuid: string","backupUuid: string","data: { key: string; value: string; is_preview?: boolean }","data: { name?: string; description?: string }","data: { name: string; description?: string }","id: number","deploymentUuid: string","data: {\n name: string;\n private_key: string;\n description?: string;\n }","data: { name?: string; private_key?: string; description?: string }","skip: number","take: number","query: string","apps","issues: string[]","issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }>","failed: string[]","force: boolean","instance: CoolifyService | null","result: Result<T, Error>","svc: CoolifyService","options?: { teamId?: string; projectId?: string } & IPaginationOptions","query: string","options: ICoolifyAppOptions","onProgress?: IProgressCallback","uuid: string","options?: { force?: boolean; tag?: string }","options?: { force?: boolean; instantDeploy?: boolean }","options?: IDeleteOptions","options: ICoolifyUpdateOptions","options?: ICoolifyLogsOptions","skip?: number","take?: number","command: string","key: string","value: string","isBuildTime?: boolean","vars: Array<{ key: string; value: string; is_preview?: boolean }>","options?: IPaginationOptions","type: string","data: Record<string, unknown>","dbUuid: string","backupUuid: string","data: { key: string; value: string; is_preview?: boolean }","name: string","description?: string","data: { name?: string; description?: string }","projectUuid: string","data: { name: string; description?: string }","id: number","teamId: number","data: {\n name: string;\n private_key: string;\n description?: string;\n }","data: { name?: string; private_key?: string; description?: string }","deploymentUuid: string","appUuid: string","servicesToTest?: string[]","force?: boolean","options?: ICoolifyOptions","resource: T","coolifyTools: Tool[]","_sdk: Coolify | null","fn: (sdk: Coolify) => Promise<unknown>","label: string","fn: (sdk: Coolify) => Promise<unknown[]>","itemKey: string","name: string","args: Record<string, unknown>","d: string","operation: string","onStep?: TraceCallback","step: string","detail?: string","traceStep: ITraceStep","success: boolean","error?: string","svc: CoolifyService","uuid: string","command: string","appUuid: string","servicesToTest: string[]","networkEnv: Record<string, string>","dns: INetworkInfo[\"dns\"]","connectivity: INetworkInfo[\"connectivity\"]","deploymentUuid: string","ERROR_PATTERNS: Array<{\n pattern: RegExp;\n category: IDeployFailureAnalysis[\"category\"];\n summary: string;\n suggestion: string;\n}>","uuid: string | undefined","field: keyof ICoolifyDeployState"],"sources":["../../../../node_modules/.bun/@mks2508+no-throw@0.1.0/node_modules/@mks2508/no-throw/dist/index.mjs","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/environment-COWvu6Wz.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/Logger-D-gmmgR2.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/formatting-CYjT9yhO.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/index.js","../src/coolify/config.ts","../src/coolify/index.ts","../src/sdk.ts","../src/tools/definitions.ts","../src/tools/handlers.ts","../src/trace.ts","../src/network.ts","../src/cli/coolify-state.ts","../src/index.ts"],"sourcesContent":["//#region src/result.ts\n/**\n* Creates a successful Result containing the given value.\n*\n* @template T - The type of the success value\n* @param value - The value to wrap in an Ok\n* @returns An Ok containing the value\n*\n* @example\n* ```typescript\n* const result = ok(42)\n* // result.ok === true\n* // result.value === 42\n* ```\n*/\nfunction ok(value) {\n\treturn {\n\t\tok: true,\n\t\tvalue\n\t};\n}\n/**\n* Creates a failed Result containing the given error.\n*\n* @template E - The type of the error value\n* @param error - The error to wrap in an Err\n* @returns An Err containing the error\n*\n* @example\n* ```typescript\n* const result = err('Something went wrong')\n* // result.ok === false\n* // result.error === 'Something went wrong'\n* ```\n*/\nfunction err(error) {\n\treturn {\n\t\tok: false,\n\t\terror\n\t};\n}\n/**\n* Type guard that narrows a Result to Ok.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to check\n* @returns `true` if the Result is Ok, enabling type narrowing\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = ok(42)\n*\n* if (isOk(result)) {\n* // TypeScript knows result.value exists here\n* console.log(result.value)\n* }\n* ```\n*/\nfunction isOk(result) {\n\treturn result.ok;\n}\n/**\n* Type guard that narrows a Result to Err.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to check\n* @returns `true` if the Result is Err, enabling type narrowing\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = err('failed')\n*\n* if (isErr(result)) {\n* // TypeScript knows result.error exists here\n* console.error(result.error)\n* }\n* ```\n*/\nfunction isErr(result) {\n\treturn !result.ok;\n}\n/**\n* Extracts the value from an Ok Result or throws an error if Err.\n*\n* **Warning**: This function throws. Prefer `unwrapOr`, `unwrapOrElse`, or `match`\n* for safer error handling.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @returns The contained value if Ok\n* @throws Error with message from ResultError or stringified error if Err\n*\n* @example\n* ```typescript\n* const success = ok(42)\n* unwrap(success) // Returns 42\n*\n* const failure = err('oops')\n* unwrap(failure) // Throws Error: 'Unwrap called on Err: oops'\n* ```\n*/\nfunction unwrap(result) {\n\tif (isOk(result)) return result.value;\n\tconst errMsg = result.error instanceof Object && \"message\" in result.error ? result.error.message : String(result.error);\n\tthrow new Error(`Unwrap called on Err: ${errMsg}`);\n}\n/**\n* Extracts the value from an Ok Result or returns a default value if Err.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @param defaultValue - The value to return if the Result is Err\n* @returns The contained value if Ok, otherwise the default value\n*\n* @example\n* ```typescript\n* unwrapOr(ok(42), 0) // Returns 42\n* unwrapOr(err('oops'), 0) // Returns 0\n* ```\n*/\nfunction unwrapOr(result, defaultValue) {\n\treturn isOk(result) ? result.value : defaultValue;\n}\n/**\n* Extracts the value from an Ok Result or computes a value from the error if Err.\n*\n* Unlike `unwrapOr`, the default value is lazily computed only when needed.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @param fn - Function to compute the default value from the error\n* @returns The contained value if Ok, otherwise the computed value\n*\n* @example\n* ```typescript\n* unwrapOrElse(ok(42), () => 0) // Returns 42\n* unwrapOrElse(err('error'), (e) => e.length) // Returns 5\n* unwrapOrElse(err('not found'), () => fetchDefault()) // Only fetches on error\n* ```\n*/\nfunction unwrapOrElse(result, fn) {\n\treturn isOk(result) ? result.value : fn(result.error);\n}\n/**\n* Transforms the Ok value using the provided function, leaving Err unchanged.\n*\n* This is the functor map operation for Result, allowing you to transform\n* success values while automatically propagating errors.\n*\n* @template T - The type of the input success value\n* @template U - The type of the output success value\n* @template E - The type of the error value\n* @param result - The Result to transform\n* @param fn - Function to apply to the Ok value\n* @returns A new Result with the transformed value, or the original Err\n*\n* @example\n* ```typescript\n* map(ok(2), x => x * 2) // ok(4)\n* map(err('oops'), x => x * 2) // err('oops')\n*\n* // Chaining transformations\n* const result = ok('hello')\n* const upper = map(result, s => s.toUpperCase())\n* const length = map(upper, s => s.length)\n* // length = ok(5)\n* ```\n*/\nfunction map(result, fn) {\n\treturn isOk(result) ? ok(fn(result.value)) : result;\n}\n/**\n* Transforms the Err value using the provided function, leaving Ok unchanged.\n*\n* Useful for converting error types or adding context to errors.\n*\n* @template T - The type of the success value\n* @template E - The type of the input error value\n* @template F - The type of the output error value\n* @param result - The Result to transform\n* @param fn - Function to apply to the Err value\n* @returns A new Result with the transformed error, or the original Ok\n*\n* @example\n* ```typescript\n* mapErr(err('oops'), e => e.toUpperCase()) // err('OOPS')\n* mapErr(ok(42), e => e.toUpperCase()) // ok(42)\n*\n* // Converting error types\n* const result = err('not found')\n* const typed = mapErr(result, msg => ({ code: 'NOT_FOUND', message: msg }))\n* ```\n*/\nfunction mapErr(result, fn) {\n\treturn isErr(result) ? err(fn(result.error)) : result;\n}\n/**\n* Chains a function that returns a Result over the Ok value (monadic bind).\n*\n* Unlike `map`, the function returns a Result, which is then flattened.\n* This enables composing operations that may fail.\n*\n* @template T - The type of the input success value\n* @template U - The type of the output success value\n* @template E - The type of the error value\n* @param result - The Result to chain\n* @param fn - Function that takes the Ok value and returns a new Result\n* @returns The Result from fn if input is Ok, otherwise the original Err\n*\n* @example\n* ```typescript\n* const parseNumber = (s: string): Result<number, string> => {\n* const n = parseInt(s, 10)\n* return isNaN(n) ? err('not a number') : ok(n)\n* }\n*\n* const divide = (a: number, b: number): Result<number, string> =>\n* b === 0 ? err('division by zero') : ok(a / b)\n*\n* // Chain operations that may fail\n* const result = flatMap(parseNumber('10'), n => divide(n, 2))\n* // result = ok(5)\n*\n* const failed = flatMap(parseNumber('abc'), n => divide(n, 2))\n* // failed = err('not a number')\n* ```\n*/\nfunction flatMap(result, fn) {\n\treturn isOk(result) ? fn(result.value) : result;\n}\n/**\n* Executes a side effect on the Ok value without changing the Result.\n*\n* Useful for logging, debugging, or other side effects in a pipeline.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to tap\n* @param fn - Side effect function to execute on Ok value\n* @returns The original Result unchanged\n*\n* @example\n* ```typescript\n* const result = ok(42)\n* const same = tap(result, v => console.log('Got:', v))\n* // Logs: 'Got: 42'\n* // same === result\n*\n* tap(err('oops'), v => console.log('Got:', v))\n* // Does not log anything\n* ```\n*/\nfunction tap(result, fn) {\n\tif (isOk(result)) fn(result.value);\n\treturn result;\n}\n/**\n* Executes a side effect on the Err value without changing the Result.\n*\n* Useful for logging errors or triggering error reporting.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to tap\n* @param fn - Side effect function to execute on Err value\n* @returns The original Result unchanged\n*\n* @example\n* ```typescript\n* const result = err('oops')\n* const same = tapErr(result, e => console.error('Error:', e))\n* // Logs: 'Error: oops'\n* // same === result\n*\n* tapErr(ok(42), e => console.error('Error:', e))\n* // Does not log anything\n* ```\n*/\nfunction tapErr(result, fn) {\n\tif (isErr(result)) fn(result.error);\n\treturn result;\n}\n/**\n* Pattern matches on a Result, applying the appropriate handler function.\n*\n* Provides exhaustive handling of both Ok and Err cases, ensuring you\n* handle all possibilities.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @template U - The type of the return value from both handlers\n* @param result - The Result to match on\n* @param handlers - Object containing `onOk` and `onErr` handler functions\n* @returns The return value from whichever handler was called\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = ok(42)\n*\n* const message = match(result, {\n* onOk: (value) => `Success: ${value}`,\n* onErr: (error) => `Failed: ${error}`\n* })\n* // message = 'Success: 42'\n*\n* // Transforming to different types\n* const status = match(fetchResult, {\n* onOk: (data) => ({ status: 'loaded', data }),\n* onErr: (err) => ({ status: 'error', message: err.message })\n* })\n* ```\n*/\nfunction match(result, handlers) {\n\treturn isOk(result) ? handlers.onOk(result.value) : handlers.onErr(result.error);\n}\n/**\n* Collects an array of Results into a Result containing an array.\n*\n* If all Results are Ok, returns Ok with an array of all values.\n* If any Result is Err, returns the first Err encountered.\n*\n* @template T - The type of the success values\n* @template E - The type of the error value\n* @param results - Array of Results to collect\n* @returns Ok with array of values if all succeed, or first Err\n*\n* @example\n* ```typescript\n* collect([ok(1), ok(2), ok(3)])\n* // ok([1, 2, 3])\n*\n* collect([ok(1), err('first'), err('second')])\n* // err('first')\n*\n* collect([])\n* // ok([])\n*\n* // Useful for validating multiple fields\n* const validations = [\n* validateName(name),\n* validateEmail(email),\n* validateAge(age)\n* ]\n* const allValid = collect(validations)\n* ```\n*/\nfunction collect(results) {\n\tconst values = [];\n\tfor (const result of results) {\n\t\tif (isErr(result)) return result;\n\t\tvalues.push(result.value);\n\t}\n\treturn ok(values);\n}\nfunction all(...results) {\n\treturn collect(results);\n}\n\n//#endregion\n//#region src/error.ts\n/**\n* Creates a ResultError with the given code, message, and optional cause.\n*\n* @template C - The type of error code (inferred from the code parameter)\n* @param code - Unique error code identifying the type of error\n* @param message - Human-readable error message\n* @param cause - Optional original error that caused this error\n* @returns A new ResultError object\n*\n* @example\n* ```typescript\n* // Basic error\n* const error = resultError('NOT_FOUND', 'User not found')\n* // { code: 'NOT_FOUND', message: 'User not found' }\n*\n* // With cause\n* try {\n* await fetchUser(id)\n* } catch (e) {\n* const error = resultError('FETCH_FAILED', 'Could not fetch user', e as Error)\n* return err(error)\n* }\n*\n* // With typed error codes\n* const ApiError = {\n* NotFound: 'NOT_FOUND',\n* Timeout: 'TIMEOUT'\n* } as const\n*\n* const typedError = resultError(ApiError.NotFound, 'Resource not found')\n* // typedError.code is typed as 'NOT_FOUND'\n* ```\n*/\nfunction resultError(code, message, cause) {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\tcause\n\t};\n}\n/**\n* Default error code for unknown or unspecified errors.\n*\n* Use this when catching exceptions that don't map to a specific error code\n* in your domain.\n*\n* @example\n* ```typescript\n* import { tryCatch, UNKNOWN_ERROR } from '@mks2508/no-throw'\n*\n* const result = tryCatch(() => {\n* throw new Error('Unexpected!')\n* })\n*\n* if (isErr(result)) {\n* console.log(result.error.code) // 'UNKNOWN'\n* }\n*\n* // Or provide a specific code\n* const result2 = tryCatch(() => {\n* throw new Error('Unexpected!')\n* }, 'PARSING_ERROR')\n*\n* if (isErr(result2)) {\n* console.log(result2.error.code) // 'PARSING_ERROR'\n* }\n* ```\n*/\nconst UNKNOWN_ERROR = \"UNKNOWN\";\n\n//#endregion\n//#region src/utils.ts\n/**\n* @fileoverview Utility functions for exception wrapping and Result creation.\n* @module @mks2508/no-throw/utils\n*/\n/**\n* Creates a failure Result with a structured ResultError.\n*\n* This is a convenience function that combines `err()` and `resultError()`\n* for creating typed error Results in a single call.\n*\n* @template C - The type of error code (inferred from the code parameter)\n* @param code - Unique error code identifying the type of error\n* @param message - Human-readable error message\n* @param cause - Optional original error that caused this error\n* @returns An Err Result containing the ResultError\n*\n* @example\n* ```typescript\n* // Basic usage\n* function findUser(id: string): Result<User, ResultError<'NOT_FOUND'>> {\n* const user = db.get(id)\n* if (!user) {\n* return fail('NOT_FOUND', `User ${id} not found`)\n* }\n* return ok(user)\n* }\n*\n* // With error chaining\n* async function fetchData(url: string): Promise<Result<Data, ResultError>> {\n* try {\n* const response = await fetch(url)\n* if (!response.ok) {\n* return fail('HTTP_ERROR', `Request failed: ${response.status}`)\n* }\n* return ok(await response.json())\n* } catch (e) {\n* return fail('NETWORK_ERROR', 'Network request failed', e as Error)\n* }\n* }\n*\n* // With typed error codes\n* const UserError = {\n* NotFound: 'USER_NOT_FOUND',\n* InvalidEmail: 'INVALID_EMAIL',\n* Suspended: 'USER_SUSPENDED'\n* } as const\n*\n* type UserError = ResultError<ErrorCode<typeof UserError>>\n*\n* function validateUser(email: string): Result<void, UserError> {\n* if (!email.includes('@')) {\n* return fail(UserError.InvalidEmail, 'Email must contain @')\n* }\n* return ok(undefined)\n* }\n* ```\n*/\nfunction fail(code, message, cause) {\n\treturn err(resultError(code, message, cause));\n}\n/**\n* Converts a Promise that may reject into a Promise that resolves to a Result.\n*\n* This is useful for integrating with APIs that use exceptions for error handling,\n* wrapping them in the Result pattern.\n*\n* @template T - The type of the resolved value\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param promise - The Promise to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Promise that always resolves to a Result\n*\n* @example\n* ```typescript\n* // Basic usage with fetch\n* const result = await fromPromise(fetch('/api/users'))\n* if (isOk(result)) {\n* const response = result.value\n* }\n*\n* // With custom error code\n* const result = await fromPromise(\n* fetch('/api/users'),\n* 'NETWORK_ERROR'\n* )\n*\n* // Chaining with other Result operations\n* const users = await fromPromise(fetch('/api/users'))\n* .then(r => flatMap(r, async response => {\n* if (!response.ok) return fail('HTTP_ERROR', `Status: ${response.status}`)\n* return fromPromise(response.json(), 'PARSE_ERROR')\n* }))\n*\n* // Comparing approaches\n* // Before (exceptions)\n* try {\n* const response = await fetch('/api/users')\n* const data = await response.json()\n* return data\n* } catch (e) {\n* console.error(e)\n* return null\n* }\n*\n* // After (Result)\n* const result = await fromPromise(fetch('/api/users'), 'FETCH_ERROR')\n* if (isErr(result)) {\n* console.error(result.error.message)\n* return null\n* }\n* const data = await fromPromise(result.value.json(), 'PARSE_ERROR')\n* ```\n*/\nasync function fromPromise(promise, errorCode) {\n\ttry {\n\t\treturn ok(await promise);\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n/**\n* Wraps a synchronous function that may throw into a function returning Result.\n*\n* Use this to safely call code that might throw exceptions, converting them\n* into Results instead.\n*\n* @template T - The return type of the function\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param fn - The function to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Result containing either the return value or a ResultError\n*\n* @example\n* ```typescript\n* // Wrapping JSON.parse\n* const result = tryCatch(() => JSON.parse(jsonString))\n* if (isOk(result)) {\n* console.log(result.value)\n* } else {\n* console.error('Invalid JSON:', result.error.message)\n* }\n*\n* // With custom error code\n* const result = tryCatch(\n* () => JSON.parse(jsonString),\n* 'JSON_PARSE_ERROR'\n* )\n*\n* // Wrapping any throwing function\n* const result = tryCatch(() => {\n* const value = riskyOperation()\n* return transform(value)\n* }, 'OPERATION_FAILED')\n*\n* // Practical example: safe regex\n* function safeRegex(pattern: string): Result<RegExp, ResultError<'INVALID_REGEX'>> {\n* return tryCatch(() => new RegExp(pattern), 'INVALID_REGEX')\n* }\n*\n* const regex = safeRegex('[invalid')\n* // regex = err({ code: 'INVALID_REGEX', message: '...', cause: SyntaxError })\n* ```\n*/\nfunction tryCatch(fn, errorCode) {\n\ttry {\n\t\treturn ok(fn());\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n/**\n* Wraps an async function that may throw into a function returning Promise<Result>.\n*\n* Similar to `tryCatch` but for async functions. The function is immediately\n* invoked and its result is wrapped.\n*\n* @template T - The resolved type of the async function\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param fn - The async function to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Promise that resolves to a Result\n*\n* @example\n* ```typescript\n* // Basic usage\n* const result = await tryCatchAsync(async () => {\n* const response = await fetch('/api/data')\n* return response.json()\n* })\n*\n* // With custom error code\n* const result = await tryCatchAsync(\n* async () => {\n* const data = await fetchData()\n* return processData(data)\n* },\n* 'DATA_PROCESSING_ERROR'\n* )\n*\n* // Combining multiple async operations\n* const result = await tryCatchAsync(async () => {\n* const user = await db.users.findOne(id)\n* if (!user) throw new Error('User not found')\n*\n* const posts = await db.posts.find({ userId: user.id })\n* return { user, posts }\n* }, 'FETCH_USER_DATA')\n*\n* // Difference from fromPromise:\n* // - fromPromise: wraps an existing Promise\n* // - tryCatchAsync: creates and wraps a new Promise from an async function\n*\n* // Use fromPromise when you have a Promise:\n* const p = someAsyncOperation()\n* const r1 = await fromPromise(p, 'ERROR')\n*\n* // Use tryCatchAsync when you want to define the async logic:\n* const r2 = await tryCatchAsync(async () => {\n* // your async logic here\n* }, 'ERROR')\n* ```\n*/\nasync function tryCatchAsync(fn, errorCode) {\n\ttry {\n\t\treturn ok(await fn());\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n\n//#endregion\nexport { UNKNOWN_ERROR, all, collect, err, fail, flatMap, fromPromise, isErr, isOk, map, mapErr, match, ok, resultError, tap, tapErr, tryCatch, tryCatchAsync, unwrap, unwrapOr, unwrapOrElse };\n//# sourceMappingURL=index.mjs.map","function isMinifiedFile(filename) {\n const minifiedPatterns = [\n /\\.min\\.js$/,\n /\\.bundle\\.js$/,\n /\\.chunk\\.js$/,\n /-[\\w\\d]{8,}\\.js$/,\n // Hash-based filenames\n /Logger-[A-Za-z0-9]+\\.js$/,\n // Logger bundle files\n /node_modules/,\n /dist\\//,\n /build\\//,\n /\\.mjs$/\n ];\n return minifiedPatterns.some((pattern) => pattern.test(filename));\n}\nfunction extractCleanFilename(fullPath) {\n const filename = fullPath.split(/[/\\\\]/).pop() || fullPath;\n return filename.replace(/\\.min\\.js$/, \".js\").replace(/\\.bundle\\.js$/, \".js\").replace(/\\.chunk\\.js$/, \".js\").replace(/-[\\w\\d]{8,}\\.js$/, \".js\").replace(/Logger-[A-Za-z0-9]+\\.js$/, \"logger.ts\");\n}\nfunction parseStackTrace() {\n try {\n const stack = new Error().stack;\n if (!stack) {\n return null;\n }\n const lines = stack.split(\"\\n\").filter((line) => line.trim());\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n if (!line) {\n continue;\n }\n if (line.includes(\"parseStackTrace\") || line.includes(\"Logger.\") || line.includes(\".log(\") || line.includes(\"createStyledOutput\")) {\n continue;\n }\n let match;\n const chromeMatch = line.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/);\n if (chromeMatch) {\n const filename = chromeMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = chromeMatch;\n } else {\n const firefoxMatch = line.match(/(.+?)@(.+?):(\\d+):(\\d+)$/);\n if (firefoxMatch) {\n const filename = firefoxMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = firefoxMatch;\n } else {\n const safariMatch = line.match(/(\\S+)?@(.+?):(\\d+):(\\d+)$/);\n if (safariMatch) {\n const filename = safariMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = safariMatch;\n }\n }\n }\n if (!match) {\n continue;\n }\n const [, functionName, file, lineStr, columnStr] = match;\n if (!file) {\n continue;\n }\n const cleanFileName = extractCleanFilename(file).split(\"?\")[0];\n if (!cleanFileName) {\n continue;\n }\n const lineNum = lineStr ? parseInt(lineStr, 10) : 0;\n const columnNum = columnStr ? parseInt(columnStr, 10) : 0;\n const cleanFunction = functionName && functionName.trim() ? functionName.trim() : void 0;\n return {\n file: cleanFileName ? cleanFileName : \"unknown\",\n line: lineNum,\n column: columnNum,\n function: cleanFunction\n };\n }\n return null;\n } catch {\n return null;\n }\n}\nconst DEFAULT_CONFIG = {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n theme: \"default\",\n bannerType: \"simple\",\n bufferSize: 1e3,\n autoDetectTheme: true,\n outputFormat: \"auto\"\n};\nconst LEVEL_STYLES = {\n debug: {\n emoji: \"🔍\",\n label: \"DEBUG\",\n background: \"linear-gradient(90deg, #6c757d, #495057)\",\n color: \"#ffffff\",\n border: \"1px solid #6c757d\",\n shadow: \"0 2px 4px rgba(108, 117, 125, 0.3)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(90deg, #007bff, #0056b3)\",\n color: \"#ffffff\",\n border: \"1px solid #007bff\",\n shadow: \"0 2px 4px rgba(0, 123, 255, 0.3)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(90deg, #ffc107, #e0a800)\",\n color: \"#000000\",\n border: \"1px solid #ffc107\",\n shadow: \"0 2px 4px rgba(255, 193, 7, 0.3)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(90deg, #dc3545, #c82333)\",\n color: \"#ffffff\",\n border: \"1px solid #dc3545\",\n shadow: \"0 2px 4px rgba(220, 53, 69, 0.3)\"\n },\n critical: {\n emoji: \"🚨\",\n label: \"CRITICAL\",\n background: \"linear-gradient(90deg, #8B0000, #FF0000)\",\n color: \"#ffffff\",\n border: \"2px solid #FF0000\",\n shadow: \"0 4px 8px rgba(255, 0, 0, 0.4)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(90deg, #28a745, #1e7e34)\",\n color: \"#ffffff\",\n border: \"1px solid #28a745\",\n shadow: \"0 2px 4px rgba(40, 167, 69, 0.3)\"\n }\n};\nconst BUFFER_LIMITS = {\n MIN_SIZE: 50,\n DEFAULT_SIZE: 1e3,\n MAX_SIZE: 1e4\n};\nconst EXPORT_FORMATS = {\n json: { extension: \".json\", mimeType: \"application/json\" },\n csv: { extension: \".csv\", mimeType: \"text/csv\" },\n markdown: { extension: \".md\", mimeType: \"text/markdown\" },\n plain: { extension: \".txt\", mimeType: \"text/plain\" },\n html: { extension: \".html\", mimeType: \"text/html\" }\n};\nconst TIME_UNITS = {\n ms: 1,\n s: 1e3,\n m: 60 * 1e3,\n h: 60 * 60 * 1e3,\n d: 24 * 60 * 60 * 1e3\n};\nconst ADAPTIVE_COLORS = {\n timestamp: {\n light: \"#666666\",\n dark: \"#a0a0a0\"\n },\n messageText: {\n light: \"#2d3748\",\n dark: \"#f7fafc\"\n },\n prefix: {\n light: \"#2d3748\",\n dark: \"#e2e8f0\"\n },\n prefixBackground: {\n light: \"#2d3748\",\n dark: \"#4a5568\"\n },\n location: {\n light: \"#718096\",\n dark: \"#a0aec0\"\n }\n};\nconst BUILD_PRESETS = {\n /**\n * Configuración optimizada para Next.js builds\n */\n nextjs: {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: false,\n enableStackTrace: false,\n autoDetectTheme: false,\n outputFormat: \"build\"\n },\n /**\n * Configuración para Webpack builds\n */\n webpack: {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: false,\n autoDetectTheme: false,\n outputFormat: \"build\"\n },\n /**\n * Configuración para CI/CD environments\n */\n ci: {\n verbosity: \"info\",\n enableColors: false,\n enableTimestamps: true,\n enableStackTrace: true,\n autoDetectTheme: false,\n outputFormat: \"ci\"\n },\n /**\n * Configuración para desarrollo terminal\n */\n terminal: {\n verbosity: \"debug\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n autoDetectTheme: false,\n outputFormat: \"ansi\"\n }\n};\nconst ENVIRONMENT_DETECTION = {\n // Next.js detection\n isNextJS: typeof process !== \"undefined\" && (process.env.NEXT_RUNTIME || process.env.NEXT_PUBLIC_VERCEL_ENV || process.argv && process.argv.some((arg) => arg.includes(\"next\"))),\n // Webpack detection\n isWebpack: typeof process !== \"undefined\" && (process.env.WEBPACK_ENV || process.env.WEBPACK_BUILD || process.argv && process.argv.some((arg) => arg.includes(\"webpack\"))),\n // CI/CD detection\n isCI: typeof process !== \"undefined\" && (process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL || process.env.GITLAB_CI || process.env.TRAVIS || process.env.CIRCLECI),\n // Build detection\n isBuild: typeof process !== \"undefined\" && true,\n // Terminal with ANSI support\n isTerminal: typeof process !== \"undefined\" && (process.stdout?.isTTY === true && process.env.TERM !== \"dumb\")\n};\nfunction detectEnvironmentPreset() {\n if (ENVIRONMENT_DETECTION.isCI) {\n return \"ci\";\n }\n if (ENVIRONMENT_DETECTION.isNextJS) {\n return \"nextjs\";\n }\n if (ENVIRONMENT_DETECTION.isWebpack) {\n return \"webpack\";\n }\n if (ENVIRONMENT_DETECTION.isTerminal) {\n return \"terminal\";\n }\n return \"terminal\";\n}\nfunction getOptimalConfig() {\n const preset = detectEnvironmentPreset();\n return {\n ...DEFAULT_CONFIG,\n ...BUILD_PRESETS[preset]\n };\n}\nfunction formatTimestamp() {\n try {\n const now = /* @__PURE__ */ new Date();\n return now.toISOString();\n } catch {\n return (/* @__PURE__ */ new Date()).toISOString();\n }\n}\nfunction parseRelativeTime(timeStr) {\n const match = timeStr.match(/^(\\d+)(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Invalid time format: ${timeStr}. Use format like \"2h\", \"30m\", \"1d\"`);\n }\n const [, amount, unit] = match;\n const multiplier = TIME_UNITS[unit];\n return parseInt(amount || \"0\", 10) * multiplier;\n}\nfunction parseTimeInput(input) {\n if (input instanceof Date) {\n return input;\n }\n if (typeof input === \"number\") {\n return new Date(Date.now() - input * TIME_UNITS.h);\n }\n if (typeof input === \"string\") {\n const isoDate = new Date(input);\n if (!isNaN(isoDate.getTime())) {\n return isoDate;\n }\n try {\n const ms = parseRelativeTime(input);\n return new Date(Date.now() - ms);\n } catch {\n throw new Error(`Invalid time format: ${input}`);\n }\n }\n throw new Error(`Unsupported time input type: ${typeof input}`);\n}\nfunction formatDisplayTime(date, format = \"short\") {\n switch (format) {\n case \"time-only\":\n return date.toTimeString().slice(0, 8);\n // HH:MM:SS\n case \"full\":\n return date.toISOString();\n case \"short\":\n default:\n return date.toISOString().slice(11, 23);\n }\n}\nclass StyleBuilder {\n styles = [];\n constructor(baseStyle = \"\") {\n if (baseStyle) this.styles.push(baseStyle);\n }\n /**\n * Add background color or gradient\n */\n bg(background) {\n this.styles.push(`background: ${background}`);\n return this;\n }\n /**\n * Add text color\n */\n color(color) {\n this.styles.push(`color: ${color}`);\n return this;\n }\n /**\n * Add border styling\n */\n border(border) {\n this.styles.push(`border: ${border}`);\n return this;\n }\n /**\n * Add box shadow\n */\n shadow(shadow) {\n this.styles.push(`box-shadow: ${shadow}`);\n return this;\n }\n /**\n * Add padding\n */\n padding(padding) {\n this.styles.push(`padding: ${padding}`);\n return this;\n }\n /**\n * Add margin\n */\n margin(margin) {\n this.styles.push(`margin: ${margin}`);\n return this;\n }\n /**\n * Add border radius\n */\n rounded(radius = \"4px\") {\n this.styles.push(`border-radius: ${radius}`);\n return this;\n }\n /**\n * Add font weight\n */\n bold() {\n this.styles.push(\"font-weight: bold\");\n return this;\n }\n /**\n * Add font styling\n */\n font(font) {\n this.styles.push(`font-family: ${font}`);\n return this;\n }\n /**\n * Set monospace font family (alias for common monospace fonts)\n */\n mono() {\n return this.font('Monaco, Consolas, \"Courier New\", monospace');\n }\n /**\n * Set system font family (alias for system fonts)\n */\n system() {\n return this.font('system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif');\n }\n /**\n * Add font size\n */\n size(size) {\n this.styles.push(`font-size: ${size}`);\n return this;\n }\n /**\n * Add line height\n */\n lineHeight(height) {\n this.styles.push(`line-height: ${height}`);\n return this;\n }\n /**\n * Add text decoration\n */\n underline() {\n this.styles.push(\"text-decoration: underline\");\n return this;\n }\n /**\n * Add text transform\n */\n uppercase() {\n this.styles.push(\"text-transform: uppercase\");\n return this;\n }\n /**\n * Add opacity\n */\n opacity(value) {\n this.styles.push(`opacity: ${value}`);\n return this;\n }\n /**\n * Add display property\n */\n display(value) {\n this.styles.push(`display: ${value}`);\n return this;\n }\n /**\n * Add position property\n */\n position(value) {\n this.styles.push(`position: ${value}`);\n return this;\n }\n /**\n * Add transform property\n */\n transform(value) {\n this.styles.push(`transform: ${value}`);\n return this;\n }\n /**\n * Add animation property\n */\n animation(value) {\n this.styles.push(`animation: ${value}`);\n return this;\n }\n /**\n * Add transition property\n */\n transition(value) {\n this.styles.push(`transition: ${value}`);\n return this;\n }\n /**\n * Add cursor property\n */\n cursor(value) {\n this.styles.push(`cursor: ${value}`);\n return this;\n }\n /**\n * Add any custom CSS property\n */\n custom(property, value) {\n this.styles.push(`${property}: ${value}`);\n return this;\n }\n /**\n * Add any CSS property (alias for custom)\n */\n css(property, value) {\n return this.custom(property, value);\n }\n /**\n * Build the final CSS string\n */\n build() {\n return this.styles.join(\"; \");\n }\n /**\n * Clear all styles and start fresh\n */\n clear() {\n this.styles = [];\n return this;\n }\n /**\n * Clone this StyleBuilder with the same styles\n */\n clone() {\n const cloned = new StyleBuilder();\n cloned.styles = [...this.styles];\n return cloned;\n }\n /**\n * Merge another StyleBuilder's styles into this one\n */\n merge(other) {\n this.styles.push(...other.styles);\n return this;\n }\n}\nfunction createStyler() {\n const builder = new StyleBuilder();\n return new Proxy(builder, {\n get(target, prop) {\n if (prop in target) {\n const method = target[prop];\n if (typeof method === \"function\") {\n return method.bind(target);\n }\n return method;\n }\n return void 0;\n }\n });\n}\ncreateStyler();\nconst StylePresets = {\n success: () => new StyleBuilder().bg(\"linear-gradient(135deg, #00b894 0%, #00a085 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n error: () => new StyleBuilder().bg(\"linear-gradient(135deg, #e84393 0%, #d63031 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n warning: () => new StyleBuilder().bg(\"linear-gradient(135deg, #fdcb6e 0%, #e17055 100%)\").color(\"#2d3436\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n info: () => new StyleBuilder().bg(\"linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n debug: () => new StyleBuilder().bg(\"linear-gradient(135deg, #667eea 0%, #764ba2 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n muted: () => new StyleBuilder().color(\"#6c757d\").font(\"Monaco, Consolas, monospace\").size(\"12px\"),\n accent: () => new StyleBuilder().bg(\"#f8f9fa\").color(\"#495057\").padding(\"2px 6px\").rounded(\"3px\").border(\"1px solid #dee2e6\"),\n neon: () => new StyleBuilder().bg(\"linear-gradient(135deg, #0f3460 0%, #e94560 100%)\").color(\"#00ffff\").padding(\"4px 8px\").rounded(\"4px\").bold().shadow(\"0 0 10px rgba(0, 255, 255, 0.5)\")\n};\nfunction getEnvironment() {\n if (typeof globalThis !== \"undefined\" && globalThis.Deno) {\n return \"deno\";\n }\n if (typeof window === \"undefined\" && typeof self !== \"undefined\" && typeof self.importScripts === \"function\") {\n return \"webworker\";\n }\n if (typeof process !== \"undefined\" && process.versions && process.versions.node) {\n if (isRunningInTerminal()) {\n return \"terminal\";\n }\n return \"server\";\n }\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n return \"browser\";\n }\n return \"unknown\";\n}\nfunction isRunningInTerminal() {\n if (typeof process === \"undefined\") return false;\n const isTTY = process.stdout && process.stdout.isTTY;\n const hasTerminalEnv = process.env && (process.env.TERM || process.env.TERM_PROGRAM || process.env.SSH_TTY || process.env.TERM_SESSION_ID);\n const terminalPrograms = [\n \"vscode\",\n \"hyper\",\n \"iterm\",\n \"terminal\",\n \"alacritty\",\n \"kitty\",\n \"gnome-terminal\",\n \"konsole\",\n \"xterm\",\n \"tmux\",\n \"screen\"\n ];\n const isTerminalProgram = hasTerminalEnv && terminalPrograms.some(\n (program) => process.env.TERM_PROGRAM?.toLowerCase().includes(program) || process.env.TERM?.toLowerCase().includes(program)\n );\n return Boolean(isTTY || hasTerminalEnv || isTerminalProgram);\n}\nfunction supportsANSI() {\n const env = getEnvironment();\n if (env === \"browser\") return false;\n if (env === \"terminal\") return true;\n if (env === \"server\") return checkServerANSISupport();\n return false;\n}\nfunction checkServerANSISupport() {\n if (typeof process === \"undefined\") return false;\n const supportsANSI2 = process.env && (process.env.COLORTERM || process.env.FORCE_COLOR || process.env.TERM && process.env.TERM !== \"dumb\" || process.env.TERM_PROGRAM);\n return Boolean(supportsANSI2);\n}\nfunction getColorCapability() {\n const env = getEnvironment();\n if (env === \"browser\") {\n return \"full\";\n }\n if (!supportsANSI()) {\n return \"none\";\n }\n if (typeof process !== \"undefined\" && process.env) {\n const hasTrueColor = process.env.COLORTERM === \"truecolor\" || process.env.COLORTERM === \"24bit\";\n const has256Colors = process.env.TERM && process.env.TERM.includes(\"256\");\n if (hasTrueColor || has256Colors) {\n return \"full\";\n }\n }\n return \"basic\";\n}\nfunction getTerminalWidth() {\n if (typeof process !== \"undefined\" && process.stdout?.columns) {\n return process.stdout.columns;\n }\n return 80;\n}\nfunction getTerminalHeight() {\n if (typeof process !== \"undefined\" && process.stdout?.rows) {\n return process.stdout.rows;\n }\n return 24;\n}\nfunction getEnvironmentInfo() {\n return {\n environment: getEnvironment(),\n supportsANSI: supportsANSI(),\n colorCapability: getColorCapability(),\n isTTY: typeof process !== \"undefined\" ? Boolean(process.stdout?.isTTY) : false,\n platform: typeof process !== \"undefined\" ? process.platform : \"unknown\",\n nodeVersion: typeof process !== \"undefined\" ? process.versions?.node : null,\n term: typeof process !== \"undefined\" ? process.env?.TERM : null,\n colorTerm: typeof process !== \"undefined\" ? process.env?.COLORTERM : null,\n terminalWidth: getTerminalWidth(),\n terminalHeight: getTerminalHeight()\n };\n}\nconst ANSI_16_COLORS = {\n black: { fg: \"30\", bg: \"40\", bright: { fg: \"90\", bg: \"100\" } },\n red: { fg: \"31\", bg: \"41\", bright: { fg: \"91\", bg: \"101\" } },\n green: { fg: \"32\", bg: \"42\", bright: { fg: \"92\", bg: \"102\" } },\n yellow: { fg: \"33\", bg: \"43\", bright: { fg: \"93\", bg: \"103\" } },\n blue: { fg: \"34\", bg: \"44\", bright: { fg: \"94\", bg: \"104\" } },\n magenta: { fg: \"35\", bg: \"45\", bright: { fg: \"95\", bg: \"105\" } },\n cyan: { fg: \"36\", bg: \"46\", bright: { fg: \"96\", bg: \"106\" } },\n white: { fg: \"37\", bg: \"47\", bright: { fg: \"97\", bg: \"107\" } },\n gray: { fg: \"90\", bg: \"100\", bright: { fg: \"37\", bg: \"47\" } },\n grey: { fg: \"90\", bg: \"100\", bright: { fg: \"37\", bg: \"47\" } }\n};\nconst CSS_NAMED_COLORS = {\n aliceblue: \"#f0f8ff\",\n antiquewhite: \"#faebd7\",\n aqua: \"#00ffff\",\n aquamarine: \"#7fffd4\",\n azure: \"#f0ffff\",\n beige: \"#f5f5dc\",\n bisque: \"#ffe4c4\",\n black: \"#000000\",\n blanchedalmond: \"#ffebcd\",\n blue: \"#0000ff\",\n blueviolet: \"#8a2be2\",\n brown: \"#a52a2a\",\n burlywood: \"#deb887\",\n cadetblue: \"#5f9ea0\",\n chartreuse: \"#7fff00\",\n chocolate: \"#d2691e\",\n coral: \"#ff7f50\",\n cornflowerblue: \"#6495ed\",\n cornsilk: \"#fff8dc\",\n crimson: \"#dc143c\",\n cyan: \"#00ffff\",\n darkblue: \"#00008b\",\n darkcyan: \"#008b8b\",\n darkgoldenrod: \"#b8860b\",\n darkgray: \"#a9a9a9\",\n darkgreen: \"#006400\",\n darkkhaki: \"#bdb76b\",\n darkmagenta: \"#8b008b\",\n darkolivegreen: \"#556b2f\",\n darkorange: \"#ff8c00\",\n darkorchid: \"#9932cc\",\n darkred: \"#8b0000\",\n darksalmon: \"#e9967a\",\n darkseagreen: \"#8fbc8f\",\n darkslateblue: \"#483d8b\",\n darkslategray: \"#2f4f4f\",\n darkturquoise: \"#00ced1\",\n darkviolet: \"#9400d3\",\n deeppink: \"#ff1493\",\n deepskyblue: \"#00bfff\",\n dimgray: \"#696969\",\n dodgerblue: \"#1e90ff\",\n firebrick: \"#b22222\",\n floralwhite: \"#fffaf0\",\n forestgreen: \"#228b22\",\n fuchsia: \"#ff00ff\",\n gainsboro: \"#dcdcdc\",\n ghostwhite: \"#f8f8ff\",\n gold: \"#ffd700\",\n goldenrod: \"#daa520\",\n gray: \"#808080\",\n green: \"#008000\",\n greenyellow: \"#adff2f\",\n honeydew: \"#f0fff0\",\n hotpink: \"#ff69b4\",\n indianred: \"#cd5c5c\",\n indigo: \"#4b0082\",\n ivory: \"#fffff0\",\n khaki: \"#f0e68c\",\n lavender: \"#e6e6fa\",\n lavenderblush: \"#fff0f5\",\n lawngreen: \"#7cfc00\",\n lemonchiffon: \"#fffacd\",\n lightblue: \"#add8e6\",\n lightcoral: \"#f08080\",\n lightcyan: \"#e0ffff\",\n lightgoldenrodyellow: \"#fafad2\",\n lightgray: \"#d3d3d3\",\n lightgreen: \"#90ee90\",\n lightpink: \"#ffb6c1\",\n lightsalmon: \"#ffa07a\",\n lightseagreen: \"#20b2aa\",\n lightskyblue: \"#87cefa\",\n lightslategray: \"#778899\",\n lightsteelblue: \"#b0c4de\",\n lightyellow: \"#ffffe0\",\n lime: \"#00ff00\",\n limegreen: \"#32cd32\",\n linen: \"#faf0e6\",\n magenta: \"#ff00ff\",\n maroon: \"#800000\",\n mediumaquamarine: \"#66cdaa\",\n mediumblue: \"#0000cd\",\n mediumorchid: \"#ba55d3\",\n mediumpurple: \"#9370db\",\n mediumseagreen: \"#3cb371\",\n mediumslateblue: \"#7b68ee\",\n mediumspringgreen: \"#00fa9a\",\n mediumturquoise: \"#48d1cc\",\n mediumvioletred: \"#c71585\",\n midnightblue: \"#191970\",\n mintcream: \"#f5fffa\",\n mistyrose: \"#ffe4e1\",\n moccasin: \"#ffe4b5\",\n navajowhite: \"#ffdead\",\n navy: \"#000080\",\n oldlace: \"#fdf5e6\",\n olive: \"#808000\",\n olivedrab: \"#6b8e23\",\n orange: \"#ffa500\",\n orangered: \"#ff4500\",\n orchid: \"#da70d6\",\n palegoldenrod: \"#eee8aa\",\n palegreen: \"#98fb98\",\n paleturquoise: \"#afeeee\",\n palevioletred: \"#db7093\",\n papayawhip: \"#ffefd5\",\n peachpuff: \"#ffdab9\",\n peru: \"#cd853f\",\n pink: \"#ffc0cb\",\n plum: \"#dda0dd\",\n powderblue: \"#b0e0e6\",\n purple: \"#800080\",\n rebeccapurple: \"#663399\",\n red: \"#ff0000\",\n rosybrown: \"#bc8f8f\",\n royalblue: \"#4169e1\",\n saddlebrown: \"#8b4513\",\n salmon: \"#fa8072\",\n sandybrown: \"#f4a460\",\n seagreen: \"#2e8b57\",\n seashell: \"#fff5ee\",\n sienna: \"#a0522d\",\n silver: \"#c0c0c0\",\n skyblue: \"#87ceeb\",\n slateblue: \"#6a5acd\",\n slategray: \"#708090\",\n snow: \"#fffafa\",\n springgreen: \"#00ff7f\",\n steelblue: \"#4682b4\",\n tan: \"#d2b48c\",\n teal: \"#008080\",\n thistle: \"#d8bfd8\",\n tomato: \"#ff6347\",\n turquoise: \"#40e0d0\",\n violet: \"#ee82ee\",\n wheat: \"#f5deb3\",\n white: \"#ffffff\",\n whitesmoke: \"#f5f5f5\",\n yellow: \"#ffff00\",\n yellowgreen: \"#9acd32\"\n};\nfunction hexToRgb(hex) {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result || !result[1] || !result[2] || !result[3]) {\n return { r: 255, g: 255, b: 255 };\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16)\n };\n}\nfunction rgbToHex(r, g, b) {\n return \"#\" + [r, g, b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction hexTo256(hex) {\n const { r, g, b } = hexToRgb(hex);\n if (r === g && g === b) {\n if (r < 8) return 16;\n if (r > 248) return 231;\n return Math.round((r - 8) / 247 * 24) + 232;\n }\n const ri = Math.round(r / 255 * 5);\n const gi = Math.round(g / 255 * 5);\n const bi = Math.round(b / 255 * 5);\n return 16 + 36 * ri + 6 * gi + bi;\n}\nfunction colorToHex(color) {\n if (color.startsWith(\"#\")) {\n return color;\n }\n const named = CSS_NAMED_COLORS[color.toLowerCase()];\n if (named) {\n return named;\n }\n const rgbMatch = color.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (rgbMatch && rgbMatch[1] && rgbMatch[2] && rgbMatch[3]) {\n return rgbToHex(\n parseInt(rgbMatch[1]),\n parseInt(rgbMatch[2]),\n parseInt(rgbMatch[3])\n );\n }\n return \"#ffffff\";\n}\nfunction getANSIForeground(color, capability) {\n if (capability === \"none\") return \"\";\n const lowerColor = color.toLowerCase();\n if (capability === \"basic\" && ANSI_16_COLORS[lowerColor]) {\n return `\\x1B[${ANSI_16_COLORS[lowerColor].fg}m`;\n }\n if (capability === \"basic\") {\n const hex2 = colorToHex(color);\n const nearestBasic = findNearestBasicColor(hex2);\n const basicColor = ANSI_16_COLORS[nearestBasic];\n return basicColor ? `\\x1B[${basicColor.fg}m` : \"\\x1B[37m\";\n }\n const hex = colorToHex(color);\n const { r, g, b } = hexToRgb(hex);\n return `\\x1B[38;2;${r};${g};${b}m`;\n}\nfunction getANSIBackground(color, capability) {\n if (capability === \"none\") return \"\";\n const lowerColor = color.toLowerCase();\n if (capability === \"basic\" && ANSI_16_COLORS[lowerColor]) {\n return `\\x1B[${ANSI_16_COLORS[lowerColor].bg}m`;\n }\n if (capability === \"basic\") {\n const hex2 = colorToHex(color);\n const nearestBasic = findNearestBasicColor(hex2);\n const basicColor = ANSI_16_COLORS[nearestBasic];\n return basicColor ? `\\x1B[${basicColor.bg}m` : \"\\x1B[47m\";\n }\n const hex = colorToHex(color);\n const { r, g, b } = hexToRgb(hex);\n return `\\x1B[48;2;${r};${g};${b}m`;\n}\nfunction getANSI256Foreground(colorIndex) {\n return `\\x1B[38;5;${colorIndex}m`;\n}\nfunction getANSI256Background(colorIndex) {\n return `\\x1B[48;5;${colorIndex}m`;\n}\nfunction findNearestBasicColor(hex) {\n const { r, g, b } = hexToRgb(hex);\n const basicColors = {\n black: { r: 0, g: 0, b: 0 },\n red: { r: 205, g: 0, b: 0 },\n green: { r: 0, g: 205, b: 0 },\n yellow: { r: 205, g: 205, b: 0 },\n blue: { r: 0, g: 0, b: 238 },\n magenta: { r: 205, g: 0, b: 205 },\n cyan: { r: 0, g: 205, b: 205 },\n white: { r: 229, g: 229, b: 229 }\n };\n let nearest = \"white\";\n let minDistance = Infinity;\n for (const [name, rgb] of Object.entries(basicColors)) {\n const distance = Math.sqrt(\n Math.pow(r - rgb.r, 2) + Math.pow(g - rgb.g, 2) + Math.pow(b - rgb.b, 2)\n );\n if (distance < minDistance) {\n minDistance = distance;\n nearest = name;\n }\n }\n return nearest;\n}\nfunction extractGradientColors(gradient) {\n const hexMatches = gradient.match(/#[a-fA-F0-9]{6}/g) || [];\n const rgbMatches = gradient.match(/rgba?\\([^)]+\\)/g) || [];\n const namedMatches = gradient.match(/,\\s*([a-z]+)(?:\\s|,|\\))/gi) || [];\n const colors = [\n ...hexMatches,\n ...rgbMatches.map(colorToHex),\n ...namedMatches.map((m) => {\n const name = m.replace(/[,\\s)]/g, \"\").toLowerCase();\n return CSS_NAMED_COLORS[name] || null;\n }).filter((c) => c !== null)\n ];\n return colors.length > 0 ? colors : [\"#ffffff\"];\n}\nfunction gradientToSingleColor(gradient) {\n const colors = extractGradientColors(gradient);\n if (colors.length === 0) return \"#ffffff\";\n if (colors.length === 1) return colors[0] ?? \"#ffffff\";\n const rgbs = colors.map((c) => hexToRgb(colorToHex(c)));\n const avgR = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.r, 0) / rgbs.length);\n const avgG = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.g, 0) / rgbs.length);\n const avgB = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.b, 0) / rgbs.length);\n return rgbToHex(avgR, avgG, avgB);\n}\nfunction cssColorToANSI(cssColor, capability, isBackground = false) {\n if (capability === \"none\") return \"\";\n let resolvedColor;\n if (cssColor.includes(\"gradient\")) {\n resolvedColor = gradientToSingleColor(cssColor);\n } else {\n resolvedColor = colorToHex(cssColor);\n }\n return isBackground ? getANSIBackground(resolvedColor, capability) : getANSIForeground(resolvedColor, capability);\n}\nconst ANSI = {\n reset: \"\\x1B[0m\",\n bold: \"\\x1B[1m\",\n dim: \"\\x1B[2m\",\n italic: \"\\x1B[3m\",\n underline: \"\\x1B[4m\",\n blink: \"\\x1B[5m\",\n inverse: \"\\x1B[7m\",\n hidden: \"\\x1B[8m\",\n strikethrough: \"\\x1B[9m\",\n fg: {\n black: \"\\x1B[30m\",\n red: \"\\x1B[31m\",\n green: \"\\x1B[32m\",\n yellow: \"\\x1B[33m\",\n blue: \"\\x1B[34m\",\n magenta: \"\\x1B[35m\",\n cyan: \"\\x1B[36m\",\n white: \"\\x1B[37m\",\n gray: \"\\x1B[90m\",\n brightRed: \"\\x1B[91m\",\n brightGreen: \"\\x1B[92m\",\n brightYellow: \"\\x1B[93m\",\n brightBlue: \"\\x1B[94m\",\n brightMagenta: \"\\x1B[95m\",\n brightCyan: \"\\x1B[96m\",\n brightWhite: \"\\x1B[97m\"\n },\n bg: {\n black: \"\\x1B[40m\",\n red: \"\\x1B[41m\",\n green: \"\\x1B[42m\",\n yellow: \"\\x1B[43m\",\n blue: \"\\x1B[44m\",\n magenta: \"\\x1B[45m\",\n cyan: \"\\x1B[46m\",\n white: \"\\x1B[47m\",\n gray: \"\\x1B[100m\",\n brightRed: \"\\x1B[101m\",\n brightGreen: \"\\x1B[102m\",\n brightYellow: \"\\x1B[103m\",\n brightBlue: \"\\x1B[104m\",\n brightMagenta: \"\\x1B[105m\",\n brightCyan: \"\\x1B[106m\",\n brightWhite: \"\\x1B[107m\"\n },\n rgb: (r, g, b) => `\\x1B[38;2;${r};${g};${b}m`,\n bgRgb: (r, g, b) => `\\x1B[48;2;${r};${g};${b}m`,\n color256: (n) => `\\x1B[38;5;${n}m`,\n bgColor256: (n) => `\\x1B[48;5;${n}m`\n};\nclass TerminalRenderer {\n colorCapability;\n constructor(colorCapability = \"full\") {\n this.colorCapability = colorCapability;\n }\n /**\n * Get ANSI color codes - now supports truecolor/256-color\n */\n getColorCode(color, background = false) {\n return background ? getANSIBackground(color, this.colorCapability) : getANSIForeground(color, this.colorCapability);\n }\n /**\n * Get ANSI style codes\n */\n getStyleCode(styles) {\n const styleCodes = {\n \"bold\": \"1\",\n \"dim\": \"2\",\n \"italic\": \"3\",\n \"underline\": \"4\",\n \"reset\": \"0\"\n };\n const codes = styles.map((style) => styleCodes[style] || \"0\").join(\";\");\n return codes ? `\\x1B[${codes}m` : \"\";\n }\n /**\n * Convert log styles to ANSI formatting\n */\n renderTerminal(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const result = { text: \"\", reset };\n if (styles) {\n result.timestamp = this.styleTimestamp(timestamp, styles.timestamp);\n result.level = this.styleLevel(level, styles.level);\n result.prefix = this.stylePrefix(prefix, styles.prefix);\n result.message = this.styleMessage(message, styles.message);\n result.location = this.styleLocation(location, styles.location);\n } else {\n result.timestamp = this.styleTimestamp(timestamp);\n result.level = this.styleLevel(level);\n result.prefix = this.stylePrefix(prefix);\n result.message = this.styleMessage(message);\n result.location = this.styleLocation(location);\n }\n const parts = [];\n if (result.timestamp) parts.push(result.timestamp);\n if (result.level) parts.push(result.level);\n if (result.prefix) parts.push(result.prefix);\n if (result.message) parts.push(result.message);\n if (result.location) parts.push(result.location);\n result.text = parts.join(\" \") + reset;\n return result;\n }\n /**\n * Style timestamp based on preset or defaults\n */\n styleTimestamp(timestamp, style) {\n if (!timestamp || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return timestamp;\n }\n const dimStyle = this.getStyleCode([\"dim\"]);\n return `${dimStyle}${timestamp}${\"\\x1B[0m\"}`;\n }\n /**\n * Style level with appropriate colors and formatting\n */\n styleLevel(level, style) {\n if (!style?.show) return \"\";\n const levelText = this.getLevelText(level);\n const levelColors = {\n \"debug\": \"magenta\",\n \"info\": \"blue\",\n \"warn\": \"yellow\",\n \"error\": \"red\",\n \"critical\": \"red\"\n };\n if (this.colorCapability === \"none\") {\n return `[${levelText}]`;\n }\n const color = levelColors[level] || \"white\";\n const colorCode = this.getColorCode(color);\n const boldStyle = this.getStyleCode([\"bold\"]);\n if (style?.style === \"compact\") {\n return `${colorCode}[${levelText}]${\"\\x1B[0m\"}`;\n } else {\n return `${colorCode}${boldStyle}[${levelText}]${\"\\x1B[0m\"}`;\n }\n }\n /**\n * Style prefix based on preset - now as a badge\n */\n stylePrefix(prefix, style) {\n if (!prefix || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return `[${prefix}]`;\n }\n const colorCode = this.getColorCode(\"cyan\");\n const bgBlack = \"\\x1B[40m\";\n return `${bgBlack}${colorCode}[${prefix.toUpperCase()}]${\"\\x1B[0m\"}`;\n }\n /**\n * Style message based on preset\n */\n styleMessage(message, style) {\n if (!style?.show) return message;\n return message;\n }\n /**\n * Style location (file:line) information\n */\n styleLocation(location, style) {\n if (!location || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return `(${location})`;\n }\n const dimStyle = this.getStyleCode([\"dim\"]);\n if (style?.style === \"clickable\") {\n const underlineStyle = this.getStyleCode([\"dim\", \"underline\"]);\n return `${underlineStyle}(${location})${\"\\x1B[0m\"}`;\n }\n return `${dimStyle}(${location})${\"\\x1B[0m\"}`;\n }\n /**\n * Get text representation of log level\n */\n getLevelText(level) {\n const levelMap = {\n \"debug\": \"DEBUG\",\n \"info\": \"INFO\",\n \"warn\": \"WARN\",\n \"error\": \"ERROR\",\n \"critical\": \"CRITICAL\"\n };\n return levelMap[level] || String(level).toUpperCase();\n }\n /**\n * Create cyberpunk-style ANSI rendering with truecolor support\n */\n renderCyberpunk(level, message, timestamp, prefix, location) {\n const reset = ANSI.reset;\n const cyberpunkColors = {\n \"debug\": \"#ff00ff\",\n // Neon magenta\n \"info\": \"#00ffff\",\n // Neon cyan\n \"warn\": \"#ffff00\",\n // Neon yellow\n \"error\": \"#ff0040\",\n // Neon red-pink\n \"critical\": \"#ff0000\"\n // Pure red\n };\n const parts = [];\n if (timestamp) {\n parts.push(`${ANSI.dim}${timestamp}${reset}`);\n }\n const levelColor = this.getColorCode(cyberpunkColors[level] || \"#ffffff\");\n const bgBlack = ANSI.bg.black;\n const bold = level === \"critical\" ? ANSI.bold : \"\";\n parts.push(`${bgBlack}${levelColor}${bold} ${this.getLevelText(level)} ${reset}`);\n if (prefix) {\n const cyanColor = this.getColorCode(\"#00ffff\");\n parts.push(`${bgBlack}${cyanColor}[${prefix.toUpperCase()}]${reset}`);\n }\n parts.push(message);\n if (location) {\n parts.push(`${ANSI.dim}(${location})${reset}`);\n }\n return {\n text: parts.join(\" \"),\n reset\n };\n }\n /**\n * Create minimal ANSI rendering with truecolor support\n */\n renderMinimal(level, message, timestamp, prefix) {\n const reset = ANSI.reset;\n const minimalColors = {\n \"debug\": \"#c678dd\",\n // Soft purple\n \"info\": \"#61afef\",\n // Soft blue\n \"warn\": \"#e5c07b\",\n // Soft yellow\n \"error\": \"#e06c75\",\n // Soft red\n \"critical\": \"#be5046\"\n // Dark red\n };\n const parts = [];\n if (timestamp) {\n parts.push(`${ANSI.dim}${timestamp}${reset}`);\n }\n const levelColor = this.getColorCode(minimalColors[level] || \"#abb2bf\");\n const bold = level === \"critical\" ? ANSI.bold : \"\";\n parts.push(`${levelColor}${bold}${this.getLevelText(level)}:${reset}`);\n if (prefix) {\n const cyanColor = this.getColorCode(\"#56b6c2\");\n parts.push(`${cyanColor}[${prefix.toUpperCase()}]${reset}`);\n }\n parts.push(message);\n return {\n text: parts.join(\" \"),\n reset\n };\n }\n /**\n * Get chalk-like interface for log level with truecolor support\n */\n getChalkForLevel(level) {\n const levelColors = {\n \"debug\": \"#c678dd\",\n \"info\": \"#61afef\",\n \"warn\": \"#e5c07b\",\n \"error\": \"#e06c75\",\n \"critical\": \"#be5046\"\n };\n const reset = ANSI.reset;\n return {\n color: (text) => {\n const color = levelColors[level] || \"#abb2bf\";\n const colorCode = this.getColorCode(color);\n return `${colorCode}${text}${reset}`;\n },\n bold: (text) => `${ANSI.bold}${text}${reset}`,\n dim: (text) => `${ANSI.dim}${text}${reset}`,\n bgGray: (text) => `${ANSI.bg.gray}${text}${reset}`,\n bgBlue: (text) => `${this.getColorCode(\"#1e3a5f\", true)}${text}${reset}`,\n reset: (text) => text,\n cyan: {\n bold: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${cyan}${ANSI.bold}${text}${reset}`;\n },\n dim: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${cyan}${ANSI.dim}${text}${reset}`;\n },\n bg: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${ANSI.bg.black}${cyan}[${text.toUpperCase()}]${reset}`;\n }\n }\n };\n }\n}\nclass CSS2ANSIAdapter {\n renderer;\n constructor() {\n const colorCapability = getColorCapability();\n this.renderer = new TerminalRenderer(colorCapability);\n }\n /**\n * Convert LogStyles to ANSIStyle for terminal rendering\n */\n adaptStyles(level, message, timestamp, prefix, location, styles, presetName) {\n if (presetName) {\n switch (presetName) {\n case \"cyberpunk\":\n return this.renderer.renderCyberpunk(level, message, timestamp, prefix, location);\n case \"minimal\":\n return this.renderer.renderMinimal(level, message, timestamp, prefix);\n case \"production\":\n return this.adaptProductionStyles(level, message, timestamp, prefix, location, styles);\n case \"debug\":\n return this.adaptDebugStyles(level, message, timestamp, prefix, location, styles);\n case \"glassmorphism\":\n return this.adaptGlassmorphismStyles(level, message, timestamp, prefix, location, styles);\n }\n }\n return this.renderer.renderTerminal(level, message, timestamp, prefix, location, styles);\n }\n /**\n * Adapt production preset for terminal\n */\n adaptProductionStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n parts.push(levelChalk.color(`[${this.renderer[\"getLevelText\"](level)}]`));\n }\n if (prefix && styles?.prefix?.show) {\n parts.push(levelChalk.dim(`[${prefix}]`));\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n parts.push(levelChalk.dim(`(${location})`));\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Adapt debug preset for terminal\n */\n adaptDebugStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n if (styles?.level?.style === \"compact\") {\n parts.push(levelChalk.color(`[${this.renderer[\"getLevelText\"](level)}]`));\n } else {\n parts.push(levelChalk.bold(`[${this.renderer[\"getLevelText\"](level)}]`));\n }\n }\n if (prefix && styles?.prefix?.show) {\n if (styles?.prefix?.style === \"compact\") {\n parts.push(levelChalk.cyan.dim(`[${prefix}]`));\n } else {\n parts.push(levelChalk.cyan.bold(`[${prefix}]`));\n }\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n if (styles?.location?.style === \"clickable\") {\n parts.push(levelChalk.dim(`${location} (clickable)`));\n } else {\n parts.push(levelChalk.dim(`(${location})`));\n }\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Adapt glassmorphism preset for terminal\n */\n adaptGlassmorphismStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n parts.push(levelChalk.bgGray(` ${this.renderer[\"getLevelText\"](level)} `));\n }\n if (prefix && styles?.prefix?.show) {\n parts.push(levelChalk.bgBlue(`[${prefix}]`));\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n parts.push(levelChalk.dim(`(${location})`));\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Convert CSS color values to ANSI-friendly colors\n */\n adaptColor(cssColor) {\n if (cssColor.startsWith(\"#\")) {\n return cssColor;\n }\n if (cssColor.startsWith(\"rgb(\")) {\n return cssColor;\n }\n if (cssColor.includes(\"gradient\")) {\n return this.extractColorFromGradient(cssColor);\n }\n return this.cssNameToANSI(cssColor);\n }\n /**\n * Extract primary color from CSS gradient\n */\n extractColorFromGradient(gradient) {\n const match = gradient.match(/#[0-9a-fA-F]{6}|rgb\\([^)]+\\)/);\n return match ? match[0] : \"#ffffff\";\n }\n /**\n * Convert CSS color names to ANSI-compatible names\n */\n cssNameToANSI(cssColor) {\n const colorMap = {\n \"black\": \"black\",\n \"white\": \"white\",\n \"red\": \"red\",\n \"green\": \"green\",\n \"blue\": \"blue\",\n \"yellow\": \"yellow\",\n \"cyan\": \"cyan\",\n \"magenta\": \"magenta\",\n \"gray\": \"gray\",\n \"grey\": \"gray\",\n \"orange\": \"yellow\",\n \"purple\": \"magenta\",\n \"pink\": \"red\",\n \"brown\": \"yellow\",\n \"lightblue\": \"cyan\",\n \"lightgreen\": \"green\",\n \"lightgray\": \"gray\",\n \"lightgrey\": \"gray\"\n };\n return colorMap[cssColor.toLowerCase()] || \"white\";\n }\n /**\n * Check if a style should be rendered in terminal\n */\n shouldRenderStyle(styleType, styles) {\n if (!styles) return true;\n const styleConfig = styles[styleType];\n return styleConfig?.show !== false;\n }\n /**\n * Get renderer instance for advanced usage\n */\n getRenderer() {\n return this.renderer;\n }\n}\nconst css2ansiAdapter = new CSS2ANSIAdapter();\nfunction adaptToTerminal(level, message, timestamp, prefix, location, styles, presetName) {\n return css2ansiAdapter.adaptStyles(level, message, timestamp, prefix, location, styles, presetName);\n}\nfunction detectDevToolsTheme() {\n try {\n if (typeof window === \"undefined\" || !window.matchMedia) {\n return \"light\";\n }\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n return mediaQuery.matches ? \"dark\" : \"light\";\n } catch (error) {\n console.warn(\"Failed to detect DevTools theme:\", error);\n return \"light\";\n }\n}\nfunction getAdaptiveColor(colors, theme) {\n const currentTheme = theme ?? detectDevToolsTheme();\n return colors[currentTheme];\n}\nfunction setupThemeChangeListener(callback) {\n try {\n if (typeof window === \"undefined\" || !window.matchMedia) {\n return null;\n }\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n const handler = (e) => {\n callback(e.matches ? \"dark\" : \"light\");\n };\n if (mediaQuery.addEventListener) {\n mediaQuery.addEventListener(\"change\", handler);\n return () => mediaQuery.removeEventListener(\"change\", handler);\n } else if (mediaQuery.addListener) {\n mediaQuery.addListener(handler);\n return () => mediaQuery.removeListener?.(handler);\n }\n return null;\n } catch (error) {\n console.warn(\"Failed to set up theme change listener:\", error);\n return null;\n }\n}\nfunction createStyledOutput(level, levelStyles, prefix, message, stackInfo, autoDetectTheme = true, presetStyles, presetName) {\n const levelConfig = levelStyles[level];\n const timestamp = formatTimestamp();\n const environment = getEnvironment();\n if (environment !== \"browser\" && supportsANSI()) {\n return createTerminalOutput(level, message, timestamp, prefix, stackInfo, presetStyles, presetName);\n }\n const currentTheme = autoDetectTheme ? detectDevToolsTheme() : \"light\";\n const timestampStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.timestamp, currentTheme)).size(\"11px\").font(\"Monaco, Consolas, monospace\").build();\n const levelStyle = new StyleBuilder().bg(levelConfig.background).color(levelConfig.color).border(levelConfig.border).shadow(levelConfig.shadow).padding(\"2px 8px\").rounded(\"4px\").bold().font(\"Monaco, Consolas, monospace\").size(\"12px\").build();\n const prefixStyle = new StyleBuilder().bg(getAdaptiveColor(ADAPTIVE_COLORS.prefixBackground, currentTheme)).color(getAdaptiveColor(ADAPTIVE_COLORS.prefix, currentTheme)).padding(\"2px 6px\").rounded(\"3px\").bold().font(\"Monaco, Consolas, monospace\").size(\"11px\").build();\n const messageStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.messageText, currentTheme)).font(\"system-ui, -apple-system, sans-serif\").size(\"14px\").build();\n const locationStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.location, currentTheme)).size(\"11px\").font(\"Monaco, Consolas, monospace\").build();\n let format = `%c${timestamp.slice(11, 23)} %c${levelConfig.emoji} ${levelConfig.label}`;\n const styles = [timestampStyle, levelStyle];\n if (prefix) {\n format += ` %c${prefix}`;\n styles.push(prefixStyle);\n }\n format += ` %c${message}`;\n styles.push(messageStyle);\n if (stackInfo) {\n format += ` %c(${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n styles.push(locationStyle);\n }\n return [format, ...styles];\n}\nfunction generateLogId() {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\nfunction escapeHtml(text) {\n const div = document.createElement(\"div\");\n div.textContent = text;\n return div.innerHTML;\n}\nfunction safeStringify(obj, _maxDepth = 3) {\n try {\n return JSON.stringify(obj, (_key, value) => {\n if (typeof value === \"function\") return \"[Function]\";\n if (value instanceof Error) return `[Error: ${value.message}]`;\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"undefined\") return \"[undefined]\";\n return value;\n }, 2);\n } catch (error) {\n return String(obj);\n }\n}\nfunction createTerminalOutput(level, message, timestamp, prefix, stackInfo, presetStyles, presetName) {\n const location = stackInfo ? `${stackInfo.file}:${stackInfo.line}:${stackInfo.column}` : void 0;\n const ansiStyle = adaptToTerminal(\n level,\n message,\n timestamp,\n prefix,\n location,\n presetStyles,\n presetName\n );\n return [ansiStyle.text];\n}\nconst isNode = typeof process !== \"undefined\" && process.versions && process.versions.node;\nconst isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\nfunction supportsCSSColors() {\n return isBrowser;\n}\nfunction supportsANSIColors() {\n if (isNode) {\n return process.stdout?.isTTY === true || process.env.FORCE_COLOR === \"1\" || process.env.FORCE_COLOR === \"true\";\n }\n return false;\n}\nexport {\n ANSI as A,\n BUILD_PRESETS as B,\n getAdaptiveColor as C,\n DEFAULT_CONFIG as D,\n ENVIRONMENT_DETECTION as E,\n ADAPTIVE_COLORS as F,\n BUFFER_LIMITS as G,\n generateLogId as H,\n parseTimeInput as I,\n formatDisplayTime as J,\n safeStringify as K,\n LEVEL_STYLES as L,\n escapeHtml as M,\n EXPORT_FORMATS as N,\n setupThemeChangeListener as O,\n StylePresets as S,\n TerminalRenderer as T,\n isBrowser as a,\n StyleBuilder as b,\n hexTo256 as c,\n detectEnvironmentPreset as d,\n colorToHex as e,\n formatTimestamp as f,\n getOptimalConfig as g,\n hexToRgb as h,\n isNode as i,\n getANSIForeground as j,\n getANSIBackground as k,\n getANSI256Foreground as l,\n getANSI256Background as m,\n cssColorToANSI as n,\n getEnvironment as o,\n parseStackTrace as p,\n isRunningInTerminal as q,\n rgbToHex as r,\n supportsANSI as s,\n getColorCapability as t,\n getTerminalWidth as u,\n getTerminalHeight as v,\n getEnvironmentInfo as w,\n supportsCSSColors as x,\n createStyledOutput as y,\n supportsANSIColors as z\n};\n//# sourceMappingURL=environment-COWvu6Wz.js.map\n","import { C as getAdaptiveColor, F as ADAPTIVE_COLORS, b as StyleBuilder, j as getANSIForeground, A as ANSI, u as getTerminalWidth, G as BUFFER_LIMITS, H as generateLogId, I as parseTimeInput, J as formatDisplayTime, K as safeStringify, M as escapeHtml, N as EXPORT_FORMATS, D as DEFAULT_CONFIG$1, O as setupThemeChangeListener, o as getEnvironment, p as parseStackTrace, f as formatTimestamp$1, y as createStyledOutput, t as getColorCapability, S as StylePresets } from \"./environment-COWvu6Wz.js\";\nconst DEFAULT_CONFIG = {\n maxDepth: 5,\n circular: \"placeholder\",\n preserveUndefined: false\n};\nclass SerializerRegistry {\n serializers = /* @__PURE__ */ new Map();\n config;\n constructor(config = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.registerDefaults();\n }\n registerDefaults() {\n this.add(Error, (err) => ({\n name: err.name,\n message: err.message,\n stack: err.stack?.split(\"\\n\").slice(0, 10),\n ...err.cause ? { cause: this.serialize(err.cause) } : {}\n }), 100);\n this.add(Date, (date) => ({\n iso: date.toISOString(),\n timestamp: date.getTime()\n }), 90);\n this.add(RegExp, (regex) => ({\n pattern: regex.source,\n flags: regex.flags\n }), 90);\n this.add(Map, (map, ctx) => {\n const obj = {};\n map.forEach((value, key) => {\n const keyStr = typeof key === \"object\" ? JSON.stringify(key) : String(key);\n obj[keyStr] = this.serializeInternal(value, {\n ...ctx,\n depth: ctx.depth + 1,\n path: [...ctx.path, keyStr]\n });\n });\n return { __type: \"Map\", entries: obj };\n }, 80);\n this.add(Set, (set, ctx) => ({\n __type: \"Set\",\n values: Array.from(set).map(\n (v, i) => this.serializeInternal(v, {\n ...ctx,\n depth: ctx.depth + 1,\n path: [...ctx.path, `[${i}]`]\n })\n )\n }), 80);\n if (typeof Buffer !== \"undefined\") {\n this.add(Buffer, (buf) => ({\n __type: \"Buffer\",\n length: buf.length,\n preview: buf.slice(0, 50).toString(\"hex\")\n }), 70);\n }\n }\n add(type, serializer, priority = 50) {\n this.serializers.set(type, { type, serializer, priority });\n }\n remove(type) {\n return this.serializers.delete(type);\n }\n has(type) {\n return this.serializers.has(type);\n }\n getAll() {\n return Array.from(this.serializers.values()).sort((a, b) => (b.priority ?? 50) - (a.priority ?? 50));\n }\n findSerializer(value) {\n const sorted = this.getAll();\n for (const entry of sorted) {\n if (value instanceof entry.type) {\n return entry;\n }\n }\n return null;\n }\n serializeInternal(value, context) {\n if (value === null) return null;\n if (value === void 0) return this.config.preserveUndefined ? void 0 : \"[undefined]\";\n if (typeof value === \"function\") return `[Function: ${value.name || \"anonymous\"}]`;\n if (typeof value !== \"object\") return value;\n if (context.depth >= this.config.maxDepth) {\n return \"[Max Depth]\";\n }\n if (context.seen.has(value)) {\n switch (this.config.circular) {\n case \"error\":\n throw new Error(`Circular reference at ${context.path.join(\".\")}`);\n case \"skip\":\n return void 0;\n case \"placeholder\":\n default:\n return \"[Circular]\";\n }\n }\n context.seen.add(value);\n const serializer = this.findSerializer(value);\n if (serializer) {\n return serializer.serializer(value, context);\n }\n if (Array.isArray(value)) {\n return value.map(\n (item, i) => this.serializeInternal(item, {\n ...context,\n depth: context.depth + 1,\n path: [...context.path, `[${i}]`]\n })\n );\n }\n const result = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = this.serializeInternal(val, {\n ...context,\n depth: context.depth + 1,\n path: [...context.path, key]\n });\n }\n return result;\n }\n serialize(value, config) {\n const mergedConfig = { ...this.config, ...config };\n return this.serializeInternal(value, {\n depth: 0,\n maxDepth: mergedConfig.maxDepth,\n path: [],\n seen: /* @__PURE__ */ new WeakSet()\n });\n }\n}\nfunction generateId() {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\nclass HookManager {\n hooks = /* @__PURE__ */ new Map();\n middlewares = [];\n constructor() {\n this.hooks.set(\"beforeLog\", []);\n this.hooks.set(\"afterLog\", []);\n this.hooks.set(\"onError\", []);\n }\n on(event, callback, priority = 50) {\n const registration = {\n id: generateId(),\n event,\n callback,\n priority,\n once: false\n };\n const hooks = this.hooks.get(event);\n hooks.push(registration);\n hooks.sort((a, b) => b.priority - a.priority);\n return () => this.removeHook(event, registration.id);\n }\n once(event, callback, priority = 50) {\n const registration = {\n id: generateId(),\n event,\n callback,\n priority,\n once: true\n };\n const hooks = this.hooks.get(event);\n hooks.push(registration);\n hooks.sort((a, b) => b.priority - a.priority);\n return () => this.removeHook(event, registration.id);\n }\n off(event, callback) {\n const hooks = this.hooks.get(event);\n if (!hooks) return false;\n const index = hooks.findIndex((h) => h.callback === callback);\n if (index >= 0) {\n hooks.splice(index, 1);\n return true;\n }\n return false;\n }\n removeHook(event, id) {\n const hooks = this.hooks.get(event);\n if (hooks) {\n const index = hooks.findIndex((h) => h.id === id);\n if (index >= 0) {\n hooks.splice(index, 1);\n }\n }\n }\n use(middleware, priority = 50) {\n const registration = {\n id: generateId(),\n fn: middleware,\n priority\n };\n this.middlewares.push(registration);\n this.middlewares.sort((a, b) => b.priority - a.priority);\n return () => {\n const index = this.middlewares.findIndex((m) => m.id === registration.id);\n if (index >= 0) {\n this.middlewares.splice(index, 1);\n }\n };\n }\n async emit(event, entry) {\n const hooks = this.hooks.get(event) || [];\n let currentEntry = { ...entry };\n const toRemove = [];\n for (const hook of hooks) {\n try {\n const result = await hook.callback(currentEntry);\n if (result) {\n currentEntry = { ...currentEntry, ...result };\n }\n if (hook.once) {\n toRemove.push(hook.id);\n }\n } catch (error) {\n if (event !== \"onError\") {\n await this.emit(\"onError\", {\n ...currentEntry,\n error,\n hookEvent: event\n });\n }\n }\n }\n toRemove.forEach((id) => this.removeHook(event, id));\n return currentEntry;\n }\n async process(entry) {\n let currentEntry = { ...entry };\n currentEntry = await this.emit(\"beforeLog\", currentEntry);\n if (this.middlewares.length > 0) {\n let index = 0;\n const executeNext = async () => {\n if (index < this.middlewares.length) {\n const middleware = this.middlewares[index++];\n if (middleware) {\n await middleware.fn(currentEntry, executeNext);\n }\n }\n };\n await executeNext();\n }\n return currentEntry;\n }\n async afterProcess(entry) {\n await this.emit(\"afterLog\", entry);\n }\n clear() {\n this.hooks.forEach((hooks) => hooks.length = 0);\n this.middlewares.length = 0;\n }\n getStats() {\n return {\n hooks: {\n beforeLog: this.hooks.get(\"beforeLog\")?.length || 0,\n afterLog: this.hooks.get(\"afterLog\")?.length || 0,\n onError: this.hooks.get(\"onError\")?.length || 0\n },\n middlewares: this.middlewares.length\n };\n }\n}\nconst LOG_LEVELS = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n critical: 4\n};\nfunction generateTransportId() {\n return `transport-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;\n}\nclass TransportManager {\n transports = /* @__PURE__ */ new Map();\n defaultLevel = \"info\";\n constructor(defaultLevel) {\n if (defaultLevel) {\n this.defaultLevel = defaultLevel;\n }\n }\n add(target) {\n const id = generateTransportId();\n const level = target.level || this.defaultLevel;\n let transport;\n if (typeof target.target === \"string\") {\n throw new Error(`String transport targets not supported. Use inline transport object.`);\n } else {\n transport = target.target;\n }\n const entry = {\n id,\n transport,\n options: target.options || {},\n level,\n levelValue: LOG_LEVELS[level]\n };\n this.transports.set(id, entry);\n return id;\n }\n remove(id) {\n const entry = this.transports.get(id);\n if (entry) {\n entry.transport.close?.();\n return this.transports.delete(id);\n }\n return false;\n }\n async write(record) {\n const promises = [];\n for (const entry of this.transports.values()) {\n if (record.levelValue < entry.levelValue) {\n continue;\n }\n let transformedRecord = record;\n if (entry.options.transform) {\n const result2 = entry.options.transform(record);\n if (result2 === null) continue;\n transformedRecord = result2;\n }\n const result = entry.transport.write(transformedRecord);\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n await Promise.all(promises);\n }\n async flush() {\n const promises = [];\n for (const entry of this.transports.values()) {\n if (entry.transport.flush) {\n const result = entry.transport.flush();\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n }\n await Promise.all(promises);\n }\n async close() {\n await this.flush();\n const promises = [];\n for (const entry of this.transports.values()) {\n if (entry.transport.close) {\n const result = entry.transport.close();\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n }\n await Promise.all(promises);\n this.transports.clear();\n }\n get count() {\n return this.transports.size;\n }\n list() {\n return Array.from(this.transports.keys());\n }\n}\nconst THEME_PRESETS = {\n default: {\n debug: {\n emoji: \"🐞\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #667eea 0%, #764ba2 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #667eea\",\n shadow: \"0 2px 4px rgba(102, 126, 234, 0.3)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #74b9ff\",\n shadow: \"0 2px 4px rgba(116, 185, 255, 0.3)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #fdcb6e 0%, #e17055 100%)\",\n color: \"#2d3436\",\n border: \"1px solid #fdcb6e\",\n shadow: \"0 2px 4px rgba(253, 203, 110, 0.3)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #e84393 0%, #d63031 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #e84393\",\n shadow: \"0 2px 4px rgba(232, 67, 147, 0.3)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #00b894 0%, #00a085 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #00b894\",\n shadow: \"0 2px 4px rgba(0, 184, 148, 0.3)\"\n },\n critical: {\n emoji: \"🔥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #ff3838 0%, #ff1744 100%)\",\n color: \"#ffffff\",\n border: \"2px solid #ff3838\",\n shadow: \"0 4px 8px rgba(255, 56, 56, 0.5)\"\n }\n },\n dark: {\n debug: {\n emoji: \"🌙\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #2d3748 0%, #4a5568 100%)\",\n color: \"#e2e8f0\",\n border: \"1px solid #4a5568\",\n shadow: \"0 2px 4px rgba(45, 55, 72, 0.8)\"\n },\n info: {\n emoji: \"💡\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #1a202c 0%, #2d3748 100%)\",\n color: \"#90cdf4\",\n border: \"1px solid #3182ce\",\n shadow: \"0 2px 4px rgba(26, 32, 44, 0.8)\"\n },\n warn: {\n emoji: \"⚡\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #744210 0%, #975a16 100%)\",\n color: \"#faf089\",\n border: \"1px solid #d69e2e\",\n shadow: \"0 2px 4px rgba(116, 66, 16, 0.8)\"\n },\n error: {\n emoji: \"💀\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #742a2a 0%, #9b2c2c 100%)\",\n color: \"#feb2b2\",\n border: \"1px solid #e53e3e\",\n shadow: \"0 2px 4px rgba(116, 42, 42, 0.8)\"\n },\n success: {\n emoji: \"🎯\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #276749 0%, #2f855a 100%)\",\n color: \"#9ae6b4\",\n border: \"1px solid #38a169\",\n shadow: \"0 2px 4px rgba(39, 103, 73, 0.8)\"\n },\n critical: {\n emoji: \"💥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #1a1a1a 0%, #ff0000 100%)\",\n color: \"#ffffff\",\n border: \"2px solid #ff0000\",\n shadow: \"0 4px 8px rgba(255, 0, 0, 0.9)\"\n }\n },\n neon: {\n debug: {\n emoji: \"⚡\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #0f3460 0%, #e94560 100%)\",\n color: \"#00ffff\",\n border: \"1px solid #00ffff\",\n shadow: \"0 0 10px rgba(0, 255, 255, 0.5)\"\n },\n info: {\n emoji: \"🔮\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #16213e 0%, #0f3460 100%)\",\n color: \"#00ff41\",\n border: \"1px solid #00ff41\",\n shadow: \"0 0 10px rgba(0, 255, 65, 0.5)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #533a03 0%, #e94560 100%)\",\n color: \"#ffff00\",\n border: \"1px solid #ffff00\",\n shadow: \"0 0 10px rgba(255, 255, 0, 0.5)\"\n },\n error: {\n emoji: \"💥\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #5c0a0a 0%, #ff073a 100%)\",\n color: \"#ff073a\",\n border: \"1px solid #ff073a\",\n shadow: \"0 0 10px rgba(255, 7, 58, 0.8)\"\n },\n success: {\n emoji: \"✨\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #0a5c0a 0%, #39ff14 100%)\",\n color: \"#39ff14\",\n border: \"1px solid #39ff14\",\n shadow: \"0 0 10px rgba(57, 255, 20, 0.8)\"\n },\n critical: {\n emoji: \"🌟\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #000000 0%, #ff0080 100%)\",\n color: \"#ff0080\",\n border: \"2px solid #ff0080\",\n shadow: \"0 0 20px rgba(255, 0, 128, 1)\"\n }\n },\n minimal: {\n debug: {\n emoji: \"\",\n label: \"DEBUG\",\n background: \"#f7fafc\",\n color: \"#4a5568\",\n border: \"1px solid #e2e8f0\",\n shadow: \"none\"\n },\n info: {\n emoji: \"\",\n label: \"INFO\",\n background: \"#ebf8ff\",\n color: \"#2b6cb0\",\n border: \"1px solid #bee3f8\",\n shadow: \"none\"\n },\n warn: {\n emoji: \"\",\n label: \"WARN\",\n background: \"#fffbf0\",\n color: \"#c05621\",\n border: \"1px solid #fed7aa\",\n shadow: \"none\"\n },\n error: {\n emoji: \"\",\n label: \"ERROR\",\n background: \"#fef5f5\",\n color: \"#c53030\",\n border: \"1px solid #fca5a5\",\n shadow: \"none\"\n },\n success: {\n emoji: \"\",\n label: \"SUCCESS\",\n background: \"#f0fff4\",\n color: \"#2f855a\",\n border: \"1px solid #9ae6b4\",\n shadow: \"none\"\n },\n critical: {\n emoji: \"\",\n label: \"CRITICAL\",\n background: \"#fef5f5\",\n color: \"#e53e3e\",\n border: \"2px solid #f56565\",\n shadow: \"none\"\n }\n },\n // Additional theme variants can be added here\n light: {\n debug: {\n emoji: \"🔍\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)\",\n color: \"#1565c0\",\n border: \"1px solid #90caf9\",\n shadow: \"0 1px 3px rgba(33, 150, 243, 0.2)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%)\",\n color: \"#7b1fa2\",\n border: \"1px solid #ce93d8\",\n shadow: \"0 1px 3px rgba(156, 39, 176, 0.2)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%)\",\n color: \"#f57c00\",\n border: \"1px solid #ffcc02\",\n shadow: \"0 1px 3px rgba(255, 152, 0, 0.2)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%)\",\n color: \"#d32f2f\",\n border: \"1px solid #f44336\",\n shadow: \"0 1px 3px rgba(244, 67, 54, 0.2)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%)\",\n color: \"#388e3c\",\n border: \"1px solid #4caf50\",\n shadow: \"0 1px 3px rgba(76, 175, 80, 0.2)\"\n },\n critical: {\n emoji: \"🚨\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%)\",\n color: \"#c2185b\",\n border: \"2px solid #e91e63\",\n shadow: \"0 2px 6px rgba(233, 30, 99, 0.3)\"\n }\n },\n cyberpunk: {\n debug: {\n emoji: \"🤖\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #0d1b2a 0%, #415a77 100%)\",\n color: \"#00d4aa\",\n border: \"1px solid #00d4aa\",\n shadow: \"0 0 15px rgba(0, 212, 170, 0.4)\"\n },\n info: {\n emoji: \"🔗\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #1b263b 0%, #0d1b2a 100%)\",\n color: \"#00b4d8\",\n border: \"1px solid #00b4d8\",\n shadow: \"0 0 15px rgba(0, 180, 216, 0.4)\"\n },\n warn: {\n emoji: \"⚡\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #f72585 0%, #b5179e 100%)\",\n color: \"#ffff3f\",\n border: \"1px solid #ffff3f\",\n shadow: \"0 0 15px rgba(255, 255, 63, 0.4)\"\n },\n error: {\n emoji: \"💀\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #7209b7 0%, #480ca8 100%)\",\n color: \"#ff006e\",\n border: \"1px solid #ff006e\",\n shadow: \"0 0 15px rgba(255, 0, 110, 0.6)\"\n },\n success: {\n emoji: \"⚡\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #003566 0%, #001d3d 100%)\",\n color: \"#00f5ff\",\n border: \"1px solid #00f5ff\",\n shadow: \"0 0 15px rgba(0, 245, 255, 0.4)\"\n },\n critical: {\n emoji: \"💥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #000000 0%, #ff0040 100%)\",\n color: \"#ff0040\",\n border: \"2px solid #ff0040\",\n shadow: \"0 0 25px rgba(255, 0, 64, 0.8)\"\n }\n }\n};\nconst BANNER_VARIANTS = {\n simple: {\n text: \"🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀\",\n style: \"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold; font-size: 14px;\"\n },\n ascii: {\n text: `\n ___ ____ _ __ ___ _ __ _____ _____ ____ __ ___ _____ _____ _____ ____ \n / _ \\\\ / __ \\\\| | / / / _ \\\\ | \\\\ | |/ ____| ____| _ \\\\ | | / _ \\\\ / ____| ___| _ | _ \\\\ \n / /_\\\\ \\\\ / / _\\` | |/ / / /_\\\\ \\\\ | \\\\| | | | |__ | | | | | | / / \\\\ \\\\| | __| |_ | |_| | |_) |\n | _ || | (_| | < | _ | | . \\` | | | __| | | | | | | | | | | | |_ | _| | /| _ < \n | | | |\\\\ \\\\__,_|_|\\\\_\\\\ | | | | | |\\\\ | |___| |____| |_| | | |__\\\\ \\\\_/ /| |__| | |___| |\\\\ \\\\| |_) |\n \\\\_| |_/ \\\\____/ \\\\_| |_/ |_| \\\\_|\\\\_____|______|____/ |_____/\\\\___/ \\\\_____|_____|_| \\\\_|____/\n\n Advanced Logger v2.0.0 - Console Excellence`,\n style: 'font-family: \"Courier New\", Consolas, Monaco, monospace; color: #667eea; font-size: 11px; line-height: 1.2;'\n },\n unicode: {\n text: `\n╔══════════════════════════════════════════════════════════════════════════╗\n║ 🚀 ADVANCED LOGGER v2.0.0 ║\n║ State-of-the-art Console Styling ║ \n╚══════════════════════════════════════════════════════════════════════════╝`,\n style: 'font-family: \"Courier New\", Consolas, Monaco, monospace; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; font-size: 12px; line-height: 1.3;'\n },\n svg: {\n text: \" \",\n style: `\n background-image: url(\"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 80'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='8'/><text x='200' y='30' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>🚀 ADVANCED LOGGER</text><text x='200' y='50' text-anchor='middle' fill='white' font-family='monospace' font-size='12'>State-of-the-art Console Styling</text><text x='200' y='65' text-anchor='middle' fill='white' font-family='monospace' font-size='10'>v2.0.0</text></svg>\");\n background-repeat: no-repeat;\n background-size: 400px 80px;\n padding: 40px 200px;\n color: transparent;\n display: inline-block;\n border-radius: 8px;\n `\n },\n animated: {\n text: \" 🚀 ADVANCED LOGGER v2.0.0 \",\n style: `\n background: linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2);\n background-size: 400% 400%;\n color: white;\n padding: 15px 25px;\n border-radius: 10px;\n font-weight: bold;\n font-size: 14px;\n font-family: monospace;\n animation: gradientShift 3s ease infinite;\n display: inline-block;\n `\n }\n};\nconst THEME_BANNERS = {\n default: {\n simple: \"🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀\",\n style: \"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold;\"\n },\n dark: {\n simple: \"🌙 ADVANCED LOGGER v2.0.0 - Dark Mode Console Excellence 🌙\",\n style: \"background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); color: #e2e8f0; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #4a5568;\"\n },\n neon: {\n simple: \"⚡ ADVANCED LOGGER v2.0.0 - Cyberpunk Console Experience ⚡\",\n style: \"background: linear-gradient(135deg, #0f3460 0%, #e94560 100%); color: #00ffff; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00ffff;\"\n },\n minimal: {\n simple: \"ADVANCED LOGGER v2.0.0 - Clean Console Styling\",\n style: \"background: #f7fafc; color: #2d3748; padding: 8px 16px; border: 1px solid #e2e8f0; border-radius: 4px; font-weight: 500;\"\n },\n light: {\n simple: \"☀️ ADVANCED LOGGER v2.0.0 - Bright Console Styling ☀️\",\n style: \"background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); color: #495057; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #dee2e6;\"\n },\n cyberpunk: {\n simple: \"🤖 ADVANCED LOGGER v2.0.0 - Neural Console Interface 🤖\",\n style: \"background: linear-gradient(135deg, #0d1b2a 0%, #415a77 100%); color: #00d4aa; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00d4aa; border: 1px solid #00d4aa;\"\n }\n};\nfunction detectBannerCapabilities() {\n const userAgent = navigator.userAgent;\n const isChrome = /Chrome/.test(userAgent);\n const isFirefox = /Firefox/.test(userAgent);\n const isSafari = /Safari/.test(userAgent) && !/Chrome/.test(userAgent);\n const supportsSVG = !!document.createElementNS && !!document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\").createSVGRect;\n const supportsAnimations = typeof document !== \"undefined\" && \"animationName\" in document.createElement(\"div\").style;\n if (supportsAnimations && isChrome) {\n return \"animated\";\n } else if (supportsSVG && (isChrome || isFirefox)) {\n return \"svg\";\n } else if (isChrome || isFirefox) {\n return \"unicode\";\n } else if (isSafari) {\n return \"ascii\";\n }\n return \"simple\";\n}\nfunction displayInitBanner(bannerType) {\n const selectedType = bannerType || detectBannerCapabilities();\n const banner = BANNER_VARIANTS[selectedType];\n if (selectedType === \"animated\") {\n const style = document.createElement(\"style\");\n style.textContent = `\n @keyframes gradientShift {\n 0% { background-position: 0% 50%; }\n 50% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n `;\n document.head.appendChild(style);\n }\n console.log(`%c${banner.text}`, banner.style);\n const features = [\n \"🎨 Advanced CSS Console Styling\",\n \"📍 Automatic Stack Trace Parsing\",\n \"🔧 Scoped Loggers & Prefixes\",\n \"⚡ Performance Timers\",\n \"🎯 Verbosity Filtering\",\n \"🔌 Extensible Handlers\",\n \"📱 Modern TypeScript Patterns\",\n \"📤 Export & Clipboard Support\"\n ];\n console.group(`%c✨ Features`, \"background: #f8f9fa; color: #495057; padding: 4px 8px; border-radius: 4px; font-weight: bold;\");\n features.forEach((feature) => {\n console.log(`%c${feature}`, \"color: #6c757d; font-size: 13px;\");\n });\n console.groupEnd();\n console.log(\"\");\n}\nclass BaseStyler {\n builder;\n constructor(builder = new StyleBuilder()) {\n this.builder = builder;\n }\n /**\n * Primary brand color (typically blue)\n */\n primary() {\n return this.color(\"#007bff\");\n }\n /**\n * Secondary color (typically gray)\n */\n secondary() {\n return this.color(\"#6c757d\");\n }\n /**\n * Accent color for highlights\n */\n accent() {\n return this.color(\"#17a2b8\");\n }\n /**\n * Muted/subtle color - automatically adaptive\n */\n muted() {\n const mutedColors = { light: \"#6c757d\", dark: \"#a0aec0\" };\n return this.color(getAdaptiveColor(mutedColors));\n }\n /**\n * Success color (green)\n */\n success() {\n return this.color(\"#28a745\");\n }\n /**\n * Warning color (yellow/orange)\n */\n warning() {\n return this.color(\"#ffc107\");\n }\n /**\n * Danger/error color (red)\n */\n danger() {\n return this.color(\"#dc3545\");\n }\n /**\n * Monospace font family\n */\n mono() {\n this.builder.font('Monaco, Consolas, \"Courier New\", monospace');\n return this;\n }\n /**\n * System font family\n */\n system() {\n this.builder.font('system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif');\n return this;\n }\n /**\n * Readable font optimized for text\n */\n readable() {\n this.builder.font('Georgia, \"Times New Roman\", serif');\n return this;\n }\n /**\n * Compact spacing\n */\n compact() {\n this.builder.padding(\"1px 4px\").margin(\"0 1px\");\n return this;\n }\n /**\n * Spacious layout\n */\n spacious() {\n this.builder.padding(\"6px 12px\").margin(\"2px 4px\");\n return this;\n }\n /**\n * Inline display\n */\n inline() {\n this.builder.display(\"inline-block\");\n return this;\n }\n /**\n * Glass morphism effect\n */\n glassmorphic() {\n this.builder.css(\"backdrop-filter\", \"blur(10px)\").css(\"background\", \"rgba(255, 255, 255, 0.1)\").border(\"1px solid rgba(255, 255, 255, 0.2)\").rounded(\"8px\");\n return this;\n }\n /**\n * Neon glow effect\n */\n neon() {\n const neonColor = \"#00ffff\";\n this.builder.color(neonColor).border(`1px solid ${neonColor}`).shadow(`0 0 10px ${neonColor}, 0 0 20px ${neonColor}`).css(\"text-shadow\", `0 0 5px ${neonColor}`);\n return this;\n }\n /**\n * Gradient background\n */\n gradient(from = \"#667eea\", to = \"#764ba2\") {\n this.builder.bg(`linear-gradient(135deg, ${from} 0%, ${to} 100%)`);\n return this;\n }\n /**\n * Bold text\n */\n bold() {\n this.builder.bold();\n return this;\n }\n /**\n * Set color with automatic adaptation\n */\n color(color) {\n this.builder.color(color);\n return this;\n }\n /**\n * Build the final CSS string\n */\n build() {\n return this.builder.build();\n }\n}\nclass TimestampStyler extends BaseStyler {\n /**\n * Default timestamp style - subtle and informative\n */\n default() {\n this.muted().mono();\n this.builder.size(\"11px\");\n return this;\n }\n /**\n * Hide timestamp\n */\n hidden() {\n this.builder.display(\"none\");\n return this;\n }\n /**\n * Minimal timestamp (just time, no date)\n */\n minimal() {\n this.muted().mono();\n this.builder.size(\"10px\").opacity(0.7);\n return this;\n }\n /**\n * Set font size\n */\n size(size) {\n this.builder.size(size);\n return this;\n }\n}\nclass LevelStyler extends BaseStyler {\n /**\n * Colorful gradient badge\n */\n badge() {\n this.builder.padding(\"2px 8px\").rounded(\"4px\").bold().color(\"#ffffff\");\n return this;\n }\n /**\n * Glowing effect for dark themes\n */\n glowing() {\n return this.neon().badge();\n }\n /**\n * Minimal flat style\n */\n flat() {\n this.builder.padding(\"1px 6px\").rounded(\"2px\").border(\"1px solid currentColor\").css(\"background\", \"transparent\");\n return this;\n }\n /**\n * Uppercase text\n */\n uppercase() {\n this.builder.uppercase();\n return this;\n }\n}\nclass PrefixStyler extends BaseStyler {\n /**\n * Dark theme prefix\n */\n dark() {\n const prefixColors = { light: \"#2d3748\", dark: \"#4a5568\" };\n const textColors = { light: \"#e2e8f0\", dark: \"#f7fafc\" };\n this.builder.bg(getAdaptiveColor(prefixColors)).color(getAdaptiveColor(textColors)).padding(\"2px 6px\").rounded(\"3px\").bold().mono().size(\"11px\");\n return this;\n }\n /**\n * Light theme prefix\n */\n light() {\n this.builder.bg(\"#f8f9fa\").color(\"#495057\").padding(\"2px 6px\").rounded(\"3px\").bold().mono().size(\"11px\").border(\"1px solid #dee2e6\");\n return this;\n }\n /**\n * Compact prefix\n */\n compact() {\n this.builder.padding(\"1px 4px\").size(\"10px\").rounded(\"2px\");\n return this;\n }\n}\nclass MessageStyler extends BaseStyler {\n /**\n * Readable message text - automatically adaptive\n */\n readable() {\n this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).system().size(\"14px\");\n return this;\n }\n /**\n * Code-style monospace text\n */\n code() {\n this.builder.mono().size(\"13px\").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).bg(\"rgba(0, 0, 0, 0.05)\").padding(\"1px 4px\").rounded(\"3px\");\n return this;\n }\n /**\n * Large, prominent text\n */\n large() {\n this.builder.size(\"16px\").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText));\n return this;\n }\n}\nclass LocationStyler extends BaseStyler {\n /**\n * Subtle location info - automatically adaptive\n */\n subtle() {\n this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.location)).mono().size(\"11px\").opacity(0.7);\n return this;\n }\n /**\n * Hide location info\n */\n hidden() {\n this.builder.display(\"none\");\n return this;\n }\n /**\n * Clickable style (for IDE integration)\n */\n clickable() {\n this.subtle();\n this.builder.css(\"text-decoration\", \"underline\").cursor(\"pointer\");\n return this;\n }\n}\nclass LogStyleBuilder {\n logStyles = {};\n logger;\n constructor(logger) {\n this.logger = logger;\n }\n /**\n * Configure timestamp styling\n */\n timestamp() {\n return new TimestampStyleBuilderProxy(this);\n }\n /**\n * Configure level badge styling\n */\n level() {\n return new LevelStyleBuilderProxy(this);\n }\n /**\n * Configure prefix styling\n */\n prefix() {\n return new PrefixStyleBuilderProxy(this);\n }\n /**\n * Configure message text styling\n */\n message() {\n return new MessageStyleBuilderProxy(this);\n }\n /**\n * Configure location info styling\n */\n location() {\n return new LocationStyleBuilderProxy(this);\n }\n /**\n * Use a predefined preset\n */\n usePreset(presetName) {\n console.warn(`Preset '${presetName}' will be available in next implementation phase`);\n return this;\n }\n /**\n * Customize with partial configuration\n */\n customize(overrides) {\n this.logStyles = { ...this.logStyles, ...overrides };\n return this;\n }\n /**\n * Set layout spacing\n */\n spacing(type) {\n if (!this.logStyles.layout) {\n this.logStyles.layout = { spacing: type };\n } else {\n this.logStyles.layout.spacing = type;\n }\n switch (type) {\n case \"compact\":\n this.logStyles.layout.innerPadding = \"1px\";\n this.logStyles.layout.outerMargin = \"0px\";\n break;\n case \"spacious\":\n this.logStyles.layout.innerPadding = \"4px\";\n this.logStyles.layout.outerMargin = \"2px\";\n break;\n default:\n this.logStyles.layout.innerPadding = \"2px\";\n this.logStyles.layout.outerMargin = \"1px\";\n }\n return this;\n }\n /**\n * Set backdrop filter for glassmorphism effects\n */\n backdrop(filter) {\n this.logStyles.backdrop = filter;\n return this;\n }\n /**\n * Set overall transparency\n */\n transparency(value) {\n this.logStyles.transparency = Math.max(0, Math.min(1, value));\n return this;\n }\n /**\n * Apply the configured styles to the logger\n */\n apply() {\n this.logger._customLogStyles = this.logStyles;\n console.log(\"Applied log styles:\", this.logStyles);\n }\n /**\n * Get current configuration (for debugging)\n */\n getConfig() {\n return { ...this.logStyles };\n }\n /**\n * Internal method to update part configuration\n */\n _updatePartConfig(part, styles) {\n if (part === \"layout\" || part === \"backdrop\" || part === \"transparency\") {\n return;\n }\n if (!this.logStyles[part]) {\n this.logStyles[part] = {};\n }\n this.logStyles[part].style = styles;\n }\n}\nclass PartStyleBuilderProxy {\n parentBuilder;\n partName;\n constructor(parentBuilder, partName) {\n this.parentBuilder = parentBuilder;\n this.partName = partName;\n }\n /**\n * Return to the main builder for chaining other parts\n */\n and() {\n return this.parentBuilder;\n }\n /**\n * Apply styles and finish configuration\n */\n apply() {\n this.parentBuilder.apply();\n }\n /**\n * Helper to apply styles to the parent builder\n */\n applyStyles(styler) {\n const styles = styler.build();\n this.parentBuilder._updatePartConfig(this.partName, styles);\n return this;\n }\n}\nclass TimestampStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"timestamp\");\n }\n default() {\n return this.applyStyles(new TimestampStyler().default());\n }\n hidden() {\n return this.applyStyles(new TimestampStyler().hidden());\n }\n minimal() {\n return this.applyStyles(new TimestampStyler().minimal());\n }\n muted() {\n return this.applyStyles(new TimestampStyler().muted());\n }\n mono() {\n return this.applyStyles(new TimestampStyler().mono());\n }\n compact() {\n return this.applyStyles(new TimestampStyler().compact());\n }\n}\nclass LevelStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"level\");\n }\n badge() {\n return this.applyStyles(new LevelStyler().badge());\n }\n gradient(from, to) {\n return this.applyStyles(new LevelStyler().gradient(from, to));\n }\n glowing() {\n return this.applyStyles(new LevelStyler().glowing());\n }\n flat() {\n return this.applyStyles(new LevelStyler().flat());\n }\n bold() {\n return this.applyStyles(new LevelStyler().bold());\n }\n uppercase() {\n return this.applyStyles(new LevelStyler().uppercase());\n }\n neon() {\n return this.applyStyles(new LevelStyler().neon());\n }\n}\nclass PrefixStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"prefix\");\n }\n dark() {\n return this.applyStyles(new PrefixStyler().dark());\n }\n light() {\n return this.applyStyles(new PrefixStyler().light());\n }\n compact() {\n return this.applyStyles(new PrefixStyler().compact());\n }\n muted() {\n return this.applyStyles(new PrefixStyler().muted());\n }\n mono() {\n return this.applyStyles(new PrefixStyler().mono());\n }\n}\nclass MessageStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"message\");\n }\n readable() {\n return this.applyStyles(new MessageStyler().readable());\n }\n code() {\n return this.applyStyles(new MessageStyler().code());\n }\n large() {\n return this.applyStyles(new MessageStyler().large());\n }\n system() {\n return this.applyStyles(new MessageStyler().system());\n }\n mono() {\n return this.applyStyles(new MessageStyler().mono());\n }\n}\nclass LocationStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"location\");\n }\n subtle() {\n return this.applyStyles(new LocationStyler().subtle());\n }\n hidden() {\n return this.applyStyles(new LocationStyler().hidden());\n }\n clickable() {\n return this.applyStyles(new LocationStyler().clickable());\n }\n muted() {\n return this.applyStyles(new LocationStyler().muted());\n }\n mono() {\n return this.applyStyles(new LocationStyler().mono());\n }\n}\nfunction createLogStyleBuilder(logger) {\n return new LogStyleBuilder(logger);\n}\nconst SMART_PRESETS = {\n /**\n * Default preset - works perfectly out-of-the-box\n * Clean, readable, automatically adaptive to dark/light themes\n */\n default: {\n layout: {\n spacing: \"normal\",\n innerPadding: \"2px\",\n outerMargin: \"1px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"Monaco, Consolas, monospace\",\n size: \"11px\"\n },\n level: {\n show: true,\n style: \"badge\",\n uppercase: false,\n padding: \"2px 8px\"\n },\n prefix: {\n show: true,\n style: \"dark\",\n // Automatically adaptive\n padding: \"2px 6px\"\n },\n message: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"system-ui, -apple-system, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"Monaco, Consolas, monospace\",\n size: \"11px\"\n }\n },\n /**\n * Cyberpunk preset - neon colors, glowing effects, dark theme\n */\n cyberpunk: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"1px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: true,\n color: \"#00ffff\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\",\n style: \"neon\"\n },\n level: {\n show: true,\n style: \"glowing\",\n uppercase: true,\n padding: \"2px 8px\"\n },\n prefix: {\n show: true,\n color: \"#ff0080\",\n background: \"rgba(255, 0, 128, 0.1)\",\n border: \"1px solid #ff0080\",\n style: \"neon\"\n },\n message: {\n show: true,\n color: \"#00ff41\",\n font: \"Monaco, Consolas, monospace\",\n size: \"13px\"\n },\n location: {\n show: false\n // Hidden for cleaner look\n },\n backdrop: \"blur(2px)\",\n transparency: 0.9\n },\n /**\n * Glassmorphism preset - modern blur effects, transparency\n */\n glassmorphism: {\n layout: {\n spacing: \"spacious\",\n innerPadding: \"4px\",\n outerMargin: \"2px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\",\n style: \"glassmorphic\"\n },\n level: {\n show: true,\n style: \"glassmorphic\",\n uppercase: false,\n padding: \"4px 12px\"\n },\n prefix: {\n show: true,\n style: \"glassmorphic\",\n padding: \"3px 8px\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\",\n style: \"glassmorphic\"\n },\n backdrop: \"blur(10px)\",\n transparency: 0.8\n },\n /**\n * Minimal preset - clean, no decorations, maximum readability\n */\n minimal: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"0px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: false\n // Hidden for minimal look\n },\n level: {\n show: true,\n style: \"flat\",\n uppercase: true,\n padding: \"0px 4px\",\n border: \"none\",\n background: \"transparent\"\n },\n prefix: {\n show: true,\n style: \"flat\",\n padding: \"0px 4px\",\n border: \"none\",\n background: \"transparent\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: false\n // Hidden for minimal look\n }\n },\n /**\n * Debug preset - monospace, detailed, compact for development\n */\n debug: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"1px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n level: {\n show: true,\n style: \"compact\",\n uppercase: true,\n padding: \"1px 4px\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n prefix: {\n show: true,\n style: \"compact\",\n padding: \"1px 4px\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"12px\"\n },\n location: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\",\n style: \"clickable\"\n }\n },\n /**\n * Production preset - clean, essential info only\n */\n production: {\n layout: {\n spacing: \"normal\",\n innerPadding: \"2px\",\n outerMargin: \"1px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\"\n },\n level: {\n show: true,\n style: \"badge\",\n uppercase: false,\n padding: \"2px 6px\"\n },\n prefix: {\n show: false\n // Hidden in production\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: false\n // Hidden in production\n }\n }\n};\nfunction getSmartPreset(name) {\n return SMART_PRESETS[name] || null;\n}\nfunction getAvailablePresets() {\n return Object.keys(SMART_PRESETS);\n}\nfunction hasPreset(name) {\n return name in SMART_PRESETS;\n}\nfunction stripAnsi(str) {\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\nfunction getVisibleLength(str) {\n return stripAnsi(str).length;\n}\nfunction padToWidth(str, width, align = \"left\") {\n const visibleLen = getVisibleLength(str);\n if (visibleLen >= width) return str;\n const padding = width - visibleLen;\n switch (align) {\n case \"right\":\n return \" \".repeat(padding) + str;\n case \"center\":\n const leftPad = Math.floor(padding / 2);\n const rightPad = padding - leftPad;\n return \" \".repeat(leftPad) + str + \" \".repeat(rightPad);\n case \"left\":\n default:\n return str + \" \".repeat(padding);\n }\n}\nfunction formatWithRightAlign(leftContent, rightContent, maxWidth) {\n const width = maxWidth ?? getTerminalWidth();\n const leftLen = getVisibleLength(leftContent);\n const rightLen = getVisibleLength(rightContent);\n const gap = width - leftLen - rightLen;\n if (gap <= 1) {\n return `${leftContent} ${rightContent}`;\n }\n return `${leftContent}${\" \".repeat(gap)}${rightContent}`;\n}\nfunction formatColumns(columns, maxWidth, colorCapability = \"full\") {\n const width = maxWidth ?? getTerminalWidth();\n columns.length;\n const columnsWithWidths = columns.map((col, idx) => {\n if (col.width) return { ...col, calculatedWidth: col.width };\n const remainingWidth = width - columns.filter((c, i) => i !== idx && c.width).reduce((sum, c) => sum + (c.width ?? 0), 0);\n const autoColumns = columns.filter((c) => !c.width).length;\n const calculatedWidth = Math.floor(remainingWidth / autoColumns);\n return { ...col, calculatedWidth };\n });\n return columnsWithWidths.map((col) => {\n let content = col.content;\n if (col.color && colorCapability !== \"none\") {\n const colorCode = getANSIForeground(col.color, colorCapability);\n content = `${colorCode}${content}${ANSI.reset}`;\n }\n return padToWidth(content, col.calculatedWidth, col.align);\n }).join(\"\");\n}\nfunction formatKeyValue(obj, colorCapability = \"full\", options = {}) {\n const {\n separator = \" \",\n keyColor = \"#888888\",\n valueColor = \"#00ffff\"\n } = options;\n const entries = Object.entries(obj);\n if (entries.length === 0) return \"\";\n const keyColorCode = colorCapability !== \"none\" ? getANSIForeground(keyColor, colorCapability) : \"\";\n const valueColorCode = colorCapability !== \"none\" ? getANSIForeground(valueColor, colorCapability) : \"\";\n const reset = colorCapability !== \"none\" ? ANSI.reset : \"\";\n return entries.map(([key, value]) => {\n const valueStr = typeof value === \"object\" ? JSON.stringify(value) : String(value);\n return `${keyColorCode}${key}:${reset} ${valueColorCode}${valueStr}${reset}`;\n }).join(separator);\n}\nfunction isKeyValueObject(obj) {\n if (typeof obj !== \"object\" || obj === null) return false;\n if (Array.isArray(obj)) return false;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return false;\n const values = Object.values(obj);\n return values.every(\n (v) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\" || v === null\n );\n}\nfunction formatBadge(badge, style = \"brackets\", colorCapability = \"full\", color) {\n const colorCode = color && colorCapability !== \"none\" ? getANSIForeground(color, colorCapability) : \"\";\n const reset = colorCapability !== \"none\" ? ANSI.reset : \"\";\n const bgBlack = colorCapability !== \"none\" ? ANSI.bg.black : \"\";\n const text = badge.toUpperCase();\n switch (style) {\n case \"rounded\":\n return `${bgBlack}${colorCode}⟨${text}⟩${reset}`;\n case \"plain\":\n return `${colorCode}${text}${reset}`;\n case \"unicode\":\n return `${bgBlack}${colorCode}╭${text}╮${reset}`;\n case \"pill\":\n return `${bgBlack}${colorCode}⦗${text}⦘${reset}`;\n case \"brackets\":\n default:\n return `${bgBlack}${colorCode}[${text}]${reset}`;\n }\n}\nfunction formatTimestamp(date = /* @__PURE__ */ new Date(), format = \"time\") {\n switch (format) {\n case \"iso\":\n return date.toISOString();\n case \"date\":\n return date.toISOString().split(\"T\")[0] ?? \"\";\n case \"time\":\n return date.toTimeString().slice(0, 8);\n case \"timeMs\":\n return date.toTimeString().slice(0, 8) + \".\" + String(date.getMilliseconds()).padStart(3, \"0\");\n case \"relative\":\n return formatRelativeTime(date);\n case \"elapsed\":\n return formatElapsedTime(date);\n case \"custom\":\n default:\n return date.toLocaleTimeString();\n }\n}\nlet startTime = null;\nfunction formatRelativeTime(date) {\n if (startTime === null) {\n startTime = Date.now();\n }\n const diff = date.getTime() - startTime;\n if (diff < 1e3) {\n return `+${diff}ms`;\n } else if (diff < 6e4) {\n return `+${(diff / 1e3).toFixed(1)}s`;\n } else {\n const mins = Math.floor(diff / 6e4);\n const secs = Math.floor(diff % 6e4 / 1e3);\n return `+${mins}m${secs}s`;\n }\n}\nfunction formatElapsedTime(date) {\n if (startTime === null) {\n startTime = Date.now();\n }\n const diff = date.getTime() - startTime;\n const hours = Math.floor(diff / 36e5);\n const mins = Math.floor(diff % 36e5 / 6e4);\n const secs = Math.floor(diff % 6e4 / 1e3);\n return `${String(hours).padStart(2, \"0\")}:${String(mins).padStart(2, \"0\")}:${String(secs).padStart(2, \"0\")}`;\n}\nfunction resetStartTime() {\n startTime = Date.now();\n}\nfunction applyLogOptions(message, options, colorCapability = \"full\") {\n let result = message;\n if (options.rightAlign) {\n result = formatWithRightAlign(message, options.rightAlign);\n }\n return result;\n}\nclass ScopedLogger {\n parent;\n scopeName;\n badgeList = [];\n contextStack = [];\n _timers;\n constructor(parent, scopeName) {\n this.parent = parent;\n this.scopeName = scopeName;\n }\n get timers() {\n if (!this._timers) this._timers = /* @__PURE__ */ new Map();\n return this._timers;\n }\n getBindings() {\n return {\n scope: this.getScopePrefix(),\n badges: this.badgeList.length > 0 ? [...this.badgeList] : void 0\n };\n }\n getScopePrefix() {\n if (this.contextStack.length === 0) return this.scopeName;\n return [this.scopeName, ...this.contextStack].join(\":\");\n }\n badges(badges) {\n this.badgeList = [...badges];\n return this;\n }\n badge(badge) {\n if (!this.badgeList.includes(badge)) {\n this.badgeList.push(badge);\n }\n return this;\n }\n clearBadges() {\n this.badgeList = [];\n return this;\n }\n style(presetName) {\n this.parent.setTheme(presetName);\n return this;\n }\n context(contextName) {\n return new ContextLogger(this, contextName);\n }\n time(label) {\n this.timers.set(label, {\n label: `${this.scopeName}:${label}`,\n startTime: performance.now()\n });\n }\n timeEnd(label) {\n const timer = this.timers.get(label);\n if (!timer) {\n this.warn(`Timer '${label}' not found`);\n return void 0;\n }\n const elapsed = performance.now() - timer.startTime;\n this.timers.delete(label);\n this.success(`Timer: ${label} - ${elapsed.toFixed(2)}ms`);\n return elapsed;\n }\n debug(...args) {\n this.parent.logWithBindings(this.getBindings(), \"debug\", ...args);\n }\n info(...args) {\n this.parent.logWithBindings(this.getBindings(), \"info\", ...args);\n }\n warn(...args) {\n this.parent.logWithBindings(this.getBindings(), \"warn\", ...args);\n }\n error(...args) {\n this.parent.logWithBindings(this.getBindings(), \"error\", ...args);\n }\n success(...args) {\n const bindings = this.getBindings();\n this.parent.logWithBindings(bindings, \"info\", ...args);\n }\n critical(...args) {\n this.parent.logWithBindings(this.getBindings(), \"critical\", ...args);\n }\n trace(...args) {\n this.parent.logWithBindings(this.getBindings(), \"debug\", ...args);\n console.trace(`[${this.scopeName}]`);\n }\n _pushContext(context) {\n this.contextStack.push(context);\n }\n _popContext() {\n this.contextStack.pop();\n }\n}\nclass APILogger extends ScopedLogger {\n constructor(parent, apiName) {\n super(parent, `API:${apiName}`);\n this.badge(\"API\");\n }\n slow(message, duration) {\n this.badge(\"SLOW\");\n const msg = duration ? `${message} (${duration}ms)` : message;\n this.warn(msg);\n }\n rateLimit(message) {\n this.badge(\"RATE_LIMIT\");\n this.warn(message);\n }\n auth(message) {\n this.badge(\"AUTH\");\n this.error(message);\n }\n deprecated(message) {\n this.badge(\"DEPRECATED\");\n this.warn(message);\n }\n}\nclass ComponentLogger extends ScopedLogger {\n constructor(parent, componentName) {\n super(parent, componentName);\n this.badge(\"COMPONENT\");\n }\n lifecycle(event, message) {\n this.badge(\"LIFECYCLE\");\n const msg = message ? `${event}: ${message}` : event;\n this.info(msg);\n }\n stateChange(from, to, data) {\n this.badge(\"STATE\");\n const msg = `${from} → ${to}`;\n if (data) {\n this.info(msg, data);\n } else {\n this.info(msg);\n }\n }\n propsChange(changes) {\n this.badge(\"PROPS\");\n this.debug(\"Props changed:\", changes);\n }\n}\nclass ContextLogger {\n parentLogger;\n contextName;\n constructor(parentLogger, contextName) {\n this.parentLogger = parentLogger;\n this.contextName = contextName;\n }\n run(fn) {\n this.parentLogger._pushContext(this.contextName);\n try {\n return fn();\n } finally {\n this.parentLogger._popContext();\n }\n }\n async runAsync(fn) {\n this.parentLogger._pushContext(this.contextName);\n try {\n return await fn();\n } finally {\n this.parentLogger._popContext();\n }\n }\n start() {\n this.parentLogger._pushContext(this.contextName);\n }\n end() {\n this.parentLogger._popContext();\n }\n debug(...args) {\n this.parentLogger.debug(...args);\n }\n info(...args) {\n this.parentLogger.info(...args);\n }\n warn(...args) {\n this.parentLogger.warn(...args);\n }\n error(...args) {\n this.parentLogger.error(...args);\n }\n success(...args) {\n this.parentLogger.success(...args);\n }\n critical(...args) {\n this.parentLogger.critical(...args);\n }\n}\nclass ExportLogHandler {\n buffer = [];\n maxSize;\n groupDepth = 0;\n currentGroup;\n constructor(maxSize = BUFFER_LIMITS.DEFAULT_SIZE) {\n this.maxSize = Math.min(Math.max(maxSize, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);\n }\n /**\n * Handle incoming log and store in buffer\n */\n handle(level, message, args, metadata) {\n const entry = {\n id: generateLogId(),\n timestamp: metadata.timestamp,\n level,\n prefix: metadata.prefix,\n message,\n args,\n location: metadata.stackInfo,\n groupInfo: this.groupDepth > 0 ? {\n depth: this.groupDepth,\n groupName: this.currentGroup\n } : void 0\n };\n this.buffer.push(entry);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n }\n /**\n * Set group tracking for nested logs\n */\n setGroupInfo(depth, groupName) {\n this.groupDepth = depth;\n this.currentGroup = groupName;\n }\n /**\n * Get buffer statistics\n */\n getBufferStats() {\n const levelCounts = this.buffer.reduce((acc, entry) => {\n const currentCount = acc[entry.level] ? acc[entry.level] : 0;\n acc[entry.level] = currentCount + 1;\n return acc;\n }, {});\n let oldestLog;\n let newestLog;\n if (this.buffer.length > 0) {\n const firstEntry = this.buffer[0];\n const lastEntry = this.buffer[this.buffer.length - 1];\n if (firstEntry && firstEntry.timestamp) {\n oldestLog = new Date(firstEntry.timestamp);\n }\n if (lastEntry && lastEntry.timestamp) {\n newestLog = new Date(lastEntry.timestamp);\n }\n }\n return {\n size: this.buffer.length,\n maxSize: this.maxSize,\n usage: this.buffer.length / this.maxSize * 100,\n oldestLog,\n newestLog,\n levelCounts: {\n debug: levelCounts.debug ? levelCounts.debug : 0,\n info: levelCounts.info ? levelCounts.info : 0,\n warn: levelCounts.warn ? levelCounts.warn : 0,\n error: levelCounts.error ? levelCounts.error : 0,\n critical: levelCounts.critical ? levelCounts.critical : 0\n }\n };\n }\n /**\n * Clear the buffer\n */\n clearBuffer() {\n this.buffer = [];\n }\n /**\n * Set buffer size (with limits)\n */\n setBufferSize(size) {\n this.maxSize = Math.min(Math.max(size, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);\n if (this.buffer.length > this.maxSize) {\n this.buffer = this.buffer.slice(-this.maxSize);\n }\n }\n /**\n * Filter logs based on criteria\n */\n filterLogs(filters = {}) {\n let filtered = [...this.buffer];\n if (filters.levels?.length) {\n filtered = filtered.filter((entry) => filters.levels.includes(entry.level));\n }\n if (filters.prefixes?.length) {\n filtered = filtered.filter(\n (entry) => entry.prefix && filters.prefixes.includes(entry.prefix)\n );\n }\n if (filters.excludePrefixes?.length) {\n filtered = filtered.filter(\n (entry) => !entry.prefix || !filters.excludePrefixes.includes(entry.prefix)\n );\n }\n if (filters.since) {\n const sinceDate = parseTimeInput(filters.since);\n filtered = filtered.filter((entry) => new Date(entry.timestamp) >= sinceDate);\n }\n if (filters.until) {\n const untilDate = parseTimeInput(filters.until);\n filtered = filtered.filter((entry) => new Date(entry.timestamp) <= untilDate);\n }\n if (filters.withStackTrace) {\n filtered = filtered.filter((entry) => entry.location);\n }\n if (filters.errorsOnly) {\n filtered = filtered.filter((entry) => entry.level === \"error\" || entry.level === \"critical\");\n }\n if (filters.search) {\n const searchTerm = filters.search.toLowerCase();\n filtered = filtered.filter(\n (entry) => entry.message.toLowerCase().includes(searchTerm) || entry.args.some(\n (arg) => String(arg).toLowerCase().includes(searchTerm)\n )\n );\n }\n if (filters.last) {\n filtered = filtered.slice(-filters.last);\n }\n if (filters.first) {\n filtered = filtered.slice(0, filters.first);\n }\n return filtered;\n }\n /**\n * Export logs in JSON format\n */\n exportJSON(logs, options) {\n const data = logs.map((entry) => ({\n timestamp: entry.timestamp,\n level: entry.level,\n prefix: entry.prefix,\n message: entry.message,\n ...options.minimal ? {} : {\n args: entry.args.slice(1),\n location: entry.location,\n groupInfo: entry.groupInfo\n }\n }));\n return options.compact ? JSON.stringify(data) : JSON.stringify(data, null, 2);\n }\n /**\n * Export logs in CSV format\n */\n exportCSV(logs, options) {\n const headers = options.minimal ? [\"Timestamp\", \"Level\", \"Prefix\", \"Message\"] : [\"Timestamp\", \"Level\", \"Prefix\", \"Message\", \"File\", \"Line\", \"Args\"];\n const rows = logs.map((entry) => {\n const baseRow = [\n formatDisplayTime(new Date(entry.timestamp), \"full\"),\n entry.level.toUpperCase(),\n entry.prefix || \"\",\n `\"${entry.message.replace(/\"/g, '\"\"')}\"`\n ];\n if (!options.minimal) {\n baseRow.push(\n entry.location?.file || \"\",\n entry.location?.line?.toString() || \"\",\n `\"${safeStringify(entry.args.slice(1)).replace(/\"/g, '\"\"')}\"`\n );\n }\n return baseRow;\n });\n return [headers.join(\",\"), ...rows.map((row) => row.join(\",\"))].join(\"\\n\");\n }\n /**\n * Export logs in Markdown format\n */\n exportMarkdown(logs, options) {\n const now = /* @__PURE__ */ new Date();\n let content = `# Log Export - ${formatDisplayTime(now, \"full\")}\n\n`;\n if (!options.minimal) {\n const summary = this.getBufferStats();\n content += `## Summary\n`;\n content += `- **Total logs**: ${logs.length}\n`;\n content += `- **Errors**: ${summary.levelCounts.error + summary.levelCounts.critical}\n`;\n content += `- **Warnings**: ${summary.levelCounts.warn}\n\n`;\n }\n if (options.groupBy === \"level\") {\n const grouped = logs.reduce((acc, entry) => {\n const level = entry.level;\n if (!acc[level]) {\n acc[level] = [];\n }\n const levelArray = acc[level];\n if (levelArray) {\n levelArray.push(entry);\n }\n return acc;\n }, {});\n Object.entries(grouped).forEach(([level, entries]) => {\n const emoji = this.getLevelEmoji(level);\n content += `## ${emoji} ${level.toUpperCase()} (${entries.length})\n\n`;\n entries.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"time-only\");\n const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n const prefix = entry.prefix ? ` **${entry.prefix}**:` : \"\";\n content += `- \\`${time}\\`${prefix} ${entry.message}${location}\n`;\n });\n content += \"\\n\";\n });\n } else {\n content += \"## Logs\\n\\n\";\n logs.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"time-only\");\n const emoji = this.getLevelEmoji(entry.level);\n const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n const prefix = entry.prefix ? ` **${entry.prefix}**:` : \"\";\n content += `- \\`${time}\\` ${emoji}${prefix} ${entry.message}${location}\n`;\n });\n }\n return content;\n }\n /**\n * Export logs in plain text format\n */\n exportPlain(logs, options) {\n return logs.map((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), options.minimal ? \"time-only\" : \"short\");\n const level = entry.level.toUpperCase().padEnd(8);\n const prefix = entry.prefix ? `[${entry.prefix}] ` : \"\";\n const location = !options.minimal && entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n return `${time} ${level} ${prefix}${entry.message}${location}`;\n }).join(\"\\n\");\n }\n /**\n * Export logs in HTML format\n */\n exportHTML(logs, _options) {\n const title = `Log Export - ${formatDisplayTime(/* @__PURE__ */ new Date(), \"full\")}`;\n let html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 20px; line-height: 1.6; }\n .header { border-bottom: 2px solid #ddd; padding-bottom: 20px; margin-bottom: 20px; }\n .log-entry { margin: 5px 0; padding: 8px; border-radius: 4px; font-family: 'Monaco', 'Consolas', monospace; }\n .timestamp { color: #666; font-size: 0.9em; }\n .level { font-weight: bold; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }\n .prefix { background: #2d3748; color: #e2e8f0; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }\n .location { color: #718096; font-size: 0.9em; }\n .debug { background: #f0f4ff; }\n .info { background: #f0f9ff; }\n .warn { background: #fffbeb; }\n .error { background: #fef2f2; }\n .critical { background: #fef2f2; border-left: 4px solid #dc2626; }\n .level.debug { background: #667eea; color: white; }\n .level.info { background: #74b9ff; color: white; }\n .level.warn { background: #fdcb6e; color: #2d3436; }\n .level.error { background: #e84393; color: white; }\n .level.critical { background: #ff3838; color: white; }\n </style>\n</head>\n<body>\n <div class=\"header\">\n <h1>${title}</h1>\n <p>Generated by Advanced Logger v2.0.0</p>\n </div>\n <div class=\"logs\">`;\n logs.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"full\");\n const location = entry.location ? ` <span class=\"location\">(${escapeHtml(entry.location.file)}:${entry.location.line})</span>` : \"\";\n const prefix = entry.prefix ? ` <span class=\"prefix\">${escapeHtml(entry.prefix)}</span>` : \"\";\n html += `\n <div class=\"log-entry ${entry.level}\">\n <span class=\"timestamp\">${time}</span>\n <span class=\"level ${entry.level}\">${entry.level.toUpperCase()}</span>\n ${prefix}\n <span class=\"message\">${escapeHtml(entry.message)}</span>\n ${location}\n </div>`;\n });\n html += `\n </div>\n</body>\n</html>`;\n return html;\n }\n /**\n * Get emoji for log level\n */\n getLevelEmoji(level) {\n const emojis = {\n debug: \"🐞\",\n info: \"ℹ️\",\n warn: \"⚠️\",\n error: \"❌\",\n critical: \"🔥\"\n };\n return emojis[level] || \"\";\n }\n /**\n * Main export function\n */\n export(format, filters = {}, options = {}) {\n const filteredLogs = this.filterLogs(filters);\n let data;\n switch (format) {\n case \"json\":\n data = this.exportJSON(filteredLogs, options);\n break;\n case \"csv\":\n data = this.exportCSV(filteredLogs, options);\n break;\n case \"markdown\":\n data = this.exportMarkdown(filteredLogs, options);\n break;\n case \"plain\":\n data = this.exportPlain(filteredLogs, options);\n break;\n case \"html\":\n data = this.exportHTML(filteredLogs, options);\n break;\n default:\n throw new Error(`Unsupported export format: ${format}`);\n }\n return {\n format,\n data,\n metadata: {\n totalLogs: this.buffer.length,\n filteredLogs: filteredLogs.length,\n exportedAt: (/* @__PURE__ */ new Date()).toISOString(),\n filters,\n options\n }\n };\n }\n /**\n * Copy to clipboard with fallback\n */\n async copyToClipboard(format, filters = {}, options = {}) {\n const result = this.export(format, filters, options);\n try {\n if (navigator.clipboard && window.isSecureContext) {\n await navigator.clipboard.writeText(result.data);\n return true;\n } else {\n const textArea = document.createElement(\"textarea\");\n textArea.value = result.data;\n textArea.style.position = \"fixed\";\n textArea.style.opacity = \"0\";\n document.body.appendChild(textArea);\n textArea.focus();\n textArea.select();\n const success = document.execCommand(\"copy\");\n document.body.removeChild(textArea);\n return success;\n }\n } catch (error) {\n console.error(\"Failed to copy to clipboard:\", error);\n return false;\n }\n }\n /**\n * Get all logs (for debugging)\n */\n getAllLogs() {\n return [...this.buffer];\n }\n /**\n * Save export to file with download prompt\n */\n async saveToFile(format, filters = {}, options = {}) {\n try {\n const result = this.export(format, filters, options);\n const blob = new Blob([result.data], {\n type: this.getMimeType(format)\n });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n const filename = this.generateFilename(format, filters);\n a.href = url;\n a.download = filename;\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n return true;\n } catch (error) {\n console.error(\"Failed to save file:\", error);\n return false;\n }\n }\n /**\n * Get MIME type for format\n */\n getMimeType(format) {\n const mimeTypes = {\n json: \"application/json\",\n csv: \"text/csv\",\n markdown: \"text/markdown\",\n plain: \"text/plain\",\n html: \"text/html\"\n };\n return mimeTypes[format] || \"text/plain\";\n }\n /**\n * Generate filename with timestamp\n */\n generateFilename(format, filters) {\n const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, \"-\").slice(0, -5);\n const prefix = filters.prefixes?.length === 1 ? `_${filters.prefixes[0]}` : \"\";\n const extension = format === \"markdown\" ? \"md\" : format;\n return `logs${prefix}_${timestamp}.${extension}`;\n }\n /**\n * Stream logs to external endpoint\n */\n async streamToEndpoint(endpoint, filters = {}, options = {}) {\n try {\n const logs = this.filterLogs(filters);\n const batchSize = options.batchSize || 100;\n const format = options.format || \"json\";\n for (let i = 0; i < logs.length; i += batchSize) {\n const batch = logs.slice(i, i + batchSize);\n const result = this.export(format, {}, { compact: true });\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (options.apiKey) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n logs: batch,\n metadata: {\n batchIndex: Math.floor(i / batchSize),\n totalBatches: Math.ceil(logs.length / batchSize),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n }\n })\n });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n }\n return true;\n } catch (error) {\n console.error(\"Failed to stream logs:\", error);\n return false;\n }\n }\n /**\n * Create export with metadata enrichment\n */\n exportWithMetadata(format, filters = {}, options = {}) {\n const baseResult = this.export(format, filters, options);\n const bufferStats = this.getBufferStats();\n return {\n ...baseResult,\n metadata: {\n ...baseResult.metadata,\n bufferStats,\n performance: {\n memoryUsage: this.estimateMemoryUsage(),\n processingTime: Date.now()\n },\n system: {\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : \"Node.js\",\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone\n }\n }\n };\n }\n /**\n * Estimate memory usage of buffer\n */\n estimateMemoryUsage() {\n const sampleEntry = this.buffer[0];\n if (!sampleEntry) return 0;\n const sampleSize = JSON.stringify(sampleEntry).length;\n return sampleSize * this.buffer.length;\n }\n}\nclass CommandProcessor {\n commands = /* @__PURE__ */ new Map();\n aliases = /* @__PURE__ */ new Map();\n plugins = /* @__PURE__ */ new Map();\n history = [];\n maxHistorySize = 100;\n isInteractiveMode = false;\n /**\n * Register a command\n */\n registerCommand(command) {\n this.commands.set(command.name, command);\n if (command.aliases) {\n for (const alias of command.aliases) {\n this.aliases.set(alias, command.name);\n }\n }\n }\n /**\n * Register a plugin\n */\n registerPlugin(plugin, logger) {\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin ${plugin.name} is already registered`);\n }\n this.plugins.set(plugin.name, plugin);\n for (const command of plugin.commands) {\n this.registerCommand(command);\n }\n if (plugin.initialize && logger) {\n plugin.initialize(this, logger);\n }\n }\n /**\n * Unregister a plugin\n */\n unregisterPlugin(pluginName) {\n const plugin = this.plugins.get(pluginName);\n if (!plugin) return;\n for (const command of plugin.commands) {\n this.commands.delete(command.name);\n if (command.aliases) {\n for (const alias of command.aliases) {\n this.aliases.delete(alias);\n }\n }\n }\n if (plugin.cleanup) {\n plugin.cleanup();\n }\n this.plugins.delete(pluginName);\n }\n /**\n * Get all registered commands\n */\n getCommands() {\n return Array.from(this.commands.values());\n }\n /**\n * Get a specific command\n */\n getCommand(name) {\n let command = this.commands.get(name);\n if (command) return command;\n const aliasTarget = this.aliases.get(name);\n if (aliasTarget) {\n return this.commands.get(aliasTarget);\n }\n return void 0;\n }\n /**\n * Get command history\n */\n getHistory() {\n return [...this.history];\n }\n /**\n * Clear command history\n */\n clearHistory() {\n this.history = [];\n }\n /**\n * Get registered plugins\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n /**\n * Enter interactive mode\n */\n enterInteractiveMode(logger) {\n this.isInteractiveMode = true;\n logger.info(\"🔧 Interactive CLI mode activated. Type /exit to quit, /help for commands.\");\n if (typeof window !== \"undefined\") {\n this.setupBrowserInteractiveMode(logger);\n }\n }\n /**\n * Exit interactive mode\n */\n exitInteractiveMode() {\n this.isInteractiveMode = false;\n }\n /**\n * Setup browser interactive mode\n */\n setupBrowserInteractiveMode(logger) {\n window.cli = (commandString) => {\n return this.processCommand(`/${commandString}`, logger);\n };\n logger.info('💡 Use cli(\"command\") to execute CLI commands in browser console.');\n }\n /**\n * Process a CLI command\n */\n async processCommand(commandString, logger) {\n if (!commandString.startsWith(\"/\")) {\n logger.error(\"Invalid command. Commands must start with /\");\n this.addToHistory(commandString, false);\n return;\n }\n const parts = commandString.slice(1).split(\" \");\n const commandName = parts[0] || \"\";\n const args = parts.slice(1).join(\" \");\n const command = this.getCommand(commandName);\n if (!command) {\n logger.error(`Unknown command: ${commandName}. Type /help for available commands.`);\n const suggestions = this.getSuggestions(commandName);\n if (suggestions.length > 0) {\n logger.info(`📋 Did you mean: ${suggestions.slice(0, 3).join(\", \")}?`);\n }\n this.addToHistory(commandString, false);\n return;\n }\n try {\n await command.execute(args || \"\", logger);\n this.addToHistory(commandString, true);\n } catch (error) {\n logger.error(`Command '${commandName}' failed:`, error);\n this.addToHistory(commandString, false);\n }\n }\n /**\n * Add command to history\n */\n addToHistory(command, success) {\n this.history.unshift({\n command,\n timestamp: /* @__PURE__ */ new Date(),\n success\n });\n if (this.history.length > this.maxHistorySize) {\n this.history = this.history.slice(0, this.maxHistorySize);\n }\n }\n /**\n * Get command suggestions for partial matches\n */\n getSuggestions(partial) {\n const commandNames = Array.from(this.commands.keys());\n return commandNames.filter((name) => name.startsWith(partial));\n }\n}\nclass ConfigCommand {\n name = \"config\";\n description = \"Show or update logger configuration\";\n usage = \"/config [json|key=value,...]\";\n execute(args, logger) {\n if (!args) {\n this.showStatus(logger);\n return;\n }\n try {\n if (args.startsWith(\"{\")) {\n const config = JSON.parse(args);\n this.applyConfig(config, logger);\n } else {\n const pairs = args.split(\",\").map((pair) => pair.trim().split(\"=\"));\n const config = {};\n pairs.forEach(([key, value]) => {\n if (key && value) {\n config[key.trim()] = value.trim().replace(/[\"']/g, \"\");\n }\n });\n this.applyConfig(config, logger);\n }\n } catch (error) {\n logger.error(\"Invalid config format. Use JSON or key=value pairs:\", error);\n logger.info('Examples: /config {\"theme\":\"dark\"} or /config theme=neon,verbosity=debug');\n }\n }\n showStatus(logger) {\n const statusData = {\n theme: logger.getConfig().theme || \"default\",\n verbosity: logger.getConfig().verbosity,\n colors: logger.getConfig().enableColors,\n timestamps: logger.getConfig().enableTimestamps,\n stackTrace: logger.getConfig().enableStackTrace,\n globalPrefix: logger.getConfig().globalPrefix || \"none\",\n bannerType: logger.getConfig().bannerType || \"simple\",\n handlers: logger.getHandlers().length\n };\n logger.group(\"⚙️ Logger Configuration\");\n logger.table(statusData);\n logger.groupEnd();\n }\n applyConfig(config, logger) {\n const validKeys = [\"theme\", \"verbosity\", \"enableColors\", \"enableTimestamps\", \"enableStackTrace\", \"globalPrefix\", \"bannerType\"];\n const applied = [];\n Object.entries(config).forEach(([key, value]) => {\n if (validKeys.includes(key)) {\n if (key === \"theme\" && typeof value === \"string\") {\n logger.setTheme(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"bannerType\" && typeof value === \"string\") {\n logger.setBannerType(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"verbosity\") {\n logger.setVerbosity(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"globalPrefix\") {\n logger.setGlobalPrefix(value);\n applied.push(`${key}=${value}`);\n } else {\n logger.updateConfig({ [key]: value });\n applied.push(`${key}=${value}`);\n }\n } else {\n logger.warn(`Invalid config key: ${key}`);\n }\n });\n if (applied.length > 0) {\n logger.success(`Configuration updated: ${applied.join(\", \")}`);\n }\n }\n}\nclass ThemesCommand {\n name = \"themes\";\n description = \"Show available theme presets\";\n usage = \"/themes\";\n execute(_args, logger) {\n logger.group(\"🎨 Available Themes\");\n Object.keys(THEME_PRESETS).forEach((themeName) => {\n const preview = THEME_PRESETS[themeName];\n const previewStyle = new StyleBuilder().bg(preview.info.background).color(preview.info.color).padding(\"4px 8px\").rounded(\"4px\").border(preview.info.border).build();\n console.log(`%c${themeName}`, previewStyle, `- ${themeName} theme preview`);\n });\n logger.groupEnd();\n }\n}\nclass BannersCommand {\n name = \"banners\";\n description = \"Show available banner types\";\n usage = \"/banners\";\n execute(_args, logger) {\n logger.group(\"🖼️ Available Banner Types\");\n Object.keys(BANNER_VARIANTS).forEach((bannerName) => {\n const banner = BANNER_VARIANTS[bannerName];\n console.log(`%c${bannerName}`, \"font-weight: bold; color: #667eea;\");\n console.log(`%cPreview:`, \"color: #666; font-size: 12px;\");\n if (bannerName === \"simple\") {\n console.log(`%c${banner.text}`, banner.style);\n } else if (bannerName === \"ascii\") {\n console.log(`%c${banner.text.split(\"\\n\").slice(1, 4).join(\"\\n\")}...`, \"font-family: monospace; color: #667eea; font-size: 10px;\");\n } else if (bannerName === \"unicode\") {\n console.log(`%c${banner.text}`, banner.style);\n } else {\n console.log(`%c${bannerName} banner`, \"color: #666; font-style: italic;\");\n }\n });\n logger.groupEnd();\n }\n}\nclass BannerCommand {\n name = \"banner\";\n description = \"Change or show current banner type\";\n usage = \"/banner [type]\";\n execute(args, logger) {\n if (!args) {\n logger.showBanner();\n return;\n }\n if (args in BANNER_VARIANTS) {\n logger.setBannerType(args);\n logger.showBanner();\n } else {\n logger.error(`Invalid banner type: ${args}. Available: ${Object.keys(BANNER_VARIANTS).join(\", \")}`);\n }\n }\n}\nclass StatusCommand {\n name = \"status\";\n description = \"Show current logger status and configuration\";\n usage = \"/status\";\n execute(_args, logger) {\n const config = logger.getConfig();\n const statusData = {\n theme: config.theme ? config.theme : \"default\",\n verbosity: config.verbosity,\n colors: config.enableColors,\n timestamps: config.enableTimestamps,\n stackTrace: config.enableStackTrace,\n globalPrefix: config.globalPrefix ? config.globalPrefix : \"none\",\n bannerType: config.bannerType ? config.bannerType : \"simple\",\n handlers: logger.getHandlers().length,\n bufferSize: config.bufferSize ? config.bufferSize : 1e3\n };\n logger.group(\"⚙️ Logger Configuration\");\n logger.table(statusData);\n logger.groupEnd();\n const exportHandler = logger.getExportHandler();\n if (exportHandler) {\n const bufferStats = exportHandler.getBufferStats();\n logger.group(\"📊 Buffer Statistics\");\n logger.table({\n size: `${bufferStats.size}/${bufferStats.maxSize}`,\n usage: `${bufferStats.usage.toFixed(1)}%`,\n oldestLog: bufferStats.oldestLog ? bufferStats.oldestLog.toISOString() : \"None\",\n newestLog: bufferStats.newestLog ? bufferStats.newestLog.toISOString() : \"None\",\n errorCount: bufferStats.levelCounts.error + bufferStats.levelCounts.critical,\n warningCount: bufferStats.levelCounts.warn\n });\n logger.groupEnd();\n }\n }\n}\nclass ResetCommand {\n name = \"reset\";\n description = \"Reset logger configuration to defaults\";\n usage = \"/reset\";\n execute(_args, logger) {\n logger.resetConfig();\n }\n}\nclass DemoCommand {\n name = \"demo\";\n description = \"Show comprehensive feature demonstration\";\n usage = \"/demo\";\n execute(_args, logger) {\n logger.group(\"🎪 Advanced Logger Demo\");\n logger.debug(\"Debug message with detailed information\");\n logger.info(\"Informational message about system state\");\n logger.warn(\"Warning about deprecated feature\");\n logger.error(\"Error processing user request\");\n logger.success(\"Operation completed successfully\");\n logger.critical(\"Critical system failure detected\");\n logger.group(\"📊 Advanced Features Demo\");\n logger.table([\n { feature: \"Styled Console\", status: \"✅ Active\", performance: \"Excellent\" },\n { feature: \"Theme System\", status: \"✅ Active\", performance: \"Great\" },\n { feature: \"CLI Interface\", status: \"✅ Active\", performance: \"Good\" },\n { feature: \"Export System\", status: \"✅ Active\", performance: \"Excellent\" }\n ]);\n logger.time(\"demo-operation\");\n setTimeout(() => {\n logger.timeEnd(\"demo-operation\");\n }, 100);\n logger.logWithSVG(\"SVG Demo\");\n logger.logAnimated(\"🌟 Animated Logger Demo 🌟\", 2);\n logger.groupEnd();\n logger.groupEnd();\n logger.info(\"Demo completed! Check the console for styled output.\");\n }\n}\nfunction parseArguments(args) {\n const filters = {};\n const options = {};\n let format;\n if (!args.trim()) return { filters, options };\n const argParts = args.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g) || [];\n for (let i = 0; i < argParts.length; i++) {\n const arg = argParts[i];\n if (!arg) {\n continue;\n }\n if (i === 0 && !arg.startsWith(\"--\") && arg in EXPORT_FORMATS) {\n format = arg;\n continue;\n }\n if (arg.startsWith(\"--\")) {\n const [flag, value] = arg.slice(2).split(\"=\");\n switch (flag) {\n case \"level\":\n case \"levels\":\n if (value) {\n filters.levels = value.split(\",\").map((l) => l.trim());\n }\n break;\n case \"since\":\n if (value) filters.since = value;\n break;\n case \"until\":\n if (value) filters.until = value;\n break;\n case \"prefix\":\n case \"prefixes\":\n if (value) {\n filters.prefixes = value.split(\",\").map((p) => p.trim());\n }\n break;\n case \"exclude-prefix\":\n case \"exclude-prefixes\":\n if (value) {\n filters.excludePrefixes = value.split(\",\").map((p) => p.trim());\n }\n break;\n case \"last\":\n if (value) filters.last = parseInt(value, 10);\n break;\n case \"first\":\n if (value) filters.first = parseInt(value, 10);\n break;\n case \"search\":\n if (value) filters.search = value.replace(/['\"]/g, \"\");\n break;\n case \"with-stack\":\n filters.withStackTrace = true;\n break;\n case \"errors-only\":\n filters.errorsOnly = true;\n break;\n case \"group-by\":\n if (value) {\n filters.groupBy = value;\n options.groupBy = value;\n }\n break;\n case \"minimal\":\n options.minimal = true;\n break;\n case \"compact\":\n options.compact = true;\n break;\n case \"styled\":\n options.styled = true;\n break;\n }\n }\n }\n return { filters, options, format };\n}\nclass ExportCommand {\n name = \"export\";\n description = \"Export logs to various formats\";\n usage = \"/export <format> [--filter=value] [--option]\";\n execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available. Make sure ExportLogHandler is registered.\");\n return;\n }\n const { filters, options, format } = parseArguments(args);\n if (!format) {\n logger.error(\"Format required. Available formats: \" + Object.keys(EXPORT_FORMATS).join(\", \"));\n logger.info(\"Usage: /export <format> [--filter=value]\");\n logger.info(\"Example: /export json --level=error,warn --last=50\");\n return;\n }\n try {\n const result = exportHandler.export(format, filters, options);\n logger.success(`✅ Export completed: ${result.metadata.filteredLogs} logs exported in ${format} format`);\n if (result.data.length < 1e3) {\n logger.group(`📄 Preview (${format.toUpperCase()})`);\n console.log(result.data);\n logger.groupEnd();\n } else {\n logger.info(`📄 Export size: ${(result.data.length / 1024).toFixed(2)}KB`);\n }\n logger.table({\n format: result.format,\n totalLogs: result.metadata.totalLogs,\n filtered: result.metadata.filteredLogs,\n exported: result.metadata.exportedAt\n });\n } catch (error) {\n logger.error(\"Export failed:\", error);\n }\n }\n}\nclass CopyCommand {\n name = \"copy\";\n description = \"Copy logs to clipboard\";\n usage = \"/copy <format> [--filter=value] [--option]\";\n async execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available. Make sure ExportLogHandler is registered.\");\n return;\n }\n const { filters, options, format } = parseArguments(args);\n if (!format) {\n logger.error(\"Format required. Available formats: \" + Object.keys(EXPORT_FORMATS).join(\", \"));\n logger.info(\"Usage: /copy <format> [--filter=value]\");\n logger.info(\"Example: /copy plain --level=error --last=25\");\n return;\n }\n try {\n const success = await exportHandler.copyToClipboard(format, filters, options);\n if (success) {\n const result = exportHandler.export(format, filters, options);\n logger.success(`📋 Copied ${result.metadata.filteredLogs} logs to clipboard (${format} format)`);\n } else {\n logger.error(\"Failed to copy to clipboard. Browser may not support clipboard API.\");\n }\n } catch (error) {\n logger.error(\"Copy failed:\", error);\n }\n }\n}\nclass BufferSizeCommand {\n name = \"buffer-size\";\n description = \"Set log buffer size\";\n usage = \"/buffer-size <size>\";\n execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const size = parseInt(args.trim(), 10);\n if (isNaN(size) || size <= 0) {\n logger.error(\"Invalid buffer size. Must be a positive number.\");\n logger.info(\"Example: /buffer-size 2000\");\n return;\n }\n exportHandler.setBufferSize(size);\n logger.success(`Buffer size set to ${size}`);\n }\n}\nclass ClearBufferCommand {\n name = \"clear-buffer\";\n description = \"Clear the log buffer\";\n usage = \"/clear-buffer\";\n execute(_args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const stats = exportHandler.getBufferStats();\n exportHandler.clearBuffer();\n logger.success(`✅ Buffer cleared. Removed ${stats.size} log entries.`);\n }\n}\nclass BufferInfoCommand {\n name = \"buffer-info\";\n description = \"Show buffer statistics and information\";\n usage = \"/buffer-info\";\n execute(_args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const stats = exportHandler.getBufferStats();\n logger.group(\"📊 Buffer Information\");\n logger.table({\n size: `${stats.size}/${stats.maxSize}`,\n usage: `${stats.usage.toFixed(1)}%`,\n oldestLog: stats.oldestLog?.toLocaleString() || \"None\",\n newestLog: stats.newestLog?.toLocaleString() || \"None\"\n });\n logger.group(\"📈 Log Level Counts\");\n logger.table(stats.levelCounts);\n logger.groupEnd();\n logger.groupEnd();\n }\n}\nclass HelpCommand {\n name = \"help\";\n description = \"Show CLI help and available commands\";\n usage = \"/help [command]\";\n execute(_args, logger) {\n const helpStyle = new StyleBuilder().bg(\"linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)\").color(\"#495057\").padding(\"15px 20px\").rounded(\"8px\").border(\"1px solid #dee2e6\").font(\"Monaco, Consolas, monospace\").size(\"13px\").build();\n const helpText = `\n╭─────────────── ADVANCED LOGGER CLI COMMANDS ─────────────────╮\n│ │\n│ CONFIGURATION │\n│ /config Show current configuration │\n│ /config {json} Apply JSON configuration │\n│ /config key=val Apply key-value configuration │\n│ /themes Show available themes │\n│ /banners Show available banner types │\n│ /banner [type] Change/show banner type │\n│ /status Show logger status & buffer stats │\n│ /demo Show feature demonstration │\n│ /reset Reset to default configuration │\n│ │\n│ EXPORT & CLIPBOARD │\n│ /export <format> Export logs (json|csv|md|plain|html) │\n│ /copy <format> Copy logs to clipboard │\n│ /buffer-size N Set log buffer size │\n│ /buffer-info Show buffer statistics │\n│ /clear-buffer Clear stored logs │\n│ │\n│ EXPORT FILTERS (for export/copy commands) │\n│ --level error,warn Filter by log levels │\n│ --since 2h Logs from last 2 hours │\n│ --until 1h Logs until 1 hour ago │\n│ --prefix API,DB Filter by prefixes │\n│ --exclude-prefix INT Exclude prefixes │\n│ --last 50 Last 50 logs only │\n│ --first 25 First 25 logs only │\n│ --search \"error\" Search in log messages │\n│ --with-stack Only logs with stack traces │\n│ --errors-only Only error + critical logs │\n│ --group-by level Group by level/prefix/hour │\n│ │\n│ EXPORT OPTIONS │\n│ --minimal Minimal output format │\n│ --compact Remove extra whitespace │\n│ --styled Include styling (HTML format) │\n│ │\n├──────────────────── CONFIGURATION OPTIONS ─────────────────┤\n│ │\n│ theme: default | dark | light | neon | minimal | cyberpunk│\n│ bannerType: simple | ascii | unicode | svg | animated │\n│ verbosity: debug | info | warn | error | critical | silent│\n│ enableColors: true | false │\n│ enableTimestamps: true | false │\n│ enableStackTrace: true | false │\n│ globalPrefix: \"string\" │\n│ bufferSize: number (50-10000) │\n│ │\n├──────────────────────── EXAMPLES ──────────────────────────┤\n│ │\n│ Basic Configuration: │\n│ /config {\"theme\":\"dark\",\"verbosity\":\"debug\"} │\n│ /config theme=neon,bufferSize=2000 │\n│ /banner animated Change to animated banner │\n│ │\n│ Export Examples: │\n│ /export json --level=error,warn --last=25 │\n│ /export csv --since=2h --prefix=API │\n│ /export markdown --group-by=level --errors-only │\n│ /export html --styled --since=1h │\n│ │\n│ Clipboard Examples: │\n│ /copy plain --minimal --last=10 │\n│ /copy json --search=\"authentication\" --compact │\n│ /copy csv --since=30m --exclude-prefix=DEBUG │\n│ │\n│ Buffer Management: │\n│ /buffer-size 5000 Increase buffer to 5000 logs │\n│ /buffer-info Show detailed buffer statistics │\n│ /clear-buffer Clear all stored logs │\n│ │\n│ Time Formats: │\n│ --since=2h 2 hours ago │\n│ --since=30m 30 minutes ago │\n│ --since=1d 1 day ago │\n│ --since=\"2024-01-01T10:00:00Z\" Specific ISO date │\n│ │\n╰─────────────────────────────────────────────────────────────╯`;\n console.log(`%c${helpText}`, helpStyle);\n logger.group(\"💡 Quick Tips\");\n const tips = [\n \"Use /demo to see all logger features in action\",\n \"Logs are automatically stored in a circular buffer for export\",\n \"Export formats: JSON (structured), CSV (Excel), Markdown (readable), Plain (simple), HTML (styled)\",\n \"Time filters support relative (2h, 30m) and absolute (ISO) formats\",\n 'Combine multiple filters: /export json --level=error --since=1h --search=\"auth\"',\n \"Use /copy for quick clipboard access instead of /export\"\n ];\n tips.forEach((tip) => {\n logger.info(`• ${tip}`);\n });\n logger.groupEnd();\n }\n}\nclass HistoryCommand {\n name = \"history\";\n description = \"Show command execution history\";\n usage = \"/history [limit] - Show recent commands (default: 10)\";\n category = \"system\";\n aliases = [\"hist\", \"h\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n const limit = parseInt(args) || 10;\n const history = processor.getHistory().slice(0, limit);\n if (history.length === 0) {\n logger.info(\"📝 No command history available\");\n return;\n }\n logger.info(`📋 Last ${history.length} commands:`);\n history.forEach((entry, index) => {\n const status = entry.success ? \"✅\" : \"❌\";\n const time = entry.timestamp.toLocaleTimeString();\n logger.info(`${status} [${time}] ${entry.command}`);\n });\n }\n}\nclass ClearHistoryCommand {\n name = \"clearhistory\";\n description = \"Clear command execution history\";\n usage = \"/clearhistory - Remove all command history\";\n category = \"system\";\n aliases = [\"clrhist\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n processor.clearHistory();\n logger.success(\"🗑️ Command history cleared\");\n }\n}\nclass InteractiveCommand {\n name = \"interactive\";\n description = \"Enter interactive CLI mode\";\n usage = \"/interactive - Start interactive command mode\";\n category = \"system\";\n aliases = [\"i\", \"repl\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n processor.enterInteractiveMode(logger);\n }\n}\nclass PluginsCommand {\n name = \"plugins\";\n description = \"List loaded CLI plugins\";\n usage = \"/plugins - Show all registered plugins\";\n category = \"system\";\n aliases = [\"plug\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n const plugins = processor.getPlugins();\n if (plugins.length === 0) {\n logger.info(\"🔌 No plugins registered\");\n return;\n }\n logger.info(`🔌 Loaded plugins (${plugins.length}):`);\n plugins.forEach((plugin) => {\n logger.info(` 📦 ${plugin.name} v${plugin.version} - ${plugin.description}`);\n logger.info(` Commands: ${plugin.commands.map((c) => c.name).join(\", \")}`);\n });\n }\n}\nfunction createDefaultCLI() {\n const processor = new CommandProcessor();\n processor.registerCommand(new HelpCommand());\n processor.registerCommand(new ConfigCommand());\n processor.registerCommand(new ThemesCommand());\n processor.registerCommand(new BannersCommand());\n processor.registerCommand(new BannerCommand());\n processor.registerCommand(new StatusCommand());\n processor.registerCommand(new ResetCommand());\n processor.registerCommand(new DemoCommand());\n processor.registerCommand(new ExportCommand());\n processor.registerCommand(new CopyCommand());\n processor.registerCommand(new BufferSizeCommand());\n processor.registerCommand(new ClearBufferCommand());\n processor.registerCommand(new BufferInfoCommand());\n processor.registerCommand(new HistoryCommand());\n processor.registerCommand(new ClearHistoryCommand());\n processor.registerCommand(new InteractiveCommand());\n processor.registerCommand(new PluginsCommand());\n return processor;\n}\nlet LEVEL_STYLES = THEME_PRESETS.default;\nclass Logger {\n config;\n scopedPrefix;\n handlers = [];\n timers = /* @__PURE__ */ new Map();\n groupDepth = 0;\n exportHandler;\n cliProcessor;\n themeChangeListener;\n badgeList = [];\n displaySettings = {\n showTimestamp: true,\n showLocation: true,\n showBadges: true\n };\n serializerRegistry;\n hookManager;\n transportManager;\n /**\n * Crea una nueva instancia del Logger\n * \n * @param {Partial<LoggerConfig>} config - Configuración opcional del logger\n * \n * @example\n * // Logger con configuración personalizada\n * const logger = new Logger({\n * theme: 'neon',\n * globalPrefix: 'MiApp',\n * verbosity: 'debug',\n * bufferSize: 1000\n * });\n */\n constructor(config = {}) {\n this.config = {\n ...DEFAULT_CONFIG$1,\n ...config\n };\n this.serializerRegistry = new SerializerRegistry();\n this.hookManager = new HookManager();\n if (this.config.bufferSize) {\n this.exportHandler = new ExportLogHandler(this.config.bufferSize);\n this.handlers.push(this.exportHandler);\n }\n this.cliProcessor = createDefaultCLI();\n if (this.config.autoDetectTheme) {\n this.setupAutoThemeDetection();\n }\n }\n // ===== PRIVATE HELPER METHODS =====\n /**\n * Configura la detección automática de tema con listener de cambios\n * @private\n * @description Detecta automáticamente si el navegador está en modo claro u oscuro\n */\n setupAutoThemeDetection() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.themeChangeListener = setupThemeChangeListener((theme) => {\n this.debug(`DevTools theme changed to: ${theme}`);\n });\n }\n // ===== CONFIGURATION METHODS =====\n /**\n * Obtiene la configuración actual del logger\n * \n * @returns {LoggerConfig} Configuración completa actual\n * \n * @example\n * const config = logger.getConfig();\n * console.log('Verbosidad actual:', config.verbosity);\n * console.log('Tema actual:', config.theme);\n * \n * @since 0.3.0\n */\n getConfig() {\n return { ...this.config };\n }\n /**\n * Actualiza la configuración del logger\n * \n * @param {Partial<LoggerConfig>} updates - Propiedades a actualizar\n * \n * @example\n * logger.updateConfig({\n * verbosity: 'debug',\n * enableTimestamps: false,\n * theme: 'cyberpunk'\n * });\n * \n * @since 0.3.0\n */\n updateConfig(updates) {\n const previousAutoDetect = this.config.autoDetectTheme;\n this.config = { ...this.config, ...updates };\n if (updates.autoDetectTheme !== void 0 && updates.autoDetectTheme !== previousAutoDetect) {\n if (updates.autoDetectTheme) {\n this.setupAutoThemeDetection();\n } else if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n }\n }\n /**\n * Establece el prefijo global para todos los mensajes de log\n * \n * @param {string} prefix - Prefijo a usar\n * \n * @example\n * logger.setGlobalPrefix('MiApp');\n * logger.info('Iniciado'); // [MiApp] Iniciado\n * \n * @since 0.3.0\n */\n setGlobalPrefix(prefix) {\n this.config.globalPrefix = prefix;\n }\n /**\n * Establece el nivel de verbosidad para filtrar la salida de logs\n * \n * @param {Verbosity} level - Nivel mínimo a mostrar ('debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent')\n * \n * @example\n * logger.setVerbosity('warn'); // Solo muestra warn, error y critical\n * logger.setVerbosity('debug'); // Muestra todos los niveles\n * logger.setVerbosity('silent'); // No muestra nada\n * \n * @since 0.3.0\n */\n setVerbosity(level) {\n this.config.verbosity = level;\n }\n /**\n * Establece el tema del logger\n * \n * @param {ThemeVariant} theme - Tema a aplicar ('default' | 'dark' | 'light' | 'neon' | 'minimal' | 'cyberpunk')\n * \n * @example\n * logger.setTheme('neon'); // Tema con colores neón\n * logger.setTheme('minimal'); // Tema minimalista\n * logger.setTheme('cyberpunk'); // Tema cyberpunk con efectos\n * \n * @since 0.3.0\n */\n setTheme(theme) {\n if (hasPreset(theme)) {\n this.preset(theme);\n return;\n }\n if (theme in THEME_PRESETS) {\n LEVEL_STYLES = THEME_PRESETS[theme];\n this.config.theme = theme;\n if (theme in THEME_BANNERS) {\n const themeBanner = THEME_BANNERS[theme];\n console.log(`%c${themeBanner.simple}`, themeBanner.style);\n }\n this.success(`Theme changed to: ${theme}`);\n } else {\n this.error(`Invalid theme: ${theme}. Available:`, [...getAvailablePresets(), ...Object.keys(THEME_PRESETS)]);\n }\n }\n /**\n * Establece el tipo de banner para mostrar en la inicialización\n * \n * @param {BannerType} bannerType - Tipo de banner ('simple' | 'ascii' | 'unicode' | 'svg' | 'animated')\n * \n * @example\n * logger.setBannerType('ascii'); // Banner con arte ASCII\n * logger.setBannerType('unicode'); // Banner con caracteres Unicode\n * logger.setBannerType('animated'); // Banner con animación\n * \n * @since 0.3.0\n */\n setBannerType(bannerType) {\n this.config.bannerType = bannerType;\n this.success(`Banner type changed to: ${bannerType}`);\n }\n /**\n * Reinicia el logger a la configuración por defecto\n * \n * @example\n * logger.resetConfig();\n * // Todo vuelve a la configuración inicial\n * \n * @since 0.3.0\n */\n resetConfig() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.config = { ...DEFAULT_CONFIG$1 };\n LEVEL_STYLES = THEME_PRESETS.default;\n if (this.config.autoDetectTheme) {\n this.setupAutoThemeDetection();\n }\n this.success(\"Logger configuration reset to defaults\");\n }\n /**\n * Método de limpieza para eliminar listeners y liberar recursos\n * \n * @example\n * // Antes de cerrar la aplicación\n * logger.cleanup();\n * \n * @since 0.3.0\n */\n cleanup() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.transportManager?.close().catch(() => {\n });\n }\n // ===== SIMPLIFIED API =====\n /**\n * Aplica un preset inteligente - funciona perfectamente sin configuración\n * \n * @param {string} name - Nombre del preset a aplicar\n * \n * @example\n * // Presets disponibles\n * logger.preset('default'); // Limpio y adaptativo\n * logger.preset('cyberpunk'); // Colores neón, efectos brillantes\n * logger.preset('glassmorphism'); // Efectos de blur modernos\n * logger.preset('minimal'); // Minimalista y elegante\n * logger.preset('debug'); // Modo desarrollo detallado\n * logger.preset('production'); // Optimizado para producción\n * \n * @since 0.3.0\n */\n preset(name) {\n if (!hasPreset(name)) {\n this.error(`Unknown preset: ${name}. Available presets:`, getAvailablePresets());\n return;\n }\n const presetConfig = getSmartPreset(name);\n if (presetConfig) {\n this.displaySettings.showTimestamp = presetConfig.timestamp?.show ?? true;\n this.displaySettings.showLocation = presetConfig.location?.show ?? true;\n this._activePreset = presetConfig;\n this._activePresetName = name;\n if (getEnvironment() === \"browser\") {\n this.success(`Applied preset: ${name}`);\n }\n }\n }\n /**\n * Lista todos los presets disponibles\n * \n * @returns {string[]} Array con nombres de presets disponibles\n * \n * @example\n * const disponibles = logger.presets();\n * console.log(disponibles); // ['default', 'cyberpunk', 'glassmorphism', ...]\n * \n * @since 0.3.0\n */\n presets() {\n return getAvailablePresets();\n }\n // ===== TOGGLE METHODS =====\n /**\n * Oculta el timestamp en los logs\n * \n * @example\n * logger.hideTimestamp();\n * logger.info('Sin marca de tiempo'); // Sin timestamp visible\n * \n * @since 0.3.0\n */\n hideTimestamp() {\n this.displaySettings.showTimestamp = false;\n return this;\n }\n /**\n * Muestra el timestamp en los logs\n * \n * @example\n * logger.showTimestamp();\n * logger.info('Con marca de tiempo'); // [2024-01-15 10:30:45] Con marca de tiempo\n * \n * @since 0.3.0\n */\n showTimestamp() {\n this.displaySettings.showTimestamp = true;\n return this;\n }\n /**\n * Oculta la información de ubicación (archivo:línea) en los logs\n * \n * @example\n * logger.hideLocation();\n * logger.debug('Sin ubicación'); // Sin mostrar archivo:línea\n * \n * @since 0.3.0\n */\n hideLocation() {\n this.displaySettings.showLocation = false;\n return this;\n }\n /**\n * Muestra la información de ubicación (archivo:línea) en los logs\n * \n * @example\n * logger.showLocation();\n * logger.debug('Con ubicación'); // app.js:42 Con ubicación\n * \n * @since 0.3.0\n */\n showLocation() {\n this.displaySettings.showLocation = true;\n return this;\n }\n /**\n * Oculta los badges en los logs\n * \n * @example\n * logger.hideBadges();\n * const api = logger.api('REST');\n * api.info('Sin badges'); // Sin mostrar [API] [REST]\n * \n * @since 0.3.0\n */\n hideBadges() {\n this.displaySettings.showBadges = false;\n return this;\n }\n /**\n * Muestra los badges en los logs\n *\n * @example\n * logger.showBadges();\n * const api = logger.api('GraphQL');\n * api.info('Con badges'); // [API] [GraphQL] Con badges\n *\n * @since 0.3.0\n */\n showBadges() {\n this.displaySettings.showBadges = true;\n return this;\n }\n /**\n * Establece múltiples badges para los logs\n *\n * @param {string[]} badges - Array de badges a mostrar\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.badges(['v3', 'stable']).info('Release publicado');\n * logger.badges(['API', 'v2']).warn('Endpoint deprecado');\n *\n * @since 3.0.0\n */\n badges(badges2) {\n this.badgeList = [...badges2];\n return this;\n }\n /**\n * Añade un badge individual a la lista\n *\n * @param {string} badge - Badge a añadir\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.badge('DEBUG').badge('AUTH').info('Token validado');\n *\n * @since 3.0.0\n */\n badge(badge2) {\n if (!this.badgeList.includes(badge2)) {\n this.badgeList.push(badge2);\n }\n return this;\n }\n /**\n * Limpia todos los badges activos\n *\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.clearBadges().info('Sin badges');\n *\n * @since 3.0.0\n */\n clearBadges() {\n this.badgeList = [];\n return this;\n }\n // ===== SCOPED LOGGERS =====\n component(name) {\n return new ComponentLogger(this, name);\n }\n api(name) {\n return new APILogger(this, name);\n }\n scope(name) {\n return new ScopedLogger(this, name);\n }\n // ===== SIMPLE CUSTOMIZATION =====\n /**\n * Personalización simple con configuración mínima\n * \n * @param {Object} overrides - Opciones de personalización\n * @param {Object} overrides.message - Configuración del mensaje\n * @param {Object} overrides.timestamp - Configuración del timestamp\n * @param {Object} overrides.location - Configuración de ubicación\n * @param {Object} overrides.level - Configuración del nivel\n * @param {Object} overrides.prefix - Configuración del prefijo\n * @param {string} overrides.spacing - Espaciado: 'compact' | 'normal' | 'spacious'\n * \n * @example\n * logger.customize({\n * message: { color: '#00ff00', size: '16px' },\n * timestamp: { show: false },\n * spacing: 'compact'\n * });\n * \n * @since 0.3.0\n */\n customize(overrides) {\n if (overrides.timestamp?.show !== void 0) {\n this.displaySettings.showTimestamp = overrides.timestamp.show;\n }\n if (overrides.location?.show !== void 0) {\n this.displaySettings.showLocation = overrides.location.show;\n }\n if (overrides.prefix?.show !== void 0) ;\n this._customization = overrides;\n this.success(\"Customization applied\");\n }\n /**\n * Access advanced styling API (for power users)\n */\n styles() {\n return createLogStyleBuilder(this);\n }\n // ===== HANDLER MANAGEMENT =====\n /**\n * Añade un handler personalizado para extender funcionalidad\n * \n * @param {ILogHandler} handler - Handler que implementa ILogHandler\n * \n * @example\n * // Handler personalizado para enviar logs a servidor\n * const remoteHandler = new RemoteLogHandler('https://api.ejemplo.com/logs');\n * logger.addHandler(remoteHandler);\n * \n * @example\n * // Handler para guardar en archivo\n * const fileHandler = new FileLogHandler('./app.log');\n * logger.addHandler(fileHandler);\n * \n * @since 0.3.0\n */\n addHandler(handler) {\n this.handlers.push(handler);\n }\n /**\n * Obtiene todos los handlers registrados\n * \n * @returns {ILogHandler[]} Array de handlers activos\n * @since 0.3.0\n */\n getHandlers() {\n return [...this.handlers];\n }\n /**\n * Obtiene el handler de exportación si está disponible\n *\n * @returns {ExportLogHandler | undefined} Handler de exportación o undefined\n * @since 0.3.0\n */\n getExportHandler() {\n return this.exportHandler;\n }\n // ===== SERIALIZERS =====\n /**\n * Añade un serializador personalizado para un tipo específico\n *\n * @param type - Constructor del tipo a serializar\n * @param serializer - Función de serialización\n * @param priority - Prioridad (mayor = primero)\n *\n * @example\n * logger.addSerializer(Error, (err) => ({\n * name: err.name,\n * message: err.message,\n * stack: err.stack?.split('\\n').slice(0, 5)\n * }));\n *\n * @since 3.0.0\n */\n addSerializer(type, serializer, priority) {\n this.serializerRegistry.add(type, serializer, priority);\n }\n /**\n * Elimina un serializador registrado\n *\n * @param type - Constructor del tipo a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n removeSerializer(type) {\n return this.serializerRegistry.remove(type);\n }\n /**\n * Obtiene el registry de serializadores\n *\n * @returns SerializerRegistry\n * @since 3.0.0\n */\n getSerializerRegistry() {\n return this.serializerRegistry;\n }\n // ===== HOOKS & MIDDLEWARE =====\n /**\n * Registra un hook para un evento\n *\n * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'\n * @param callback - Función a ejecutar\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @example\n * const unsubscribe = logger.on('beforeLog', (entry) => {\n * entry.correlationId = getCorrelationId();\n * return entry;\n * });\n *\n * @since 3.0.0\n */\n on(event, callback, priority) {\n return this.hookManager.on(event, callback, priority);\n }\n /**\n * Registra un hook que se ejecuta solo una vez\n *\n * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'\n * @param callback - Función a ejecutar\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @since 3.0.0\n */\n once(event, callback, priority) {\n return this.hookManager.once(event, callback, priority);\n }\n /**\n * Elimina un hook registrado\n *\n * @param event - Evento del hook\n * @param callback - Callback a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n off(event, callback) {\n return this.hookManager.off(event, callback);\n }\n /**\n * Añade un middleware al pipeline\n *\n * @param middleware - Función middleware\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @example\n * logger.use((entry, next) => {\n * entry.requestId = asyncLocalStorage.getStore()?.requestId;\n * next();\n * });\n *\n * @since 3.0.0\n */\n use(middleware, priority) {\n return this.hookManager.use(middleware, priority);\n }\n /**\n * Obtiene el HookManager\n *\n * @returns HookManager\n * @since 3.0.0\n */\n getHookManager() {\n return this.hookManager;\n }\n // ===== TRANSPORTS =====\n /**\n * Añade un transport para envío de logs\n *\n * @param target - Configuración del transport\n * @returns ID único del transport\n *\n * @example\n * // File transport\n * logger.addTransport({\n * target: 'file',\n * options: { destination: '/var/log/app.log' }\n * });\n *\n * @example\n * // HTTP transport con batching\n * logger.addTransport({\n * target: 'http',\n * options: {\n * url: 'https://logs.example.com',\n * batchSize: 100,\n * flushInterval: 5000\n * },\n * level: 'warn'\n * });\n *\n * @since 3.0.0\n */\n addTransport(target) {\n if (!this.transportManager) {\n this.transportManager = new TransportManager();\n }\n return this.transportManager.add(target);\n }\n /**\n * Elimina un transport\n *\n * @param id - ID del transport a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n removeTransport(id) {\n return this.transportManager?.remove(id) ?? false;\n }\n /**\n * Fuerza el flush de todos los transports\n *\n * @returns Promise que resuelve cuando todos los buffers están vaciados\n *\n * @since 3.0.0\n */\n async flushTransports() {\n await this.transportManager?.flush();\n }\n /**\n * Cierra todos los transports\n *\n * @returns Promise que resuelve cuando todos están cerrados\n *\n * @since 3.0.0\n */\n async closeTransports() {\n await this.transportManager?.close();\n }\n /**\n * Obtiene el TransportManager\n *\n * @returns TransportManager o undefined si no hay transports\n * @since 3.0.0\n */\n getTransportManager() {\n return this.transportManager;\n }\n // ===== CORE LOGGING METHODS =====\n /**\n * Verifica si un nivel de log debe mostrarse según la verbosidad actual\n * @private\n * @param {LogLevel} level - Nivel de log a verificar\n * @returns {boolean} True si debe mostrarse, false si no\n */\n shouldLog(level) {\n if (this.config.verbosity === \"silent\") return false;\n const levels = { debug: 0, info: 1, warn: 2, error: 3, critical: 4 };\n return levels[level] >= levels[this.config.verbosity];\n }\n /**\n * Obtiene el prefijo efectivo (global + scope)\n * @private\n * @returns {string | undefined} Prefijo combinado o undefined\n */\n getEffectivePrefix() {\n const parts = [this.config.globalPrefix, this.scopedPrefix].filter(Boolean);\n return parts.length > 0 ? parts.join(\":\") : void 0;\n }\n /**\n * Método central de logging que maneja estilos y formato\n * @protected\n * @param {LogLevel} level - Nivel del log\n * @param {...any} args - Argumentos a loggear\n */\n log(level, ...args) {\n if (!this.shouldLog(level)) return;\n const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;\n const prefix = this.getEffectivePrefix();\n const timestamp = formatTimestamp$1();\n const serializedArgs = args.map((arg) => this.serializerRegistry.serialize(arg));\n let message = serializedArgs.length > 0 ? String(serializedArgs[0]) : \"\";\n if (this.badgeList.length > 0 && this.displaySettings.showBadges) {\n const badgePrefix = this.badgeList.map((b) => `[${b}]`).join(\"\");\n message = badgePrefix + \" \" + message;\n }\n const additionalArgs = serializedArgs.slice(1);\n let hookEntry = {\n level,\n message,\n args: serializedArgs,\n timestamp,\n prefix,\n stackInfo: stackInfo || void 0\n };\n this.hookManager.emit(\"beforeLog\", hookEntry).then((processed) => {\n message = processed.message;\n }).catch(() => {\n });\n const [format, ...styles2] = createStyledOutput(\n level,\n LEVEL_STYLES,\n prefix,\n message,\n this.displaySettings.showLocation ? stackInfo : null,\n this.config.autoDetectTheme,\n this._activePreset,\n this._activePresetName\n );\n const groupIndent = \" \".repeat(this.groupDepth);\n const finalFormat = groupIndent + format;\n this.writeOutput(finalFormat, level, styles2, additionalArgs);\n if (this.exportHandler) {\n this.exportHandler.setGroupInfo(this.groupDepth);\n }\n const metadata = {\n timestamp,\n level,\n prefix,\n stackInfo: stackInfo ? stackInfo : void 0\n };\n this.handlers.forEach((handler) => {\n try {\n handler.handle(level, message, serializedArgs, metadata);\n } catch (error2) {\n console.error(\"Log handler failed:\", error2);\n }\n });\n if (this.transportManager) {\n const levelValues = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n critical: 4\n };\n const record = {\n level,\n levelValue: levelValues[level],\n time: Date.now(),\n msg: message,\n prefix,\n location: stackInfo ? {\n file: stackInfo.file,\n line: stackInfo.line,\n column: stackInfo.column,\n function: stackInfo.function\n } : void 0\n };\n this.transportManager.write(record).catch(() => {\n });\n }\n this.hookManager.emit(\"afterLog\", hookEntry).catch(() => {\n });\n }\n logWithBindings(bindings, level, ...args) {\n if (!this.shouldLog(level)) return;\n let prefix = \"\";\n const colorCapability = getColorCapability();\n if (bindings.badges?.length) {\n prefix += bindings.badges.map((b) => formatBadge(b, \"pill\", colorCapability, \"#00ff88\")).join(\" \") + \" \";\n }\n if (bindings.scope) {\n prefix += formatBadge(bindings.scope, \"pill\", colorCapability, \"#00ffff\") + \" \";\n }\n if (prefix && args.length > 0) {\n args[0] = prefix + String(args[0]);\n }\n this.log(level, ...args);\n }\n debug(...args) {\n this.log(\"debug\", ...args);\n }\n /**\n * Registra mensajes informativos\n * \n * @param {...any} args - Mensajes y datos informativos\n * \n * @example\n * logger.info('Servidor iniciado en puerto 3000');\n * logger.info('Usuario conectado:', userId);\n * logger.info('Procesando', totalItems, 'elementos');\n * \n * @since 0.3.0\n */\n info(...args) {\n this.log(\"info\", ...args);\n }\n /**\n * Registra mensajes de advertencia\n * \n * @param {...any} args - Mensajes de advertencia\n * \n * @example\n * logger.warn('Memoria al 85% de capacidad');\n * logger.warn('API deprecada, usar v2');\n * logger.warn('Reintentos agotados:', maxRetries);\n * \n * @since 0.3.0\n */\n warn(...args) {\n this.log(\"warn\", ...args);\n }\n /**\n * Registra mensajes de error\n * \n * @param {...any} args - Mensajes de error y stack traces\n * \n * @example\n * logger.error('Fallo en conexión a base de datos');\n * logger.error('Error al procesar:', error.message, error.stack);\n * logger.error('Código de error:', errorCode);\n * \n * @since 0.3.0\n */\n error(...args) {\n this.log(\"error\", ...args);\n }\n /**\n * Registra mensajes de éxito (nivel info especial)\n * \n * @param {...any} args - Mensajes de operaciones exitosas\n * \n * @example\n * logger.success('Base de datos conectada');\n * logger.success('Usuario creado con ID:', userId);\n * logger.success('✓ Tests pasados: 42/42');\n * \n * @since 0.3.0\n */\n success(...args) {\n if (!this.shouldLog(\"info\")) return;\n const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;\n const prefix = this.getEffectivePrefix();\n const message = args.length > 0 ? String(args[0]) : \"\";\n const additionalArgs = args.slice(1);\n const [format, ...styles2] = createStyledOutput(\n \"info\",\n LEVEL_STYLES,\n prefix,\n message,\n this.displaySettings.showLocation ? stackInfo : null,\n this.config.autoDetectTheme,\n this._activePreset,\n this._activePresetName\n );\n const successStyle = LEVEL_STYLES.success;\n let emoji = \"✅\";\n let label = \"SUCCESS\";\n if (successStyle) {\n if (successStyle.emoji) {\n emoji = successStyle.emoji;\n }\n if (successStyle.label) {\n label = successStyle.label;\n }\n }\n const successFormat = format.replace(/ℹ️ INFO/, `${emoji} ${label}`);\n const groupIndent = \" \".repeat(this.groupDepth);\n const finalFormat = groupIndent + successFormat;\n if (additionalArgs.length > 0) {\n console.log(finalFormat, ...styles2, ...additionalArgs);\n } else {\n console.log(finalFormat, ...styles2);\n }\n const metadata = {\n timestamp: formatTimestamp$1(),\n level: \"info\",\n prefix,\n stackInfo: stackInfo ? stackInfo : void 0\n };\n this.handlers.forEach((handler) => {\n try {\n handler.handle(\"info\", message, args, metadata);\n } catch (error2) {\n console.error(\"Log handler failed:\", error2);\n }\n });\n }\n /**\n * Registra información de trace (debugging detallado)\n * \n * @param {...any} args - Datos detallados para debugging\n * \n * @example\n * logger.trace('Entrando en función processData');\n * logger.trace('Stack completo:', new Error().stack);\n * \n * @since 0.3.0\n */\n trace(...args) {\n this.log(\"debug\", ...args);\n if (this.shouldLog(\"debug\")) {\n console.trace(...args);\n }\n }\n /**\n * Registra errores críticos (prioridad más alta)\n * \n * @param {...any} args - Errores críticos del sistema\n * \n * @example\n * logger.critical('Sistema caído - reinicio inmediato requerido');\n * logger.critical('Pérdida de datos detectada');\n * logger.critical('Brecha de seguridad:', securityError);\n * \n * @since 0.3.0\n */\n critical(...args) {\n this.log(\"critical\", ...args);\n }\n // ===== ADVANCED LOGGING FEATURES =====\n /**\n * Muestra datos en formato de tabla\n * \n * @param {any} data - Datos a mostrar (array de objetos o matriz)\n * @param {string[]} columns - Columnas específicas a mostrar (opcional)\n * \n * @example\n * const usuarios = [\n * { id: 1, nombre: 'Juan', edad: 30 },\n * { id: 2, nombre: 'María', edad: 25 }\n * ];\n * logger.table(usuarios);\n * logger.table(usuarios, ['nombre', 'edad']); // Solo estas columnas\n * \n * @since 0.3.0\n */\n table(data, columns) {\n if (!this.shouldLog(\"info\")) return;\n const prefix = this.getEffectivePrefix();\n const tableStyle = StylePresets.accent().build();\n const format = `%c📊 TABLE${prefix ? ` [${prefix}]` : \"\"}`;\n console.log(format, tableStyle);\n if (columns) {\n console.table(data, columns);\n } else {\n console.table(data);\n }\n }\n /**\n * Inicia un grupo colapsable en la consola\n * \n * @param {string} label - Etiqueta del grupo\n * @param {boolean} collapsed - Si el grupo inicia colapsado (default: false)\n * \n * @example\n * logger.group('Procesando usuarios');\n * logger.info('Usuario 1 procesado');\n * logger.info('Usuario 2 procesado');\n * logger.groupEnd();\n * \n * @example\n * // Grupo colapsado por defecto\n * logger.group('Detalles adicionales', true);\n * logger.debug('Información detallada aquí');\n * logger.groupEnd();\n * \n * @since 0.3.0\n */\n group(label, collapsed = false) {\n const groupStyle = new StyleBuilder().bg(\"linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)\").color(\"#1565c0\").border(\"1px solid #90caf9\").padding(\"4px 12px\").rounded(\"6px\").bold().build();\n const format = `%c📁 ${label}`;\n if (collapsed) {\n console.groupCollapsed(format, groupStyle);\n } else {\n console.group(format, groupStyle);\n }\n this.groupDepth++;\n }\n /**\n * Finaliza el grupo actual de la consola\n * \n * @example\n * logger.group('Operaciones');\n * logger.info('Operación 1');\n * logger.info('Operación 2');\n * logger.groupEnd(); // Cierra el grupo\n * \n * @since 0.3.0\n */\n groupEnd() {\n if (this.groupDepth > 0) {\n console.groupEnd();\n this.groupDepth--;\n }\n }\n // ===== PERFORMANCE TIMING =====\n /**\n * Inicia un temporizador con la etiqueta dada\n * \n * @param {string} label - Etiqueta identificadora del temporizador\n * \n * @example\n * logger.time('proceso-datos');\n * // ... operación costosa ...\n * logger.timeEnd('proceso-datos'); // ⏱️ Timer ended: proceso-datos - 1523.45ms\n * \n * @since 0.3.0\n */\n time(label) {\n const timer = {\n label,\n startTime: performance.now()\n };\n this.timers.set(label, timer);\n const timerStyle = StylePresets.warning().build();\n console.log(`%c⏱️ Timer started: ${label}`, timerStyle);\n }\n /**\n * Finaliza un temporizador y muestra el tiempo transcurrido\n * \n * @param {string} label - Etiqueta del temporizador a finalizar\n * \n * @example\n * logger.time('consulta-db');\n * await consultarBaseDatos();\n * logger.timeEnd('consulta-db'); // ⏱️ Timer ended: consulta-db - 234.56ms\n * \n * @since 0.3.0\n */\n timeEnd(label) {\n const timer = this.timers.get(label);\n if (!timer) {\n this.warn(`Timer '${label}' does not exist`);\n return;\n }\n const elapsed = performance.now() - timer.startTime;\n this.timers.delete(label);\n const timerStyle = StylePresets.success().build();\n console.log(`%c⏱️ Timer ended: ${label} - ${elapsed.toFixed(2)}ms`, timerStyle);\n }\n // ===== ADVANCED VISUAL FEATURES =====\n /**\n * Muestra un banner con el tipo especificado o configurado\n * \n * @param {BannerType} bannerType - Tipo de banner (opcional)\n * \n * @example\n * logger.showBanner('ascii'); // Banner ASCII art\n * logger.showBanner('unicode'); // Banner con caracteres Unicode\n * logger.showBanner('svg'); // Banner con gráfico SVG\n * logger.showBanner(); // Usa el tipo configurado\n * \n * @since 0.3.0\n */\n showBanner(bannerType) {\n const effectiveBannerType = bannerType ? bannerType : this.config.bannerType;\n displayInitBanner(effectiveBannerType);\n }\n /**\n * Registra mensaje con imagen SVG de fondo\n * \n * @param {string} message - Mensaje a mostrar\n * @param {string} svgContent - Contenido SVG personalizado (opcional)\n * @param {StyleOptions} options - Opciones de estilo (ancho, alto, padding)\n * \n * @example\n * // SVG automático con gradiente\n * logger.logWithSVG('🎆 Bienvenido a Better Logger');\n * \n * @example\n * // SVG personalizado\n * const customSVG = '<svg>...</svg>';\n * logger.logWithSVG('Logo', customSVG, { width: 400, height: 100 });\n * \n * @since 0.3.0\n */\n logWithSVG(message, svgContent, options = {}) {\n const { width = 300, height = 60, padding = \"30px 150px\" } = options;\n let svgDataUri = \"\";\n if (svgContent) {\n const encodedSVG = encodeURIComponent(svgContent);\n svgDataUri = `data:image/svg+xml,${encodedSVG}`;\n } else {\n const defaultSVG = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${width} ${height}'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='4'/><text x='${width / 2}' y='${height / 2 + 5}' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>${message}</text></svg>`;\n svgDataUri = `data:image/svg+xml,${encodeURIComponent(defaultSVG)}`;\n }\n const svgStyle = new StyleBuilder().bg(`url(\"${svgDataUri}\") no-repeat center center`).padding(padding).color(\"transparent\").rounded(\"4px\").build();\n console.log(`%c${message}`, svgStyle);\n }\n /**\n * Registra mensaje con gradiente animado de fondo\n * \n * @param {string} message - Mensaje a animar\n * @param {number} duration - Duración de la animación en segundos (default: 3)\n * \n * @example\n * logger.logAnimated('🌈 Animación en progreso');\n * logger.logAnimated('Cargando...', 5); // Animación de 5 segundos\n * \n * @since 0.3.0\n */\n logAnimated(message, duration = 3) {\n if (!document.getElementById(\"logger-animations\")) {\n const style = document.createElement(\"style\");\n style.id = \"logger-animations\";\n style.textContent = `\n @keyframes loggerGradient {\n 0% { background-position: 0% 50%; }\n 50% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n `;\n document.head.appendChild(style);\n }\n const animatedStyle = new StyleBuilder().bg(\"linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2)\").css(\"background-size\", \"400% 400%\").color(\"#ffffff\").padding(\"12px 20px\").rounded(\"8px\").bold().font(\"Monaco, Consolas, monospace\").animation(`loggerGradient ${duration}s ease infinite`).display(\"inline-block\").build();\n console.log(`%c${message}`, animatedStyle);\n }\n /**\n * Agrupa logs por una propiedad específica usando Object.groupBy (cuando esté disponible)\n * \n * @param {T[]} items - Array de elementos a agrupar\n * @param {Function} groupBy - Función que retorna la clave de agrupación\n * \n * @example\n * const ventas = [\n * { producto: 'Laptop', categoria: 'Electrónica', precio: 1200 },\n * { producto: 'Mouse', categoria: 'Electrónica', precio: 25 },\n * { producto: 'Libro', categoria: 'Literatura', precio: 15 }\n * ];\n * logger.logGrouped(ventas, item => item.categoria);\n * \n * @since 0.3.0\n */\n logGrouped(items, groupBy) {\n try {\n let grouped;\n if (Object.groupBy) {\n grouped = Object.groupBy(items, groupBy);\n } else {\n grouped = items.reduce((acc, item) => {\n const key = groupBy(item);\n if (!acc[key]) {\n acc[key] = [];\n }\n acc[key].push(item);\n return acc;\n }, {});\n }\n Object.entries(grouped).forEach(([group2, groupItems]) => {\n this.group(`Group: ${group2}`);\n this.table(groupItems);\n this.groupEnd();\n });\n } catch {\n this.info(\"Grouped data:\", items);\n }\n }\n // ===== OUTPUT WRITER SYSTEM =====\n /**\n * Writes formatted output to the configured destination.\n * Respects outputMode configuration for console, silent, or custom output.\n *\n * @private\n * @param {string} message - Formatted log message\n * @param {LogLevel} level - Log level\n * @param {string[]} styles - CSS styles for browser console\n * @param {any[]} additionalArgs - Additional arguments to log\n * @since 4.0.0\n */\n writeOutput(message, level, styles2, additionalArgs) {\n const mode = this.config.outputMode ?? \"console\";\n if (mode === \"silent\") {\n return;\n }\n if (mode === \"custom\" && this.config.outputWriter) {\n const fullMessage = additionalArgs.length > 0 ? `${message} ${additionalArgs.map((a) => String(a)).join(\" \")}` : message;\n this.config.outputWriter.write(fullMessage, level, styles2);\n return;\n }\n if (additionalArgs.length > 0) {\n console.log(message, ...styles2, ...additionalArgs);\n } else {\n console.log(message, ...styles2);\n }\n }\n // ===== CLI SYSTEM =====\n /**\n * Procesador de comandos CLI para configuración y exportación del logger\n * \n * @param {string} command - Comando CLI a ejecutar\n * @returns {Promise<void>}\n * \n * @example\n * // Comandos disponibles\n * await logger.cli('export json'); // Exporta logs en JSON\n * await logger.cli('export csv'); // Exporta logs en CSV\n * await logger.cli('theme list'); // Lista temas disponibles\n * await logger.cli('theme set neon'); // Cambia al tema neon\n * await logger.cli('config show'); // Muestra configuración actual\n * await logger.cli('history clear'); // Limpia historial de logs\n * await logger.cli('status'); // Muestra estado del logger\n * await logger.cli('help'); // Muestra ayuda de comandos\n * \n * @since 0.3.0\n */\n async cli(command) {\n if (!this.cliProcessor) {\n this.error(\"CLI processor not initialized\");\n return;\n }\n await this.cliProcessor.processCommand(command, this);\n }\n}\nlet _defaultLogger = null;\nfunction getDefaultLogger() {\n if (!_defaultLogger) {\n _defaultLogger = new Logger({\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n bufferSize: 1e3\n // Enable export functionality by default\n });\n try {\n displayInitBanner();\n } catch (error2) {\n }\n }\n return _defaultLogger;\n}\ngetDefaultLogger();\nexport {\n APILogger as A,\n BANNER_VARIANTS as B,\n ComponentLogger as C,\n ExportLogHandler as E,\n HookManager as H,\n Logger as L,\n SerializerRegistry as S,\n THEME_PRESETS as T,\n THEME_BANNERS as a,\n TransportManager as b,\n ScopedLogger as c,\n ContextLogger as d,\n formatColumns as e,\n formatWithRightAlign as f,\n formatKeyValue as g,\n formatBadge as h,\n formatTimestamp as i,\n formatRelativeTime as j,\n formatElapsedTime as k,\n isKeyValueObject as l,\n getVisibleLength as m,\n applyLogOptions as n,\n displayInitBanner as o,\n padToWidth as p,\n resetStartTime as r,\n stripAnsi as s\n};\n//# sourceMappingURL=Logger-D-gmmgR2.js.map\n","import { z as supportsANSIColors, f as formatTimestamp } from \"./environment-COWvu6Wz.js\";\nconst ANSI_CODES = {\n // Colors\n black: 30,\n red: 31,\n green: 32,\n yellow: 33,\n blue: 34,\n cyan: 36,\n white: 37,\n // Bright colors\n brightBlack: 90,\n bgRed: 41,\n bgGreen: 42,\n bgYellow: 43,\n // Styles\n reset: 0,\n bold: 1,\n dim: 2,\n underline: 4,\n blink: 5\n};\nconst ANSI_LEVEL_STYLES = {\n debug: {\n color: ANSI_CODES.brightBlack,\n styles: [ANSI_CODES.dim],\n emoji: \"🔍\"\n },\n info: {\n color: ANSI_CODES.blue,\n styles: [ANSI_CODES.bold],\n emoji: \"ℹ️\"\n },\n warn: {\n color: ANSI_CODES.yellow,\n background: ANSI_CODES.bgYellow,\n styles: [ANSI_CODES.bold, ANSI_CODES.black],\n emoji: \"⚠️\"\n },\n error: {\n color: ANSI_CODES.red,\n background: ANSI_CODES.bgRed,\n styles: [ANSI_CODES.bold],\n emoji: \"❌\"\n },\n critical: {\n color: ANSI_CODES.white,\n background: ANSI_CODES.bgRed,\n styles: [ANSI_CODES.bold, ANSI_CODES.blink],\n emoji: \"🚨\"\n },\n success: {\n color: ANSI_CODES.green,\n background: ANSI_CODES.bgGreen,\n styles: [ANSI_CODES.bold],\n emoji: \"✅\"\n }\n};\nfunction ansi(code) {\n const codes = Array.isArray(code) ? code : [code];\n return `\\x1B[${codes.join(\";\")}m`;\n}\nfunction ansiStyle(text, codes) {\n if (!supportsANSIColors()) return text;\n return `${ansi(codes)}${text}${ansi(ANSI_CODES.reset)}`;\n}\nfunction ansiColor(text, color) {\n return ansiStyle(text, [color]);\n}\nfunction ansiBackground(text, bg, color) {\n if (color) {\n return ansiStyle(text, [color, bg]);\n }\n return ansiStyle(text, [bg]);\n}\nfunction ansiBold(text) {\n return ansiStyle(text, [ANSI_CODES.bold]);\n}\nfunction ansiDim(text) {\n return ansiStyle(text, [ANSI_CODES.dim]);\n}\nfunction ansiUnderline(text) {\n return ansiStyle(text, [ANSI_CODES.underline]);\n}\nfunction formatTimestampANSI(timestamp) {\n return ansiColor(timestamp, ANSI_CODES.brightBlack);\n}\nfunction formatLogLevelANSI(level, useEmojis = true) {\n const style = ANSI_LEVEL_STYLES[level];\n const emoji = useEmojis ? style.emoji : \"\";\n const label = level.toUpperCase().padEnd(8);\n if (!supportsANSIColors()) {\n return `${emoji} ${label}`;\n }\n let codes = [style.color, ...style.styles];\n if (style.background) {\n codes.push(style.background);\n }\n return ansiStyle(`${emoji} ${label}`, codes);\n}\nfunction formatSuccessANSI(message, useEmojis = true) {\n const style = ANSI_LEVEL_STYLES.success;\n const emoji = useEmojis ? style.emoji : \"\";\n if (!supportsANSIColors()) {\n return `${emoji} SUCCESS: ${message}`;\n }\n const prefix = ansiStyle(`${emoji} SUCCESS:`, [style.color, ...style.styles]);\n return `${prefix} ${message}`;\n}\nfunction formatPrefixANSI(prefix) {\n if (!supportsANSIColors()) {\n return `[${prefix}]`;\n }\n return ansiStyle(`[${prefix}]`, [ANSI_CODES.cyan, ANSI_CODES.bold]);\n}\nfunction formatLocationANSI(location) {\n if (!supportsANSIColors()) {\n return `(${location})`;\n }\n return ansiColor(`(${location})`, ANSI_CODES.brightBlack);\n}\nconst BUILD_FORMATTERS = {\n /**\n * Format compilation step\n */\n compilation: (step, status = \"starting\") => {\n const stepText = ansiBold(step);\n switch (status) {\n case \"starting\":\n return `${ansiColor(\"⚙️\", ANSI_CODES.blue)} ${stepText}...`;\n case \"completed\":\n return `${ansiColor(\"✓\", ANSI_CODES.green)} ${stepText} ${ansiColor(\"completed\", ANSI_CODES.green)}`;\n case \"failed\":\n return `${ansiColor(\"✗\", ANSI_CODES.red)} ${stepText} ${ansiColor(\"failed\", ANSI_CODES.red)}`;\n default:\n return stepText;\n }\n },\n /**\n * Format warning message\n */\n warning: (message) => {\n return `${ansiColor(\"⚠\", ANSI_CODES.yellow)} ${ansiStyle(\"Warning:\", [ANSI_CODES.yellow, ANSI_CODES.bold])} ${message}`;\n },\n /**\n * Format error message\n */\n error: (message) => {\n return `${ansiColor(\"✗\", ANSI_CODES.red)} ${ansiStyle(\"Error:\", [ANSI_CODES.red, ANSI_CODES.bold])} ${message}`;\n },\n /**\n * Format success message\n */\n success: (message) => {\n return `${ansiColor(\"✓\", ANSI_CODES.green)} ${ansiColor(message, ANSI_CODES.green)}`;\n },\n /**\n * Format info message\n */\n info: (message) => {\n return `${ansiColor(\"ℹ\", ANSI_CODES.blue)} ${message}`;\n }\n};\nconst EMOJI_ALTERNATIVES = {\n \"🔍\": \"[DEBUG]\",\n \"ℹ️\": \"[INFO]\",\n \"⚠️\": \"[WARN]\",\n \"❌\": \"[ERROR]\",\n \"🚨\": \"[CRITICAL]\",\n \"✅\": \"[OK]\",\n \"✓\": \"[OK]\",\n \"✗\": \"[FAIL]\",\n \"⚙️\": \"[BUILD]\",\n \"📦\": \"[PKG]\"\n};\nfunction sanitizeEmojis(text) {\n const isModernTerminal = process.env.TERM && (process.env.TERM.includes(\"xterm\") || process.env.TERM.includes(\"screen\") || process.env.TERM.includes(\"tmux\"));\n const isCI = process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL;\n if (isModernTerminal && !isCI) {\n return text;\n }\n let result = text;\n Object.entries(EMOJI_ALTERNATIVES).forEach(([emoji, alt]) => {\n result = result.replace(new RegExp(emoji, \"g\"), alt);\n });\n return result;\n}\nfunction createOutput(level, message, prefix, stackInfo, format = \"auto\") {\n const detectedFormat = format === \"auto\" ? detectOptimalFormat() : format;\n switch (detectedFormat) {\n case \"ansi\":\n return createANSIOutput(level, message, prefix, stackInfo);\n case \"build\":\n return createBuildOutput(level, message, prefix, stackInfo);\n case \"ci\":\n return createCIOutput(level, message, prefix, stackInfo);\n case \"plain\":\n default:\n return createPlainOutput(level, message, prefix, stackInfo);\n }\n}\nfunction createPlainOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return output;\n}\nfunction createANSIOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = \"\";\n output += formatTimestampANSI(`[${timeStr}]`) + \" \";\n output += formatLogLevelANSI(level) + \" \";\n if (prefix) {\n output += formatPrefixANSI(prefix) + \" \";\n }\n output += message;\n if (stackInfo) {\n output += \" \" + formatLocationANSI(`(${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`);\n }\n return sanitizeEmojis(output);\n}\nfunction createBuildOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = \"\";\n if (supportsANSIColors()) {\n output += formatTimestampANSI(`[${timeStr}]`) + \" \";\n switch (level) {\n case \"info\":\n output += BUILD_FORMATTERS.info(message);\n break;\n case \"warn\":\n output += BUILD_FORMATTERS.warning(message);\n break;\n case \"error\":\n case \"critical\":\n output += BUILD_FORMATTERS.error(message);\n break;\n default:\n output += `${formatLogLevelANSI(level)} ${message}`;\n }\n } else {\n output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n }\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return sanitizeEmojis(output);\n}\nfunction createCIOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return sanitizeEmojis(output);\n}\nfunction detectOptimalFormat() {\n const isCI = process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL || process.env.GITLAB_CI || process.env.TRAVIS || process.env.CIRCLECI;\n process.env.NEXT_RUNTIME || process.argv.some((arg) => arg.includes(\"next\"));\n if (isCI) {\n return \"ci\";\n }\n {\n return \"build\";\n }\n}\nfunction getConsoleMethod(level) {\n switch (level) {\n case \"debug\":\n return \"log\";\n case \"info\":\n return \"info\";\n case \"warn\":\n return \"warn\";\n case \"error\":\n case \"critical\":\n return \"error\";\n default:\n return \"log\";\n }\n}\nfunction createLogEntry(level, message, args, prefix, stackInfo) {\n return {\n timestamp: formatTimestamp(),\n level: level.toUpperCase(),\n prefix,\n message,\n args: args.slice(1),\n // Exclude the first message argument\n location: stackInfo ? {\n file: stackInfo.file,\n line: stackInfo.line,\n column: stackInfo.column,\n function: stackInfo.function\n } : void 0,\n raw: args\n };\n}\nfunction formatTablePlain(data, columns) {\n try {\n if (Array.isArray(data)) {\n if (data.length === 0) return \"[Empty Array]\";\n if (typeof data[0] !== \"object\") {\n return data.map((item, i) => `${i}: ${item}`).join(\"\\n\");\n }\n const keys = columns || Object.keys(data[0] || {});\n const header = keys.join(\"\t\");\n const rows = data.map(\n (item) => keys.map((key) => String(item[key] || \"\")).join(\"\t\")\n );\n return [header, ...rows].join(\"\\n\");\n }\n if (typeof data === \"object\" && data !== null) {\n return Object.entries(data).map(([key, value]) => `${key}: ${value}`).join(\"\\n\");\n }\n return String(data);\n } catch (error) {\n return `[Error formatting table: ${error}]`;\n }\n}\nfunction safeSerialize(obj, maxDepth = 3, currentDepth = 0) {\n if (currentDepth >= maxDepth) {\n return \"[Max Depth Reached]\";\n }\n if (obj === null) return null;\n if (obj === void 0) return \"[undefined]\";\n if (typeof obj === \"function\") return \"[Function]\";\n if (obj instanceof Error) return `[Error: ${obj.message}]`;\n if (obj instanceof Date) return obj.toISOString();\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) {\n return obj.map((item) => safeSerialize(item, maxDepth, currentDepth + 1));\n }\n const result = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = safeSerialize(value, maxDepth, currentDepth + 1);\n }\n return result;\n}\nexport {\n BUILD_FORMATTERS as B,\n createANSIOutput as a,\n createBuildOutput as b,\n createOutput as c,\n detectOptimalFormat as d,\n createCIOutput as e,\n ansiStyle as f,\n ansiColor as g,\n ansiBackground as h,\n ansiBold as i,\n ansiDim as j,\n ansiUnderline as k,\n formatLogLevelANSI as l,\n formatSuccessANSI as m,\n sanitizeEmojis as n,\n getConsoleMethod as o,\n createLogEntry as p,\n formatTablePlain as q,\n createPlainOutput as r,\n safeSerialize as s\n};\n//# sourceMappingURL=formatting-CYjT9yhO.js.map\n","import { L as Logger } from \"./chunks/Logger-D-gmmgR2.js\";\nimport { A, B, C, d, H, c, S, a, T, b, n, h, e, k, g, j, i, f, m, l, p, r, s } from \"./chunks/Logger-D-gmmgR2.js\";\nimport { i as isNode, a as isBrowser, S as StylePresets, b as StyleBuilder } from \"./chunks/environment-COWvu6Wz.js\";\nimport { A as A2, B as B2, D, E, T as T2, e as e2, n as n2, d as d2, f as f2, m as m2, l as l2, k as k2, j as j2, t, o, w, g as g2, v, u, c as c2, h as h2, q, p as p2, r as r2, s as s2 } from \"./chunks/environment-COWvu6Wz.js\";\nimport { s as safeSerialize } from \"./chunks/formatting-CYjT9yhO.js\";\nimport { B as B3, h as h3, i as i2, g as g3, j as j3, f as f3, k as k3, a as a2, b as b2, e as e3, c as c3, d as d3, l as l3, m as m3, n as n3 } from \"./chunks/formatting-CYjT9yhO.js\";\nimport { R } from \"./chunks/RemoteLogHandler-CjWpWZGl.js\";\nclass ConsoleTransport {\n constructor(options) {\n this.options = options;\n }\n name = \"console\";\n write(record) {\n const method = this.getConsoleMethod(record.level);\n const prefix = record.prefix ? `[${record.prefix}] ` : \"\";\n const location = record.location ? ` (${record.location.file}:${record.location.line})` : \"\";\n console[method](`[${record.level.toUpperCase()}]${prefix} ${record.msg}${location}`);\n }\n getConsoleMethod(level) {\n switch (level) {\n case \"debug\":\n return \"log\";\n case \"info\":\n return \"info\";\n case \"warn\":\n return \"warn\";\n case \"error\":\n case \"critical\":\n return \"error\";\n default:\n return \"log\";\n }\n }\n}\nclass FileTransport {\n name = \"file\";\n buffer = [];\n flushTimer;\n options;\n constructor(options) {\n this.options = options || {};\n if (this.options.flushInterval) {\n this.flushTimer = setInterval(() => this.flush(), this.options.flushInterval);\n }\n }\n write(record) {\n const line = JSON.stringify(record) + \"\\n\";\n this.buffer.push(line);\n if (this.buffer.length >= (this.options.batchSize || 100)) {\n this.flush();\n }\n }\n async flush() {\n if (this.buffer.length === 0) return;\n const lines = this.buffer.join(\"\");\n this.buffer = [];\n if (typeof globalThis.process !== \"undefined\" && typeof require === \"function\") {\n try {\n const fs = require(\"fs\");\n const dest = this.options.destination || \"app.log\";\n fs.appendFileSync(dest, lines);\n } catch {\n }\n }\n }\n close() {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n }\n this.flush();\n }\n}\nclass HttpTransport {\n name = \"http\";\n buffer = [];\n flushTimer;\n options;\n constructor(options) {\n this.options = options || {};\n if (this.options.flushInterval) {\n this.flushTimer = setInterval(() => this.flush(), this.options.flushInterval);\n }\n }\n write(record) {\n this.buffer.push(record);\n if (this.buffer.length >= (this.options.batchSize || 50)) {\n this.flush();\n }\n }\n async flush() {\n if (this.buffer.length === 0 || !this.options.url) return;\n const records = [...this.buffer];\n this.buffer = [];\n try {\n await fetch(this.options.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.options.headers\n },\n body: JSON.stringify({ logs: records })\n });\n } catch {\n this.buffer.unshift(...records);\n }\n }\n close() {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n }\n this.flush();\n }\n}\nclass FileLogHandler {\n filename;\n maxSize;\n fs;\n // Node.js fs module\n constructor(filename = \"app.log\", maxSize) {\n this.filename = filename;\n this.maxSize = maxSize;\n if (isNode) {\n try {\n this.fs = require(\"fs\");\n } catch (error2) {\n console.warn(\"FileLogHandler: Unable to load fs module:\", error2);\n }\n }\n }\n handle(level, message, args, metadata) {\n const logEntry = {\n timestamp: metadata.timestamp,\n level: level.toUpperCase(),\n prefix: metadata.prefix,\n message,\n args: args.slice(1).map((arg) => safeSerialize(arg)),\n location: metadata.stackInfo\n };\n const logLine = this.formatLogLine(logEntry);\n if (isNode && this.fs) {\n this.writeToFileNode(logLine);\n } else if (isBrowser) {\n this.writeToFileLocal(logLine);\n } else {\n console.log(`[FILE-LOG] ${logLine}`);\n }\n }\n /**\n * Format log entry as a single line for file storage\n */\n formatLogLine(entry) {\n const parts = [\n entry.timestamp,\n `[${entry.level}]`,\n entry.prefix ? `[${entry.prefix}]` : \"\",\n entry.message\n ].filter(Boolean);\n let line = parts.join(\" \");\n if (entry.args && entry.args.length > 0) {\n line += \" \" + entry.args.map(\n (arg) => typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n ).join(\" \");\n }\n if (entry.location) {\n line += ` (${entry.location.file}:${entry.location.line}:${entry.location.column})`;\n }\n return line;\n }\n /**\n * Write to actual file in Node.js environment\n */\n writeToFileNode(logLine) {\n if (!this.fs) return;\n try {\n if (this.maxSize) {\n try {\n const stats = this.fs.statSync(this.filename);\n if (stats.size > this.maxSize) {\n const backupName = `${this.filename}.bak`;\n this.fs.renameSync(this.filename, backupName);\n }\n } catch (error2) {\n }\n }\n this.fs.appendFileSync(this.filename, logLine + \"\\n\", \"utf8\");\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to write to file:\", error2);\n }\n }\n /**\n * Write to localStorage in browser environment\n */\n writeToFileLocal(logLine) {\n try {\n const storageKey = `logger_${this.filename}`;\n const existingLogs = localStorage.getItem(storageKey) || \"\";\n let newLogs = existingLogs;\n if (existingLogs.length > 0) {\n newLogs += \"\\n\";\n }\n newLogs += logLine;\n if (this.maxSize || newLogs.split(\"\\n\").length > 1e3) {\n const lines = newLogs.split(\"\\n\");\n const maxLines = this.maxSize ? Math.floor(this.maxSize / 100) : 1e3;\n if (lines.length > maxLines) {\n newLogs = lines.slice(-maxLines).join(\"\\n\");\n }\n }\n localStorage.setItem(storageKey, newLogs);\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to write to localStorage:\", error2);\n }\n }\n /**\n * Get stored logs (useful for debugging)\n */\n getLogs() {\n if (isNode && this.fs) {\n try {\n return this.fs.readFileSync(this.filename, \"utf8\");\n } catch (error2) {\n return null;\n }\n } else if (isBrowser) {\n const storageKey = `logger_${this.filename}`;\n return localStorage.getItem(storageKey);\n }\n return null;\n }\n /**\n * Clear stored logs\n */\n clearLogs() {\n if (isNode && this.fs) {\n try {\n this.fs.writeFileSync(this.filename, \"\", \"utf8\");\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to clear file:\", error2);\n }\n } else if (isBrowser) {\n const storageKey = `logger_${this.filename}`;\n localStorage.removeItem(storageKey);\n }\n }\n}\nclass AnalyticsLogHandler {\n handle(level, message, _args, metadata) {\n if (level === \"error\" || level === \"critical\") {\n console.debug(\"Analytics: Error tracked\", {\n level,\n message,\n timestamp: metadata.timestamp\n });\n }\n }\n}\nconst DEFAULT_CONFIG = {\n maxEntries: 100,\n ttl: 5 * 60 * 1e3,\n enabled: true\n};\nclass StyleCache {\n cache = /* @__PURE__ */ new Map();\n config;\n hitCount = 0;\n missCount = 0;\n constructor(config = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n generateKey(key) {\n return `${key.level}:${key.theme}:${key.presetName || \"default\"}:${key.hasPrefix}:${key.hasLocation}`;\n }\n get(key) {\n if (!this.config.enabled) return null;\n const cacheKey = this.generateKey(key);\n const entry = this.cache.get(cacheKey);\n if (!entry) {\n this.missCount++;\n return null;\n }\n if (Date.now() - entry.createdAt > this.config.ttl) {\n this.cache.delete(cacheKey);\n this.missCount++;\n return null;\n }\n entry.hits++;\n this.cache.delete(cacheKey);\n this.cache.set(cacheKey, entry);\n this.hitCount++;\n return entry;\n }\n set(key, format, styles) {\n if (!this.config.enabled) return;\n const cacheKey = this.generateKey(key);\n if (this.cache.size >= this.config.maxEntries) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n this.cache.delete(firstKey);\n }\n }\n this.cache.set(cacheKey, {\n format,\n styles: [...styles],\n createdAt: Date.now(),\n hits: 0\n });\n }\n clear() {\n this.cache.clear();\n this.hitCount = 0;\n this.missCount = 0;\n }\n getStats() {\n const total = this.hitCount + this.missCount;\n return {\n size: this.cache.size,\n maxSize: this.config.maxEntries,\n hitRate: total > 0 ? this.hitCount / total : 0,\n hits: this.hitCount,\n misses: this.missCount\n };\n }\n setEnabled(enabled) {\n this.config.enabled = enabled;\n if (!enabled) {\n this.clear();\n }\n }\n isEnabled() {\n return this.config.enabled;\n }\n}\nlet _styleCache = null;\nfunction getStyleCache() {\n if (!_styleCache) {\n _styleCache = new StyleCache();\n }\n return _styleCache;\n}\nclass BufferWriter {\n buffer = [];\n maxSize;\n /**\n * Creates a new BufferWriter\n * @param maxSize - Maximum number of entries to buffer (default: 1000)\n */\n constructor(maxSize = 1e3) {\n this.maxSize = maxSize;\n }\n /**\n * Writes a log entry to the buffer\n * @param message - Formatted log message\n * @param level - Log level\n * @param styles - CSS styles (for browser console)\n */\n write(message, level, styles) {\n if (this.buffer.length >= this.maxSize) {\n this.buffer.shift();\n }\n this.buffer.push({\n message,\n level,\n styles,\n timestamp: Date.now()\n });\n }\n /**\n * Returns all buffered entries\n * @returns Copy of the buffer array\n */\n getBuffer() {\n return [...this.buffer];\n }\n /**\n * Returns buffered entries filtered by log level\n * @param levels - Log levels to include\n * @returns Filtered buffer entries\n */\n getByLevel(...levels) {\n return this.buffer.filter((entry) => levels.includes(entry.level));\n }\n /**\n * Returns the number of buffered entries\n */\n get size() {\n return this.buffer.length;\n }\n /**\n * Checks if buffer is empty\n */\n get isEmpty() {\n return this.buffer.length === 0;\n }\n /**\n * Clears all buffered entries\n */\n clear() {\n this.buffer = [];\n }\n /**\n * Outputs all buffered entries to console and clears the buffer\n */\n flush() {\n this.buffer.forEach((entry) => {\n if (entry.styles.length > 0) {\n console.log(entry.message, ...entry.styles);\n } else {\n console.log(entry.message);\n }\n });\n this.clear();\n }\n /**\n * Outputs buffered entries to console without clearing\n */\n replay() {\n this.buffer.forEach((entry) => {\n if (entry.styles.length > 0) {\n console.log(entry.message, ...entry.styles);\n } else {\n console.log(entry.message);\n }\n });\n }\n /**\n * Returns all messages as an array of strings\n */\n toArray() {\n return this.buffer.map((entry) => entry.message);\n }\n /**\n * Returns all messages joined as a single string\n * @param separator - String to join messages with (default: newline)\n */\n toString(separator = \"\\n\") {\n return this.toArray().join(separator);\n }\n}\nlet _logger = null;\nfunction getLogger() {\n if (!_logger) {\n _logger = new Logger();\n }\n return _logger;\n}\nconst index = getLogger();\nconst debug = (...args) => getLogger().debug(...args);\nconst info = (...args) => getLogger().info(...args);\nconst warn = (...args) => getLogger().warn(...args);\nconst error = (...args) => getLogger().error(...args);\nconst success = (...args) => getLogger().success(...args);\nconst critical = (...args) => getLogger().critical(...args);\nconst trace = (...args) => getLogger().trace(...args);\nconst table = (data, columns) => getLogger().table(data, columns);\nconst group = (label, collapsed) => getLogger().group(label, collapsed);\nconst groupEnd = () => getLogger().groupEnd();\nconst time = (label) => getLogger().time(label);\nconst timeEnd = (label) => getLogger().timeEnd(label);\nconst setGlobalPrefix = (prefix) => getLogger().setGlobalPrefix(prefix);\nconst scope = (name) => getLogger().scope(name);\nconst component = (name) => getLogger().component(name);\nconst api = (name) => getLogger().api(name);\nconst badges = (badgeList) => getLogger().badges(badgeList);\nconst badge = (badgeName) => getLogger().badge(badgeName);\nconst clearBadges = () => getLogger().clearBadges();\nconst setVerbosity = (level) => getLogger().setVerbosity(level);\nconst addHandler = (handler) => getLogger().addHandler(handler);\nconst setTheme = (theme) => getLogger().setTheme(theme);\nconst setBannerType = (bannerType) => getLogger().setBannerType(bannerType);\nconst showBanner = (bannerType) => getLogger().showBanner(bannerType);\nconst logWithSVG = (message, svgContent, options) => getLogger().logWithSVG(message, svgContent, options);\nconst logAnimated = (message, duration) => getLogger().logAnimated(message, duration);\nconst cli = (command) => getLogger().cli(command);\nconst addSerializer = (type, serializer, priority) => getLogger().addSerializer(type, serializer, priority);\nconst removeSerializer = (type) => getLogger().removeSerializer(type);\nconst on = (event, callback, priority) => getLogger().on(event, callback, priority);\nconst once = (event, callback, priority) => getLogger().once(event, callback, priority);\nconst off = (event, callback) => getLogger().off(event, callback);\nconst use = (middleware, priority) => getLogger().use(middleware, priority);\nconst addTransport = (target) => getLogger().addTransport(target);\nconst removeTransport = (id) => getLogger().removeTransport(id);\nconst flushTransports = () => getLogger().flushTransports();\nconst closeTransports = () => getLogger().closeTransports();\nconst createStyle = () => new StyleBuilder();\nconst stylePresets = {\n success: StylePresets.success().build(),\n error: StylePresets.error().build(),\n warning: StylePresets.warning().build(),\n info: StylePresets.info().build(),\n accent: StylePresets.accent().build()\n};\nexport {\n A2 as ANSI,\n A as APILogger,\n AnalyticsLogHandler,\n B as BANNER_VARIANTS,\n B3 as BUILD_FORMATTERS,\n B2 as BUILD_PRESETS,\n BufferWriter,\n C as ComponentLogger,\n ConsoleTransport,\n d as ContextLogger,\n D as DEFAULT_CONFIG,\n E as ENVIRONMENT_DETECTION,\n FileLogHandler,\n FileTransport,\n H as HookManager,\n HttpTransport,\n Logger,\n R as RemoteLogHandler,\n c as ScopedLogger,\n S as SerializerRegistry,\n StyleBuilder,\n StyleCache,\n StylePresets,\n a as THEME_BANNERS,\n T as THEME_PRESETS,\n T2 as TerminalRenderer,\n b as TransportManager,\n addHandler,\n addSerializer,\n addTransport,\n h3 as ansiBackground,\n i2 as ansiBold,\n g3 as ansiColor,\n j3 as ansiDim,\n f3 as ansiStyle,\n k3 as ansiUnderline,\n api,\n n as applyLogOptions,\n badge,\n badges,\n clearBadges,\n cli,\n closeTransports,\n e2 as colorToHex,\n component,\n a2 as createANSIOutput,\n b2 as createBuildOutput,\n e3 as createCIOutput,\n c3 as createOutput,\n createStyle,\n critical,\n n2 as cssColorToANSI,\n debug,\n index as default,\n d2 as detectEnvironmentPreset,\n d3 as detectOptimalFormat,\n error,\n flushTransports,\n h as formatBadge,\n e as formatColumns,\n k as formatElapsedTime,\n g as formatKeyValue,\n l3 as formatLogLevelANSI,\n j as formatRelativeTime,\n m3 as formatSuccessANSI,\n f2 as formatTimestamp,\n i as formatTimestampExt,\n f as formatWithRightAlign,\n m2 as getANSI256Background,\n l2 as getANSI256Foreground,\n k2 as getANSIBackground,\n j2 as getANSIForeground,\n t as getColorCapability,\n o as getEnvironment,\n w as getEnvironmentInfo,\n g2 as getOptimalConfig,\n getStyleCache,\n v as getTerminalHeight,\n u as getTerminalWidth,\n m as getVisibleLength,\n group,\n groupEnd,\n c2 as hexTo256,\n h2 as hexToRgb,\n info,\n l as isKeyValueObject,\n q as isRunningInTerminal,\n logAnimated,\n logWithSVG,\n off,\n on,\n once,\n p as padToWidth,\n p2 as parseStackTrace,\n removeSerializer,\n removeTransport,\n r as resetStartTime,\n r2 as rgbToHex,\n n3 as sanitizeEmojis,\n scope,\n setBannerType,\n setGlobalPrefix,\n setTheme,\n setVerbosity,\n showBanner,\n s as stripAnsi,\n stylePresets,\n success,\n s2 as supportsANSI,\n table,\n time,\n timeEnd,\n trace,\n use,\n warn\n};\n//# sourceMappingURL=index.js.map\n","/**\n * Configuration management for Coolify MCP server.\n *\n * Simplified config that reads from ~/.config/coolify-mks-cli-mcp/config.json\n * or falls back to environment variables.\n *\n * @module\n */\n\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { ok, err, isOk, type Result } from \"@mks2508/no-throw\";\n\nconst CONFIG_DIR = join(homedir(), \".config\", \"coolify-mks-cli-mcp\");\nconst CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\n/**\n * Coolify configuration structure.\n */\nexport interface ICoolifyConfig {\n /** Coolify instance URL */\n url?: string;\n /** Coolify API token */\n token?: string;\n}\n\n/**\n * Loads Coolify configuration from config file or environment variables.\n *\n * Priority: Config file > Environment variables\n *\n * @returns Result with configuration or error\n *\n * @example\n * ```typescript\n * const result = await loadConfig()\n * if (isOk(result)) {\n * console.log('Coolify URL:', result.value.url)\n * }\n * ```\n */\nexport async function loadConfig(): Promise<Result<ICoolifyConfig, Error>> {\n try {\n if (existsSync(CONFIG_FILE)) {\n const content = await readFile(CONFIG_FILE, \"utf-8\");\n const parsed = JSON.parse(content) as ICoolifyConfig;\n return ok(parsed);\n }\n\n // Fallback to environment variables\n return ok({\n url: process.env.COOLIFY_URL,\n token: process.env.COOLIFY_TOKEN,\n });\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Saves Coolify configuration to file.\n *\n * Creates the config directory if it doesn't exist.\n *\n * @param config - Configuration to save\n * @returns Result indicating success or error\n *\n * @example\n * ```typescript\n * const result = await saveConfig({ url: 'https://coolify.example.com', token: 'xxx' })\n * ```\n */\nexport async function saveConfig(\n config: ICoolifyConfig,\n): Promise<Result<void, Error>> {\n try {\n if (!existsSync(CONFIG_DIR)) {\n await mkdir(CONFIG_DIR, { recursive: true });\n }\n await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));\n return ok(undefined);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Gets the Coolify URL from config or environment.\n *\n * @returns Coolify URL or undefined\n */\nexport async function getCoolifyUrl(): Promise<string | undefined> {\n const result = await loadConfig();\n if (isOk(result)) {\n return result.value.url || process.env.COOLIFY_URL;\n }\n return process.env.COOLIFY_URL;\n}\n\n/**\n * Gets the Coolify token from config or environment.\n *\n * @returns Coolify token or undefined\n */\nexport async function getCoolifyToken(): Promise<string | undefined> {\n const result = await loadConfig();\n if (isOk(result)) {\n return result.value.token || process.env.COOLIFY_TOKEN;\n }\n return process.env.COOLIFY_TOKEN;\n}\n\nexport { CONFIG_DIR, CONFIG_FILE };\n","/**\n * Coolify service for MCP server and CLI.\n *\n * Provides all Coolify API operations for deployment management.\n *\n * @module\n */\n\nimport { ok, err, isErr, type Result } from \"@mks2508/no-throw\";\nimport { component } from \"@mks2508/better-logger\";\nimport { loadConfig, type ICoolifyConfig } from \"./config.js\";\nimport {\n type ICoolifyAppOptions,\n type ICoolifyAppResult,\n type ICoolifyApplication,\n type ICoolifyDatabase,\n type ICoolifyDatabaseBackup,\n type ICoolifyDeleteResult,\n type ICoolifyDeployment,\n type ICoolifyDeployOptions,\n type ICoolifyDeployResult,\n type ICoolifyDestination,\n type ICoolifyEnvironment,\n type ICoolifyLogs,\n type ICoolifyLogsOptions,\n type ICoolifyPrivateKey,\n type ICoolifyProject,\n type ICoolifyServer,\n type ICoolifyServerDomain,\n type ICoolifyServerResource,\n type ICoolifyService as ICoolifyServiceType,\n type ICoolifyTeam,\n type ICoolifyUpdateOptions,\n type ICoolifyVersion,\n type IProgressCallback,\n} from \"./types.js\";\n\nconst log = component(\"CoolifyService\");\n\n/**\n * Coolify API response type.\n */\ninterface ICoolifyApiResponse<T> {\n data?: T;\n error?: string;\n status: number;\n durationMs?: number;\n}\n\n/**\n * Environment variable from Coolify API.\n */\nexport interface ICoolifyEnvVar {\n uuid: string;\n key: string;\n value: string;\n real_value?: string;\n is_buildtime: boolean;\n is_runtime: boolean;\n is_required: boolean;\n}\n\n/**\n * Coolify service for deployment operations.\n *\n * @example\n * ```typescript\n * const coolify = new CoolifyService()\n * const initResult = await coolify.init()\n * if (initResult.isErr()) {\n * console.error(initResult.error.message)\n * return\n * }\n *\n * const deployResult = await coolify.deploy({ uuid: 'app-uuid' })\n * if (deployResult.isOk()) {\n * console.log('Deployment UUID:', deployResult.value.deploymentUuid)\n * }\n * ```\n */\nexport class CoolifyService {\n private baseUrl: string | undefined;\n private token: string | undefined;\n private config: ICoolifyConfig = {};\n\n /**\n * Checks if the service is configured with URL and token.\n *\n * @returns true if both URL and token are set\n */\n isConfigured(): boolean {\n const hasUrl = !!this.baseUrl || !!process.env.COOLIFY_URL;\n const hasToken = !!this.token || !!process.env.COOLIFY_TOKEN;\n return hasUrl && hasToken;\n }\n\n /**\n * Initializes the Coolify service by loading configuration.\n *\n * @returns Result indicating success or error\n */\n async init(): Promise<Result<void, Error>> {\n const configResult = await loadConfig();\n\n if (isErr(configResult)) {\n log.error(\"Failed to load config\");\n return err(configResult.error);\n }\n\n this.config = configResult.value;\n this.baseUrl = this.config.url || process.env.COOLIFY_URL;\n this.token = this.config.token || process.env.COOLIFY_TOKEN;\n\n if (!this.baseUrl) {\n log.error(\"No Coolify URL configured\");\n log.info(\n \"Set COOLIFY_URL environment variable or run: coolify-mcp config set url <url>\",\n );\n return err(\n new Error(\n \"No Coolify URL configured. Set COOLIFY_URL or use config command.\",\n ),\n );\n }\n\n if (!this.token) {\n log.error(\"No Coolify token configured\");\n log.info(\n \"Set COOLIFY_TOKEN environment variable or run: coolify-mcp config set token <token>\",\n );\n return err(\n new Error(\n \"No Coolify token configured. Set COOLIFY_TOKEN or use config command.\",\n ),\n );\n }\n\n log.debug(\"Coolify connection configured\");\n return ok(undefined);\n }\n\n /**\n * Makes a request to the Coolify API.\n *\n * @param endpoint - API endpoint\n * @param options - Fetch options\n * @returns API response with data or error\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<ICoolifyApiResponse<T>> {\n const startTime = Date.now();\n\n if (!this.baseUrl || !this.token) {\n return {\n error: \"Coolify not configured\",\n status: 0,\n durationMs: Date.now() - startTime,\n };\n }\n\n try {\n const baseUrl = this.baseUrl.replace(/\\/+$/, \"\");\n const url = `${baseUrl}/api/v1${endpoint}`;\n\n const response = await fetch(url, {\n ...options,\n headers: {\n Authorization: `Bearer ${this.token}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n ...options.headers,\n },\n });\n\n const text = await response.text();\n const durationMs = Date.now() - startTime;\n let data: T | undefined;\n\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n if (!response.ok) {\n return {\n error: text || `HTTP ${response.status}`,\n status: response.status,\n durationMs,\n };\n }\n }\n\n if (!response.ok) {\n const parsed = data as\n | { message?: string; errors?: Record<string, string[]> }\n | undefined;\n let errorMessage = parsed?.message || `HTTP ${response.status}`;\n // Include validation errors if present (Coolify returns { message, errors: { field: [reasons] } })\n if (parsed?.errors) {\n const details = Object.entries(parsed.errors)\n .map(\n ([field, reasons]) =>\n `${field}: ${Array.isArray(reasons) ? reasons.join(\", \") : String(reasons)}`,\n )\n .join(\"; \");\n errorMessage += ` — ${details}`;\n }\n return { error: errorMessage, status: response.status, durationMs };\n }\n\n return { data, status: response.status, durationMs };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return { error: message, status: 0, durationMs: Date.now() - startTime };\n }\n }\n\n /**\n * Deploys an application.\n *\n * @param options - Deployment options\n * @param onProgress - Optional progress callback (0-100, message, step)\n * @returns Result with deployment info or error\n */\n async deploy(\n options: ICoolifyDeployOptions,\n onProgress?: IProgressCallback,\n ): Promise<Result<ICoolifyDeployResult, Error>> {\n if (!options.uuid && !options.tag) {\n return err(new Error(\"Either uuid or tag is required\"));\n }\n\n const appId = options.uuid?.slice(0, 8) || options.tag || \"unknown\";\n onProgress?.(5, `Preparing deployment for ${appId}...`);\n\n log.info(`Deploying application ${options.uuid || options.tag}`);\n\n onProgress?.(25, \"Validating deployment configuration\");\n onProgress?.(50, \"Triggering build pipeline...\");\n\n // Build query parameters for deploy endpoint\n const params = new URLSearchParams();\n if (options.uuid) params.set(\"uuid\", options.uuid);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.force) params.set(\"force\", \"true\");\n\n const endpoint = `/deploy${params.toString() ? `?${params.toString()}` : \"\"}`;\n\n const result = await this.request<{\n deployments: Array<{\n message: string;\n resource_uuid: string;\n deployment_uuid: string;\n }>;\n }>(endpoint, {\n method: \"GET\",\n });\n\n if (result.error) {\n log.error(`Deployment failed: ${result.error}`);\n return err(new Error(result.error));\n }\n\n // Response is { deployments: [{ message, resource_uuid, deployment_uuid }] }\n const deployments = result.data?.deployments || [];\n if (deployments.length === 0) {\n log.error(\"No deployments started\");\n return err(\n new Error(\"No deployments started - check application configuration\"),\n );\n }\n\n const deployment = deployments[0];\n\n onProgress?.(90, \"Build started on Coolify server\");\n onProgress?.(100, \"Deployment triggered\");\n\n log.success(`Deployment started: ${deployment.deployment_uuid}`);\n return ok({\n success: true,\n deploymentUuid: deployment.deployment_uuid,\n resourceUuid: deployment.resource_uuid,\n });\n }\n\n /**\n * Creates a new application in Coolify.\n *\n * Uses type-specific endpoints for different application types:\n * - /applications/public - Public Git repository\n * - /applications/private-github-app - Private repo with GitHub App\n * - /applications/private-deploy-key - Private repo with deploy key\n * - /applications/dockerfile - Dockerfile-based application\n * - /applications/docker-image - Docker image\n * - /applications/docker-compose - Docker Compose application\n *\n * @param options - Application options\n * @param onProgress - Optional progress callback (0-100, message, step)\n * @returns Result with application UUID or error\n */\n async createApplication(\n options: ICoolifyAppOptions,\n onProgress?: IProgressCallback,\n ): Promise<Result<ICoolifyAppResult, Error>> {\n onProgress?.(5, `Preparing app \"${options.name}\"`);\n\n const appType = options.type || \"public\";\n log.info(`Creating application ${options.name} (type: ${appType})`);\n\n onProgress?.(25, `Validating server ${options.serverUuid.slice(0, 8)}...`);\n onProgress?.(50, \"Sending creation request to Coolify API...\");\n\n // Determine endpoint based on application type\n const endpointMap: Record<string, string> = {\n public: \"/applications/public\",\n \"private-github-app\": \"/applications/private-github-app\",\n \"private-deploy-key\": \"/applications/private-deploy-key\",\n dockerfile: \"/applications/dockerfile\",\n \"docker-image\": \"/applications/docker-image\",\n \"docker-compose\": \"/applications/docker-compose\",\n dockerimage: \"/applications/dockerimage\",\n dockercompose: \"/applications/dockercompose\",\n };\n\n const endpoint = endpointMap[appType] || \"/applications/public\";\n\n // Build request body based on application type\n const body: Record<string, unknown> = {\n name: options.name,\n description: options.description,\n project_uuid: options.projectUuid,\n environment_uuid: options.environmentUuid,\n server_uuid: options.serverUuid,\n };\n\n // Type-specific fields\n if (\n appType === \"public\" ||\n appType === \"private-github-app\" ||\n appType === \"private-deploy-key\"\n ) {\n if (options.githubRepoUrl) {\n // Coolify expects 'user/repo' format, not full URL\n body.git_repository = options.githubRepoUrl\n .replace(/^https?:\\/\\/github\\.com\\//, \"\")\n .replace(/\\.git$/, \"\");\n }\n if (options.githubAppUuid) {\n body.github_app_uuid = options.githubAppUuid;\n }\n body.git_branch = options.branch || \"main\";\n body.build_pack = options.buildPack || \"dockerfile\";\n if (options.portsExposes) {\n body.ports_exposes = options.portsExposes;\n }\n // Dockerfile / Docker Compose configuration\n if (options.dockerfileLocation) {\n body.dockerfile_location = options.dockerfileLocation;\n }\n if (options.dockerComposeLocation) {\n body.docker_compose_location = options.dockerComposeLocation;\n }\n if (options.baseDirectory) {\n body.base_directory = options.baseDirectory;\n }\n } else if (appType === \"docker-image\" && options.dockerImage) {\n body.docker_image = options.dockerImage;\n } else if (appType === \"docker-compose\" && options.dockerCompose) {\n body.docker_compose = options.dockerCompose;\n }\n\n log.debug(`Create application body: ${JSON.stringify(body, null, 2)}`);\n log.debug(`Endpoint: POST ${endpoint}`);\n\n const result = await this.request<{ uuid: string }>(endpoint, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n\n if (result.error) {\n log.error(`Failed to create application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n onProgress?.(100, `Application \"${options.name}\" created`);\n\n log.success(`Application created: ${result.data?.uuid}`);\n return ok({\n success: true,\n uuid: result.data?.uuid,\n });\n }\n\n /**\n * Sets environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @param envVars - Environment variables to set\n * @returns Result indicating success or error\n */\n async setEnvironmentVariables(\n appUuid: string,\n envVars: Record<string, string>,\n ): Promise<Result<void, Error>> {\n log.info(\n `Setting ${Object.keys(envVars).length} environment variables for ${appUuid}`,\n );\n\n // Coolify API: POST to create, PATCH to update existing\n for (const [key, value] of Object.entries(envVars)) {\n const result = await this.request(`/applications/${appUuid}/envs`, {\n method: \"POST\",\n body: JSON.stringify({ key, value, is_preview: false }),\n });\n\n if (result.error && result.error.includes(\"already exists\")) {\n // Var exists — DELETE + re-POST (Coolify PATCH on envs returns 404)\n const listResult = await this.request<\n Array<{ uuid: string; key: string }>\n >(`/applications/${appUuid}/envs`);\n const existing = listResult.data?.find((v) => v.key === key);\n if (existing) {\n await this.request(`/applications/${appUuid}/envs/${existing.uuid}`, {\n method: \"DELETE\",\n });\n const repost = await this.request(`/applications/${appUuid}/envs`, {\n method: \"POST\",\n body: JSON.stringify({ key, value, is_preview: false }),\n });\n if (repost.error) {\n log.error(`Failed to update env var ${key}: ${repost.error}`);\n return err(new Error(`Failed to update ${key}: ${repost.error}`));\n }\n log.debug(`Updated existing env var: ${key}`);\n } else {\n log.error(`Failed to set env var ${key}: ${result.error}`);\n return err(new Error(`Failed to set ${key}: ${result.error}`));\n }\n } else if (result.error) {\n log.error(`Failed to set env var ${key}: ${result.error}`);\n return err(new Error(`Failed to set ${key}: ${result.error}`));\n }\n }\n\n log.success(`${Object.keys(envVars).length} environment variables set`);\n return ok(undefined);\n }\n\n /**\n * Gets environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with environment variables or error\n */\n async getEnvironmentVariables(\n appUuid: string,\n ): Promise<Result<ICoolifyEnvVar[], Error>> {\n log.info(`Getting environment variables for ${appUuid}`);\n\n const result = await this.request<ICoolifyEnvVar[]>(\n `/applications/${appUuid}/envs`,\n );\n\n if (result.error) {\n log.error(`Failed to get env vars: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environment variables retrieved for ${appUuid}`);\n return ok(result.data || []);\n }\n\n /**\n * Sets a single environment variable for an application.\n * Uses PATCH if variable exists, POST if it doesn't.\n *\n * @param appUuid - Application UUID\n * @param key - Variable name\n * @param value - Variable value\n * @param isBuildTime - Whether the variable is available at build time (only for new vars)\n * @returns Result indicating success or error\n */\n async setEnvironmentVariable(\n appUuid: string,\n key: string,\n value: string,\n _isBuildTime: boolean = false,\n ): Promise<Result<void, Error>> {\n log.info(`Setting environment variable ${key} for ${appUuid}`);\n\n // Check if variable already exists\n const existingVars = await this.getEnvironmentVariables(appUuid);\n if (isErr(existingVars)) {\n return err(existingVars.error);\n }\n\n const exists = existingVars.value.some((ev) => ev.key === key);\n\n if (exists) {\n // Use PATCH to update existing variable\n log.debug(`Variable ${key} exists, using PATCH to update`);\n const result = await this.request<{ uuid: string }>(\n `/applications/${appUuid}/envs`,\n {\n method: \"PATCH\",\n body: JSON.stringify({ key, value }),\n },\n );\n\n if (result.error) {\n log.error(`Failed to update env var: ${result.error}`);\n return err(new Error(result.error));\n }\n } else {\n // Use POST to create new variable\n log.debug(`Variable ${key} does not exist, using POST to create`);\n const result = await this.request<{ uuid: string }>(\n `/applications/${appUuid}/envs`,\n {\n method: \"POST\",\n body: JSON.stringify({ key, value }),\n },\n );\n\n if (result.error) {\n log.error(`Failed to create env var: ${result.error}`);\n return err(new Error(result.error));\n }\n }\n\n log.success(`Environment variable ${key} set for ${appUuid}`);\n return ok(undefined);\n }\n\n /**\n * Deletes an environment variable from an application.\n *\n * @param appUuid - Application UUID\n * @param key - Variable name to delete\n * @returns Result indicating success or error\n */\n async deleteEnvironmentVariable(\n appUuid: string,\n key: string,\n ): Promise<Result<void, Error>> {\n log.info(`Deleting environment variable ${key} from ${appUuid}`);\n\n // First get all env vars to find the UUID of the one to delete\n const envVarsResult = await this.getEnvironmentVariables(appUuid);\n if (isErr(envVarsResult)) {\n return err(envVarsResult.error);\n }\n\n const envVar = envVarsResult.value.find((ev) => ev.key === key);\n if (!envVar) {\n log.error(`Environment variable ${key} not found`);\n return err(new Error(`Environment variable ${key} not found`));\n }\n\n const result = await this.request(\n `/applications/${appUuid}/envs/${envVar.uuid}`,\n {\n method: \"DELETE\",\n },\n );\n\n if (result.error) {\n log.error(`Failed to delete env var: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environment variable ${key} deleted from ${appUuid}`);\n return ok(undefined);\n }\n\n /**\n * Gets the status of an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with status or error\n */\n async getApplicationStatus(appUuid: string): Promise<Result<string, Error>> {\n const result = await this.request<{ status: string }>(\n `/applications/${appUuid}`,\n );\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data?.status || \"unknown\");\n }\n\n /**\n * Lists available servers in Coolify.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with servers or error\n */\n async listServers(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyServer[], Error>> {\n let endpoint = \"/servers\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyServer[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server details or error\n */\n async getServer(serverUuid: string): Promise<Result<ICoolifyServer, Error>> {\n log.info(`Getting server details for ${serverUuid}`);\n\n const result = await this.request<ICoolifyServer>(`/servers/${serverUuid}`);\n\n if (result.error) {\n log.error(`Failed to get server: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Server details retrieved: ${serverUuid}`);\n return ok(result.data as ICoolifyServer);\n }\n\n /**\n * Lists all GitHub Apps configured in Coolify.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with GitHub Apps list or error\n */\n async listGithubApps(\n page?: number,\n perPage?: number,\n ): Promise<\n Result<\n Array<{ id: number; uuid: string; name: string; is_public: boolean }>,\n Error\n >\n > {\n let endpoint = \"/github-apps\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result =\n await this.request<\n Array<{ id: number; uuid: string; name: string; is_public: boolean }>\n >(endpoint);\n if (result.error) return err(new Error(result.error));\n return ok(result.data || []);\n }\n\n /**\n * Lists all projects.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with projects list or error\n */\n async listProjects(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyProject[], Error>> {\n let endpoint = \"/projects\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyProject[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Creates a new project.\n *\n * @param name - Project name\n * @param description - Optional project description\n * @returns Result with created project or error\n */\n async createProject(\n name: string,\n description?: string,\n ): Promise<Result<ICoolifyProject, Error>> {\n log.info(`Creating project: ${name}`);\n\n const result = await this.request<ICoolifyProject>(\"/projects\", {\n method: \"POST\",\n body: JSON.stringify({ name, description: description || \"\" }),\n });\n\n if (result.error) {\n log.error(`Failed to create project: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Project created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Gets environments for a project.\n *\n * @param projectUuid - Project UUID\n * @returns Result with environments list or error\n */\n async getProjectEnvironments(\n projectUuid: string,\n ): Promise<Result<ICoolifyEnvironment[], Error>> {\n log.info(`Getting environments for project ${projectUuid}`);\n\n const result = await this.request<{ environments: ICoolifyEnvironment[] }>(\n `/projects/${projectUuid}`,\n );\n\n if (result.error) {\n log.error(`Failed to get environments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environments retrieved for project ${projectUuid}`);\n return ok(result.data?.environments || []);\n }\n\n /**\n * Lists all teams.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with teams list or error\n */\n async listTeams(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyTeam[], Error>> {\n let endpoint = \"/teams\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyTeam[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Gets available destinations for a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with destinations or error\n */\n async getServerDestinations(\n serverUuid: string,\n ): Promise<Result<ICoolifyDestination[], Error>> {\n const result = await this.request<{\n destinations: ICoolifyDestination[];\n }>(`/servers/${serverUuid}`);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data?.destinations || []);\n }\n\n /**\n * Lists all applications.\n *\n * @param teamId - Optional team ID to filter by\n * @param projectId - Optional project ID to filter by\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with applications list or error\n */\n async listApplications(\n teamId?: string,\n projectId?: string,\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyApplication[], Error>> {\n log.info(\"Listing applications\");\n\n let endpoint = \"/applications\";\n const params = new URLSearchParams();\n if (teamId) params.set(\"team_id\", teamId);\n if (projectId) params.set(\"project_id\", projectId);\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyApplication[]>(endpoint);\n\n if (result.error) {\n log.error(`Failed to list applications: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Listed ${result.data?.length || 0} applications`);\n return ok(result.data || []);\n }\n\n /**\n * Deletes an application.\n *\n * @param appUuid - Application UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteApplication(\n appUuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/applications/${appUuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n\n if (result.error) {\n log.error(`Failed to delete application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application deleted: ${appUuid}`);\n return ok({ success: true, message: \"Application deleted\" });\n }\n\n /**\n * Updates an application configuration.\n *\n * @param appUuid - Application UUID\n * @param options - Update options\n * @returns Result with updated application or error\n */\n async updateApplication(\n appUuid: string,\n options: ICoolifyUpdateOptions,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Updating application ${appUuid}`);\n\n const body: Record<string, unknown> = {};\n if (options.name) body.name = options.name;\n if (options.description) body.description = options.description;\n if (options.buildPack) body.build_pack = options.buildPack;\n if (options.gitBranch) body.git_branch = options.gitBranch;\n if (options.portsExposes) body.ports_exposes = options.portsExposes;\n if (options.installCommand) body.install_command = options.installCommand;\n if (options.buildCommand) body.build_command = options.buildCommand;\n if (options.startCommand) body.start_command = options.startCommand;\n if (options.dockerfileLocation)\n body.dockerfile_location = options.dockerfileLocation;\n if (options.baseDirectory) body.base_directory = options.baseDirectory;\n if (options.domains) body.domains = options.domains;\n if (options.dockerComposeDomains)\n body.docker_compose_domains = options.dockerComposeDomains;\n if (options.isForceHttpsEnabled !== undefined)\n body.is_force_https_enabled = options.isForceHttpsEnabled;\n if (options.isAutoDeployEnabled !== undefined)\n body.is_auto_deploy_enabled = options.isAutoDeployEnabled;\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(body),\n },\n );\n\n if (result.error) {\n log.error(`Failed to update application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application updated: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Gets application logs.\n *\n * @param appUuid - Application UUID\n * @param options - Log retrieval options\n * @returns Result with logs or error\n */\n async getApplicationLogs(\n appUuid: string,\n options: ICoolifyLogsOptions = {},\n ): Promise<Result<ICoolifyLogs, Error>> {\n log.info(`Getting logs for application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options.follow) params.set(\"follow\", \"true\");\n if (options.tail) params.set(\"lines\", options.tail.toString());\n if (options.serviceName) params.set(\"service_name\", options.serviceName);\n\n const endpoint = `/applications/${appUuid}/logs${params.toString() ? `?${params.toString()}` : \"\"}`;\n\n const result = await this.request<{ logs: string | string[] }>(endpoint);\n\n if (result.error) {\n log.error(`Failed to get logs: ${result.error}`);\n return err(new Error(result.error));\n }\n\n // Coolify API returns logs as a single newline-delimited string for\n // docker-compose apps, but as string[] for single-container apps.\n const rawLogs = result.data?.logs;\n const logsArray: string[] = Array.isArray(rawLogs)\n ? rawLogs\n : typeof rawLogs === \"string\"\n ? rawLogs.split(\"\\n\").filter((l: string) => l.length > 0)\n : [];\n\n log.success(`Logs retrieved for application: ${appUuid}`);\n return ok({\n logs: logsArray,\n timestamp: new Date().toISOString(),\n });\n }\n\n /**\n * Executes a command on an application's running container.\n *\n * @param appUuid - Application UUID\n * @param command - Shell command to execute\n * @returns Result with command output or error\n */\n async executeCommand(\n appUuid: string,\n command: string,\n ): Promise<Result<{ message?: string; response?: string }, Error>> {\n log.info(`Executing command on application ${appUuid}`);\n\n const result = await this.request<{\n message?: string;\n response?: string;\n }>(`/applications/${appUuid}/execute-command`, {\n method: \"POST\",\n body: JSON.stringify({ command }),\n });\n\n if (result.error) {\n log.error(`Failed to execute command: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Command executed on ${appUuid}`);\n return ok(result.data || { message: \"Command executed\" });\n }\n\n /**\n * Bulk updates environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @param envVars - Array of { key, value, is_preview? } objects\n * @returns Result indicating success or error\n */\n async bulkUpdateEnvironmentVariables(\n appUuid: string,\n envVars: Array<{\n key: string;\n value: string;\n is_preview?: boolean;\n }>,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Bulk updating ${envVars.length} env vars for ${appUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/applications/${appUuid}/envs/bulk`,\n {\n method: \"PATCH\",\n body: JSON.stringify(envVars),\n },\n );\n\n if (result.error) {\n log.error(`Failed to bulk update env vars: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Bulk updated ${envVars.length} env vars for ${appUuid}`);\n return ok(result.data || { message: \"Environment variables updated\" });\n }\n\n /**\n * Gets deployment history for an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with deployment history or error\n */\n async getApplicationDeploymentHistory(\n appUuid: string,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Getting deployment history for ${appUuid}`);\n\n // Coolify API: /deployments/applications/{appUuid}\n // Response: { count: number, deployments: ICoolifyDeployment[] }\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(`/deployments/applications/${appUuid}`);\n\n if (result.error) {\n log.error(`Failed to get deployment history: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment history retrieved for ${appUuid}`);\n return ok(result.data?.deployments || []);\n }\n\n /**\n * Starts a stopped application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @param options - Optional start options (force, instant_deploy)\n * @returns Result with application status or error\n */\n async startApplication(\n appUuid: string,\n options?: { force?: boolean; instantDeploy?: boolean },\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Starting application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options?.force) params.set(\"force\", \"true\");\n if (options?.instantDeploy) params.set(\"instant_deploy\", \"true\");\n const queryString = params.toString();\n const endpoint = `/applications/${appUuid}/start${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyApplication>(endpoint, {\n method: \"GET\",\n });\n\n if (result.error) {\n log.error(`Failed to start application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application started: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Stops a running application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @returns Result with application status or error\n */\n async stopApplication(\n appUuid: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Stopping application ${appUuid}`);\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}/stop`,\n { method: \"GET\" },\n );\n\n if (result.error) {\n log.error(`Failed to stop application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application stopped: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Restarts an application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @returns Result with application status or error\n */\n async restartApplication(\n appUuid: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Restarting application ${appUuid}`);\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}/restart`,\n { method: \"GET\" },\n );\n\n if (result.error) {\n log.error(`Failed to restart application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application restarted: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n\n /**\n * Gets the Coolify server version.\n *\n * @returns Result with version info or error\n */\n async getVersion(): Promise<Result<ICoolifyVersion, Error>> {\n log.info(\"Getting Coolify version\");\n\n // /version returns plain text, not JSON\n if (!this.baseUrl || !this.token) {\n return err(new Error(\"Coolify not configured\"));\n }\n\n try {\n const baseUrl = this.baseUrl.replace(/\\/+$/, \"\");\n const url = `${baseUrl}/api/v1/version`;\n const response = await fetch(url, {\n headers: {\n Authorization: `Bearer ${this.token}`,\n },\n });\n\n if (!response.ok) {\n return err(\n new Error(`HTTP ${response.status}: ${response.statusText}`),\n );\n }\n\n const version = (await response.text()).trim();\n log.success(`Coolify version: ${version}`);\n return ok({ version });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return err(new Error(message));\n }\n }\n\n // ===========================================================================\n // Database endpoints\n // ===========================================================================\n\n /**\n * Lists all databases.\n *\n * @param page - Optional page number\n * @param perPage - Optional items per page\n * @returns Result with databases list or error\n */\n async listDatabases(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyDatabase[], Error>> {\n log.info(\"Listing databases\");\n\n let endpoint = \"/databases\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) endpoint += `?${params.toString()}`;\n\n const result = await this.request<ICoolifyDatabase[]>(endpoint);\n if (result.error) return err(new Error(result.error));\n\n log.success(`Listed ${result.data?.length || 0} databases`);\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific database.\n *\n * @param uuid - Database UUID\n * @returns Result with database details or error\n */\n async getDatabase(uuid: string): Promise<Result<ICoolifyDatabase, Error>> {\n log.info(`Getting database ${uuid}`);\n\n const result = await this.request<ICoolifyDatabase>(`/databases/${uuid}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyDatabase);\n }\n\n /**\n * Creates a database of the specified type.\n *\n * @param dbType - Database type (postgresql, mysql, mariadb, mongodb, redis, keydb, clickhouse, dragonfly)\n * @param data - Database creation data\n * @returns Result with created database UUID or error\n */\n async createDatabase(\n dbType: string,\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(`Creating ${dbType} database`);\n\n const result = await this.request<{ uuid: string }>(\n `/databases/${dbType}`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a database configuration.\n *\n * @param uuid - Database UUID\n * @param data - Update data\n * @returns Result with updated database or error\n */\n async updateDatabase(\n uuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyDatabase, Error>> {\n log.info(`Updating database ${uuid}`);\n\n const result = await this.request<ICoolifyDatabase>(`/databases/${uuid}`, {\n method: \"PATCH\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database updated: ${uuid}`);\n return ok(result.data as ICoolifyDatabase);\n }\n\n /**\n * Deletes a database.\n *\n * @param uuid - Database UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteDatabase(\n uuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting database ${uuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/databases/${uuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database deleted: ${uuid}`);\n return ok({ success: true, message: \"Database deleted\" });\n }\n\n /**\n * Starts a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async startDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Starting database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/start`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database started: ${uuid}`);\n return ok(result.data || { message: \"Database started\" });\n }\n\n /**\n * Stops a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async stopDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Stopping database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/stop`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database stopped: ${uuid}`);\n return ok(result.data || { message: \"Database stopped\" });\n }\n\n /**\n * Restarts a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async restartDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Restarting database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/restart`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database restarted: ${uuid}`);\n return ok(result.data || { message: \"Database restarted\" });\n }\n\n // ===========================================================================\n // Database Backup endpoints\n // ===========================================================================\n\n /**\n * Lists backups for a database.\n *\n * @param databaseUuid - Database UUID\n * @returns Result with backups list or error\n */\n async listDatabaseBackups(\n databaseUuid: string,\n ): Promise<Result<ICoolifyDatabaseBackup[], Error>> {\n log.info(`Listing backups for database ${databaseUuid}`);\n\n const result = await this.request<ICoolifyDatabaseBackup[]>(\n `/databases/${databaseUuid}/backups`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets a specific database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @returns Result with backup details or error\n */\n async getDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n ): Promise<Result<ICoolifyDatabaseBackup, Error>> {\n const result = await this.request<ICoolifyDatabaseBackup>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyDatabaseBackup);\n }\n\n /**\n * Creates a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param data - Backup creation data\n * @returns Result with created backup or error\n */\n async createDatabaseBackup(\n databaseUuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyDatabaseBackup, Error>> {\n log.info(`Creating backup for database ${databaseUuid}`);\n\n const result = await this.request<ICoolifyDatabaseBackup>(\n `/databases/${databaseUuid}/backups`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(\"Database backup created\");\n return ok(result.data as ICoolifyDatabaseBackup);\n }\n\n /**\n * Updates a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @param data - Update data\n * @returns Result indicating success or error\n */\n async updateDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Backup updated\" });\n }\n\n /**\n * Deletes a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @returns Result indicating success or error\n */\n async deleteDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Backup deleted\" });\n }\n\n // ===========================================================================\n // Service endpoints\n // ===========================================================================\n\n /**\n * Lists all services.\n *\n * @param page - Optional page number\n * @param perPage - Optional items per page\n * @returns Result with services list or error\n */\n async listServices(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyServiceType[], Error>> {\n log.info(\"Listing services\");\n\n let endpoint = \"/services\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) endpoint += `?${params.toString()}`;\n\n const result = await this.request<ICoolifyServiceType[]>(endpoint);\n if (result.error) return err(new Error(result.error));\n\n log.success(`Listed ${result.data?.length || 0} services`);\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific service.\n *\n * @param uuid - Service UUID\n * @returns Result with service details or error\n */\n async getService(uuid: string): Promise<Result<ICoolifyServiceType, Error>> {\n log.info(`Getting service ${uuid}`);\n\n const result = await this.request<ICoolifyServiceType>(`/services/${uuid}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyServiceType);\n }\n\n /**\n * Creates a new service.\n *\n * @param data - Service creation data\n * @returns Result with created service or error\n */\n async createService(\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating service\");\n\n const result = await this.request<{ uuid: string }>(\"/services\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a service configuration.\n *\n * @param uuid - Service UUID\n * @param data - Update data\n * @returns Result with updated service or error\n */\n async updateService(\n uuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyServiceType, Error>> {\n log.info(`Updating service ${uuid}`);\n\n const result = await this.request<ICoolifyServiceType>(\n `/services/${uuid}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(data),\n },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service updated: ${uuid}`);\n return ok(result.data as ICoolifyServiceType);\n }\n\n /**\n * Deletes a service.\n *\n * @param uuid - Service UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteService(\n uuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting service ${uuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/services/${uuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service deleted: ${uuid}`);\n return ok({ success: true, message: \"Service deleted\" });\n }\n\n /**\n * Starts a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async startService(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Starting service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/start`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service started: ${uuid}`);\n return ok(result.data || { message: \"Service started\" });\n }\n\n /**\n * Stops a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async stopService(uuid: string): Promise<Result<{ message: string }, Error>> {\n log.info(`Stopping service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/stop`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service stopped: ${uuid}`);\n return ok(result.data || { message: \"Service stopped\" });\n }\n\n /**\n * Restarts a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async restartService(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Restarting service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/restart`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service restarted: ${uuid}`);\n return ok(result.data || { message: \"Service restarted\" });\n }\n\n /**\n * Lists environment variables for a service.\n *\n * @param uuid - Service UUID\n * @returns Result with env vars list or error\n */\n async listServiceEnvVars(\n uuid: string,\n ): Promise<Result<ICoolifyEnvVar[], Error>> {\n const result = await this.request<ICoolifyEnvVar[]>(\n `/services/${uuid}/envs`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Creates an environment variable for a service.\n *\n * @param uuid - Service UUID\n * @param data - Env var data (key, value, is_preview)\n * @returns Result with created env var UUID or error\n */\n async createServiceEnvVar(\n uuid: string,\n data: { key: string; value: string; is_preview?: boolean },\n ): Promise<Result<{ uuid: string }, Error>> {\n const result = await this.request<{ uuid: string }>(\n `/services/${uuid}/envs`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data!);\n }\n\n // ===========================================================================\n // Additional Server endpoints\n // ===========================================================================\n\n /**\n * Gets resources deployed on a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server resources or error\n */\n async getServerResources(\n serverUuid: string,\n ): Promise<Result<ICoolifyServerResource[], Error>> {\n log.info(`Getting resources for server ${serverUuid}`);\n\n const result = await this.request<ICoolifyServerResource[]>(\n `/servers/${serverUuid}/resources`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets domains configured on a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server domains or error\n */\n async getServerDomains(\n serverUuid: string,\n ): Promise<Result<ICoolifyServerDomain[], Error>> {\n log.info(`Getting domains for server ${serverUuid}`);\n\n const result = await this.request<ICoolifyServerDomain[]>(\n `/servers/${serverUuid}/domains`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Validates a server connection.\n *\n * @param serverUuid - Server UUID\n * @returns Result with validation status or error\n */\n async validateServer(\n serverUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Validating server ${serverUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/servers/${serverUuid}/validate`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Server validated\" });\n }\n\n /**\n * Creates a new server.\n *\n * @param data - Server creation data\n * @returns Result with created server UUID or error\n */\n async createServer(\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating server\");\n\n const result = await this.request<{ uuid: string }>(\"/servers\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Server created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Deletes a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result indicating success or error\n */\n async deleteServer(\n serverUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting server ${serverUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/servers/${serverUuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Server deleted: ${serverUuid}`);\n return ok(result.data || { message: \"Server deleted\" });\n }\n\n // ===========================================================================\n // Additional Project endpoints\n // ===========================================================================\n\n /**\n * Updates a project.\n *\n * @param uuid - Project UUID\n * @param data - Update data (name, description)\n * @returns Result with updated project or error\n */\n async updateProject(\n uuid: string,\n data: { name?: string; description?: string },\n ): Promise<Result<ICoolifyProject, Error>> {\n log.info(`Updating project ${uuid}`);\n\n const result = await this.request<ICoolifyProject>(`/projects/${uuid}`, {\n method: \"PATCH\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Project updated: ${uuid}`);\n return ok(result.data as ICoolifyProject);\n }\n\n /**\n * Deletes a project.\n *\n * @param uuid - Project UUID\n * @returns Result indicating success or error\n */\n async deleteProject(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting project ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/projects/${uuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Project deleted: ${uuid}`);\n return ok(result.data || { message: \"Project deleted\" });\n }\n\n /**\n * Creates a new environment within a project.\n *\n * @param projectUuid - Project UUID\n * @param data - Environment creation data (name, description)\n * @returns Result with created environment UUID or error\n */\n async createProjectEnvironment(\n projectUuid: string,\n data: { name: string; description?: string },\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(`Creating environment in project ${projectUuid}`);\n\n const result = await this.request<{ uuid: string }>(\n `/projects/${projectUuid}/environments`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(\"Environment created\");\n return ok(result.data!);\n }\n\n // ===========================================================================\n // Additional Team endpoints\n // ===========================================================================\n\n /**\n * Gets the current team.\n *\n * @returns Result with current team or error\n */\n async getCurrentTeam(): Promise<Result<ICoolifyTeam, Error>> {\n log.info(\"Getting current team\");\n\n const result = await this.request<ICoolifyTeam>(\"/teams/current\");\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyTeam);\n }\n\n /**\n * Gets a specific team by ID.\n *\n * @param id - Team ID\n * @returns Result with team details or error\n */\n async getTeam(id: number): Promise<Result<ICoolifyTeam, Error>> {\n log.info(`Getting team ${id}`);\n\n const result = await this.request<ICoolifyTeam>(`/teams/${id}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyTeam);\n }\n\n /**\n * Gets members of a specific team.\n *\n * @param id - Team ID\n * @returns Result with team members or error\n */\n async getTeamMembers(\n id: number,\n ): Promise<\n Result<Array<{ id: number; name: string; email: string }>, Error>\n > {\n log.info(`Getting members for team ${id}`);\n\n const result = await this.request<\n Array<{ id: number; name: string; email: string }>\n >(`/teams/${id}/members`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n // ===========================================================================\n // Deployment Control\n // ===========================================================================\n\n /**\n * Cancels a deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result indicating success or error\n */\n async cancelDeployment(\n deploymentUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Cancelling deployment ${deploymentUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/deployments/${deploymentUuid}/cancel`,\n { method: \"POST\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Deployment cancelled: ${deploymentUuid}`);\n return ok(result.data || { message: \"Deployment cancelled\" });\n }\n\n // ===========================================================================\n // SSH / Private Key endpoints\n // ===========================================================================\n\n /**\n * Lists all private keys.\n *\n * @returns Result with private keys list or error\n */\n async listPrivateKeys(): Promise<Result<ICoolifyPrivateKey[], Error>> {\n log.info(\"Listing private keys\");\n\n const result = await this.request<ICoolifyPrivateKey[]>(\"/security/keys\");\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets a specific private key.\n *\n * @param uuid - Private key UUID\n * @returns Result with private key details or error\n */\n async getPrivateKey(\n uuid: string,\n ): Promise<Result<ICoolifyPrivateKey, Error>> {\n const result = await this.request<ICoolifyPrivateKey>(\n `/security/keys/${uuid}`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyPrivateKey);\n }\n\n /**\n * Creates a new private key.\n *\n * @param data - Key creation data (name, private_key, description)\n * @returns Result with created key UUID or error\n */\n async createPrivateKey(data: {\n name: string;\n private_key: string;\n description?: string;\n }): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating private key\");\n\n const result = await this.request<{ uuid: string }>(\"/security/keys\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Private key created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a private key.\n *\n * @param uuid - Private key UUID\n * @param data - Update data\n * @returns Result with updated key or error\n */\n async updatePrivateKey(\n uuid: string,\n data: { name?: string; private_key?: string; description?: string },\n ): Promise<Result<ICoolifyPrivateKey, Error>> {\n const result = await this.request<ICoolifyPrivateKey>(\n `/security/keys/${uuid}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyPrivateKey);\n }\n\n /**\n * Deletes a private key.\n *\n * @param uuid - Private key UUID\n * @returns Result indicating success or error\n */\n async deletePrivateKey(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting private key ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/security/keys/${uuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Private key deleted: ${uuid}`);\n return ok(result.data || { message: \"Private key deleted\" });\n }\n\n // ===========================================================================\n // GitHub App endpoints (additional)\n // ===========================================================================\n\n /**\n * Creates a GitHub App configuration.\n *\n * @param data - GitHub App creation data\n * @returns Result with created app or error\n */\n async createGitHubApp(\n data: Record<string, unknown>,\n ): Promise<Result<{ id: number; uuid: string }, Error>> {\n log.info(\"Creating GitHub App\");\n\n const result = await this.request<{ id: number; uuid: string }>(\n \"/github-apps\",\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data!);\n }\n\n /**\n * Updates a GitHub App configuration.\n *\n * @param id - GitHub App ID\n * @param data - Update data\n * @returns Result with updated app or error\n */\n async updateGitHubApp(\n id: number,\n data: Record<string, unknown>,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/github-apps/${id}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"GitHub App updated\" });\n }\n\n /**\n * Deletes a GitHub App configuration.\n *\n * @param id - GitHub App ID\n * @returns Result indicating success or error\n */\n async deleteGitHubApp(\n id: number,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting GitHub App ${id}`);\n\n const result = await this.request<{ message: string }>(\n `/github-apps/${id}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"GitHub App deleted\" });\n }\n\n /**\n * Lists all active and queued deployments.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with deployments list or error\n */\n async listDeployments(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(\"Listing active deployments\");\n\n let endpoint = \"/deployments\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyDeployment[]>(endpoint);\n\n if (result.error) {\n log.error(`Failed to list deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Listed ${result.data?.length || 0} active deployments`);\n return ok(result.data || []);\n }\n\n /**\n * Gets detailed information about a specific deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result with deployment details or error\n */\n async getDeployment(\n deploymentUuid: string,\n ): Promise<Result<ICoolifyDeployment, Error>> {\n log.info(`Getting deployment details for ${deploymentUuid}`);\n\n const result = await this.request<ICoolifyDeployment>(\n `/deployments/${deploymentUuid}`,\n );\n\n if (result.error) {\n log.error(`Failed to get deployment: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment details retrieved: ${deploymentUuid}`);\n return ok(result.data as ICoolifyDeployment);\n }\n\n /**\n * Gets logs for a specific deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result with deployment status and logs or error\n */\n async getDeploymentLogs(\n deploymentUuid: string,\n ): Promise<\n Result<{ status: string; logs: string; deployment_uuid: string }, Error>\n > {\n log.info(`Getting deployment logs for ${deploymentUuid}`);\n\n const result = await this.request<{\n status: string;\n logs: string;\n deployment_uuid: string;\n }>(`/deployments/${deploymentUuid}`);\n\n if (result.error) {\n log.error(`Failed to get deployment logs: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment logs retrieved: ${deploymentUuid}`);\n return ok({\n status: result.data?.status || \"unknown\",\n logs: result.data?.logs || \"\",\n deployment_uuid: result.data?.deployment_uuid || deploymentUuid,\n });\n }\n\n /**\n * Gets deployment history for a specific application.\n *\n * @param appUuid - Application UUID\n * @param skip - Number of deployments to skip\n * @param take - Number of deployments to return\n * @returns Result with deployments list or error\n */\n async getApplicationDeployments(\n appUuid: string,\n skip: number = 0,\n take: number = 10,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Getting deployments for application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (skip > 0) params.set(\"skip\", skip.toString());\n if (take !== 10) params.set(\"take\", take.toString());\n\n const endpoint = `/applications/${appUuid}/deployments${params.toString() ? `?${params.toString()}` : \"\"}`;\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(endpoint);\n\n if (result.error) {\n log.error(`Failed to get application deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n const deployments = result.data?.deployments || [];\n log.success(`Retrieved ${deployments.length} deployments for ${appUuid}`);\n return ok(deployments);\n }\n\n /**\n * Lists deployments for a specific application.\n *\n * Uses the /deployments/applications/{appUuid} endpoint which returns\n * all deployments (active, queued, and completed) for a single application.\n * This differs from listDeployments() which returns ALL deployments globally.\n *\n * @param appUuid - Application UUID\n * @returns Result with deployments list or error\n */\n async listApplicationDeployments(\n appUuid: string,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Listing deployments for application ${appUuid}`);\n\n // API returns { count: number, deployments: ICoolifyDeployment[] }\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(`/deployments/applications/${appUuid}`);\n\n if (result.error) {\n log.error(`Failed to list application deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n const deployments = result.data?.deployments || [];\n log.success(`Listed ${deployments.length} deployments for ${appUuid}`);\n return ok(deployments);\n }\n\n // ===========================================================================\n // Smart Resolution Helpers\n // ===========================================================================\n\n /**\n * Resolves an application by UUID, name, or domain (FQDN).\n *\n * @param query - UUID, name, or domain to search for\n * @returns Result with application or error\n */\n async resolveApplication(\n query: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Resolving application: ${query}`);\n\n // If it looks like a UUID, try direct lookup first\n if (this.isLikelyUuid(query)) {\n const apps = await this.listApplications();\n if (isErr(apps)) return err(apps.error);\n const match = apps.value.find((a) => a.uuid === query);\n if (match) return ok(match);\n }\n\n // Search by name or domain\n const apps = await this.listApplications();\n if (isErr(apps)) return err(apps.error);\n\n const lowerQuery = query.toLowerCase();\n const matches = apps.value.filter(\n (a) =>\n a.name?.toLowerCase() === lowerQuery ||\n a.fqdn?.toLowerCase().includes(lowerQuery) ||\n a.uuid.startsWith(query),\n );\n\n if (matches.length === 1) return ok(matches[0]);\n if (matches.length === 0) {\n return err(\n new Error(\n `No application found matching \"${query}\". Use 'list' to see available applications.`,\n ),\n );\n }\n\n const names = matches.map((a) => ` - ${a.name} (${a.uuid})`).join(\"\\n\");\n return err(\n new Error(\n `Multiple applications match \"${query}\":\\n${names}\\nPlease use the full UUID.`,\n ),\n );\n }\n\n /**\n * Resolves a server by UUID, name, or IP address.\n *\n * @param query - UUID, name, or IP to search for\n * @returns Result with server or error\n */\n async resolveServer(query: string): Promise<Result<ICoolifyServer, Error>> {\n log.info(`Resolving server: ${query}`);\n\n const servers = await this.listServers();\n if (isErr(servers)) return err(servers.error);\n\n const lowerQuery = query.toLowerCase();\n const match = servers.value.find(\n (s) =>\n s.uuid === query ||\n s.name?.toLowerCase() === lowerQuery ||\n s.ip === query ||\n s.uuid.startsWith(query),\n );\n\n if (match) return ok(match);\n return err(\n new Error(\n `No server found matching \"${query}\". Use 'servers' to see available servers.`,\n ),\n );\n }\n\n /**\n * Checks if a string looks like a UUID (Coolify or standard format).\n *\n * @param query - String to check\n * @returns true if it looks like a UUID\n */\n private isLikelyUuid(query: string): boolean {\n if (/^[a-z0-9]{20,}$/i.test(query)) return true;\n if (\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(\n query,\n )\n )\n return true;\n return false;\n }\n\n // ===========================================================================\n // Diagnostics\n // ===========================================================================\n\n /**\n * Diagnoses an application by aggregating health, logs, deployments, and env vars.\n *\n * @param query - Application UUID, name, or domain\n * @returns Result with diagnostic report or error\n */\n async diagnoseApplication(query: string): Promise<\n Result<\n {\n application: ICoolifyApplication;\n recentDeployments: ICoolifyDeployment[];\n envVarCount: number;\n recentLogs: string[];\n issues: string[];\n },\n Error\n >\n > {\n log.info(`Diagnosing application: ${query}`);\n\n const appResult = await this.resolveApplication(query);\n if (isErr(appResult)) return err(appResult.error);\n\n const app = appResult.value;\n const issues: string[] = [];\n\n // Gather data in parallel\n const [deploymentsResult, envResult, logsResult] = await Promise.all([\n this.getApplicationDeploymentHistory(app.uuid),\n this.getEnvironmentVariables(app.uuid),\n this.getApplicationLogs(app.uuid, { tail: 20 }),\n ]);\n\n const deployments = isErr(deploymentsResult) ? [] : deploymentsResult.value;\n const envVarCount = isErr(envResult) ? 0 : envResult.value.length;\n const recentLogs = isErr(logsResult) ? [] : logsResult.value.logs;\n\n // Check for issues\n if (app.status?.includes(\"stopped\")) {\n issues.push(\"Application is stopped\");\n }\n if (!app.fqdn) {\n issues.push(\"No domain configured\");\n }\n if (envVarCount === 0) {\n issues.push(\"No environment variables set\");\n }\n\n const recentDeploys = deployments.slice(-5);\n const failedDeploys = recentDeploys.filter((d) =>\n d.status?.includes(\"failed\"),\n );\n if (failedDeploys.length > 0) {\n issues.push(\n `${failedDeploys.length} of last ${recentDeploys.length} deployments failed`,\n );\n }\n\n log.success(`Diagnosis complete for ${app.name}`);\n return ok({\n application: app,\n recentDeployments: recentDeploys,\n envVarCount,\n recentLogs,\n issues,\n });\n }\n\n /**\n * Diagnoses a server by aggregating health, resources, and domains.\n *\n * @param query - Server UUID, name, or IP\n * @returns Result with diagnostic report or error\n */\n async diagnoseServer(query: string): Promise<\n Result<\n {\n server: ICoolifyServer;\n resources: ICoolifyServerResource[];\n domains: ICoolifyServerDomain[];\n issues: string[];\n },\n Error\n >\n > {\n log.info(`Diagnosing server: ${query}`);\n\n const serverResult = await this.resolveServer(query);\n if (isErr(serverResult)) return err(serverResult.error);\n\n const server = serverResult.value;\n const issues: string[] = [];\n\n const [resourcesResult, domainsResult] = await Promise.all([\n this.getServerResources(server.uuid),\n this.getServerDomains(server.uuid),\n ]);\n\n const resources = isErr(resourcesResult) ? [] : resourcesResult.value;\n const domains = isErr(domainsResult) ? [] : domainsResult.value;\n\n if (!server.is_reachable) {\n issues.push(\"Server is not reachable\");\n }\n if (!server.is_usable) {\n issues.push(\"Server is not usable\");\n }\n if (resources.length === 0) {\n issues.push(\"No resources deployed on this server\");\n }\n\n log.success(`Server diagnosis complete for ${server.name}`);\n return ok({ server, resources, domains, issues });\n }\n\n /**\n * Scans all infrastructure for potential issues.\n *\n * @returns Result with issues report or error\n */\n async findInfrastructureIssues(): Promise<\n Result<\n {\n totalServers: number;\n totalApps: number;\n totalDatabases: number;\n totalServices: number;\n issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }>;\n },\n Error\n >\n > {\n log.info(\"Scanning infrastructure for issues\");\n\n const [serversR, appsR, dbsR, svcsR] = await Promise.all([\n this.listServers(),\n this.listApplications(),\n this.listDatabases(),\n this.listServices(),\n ]);\n\n const servers = isErr(serversR) ? [] : serversR.value;\n const apps = isErr(appsR) ? [] : appsR.value;\n const dbs = isErr(dbsR) ? [] : dbsR.value;\n const svcs = isErr(svcsR) ? [] : svcsR.value;\n\n const issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }> = [];\n\n for (const server of servers) {\n if (!server.is_reachable) {\n issues.push({\n type: \"server\",\n resource: server.name,\n uuid: server.uuid,\n message: \"Server unreachable\",\n });\n }\n }\n\n for (const app of apps) {\n if (app.status?.includes(\"stopped\")) {\n issues.push({\n type: \"application\",\n resource: app.name,\n uuid: app.uuid,\n message: \"Application stopped\",\n });\n }\n if (app.status?.includes(\"failed\") || app.status?.includes(\"error\")) {\n issues.push({\n type: \"application\",\n resource: app.name,\n uuid: app.uuid,\n message: `Status: ${app.status}`,\n });\n }\n }\n\n for (const db of dbs) {\n if (db.status?.includes(\"stopped\") || db.status?.includes(\"exited\")) {\n issues.push({\n type: \"database\",\n resource: db.name,\n uuid: db.uuid,\n message: `Database stopped: ${db.status}`,\n });\n }\n }\n\n for (const svc of svcs) {\n if (svc.status?.includes(\"stopped\") || svc.status?.includes(\"exited\")) {\n issues.push({\n type: \"service\",\n resource: svc.name,\n uuid: svc.uuid,\n message: `Service stopped: ${svc.status}`,\n });\n }\n }\n\n log.success(\n `Infrastructure scan complete: ${issues.length} issue(s) found`,\n );\n return ok({\n totalServers: servers.length,\n totalApps: apps.length,\n totalDatabases: dbs.length,\n totalServices: svcs.length,\n issues,\n });\n }\n\n // ===========================================================================\n // Batch Operations\n // ===========================================================================\n\n /**\n * Restarts all applications in a project.\n *\n * @param projectUuid - Project UUID\n * @returns Result with batch operation results\n */\n async restartProjectApps(\n projectUuid: string,\n ): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(`Restarting all apps in project ${projectUuid}`);\n\n const appsResult = await this.listApplications(undefined, projectUuid);\n if (isErr(appsResult)) return err(appsResult.error);\n\n const apps = appsResult.value;\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of apps) {\n const result = await this.restartApplication(app.uuid);\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Restarted ${succeeded}/${apps.length} apps in project`);\n return ok({ total: apps.length, succeeded, failed });\n }\n\n /**\n * Redeploys all applications in a project.\n *\n * @param projectUuid - Project UUID\n * @param force - Force rebuild\n * @returns Result with batch operation results\n */\n async redeployProjectApps(\n projectUuid: string,\n force: boolean = false,\n ): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(`Redeploying all apps in project ${projectUuid}`);\n\n const appsResult = await this.listApplications(undefined, projectUuid);\n if (isErr(appsResult)) return err(appsResult.error);\n\n const apps = appsResult.value;\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of apps) {\n const result = await this.deploy({ uuid: app.uuid, force });\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Redeployed ${succeeded}/${apps.length} apps in project`);\n return ok({ total: apps.length, succeeded, failed });\n }\n\n /**\n * Stops all running applications.\n *\n * @returns Result with batch operation results\n */\n async stopAllApps(): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(\"Stopping all applications\");\n\n const appsResult = await this.listApplications();\n if (isErr(appsResult)) return err(appsResult.error);\n\n const running = appsResult.value.filter(\n (a) => !a.status?.includes(\"stopped\"),\n );\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of running) {\n const result = await this.stopApplication(app.uuid);\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Stopped ${succeeded}/${running.length} apps`);\n return ok({ total: running.length, succeeded, failed });\n }\n\n // ===========================================================================\n // Summary Types (Token Optimization for MCP)\n // ===========================================================================\n\n /**\n * Lists applications with minimal fields for token efficiency.\n *\n * @returns Result with application summaries or error\n */\n async listApplicationSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n status: string;\n fqdn: string | null;\n }>,\n Error\n >\n > {\n const result = await this.listApplications();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((a) => ({\n uuid: a.uuid,\n name: a.name,\n status: a.status,\n fqdn: a.fqdn || null,\n })),\n );\n }\n\n /**\n * Lists servers with minimal fields for token efficiency.\n *\n * @returns Result with server summaries or error\n */\n async listServerSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n ip: string;\n is_reachable: boolean;\n }>,\n Error\n >\n > {\n const result = await this.listServers();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((s) => ({\n uuid: s.uuid,\n name: s.name,\n ip: s.ip || \"\",\n is_reachable: s.is_reachable || false,\n })),\n );\n }\n\n /**\n * Lists databases with minimal fields for token efficiency.\n *\n * @returns Result with database summaries or error\n */\n async listDatabaseSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n type: string;\n status: string;\n }>,\n Error\n >\n > {\n const result = await this.listDatabases();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((d) => ({\n uuid: d.uuid,\n name: d.name,\n type: d.type,\n status: d.status,\n })),\n );\n }\n\n /**\n * Lists services with minimal fields for token efficiency.\n *\n * @returns Result with service summaries or error\n */\n async listServiceSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n type: string;\n status: string;\n }>,\n Error\n >\n > {\n const result = await this.listServices();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((s) => ({\n uuid: s.uuid,\n name: s.name,\n type: s.type,\n status: s.status,\n })),\n );\n }\n}\n\nlet instance: CoolifyService | null = null;\n\n/**\n * Gets the singleton CoolifyService instance.\n *\n * @returns The CoolifyService instance\n */\nexport function getCoolifyService(): CoolifyService {\n if (!instance) {\n instance = new CoolifyService();\n }\n return instance;\n}\n\n// Re-export types\nexport type {\n ICoolifyServer,\n ICoolifyServerResource,\n ICoolifyServerDomain,\n ICoolifyDestination,\n ICoolifyProject,\n ICoolifyTeam,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyPrivateKey,\n ICoolifyDeployment,\n ICoolifyVersion,\n ICoolifyAppOptions,\n ICoolifyAppResult,\n ICoolifyDeployOptions,\n ICoolifyDeployResult,\n ICoolifyDeleteResult,\n ICoolifyUpdateOptions,\n ICoolifyLogsOptions,\n ICoolifyLogs,\n IProgressCallback,\n} from \"./types.js\";\n","/**\n * Coolify SDK — Fluent, resource-based API for Coolify.\n *\n * Every parameter from CoolifyService is exposed. Nothing is lost.\n *\n * @module\n */\n\nimport { isErr, type Result } from \"@mks2508/no-throw\";\nimport { CoolifyService } from \"./coolify/index.js\";\nimport type {\n ICoolifyAppOptions,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyDeleteResult,\n ICoolifyDeployment,\n ICoolifyDeployResult,\n ICoolifyDestination,\n ICoolifyEnvironment,\n ICoolifyLogs,\n ICoolifyLogsOptions,\n ICoolifyPrivateKey,\n ICoolifyProject,\n ICoolifyServer,\n ICoolifyServerDomain,\n ICoolifyServerResource,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyTeam,\n ICoolifyUpdateOptions,\n ICoolifyVersion,\n IProgressCallback,\n} from \"./coolify/types.js\";\nimport type { ICoolifyEnvVar } from \"./coolify/index.js\";\n\n/** SDK configuration options. */\nexport interface ICoolifyOptions {\n /** Coolify instance URL (e.g., https://coolify.example.com) */\n url: string;\n /** API token (generate in Coolify > Settings > API Tokens) */\n token: string;\n}\n\n/** Cascade delete options. */\nexport interface IDeleteOptions {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n}\n\n/** Pagination options. */\nexport interface IPaginationOptions {\n page?: number;\n perPage?: number;\n}\n\nfunction unwrap<T>(result: Result<T, Error>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n// ─── Resource Classes ────────────────────────────────────────────────────────\n\nclass ApplicationsResource {\n constructor(private svc: CoolifyService) {}\n\n /** List all applications. Supports filtering and pagination. */\n async list(\n options?: { teamId?: string; projectId?: string } & IPaginationOptions,\n ): Promise<ICoolifyApplication[]> {\n return unwrap(\n await this.svc.listApplications(\n options?.teamId,\n options?.projectId,\n options?.page,\n options?.perPage,\n ),\n );\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listApplicationSummaries());\n }\n\n /** Resolve application by name, domain, or UUID. */\n async resolve(query: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.resolveApplication(query));\n }\n\n /** Create a new application. All ICoolifyAppOptions supported. */\n async create(options: ICoolifyAppOptions, onProgress?: IProgressCallback) {\n return unwrap(await this.svc.createApplication(options, onProgress));\n }\n\n /** Deploy an application. Supports force rebuild and progress tracking. */\n async deploy(\n uuid: string,\n options?: { force?: boolean; tag?: string },\n onProgress?: IProgressCallback,\n ): Promise<ICoolifyDeployResult> {\n return unwrap(await this.svc.deploy({ uuid, ...options }, onProgress));\n }\n\n /** Start application. Supports force and instant_deploy. */\n async start(\n uuid: string,\n options?: { force?: boolean; instantDeploy?: boolean },\n ): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.startApplication(uuid, options));\n }\n\n async stop(uuid: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.stopApplication(uuid));\n }\n\n async restart(uuid: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.restartApplication(uuid));\n }\n\n /** Delete application with optional cascade options. */\n async delete(\n uuid: string,\n options?: IDeleteOptions,\n ): Promise<ICoolifyDeleteResult> {\n return unwrap(await this.svc.deleteApplication(uuid, options));\n }\n\n /** Update application configuration. All ICoolifyUpdateOptions supported. */\n async update(\n uuid: string,\n options: ICoolifyUpdateOptions,\n ): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.updateApplication(uuid, options));\n }\n\n /** Get application logs. Supports lines, serviceName, follow. */\n async logs(\n uuid: string,\n options?: ICoolifyLogsOptions,\n ): Promise<ICoolifyLogs> {\n return unwrap(await this.svc.getApplicationLogs(uuid, options));\n }\n\n /** Get deployment history with optional pagination. */\n async deployments(\n uuid: string,\n skip?: number,\n take?: number,\n ): Promise<ICoolifyDeployment[]> {\n return unwrap(await this.svc.getApplicationDeployments(uuid, skip, take));\n }\n\n async exec(uuid: string, command: string) {\n return unwrap(await this.svc.executeCommand(uuid, command));\n }\n\n async envVars(uuid: string): Promise<ICoolifyEnvVar[]> {\n return unwrap(await this.svc.getEnvironmentVariables(uuid));\n }\n\n async setEnv(\n uuid: string,\n key: string,\n value: string,\n isBuildTime?: boolean,\n ) {\n return unwrap(\n await this.svc.setEnvironmentVariable(uuid, key, value, isBuildTime),\n );\n }\n\n async bulkSetEnv(\n uuid: string,\n vars: Array<{ key: string; value: string; is_preview?: boolean }>,\n ) {\n return unwrap(await this.svc.bulkUpdateEnvironmentVariables(uuid, vars));\n }\n\n async deleteEnv(uuid: string, key: string) {\n return unwrap(await this.svc.deleteEnvironmentVariable(uuid, key));\n }\n}\n\nclass DatabasesResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyDatabase[]> {\n return unwrap(\n await this.svc.listDatabases(options?.page, options?.perPage),\n );\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listDatabaseSummaries());\n }\n\n async get(uuid: string): Promise<ICoolifyDatabase> {\n return unwrap(await this.svc.getDatabase(uuid));\n }\n\n async create(type: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.createDatabase(type, data));\n }\n\n async update(uuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateDatabase(uuid, data));\n }\n\n async start(uuid: string) {\n return unwrap(await this.svc.startDatabase(uuid));\n }\n async stop(uuid: string) {\n return unwrap(await this.svc.stopDatabase(uuid));\n }\n async restart(uuid: string) {\n return unwrap(await this.svc.restartDatabase(uuid));\n }\n\n /** Delete with optional cascade options. */\n async delete(uuid: string, options?: IDeleteOptions) {\n return unwrap(await this.svc.deleteDatabase(uuid, options));\n }\n\n async backups(uuid: string): Promise<ICoolifyDatabaseBackup[]> {\n return unwrap(await this.svc.listDatabaseBackups(uuid));\n }\n\n async getBackup(dbUuid: string, backupUuid: string) {\n return unwrap(await this.svc.getDatabaseBackup(dbUuid, backupUuid));\n }\n\n async createBackup(dbUuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.createDatabaseBackup(dbUuid, data));\n }\n\n async deleteBackup(dbUuid: string, backupUuid: string) {\n return unwrap(await this.svc.deleteDatabaseBackup(dbUuid, backupUuid));\n }\n}\n\nclass ServicesResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyServiceType[]> {\n return unwrap(await this.svc.listServices(options?.page, options?.perPage));\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listServiceSummaries());\n }\n\n async get(uuid: string): Promise<ICoolifyServiceType> {\n return unwrap(await this.svc.getService(uuid));\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createService(data));\n }\n\n async update(uuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateService(uuid, data));\n }\n\n async start(uuid: string) {\n return unwrap(await this.svc.startService(uuid));\n }\n async stop(uuid: string) {\n return unwrap(await this.svc.stopService(uuid));\n }\n async restart(uuid: string) {\n return unwrap(await this.svc.restartService(uuid));\n }\n\n /** Delete with optional cascade options. */\n async delete(uuid: string, options?: IDeleteOptions) {\n return unwrap(await this.svc.deleteService(uuid, options));\n }\n\n async envVars(uuid: string): Promise<ICoolifyEnvVar[]> {\n return unwrap(await this.svc.listServiceEnvVars(uuid));\n }\n\n async setEnv(\n uuid: string,\n data: { key: string; value: string; is_preview?: boolean },\n ) {\n return unwrap(await this.svc.createServiceEnvVar(uuid, data));\n }\n}\n\nclass ServersResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyServer[]> {\n return unwrap(await this.svc.listServers(options?.page, options?.perPage));\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listServerSummaries());\n }\n\n async resolve(query: string): Promise<ICoolifyServer> {\n return unwrap(await this.svc.resolveServer(query));\n }\n\n async get(uuid: string): Promise<ICoolifyServer> {\n return unwrap(await this.svc.getServer(uuid));\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createServer(data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deleteServer(uuid));\n }\n\n async resources(uuid: string): Promise<ICoolifyServerResource[]> {\n return unwrap(await this.svc.getServerResources(uuid));\n }\n\n async domains(uuid: string): Promise<ICoolifyServerDomain[]> {\n return unwrap(await this.svc.getServerDomains(uuid));\n }\n\n async destinations(uuid: string): Promise<ICoolifyDestination[]> {\n return unwrap(await this.svc.getServerDestinations(uuid));\n }\n\n async validate(uuid: string) {\n return unwrap(await this.svc.validateServer(uuid));\n }\n}\n\nclass ProjectsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyProject[]> {\n return unwrap(await this.svc.listProjects(options?.page, options?.perPage));\n }\n\n async create(name: string, description?: string): Promise<ICoolifyProject> {\n return unwrap(await this.svc.createProject(name, description));\n }\n\n async update(uuid: string, data: { name?: string; description?: string }) {\n return unwrap(await this.svc.updateProject(uuid, data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deleteProject(uuid));\n }\n\n async environments(projectUuid: string): Promise<ICoolifyEnvironment[]> {\n return unwrap(await this.svc.getProjectEnvironments(projectUuid));\n }\n\n async createEnvironment(\n projectUuid: string,\n data: { name: string; description?: string },\n ) {\n return unwrap(await this.svc.createProjectEnvironment(projectUuid, data));\n }\n}\n\nclass TeamsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyTeam[]> {\n return unwrap(await this.svc.listTeams(options?.page, options?.perPage));\n }\n\n async current(): Promise<ICoolifyTeam> {\n return unwrap(await this.svc.getCurrentTeam());\n }\n\n async get(id: number): Promise<ICoolifyTeam> {\n return unwrap(await this.svc.getTeam(id));\n }\n\n async members(teamId: number) {\n return unwrap(await this.svc.getTeamMembers(teamId));\n }\n}\n\nclass KeysResource {\n constructor(private svc: CoolifyService) {}\n\n async list(): Promise<ICoolifyPrivateKey[]> {\n return unwrap(await this.svc.listPrivateKeys());\n }\n\n async get(uuid: string): Promise<ICoolifyPrivateKey> {\n return unwrap(await this.svc.getPrivateKey(uuid));\n }\n\n async create(data: {\n name: string;\n private_key: string;\n description?: string;\n }) {\n return unwrap(await this.svc.createPrivateKey(data));\n }\n\n async update(\n uuid: string,\n data: { name?: string; private_key?: string; description?: string },\n ) {\n return unwrap(await this.svc.updatePrivateKey(uuid, data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deletePrivateKey(uuid));\n }\n}\n\nclass DeploymentsResource {\n constructor(private svc: CoolifyService) {}\n\n async active(options?: IPaginationOptions): Promise<ICoolifyDeployment[]> {\n return unwrap(\n await this.svc.listDeployments(options?.page, options?.perPage),\n );\n }\n\n async get(uuid: string): Promise<ICoolifyDeployment> {\n return unwrap(await this.svc.getDeployment(uuid));\n }\n\n /** Get deployment with build logs. */\n async logs(uuid: string) {\n return unwrap(await this.svc.getDeploymentLogs(uuid));\n }\n\n async cancel(uuid: string) {\n return unwrap(await this.svc.cancelDeployment(uuid));\n }\n}\n\nclass DiagnoseResource {\n constructor(private svc: CoolifyService) {}\n\n async app(query: string) {\n return unwrap(await this.svc.diagnoseApplication(query));\n }\n\n async server(query: string) {\n return unwrap(await this.svc.diagnoseServer(query));\n }\n\n async infrastructure() {\n return unwrap(await this.svc.findInfrastructureIssues());\n }\n\n /** Analyze a failed deployment — extracts errors from build logs. */\n async deployFailure(deploymentUuid: string) {\n const { analyzeDeployFailure } = await import(\"./network.js\");\n return unwrap(await analyzeDeployFailure(this.svc, deploymentUuid));\n }\n}\n\n/**\n * Network diagnostics — inspect Docker networks, proxy, DNS, connectivity.\n */\nclass NetworkResource {\n constructor(private svc: CoolifyService) {}\n\n /**\n * Inspect container network environment.\n *\n * @param appUuid - Application UUID\n * @param servicesToTest - Service names to test connectivity (e.g., ['db', 'redis'])\n */\n async inspect(appUuid: string, servicesToTest?: string[]) {\n const { inspectNetwork } = await import(\"./network.js\");\n return unwrap(await inspectNetwork(this.svc, appUuid, servicesToTest));\n }\n}\n\nclass BatchResource {\n constructor(private svc: CoolifyService) {}\n\n async restartProject(projectUuid: string) {\n return unwrap(await this.svc.restartProjectApps(projectUuid));\n }\n\n async redeployProject(projectUuid: string, force?: boolean) {\n return unwrap(await this.svc.redeployProjectApps(projectUuid, force));\n }\n\n async stopAll() {\n return unwrap(await this.svc.stopAllApps());\n }\n}\n\nclass GitHubAppsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions) {\n return unwrap(\n await this.svc.listGithubApps(options?.page, options?.perPage),\n );\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createGitHubApp(data));\n }\n\n async update(id: number, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateGitHubApp(id, data));\n }\n\n async delete(id: number) {\n return unwrap(await this.svc.deleteGitHubApp(id));\n }\n}\n\n// ─── Main SDK Class ──────────────────────────────────────────────────────────\n\n/**\n * Coolify SDK — The main entry point for interacting with a Coolify instance.\n *\n * Every parameter from the internal CoolifyService is exposed.\n * Nothing is lost — progress callbacks, pagination, cascade deletes, all supported.\n */\nexport class Coolify {\n /** @internal */\n readonly svc: CoolifyService;\n private initialized = false;\n\n readonly applications: ApplicationsResource;\n readonly databases: DatabasesResource;\n readonly services: ServicesResource;\n readonly servers: ServersResource;\n readonly projects: ProjectsResource;\n readonly teams: TeamsResource;\n readonly keys: KeysResource;\n readonly deployments: DeploymentsResource;\n readonly diagnose: DiagnoseResource;\n readonly network: NetworkResource;\n readonly batch: BatchResource;\n readonly githubApps: GitHubAppsResource;\n\n constructor(options?: ICoolifyOptions) {\n this.svc = new CoolifyService();\n\n if (options) {\n process.env.COOLIFY_URL = options.url;\n process.env.COOLIFY_TOKEN = options.token;\n }\n\n const autoInit = <T extends object>(resource: T): T => {\n return new Proxy(resource, {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") return value;\n return async (...args: unknown[]) => {\n await this.ensureInit();\n return (value as Function).apply(target, args);\n };\n },\n });\n };\n\n this.applications = autoInit(new ApplicationsResource(this.svc));\n this.databases = autoInit(new DatabasesResource(this.svc));\n this.services = autoInit(new ServicesResource(this.svc));\n this.servers = autoInit(new ServersResource(this.svc));\n this.projects = autoInit(new ProjectsResource(this.svc));\n this.teams = autoInit(new TeamsResource(this.svc));\n this.keys = autoInit(new KeysResource(this.svc));\n this.deployments = autoInit(new DeploymentsResource(this.svc));\n this.diagnose = autoInit(new DiagnoseResource(this.svc));\n this.network = autoInit(new NetworkResource(this.svc));\n this.batch = autoInit(new BatchResource(this.svc));\n this.githubApps = autoInit(new GitHubAppsResource(this.svc));\n }\n\n static fromEnv(): Coolify {\n return new Coolify();\n }\n\n private async ensureInit(): Promise<void> {\n if (this.initialized) return;\n const initResult = await this.svc.init();\n if (isErr(initResult)) {\n throw new Error(`Coolify connection failed: ${initResult.error.message}`);\n }\n this.initialized = true;\n }\n\n async version(): Promise<ICoolifyVersion> {\n await this.ensureInit();\n return unwrap(await this.svc.getVersion());\n }\n}\n","/**\n * MCP Tool definitions for Coolify.\n *\n * Defines all 21 tools with their input schemas.\n *\n * @module\n */\n\nimport type { Tool } from \"@modelcontextprotocol/sdk/types.js\";\n\n/**\n * All Coolify MCP tool definitions.\n */\nexport const coolifyTools: Tool[] = [\n {\n name: \"deploy\",\n description: `Deploy or redeploy an application to Coolify.\n\nTriggers a new deployment for the specified application UUID.\nCan force rebuild without cache if needed.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID in Coolify\",\n format: \"uuid\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force rebuild without cache\",\n default: false,\n },\n tag: {\n type: \"string\" as const,\n description: \"Deploy specific tag/version\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_env_vars\",\n description: `Get environment variables for a Coolify application.\n\nReturns all environment variables with metadata including whether\nthey are runtime or buildtime, and if they are required.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"set_env_vars\",\n description: `Set environment variables for a Coolify application.\n\nUpdates or adds environment variables. Existing vars not in the\ninput are preserved. Redeploy after setting to apply changes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n envVars: {\n type: \"object\" as const,\n description: \"Key-value pairs of environment variables\",\n additionalProperties: { type: \"string\" as const },\n },\n },\n required: [\"uuid\", \"envVars\"],\n },\n },\n {\n name: \"get_deployment_status\",\n description: `Get the current status of a Coolify application.\n\nReturns deployment state, health status, and resource usage.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"list_applications\",\n description: `List all applications in Coolify.\n\nOptionally filter by team or project ID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n teamId: {\n type: \"string\" as const,\n description: \"Filter by Team ID\",\n },\n projectId: {\n type: \"string\" as const,\n description: \"Filter by Project ID\",\n },\n },\n },\n },\n {\n name: \"delete_application\",\n description: `Delete an application from Coolify.\n\nWARNING: This action is irreversible. All deployments, environment\nvariables, domains, and history will be permanently deleted.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to delete\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_application_logs\",\n description: `Get logs for a Coolify application.\n\nRetrieve recent logs. For docker-compose apps, use serviceName to filter by container.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n tail: {\n type: \"number\" as const,\n description: \"Number of log lines to retrieve (default: 100)\",\n },\n serviceName: {\n type: \"string\" as const,\n description:\n \"Service name to filter logs (for docker-compose apps, e.g., 'app', 'db')\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_application\",\n description: `Start a stopped Coolify application.\n\nUse this to start applications that were previously stopped.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to start\",\n format: \"uuid\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force start even if already running\",\n },\n instantDeploy: {\n type: \"boolean\" as const,\n description: \"Instant deploy without waiting for queue\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_application\",\n description: `Stop a running Coolify application.\n\nWARNING: This will make the application temporarily unavailable.\nContainers will be stopped but not deleted.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to stop\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_application\",\n description: `Restart a Coolify application.\n\nEquivalent to stopping and then starting the application.\nUseful to apply configuration changes or recover from errors.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to restart\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_deployment_history\",\n description: `Get deployment history for a Coolify application.\n\nReturns list of all deployments with status, timestamps, and commit info.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"update_application\",\n description: `Update configuration for a Coolify application.\n\nCan modify name, description, build settings, commands, and domains.\nRedeploy after updating to apply changes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n name: {\n type: \"string\" as const,\n description: \"New application name\",\n },\n description: {\n type: \"string\" as const,\n description: \"New description\",\n },\n buildPack: {\n type: \"string\" as const,\n description: \"Build pack type\",\n enum: [\"dockerfile\", \"nixpacks\", \"static\", \"dockercompose\"],\n },\n gitBranch: {\n type: \"string\" as const,\n description: \"Git branch to deploy\",\n },\n portsExposes: {\n type: \"string\" as const,\n description: \"Ports to expose (comma-separated)\",\n },\n installCommand: {\n type: \"string\" as const,\n description: \"Install command (nixpacks)\",\n },\n buildCommand: {\n type: \"string\" as const,\n description: \"Build command\",\n },\n startCommand: {\n type: \"string\" as const,\n description: \"Start command\",\n },\n domains: {\n type: \"string\" as const,\n description:\n 'Domains/FQDN - comma separated list with protocol (e.g., \"https://app.example.com,https://www.example.com\")',\n },\n isForceHttpsEnabled: {\n type: \"boolean\" as const,\n description: \"Force HTTPS redirect\",\n },\n isAutoDeployEnabled: {\n type: \"boolean\" as const,\n description: \"Enable auto deploy on git push\",\n },\n dockerfileLocation: {\n type: \"string\" as const,\n description: \"Dockerfile location relative to repo root\",\n },\n baseDirectory: {\n type: \"string\" as const,\n description: 'Base directory for build context (default: \"/\")',\n },\n dockerComposeDomains: {\n type: \"string\" as const,\n description:\n 'Docker Compose domains JSON: { \"service-name\": { \"domain\": \"https://...\" } }',\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"set_domains\",\n description: `Set domains/FQDN for a Coolify application.\n\nConfigure custom domains for your application. Coolify automatically handles SSL certificates via Let's Encrypt.\n\nDomain format:\n- Use FQDN with protocol: https://app.example.com\n- Multiple domains separated by comma: https://app.example.com,https://www.example.com\n- Can include port mapping: https://api.example.com:3000`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n domains: {\n type: \"string\" as const,\n description:\n 'Domains/FQDN - comma separated list with protocol (e.g., \"https://app.example.com,https://www.example.com\")',\n },\n forceHttps: {\n type: \"boolean\" as const,\n description: \"Force HTTPS redirect (default: true)\",\n default: true,\n },\n },\n required: [\"uuid\", \"domains\"],\n },\n },\n {\n name: \"list_servers\",\n description: `List all available servers in Coolify.\n\nReturns server UUIDs, names, and IPs. Use server UUID when creating applications.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_server\",\n description: `Get details of a specific Coolify server.\n\nReturns server information including name, IP, status, and configuration.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to get details for\",\n format: \"uuid\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"list_projects\",\n description: `List all projects in Coolify.\n\nReturns project UUIDs, names, and associated environments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"list_teams\",\n description: `List all teams in Coolify.\n\nReturns team IDs, names, and configuration.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_server_destinations\",\n description: `Get available destinations for a Coolify server.\n\nReturns destination UUIDs needed when creating applications.\nEach destination represents a Docker network/environment on the server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to get destinations for\",\n format: \"uuid\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"create_application\",\n description: `Create a new application in Coolify from a GitHub repository.\n\nRequires server UUID and destination UUID (get them from list_servers and get_server_destinations).\nThe GitHub repository must be accessible via the configured GitHub App.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\" as const,\n description: \"Application name\",\n },\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to deploy to\",\n format: \"uuid\",\n },\n destinationUuid: {\n type: \"string\" as const,\n description: \"Destination UUID (Docker network)\",\n format: \"uuid\",\n },\n githubRepoUrl: {\n type: \"string\" as const,\n description:\n \"GitHub repository URL (e.g., https://github.com/user/repo)\",\n },\n description: {\n type: \"string\" as const,\n description: \"Application description\",\n },\n branch: {\n type: \"string\" as const,\n description: \"Git branch to deploy\",\n default: \"main\",\n },\n buildPack: {\n type: \"string\" as const,\n description: \"Build pack type\",\n enum: [\"dockerfile\", \"nixpacks\", \"static\", \"dockercompose\"],\n default: \"nixpacks\",\n },\n type: {\n type: \"string\" as const,\n description: \"Application type\",\n enum: [\n \"public\",\n \"private-github-app\",\n \"private-deploy-key\",\n \"dockerfile\",\n \"docker-image\",\n \"docker-compose\",\n ],\n default: \"public\",\n },\n dockerComposeLocation: {\n type: \"string\" as const,\n description:\n \"Docker Compose file location relative to repo root (for dockercompose buildPack)\",\n },\n dockerfileLocation: {\n type: \"string\" as const,\n description: \"Dockerfile location relative to repo root\",\n },\n baseDirectory: {\n type: \"string\" as const,\n description: 'Base directory for build context (default: \"/\")',\n },\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n environmentUuid: {\n type: \"string\" as const,\n description: \"Environment UUID\",\n },\n githubAppUuid: {\n type: \"string\" as const,\n description:\n \"GitHub App UUID (for private-github-app type, get from list_github_apps)\",\n },\n portsExposes: {\n type: \"string\" as const,\n description: \"Ports to expose (e.g., '3000' or '3000,8080')\",\n },\n },\n required: [\"name\", \"serverUuid\"],\n },\n },\n {\n name: \"create_project\",\n description: `Create a new project in Coolify.\n\nProjects organize applications into logical groups. Each project has one or more environments (e.g., production, staging).`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\" as const,\n description: \"Project name\",\n },\n description: {\n type: \"string\" as const,\n description: \"Project description\",\n },\n },\n required: [\"name\"],\n },\n },\n {\n name: \"get_resource_usage\",\n description: `Get resource usage for a Coolify application.\n\nReturns current resource consumption metrics.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"health_check\",\n description: `Check if Coolify API is accessible and credentials are valid.\n\nReturns connection status and API version info if available.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"list_deployments\",\n description: `List all active and queued deployments across all applications.\n\nReturns deployments that are currently in progress or waiting in queue.\nUseful for monitoring ongoing builds and deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_deployment\",\n description: `Get detailed information about a specific deployment.\n\nReturns deployment status, logs, timestamps, and error messages if any.\nUse deployment UUID from list_deployments or get_application_deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n {\n name: \"get_application_deployments\",\n description: `Get deployment history for a specific application.\n\nReturns list of all deployments with status, timestamps, commit info, and logs.\nUseful for debugging failed deployments and tracking deployment history.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n skip: {\n type: \"number\" as const,\n description: \"Number of deployments to skip (pagination)\",\n default: 0,\n },\n take: {\n type: \"number\" as const,\n description: \"Number of deployments to return (default: 10)\",\n default: 10,\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_application_details\",\n description: `Get detailed information about a Coolify application.\n\nReturns full application configuration including name, description,\nbuild settings, environment, and deployment status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n {\n name: \"execute_command\",\n description: `Execute a shell command on an application's running container.\n\nUseful for debugging, checking file contents, or running one-off operations.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n command: {\n type: \"string\" as const,\n description:\n \"Shell command to execute (e.g., 'ls -la', 'cat /app/logs/error.log')\",\n },\n },\n required: [\"uuid\", \"command\"],\n },\n },\n {\n name: \"bulk_update_env_vars\",\n description: `Bulk update environment variables for an application.\n\nMore efficient than setting variables one by one. Accepts an array of key-value pairs.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n envVars: {\n type: \"array\" as const,\n description: \"Array of { key, value, is_preview? } objects\",\n items: {\n type: \"object\" as const,\n properties: {\n key: { type: \"string\" as const },\n value: { type: \"string\" as const },\n is_preview: { type: \"boolean\" as const },\n },\n required: [\"key\", \"value\"],\n },\n },\n },\n required: [\"uuid\", \"envVars\"],\n },\n },\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n {\n name: \"get_version\",\n description: `Get the Coolify server version.\n\nReturns the version string of the connected Coolify instance.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Database Management\n // ===========================================================================\n {\n name: \"list_databases\",\n description: `List all databases in Coolify.\n\nReturns database UUIDs, names, types, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_database\",\n description: `Get details of a specific database.\n\nReturns full database configuration, connection info, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"create_database\",\n description: `Create a new database in Coolify.\n\nSupports types: postgresql, mysql, mariadb, mongodb, redis, keydb, clickhouse, dragonfly.\nRequires server_uuid and project_uuid in the data.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n dbType: {\n type: \"string\" as const,\n description: \"Database type\",\n enum: [\n \"postgresql\",\n \"mysql\",\n \"mariadb\",\n \"mongodb\",\n \"redis\",\n \"keydb\",\n \"clickhouse\",\n \"dragonfly\",\n ],\n },\n data: {\n type: \"object\" as const,\n description:\n \"Database creation data (server_uuid, project_uuid, environment_name, etc.)\",\n additionalProperties: true,\n },\n },\n required: [\"dbType\", \"data\"],\n },\n },\n {\n name: \"delete_database\",\n description: `Delete a database from Coolify.\n\nWARNING: This action is irreversible.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to delete\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_database\",\n description: `Start a stopped database.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to start\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_database\",\n description: `Stop a running database.\n\nWARNING: This will make the database temporarily unavailable.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to stop\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_database\",\n description: `Restart a database.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to restart\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Service Management\n // ===========================================================================\n {\n name: \"list_services\",\n description: `List all services in Coolify.\n\nReturns service UUIDs, names, types, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_service\",\n description: `Get details of a specific service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_service\",\n description: `Start a stopped service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to start\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_service\",\n description: `Stop a running service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to stop\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_service\",\n description: `Restart a service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to restart\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"delete_service\",\n description: `Delete a service from Coolify.\n\nWARNING: This action is irreversible.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to delete\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Server (additional)\n // ===========================================================================\n {\n name: \"get_server_resources\",\n description: `Get all resources deployed on a server.\n\nReturns applications, databases, and services running on the server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"get_server_domains\",\n description: `Get all domains configured on a server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"validate_server\",\n description: `Validate a server connection in Coolify.\n\nChecks if the server is reachable and properly configured.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to validate\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n\n // ===========================================================================\n // Deployment Control\n // ===========================================================================\n {\n name: \"cancel_deployment\",\n description: `Cancel an in-progress deployment.\n\nStops the build/deployment process for the specified deployment.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID to cancel\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n\n // ===========================================================================\n // Teams (additional)\n // ===========================================================================\n {\n name: \"get_current_team\",\n description: `Get the current team associated with the API token.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_team_members\",\n description: `Get members of a specific team.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n teamId: {\n type: \"number\" as const,\n description: \"Team ID\",\n },\n },\n required: [\"teamId\"],\n },\n },\n\n // ===========================================================================\n // Private Keys / SSH\n // ===========================================================================\n {\n name: \"list_private_keys\",\n description: `List all SSH private keys configured in Coolify.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_private_key\",\n description: `Get details of a specific SSH private key.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Private key UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Smart Resolution\n // ===========================================================================\n {\n name: \"resolve_application\",\n description: `Find an application by name, domain, or UUID.\n\nSearches across all applications and returns the match. Useful when you know\nthe app name but not the UUID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Application name, domain (FQDN), or UUID to search for\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"resolve_server\",\n description: `Find a server by name, IP, or UUID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Server name, IP address, or UUID to search for\",\n },\n },\n required: [\"query\"],\n },\n },\n\n // ===========================================================================\n // Diagnostics\n // ===========================================================================\n {\n name: \"diagnose_application\",\n description: `Run a comprehensive diagnostic on an application.\n\nAggregates status, recent deployments, environment variables, and logs\ninto a single diagnostic report with identified issues.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Application name, domain, or UUID to diagnose\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"diagnose_server\",\n description: `Run a comprehensive diagnostic on a server.\n\nAggregates server health, deployed resources, and domains into a diagnostic report.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Server name, IP, or UUID to diagnose\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"find_infrastructure_issues\",\n description: `Scan all infrastructure for potential issues.\n\nChecks all servers, applications, databases, and services for problems\nlike unreachable servers, stopped apps, failed deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Batch Operations\n // ===========================================================================\n {\n name: \"restart_project_apps\",\n description: `Restart all applications in a project.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n },\n required: [\"projectUuid\"],\n },\n },\n {\n name: \"redeploy_project_apps\",\n description: `Redeploy all applications in a project.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force rebuild without cache\",\n default: false,\n },\n },\n required: [\"projectUuid\"],\n },\n },\n {\n name: \"stop_all_apps\",\n description: `Emergency stop all running applications.\n\nWARNING: This will stop ALL running applications across all projects.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Network Diagnostics\n // ===========================================================================\n {\n name: \"inspect_network\",\n description: `Inspect Docker container network environment for an application.\n\nReturns /etc/hosts, DNS resolution, network env vars, interfaces,\nand optionally tests connectivity to other services.\nEssential for debugging docker-compose networking issues.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n servicesToTest: {\n type: \"array\" as const,\n description:\n \"Service names to test connectivity (e.g., ['db', 'redis', 'app'])\",\n items: { type: \"string\" as const },\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"analyze_deploy_failure\",\n description: `Analyze a failed deployment by inspecting build logs.\n\nAutomatically extracts error lines, categorizes the failure type\n(build_error, install_error, docker_error, network_error, timeout),\nand suggests fixes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID of the failed deployment\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n];\n","/**\n * MCP Tool handlers for Coolify.\n *\n * All handlers route through the Coolify SDK facade.\n * Uses a generic mcpCall wrapper to eliminate boilerplate.\n *\n * @module\n */\n\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Coolify } from \"../sdk.js\";\n\n/** Singleton SDK for MCP usage (reads env vars / config file). */\nlet _sdk: Coolify | null = null;\nfunction getSdk(): Coolify {\n if (!_sdk) _sdk = Coolify.fromEnv();\n return _sdk;\n}\n\n/**\n * Wraps an SDK call into an MCP tool result.\n * On success → JSON response. On error → isError response.\n *\n * @param fn - Async function that calls the SDK (throws on error)\n * @param label - Error context label\n * @returns MCP CallToolResult\n */\nasync function mcpCall(\n fn: (sdk: Coolify) => Promise<unknown>,\n label: string,\n): Promise<CallToolResult> {\n try {\n const data = await fn(getSdk());\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n typeof data === \"object\" && data !== null\n ? { success: true, ...data }\n : { success: true, result: data },\n null,\n 2,\n ),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: \"text\",\n text: `${label}: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/** Wraps SDK call returning an array into { count, items } format. */\nasync function mcpList(\n fn: (sdk: Coolify) => Promise<unknown[]>,\n itemKey: string,\n label: string,\n): Promise<CallToolResult> {\n return mcpCall(async (sdk) => {\n const items = await fn(sdk);\n return { count: items.length, [itemKey]: items };\n }, label);\n}\n\n/**\n * Main handler — routes tool calls to SDK methods.\n *\n * @param name - Tool name\n * @param args - Tool arguments\n * @returns MCP tool result\n */\nexport async function handleToolCall(\n name: string,\n args: Record<string, unknown>,\n): Promise<CallToolResult> {\n const a = args as any;\n\n switch (name) {\n // ─── Applications ──────────────────────────────────────────────────\n case \"deploy\":\n return mcpCall(\n (s) =>\n s.applications\n .deploy(a.uuid, { force: a.force, tag: a.tag })\n .then((r) => ({\n deploymentUuid: r.deploymentUuid,\n resourceUuid: r.resourceUuid,\n message: \"Deployment started\",\n })),\n \"Deployment failed\",\n );\n case \"list_applications\":\n return mcpList(\n (s) => s.applications.list(),\n \"applications\",\n \"Failed to list applications\",\n );\n case \"get_application_details\":\n return mcpCall(\n (s) =>\n s.applications.resolve(a.uuid).then((app) => ({ application: app })),\n \"Failed to get application\",\n );\n case \"start_application\":\n return mcpCall(\n (s) =>\n s.applications\n .start(a.uuid, { force: a.force, instantDeploy: a.instantDeploy })\n .then(() => ({\n message: `Application ${a.uuid} started`,\n })),\n \"Failed to start application\",\n );\n case \"stop_application\":\n return mcpCall(\n (s) =>\n s.applications.stop(a.uuid).then(() => ({\n message: `Application ${a.uuid} stopped`,\n })),\n \"Failed to stop application\",\n );\n case \"restart_application\":\n return mcpCall(\n (s) =>\n s.applications.restart(a.uuid).then(() => ({\n message: `Application ${a.uuid} restarted`,\n })),\n \"Failed to restart application\",\n );\n case \"delete_application\":\n return mcpCall(\n (s) =>\n s.applications.delete(a.uuid).then(() => ({\n message: `Application ${a.uuid} deleted`,\n })),\n \"Failed to delete application\",\n );\n case \"update_application\":\n return mcpCall(\n (s) =>\n s.applications\n .update(a.uuid, {\n name: a.name,\n description: a.description,\n buildPack: a.buildPack,\n gitBranch: a.gitBranch,\n portsExposes: a.portsExposes,\n installCommand: a.installCommand,\n buildCommand: a.buildCommand,\n startCommand: a.startCommand,\n domains: a.domains,\n isForceHttpsEnabled: a.isForceHttpsEnabled,\n isAutoDeployEnabled: a.isAutoDeployEnabled,\n })\n .then((app) => ({\n message: `Application ${a.uuid} updated`,\n application: app,\n })),\n \"Failed to update application\",\n );\n case \"get_application_logs\":\n return mcpCall(\n (s) =>\n s.applications\n .logs(a.uuid, { tail: a.tail, serviceName: a.serviceName })\n .then((logs) => ({\n timestamp: logs.timestamp,\n logCount: logs.logs.length,\n logs: logs.logs,\n })),\n \"Failed to get logs\",\n );\n case \"get_deployment_history\":\n return mcpList(\n (s) => s.applications.deployments(a.uuid),\n \"deployments\",\n \"Failed to get deployment history\",\n );\n case \"get_application_deployments\":\n return mcpList(\n (s) => s.applications.deployments(a.uuid),\n \"deployments\",\n \"Failed to get deployments\",\n );\n case \"execute_command\":\n return mcpCall(\n (s) => s.applications.exec(a.uuid, a.command),\n \"Failed to execute command\",\n );\n\n // ─── Environment Variables ─────────────────────────────────────────\n case \"get_env_vars\":\n return mcpCall(\n (s) =>\n s.applications.envVars(a.uuid).then((vars) => ({\n total: vars.length,\n runtime: vars.filter((v) => v.is_runtime),\n buildtime: vars.filter((v) => v.is_buildtime),\n })),\n \"Failed to get env vars\",\n );\n case \"set_env_vars\":\n return mcpCall((s) => {\n const entries = Object.entries(a.envVars as Record<string, string>);\n return s.applications\n .bulkSetEnv(\n a.uuid,\n entries.map(([key, value]) => ({ key, value })),\n )\n .then(() => ({\n message: `Set ${entries.length} environment variable(s)`,\n }));\n }, \"Failed to set env vars\");\n case \"bulk_update_env_vars\":\n return mcpCall(\n (s) =>\n s.applications.bulkSetEnv(a.uuid, a.envVars).then(() => ({\n message: `Bulk updated ${a.envVars.length} variable(s)`,\n })),\n \"Failed to bulk update env vars\",\n );\n\n // ─── Domains ───────────────────────────────────────────────────────\n case \"set_domains\":\n return mcpCall(\n (s) =>\n s.applications\n .update(a.uuid, {\n domains: a.domains,\n isForceHttpsEnabled: a.forceHttps ?? true,\n })\n .then(() => ({\n message: `Domains set for ${a.uuid}`,\n domains: a.domains.split(\",\").map((d: string) => d.trim()),\n })),\n \"Failed to set domains\",\n );\n\n // ─── Deployment Status ─────────────────────────────────────────────\n case \"get_deployment_status\":\n return mcpCall(\n (s) =>\n s.applications\n .resolve(a.uuid)\n .then((app) => ({ status: app.status })),\n \"Failed to get status\",\n );\n\n // ─── Deployments ───────────────────────────────────────────────────\n case \"list_deployments\":\n return mcpList(\n (s) => s.deployments.active(),\n \"deployments\",\n \"Failed to list deployments\",\n );\n case \"get_deployment\":\n return mcpCall(\n (s) =>\n s.deployments.get(a.deploymentUuid).then((d) => ({ deployment: d })),\n \"Failed to get deployment\",\n );\n case \"cancel_deployment\":\n return mcpCall(\n (s) =>\n s.deployments\n .cancel(a.deploymentUuid)\n .then(() => ({ message: \"Deployment cancelled\" })),\n \"Failed to cancel deployment\",\n );\n\n // ─── Servers ───────────────────────────────────────────────────────\n case \"list_servers\":\n return mcpList(\n (s) => s.servers.list(),\n \"servers\",\n \"Failed to list servers\",\n );\n case \"get_server\":\n return mcpCall(\n (s) => s.servers.get(a.serverUuid).then((srv) => ({ server: srv })),\n \"Failed to get server\",\n );\n case \"get_server_destinations\":\n return mcpList(\n (s) => s.servers.destinations(a.serverUuid),\n \"destinations\",\n \"Failed to get destinations\",\n );\n case \"get_server_resources\":\n return mcpList(\n (s) => s.servers.resources(a.serverUuid),\n \"resources\",\n \"Failed to get server resources\",\n );\n case \"get_server_domains\":\n return mcpList(\n (s) => s.servers.domains(a.serverUuid),\n \"domains\",\n \"Failed to get server domains\",\n );\n case \"validate_server\":\n return mcpCall(\n (s) =>\n s.servers\n .validate(a.serverUuid)\n .then(() => ({ message: \"Server validated\" })),\n \"Failed to validate server\",\n );\n\n // ─── Projects ──────────────────────────────────────────────────────\n case \"list_projects\":\n return mcpList(\n (s) => s.projects.list(),\n \"projects\",\n \"Failed to list projects\",\n );\n case \"create_project\":\n return mcpCall(\n (s) =>\n s.projects.create(a.name, a.description).then((p) => ({\n message: `Project \"${a.name}\" created`,\n uuid: p.uuid,\n })),\n \"Failed to create project\",\n );\n case \"create_application\":\n return mcpCall(\n (s) =>\n s.applications\n .create({\n name: a.name,\n description: a.description,\n projectUuid: a.projectUuid,\n environmentUuid: a.environmentUuid,\n serverUuid: a.serverUuid,\n type: a.type || \"public\",\n githubAppUuid: a.githubAppUuid,\n githubRepoUrl: a.githubRepoUrl,\n branch: a.branch,\n buildPack: a.buildPack,\n portsExposes: a.portsExposes,\n dockerComposeLocation: a.dockerComposeLocation,\n dockerfileLocation: a.dockerfileLocation,\n baseDirectory: a.baseDirectory,\n })\n .then((r) => ({\n message: `Application \"${a.name}\" created`,\n uuid: r.uuid,\n })),\n \"Failed to create application\",\n );\n\n // ─── Teams ─────────────────────────────────────────────────────────\n case \"list_teams\":\n return mcpList((s) => s.teams.list(), \"teams\", \"Failed to list teams\");\n case \"get_current_team\":\n return mcpCall(\n (s) => s.teams.current().then((t) => ({ team: t })),\n \"Failed to get current team\",\n );\n case \"get_team_members\":\n return mcpList(\n (s) => s.teams.members(a.teamId),\n \"members\",\n \"Failed to get team members\",\n );\n\n // ─── Databases ─────────────────────────────────────────────────────\n case \"list_databases\":\n return mcpList(\n (s) => s.databases.list(),\n \"databases\",\n \"Failed to list databases\",\n );\n case \"get_database\":\n return mcpCall(\n (s) => s.databases.get(a.uuid).then((db) => ({ database: db })),\n \"Failed to get database\",\n );\n case \"create_database\":\n return mcpCall(\n (s) =>\n s.databases.create(a.dbType, a.data).then((r) => ({\n message: `${a.dbType} database created`,\n uuid: r.uuid,\n })),\n \"Failed to create database\",\n );\n case \"delete_database\":\n return mcpCall(\n (s) =>\n s.databases\n .delete(a.uuid)\n .then(() => ({ message: \"Database deleted\" })),\n \"Failed to delete database\",\n );\n case \"start_database\":\n return mcpCall(\n (s) =>\n s.databases\n .start(a.uuid)\n .then(() => ({ message: \"Database started\" })),\n \"Failed to start database\",\n );\n case \"stop_database\":\n return mcpCall(\n (s) =>\n s.databases\n .stop(a.uuid)\n .then(() => ({ message: \"Database stopped\" })),\n \"Failed to stop database\",\n );\n case \"restart_database\":\n return mcpCall(\n (s) =>\n s.databases\n .restart(a.uuid)\n .then(() => ({ message: \"Database restarted\" })),\n \"Failed to restart database\",\n );\n\n // ─── Services ──────────────────────────────────────────────────────\n case \"list_services\":\n return mcpList(\n (s) => s.services.list(),\n \"services\",\n \"Failed to list services\",\n );\n case \"get_service\":\n return mcpCall(\n (s) => s.services.get(a.uuid).then((svc) => ({ service: svc })),\n \"Failed to get service\",\n );\n case \"start_service\":\n return mcpCall(\n (s) =>\n s.services.start(a.uuid).then(() => ({ message: \"Service started\" })),\n \"Failed to start service\",\n );\n case \"stop_service\":\n return mcpCall(\n (s) =>\n s.services.stop(a.uuid).then(() => ({ message: \"Service stopped\" })),\n \"Failed to stop service\",\n );\n case \"restart_service\":\n return mcpCall(\n (s) =>\n s.services\n .restart(a.uuid)\n .then(() => ({ message: \"Service restarted\" })),\n \"Failed to restart service\",\n );\n case \"delete_service\":\n return mcpCall(\n (s) =>\n s.services\n .delete(a.uuid)\n .then(() => ({ message: \"Service deleted\" })),\n \"Failed to delete service\",\n );\n\n // ─── Private Keys ──────────────────────────────────────────────────\n case \"list_private_keys\":\n return mcpList(\n (s) => s.keys.list(),\n \"keys\",\n \"Failed to list private keys\",\n );\n case \"get_private_key\":\n return mcpCall(\n (s) => s.keys.get(a.uuid).then((k) => ({ privateKey: k })),\n \"Failed to get private key\",\n );\n\n // ─── Smart Resolution ──────────────────────────────────────────────\n case \"resolve_application\":\n return mcpCall(\n (s) =>\n s.applications.resolve(a.query).then((app) => ({\n application: {\n uuid: app.uuid,\n name: app.name,\n status: app.status,\n fqdn: app.fqdn,\n },\n })),\n \"Failed to resolve application\",\n );\n case \"resolve_server\":\n return mcpCall(\n (s) =>\n s.servers.resolve(a.query).then((srv) => ({\n server: {\n uuid: srv.uuid,\n name: srv.name,\n ip: srv.ip,\n is_reachable: srv.is_reachable,\n },\n })),\n \"Failed to resolve server\",\n );\n\n // ─── Diagnostics ───────────────────────────────────────────────────\n case \"diagnose_application\":\n return mcpCall((s) => s.diagnose.app(a.query), \"Diagnosis failed\");\n case \"diagnose_server\":\n return mcpCall((s) => s.diagnose.server(a.query), \"Diagnosis failed\");\n case \"find_infrastructure_issues\":\n return mcpCall(\n (s) => s.diagnose.infrastructure(),\n \"Infrastructure scan failed\",\n );\n\n // ─── Batch Operations ──────────────────────────────────────────────\n case \"restart_project_apps\":\n return mcpCall(\n (s) => s.batch.restartProject(a.projectUuid),\n \"Batch restart failed\",\n );\n case \"redeploy_project_apps\":\n return mcpCall(\n (s) => s.batch.redeployProject(a.projectUuid, a.force),\n \"Batch redeploy failed\",\n );\n case \"stop_all_apps\":\n return mcpCall((s) => s.batch.stopAll(), \"Stop all failed\");\n\n // ─── Network Diagnostics ─────────────────────────────────────────\n case \"inspect_network\":\n return mcpCall(\n (s) => s.network.inspect(a.uuid, a.servicesToTest),\n \"Network inspection failed\",\n );\n case \"analyze_deploy_failure\":\n return mcpCall(\n (s) => s.diagnose.deployFailure(a.deploymentUuid),\n \"Deploy analysis failed\",\n );\n\n // ─── Version / Health ──────────────────────────────────────────────\n case \"get_version\":\n return mcpCall(\n (s) => s.version().then((v) => ({ version: v.version })),\n \"Failed to get version\",\n );\n case \"health_check\":\n return mcpCall(\n (s) =>\n s.servers.list().then(() => ({\n status: \"healthy\",\n message: \"Coolify API is accessible\",\n })),\n \"Health check failed\",\n );\n case \"get_resource_usage\":\n return mcpCall(\n (s) =>\n s.applications\n .resolve(a.uuid)\n .then((app) => ({ status: app.status })),\n \"Failed to get resource usage\",\n );\n\n default:\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n}\n","/**\n * Operation tracing system.\n *\n * Provides step-by-step tracing for all operations across CLI, MCP, and SDK.\n * - **CLI mode**: Logs to stderr with chalk colors (no spinners in trace)\n * - **MCP mode**: Collects steps silently, returns in response\n * - **SDK mode**: Fires callback if provided, otherwise collects\n *\n * @module\n */\n\n/**\n * A single trace step.\n */\nexport interface ITraceStep {\n /** Timestamp */\n ts: string;\n /** Step label */\n step: string;\n /** Duration in ms (filled after completion) */\n durationMs?: number;\n /** Optional detail */\n detail?: string;\n}\n\n/**\n * Complete operation trace.\n */\nexport interface IOperationTrace {\n /** Operation name */\n operation: string;\n /** All steps */\n steps: ITraceStep[];\n /** Total duration */\n totalMs: number;\n /** Whether operation succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Callback for real-time trace updates.\n */\nexport type TraceCallback = (step: string, detail?: string) => void;\n\n/** Detect if running as MCP server (stdout is the transport). */\nexport function isMcpMode(): boolean {\n // MCP servers communicate over stdout — if we're piped, assume MCP\n return !process.stdout.isTTY;\n}\n\n/**\n * Operation tracer that collects steps.\n */\nexport class OperationTracer {\n private steps: ITraceStep[] = [];\n private startTime: number;\n private stepStart: number;\n private onStep?: TraceCallback;\n\n constructor(\n public readonly operation: string,\n onStep?: TraceCallback,\n ) {\n this.startTime = Date.now();\n this.stepStart = this.startTime;\n this.onStep = onStep;\n }\n\n /**\n * Records a trace step.\n *\n * @param step - Step description\n * @param detail - Optional detail\n */\n step(step: string, detail?: string): void {\n const now = Date.now();\n const traceStep: ITraceStep = {\n ts: new Date(now).toISOString(),\n step,\n durationMs: now - this.stepStart,\n detail,\n };\n this.steps.push(traceStep);\n this.stepStart = now;\n\n // Fire callback for real-time updates\n this.onStep?.(step, detail);\n\n // In TTY (CLI) mode, log to stderr so it doesn't pollute MCP stdout\n if (process.stderr.isTTY) {\n const prefix = `\\x1b[90m[${this.operation}]\\x1b[0m`;\n const elapsed = `\\x1b[33m${traceStep.durationMs}ms\\x1b[0m`;\n const detailStr = detail ? ` \\x1b[90m(${detail})\\x1b[0m` : \"\";\n process.stderr.write(`${prefix} ${step} ${elapsed}${detailStr}\\n`);\n }\n }\n\n /**\n * Finalizes the trace.\n *\n * @param success - Whether operation succeeded\n * @param error - Error message if failed\n * @returns Complete operation trace\n */\n finish(success: boolean, error?: string): IOperationTrace {\n return {\n operation: this.operation,\n steps: this.steps,\n totalMs: Date.now() - this.startTime,\n success,\n error,\n };\n }\n}\n","/**\n * Network diagnostic module.\n *\n * Uses exec to inspect Docker networks, Traefik proxy, DNS, and container connectivity.\n * All commands run inside the application container via the Coolify exec API.\n *\n * @module\n */\n\nimport { isErr, type Result, ok, err } from \"@mks2508/no-throw\";\nimport type { CoolifyService } from \"./coolify/index.js\";\nimport { OperationTracer, type IOperationTrace } from \"./trace.js\";\n\n/**\n * Container network information.\n */\nexport interface INetworkInfo {\n /** /etc/hosts entries */\n hosts: string[];\n /** DNS resolution results */\n dns: Array<{ hostname: string; resolved: boolean; ip?: string }>;\n /** Container environment variables related to networking */\n networkEnv: Record<string, string>;\n /** Reachable services (connectivity test results) */\n connectivity: Array<{\n target: string;\n reachable: boolean;\n responseTime?: number;\n }>;\n /** Container's network interfaces */\n interfaces: string[];\n /** Operation trace */\n trace: IOperationTrace;\n}\n\n/**\n * Deploy failure analysis.\n */\nexport interface IDeployFailureAnalysis {\n /** Deployment UUID */\n deploymentUuid: string;\n /** Deployment status */\n status: string;\n /** Raw build logs */\n rawLogs: string;\n /** Extracted error lines */\n errors: string[];\n /** Likely error category */\n category:\n | \"build_error\"\n | \"install_error\"\n | \"docker_error\"\n | \"network_error\"\n | \"timeout\"\n | \"unknown\";\n /** Human-readable summary */\n summary: string;\n /** Suggested fix */\n suggestion: string;\n /** Operation trace */\n trace: IOperationTrace;\n}\n\n/** Common error patterns in build logs. */\nconst ERROR_PATTERNS: Array<{\n pattern: RegExp;\n category: IDeployFailureAnalysis[\"category\"];\n summary: string;\n suggestion: string;\n}> = [\n {\n pattern: /npm ERR!|yarn error|pnpm ERR/i,\n category: \"install_error\",\n summary: \"Package installation failed\",\n suggestion:\n \"Check package.json for invalid dependencies. Try deleting lock file and rebuilding.\",\n },\n {\n pattern: /COPY failed|COPY --from.*not found|no such file/i,\n category: \"docker_error\",\n summary: \"Dockerfile COPY failed — file not found\",\n suggestion:\n \"Check Dockerfile paths and base_directory. Ensure source files exist in build context.\",\n },\n {\n pattern: /error TS\\d+|TypeError|SyntaxError|ReferenceError/i,\n category: \"build_error\",\n summary: \"TypeScript/JavaScript compilation error\",\n suggestion:\n \"Fix the type errors locally before deploying. Run `bun run typecheck`.\",\n },\n {\n pattern: /ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|getaddrinfo/i,\n category: \"network_error\",\n summary: \"Network connectivity issue during build\",\n suggestion:\n \"Server may have DNS issues or firewall blocking outbound connections. Check server network.\",\n },\n {\n pattern: /OOMKilled|out of memory|Cannot allocate memory/i,\n category: \"build_error\",\n summary: \"Out of memory during build\",\n suggestion:\n \"Server ran out of RAM. Use a build server or increase server memory.\",\n },\n {\n pattern: /context deadline exceeded|timed out/i,\n category: \"timeout\",\n summary: \"Operation timed out\",\n suggestion:\n \"Build took too long. Check if server is overloaded or network is slow.\",\n },\n {\n pattern: /permission denied|EACCES/i,\n category: \"docker_error\",\n summary: \"Permission denied\",\n suggestion:\n \"Check file permissions in Dockerfile. Ensure non-root user has access to needed paths.\",\n },\n {\n pattern: /exec.*not found|command not found/i,\n category: \"build_error\",\n summary: \"Command not found during build\",\n suggestion:\n \"A required binary is missing in the Docker image. Add it to the Dockerfile or use a different base image.\",\n },\n];\n\n/**\n * Safely execute a command, returning output or empty string on failure.\n */\nasync function safeExec(\n svc: CoolifyService,\n uuid: string,\n command: string,\n): Promise<string> {\n const result = await svc.executeCommand(uuid, command);\n if (isErr(result)) return \"\";\n return result.value.response || result.value.message || \"\";\n}\n\n/**\n * Inspects the network environment of an application container.\n *\n * @param svc - CoolifyService instance\n * @param appUuid - Application UUID\n * @param servicesToTest - Optional list of service names to test connectivity (e.g., ['db', 'redis'])\n * @returns Network diagnostic information\n */\nexport async function inspectNetwork(\n svc: CoolifyService,\n appUuid: string,\n servicesToTest: string[] = [],\n): Promise<Result<INetworkInfo, Error>> {\n const tracer = new OperationTracer(\"network:inspect\");\n\n try {\n tracer.step(\"Fetching /etc/hosts\");\n const hostsRaw = await safeExec(svc, appUuid, \"cat /etc/hosts 2>/dev/null\");\n const hosts = hostsRaw\n .split(\"\\n\")\n .filter((l) => l.trim() && !l.startsWith(\"#\"));\n\n tracer.step(\"Checking network interfaces\");\n const ifRaw = await safeExec(\n svc,\n appUuid,\n \"ip addr 2>/dev/null || ifconfig 2>/dev/null || cat /proc/net/if_inet6 2>/dev/null || echo 'no network tools'\",\n );\n const interfaces = ifRaw\n .split(\"\\n\")\n .filter((l) => l.includes(\"inet\") || l.includes(\"scope\"));\n\n tracer.step(\"Extracting network env vars\");\n const envRaw = await safeExec(\n svc,\n appUuid,\n \"env 2>/dev/null | grep -iE '(HOST|PORT|URL|DATABASE|REDIS|MONGO|POSTGRES|MYSQL|DB_|COOLIFY)' | sort\",\n );\n const networkEnv: Record<string, string> = {};\n for (const line of envRaw.split(\"\\n\").filter(Boolean)) {\n const [key, ...rest] = line.split(\"=\");\n if (key) networkEnv[key] = rest.join(\"=\");\n }\n\n tracer.step(\"Testing DNS resolution\");\n const dnsTargets = [\n ...servicesToTest,\n ...Object.values(networkEnv)\n .filter((v) => !v.includes(\"/\") && !v.includes(\":\"))\n .filter((v) => /^[a-z][a-z0-9-]*$/i.test(v)),\n ];\n const uniqueTargets = [...new Set(dnsTargets)].slice(0, 10);\n\n const dns: INetworkInfo[\"dns\"] = [];\n for (const hostname of uniqueTargets) {\n const nslookup = await safeExec(\n svc,\n appUuid,\n `getent hosts ${hostname} 2>/dev/null || nslookup ${hostname} 2>/dev/null || echo 'FAIL'`,\n );\n const resolved = !nslookup.includes(\"FAIL\") && nslookup.trim().length > 0;\n const ip = resolved ? nslookup.split(/\\s+/)[0] : undefined;\n dns.push({ hostname, resolved, ip });\n }\n\n tracer.step(\n \"Testing service connectivity\",\n `${uniqueTargets.length} targets`,\n );\n const connectivity: INetworkInfo[\"connectivity\"] = [];\n for (const target of servicesToTest) {\n const start = Date.now();\n const curlResult = await safeExec(\n svc,\n appUuid,\n `timeout 3 sh -c \"echo > /dev/tcp/${target}/80 2>/dev/null && echo OK || curl -sf --max-time 2 http://${target}/ >/dev/null 2>&1 && echo OK || echo FAIL\"`,\n );\n connectivity.push({\n target,\n reachable: curlResult.includes(\"OK\"),\n responseTime: Date.now() - start,\n });\n }\n\n const trace = tracer.finish(true);\n return ok({ hosts, dns, networkEnv, connectivity, interfaces, trace });\n } catch (error) {\n const trace = tracer.finish(\n false,\n error instanceof Error ? error.message : String(error),\n );\n return err(new Error(`Network inspection failed: ${trace.error}`));\n }\n}\n\n/**\n * Analyzes a failed deployment, extracting errors from build logs.\n *\n * @param svc - CoolifyService instance\n * @param deploymentUuid - Deployment UUID\n * @returns Failure analysis with categorized errors\n */\nexport async function analyzeDeployFailure(\n svc: CoolifyService,\n deploymentUuid: string,\n): Promise<Result<IDeployFailureAnalysis, Error>> {\n const tracer = new OperationTracer(\"deploy:analyze\");\n\n try {\n tracer.step(\"Fetching deployment details\");\n const deployResult = await svc.getDeploymentLogs(deploymentUuid);\n if (isErr(deployResult)) {\n return err(deployResult.error);\n }\n\n const { status, logs: rawLogs } = deployResult.value;\n\n tracer.step(\"Extracting error lines\", `${rawLogs.length} chars`);\n const lines = rawLogs.split(\"\\n\");\n const errors = lines.filter(\n (l) =>\n /error|ERR!|failed|FAIL|fatal|panic|exception/i.test(l) &&\n !/no error|success/i.test(l),\n );\n\n tracer.step(\"Categorizing error\");\n let matchedPattern = ERROR_PATTERNS.find((p) => p.pattern.test(rawLogs));\n\n if (!matchedPattern) {\n matchedPattern = {\n pattern: /./,\n category: \"unknown\",\n summary: \"Unknown build failure\",\n suggestion:\n \"Check the full build logs with `build-logs <deployment-uuid>` for details.\",\n };\n }\n\n const trace = tracer.finish(true);\n return ok({\n deploymentUuid,\n status,\n rawLogs,\n errors: errors.slice(0, 20),\n category: matchedPattern.category,\n summary: matchedPattern.summary,\n suggestion: matchedPattern.suggestion,\n trace,\n });\n } catch (error) {\n const trace = tracer.finish(\n false,\n error instanceof Error ? error.message : String(error),\n );\n return err(new Error(`Deploy analysis failed: ${trace.error}`));\n }\n}\n","/**\n * .coolify.json state loader for CLI.\n *\n * When running CLI commands from a project directory that has a .coolify.json\n * (generated by create-bunspace or first deploy), reads the state to auto-fill\n * UUIDs so users don't need to copy-paste them.\n *\n * @module\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * State stored in .coolify.json (generated by create-bunspace deployer).\n */\nexport interface ICoolifyDeployState {\n /** Application UUID in Coolify */\n appUuid: string;\n /** Server UUID */\n serverUuid: string;\n /** Project UUID */\n projectUuid: string;\n /** Environment UUID */\n environmentUuid: string;\n /** Domain if configured */\n domain?: string;\n /** Docker compose or Dockerfile path */\n dockerComposePath?: string;\n /** Base directory for build context */\n baseDirectory?: string;\n /** Git branch */\n branch?: string;\n /** Application type */\n type?: string;\n /** Build pack */\n buildPack?: string;\n /** Auto-deploy enabled */\n autoDeployEnabled?: boolean;\n}\n\nconst STATE_FILE = \".coolify.json\";\n\n/**\n * Loads .coolify.json from the current working directory.\n *\n * @returns The deploy state if found, null otherwise\n */\nexport function loadCoolifyState(): ICoolifyDeployState | null {\n const statePath = join(process.cwd(), STATE_FILE);\n\n if (!existsSync(statePath)) {\n return null;\n }\n\n try {\n const content = readFileSync(statePath, \"utf-8\");\n const state = JSON.parse(content) as ICoolifyDeployState;\n\n if (!state.appUuid) {\n return null;\n }\n\n return state;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves a UUID argument — if not provided, tries to read from .coolify.json.\n *\n * @param uuid - UUID from CLI argument (may be undefined)\n * @param field - Which field to read from .coolify.json (default: appUuid)\n * @returns The resolved UUID or null if not found\n */\nexport function resolveUuid(\n uuid: string | undefined,\n field: keyof ICoolifyDeployState = \"appUuid\",\n): string | null {\n if (uuid) return uuid;\n\n const state = loadCoolifyState();\n if (!state) return null;\n\n const value = state[field];\n return typeof value === \"string\" ? value : null;\n}\n","/**\n * @mks2508/coolify-mks-cli-mcp — SDK, CLI, and MCP server for Coolify.\n *\n * Use as a library (SDK):\n * ```typescript\n * import { Coolify } from '@mks2508/coolify-mks-cli-mcp'\n *\n * const coolify = new Coolify({ url: 'https://coolify.example.com', token: '...' })\n * const apps = await coolify.applications.list()\n * const app = await coolify.applications.resolve('my-app')\n * await coolify.applications.deploy(app.uuid)\n * ```\n *\n * Use as MCP server:\n * ```bash\n * coolify-mcp-server # stdio transport\n * ```\n *\n * Use as CLI:\n * ```bash\n * coolify-mcp list\n * coolify-mcp deploy\n * coolify-mcp logs\n * ```\n *\n * @module\n */\n\n// ─── SDK: Coolify (primary export) ───────────────────────────────────────────\n\nexport { Coolify, type ICoolifyOptions } from \"./sdk.js\";\n\n// ─── Internal CoolifyService (for MCP/CLI, advanced usage) ──────────────────\n\nexport {\n CoolifyService,\n getCoolifyService,\n type ICoolifyEnvVar,\n} from \"./coolify/index.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type {\n ICoolifyServer,\n ICoolifyServerResource,\n ICoolifyServerDomain,\n ICoolifyDestination,\n ICoolifyProject,\n ICoolifyTeam,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyPrivateKey,\n ICoolifyDeployment,\n ICoolifyVersion,\n ICoolifyAppOptions,\n ICoolifyAppResult,\n ICoolifyDeployOptions,\n ICoolifyDeployResult,\n ICoolifyDeleteResult,\n ICoolifyUpdateOptions,\n ICoolifyLogsOptions,\n ICoolifyLogs,\n ICoolifyEnvironment,\n IProgressCallback,\n TCoolifyApplicationType,\n} from \"./coolify/types.js\";\n\n// ─── MCP Tools (for building custom MCP servers) ─────────────────────────────\n\nexport { coolifyTools } from \"./tools/definitions.js\";\nexport { handleToolCall } from \"./tools/handlers.js\";\n\n// ─── Network diagnostics + operation tracing ─────────────────────────────────\n\nexport { inspectNetwork, analyzeDeployFailure } from \"./network.js\";\nexport type { INetworkInfo, IDeployFailureAnalysis } from \"./network.js\";\nexport { OperationTracer, isMcpMode } from \"./trace.js\";\nexport type { ITraceStep, IOperationTrace, TraceCallback } from \"./trace.js\";\n\n// ─── .coolify.json state (for scaffolder integration) ────────────────────────\n\nexport {\n loadCoolifyState,\n resolveUuid,\n type ICoolifyDeployState,\n} from \"./cli/coolify-state.js\";\n"],"x_google_ignoreList":[0,1,2,3,4],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,GAAG,OAAO;AAClB,QAAO;EACN,IAAI;EACJ;CACA;AACD;;;;;;;;;;;;;;;AAeD,SAAS,IAAI,OAAO;AACnB,QAAO;EACN,IAAI;EACJ;CACA;AACD;;;;;;;;;;;;;;;;;;;AAwCD,SAAS,MAAM,QAAQ;AACtB,SAAQ,OAAO;AACf;;;;;AClFD,SAAS,eAAe,UAAU;CAChC,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;EAEA;EAEA;EACA;EACA;EACA;CACD;AACD,QAAO,iBAAiB,KAAK,CAAC,YAAY,QAAQ,KAAK,SAAS,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O;EACR;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;EACV;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GACP,SAAS;EACV;EACD,SAAS;GACP,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,UAAU;GACR,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,OAAO;EACR;EACD,UAAU;EACV,cAAc;CACf;CAID,SAAS;EACP,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW,EACT,MAAM,MAEP;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;GACT,QAAQ;GACR,YAAY;EACb;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GACP,SAAS;GACT,QAAQ;GACR,YAAY;EACb;EACD,SAAS;GACP,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,UAAU,EACR,MAAM,MAEP;CACF;CAID,OAAO;EACL,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW;GACT,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;GACT,MAAM;GACN,MAAM;EACP;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GACP,SAAS;GACT,MAAM;GACN,MAAM;EACP;EACD,SAAS;GACP,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,UAAU;GACR,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,OAAO;EACR;CACF;CAID,YAAY;EACV,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW;GACT,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;EACV;EACD,QAAQ,EACN,MAAM,MAEP;EACD,SAAS;GACP,M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;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACb,sBAAsB,EAAE,MAAM,SAAmB;IAClD;GACF;GACD,UAAU,CAAC,QAAQ,SAAU;EAC9B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,QAAQ;KACN,MAAM;KACN,aAAa;IACd;IACD,WAAW;KACT,MAAM;KACN,aAAa;IACd;GACF;EACF;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aACE;IACH;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,OAAO;KACL,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,WAAW;KACT,MAAM;KACN,aAAa;KACb,MAAM;MAAC;MAAc;MAAY;MAAU;KAAgB;IAC5D;IACD,WAAW;KACT,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,gBAAgB;KACd,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,SAAS;KACP,MAAM;KACN,aACE;IACH;IACD,qBAAqB;KACnB,MAAM;KACN,aAAa;IACd;IACD,qBAAqB;KACnB,MAAM;KACN,aAAa;IACd;IACD,oBAAoB;KAClB,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;IACD,sBAAsB;KACpB,MAAM;KACN,aACE;IACH;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;;;;;EAQd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,SAAS;KACP,MAAM;KACN,aACE;IACH;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACb,SAAS;IACV;GACF;GACD,UAAU,CAAC,QAAQ,SAAU;EAC9B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,iBAAiB;KACf,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,eAAe;KACb,MAAM;KACN,aACE;IACH;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACb,SAAS;IACV;IACD,WAAW;KACT,MAAM;KACN,aAAa;KACb,MAAM;MAAC;MAAc;MAAY;MAAU;KAAgB;KAC3D,SAAS;IACV;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,MAAM;MACJ;MACA;MACA;MACA;MACA;MACA;KACD;KACD,SAAS;IACV;IACD,uBAAuB;KACrB,MAAM;KACN,aACE;IACH;IACD,oBAAoB;KAClB,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aACE;IACH;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,QAAQ,YAAa;EACjC;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,gBAAgB;IACd,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,gBAAiB;EAC7B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,SAAS;IACV;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,SAAS;IACV;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,M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AAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,gBAAgB;IACd,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,gBAAiB;EAC7B;CACF;CAKD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,QAAQ;IACN,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,QAAS;EACrB;CACF;CAKD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CAKD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,aAAa;IACX,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,aAAc;EAC1B;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY;IACV,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACb,SAAS;IACV;GACF;GACD,UAAU,CAAC,aAAc;EAC1B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;;;EAKd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,gBAAgB;KACd,MAAM;KACN,aACE;KACF,OAAO,EAAE,MAAM,SAAmB;IACnC;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;;EAKd,aAAa;GACX,MAAM;GACN,YAAY,EACV,gBAAgB;IACd,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,gBAAiB;EAC7B;CACF;AACF;;;;;ACnqCD,IAAIC,OAAuB;AAC3B,SAAS,SAAkB;AACzB,MAAK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O;AAGT,KAAI;EACF,MAAM,UAAU,0BAAa,WAAW,QAAQ;EAChD,MAAM,QAAQ,KAAK,MAAM,QAAQ;AAEjC,OAAK,MAAM,QACT,QAAO;AAGT,SAAO;CACR,QAAO;AACN,SAAO;CACR;AACF;;;;;;;;AASD,SAAgB,YACdC,MACAC,QAAmC,WACpB;AACf,KAAI,KAAM,QAAO;CAEjB,MAAM,QAAQ,kBAAkB;AAChC,MAAK,MAAO,QAAO;CAEnB,MAAM,QAAQ,MAAM;AACpB,eAAc,UAAU,WAAW,QAAQ;AAC5C;;;;ACXD,cAAoE;AAEpE,YAAwD"}
1
+ {"version":3,"file":"index.cjs","names":["DEFAULT_CONFIG","DEFAULT_CONFIG","err","index","DEFAULT_CONFIG$1","endpoint: string","options: RequestInit","data: T | undefined","options: ICoolifyDeployOptions","onProgress?: IProgressCallback","options: ICoolifyAppOptions","endpointMap: Record<string, string>","body: Record<string, unknown>","appUuid: string","envVars: Record<string, string>","key: string","value: string","isBuildTime: boolean","page?: number","perPage?: number","serverUuid: string","name: string","description?: string","projectUuid: string","teamId?: string","projectId?: string","options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n }","options: ICoolifyUpdateOptions","options: ICoolifyLogsOptions","logsArray: string[]","l: string","command: string","envVars: Array<{\n key: string;\n value: string;\n is_preview?: boolean;\n }>","options?: { force?: boolean; instantDeploy?: boolean }","uuid: string","dbType: string","data: Record<string, unknown>","databaseUuid: string","backupUuid: string","projectNodes: ICoolifyProjectNode[]","resource: ICoolifyResource","data: { key: string; value: string; is_preview?: boolean }","data: { name?: string; description?: string }","data: { name: string; description?: string }","id: number","deploymentUuid: string","data: {\n name: string;\n private_key: string;\n description?: string;\n }","data: { name?: string; private_key?: string; description?: string }","skip: number","take: number","query: string","apps","issues: string[]","issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }>","failed: string[]","force: boolean","instance: CoolifyService | null","result: Result<T, Error>","svc: CoolifyService","options?: { teamId?: string; projectId?: string } & IPaginationOptions","query: string","options: ICoolifyAppOptions","onProgress?: IProgressCallback","uuid: string","options?: { force?: boolean; tag?: string }","options?: { force?: boolean; instantDeploy?: boolean }","options?: IDeleteOptions","options: ICoolifyUpdateOptions","options?: ICoolifyLogsOptions","skip?: number","take?: number","command: string","key: string","value: string","isBuildTime?: boolean","vars: Array<{ key: string; value: string; is_preview?: boolean }>","options: {\n /** Path to .env file (default: reads from .env in cwd) */\n filePath?: string;\n /** Preview changes without applying */\n dryRun?: boolean;\n /** Delete vars not in file */\n prune?: boolean;\n /** Callback for progress updates (optional) */\n onProgress?: (update: {\n type: 'add' | 'update' | 'remove';\n key: string;\n value?: string;\n }) => void;\n }","envContent: string","toAdd: Array<{ key: string; value: string }>","toUpdate: Array<{\n key: string;\n value: string;\n oldValue: string;\n }>","toRemove: string[]","content: string","options?: IPaginationOptions","type: string","data: Record<string, unknown>","dbUuid: string","backupUuid: string","data: { key: string; value: string; is_preview?: boolean }","name: string","description?: string","data: { name?: string; description?: string }","projectUuid: string","data: { name: string; description?: string }","id: number","teamId: number","data: {\n name: string;\n private_key: string;\n description?: string;\n }","data: { name?: string; private_key?: string; description?: string }","deploymentUuid: string","appUuid: string","servicesToTest?: string[]","force?: boolean","options?: ICoolifyOptions","resource: T","coolifyTools: Tool[]","_sdk: Coolify | null","fn: (sdk: Coolify) => Promise<unknown>","label: string","fn: (sdk: Coolify) => Promise<unknown[]>","itemKey: string","name: string","args: Record<string, unknown>","d: string","operation: string","onStep?: TraceCallback","step: string","detail?: string","traceStep: ITraceStep","success: boolean","error?: string","svc: CoolifyService","uuid: string","command: string","appUuid: string","servicesToTest: string[]","networkEnv: Record<string, string>","dns: INetworkInfo[\"dns\"]","connectivity: INetworkInfo[\"connectivity\"]","deploymentUuid: string","ERROR_PATTERNS: Array<{\n pattern: RegExp;\n category: IDeployFailureAnalysis[\"category\"];\n summary: string;\n suggestion: string;\n}>","uuid: string | undefined","field: keyof ICoolifyDeployState"],"sources":["../../../../node_modules/.bun/@mks2508+no-throw@0.1.0/node_modules/@mks2508/no-throw/dist/index.mjs","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/environment-COWvu6Wz.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/Logger-D-gmmgR2.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/chunks/formatting-CYjT9yhO.js","../../../../node_modules/.bun/@mks2508+better-logger@4.0.0/node_modules/@mks2508/better-logger/dist/index.js","../src/coolify/config.ts","../src/coolify/index.ts","../src/sdk.ts","../src/tools/definitions.ts","../src/tools/handlers.ts","../src/trace.ts","../src/network.ts","../src/cli/coolify-state.ts","../src/index.ts"],"sourcesContent":["//#region src/result.ts\n/**\n* Creates a successful Result containing the given value.\n*\n* @template T - The type of the success value\n* @param value - The value to wrap in an Ok\n* @returns An Ok containing the value\n*\n* @example\n* ```typescript\n* const result = ok(42)\n* // result.ok === true\n* // result.value === 42\n* ```\n*/\nfunction ok(value) {\n\treturn {\n\t\tok: true,\n\t\tvalue\n\t};\n}\n/**\n* Creates a failed Result containing the given error.\n*\n* @template E - The type of the error value\n* @param error - The error to wrap in an Err\n* @returns An Err containing the error\n*\n* @example\n* ```typescript\n* const result = err('Something went wrong')\n* // result.ok === false\n* // result.error === 'Something went wrong'\n* ```\n*/\nfunction err(error) {\n\treturn {\n\t\tok: false,\n\t\terror\n\t};\n}\n/**\n* Type guard that narrows a Result to Ok.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to check\n* @returns `true` if the Result is Ok, enabling type narrowing\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = ok(42)\n*\n* if (isOk(result)) {\n* // TypeScript knows result.value exists here\n* console.log(result.value)\n* }\n* ```\n*/\nfunction isOk(result) {\n\treturn result.ok;\n}\n/**\n* Type guard that narrows a Result to Err.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to check\n* @returns `true` if the Result is Err, enabling type narrowing\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = err('failed')\n*\n* if (isErr(result)) {\n* // TypeScript knows result.error exists here\n* console.error(result.error)\n* }\n* ```\n*/\nfunction isErr(result) {\n\treturn !result.ok;\n}\n/**\n* Extracts the value from an Ok Result or throws an error if Err.\n*\n* **Warning**: This function throws. Prefer `unwrapOr`, `unwrapOrElse`, or `match`\n* for safer error handling.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @returns The contained value if Ok\n* @throws Error with message from ResultError or stringified error if Err\n*\n* @example\n* ```typescript\n* const success = ok(42)\n* unwrap(success) // Returns 42\n*\n* const failure = err('oops')\n* unwrap(failure) // Throws Error: 'Unwrap called on Err: oops'\n* ```\n*/\nfunction unwrap(result) {\n\tif (isOk(result)) return result.value;\n\tconst errMsg = result.error instanceof Object && \"message\" in result.error ? result.error.message : String(result.error);\n\tthrow new Error(`Unwrap called on Err: ${errMsg}`);\n}\n/**\n* Extracts the value from an Ok Result or returns a default value if Err.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @param defaultValue - The value to return if the Result is Err\n* @returns The contained value if Ok, otherwise the default value\n*\n* @example\n* ```typescript\n* unwrapOr(ok(42), 0) // Returns 42\n* unwrapOr(err('oops'), 0) // Returns 0\n* ```\n*/\nfunction unwrapOr(result, defaultValue) {\n\treturn isOk(result) ? result.value : defaultValue;\n}\n/**\n* Extracts the value from an Ok Result or computes a value from the error if Err.\n*\n* Unlike `unwrapOr`, the default value is lazily computed only when needed.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to unwrap\n* @param fn - Function to compute the default value from the error\n* @returns The contained value if Ok, otherwise the computed value\n*\n* @example\n* ```typescript\n* unwrapOrElse(ok(42), () => 0) // Returns 42\n* unwrapOrElse(err('error'), (e) => e.length) // Returns 5\n* unwrapOrElse(err('not found'), () => fetchDefault()) // Only fetches on error\n* ```\n*/\nfunction unwrapOrElse(result, fn) {\n\treturn isOk(result) ? result.value : fn(result.error);\n}\n/**\n* Transforms the Ok value using the provided function, leaving Err unchanged.\n*\n* This is the functor map operation for Result, allowing you to transform\n* success values while automatically propagating errors.\n*\n* @template T - The type of the input success value\n* @template U - The type of the output success value\n* @template E - The type of the error value\n* @param result - The Result to transform\n* @param fn - Function to apply to the Ok value\n* @returns A new Result with the transformed value, or the original Err\n*\n* @example\n* ```typescript\n* map(ok(2), x => x * 2) // ok(4)\n* map(err('oops'), x => x * 2) // err('oops')\n*\n* // Chaining transformations\n* const result = ok('hello')\n* const upper = map(result, s => s.toUpperCase())\n* const length = map(upper, s => s.length)\n* // length = ok(5)\n* ```\n*/\nfunction map(result, fn) {\n\treturn isOk(result) ? ok(fn(result.value)) : result;\n}\n/**\n* Transforms the Err value using the provided function, leaving Ok unchanged.\n*\n* Useful for converting error types or adding context to errors.\n*\n* @template T - The type of the success value\n* @template E - The type of the input error value\n* @template F - The type of the output error value\n* @param result - The Result to transform\n* @param fn - Function to apply to the Err value\n* @returns A new Result with the transformed error, or the original Ok\n*\n* @example\n* ```typescript\n* mapErr(err('oops'), e => e.toUpperCase()) // err('OOPS')\n* mapErr(ok(42), e => e.toUpperCase()) // ok(42)\n*\n* // Converting error types\n* const result = err('not found')\n* const typed = mapErr(result, msg => ({ code: 'NOT_FOUND', message: msg }))\n* ```\n*/\nfunction mapErr(result, fn) {\n\treturn isErr(result) ? err(fn(result.error)) : result;\n}\n/**\n* Chains a function that returns a Result over the Ok value (monadic bind).\n*\n* Unlike `map`, the function returns a Result, which is then flattened.\n* This enables composing operations that may fail.\n*\n* @template T - The type of the input success value\n* @template U - The type of the output success value\n* @template E - The type of the error value\n* @param result - The Result to chain\n* @param fn - Function that takes the Ok value and returns a new Result\n* @returns The Result from fn if input is Ok, otherwise the original Err\n*\n* @example\n* ```typescript\n* const parseNumber = (s: string): Result<number, string> => {\n* const n = parseInt(s, 10)\n* return isNaN(n) ? err('not a number') : ok(n)\n* }\n*\n* const divide = (a: number, b: number): Result<number, string> =>\n* b === 0 ? err('division by zero') : ok(a / b)\n*\n* // Chain operations that may fail\n* const result = flatMap(parseNumber('10'), n => divide(n, 2))\n* // result = ok(5)\n*\n* const failed = flatMap(parseNumber('abc'), n => divide(n, 2))\n* // failed = err('not a number')\n* ```\n*/\nfunction flatMap(result, fn) {\n\treturn isOk(result) ? fn(result.value) : result;\n}\n/**\n* Executes a side effect on the Ok value without changing the Result.\n*\n* Useful for logging, debugging, or other side effects in a pipeline.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to tap\n* @param fn - Side effect function to execute on Ok value\n* @returns The original Result unchanged\n*\n* @example\n* ```typescript\n* const result = ok(42)\n* const same = tap(result, v => console.log('Got:', v))\n* // Logs: 'Got: 42'\n* // same === result\n*\n* tap(err('oops'), v => console.log('Got:', v))\n* // Does not log anything\n* ```\n*/\nfunction tap(result, fn) {\n\tif (isOk(result)) fn(result.value);\n\treturn result;\n}\n/**\n* Executes a side effect on the Err value without changing the Result.\n*\n* Useful for logging errors or triggering error reporting.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @param result - The Result to tap\n* @param fn - Side effect function to execute on Err value\n* @returns The original Result unchanged\n*\n* @example\n* ```typescript\n* const result = err('oops')\n* const same = tapErr(result, e => console.error('Error:', e))\n* // Logs: 'Error: oops'\n* // same === result\n*\n* tapErr(ok(42), e => console.error('Error:', e))\n* // Does not log anything\n* ```\n*/\nfunction tapErr(result, fn) {\n\tif (isErr(result)) fn(result.error);\n\treturn result;\n}\n/**\n* Pattern matches on a Result, applying the appropriate handler function.\n*\n* Provides exhaustive handling of both Ok and Err cases, ensuring you\n* handle all possibilities.\n*\n* @template T - The type of the success value\n* @template E - The type of the error value\n* @template U - The type of the return value from both handlers\n* @param result - The Result to match on\n* @param handlers - Object containing `onOk` and `onErr` handler functions\n* @returns The return value from whichever handler was called\n*\n* @example\n* ```typescript\n* const result: Result<number, string> = ok(42)\n*\n* const message = match(result, {\n* onOk: (value) => `Success: ${value}`,\n* onErr: (error) => `Failed: ${error}`\n* })\n* // message = 'Success: 42'\n*\n* // Transforming to different types\n* const status = match(fetchResult, {\n* onOk: (data) => ({ status: 'loaded', data }),\n* onErr: (err) => ({ status: 'error', message: err.message })\n* })\n* ```\n*/\nfunction match(result, handlers) {\n\treturn isOk(result) ? handlers.onOk(result.value) : handlers.onErr(result.error);\n}\n/**\n* Collects an array of Results into a Result containing an array.\n*\n* If all Results are Ok, returns Ok with an array of all values.\n* If any Result is Err, returns the first Err encountered.\n*\n* @template T - The type of the success values\n* @template E - The type of the error value\n* @param results - Array of Results to collect\n* @returns Ok with array of values if all succeed, or first Err\n*\n* @example\n* ```typescript\n* collect([ok(1), ok(2), ok(3)])\n* // ok([1, 2, 3])\n*\n* collect([ok(1), err('first'), err('second')])\n* // err('first')\n*\n* collect([])\n* // ok([])\n*\n* // Useful for validating multiple fields\n* const validations = [\n* validateName(name),\n* validateEmail(email),\n* validateAge(age)\n* ]\n* const allValid = collect(validations)\n* ```\n*/\nfunction collect(results) {\n\tconst values = [];\n\tfor (const result of results) {\n\t\tif (isErr(result)) return result;\n\t\tvalues.push(result.value);\n\t}\n\treturn ok(values);\n}\nfunction all(...results) {\n\treturn collect(results);\n}\n\n//#endregion\n//#region src/error.ts\n/**\n* Creates a ResultError with the given code, message, and optional cause.\n*\n* @template C - The type of error code (inferred from the code parameter)\n* @param code - Unique error code identifying the type of error\n* @param message - Human-readable error message\n* @param cause - Optional original error that caused this error\n* @returns A new ResultError object\n*\n* @example\n* ```typescript\n* // Basic error\n* const error = resultError('NOT_FOUND', 'User not found')\n* // { code: 'NOT_FOUND', message: 'User not found' }\n*\n* // With cause\n* try {\n* await fetchUser(id)\n* } catch (e) {\n* const error = resultError('FETCH_FAILED', 'Could not fetch user', e as Error)\n* return err(error)\n* }\n*\n* // With typed error codes\n* const ApiError = {\n* NotFound: 'NOT_FOUND',\n* Timeout: 'TIMEOUT'\n* } as const\n*\n* const typedError = resultError(ApiError.NotFound, 'Resource not found')\n* // typedError.code is typed as 'NOT_FOUND'\n* ```\n*/\nfunction resultError(code, message, cause) {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\tcause\n\t};\n}\n/**\n* Default error code for unknown or unspecified errors.\n*\n* Use this when catching exceptions that don't map to a specific error code\n* in your domain.\n*\n* @example\n* ```typescript\n* import { tryCatch, UNKNOWN_ERROR } from '@mks2508/no-throw'\n*\n* const result = tryCatch(() => {\n* throw new Error('Unexpected!')\n* })\n*\n* if (isErr(result)) {\n* console.log(result.error.code) // 'UNKNOWN'\n* }\n*\n* // Or provide a specific code\n* const result2 = tryCatch(() => {\n* throw new Error('Unexpected!')\n* }, 'PARSING_ERROR')\n*\n* if (isErr(result2)) {\n* console.log(result2.error.code) // 'PARSING_ERROR'\n* }\n* ```\n*/\nconst UNKNOWN_ERROR = \"UNKNOWN\";\n\n//#endregion\n//#region src/utils.ts\n/**\n* @fileoverview Utility functions for exception wrapping and Result creation.\n* @module @mks2508/no-throw/utils\n*/\n/**\n* Creates a failure Result with a structured ResultError.\n*\n* This is a convenience function that combines `err()` and `resultError()`\n* for creating typed error Results in a single call.\n*\n* @template C - The type of error code (inferred from the code parameter)\n* @param code - Unique error code identifying the type of error\n* @param message - Human-readable error message\n* @param cause - Optional original error that caused this error\n* @returns An Err Result containing the ResultError\n*\n* @example\n* ```typescript\n* // Basic usage\n* function findUser(id: string): Result<User, ResultError<'NOT_FOUND'>> {\n* const user = db.get(id)\n* if (!user) {\n* return fail('NOT_FOUND', `User ${id} not found`)\n* }\n* return ok(user)\n* }\n*\n* // With error chaining\n* async function fetchData(url: string): Promise<Result<Data, ResultError>> {\n* try {\n* const response = await fetch(url)\n* if (!response.ok) {\n* return fail('HTTP_ERROR', `Request failed: ${response.status}`)\n* }\n* return ok(await response.json())\n* } catch (e) {\n* return fail('NETWORK_ERROR', 'Network request failed', e as Error)\n* }\n* }\n*\n* // With typed error codes\n* const UserError = {\n* NotFound: 'USER_NOT_FOUND',\n* InvalidEmail: 'INVALID_EMAIL',\n* Suspended: 'USER_SUSPENDED'\n* } as const\n*\n* type UserError = ResultError<ErrorCode<typeof UserError>>\n*\n* function validateUser(email: string): Result<void, UserError> {\n* if (!email.includes('@')) {\n* return fail(UserError.InvalidEmail, 'Email must contain @')\n* }\n* return ok(undefined)\n* }\n* ```\n*/\nfunction fail(code, message, cause) {\n\treturn err(resultError(code, message, cause));\n}\n/**\n* Converts a Promise that may reject into a Promise that resolves to a Result.\n*\n* This is useful for integrating with APIs that use exceptions for error handling,\n* wrapping them in the Result pattern.\n*\n* @template T - The type of the resolved value\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param promise - The Promise to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Promise that always resolves to a Result\n*\n* @example\n* ```typescript\n* // Basic usage with fetch\n* const result = await fromPromise(fetch('/api/users'))\n* if (isOk(result)) {\n* const response = result.value\n* }\n*\n* // With custom error code\n* const result = await fromPromise(\n* fetch('/api/users'),\n* 'NETWORK_ERROR'\n* )\n*\n* // Chaining with other Result operations\n* const users = await fromPromise(fetch('/api/users'))\n* .then(r => flatMap(r, async response => {\n* if (!response.ok) return fail('HTTP_ERROR', `Status: ${response.status}`)\n* return fromPromise(response.json(), 'PARSE_ERROR')\n* }))\n*\n* // Comparing approaches\n* // Before (exceptions)\n* try {\n* const response = await fetch('/api/users')\n* const data = await response.json()\n* return data\n* } catch (e) {\n* console.error(e)\n* return null\n* }\n*\n* // After (Result)\n* const result = await fromPromise(fetch('/api/users'), 'FETCH_ERROR')\n* if (isErr(result)) {\n* console.error(result.error.message)\n* return null\n* }\n* const data = await fromPromise(result.value.json(), 'PARSE_ERROR')\n* ```\n*/\nasync function fromPromise(promise, errorCode) {\n\ttry {\n\t\treturn ok(await promise);\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n/**\n* Wraps a synchronous function that may throw into a function returning Result.\n*\n* Use this to safely call code that might throw exceptions, converting them\n* into Results instead.\n*\n* @template T - The return type of the function\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param fn - The function to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Result containing either the return value or a ResultError\n*\n* @example\n* ```typescript\n* // Wrapping JSON.parse\n* const result = tryCatch(() => JSON.parse(jsonString))\n* if (isOk(result)) {\n* console.log(result.value)\n* } else {\n* console.error('Invalid JSON:', result.error.message)\n* }\n*\n* // With custom error code\n* const result = tryCatch(\n* () => JSON.parse(jsonString),\n* 'JSON_PARSE_ERROR'\n* )\n*\n* // Wrapping any throwing function\n* const result = tryCatch(() => {\n* const value = riskyOperation()\n* return transform(value)\n* }, 'OPERATION_FAILED')\n*\n* // Practical example: safe regex\n* function safeRegex(pattern: string): Result<RegExp, ResultError<'INVALID_REGEX'>> {\n* return tryCatch(() => new RegExp(pattern), 'INVALID_REGEX')\n* }\n*\n* const regex = safeRegex('[invalid')\n* // regex = err({ code: 'INVALID_REGEX', message: '...', cause: SyntaxError })\n* ```\n*/\nfunction tryCatch(fn, errorCode) {\n\ttry {\n\t\treturn ok(fn());\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n/**\n* Wraps an async function that may throw into a function returning Promise<Result>.\n*\n* Similar to `tryCatch` but for async functions. The function is immediately\n* invoked and its result is wrapped.\n*\n* @template T - The resolved type of the async function\n* @template C - The type of error code (defaults to 'UNKNOWN')\n* @param fn - The async function to wrap\n* @param errorCode - Optional error code to use instead of UNKNOWN_ERROR\n* @returns A Promise that resolves to a Result\n*\n* @example\n* ```typescript\n* // Basic usage\n* const result = await tryCatchAsync(async () => {\n* const response = await fetch('/api/data')\n* return response.json()\n* })\n*\n* // With custom error code\n* const result = await tryCatchAsync(\n* async () => {\n* const data = await fetchData()\n* return processData(data)\n* },\n* 'DATA_PROCESSING_ERROR'\n* )\n*\n* // Combining multiple async operations\n* const result = await tryCatchAsync(async () => {\n* const user = await db.users.findOne(id)\n* if (!user) throw new Error('User not found')\n*\n* const posts = await db.posts.find({ userId: user.id })\n* return { user, posts }\n* }, 'FETCH_USER_DATA')\n*\n* // Difference from fromPromise:\n* // - fromPromise: wraps an existing Promise\n* // - tryCatchAsync: creates and wraps a new Promise from an async function\n*\n* // Use fromPromise when you have a Promise:\n* const p = someAsyncOperation()\n* const r1 = await fromPromise(p, 'ERROR')\n*\n* // Use tryCatchAsync when you want to define the async logic:\n* const r2 = await tryCatchAsync(async () => {\n* // your async logic here\n* }, 'ERROR')\n* ```\n*/\nasync function tryCatchAsync(fn, errorCode) {\n\ttry {\n\t\treturn ok(await fn());\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error : new Error(String(error));\n\t\treturn err(resultError(errorCode ?? UNKNOWN_ERROR, cause.message, cause));\n\t}\n}\n\n//#endregion\nexport { UNKNOWN_ERROR, all, collect, err, fail, flatMap, fromPromise, isErr, isOk, map, mapErr, match, ok, resultError, tap, tapErr, tryCatch, tryCatchAsync, unwrap, unwrapOr, unwrapOrElse };\n//# sourceMappingURL=index.mjs.map","function isMinifiedFile(filename) {\n const minifiedPatterns = [\n /\\.min\\.js$/,\n /\\.bundle\\.js$/,\n /\\.chunk\\.js$/,\n /-[\\w\\d]{8,}\\.js$/,\n // Hash-based filenames\n /Logger-[A-Za-z0-9]+\\.js$/,\n // Logger bundle files\n /node_modules/,\n /dist\\//,\n /build\\//,\n /\\.mjs$/\n ];\n return minifiedPatterns.some((pattern) => pattern.test(filename));\n}\nfunction extractCleanFilename(fullPath) {\n const filename = fullPath.split(/[/\\\\]/).pop() || fullPath;\n return filename.replace(/\\.min\\.js$/, \".js\").replace(/\\.bundle\\.js$/, \".js\").replace(/\\.chunk\\.js$/, \".js\").replace(/-[\\w\\d]{8,}\\.js$/, \".js\").replace(/Logger-[A-Za-z0-9]+\\.js$/, \"logger.ts\");\n}\nfunction parseStackTrace() {\n try {\n const stack = new Error().stack;\n if (!stack) {\n return null;\n }\n const lines = stack.split(\"\\n\").filter((line) => line.trim());\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n if (!line) {\n continue;\n }\n if (line.includes(\"parseStackTrace\") || line.includes(\"Logger.\") || line.includes(\".log(\") || line.includes(\"createStyledOutput\")) {\n continue;\n }\n let match;\n const chromeMatch = line.match(/at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/);\n if (chromeMatch) {\n const filename = chromeMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = chromeMatch;\n } else {\n const firefoxMatch = line.match(/(.+?)@(.+?):(\\d+):(\\d+)$/);\n if (firefoxMatch) {\n const filename = firefoxMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = firefoxMatch;\n } else {\n const safariMatch = line.match(/(\\S+)?@(.+?):(\\d+):(\\d+)$/);\n if (safariMatch) {\n const filename = safariMatch[2];\n if (filename && isMinifiedFile(filename)) {\n continue;\n }\n match = safariMatch;\n }\n }\n }\n if (!match) {\n continue;\n }\n const [, functionName, file, lineStr, columnStr] = match;\n if (!file) {\n continue;\n }\n const cleanFileName = extractCleanFilename(file).split(\"?\")[0];\n if (!cleanFileName) {\n continue;\n }\n const lineNum = lineStr ? parseInt(lineStr, 10) : 0;\n const columnNum = columnStr ? parseInt(columnStr, 10) : 0;\n const cleanFunction = functionName && functionName.trim() ? functionName.trim() : void 0;\n return {\n file: cleanFileName ? cleanFileName : \"unknown\",\n line: lineNum,\n column: columnNum,\n function: cleanFunction\n };\n }\n return null;\n } catch {\n return null;\n }\n}\nconst DEFAULT_CONFIG = {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n theme: \"default\",\n bannerType: \"simple\",\n bufferSize: 1e3,\n autoDetectTheme: true,\n outputFormat: \"auto\"\n};\nconst LEVEL_STYLES = {\n debug: {\n emoji: \"🔍\",\n label: \"DEBUG\",\n background: \"linear-gradient(90deg, #6c757d, #495057)\",\n color: \"#ffffff\",\n border: \"1px solid #6c757d\",\n shadow: \"0 2px 4px rgba(108, 117, 125, 0.3)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(90deg, #007bff, #0056b3)\",\n color: \"#ffffff\",\n border: \"1px solid #007bff\",\n shadow: \"0 2px 4px rgba(0, 123, 255, 0.3)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(90deg, #ffc107, #e0a800)\",\n color: \"#000000\",\n border: \"1px solid #ffc107\",\n shadow: \"0 2px 4px rgba(255, 193, 7, 0.3)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(90deg, #dc3545, #c82333)\",\n color: \"#ffffff\",\n border: \"1px solid #dc3545\",\n shadow: \"0 2px 4px rgba(220, 53, 69, 0.3)\"\n },\n critical: {\n emoji: \"🚨\",\n label: \"CRITICAL\",\n background: \"linear-gradient(90deg, #8B0000, #FF0000)\",\n color: \"#ffffff\",\n border: \"2px solid #FF0000\",\n shadow: \"0 4px 8px rgba(255, 0, 0, 0.4)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(90deg, #28a745, #1e7e34)\",\n color: \"#ffffff\",\n border: \"1px solid #28a745\",\n shadow: \"0 2px 4px rgba(40, 167, 69, 0.3)\"\n }\n};\nconst BUFFER_LIMITS = {\n MIN_SIZE: 50,\n DEFAULT_SIZE: 1e3,\n MAX_SIZE: 1e4\n};\nconst EXPORT_FORMATS = {\n json: { extension: \".json\", mimeType: \"application/json\" },\n csv: { extension: \".csv\", mimeType: \"text/csv\" },\n markdown: { extension: \".md\", mimeType: \"text/markdown\" },\n plain: { extension: \".txt\", mimeType: \"text/plain\" },\n html: { extension: \".html\", mimeType: \"text/html\" }\n};\nconst TIME_UNITS = {\n ms: 1,\n s: 1e3,\n m: 60 * 1e3,\n h: 60 * 60 * 1e3,\n d: 24 * 60 * 60 * 1e3\n};\nconst ADAPTIVE_COLORS = {\n timestamp: {\n light: \"#666666\",\n dark: \"#a0a0a0\"\n },\n messageText: {\n light: \"#2d3748\",\n dark: \"#f7fafc\"\n },\n prefix: {\n light: \"#2d3748\",\n dark: \"#e2e8f0\"\n },\n prefixBackground: {\n light: \"#2d3748\",\n dark: \"#4a5568\"\n },\n location: {\n light: \"#718096\",\n dark: \"#a0aec0\"\n }\n};\nconst BUILD_PRESETS = {\n /**\n * Configuración optimizada para Next.js builds\n */\n nextjs: {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: false,\n enableStackTrace: false,\n autoDetectTheme: false,\n outputFormat: \"build\"\n },\n /**\n * Configuración para Webpack builds\n */\n webpack: {\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: false,\n autoDetectTheme: false,\n outputFormat: \"build\"\n },\n /**\n * Configuración para CI/CD environments\n */\n ci: {\n verbosity: \"info\",\n enableColors: false,\n enableTimestamps: true,\n enableStackTrace: true,\n autoDetectTheme: false,\n outputFormat: \"ci\"\n },\n /**\n * Configuración para desarrollo terminal\n */\n terminal: {\n verbosity: \"debug\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n autoDetectTheme: false,\n outputFormat: \"ansi\"\n }\n};\nconst ENVIRONMENT_DETECTION = {\n // Next.js detection\n isNextJS: typeof process !== \"undefined\" && (process.env.NEXT_RUNTIME || process.env.NEXT_PUBLIC_VERCEL_ENV || process.argv && process.argv.some((arg) => arg.includes(\"next\"))),\n // Webpack detection\n isWebpack: typeof process !== \"undefined\" && (process.env.WEBPACK_ENV || process.env.WEBPACK_BUILD || process.argv && process.argv.some((arg) => arg.includes(\"webpack\"))),\n // CI/CD detection\n isCI: typeof process !== \"undefined\" && (process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL || process.env.GITLAB_CI || process.env.TRAVIS || process.env.CIRCLECI),\n // Build detection\n isBuild: typeof process !== \"undefined\" && true,\n // Terminal with ANSI support\n isTerminal: typeof process !== \"undefined\" && (process.stdout?.isTTY === true && process.env.TERM !== \"dumb\")\n};\nfunction detectEnvironmentPreset() {\n if (ENVIRONMENT_DETECTION.isCI) {\n return \"ci\";\n }\n if (ENVIRONMENT_DETECTION.isNextJS) {\n return \"nextjs\";\n }\n if (ENVIRONMENT_DETECTION.isWebpack) {\n return \"webpack\";\n }\n if (ENVIRONMENT_DETECTION.isTerminal) {\n return \"terminal\";\n }\n return \"terminal\";\n}\nfunction getOptimalConfig() {\n const preset = detectEnvironmentPreset();\n return {\n ...DEFAULT_CONFIG,\n ...BUILD_PRESETS[preset]\n };\n}\nfunction formatTimestamp() {\n try {\n const now = /* @__PURE__ */ new Date();\n return now.toISOString();\n } catch {\n return (/* @__PURE__ */ new Date()).toISOString();\n }\n}\nfunction parseRelativeTime(timeStr) {\n const match = timeStr.match(/^(\\d+)(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Invalid time format: ${timeStr}. Use format like \"2h\", \"30m\", \"1d\"`);\n }\n const [, amount, unit] = match;\n const multiplier = TIME_UNITS[unit];\n return parseInt(amount || \"0\", 10) * multiplier;\n}\nfunction parseTimeInput(input) {\n if (input instanceof Date) {\n return input;\n }\n if (typeof input === \"number\") {\n return new Date(Date.now() - input * TIME_UNITS.h);\n }\n if (typeof input === \"string\") {\n const isoDate = new Date(input);\n if (!isNaN(isoDate.getTime())) {\n return isoDate;\n }\n try {\n const ms = parseRelativeTime(input);\n return new Date(Date.now() - ms);\n } catch {\n throw new Error(`Invalid time format: ${input}`);\n }\n }\n throw new Error(`Unsupported time input type: ${typeof input}`);\n}\nfunction formatDisplayTime(date, format = \"short\") {\n switch (format) {\n case \"time-only\":\n return date.toTimeString().slice(0, 8);\n // HH:MM:SS\n case \"full\":\n return date.toISOString();\n case \"short\":\n default:\n return date.toISOString().slice(11, 23);\n }\n}\nclass StyleBuilder {\n styles = [];\n constructor(baseStyle = \"\") {\n if (baseStyle) this.styles.push(baseStyle);\n }\n /**\n * Add background color or gradient\n */\n bg(background) {\n this.styles.push(`background: ${background}`);\n return this;\n }\n /**\n * Add text color\n */\n color(color) {\n this.styles.push(`color: ${color}`);\n return this;\n }\n /**\n * Add border styling\n */\n border(border) {\n this.styles.push(`border: ${border}`);\n return this;\n }\n /**\n * Add box shadow\n */\n shadow(shadow) {\n this.styles.push(`box-shadow: ${shadow}`);\n return this;\n }\n /**\n * Add padding\n */\n padding(padding) {\n this.styles.push(`padding: ${padding}`);\n return this;\n }\n /**\n * Add margin\n */\n margin(margin) {\n this.styles.push(`margin: ${margin}`);\n return this;\n }\n /**\n * Add border radius\n */\n rounded(radius = \"4px\") {\n this.styles.push(`border-radius: ${radius}`);\n return this;\n }\n /**\n * Add font weight\n */\n bold() {\n this.styles.push(\"font-weight: bold\");\n return this;\n }\n /**\n * Add font styling\n */\n font(font) {\n this.styles.push(`font-family: ${font}`);\n return this;\n }\n /**\n * Set monospace font family (alias for common monospace fonts)\n */\n mono() {\n return this.font('Monaco, Consolas, \"Courier New\", monospace');\n }\n /**\n * Set system font family (alias for system fonts)\n */\n system() {\n return this.font('system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif');\n }\n /**\n * Add font size\n */\n size(size) {\n this.styles.push(`font-size: ${size}`);\n return this;\n }\n /**\n * Add line height\n */\n lineHeight(height) {\n this.styles.push(`line-height: ${height}`);\n return this;\n }\n /**\n * Add text decoration\n */\n underline() {\n this.styles.push(\"text-decoration: underline\");\n return this;\n }\n /**\n * Add text transform\n */\n uppercase() {\n this.styles.push(\"text-transform: uppercase\");\n return this;\n }\n /**\n * Add opacity\n */\n opacity(value) {\n this.styles.push(`opacity: ${value}`);\n return this;\n }\n /**\n * Add display property\n */\n display(value) {\n this.styles.push(`display: ${value}`);\n return this;\n }\n /**\n * Add position property\n */\n position(value) {\n this.styles.push(`position: ${value}`);\n return this;\n }\n /**\n * Add transform property\n */\n transform(value) {\n this.styles.push(`transform: ${value}`);\n return this;\n }\n /**\n * Add animation property\n */\n animation(value) {\n this.styles.push(`animation: ${value}`);\n return this;\n }\n /**\n * Add transition property\n */\n transition(value) {\n this.styles.push(`transition: ${value}`);\n return this;\n }\n /**\n * Add cursor property\n */\n cursor(value) {\n this.styles.push(`cursor: ${value}`);\n return this;\n }\n /**\n * Add any custom CSS property\n */\n custom(property, value) {\n this.styles.push(`${property}: ${value}`);\n return this;\n }\n /**\n * Add any CSS property (alias for custom)\n */\n css(property, value) {\n return this.custom(property, value);\n }\n /**\n * Build the final CSS string\n */\n build() {\n return this.styles.join(\"; \");\n }\n /**\n * Clear all styles and start fresh\n */\n clear() {\n this.styles = [];\n return this;\n }\n /**\n * Clone this StyleBuilder with the same styles\n */\n clone() {\n const cloned = new StyleBuilder();\n cloned.styles = [...this.styles];\n return cloned;\n }\n /**\n * Merge another StyleBuilder's styles into this one\n */\n merge(other) {\n this.styles.push(...other.styles);\n return this;\n }\n}\nfunction createStyler() {\n const builder = new StyleBuilder();\n return new Proxy(builder, {\n get(target, prop) {\n if (prop in target) {\n const method = target[prop];\n if (typeof method === \"function\") {\n return method.bind(target);\n }\n return method;\n }\n return void 0;\n }\n });\n}\ncreateStyler();\nconst StylePresets = {\n success: () => new StyleBuilder().bg(\"linear-gradient(135deg, #00b894 0%, #00a085 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n error: () => new StyleBuilder().bg(\"linear-gradient(135deg, #e84393 0%, #d63031 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n warning: () => new StyleBuilder().bg(\"linear-gradient(135deg, #fdcb6e 0%, #e17055 100%)\").color(\"#2d3436\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n info: () => new StyleBuilder().bg(\"linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n debug: () => new StyleBuilder().bg(\"linear-gradient(135deg, #667eea 0%, #764ba2 100%)\").color(\"#ffffff\").padding(\"4px 8px\").rounded(\"4px\").bold(),\n muted: () => new StyleBuilder().color(\"#6c757d\").font(\"Monaco, Consolas, monospace\").size(\"12px\"),\n accent: () => new StyleBuilder().bg(\"#f8f9fa\").color(\"#495057\").padding(\"2px 6px\").rounded(\"3px\").border(\"1px solid #dee2e6\"),\n neon: () => new StyleBuilder().bg(\"linear-gradient(135deg, #0f3460 0%, #e94560 100%)\").color(\"#00ffff\").padding(\"4px 8px\").rounded(\"4px\").bold().shadow(\"0 0 10px rgba(0, 255, 255, 0.5)\")\n};\nfunction getEnvironment() {\n if (typeof globalThis !== \"undefined\" && globalThis.Deno) {\n return \"deno\";\n }\n if (typeof window === \"undefined\" && typeof self !== \"undefined\" && typeof self.importScripts === \"function\") {\n return \"webworker\";\n }\n if (typeof process !== \"undefined\" && process.versions && process.versions.node) {\n if (isRunningInTerminal()) {\n return \"terminal\";\n }\n return \"server\";\n }\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n return \"browser\";\n }\n return \"unknown\";\n}\nfunction isRunningInTerminal() {\n if (typeof process === \"undefined\") return false;\n const isTTY = process.stdout && process.stdout.isTTY;\n const hasTerminalEnv = process.env && (process.env.TERM || process.env.TERM_PROGRAM || process.env.SSH_TTY || process.env.TERM_SESSION_ID);\n const terminalPrograms = [\n \"vscode\",\n \"hyper\",\n \"iterm\",\n \"terminal\",\n \"alacritty\",\n \"kitty\",\n \"gnome-terminal\",\n \"konsole\",\n \"xterm\",\n \"tmux\",\n \"screen\"\n ];\n const isTerminalProgram = hasTerminalEnv && terminalPrograms.some(\n (program) => process.env.TERM_PROGRAM?.toLowerCase().includes(program) || process.env.TERM?.toLowerCase().includes(program)\n );\n return Boolean(isTTY || hasTerminalEnv || isTerminalProgram);\n}\nfunction supportsANSI() {\n const env = getEnvironment();\n if (env === \"browser\") return false;\n if (env === \"terminal\") return true;\n if (env === \"server\") return checkServerANSISupport();\n return false;\n}\nfunction checkServerANSISupport() {\n if (typeof process === \"undefined\") return false;\n const supportsANSI2 = process.env && (process.env.COLORTERM || process.env.FORCE_COLOR || process.env.TERM && process.env.TERM !== \"dumb\" || process.env.TERM_PROGRAM);\n return Boolean(supportsANSI2);\n}\nfunction getColorCapability() {\n const env = getEnvironment();\n if (env === \"browser\") {\n return \"full\";\n }\n if (!supportsANSI()) {\n return \"none\";\n }\n if (typeof process !== \"undefined\" && process.env) {\n const hasTrueColor = process.env.COLORTERM === \"truecolor\" || process.env.COLORTERM === \"24bit\";\n const has256Colors = process.env.TERM && process.env.TERM.includes(\"256\");\n if (hasTrueColor || has256Colors) {\n return \"full\";\n }\n }\n return \"basic\";\n}\nfunction getTerminalWidth() {\n if (typeof process !== \"undefined\" && process.stdout?.columns) {\n return process.stdout.columns;\n }\n return 80;\n}\nfunction getTerminalHeight() {\n if (typeof process !== \"undefined\" && process.stdout?.rows) {\n return process.stdout.rows;\n }\n return 24;\n}\nfunction getEnvironmentInfo() {\n return {\n environment: getEnvironment(),\n supportsANSI: supportsANSI(),\n colorCapability: getColorCapability(),\n isTTY: typeof process !== \"undefined\" ? Boolean(process.stdout?.isTTY) : false,\n platform: typeof process !== \"undefined\" ? process.platform : \"unknown\",\n nodeVersion: typeof process !== \"undefined\" ? process.versions?.node : null,\n term: typeof process !== \"undefined\" ? process.env?.TERM : null,\n colorTerm: typeof process !== \"undefined\" ? process.env?.COLORTERM : null,\n terminalWidth: getTerminalWidth(),\n terminalHeight: getTerminalHeight()\n };\n}\nconst ANSI_16_COLORS = {\n black: { fg: \"30\", bg: \"40\", bright: { fg: \"90\", bg: \"100\" } },\n red: { fg: \"31\", bg: \"41\", bright: { fg: \"91\", bg: \"101\" } },\n green: { fg: \"32\", bg: \"42\", bright: { fg: \"92\", bg: \"102\" } },\n yellow: { fg: \"33\", bg: \"43\", bright: { fg: \"93\", bg: \"103\" } },\n blue: { fg: \"34\", bg: \"44\", bright: { fg: \"94\", bg: \"104\" } },\n magenta: { fg: \"35\", bg: \"45\", bright: { fg: \"95\", bg: \"105\" } },\n cyan: { fg: \"36\", bg: \"46\", bright: { fg: \"96\", bg: \"106\" } },\n white: { fg: \"37\", bg: \"47\", bright: { fg: \"97\", bg: \"107\" } },\n gray: { fg: \"90\", bg: \"100\", bright: { fg: \"37\", bg: \"47\" } },\n grey: { fg: \"90\", bg: \"100\", bright: { fg: \"37\", bg: \"47\" } }\n};\nconst CSS_NAMED_COLORS = {\n aliceblue: \"#f0f8ff\",\n antiquewhite: \"#faebd7\",\n aqua: \"#00ffff\",\n aquamarine: \"#7fffd4\",\n azure: \"#f0ffff\",\n beige: \"#f5f5dc\",\n bisque: \"#ffe4c4\",\n black: \"#000000\",\n blanchedalmond: \"#ffebcd\",\n blue: \"#0000ff\",\n blueviolet: \"#8a2be2\",\n brown: \"#a52a2a\",\n burlywood: \"#deb887\",\n cadetblue: \"#5f9ea0\",\n chartreuse: \"#7fff00\",\n chocolate: \"#d2691e\",\n coral: \"#ff7f50\",\n cornflowerblue: \"#6495ed\",\n cornsilk: \"#fff8dc\",\n crimson: \"#dc143c\",\n cyan: \"#00ffff\",\n darkblue: \"#00008b\",\n darkcyan: \"#008b8b\",\n darkgoldenrod: \"#b8860b\",\n darkgray: \"#a9a9a9\",\n darkgreen: \"#006400\",\n darkkhaki: \"#bdb76b\",\n darkmagenta: \"#8b008b\",\n darkolivegreen: \"#556b2f\",\n darkorange: \"#ff8c00\",\n darkorchid: \"#9932cc\",\n darkred: \"#8b0000\",\n darksalmon: \"#e9967a\",\n darkseagreen: \"#8fbc8f\",\n darkslateblue: \"#483d8b\",\n darkslategray: \"#2f4f4f\",\n darkturquoise: \"#00ced1\",\n darkviolet: \"#9400d3\",\n deeppink: \"#ff1493\",\n deepskyblue: \"#00bfff\",\n dimgray: \"#696969\",\n dodgerblue: \"#1e90ff\",\n firebrick: \"#b22222\",\n floralwhite: \"#fffaf0\",\n forestgreen: \"#228b22\",\n fuchsia: \"#ff00ff\",\n gainsboro: \"#dcdcdc\",\n ghostwhite: \"#f8f8ff\",\n gold: \"#ffd700\",\n goldenrod: \"#daa520\",\n gray: \"#808080\",\n green: \"#008000\",\n greenyellow: \"#adff2f\",\n honeydew: \"#f0fff0\",\n hotpink: \"#ff69b4\",\n indianred: \"#cd5c5c\",\n indigo: \"#4b0082\",\n ivory: \"#fffff0\",\n khaki: \"#f0e68c\",\n lavender: \"#e6e6fa\",\n lavenderblush: \"#fff0f5\",\n lawngreen: \"#7cfc00\",\n lemonchiffon: \"#fffacd\",\n lightblue: \"#add8e6\",\n lightcoral: \"#f08080\",\n lightcyan: \"#e0ffff\",\n lightgoldenrodyellow: \"#fafad2\",\n lightgray: \"#d3d3d3\",\n lightgreen: \"#90ee90\",\n lightpink: \"#ffb6c1\",\n lightsalmon: \"#ffa07a\",\n lightseagreen: \"#20b2aa\",\n lightskyblue: \"#87cefa\",\n lightslategray: \"#778899\",\n lightsteelblue: \"#b0c4de\",\n lightyellow: \"#ffffe0\",\n lime: \"#00ff00\",\n limegreen: \"#32cd32\",\n linen: \"#faf0e6\",\n magenta: \"#ff00ff\",\n maroon: \"#800000\",\n mediumaquamarine: \"#66cdaa\",\n mediumblue: \"#0000cd\",\n mediumorchid: \"#ba55d3\",\n mediumpurple: \"#9370db\",\n mediumseagreen: \"#3cb371\",\n mediumslateblue: \"#7b68ee\",\n mediumspringgreen: \"#00fa9a\",\n mediumturquoise: \"#48d1cc\",\n mediumvioletred: \"#c71585\",\n midnightblue: \"#191970\",\n mintcream: \"#f5fffa\",\n mistyrose: \"#ffe4e1\",\n moccasin: \"#ffe4b5\",\n navajowhite: \"#ffdead\",\n navy: \"#000080\",\n oldlace: \"#fdf5e6\",\n olive: \"#808000\",\n olivedrab: \"#6b8e23\",\n orange: \"#ffa500\",\n orangered: \"#ff4500\",\n orchid: \"#da70d6\",\n palegoldenrod: \"#eee8aa\",\n palegreen: \"#98fb98\",\n paleturquoise: \"#afeeee\",\n palevioletred: \"#db7093\",\n papayawhip: \"#ffefd5\",\n peachpuff: \"#ffdab9\",\n peru: \"#cd853f\",\n pink: \"#ffc0cb\",\n plum: \"#dda0dd\",\n powderblue: \"#b0e0e6\",\n purple: \"#800080\",\n rebeccapurple: \"#663399\",\n red: \"#ff0000\",\n rosybrown: \"#bc8f8f\",\n royalblue: \"#4169e1\",\n saddlebrown: \"#8b4513\",\n salmon: \"#fa8072\",\n sandybrown: \"#f4a460\",\n seagreen: \"#2e8b57\",\n seashell: \"#fff5ee\",\n sienna: \"#a0522d\",\n silver: \"#c0c0c0\",\n skyblue: \"#87ceeb\",\n slateblue: \"#6a5acd\",\n slategray: \"#708090\",\n snow: \"#fffafa\",\n springgreen: \"#00ff7f\",\n steelblue: \"#4682b4\",\n tan: \"#d2b48c\",\n teal: \"#008080\",\n thistle: \"#d8bfd8\",\n tomato: \"#ff6347\",\n turquoise: \"#40e0d0\",\n violet: \"#ee82ee\",\n wheat: \"#f5deb3\",\n white: \"#ffffff\",\n whitesmoke: \"#f5f5f5\",\n yellow: \"#ffff00\",\n yellowgreen: \"#9acd32\"\n};\nfunction hexToRgb(hex) {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result || !result[1] || !result[2] || !result[3]) {\n return { r: 255, g: 255, b: 255 };\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16)\n };\n}\nfunction rgbToHex(r, g, b) {\n return \"#\" + [r, g, b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction hexTo256(hex) {\n const { r, g, b } = hexToRgb(hex);\n if (r === g && g === b) {\n if (r < 8) return 16;\n if (r > 248) return 231;\n return Math.round((r - 8) / 247 * 24) + 232;\n }\n const ri = Math.round(r / 255 * 5);\n const gi = Math.round(g / 255 * 5);\n const bi = Math.round(b / 255 * 5);\n return 16 + 36 * ri + 6 * gi + bi;\n}\nfunction colorToHex(color) {\n if (color.startsWith(\"#\")) {\n return color;\n }\n const named = CSS_NAMED_COLORS[color.toLowerCase()];\n if (named) {\n return named;\n }\n const rgbMatch = color.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);\n if (rgbMatch && rgbMatch[1] && rgbMatch[2] && rgbMatch[3]) {\n return rgbToHex(\n parseInt(rgbMatch[1]),\n parseInt(rgbMatch[2]),\n parseInt(rgbMatch[3])\n );\n }\n return \"#ffffff\";\n}\nfunction getANSIForeground(color, capability) {\n if (capability === \"none\") return \"\";\n const lowerColor = color.toLowerCase();\n if (capability === \"basic\" && ANSI_16_COLORS[lowerColor]) {\n return `\\x1B[${ANSI_16_COLORS[lowerColor].fg}m`;\n }\n if (capability === \"basic\") {\n const hex2 = colorToHex(color);\n const nearestBasic = findNearestBasicColor(hex2);\n const basicColor = ANSI_16_COLORS[nearestBasic];\n return basicColor ? `\\x1B[${basicColor.fg}m` : \"\\x1B[37m\";\n }\n const hex = colorToHex(color);\n const { r, g, b } = hexToRgb(hex);\n return `\\x1B[38;2;${r};${g};${b}m`;\n}\nfunction getANSIBackground(color, capability) {\n if (capability === \"none\") return \"\";\n const lowerColor = color.toLowerCase();\n if (capability === \"basic\" && ANSI_16_COLORS[lowerColor]) {\n return `\\x1B[${ANSI_16_COLORS[lowerColor].bg}m`;\n }\n if (capability === \"basic\") {\n const hex2 = colorToHex(color);\n const nearestBasic = findNearestBasicColor(hex2);\n const basicColor = ANSI_16_COLORS[nearestBasic];\n return basicColor ? `\\x1B[${basicColor.bg}m` : \"\\x1B[47m\";\n }\n const hex = colorToHex(color);\n const { r, g, b } = hexToRgb(hex);\n return `\\x1B[48;2;${r};${g};${b}m`;\n}\nfunction getANSI256Foreground(colorIndex) {\n return `\\x1B[38;5;${colorIndex}m`;\n}\nfunction getANSI256Background(colorIndex) {\n return `\\x1B[48;5;${colorIndex}m`;\n}\nfunction findNearestBasicColor(hex) {\n const { r, g, b } = hexToRgb(hex);\n const basicColors = {\n black: { r: 0, g: 0, b: 0 },\n red: { r: 205, g: 0, b: 0 },\n green: { r: 0, g: 205, b: 0 },\n yellow: { r: 205, g: 205, b: 0 },\n blue: { r: 0, g: 0, b: 238 },\n magenta: { r: 205, g: 0, b: 205 },\n cyan: { r: 0, g: 205, b: 205 },\n white: { r: 229, g: 229, b: 229 }\n };\n let nearest = \"white\";\n let minDistance = Infinity;\n for (const [name, rgb] of Object.entries(basicColors)) {\n const distance = Math.sqrt(\n Math.pow(r - rgb.r, 2) + Math.pow(g - rgb.g, 2) + Math.pow(b - rgb.b, 2)\n );\n if (distance < minDistance) {\n minDistance = distance;\n nearest = name;\n }\n }\n return nearest;\n}\nfunction extractGradientColors(gradient) {\n const hexMatches = gradient.match(/#[a-fA-F0-9]{6}/g) || [];\n const rgbMatches = gradient.match(/rgba?\\([^)]+\\)/g) || [];\n const namedMatches = gradient.match(/,\\s*([a-z]+)(?:\\s|,|\\))/gi) || [];\n const colors = [\n ...hexMatches,\n ...rgbMatches.map(colorToHex),\n ...namedMatches.map((m) => {\n const name = m.replace(/[,\\s)]/g, \"\").toLowerCase();\n return CSS_NAMED_COLORS[name] || null;\n }).filter((c) => c !== null)\n ];\n return colors.length > 0 ? colors : [\"#ffffff\"];\n}\nfunction gradientToSingleColor(gradient) {\n const colors = extractGradientColors(gradient);\n if (colors.length === 0) return \"#ffffff\";\n if (colors.length === 1) return colors[0] ?? \"#ffffff\";\n const rgbs = colors.map((c) => hexToRgb(colorToHex(c)));\n const avgR = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.r, 0) / rgbs.length);\n const avgG = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.g, 0) / rgbs.length);\n const avgB = Math.round(rgbs.reduce((sum, rgb) => sum + rgb.b, 0) / rgbs.length);\n return rgbToHex(avgR, avgG, avgB);\n}\nfunction cssColorToANSI(cssColor, capability, isBackground = false) {\n if (capability === \"none\") return \"\";\n let resolvedColor;\n if (cssColor.includes(\"gradient\")) {\n resolvedColor = gradientToSingleColor(cssColor);\n } else {\n resolvedColor = colorToHex(cssColor);\n }\n return isBackground ? getANSIBackground(resolvedColor, capability) : getANSIForeground(resolvedColor, capability);\n}\nconst ANSI = {\n reset: \"\\x1B[0m\",\n bold: \"\\x1B[1m\",\n dim: \"\\x1B[2m\",\n italic: \"\\x1B[3m\",\n underline: \"\\x1B[4m\",\n blink: \"\\x1B[5m\",\n inverse: \"\\x1B[7m\",\n hidden: \"\\x1B[8m\",\n strikethrough: \"\\x1B[9m\",\n fg: {\n black: \"\\x1B[30m\",\n red: \"\\x1B[31m\",\n green: \"\\x1B[32m\",\n yellow: \"\\x1B[33m\",\n blue: \"\\x1B[34m\",\n magenta: \"\\x1B[35m\",\n cyan: \"\\x1B[36m\",\n white: \"\\x1B[37m\",\n gray: \"\\x1B[90m\",\n brightRed: \"\\x1B[91m\",\n brightGreen: \"\\x1B[92m\",\n brightYellow: \"\\x1B[93m\",\n brightBlue: \"\\x1B[94m\",\n brightMagenta: \"\\x1B[95m\",\n brightCyan: \"\\x1B[96m\",\n brightWhite: \"\\x1B[97m\"\n },\n bg: {\n black: \"\\x1B[40m\",\n red: \"\\x1B[41m\",\n green: \"\\x1B[42m\",\n yellow: \"\\x1B[43m\",\n blue: \"\\x1B[44m\",\n magenta: \"\\x1B[45m\",\n cyan: \"\\x1B[46m\",\n white: \"\\x1B[47m\",\n gray: \"\\x1B[100m\",\n brightRed: \"\\x1B[101m\",\n brightGreen: \"\\x1B[102m\",\n brightYellow: \"\\x1B[103m\",\n brightBlue: \"\\x1B[104m\",\n brightMagenta: \"\\x1B[105m\",\n brightCyan: \"\\x1B[106m\",\n brightWhite: \"\\x1B[107m\"\n },\n rgb: (r, g, b) => `\\x1B[38;2;${r};${g};${b}m`,\n bgRgb: (r, g, b) => `\\x1B[48;2;${r};${g};${b}m`,\n color256: (n) => `\\x1B[38;5;${n}m`,\n bgColor256: (n) => `\\x1B[48;5;${n}m`\n};\nclass TerminalRenderer {\n colorCapability;\n constructor(colorCapability = \"full\") {\n this.colorCapability = colorCapability;\n }\n /**\n * Get ANSI color codes - now supports truecolor/256-color\n */\n getColorCode(color, background = false) {\n return background ? getANSIBackground(color, this.colorCapability) : getANSIForeground(color, this.colorCapability);\n }\n /**\n * Get ANSI style codes\n */\n getStyleCode(styles) {\n const styleCodes = {\n \"bold\": \"1\",\n \"dim\": \"2\",\n \"italic\": \"3\",\n \"underline\": \"4\",\n \"reset\": \"0\"\n };\n const codes = styles.map((style) => styleCodes[style] || \"0\").join(\";\");\n return codes ? `\\x1B[${codes}m` : \"\";\n }\n /**\n * Convert log styles to ANSI formatting\n */\n renderTerminal(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const result = { text: \"\", reset };\n if (styles) {\n result.timestamp = this.styleTimestamp(timestamp, styles.timestamp);\n result.level = this.styleLevel(level, styles.level);\n result.prefix = this.stylePrefix(prefix, styles.prefix);\n result.message = this.styleMessage(message, styles.message);\n result.location = this.styleLocation(location, styles.location);\n } else {\n result.timestamp = this.styleTimestamp(timestamp);\n result.level = this.styleLevel(level);\n result.prefix = this.stylePrefix(prefix);\n result.message = this.styleMessage(message);\n result.location = this.styleLocation(location);\n }\n const parts = [];\n if (result.timestamp) parts.push(result.timestamp);\n if (result.level) parts.push(result.level);\n if (result.prefix) parts.push(result.prefix);\n if (result.message) parts.push(result.message);\n if (result.location) parts.push(result.location);\n result.text = parts.join(\" \") + reset;\n return result;\n }\n /**\n * Style timestamp based on preset or defaults\n */\n styleTimestamp(timestamp, style) {\n if (!timestamp || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return timestamp;\n }\n const dimStyle = this.getStyleCode([\"dim\"]);\n return `${dimStyle}${timestamp}${\"\\x1B[0m\"}`;\n }\n /**\n * Style level with appropriate colors and formatting\n */\n styleLevel(level, style) {\n if (!style?.show) return \"\";\n const levelText = this.getLevelText(level);\n const levelColors = {\n \"debug\": \"magenta\",\n \"info\": \"blue\",\n \"warn\": \"yellow\",\n \"error\": \"red\",\n \"critical\": \"red\"\n };\n if (this.colorCapability === \"none\") {\n return `[${levelText}]`;\n }\n const color = levelColors[level] || \"white\";\n const colorCode = this.getColorCode(color);\n const boldStyle = this.getStyleCode([\"bold\"]);\n if (style?.style === \"compact\") {\n return `${colorCode}[${levelText}]${\"\\x1B[0m\"}`;\n } else {\n return `${colorCode}${boldStyle}[${levelText}]${\"\\x1B[0m\"}`;\n }\n }\n /**\n * Style prefix based on preset - now as a badge\n */\n stylePrefix(prefix, style) {\n if (!prefix || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return `[${prefix}]`;\n }\n const colorCode = this.getColorCode(\"cyan\");\n const bgBlack = \"\\x1B[40m\";\n return `${bgBlack}${colorCode}[${prefix.toUpperCase()}]${\"\\x1B[0m\"}`;\n }\n /**\n * Style message based on preset\n */\n styleMessage(message, style) {\n if (!style?.show) return message;\n return message;\n }\n /**\n * Style location (file:line) information\n */\n styleLocation(location, style) {\n if (!location || !style?.show) return \"\";\n if (this.colorCapability === \"none\") {\n return `(${location})`;\n }\n const dimStyle = this.getStyleCode([\"dim\"]);\n if (style?.style === \"clickable\") {\n const underlineStyle = this.getStyleCode([\"dim\", \"underline\"]);\n return `${underlineStyle}(${location})${\"\\x1B[0m\"}`;\n }\n return `${dimStyle}(${location})${\"\\x1B[0m\"}`;\n }\n /**\n * Get text representation of log level\n */\n getLevelText(level) {\n const levelMap = {\n \"debug\": \"DEBUG\",\n \"info\": \"INFO\",\n \"warn\": \"WARN\",\n \"error\": \"ERROR\",\n \"critical\": \"CRITICAL\"\n };\n return levelMap[level] || String(level).toUpperCase();\n }\n /**\n * Create cyberpunk-style ANSI rendering with truecolor support\n */\n renderCyberpunk(level, message, timestamp, prefix, location) {\n const reset = ANSI.reset;\n const cyberpunkColors = {\n \"debug\": \"#ff00ff\",\n // Neon magenta\n \"info\": \"#00ffff\",\n // Neon cyan\n \"warn\": \"#ffff00\",\n // Neon yellow\n \"error\": \"#ff0040\",\n // Neon red-pink\n \"critical\": \"#ff0000\"\n // Pure red\n };\n const parts = [];\n if (timestamp) {\n parts.push(`${ANSI.dim}${timestamp}${reset}`);\n }\n const levelColor = this.getColorCode(cyberpunkColors[level] || \"#ffffff\");\n const bgBlack = ANSI.bg.black;\n const bold = level === \"critical\" ? ANSI.bold : \"\";\n parts.push(`${bgBlack}${levelColor}${bold} ${this.getLevelText(level)} ${reset}`);\n if (prefix) {\n const cyanColor = this.getColorCode(\"#00ffff\");\n parts.push(`${bgBlack}${cyanColor}[${prefix.toUpperCase()}]${reset}`);\n }\n parts.push(message);\n if (location) {\n parts.push(`${ANSI.dim}(${location})${reset}`);\n }\n return {\n text: parts.join(\" \"),\n reset\n };\n }\n /**\n * Create minimal ANSI rendering with truecolor support\n */\n renderMinimal(level, message, timestamp, prefix) {\n const reset = ANSI.reset;\n const minimalColors = {\n \"debug\": \"#c678dd\",\n // Soft purple\n \"info\": \"#61afef\",\n // Soft blue\n \"warn\": \"#e5c07b\",\n // Soft yellow\n \"error\": \"#e06c75\",\n // Soft red\n \"critical\": \"#be5046\"\n // Dark red\n };\n const parts = [];\n if (timestamp) {\n parts.push(`${ANSI.dim}${timestamp}${reset}`);\n }\n const levelColor = this.getColorCode(minimalColors[level] || \"#abb2bf\");\n const bold = level === \"critical\" ? ANSI.bold : \"\";\n parts.push(`${levelColor}${bold}${this.getLevelText(level)}:${reset}`);\n if (prefix) {\n const cyanColor = this.getColorCode(\"#56b6c2\");\n parts.push(`${cyanColor}[${prefix.toUpperCase()}]${reset}`);\n }\n parts.push(message);\n return {\n text: parts.join(\" \"),\n reset\n };\n }\n /**\n * Get chalk-like interface for log level with truecolor support\n */\n getChalkForLevel(level) {\n const levelColors = {\n \"debug\": \"#c678dd\",\n \"info\": \"#61afef\",\n \"warn\": \"#e5c07b\",\n \"error\": \"#e06c75\",\n \"critical\": \"#be5046\"\n };\n const reset = ANSI.reset;\n return {\n color: (text) => {\n const color = levelColors[level] || \"#abb2bf\";\n const colorCode = this.getColorCode(color);\n return `${colorCode}${text}${reset}`;\n },\n bold: (text) => `${ANSI.bold}${text}${reset}`,\n dim: (text) => `${ANSI.dim}${text}${reset}`,\n bgGray: (text) => `${ANSI.bg.gray}${text}${reset}`,\n bgBlue: (text) => `${this.getColorCode(\"#1e3a5f\", true)}${text}${reset}`,\n reset: (text) => text,\n cyan: {\n bold: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${cyan}${ANSI.bold}${text}${reset}`;\n },\n dim: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${cyan}${ANSI.dim}${text}${reset}`;\n },\n bg: (text) => {\n const cyan = this.getColorCode(\"#00ffff\");\n return `${ANSI.bg.black}${cyan}[${text.toUpperCase()}]${reset}`;\n }\n }\n };\n }\n}\nclass CSS2ANSIAdapter {\n renderer;\n constructor() {\n const colorCapability = getColorCapability();\n this.renderer = new TerminalRenderer(colorCapability);\n }\n /**\n * Convert LogStyles to ANSIStyle for terminal rendering\n */\n adaptStyles(level, message, timestamp, prefix, location, styles, presetName) {\n if (presetName) {\n switch (presetName) {\n case \"cyberpunk\":\n return this.renderer.renderCyberpunk(level, message, timestamp, prefix, location);\n case \"minimal\":\n return this.renderer.renderMinimal(level, message, timestamp, prefix);\n case \"production\":\n return this.adaptProductionStyles(level, message, timestamp, prefix, location, styles);\n case \"debug\":\n return this.adaptDebugStyles(level, message, timestamp, prefix, location, styles);\n case \"glassmorphism\":\n return this.adaptGlassmorphismStyles(level, message, timestamp, prefix, location, styles);\n }\n }\n return this.renderer.renderTerminal(level, message, timestamp, prefix, location, styles);\n }\n /**\n * Adapt production preset for terminal\n */\n adaptProductionStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n parts.push(levelChalk.color(`[${this.renderer[\"getLevelText\"](level)}]`));\n }\n if (prefix && styles?.prefix?.show) {\n parts.push(levelChalk.dim(`[${prefix}]`));\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n parts.push(levelChalk.dim(`(${location})`));\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Adapt debug preset for terminal\n */\n adaptDebugStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n if (styles?.level?.style === \"compact\") {\n parts.push(levelChalk.color(`[${this.renderer[\"getLevelText\"](level)}]`));\n } else {\n parts.push(levelChalk.bold(`[${this.renderer[\"getLevelText\"](level)}]`));\n }\n }\n if (prefix && styles?.prefix?.show) {\n if (styles?.prefix?.style === \"compact\") {\n parts.push(levelChalk.cyan.dim(`[${prefix}]`));\n } else {\n parts.push(levelChalk.cyan.bold(`[${prefix}]`));\n }\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n if (styles?.location?.style === \"clickable\") {\n parts.push(levelChalk.dim(`${location} (clickable)`));\n } else {\n parts.push(levelChalk.dim(`(${location})`));\n }\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Adapt glassmorphism preset for terminal\n */\n adaptGlassmorphismStyles(level, message, timestamp, prefix, location, styles) {\n const reset = \"\\x1B[0m\";\n const levelChalk = this.renderer.getChalkForLevel(level);\n const parts = [];\n if (timestamp && styles?.timestamp?.show) {\n parts.push(levelChalk.dim(timestamp));\n }\n if (styles?.level?.show) {\n parts.push(levelChalk.bgGray(` ${this.renderer[\"getLevelText\"](level)} `));\n }\n if (prefix && styles?.prefix?.show) {\n parts.push(levelChalk.bgBlue(`[${prefix}]`));\n }\n if (message && styles?.message?.show) {\n parts.push(levelChalk.reset(message));\n }\n if (location && styles?.location?.show) {\n parts.push(levelChalk.dim(`(${location})`));\n }\n return {\n text: parts.join(\" \") + reset,\n reset\n };\n }\n /**\n * Convert CSS color values to ANSI-friendly colors\n */\n adaptColor(cssColor) {\n if (cssColor.startsWith(\"#\")) {\n return cssColor;\n }\n if (cssColor.startsWith(\"rgb(\")) {\n return cssColor;\n }\n if (cssColor.includes(\"gradient\")) {\n return this.extractColorFromGradient(cssColor);\n }\n return this.cssNameToANSI(cssColor);\n }\n /**\n * Extract primary color from CSS gradient\n */\n extractColorFromGradient(gradient) {\n const match = gradient.match(/#[0-9a-fA-F]{6}|rgb\\([^)]+\\)/);\n return match ? match[0] : \"#ffffff\";\n }\n /**\n * Convert CSS color names to ANSI-compatible names\n */\n cssNameToANSI(cssColor) {\n const colorMap = {\n \"black\": \"black\",\n \"white\": \"white\",\n \"red\": \"red\",\n \"green\": \"green\",\n \"blue\": \"blue\",\n \"yellow\": \"yellow\",\n \"cyan\": \"cyan\",\n \"magenta\": \"magenta\",\n \"gray\": \"gray\",\n \"grey\": \"gray\",\n \"orange\": \"yellow\",\n \"purple\": \"magenta\",\n \"pink\": \"red\",\n \"brown\": \"yellow\",\n \"lightblue\": \"cyan\",\n \"lightgreen\": \"green\",\n \"lightgray\": \"gray\",\n \"lightgrey\": \"gray\"\n };\n return colorMap[cssColor.toLowerCase()] || \"white\";\n }\n /**\n * Check if a style should be rendered in terminal\n */\n shouldRenderStyle(styleType, styles) {\n if (!styles) return true;\n const styleConfig = styles[styleType];\n return styleConfig?.show !== false;\n }\n /**\n * Get renderer instance for advanced usage\n */\n getRenderer() {\n return this.renderer;\n }\n}\nconst css2ansiAdapter = new CSS2ANSIAdapter();\nfunction adaptToTerminal(level, message, timestamp, prefix, location, styles, presetName) {\n return css2ansiAdapter.adaptStyles(level, message, timestamp, prefix, location, styles, presetName);\n}\nfunction detectDevToolsTheme() {\n try {\n if (typeof window === \"undefined\" || !window.matchMedia) {\n return \"light\";\n }\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n return mediaQuery.matches ? \"dark\" : \"light\";\n } catch (error) {\n console.warn(\"Failed to detect DevTools theme:\", error);\n return \"light\";\n }\n}\nfunction getAdaptiveColor(colors, theme) {\n const currentTheme = theme ?? detectDevToolsTheme();\n return colors[currentTheme];\n}\nfunction setupThemeChangeListener(callback) {\n try {\n if (typeof window === \"undefined\" || !window.matchMedia) {\n return null;\n }\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n const handler = (e) => {\n callback(e.matches ? \"dark\" : \"light\");\n };\n if (mediaQuery.addEventListener) {\n mediaQuery.addEventListener(\"change\", handler);\n return () => mediaQuery.removeEventListener(\"change\", handler);\n } else if (mediaQuery.addListener) {\n mediaQuery.addListener(handler);\n return () => mediaQuery.removeListener?.(handler);\n }\n return null;\n } catch (error) {\n console.warn(\"Failed to set up theme change listener:\", error);\n return null;\n }\n}\nfunction createStyledOutput(level, levelStyles, prefix, message, stackInfo, autoDetectTheme = true, presetStyles, presetName) {\n const levelConfig = levelStyles[level];\n const timestamp = formatTimestamp();\n const environment = getEnvironment();\n if (environment !== \"browser\" && supportsANSI()) {\n return createTerminalOutput(level, message, timestamp, prefix, stackInfo, presetStyles, presetName);\n }\n const currentTheme = autoDetectTheme ? detectDevToolsTheme() : \"light\";\n const timestampStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.timestamp, currentTheme)).size(\"11px\").font(\"Monaco, Consolas, monospace\").build();\n const levelStyle = new StyleBuilder().bg(levelConfig.background).color(levelConfig.color).border(levelConfig.border).shadow(levelConfig.shadow).padding(\"2px 8px\").rounded(\"4px\").bold().font(\"Monaco, Consolas, monospace\").size(\"12px\").build();\n const prefixStyle = new StyleBuilder().bg(getAdaptiveColor(ADAPTIVE_COLORS.prefixBackground, currentTheme)).color(getAdaptiveColor(ADAPTIVE_COLORS.prefix, currentTheme)).padding(\"2px 6px\").rounded(\"3px\").bold().font(\"Monaco, Consolas, monospace\").size(\"11px\").build();\n const messageStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.messageText, currentTheme)).font(\"system-ui, -apple-system, sans-serif\").size(\"14px\").build();\n const locationStyle = new StyleBuilder().color(getAdaptiveColor(ADAPTIVE_COLORS.location, currentTheme)).size(\"11px\").font(\"Monaco, Consolas, monospace\").build();\n let format = `%c${timestamp.slice(11, 23)} %c${levelConfig.emoji} ${levelConfig.label}`;\n const styles = [timestampStyle, levelStyle];\n if (prefix) {\n format += ` %c${prefix}`;\n styles.push(prefixStyle);\n }\n format += ` %c${message}`;\n styles.push(messageStyle);\n if (stackInfo) {\n format += ` %c(${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n styles.push(locationStyle);\n }\n return [format, ...styles];\n}\nfunction generateLogId() {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\nfunction escapeHtml(text) {\n const div = document.createElement(\"div\");\n div.textContent = text;\n return div.innerHTML;\n}\nfunction safeStringify(obj, _maxDepth = 3) {\n try {\n return JSON.stringify(obj, (_key, value) => {\n if (typeof value === \"function\") return \"[Function]\";\n if (value instanceof Error) return `[Error: ${value.message}]`;\n if (value instanceof Date) return value.toISOString();\n if (typeof value === \"undefined\") return \"[undefined]\";\n return value;\n }, 2);\n } catch (error) {\n return String(obj);\n }\n}\nfunction createTerminalOutput(level, message, timestamp, prefix, stackInfo, presetStyles, presetName) {\n const location = stackInfo ? `${stackInfo.file}:${stackInfo.line}:${stackInfo.column}` : void 0;\n const ansiStyle = adaptToTerminal(\n level,\n message,\n timestamp,\n prefix,\n location,\n presetStyles,\n presetName\n );\n return [ansiStyle.text];\n}\nconst isNode = typeof process !== \"undefined\" && process.versions && process.versions.node;\nconst isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\nfunction supportsCSSColors() {\n return isBrowser;\n}\nfunction supportsANSIColors() {\n if (isNode) {\n return process.stdout?.isTTY === true || process.env.FORCE_COLOR === \"1\" || process.env.FORCE_COLOR === \"true\";\n }\n return false;\n}\nexport {\n ANSI as A,\n BUILD_PRESETS as B,\n getAdaptiveColor as C,\n DEFAULT_CONFIG as D,\n ENVIRONMENT_DETECTION as E,\n ADAPTIVE_COLORS as F,\n BUFFER_LIMITS as G,\n generateLogId as H,\n parseTimeInput as I,\n formatDisplayTime as J,\n safeStringify as K,\n LEVEL_STYLES as L,\n escapeHtml as M,\n EXPORT_FORMATS as N,\n setupThemeChangeListener as O,\n StylePresets as S,\n TerminalRenderer as T,\n isBrowser as a,\n StyleBuilder as b,\n hexTo256 as c,\n detectEnvironmentPreset as d,\n colorToHex as e,\n formatTimestamp as f,\n getOptimalConfig as g,\n hexToRgb as h,\n isNode as i,\n getANSIForeground as j,\n getANSIBackground as k,\n getANSI256Foreground as l,\n getANSI256Background as m,\n cssColorToANSI as n,\n getEnvironment as o,\n parseStackTrace as p,\n isRunningInTerminal as q,\n rgbToHex as r,\n supportsANSI as s,\n getColorCapability as t,\n getTerminalWidth as u,\n getTerminalHeight as v,\n getEnvironmentInfo as w,\n supportsCSSColors as x,\n createStyledOutput as y,\n supportsANSIColors as z\n};\n//# sourceMappingURL=environment-COWvu6Wz.js.map\n","import { C as getAdaptiveColor, F as ADAPTIVE_COLORS, b as StyleBuilder, j as getANSIForeground, A as ANSI, u as getTerminalWidth, G as BUFFER_LIMITS, H as generateLogId, I as parseTimeInput, J as formatDisplayTime, K as safeStringify, M as escapeHtml, N as EXPORT_FORMATS, D as DEFAULT_CONFIG$1, O as setupThemeChangeListener, o as getEnvironment, p as parseStackTrace, f as formatTimestamp$1, y as createStyledOutput, t as getColorCapability, S as StylePresets } from \"./environment-COWvu6Wz.js\";\nconst DEFAULT_CONFIG = {\n maxDepth: 5,\n circular: \"placeholder\",\n preserveUndefined: false\n};\nclass SerializerRegistry {\n serializers = /* @__PURE__ */ new Map();\n config;\n constructor(config = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.registerDefaults();\n }\n registerDefaults() {\n this.add(Error, (err) => ({\n name: err.name,\n message: err.message,\n stack: err.stack?.split(\"\\n\").slice(0, 10),\n ...err.cause ? { cause: this.serialize(err.cause) } : {}\n }), 100);\n this.add(Date, (date) => ({\n iso: date.toISOString(),\n timestamp: date.getTime()\n }), 90);\n this.add(RegExp, (regex) => ({\n pattern: regex.source,\n flags: regex.flags\n }), 90);\n this.add(Map, (map, ctx) => {\n const obj = {};\n map.forEach((value, key) => {\n const keyStr = typeof key === \"object\" ? JSON.stringify(key) : String(key);\n obj[keyStr] = this.serializeInternal(value, {\n ...ctx,\n depth: ctx.depth + 1,\n path: [...ctx.path, keyStr]\n });\n });\n return { __type: \"Map\", entries: obj };\n }, 80);\n this.add(Set, (set, ctx) => ({\n __type: \"Set\",\n values: Array.from(set).map(\n (v, i) => this.serializeInternal(v, {\n ...ctx,\n depth: ctx.depth + 1,\n path: [...ctx.path, `[${i}]`]\n })\n )\n }), 80);\n if (typeof Buffer !== \"undefined\") {\n this.add(Buffer, (buf) => ({\n __type: \"Buffer\",\n length: buf.length,\n preview: buf.slice(0, 50).toString(\"hex\")\n }), 70);\n }\n }\n add(type, serializer, priority = 50) {\n this.serializers.set(type, { type, serializer, priority });\n }\n remove(type) {\n return this.serializers.delete(type);\n }\n has(type) {\n return this.serializers.has(type);\n }\n getAll() {\n return Array.from(this.serializers.values()).sort((a, b) => (b.priority ?? 50) - (a.priority ?? 50));\n }\n findSerializer(value) {\n const sorted = this.getAll();\n for (const entry of sorted) {\n if (value instanceof entry.type) {\n return entry;\n }\n }\n return null;\n }\n serializeInternal(value, context) {\n if (value === null) return null;\n if (value === void 0) return this.config.preserveUndefined ? void 0 : \"[undefined]\";\n if (typeof value === \"function\") return `[Function: ${value.name || \"anonymous\"}]`;\n if (typeof value !== \"object\") return value;\n if (context.depth >= this.config.maxDepth) {\n return \"[Max Depth]\";\n }\n if (context.seen.has(value)) {\n switch (this.config.circular) {\n case \"error\":\n throw new Error(`Circular reference at ${context.path.join(\".\")}`);\n case \"skip\":\n return void 0;\n case \"placeholder\":\n default:\n return \"[Circular]\";\n }\n }\n context.seen.add(value);\n const serializer = this.findSerializer(value);\n if (serializer) {\n return serializer.serializer(value, context);\n }\n if (Array.isArray(value)) {\n return value.map(\n (item, i) => this.serializeInternal(item, {\n ...context,\n depth: context.depth + 1,\n path: [...context.path, `[${i}]`]\n })\n );\n }\n const result = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = this.serializeInternal(val, {\n ...context,\n depth: context.depth + 1,\n path: [...context.path, key]\n });\n }\n return result;\n }\n serialize(value, config) {\n const mergedConfig = { ...this.config, ...config };\n return this.serializeInternal(value, {\n depth: 0,\n maxDepth: mergedConfig.maxDepth,\n path: [],\n seen: /* @__PURE__ */ new WeakSet()\n });\n }\n}\nfunction generateId() {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\nclass HookManager {\n hooks = /* @__PURE__ */ new Map();\n middlewares = [];\n constructor() {\n this.hooks.set(\"beforeLog\", []);\n this.hooks.set(\"afterLog\", []);\n this.hooks.set(\"onError\", []);\n }\n on(event, callback, priority = 50) {\n const registration = {\n id: generateId(),\n event,\n callback,\n priority,\n once: false\n };\n const hooks = this.hooks.get(event);\n hooks.push(registration);\n hooks.sort((a, b) => b.priority - a.priority);\n return () => this.removeHook(event, registration.id);\n }\n once(event, callback, priority = 50) {\n const registration = {\n id: generateId(),\n event,\n callback,\n priority,\n once: true\n };\n const hooks = this.hooks.get(event);\n hooks.push(registration);\n hooks.sort((a, b) => b.priority - a.priority);\n return () => this.removeHook(event, registration.id);\n }\n off(event, callback) {\n const hooks = this.hooks.get(event);\n if (!hooks) return false;\n const index = hooks.findIndex((h) => h.callback === callback);\n if (index >= 0) {\n hooks.splice(index, 1);\n return true;\n }\n return false;\n }\n removeHook(event, id) {\n const hooks = this.hooks.get(event);\n if (hooks) {\n const index = hooks.findIndex((h) => h.id === id);\n if (index >= 0) {\n hooks.splice(index, 1);\n }\n }\n }\n use(middleware, priority = 50) {\n const registration = {\n id: generateId(),\n fn: middleware,\n priority\n };\n this.middlewares.push(registration);\n this.middlewares.sort((a, b) => b.priority - a.priority);\n return () => {\n const index = this.middlewares.findIndex((m) => m.id === registration.id);\n if (index >= 0) {\n this.middlewares.splice(index, 1);\n }\n };\n }\n async emit(event, entry) {\n const hooks = this.hooks.get(event) || [];\n let currentEntry = { ...entry };\n const toRemove = [];\n for (const hook of hooks) {\n try {\n const result = await hook.callback(currentEntry);\n if (result) {\n currentEntry = { ...currentEntry, ...result };\n }\n if (hook.once) {\n toRemove.push(hook.id);\n }\n } catch (error) {\n if (event !== \"onError\") {\n await this.emit(\"onError\", {\n ...currentEntry,\n error,\n hookEvent: event\n });\n }\n }\n }\n toRemove.forEach((id) => this.removeHook(event, id));\n return currentEntry;\n }\n async process(entry) {\n let currentEntry = { ...entry };\n currentEntry = await this.emit(\"beforeLog\", currentEntry);\n if (this.middlewares.length > 0) {\n let index = 0;\n const executeNext = async () => {\n if (index < this.middlewares.length) {\n const middleware = this.middlewares[index++];\n if (middleware) {\n await middleware.fn(currentEntry, executeNext);\n }\n }\n };\n await executeNext();\n }\n return currentEntry;\n }\n async afterProcess(entry) {\n await this.emit(\"afterLog\", entry);\n }\n clear() {\n this.hooks.forEach((hooks) => hooks.length = 0);\n this.middlewares.length = 0;\n }\n getStats() {\n return {\n hooks: {\n beforeLog: this.hooks.get(\"beforeLog\")?.length || 0,\n afterLog: this.hooks.get(\"afterLog\")?.length || 0,\n onError: this.hooks.get(\"onError\")?.length || 0\n },\n middlewares: this.middlewares.length\n };\n }\n}\nconst LOG_LEVELS = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n critical: 4\n};\nfunction generateTransportId() {\n return `transport-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;\n}\nclass TransportManager {\n transports = /* @__PURE__ */ new Map();\n defaultLevel = \"info\";\n constructor(defaultLevel) {\n if (defaultLevel) {\n this.defaultLevel = defaultLevel;\n }\n }\n add(target) {\n const id = generateTransportId();\n const level = target.level || this.defaultLevel;\n let transport;\n if (typeof target.target === \"string\") {\n throw new Error(`String transport targets not supported. Use inline transport object.`);\n } else {\n transport = target.target;\n }\n const entry = {\n id,\n transport,\n options: target.options || {},\n level,\n levelValue: LOG_LEVELS[level]\n };\n this.transports.set(id, entry);\n return id;\n }\n remove(id) {\n const entry = this.transports.get(id);\n if (entry) {\n entry.transport.close?.();\n return this.transports.delete(id);\n }\n return false;\n }\n async write(record) {\n const promises = [];\n for (const entry of this.transports.values()) {\n if (record.levelValue < entry.levelValue) {\n continue;\n }\n let transformedRecord = record;\n if (entry.options.transform) {\n const result2 = entry.options.transform(record);\n if (result2 === null) continue;\n transformedRecord = result2;\n }\n const result = entry.transport.write(transformedRecord);\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n await Promise.all(promises);\n }\n async flush() {\n const promises = [];\n for (const entry of this.transports.values()) {\n if (entry.transport.flush) {\n const result = entry.transport.flush();\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n }\n await Promise.all(promises);\n }\n async close() {\n await this.flush();\n const promises = [];\n for (const entry of this.transports.values()) {\n if (entry.transport.close) {\n const result = entry.transport.close();\n if (result instanceof Promise) {\n promises.push(result);\n }\n }\n }\n await Promise.all(promises);\n this.transports.clear();\n }\n get count() {\n return this.transports.size;\n }\n list() {\n return Array.from(this.transports.keys());\n }\n}\nconst THEME_PRESETS = {\n default: {\n debug: {\n emoji: \"🐞\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #667eea 0%, #764ba2 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #667eea\",\n shadow: \"0 2px 4px rgba(102, 126, 234, 0.3)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #74b9ff\",\n shadow: \"0 2px 4px rgba(116, 185, 255, 0.3)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #fdcb6e 0%, #e17055 100%)\",\n color: \"#2d3436\",\n border: \"1px solid #fdcb6e\",\n shadow: \"0 2px 4px rgba(253, 203, 110, 0.3)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #e84393 0%, #d63031 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #e84393\",\n shadow: \"0 2px 4px rgba(232, 67, 147, 0.3)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #00b894 0%, #00a085 100%)\",\n color: \"#ffffff\",\n border: \"1px solid #00b894\",\n shadow: \"0 2px 4px rgba(0, 184, 148, 0.3)\"\n },\n critical: {\n emoji: \"🔥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #ff3838 0%, #ff1744 100%)\",\n color: \"#ffffff\",\n border: \"2px solid #ff3838\",\n shadow: \"0 4px 8px rgba(255, 56, 56, 0.5)\"\n }\n },\n dark: {\n debug: {\n emoji: \"🌙\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #2d3748 0%, #4a5568 100%)\",\n color: \"#e2e8f0\",\n border: \"1px solid #4a5568\",\n shadow: \"0 2px 4px rgba(45, 55, 72, 0.8)\"\n },\n info: {\n emoji: \"💡\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #1a202c 0%, #2d3748 100%)\",\n color: \"#90cdf4\",\n border: \"1px solid #3182ce\",\n shadow: \"0 2px 4px rgba(26, 32, 44, 0.8)\"\n },\n warn: {\n emoji: \"⚡\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #744210 0%, #975a16 100%)\",\n color: \"#faf089\",\n border: \"1px solid #d69e2e\",\n shadow: \"0 2px 4px rgba(116, 66, 16, 0.8)\"\n },\n error: {\n emoji: \"💀\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #742a2a 0%, #9b2c2c 100%)\",\n color: \"#feb2b2\",\n border: \"1px solid #e53e3e\",\n shadow: \"0 2px 4px rgba(116, 42, 42, 0.8)\"\n },\n success: {\n emoji: \"🎯\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #276749 0%, #2f855a 100%)\",\n color: \"#9ae6b4\",\n border: \"1px solid #38a169\",\n shadow: \"0 2px 4px rgba(39, 103, 73, 0.8)\"\n },\n critical: {\n emoji: \"💥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #1a1a1a 0%, #ff0000 100%)\",\n color: \"#ffffff\",\n border: \"2px solid #ff0000\",\n shadow: \"0 4px 8px rgba(255, 0, 0, 0.9)\"\n }\n },\n neon: {\n debug: {\n emoji: \"⚡\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #0f3460 0%, #e94560 100%)\",\n color: \"#00ffff\",\n border: \"1px solid #00ffff\",\n shadow: \"0 0 10px rgba(0, 255, 255, 0.5)\"\n },\n info: {\n emoji: \"🔮\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #16213e 0%, #0f3460 100%)\",\n color: \"#00ff41\",\n border: \"1px solid #00ff41\",\n shadow: \"0 0 10px rgba(0, 255, 65, 0.5)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #533a03 0%, #e94560 100%)\",\n color: \"#ffff00\",\n border: \"1px solid #ffff00\",\n shadow: \"0 0 10px rgba(255, 255, 0, 0.5)\"\n },\n error: {\n emoji: \"💥\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #5c0a0a 0%, #ff073a 100%)\",\n color: \"#ff073a\",\n border: \"1px solid #ff073a\",\n shadow: \"0 0 10px rgba(255, 7, 58, 0.8)\"\n },\n success: {\n emoji: \"✨\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #0a5c0a 0%, #39ff14 100%)\",\n color: \"#39ff14\",\n border: \"1px solid #39ff14\",\n shadow: \"0 0 10px rgba(57, 255, 20, 0.8)\"\n },\n critical: {\n emoji: \"🌟\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #000000 0%, #ff0080 100%)\",\n color: \"#ff0080\",\n border: \"2px solid #ff0080\",\n shadow: \"0 0 20px rgba(255, 0, 128, 1)\"\n }\n },\n minimal: {\n debug: {\n emoji: \"\",\n label: \"DEBUG\",\n background: \"#f7fafc\",\n color: \"#4a5568\",\n border: \"1px solid #e2e8f0\",\n shadow: \"none\"\n },\n info: {\n emoji: \"\",\n label: \"INFO\",\n background: \"#ebf8ff\",\n color: \"#2b6cb0\",\n border: \"1px solid #bee3f8\",\n shadow: \"none\"\n },\n warn: {\n emoji: \"\",\n label: \"WARN\",\n background: \"#fffbf0\",\n color: \"#c05621\",\n border: \"1px solid #fed7aa\",\n shadow: \"none\"\n },\n error: {\n emoji: \"\",\n label: \"ERROR\",\n background: \"#fef5f5\",\n color: \"#c53030\",\n border: \"1px solid #fca5a5\",\n shadow: \"none\"\n },\n success: {\n emoji: \"\",\n label: \"SUCCESS\",\n background: \"#f0fff4\",\n color: \"#2f855a\",\n border: \"1px solid #9ae6b4\",\n shadow: \"none\"\n },\n critical: {\n emoji: \"\",\n label: \"CRITICAL\",\n background: \"#fef5f5\",\n color: \"#e53e3e\",\n border: \"2px solid #f56565\",\n shadow: \"none\"\n }\n },\n // Additional theme variants can be added here\n light: {\n debug: {\n emoji: \"🔍\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)\",\n color: \"#1565c0\",\n border: \"1px solid #90caf9\",\n shadow: \"0 1px 3px rgba(33, 150, 243, 0.2)\"\n },\n info: {\n emoji: \"ℹ️\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%)\",\n color: \"#7b1fa2\",\n border: \"1px solid #ce93d8\",\n shadow: \"0 1px 3px rgba(156, 39, 176, 0.2)\"\n },\n warn: {\n emoji: \"⚠️\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%)\",\n color: \"#f57c00\",\n border: \"1px solid #ffcc02\",\n shadow: \"0 1px 3px rgba(255, 152, 0, 0.2)\"\n },\n error: {\n emoji: \"❌\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%)\",\n color: \"#d32f2f\",\n border: \"1px solid #f44336\",\n shadow: \"0 1px 3px rgba(244, 67, 54, 0.2)\"\n },\n success: {\n emoji: \"✅\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%)\",\n color: \"#388e3c\",\n border: \"1px solid #4caf50\",\n shadow: \"0 1px 3px rgba(76, 175, 80, 0.2)\"\n },\n critical: {\n emoji: \"🚨\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%)\",\n color: \"#c2185b\",\n border: \"2px solid #e91e63\",\n shadow: \"0 2px 6px rgba(233, 30, 99, 0.3)\"\n }\n },\n cyberpunk: {\n debug: {\n emoji: \"🤖\",\n label: \"DEBUG\",\n background: \"linear-gradient(135deg, #0d1b2a 0%, #415a77 100%)\",\n color: \"#00d4aa\",\n border: \"1px solid #00d4aa\",\n shadow: \"0 0 15px rgba(0, 212, 170, 0.4)\"\n },\n info: {\n emoji: \"🔗\",\n label: \"INFO\",\n background: \"linear-gradient(135deg, #1b263b 0%, #0d1b2a 100%)\",\n color: \"#00b4d8\",\n border: \"1px solid #00b4d8\",\n shadow: \"0 0 15px rgba(0, 180, 216, 0.4)\"\n },\n warn: {\n emoji: \"⚡\",\n label: \"WARN\",\n background: \"linear-gradient(135deg, #f72585 0%, #b5179e 100%)\",\n color: \"#ffff3f\",\n border: \"1px solid #ffff3f\",\n shadow: \"0 0 15px rgba(255, 255, 63, 0.4)\"\n },\n error: {\n emoji: \"💀\",\n label: \"ERROR\",\n background: \"linear-gradient(135deg, #7209b7 0%, #480ca8 100%)\",\n color: \"#ff006e\",\n border: \"1px solid #ff006e\",\n shadow: \"0 0 15px rgba(255, 0, 110, 0.6)\"\n },\n success: {\n emoji: \"⚡\",\n label: \"SUCCESS\",\n background: \"linear-gradient(135deg, #003566 0%, #001d3d 100%)\",\n color: \"#00f5ff\",\n border: \"1px solid #00f5ff\",\n shadow: \"0 0 15px rgba(0, 245, 255, 0.4)\"\n },\n critical: {\n emoji: \"💥\",\n label: \"CRITICAL\",\n background: \"linear-gradient(135deg, #000000 0%, #ff0040 100%)\",\n color: \"#ff0040\",\n border: \"2px solid #ff0040\",\n shadow: \"0 0 25px rgba(255, 0, 64, 0.8)\"\n }\n }\n};\nconst BANNER_VARIANTS = {\n simple: {\n text: \"🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀\",\n style: \"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold; font-size: 14px;\"\n },\n ascii: {\n text: `\n ___ ____ _ __ ___ _ __ _____ _____ ____ __ ___ _____ _____ _____ ____ \n / _ \\\\ / __ \\\\| | / / / _ \\\\ | \\\\ | |/ ____| ____| _ \\\\ | | / _ \\\\ / ____| ___| _ | _ \\\\ \n / /_\\\\ \\\\ / / _\\` | |/ / / /_\\\\ \\\\ | \\\\| | | | |__ | | | | | | / / \\\\ \\\\| | __| |_ | |_| | |_) |\n | _ || | (_| | < | _ | | . \\` | | | __| | | | | | | | | | | | |_ | _| | /| _ < \n | | | |\\\\ \\\\__,_|_|\\\\_\\\\ | | | | | |\\\\ | |___| |____| |_| | | |__\\\\ \\\\_/ /| |__| | |___| |\\\\ \\\\| |_) |\n \\\\_| |_/ \\\\____/ \\\\_| |_/ |_| \\\\_|\\\\_____|______|____/ |_____/\\\\___/ \\\\_____|_____|_| \\\\_|____/\n\n Advanced Logger v2.0.0 - Console Excellence`,\n style: 'font-family: \"Courier New\", Consolas, Monaco, monospace; color: #667eea; font-size: 11px; line-height: 1.2;'\n },\n unicode: {\n text: `\n╔══════════════════════════════════════════════════════════════════════════╗\n║ 🚀 ADVANCED LOGGER v2.0.0 ║\n║ State-of-the-art Console Styling ║ \n╚══════════════════════════════════════════════════════════════════════════╝`,\n style: 'font-family: \"Courier New\", Consolas, Monaco, monospace; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; font-size: 12px; line-height: 1.3;'\n },\n svg: {\n text: \" \",\n style: `\n background-image: url(\"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 80'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='8'/><text x='200' y='30' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>🚀 ADVANCED LOGGER</text><text x='200' y='50' text-anchor='middle' fill='white' font-family='monospace' font-size='12'>State-of-the-art Console Styling</text><text x='200' y='65' text-anchor='middle' fill='white' font-family='monospace' font-size='10'>v2.0.0</text></svg>\");\n background-repeat: no-repeat;\n background-size: 400px 80px;\n padding: 40px 200px;\n color: transparent;\n display: inline-block;\n border-radius: 8px;\n `\n },\n animated: {\n text: \" 🚀 ADVANCED LOGGER v2.0.0 \",\n style: `\n background: linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2);\n background-size: 400% 400%;\n color: white;\n padding: 15px 25px;\n border-radius: 10px;\n font-weight: bold;\n font-size: 14px;\n font-family: monospace;\n animation: gradientShift 3s ease infinite;\n display: inline-block;\n `\n }\n};\nconst THEME_BANNERS = {\n default: {\n simple: \"🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀\",\n style: \"background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold;\"\n },\n dark: {\n simple: \"🌙 ADVANCED LOGGER v2.0.0 - Dark Mode Console Excellence 🌙\",\n style: \"background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); color: #e2e8f0; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #4a5568;\"\n },\n neon: {\n simple: \"⚡ ADVANCED LOGGER v2.0.0 - Cyberpunk Console Experience ⚡\",\n style: \"background: linear-gradient(135deg, #0f3460 0%, #e94560 100%); color: #00ffff; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00ffff;\"\n },\n minimal: {\n simple: \"ADVANCED LOGGER v2.0.0 - Clean Console Styling\",\n style: \"background: #f7fafc; color: #2d3748; padding: 8px 16px; border: 1px solid #e2e8f0; border-radius: 4px; font-weight: 500;\"\n },\n light: {\n simple: \"☀️ ADVANCED LOGGER v2.0.0 - Bright Console Styling ☀️\",\n style: \"background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); color: #495057; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #dee2e6;\"\n },\n cyberpunk: {\n simple: \"🤖 ADVANCED LOGGER v2.0.0 - Neural Console Interface 🤖\",\n style: \"background: linear-gradient(135deg, #0d1b2a 0%, #415a77 100%); color: #00d4aa; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00d4aa; border: 1px solid #00d4aa;\"\n }\n};\nfunction detectBannerCapabilities() {\n const userAgent = navigator.userAgent;\n const isChrome = /Chrome/.test(userAgent);\n const isFirefox = /Firefox/.test(userAgent);\n const isSafari = /Safari/.test(userAgent) && !/Chrome/.test(userAgent);\n const supportsSVG = !!document.createElementNS && !!document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\").createSVGRect;\n const supportsAnimations = typeof document !== \"undefined\" && \"animationName\" in document.createElement(\"div\").style;\n if (supportsAnimations && isChrome) {\n return \"animated\";\n } else if (supportsSVG && (isChrome || isFirefox)) {\n return \"svg\";\n } else if (isChrome || isFirefox) {\n return \"unicode\";\n } else if (isSafari) {\n return \"ascii\";\n }\n return \"simple\";\n}\nfunction displayInitBanner(bannerType) {\n const selectedType = bannerType || detectBannerCapabilities();\n const banner = BANNER_VARIANTS[selectedType];\n if (selectedType === \"animated\") {\n const style = document.createElement(\"style\");\n style.textContent = `\n @keyframes gradientShift {\n 0% { background-position: 0% 50%; }\n 50% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n `;\n document.head.appendChild(style);\n }\n console.log(`%c${banner.text}`, banner.style);\n const features = [\n \"🎨 Advanced CSS Console Styling\",\n \"📍 Automatic Stack Trace Parsing\",\n \"🔧 Scoped Loggers & Prefixes\",\n \"⚡ Performance Timers\",\n \"🎯 Verbosity Filtering\",\n \"🔌 Extensible Handlers\",\n \"📱 Modern TypeScript Patterns\",\n \"📤 Export & Clipboard Support\"\n ];\n console.group(`%c✨ Features`, \"background: #f8f9fa; color: #495057; padding: 4px 8px; border-radius: 4px; font-weight: bold;\");\n features.forEach((feature) => {\n console.log(`%c${feature}`, \"color: #6c757d; font-size: 13px;\");\n });\n console.groupEnd();\n console.log(\"\");\n}\nclass BaseStyler {\n builder;\n constructor(builder = new StyleBuilder()) {\n this.builder = builder;\n }\n /**\n * Primary brand color (typically blue)\n */\n primary() {\n return this.color(\"#007bff\");\n }\n /**\n * Secondary color (typically gray)\n */\n secondary() {\n return this.color(\"#6c757d\");\n }\n /**\n * Accent color for highlights\n */\n accent() {\n return this.color(\"#17a2b8\");\n }\n /**\n * Muted/subtle color - automatically adaptive\n */\n muted() {\n const mutedColors = { light: \"#6c757d\", dark: \"#a0aec0\" };\n return this.color(getAdaptiveColor(mutedColors));\n }\n /**\n * Success color (green)\n */\n success() {\n return this.color(\"#28a745\");\n }\n /**\n * Warning color (yellow/orange)\n */\n warning() {\n return this.color(\"#ffc107\");\n }\n /**\n * Danger/error color (red)\n */\n danger() {\n return this.color(\"#dc3545\");\n }\n /**\n * Monospace font family\n */\n mono() {\n this.builder.font('Monaco, Consolas, \"Courier New\", monospace');\n return this;\n }\n /**\n * System font family\n */\n system() {\n this.builder.font('system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif');\n return this;\n }\n /**\n * Readable font optimized for text\n */\n readable() {\n this.builder.font('Georgia, \"Times New Roman\", serif');\n return this;\n }\n /**\n * Compact spacing\n */\n compact() {\n this.builder.padding(\"1px 4px\").margin(\"0 1px\");\n return this;\n }\n /**\n * Spacious layout\n */\n spacious() {\n this.builder.padding(\"6px 12px\").margin(\"2px 4px\");\n return this;\n }\n /**\n * Inline display\n */\n inline() {\n this.builder.display(\"inline-block\");\n return this;\n }\n /**\n * Glass morphism effect\n */\n glassmorphic() {\n this.builder.css(\"backdrop-filter\", \"blur(10px)\").css(\"background\", \"rgba(255, 255, 255, 0.1)\").border(\"1px solid rgba(255, 255, 255, 0.2)\").rounded(\"8px\");\n return this;\n }\n /**\n * Neon glow effect\n */\n neon() {\n const neonColor = \"#00ffff\";\n this.builder.color(neonColor).border(`1px solid ${neonColor}`).shadow(`0 0 10px ${neonColor}, 0 0 20px ${neonColor}`).css(\"text-shadow\", `0 0 5px ${neonColor}`);\n return this;\n }\n /**\n * Gradient background\n */\n gradient(from = \"#667eea\", to = \"#764ba2\") {\n this.builder.bg(`linear-gradient(135deg, ${from} 0%, ${to} 100%)`);\n return this;\n }\n /**\n * Bold text\n */\n bold() {\n this.builder.bold();\n return this;\n }\n /**\n * Set color with automatic adaptation\n */\n color(color) {\n this.builder.color(color);\n return this;\n }\n /**\n * Build the final CSS string\n */\n build() {\n return this.builder.build();\n }\n}\nclass TimestampStyler extends BaseStyler {\n /**\n * Default timestamp style - subtle and informative\n */\n default() {\n this.muted().mono();\n this.builder.size(\"11px\");\n return this;\n }\n /**\n * Hide timestamp\n */\n hidden() {\n this.builder.display(\"none\");\n return this;\n }\n /**\n * Minimal timestamp (just time, no date)\n */\n minimal() {\n this.muted().mono();\n this.builder.size(\"10px\").opacity(0.7);\n return this;\n }\n /**\n * Set font size\n */\n size(size) {\n this.builder.size(size);\n return this;\n }\n}\nclass LevelStyler extends BaseStyler {\n /**\n * Colorful gradient badge\n */\n badge() {\n this.builder.padding(\"2px 8px\").rounded(\"4px\").bold().color(\"#ffffff\");\n return this;\n }\n /**\n * Glowing effect for dark themes\n */\n glowing() {\n return this.neon().badge();\n }\n /**\n * Minimal flat style\n */\n flat() {\n this.builder.padding(\"1px 6px\").rounded(\"2px\").border(\"1px solid currentColor\").css(\"background\", \"transparent\");\n return this;\n }\n /**\n * Uppercase text\n */\n uppercase() {\n this.builder.uppercase();\n return this;\n }\n}\nclass PrefixStyler extends BaseStyler {\n /**\n * Dark theme prefix\n */\n dark() {\n const prefixColors = { light: \"#2d3748\", dark: \"#4a5568\" };\n const textColors = { light: \"#e2e8f0\", dark: \"#f7fafc\" };\n this.builder.bg(getAdaptiveColor(prefixColors)).color(getAdaptiveColor(textColors)).padding(\"2px 6px\").rounded(\"3px\").bold().mono().size(\"11px\");\n return this;\n }\n /**\n * Light theme prefix\n */\n light() {\n this.builder.bg(\"#f8f9fa\").color(\"#495057\").padding(\"2px 6px\").rounded(\"3px\").bold().mono().size(\"11px\").border(\"1px solid #dee2e6\");\n return this;\n }\n /**\n * Compact prefix\n */\n compact() {\n this.builder.padding(\"1px 4px\").size(\"10px\").rounded(\"2px\");\n return this;\n }\n}\nclass MessageStyler extends BaseStyler {\n /**\n * Readable message text - automatically adaptive\n */\n readable() {\n this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).system().size(\"14px\");\n return this;\n }\n /**\n * Code-style monospace text\n */\n code() {\n this.builder.mono().size(\"13px\").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).bg(\"rgba(0, 0, 0, 0.05)\").padding(\"1px 4px\").rounded(\"3px\");\n return this;\n }\n /**\n * Large, prominent text\n */\n large() {\n this.builder.size(\"16px\").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText));\n return this;\n }\n}\nclass LocationStyler extends BaseStyler {\n /**\n * Subtle location info - automatically adaptive\n */\n subtle() {\n this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.location)).mono().size(\"11px\").opacity(0.7);\n return this;\n }\n /**\n * Hide location info\n */\n hidden() {\n this.builder.display(\"none\");\n return this;\n }\n /**\n * Clickable style (for IDE integration)\n */\n clickable() {\n this.subtle();\n this.builder.css(\"text-decoration\", \"underline\").cursor(\"pointer\");\n return this;\n }\n}\nclass LogStyleBuilder {\n logStyles = {};\n logger;\n constructor(logger) {\n this.logger = logger;\n }\n /**\n * Configure timestamp styling\n */\n timestamp() {\n return new TimestampStyleBuilderProxy(this);\n }\n /**\n * Configure level badge styling\n */\n level() {\n return new LevelStyleBuilderProxy(this);\n }\n /**\n * Configure prefix styling\n */\n prefix() {\n return new PrefixStyleBuilderProxy(this);\n }\n /**\n * Configure message text styling\n */\n message() {\n return new MessageStyleBuilderProxy(this);\n }\n /**\n * Configure location info styling\n */\n location() {\n return new LocationStyleBuilderProxy(this);\n }\n /**\n * Use a predefined preset\n */\n usePreset(presetName) {\n console.warn(`Preset '${presetName}' will be available in next implementation phase`);\n return this;\n }\n /**\n * Customize with partial configuration\n */\n customize(overrides) {\n this.logStyles = { ...this.logStyles, ...overrides };\n return this;\n }\n /**\n * Set layout spacing\n */\n spacing(type) {\n if (!this.logStyles.layout) {\n this.logStyles.layout = { spacing: type };\n } else {\n this.logStyles.layout.spacing = type;\n }\n switch (type) {\n case \"compact\":\n this.logStyles.layout.innerPadding = \"1px\";\n this.logStyles.layout.outerMargin = \"0px\";\n break;\n case \"spacious\":\n this.logStyles.layout.innerPadding = \"4px\";\n this.logStyles.layout.outerMargin = \"2px\";\n break;\n default:\n this.logStyles.layout.innerPadding = \"2px\";\n this.logStyles.layout.outerMargin = \"1px\";\n }\n return this;\n }\n /**\n * Set backdrop filter for glassmorphism effects\n */\n backdrop(filter) {\n this.logStyles.backdrop = filter;\n return this;\n }\n /**\n * Set overall transparency\n */\n transparency(value) {\n this.logStyles.transparency = Math.max(0, Math.min(1, value));\n return this;\n }\n /**\n * Apply the configured styles to the logger\n */\n apply() {\n this.logger._customLogStyles = this.logStyles;\n console.log(\"Applied log styles:\", this.logStyles);\n }\n /**\n * Get current configuration (for debugging)\n */\n getConfig() {\n return { ...this.logStyles };\n }\n /**\n * Internal method to update part configuration\n */\n _updatePartConfig(part, styles) {\n if (part === \"layout\" || part === \"backdrop\" || part === \"transparency\") {\n return;\n }\n if (!this.logStyles[part]) {\n this.logStyles[part] = {};\n }\n this.logStyles[part].style = styles;\n }\n}\nclass PartStyleBuilderProxy {\n parentBuilder;\n partName;\n constructor(parentBuilder, partName) {\n this.parentBuilder = parentBuilder;\n this.partName = partName;\n }\n /**\n * Return to the main builder for chaining other parts\n */\n and() {\n return this.parentBuilder;\n }\n /**\n * Apply styles and finish configuration\n */\n apply() {\n this.parentBuilder.apply();\n }\n /**\n * Helper to apply styles to the parent builder\n */\n applyStyles(styler) {\n const styles = styler.build();\n this.parentBuilder._updatePartConfig(this.partName, styles);\n return this;\n }\n}\nclass TimestampStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"timestamp\");\n }\n default() {\n return this.applyStyles(new TimestampStyler().default());\n }\n hidden() {\n return this.applyStyles(new TimestampStyler().hidden());\n }\n minimal() {\n return this.applyStyles(new TimestampStyler().minimal());\n }\n muted() {\n return this.applyStyles(new TimestampStyler().muted());\n }\n mono() {\n return this.applyStyles(new TimestampStyler().mono());\n }\n compact() {\n return this.applyStyles(new TimestampStyler().compact());\n }\n}\nclass LevelStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"level\");\n }\n badge() {\n return this.applyStyles(new LevelStyler().badge());\n }\n gradient(from, to) {\n return this.applyStyles(new LevelStyler().gradient(from, to));\n }\n glowing() {\n return this.applyStyles(new LevelStyler().glowing());\n }\n flat() {\n return this.applyStyles(new LevelStyler().flat());\n }\n bold() {\n return this.applyStyles(new LevelStyler().bold());\n }\n uppercase() {\n return this.applyStyles(new LevelStyler().uppercase());\n }\n neon() {\n return this.applyStyles(new LevelStyler().neon());\n }\n}\nclass PrefixStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"prefix\");\n }\n dark() {\n return this.applyStyles(new PrefixStyler().dark());\n }\n light() {\n return this.applyStyles(new PrefixStyler().light());\n }\n compact() {\n return this.applyStyles(new PrefixStyler().compact());\n }\n muted() {\n return this.applyStyles(new PrefixStyler().muted());\n }\n mono() {\n return this.applyStyles(new PrefixStyler().mono());\n }\n}\nclass MessageStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"message\");\n }\n readable() {\n return this.applyStyles(new MessageStyler().readable());\n }\n code() {\n return this.applyStyles(new MessageStyler().code());\n }\n large() {\n return this.applyStyles(new MessageStyler().large());\n }\n system() {\n return this.applyStyles(new MessageStyler().system());\n }\n mono() {\n return this.applyStyles(new MessageStyler().mono());\n }\n}\nclass LocationStyleBuilderProxy extends PartStyleBuilderProxy {\n constructor(parentBuilder) {\n super(parentBuilder, \"location\");\n }\n subtle() {\n return this.applyStyles(new LocationStyler().subtle());\n }\n hidden() {\n return this.applyStyles(new LocationStyler().hidden());\n }\n clickable() {\n return this.applyStyles(new LocationStyler().clickable());\n }\n muted() {\n return this.applyStyles(new LocationStyler().muted());\n }\n mono() {\n return this.applyStyles(new LocationStyler().mono());\n }\n}\nfunction createLogStyleBuilder(logger) {\n return new LogStyleBuilder(logger);\n}\nconst SMART_PRESETS = {\n /**\n * Default preset - works perfectly out-of-the-box\n * Clean, readable, automatically adaptive to dark/light themes\n */\n default: {\n layout: {\n spacing: \"normal\",\n innerPadding: \"2px\",\n outerMargin: \"1px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"Monaco, Consolas, monospace\",\n size: \"11px\"\n },\n level: {\n show: true,\n style: \"badge\",\n uppercase: false,\n padding: \"2px 8px\"\n },\n prefix: {\n show: true,\n style: \"dark\",\n // Automatically adaptive\n padding: \"2px 6px\"\n },\n message: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"system-ui, -apple-system, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: true,\n color: \"auto\",\n // Automatically adaptive\n font: \"Monaco, Consolas, monospace\",\n size: \"11px\"\n }\n },\n /**\n * Cyberpunk preset - neon colors, glowing effects, dark theme\n */\n cyberpunk: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"1px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: true,\n color: \"#00ffff\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\",\n style: \"neon\"\n },\n level: {\n show: true,\n style: \"glowing\",\n uppercase: true,\n padding: \"2px 8px\"\n },\n prefix: {\n show: true,\n color: \"#ff0080\",\n background: \"rgba(255, 0, 128, 0.1)\",\n border: \"1px solid #ff0080\",\n style: \"neon\"\n },\n message: {\n show: true,\n color: \"#00ff41\",\n font: \"Monaco, Consolas, monospace\",\n size: \"13px\"\n },\n location: {\n show: false\n // Hidden for cleaner look\n },\n backdrop: \"blur(2px)\",\n transparency: 0.9\n },\n /**\n * Glassmorphism preset - modern blur effects, transparency\n */\n glassmorphism: {\n layout: {\n spacing: \"spacious\",\n innerPadding: \"4px\",\n outerMargin: \"2px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\",\n style: \"glassmorphic\"\n },\n level: {\n show: true,\n style: \"glassmorphic\",\n uppercase: false,\n padding: \"4px 12px\"\n },\n prefix: {\n show: true,\n style: \"glassmorphic\",\n padding: \"3px 8px\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\",\n style: \"glassmorphic\"\n },\n backdrop: \"blur(10px)\",\n transparency: 0.8\n },\n /**\n * Minimal preset - clean, no decorations, maximum readability\n */\n minimal: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"0px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: false\n // Hidden for minimal look\n },\n level: {\n show: true,\n style: \"flat\",\n uppercase: true,\n padding: \"0px 4px\",\n border: \"none\",\n background: \"transparent\"\n },\n prefix: {\n show: true,\n style: \"flat\",\n padding: \"0px 4px\",\n border: \"none\",\n background: \"transparent\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: false\n // Hidden for minimal look\n }\n },\n /**\n * Debug preset - monospace, detailed, compact for development\n */\n debug: {\n layout: {\n spacing: \"compact\",\n innerPadding: \"1px\",\n outerMargin: \"0px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n level: {\n show: true,\n style: \"compact\",\n uppercase: true,\n padding: \"1px 4px\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n prefix: {\n show: true,\n style: \"compact\",\n padding: \"1px 4px\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\"\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"12px\"\n },\n location: {\n show: true,\n color: \"auto\",\n font: \"Monaco, Consolas, monospace\",\n size: \"10px\",\n style: \"clickable\"\n }\n },\n /**\n * Production preset - clean, essential info only\n */\n production: {\n layout: {\n spacing: \"normal\",\n innerPadding: \"2px\",\n outerMargin: \"1px\"\n },\n timestamp: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"11px\"\n },\n level: {\n show: true,\n style: \"badge\",\n uppercase: false,\n padding: \"2px 6px\"\n },\n prefix: {\n show: false\n // Hidden in production\n },\n message: {\n show: true,\n color: \"auto\",\n font: \"system-ui, sans-serif\",\n size: \"14px\"\n },\n location: {\n show: false\n // Hidden in production\n }\n }\n};\nfunction getSmartPreset(name) {\n return SMART_PRESETS[name] || null;\n}\nfunction getAvailablePresets() {\n return Object.keys(SMART_PRESETS);\n}\nfunction hasPreset(name) {\n return name in SMART_PRESETS;\n}\nfunction stripAnsi(str) {\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\nfunction getVisibleLength(str) {\n return stripAnsi(str).length;\n}\nfunction padToWidth(str, width, align = \"left\") {\n const visibleLen = getVisibleLength(str);\n if (visibleLen >= width) return str;\n const padding = width - visibleLen;\n switch (align) {\n case \"right\":\n return \" \".repeat(padding) + str;\n case \"center\":\n const leftPad = Math.floor(padding / 2);\n const rightPad = padding - leftPad;\n return \" \".repeat(leftPad) + str + \" \".repeat(rightPad);\n case \"left\":\n default:\n return str + \" \".repeat(padding);\n }\n}\nfunction formatWithRightAlign(leftContent, rightContent, maxWidth) {\n const width = maxWidth ?? getTerminalWidth();\n const leftLen = getVisibleLength(leftContent);\n const rightLen = getVisibleLength(rightContent);\n const gap = width - leftLen - rightLen;\n if (gap <= 1) {\n return `${leftContent} ${rightContent}`;\n }\n return `${leftContent}${\" \".repeat(gap)}${rightContent}`;\n}\nfunction formatColumns(columns, maxWidth, colorCapability = \"full\") {\n const width = maxWidth ?? getTerminalWidth();\n columns.length;\n const columnsWithWidths = columns.map((col, idx) => {\n if (col.width) return { ...col, calculatedWidth: col.width };\n const remainingWidth = width - columns.filter((c, i) => i !== idx && c.width).reduce((sum, c) => sum + (c.width ?? 0), 0);\n const autoColumns = columns.filter((c) => !c.width).length;\n const calculatedWidth = Math.floor(remainingWidth / autoColumns);\n return { ...col, calculatedWidth };\n });\n return columnsWithWidths.map((col) => {\n let content = col.content;\n if (col.color && colorCapability !== \"none\") {\n const colorCode = getANSIForeground(col.color, colorCapability);\n content = `${colorCode}${content}${ANSI.reset}`;\n }\n return padToWidth(content, col.calculatedWidth, col.align);\n }).join(\"\");\n}\nfunction formatKeyValue(obj, colorCapability = \"full\", options = {}) {\n const {\n separator = \" \",\n keyColor = \"#888888\",\n valueColor = \"#00ffff\"\n } = options;\n const entries = Object.entries(obj);\n if (entries.length === 0) return \"\";\n const keyColorCode = colorCapability !== \"none\" ? getANSIForeground(keyColor, colorCapability) : \"\";\n const valueColorCode = colorCapability !== \"none\" ? getANSIForeground(valueColor, colorCapability) : \"\";\n const reset = colorCapability !== \"none\" ? ANSI.reset : \"\";\n return entries.map(([key, value]) => {\n const valueStr = typeof value === \"object\" ? JSON.stringify(value) : String(value);\n return `${keyColorCode}${key}:${reset} ${valueColorCode}${valueStr}${reset}`;\n }).join(separator);\n}\nfunction isKeyValueObject(obj) {\n if (typeof obj !== \"object\" || obj === null) return false;\n if (Array.isArray(obj)) return false;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return false;\n const values = Object.values(obj);\n return values.every(\n (v) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\" || v === null\n );\n}\nfunction formatBadge(badge, style = \"brackets\", colorCapability = \"full\", color) {\n const colorCode = color && colorCapability !== \"none\" ? getANSIForeground(color, colorCapability) : \"\";\n const reset = colorCapability !== \"none\" ? ANSI.reset : \"\";\n const bgBlack = colorCapability !== \"none\" ? ANSI.bg.black : \"\";\n const text = badge.toUpperCase();\n switch (style) {\n case \"rounded\":\n return `${bgBlack}${colorCode}⟨${text}⟩${reset}`;\n case \"plain\":\n return `${colorCode}${text}${reset}`;\n case \"unicode\":\n return `${bgBlack}${colorCode}╭${text}╮${reset}`;\n case \"pill\":\n return `${bgBlack}${colorCode}⦗${text}⦘${reset}`;\n case \"brackets\":\n default:\n return `${bgBlack}${colorCode}[${text}]${reset}`;\n }\n}\nfunction formatTimestamp(date = /* @__PURE__ */ new Date(), format = \"time\") {\n switch (format) {\n case \"iso\":\n return date.toISOString();\n case \"date\":\n return date.toISOString().split(\"T\")[0] ?? \"\";\n case \"time\":\n return date.toTimeString().slice(0, 8);\n case \"timeMs\":\n return date.toTimeString().slice(0, 8) + \".\" + String(date.getMilliseconds()).padStart(3, \"0\");\n case \"relative\":\n return formatRelativeTime(date);\n case \"elapsed\":\n return formatElapsedTime(date);\n case \"custom\":\n default:\n return date.toLocaleTimeString();\n }\n}\nlet startTime = null;\nfunction formatRelativeTime(date) {\n if (startTime === null) {\n startTime = Date.now();\n }\n const diff = date.getTime() - startTime;\n if (diff < 1e3) {\n return `+${diff}ms`;\n } else if (diff < 6e4) {\n return `+${(diff / 1e3).toFixed(1)}s`;\n } else {\n const mins = Math.floor(diff / 6e4);\n const secs = Math.floor(diff % 6e4 / 1e3);\n return `+${mins}m${secs}s`;\n }\n}\nfunction formatElapsedTime(date) {\n if (startTime === null) {\n startTime = Date.now();\n }\n const diff = date.getTime() - startTime;\n const hours = Math.floor(diff / 36e5);\n const mins = Math.floor(diff % 36e5 / 6e4);\n const secs = Math.floor(diff % 6e4 / 1e3);\n return `${String(hours).padStart(2, \"0\")}:${String(mins).padStart(2, \"0\")}:${String(secs).padStart(2, \"0\")}`;\n}\nfunction resetStartTime() {\n startTime = Date.now();\n}\nfunction applyLogOptions(message, options, colorCapability = \"full\") {\n let result = message;\n if (options.rightAlign) {\n result = formatWithRightAlign(message, options.rightAlign);\n }\n return result;\n}\nclass ScopedLogger {\n parent;\n scopeName;\n badgeList = [];\n contextStack = [];\n _timers;\n constructor(parent, scopeName) {\n this.parent = parent;\n this.scopeName = scopeName;\n }\n get timers() {\n if (!this._timers) this._timers = /* @__PURE__ */ new Map();\n return this._timers;\n }\n getBindings() {\n return {\n scope: this.getScopePrefix(),\n badges: this.badgeList.length > 0 ? [...this.badgeList] : void 0\n };\n }\n getScopePrefix() {\n if (this.contextStack.length === 0) return this.scopeName;\n return [this.scopeName, ...this.contextStack].join(\":\");\n }\n badges(badges) {\n this.badgeList = [...badges];\n return this;\n }\n badge(badge) {\n if (!this.badgeList.includes(badge)) {\n this.badgeList.push(badge);\n }\n return this;\n }\n clearBadges() {\n this.badgeList = [];\n return this;\n }\n style(presetName) {\n this.parent.setTheme(presetName);\n return this;\n }\n context(contextName) {\n return new ContextLogger(this, contextName);\n }\n time(label) {\n this.timers.set(label, {\n label: `${this.scopeName}:${label}`,\n startTime: performance.now()\n });\n }\n timeEnd(label) {\n const timer = this.timers.get(label);\n if (!timer) {\n this.warn(`Timer '${label}' not found`);\n return void 0;\n }\n const elapsed = performance.now() - timer.startTime;\n this.timers.delete(label);\n this.success(`Timer: ${label} - ${elapsed.toFixed(2)}ms`);\n return elapsed;\n }\n debug(...args) {\n this.parent.logWithBindings(this.getBindings(), \"debug\", ...args);\n }\n info(...args) {\n this.parent.logWithBindings(this.getBindings(), \"info\", ...args);\n }\n warn(...args) {\n this.parent.logWithBindings(this.getBindings(), \"warn\", ...args);\n }\n error(...args) {\n this.parent.logWithBindings(this.getBindings(), \"error\", ...args);\n }\n success(...args) {\n const bindings = this.getBindings();\n this.parent.logWithBindings(bindings, \"info\", ...args);\n }\n critical(...args) {\n this.parent.logWithBindings(this.getBindings(), \"critical\", ...args);\n }\n trace(...args) {\n this.parent.logWithBindings(this.getBindings(), \"debug\", ...args);\n console.trace(`[${this.scopeName}]`);\n }\n _pushContext(context) {\n this.contextStack.push(context);\n }\n _popContext() {\n this.contextStack.pop();\n }\n}\nclass APILogger extends ScopedLogger {\n constructor(parent, apiName) {\n super(parent, `API:${apiName}`);\n this.badge(\"API\");\n }\n slow(message, duration) {\n this.badge(\"SLOW\");\n const msg = duration ? `${message} (${duration}ms)` : message;\n this.warn(msg);\n }\n rateLimit(message) {\n this.badge(\"RATE_LIMIT\");\n this.warn(message);\n }\n auth(message) {\n this.badge(\"AUTH\");\n this.error(message);\n }\n deprecated(message) {\n this.badge(\"DEPRECATED\");\n this.warn(message);\n }\n}\nclass ComponentLogger extends ScopedLogger {\n constructor(parent, componentName) {\n super(parent, componentName);\n this.badge(\"COMPONENT\");\n }\n lifecycle(event, message) {\n this.badge(\"LIFECYCLE\");\n const msg = message ? `${event}: ${message}` : event;\n this.info(msg);\n }\n stateChange(from, to, data) {\n this.badge(\"STATE\");\n const msg = `${from} → ${to}`;\n if (data) {\n this.info(msg, data);\n } else {\n this.info(msg);\n }\n }\n propsChange(changes) {\n this.badge(\"PROPS\");\n this.debug(\"Props changed:\", changes);\n }\n}\nclass ContextLogger {\n parentLogger;\n contextName;\n constructor(parentLogger, contextName) {\n this.parentLogger = parentLogger;\n this.contextName = contextName;\n }\n run(fn) {\n this.parentLogger._pushContext(this.contextName);\n try {\n return fn();\n } finally {\n this.parentLogger._popContext();\n }\n }\n async runAsync(fn) {\n this.parentLogger._pushContext(this.contextName);\n try {\n return await fn();\n } finally {\n this.parentLogger._popContext();\n }\n }\n start() {\n this.parentLogger._pushContext(this.contextName);\n }\n end() {\n this.parentLogger._popContext();\n }\n debug(...args) {\n this.parentLogger.debug(...args);\n }\n info(...args) {\n this.parentLogger.info(...args);\n }\n warn(...args) {\n this.parentLogger.warn(...args);\n }\n error(...args) {\n this.parentLogger.error(...args);\n }\n success(...args) {\n this.parentLogger.success(...args);\n }\n critical(...args) {\n this.parentLogger.critical(...args);\n }\n}\nclass ExportLogHandler {\n buffer = [];\n maxSize;\n groupDepth = 0;\n currentGroup;\n constructor(maxSize = BUFFER_LIMITS.DEFAULT_SIZE) {\n this.maxSize = Math.min(Math.max(maxSize, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);\n }\n /**\n * Handle incoming log and store in buffer\n */\n handle(level, message, args, metadata) {\n const entry = {\n id: generateLogId(),\n timestamp: metadata.timestamp,\n level,\n prefix: metadata.prefix,\n message,\n args,\n location: metadata.stackInfo,\n groupInfo: this.groupDepth > 0 ? {\n depth: this.groupDepth,\n groupName: this.currentGroup\n } : void 0\n };\n this.buffer.push(entry);\n if (this.buffer.length > this.maxSize) {\n this.buffer.shift();\n }\n }\n /**\n * Set group tracking for nested logs\n */\n setGroupInfo(depth, groupName) {\n this.groupDepth = depth;\n this.currentGroup = groupName;\n }\n /**\n * Get buffer statistics\n */\n getBufferStats() {\n const levelCounts = this.buffer.reduce((acc, entry) => {\n const currentCount = acc[entry.level] ? acc[entry.level] : 0;\n acc[entry.level] = currentCount + 1;\n return acc;\n }, {});\n let oldestLog;\n let newestLog;\n if (this.buffer.length > 0) {\n const firstEntry = this.buffer[0];\n const lastEntry = this.buffer[this.buffer.length - 1];\n if (firstEntry && firstEntry.timestamp) {\n oldestLog = new Date(firstEntry.timestamp);\n }\n if (lastEntry && lastEntry.timestamp) {\n newestLog = new Date(lastEntry.timestamp);\n }\n }\n return {\n size: this.buffer.length,\n maxSize: this.maxSize,\n usage: this.buffer.length / this.maxSize * 100,\n oldestLog,\n newestLog,\n levelCounts: {\n debug: levelCounts.debug ? levelCounts.debug : 0,\n info: levelCounts.info ? levelCounts.info : 0,\n warn: levelCounts.warn ? levelCounts.warn : 0,\n error: levelCounts.error ? levelCounts.error : 0,\n critical: levelCounts.critical ? levelCounts.critical : 0\n }\n };\n }\n /**\n * Clear the buffer\n */\n clearBuffer() {\n this.buffer = [];\n }\n /**\n * Set buffer size (with limits)\n */\n setBufferSize(size) {\n this.maxSize = Math.min(Math.max(size, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);\n if (this.buffer.length > this.maxSize) {\n this.buffer = this.buffer.slice(-this.maxSize);\n }\n }\n /**\n * Filter logs based on criteria\n */\n filterLogs(filters = {}) {\n let filtered = [...this.buffer];\n if (filters.levels?.length) {\n filtered = filtered.filter((entry) => filters.levels.includes(entry.level));\n }\n if (filters.prefixes?.length) {\n filtered = filtered.filter(\n (entry) => entry.prefix && filters.prefixes.includes(entry.prefix)\n );\n }\n if (filters.excludePrefixes?.length) {\n filtered = filtered.filter(\n (entry) => !entry.prefix || !filters.excludePrefixes.includes(entry.prefix)\n );\n }\n if (filters.since) {\n const sinceDate = parseTimeInput(filters.since);\n filtered = filtered.filter((entry) => new Date(entry.timestamp) >= sinceDate);\n }\n if (filters.until) {\n const untilDate = parseTimeInput(filters.until);\n filtered = filtered.filter((entry) => new Date(entry.timestamp) <= untilDate);\n }\n if (filters.withStackTrace) {\n filtered = filtered.filter((entry) => entry.location);\n }\n if (filters.errorsOnly) {\n filtered = filtered.filter((entry) => entry.level === \"error\" || entry.level === \"critical\");\n }\n if (filters.search) {\n const searchTerm = filters.search.toLowerCase();\n filtered = filtered.filter(\n (entry) => entry.message.toLowerCase().includes(searchTerm) || entry.args.some(\n (arg) => String(arg).toLowerCase().includes(searchTerm)\n )\n );\n }\n if (filters.last) {\n filtered = filtered.slice(-filters.last);\n }\n if (filters.first) {\n filtered = filtered.slice(0, filters.first);\n }\n return filtered;\n }\n /**\n * Export logs in JSON format\n */\n exportJSON(logs, options) {\n const data = logs.map((entry) => ({\n timestamp: entry.timestamp,\n level: entry.level,\n prefix: entry.prefix,\n message: entry.message,\n ...options.minimal ? {} : {\n args: entry.args.slice(1),\n location: entry.location,\n groupInfo: entry.groupInfo\n }\n }));\n return options.compact ? JSON.stringify(data) : JSON.stringify(data, null, 2);\n }\n /**\n * Export logs in CSV format\n */\n exportCSV(logs, options) {\n const headers = options.minimal ? [\"Timestamp\", \"Level\", \"Prefix\", \"Message\"] : [\"Timestamp\", \"Level\", \"Prefix\", \"Message\", \"File\", \"Line\", \"Args\"];\n const rows = logs.map((entry) => {\n const baseRow = [\n formatDisplayTime(new Date(entry.timestamp), \"full\"),\n entry.level.toUpperCase(),\n entry.prefix || \"\",\n `\"${entry.message.replace(/\"/g, '\"\"')}\"`\n ];\n if (!options.minimal) {\n baseRow.push(\n entry.location?.file || \"\",\n entry.location?.line?.toString() || \"\",\n `\"${safeStringify(entry.args.slice(1)).replace(/\"/g, '\"\"')}\"`\n );\n }\n return baseRow;\n });\n return [headers.join(\",\"), ...rows.map((row) => row.join(\",\"))].join(\"\\n\");\n }\n /**\n * Export logs in Markdown format\n */\n exportMarkdown(logs, options) {\n const now = /* @__PURE__ */ new Date();\n let content = `# Log Export - ${formatDisplayTime(now, \"full\")}\n\n`;\n if (!options.minimal) {\n const summary = this.getBufferStats();\n content += `## Summary\n`;\n content += `- **Total logs**: ${logs.length}\n`;\n content += `- **Errors**: ${summary.levelCounts.error + summary.levelCounts.critical}\n`;\n content += `- **Warnings**: ${summary.levelCounts.warn}\n\n`;\n }\n if (options.groupBy === \"level\") {\n const grouped = logs.reduce((acc, entry) => {\n const level = entry.level;\n if (!acc[level]) {\n acc[level] = [];\n }\n const levelArray = acc[level];\n if (levelArray) {\n levelArray.push(entry);\n }\n return acc;\n }, {});\n Object.entries(grouped).forEach(([level, entries]) => {\n const emoji = this.getLevelEmoji(level);\n content += `## ${emoji} ${level.toUpperCase()} (${entries.length})\n\n`;\n entries.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"time-only\");\n const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n const prefix = entry.prefix ? ` **${entry.prefix}**:` : \"\";\n content += `- \\`${time}\\`${prefix} ${entry.message}${location}\n`;\n });\n content += \"\\n\";\n });\n } else {\n content += \"## Logs\\n\\n\";\n logs.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"time-only\");\n const emoji = this.getLevelEmoji(entry.level);\n const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n const prefix = entry.prefix ? ` **${entry.prefix}**:` : \"\";\n content += `- \\`${time}\\` ${emoji}${prefix} ${entry.message}${location}\n`;\n });\n }\n return content;\n }\n /**\n * Export logs in plain text format\n */\n exportPlain(logs, options) {\n return logs.map((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), options.minimal ? \"time-only\" : \"short\");\n const level = entry.level.toUpperCase().padEnd(8);\n const prefix = entry.prefix ? `[${entry.prefix}] ` : \"\";\n const location = !options.minimal && entry.location ? ` (${entry.location.file}:${entry.location.line})` : \"\";\n return `${time} ${level} ${prefix}${entry.message}${location}`;\n }).join(\"\\n\");\n }\n /**\n * Export logs in HTML format\n */\n exportHTML(logs, _options) {\n const title = `Log Export - ${formatDisplayTime(/* @__PURE__ */ new Date(), \"full\")}`;\n let html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 20px; line-height: 1.6; }\n .header { border-bottom: 2px solid #ddd; padding-bottom: 20px; margin-bottom: 20px; }\n .log-entry { margin: 5px 0; padding: 8px; border-radius: 4px; font-family: 'Monaco', 'Consolas', monospace; }\n .timestamp { color: #666; font-size: 0.9em; }\n .level { font-weight: bold; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }\n .prefix { background: #2d3748; color: #e2e8f0; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }\n .location { color: #718096; font-size: 0.9em; }\n .debug { background: #f0f4ff; }\n .info { background: #f0f9ff; }\n .warn { background: #fffbeb; }\n .error { background: #fef2f2; }\n .critical { background: #fef2f2; border-left: 4px solid #dc2626; }\n .level.debug { background: #667eea; color: white; }\n .level.info { background: #74b9ff; color: white; }\n .level.warn { background: #fdcb6e; color: #2d3436; }\n .level.error { background: #e84393; color: white; }\n .level.critical { background: #ff3838; color: white; }\n </style>\n</head>\n<body>\n <div class=\"header\">\n <h1>${title}</h1>\n <p>Generated by Advanced Logger v2.0.0</p>\n </div>\n <div class=\"logs\">`;\n logs.forEach((entry) => {\n const time = formatDisplayTime(new Date(entry.timestamp), \"full\");\n const location = entry.location ? ` <span class=\"location\">(${escapeHtml(entry.location.file)}:${entry.location.line})</span>` : \"\";\n const prefix = entry.prefix ? ` <span class=\"prefix\">${escapeHtml(entry.prefix)}</span>` : \"\";\n html += `\n <div class=\"log-entry ${entry.level}\">\n <span class=\"timestamp\">${time}</span>\n <span class=\"level ${entry.level}\">${entry.level.toUpperCase()}</span>\n ${prefix}\n <span class=\"message\">${escapeHtml(entry.message)}</span>\n ${location}\n </div>`;\n });\n html += `\n </div>\n</body>\n</html>`;\n return html;\n }\n /**\n * Get emoji for log level\n */\n getLevelEmoji(level) {\n const emojis = {\n debug: \"🐞\",\n info: \"ℹ️\",\n warn: \"⚠️\",\n error: \"❌\",\n critical: \"🔥\"\n };\n return emojis[level] || \"\";\n }\n /**\n * Main export function\n */\n export(format, filters = {}, options = {}) {\n const filteredLogs = this.filterLogs(filters);\n let data;\n switch (format) {\n case \"json\":\n data = this.exportJSON(filteredLogs, options);\n break;\n case \"csv\":\n data = this.exportCSV(filteredLogs, options);\n break;\n case \"markdown\":\n data = this.exportMarkdown(filteredLogs, options);\n break;\n case \"plain\":\n data = this.exportPlain(filteredLogs, options);\n break;\n case \"html\":\n data = this.exportHTML(filteredLogs, options);\n break;\n default:\n throw new Error(`Unsupported export format: ${format}`);\n }\n return {\n format,\n data,\n metadata: {\n totalLogs: this.buffer.length,\n filteredLogs: filteredLogs.length,\n exportedAt: (/* @__PURE__ */ new Date()).toISOString(),\n filters,\n options\n }\n };\n }\n /**\n * Copy to clipboard with fallback\n */\n async copyToClipboard(format, filters = {}, options = {}) {\n const result = this.export(format, filters, options);\n try {\n if (navigator.clipboard && window.isSecureContext) {\n await navigator.clipboard.writeText(result.data);\n return true;\n } else {\n const textArea = document.createElement(\"textarea\");\n textArea.value = result.data;\n textArea.style.position = \"fixed\";\n textArea.style.opacity = \"0\";\n document.body.appendChild(textArea);\n textArea.focus();\n textArea.select();\n const success = document.execCommand(\"copy\");\n document.body.removeChild(textArea);\n return success;\n }\n } catch (error) {\n console.error(\"Failed to copy to clipboard:\", error);\n return false;\n }\n }\n /**\n * Get all logs (for debugging)\n */\n getAllLogs() {\n return [...this.buffer];\n }\n /**\n * Save export to file with download prompt\n */\n async saveToFile(format, filters = {}, options = {}) {\n try {\n const result = this.export(format, filters, options);\n const blob = new Blob([result.data], {\n type: this.getMimeType(format)\n });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n const filename = this.generateFilename(format, filters);\n a.href = url;\n a.download = filename;\n a.style.display = \"none\";\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n return true;\n } catch (error) {\n console.error(\"Failed to save file:\", error);\n return false;\n }\n }\n /**\n * Get MIME type for format\n */\n getMimeType(format) {\n const mimeTypes = {\n json: \"application/json\",\n csv: \"text/csv\",\n markdown: \"text/markdown\",\n plain: \"text/plain\",\n html: \"text/html\"\n };\n return mimeTypes[format] || \"text/plain\";\n }\n /**\n * Generate filename with timestamp\n */\n generateFilename(format, filters) {\n const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, \"-\").slice(0, -5);\n const prefix = filters.prefixes?.length === 1 ? `_${filters.prefixes[0]}` : \"\";\n const extension = format === \"markdown\" ? \"md\" : format;\n return `logs${prefix}_${timestamp}.${extension}`;\n }\n /**\n * Stream logs to external endpoint\n */\n async streamToEndpoint(endpoint, filters = {}, options = {}) {\n try {\n const logs = this.filterLogs(filters);\n const batchSize = options.batchSize || 100;\n const format = options.format || \"json\";\n for (let i = 0; i < logs.length; i += batchSize) {\n const batch = logs.slice(i, i + batchSize);\n const result = this.export(format, {}, { compact: true });\n const headers = {\n \"Content-Type\": \"application/json\"\n };\n if (options.apiKey) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n logs: batch,\n metadata: {\n batchIndex: Math.floor(i / batchSize),\n totalBatches: Math.ceil(logs.length / batchSize),\n timestamp: (/* @__PURE__ */ new Date()).toISOString()\n }\n })\n });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n }\n return true;\n } catch (error) {\n console.error(\"Failed to stream logs:\", error);\n return false;\n }\n }\n /**\n * Create export with metadata enrichment\n */\n exportWithMetadata(format, filters = {}, options = {}) {\n const baseResult = this.export(format, filters, options);\n const bufferStats = this.getBufferStats();\n return {\n ...baseResult,\n metadata: {\n ...baseResult.metadata,\n bufferStats,\n performance: {\n memoryUsage: this.estimateMemoryUsage(),\n processingTime: Date.now()\n },\n system: {\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : \"Node.js\",\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone\n }\n }\n };\n }\n /**\n * Estimate memory usage of buffer\n */\n estimateMemoryUsage() {\n const sampleEntry = this.buffer[0];\n if (!sampleEntry) return 0;\n const sampleSize = JSON.stringify(sampleEntry).length;\n return sampleSize * this.buffer.length;\n }\n}\nclass CommandProcessor {\n commands = /* @__PURE__ */ new Map();\n aliases = /* @__PURE__ */ new Map();\n plugins = /* @__PURE__ */ new Map();\n history = [];\n maxHistorySize = 100;\n isInteractiveMode = false;\n /**\n * Register a command\n */\n registerCommand(command) {\n this.commands.set(command.name, command);\n if (command.aliases) {\n for (const alias of command.aliases) {\n this.aliases.set(alias, command.name);\n }\n }\n }\n /**\n * Register a plugin\n */\n registerPlugin(plugin, logger) {\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin ${plugin.name} is already registered`);\n }\n this.plugins.set(plugin.name, plugin);\n for (const command of plugin.commands) {\n this.registerCommand(command);\n }\n if (plugin.initialize && logger) {\n plugin.initialize(this, logger);\n }\n }\n /**\n * Unregister a plugin\n */\n unregisterPlugin(pluginName) {\n const plugin = this.plugins.get(pluginName);\n if (!plugin) return;\n for (const command of plugin.commands) {\n this.commands.delete(command.name);\n if (command.aliases) {\n for (const alias of command.aliases) {\n this.aliases.delete(alias);\n }\n }\n }\n if (plugin.cleanup) {\n plugin.cleanup();\n }\n this.plugins.delete(pluginName);\n }\n /**\n * Get all registered commands\n */\n getCommands() {\n return Array.from(this.commands.values());\n }\n /**\n * Get a specific command\n */\n getCommand(name) {\n let command = this.commands.get(name);\n if (command) return command;\n const aliasTarget = this.aliases.get(name);\n if (aliasTarget) {\n return this.commands.get(aliasTarget);\n }\n return void 0;\n }\n /**\n * Get command history\n */\n getHistory() {\n return [...this.history];\n }\n /**\n * Clear command history\n */\n clearHistory() {\n this.history = [];\n }\n /**\n * Get registered plugins\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n /**\n * Enter interactive mode\n */\n enterInteractiveMode(logger) {\n this.isInteractiveMode = true;\n logger.info(\"🔧 Interactive CLI mode activated. Type /exit to quit, /help for commands.\");\n if (typeof window !== \"undefined\") {\n this.setupBrowserInteractiveMode(logger);\n }\n }\n /**\n * Exit interactive mode\n */\n exitInteractiveMode() {\n this.isInteractiveMode = false;\n }\n /**\n * Setup browser interactive mode\n */\n setupBrowserInteractiveMode(logger) {\n window.cli = (commandString) => {\n return this.processCommand(`/${commandString}`, logger);\n };\n logger.info('💡 Use cli(\"command\") to execute CLI commands in browser console.');\n }\n /**\n * Process a CLI command\n */\n async processCommand(commandString, logger) {\n if (!commandString.startsWith(\"/\")) {\n logger.error(\"Invalid command. Commands must start with /\");\n this.addToHistory(commandString, false);\n return;\n }\n const parts = commandString.slice(1).split(\" \");\n const commandName = parts[0] || \"\";\n const args = parts.slice(1).join(\" \");\n const command = this.getCommand(commandName);\n if (!command) {\n logger.error(`Unknown command: ${commandName}. Type /help for available commands.`);\n const suggestions = this.getSuggestions(commandName);\n if (suggestions.length > 0) {\n logger.info(`📋 Did you mean: ${suggestions.slice(0, 3).join(\", \")}?`);\n }\n this.addToHistory(commandString, false);\n return;\n }\n try {\n await command.execute(args || \"\", logger);\n this.addToHistory(commandString, true);\n } catch (error) {\n logger.error(`Command '${commandName}' failed:`, error);\n this.addToHistory(commandString, false);\n }\n }\n /**\n * Add command to history\n */\n addToHistory(command, success) {\n this.history.unshift({\n command,\n timestamp: /* @__PURE__ */ new Date(),\n success\n });\n if (this.history.length > this.maxHistorySize) {\n this.history = this.history.slice(0, this.maxHistorySize);\n }\n }\n /**\n * Get command suggestions for partial matches\n */\n getSuggestions(partial) {\n const commandNames = Array.from(this.commands.keys());\n return commandNames.filter((name) => name.startsWith(partial));\n }\n}\nclass ConfigCommand {\n name = \"config\";\n description = \"Show or update logger configuration\";\n usage = \"/config [json|key=value,...]\";\n execute(args, logger) {\n if (!args) {\n this.showStatus(logger);\n return;\n }\n try {\n if (args.startsWith(\"{\")) {\n const config = JSON.parse(args);\n this.applyConfig(config, logger);\n } else {\n const pairs = args.split(\",\").map((pair) => pair.trim().split(\"=\"));\n const config = {};\n pairs.forEach(([key, value]) => {\n if (key && value) {\n config[key.trim()] = value.trim().replace(/[\"']/g, \"\");\n }\n });\n this.applyConfig(config, logger);\n }\n } catch (error) {\n logger.error(\"Invalid config format. Use JSON or key=value pairs:\", error);\n logger.info('Examples: /config {\"theme\":\"dark\"} or /config theme=neon,verbosity=debug');\n }\n }\n showStatus(logger) {\n const statusData = {\n theme: logger.getConfig().theme || \"default\",\n verbosity: logger.getConfig().verbosity,\n colors: logger.getConfig().enableColors,\n timestamps: logger.getConfig().enableTimestamps,\n stackTrace: logger.getConfig().enableStackTrace,\n globalPrefix: logger.getConfig().globalPrefix || \"none\",\n bannerType: logger.getConfig().bannerType || \"simple\",\n handlers: logger.getHandlers().length\n };\n logger.group(\"⚙️ Logger Configuration\");\n logger.table(statusData);\n logger.groupEnd();\n }\n applyConfig(config, logger) {\n const validKeys = [\"theme\", \"verbosity\", \"enableColors\", \"enableTimestamps\", \"enableStackTrace\", \"globalPrefix\", \"bannerType\"];\n const applied = [];\n Object.entries(config).forEach(([key, value]) => {\n if (validKeys.includes(key)) {\n if (key === \"theme\" && typeof value === \"string\") {\n logger.setTheme(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"bannerType\" && typeof value === \"string\") {\n logger.setBannerType(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"verbosity\") {\n logger.setVerbosity(value);\n applied.push(`${key}=${value}`);\n } else if (key === \"globalPrefix\") {\n logger.setGlobalPrefix(value);\n applied.push(`${key}=${value}`);\n } else {\n logger.updateConfig({ [key]: value });\n applied.push(`${key}=${value}`);\n }\n } else {\n logger.warn(`Invalid config key: ${key}`);\n }\n });\n if (applied.length > 0) {\n logger.success(`Configuration updated: ${applied.join(\", \")}`);\n }\n }\n}\nclass ThemesCommand {\n name = \"themes\";\n description = \"Show available theme presets\";\n usage = \"/themes\";\n execute(_args, logger) {\n logger.group(\"🎨 Available Themes\");\n Object.keys(THEME_PRESETS).forEach((themeName) => {\n const preview = THEME_PRESETS[themeName];\n const previewStyle = new StyleBuilder().bg(preview.info.background).color(preview.info.color).padding(\"4px 8px\").rounded(\"4px\").border(preview.info.border).build();\n console.log(`%c${themeName}`, previewStyle, `- ${themeName} theme preview`);\n });\n logger.groupEnd();\n }\n}\nclass BannersCommand {\n name = \"banners\";\n description = \"Show available banner types\";\n usage = \"/banners\";\n execute(_args, logger) {\n logger.group(\"🖼️ Available Banner Types\");\n Object.keys(BANNER_VARIANTS).forEach((bannerName) => {\n const banner = BANNER_VARIANTS[bannerName];\n console.log(`%c${bannerName}`, \"font-weight: bold; color: #667eea;\");\n console.log(`%cPreview:`, \"color: #666; font-size: 12px;\");\n if (bannerName === \"simple\") {\n console.log(`%c${banner.text}`, banner.style);\n } else if (bannerName === \"ascii\") {\n console.log(`%c${banner.text.split(\"\\n\").slice(1, 4).join(\"\\n\")}...`, \"font-family: monospace; color: #667eea; font-size: 10px;\");\n } else if (bannerName === \"unicode\") {\n console.log(`%c${banner.text}`, banner.style);\n } else {\n console.log(`%c${bannerName} banner`, \"color: #666; font-style: italic;\");\n }\n });\n logger.groupEnd();\n }\n}\nclass BannerCommand {\n name = \"banner\";\n description = \"Change or show current banner type\";\n usage = \"/banner [type]\";\n execute(args, logger) {\n if (!args) {\n logger.showBanner();\n return;\n }\n if (args in BANNER_VARIANTS) {\n logger.setBannerType(args);\n logger.showBanner();\n } else {\n logger.error(`Invalid banner type: ${args}. Available: ${Object.keys(BANNER_VARIANTS).join(\", \")}`);\n }\n }\n}\nclass StatusCommand {\n name = \"status\";\n description = \"Show current logger status and configuration\";\n usage = \"/status\";\n execute(_args, logger) {\n const config = logger.getConfig();\n const statusData = {\n theme: config.theme ? config.theme : \"default\",\n verbosity: config.verbosity,\n colors: config.enableColors,\n timestamps: config.enableTimestamps,\n stackTrace: config.enableStackTrace,\n globalPrefix: config.globalPrefix ? config.globalPrefix : \"none\",\n bannerType: config.bannerType ? config.bannerType : \"simple\",\n handlers: logger.getHandlers().length,\n bufferSize: config.bufferSize ? config.bufferSize : 1e3\n };\n logger.group(\"⚙️ Logger Configuration\");\n logger.table(statusData);\n logger.groupEnd();\n const exportHandler = logger.getExportHandler();\n if (exportHandler) {\n const bufferStats = exportHandler.getBufferStats();\n logger.group(\"📊 Buffer Statistics\");\n logger.table({\n size: `${bufferStats.size}/${bufferStats.maxSize}`,\n usage: `${bufferStats.usage.toFixed(1)}%`,\n oldestLog: bufferStats.oldestLog ? bufferStats.oldestLog.toISOString() : \"None\",\n newestLog: bufferStats.newestLog ? bufferStats.newestLog.toISOString() : \"None\",\n errorCount: bufferStats.levelCounts.error + bufferStats.levelCounts.critical,\n warningCount: bufferStats.levelCounts.warn\n });\n logger.groupEnd();\n }\n }\n}\nclass ResetCommand {\n name = \"reset\";\n description = \"Reset logger configuration to defaults\";\n usage = \"/reset\";\n execute(_args, logger) {\n logger.resetConfig();\n }\n}\nclass DemoCommand {\n name = \"demo\";\n description = \"Show comprehensive feature demonstration\";\n usage = \"/demo\";\n execute(_args, logger) {\n logger.group(\"🎪 Advanced Logger Demo\");\n logger.debug(\"Debug message with detailed information\");\n logger.info(\"Informational message about system state\");\n logger.warn(\"Warning about deprecated feature\");\n logger.error(\"Error processing user request\");\n logger.success(\"Operation completed successfully\");\n logger.critical(\"Critical system failure detected\");\n logger.group(\"📊 Advanced Features Demo\");\n logger.table([\n { feature: \"Styled Console\", status: \"✅ Active\", performance: \"Excellent\" },\n { feature: \"Theme System\", status: \"✅ Active\", performance: \"Great\" },\n { feature: \"CLI Interface\", status: \"✅ Active\", performance: \"Good\" },\n { feature: \"Export System\", status: \"✅ Active\", performance: \"Excellent\" }\n ]);\n logger.time(\"demo-operation\");\n setTimeout(() => {\n logger.timeEnd(\"demo-operation\");\n }, 100);\n logger.logWithSVG(\"SVG Demo\");\n logger.logAnimated(\"🌟 Animated Logger Demo 🌟\", 2);\n logger.groupEnd();\n logger.groupEnd();\n logger.info(\"Demo completed! Check the console for styled output.\");\n }\n}\nfunction parseArguments(args) {\n const filters = {};\n const options = {};\n let format;\n if (!args.trim()) return { filters, options };\n const argParts = args.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g) || [];\n for (let i = 0; i < argParts.length; i++) {\n const arg = argParts[i];\n if (!arg) {\n continue;\n }\n if (i === 0 && !arg.startsWith(\"--\") && arg in EXPORT_FORMATS) {\n format = arg;\n continue;\n }\n if (arg.startsWith(\"--\")) {\n const [flag, value] = arg.slice(2).split(\"=\");\n switch (flag) {\n case \"level\":\n case \"levels\":\n if (value) {\n filters.levels = value.split(\",\").map((l) => l.trim());\n }\n break;\n case \"since\":\n if (value) filters.since = value;\n break;\n case \"until\":\n if (value) filters.until = value;\n break;\n case \"prefix\":\n case \"prefixes\":\n if (value) {\n filters.prefixes = value.split(\",\").map((p) => p.trim());\n }\n break;\n case \"exclude-prefix\":\n case \"exclude-prefixes\":\n if (value) {\n filters.excludePrefixes = value.split(\",\").map((p) => p.trim());\n }\n break;\n case \"last\":\n if (value) filters.last = parseInt(value, 10);\n break;\n case \"first\":\n if (value) filters.first = parseInt(value, 10);\n break;\n case \"search\":\n if (value) filters.search = value.replace(/['\"]/g, \"\");\n break;\n case \"with-stack\":\n filters.withStackTrace = true;\n break;\n case \"errors-only\":\n filters.errorsOnly = true;\n break;\n case \"group-by\":\n if (value) {\n filters.groupBy = value;\n options.groupBy = value;\n }\n break;\n case \"minimal\":\n options.minimal = true;\n break;\n case \"compact\":\n options.compact = true;\n break;\n case \"styled\":\n options.styled = true;\n break;\n }\n }\n }\n return { filters, options, format };\n}\nclass ExportCommand {\n name = \"export\";\n description = \"Export logs to various formats\";\n usage = \"/export <format> [--filter=value] [--option]\";\n execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available. Make sure ExportLogHandler is registered.\");\n return;\n }\n const { filters, options, format } = parseArguments(args);\n if (!format) {\n logger.error(\"Format required. Available formats: \" + Object.keys(EXPORT_FORMATS).join(\", \"));\n logger.info(\"Usage: /export <format> [--filter=value]\");\n logger.info(\"Example: /export json --level=error,warn --last=50\");\n return;\n }\n try {\n const result = exportHandler.export(format, filters, options);\n logger.success(`✅ Export completed: ${result.metadata.filteredLogs} logs exported in ${format} format`);\n if (result.data.length < 1e3) {\n logger.group(`📄 Preview (${format.toUpperCase()})`);\n console.log(result.data);\n logger.groupEnd();\n } else {\n logger.info(`📄 Export size: ${(result.data.length / 1024).toFixed(2)}KB`);\n }\n logger.table({\n format: result.format,\n totalLogs: result.metadata.totalLogs,\n filtered: result.metadata.filteredLogs,\n exported: result.metadata.exportedAt\n });\n } catch (error) {\n logger.error(\"Export failed:\", error);\n }\n }\n}\nclass CopyCommand {\n name = \"copy\";\n description = \"Copy logs to clipboard\";\n usage = \"/copy <format> [--filter=value] [--option]\";\n async execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available. Make sure ExportLogHandler is registered.\");\n return;\n }\n const { filters, options, format } = parseArguments(args);\n if (!format) {\n logger.error(\"Format required. Available formats: \" + Object.keys(EXPORT_FORMATS).join(\", \"));\n logger.info(\"Usage: /copy <format> [--filter=value]\");\n logger.info(\"Example: /copy plain --level=error --last=25\");\n return;\n }\n try {\n const success = await exportHandler.copyToClipboard(format, filters, options);\n if (success) {\n const result = exportHandler.export(format, filters, options);\n logger.success(`📋 Copied ${result.metadata.filteredLogs} logs to clipboard (${format} format)`);\n } else {\n logger.error(\"Failed to copy to clipboard. Browser may not support clipboard API.\");\n }\n } catch (error) {\n logger.error(\"Copy failed:\", error);\n }\n }\n}\nclass BufferSizeCommand {\n name = \"buffer-size\";\n description = \"Set log buffer size\";\n usage = \"/buffer-size <size>\";\n execute(args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const size = parseInt(args.trim(), 10);\n if (isNaN(size) || size <= 0) {\n logger.error(\"Invalid buffer size. Must be a positive number.\");\n logger.info(\"Example: /buffer-size 2000\");\n return;\n }\n exportHandler.setBufferSize(size);\n logger.success(`Buffer size set to ${size}`);\n }\n}\nclass ClearBufferCommand {\n name = \"clear-buffer\";\n description = \"Clear the log buffer\";\n usage = \"/clear-buffer\";\n execute(_args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const stats = exportHandler.getBufferStats();\n exportHandler.clearBuffer();\n logger.success(`✅ Buffer cleared. Removed ${stats.size} log entries.`);\n }\n}\nclass BufferInfoCommand {\n name = \"buffer-info\";\n description = \"Show buffer statistics and information\";\n usage = \"/buffer-info\";\n execute(_args, logger) {\n const exportHandler = logger.getExportHandler();\n if (!exportHandler) {\n logger.error(\"Export handler not available.\");\n return;\n }\n const stats = exportHandler.getBufferStats();\n logger.group(\"📊 Buffer Information\");\n logger.table({\n size: `${stats.size}/${stats.maxSize}`,\n usage: `${stats.usage.toFixed(1)}%`,\n oldestLog: stats.oldestLog?.toLocaleString() || \"None\",\n newestLog: stats.newestLog?.toLocaleString() || \"None\"\n });\n logger.group(\"📈 Log Level Counts\");\n logger.table(stats.levelCounts);\n logger.groupEnd();\n logger.groupEnd();\n }\n}\nclass HelpCommand {\n name = \"help\";\n description = \"Show CLI help and available commands\";\n usage = \"/help [command]\";\n execute(_args, logger) {\n const helpStyle = new StyleBuilder().bg(\"linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)\").color(\"#495057\").padding(\"15px 20px\").rounded(\"8px\").border(\"1px solid #dee2e6\").font(\"Monaco, Consolas, monospace\").size(\"13px\").build();\n const helpText = `\n╭─────────────── ADVANCED LOGGER CLI COMMANDS ─────────────────╮\n│ │\n│ CONFIGURATION │\n│ /config Show current configuration │\n│ /config {json} Apply JSON configuration │\n│ /config key=val Apply key-value configuration │\n│ /themes Show available themes │\n│ /banners Show available banner types │\n│ /banner [type] Change/show banner type │\n│ /status Show logger status & buffer stats │\n│ /demo Show feature demonstration │\n│ /reset Reset to default configuration │\n│ │\n│ EXPORT & CLIPBOARD │\n│ /export <format> Export logs (json|csv|md|plain|html) │\n│ /copy <format> Copy logs to clipboard │\n│ /buffer-size N Set log buffer size │\n│ /buffer-info Show buffer statistics │\n│ /clear-buffer Clear stored logs │\n│ │\n│ EXPORT FILTERS (for export/copy commands) │\n│ --level error,warn Filter by log levels │\n│ --since 2h Logs from last 2 hours │\n│ --until 1h Logs until 1 hour ago │\n│ --prefix API,DB Filter by prefixes │\n│ --exclude-prefix INT Exclude prefixes │\n│ --last 50 Last 50 logs only │\n│ --first 25 First 25 logs only │\n│ --search \"error\" Search in log messages │\n│ --with-stack Only logs with stack traces │\n│ --errors-only Only error + critical logs │\n│ --group-by level Group by level/prefix/hour │\n│ │\n│ EXPORT OPTIONS │\n│ --minimal Minimal output format │\n│ --compact Remove extra whitespace │\n│ --styled Include styling (HTML format) │\n│ │\n├──────────────────── CONFIGURATION OPTIONS ─────────────────┤\n│ │\n│ theme: default | dark | light | neon | minimal | cyberpunk│\n│ bannerType: simple | ascii | unicode | svg | animated │\n│ verbosity: debug | info | warn | error | critical | silent│\n│ enableColors: true | false │\n│ enableTimestamps: true | false │\n│ enableStackTrace: true | false │\n│ globalPrefix: \"string\" │\n│ bufferSize: number (50-10000) │\n│ │\n├──────────────────────── EXAMPLES ──────────────────────────┤\n│ │\n│ Basic Configuration: │\n│ /config {\"theme\":\"dark\",\"verbosity\":\"debug\"} │\n│ /config theme=neon,bufferSize=2000 │\n│ /banner animated Change to animated banner │\n│ │\n│ Export Examples: │\n│ /export json --level=error,warn --last=25 │\n│ /export csv --since=2h --prefix=API │\n│ /export markdown --group-by=level --errors-only │\n│ /export html --styled --since=1h │\n│ │\n│ Clipboard Examples: │\n│ /copy plain --minimal --last=10 │\n│ /copy json --search=\"authentication\" --compact │\n│ /copy csv --since=30m --exclude-prefix=DEBUG │\n│ │\n│ Buffer Management: │\n│ /buffer-size 5000 Increase buffer to 5000 logs │\n│ /buffer-info Show detailed buffer statistics │\n│ /clear-buffer Clear all stored logs │\n│ │\n│ Time Formats: │\n│ --since=2h 2 hours ago │\n│ --since=30m 30 minutes ago │\n│ --since=1d 1 day ago │\n│ --since=\"2024-01-01T10:00:00Z\" Specific ISO date │\n│ │\n╰─────────────────────────────────────────────────────────────╯`;\n console.log(`%c${helpText}`, helpStyle);\n logger.group(\"💡 Quick Tips\");\n const tips = [\n \"Use /demo to see all logger features in action\",\n \"Logs are automatically stored in a circular buffer for export\",\n \"Export formats: JSON (structured), CSV (Excel), Markdown (readable), Plain (simple), HTML (styled)\",\n \"Time filters support relative (2h, 30m) and absolute (ISO) formats\",\n 'Combine multiple filters: /export json --level=error --since=1h --search=\"auth\"',\n \"Use /copy for quick clipboard access instead of /export\"\n ];\n tips.forEach((tip) => {\n logger.info(`• ${tip}`);\n });\n logger.groupEnd();\n }\n}\nclass HistoryCommand {\n name = \"history\";\n description = \"Show command execution history\";\n usage = \"/history [limit] - Show recent commands (default: 10)\";\n category = \"system\";\n aliases = [\"hist\", \"h\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n const limit = parseInt(args) || 10;\n const history = processor.getHistory().slice(0, limit);\n if (history.length === 0) {\n logger.info(\"📝 No command history available\");\n return;\n }\n logger.info(`📋 Last ${history.length} commands:`);\n history.forEach((entry, index) => {\n const status = entry.success ? \"✅\" : \"❌\";\n const time = entry.timestamp.toLocaleTimeString();\n logger.info(`${status} [${time}] ${entry.command}`);\n });\n }\n}\nclass ClearHistoryCommand {\n name = \"clearhistory\";\n description = \"Clear command execution history\";\n usage = \"/clearhistory - Remove all command history\";\n category = \"system\";\n aliases = [\"clrhist\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n processor.clearHistory();\n logger.success(\"🗑️ Command history cleared\");\n }\n}\nclass InteractiveCommand {\n name = \"interactive\";\n description = \"Enter interactive CLI mode\";\n usage = \"/interactive - Start interactive command mode\";\n category = \"system\";\n aliases = [\"i\", \"repl\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n processor.enterInteractiveMode(logger);\n }\n}\nclass PluginsCommand {\n name = \"plugins\";\n description = \"List loaded CLI plugins\";\n usage = \"/plugins - Show all registered plugins\";\n category = \"system\";\n aliases = [\"plug\"];\n execute(args, logger) {\n const processor = logger.cliProcessor;\n if (!processor) {\n logger.error(\"CLI processor not available\");\n return;\n }\n const plugins = processor.getPlugins();\n if (plugins.length === 0) {\n logger.info(\"🔌 No plugins registered\");\n return;\n }\n logger.info(`🔌 Loaded plugins (${plugins.length}):`);\n plugins.forEach((plugin) => {\n logger.info(` 📦 ${plugin.name} v${plugin.version} - ${plugin.description}`);\n logger.info(` Commands: ${plugin.commands.map((c) => c.name).join(\", \")}`);\n });\n }\n}\nfunction createDefaultCLI() {\n const processor = new CommandProcessor();\n processor.registerCommand(new HelpCommand());\n processor.registerCommand(new ConfigCommand());\n processor.registerCommand(new ThemesCommand());\n processor.registerCommand(new BannersCommand());\n processor.registerCommand(new BannerCommand());\n processor.registerCommand(new StatusCommand());\n processor.registerCommand(new ResetCommand());\n processor.registerCommand(new DemoCommand());\n processor.registerCommand(new ExportCommand());\n processor.registerCommand(new CopyCommand());\n processor.registerCommand(new BufferSizeCommand());\n processor.registerCommand(new ClearBufferCommand());\n processor.registerCommand(new BufferInfoCommand());\n processor.registerCommand(new HistoryCommand());\n processor.registerCommand(new ClearHistoryCommand());\n processor.registerCommand(new InteractiveCommand());\n processor.registerCommand(new PluginsCommand());\n return processor;\n}\nlet LEVEL_STYLES = THEME_PRESETS.default;\nclass Logger {\n config;\n scopedPrefix;\n handlers = [];\n timers = /* @__PURE__ */ new Map();\n groupDepth = 0;\n exportHandler;\n cliProcessor;\n themeChangeListener;\n badgeList = [];\n displaySettings = {\n showTimestamp: true,\n showLocation: true,\n showBadges: true\n };\n serializerRegistry;\n hookManager;\n transportManager;\n /**\n * Crea una nueva instancia del Logger\n * \n * @param {Partial<LoggerConfig>} config - Configuración opcional del logger\n * \n * @example\n * // Logger con configuración personalizada\n * const logger = new Logger({\n * theme: 'neon',\n * globalPrefix: 'MiApp',\n * verbosity: 'debug',\n * bufferSize: 1000\n * });\n */\n constructor(config = {}) {\n this.config = {\n ...DEFAULT_CONFIG$1,\n ...config\n };\n this.serializerRegistry = new SerializerRegistry();\n this.hookManager = new HookManager();\n if (this.config.bufferSize) {\n this.exportHandler = new ExportLogHandler(this.config.bufferSize);\n this.handlers.push(this.exportHandler);\n }\n this.cliProcessor = createDefaultCLI();\n if (this.config.autoDetectTheme) {\n this.setupAutoThemeDetection();\n }\n }\n // ===== PRIVATE HELPER METHODS =====\n /**\n * Configura la detección automática de tema con listener de cambios\n * @private\n * @description Detecta automáticamente si el navegador está en modo claro u oscuro\n */\n setupAutoThemeDetection() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.themeChangeListener = setupThemeChangeListener((theme) => {\n this.debug(`DevTools theme changed to: ${theme}`);\n });\n }\n // ===== CONFIGURATION METHODS =====\n /**\n * Obtiene la configuración actual del logger\n * \n * @returns {LoggerConfig} Configuración completa actual\n * \n * @example\n * const config = logger.getConfig();\n * console.log('Verbosidad actual:', config.verbosity);\n * console.log('Tema actual:', config.theme);\n * \n * @since 0.3.0\n */\n getConfig() {\n return { ...this.config };\n }\n /**\n * Actualiza la configuración del logger\n * \n * @param {Partial<LoggerConfig>} updates - Propiedades a actualizar\n * \n * @example\n * logger.updateConfig({\n * verbosity: 'debug',\n * enableTimestamps: false,\n * theme: 'cyberpunk'\n * });\n * \n * @since 0.3.0\n */\n updateConfig(updates) {\n const previousAutoDetect = this.config.autoDetectTheme;\n this.config = { ...this.config, ...updates };\n if (updates.autoDetectTheme !== void 0 && updates.autoDetectTheme !== previousAutoDetect) {\n if (updates.autoDetectTheme) {\n this.setupAutoThemeDetection();\n } else if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n }\n }\n /**\n * Establece el prefijo global para todos los mensajes de log\n * \n * @param {string} prefix - Prefijo a usar\n * \n * @example\n * logger.setGlobalPrefix('MiApp');\n * logger.info('Iniciado'); // [MiApp] Iniciado\n * \n * @since 0.3.0\n */\n setGlobalPrefix(prefix) {\n this.config.globalPrefix = prefix;\n }\n /**\n * Establece el nivel de verbosidad para filtrar la salida de logs\n * \n * @param {Verbosity} level - Nivel mínimo a mostrar ('debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent')\n * \n * @example\n * logger.setVerbosity('warn'); // Solo muestra warn, error y critical\n * logger.setVerbosity('debug'); // Muestra todos los niveles\n * logger.setVerbosity('silent'); // No muestra nada\n * \n * @since 0.3.0\n */\n setVerbosity(level) {\n this.config.verbosity = level;\n }\n /**\n * Establece el tema del logger\n * \n * @param {ThemeVariant} theme - Tema a aplicar ('default' | 'dark' | 'light' | 'neon' | 'minimal' | 'cyberpunk')\n * \n * @example\n * logger.setTheme('neon'); // Tema con colores neón\n * logger.setTheme('minimal'); // Tema minimalista\n * logger.setTheme('cyberpunk'); // Tema cyberpunk con efectos\n * \n * @since 0.3.0\n */\n setTheme(theme) {\n if (hasPreset(theme)) {\n this.preset(theme);\n return;\n }\n if (theme in THEME_PRESETS) {\n LEVEL_STYLES = THEME_PRESETS[theme];\n this.config.theme = theme;\n if (theme in THEME_BANNERS) {\n const themeBanner = THEME_BANNERS[theme];\n console.log(`%c${themeBanner.simple}`, themeBanner.style);\n }\n this.success(`Theme changed to: ${theme}`);\n } else {\n this.error(`Invalid theme: ${theme}. Available:`, [...getAvailablePresets(), ...Object.keys(THEME_PRESETS)]);\n }\n }\n /**\n * Establece el tipo de banner para mostrar en la inicialización\n * \n * @param {BannerType} bannerType - Tipo de banner ('simple' | 'ascii' | 'unicode' | 'svg' | 'animated')\n * \n * @example\n * logger.setBannerType('ascii'); // Banner con arte ASCII\n * logger.setBannerType('unicode'); // Banner con caracteres Unicode\n * logger.setBannerType('animated'); // Banner con animación\n * \n * @since 0.3.0\n */\n setBannerType(bannerType) {\n this.config.bannerType = bannerType;\n this.success(`Banner type changed to: ${bannerType}`);\n }\n /**\n * Reinicia el logger a la configuración por defecto\n * \n * @example\n * logger.resetConfig();\n * // Todo vuelve a la configuración inicial\n * \n * @since 0.3.0\n */\n resetConfig() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.config = { ...DEFAULT_CONFIG$1 };\n LEVEL_STYLES = THEME_PRESETS.default;\n if (this.config.autoDetectTheme) {\n this.setupAutoThemeDetection();\n }\n this.success(\"Logger configuration reset to defaults\");\n }\n /**\n * Método de limpieza para eliminar listeners y liberar recursos\n * \n * @example\n * // Antes de cerrar la aplicación\n * logger.cleanup();\n * \n * @since 0.3.0\n */\n cleanup() {\n if (this.themeChangeListener) {\n this.themeChangeListener();\n this.themeChangeListener = null;\n }\n this.transportManager?.close().catch(() => {\n });\n }\n // ===== SIMPLIFIED API =====\n /**\n * Aplica un preset inteligente - funciona perfectamente sin configuración\n * \n * @param {string} name - Nombre del preset a aplicar\n * \n * @example\n * // Presets disponibles\n * logger.preset('default'); // Limpio y adaptativo\n * logger.preset('cyberpunk'); // Colores neón, efectos brillantes\n * logger.preset('glassmorphism'); // Efectos de blur modernos\n * logger.preset('minimal'); // Minimalista y elegante\n * logger.preset('debug'); // Modo desarrollo detallado\n * logger.preset('production'); // Optimizado para producción\n * \n * @since 0.3.0\n */\n preset(name) {\n if (!hasPreset(name)) {\n this.error(`Unknown preset: ${name}. Available presets:`, getAvailablePresets());\n return;\n }\n const presetConfig = getSmartPreset(name);\n if (presetConfig) {\n this.displaySettings.showTimestamp = presetConfig.timestamp?.show ?? true;\n this.displaySettings.showLocation = presetConfig.location?.show ?? true;\n this._activePreset = presetConfig;\n this._activePresetName = name;\n if (getEnvironment() === \"browser\") {\n this.success(`Applied preset: ${name}`);\n }\n }\n }\n /**\n * Lista todos los presets disponibles\n * \n * @returns {string[]} Array con nombres de presets disponibles\n * \n * @example\n * const disponibles = logger.presets();\n * console.log(disponibles); // ['default', 'cyberpunk', 'glassmorphism', ...]\n * \n * @since 0.3.0\n */\n presets() {\n return getAvailablePresets();\n }\n // ===== TOGGLE METHODS =====\n /**\n * Oculta el timestamp en los logs\n * \n * @example\n * logger.hideTimestamp();\n * logger.info('Sin marca de tiempo'); // Sin timestamp visible\n * \n * @since 0.3.0\n */\n hideTimestamp() {\n this.displaySettings.showTimestamp = false;\n return this;\n }\n /**\n * Muestra el timestamp en los logs\n * \n * @example\n * logger.showTimestamp();\n * logger.info('Con marca de tiempo'); // [2024-01-15 10:30:45] Con marca de tiempo\n * \n * @since 0.3.0\n */\n showTimestamp() {\n this.displaySettings.showTimestamp = true;\n return this;\n }\n /**\n * Oculta la información de ubicación (archivo:línea) en los logs\n * \n * @example\n * logger.hideLocation();\n * logger.debug('Sin ubicación'); // Sin mostrar archivo:línea\n * \n * @since 0.3.0\n */\n hideLocation() {\n this.displaySettings.showLocation = false;\n return this;\n }\n /**\n * Muestra la información de ubicación (archivo:línea) en los logs\n * \n * @example\n * logger.showLocation();\n * logger.debug('Con ubicación'); // app.js:42 Con ubicación\n * \n * @since 0.3.0\n */\n showLocation() {\n this.displaySettings.showLocation = true;\n return this;\n }\n /**\n * Oculta los badges en los logs\n * \n * @example\n * logger.hideBadges();\n * const api = logger.api('REST');\n * api.info('Sin badges'); // Sin mostrar [API] [REST]\n * \n * @since 0.3.0\n */\n hideBadges() {\n this.displaySettings.showBadges = false;\n return this;\n }\n /**\n * Muestra los badges en los logs\n *\n * @example\n * logger.showBadges();\n * const api = logger.api('GraphQL');\n * api.info('Con badges'); // [API] [GraphQL] Con badges\n *\n * @since 0.3.0\n */\n showBadges() {\n this.displaySettings.showBadges = true;\n return this;\n }\n /**\n * Establece múltiples badges para los logs\n *\n * @param {string[]} badges - Array de badges a mostrar\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.badges(['v3', 'stable']).info('Release publicado');\n * logger.badges(['API', 'v2']).warn('Endpoint deprecado');\n *\n * @since 3.0.0\n */\n badges(badges2) {\n this.badgeList = [...badges2];\n return this;\n }\n /**\n * Añade un badge individual a la lista\n *\n * @param {string} badge - Badge a añadir\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.badge('DEBUG').badge('AUTH').info('Token validado');\n *\n * @since 3.0.0\n */\n badge(badge2) {\n if (!this.badgeList.includes(badge2)) {\n this.badgeList.push(badge2);\n }\n return this;\n }\n /**\n * Limpia todos los badges activos\n *\n * @returns {this} Logger instance para encadenamiento\n *\n * @example\n * logger.clearBadges().info('Sin badges');\n *\n * @since 3.0.0\n */\n clearBadges() {\n this.badgeList = [];\n return this;\n }\n // ===== SCOPED LOGGERS =====\n component(name) {\n return new ComponentLogger(this, name);\n }\n api(name) {\n return new APILogger(this, name);\n }\n scope(name) {\n return new ScopedLogger(this, name);\n }\n // ===== SIMPLE CUSTOMIZATION =====\n /**\n * Personalización simple con configuración mínima\n * \n * @param {Object} overrides - Opciones de personalización\n * @param {Object} overrides.message - Configuración del mensaje\n * @param {Object} overrides.timestamp - Configuración del timestamp\n * @param {Object} overrides.location - Configuración de ubicación\n * @param {Object} overrides.level - Configuración del nivel\n * @param {Object} overrides.prefix - Configuración del prefijo\n * @param {string} overrides.spacing - Espaciado: 'compact' | 'normal' | 'spacious'\n * \n * @example\n * logger.customize({\n * message: { color: '#00ff00', size: '16px' },\n * timestamp: { show: false },\n * spacing: 'compact'\n * });\n * \n * @since 0.3.0\n */\n customize(overrides) {\n if (overrides.timestamp?.show !== void 0) {\n this.displaySettings.showTimestamp = overrides.timestamp.show;\n }\n if (overrides.location?.show !== void 0) {\n this.displaySettings.showLocation = overrides.location.show;\n }\n if (overrides.prefix?.show !== void 0) ;\n this._customization = overrides;\n this.success(\"Customization applied\");\n }\n /**\n * Access advanced styling API (for power users)\n */\n styles() {\n return createLogStyleBuilder(this);\n }\n // ===== HANDLER MANAGEMENT =====\n /**\n * Añade un handler personalizado para extender funcionalidad\n * \n * @param {ILogHandler} handler - Handler que implementa ILogHandler\n * \n * @example\n * // Handler personalizado para enviar logs a servidor\n * const remoteHandler = new RemoteLogHandler('https://api.ejemplo.com/logs');\n * logger.addHandler(remoteHandler);\n * \n * @example\n * // Handler para guardar en archivo\n * const fileHandler = new FileLogHandler('./app.log');\n * logger.addHandler(fileHandler);\n * \n * @since 0.3.0\n */\n addHandler(handler) {\n this.handlers.push(handler);\n }\n /**\n * Obtiene todos los handlers registrados\n * \n * @returns {ILogHandler[]} Array de handlers activos\n * @since 0.3.0\n */\n getHandlers() {\n return [...this.handlers];\n }\n /**\n * Obtiene el handler de exportación si está disponible\n *\n * @returns {ExportLogHandler | undefined} Handler de exportación o undefined\n * @since 0.3.0\n */\n getExportHandler() {\n return this.exportHandler;\n }\n // ===== SERIALIZERS =====\n /**\n * Añade un serializador personalizado para un tipo específico\n *\n * @param type - Constructor del tipo a serializar\n * @param serializer - Función de serialización\n * @param priority - Prioridad (mayor = primero)\n *\n * @example\n * logger.addSerializer(Error, (err) => ({\n * name: err.name,\n * message: err.message,\n * stack: err.stack?.split('\\n').slice(0, 5)\n * }));\n *\n * @since 3.0.0\n */\n addSerializer(type, serializer, priority) {\n this.serializerRegistry.add(type, serializer, priority);\n }\n /**\n * Elimina un serializador registrado\n *\n * @param type - Constructor del tipo a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n removeSerializer(type) {\n return this.serializerRegistry.remove(type);\n }\n /**\n * Obtiene el registry de serializadores\n *\n * @returns SerializerRegistry\n * @since 3.0.0\n */\n getSerializerRegistry() {\n return this.serializerRegistry;\n }\n // ===== HOOKS & MIDDLEWARE =====\n /**\n * Registra un hook para un evento\n *\n * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'\n * @param callback - Función a ejecutar\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @example\n * const unsubscribe = logger.on('beforeLog', (entry) => {\n * entry.correlationId = getCorrelationId();\n * return entry;\n * });\n *\n * @since 3.0.0\n */\n on(event, callback, priority) {\n return this.hookManager.on(event, callback, priority);\n }\n /**\n * Registra un hook que se ejecuta solo una vez\n *\n * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'\n * @param callback - Función a ejecutar\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @since 3.0.0\n */\n once(event, callback, priority) {\n return this.hookManager.once(event, callback, priority);\n }\n /**\n * Elimina un hook registrado\n *\n * @param event - Evento del hook\n * @param callback - Callback a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n off(event, callback) {\n return this.hookManager.off(event, callback);\n }\n /**\n * Añade un middleware al pipeline\n *\n * @param middleware - Función middleware\n * @param priority - Prioridad (mayor = primero)\n * @returns Función para desregistrar\n *\n * @example\n * logger.use((entry, next) => {\n * entry.requestId = asyncLocalStorage.getStore()?.requestId;\n * next();\n * });\n *\n * @since 3.0.0\n */\n use(middleware, priority) {\n return this.hookManager.use(middleware, priority);\n }\n /**\n * Obtiene el HookManager\n *\n * @returns HookManager\n * @since 3.0.0\n */\n getHookManager() {\n return this.hookManager;\n }\n // ===== TRANSPORTS =====\n /**\n * Añade un transport para envío de logs\n *\n * @param target - Configuración del transport\n * @returns ID único del transport\n *\n * @example\n * // File transport\n * logger.addTransport({\n * target: 'file',\n * options: { destination: '/var/log/app.log' }\n * });\n *\n * @example\n * // HTTP transport con batching\n * logger.addTransport({\n * target: 'http',\n * options: {\n * url: 'https://logs.example.com',\n * batchSize: 100,\n * flushInterval: 5000\n * },\n * level: 'warn'\n * });\n *\n * @since 3.0.0\n */\n addTransport(target) {\n if (!this.transportManager) {\n this.transportManager = new TransportManager();\n }\n return this.transportManager.add(target);\n }\n /**\n * Elimina un transport\n *\n * @param id - ID del transport a remover\n * @returns true si se eliminó\n *\n * @since 3.0.0\n */\n removeTransport(id) {\n return this.transportManager?.remove(id) ?? false;\n }\n /**\n * Fuerza el flush de todos los transports\n *\n * @returns Promise que resuelve cuando todos los buffers están vaciados\n *\n * @since 3.0.0\n */\n async flushTransports() {\n await this.transportManager?.flush();\n }\n /**\n * Cierra todos los transports\n *\n * @returns Promise que resuelve cuando todos están cerrados\n *\n * @since 3.0.0\n */\n async closeTransports() {\n await this.transportManager?.close();\n }\n /**\n * Obtiene el TransportManager\n *\n * @returns TransportManager o undefined si no hay transports\n * @since 3.0.0\n */\n getTransportManager() {\n return this.transportManager;\n }\n // ===== CORE LOGGING METHODS =====\n /**\n * Verifica si un nivel de log debe mostrarse según la verbosidad actual\n * @private\n * @param {LogLevel} level - Nivel de log a verificar\n * @returns {boolean} True si debe mostrarse, false si no\n */\n shouldLog(level) {\n if (this.config.verbosity === \"silent\") return false;\n const levels = { debug: 0, info: 1, warn: 2, error: 3, critical: 4 };\n return levels[level] >= levels[this.config.verbosity];\n }\n /**\n * Obtiene el prefijo efectivo (global + scope)\n * @private\n * @returns {string | undefined} Prefijo combinado o undefined\n */\n getEffectivePrefix() {\n const parts = [this.config.globalPrefix, this.scopedPrefix].filter(Boolean);\n return parts.length > 0 ? parts.join(\":\") : void 0;\n }\n /**\n * Método central de logging que maneja estilos y formato\n * @protected\n * @param {LogLevel} level - Nivel del log\n * @param {...any} args - Argumentos a loggear\n */\n log(level, ...args) {\n if (!this.shouldLog(level)) return;\n const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;\n const prefix = this.getEffectivePrefix();\n const timestamp = formatTimestamp$1();\n const serializedArgs = args.map((arg) => this.serializerRegistry.serialize(arg));\n let message = serializedArgs.length > 0 ? String(serializedArgs[0]) : \"\";\n if (this.badgeList.length > 0 && this.displaySettings.showBadges) {\n const badgePrefix = this.badgeList.map((b) => `[${b}]`).join(\"\");\n message = badgePrefix + \" \" + message;\n }\n const additionalArgs = serializedArgs.slice(1);\n let hookEntry = {\n level,\n message,\n args: serializedArgs,\n timestamp,\n prefix,\n stackInfo: stackInfo || void 0\n };\n this.hookManager.emit(\"beforeLog\", hookEntry).then((processed) => {\n message = processed.message;\n }).catch(() => {\n });\n const [format, ...styles2] = createStyledOutput(\n level,\n LEVEL_STYLES,\n prefix,\n message,\n this.displaySettings.showLocation ? stackInfo : null,\n this.config.autoDetectTheme,\n this._activePreset,\n this._activePresetName\n );\n const groupIndent = \" \".repeat(this.groupDepth);\n const finalFormat = groupIndent + format;\n this.writeOutput(finalFormat, level, styles2, additionalArgs);\n if (this.exportHandler) {\n this.exportHandler.setGroupInfo(this.groupDepth);\n }\n const metadata = {\n timestamp,\n level,\n prefix,\n stackInfo: stackInfo ? stackInfo : void 0\n };\n this.handlers.forEach((handler) => {\n try {\n handler.handle(level, message, serializedArgs, metadata);\n } catch (error2) {\n console.error(\"Log handler failed:\", error2);\n }\n });\n if (this.transportManager) {\n const levelValues = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n critical: 4\n };\n const record = {\n level,\n levelValue: levelValues[level],\n time: Date.now(),\n msg: message,\n prefix,\n location: stackInfo ? {\n file: stackInfo.file,\n line: stackInfo.line,\n column: stackInfo.column,\n function: stackInfo.function\n } : void 0\n };\n this.transportManager.write(record).catch(() => {\n });\n }\n this.hookManager.emit(\"afterLog\", hookEntry).catch(() => {\n });\n }\n logWithBindings(bindings, level, ...args) {\n if (!this.shouldLog(level)) return;\n let prefix = \"\";\n const colorCapability = getColorCapability();\n if (bindings.badges?.length) {\n prefix += bindings.badges.map((b) => formatBadge(b, \"pill\", colorCapability, \"#00ff88\")).join(\" \") + \" \";\n }\n if (bindings.scope) {\n prefix += formatBadge(bindings.scope, \"pill\", colorCapability, \"#00ffff\") + \" \";\n }\n if (prefix && args.length > 0) {\n args[0] = prefix + String(args[0]);\n }\n this.log(level, ...args);\n }\n debug(...args) {\n this.log(\"debug\", ...args);\n }\n /**\n * Registra mensajes informativos\n * \n * @param {...any} args - Mensajes y datos informativos\n * \n * @example\n * logger.info('Servidor iniciado en puerto 3000');\n * logger.info('Usuario conectado:', userId);\n * logger.info('Procesando', totalItems, 'elementos');\n * \n * @since 0.3.0\n */\n info(...args) {\n this.log(\"info\", ...args);\n }\n /**\n * Registra mensajes de advertencia\n * \n * @param {...any} args - Mensajes de advertencia\n * \n * @example\n * logger.warn('Memoria al 85% de capacidad');\n * logger.warn('API deprecada, usar v2');\n * logger.warn('Reintentos agotados:', maxRetries);\n * \n * @since 0.3.0\n */\n warn(...args) {\n this.log(\"warn\", ...args);\n }\n /**\n * Registra mensajes de error\n * \n * @param {...any} args - Mensajes de error y stack traces\n * \n * @example\n * logger.error('Fallo en conexión a base de datos');\n * logger.error('Error al procesar:', error.message, error.stack);\n * logger.error('Código de error:', errorCode);\n * \n * @since 0.3.0\n */\n error(...args) {\n this.log(\"error\", ...args);\n }\n /**\n * Registra mensajes de éxito (nivel info especial)\n * \n * @param {...any} args - Mensajes de operaciones exitosas\n * \n * @example\n * logger.success('Base de datos conectada');\n * logger.success('Usuario creado con ID:', userId);\n * logger.success('✓ Tests pasados: 42/42');\n * \n * @since 0.3.0\n */\n success(...args) {\n if (!this.shouldLog(\"info\")) return;\n const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;\n const prefix = this.getEffectivePrefix();\n const message = args.length > 0 ? String(args[0]) : \"\";\n const additionalArgs = args.slice(1);\n const [format, ...styles2] = createStyledOutput(\n \"info\",\n LEVEL_STYLES,\n prefix,\n message,\n this.displaySettings.showLocation ? stackInfo : null,\n this.config.autoDetectTheme,\n this._activePreset,\n this._activePresetName\n );\n const successStyle = LEVEL_STYLES.success;\n let emoji = \"✅\";\n let label = \"SUCCESS\";\n if (successStyle) {\n if (successStyle.emoji) {\n emoji = successStyle.emoji;\n }\n if (successStyle.label) {\n label = successStyle.label;\n }\n }\n const successFormat = format.replace(/ℹ️ INFO/, `${emoji} ${label}`);\n const groupIndent = \" \".repeat(this.groupDepth);\n const finalFormat = groupIndent + successFormat;\n if (additionalArgs.length > 0) {\n console.log(finalFormat, ...styles2, ...additionalArgs);\n } else {\n console.log(finalFormat, ...styles2);\n }\n const metadata = {\n timestamp: formatTimestamp$1(),\n level: \"info\",\n prefix,\n stackInfo: stackInfo ? stackInfo : void 0\n };\n this.handlers.forEach((handler) => {\n try {\n handler.handle(\"info\", message, args, metadata);\n } catch (error2) {\n console.error(\"Log handler failed:\", error2);\n }\n });\n }\n /**\n * Registra información de trace (debugging detallado)\n * \n * @param {...any} args - Datos detallados para debugging\n * \n * @example\n * logger.trace('Entrando en función processData');\n * logger.trace('Stack completo:', new Error().stack);\n * \n * @since 0.3.0\n */\n trace(...args) {\n this.log(\"debug\", ...args);\n if (this.shouldLog(\"debug\")) {\n console.trace(...args);\n }\n }\n /**\n * Registra errores críticos (prioridad más alta)\n * \n * @param {...any} args - Errores críticos del sistema\n * \n * @example\n * logger.critical('Sistema caído - reinicio inmediato requerido');\n * logger.critical('Pérdida de datos detectada');\n * logger.critical('Brecha de seguridad:', securityError);\n * \n * @since 0.3.0\n */\n critical(...args) {\n this.log(\"critical\", ...args);\n }\n // ===== ADVANCED LOGGING FEATURES =====\n /**\n * Muestra datos en formato de tabla\n * \n * @param {any} data - Datos a mostrar (array de objetos o matriz)\n * @param {string[]} columns - Columnas específicas a mostrar (opcional)\n * \n * @example\n * const usuarios = [\n * { id: 1, nombre: 'Juan', edad: 30 },\n * { id: 2, nombre: 'María', edad: 25 }\n * ];\n * logger.table(usuarios);\n * logger.table(usuarios, ['nombre', 'edad']); // Solo estas columnas\n * \n * @since 0.3.0\n */\n table(data, columns) {\n if (!this.shouldLog(\"info\")) return;\n const prefix = this.getEffectivePrefix();\n const tableStyle = StylePresets.accent().build();\n const format = `%c📊 TABLE${prefix ? ` [${prefix}]` : \"\"}`;\n console.log(format, tableStyle);\n if (columns) {\n console.table(data, columns);\n } else {\n console.table(data);\n }\n }\n /**\n * Inicia un grupo colapsable en la consola\n * \n * @param {string} label - Etiqueta del grupo\n * @param {boolean} collapsed - Si el grupo inicia colapsado (default: false)\n * \n * @example\n * logger.group('Procesando usuarios');\n * logger.info('Usuario 1 procesado');\n * logger.info('Usuario 2 procesado');\n * logger.groupEnd();\n * \n * @example\n * // Grupo colapsado por defecto\n * logger.group('Detalles adicionales', true);\n * logger.debug('Información detallada aquí');\n * logger.groupEnd();\n * \n * @since 0.3.0\n */\n group(label, collapsed = false) {\n const groupStyle = new StyleBuilder().bg(\"linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)\").color(\"#1565c0\").border(\"1px solid #90caf9\").padding(\"4px 12px\").rounded(\"6px\").bold().build();\n const format = `%c📁 ${label}`;\n if (collapsed) {\n console.groupCollapsed(format, groupStyle);\n } else {\n console.group(format, groupStyle);\n }\n this.groupDepth++;\n }\n /**\n * Finaliza el grupo actual de la consola\n * \n * @example\n * logger.group('Operaciones');\n * logger.info('Operación 1');\n * logger.info('Operación 2');\n * logger.groupEnd(); // Cierra el grupo\n * \n * @since 0.3.0\n */\n groupEnd() {\n if (this.groupDepth > 0) {\n console.groupEnd();\n this.groupDepth--;\n }\n }\n // ===== PERFORMANCE TIMING =====\n /**\n * Inicia un temporizador con la etiqueta dada\n * \n * @param {string} label - Etiqueta identificadora del temporizador\n * \n * @example\n * logger.time('proceso-datos');\n * // ... operación costosa ...\n * logger.timeEnd('proceso-datos'); // ⏱️ Timer ended: proceso-datos - 1523.45ms\n * \n * @since 0.3.0\n */\n time(label) {\n const timer = {\n label,\n startTime: performance.now()\n };\n this.timers.set(label, timer);\n const timerStyle = StylePresets.warning().build();\n console.log(`%c⏱️ Timer started: ${label}`, timerStyle);\n }\n /**\n * Finaliza un temporizador y muestra el tiempo transcurrido\n * \n * @param {string} label - Etiqueta del temporizador a finalizar\n * \n * @example\n * logger.time('consulta-db');\n * await consultarBaseDatos();\n * logger.timeEnd('consulta-db'); // ⏱️ Timer ended: consulta-db - 234.56ms\n * \n * @since 0.3.0\n */\n timeEnd(label) {\n const timer = this.timers.get(label);\n if (!timer) {\n this.warn(`Timer '${label}' does not exist`);\n return;\n }\n const elapsed = performance.now() - timer.startTime;\n this.timers.delete(label);\n const timerStyle = StylePresets.success().build();\n console.log(`%c⏱️ Timer ended: ${label} - ${elapsed.toFixed(2)}ms`, timerStyle);\n }\n // ===== ADVANCED VISUAL FEATURES =====\n /**\n * Muestra un banner con el tipo especificado o configurado\n * \n * @param {BannerType} bannerType - Tipo de banner (opcional)\n * \n * @example\n * logger.showBanner('ascii'); // Banner ASCII art\n * logger.showBanner('unicode'); // Banner con caracteres Unicode\n * logger.showBanner('svg'); // Banner con gráfico SVG\n * logger.showBanner(); // Usa el tipo configurado\n * \n * @since 0.3.0\n */\n showBanner(bannerType) {\n const effectiveBannerType = bannerType ? bannerType : this.config.bannerType;\n displayInitBanner(effectiveBannerType);\n }\n /**\n * Registra mensaje con imagen SVG de fondo\n * \n * @param {string} message - Mensaje a mostrar\n * @param {string} svgContent - Contenido SVG personalizado (opcional)\n * @param {StyleOptions} options - Opciones de estilo (ancho, alto, padding)\n * \n * @example\n * // SVG automático con gradiente\n * logger.logWithSVG('🎆 Bienvenido a Better Logger');\n * \n * @example\n * // SVG personalizado\n * const customSVG = '<svg>...</svg>';\n * logger.logWithSVG('Logo', customSVG, { width: 400, height: 100 });\n * \n * @since 0.3.0\n */\n logWithSVG(message, svgContent, options = {}) {\n const { width = 300, height = 60, padding = \"30px 150px\" } = options;\n let svgDataUri = \"\";\n if (svgContent) {\n const encodedSVG = encodeURIComponent(svgContent);\n svgDataUri = `data:image/svg+xml,${encodedSVG}`;\n } else {\n const defaultSVG = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${width} ${height}'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='4'/><text x='${width / 2}' y='${height / 2 + 5}' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>${message}</text></svg>`;\n svgDataUri = `data:image/svg+xml,${encodeURIComponent(defaultSVG)}`;\n }\n const svgStyle = new StyleBuilder().bg(`url(\"${svgDataUri}\") no-repeat center center`).padding(padding).color(\"transparent\").rounded(\"4px\").build();\n console.log(`%c${message}`, svgStyle);\n }\n /**\n * Registra mensaje con gradiente animado de fondo\n * \n * @param {string} message - Mensaje a animar\n * @param {number} duration - Duración de la animación en segundos (default: 3)\n * \n * @example\n * logger.logAnimated('🌈 Animación en progreso');\n * logger.logAnimated('Cargando...', 5); // Animación de 5 segundos\n * \n * @since 0.3.0\n */\n logAnimated(message, duration = 3) {\n if (!document.getElementById(\"logger-animations\")) {\n const style = document.createElement(\"style\");\n style.id = \"logger-animations\";\n style.textContent = `\n @keyframes loggerGradient {\n 0% { background-position: 0% 50%; }\n 50% { background-position: 100% 50%; }\n 100% { background-position: 0% 50%; }\n }\n `;\n document.head.appendChild(style);\n }\n const animatedStyle = new StyleBuilder().bg(\"linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2)\").css(\"background-size\", \"400% 400%\").color(\"#ffffff\").padding(\"12px 20px\").rounded(\"8px\").bold().font(\"Monaco, Consolas, monospace\").animation(`loggerGradient ${duration}s ease infinite`).display(\"inline-block\").build();\n console.log(`%c${message}`, animatedStyle);\n }\n /**\n * Agrupa logs por una propiedad específica usando Object.groupBy (cuando esté disponible)\n * \n * @param {T[]} items - Array de elementos a agrupar\n * @param {Function} groupBy - Función que retorna la clave de agrupación\n * \n * @example\n * const ventas = [\n * { producto: 'Laptop', categoria: 'Electrónica', precio: 1200 },\n * { producto: 'Mouse', categoria: 'Electrónica', precio: 25 },\n * { producto: 'Libro', categoria: 'Literatura', precio: 15 }\n * ];\n * logger.logGrouped(ventas, item => item.categoria);\n * \n * @since 0.3.0\n */\n logGrouped(items, groupBy) {\n try {\n let grouped;\n if (Object.groupBy) {\n grouped = Object.groupBy(items, groupBy);\n } else {\n grouped = items.reduce((acc, item) => {\n const key = groupBy(item);\n if (!acc[key]) {\n acc[key] = [];\n }\n acc[key].push(item);\n return acc;\n }, {});\n }\n Object.entries(grouped).forEach(([group2, groupItems]) => {\n this.group(`Group: ${group2}`);\n this.table(groupItems);\n this.groupEnd();\n });\n } catch {\n this.info(\"Grouped data:\", items);\n }\n }\n // ===== OUTPUT WRITER SYSTEM =====\n /**\n * Writes formatted output to the configured destination.\n * Respects outputMode configuration for console, silent, or custom output.\n *\n * @private\n * @param {string} message - Formatted log message\n * @param {LogLevel} level - Log level\n * @param {string[]} styles - CSS styles for browser console\n * @param {any[]} additionalArgs - Additional arguments to log\n * @since 4.0.0\n */\n writeOutput(message, level, styles2, additionalArgs) {\n const mode = this.config.outputMode ?? \"console\";\n if (mode === \"silent\") {\n return;\n }\n if (mode === \"custom\" && this.config.outputWriter) {\n const fullMessage = additionalArgs.length > 0 ? `${message} ${additionalArgs.map((a) => String(a)).join(\" \")}` : message;\n this.config.outputWriter.write(fullMessage, level, styles2);\n return;\n }\n if (additionalArgs.length > 0) {\n console.log(message, ...styles2, ...additionalArgs);\n } else {\n console.log(message, ...styles2);\n }\n }\n // ===== CLI SYSTEM =====\n /**\n * Procesador de comandos CLI para configuración y exportación del logger\n * \n * @param {string} command - Comando CLI a ejecutar\n * @returns {Promise<void>}\n * \n * @example\n * // Comandos disponibles\n * await logger.cli('export json'); // Exporta logs en JSON\n * await logger.cli('export csv'); // Exporta logs en CSV\n * await logger.cli('theme list'); // Lista temas disponibles\n * await logger.cli('theme set neon'); // Cambia al tema neon\n * await logger.cli('config show'); // Muestra configuración actual\n * await logger.cli('history clear'); // Limpia historial de logs\n * await logger.cli('status'); // Muestra estado del logger\n * await logger.cli('help'); // Muestra ayuda de comandos\n * \n * @since 0.3.0\n */\n async cli(command) {\n if (!this.cliProcessor) {\n this.error(\"CLI processor not initialized\");\n return;\n }\n await this.cliProcessor.processCommand(command, this);\n }\n}\nlet _defaultLogger = null;\nfunction getDefaultLogger() {\n if (!_defaultLogger) {\n _defaultLogger = new Logger({\n verbosity: \"info\",\n enableColors: true,\n enableTimestamps: true,\n enableStackTrace: true,\n bufferSize: 1e3\n // Enable export functionality by default\n });\n try {\n displayInitBanner();\n } catch (error2) {\n }\n }\n return _defaultLogger;\n}\ngetDefaultLogger();\nexport {\n APILogger as A,\n BANNER_VARIANTS as B,\n ComponentLogger as C,\n ExportLogHandler as E,\n HookManager as H,\n Logger as L,\n SerializerRegistry as S,\n THEME_PRESETS as T,\n THEME_BANNERS as a,\n TransportManager as b,\n ScopedLogger as c,\n ContextLogger as d,\n formatColumns as e,\n formatWithRightAlign as f,\n formatKeyValue as g,\n formatBadge as h,\n formatTimestamp as i,\n formatRelativeTime as j,\n formatElapsedTime as k,\n isKeyValueObject as l,\n getVisibleLength as m,\n applyLogOptions as n,\n displayInitBanner as o,\n padToWidth as p,\n resetStartTime as r,\n stripAnsi as s\n};\n//# sourceMappingURL=Logger-D-gmmgR2.js.map\n","import { z as supportsANSIColors, f as formatTimestamp } from \"./environment-COWvu6Wz.js\";\nconst ANSI_CODES = {\n // Colors\n black: 30,\n red: 31,\n green: 32,\n yellow: 33,\n blue: 34,\n cyan: 36,\n white: 37,\n // Bright colors\n brightBlack: 90,\n bgRed: 41,\n bgGreen: 42,\n bgYellow: 43,\n // Styles\n reset: 0,\n bold: 1,\n dim: 2,\n underline: 4,\n blink: 5\n};\nconst ANSI_LEVEL_STYLES = {\n debug: {\n color: ANSI_CODES.brightBlack,\n styles: [ANSI_CODES.dim],\n emoji: \"🔍\"\n },\n info: {\n color: ANSI_CODES.blue,\n styles: [ANSI_CODES.bold],\n emoji: \"ℹ️\"\n },\n warn: {\n color: ANSI_CODES.yellow,\n background: ANSI_CODES.bgYellow,\n styles: [ANSI_CODES.bold, ANSI_CODES.black],\n emoji: \"⚠️\"\n },\n error: {\n color: ANSI_CODES.red,\n background: ANSI_CODES.bgRed,\n styles: [ANSI_CODES.bold],\n emoji: \"❌\"\n },\n critical: {\n color: ANSI_CODES.white,\n background: ANSI_CODES.bgRed,\n styles: [ANSI_CODES.bold, ANSI_CODES.blink],\n emoji: \"🚨\"\n },\n success: {\n color: ANSI_CODES.green,\n background: ANSI_CODES.bgGreen,\n styles: [ANSI_CODES.bold],\n emoji: \"✅\"\n }\n};\nfunction ansi(code) {\n const codes = Array.isArray(code) ? code : [code];\n return `\\x1B[${codes.join(\";\")}m`;\n}\nfunction ansiStyle(text, codes) {\n if (!supportsANSIColors()) return text;\n return `${ansi(codes)}${text}${ansi(ANSI_CODES.reset)}`;\n}\nfunction ansiColor(text, color) {\n return ansiStyle(text, [color]);\n}\nfunction ansiBackground(text, bg, color) {\n if (color) {\n return ansiStyle(text, [color, bg]);\n }\n return ansiStyle(text, [bg]);\n}\nfunction ansiBold(text) {\n return ansiStyle(text, [ANSI_CODES.bold]);\n}\nfunction ansiDim(text) {\n return ansiStyle(text, [ANSI_CODES.dim]);\n}\nfunction ansiUnderline(text) {\n return ansiStyle(text, [ANSI_CODES.underline]);\n}\nfunction formatTimestampANSI(timestamp) {\n return ansiColor(timestamp, ANSI_CODES.brightBlack);\n}\nfunction formatLogLevelANSI(level, useEmojis = true) {\n const style = ANSI_LEVEL_STYLES[level];\n const emoji = useEmojis ? style.emoji : \"\";\n const label = level.toUpperCase().padEnd(8);\n if (!supportsANSIColors()) {\n return `${emoji} ${label}`;\n }\n let codes = [style.color, ...style.styles];\n if (style.background) {\n codes.push(style.background);\n }\n return ansiStyle(`${emoji} ${label}`, codes);\n}\nfunction formatSuccessANSI(message, useEmojis = true) {\n const style = ANSI_LEVEL_STYLES.success;\n const emoji = useEmojis ? style.emoji : \"\";\n if (!supportsANSIColors()) {\n return `${emoji} SUCCESS: ${message}`;\n }\n const prefix = ansiStyle(`${emoji} SUCCESS:`, [style.color, ...style.styles]);\n return `${prefix} ${message}`;\n}\nfunction formatPrefixANSI(prefix) {\n if (!supportsANSIColors()) {\n return `[${prefix}]`;\n }\n return ansiStyle(`[${prefix}]`, [ANSI_CODES.cyan, ANSI_CODES.bold]);\n}\nfunction formatLocationANSI(location) {\n if (!supportsANSIColors()) {\n return `(${location})`;\n }\n return ansiColor(`(${location})`, ANSI_CODES.brightBlack);\n}\nconst BUILD_FORMATTERS = {\n /**\n * Format compilation step\n */\n compilation: (step, status = \"starting\") => {\n const stepText = ansiBold(step);\n switch (status) {\n case \"starting\":\n return `${ansiColor(\"⚙️\", ANSI_CODES.blue)} ${stepText}...`;\n case \"completed\":\n return `${ansiColor(\"✓\", ANSI_CODES.green)} ${stepText} ${ansiColor(\"completed\", ANSI_CODES.green)}`;\n case \"failed\":\n return `${ansiColor(\"✗\", ANSI_CODES.red)} ${stepText} ${ansiColor(\"failed\", ANSI_CODES.red)}`;\n default:\n return stepText;\n }\n },\n /**\n * Format warning message\n */\n warning: (message) => {\n return `${ansiColor(\"⚠\", ANSI_CODES.yellow)} ${ansiStyle(\"Warning:\", [ANSI_CODES.yellow, ANSI_CODES.bold])} ${message}`;\n },\n /**\n * Format error message\n */\n error: (message) => {\n return `${ansiColor(\"✗\", ANSI_CODES.red)} ${ansiStyle(\"Error:\", [ANSI_CODES.red, ANSI_CODES.bold])} ${message}`;\n },\n /**\n * Format success message\n */\n success: (message) => {\n return `${ansiColor(\"✓\", ANSI_CODES.green)} ${ansiColor(message, ANSI_CODES.green)}`;\n },\n /**\n * Format info message\n */\n info: (message) => {\n return `${ansiColor(\"ℹ\", ANSI_CODES.blue)} ${message}`;\n }\n};\nconst EMOJI_ALTERNATIVES = {\n \"🔍\": \"[DEBUG]\",\n \"ℹ️\": \"[INFO]\",\n \"⚠️\": \"[WARN]\",\n \"❌\": \"[ERROR]\",\n \"🚨\": \"[CRITICAL]\",\n \"✅\": \"[OK]\",\n \"✓\": \"[OK]\",\n \"✗\": \"[FAIL]\",\n \"⚙️\": \"[BUILD]\",\n \"📦\": \"[PKG]\"\n};\nfunction sanitizeEmojis(text) {\n const isModernTerminal = process.env.TERM && (process.env.TERM.includes(\"xterm\") || process.env.TERM.includes(\"screen\") || process.env.TERM.includes(\"tmux\"));\n const isCI = process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL;\n if (isModernTerminal && !isCI) {\n return text;\n }\n let result = text;\n Object.entries(EMOJI_ALTERNATIVES).forEach(([emoji, alt]) => {\n result = result.replace(new RegExp(emoji, \"g\"), alt);\n });\n return result;\n}\nfunction createOutput(level, message, prefix, stackInfo, format = \"auto\") {\n const detectedFormat = format === \"auto\" ? detectOptimalFormat() : format;\n switch (detectedFormat) {\n case \"ansi\":\n return createANSIOutput(level, message, prefix, stackInfo);\n case \"build\":\n return createBuildOutput(level, message, prefix, stackInfo);\n case \"ci\":\n return createCIOutput(level, message, prefix, stackInfo);\n case \"plain\":\n default:\n return createPlainOutput(level, message, prefix, stackInfo);\n }\n}\nfunction createPlainOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return output;\n}\nfunction createANSIOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = \"\";\n output += formatTimestampANSI(`[${timeStr}]`) + \" \";\n output += formatLogLevelANSI(level) + \" \";\n if (prefix) {\n output += formatPrefixANSI(prefix) + \" \";\n }\n output += message;\n if (stackInfo) {\n output += \" \" + formatLocationANSI(`(${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`);\n }\n return sanitizeEmojis(output);\n}\nfunction createBuildOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = \"\";\n if (supportsANSIColors()) {\n output += formatTimestampANSI(`[${timeStr}]`) + \" \";\n switch (level) {\n case \"info\":\n output += BUILD_FORMATTERS.info(message);\n break;\n case \"warn\":\n output += BUILD_FORMATTERS.warning(message);\n break;\n case \"error\":\n case \"critical\":\n output += BUILD_FORMATTERS.error(message);\n break;\n default:\n output += `${formatLogLevelANSI(level)} ${message}`;\n }\n } else {\n output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n }\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return sanitizeEmojis(output);\n}\nfunction createCIOutput(level, message, prefix, stackInfo) {\n const timestamp = formatTimestamp();\n const timeStr = timestamp.slice(11, 23);\n let output = `[${timeStr}] [${level.toUpperCase()}]`;\n if (prefix) {\n output += ` [${prefix}]`;\n }\n output += ` ${message}`;\n if (stackInfo) {\n output += ` (${stackInfo.file}:${stackInfo.line}:${stackInfo.column})`;\n }\n return sanitizeEmojis(output);\n}\nfunction detectOptimalFormat() {\n const isCI = process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL || process.env.GITLAB_CI || process.env.TRAVIS || process.env.CIRCLECI;\n process.env.NEXT_RUNTIME || process.argv.some((arg) => arg.includes(\"next\"));\n if (isCI) {\n return \"ci\";\n }\n {\n return \"build\";\n }\n}\nfunction getConsoleMethod(level) {\n switch (level) {\n case \"debug\":\n return \"log\";\n case \"info\":\n return \"info\";\n case \"warn\":\n return \"warn\";\n case \"error\":\n case \"critical\":\n return \"error\";\n default:\n return \"log\";\n }\n}\nfunction createLogEntry(level, message, args, prefix, stackInfo) {\n return {\n timestamp: formatTimestamp(),\n level: level.toUpperCase(),\n prefix,\n message,\n args: args.slice(1),\n // Exclude the first message argument\n location: stackInfo ? {\n file: stackInfo.file,\n line: stackInfo.line,\n column: stackInfo.column,\n function: stackInfo.function\n } : void 0,\n raw: args\n };\n}\nfunction formatTablePlain(data, columns) {\n try {\n if (Array.isArray(data)) {\n if (data.length === 0) return \"[Empty Array]\";\n if (typeof data[0] !== \"object\") {\n return data.map((item, i) => `${i}: ${item}`).join(\"\\n\");\n }\n const keys = columns || Object.keys(data[0] || {});\n const header = keys.join(\"\t\");\n const rows = data.map(\n (item) => keys.map((key) => String(item[key] || \"\")).join(\"\t\")\n );\n return [header, ...rows].join(\"\\n\");\n }\n if (typeof data === \"object\" && data !== null) {\n return Object.entries(data).map(([key, value]) => `${key}: ${value}`).join(\"\\n\");\n }\n return String(data);\n } catch (error) {\n return `[Error formatting table: ${error}]`;\n }\n}\nfunction safeSerialize(obj, maxDepth = 3, currentDepth = 0) {\n if (currentDepth >= maxDepth) {\n return \"[Max Depth Reached]\";\n }\n if (obj === null) return null;\n if (obj === void 0) return \"[undefined]\";\n if (typeof obj === \"function\") return \"[Function]\";\n if (obj instanceof Error) return `[Error: ${obj.message}]`;\n if (obj instanceof Date) return obj.toISOString();\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) {\n return obj.map((item) => safeSerialize(item, maxDepth, currentDepth + 1));\n }\n const result = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = safeSerialize(value, maxDepth, currentDepth + 1);\n }\n return result;\n}\nexport {\n BUILD_FORMATTERS as B,\n createANSIOutput as a,\n createBuildOutput as b,\n createOutput as c,\n detectOptimalFormat as d,\n createCIOutput as e,\n ansiStyle as f,\n ansiColor as g,\n ansiBackground as h,\n ansiBold as i,\n ansiDim as j,\n ansiUnderline as k,\n formatLogLevelANSI as l,\n formatSuccessANSI as m,\n sanitizeEmojis as n,\n getConsoleMethod as o,\n createLogEntry as p,\n formatTablePlain as q,\n createPlainOutput as r,\n safeSerialize as s\n};\n//# sourceMappingURL=formatting-CYjT9yhO.js.map\n","import { L as Logger } from \"./chunks/Logger-D-gmmgR2.js\";\nimport { A, B, C, d, H, c, S, a, T, b, n, h, e, k, g, j, i, f, m, l, p, r, s } from \"./chunks/Logger-D-gmmgR2.js\";\nimport { i as isNode, a as isBrowser, S as StylePresets, b as StyleBuilder } from \"./chunks/environment-COWvu6Wz.js\";\nimport { A as A2, B as B2, D, E, T as T2, e as e2, n as n2, d as d2, f as f2, m as m2, l as l2, k as k2, j as j2, t, o, w, g as g2, v, u, c as c2, h as h2, q, p as p2, r as r2, s as s2 } from \"./chunks/environment-COWvu6Wz.js\";\nimport { s as safeSerialize } from \"./chunks/formatting-CYjT9yhO.js\";\nimport { B as B3, h as h3, i as i2, g as g3, j as j3, f as f3, k as k3, a as a2, b as b2, e as e3, c as c3, d as d3, l as l3, m as m3, n as n3 } from \"./chunks/formatting-CYjT9yhO.js\";\nimport { R } from \"./chunks/RemoteLogHandler-CjWpWZGl.js\";\nclass ConsoleTransport {\n constructor(options) {\n this.options = options;\n }\n name = \"console\";\n write(record) {\n const method = this.getConsoleMethod(record.level);\n const prefix = record.prefix ? `[${record.prefix}] ` : \"\";\n const location = record.location ? ` (${record.location.file}:${record.location.line})` : \"\";\n console[method](`[${record.level.toUpperCase()}]${prefix} ${record.msg}${location}`);\n }\n getConsoleMethod(level) {\n switch (level) {\n case \"debug\":\n return \"log\";\n case \"info\":\n return \"info\";\n case \"warn\":\n return \"warn\";\n case \"error\":\n case \"critical\":\n return \"error\";\n default:\n return \"log\";\n }\n }\n}\nclass FileTransport {\n name = \"file\";\n buffer = [];\n flushTimer;\n options;\n constructor(options) {\n this.options = options || {};\n if (this.options.flushInterval) {\n this.flushTimer = setInterval(() => this.flush(), this.options.flushInterval);\n }\n }\n write(record) {\n const line = JSON.stringify(record) + \"\\n\";\n this.buffer.push(line);\n if (this.buffer.length >= (this.options.batchSize || 100)) {\n this.flush();\n }\n }\n async flush() {\n if (this.buffer.length === 0) return;\n const lines = this.buffer.join(\"\");\n this.buffer = [];\n if (typeof globalThis.process !== \"undefined\" && typeof require === \"function\") {\n try {\n const fs = require(\"fs\");\n const dest = this.options.destination || \"app.log\";\n fs.appendFileSync(dest, lines);\n } catch {\n }\n }\n }\n close() {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n }\n this.flush();\n }\n}\nclass HttpTransport {\n name = \"http\";\n buffer = [];\n flushTimer;\n options;\n constructor(options) {\n this.options = options || {};\n if (this.options.flushInterval) {\n this.flushTimer = setInterval(() => this.flush(), this.options.flushInterval);\n }\n }\n write(record) {\n this.buffer.push(record);\n if (this.buffer.length >= (this.options.batchSize || 50)) {\n this.flush();\n }\n }\n async flush() {\n if (this.buffer.length === 0 || !this.options.url) return;\n const records = [...this.buffer];\n this.buffer = [];\n try {\n await fetch(this.options.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.options.headers\n },\n body: JSON.stringify({ logs: records })\n });\n } catch {\n this.buffer.unshift(...records);\n }\n }\n close() {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n }\n this.flush();\n }\n}\nclass FileLogHandler {\n filename;\n maxSize;\n fs;\n // Node.js fs module\n constructor(filename = \"app.log\", maxSize) {\n this.filename = filename;\n this.maxSize = maxSize;\n if (isNode) {\n try {\n this.fs = require(\"fs\");\n } catch (error2) {\n console.warn(\"FileLogHandler: Unable to load fs module:\", error2);\n }\n }\n }\n handle(level, message, args, metadata) {\n const logEntry = {\n timestamp: metadata.timestamp,\n level: level.toUpperCase(),\n prefix: metadata.prefix,\n message,\n args: args.slice(1).map((arg) => safeSerialize(arg)),\n location: metadata.stackInfo\n };\n const logLine = this.formatLogLine(logEntry);\n if (isNode && this.fs) {\n this.writeToFileNode(logLine);\n } else if (isBrowser) {\n this.writeToFileLocal(logLine);\n } else {\n console.log(`[FILE-LOG] ${logLine}`);\n }\n }\n /**\n * Format log entry as a single line for file storage\n */\n formatLogLine(entry) {\n const parts = [\n entry.timestamp,\n `[${entry.level}]`,\n entry.prefix ? `[${entry.prefix}]` : \"\",\n entry.message\n ].filter(Boolean);\n let line = parts.join(\" \");\n if (entry.args && entry.args.length > 0) {\n line += \" \" + entry.args.map(\n (arg) => typeof arg === \"object\" ? JSON.stringify(arg) : String(arg)\n ).join(\" \");\n }\n if (entry.location) {\n line += ` (${entry.location.file}:${entry.location.line}:${entry.location.column})`;\n }\n return line;\n }\n /**\n * Write to actual file in Node.js environment\n */\n writeToFileNode(logLine) {\n if (!this.fs) return;\n try {\n if (this.maxSize) {\n try {\n const stats = this.fs.statSync(this.filename);\n if (stats.size > this.maxSize) {\n const backupName = `${this.filename}.bak`;\n this.fs.renameSync(this.filename, backupName);\n }\n } catch (error2) {\n }\n }\n this.fs.appendFileSync(this.filename, logLine + \"\\n\", \"utf8\");\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to write to file:\", error2);\n }\n }\n /**\n * Write to localStorage in browser environment\n */\n writeToFileLocal(logLine) {\n try {\n const storageKey = `logger_${this.filename}`;\n const existingLogs = localStorage.getItem(storageKey) || \"\";\n let newLogs = existingLogs;\n if (existingLogs.length > 0) {\n newLogs += \"\\n\";\n }\n newLogs += logLine;\n if (this.maxSize || newLogs.split(\"\\n\").length > 1e3) {\n const lines = newLogs.split(\"\\n\");\n const maxLines = this.maxSize ? Math.floor(this.maxSize / 100) : 1e3;\n if (lines.length > maxLines) {\n newLogs = lines.slice(-maxLines).join(\"\\n\");\n }\n }\n localStorage.setItem(storageKey, newLogs);\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to write to localStorage:\", error2);\n }\n }\n /**\n * Get stored logs (useful for debugging)\n */\n getLogs() {\n if (isNode && this.fs) {\n try {\n return this.fs.readFileSync(this.filename, \"utf8\");\n } catch (error2) {\n return null;\n }\n } else if (isBrowser) {\n const storageKey = `logger_${this.filename}`;\n return localStorage.getItem(storageKey);\n }\n return null;\n }\n /**\n * Clear stored logs\n */\n clearLogs() {\n if (isNode && this.fs) {\n try {\n this.fs.writeFileSync(this.filename, \"\", \"utf8\");\n } catch (error2) {\n console.error(\"FileLogHandler: Failed to clear file:\", error2);\n }\n } else if (isBrowser) {\n const storageKey = `logger_${this.filename}`;\n localStorage.removeItem(storageKey);\n }\n }\n}\nclass AnalyticsLogHandler {\n handle(level, message, _args, metadata) {\n if (level === \"error\" || level === \"critical\") {\n console.debug(\"Analytics: Error tracked\", {\n level,\n message,\n timestamp: metadata.timestamp\n });\n }\n }\n}\nconst DEFAULT_CONFIG = {\n maxEntries: 100,\n ttl: 5 * 60 * 1e3,\n enabled: true\n};\nclass StyleCache {\n cache = /* @__PURE__ */ new Map();\n config;\n hitCount = 0;\n missCount = 0;\n constructor(config = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n generateKey(key) {\n return `${key.level}:${key.theme}:${key.presetName || \"default\"}:${key.hasPrefix}:${key.hasLocation}`;\n }\n get(key) {\n if (!this.config.enabled) return null;\n const cacheKey = this.generateKey(key);\n const entry = this.cache.get(cacheKey);\n if (!entry) {\n this.missCount++;\n return null;\n }\n if (Date.now() - entry.createdAt > this.config.ttl) {\n this.cache.delete(cacheKey);\n this.missCount++;\n return null;\n }\n entry.hits++;\n this.cache.delete(cacheKey);\n this.cache.set(cacheKey, entry);\n this.hitCount++;\n return entry;\n }\n set(key, format, styles) {\n if (!this.config.enabled) return;\n const cacheKey = this.generateKey(key);\n if (this.cache.size >= this.config.maxEntries) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n this.cache.delete(firstKey);\n }\n }\n this.cache.set(cacheKey, {\n format,\n styles: [...styles],\n createdAt: Date.now(),\n hits: 0\n });\n }\n clear() {\n this.cache.clear();\n this.hitCount = 0;\n this.missCount = 0;\n }\n getStats() {\n const total = this.hitCount + this.missCount;\n return {\n size: this.cache.size,\n maxSize: this.config.maxEntries,\n hitRate: total > 0 ? this.hitCount / total : 0,\n hits: this.hitCount,\n misses: this.missCount\n };\n }\n setEnabled(enabled) {\n this.config.enabled = enabled;\n if (!enabled) {\n this.clear();\n }\n }\n isEnabled() {\n return this.config.enabled;\n }\n}\nlet _styleCache = null;\nfunction getStyleCache() {\n if (!_styleCache) {\n _styleCache = new StyleCache();\n }\n return _styleCache;\n}\nclass BufferWriter {\n buffer = [];\n maxSize;\n /**\n * Creates a new BufferWriter\n * @param maxSize - Maximum number of entries to buffer (default: 1000)\n */\n constructor(maxSize = 1e3) {\n this.maxSize = maxSize;\n }\n /**\n * Writes a log entry to the buffer\n * @param message - Formatted log message\n * @param level - Log level\n * @param styles - CSS styles (for browser console)\n */\n write(message, level, styles) {\n if (this.buffer.length >= this.maxSize) {\n this.buffer.shift();\n }\n this.buffer.push({\n message,\n level,\n styles,\n timestamp: Date.now()\n });\n }\n /**\n * Returns all buffered entries\n * @returns Copy of the buffer array\n */\n getBuffer() {\n return [...this.buffer];\n }\n /**\n * Returns buffered entries filtered by log level\n * @param levels - Log levels to include\n * @returns Filtered buffer entries\n */\n getByLevel(...levels) {\n return this.buffer.filter((entry) => levels.includes(entry.level));\n }\n /**\n * Returns the number of buffered entries\n */\n get size() {\n return this.buffer.length;\n }\n /**\n * Checks if buffer is empty\n */\n get isEmpty() {\n return this.buffer.length === 0;\n }\n /**\n * Clears all buffered entries\n */\n clear() {\n this.buffer = [];\n }\n /**\n * Outputs all buffered entries to console and clears the buffer\n */\n flush() {\n this.buffer.forEach((entry) => {\n if (entry.styles.length > 0) {\n console.log(entry.message, ...entry.styles);\n } else {\n console.log(entry.message);\n }\n });\n this.clear();\n }\n /**\n * Outputs buffered entries to console without clearing\n */\n replay() {\n this.buffer.forEach((entry) => {\n if (entry.styles.length > 0) {\n console.log(entry.message, ...entry.styles);\n } else {\n console.log(entry.message);\n }\n });\n }\n /**\n * Returns all messages as an array of strings\n */\n toArray() {\n return this.buffer.map((entry) => entry.message);\n }\n /**\n * Returns all messages joined as a single string\n * @param separator - String to join messages with (default: newline)\n */\n toString(separator = \"\\n\") {\n return this.toArray().join(separator);\n }\n}\nlet _logger = null;\nfunction getLogger() {\n if (!_logger) {\n _logger = new Logger();\n }\n return _logger;\n}\nconst index = getLogger();\nconst debug = (...args) => getLogger().debug(...args);\nconst info = (...args) => getLogger().info(...args);\nconst warn = (...args) => getLogger().warn(...args);\nconst error = (...args) => getLogger().error(...args);\nconst success = (...args) => getLogger().success(...args);\nconst critical = (...args) => getLogger().critical(...args);\nconst trace = (...args) => getLogger().trace(...args);\nconst table = (data, columns) => getLogger().table(data, columns);\nconst group = (label, collapsed) => getLogger().group(label, collapsed);\nconst groupEnd = () => getLogger().groupEnd();\nconst time = (label) => getLogger().time(label);\nconst timeEnd = (label) => getLogger().timeEnd(label);\nconst setGlobalPrefix = (prefix) => getLogger().setGlobalPrefix(prefix);\nconst scope = (name) => getLogger().scope(name);\nconst component = (name) => getLogger().component(name);\nconst api = (name) => getLogger().api(name);\nconst badges = (badgeList) => getLogger().badges(badgeList);\nconst badge = (badgeName) => getLogger().badge(badgeName);\nconst clearBadges = () => getLogger().clearBadges();\nconst setVerbosity = (level) => getLogger().setVerbosity(level);\nconst addHandler = (handler) => getLogger().addHandler(handler);\nconst setTheme = (theme) => getLogger().setTheme(theme);\nconst setBannerType = (bannerType) => getLogger().setBannerType(bannerType);\nconst showBanner = (bannerType) => getLogger().showBanner(bannerType);\nconst logWithSVG = (message, svgContent, options) => getLogger().logWithSVG(message, svgContent, options);\nconst logAnimated = (message, duration) => getLogger().logAnimated(message, duration);\nconst cli = (command) => getLogger().cli(command);\nconst addSerializer = (type, serializer, priority) => getLogger().addSerializer(type, serializer, priority);\nconst removeSerializer = (type) => getLogger().removeSerializer(type);\nconst on = (event, callback, priority) => getLogger().on(event, callback, priority);\nconst once = (event, callback, priority) => getLogger().once(event, callback, priority);\nconst off = (event, callback) => getLogger().off(event, callback);\nconst use = (middleware, priority) => getLogger().use(middleware, priority);\nconst addTransport = (target) => getLogger().addTransport(target);\nconst removeTransport = (id) => getLogger().removeTransport(id);\nconst flushTransports = () => getLogger().flushTransports();\nconst closeTransports = () => getLogger().closeTransports();\nconst createStyle = () => new StyleBuilder();\nconst stylePresets = {\n success: StylePresets.success().build(),\n error: StylePresets.error().build(),\n warning: StylePresets.warning().build(),\n info: StylePresets.info().build(),\n accent: StylePresets.accent().build()\n};\nexport {\n A2 as ANSI,\n A as APILogger,\n AnalyticsLogHandler,\n B as BANNER_VARIANTS,\n B3 as BUILD_FORMATTERS,\n B2 as BUILD_PRESETS,\n BufferWriter,\n C as ComponentLogger,\n ConsoleTransport,\n d as ContextLogger,\n D as DEFAULT_CONFIG,\n E as ENVIRONMENT_DETECTION,\n FileLogHandler,\n FileTransport,\n H as HookManager,\n HttpTransport,\n Logger,\n R as RemoteLogHandler,\n c as ScopedLogger,\n S as SerializerRegistry,\n StyleBuilder,\n StyleCache,\n StylePresets,\n a as THEME_BANNERS,\n T as THEME_PRESETS,\n T2 as TerminalRenderer,\n b as TransportManager,\n addHandler,\n addSerializer,\n addTransport,\n h3 as ansiBackground,\n i2 as ansiBold,\n g3 as ansiColor,\n j3 as ansiDim,\n f3 as ansiStyle,\n k3 as ansiUnderline,\n api,\n n as applyLogOptions,\n badge,\n badges,\n clearBadges,\n cli,\n closeTransports,\n e2 as colorToHex,\n component,\n a2 as createANSIOutput,\n b2 as createBuildOutput,\n e3 as createCIOutput,\n c3 as createOutput,\n createStyle,\n critical,\n n2 as cssColorToANSI,\n debug,\n index as default,\n d2 as detectEnvironmentPreset,\n d3 as detectOptimalFormat,\n error,\n flushTransports,\n h as formatBadge,\n e as formatColumns,\n k as formatElapsedTime,\n g as formatKeyValue,\n l3 as formatLogLevelANSI,\n j as formatRelativeTime,\n m3 as formatSuccessANSI,\n f2 as formatTimestamp,\n i as formatTimestampExt,\n f as formatWithRightAlign,\n m2 as getANSI256Background,\n l2 as getANSI256Foreground,\n k2 as getANSIBackground,\n j2 as getANSIForeground,\n t as getColorCapability,\n o as getEnvironment,\n w as getEnvironmentInfo,\n g2 as getOptimalConfig,\n getStyleCache,\n v as getTerminalHeight,\n u as getTerminalWidth,\n m as getVisibleLength,\n group,\n groupEnd,\n c2 as hexTo256,\n h2 as hexToRgb,\n info,\n l as isKeyValueObject,\n q as isRunningInTerminal,\n logAnimated,\n logWithSVG,\n off,\n on,\n once,\n p as padToWidth,\n p2 as parseStackTrace,\n removeSerializer,\n removeTransport,\n r as resetStartTime,\n r2 as rgbToHex,\n n3 as sanitizeEmojis,\n scope,\n setBannerType,\n setGlobalPrefix,\n setTheme,\n setVerbosity,\n showBanner,\n s as stripAnsi,\n stylePresets,\n success,\n s2 as supportsANSI,\n table,\n time,\n timeEnd,\n trace,\n use,\n warn\n};\n//# sourceMappingURL=index.js.map\n","/**\n * Configuration management for Coolify MCP server.\n *\n * Simplified config that reads from ~/.config/coolify-mks-cli-mcp/config.json\n * or falls back to environment variables.\n *\n * @module\n */\n\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { ok, err, isOk, type Result } from \"@mks2508/no-throw\";\n\nconst CONFIG_DIR = join(homedir(), \".config\", \"coolify-mks-cli-mcp\");\nconst CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\n/**\n * Coolify configuration structure.\n */\nexport interface ICoolifyConfig {\n /** Coolify instance URL */\n url?: string;\n /** Coolify API token */\n token?: string;\n}\n\n/**\n * Loads Coolify configuration from config file or environment variables.\n *\n * Priority: Config file > Environment variables\n *\n * @returns Result with configuration or error\n *\n * @example\n * ```typescript\n * const result = await loadConfig()\n * if (isOk(result)) {\n * console.log('Coolify URL:', result.value.url)\n * }\n * ```\n */\nexport async function loadConfig(): Promise<Result<ICoolifyConfig, Error>> {\n try {\n if (existsSync(CONFIG_FILE)) {\n const content = await readFile(CONFIG_FILE, \"utf-8\");\n const parsed = JSON.parse(content) as ICoolifyConfig;\n return ok(parsed);\n }\n\n // Fallback to environment variables\n return ok({\n url: process.env.COOLIFY_URL,\n token: process.env.COOLIFY_TOKEN,\n });\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Saves Coolify configuration to file.\n *\n * Creates the config directory if it doesn't exist.\n *\n * @param config - Configuration to save\n * @returns Result indicating success or error\n *\n * @example\n * ```typescript\n * const result = await saveConfig({ url: 'https://coolify.example.com', token: 'xxx' })\n * ```\n */\nexport async function saveConfig(\n config: ICoolifyConfig,\n): Promise<Result<void, Error>> {\n try {\n if (!existsSync(CONFIG_DIR)) {\n await mkdir(CONFIG_DIR, { recursive: true });\n }\n await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));\n return ok(undefined);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Gets the Coolify URL from config or environment.\n *\n * @returns Coolify URL or undefined\n */\nexport async function getCoolifyUrl(): Promise<string | undefined> {\n const result = await loadConfig();\n if (isOk(result)) {\n return result.value.url || process.env.COOLIFY_URL;\n }\n return process.env.COOLIFY_URL;\n}\n\n/**\n * Gets the Coolify token from config or environment.\n *\n * @returns Coolify token or undefined\n */\nexport async function getCoolifyToken(): Promise<string | undefined> {\n const result = await loadConfig();\n if (isOk(result)) {\n return result.value.token || process.env.COOLIFY_TOKEN;\n }\n return process.env.COOLIFY_TOKEN;\n}\n\nexport { CONFIG_DIR, CONFIG_FILE };\n","/**\n * Coolify service for MCP server and CLI.\n *\n * Provides all Coolify API operations for deployment management.\n *\n * @module\n */\n\nimport { ok, err, isErr, type Result } from \"@mks2508/no-throw\";\nimport { component } from \"@mks2508/better-logger\";\nimport { loadConfig, type ICoolifyConfig } from \"./config.js\";\nimport {\n type ICoolifyAppOptions,\n type ICoolifyAppResult,\n type ICoolifyApplication,\n type ICoolifyDatabase,\n type ICoolifyDatabaseBackup,\n type ICoolifyDeleteResult,\n type ICoolifyDeployment,\n type ICoolifyDeployOptions,\n type ICoolifyDeployResult,\n type ICoolifyDestination,\n type ICoolifyEnvironment,\n type ICoolifyLogs,\n type ICoolifyLogsOptions,\n type ICoolifyPrivateKey,\n type ICoolifyProject,\n type ICoolifyServer,\n type ICoolifyServerDomain,\n type ICoolifyServerResource,\n type ICoolifyService as ICoolifyServiceType,\n type ICoolifyTeam,\n type ICoolifyUpdateOptions,\n type ICoolifyVersion,\n type ICoolifyInfrastructureTree,\n type ICoolifyProjectNode,\n type ICoolifyEnvironmentNode,\n type ICoolifyResource,\n type IProgressCallback,\n} from \"./types.js\";\n\nconst log = component(\"CoolifyService\");\n\n/**\n * Coolify API response type.\n */\ninterface ICoolifyApiResponse<T> {\n data?: T;\n error?: string;\n status: number;\n durationMs?: number;\n}\n\n/**\n * Environment variable from Coolify API.\n */\nexport interface ICoolifyEnvVar {\n uuid: string;\n key: string;\n value: string;\n real_value?: string;\n is_buildtime: boolean;\n is_runtime: boolean;\n is_required: boolean;\n}\n\n/**\n * Coolify service for deployment operations.\n *\n * @example\n * ```typescript\n * const coolify = new CoolifyService()\n * const initResult = await coolify.init()\n * if (initResult.isErr()) {\n * console.error(initResult.error.message)\n * return\n * }\n *\n * const deployResult = await coolify.deploy({ uuid: 'app-uuid' })\n * if (deployResult.isOk()) {\n * console.log('Deployment UUID:', deployResult.value.deploymentUuid)\n * }\n * ```\n */\nexport class CoolifyService {\n private baseUrl: string | undefined;\n private token: string | undefined;\n private config: ICoolifyConfig = {};\n\n /**\n * Checks if the service is configured with URL and token.\n *\n * @returns true if both URL and token are set\n */\n isConfigured(): boolean {\n const hasUrl = !!this.baseUrl || !!process.env.COOLIFY_URL;\n const hasToken = !!this.token || !!process.env.COOLIFY_TOKEN;\n return hasUrl && hasToken;\n }\n\n /**\n * Initializes the Coolify service by loading configuration.\n *\n * @returns Result indicating success or error\n */\n async init(): Promise<Result<void, Error>> {\n const configResult = await loadConfig();\n\n if (isErr(configResult)) {\n log.error(\"Failed to load config\");\n return err(configResult.error);\n }\n\n this.config = configResult.value;\n this.baseUrl = this.config.url || process.env.COOLIFY_URL;\n this.token = this.config.token || process.env.COOLIFY_TOKEN;\n\n if (!this.baseUrl) {\n log.error(\"No Coolify URL configured\");\n log.info(\n \"Set COOLIFY_URL environment variable or run: coolify-mcp config set url <url>\",\n );\n return err(\n new Error(\n \"No Coolify URL configured. Set COOLIFY_URL or use config command.\",\n ),\n );\n }\n\n if (!this.token) {\n log.error(\"No Coolify token configured\");\n log.info(\n \"Set COOLIFY_TOKEN environment variable or run: coolify-mcp config set token <token>\",\n );\n return err(\n new Error(\n \"No Coolify token configured. Set COOLIFY_TOKEN or use config command.\",\n ),\n );\n }\n\n log.debug(\"Coolify connection configured\");\n return ok(undefined);\n }\n\n /**\n * Makes a request to the Coolify API.\n *\n * @param endpoint - API endpoint\n * @param options - Fetch options\n * @returns API response with data or error\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<ICoolifyApiResponse<T>> {\n const startTime = Date.now();\n\n if (!this.baseUrl || !this.token) {\n return {\n error: \"Coolify not configured\",\n status: 0,\n durationMs: Date.now() - startTime,\n };\n }\n\n try {\n const baseUrl = this.baseUrl.replace(/\\/+$/, \"\");\n const url = `${baseUrl}/api/v1${endpoint}`;\n\n const response = await fetch(url, {\n ...options,\n headers: {\n Authorization: `Bearer ${this.token}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n ...options.headers,\n },\n });\n\n const text = await response.text();\n const durationMs = Date.now() - startTime;\n let data: T | undefined;\n\n try {\n data = text ? JSON.parse(text) : undefined;\n } catch {\n if (!response.ok) {\n return {\n error: text || `HTTP ${response.status}`,\n status: response.status,\n durationMs,\n };\n }\n }\n\n if (!response.ok) {\n const parsed = data as\n | { message?: string; errors?: Record<string, string[]> }\n | undefined;\n let errorMessage = parsed?.message || `HTTP ${response.status}`;\n // Include validation errors if present (Coolify returns { message, errors: { field: [reasons] } })\n if (parsed?.errors) {\n const details = Object.entries(parsed.errors)\n .map(\n ([field, reasons]) =>\n `${field}: ${Array.isArray(reasons) ? reasons.join(\", \") : String(reasons)}`,\n )\n .join(\"; \");\n errorMessage += ` — ${details}`;\n }\n return { error: errorMessage, status: response.status, durationMs };\n }\n\n return { data, status: response.status, durationMs };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return { error: message, status: 0, durationMs: Date.now() - startTime };\n }\n }\n\n /**\n * Deploys an application.\n *\n * @param options - Deployment options\n * @param onProgress - Optional progress callback (0-100, message, step)\n * @returns Result with deployment info or error\n */\n async deploy(\n options: ICoolifyDeployOptions,\n onProgress?: IProgressCallback,\n ): Promise<Result<ICoolifyDeployResult, Error>> {\n if (!options.uuid && !options.tag) {\n return err(new Error(\"Either uuid or tag is required\"));\n }\n\n const appId = options.uuid?.slice(0, 8) || options.tag || \"unknown\";\n onProgress?.(5, `Preparing deployment for ${appId}...`);\n\n log.info(`Deploying application ${options.uuid || options.tag}`);\n\n onProgress?.(25, \"Validating deployment configuration\");\n onProgress?.(50, \"Triggering build pipeline...\");\n\n // Build query parameters for deploy endpoint\n const params = new URLSearchParams();\n if (options.uuid) params.set(\"uuid\", options.uuid);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.force) params.set(\"force\", \"true\");\n\n const endpoint = `/deploy${params.toString() ? `?${params.toString()}` : \"\"}`;\n\n const result = await this.request<{\n deployments: Array<{\n message: string;\n resource_uuid: string;\n deployment_uuid: string;\n }>;\n }>(endpoint, {\n method: \"GET\",\n });\n\n if (result.error) {\n log.error(`Deployment failed: ${result.error}`);\n return err(new Error(result.error));\n }\n\n // Response is { deployments: [{ message, resource_uuid, deployment_uuid }] }\n const deployments = result.data?.deployments || [];\n if (deployments.length === 0) {\n log.error(\"No deployments started\");\n return err(\n new Error(\"No deployments started - check application configuration\"),\n );\n }\n\n const deployment = deployments[0];\n\n onProgress?.(90, \"Build started on Coolify server\");\n onProgress?.(100, \"Deployment triggered\");\n\n log.success(`Deployment started: ${deployment.deployment_uuid}`);\n return ok({\n success: true,\n deploymentUuid: deployment.deployment_uuid,\n resourceUuid: deployment.resource_uuid,\n });\n }\n\n /**\n * Creates a new application in Coolify.\n *\n * Uses type-specific endpoints for different application types:\n * - /applications/public - Public Git repository\n * - /applications/private-github-app - Private repo with GitHub App\n * - /applications/private-deploy-key - Private repo with deploy key\n * - /applications/dockerfile - Dockerfile-based application\n * - /applications/docker-image - Docker image\n * - /applications/docker-compose - Docker Compose application\n *\n * @param options - Application options\n * @param onProgress - Optional progress callback (0-100, message, step)\n * @returns Result with application UUID or error\n */\n async createApplication(\n options: ICoolifyAppOptions,\n onProgress?: IProgressCallback,\n ): Promise<Result<ICoolifyAppResult, Error>> {\n onProgress?.(5, `Preparing app \"${options.name}\"`);\n\n const appType = options.type || \"public\";\n log.info(`Creating application ${options.name} (type: ${appType})`);\n\n onProgress?.(25, `Validating server ${options.serverUuid.slice(0, 8)}...`);\n onProgress?.(50, \"Sending creation request to Coolify API...\");\n\n // Determine endpoint based on application type\n const endpointMap: Record<string, string> = {\n public: \"/applications/public\",\n \"private-github-app\": \"/applications/private-github-app\",\n \"private-deploy-key\": \"/applications/private-deploy-key\",\n dockerfile: \"/applications/dockerfile\",\n \"docker-image\": \"/applications/docker-image\",\n \"docker-compose\": \"/applications/docker-compose\",\n dockerimage: \"/applications/dockerimage\",\n dockercompose: \"/applications/dockercompose\",\n };\n\n const endpoint = endpointMap[appType] || \"/applications/public\";\n\n // Build request body based on application type\n const body: Record<string, unknown> = {\n name: options.name,\n description: options.description,\n project_uuid: options.projectUuid,\n environment_uuid: options.environmentUuid,\n server_uuid: options.serverUuid,\n };\n\n // Git repository — applies to all types that have a repo URL\n if (options.githubRepoUrl) {\n // Coolify expects 'user/repo' format, not full URL\n body.git_repository = options.githubRepoUrl\n .replace(/^https?:\\/\\/github\\.com\\//, \"\")\n .replace(/\\.git$/, \"\");\n }\n\n // Type-specific fields\n if (\n appType === \"public\" ||\n appType === \"private-github-app\" ||\n appType === \"private-deploy-key\"\n ) {\n if (options.githubAppUuid) {\n body.github_app_uuid = options.githubAppUuid;\n }\n body.git_branch = options.branch || \"main\";\n body.build_pack = options.buildPack || \"dockerfile\";\n if (options.portsExposes) {\n body.ports_exposes = options.portsExposes;\n }\n // Dockerfile / Docker Compose configuration\n if (options.dockerfileLocation) {\n body.dockerfile_location = options.dockerfileLocation;\n }\n if (options.dockerComposeLocation) {\n body.docker_compose_location = options.dockerComposeLocation;\n }\n if (options.baseDirectory) {\n body.base_directory = options.baseDirectory;\n }\n } else if (appType === \"docker-image\" && options.dockerImage) {\n body.docker_image = options.dockerImage;\n } else if (appType === \"docker-compose\" && options.dockerCompose) {\n body.docker_compose = options.dockerCompose;\n }\n\n log.debug(`Create application body: ${JSON.stringify(body, null, 2)}`);\n log.debug(`Endpoint: POST ${endpoint}`);\n\n const result = await this.request<{ uuid: string }>(endpoint, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n\n if (result.error) {\n log.error(`Failed to create application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n onProgress?.(100, `Application \"${options.name}\" created`);\n\n log.success(`Application created: ${result.data?.uuid}`);\n return ok({\n success: true,\n uuid: result.data?.uuid,\n });\n }\n\n /**\n * Sets environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @param envVars - Environment variables to set\n * @returns Result indicating success or error\n */\n async setEnvironmentVariables(\n appUuid: string,\n envVars: Record<string, string>,\n ): Promise<Result<void, Error>> {\n log.info(\n `Setting ${Object.keys(envVars).length} environment variables for ${appUuid}`,\n );\n\n // Coolify API: POST to create, PATCH to update existing\n for (const [key, value] of Object.entries(envVars)) {\n const result = await this.request(`/applications/${appUuid}/envs`, {\n method: \"POST\",\n body: JSON.stringify({ key, value, is_preview: false, is_buildtime: false }),\n });\n\n if (result.error && result.error.includes(\"already exists\")) {\n // Var exists — DELETE + re-POST (Coolify PATCH on envs returns 404)\n const listResult = await this.request<\n Array<{ uuid: string; key: string }>\n >(`/applications/${appUuid}/envs`);\n const existing = listResult.data?.find((v) => v.key === key);\n if (existing) {\n await this.request(`/applications/${appUuid}/envs/${existing.uuid}`, {\n method: \"DELETE\",\n });\n const repost = await this.request(`/applications/${appUuid}/envs`, {\n method: \"POST\",\n body: JSON.stringify({ key, value, is_preview: false, is_buildtime: false }),\n });\n if (repost.error) {\n log.error(`Failed to update env var ${key}: ${repost.error}`);\n return err(new Error(`Failed to update ${key}: ${repost.error}`));\n }\n log.debug(`Updated existing env var: ${key}`);\n } else {\n log.error(`Failed to set env var ${key}: ${result.error}`);\n return err(new Error(`Failed to set ${key}: ${result.error}`));\n }\n } else if (result.error) {\n log.error(`Failed to set env var ${key}: ${result.error}`);\n return err(new Error(`Failed to set ${key}: ${result.error}`));\n }\n }\n\n log.success(`${Object.keys(envVars).length} environment variables set`);\n return ok(undefined);\n }\n\n /**\n * Gets environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with environment variables or error\n */\n async getEnvironmentVariables(\n appUuid: string,\n ): Promise<Result<ICoolifyEnvVar[], Error>> {\n log.info(`Getting environment variables for ${appUuid}`);\n\n const result = await this.request<ICoolifyEnvVar[]>(\n `/applications/${appUuid}/envs`,\n );\n\n if (result.error) {\n log.error(`Failed to get env vars: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environment variables retrieved for ${appUuid}`);\n return ok(result.data || []);\n }\n\n /**\n * Sets a single environment variable for an application.\n * Uses PATCH if variable exists, POST if it doesn't.\n *\n * @param appUuid - Application UUID\n * @param key - Variable name\n * @param value - Variable value\n * @param isBuildTime - Whether the variable is available at build time (only for new vars)\n * @returns Result indicating success or error\n */\n async setEnvironmentVariable(\n appUuid: string,\n key: string,\n value: string,\n isBuildTime: boolean = false,\n ): Promise<Result<void, Error>> {\n log.info(`Setting environment variable ${key} for ${appUuid} (buildtime: ${isBuildTime})`);\n\n // Check if variable already exists\n const existingVars = await this.getEnvironmentVariables(appUuid);\n if (isErr(existingVars)) {\n return err(existingVars.error);\n }\n\n const exists = existingVars.value.some((ev) => ev.key === key);\n\n if (exists) {\n // Use PATCH to update existing variable\n log.debug(`Variable ${key} exists, using PATCH to update`);\n const result = await this.request<{ uuid: string }>(\n `/applications/${appUuid}/envs`,\n {\n method: \"PATCH\",\n body: JSON.stringify({\n key,\n value,\n is_buildtime: isBuildTime,\n }),\n },\n );\n\n if (result.error) {\n log.error(`Failed to update env var: ${result.error}`);\n return err(new Error(result.error));\n }\n } else {\n // Use POST to create new variable\n log.debug(`Variable ${key} does not exist, using POST to create`);\n const result = await this.request<{ uuid: string }>(\n `/applications/${appUuid}/envs`,\n {\n method: \"POST\",\n body: JSON.stringify({\n key,\n value,\n is_buildtime: isBuildTime,\n }),\n },\n );\n\n if (result.error) {\n log.error(`Failed to create env var: ${result.error}`);\n return err(new Error(result.error));\n }\n }\n\n log.success(`Environment variable ${key} set for ${appUuid}`);\n return ok(undefined);\n }\n\n /**\n * Deletes an environment variable from an application.\n *\n * @param appUuid - Application UUID\n * @param key - Variable name to delete\n * @returns Result indicating success or error\n */\n async deleteEnvironmentVariable(\n appUuid: string,\n key: string,\n ): Promise<Result<void, Error>> {\n log.info(`Deleting environment variable ${key} from ${appUuid}`);\n\n // First get all env vars to find the UUID of the one to delete\n const envVarsResult = await this.getEnvironmentVariables(appUuid);\n if (isErr(envVarsResult)) {\n return err(envVarsResult.error);\n }\n\n const envVar = envVarsResult.value.find((ev) => ev.key === key);\n if (!envVar) {\n log.error(`Environment variable ${key} not found`);\n return err(new Error(`Environment variable ${key} not found`));\n }\n\n const result = await this.request(\n `/applications/${appUuid}/envs/${envVar.uuid}`,\n {\n method: \"DELETE\",\n },\n );\n\n if (result.error) {\n log.error(`Failed to delete env var: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environment variable ${key} deleted from ${appUuid}`);\n return ok(undefined);\n }\n\n /**\n * Gets the status of an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with status or error\n */\n async getApplicationStatus(appUuid: string): Promise<Result<string, Error>> {\n const result = await this.request<{ status: string }>(\n `/applications/${appUuid}`,\n );\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data?.status || \"unknown\");\n }\n\n /**\n * Lists available servers in Coolify.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with servers or error\n */\n async listServers(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyServer[], Error>> {\n let endpoint = \"/servers\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyServer[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server details or error\n */\n async getServer(serverUuid: string): Promise<Result<ICoolifyServer, Error>> {\n log.info(`Getting server details for ${serverUuid}`);\n\n const result = await this.request<ICoolifyServer>(`/servers/${serverUuid}`);\n\n if (result.error) {\n log.error(`Failed to get server: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Server details retrieved: ${serverUuid}`);\n return ok(result.data as ICoolifyServer);\n }\n\n /**\n * Lists all GitHub Apps configured in Coolify.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with GitHub Apps list or error\n */\n async listGithubApps(\n page?: number,\n perPage?: number,\n ): Promise<\n Result<\n Array<{ id: number; uuid: string; name: string; is_public: boolean }>,\n Error\n >\n > {\n let endpoint = \"/github-apps\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result =\n await this.request<\n Array<{ id: number; uuid: string; name: string; is_public: boolean }>\n >(endpoint);\n if (result.error) return err(new Error(result.error));\n return ok(result.data || []);\n }\n\n /**\n * Lists all projects.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with projects list or error\n */\n async listProjects(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyProject[], Error>> {\n let endpoint = \"/projects\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyProject[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Creates a new project.\n *\n * @param name - Project name\n * @param description - Optional project description\n * @returns Result with created project or error\n */\n async createProject(\n name: string,\n description?: string,\n ): Promise<Result<ICoolifyProject, Error>> {\n log.info(`Creating project: ${name}`);\n\n const result = await this.request<ICoolifyProject>(\"/projects\", {\n method: \"POST\",\n body: JSON.stringify({ name, description: description || \"\" }),\n });\n\n if (result.error) {\n log.error(`Failed to create project: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Project created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Gets environments for a project.\n *\n * @param projectUuid - Project UUID\n * @returns Result with environments list or error\n */\n async getProjectEnvironments(\n projectUuid: string,\n ): Promise<Result<ICoolifyEnvironment[], Error>> {\n log.info(`Getting environments for project ${projectUuid}`);\n\n const result = await this.request<{ environments: ICoolifyEnvironment[] }>(\n `/projects/${projectUuid}`,\n );\n\n if (result.error) {\n log.error(`Failed to get environments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Environments retrieved for project ${projectUuid}`);\n return ok(result.data?.environments || []);\n }\n\n /**\n * Lists all teams.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with teams list or error\n */\n async listTeams(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyTeam[], Error>> {\n let endpoint = \"/teams\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyTeam[]>(endpoint);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data || []);\n }\n\n /**\n * Gets available destinations for a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with destinations or error\n */\n async getServerDestinations(\n serverUuid: string,\n ): Promise<Result<ICoolifyDestination[], Error>> {\n const result = await this.request<{\n destinations: ICoolifyDestination[];\n }>(`/servers/${serverUuid}`);\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n return ok(result.data?.destinations || []);\n }\n\n /**\n * Lists all applications.\n *\n * @param teamId - Optional team ID to filter by\n * @param projectId - Optional project ID to filter by\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with applications list or error\n */\n async listApplications(\n teamId?: string,\n projectId?: string,\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyApplication[], Error>> {\n log.info(\"Listing applications\");\n\n let endpoint = \"/applications\";\n const params = new URLSearchParams();\n if (teamId) params.set(\"team_id\", teamId);\n if (projectId) params.set(\"project_id\", projectId);\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyApplication[]>(endpoint);\n\n if (result.error) {\n log.error(`Failed to list applications: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Listed ${result.data?.length || 0} applications`);\n return ok(result.data || []);\n }\n\n /**\n * Deletes an application.\n *\n * @param appUuid - Application UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteApplication(\n appUuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/applications/${appUuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n\n if (result.error) {\n log.error(`Failed to delete application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application deleted: ${appUuid}`);\n return ok({ success: true, message: \"Application deleted\" });\n }\n\n /**\n * Updates an application configuration.\n *\n * @param appUuid - Application UUID\n * @param options - Update options\n * @returns Result with updated application or error\n */\n async updateApplication(\n appUuid: string,\n options: ICoolifyUpdateOptions,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Updating application ${appUuid}`);\n\n const body: Record<string, unknown> = {};\n if (options.name) body.name = options.name;\n if (options.description) body.description = options.description;\n if (options.buildPack) body.build_pack = options.buildPack;\n if (options.gitBranch) body.git_branch = options.gitBranch;\n if (options.portsExposes) body.ports_exposes = options.portsExposes;\n if (options.installCommand) body.install_command = options.installCommand;\n if (options.buildCommand) body.build_command = options.buildCommand;\n if (options.startCommand) body.start_command = options.startCommand;\n if (options.dockerfileLocation)\n body.dockerfile_location = options.dockerfileLocation;\n if (options.baseDirectory) body.base_directory = options.baseDirectory;\n if (options.domains) body.domains = options.domains;\n if (options.dockerComposeDomains)\n body.docker_compose_domains = options.dockerComposeDomains;\n if (options.isForceHttpsEnabled !== undefined)\n body.is_force_https_enabled = options.isForceHttpsEnabled;\n if (options.isAutoDeployEnabled !== undefined)\n body.is_auto_deploy_enabled = options.isAutoDeployEnabled;\n if (options.healthCheckEnabled !== undefined)\n body.health_check_enabled = options.healthCheckEnabled;\n if (options.healthCheckPath)\n body.health_check_path = options.healthCheckPath;\n if (options.healthCheckPort)\n body.health_check_port = String(options.healthCheckPort);\n if (options.healthCheckMethod)\n body.health_check_method = options.healthCheckMethod;\n if (options.healthCheckInterval)\n body.health_check_interval = options.healthCheckInterval;\n if (options.healthCheckTimeout)\n body.health_check_timeout = options.healthCheckTimeout;\n if (options.healthCheckRetries)\n body.health_check_retries = options.healthCheckRetries;\n if (options.healthCheckStartPeriod)\n body.health_check_start_period = options.healthCheckStartPeriod;\n if (options.healthCheckReturnCode)\n body.health_check_return_code = options.healthCheckReturnCode;\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(body),\n },\n );\n\n if (result.error) {\n log.error(`Failed to update application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application updated: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Gets application logs.\n *\n * @param appUuid - Application UUID\n * @param options - Log retrieval options\n * @returns Result with logs or error\n */\n async getApplicationLogs(\n appUuid: string,\n options: ICoolifyLogsOptions = {},\n ): Promise<Result<ICoolifyLogs, Error>> {\n log.info(`Getting logs for application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options.follow) params.set(\"follow\", \"true\");\n if (options.tail) params.set(\"lines\", options.tail.toString());\n if (options.serviceName) params.set(\"service_name\", options.serviceName);\n\n const endpoint = `/applications/${appUuid}/logs${params.toString() ? `?${params.toString()}` : \"\"}`;\n\n const result = await this.request<{ logs: string | string[] }>(endpoint);\n\n if (result.error) {\n log.error(`Failed to get logs: ${result.error}`);\n return err(new Error(result.error));\n }\n\n // Coolify API returns logs as a single newline-delimited string for\n // docker-compose apps, but as string[] for single-container apps.\n const rawLogs = result.data?.logs;\n const logsArray: string[] = Array.isArray(rawLogs)\n ? rawLogs\n : typeof rawLogs === \"string\"\n ? rawLogs.split(\"\\n\").filter((l: string) => l.length > 0)\n : [];\n\n log.success(`Logs retrieved for application: ${appUuid}`);\n return ok({\n logs: logsArray,\n timestamp: new Date().toISOString(),\n });\n }\n\n /**\n * Executes a command on an application's running container.\n *\n * @param appUuid - Application UUID\n * @param command - Shell command to execute\n * @returns Result with command output or error\n */\n async executeCommand(\n appUuid: string,\n command: string,\n ): Promise<Result<{ message?: string; response?: string }, Error>> {\n log.info(`Executing command on application ${appUuid}`);\n\n const result = await this.request<{\n message?: string;\n response?: string;\n }>(`/applications/${appUuid}/execute-command`, {\n method: \"POST\",\n body: JSON.stringify({ command }),\n });\n\n if (result.error) {\n log.error(`Failed to execute command: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Command executed on ${appUuid}`);\n return ok(result.data || { message: \"Command executed\" });\n }\n\n /**\n * Bulk updates environment variables for an application.\n *\n * @param appUuid - Application UUID\n * @param envVars - Array of { key, value, is_preview? } objects\n * @returns Result indicating success or error\n */\n async bulkUpdateEnvironmentVariables(\n appUuid: string,\n envVars: Array<{\n key: string;\n value: string;\n is_preview?: boolean;\n }>,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Bulk updating ${envVars.length} env vars for ${appUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/applications/${appUuid}/envs/bulk`,\n {\n method: \"PATCH\",\n body: JSON.stringify(envVars),\n },\n );\n\n if (result.error) {\n log.error(`Failed to bulk update env vars: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Bulk updated ${envVars.length} env vars for ${appUuid}`);\n return ok(result.data || { message: \"Environment variables updated\" });\n }\n\n /**\n * Gets deployment history for an application.\n *\n * @param appUuid - Application UUID\n * @returns Result with deployment history or error\n */\n async getApplicationDeploymentHistory(\n appUuid: string,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Getting deployment history for ${appUuid}`);\n\n // Coolify API: /deployments/applications/{appUuid}\n // Response: { count: number, deployments: ICoolifyDeployment[] }\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(`/deployments/applications/${appUuid}`);\n\n if (result.error) {\n log.error(`Failed to get deployment history: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment history retrieved for ${appUuid}`);\n return ok(result.data?.deployments || []);\n }\n\n /**\n * Starts a stopped application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @param options - Optional start options (force, instant_deploy)\n * @returns Result with application status or error\n */\n async startApplication(\n appUuid: string,\n options?: { force?: boolean; instantDeploy?: boolean },\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Starting application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (options?.force) params.set(\"force\", \"true\");\n if (options?.instantDeploy) params.set(\"instant_deploy\", \"true\");\n const queryString = params.toString();\n const endpoint = `/applications/${appUuid}/start${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyApplication>(endpoint, {\n method: \"GET\",\n });\n\n if (result.error) {\n log.error(`Failed to start application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application started: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Stops a running application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @returns Result with application status or error\n */\n async stopApplication(\n appUuid: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Stopping application ${appUuid}`);\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}/stop`,\n { method: \"GET\" },\n );\n\n if (result.error) {\n log.error(`Failed to stop application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application stopped: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n /**\n * Restarts an application.\n * Note: Coolify API uses GET for application start/stop/restart.\n *\n * @param appUuid - Application UUID\n * @returns Result with application status or error\n */\n async restartApplication(\n appUuid: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Restarting application ${appUuid}`);\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}/restart`,\n { method: \"GET\" },\n );\n\n if (result.error) {\n log.error(`Failed to restart application: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Application restarted: ${appUuid}`);\n return ok(result.data as ICoolifyApplication);\n }\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n\n /**\n * Gets the Coolify server version.\n *\n * @returns Result with version info or error\n */\n async getVersion(): Promise<Result<ICoolifyVersion, Error>> {\n log.info(\"Getting Coolify version\");\n\n // /version returns plain text, not JSON\n if (!this.baseUrl || !this.token) {\n return err(new Error(\"Coolify not configured\"));\n }\n\n try {\n const baseUrl = this.baseUrl.replace(/\\/+$/, \"\");\n const url = `${baseUrl}/api/v1/version`;\n const response = await fetch(url, {\n headers: {\n Authorization: `Bearer ${this.token}`,\n },\n });\n\n if (!response.ok) {\n return err(\n new Error(`HTTP ${response.status}: ${response.statusText}`),\n );\n }\n\n const version = (await response.text()).trim();\n log.success(`Coolify version: ${version}`);\n return ok({ version });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return err(new Error(message));\n }\n }\n\n // ===========================================================================\n // Database endpoints\n // ===========================================================================\n\n /**\n * Lists all databases.\n *\n * @param page - Optional page number\n * @param perPage - Optional items per page\n * @returns Result with databases list or error\n */\n async listDatabases(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyDatabase[], Error>> {\n log.info(\"Listing databases\");\n\n let endpoint = \"/databases\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) endpoint += `?${params.toString()}`;\n\n const result = await this.request<ICoolifyDatabase[]>(endpoint);\n if (result.error) return err(new Error(result.error));\n\n log.success(`Listed ${result.data?.length || 0} databases`);\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific database.\n *\n * @param uuid - Database UUID\n * @returns Result with database details or error\n */\n async getDatabase(uuid: string): Promise<Result<ICoolifyDatabase, Error>> {\n log.info(`Getting database ${uuid}`);\n\n const result = await this.request<ICoolifyDatabase>(`/databases/${uuid}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyDatabase);\n }\n\n /**\n * Creates a database of the specified type.\n *\n * @param dbType - Database type (postgresql, mysql, mariadb, mongodb, redis, keydb, clickhouse, dragonfly)\n * @param data - Database creation data\n * @returns Result with created database UUID or error\n */\n async createDatabase(\n dbType: string,\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(`Creating ${dbType} database`);\n\n const result = await this.request<{ uuid: string }>(\n `/databases/${dbType}`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a database configuration.\n *\n * @param uuid - Database UUID\n * @param data - Update data\n * @returns Result with updated database or error\n */\n async updateDatabase(\n uuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyDatabase, Error>> {\n log.info(`Updating database ${uuid}`);\n\n const result = await this.request<ICoolifyDatabase>(`/databases/${uuid}`, {\n method: \"PATCH\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database updated: ${uuid}`);\n return ok(result.data as ICoolifyDatabase);\n }\n\n /**\n * Deletes a database.\n *\n * @param uuid - Database UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteDatabase(\n uuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting database ${uuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/databases/${uuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database deleted: ${uuid}`);\n return ok({ success: true, message: \"Database deleted\" });\n }\n\n /**\n * Starts a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async startDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Starting database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/start`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database started: ${uuid}`);\n return ok(result.data || { message: \"Database started\" });\n }\n\n /**\n * Stops a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async stopDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Stopping database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/stop`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database stopped: ${uuid}`);\n return ok(result.data || { message: \"Database stopped\" });\n }\n\n /**\n * Restarts a database.\n *\n * @param uuid - Database UUID\n * @returns Result indicating success or error\n */\n async restartDatabase(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Restarting database ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/databases/${uuid}/restart`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Database restarted: ${uuid}`);\n return ok(result.data || { message: \"Database restarted\" });\n }\n\n // ===========================================================================\n // Database Backup endpoints\n // ===========================================================================\n\n /**\n * Lists backups for a database.\n *\n * @param databaseUuid - Database UUID\n * @returns Result with backups list or error\n */\n async listDatabaseBackups(\n databaseUuid: string,\n ): Promise<Result<ICoolifyDatabaseBackup[], Error>> {\n log.info(`Listing backups for database ${databaseUuid}`);\n\n const result = await this.request<ICoolifyDatabaseBackup[]>(\n `/databases/${databaseUuid}/backups`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets a specific database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @returns Result with backup details or error\n */\n async getDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n ): Promise<Result<ICoolifyDatabaseBackup, Error>> {\n const result = await this.request<ICoolifyDatabaseBackup>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyDatabaseBackup);\n }\n\n /**\n * Creates a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param data - Backup creation data\n * @returns Result with created backup or error\n */\n async createDatabaseBackup(\n databaseUuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyDatabaseBackup, Error>> {\n log.info(`Creating backup for database ${databaseUuid}`);\n\n const result = await this.request<ICoolifyDatabaseBackup>(\n `/databases/${databaseUuid}/backups`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(\"Database backup created\");\n return ok(result.data as ICoolifyDatabaseBackup);\n }\n\n /**\n * Updates a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @param data - Update data\n * @returns Result indicating success or error\n */\n async updateDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Backup updated\" });\n }\n\n /**\n * Deletes a database backup.\n *\n * @param databaseUuid - Database UUID\n * @param backupUuid - Backup UUID\n * @returns Result indicating success or error\n */\n async deleteDatabaseBackup(\n databaseUuid: string,\n backupUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/databases/${databaseUuid}/backups/${backupUuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Backup deleted\" });\n }\n\n // ===========================================================================\n // Service endpoints\n // ===========================================================================\n\n /**\n * Lists all services.\n *\n * @param page - Optional page number\n * @param perPage - Optional items per page\n * @returns Result with services list or error\n */\n async listServices(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyServiceType[], Error>> {\n log.info(\"Listing services\");\n\n let endpoint = \"/services\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) endpoint += `?${params.toString()}`;\n\n const result = await this.request<ICoolifyServiceType[]>(endpoint);\n if (result.error) return err(new Error(result.error));\n\n log.success(`Listed ${result.data?.length || 0} services`);\n return ok(result.data || []);\n }\n\n /**\n * Gets details of a specific service.\n *\n * @param uuid - Service UUID\n * @returns Result with service details or error\n */\n async getService(uuid: string): Promise<Result<ICoolifyServiceType, Error>> {\n log.info(`Getting service ${uuid}`);\n\n const result = await this.request<ICoolifyServiceType>(`/services/${uuid}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyServiceType);\n }\n\n /**\n * Creates a new service.\n *\n * @param data - Service creation data\n * @returns Result with created service or error\n */\n async createService(\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating service\");\n\n const result = await this.request<{ uuid: string }>(\"/services\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a service configuration.\n *\n * @param uuid - Service UUID\n * @param data - Update data\n * @returns Result with updated service or error\n */\n async updateService(\n uuid: string,\n data: Record<string, unknown>,\n ): Promise<Result<ICoolifyServiceType, Error>> {\n log.info(`Updating service ${uuid}`);\n\n const result = await this.request<ICoolifyServiceType>(\n `/services/${uuid}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(data),\n },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service updated: ${uuid}`);\n return ok(result.data as ICoolifyServiceType);\n }\n\n /**\n * Deletes a service.\n *\n * @param uuid - Service UUID\n * @param options - Delete options for cascade deletion\n * @returns Result indicating success or error\n */\n async deleteService(\n uuid: string,\n options?: {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n },\n ): Promise<Result<ICoolifyDeleteResult, Error>> {\n log.info(`Deleting service ${uuid}`);\n\n const params = new URLSearchParams();\n if (options?.deleteConfigurations)\n params.set(\"delete_configurations\", \"true\");\n if (options?.deleteVolumes) params.set(\"delete_volumes\", \"true\");\n if (options?.dockerCleanup) params.set(\"docker_cleanup\", \"true\");\n if (options?.deleteConnectedNetworks)\n params.set(\"delete_connected_networks\", \"true\");\n\n const queryString = params.toString();\n const endpoint = `/services/${uuid}${queryString ? `?${queryString}` : \"\"}`;\n\n const result = await this.request<ICoolifyDeleteResult>(endpoint, {\n method: \"DELETE\",\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service deleted: ${uuid}`);\n return ok({ success: true, message: \"Service deleted\" });\n }\n\n /**\n * Gets the full infrastructure tree: Projects → Environments → Resources.\n *\n * Fetches all projects, apps, databases, and services in parallel,\n * then groups them by environment_id into a hierarchical tree.\n *\n * @returns Result with the full infrastructure tree or error\n */\n async getInfrastructureTree(): Promise<\n Result<ICoolifyInfrastructureTree, Error>\n > {\n log.info(\"Building infrastructure tree\");\n\n // Fetch all data in parallel\n const [projectsResult, appsResult, dbsResult, svcsResult, serversResult] =\n await Promise.all([\n this.listProjects(),\n this.listApplications(),\n this.listDatabases(),\n this.listServices(),\n this.listServers(),\n ]);\n\n if (isErr(projectsResult)) return err(projectsResult.error);\n if (isErr(appsResult)) return err(appsResult.error);\n if (isErr(serversResult)) return err(serversResult.error);\n\n const projects = projectsResult.value;\n const apps = appsResult.value;\n const dbs = isErr(dbsResult) ? [] : dbsResult.value;\n const svcs = isErr(svcsResult) ? [] : svcsResult.value;\n const servers = serversResult.value;\n\n // Fetch environments for each project in parallel\n const envResults = await Promise.allSettled(\n projects.map((p) => this.getProjectEnvironments(p.uuid)),\n );\n\n // Build environment_id → { projectUuid, envName, envUuid } mapping\n const envIdMap = new Map<\n number,\n { projectUuid: string; envName: string; envUuid: string }\n >();\n\n for (let i = 0; i < projects.length; i++) {\n const envResult = envResults[i];\n if (envResult.status === \"fulfilled\" && !isErr(envResult.value)) {\n for (const env of envResult.value.value) {\n envIdMap.set(env.id, {\n projectUuid: projects[i].uuid,\n envName: env.name,\n envUuid: env.uuid,\n });\n }\n }\n }\n\n // Build project nodes\n const projectNodes: ICoolifyProjectNode[] = projects.map((p) => ({\n uuid: p.uuid,\n name: p.name,\n description: p.description,\n environments: [],\n }));\n\n const projectMap = new Map<string, ICoolifyProjectNode>();\n for (const node of projectNodes) {\n projectMap.set(node.uuid, node);\n }\n\n // Populate environments from envIdMap\n const envNodeMap = new Map<number, ICoolifyEnvironmentNode>();\n for (const [envId, info] of envIdMap) {\n const project = projectMap.get(info.projectUuid);\n if (!project) continue;\n\n let envNode = project.environments.find((e) => e.id === envId);\n if (!envNode) {\n envNode = {\n id: envId,\n uuid: info.envUuid,\n name: info.envName,\n resources: [],\n };\n project.environments.push(envNode);\n }\n envNodeMap.set(envId, envNode);\n }\n\n // Assign apps to environments\n for (const app of apps) {\n const envNode = app.environment_id\n ? envNodeMap.get(app.environment_id)\n : undefined;\n const resource: ICoolifyResource = {\n uuid: app.uuid,\n name: app.name,\n kind: \"app\",\n status: app.status,\n fqdn: app.fqdn,\n };\n if (envNode) {\n envNode.resources.push(resource);\n }\n }\n\n // Assign databases to environments\n for (const db of dbs) {\n const envNode = (db as any).environment_id\n ? envNodeMap.get((db as any).environment_id)\n : undefined;\n const resource: ICoolifyResource = {\n uuid: db.uuid,\n name: db.name,\n kind: \"database\",\n status: db.status,\n dbType: db.type,\n };\n if (envNode) {\n envNode.resources.push(resource);\n }\n }\n\n // Assign services to environments\n for (const svc of svcs) {\n const envNode = (svc as any).environment_id\n ? envNodeMap.get((svc as any).environment_id)\n : undefined;\n const resource: ICoolifyResource = {\n uuid: svc.uuid,\n name: svc.name,\n kind: \"service\",\n status: svc.status,\n };\n if (envNode) {\n envNode.resources.push(resource);\n }\n }\n\n // Filter out empty projects\n const populatedProjects = projectNodes.filter(\n (p) => p.environments.some((e) => e.resources.length > 0),\n );\n\n // Aggregate counts\n const allStatuses = [\n ...apps.map((a) => a.status),\n ...dbs.map((d) => d.status),\n ...svcs.map((s) => s.status),\n ];\n const counts = {\n projects: populatedProjects.length,\n apps: apps.length,\n databases: dbs.length,\n services: svcs.length,\n healthy: allStatuses.filter((s) => s.includes(\"healthy\")).length,\n running: allStatuses.filter(\n (s) => s.startsWith(\"running\") && !s.includes(\"healthy\"),\n ).length,\n stopped: allStatuses.filter((s) => s.includes(\"exited\")).length,\n unhealthy: allStatuses.filter((s) => s.includes(\"unhealthy\")).length,\n };\n\n const server = servers[0] || { name: \"Unknown\" };\n\n log.success(\n `Infrastructure tree built: ${counts.projects} projects, ${counts.apps} apps, ${counts.databases} dbs, ${counts.services} svcs`,\n );\n\n return ok({\n server: {\n name: server.name,\n ip: server.ip,\n uuid: server.uuid,\n },\n projects: populatedProjects,\n counts,\n });\n }\n\n /**\n * Starts a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async startService(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Starting service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/start`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service started: ${uuid}`);\n return ok(result.data || { message: \"Service started\" });\n }\n\n /**\n * Stops a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async stopService(uuid: string): Promise<Result<{ message: string }, Error>> {\n log.info(`Stopping service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/stop`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service stopped: ${uuid}`);\n return ok(result.data || { message: \"Service stopped\" });\n }\n\n /**\n * Restarts a service.\n * Note: Coolify API uses GET for service start/stop/restart.\n *\n * @param uuid - Service UUID\n * @returns Result indicating success or error\n */\n async restartService(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Restarting service ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/services/${uuid}/restart`,\n { method: \"GET\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Service restarted: ${uuid}`);\n return ok(result.data || { message: \"Service restarted\" });\n }\n\n /**\n * Lists environment variables for a service.\n *\n * @param uuid - Service UUID\n * @returns Result with env vars list or error\n */\n async listServiceEnvVars(\n uuid: string,\n ): Promise<Result<ICoolifyEnvVar[], Error>> {\n const result = await this.request<ICoolifyEnvVar[]>(\n `/services/${uuid}/envs`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Creates an environment variable for a service.\n *\n * @param uuid - Service UUID\n * @param data - Env var data (key, value, is_preview)\n * @returns Result with created env var UUID or error\n */\n async createServiceEnvVar(\n uuid: string,\n data: { key: string; value: string; is_preview?: boolean },\n ): Promise<Result<{ uuid: string }, Error>> {\n const result = await this.request<{ uuid: string }>(\n `/services/${uuid}/envs`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data!);\n }\n\n // ===========================================================================\n // Additional Server endpoints\n // ===========================================================================\n\n /**\n * Gets resources deployed on a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server resources or error\n */\n async getServerResources(\n serverUuid: string,\n ): Promise<Result<ICoolifyServerResource[], Error>> {\n log.info(`Getting resources for server ${serverUuid}`);\n\n const result = await this.request<ICoolifyServerResource[]>(\n `/servers/${serverUuid}/resources`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets domains configured on a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result with server domains or error\n */\n async getServerDomains(\n serverUuid: string,\n ): Promise<Result<ICoolifyServerDomain[], Error>> {\n log.info(`Getting domains for server ${serverUuid}`);\n\n const result = await this.request<ICoolifyServerDomain[]>(\n `/servers/${serverUuid}/domains`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Validates a server connection.\n *\n * @param serverUuid - Server UUID\n * @returns Result with validation status or error\n */\n async validateServer(\n serverUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Validating server ${serverUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/servers/${serverUuid}/validate`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"Server validated\" });\n }\n\n /**\n * Creates a new server.\n *\n * @param data - Server creation data\n * @returns Result with created server UUID or error\n */\n async createServer(\n data: Record<string, unknown>,\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating server\");\n\n const result = await this.request<{ uuid: string }>(\"/servers\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Server created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Deletes a server.\n *\n * @param serverUuid - Server UUID\n * @returns Result indicating success or error\n */\n async deleteServer(\n serverUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting server ${serverUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/servers/${serverUuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Server deleted: ${serverUuid}`);\n return ok(result.data || { message: \"Server deleted\" });\n }\n\n // ===========================================================================\n // Additional Project endpoints\n // ===========================================================================\n\n /**\n * Updates a project.\n *\n * @param uuid - Project UUID\n * @param data - Update data (name, description)\n * @returns Result with updated project or error\n */\n async updateProject(\n uuid: string,\n data: { name?: string; description?: string },\n ): Promise<Result<ICoolifyProject, Error>> {\n log.info(`Updating project ${uuid}`);\n\n const result = await this.request<ICoolifyProject>(`/projects/${uuid}`, {\n method: \"PATCH\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Project updated: ${uuid}`);\n return ok(result.data as ICoolifyProject);\n }\n\n /**\n * Deletes a project.\n *\n * @param uuid - Project UUID\n * @returns Result indicating success or error\n */\n async deleteProject(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting project ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/projects/${uuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Project deleted: ${uuid}`);\n return ok(result.data || { message: \"Project deleted\" });\n }\n\n /**\n * Creates a new environment within a project.\n *\n * @param projectUuid - Project UUID\n * @param data - Environment creation data (name, description)\n * @returns Result with created environment UUID or error\n */\n async createProjectEnvironment(\n projectUuid: string,\n data: { name: string; description?: string },\n ): Promise<Result<{ uuid: string }, Error>> {\n log.info(`Creating environment in project ${projectUuid}`);\n\n const result = await this.request<{ uuid: string }>(\n `/projects/${projectUuid}/environments`,\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(\"Environment created\");\n return ok(result.data!);\n }\n\n // ===========================================================================\n // Additional Team endpoints\n // ===========================================================================\n\n /**\n * Gets the current team.\n *\n * @returns Result with current team or error\n */\n async getCurrentTeam(): Promise<Result<ICoolifyTeam, Error>> {\n log.info(\"Getting current team\");\n\n const result = await this.request<ICoolifyTeam>(\"/teams/current\");\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyTeam);\n }\n\n /**\n * Gets a specific team by ID.\n *\n * @param id - Team ID\n * @returns Result with team details or error\n */\n async getTeam(id: number): Promise<Result<ICoolifyTeam, Error>> {\n log.info(`Getting team ${id}`);\n\n const result = await this.request<ICoolifyTeam>(`/teams/${id}`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyTeam);\n }\n\n /**\n * Gets members of a specific team.\n *\n * @param id - Team ID\n * @returns Result with team members or error\n */\n async getTeamMembers(\n id: number,\n ): Promise<\n Result<Array<{ id: number; name: string; email: string }>, Error>\n > {\n log.info(`Getting members for team ${id}`);\n\n const result = await this.request<\n Array<{ id: number; name: string; email: string }>\n >(`/teams/${id}/members`);\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n // ===========================================================================\n // Deployment Control\n // ===========================================================================\n\n /**\n * Cancels a deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result indicating success or error\n */\n async cancelDeployment(\n deploymentUuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Cancelling deployment ${deploymentUuid}`);\n\n const result = await this.request<{ message: string }>(\n `/deployments/${deploymentUuid}/cancel`,\n { method: \"POST\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Deployment cancelled: ${deploymentUuid}`);\n return ok(result.data || { message: \"Deployment cancelled\" });\n }\n\n // ===========================================================================\n // SSH / Private Key endpoints\n // ===========================================================================\n\n /**\n * Lists all private keys.\n *\n * @returns Result with private keys list or error\n */\n async listPrivateKeys(): Promise<Result<ICoolifyPrivateKey[], Error>> {\n log.info(\"Listing private keys\");\n\n const result = await this.request<ICoolifyPrivateKey[]>(\"/security/keys\");\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || []);\n }\n\n /**\n * Gets a specific private key.\n *\n * @param uuid - Private key UUID\n * @returns Result with private key details or error\n */\n async getPrivateKey(\n uuid: string,\n ): Promise<Result<ICoolifyPrivateKey, Error>> {\n const result = await this.request<ICoolifyPrivateKey>(\n `/security/keys/${uuid}`,\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyPrivateKey);\n }\n\n /**\n * Creates a new private key.\n *\n * @param data - Key creation data (name, private_key, description)\n * @returns Result with created key UUID or error\n */\n async createPrivateKey(data: {\n name: string;\n private_key: string;\n description?: string;\n }): Promise<Result<{ uuid: string }, Error>> {\n log.info(\"Creating private key\");\n\n const result = await this.request<{ uuid: string }>(\"/security/keys\", {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n if (result.error) return err(new Error(result.error));\n\n log.success(`Private key created: ${result.data?.uuid}`);\n return ok(result.data!);\n }\n\n /**\n * Updates a private key.\n *\n * @param uuid - Private key UUID\n * @param data - Update data\n * @returns Result with updated key or error\n */\n async updatePrivateKey(\n uuid: string,\n data: { name?: string; private_key?: string; description?: string },\n ): Promise<Result<ICoolifyPrivateKey, Error>> {\n const result = await this.request<ICoolifyPrivateKey>(\n `/security/keys/${uuid}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data as ICoolifyPrivateKey);\n }\n\n /**\n * Deletes a private key.\n *\n * @param uuid - Private key UUID\n * @returns Result indicating success or error\n */\n async deletePrivateKey(\n uuid: string,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting private key ${uuid}`);\n\n const result = await this.request<{ message: string }>(\n `/security/keys/${uuid}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n log.success(`Private key deleted: ${uuid}`);\n return ok(result.data || { message: \"Private key deleted\" });\n }\n\n // ===========================================================================\n // GitHub App endpoints (additional)\n // ===========================================================================\n\n /**\n * Creates a GitHub App configuration.\n *\n * @param data - GitHub App creation data\n * @returns Result with created app or error\n */\n async createGitHubApp(\n data: Record<string, unknown>,\n ): Promise<Result<{ id: number; uuid: string }, Error>> {\n log.info(\"Creating GitHub App\");\n\n const result = await this.request<{ id: number; uuid: string }>(\n \"/github-apps\",\n { method: \"POST\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data!);\n }\n\n /**\n * Updates a GitHub App configuration.\n *\n * @param id - GitHub App ID\n * @param data - Update data\n * @returns Result with updated app or error\n */\n async updateGitHubApp(\n id: number,\n data: Record<string, unknown>,\n ): Promise<Result<{ message: string }, Error>> {\n const result = await this.request<{ message: string }>(\n `/github-apps/${id}`,\n { method: \"PATCH\", body: JSON.stringify(data) },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"GitHub App updated\" });\n }\n\n /**\n * Deletes a GitHub App configuration.\n *\n * @param id - GitHub App ID\n * @returns Result indicating success or error\n */\n async deleteGitHubApp(\n id: number,\n ): Promise<Result<{ message: string }, Error>> {\n log.info(`Deleting GitHub App ${id}`);\n\n const result = await this.request<{ message: string }>(\n `/github-apps/${id}`,\n { method: \"DELETE\" },\n );\n if (result.error) return err(new Error(result.error));\n\n return ok(result.data || { message: \"GitHub App deleted\" });\n }\n\n /**\n * Lists all active and queued deployments.\n *\n * @param page - Optional page number for pagination\n * @param perPage - Optional number of items per page\n * @returns Result with deployments list or error\n */\n async listDeployments(\n page?: number,\n perPage?: number,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(\"Listing active deployments\");\n\n let endpoint = \"/deployments\";\n const params = new URLSearchParams();\n if (page) params.set(\"page\", page.toString());\n if (perPage) params.set(\"per_page\", perPage.toString());\n if (params.toString()) {\n endpoint += `?${params.toString()}`;\n }\n\n const result = await this.request<ICoolifyDeployment[]>(endpoint);\n\n if (result.error) {\n log.error(`Failed to list deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Listed ${result.data?.length || 0} active deployments`);\n return ok(result.data || []);\n }\n\n /**\n * Gets detailed information about a specific deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result with deployment details or error\n */\n async getDeployment(\n deploymentUuid: string,\n ): Promise<Result<ICoolifyDeployment, Error>> {\n log.info(`Getting deployment details for ${deploymentUuid}`);\n\n const result = await this.request<ICoolifyDeployment>(\n `/deployments/${deploymentUuid}`,\n );\n\n if (result.error) {\n log.error(`Failed to get deployment: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment details retrieved: ${deploymentUuid}`);\n return ok(result.data as ICoolifyDeployment);\n }\n\n /**\n * Gets logs for a specific deployment.\n *\n * @param deploymentUuid - Deployment UUID\n * @returns Result with deployment status and logs or error\n */\n async getDeploymentLogs(\n deploymentUuid: string,\n ): Promise<\n Result<{ status: string; logs: string; deployment_uuid: string }, Error>\n > {\n log.info(`Getting deployment logs for ${deploymentUuid}`);\n\n const result = await this.request<{\n status: string;\n logs: string;\n deployment_uuid: string;\n }>(`/deployments/${deploymentUuid}`);\n\n if (result.error) {\n log.error(`Failed to get deployment logs: ${result.error}`);\n return err(new Error(result.error));\n }\n\n log.success(`Deployment logs retrieved: ${deploymentUuid}`);\n return ok({\n status: result.data?.status || \"unknown\",\n logs: result.data?.logs || \"\",\n deployment_uuid: result.data?.deployment_uuid || deploymentUuid,\n });\n }\n\n /**\n * Gets deployment history for a specific application.\n *\n * @param appUuid - Application UUID\n * @param skip - Number of deployments to skip\n * @param take - Number of deployments to return\n * @returns Result with deployments list or error\n */\n async getApplicationDeployments(\n appUuid: string,\n skip: number = 0,\n take: number = 10,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Getting deployments for application ${appUuid}`);\n\n const params = new URLSearchParams();\n if (skip > 0) params.set(\"skip\", skip.toString());\n if (take !== 10) params.set(\"take\", take.toString());\n\n const endpoint = `/applications/${appUuid}/deployments${params.toString() ? `?${params.toString()}` : \"\"}`;\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(endpoint);\n\n if (result.error) {\n log.error(`Failed to get application deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n const deployments = result.data?.deployments || [];\n log.success(`Retrieved ${deployments.length} deployments for ${appUuid}`);\n return ok(deployments);\n }\n\n /**\n * Lists deployments for a specific application.\n *\n * Uses the /deployments/applications/{appUuid} endpoint which returns\n * all deployments (active, queued, and completed) for a single application.\n * This differs from listDeployments() which returns ALL deployments globally.\n *\n * @param appUuid - Application UUID\n * @returns Result with deployments list or error\n */\n async listApplicationDeployments(\n appUuid: string,\n ): Promise<Result<ICoolifyDeployment[], Error>> {\n log.info(`Listing deployments for application ${appUuid}`);\n\n // API returns { count: number, deployments: ICoolifyDeployment[] }\n const result = await this.request<{\n count: number;\n deployments: ICoolifyDeployment[];\n }>(`/deployments/applications/${appUuid}`);\n\n if (result.error) {\n log.error(`Failed to list application deployments: ${result.error}`);\n return err(new Error(result.error));\n }\n\n const deployments = result.data?.deployments || [];\n log.success(`Listed ${deployments.length} deployments for ${appUuid}`);\n return ok(deployments);\n }\n\n // ===========================================================================\n // Smart Resolution Helpers\n // ===========================================================================\n\n /**\n * Gets full application details by UUID.\n *\n * Makes a direct GET request to /api/v1/applications/{uuid} which returns\n * complete application data including project_uuid and environment_uuid.\n *\n * @param appUuid - Application UUID\n * @returns Result with full application details or error\n */\n async getApplication(\n appUuid: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Getting application details: ${appUuid}`);\n\n const result = await this.request<ICoolifyApplication>(\n `/applications/${appUuid}`,\n );\n\n if (result.error) {\n return err(new Error(result.error));\n }\n\n if (!result.data) {\n return err(new Error(\"Application not found\"));\n }\n\n return ok(result.data);\n }\n\n /**\n * Resolves an application by UUID, name, or domain (FQDN).\n *\n * @param query - UUID, name, or domain to search for\n * @returns Result with application or error\n */\n async resolveApplication(\n query: string,\n ): Promise<Result<ICoolifyApplication, Error>> {\n log.info(`Resolving application: ${query}`);\n\n // If it looks like a UUID, try direct lookup first\n if (this.isLikelyUuid(query)) {\n const apps = await this.listApplications();\n if (isErr(apps)) return err(apps.error);\n const match = apps.value.find((a) => a.uuid === query);\n if (match) return ok(match);\n }\n\n // Search by name or domain\n const apps = await this.listApplications();\n if (isErr(apps)) return err(apps.error);\n\n const lowerQuery = query.toLowerCase();\n const matches = apps.value.filter(\n (a) =>\n a.name?.toLowerCase() === lowerQuery ||\n a.fqdn?.toLowerCase().includes(lowerQuery) ||\n a.uuid.startsWith(query),\n );\n\n if (matches.length === 1) return ok(matches[0]);\n if (matches.length === 0) {\n return err(\n new Error(\n `No application found matching \"${query}\". Use 'list' to see available applications.`,\n ),\n );\n }\n\n const names = matches.map((a) => ` - ${a.name} (${a.uuid})`).join(\"\\n\");\n return err(\n new Error(\n `Multiple applications match \"${query}\":\\n${names}\\nPlease use the full UUID.`,\n ),\n );\n }\n\n /**\n * Resolves a server by UUID, name, or IP address.\n *\n * @param query - UUID, name, or IP to search for\n * @returns Result with server or error\n */\n async resolveServer(query: string): Promise<Result<ICoolifyServer, Error>> {\n log.info(`Resolving server: ${query}`);\n\n const servers = await this.listServers();\n if (isErr(servers)) return err(servers.error);\n\n const lowerQuery = query.toLowerCase();\n const match = servers.value.find(\n (s) =>\n s.uuid === query ||\n s.name?.toLowerCase() === lowerQuery ||\n s.ip === query ||\n s.uuid.startsWith(query),\n );\n\n if (match) return ok(match);\n return err(\n new Error(\n `No server found matching \"${query}\". Use 'servers' to see available servers.`,\n ),\n );\n }\n\n /**\n * Checks if a string looks like a UUID (Coolify or standard format).\n *\n * @param query - String to check\n * @returns true if it looks like a UUID\n */\n private isLikelyUuid(query: string): boolean {\n if (/^[a-z0-9]{20,}$/i.test(query)) return true;\n if (\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(\n query,\n )\n )\n return true;\n return false;\n }\n\n // ===========================================================================\n // Diagnostics\n // ===========================================================================\n\n /**\n * Diagnoses an application by aggregating health, logs, deployments, and env vars.\n *\n * @param query - Application UUID, name, or domain\n * @returns Result with diagnostic report or error\n */\n async diagnoseApplication(query: string): Promise<\n Result<\n {\n application: ICoolifyApplication;\n recentDeployments: ICoolifyDeployment[];\n envVarCount: number;\n recentLogs: string[];\n issues: string[];\n },\n Error\n >\n > {\n log.info(`Diagnosing application: ${query}`);\n\n const appResult = await this.resolveApplication(query);\n if (isErr(appResult)) return err(appResult.error);\n\n const app = appResult.value;\n const issues: string[] = [];\n\n // Gather data in parallel\n const [deploymentsResult, envResult, logsResult] = await Promise.all([\n this.getApplicationDeploymentHistory(app.uuid),\n this.getEnvironmentVariables(app.uuid),\n this.getApplicationLogs(app.uuid, { tail: 20 }),\n ]);\n\n const deployments = isErr(deploymentsResult) ? [] : deploymentsResult.value;\n const envVarCount = isErr(envResult) ? 0 : envResult.value.length;\n const recentLogs = isErr(logsResult) ? [] : logsResult.value.logs;\n\n // Check for issues\n if (app.status?.includes(\"stopped\")) {\n issues.push(\"Application is stopped\");\n }\n if (!app.fqdn) {\n issues.push(\"No domain configured\");\n }\n if (envVarCount === 0) {\n issues.push(\"No environment variables set\");\n }\n\n const recentDeploys = deployments.slice(-5);\n const failedDeploys = recentDeploys.filter((d) =>\n d.status?.includes(\"failed\"),\n );\n if (failedDeploys.length > 0) {\n issues.push(\n `${failedDeploys.length} of last ${recentDeploys.length} deployments failed`,\n );\n }\n\n log.success(`Diagnosis complete for ${app.name}`);\n return ok({\n application: app,\n recentDeployments: recentDeploys,\n envVarCount,\n recentLogs,\n issues,\n });\n }\n\n /**\n * Diagnoses a server by aggregating health, resources, and domains.\n *\n * @param query - Server UUID, name, or IP\n * @returns Result with diagnostic report or error\n */\n async diagnoseServer(query: string): Promise<\n Result<\n {\n server: ICoolifyServer;\n resources: ICoolifyServerResource[];\n domains: ICoolifyServerDomain[];\n issues: string[];\n },\n Error\n >\n > {\n log.info(`Diagnosing server: ${query}`);\n\n const serverResult = await this.resolveServer(query);\n if (isErr(serverResult)) return err(serverResult.error);\n\n const server = serverResult.value;\n const issues: string[] = [];\n\n const [resourcesResult, domainsResult] = await Promise.all([\n this.getServerResources(server.uuid),\n this.getServerDomains(server.uuid),\n ]);\n\n const resources = isErr(resourcesResult) ? [] : resourcesResult.value;\n const domains = isErr(domainsResult) ? [] : domainsResult.value;\n\n if (!server.is_reachable) {\n issues.push(\"Server is not reachable\");\n }\n if (!server.is_usable) {\n issues.push(\"Server is not usable\");\n }\n if (resources.length === 0) {\n issues.push(\"No resources deployed on this server\");\n }\n\n log.success(`Server diagnosis complete for ${server.name}`);\n return ok({ server, resources, domains, issues });\n }\n\n /**\n * Scans all infrastructure for potential issues.\n *\n * @returns Result with issues report or error\n */\n async findInfrastructureIssues(): Promise<\n Result<\n {\n totalServers: number;\n totalApps: number;\n totalDatabases: number;\n totalServices: number;\n issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }>;\n },\n Error\n >\n > {\n log.info(\"Scanning infrastructure for issues\");\n\n const [serversR, appsR, dbsR, svcsR] = await Promise.all([\n this.listServers(),\n this.listApplications(),\n this.listDatabases(),\n this.listServices(),\n ]);\n\n const servers = isErr(serversR) ? [] : serversR.value;\n const apps = isErr(appsR) ? [] : appsR.value;\n const dbs = isErr(dbsR) ? [] : dbsR.value;\n const svcs = isErr(svcsR) ? [] : svcsR.value;\n\n const issues: Array<{\n type: string;\n resource: string;\n uuid: string;\n message: string;\n }> = [];\n\n for (const server of servers) {\n if (!server.is_reachable) {\n issues.push({\n type: \"server\",\n resource: server.name,\n uuid: server.uuid,\n message: \"Server unreachable\",\n });\n }\n }\n\n for (const app of apps) {\n if (app.status?.includes(\"stopped\")) {\n issues.push({\n type: \"application\",\n resource: app.name,\n uuid: app.uuid,\n message: \"Application stopped\",\n });\n }\n if (app.status?.includes(\"failed\") || app.status?.includes(\"error\")) {\n issues.push({\n type: \"application\",\n resource: app.name,\n uuid: app.uuid,\n message: `Status: ${app.status}`,\n });\n }\n }\n\n for (const db of dbs) {\n if (db.status?.includes(\"stopped\") || db.status?.includes(\"exited\")) {\n issues.push({\n type: \"database\",\n resource: db.name,\n uuid: db.uuid,\n message: `Database stopped: ${db.status}`,\n });\n }\n }\n\n for (const svc of svcs) {\n if (svc.status?.includes(\"stopped\") || svc.status?.includes(\"exited\")) {\n issues.push({\n type: \"service\",\n resource: svc.name,\n uuid: svc.uuid,\n message: `Service stopped: ${svc.status}`,\n });\n }\n }\n\n log.success(\n `Infrastructure scan complete: ${issues.length} issue(s) found`,\n );\n return ok({\n totalServers: servers.length,\n totalApps: apps.length,\n totalDatabases: dbs.length,\n totalServices: svcs.length,\n issues,\n });\n }\n\n // ===========================================================================\n // Batch Operations\n // ===========================================================================\n\n /**\n * Restarts all applications in a project.\n *\n * @param projectUuid - Project UUID\n * @returns Result with batch operation results\n */\n async restartProjectApps(\n projectUuid: string,\n ): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(`Restarting all apps in project ${projectUuid}`);\n\n const appsResult = await this.listApplications(undefined, projectUuid);\n if (isErr(appsResult)) return err(appsResult.error);\n\n const apps = appsResult.value;\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of apps) {\n const result = await this.restartApplication(app.uuid);\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Restarted ${succeeded}/${apps.length} apps in project`);\n return ok({ total: apps.length, succeeded, failed });\n }\n\n /**\n * Redeploys all applications in a project.\n *\n * @param projectUuid - Project UUID\n * @param force - Force rebuild\n * @returns Result with batch operation results\n */\n async redeployProjectApps(\n projectUuid: string,\n force: boolean = false,\n ): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(`Redeploying all apps in project ${projectUuid}`);\n\n const appsResult = await this.listApplications(undefined, projectUuid);\n if (isErr(appsResult)) return err(appsResult.error);\n\n const apps = appsResult.value;\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of apps) {\n const result = await this.deploy({ uuid: app.uuid, force });\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Redeployed ${succeeded}/${apps.length} apps in project`);\n return ok({ total: apps.length, succeeded, failed });\n }\n\n /**\n * Stops all running applications.\n *\n * @returns Result with batch operation results\n */\n async stopAllApps(): Promise<\n Result<{ total: number; succeeded: number; failed: string[] }, Error>\n > {\n log.info(\"Stopping all applications\");\n\n const appsResult = await this.listApplications();\n if (isErr(appsResult)) return err(appsResult.error);\n\n const running = appsResult.value.filter(\n (a) => !a.status?.includes(\"stopped\"),\n );\n const failed: string[] = [];\n let succeeded = 0;\n\n for (const app of running) {\n const result = await this.stopApplication(app.uuid);\n if (isErr(result)) {\n failed.push(`${app.name} (${app.uuid}): ${result.error.message}`);\n } else {\n succeeded++;\n }\n }\n\n log.success(`Stopped ${succeeded}/${running.length} apps`);\n return ok({ total: running.length, succeeded, failed });\n }\n\n // ===========================================================================\n // Summary Types (Token Optimization for MCP)\n // ===========================================================================\n\n /**\n * Lists applications with minimal fields for token efficiency.\n *\n * @returns Result with application summaries or error\n */\n async listApplicationSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n status: string;\n fqdn: string | null;\n }>,\n Error\n >\n > {\n const result = await this.listApplications();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((a) => ({\n uuid: a.uuid,\n name: a.name,\n status: a.status,\n fqdn: a.fqdn || null,\n })),\n );\n }\n\n /**\n * Lists servers with minimal fields for token efficiency.\n *\n * @returns Result with server summaries or error\n */\n async listServerSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n ip: string;\n is_reachable: boolean;\n }>,\n Error\n >\n > {\n const result = await this.listServers();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((s) => ({\n uuid: s.uuid,\n name: s.name,\n ip: s.ip || \"\",\n is_reachable: s.is_reachable || false,\n })),\n );\n }\n\n /**\n * Lists databases with minimal fields for token efficiency.\n *\n * @returns Result with database summaries or error\n */\n async listDatabaseSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n type: string;\n status: string;\n }>,\n Error\n >\n > {\n const result = await this.listDatabases();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((d) => ({\n uuid: d.uuid,\n name: d.name,\n type: d.type,\n status: d.status,\n })),\n );\n }\n\n /**\n * Lists services with minimal fields for token efficiency.\n *\n * @returns Result with service summaries or error\n */\n async listServiceSummaries(): Promise<\n Result<\n Array<{\n uuid: string;\n name: string;\n type: string;\n status: string;\n }>,\n Error\n >\n > {\n const result = await this.listServices();\n if (isErr(result)) return err(result.error);\n\n return ok(\n result.value.map((s) => ({\n uuid: s.uuid,\n name: s.name,\n type: s.type,\n status: s.status,\n })),\n );\n }\n}\n\nlet instance: CoolifyService | null = null;\n\n/**\n * Gets the singleton CoolifyService instance.\n *\n * @returns The CoolifyService instance\n */\nexport function getCoolifyService(): CoolifyService {\n if (!instance) {\n instance = new CoolifyService();\n }\n return instance;\n}\n\n// Re-export types\nexport type {\n ICoolifyServer,\n ICoolifyServerResource,\n ICoolifyServerDomain,\n ICoolifyDestination,\n ICoolifyProject,\n ICoolifyTeam,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyPrivateKey,\n ICoolifyDeployment,\n ICoolifyVersion,\n ICoolifyAppOptions,\n ICoolifyAppResult,\n ICoolifyDeployOptions,\n ICoolifyDeployResult,\n ICoolifyDeleteResult,\n ICoolifyUpdateOptions,\n ICoolifyLogsOptions,\n ICoolifyLogs,\n IProgressCallback,\n ICoolifyInfrastructureTree,\n ICoolifyProjectNode,\n ICoolifyEnvironmentNode,\n ICoolifyResource,\n} from \"./types.js\";\n","/**\n * Coolify SDK — Fluent, resource-based API for Coolify.\n *\n * Every parameter from CoolifyService is exposed. Nothing is lost.\n *\n * @module\n */\n\nimport { isErr, type Result } from \"@mks2508/no-throw\";\nimport { CoolifyService } from \"./coolify/index.js\";\nimport type {\n ICoolifyAppOptions,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyDeleteResult,\n ICoolifyDeployment,\n ICoolifyDeployResult,\n ICoolifyDestination,\n ICoolifyEnvironment,\n ICoolifyLogs,\n ICoolifyLogsOptions,\n ICoolifyPrivateKey,\n ICoolifyProject,\n ICoolifyServer,\n ICoolifyServerDomain,\n ICoolifyServerResource,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyTeam,\n ICoolifyUpdateOptions,\n ICoolifyVersion,\n IProgressCallback,\n} from \"./coolify/types.js\";\nimport type { ICoolifyEnvVar } from \"./coolify/index.js\";\n\n/** SDK configuration options. */\nexport interface ICoolifyOptions {\n /** Coolify instance URL (e.g., https://coolify.example.com) */\n url: string;\n /** API token (generate in Coolify > Settings > API Tokens) */\n token: string;\n}\n\n/** Cascade delete options. */\nexport interface IDeleteOptions {\n deleteConfigurations?: boolean;\n deleteVolumes?: boolean;\n dockerCleanup?: boolean;\n deleteConnectedNetworks?: boolean;\n}\n\n/** Pagination options. */\nexport interface IPaginationOptions {\n page?: number;\n perPage?: number;\n}\n\nfunction unwrap<T>(result: Result<T, Error>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n// ─── Resource Classes ────────────────────────────────────────────────────────\n\nclass ApplicationsResource {\n constructor(private svc: CoolifyService) {}\n\n /** List all applications. Supports filtering and pagination. */\n async list(\n options?: { teamId?: string; projectId?: string } & IPaginationOptions,\n ): Promise<ICoolifyApplication[]> {\n return unwrap(\n await this.svc.listApplications(\n options?.teamId,\n options?.projectId,\n options?.page,\n options?.perPage,\n ),\n );\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listApplicationSummaries());\n }\n\n /** Resolve application by name, domain, or UUID. */\n async resolve(query: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.resolveApplication(query));\n }\n\n /** Create a new application. All ICoolifyAppOptions supported. */\n async create(options: ICoolifyAppOptions, onProgress?: IProgressCallback) {\n return unwrap(await this.svc.createApplication(options, onProgress));\n }\n\n /** Deploy an application. Supports force rebuild and progress tracking. */\n async deploy(\n uuid: string,\n options?: { force?: boolean; tag?: string },\n onProgress?: IProgressCallback,\n ): Promise<ICoolifyDeployResult> {\n return unwrap(await this.svc.deploy({ uuid, ...options }, onProgress));\n }\n\n /** Start application. Supports force and instant_deploy. */\n async start(\n uuid: string,\n options?: { force?: boolean; instantDeploy?: boolean },\n ): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.startApplication(uuid, options));\n }\n\n async stop(uuid: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.stopApplication(uuid));\n }\n\n async restart(uuid: string): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.restartApplication(uuid));\n }\n\n /** Delete application with optional cascade options. */\n async delete(\n uuid: string,\n options?: IDeleteOptions,\n ): Promise<ICoolifyDeleteResult> {\n return unwrap(await this.svc.deleteApplication(uuid, options));\n }\n\n /** Update application configuration. All ICoolifyUpdateOptions supported. */\n async update(\n uuid: string,\n options: ICoolifyUpdateOptions,\n ): Promise<ICoolifyApplication> {\n return unwrap(await this.svc.updateApplication(uuid, options));\n }\n\n /** Get application logs. Supports lines, serviceName, follow. */\n async logs(\n uuid: string,\n options?: ICoolifyLogsOptions,\n ): Promise<ICoolifyLogs> {\n return unwrap(await this.svc.getApplicationLogs(uuid, options));\n }\n\n /** Get deployment history with optional pagination. */\n async deployments(\n uuid: string,\n skip?: number,\n take?: number,\n ): Promise<ICoolifyDeployment[]> {\n return unwrap(await this.svc.getApplicationDeployments(uuid, skip, take));\n }\n\n async exec(uuid: string, command: string) {\n return unwrap(await this.svc.executeCommand(uuid, command));\n }\n\n async envVars(uuid: string): Promise<ICoolifyEnvVar[]> {\n return unwrap(await this.svc.getEnvironmentVariables(uuid));\n }\n\n async setEnv(\n uuid: string,\n key: string,\n value: string,\n isBuildTime?: boolean,\n ) {\n return unwrap(\n await this.svc.setEnvironmentVariable(uuid, key, value, isBuildTime),\n );\n }\n\n async bulkSetEnv(\n uuid: string,\n vars: Array<{ key: string; value: string; is_preview?: boolean }>,\n ) {\n return unwrap(await this.svc.bulkUpdateEnvironmentVariables(uuid, vars));\n }\n\n async deleteEnv(uuid: string, key: string) {\n return unwrap(await this.svc.deleteEnvironmentVariable(uuid, key));\n }\n\n /**\n * Sync environment variables from a local .env file to Coolify.\n *\n * @param uuid - Application UUID\n * @param options - Sync options\n * @returns Sync result with changes applied\n */\n async syncEnv(\n uuid: string,\n options: {\n /** Path to .env file (default: reads from .env in cwd) */\n filePath?: string;\n /** Preview changes without applying */\n dryRun?: boolean;\n /** Delete vars not in file */\n prune?: boolean;\n /** Callback for progress updates (optional) */\n onProgress?: (update: {\n type: 'add' | 'update' | 'remove';\n key: string;\n value?: string;\n }) => void;\n } = {},\n ): Promise<{\n added: Array<{ key: string; value: string }>;\n updated: Array<{ key: string; value: string; oldValue: string }>;\n removed: string[];\n skipped: number;\n }> {\n const { filePath, dryRun = false, prune = false, onProgress } = options;\n\n // 1. Read and parse .env file\n let envContent: string;\n try {\n envContent = await Bun.file(filePath || '.env').text();\n } catch {\n throw new Error(\n filePath\n ? `Cannot read file: ${filePath}`\n : 'No .env file found in current directory',\n );\n }\n\n const localVars = this.parseEnvContent(envContent);\n\n if (localVars.size === 0) {\n return { added: [], updated: [], removed: [], skipped: 0 };\n }\n\n // 2. Get current vars from Coolify\n const currentVarsList = await this.envVars(uuid);\n const currentVars = new Map(\n currentVarsList.map((v) => [v.key, v.value]),\n );\n\n // 3. Calculate changes\n const toAdd: Array<{ key: string; value: string }> = [];\n const toUpdate: Array<{\n key: string;\n value: string;\n oldValue: string;\n }> = [];\n const toRemove: string[] = [];\n\n for (const [key, value] of localVars.entries()) {\n const currentValue = currentVars.get(key);\n if (!currentValue) {\n toAdd.push({ key, value });\n } else if (currentValue !== value) {\n toUpdate.push({ key, value, oldValue: currentValue });\n }\n }\n\n if (prune) {\n for (const key of currentVars.keys()) {\n if (!localVars.has(key)) {\n toRemove.push(key);\n }\n }\n }\n\n // 4. Apply changes (unless dry-run)\n if (!dryRun) {\n // Add new variables\n for (const { key, value } of toAdd) {\n await this.setEnv(uuid, key, value, false);\n onProgress?.({ type: 'add', key, value });\n }\n\n // Update existing variables\n for (const { key, value } of toUpdate) {\n await this.setEnv(uuid, key, value, false);\n onProgress?.({ type: 'update', key, value });\n }\n\n // Remove pruned variables\n for (const key of toRemove) {\n await this.deleteEnv(uuid, key);\n onProgress?.({ type: 'remove', key });\n }\n } else {\n // Report what would happen in dry-run\n for (const { key, value } of toAdd) {\n onProgress?.({ type: 'add', key, value });\n }\n for (const { key, value } of toUpdate) {\n onProgress?.({ type: 'update', key, value });\n }\n for (const key of toRemove) {\n onProgress?.({ type: 'remove', key });\n }\n }\n\n return {\n added: toAdd,\n updated: toUpdate,\n removed: toRemove,\n skipped: currentVars.size - toUpdate.length - toRemove.length,\n };\n }\n\n /**\n * Parse .env file content into a Map.\n * Handles comments, empty lines, and quoted values.\n *\n * @param content - The .env file content\n * @returns Map of environment variables\n */\n private parseEnvContent(content: string): Map<string, string> {\n const envVars = new Map<string, string>();\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n // Skip comments and empty lines\n if (!trimmedLine || trimmedLine.startsWith('#')) {\n continue;\n }\n\n // Parse KEY=VALUE format\n const eqIndex = trimmedLine.indexOf('=');\n if (eqIndex === -1) {\n continue; // Skip invalid lines\n }\n\n const key = trimmedLine.slice(0, eqIndex).trim();\n let value = trimmedLine.slice(eqIndex + 1).trim();\n\n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n envVars.set(key, value);\n }\n\n return envVars;\n }\n}\n\nclass DatabasesResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyDatabase[]> {\n return unwrap(\n await this.svc.listDatabases(options?.page, options?.perPage),\n );\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listDatabaseSummaries());\n }\n\n async get(uuid: string): Promise<ICoolifyDatabase> {\n return unwrap(await this.svc.getDatabase(uuid));\n }\n\n async create(type: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.createDatabase(type, data));\n }\n\n async update(uuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateDatabase(uuid, data));\n }\n\n async start(uuid: string) {\n return unwrap(await this.svc.startDatabase(uuid));\n }\n async stop(uuid: string) {\n return unwrap(await this.svc.stopDatabase(uuid));\n }\n async restart(uuid: string) {\n return unwrap(await this.svc.restartDatabase(uuid));\n }\n\n /** Delete with optional cascade options. */\n async delete(uuid: string, options?: IDeleteOptions) {\n return unwrap(await this.svc.deleteDatabase(uuid, options));\n }\n\n async backups(uuid: string): Promise<ICoolifyDatabaseBackup[]> {\n return unwrap(await this.svc.listDatabaseBackups(uuid));\n }\n\n async getBackup(dbUuid: string, backupUuid: string) {\n return unwrap(await this.svc.getDatabaseBackup(dbUuid, backupUuid));\n }\n\n async createBackup(dbUuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.createDatabaseBackup(dbUuid, data));\n }\n\n async deleteBackup(dbUuid: string, backupUuid: string) {\n return unwrap(await this.svc.deleteDatabaseBackup(dbUuid, backupUuid));\n }\n}\n\nclass ServicesResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyServiceType[]> {\n return unwrap(await this.svc.listServices(options?.page, options?.perPage));\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listServiceSummaries());\n }\n\n async get(uuid: string): Promise<ICoolifyServiceType> {\n return unwrap(await this.svc.getService(uuid));\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createService(data));\n }\n\n async update(uuid: string, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateService(uuid, data));\n }\n\n async start(uuid: string) {\n return unwrap(await this.svc.startService(uuid));\n }\n async stop(uuid: string) {\n return unwrap(await this.svc.stopService(uuid));\n }\n async restart(uuid: string) {\n return unwrap(await this.svc.restartService(uuid));\n }\n\n /** Delete with optional cascade options. */\n async delete(uuid: string, options?: IDeleteOptions) {\n return unwrap(await this.svc.deleteService(uuid, options));\n }\n\n async envVars(uuid: string): Promise<ICoolifyEnvVar[]> {\n return unwrap(await this.svc.listServiceEnvVars(uuid));\n }\n\n async setEnv(\n uuid: string,\n data: { key: string; value: string; is_preview?: boolean },\n ) {\n return unwrap(await this.svc.createServiceEnvVar(uuid, data));\n }\n}\n\nclass ServersResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyServer[]> {\n return unwrap(await this.svc.listServers(options?.page, options?.perPage));\n }\n\n async listSummaries() {\n return unwrap(await this.svc.listServerSummaries());\n }\n\n async resolve(query: string): Promise<ICoolifyServer> {\n return unwrap(await this.svc.resolveServer(query));\n }\n\n async get(uuid: string): Promise<ICoolifyServer> {\n return unwrap(await this.svc.getServer(uuid));\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createServer(data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deleteServer(uuid));\n }\n\n async resources(uuid: string): Promise<ICoolifyServerResource[]> {\n return unwrap(await this.svc.getServerResources(uuid));\n }\n\n async domains(uuid: string): Promise<ICoolifyServerDomain[]> {\n return unwrap(await this.svc.getServerDomains(uuid));\n }\n\n async destinations(uuid: string): Promise<ICoolifyDestination[]> {\n return unwrap(await this.svc.getServerDestinations(uuid));\n }\n\n async validate(uuid: string) {\n return unwrap(await this.svc.validateServer(uuid));\n }\n}\n\nclass ProjectsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyProject[]> {\n return unwrap(await this.svc.listProjects(options?.page, options?.perPage));\n }\n\n async create(name: string, description?: string): Promise<ICoolifyProject> {\n return unwrap(await this.svc.createProject(name, description));\n }\n\n async update(uuid: string, data: { name?: string; description?: string }) {\n return unwrap(await this.svc.updateProject(uuid, data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deleteProject(uuid));\n }\n\n async environments(projectUuid: string): Promise<ICoolifyEnvironment[]> {\n return unwrap(await this.svc.getProjectEnvironments(projectUuid));\n }\n\n async createEnvironment(\n projectUuid: string,\n data: { name: string; description?: string },\n ) {\n return unwrap(await this.svc.createProjectEnvironment(projectUuid, data));\n }\n}\n\nclass TeamsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions): Promise<ICoolifyTeam[]> {\n return unwrap(await this.svc.listTeams(options?.page, options?.perPage));\n }\n\n async current(): Promise<ICoolifyTeam> {\n return unwrap(await this.svc.getCurrentTeam());\n }\n\n async get(id: number): Promise<ICoolifyTeam> {\n return unwrap(await this.svc.getTeam(id));\n }\n\n async members(teamId: number) {\n return unwrap(await this.svc.getTeamMembers(teamId));\n }\n}\n\nclass KeysResource {\n constructor(private svc: CoolifyService) {}\n\n async list(): Promise<ICoolifyPrivateKey[]> {\n return unwrap(await this.svc.listPrivateKeys());\n }\n\n async get(uuid: string): Promise<ICoolifyPrivateKey> {\n return unwrap(await this.svc.getPrivateKey(uuid));\n }\n\n async create(data: {\n name: string;\n private_key: string;\n description?: string;\n }) {\n return unwrap(await this.svc.createPrivateKey(data));\n }\n\n async update(\n uuid: string,\n data: { name?: string; private_key?: string; description?: string },\n ) {\n return unwrap(await this.svc.updatePrivateKey(uuid, data));\n }\n\n async delete(uuid: string) {\n return unwrap(await this.svc.deletePrivateKey(uuid));\n }\n}\n\nclass DeploymentsResource {\n constructor(private svc: CoolifyService) {}\n\n async active(options?: IPaginationOptions): Promise<ICoolifyDeployment[]> {\n return unwrap(\n await this.svc.listDeployments(options?.page, options?.perPage),\n );\n }\n\n async get(uuid: string): Promise<ICoolifyDeployment> {\n return unwrap(await this.svc.getDeployment(uuid));\n }\n\n /** Get deployment with build logs. */\n async logs(uuid: string) {\n return unwrap(await this.svc.getDeploymentLogs(uuid));\n }\n\n async cancel(uuid: string) {\n return unwrap(await this.svc.cancelDeployment(uuid));\n }\n}\n\nclass DiagnoseResource {\n constructor(private svc: CoolifyService) {}\n\n async app(query: string) {\n return unwrap(await this.svc.diagnoseApplication(query));\n }\n\n async server(query: string) {\n return unwrap(await this.svc.diagnoseServer(query));\n }\n\n async infrastructure() {\n return unwrap(await this.svc.findInfrastructureIssues());\n }\n\n /** Analyze a failed deployment — extracts errors from build logs. */\n async deployFailure(deploymentUuid: string) {\n const { analyzeDeployFailure } = await import(\"./network.js\");\n return unwrap(await analyzeDeployFailure(this.svc, deploymentUuid));\n }\n}\n\n/**\n * Network diagnostics — inspect Docker networks, proxy, DNS, connectivity.\n */\nclass NetworkResource {\n constructor(private svc: CoolifyService) {}\n\n /**\n * Inspect container network environment.\n *\n * @param appUuid - Application UUID\n * @param servicesToTest - Service names to test connectivity (e.g., ['db', 'redis'])\n */\n async inspect(appUuid: string, servicesToTest?: string[]) {\n const { inspectNetwork } = await import(\"./network.js\");\n return unwrap(await inspectNetwork(this.svc, appUuid, servicesToTest));\n }\n}\n\nclass BatchResource {\n constructor(private svc: CoolifyService) {}\n\n async restartProject(projectUuid: string) {\n return unwrap(await this.svc.restartProjectApps(projectUuid));\n }\n\n async redeployProject(projectUuid: string, force?: boolean) {\n return unwrap(await this.svc.redeployProjectApps(projectUuid, force));\n }\n\n async stopAll() {\n return unwrap(await this.svc.stopAllApps());\n }\n}\n\nclass GitHubAppsResource {\n constructor(private svc: CoolifyService) {}\n\n async list(options?: IPaginationOptions) {\n return unwrap(\n await this.svc.listGithubApps(options?.page, options?.perPage),\n );\n }\n\n async create(data: Record<string, unknown>) {\n return unwrap(await this.svc.createGitHubApp(data));\n }\n\n async update(id: number, data: Record<string, unknown>) {\n return unwrap(await this.svc.updateGitHubApp(id, data));\n }\n\n async delete(id: number) {\n return unwrap(await this.svc.deleteGitHubApp(id));\n }\n}\n\n// ─── Main SDK Class ──────────────────────────────────────────────────────────\n\n/**\n * Coolify SDK — The main entry point for interacting with a Coolify instance.\n *\n * Every parameter from the internal CoolifyService is exposed.\n * Nothing is lost — progress callbacks, pagination, cascade deletes, all supported.\n */\nexport class Coolify {\n /** @internal */\n readonly svc: CoolifyService;\n private initialized = false;\n\n readonly applications: ApplicationsResource;\n readonly databases: DatabasesResource;\n readonly services: ServicesResource;\n readonly servers: ServersResource;\n readonly projects: ProjectsResource;\n readonly teams: TeamsResource;\n readonly keys: KeysResource;\n readonly deployments: DeploymentsResource;\n readonly diagnose: DiagnoseResource;\n readonly network: NetworkResource;\n readonly batch: BatchResource;\n readonly githubApps: GitHubAppsResource;\n\n constructor(options?: ICoolifyOptions) {\n this.svc = new CoolifyService();\n\n if (options) {\n process.env.COOLIFY_URL = options.url;\n process.env.COOLIFY_TOKEN = options.token;\n }\n\n const autoInit = <T extends object>(resource: T): T => {\n return new Proxy(resource, {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") return value;\n return async (...args: unknown[]) => {\n await this.ensureInit();\n return (value as Function).apply(target, args);\n };\n },\n });\n };\n\n this.applications = autoInit(new ApplicationsResource(this.svc));\n this.databases = autoInit(new DatabasesResource(this.svc));\n this.services = autoInit(new ServicesResource(this.svc));\n this.servers = autoInit(new ServersResource(this.svc));\n this.projects = autoInit(new ProjectsResource(this.svc));\n this.teams = autoInit(new TeamsResource(this.svc));\n this.keys = autoInit(new KeysResource(this.svc));\n this.deployments = autoInit(new DeploymentsResource(this.svc));\n this.diagnose = autoInit(new DiagnoseResource(this.svc));\n this.network = autoInit(new NetworkResource(this.svc));\n this.batch = autoInit(new BatchResource(this.svc));\n this.githubApps = autoInit(new GitHubAppsResource(this.svc));\n }\n\n static fromEnv(): Coolify {\n return new Coolify();\n }\n\n private async ensureInit(): Promise<void> {\n if (this.initialized) return;\n const initResult = await this.svc.init();\n if (isErr(initResult)) {\n throw new Error(`Coolify connection failed: ${initResult.error.message}`);\n }\n this.initialized = true;\n }\n\n async version(): Promise<ICoolifyVersion> {\n await this.ensureInit();\n return unwrap(await this.svc.getVersion());\n }\n}\n","/**\n * MCP Tool definitions for Coolify.\n *\n * Defines all 21 tools with their input schemas.\n *\n * @module\n */\n\nimport type { Tool } from \"@modelcontextprotocol/sdk/types.js\";\n\n/**\n * All Coolify MCP tool definitions.\n */\nexport const coolifyTools: Tool[] = [\n {\n name: \"deploy\",\n description: `Deploy or redeploy an application to Coolify.\n\nTriggers a new deployment for the specified application UUID.\nCan force rebuild without cache if needed.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID in Coolify\",\n format: \"uuid\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force rebuild without cache\",\n default: false,\n },\n tag: {\n type: \"string\" as const,\n description: \"Deploy specific tag/version\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_env_vars\",\n description: `Get environment variables for a Coolify application.\n\nReturns all environment variables with metadata including whether\nthey are runtime or buildtime, and if they are required.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"set_env_vars\",\n description: `Set environment variables for a Coolify application.\n\nUpdates or adds environment variables. Existing vars not in the\ninput are preserved. Redeploy after setting to apply changes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n envVars: {\n type: \"object\" as const,\n description: \"Key-value pairs of environment variables\",\n additionalProperties: { type: \"string\" as const },\n },\n },\n required: [\"uuid\", \"envVars\"],\n },\n },\n {\n name: \"get_deployment_status\",\n description: `Get the current status of a Coolify application.\n\nReturns deployment state, health status, and resource usage.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"list_applications\",\n description: `List all applications in Coolify.\n\nOptionally filter by team or project ID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n teamId: {\n type: \"string\" as const,\n description: \"Filter by Team ID\",\n },\n projectId: {\n type: \"string\" as const,\n description: \"Filter by Project ID\",\n },\n },\n },\n },\n {\n name: \"delete_application\",\n description: `Delete an application from Coolify.\n\nWARNING: This action is irreversible. All deployments, environment\nvariables, domains, and history will be permanently deleted.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to delete\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_application_logs\",\n description: `Get logs for a Coolify application.\n\nRetrieve recent logs. For docker-compose apps, use serviceName to filter by container.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n tail: {\n type: \"number\" as const,\n description: \"Number of log lines to retrieve (default: 100)\",\n },\n serviceName: {\n type: \"string\" as const,\n description:\n \"Service name to filter logs (for docker-compose apps, e.g., 'app', 'db')\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_application\",\n description: `Start a stopped Coolify application.\n\nUse this to start applications that were previously stopped.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to start\",\n format: \"uuid\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force start even if already running\",\n },\n instantDeploy: {\n type: \"boolean\" as const,\n description: \"Instant deploy without waiting for queue\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_application\",\n description: `Stop a running Coolify application.\n\nWARNING: This will make the application temporarily unavailable.\nContainers will be stopped but not deleted.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to stop\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_application\",\n description: `Restart a Coolify application.\n\nEquivalent to stopping and then starting the application.\nUseful to apply configuration changes or recover from errors.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID to restart\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_deployment_history\",\n description: `Get deployment history for a Coolify application.\n\nReturns list of all deployments with status, timestamps, and commit info.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"update_application\",\n description: `Update configuration for a Coolify application.\n\nCan modify name, description, build settings, commands, and domains.\nRedeploy after updating to apply changes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n name: {\n type: \"string\" as const,\n description: \"New application name\",\n },\n description: {\n type: \"string\" as const,\n description: \"New description\",\n },\n buildPack: {\n type: \"string\" as const,\n description: \"Build pack type\",\n enum: [\"dockerfile\", \"nixpacks\", \"static\", \"dockercompose\"],\n },\n gitBranch: {\n type: \"string\" as const,\n description: \"Git branch to deploy\",\n },\n portsExposes: {\n type: \"string\" as const,\n description: \"Ports to expose (comma-separated)\",\n },\n installCommand: {\n type: \"string\" as const,\n description: \"Install command (nixpacks)\",\n },\n buildCommand: {\n type: \"string\" as const,\n description: \"Build command\",\n },\n startCommand: {\n type: \"string\" as const,\n description: \"Start command\",\n },\n domains: {\n type: \"string\" as const,\n description:\n 'Domains/FQDN - comma separated list with protocol (e.g., \"https://app.example.com,https://www.example.com\")',\n },\n isForceHttpsEnabled: {\n type: \"boolean\" as const,\n description: \"Force HTTPS redirect\",\n },\n isAutoDeployEnabled: {\n type: \"boolean\" as const,\n description: \"Enable auto deploy on git push\",\n },\n dockerfileLocation: {\n type: \"string\" as const,\n description: \"Dockerfile location relative to repo root\",\n },\n baseDirectory: {\n type: \"string\" as const,\n description: 'Base directory for build context (default: \"/\")',\n },\n dockerComposeDomains: {\n type: \"string\" as const,\n description:\n 'Docker Compose domains JSON: { \"service-name\": { \"domain\": \"https://...\" } }',\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"set_domains\",\n description: `Set domains/FQDN for a Coolify application.\n\nConfigure custom domains for your application. Coolify automatically handles SSL certificates via Let's Encrypt.\n\nDomain format:\n- Use FQDN with protocol: https://app.example.com\n- Multiple domains separated by comma: https://app.example.com,https://www.example.com\n- Can include port mapping: https://api.example.com:3000`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n domains: {\n type: \"string\" as const,\n description:\n 'Domains/FQDN - comma separated list with protocol (e.g., \"https://app.example.com,https://www.example.com\")',\n },\n forceHttps: {\n type: \"boolean\" as const,\n description: \"Force HTTPS redirect (default: true)\",\n default: true,\n },\n },\n required: [\"uuid\", \"domains\"],\n },\n },\n {\n name: \"list_servers\",\n description: `List all available servers in Coolify.\n\nReturns server UUIDs, names, and IPs. Use server UUID when creating applications.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_server\",\n description: `Get details of a specific Coolify server.\n\nReturns server information including name, IP, status, and configuration.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to get details for\",\n format: \"uuid\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"list_projects\",\n description: `List all projects in Coolify.\n\nReturns project UUIDs, names, and associated environments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"list_teams\",\n description: `List all teams in Coolify.\n\nReturns team IDs, names, and configuration.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_server_destinations\",\n description: `Get available destinations for a Coolify server.\n\nReturns destination UUIDs needed when creating applications.\nEach destination represents a Docker network/environment on the server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to get destinations for\",\n format: \"uuid\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"create_application\",\n description: `Create a new application in Coolify from a GitHub repository.\n\nRequires server UUID and destination UUID (get them from list_servers and get_server_destinations).\nThe GitHub repository must be accessible via the configured GitHub App.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\" as const,\n description: \"Application name\",\n },\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to deploy to\",\n format: \"uuid\",\n },\n destinationUuid: {\n type: \"string\" as const,\n description: \"Destination UUID (Docker network)\",\n format: \"uuid\",\n },\n githubRepoUrl: {\n type: \"string\" as const,\n description:\n \"GitHub repository URL (e.g., https://github.com/user/repo)\",\n },\n description: {\n type: \"string\" as const,\n description: \"Application description\",\n },\n branch: {\n type: \"string\" as const,\n description: \"Git branch to deploy\",\n default: \"main\",\n },\n buildPack: {\n type: \"string\" as const,\n description: \"Build pack type\",\n enum: [\"dockerfile\", \"nixpacks\", \"static\", \"dockercompose\"],\n default: \"nixpacks\",\n },\n type: {\n type: \"string\" as const,\n description: \"Application type\",\n enum: [\n \"public\",\n \"private-github-app\",\n \"private-deploy-key\",\n \"dockerfile\",\n \"docker-image\",\n \"docker-compose\",\n ],\n default: \"public\",\n },\n dockerComposeLocation: {\n type: \"string\" as const,\n description:\n \"Docker Compose file location relative to repo root (for dockercompose buildPack)\",\n },\n dockerfileLocation: {\n type: \"string\" as const,\n description: \"Dockerfile location relative to repo root\",\n },\n baseDirectory: {\n type: \"string\" as const,\n description: 'Base directory for build context (default: \"/\")',\n },\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n environmentUuid: {\n type: \"string\" as const,\n description: \"Environment UUID\",\n },\n githubAppUuid: {\n type: \"string\" as const,\n description:\n \"GitHub App UUID (for private-github-app type, get from list_github_apps)\",\n },\n portsExposes: {\n type: \"string\" as const,\n description: \"Ports to expose (e.g., '3000' or '3000,8080')\",\n },\n },\n required: [\"name\", \"serverUuid\"],\n },\n },\n {\n name: \"create_project\",\n description: `Create a new project in Coolify.\n\nProjects organize applications into logical groups. Each project has one or more environments (e.g., production, staging).`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\" as const,\n description: \"Project name\",\n },\n description: {\n type: \"string\" as const,\n description: \"Project description\",\n },\n },\n required: [\"name\"],\n },\n },\n {\n name: \"get_resource_usage\",\n description: `Get resource usage for a Coolify application.\n\nReturns current resource consumption metrics.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"health_check\",\n description: `Check if Coolify API is accessible and credentials are valid.\n\nReturns connection status and API version info if available.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"list_deployments\",\n description: `List all active and queued deployments across all applications.\n\nReturns deployments that are currently in progress or waiting in queue.\nUseful for monitoring ongoing builds and deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_deployment\",\n description: `Get detailed information about a specific deployment.\n\nReturns deployment status, logs, timestamps, and error messages if any.\nUse deployment UUID from list_deployments or get_application_deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n {\n name: \"get_application_deployments\",\n description: `Get deployment history for a specific application.\n\nReturns list of all deployments with status, timestamps, commit info, and logs.\nUseful for debugging failed deployments and tracking deployment history.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n skip: {\n type: \"number\" as const,\n description: \"Number of deployments to skip (pagination)\",\n default: 0,\n },\n take: {\n type: \"number\" as const,\n description: \"Number of deployments to return (default: 10)\",\n default: 10,\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"get_application_details\",\n description: `Get detailed information about a Coolify application.\n\nReturns full application configuration including name, description,\nbuild settings, environment, and deployment status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n format: \"uuid\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n {\n name: \"execute_command\",\n description: `Execute a shell command on an application's running container.\n\nUseful for debugging, checking file contents, or running one-off operations.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n command: {\n type: \"string\" as const,\n description:\n \"Shell command to execute (e.g., 'ls -la', 'cat /app/logs/error.log')\",\n },\n },\n required: [\"uuid\", \"command\"],\n },\n },\n {\n name: \"bulk_update_env_vars\",\n description: `Bulk update environment variables for an application.\n\nMore efficient than setting variables one by one. Accepts an array of key-value pairs.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n envVars: {\n type: \"array\" as const,\n description: \"Array of { key, value, is_preview? } objects\",\n items: {\n type: \"object\" as const,\n properties: {\n key: { type: \"string\" as const },\n value: { type: \"string\" as const },\n is_preview: { type: \"boolean\" as const },\n },\n required: [\"key\", \"value\"],\n },\n },\n },\n required: [\"uuid\", \"envVars\"],\n },\n },\n\n // ===========================================================================\n // Version / Health\n // ===========================================================================\n {\n name: \"get_version\",\n description: `Get the Coolify server version.\n\nReturns the version string of the connected Coolify instance.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Database Management\n // ===========================================================================\n {\n name: \"list_databases\",\n description: `List all databases in Coolify.\n\nReturns database UUIDs, names, types, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_database\",\n description: `Get details of a specific database.\n\nReturns full database configuration, connection info, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"create_database\",\n description: `Create a new database in Coolify.\n\nSupports types: postgresql, mysql, mariadb, mongodb, redis, keydb, clickhouse, dragonfly.\nRequires server_uuid and project_uuid in the data.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n dbType: {\n type: \"string\" as const,\n description: \"Database type\",\n enum: [\n \"postgresql\",\n \"mysql\",\n \"mariadb\",\n \"mongodb\",\n \"redis\",\n \"keydb\",\n \"clickhouse\",\n \"dragonfly\",\n ],\n },\n data: {\n type: \"object\" as const,\n description:\n \"Database creation data (server_uuid, project_uuid, environment_name, etc.)\",\n additionalProperties: true,\n },\n },\n required: [\"dbType\", \"data\"],\n },\n },\n {\n name: \"delete_database\",\n description: `Delete a database from Coolify.\n\nWARNING: This action is irreversible.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to delete\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_database\",\n description: `Start a stopped database.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to start\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_database\",\n description: `Stop a running database.\n\nWARNING: This will make the database temporarily unavailable.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to stop\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_database\",\n description: `Restart a database.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Database UUID to restart\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Service Management\n // ===========================================================================\n {\n name: \"list_services\",\n description: `List all services in Coolify.\n\nReturns service UUIDs, names, types, and status.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_service\",\n description: `Get details of a specific service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"start_service\",\n description: `Start a stopped service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to start\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"stop_service\",\n description: `Stop a running service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to stop\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"restart_service\",\n description: `Restart a service.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to restart\",\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"delete_service\",\n description: `Delete a service from Coolify.\n\nWARNING: This action is irreversible.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Service UUID to delete\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Server (additional)\n // ===========================================================================\n {\n name: \"get_server_resources\",\n description: `Get all resources deployed on a server.\n\nReturns applications, databases, and services running on the server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"get_server_domains\",\n description: `Get all domains configured on a server.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n {\n name: \"validate_server\",\n description: `Validate a server connection in Coolify.\n\nChecks if the server is reachable and properly configured.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n serverUuid: {\n type: \"string\" as const,\n description: \"Server UUID to validate\",\n },\n },\n required: [\"serverUuid\"],\n },\n },\n\n // ===========================================================================\n // Deployment Control\n // ===========================================================================\n {\n name: \"cancel_deployment\",\n description: `Cancel an in-progress deployment.\n\nStops the build/deployment process for the specified deployment.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID to cancel\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n\n // ===========================================================================\n // Teams (additional)\n // ===========================================================================\n {\n name: \"get_current_team\",\n description: `Get the current team associated with the API token.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_team_members\",\n description: `Get members of a specific team.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n teamId: {\n type: \"number\" as const,\n description: \"Team ID\",\n },\n },\n required: [\"teamId\"],\n },\n },\n\n // ===========================================================================\n // Private Keys / SSH\n // ===========================================================================\n {\n name: \"list_private_keys\",\n description: `List all SSH private keys configured in Coolify.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n {\n name: \"get_private_key\",\n description: `Get details of a specific SSH private key.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Private key UUID\",\n },\n },\n required: [\"uuid\"],\n },\n },\n\n // ===========================================================================\n // Smart Resolution\n // ===========================================================================\n {\n name: \"resolve_application\",\n description: `Find an application by name, domain, or UUID.\n\nSearches across all applications and returns the match. Useful when you know\nthe app name but not the UUID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Application name, domain (FQDN), or UUID to search for\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"resolve_server\",\n description: `Find a server by name, IP, or UUID.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Server name, IP address, or UUID to search for\",\n },\n },\n required: [\"query\"],\n },\n },\n\n // ===========================================================================\n // Diagnostics\n // ===========================================================================\n {\n name: \"diagnose_application\",\n description: `Run a comprehensive diagnostic on an application.\n\nAggregates status, recent deployments, environment variables, and logs\ninto a single diagnostic report with identified issues.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Application name, domain, or UUID to diagnose\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"diagnose_server\",\n description: `Run a comprehensive diagnostic on a server.\n\nAggregates server health, deployed resources, and domains into a diagnostic report.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\" as const,\n description: \"Server name, IP, or UUID to diagnose\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"find_infrastructure_issues\",\n description: `Scan all infrastructure for potential issues.\n\nChecks all servers, applications, databases, and services for problems\nlike unreachable servers, stopped apps, failed deployments.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Batch Operations\n // ===========================================================================\n {\n name: \"restart_project_apps\",\n description: `Restart all applications in a project.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n },\n required: [\"projectUuid\"],\n },\n },\n {\n name: \"redeploy_project_apps\",\n description: `Redeploy all applications in a project.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n projectUuid: {\n type: \"string\" as const,\n description: \"Project UUID\",\n },\n force: {\n type: \"boolean\" as const,\n description: \"Force rebuild without cache\",\n default: false,\n },\n },\n required: [\"projectUuid\"],\n },\n },\n {\n name: \"stop_all_apps\",\n description: `Emergency stop all running applications.\n\nWARNING: This will stop ALL running applications across all projects.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {},\n },\n },\n\n // ===========================================================================\n // Network Diagnostics\n // ===========================================================================\n {\n name: \"inspect_network\",\n description: `Inspect Docker container network environment for an application.\n\nReturns /etc/hosts, DNS resolution, network env vars, interfaces,\nand optionally tests connectivity to other services.\nEssential for debugging docker-compose networking issues.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n uuid: {\n type: \"string\" as const,\n description: \"Application UUID\",\n },\n servicesToTest: {\n type: \"array\" as const,\n description:\n \"Service names to test connectivity (e.g., ['db', 'redis', 'app'])\",\n items: { type: \"string\" as const },\n },\n },\n required: [\"uuid\"],\n },\n },\n {\n name: \"analyze_deploy_failure\",\n description: `Analyze a failed deployment by inspecting build logs.\n\nAutomatically extracts error lines, categorizes the failure type\n(build_error, install_error, docker_error, network_error, timeout),\nand suggests fixes.`,\n inputSchema: {\n type: \"object\" as const,\n properties: {\n deploymentUuid: {\n type: \"string\" as const,\n description: \"Deployment UUID of the failed deployment\",\n },\n },\n required: [\"deploymentUuid\"],\n },\n },\n];\n","/**\n * MCP Tool handlers for Coolify.\n *\n * All handlers route through the Coolify SDK facade.\n * Uses a generic mcpCall wrapper to eliminate boilerplate.\n *\n * @module\n */\n\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Coolify } from \"../sdk.js\";\n\n/** Singleton SDK for MCP usage (reads env vars / config file). */\nlet _sdk: Coolify | null = null;\nfunction getSdk(): Coolify {\n if (!_sdk) _sdk = Coolify.fromEnv();\n return _sdk;\n}\n\n/**\n * Wraps an SDK call into an MCP tool result.\n * On success → JSON response. On error → isError response.\n *\n * @param fn - Async function that calls the SDK (throws on error)\n * @param label - Error context label\n * @returns MCP CallToolResult\n */\nasync function mcpCall(\n fn: (sdk: Coolify) => Promise<unknown>,\n label: string,\n): Promise<CallToolResult> {\n try {\n const data = await fn(getSdk());\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n typeof data === \"object\" && data !== null\n ? { success: true, ...data }\n : { success: true, result: data },\n null,\n 2,\n ),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: \"text\",\n text: `${label}: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/** Wraps SDK call returning an array into { count, items } format. */\nasync function mcpList(\n fn: (sdk: Coolify) => Promise<unknown[]>,\n itemKey: string,\n label: string,\n): Promise<CallToolResult> {\n return mcpCall(async (sdk) => {\n const items = await fn(sdk);\n return { count: items.length, [itemKey]: items };\n }, label);\n}\n\n/**\n * Main handler — routes tool calls to SDK methods.\n *\n * @param name - Tool name\n * @param args - Tool arguments\n * @returns MCP tool result\n */\nexport async function handleToolCall(\n name: string,\n args: Record<string, unknown>,\n): Promise<CallToolResult> {\n const a = args as any;\n\n switch (name) {\n // ─── Applications ──────────────────────────────────────────────────\n case \"deploy\":\n return mcpCall(\n (s) =>\n s.applications\n .deploy(a.uuid, { force: a.force, tag: a.tag })\n .then((r) => ({\n deploymentUuid: r.deploymentUuid,\n resourceUuid: r.resourceUuid,\n message: \"Deployment started\",\n })),\n \"Deployment failed\",\n );\n case \"list_applications\":\n return mcpList(\n (s) => s.applications.list(),\n \"applications\",\n \"Failed to list applications\",\n );\n case \"get_application_details\":\n return mcpCall(\n (s) =>\n s.applications.resolve(a.uuid).then((app) => ({ application: app })),\n \"Failed to get application\",\n );\n case \"start_application\":\n return mcpCall(\n (s) =>\n s.applications\n .start(a.uuid, { force: a.force, instantDeploy: a.instantDeploy })\n .then(() => ({\n message: `Application ${a.uuid} started`,\n })),\n \"Failed to start application\",\n );\n case \"stop_application\":\n return mcpCall(\n (s) =>\n s.applications.stop(a.uuid).then(() => ({\n message: `Application ${a.uuid} stopped`,\n })),\n \"Failed to stop application\",\n );\n case \"restart_application\":\n return mcpCall(\n (s) =>\n s.applications.restart(a.uuid).then(() => ({\n message: `Application ${a.uuid} restarted`,\n })),\n \"Failed to restart application\",\n );\n case \"delete_application\":\n return mcpCall(\n (s) =>\n s.applications.delete(a.uuid).then(() => ({\n message: `Application ${a.uuid} deleted`,\n })),\n \"Failed to delete application\",\n );\n case \"update_application\":\n return mcpCall(\n (s) =>\n s.applications\n .update(a.uuid, {\n name: a.name,\n description: a.description,\n buildPack: a.buildPack,\n gitBranch: a.gitBranch,\n portsExposes: a.portsExposes,\n installCommand: a.installCommand,\n buildCommand: a.buildCommand,\n startCommand: a.startCommand,\n domains: a.domains,\n isForceHttpsEnabled: a.isForceHttpsEnabled,\n isAutoDeployEnabled: a.isAutoDeployEnabled,\n })\n .then((app) => ({\n message: `Application ${a.uuid} updated`,\n application: app,\n })),\n \"Failed to update application\",\n );\n case \"get_application_logs\":\n return mcpCall(\n (s) =>\n s.applications\n .logs(a.uuid, { tail: a.tail, serviceName: a.serviceName })\n .then((logs) => ({\n timestamp: logs.timestamp,\n logCount: logs.logs.length,\n logs: logs.logs,\n })),\n \"Failed to get logs\",\n );\n case \"get_deployment_history\":\n return mcpList(\n (s) => s.applications.deployments(a.uuid),\n \"deployments\",\n \"Failed to get deployment history\",\n );\n case \"get_application_deployments\":\n return mcpList(\n (s) => s.applications.deployments(a.uuid),\n \"deployments\",\n \"Failed to get deployments\",\n );\n case \"execute_command\":\n return mcpCall(\n (s) => s.applications.exec(a.uuid, a.command),\n \"Failed to execute command\",\n );\n\n // ─── Environment Variables ─────────────────────────────────────────\n case \"get_env_vars\":\n return mcpCall(\n (s) =>\n s.applications.envVars(a.uuid).then((vars) => ({\n total: vars.length,\n runtime: vars.filter((v) => v.is_runtime),\n buildtime: vars.filter((v) => v.is_buildtime),\n })),\n \"Failed to get env vars\",\n );\n case \"set_env_vars\":\n return mcpCall((s) => {\n const entries = Object.entries(a.envVars as Record<string, string>);\n return s.applications\n .bulkSetEnv(\n a.uuid,\n entries.map(([key, value]) => ({ key, value })),\n )\n .then(() => ({\n message: `Set ${entries.length} environment variable(s)`,\n }));\n }, \"Failed to set env vars\");\n case \"bulk_update_env_vars\":\n return mcpCall(\n (s) =>\n s.applications.bulkSetEnv(a.uuid, a.envVars).then(() => ({\n message: `Bulk updated ${a.envVars.length} variable(s)`,\n })),\n \"Failed to bulk update env vars\",\n );\n\n // ─── Domains ───────────────────────────────────────────────────────\n case \"set_domains\":\n return mcpCall(\n (s) =>\n s.applications\n .update(a.uuid, {\n domains: a.domains,\n isForceHttpsEnabled: a.forceHttps ?? true,\n })\n .then(() => ({\n message: `Domains set for ${a.uuid}`,\n domains: a.domains.split(\",\").map((d: string) => d.trim()),\n })),\n \"Failed to set domains\",\n );\n\n // ─── Deployment Status ─────────────────────────────────────────────\n case \"get_deployment_status\":\n return mcpCall(\n (s) =>\n s.applications\n .resolve(a.uuid)\n .then((app) => ({ status: app.status })),\n \"Failed to get status\",\n );\n\n // ─── Deployments ───────────────────────────────────────────────────\n case \"list_deployments\":\n return mcpList(\n (s) => s.deployments.active(),\n \"deployments\",\n \"Failed to list deployments\",\n );\n case \"get_deployment\":\n return mcpCall(\n (s) =>\n s.deployments.get(a.deploymentUuid).then((d) => ({ deployment: d })),\n \"Failed to get deployment\",\n );\n case \"cancel_deployment\":\n return mcpCall(\n (s) =>\n s.deployments\n .cancel(a.deploymentUuid)\n .then(() => ({ message: \"Deployment cancelled\" })),\n \"Failed to cancel deployment\",\n );\n\n // ─── Servers ───────────────────────────────────────────────────────\n case \"list_servers\":\n return mcpList(\n (s) => s.servers.list(),\n \"servers\",\n \"Failed to list servers\",\n );\n case \"get_server\":\n return mcpCall(\n (s) => s.servers.get(a.serverUuid).then((srv) => ({ server: srv })),\n \"Failed to get server\",\n );\n case \"get_server_destinations\":\n return mcpList(\n (s) => s.servers.destinations(a.serverUuid),\n \"destinations\",\n \"Failed to get destinations\",\n );\n case \"get_server_resources\":\n return mcpList(\n (s) => s.servers.resources(a.serverUuid),\n \"resources\",\n \"Failed to get server resources\",\n );\n case \"get_server_domains\":\n return mcpList(\n (s) => s.servers.domains(a.serverUuid),\n \"domains\",\n \"Failed to get server domains\",\n );\n case \"validate_server\":\n return mcpCall(\n (s) =>\n s.servers\n .validate(a.serverUuid)\n .then(() => ({ message: \"Server validated\" })),\n \"Failed to validate server\",\n );\n\n // ─── Projects ──────────────────────────────────────────────────────\n case \"list_projects\":\n return mcpList(\n (s) => s.projects.list(),\n \"projects\",\n \"Failed to list projects\",\n );\n case \"create_project\":\n return mcpCall(\n (s) =>\n s.projects.create(a.name, a.description).then((p) => ({\n message: `Project \"${a.name}\" created`,\n uuid: p.uuid,\n })),\n \"Failed to create project\",\n );\n case \"create_application\":\n return mcpCall(\n (s) =>\n s.applications\n .create({\n name: a.name,\n description: a.description,\n projectUuid: a.projectUuid,\n environmentUuid: a.environmentUuid,\n serverUuid: a.serverUuid,\n type: a.type || \"public\",\n githubAppUuid: a.githubAppUuid,\n githubRepoUrl: a.githubRepoUrl,\n branch: a.branch,\n buildPack: a.buildPack,\n portsExposes: a.portsExposes,\n dockerComposeLocation: a.dockerComposeLocation,\n dockerfileLocation: a.dockerfileLocation,\n baseDirectory: a.baseDirectory,\n })\n .then((r) => ({\n message: `Application \"${a.name}\" created`,\n uuid: r.uuid,\n })),\n \"Failed to create application\",\n );\n\n // ─── Teams ─────────────────────────────────────────────────────────\n case \"list_teams\":\n return mcpList((s) => s.teams.list(), \"teams\", \"Failed to list teams\");\n case \"get_current_team\":\n return mcpCall(\n (s) => s.teams.current().then((t) => ({ team: t })),\n \"Failed to get current team\",\n );\n case \"get_team_members\":\n return mcpList(\n (s) => s.teams.members(a.teamId),\n \"members\",\n \"Failed to get team members\",\n );\n\n // ─── Databases ─────────────────────────────────────────────────────\n case \"list_databases\":\n return mcpList(\n (s) => s.databases.list(),\n \"databases\",\n \"Failed to list databases\",\n );\n case \"get_database\":\n return mcpCall(\n (s) => s.databases.get(a.uuid).then((db) => ({ database: db })),\n \"Failed to get database\",\n );\n case \"create_database\":\n return mcpCall(\n (s) =>\n s.databases.create(a.dbType, a.data).then((r) => ({\n message: `${a.dbType} database created`,\n uuid: r.uuid,\n })),\n \"Failed to create database\",\n );\n case \"delete_database\":\n return mcpCall(\n (s) =>\n s.databases\n .delete(a.uuid)\n .then(() => ({ message: \"Database deleted\" })),\n \"Failed to delete database\",\n );\n case \"start_database\":\n return mcpCall(\n (s) =>\n s.databases\n .start(a.uuid)\n .then(() => ({ message: \"Database started\" })),\n \"Failed to start database\",\n );\n case \"stop_database\":\n return mcpCall(\n (s) =>\n s.databases\n .stop(a.uuid)\n .then(() => ({ message: \"Database stopped\" })),\n \"Failed to stop database\",\n );\n case \"restart_database\":\n return mcpCall(\n (s) =>\n s.databases\n .restart(a.uuid)\n .then(() => ({ message: \"Database restarted\" })),\n \"Failed to restart database\",\n );\n\n // ─── Services ──────────────────────────────────────────────────────\n case \"list_services\":\n return mcpList(\n (s) => s.services.list(),\n \"services\",\n \"Failed to list services\",\n );\n case \"get_service\":\n return mcpCall(\n (s) => s.services.get(a.uuid).then((svc) => ({ service: svc })),\n \"Failed to get service\",\n );\n case \"start_service\":\n return mcpCall(\n (s) =>\n s.services.start(a.uuid).then(() => ({ message: \"Service started\" })),\n \"Failed to start service\",\n );\n case \"stop_service\":\n return mcpCall(\n (s) =>\n s.services.stop(a.uuid).then(() => ({ message: \"Service stopped\" })),\n \"Failed to stop service\",\n );\n case \"restart_service\":\n return mcpCall(\n (s) =>\n s.services\n .restart(a.uuid)\n .then(() => ({ message: \"Service restarted\" })),\n \"Failed to restart service\",\n );\n case \"delete_service\":\n return mcpCall(\n (s) =>\n s.services\n .delete(a.uuid)\n .then(() => ({ message: \"Service deleted\" })),\n \"Failed to delete service\",\n );\n\n // ─── Private Keys ──────────────────────────────────────────────────\n case \"list_private_keys\":\n return mcpList(\n (s) => s.keys.list(),\n \"keys\",\n \"Failed to list private keys\",\n );\n case \"get_private_key\":\n return mcpCall(\n (s) => s.keys.get(a.uuid).then((k) => ({ privateKey: k })),\n \"Failed to get private key\",\n );\n\n // ─── Smart Resolution ──────────────────────────────────────────────\n case \"resolve_application\":\n return mcpCall(\n (s) =>\n s.applications.resolve(a.query).then((app) => ({\n application: {\n uuid: app.uuid,\n name: app.name,\n status: app.status,\n fqdn: app.fqdn,\n },\n })),\n \"Failed to resolve application\",\n );\n case \"resolve_server\":\n return mcpCall(\n (s) =>\n s.servers.resolve(a.query).then((srv) => ({\n server: {\n uuid: srv.uuid,\n name: srv.name,\n ip: srv.ip,\n is_reachable: srv.is_reachable,\n },\n })),\n \"Failed to resolve server\",\n );\n\n // ─── Diagnostics ───────────────────────────────────────────────────\n case \"diagnose_application\":\n return mcpCall((s) => s.diagnose.app(a.query), \"Diagnosis failed\");\n case \"diagnose_server\":\n return mcpCall((s) => s.diagnose.server(a.query), \"Diagnosis failed\");\n case \"find_infrastructure_issues\":\n return mcpCall(\n (s) => s.diagnose.infrastructure(),\n \"Infrastructure scan failed\",\n );\n\n // ─── Batch Operations ──────────────────────────────────────────────\n case \"restart_project_apps\":\n return mcpCall(\n (s) => s.batch.restartProject(a.projectUuid),\n \"Batch restart failed\",\n );\n case \"redeploy_project_apps\":\n return mcpCall(\n (s) => s.batch.redeployProject(a.projectUuid, a.force),\n \"Batch redeploy failed\",\n );\n case \"stop_all_apps\":\n return mcpCall((s) => s.batch.stopAll(), \"Stop all failed\");\n\n // ─── Network Diagnostics ─────────────────────────────────────────\n case \"inspect_network\":\n return mcpCall(\n (s) => s.network.inspect(a.uuid, a.servicesToTest),\n \"Network inspection failed\",\n );\n case \"analyze_deploy_failure\":\n return mcpCall(\n (s) => s.diagnose.deployFailure(a.deploymentUuid),\n \"Deploy analysis failed\",\n );\n\n // ─── Version / Health ──────────────────────────────────────────────\n case \"get_version\":\n return mcpCall(\n (s) => s.version().then((v) => ({ version: v.version })),\n \"Failed to get version\",\n );\n case \"health_check\":\n return mcpCall(\n (s) =>\n s.servers.list().then(() => ({\n status: \"healthy\",\n message: \"Coolify API is accessible\",\n })),\n \"Health check failed\",\n );\n case \"get_resource_usage\":\n return mcpCall(\n (s) =>\n s.applications\n .resolve(a.uuid)\n .then((app) => ({ status: app.status })),\n \"Failed to get resource usage\",\n );\n\n default:\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n}\n","/**\n * Operation tracing system.\n *\n * Provides step-by-step tracing for all operations across CLI, MCP, and SDK.\n * - **CLI mode**: Logs to stderr with chalk colors (no spinners in trace)\n * - **MCP mode**: Collects steps silently, returns in response\n * - **SDK mode**: Fires callback if provided, otherwise collects\n *\n * @module\n */\n\n/**\n * A single trace step.\n */\nexport interface ITraceStep {\n /** Timestamp */\n ts: string;\n /** Step label */\n step: string;\n /** Duration in ms (filled after completion) */\n durationMs?: number;\n /** Optional detail */\n detail?: string;\n}\n\n/**\n * Complete operation trace.\n */\nexport interface IOperationTrace {\n /** Operation name */\n operation: string;\n /** All steps */\n steps: ITraceStep[];\n /** Total duration */\n totalMs: number;\n /** Whether operation succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Callback for real-time trace updates.\n */\nexport type TraceCallback = (step: string, detail?: string) => void;\n\n/** Detect if running as MCP server (stdout is the transport). */\nexport function isMcpMode(): boolean {\n // MCP servers communicate over stdout — if we're piped, assume MCP\n return !process.stdout.isTTY;\n}\n\n/**\n * Operation tracer that collects steps.\n */\nexport class OperationTracer {\n private steps: ITraceStep[] = [];\n private startTime: number;\n private stepStart: number;\n private onStep?: TraceCallback;\n\n constructor(\n public readonly operation: string,\n onStep?: TraceCallback,\n ) {\n this.startTime = Date.now();\n this.stepStart = this.startTime;\n this.onStep = onStep;\n }\n\n /**\n * Records a trace step.\n *\n * @param step - Step description\n * @param detail - Optional detail\n */\n step(step: string, detail?: string): void {\n const now = Date.now();\n const traceStep: ITraceStep = {\n ts: new Date(now).toISOString(),\n step,\n durationMs: now - this.stepStart,\n detail,\n };\n this.steps.push(traceStep);\n this.stepStart = now;\n\n // Fire callback for real-time updates\n this.onStep?.(step, detail);\n\n // In TTY (CLI) mode, log to stderr so it doesn't pollute MCP stdout\n if (process.stderr.isTTY) {\n const prefix = `\\x1b[90m[${this.operation}]\\x1b[0m`;\n const elapsed = `\\x1b[33m${traceStep.durationMs}ms\\x1b[0m`;\n const detailStr = detail ? ` \\x1b[90m(${detail})\\x1b[0m` : \"\";\n process.stderr.write(`${prefix} ${step} ${elapsed}${detailStr}\\n`);\n }\n }\n\n /**\n * Finalizes the trace.\n *\n * @param success - Whether operation succeeded\n * @param error - Error message if failed\n * @returns Complete operation trace\n */\n finish(success: boolean, error?: string): IOperationTrace {\n return {\n operation: this.operation,\n steps: this.steps,\n totalMs: Date.now() - this.startTime,\n success,\n error,\n };\n }\n}\n","/**\n * Network diagnostic module.\n *\n * Uses exec to inspect Docker networks, Traefik proxy, DNS, and container connectivity.\n * All commands run inside the application container via the Coolify exec API.\n *\n * @module\n */\n\nimport { isErr, type Result, ok, err } from \"@mks2508/no-throw\";\nimport type { CoolifyService } from \"./coolify/index.js\";\nimport { OperationTracer, type IOperationTrace } from \"./trace.js\";\n\n/**\n * Container network information.\n */\nexport interface INetworkInfo {\n /** /etc/hosts entries */\n hosts: string[];\n /** DNS resolution results */\n dns: Array<{ hostname: string; resolved: boolean; ip?: string }>;\n /** Container environment variables related to networking */\n networkEnv: Record<string, string>;\n /** Reachable services (connectivity test results) */\n connectivity: Array<{\n target: string;\n reachable: boolean;\n responseTime?: number;\n }>;\n /** Container's network interfaces */\n interfaces: string[];\n /** Operation trace */\n trace: IOperationTrace;\n}\n\n/**\n * Deploy failure analysis.\n */\nexport interface IDeployFailureAnalysis {\n /** Deployment UUID */\n deploymentUuid: string;\n /** Deployment status */\n status: string;\n /** Raw build logs */\n rawLogs: string;\n /** Extracted error lines */\n errors: string[];\n /** Likely error category */\n category:\n | \"build_error\"\n | \"install_error\"\n | \"docker_error\"\n | \"network_error\"\n | \"timeout\"\n | \"unknown\";\n /** Human-readable summary */\n summary: string;\n /** Suggested fix */\n suggestion: string;\n /** Operation trace */\n trace: IOperationTrace;\n}\n\n/** Common error patterns in build logs. */\nconst ERROR_PATTERNS: Array<{\n pattern: RegExp;\n category: IDeployFailureAnalysis[\"category\"];\n summary: string;\n suggestion: string;\n}> = [\n {\n pattern: /npm ERR!|yarn error|pnpm ERR/i,\n category: \"install_error\",\n summary: \"Package installation failed\",\n suggestion:\n \"Check package.json for invalid dependencies. Try deleting lock file and rebuilding.\",\n },\n {\n pattern: /COPY failed|COPY --from.*not found|no such file/i,\n category: \"docker_error\",\n summary: \"Dockerfile COPY failed — file not found\",\n suggestion:\n \"Check Dockerfile paths and base_directory. Ensure source files exist in build context.\",\n },\n {\n pattern: /error TS\\d+|TypeError|SyntaxError|ReferenceError/i,\n category: \"build_error\",\n summary: \"TypeScript/JavaScript compilation error\",\n suggestion:\n \"Fix the type errors locally before deploying. Run `bun run typecheck`.\",\n },\n {\n pattern: /ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|getaddrinfo/i,\n category: \"network_error\",\n summary: \"Network connectivity issue during build\",\n suggestion:\n \"Server may have DNS issues or firewall blocking outbound connections. Check server network.\",\n },\n {\n pattern: /OOMKilled|out of memory|Cannot allocate memory/i,\n category: \"build_error\",\n summary: \"Out of memory during build\",\n suggestion:\n \"Server ran out of RAM. Use a build server or increase server memory.\",\n },\n {\n pattern: /context deadline exceeded|timed out/i,\n category: \"timeout\",\n summary: \"Operation timed out\",\n suggestion:\n \"Build took too long. Check if server is overloaded or network is slow.\",\n },\n {\n pattern: /permission denied|EACCES/i,\n category: \"docker_error\",\n summary: \"Permission denied\",\n suggestion:\n \"Check file permissions in Dockerfile. Ensure non-root user has access to needed paths.\",\n },\n {\n pattern: /exec.*not found|command not found/i,\n category: \"build_error\",\n summary: \"Command not found during build\",\n suggestion:\n \"A required binary is missing in the Docker image. Add it to the Dockerfile or use a different base image.\",\n },\n];\n\n/**\n * Safely execute a command, returning output or empty string on failure.\n */\nasync function safeExec(\n svc: CoolifyService,\n uuid: string,\n command: string,\n): Promise<string> {\n const result = await svc.executeCommand(uuid, command);\n if (isErr(result)) return \"\";\n return result.value.response || result.value.message || \"\";\n}\n\n/**\n * Inspects the network environment of an application container.\n *\n * @param svc - CoolifyService instance\n * @param appUuid - Application UUID\n * @param servicesToTest - Optional list of service names to test connectivity (e.g., ['db', 'redis'])\n * @returns Network diagnostic information\n */\nexport async function inspectNetwork(\n svc: CoolifyService,\n appUuid: string,\n servicesToTest: string[] = [],\n): Promise<Result<INetworkInfo, Error>> {\n const tracer = new OperationTracer(\"network:inspect\");\n\n try {\n tracer.step(\"Fetching /etc/hosts\");\n const hostsRaw = await safeExec(svc, appUuid, \"cat /etc/hosts 2>/dev/null\");\n const hosts = hostsRaw\n .split(\"\\n\")\n .filter((l) => l.trim() && !l.startsWith(\"#\"));\n\n tracer.step(\"Checking network interfaces\");\n const ifRaw = await safeExec(\n svc,\n appUuid,\n \"ip addr 2>/dev/null || ifconfig 2>/dev/null || cat /proc/net/if_inet6 2>/dev/null || echo 'no network tools'\",\n );\n const interfaces = ifRaw\n .split(\"\\n\")\n .filter((l) => l.includes(\"inet\") || l.includes(\"scope\"));\n\n tracer.step(\"Extracting network env vars\");\n const envRaw = await safeExec(\n svc,\n appUuid,\n \"env 2>/dev/null | grep -iE '(HOST|PORT|URL|DATABASE|REDIS|MONGO|POSTGRES|MYSQL|DB_|COOLIFY)' | sort\",\n );\n const networkEnv: Record<string, string> = {};\n for (const line of envRaw.split(\"\\n\").filter(Boolean)) {\n const [key, ...rest] = line.split(\"=\");\n if (key) networkEnv[key] = rest.join(\"=\");\n }\n\n tracer.step(\"Testing DNS resolution\");\n const dnsTargets = [\n ...servicesToTest,\n ...Object.values(networkEnv)\n .filter((v) => !v.includes(\"/\") && !v.includes(\":\"))\n .filter((v) => /^[a-z][a-z0-9-]*$/i.test(v)),\n ];\n const uniqueTargets = [...new Set(dnsTargets)].slice(0, 10);\n\n const dns: INetworkInfo[\"dns\"] = [];\n for (const hostname of uniqueTargets) {\n const nslookup = await safeExec(\n svc,\n appUuid,\n `getent hosts ${hostname} 2>/dev/null || nslookup ${hostname} 2>/dev/null || echo 'FAIL'`,\n );\n const resolved = !nslookup.includes(\"FAIL\") && nslookup.trim().length > 0;\n const ip = resolved ? nslookup.split(/\\s+/)[0] : undefined;\n dns.push({ hostname, resolved, ip });\n }\n\n tracer.step(\n \"Testing service connectivity\",\n `${uniqueTargets.length} targets`,\n );\n const connectivity: INetworkInfo[\"connectivity\"] = [];\n for (const target of servicesToTest) {\n const start = Date.now();\n const curlResult = await safeExec(\n svc,\n appUuid,\n `timeout 3 sh -c \"echo > /dev/tcp/${target}/80 2>/dev/null && echo OK || curl -sf --max-time 2 http://${target}/ >/dev/null 2>&1 && echo OK || echo FAIL\"`,\n );\n connectivity.push({\n target,\n reachable: curlResult.includes(\"OK\"),\n responseTime: Date.now() - start,\n });\n }\n\n const trace = tracer.finish(true);\n return ok({ hosts, dns, networkEnv, connectivity, interfaces, trace });\n } catch (error) {\n const trace = tracer.finish(\n false,\n error instanceof Error ? error.message : String(error),\n );\n return err(new Error(`Network inspection failed: ${trace.error}`));\n }\n}\n\n/**\n * Analyzes a failed deployment, extracting errors from build logs.\n *\n * @param svc - CoolifyService instance\n * @param deploymentUuid - Deployment UUID\n * @returns Failure analysis with categorized errors\n */\nexport async function analyzeDeployFailure(\n svc: CoolifyService,\n deploymentUuid: string,\n): Promise<Result<IDeployFailureAnalysis, Error>> {\n const tracer = new OperationTracer(\"deploy:analyze\");\n\n try {\n tracer.step(\"Fetching deployment details\");\n const deployResult = await svc.getDeploymentLogs(deploymentUuid);\n if (isErr(deployResult)) {\n return err(deployResult.error);\n }\n\n const { status, logs: rawLogs } = deployResult.value;\n\n tracer.step(\"Extracting error lines\", `${rawLogs.length} chars`);\n const lines = rawLogs.split(\"\\n\");\n const errors = lines.filter(\n (l) =>\n /error|ERR!|failed|FAIL|fatal|panic|exception/i.test(l) &&\n !/no error|success/i.test(l),\n );\n\n tracer.step(\"Categorizing error\");\n let matchedPattern = ERROR_PATTERNS.find((p) => p.pattern.test(rawLogs));\n\n if (!matchedPattern) {\n matchedPattern = {\n pattern: /./,\n category: \"unknown\",\n summary: \"Unknown build failure\",\n suggestion:\n \"Check the full build logs with `build-logs <deployment-uuid>` for details.\",\n };\n }\n\n const trace = tracer.finish(true);\n return ok({\n deploymentUuid,\n status,\n rawLogs,\n errors: errors.slice(0, 20),\n category: matchedPattern.category,\n summary: matchedPattern.summary,\n suggestion: matchedPattern.suggestion,\n trace,\n });\n } catch (error) {\n const trace = tracer.finish(\n false,\n error instanceof Error ? error.message : String(error),\n );\n return err(new Error(`Deploy analysis failed: ${trace.error}`));\n }\n}\n","/**\n * .coolify.json state loader for CLI.\n *\n * When running CLI commands from a project directory that has a .coolify.json\n * (generated by create-bunspace or first deploy), reads the state to auto-fill\n * UUIDs so users don't need to copy-paste them.\n *\n * @module\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * State stored in .coolify.json (generated by create-bunspace deployer or init command).\n *\n * This file links a local directory to a Coolify deployment, storing all necessary\n * UUIDs and metadata for CLI commands to work without manual UUID entry.\n */\nexport interface ICoolifyDeployState {\n /** Application UUID in Coolify */\n appUuid: string;\n /** Application name (for display purposes) */\n appName?: string;\n /** Server UUID */\n serverUuid: string;\n /** Server name (for display purposes) */\n serverName?: string;\n /** Project UUID */\n projectUuid: string;\n /** Project name (for display purposes) */\n projectName?: string;\n /** Environment UUID */\n environmentUuid: string;\n /** Environment name (for display purposes) */\n environmentName?: string;\n /** Domain if configured */\n domain?: string;\n /** Docker compose or Dockerfile path */\n dockerComposePath?: string;\n /** Base directory for build context */\n baseDirectory?: string;\n /** Git branch */\n branch?: string;\n /** Git repository URL */\n gitRepository?: string;\n /** Application source type (github-app, deploy-key, docker-image, etc.) */\n sourceType?: string;\n /** Application type (legacy, may be undefined) */\n type?: string;\n /** Build pack (dockerfile, nixpacks, static, dockercompose) */\n buildPack?: string;\n /** Auto-deploy enabled */\n autoDeployEnabled?: boolean;\n /** When this state was last updated */\n updatedAt?: string;\n /** Coolify instance URL */\n coolifyUrl?: string;\n}\n\n/**\n * Multi-app state for monorepos deploying multiple services from one repo.\n *\n * Stored alongside or instead of the single-app state in .coolify.json.\n */\nexport interface ICoolifyMultiAppState {\n /** All apps deployed from this repo */\n apps: Array<{\n /** Application UUID in Coolify */\n uuid: string;\n /** Application name */\n name: string;\n /** Service role (e.g. \"backend\", \"admin\", \"docs\", \"proxy\") */\n service: string;\n /** Domain if configured */\n domain?: string;\n /** Dockerfile path relative to repo root */\n dockerfile?: string;\n /** Exposed port */\n port?: number;\n }>;\n /** Server UUID */\n serverUuid: string;\n /** Server name (for display purposes) */\n serverName?: string;\n /** Project UUID */\n projectUuid: string;\n /** Project name (for display purposes) */\n projectName?: string;\n /** Environment UUID */\n environmentUuid: string;\n /** Environment name (for display purposes) */\n environmentName?: string;\n /** Git branch */\n branch?: string;\n /** Git repository URL */\n gitRepository?: string;\n /** Coolify instance URL */\n coolifyUrl?: string;\n /** When this state was last updated */\n updatedAt?: string;\n}\n\nconst STATE_FILE = \".coolify.json\";\n\n/**\n * Loads .coolify.json from the current working directory (single-app format).\n *\n * Handles both single-app and multi-app formats. For multi-app state with\n * exactly one app, returns a synthesized single-app state for backward compat.\n *\n * @returns The deploy state if found, null otherwise\n */\nexport function loadCoolifyState(): ICoolifyDeployState | null {\n const statePath = join(process.cwd(), STATE_FILE);\n\n if (!existsSync(statePath)) {\n return null;\n }\n\n try {\n const content = readFileSync(statePath, \"utf-8\");\n const state = JSON.parse(content);\n\n // Multi-app format — synthesize single-app state if exactly 1 app\n if (Array.isArray(state.apps)) {\n if (state.apps.length === 1) {\n const app = state.apps[0];\n return {\n appUuid: app.uuid,\n appName: app.name,\n serverUuid: state.serverUuid,\n serverName: state.serverName,\n projectUuid: state.projectUuid,\n projectName: state.projectName,\n environmentUuid: state.environmentUuid,\n environmentName: state.environmentName,\n domain: app.domain,\n branch: state.branch,\n gitRepository: state.gitRepository,\n coolifyUrl: state.coolifyUrl,\n updatedAt: state.updatedAt,\n };\n }\n // Multi-app with multiple apps — cannot auto-select\n return null;\n }\n\n // Single-app format\n if (!state.appUuid) {\n return null;\n }\n\n return state as ICoolifyDeployState;\n } catch {\n return null;\n }\n}\n\n/**\n * Loads .coolify.json in multi-app format.\n *\n * If the file is in single-app format, returns null (use loadCoolifyState instead).\n *\n * @returns The multi-app state if found, null otherwise\n */\nexport function loadMultiAppState(): ICoolifyMultiAppState | null {\n const statePath = join(process.cwd(), STATE_FILE);\n\n if (!existsSync(statePath)) {\n return null;\n }\n\n try {\n const content = readFileSync(statePath, \"utf-8\");\n const state = JSON.parse(content);\n\n if (!Array.isArray(state.apps)) {\n return null;\n }\n\n return state as ICoolifyMultiAppState;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes .coolify.json in multi-app format to the current working directory.\n *\n * @param state - The multi-app state to write\n */\nexport function writeMultiAppState(state: ICoolifyMultiAppState): void {\n const statePath = join(process.cwd(), STATE_FILE);\n writeFileSync(statePath, JSON.stringify(state, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Writes .coolify.json to the current working directory.\n *\n * @param state - The state to write\n */\nexport function writeCoolifyState(state: ICoolifyDeployState): void {\n const statePath = join(process.cwd(), STATE_FILE);\n writeFileSync(statePath, JSON.stringify(state, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Resolves a UUID argument — if not provided, tries to read from .coolify.json.\n *\n * Supports both single-app and multi-app state formats. For multi-app state\n * with exactly one app, auto-selects that app. For multiple apps, returns null\n * (user must specify explicitly).\n *\n * @param uuid - UUID from CLI argument (may be undefined)\n * @param field - Which field to read from .coolify.json (default: appUuid)\n * @returns The resolved UUID or null if not found\n */\nexport function resolveUuid(\n uuid: string | undefined,\n field: keyof ICoolifyDeployState = \"appUuid\",\n): string | null {\n // Only return directly if it looks like a UUID (lowercase alphanumeric, 16-40 chars)\n // Names like \"mks-backend\" should fall through to .coolify.json or name resolver\n if (uuid && /^[a-z0-9]{16,40}$/.test(uuid)) return uuid;\n\n // Try single-app state first (also handles multi-app with 1 app)\n const state = loadCoolifyState();\n if (state) {\n const value = state[field];\n return typeof value === \"string\" ? value : null;\n }\n\n // Try multi-app state — only auto-resolve if exactly 1 app\n const multiState = loadMultiAppState();\n if (multiState && multiState.apps.length === 1 && field === \"appUuid\") {\n return multiState.apps[0].uuid;\n }\n\n return null;\n}\n","/**\n * @mks2508/coolify-mks-cli-mcp — SDK, CLI, and MCP server for Coolify.\n *\n * Use as a library (SDK):\n * ```typescript\n * import { Coolify } from '@mks2508/coolify-mks-cli-mcp'\n *\n * const coolify = new Coolify({ url: 'https://coolify.example.com', token: '...' })\n * const apps = await coolify.applications.list()\n * const app = await coolify.applications.resolve('my-app')\n * await coolify.applications.deploy(app.uuid)\n * ```\n *\n * Use as MCP server:\n * ```bash\n * coolify-mcp-server # stdio transport\n * ```\n *\n * Use as CLI:\n * ```bash\n * coolify-mcp list\n * coolify-mcp deploy\n * coolify-mcp logs\n * ```\n *\n * @module\n */\n\n// ─── SDK: Coolify (primary export) ───────────────────────────────────────────\n\nexport { Coolify, type ICoolifyOptions } from \"./sdk.js\";\n\n// ─── Internal CoolifyService (for MCP/CLI, advanced usage) ──────────────────\n\nexport {\n CoolifyService,\n getCoolifyService,\n type ICoolifyEnvVar,\n} from \"./coolify/index.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type {\n ICoolifyServer,\n ICoolifyServerResource,\n ICoolifyServerDomain,\n ICoolifyDestination,\n ICoolifyProject,\n ICoolifyTeam,\n ICoolifyApplication,\n ICoolifyDatabase,\n ICoolifyDatabaseBackup,\n ICoolifyService as ICoolifyServiceType,\n ICoolifyPrivateKey,\n ICoolifyDeployment,\n ICoolifyVersion,\n ICoolifyAppOptions,\n ICoolifyAppResult,\n ICoolifyDeployOptions,\n ICoolifyDeployResult,\n ICoolifyDeleteResult,\n ICoolifyUpdateOptions,\n ICoolifyLogsOptions,\n ICoolifyLogs,\n ICoolifyEnvironment,\n IProgressCallback,\n TCoolifyApplicationType,\n} from \"./coolify/types.js\";\n\n// ─── MCP Tools (for building custom MCP servers) ─────────────────────────────\n\nexport { coolifyTools } from \"./tools/definitions.js\";\nexport { handleToolCall } from \"./tools/handlers.js\";\n\n// ─── Network diagnostics + operation tracing ─────────────────────────────────\n\nexport { inspectNetwork, analyzeDeployFailure } from \"./network.js\";\nexport type { INetworkInfo, IDeployFailureAnalysis } from \"./network.js\";\nexport { OperationTracer, isMcpMode } from \"./trace.js\";\nexport type { ITraceStep, IOperationTrace, TraceCallback } from \"./trace.js\";\n\n// ─── .coolify.json state (for scaffolder integration) ────────────────────────\n\nexport {\n loadCoolifyState,\n resolveUuid,\n type ICoolifyDeployState,\n} from \"./cli/coolify-state.js\";\n"],"x_google_ignoreList":[0,1,2,3,4],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,GAAG,OAAO;AAClB,QAAO;EACN,IAAI;EACJ;CACA;AACD;;;;;;;;;;;;;;;AAeD,SAAS,IAAI,OAAO;AACnB,QAAO;EACN,IAAI;EACJ;CACA;AACD;;;;;;;;;;;;;;;;;;;AAwCD,SAAS,MAAM,QAAQ;AACtB,SAAQ,OAAO;AACf;;;;;AClFD,SAAS,eAAe,UAAU;CAChC,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;EAEA;EAEA;EACA;EACA;EACA;CACD;AACD,QAAO,iBAAiB,KAAK,CAAC,YAAY,QAAQ,KAAK,SAAS,CAAC;AAClE;AACD,SAAS,qBAAqB,UAAU;CACtC,MAAM,WAAW,SAAS,MAAM,QAAQ,CAAC,KAAK,IAAI;AAClD,QAAO,SAAS,QAAQ,cAAc,MAAM,CAAC,QAAQ,iBAAiB,MAAM,CAAC,QAAQ,gBAAgB,MAAM,CAAC,QAAQ,oBAAoB,MAAM,CAAC,QAAQ,4BAA4B,YAAY;AAChM;AACD,SAAS,kBAAkB;AACzB,KAAI;EACF,MAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAK,MACH,QAAO;EAET,MAAM,QAAQ,MAAM,MAAM,KAAK,CAAC,OAAO,CAAC,SAAS,KAAK,MAAM,CAAC;AAC7D,OAAK,IAAI,IAAI,GAAG,IA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AAW;GACT,MAAM;GACN,OAAO;GAEP,MAAM;GACN,MAAM;EACP;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;EACV;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GAEP,SAAS;EACV;EACD,SAAS;GACP,MAAM;GACN,OAAO;GAEP,MAAM;GACN,MAAM;EACP;EACD,UAAU;GACR,MAAM;GACN,OAAO;GAEP,MAAM;GACN,MAAM;EACP;CACF;CAID,WAAW;EACT,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW;GACT,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,OAAO;EACR;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;EACV;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GACP,YAAY;GACZ,QAAQ;GACR,OAAO;EACR;EACD,SAAS;GACP,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,UAAU,EACR,MAAM,MAEP;EACD,UAAU;EACV,cAAc;CACf;CAID,eAAe;EACb,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW;GACT,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,OAAO;EACR;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;EACV;EACD,QAAQ;GACN,MAAM;GACN,OAAO;GACP,SAAS;EACV;EACD,SAAS;GACP,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;EACP;EACD,UAAU;GACR,MAAM;GACN,OAAO;GACP,MAAM;GACN,MAAM;GACN,OAAO;EACR;EACD,UAAU;EACV,cAAc;CACf;CAID,SAAS;EACP,QAAQ;GACN,SAAS;GACT,cAAc;GACd,aAAa;EACd;EACD,WAAW,EACT,MAAM,MAEP;EACD,OAAO;GACL,MAAM;GACN,OAAO;GACP,WAAW;GACX,SAAS;GACT,QAAQ;GACR,YAAY;EACb;EACD,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ACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,QAAQ;KACN,MAAM;KACN,aAAa;IACd;IACD,WAAW;KACT,MAAM;KACN,aAAa;IACd;GACF;EACF;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aACE;IACH;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,OAAO;KACL,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,WAAW;KACT,MAAM;KACN,aAAa;KACb,MAAM;MAAC;MAAc;MAAY;MAAU;KAAgB;IAC5D;IACD,WAAW;KACT,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,gBAAgB;KACd,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;IACD,SAAS;KACP,MAAM;KACN,aACE;IACH;IACD,qBAAqB;KACnB,MAAM;KACN,aAAa;IACd;IACD,qBAAqB;KACnB,MAAM;KACN,aAAa;IACd;IACD,oBAAoB;KAClB,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;IACD,sBAAsB;KACpB,MAAM;KACN,aACE;IACH;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;;;;;EAQd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,SAAS;KACP,MAAM;KACN,aACE;IACH;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACb,SAAS;IACV;GACF;GACD,UAAU,CAAC,QAAQ,SAAU;EAC9B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,iBAAiB;KACf,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,eAAe;KACb,MAAM;KACN,aACE;IACH;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACb,SAAS;IACV;IACD,WAAW;KACT,MAAM;KACN,aAAa;KACb,MAAM;MAAC;MAAc;MAAY;MAAU;KAAgB;KAC3D,SAAS;IACV;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,MAAM;MACJ;MACA;MACA;MACA;MACA;MACA;KACD;KACD,SAAS;IACV;IACD,uBAAuB;KACrB,MAAM;KACN,aACE;IACH;IACD,oBAAoB;KAClB,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;IACD,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,eAAe;KACb,MAAM;KACN,aACE;IACH;IACD,cAAc;KACZ,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,QAAQ,YAAa;EACjC;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,aAAa;KACX,MAAM;KACN,aAAa;IACd;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,gBAAgB;IACd,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,gBAAiB;EAC7B;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;KACb,QAAQ;IACT;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,SAAS;IACV;IACD,MAAM;KACJ,MAAM;KACN,aAAa;KACb,SAAS;IACV;GACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACb,QAAQ;GACT,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY;IACV,MAAM;KACJ,MAAM;KACN,aAAa;IACd;IACD,SAAS;KACP,MAAM;KACN,aACE;IACH;GACF;GACD,UAAU,CAAC,QAAQ,SAAU;EAC9B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,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,YAAa;EACzB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,gBAAgB;IACd,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,gBAAiB;EAC7B;CACF;CAKD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,QAAQ;IACN,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,QAAS;EACrB;CACF;CAKD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,CAAE;EACf;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,MAAO;EACnB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CACD;EACE,MAAM;EACN,cAAc;EACd,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CAKD;EACE,MAAM;EACN,cAAc;;;;EAId,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IACL,MAAM;IACN,aAAa;GACd,EACF;GACD,UAAU,CAAC,OAAQ;EACpB;CACF;CACD;EACE,MAAM;EACN,cAAc;;;EAGd,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAA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