@logtape/pretty 1.1.0-dev.306 → 1.1.0-dev.315

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -109,7 +109,10 @@ const formatter = getPrettyFormatter({
109
109
  categoryTruncate: "middle", // "middle" | "end" | false
110
110
 
111
111
  // Word wrapping
112
- wordWrap: true // true | false | number
112
+ wordWrap: true, // true | false | number
113
+
114
+ // Show properties
115
+ properties: true,
113
116
  });
114
117
  ~~~~
115
118
 
@@ -252,6 +255,15 @@ getPrettyFormatter({
252
255
  })
253
256
  ~~~~
254
257
 
258
+ ### Properties display
259
+
260
+ ~~~~ typescript
261
+ // Show properties below the message
262
+ getPrettyFormatter({
263
+ properties: true, // Show properties
264
+ })
265
+ ~~~~
266
+
255
267
 
256
268
  Advanced usage
257
269
  --------------
package/deno.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/pretty",
3
- "version": "1.1.0-dev.306+60b6894a",
3
+ "version": "1.1.0-dev.315+fc46f65c",
4
4
  "license": "MIT",
5
5
  "exports": "./mod.ts",
6
6
  "imports": {
@@ -3,6 +3,7 @@ const require_terminal = require('./terminal.cjs');
3
3
  const require_truncate = require('./truncate.cjs');
4
4
  const require_wcwidth = require('./wcwidth.cjs');
5
5
  const require_wordwrap = require('./wordwrap.cjs');
6
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
6
7
  const __util = require_rolldown_runtime.__toESM(require("#util"));
7
8
 
8
9
  //#region formatter.ts
@@ -176,7 +177,7 @@ function normalizeIconSpacing(iconMap) {
176
177
  * @since 1.0.0
177
178
  */
178
179
  function getPrettyFormatter(options = {}) {
179
- const { timestamp = "none", timestampColor = "rgb(100,116,139)", timestampStyle = "dim", level: levelFormat = "full", levelColors = {}, levelStyle = "underline", icons = true, categorySeparator = "·", categoryColor = "rgb(100,116,139)", categoryColorMap = /* @__PURE__ */ new Map(), categoryStyle = ["dim", "italic"], categoryWidth = 20, categoryTruncate = "middle", messageColor = "rgb(148,163,184)", messageStyle = "dim", colors: useColors = true, align = true, inspectOptions = {}, wordWrap = true } = options;
180
+ const { timestamp = "none", timestampColor = "rgb(100,116,139)", timestampStyle = "dim", level: levelFormat = "full", levelColors = {}, levelStyle = "underline", icons = true, categorySeparator = "·", categoryColor = "rgb(100,116,139)", categoryColorMap = /* @__PURE__ */ new Map(), categoryStyle = ["dim", "italic"], categoryWidth = 20, categoryTruncate = "middle", messageColor = "rgb(148,163,184)", messageStyle = "dim", colors: useColors = true, align = true, inspectOptions = {}, properties = false, wordWrap = true } = options;
180
181
  const baseIconMap = icons === false ? {
181
182
  trace: "",
182
183
  debug: "",
@@ -276,14 +277,7 @@ function getPrettyFormatter(options = {}) {
276
277
  else if (wordWrap === true) wordWrapWidth = require_terminal.getOptimalWordWrapWidth(80);
277
278
  else wordWrapWidth = 80;
278
279
  const categoryPatterns = prepareCategoryPatterns(categoryColorMap);
279
- const allLevels = [
280
- "trace",
281
- "debug",
282
- "info",
283
- "warning",
284
- "error",
285
- "fatal"
286
- ];
280
+ const allLevels = [...(0, __logtape_logtape.getLogLevels)()];
287
281
  const levelWidth = Math.max(...allLevels.map((l) => formatLevel(l).length));
288
282
  return (record) => {
289
283
  const icon = iconMap[record.level] || "";
@@ -341,15 +335,31 @@ function getPrettyFormatter(options = {}) {
341
335
  const paddedLevel = formattedLevel.padEnd(levelWidth + levelColorLength);
342
336
  const paddedCategory = formattedCategory.padEnd(categoryWidth + categoryColorLength);
343
337
  let result = `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} ${formattedMessage}`;
344
- if (wordWrapEnabled || message.includes("\n")) result = require_wordwrap.wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, message);
338
+ const indentWidth = require_wcwidth.getDisplayWidth(require_wcwidth.stripAnsi(`${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} `));
339
+ if (wordWrapEnabled || message.includes("\n")) result = require_wordwrap.wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, indentWidth);
340
+ if (properties) result += formatProperties(record, indentWidth, wordWrapEnabled ? wordWrapWidth : Infinity, useColors, inspectOptions);
345
341
  return result + "\n";
346
342
  } else {
347
343
  let result = `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} ${formattedMessage}`;
348
- if (wordWrapEnabled || message.includes("\n")) result = require_wordwrap.wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, message);
344
+ const indentWidth = require_wcwidth.getDisplayWidth(require_wcwidth.stripAnsi(`${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} `));
345
+ if (wordWrapEnabled || message.includes("\n")) result = require_wordwrap.wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, indentWidth);
346
+ if (properties) result += formatProperties(record, indentWidth, wordWrapEnabled ? wordWrapWidth : Infinity, useColors, inspectOptions);
349
347
  return result + "\n";
350
348
  }
351
349
  };
352
350
  }
351
+ function formatProperties(record, indentWidth, maxWidth, useColors, inspectOptions) {
352
+ let result = "";
353
+ for (const prop in record.properties) {
354
+ const propValue = record.properties[prop];
355
+ const pad = indentWidth - require_wcwidth.getDisplayWidth(prop) - 2;
356
+ result += "\n" + require_wordwrap.wrapText(`${" ".repeat(pad)}${useColors ? DIM : ""}${prop}:${useColors ? RESET : ""} ${(0, __util.inspect)(propValue, {
357
+ colors: useColors,
358
+ ...inspectOptions
359
+ })}`, maxWidth, indentWidth);
360
+ }
361
+ return result;
362
+ }
353
363
  /**
354
364
  * A pre-configured beautiful console formatter for local development.
355
365
  *
@@ -366,6 +366,17 @@ interface PrettyFormatterOptions extends Omit<TextFormatterOptions, "category" |
366
366
  */
367
367
  readonly compact?: boolean;
368
368
  };
369
+ /**
370
+ * Configuration to always render structured data.
371
+ *
372
+ * If set to `true`, any structured data that is logged will
373
+ * always be rendered. This can be very verbose. Make sure
374
+ * to configure `inspectOptions` properly for your usecase.
375
+ *
376
+ * @default `false`
377
+ * @since 1.1.0
378
+ */
379
+ readonly properties?: boolean;
369
380
  /**
370
381
  * Enable word wrapping for long messages.
371
382
  *
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.d.cts","names":[],"sources":["../formatter.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQ0E;AAiChE,cAPJ,MAqBI,EAAA;EAKE,SAAK,KAAA,EAAA,WACA;EAsBL,SAAA,IAAA,EAAA,WAAgB;EAAA,SAAA,GAAA,EAAA,WAAA;EAAA,SAA0B,MAAA,EAAA,WAAA;EAAK,SAA5B,SAAA,EAAA,WAAA;EAAG,SAAA,aAAA,EAAA,WAAA;AAalC,CAAA;;;;AAA8D,cAlDxD,UAkDwD,EAAA;EAuJ7C,SAAA,KAAA,EAAA,YACf;EAAA,SAAA,GAAA,EAAA,YAAA;EAAA,SAAa,KAAA,EAAA,YAAA;EAAoB,SAiBP,MAAA,EAAA,YAAA;EAAK,SAoBL,IAAA,EAAA,YAAA;EAAK,SAqBO,OAAA,EAAA,YAAA;EAAQ,SAAE,IAAA,EAAA,YAAA;EAAK,SAAtB,KAAA,EAAA,YAAA;CAAM;;;;AA6CV,KAnSjB,KAAA,GAmSiB,MAAA,OAlSZ,UAkSY,GAAA,OAAA,MAAA,IAAA,MAAA,IAAA,MAAA,GAAA,GAAA,IAAA,MAAA,EAAA,GAAA,IAAA;;;;;;;;AAvGf;AAyYd;;;;AAEgB;AA4VhB;;;;KA54BY,gBAAA,GAAmB,uBAAuB;;;;KAa1C,KAAA,gBAAqB,uBAAuB;;;;;;;;;;;UAuJvC,sBAAA,SACP,KAAK;;;;;;;;;;;;;;;;;4BAiBa;;;;;;;;;;;;;;;;;;;4BAoBA;;;;;;;;;;;;;;;;;;;;yBAqBH,QAAQ,OAAO,UAAU;;;;;;;;;;;;;;;;;;;wBAoB1B;;;;;;;;;;;;;;;;;;;;;;;;6BAyBK,QAAQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAqCjB;;;;;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AA,gBAAqB,uBAAuB;;;;;;;;;;;UAuJvC,sBAAA,SACP,KAAK;;;;;;;;;;;;;;;;;4BAiBa;;;;;;;;;;;;;;;;;;;4BAoBA;;;;;;;;;;;;;;;;;;;;yBAqBH,QAAQ,OAAO,UAAU;;;;;;;;;;;;;;;;;;;wBAoB1B;;;;;;;;;;;;;;;;;;;;;;;;6BAyBK,QAAQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2BAqCjB;;;;;;;;;;;;;;;;;;8BAmBG;;;;;;;;;;;;;;;;;;;2BAoBH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BA+BG;;;;;;;;;;;;;;;;;0BAkBJ;;;;;;;;;;;;;;;;;;;0BAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6JV,kBAAA,WACL,yBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0YU,iBAAiB"}
@@ -366,6 +366,17 @@ interface PrettyFormatterOptions extends Omit<TextFormatterOptions, "category" |
366
366
  */
367
367
  readonly compact?: boolean;
368
368
  };
369
+ /**
370
+ * Configuration to always render structured data.
371
+ *
372
+ * If set to `true`, any structured data that is logged will
373
+ * always be rendered. This can be very verbose. Make sure
374
+ * to configure `inspectOptions` properly for your usecase.
375
+ *
376
+ * @default `false`
377
+ * @since 1.1.0
378
+ */
379
+ readonly properties?: boolean;
369
380
  /**
370
381
  * Enable word wrapping for long messages.
371
382
  *
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.d.ts","names":[],"sources":["../formatter.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQ0E;AAiChE,cAPJ,MAqBI,EAAA;EAKE,SAAK,KAAA,EAAA,WACA;EAsBL,SAAA,IAAA,EAAA,WAAgB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;;;;;;;;;;;;2BAqCjB;;;;;;;;;;;;;;;;;;8BAmBG;;;;;;;;;;;;;;;;;;;2BAoBH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8BA+BG;;;;;;;;;;;;;;;;;0BAkBJ;;;;;;;;;;;;;;;;;;;0BAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6JV,kBAAA,WACL,yBACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0YU,iBAAiB"}
package/dist/formatter.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { getOptimalWordWrapWidth } from "./terminal.js";
2
2
  import { truncateCategory } from "./truncate.js";
3
- import { getDisplayWidth } from "./wcwidth.js";
3
+ import { getDisplayWidth, stripAnsi } from "./wcwidth.js";
4
4
  import { wrapText } from "./wordwrap.js";
5
+ import { getLogLevels } from "@logtape/logtape";
5
6
  import { inspect } from "#util";
6
7
 
7
8
  //#region formatter.ts
@@ -175,7 +176,7 @@ function normalizeIconSpacing(iconMap) {
175
176
  * @since 1.0.0
176
177
  */
177
178
  function getPrettyFormatter(options = {}) {
178
- const { timestamp = "none", timestampColor = "rgb(100,116,139)", timestampStyle = "dim", level: levelFormat = "full", levelColors = {}, levelStyle = "underline", icons = true, categorySeparator = "·", categoryColor = "rgb(100,116,139)", categoryColorMap = /* @__PURE__ */ new Map(), categoryStyle = ["dim", "italic"], categoryWidth = 20, categoryTruncate = "middle", messageColor = "rgb(148,163,184)", messageStyle = "dim", colors: useColors = true, align = true, inspectOptions = {}, wordWrap = true } = options;
179
+ const { timestamp = "none", timestampColor = "rgb(100,116,139)", timestampStyle = "dim", level: levelFormat = "full", levelColors = {}, levelStyle = "underline", icons = true, categorySeparator = "·", categoryColor = "rgb(100,116,139)", categoryColorMap = /* @__PURE__ */ new Map(), categoryStyle = ["dim", "italic"], categoryWidth = 20, categoryTruncate = "middle", messageColor = "rgb(148,163,184)", messageStyle = "dim", colors: useColors = true, align = true, inspectOptions = {}, properties = false, wordWrap = true } = options;
179
180
  const baseIconMap = icons === false ? {
180
181
  trace: "",
181
182
  debug: "",
@@ -275,14 +276,7 @@ function getPrettyFormatter(options = {}) {
275
276
  else if (wordWrap === true) wordWrapWidth = getOptimalWordWrapWidth(80);
276
277
  else wordWrapWidth = 80;
277
278
  const categoryPatterns = prepareCategoryPatterns(categoryColorMap);
278
- const allLevels = [
279
- "trace",
280
- "debug",
281
- "info",
282
- "warning",
283
- "error",
284
- "fatal"
285
- ];
279
+ const allLevels = [...getLogLevels()];
286
280
  const levelWidth = Math.max(...allLevels.map((l) => formatLevel(l).length));
287
281
  return (record) => {
288
282
  const icon = iconMap[record.level] || "";
@@ -340,15 +334,31 @@ function getPrettyFormatter(options = {}) {
340
334
  const paddedLevel = formattedLevel.padEnd(levelWidth + levelColorLength);
341
335
  const paddedCategory = formattedCategory.padEnd(categoryWidth + categoryColorLength);
342
336
  let result = `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} ${formattedMessage}`;
343
- if (wordWrapEnabled || message.includes("\n")) result = wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, message);
337
+ const indentWidth = getDisplayWidth(stripAnsi(`${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} `));
338
+ if (wordWrapEnabled || message.includes("\n")) result = wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, indentWidth);
339
+ if (properties) result += formatProperties(record, indentWidth, wordWrapEnabled ? wordWrapWidth : Infinity, useColors, inspectOptions);
344
340
  return result + "\n";
345
341
  } else {
346
342
  let result = `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} ${formattedMessage}`;
347
- if (wordWrapEnabled || message.includes("\n")) result = wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, message);
343
+ const indentWidth = getDisplayWidth(stripAnsi(`${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} `));
344
+ if (wordWrapEnabled || message.includes("\n")) result = wrapText(result, wordWrapEnabled ? wordWrapWidth : Infinity, indentWidth);
345
+ if (properties) result += formatProperties(record, indentWidth, wordWrapEnabled ? wordWrapWidth : Infinity, useColors, inspectOptions);
348
346
  return result + "\n";
349
347
  }
350
348
  };
351
349
  }
350
+ function formatProperties(record, indentWidth, maxWidth, useColors, inspectOptions) {
351
+ let result = "";
352
+ for (const prop in record.properties) {
353
+ const propValue = record.properties[prop];
354
+ const pad = indentWidth - getDisplayWidth(prop) - 2;
355
+ result += "\n" + wrapText(`${" ".repeat(pad)}${useColors ? DIM : ""}${prop}:${useColors ? RESET : ""} ${inspect(propValue, {
356
+ colors: useColors,
357
+ ...inspectOptions
358
+ })}`, maxWidth, indentWidth);
359
+ }
360
+ return result;
361
+ }
352
362
  /**
353
363
  * A pre-configured beautiful console formatter for local development.
354
364
  *
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.js","names":["color: Color","style: Style","categoryColorMap: CategoryColorMap","patterns: CategoryPattern[]","category: readonly string[]","prefix: readonly string[]","defaultIcons: Record<LogLevel, string>","iconMap: Record<LogLevel, string>","options: PrettyFormatterOptions","baseIconMap: Record<LogLevel, string>","resolvedLevelColors: Record<LogLevel, Color>","levelMappings: Record<string, Record<LogLevel, string>>","level: LogLevel","timestampFormatters: Record<string, (ts: number) => string>","timestampFn: ((ts: number) => string | null) | null","wordWrapWidth: number","allLevels: LogLevel[]","record: LogRecord","prettyFormatter: TextFormatter"],"sources":["../formatter.ts"],"sourcesContent":["import type {\n LogLevel,\n LogRecord,\n TextFormatter,\n TextFormatterOptions,\n} from \"@logtape/logtape\";\nimport { inspect } from \"#util\";\nimport { getOptimalWordWrapWidth } from \"./terminal.ts\";\nimport { truncateCategory, type TruncationStrategy } from \"./truncate.ts\";\nimport { getDisplayWidth } from \"./wcwidth.ts\";\nimport { wrapText } from \"./wordwrap.ts\";\n\n/**\n * ANSI escape codes for styling\n */\nconst RESET = \"\\x1b[0m\";\nconst DIM = \"\\x1b[2m\";\n\n// Default true color values (referenced in JSDoc)\nconst defaultColors = {\n trace: \"rgb(167,139,250)\", // Light purple\n debug: \"rgb(96,165,250)\", // Light blue\n info: \"rgb(52,211,153)\", // Emerald\n warning: \"rgb(251,191,36)\", // Amber\n error: \"rgb(248,113,113)\", // Light red\n fatal: \"rgb(220,38,38)\", // Dark red\n category: \"rgb(100,116,139)\", // Slate\n message: \"rgb(148,163,184)\", // Light slate\n timestamp: \"rgb(100,116,139)\", // Slate\n} as const;\n\n/**\n * ANSI style codes\n */\nconst styles = {\n reset: RESET,\n bold: \"\\x1b[1m\",\n dim: DIM,\n italic: \"\\x1b[3m\",\n underline: \"\\x1b[4m\",\n strikethrough: \"\\x1b[9m\",\n} as const;\n\n/**\n * Standard ANSI colors (16-color)\n */\nconst ansiColors = {\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} as const;\n\n/**\n * Color type definition\n */\nexport type Color =\n | keyof typeof ansiColors\n | `rgb(${number},${number},${number})`\n | `#${string}`\n | null;\n\n/**\n * Category color mapping for prefix-based coloring.\n *\n * Maps category prefixes (as arrays) to colors. The formatter will match\n * categories against these prefixes and use the corresponding color.\n * Longer/more specific prefixes take precedence over shorter ones.\n *\n * @example\n * ```typescript\n * new Map([\n * [[\"app\", \"auth\"], \"#ff6b6b\"], // app.auth.* -> red\n * [[\"app\", \"db\"], \"#4ecdc4\"], // app.db.* -> teal\n * [[\"app\"], \"#45b7d1\"], // app.* (fallback) -> blue\n * [[\"lib\"], \"#96ceb4\"], // lib.* -> green\n * ])\n * ```\n */\nexport type CategoryColorMap = Map<readonly string[], Color>;\n\n/**\n * Internal representation of category prefix patterns\n */\ntype CategoryPattern = {\n prefix: readonly string[];\n color: Color;\n};\n\n/**\n * Style type definition - supports single styles, arrays of styles, or null\n */\nexport type Style = keyof typeof styles | (keyof typeof styles)[] | null;\n\n// Pre-compiled regex patterns for color parsing\nconst RGB_PATTERN = /^rgb\\((\\d+),(\\d+),(\\d+)\\)$/;\nconst HEX_PATTERN = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\n/**\n * Helper function to convert color to ANSI escape code\n */\nfunction colorToAnsi(color: Color): string {\n if (color === null) return \"\";\n if (color in ansiColors) {\n return ansiColors[color as keyof typeof ansiColors];\n }\n\n // Handle rgb() format\n const rgbMatch = color.match(RGB_PATTERN);\n if (rgbMatch) {\n const [, r, g, b] = rgbMatch;\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n\n // Handle hex format (#rrggbb or #rgb)\n const hexMatch = color.match(HEX_PATTERN);\n if (hexMatch) {\n let hex = hexMatch[1];\n // Convert 3-digit hex to 6-digit\n if (hex.length === 3) {\n hex = hex.split(\"\").map((c) => c + c).join(\"\");\n }\n const r = parseInt(hex.substr(0, 2), 16);\n const g = parseInt(hex.substr(2, 2), 16);\n const b = parseInt(hex.substr(4, 2), 16);\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n\n return \"\";\n}\n\n/**\n * Helper function to convert style to ANSI escape code\n */\nfunction styleToAnsi(style: Style): string {\n if (style === null) return \"\";\n if (Array.isArray(style)) {\n return style.map((s) => styles[s] || \"\").join(\"\");\n }\n return styles[style] || \"\";\n}\n\n/**\n * Converts a category color map to internal patterns and sorts them by specificity.\n * More specific (longer) prefixes come first for proper matching precedence.\n */\nfunction prepareCategoryPatterns(\n categoryColorMap: CategoryColorMap,\n): CategoryPattern[] {\n const patterns: CategoryPattern[] = [];\n\n for (const [prefix, color] of categoryColorMap) {\n patterns.push({ prefix, color });\n }\n\n // Sort by prefix length (descending) for most-specific-first matching\n return patterns.sort((a, b) => b.prefix.length - a.prefix.length);\n}\n\n/**\n * Matches a category against category color patterns.\n * Returns the color of the first matching pattern, or null if no match.\n */\nfunction matchCategoryColor(\n category: readonly string[],\n patterns: CategoryPattern[],\n): Color {\n for (const pattern of patterns) {\n if (categoryMatches(category, pattern.prefix)) {\n return pattern.color;\n }\n }\n return null;\n}\n\n/**\n * Checks if a category matches a prefix pattern.\n * A category matches if it starts with all segments of the prefix.\n */\nfunction categoryMatches(\n category: readonly string[],\n prefix: readonly string[],\n): boolean {\n if (prefix.length > category.length) {\n return false;\n }\n\n for (let i = 0; i < prefix.length; i++) {\n if (category[i] !== prefix[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Default icons for each log level\n */\nconst defaultIcons: Record<LogLevel, string> = {\n trace: \"🔍\",\n debug: \"🐛\",\n info: \"✨\",\n warning: \"⚡\",\n error: \"❌\",\n fatal: \"💀\",\n};\n\n/**\n * Normalize icon spacing to ensure consistent column alignment.\n *\n * All icons will be padded with spaces to match the width of the widest icon,\n * ensuring consistent prefix alignment across all log levels.\n *\n * @param iconMap The icon mapping to normalize\n * @returns A new icon map with consistent spacing\n */\nfunction normalizeIconSpacing(\n iconMap: Record<LogLevel, string>,\n): Record<LogLevel, string> {\n const entries = Object.entries(iconMap) as Array<[LogLevel, string]>;\n const maxWidth = Math.max(\n ...entries.map(([, icon]) => getDisplayWidth(icon)),\n );\n\n return Object.fromEntries(\n entries.map(([level, icon]) => [\n level,\n icon + \" \".repeat(maxWidth - getDisplayWidth(icon)),\n ]),\n ) as Record<LogLevel, string>;\n}\n\n/**\n * Configuration options for the pretty formatter.\n *\n * This interface extends the base text formatter options while providing\n * extensive customization options for visual styling, layout control, and\n * development-focused features. It offers granular control over colors,\n * styles, and formatting similar to the ANSI color formatter.\n *\n * @since 1.0.0\n */\nexport interface PrettyFormatterOptions\n extends Omit<TextFormatterOptions, \"category\" | \"value\" | \"format\"> {\n /**\n * Color for timestamp display when timestamps are enabled.\n *\n * Supports true color RGB values, hex colors, or ANSI color names.\n * Set to `null` to disable timestamp coloring.\n *\n * @example\n * ```typescript\n * timestampColor: \"#888888\" // Hex color\n * timestampColor: \"rgb(128,128,128)\" // RGB color\n * timestampColor: \"cyan\" // ANSI color name\n * timestampColor: null // No color\n * ```\n *\n * @default `\"rgb(100,116,139)\"` (slate gray)\n */\n readonly timestampColor?: Color;\n\n /**\n * Visual style applied to timestamp text.\n *\n * Controls text appearance like boldness, dimming, etc.\n * Supports single styles, multiple styles combined, or no styling.\n * Combines with `timestampColor` for full styling control.\n *\n * @example\n * ```typescript\n * timestampStyle: \"dim\" // Single style: dimmed text\n * timestampStyle: \"bold\" // Single style: bold text\n * timestampStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * timestampStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * timestampStyle: null // No styling\n * ```\n *\n * @default `\"dim\"`\n */\n readonly timestampStyle?: Style;\n\n /**\n * Custom colors for each log level.\n *\n * Allows fine-grained control over level appearance. Each level can have\n * its own color scheme. Unspecified levels use built-in defaults.\n * Set individual levels to `null` to disable coloring for that level.\n *\n * @example\n * ```typescript\n * levelColors: {\n * info: \"#00ff00\", // Bright green for info\n * error: \"#ff0000\", // Bright red for errors\n * warning: \"orange\", // ANSI orange for warnings\n * debug: null, // No color for debug\n * }\n * ```\n *\n * @default Built-in color scheme (purple trace, blue debug, green info, amber warning, red error, dark red fatal)\n */\n readonly levelColors?: Partial<Record<LogLevel, Color>>;\n\n /**\n * Visual style applied to log level text.\n *\n * Controls the appearance of the level indicator (e.g., \"info\", \"error\").\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to level-specific colors.\n *\n * @example\n * ```typescript\n * levelStyle: \"bold\" // Single style: bold level text\n * levelStyle: \"underline\" // Single style: underlined level text\n * levelStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * levelStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * levelStyle: null // No additional styling\n * ```\n *\n * @default `\"underline\"`\n */\n readonly levelStyle?: Style;\n\n /**\n * Icon configuration for each log level.\n *\n * Controls the emoji/symbol displayed before each log entry.\n * Provides visual quick-identification of log severity.\n *\n * - `true`: Use built-in emoji set (🔍 trace, 🐛 debug, ✨ info, ⚠️ warning, ❌ error, 💀 fatal)\n * - `false`: Disable all icons for clean text-only output\n * - Object: Custom icon mapping, falls back to defaults for unspecified levels\n *\n * @example\n * ```typescript\n * icons: true // Use default emoji set\n * icons: false // No icons\n * icons: {\n * info: \"ℹ️\", // Custom info icon\n * error: \"🔥\", // Custom error icon\n * warning: \"⚡\", // Custom warning icon\n * }\n * ```\n *\n * @default `true` (use default emoji icons)\n */\n readonly icons?: boolean | Partial<Record<LogLevel, string>>;\n\n /**\n * Character(s) used to separate category hierarchy levels.\n *\n * Categories are hierarchical (e.g., [\"app\", \"auth\", \"jwt\"]) and this\n * separator joins them for display (e.g., \"app.auth.jwt\").\n *\n * @example\n * ```typescript\n * categorySeparator: \"·\" // app·auth·jwt\n * categorySeparator: \".\" // app.auth.jwt\n * categorySeparator: \":\" // app:auth:jwt\n * categorySeparator: \" > \" // app > auth > jwt\n * categorySeparator: \"::\" // app::auth::jwt\n * ```\n *\n * @default `\"·\"` (interpunct)\n */\n readonly categorySeparator?: string;\n\n /**\n * Default color for category display.\n *\n * Used as fallback when no specific color is found in `categoryColorMap`.\n * Controls the visual appearance of the category hierarchy display.\n *\n * @example\n * ```typescript\n * categoryColor: \"#666666\" // Gray categories\n * categoryColor: \"blue\" // Blue categories\n * categoryColor: \"rgb(100,150,200)\" // Light blue categories\n * categoryColor: null // No coloring\n * ```\n *\n * @default `\"rgb(100,116,139)\"` (slate gray)\n */\n readonly categoryColor?: Color;\n\n /**\n * Category-specific color mapping based on prefixes.\n *\n * Maps category prefixes (as arrays) to colors for visual grouping.\n * More specific (longer) prefixes take precedence over shorter ones.\n * If no prefix matches, falls back to the default `categoryColor`.\n *\n * @example\n * ```typescript\n * new Map([\n * [[\"app\", \"auth\"], \"#ff6b6b\"], // app.auth.* -> red\n * [[\"app\", \"db\"], \"#4ecdc4\"], // app.db.* -> teal\n * [[\"app\"], \"#45b7d1\"], // app.* (fallback) -> blue\n * [[\"lib\"], \"#96ceb4\"], // lib.* -> green\n * ])\n * ```\n */\n readonly categoryColorMap?: CategoryColorMap;\n\n /**\n * Visual style applied to category text.\n *\n * Controls the appearance of the category hierarchy display.\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to category colors from `categoryColor` or `categoryColorMap`.\n *\n * @example\n * ```typescript\n * categoryStyle: \"dim\" // Single style: dimmed category text\n * categoryStyle: \"italic\" // Single style: italic category text\n * categoryStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * categoryStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * categoryStyle: null // No additional styling\n * ```\n *\n * @default `[\"dim\", \"italic\"]` (dimmed for subtle appearance)\n */\n readonly categoryStyle?: Style;\n\n /**\n * Maximum display width for category names.\n *\n * Controls layout consistency by limiting category width.\n * Long categories are truncated according to `categoryTruncate` strategy.\n *\n * @default `20`\n */\n readonly categoryWidth?: number;\n\n /**\n * Strategy for truncating long category names.\n *\n * When categories exceed `categoryWidth`, this controls how truncation works.\n * Smart truncation preserves important context while maintaining layout.\n *\n * - `\"middle\"`: Keep first and last parts (e.g., \"app.server…auth.jwt\")\n * - `\"end\"`: Truncate at the end (e.g., \"app.server.middleware…\")\n * - `false`: No truncation (ignores `categoryWidth`)\n *\n * @example\n * ```typescript\n * categoryTruncate: \"middle\" // app.server…jwt (preserves context)\n * categoryTruncate: \"end\" // app.server.midd… (linear truncation)\n * categoryTruncate: false // app.server.middleware.auth.jwt (full)\n * ```\n *\n * @default `\"middle\"` (smart context-preserving truncation)\n */\n readonly categoryTruncate?: TruncationStrategy;\n\n /**\n * Color for log message text content.\n *\n * Controls the visual appearance of the actual log message content.\n * Does not affect structured values, which use syntax highlighting.\n *\n * @example\n * ```typescript\n * messageColor: \"#ffffff\" // White message text\n * messageColor: \"green\" // Green message text\n * messageColor: \"rgb(200,200,200)\" // Light gray message text\n * messageColor: null // No coloring\n * ```\n *\n * @default `\"rgb(148,163,184)\"` (light slate gray)\n */\n readonly messageColor?: Color;\n\n /**\n * Visual style applied to log message text.\n *\n * Controls the appearance of the log message content.\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to `messageColor`.\n *\n * @example\n * ```typescript\n * messageStyle: \"dim\" // Single style: dimmed message text\n * messageStyle: \"italic\" // Single style: italic message text\n * messageStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * messageStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * messageStyle: null // No additional styling\n * ```\n *\n * @default `\"dim\"` (dimmed for subtle readability)\n */\n readonly messageStyle?: Style;\n\n /**\n * Global color control for the entire formatter.\n *\n * Master switch to enable/disable all color output.\n * When disabled, produces clean monochrome output suitable for\n * non-color terminals or when colors are not desired.\n *\n * @example\n * ```typescript\n * colors: true // Full color output (default)\n * colors: false // Monochrome output only\n * ```\n *\n * @default `true` (colors enabled)\n */\n readonly colors?: boolean;\n\n /**\n * Column alignment for consistent visual layout.\n *\n * When enabled, ensures all log components (icons, levels, categories)\n * align consistently across multiple log entries, creating a clean\n * tabular appearance.\n *\n * @example\n * ```typescript\n * align: true // Aligned columns (default)\n * align: false // Compact, non-aligned output\n * ```\n *\n * @default `true` (alignment enabled)\n */\n readonly align?: boolean;\n\n /**\n * Configuration for structured value inspection and rendering.\n *\n * Controls how objects, arrays, and other complex values are displayed\n * within log messages. Uses Node.js `util.inspect()` style options.\n *\n * @example\n * ```typescript\n * inspectOptions: {\n * depth: 3, // Show 3 levels of nesting\n * colors: false, // Disable value syntax highlighting\n * compact: true, // Use compact object display\n * }\n * ```\n *\n * @default `{}` (use built-in defaults: depth=unlimited, colors=auto, compact=true)\n */\n readonly inspectOptions?: {\n /**\n * Maximum depth to traverse when inspecting nested objects.\n * @default Infinity (no depth limit)\n */\n readonly depth?: number;\n\n /**\n * Whether to use syntax highlighting colors for inspected values.\n * @default Inherited from global `colors` setting\n */\n readonly colors?: boolean;\n\n /**\n * Whether to use compact formatting for objects and arrays.\n * @default `true` (compact formatting)\n */\n readonly compact?: boolean;\n };\n\n /**\n * Enable word wrapping for long messages.\n *\n * When enabled, long messages will be wrapped at the specified width,\n * with continuation lines aligned to the message column position.\n *\n * - `true`: Auto-detect terminal width when attached to a terminal,\n * fallback to 80 columns when not in a terminal or detection fails\n * - `number`: Use the specified width in columns\n * - `false`: Disable word wrapping\n *\n * @example\n * ```typescript\n * // Auto-detect terminal width (recommended)\n * wordWrap: true\n *\n * // Custom wrap width\n * wordWrap: 120\n *\n * // Disable word wrapping (default)\n * wordWrap: false\n * ```\n *\n * @default `true` (auto-detect terminal width)\n * @since 1.0.0\n */\n readonly wordWrap?: boolean | number;\n}\n\n/**\n * Creates a beautiful console formatter optimized for local development.\n *\n * This formatter provides a Signale-inspired visual design with colorful icons,\n * smart category truncation, dimmed styling, and perfect column alignment.\n * It's specifically designed for development environments that support true colors\n * and Unicode characters.\n *\n * The formatter features:\n * - Emoji icons for each log level (🔍 trace, 🐛 debug, ✨ info, etc.)\n * - True color support with rich color schemes\n * - Intelligent category truncation for long hierarchical categories\n * - Optional timestamp display with multiple formats\n * - Configurable alignment and styling options\n * - Enhanced value rendering with syntax highlighting\n *\n * @param options Configuration options for customizing the formatter behavior.\n * @returns A text formatter function that can be used with LogTape sinks.\n *\n * @example\n * ```typescript\n * import { configure } from \"@logtape/logtape\";\n * import { getConsoleSink } from \"@logtape/logtape/sink\";\n * import { getPrettyFormatter } from \"@logtape/pretty\";\n *\n * await configure({\n * sinks: {\n * console: getConsoleSink({\n * formatter: getPrettyFormatter({\n * timestamp: \"time\",\n * categoryWidth: 25,\n * icons: {\n * info: \"📘\",\n * error: \"🔥\"\n * }\n * })\n * })\n * }\n * });\n * ```\n *\n * @since 1.0.0\n */\nexport function getPrettyFormatter(\n options: PrettyFormatterOptions = {},\n): TextFormatter {\n // Extract options with defaults\n const {\n timestamp = \"none\",\n timestampColor = \"rgb(100,116,139)\",\n timestampStyle = \"dim\",\n level: levelFormat = \"full\",\n levelColors = {},\n levelStyle = \"underline\",\n icons = true,\n categorySeparator = \"·\",\n categoryColor = \"rgb(100,116,139)\",\n categoryColorMap = new Map(),\n categoryStyle = [\"dim\", \"italic\"],\n categoryWidth = 20,\n categoryTruncate = \"middle\",\n messageColor = \"rgb(148,163,184)\",\n messageStyle = \"dim\",\n colors: useColors = true,\n align = true,\n inspectOptions = {},\n wordWrap = true,\n } = options;\n\n // Resolve icons\n const baseIconMap: Record<LogLevel, string> = icons === false\n ? { trace: \"\", debug: \"\", info: \"\", warning: \"\", error: \"\", fatal: \"\" }\n : icons === true\n ? defaultIcons\n : { ...defaultIcons, ...(icons as Partial<Record<LogLevel, string>>) };\n\n // Normalize icon spacing for consistent alignment\n const iconMap = normalizeIconSpacing(baseIconMap);\n\n // Resolve level colors with defaults\n const resolvedLevelColors: Record<LogLevel, Color> = {\n trace: defaultColors.trace,\n debug: defaultColors.debug,\n info: defaultColors.info,\n warning: defaultColors.warning,\n error: defaultColors.error,\n fatal: defaultColors.fatal,\n ...levelColors,\n };\n\n // Level formatter function with optimized mappings\n const levelMappings: Record<string, Record<LogLevel, string>> = {\n \"ABBR\": {\n trace: \"TRC\",\n debug: \"DBG\",\n info: \"INF\",\n warning: \"WRN\",\n error: \"ERR\",\n fatal: \"FTL\",\n },\n \"L\": {\n trace: \"T\",\n debug: \"D\",\n info: \"I\",\n warning: \"W\",\n error: \"E\",\n fatal: \"F\",\n },\n \"abbr\": {\n trace: \"trc\",\n debug: \"dbg\",\n info: \"inf\",\n warning: \"wrn\",\n error: \"err\",\n fatal: \"ftl\",\n },\n \"l\": {\n trace: \"t\",\n debug: \"d\",\n info: \"i\",\n warning: \"w\",\n error: \"e\",\n fatal: \"f\",\n },\n };\n\n const formatLevel = (level: LogLevel): string => {\n if (typeof levelFormat === \"function\") {\n return levelFormat(level);\n }\n\n if (levelFormat === \"FULL\") return level.toUpperCase();\n if (levelFormat === \"full\") return level;\n\n return levelMappings[levelFormat]?.[level] ?? level;\n };\n\n // Timestamp formatters lookup table\n const timestampFormatters: Record<string, (ts: number) => string> = {\n \"date-time-timezone\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \" +00:00\");\n },\n \"date-time-tz\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \" +00\");\n },\n \"date-time\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \"\");\n },\n \"time-timezone\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \" +00:00\");\n },\n \"time-tz\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \" +00\");\n },\n \"time\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \"\");\n },\n \"date\": (ts) => new Date(ts).toISOString().replace(/T.*/, \"\"),\n \"rfc3339\": (ts) => new Date(ts).toISOString(),\n };\n\n // Resolve timestamp formatter\n let timestampFn: ((ts: number) => string | null) | null = null;\n if (timestamp === \"none\" || timestamp === \"disabled\") {\n timestampFn = null;\n } else if (typeof timestamp === \"function\") {\n timestampFn = timestamp;\n } else {\n timestampFn = timestampFormatters[timestamp as string] ?? null;\n }\n\n // Configure word wrap settings\n const wordWrapEnabled = wordWrap !== false;\n let wordWrapWidth: number;\n\n if (typeof wordWrap === \"number\") {\n wordWrapWidth = wordWrap;\n } else if (wordWrap === true) {\n // Auto-detect terminal width\n wordWrapWidth = getOptimalWordWrapWidth(80);\n } else {\n wordWrapWidth = 80; // Default fallback\n }\n\n // Prepare category color patterns for matching\n const categoryPatterns = prepareCategoryPatterns(categoryColorMap);\n\n // Calculate level width based on format\n const allLevels: LogLevel[] = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warning\",\n \"error\",\n \"fatal\",\n ];\n const levelWidth = Math.max(...allLevels.map((l) => formatLevel(l).length));\n\n return (record: LogRecord): string => {\n // Calculate the prefix parts first to determine message column position\n const icon = iconMap[record.level] || \"\";\n const level = formatLevel(record.level);\n const categoryStr = truncateCategory(\n record.category,\n categoryWidth,\n categorySeparator,\n categoryTruncate,\n );\n\n // Format message with values - handle color reset/reapply for interpolated values\n let message = \"\";\n const messageColorCode = useColors ? colorToAnsi(messageColor) : \"\";\n const messageStyleCode = useColors ? styleToAnsi(messageStyle) : \"\";\n const messagePrefix = useColors\n ? `${messageStyleCode}${messageColorCode}`\n : \"\";\n\n for (let i = 0; i < record.message.length; i++) {\n if (i % 2 === 0) {\n message += record.message[i];\n } else {\n const value = record.message[i];\n const inspected = inspect(value, {\n colors: useColors,\n ...inspectOptions,\n });\n\n // Handle multiline interpolated values properly\n if (inspected.includes(\"\\n\")) {\n const lines = inspected.split(\"\\n\");\n\n const formattedLines = lines.map((line, index) => {\n if (index === 0) {\n // First line: reset formatting, add the line, then reapply\n if (useColors && (messageColorCode || messageStyleCode)) {\n return `${RESET}${line}${messagePrefix}`;\n } else {\n return line;\n }\n } else {\n // Continuation lines: just apply formatting, let wrapText handle indentation\n if (useColors && (messageColorCode || messageStyleCode)) {\n return `${line}${messagePrefix}`;\n } else {\n return line;\n }\n }\n });\n message += formattedLines.join(\"\\n\");\n } else {\n // Single line - handle normally\n if (useColors && (messageColorCode || messageStyleCode)) {\n message += `${RESET}${inspected}${messagePrefix}`;\n } else {\n message += inspected;\n }\n }\n }\n }\n\n // Parts are already calculated above\n\n // Determine category color (with prefix matching)\n const finalCategoryColor = useColors\n ? (matchCategoryColor(record.category, categoryPatterns) || categoryColor)\n : null;\n\n // Apply colors and styling\n const formattedIcon = icon;\n let formattedLevel = level;\n let formattedCategory = categoryStr;\n let formattedMessage = message;\n let formattedTimestamp = \"\";\n\n if (useColors) {\n // Apply level color and style\n const levelColorCode = colorToAnsi(resolvedLevelColors[record.level]);\n const levelStyleCode = styleToAnsi(levelStyle);\n formattedLevel = `${levelStyleCode}${levelColorCode}${level}${RESET}`;\n\n // Apply category color and style (with prefix matching)\n const categoryColorCode = colorToAnsi(finalCategoryColor);\n const categoryStyleCode = styleToAnsi(categoryStyle);\n formattedCategory =\n `${categoryStyleCode}${categoryColorCode}${categoryStr}${RESET}`;\n\n // Apply message color and style (already handled in message building above)\n formattedMessage = `${messagePrefix}${message}${RESET}`;\n }\n\n // Format timestamp if needed\n if (timestampFn) {\n const ts = timestampFn(record.timestamp);\n if (ts !== null) {\n if (useColors) {\n const timestampColorCode = colorToAnsi(timestampColor);\n const timestampStyleCode = styleToAnsi(timestampStyle);\n formattedTimestamp =\n `${timestampStyleCode}${timestampColorCode}${ts}${RESET} `;\n } else {\n formattedTimestamp = `${ts} `;\n }\n }\n }\n\n // Build the final output with alignment\n if (align) {\n // Calculate padding accounting for ANSI escape sequences\n const levelColorLength = useColors\n ? (colorToAnsi(resolvedLevelColors[record.level]).length +\n styleToAnsi(levelStyle).length + RESET.length)\n : 0;\n const categoryColorLength = useColors\n ? (colorToAnsi(finalCategoryColor).length +\n styleToAnsi(categoryStyle).length + RESET.length)\n : 0;\n\n const paddedLevel = formattedLevel.padEnd(levelWidth + levelColorLength);\n const paddedCategory = formattedCategory.padEnd(\n categoryWidth + categoryColorLength,\n );\n\n let result =\n `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} ${formattedMessage}`;\n\n // Apply word wrapping if enabled, or if there are multiline interpolated values\n if (wordWrapEnabled || message.includes(\"\\n\")) {\n result = wrapText(\n result,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n message,\n );\n }\n\n return result + \"\\n\";\n } else {\n let result =\n `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} ${formattedMessage}`;\n\n // Apply word wrapping if enabled, or if there are multiline interpolated values\n if (wordWrapEnabled || message.includes(\"\\n\")) {\n result = wrapText(\n result,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n message,\n );\n }\n\n return result + \"\\n\";\n }\n };\n}\n\n/**\n * A pre-configured beautiful console formatter for local development.\n *\n * This is a ready-to-use instance of the pretty formatter with sensible defaults\n * for most development scenarios. It provides immediate visual enhancement to\n * your logs without requiring any configuration.\n *\n * Features enabled by default:\n * - Emoji icons for all log levels\n * - True color support with rich color schemes\n * - Dimmed text styling for better readability\n * - Smart category truncation (20 characters max)\n * - Perfect column alignment\n * - No timestamp display (cleaner for development)\n *\n * For custom configuration, use {@link getPrettyFormatter} instead.\n *\n * @example\n * ```typescript\n * import { configure } from \"@logtape/logtape\";\n * import { getConsoleSink } from \"@logtape/logtape/sink\";\n * import { prettyFormatter } from \"@logtape/pretty\";\n *\n * await configure({\n * sinks: {\n * console: getConsoleSink({\n * formatter: prettyFormatter\n * })\n * }\n * });\n * ```\n *\n * @since 1.0.0\n */\nexport const prettyFormatter: TextFormatter = getPrettyFormatter();\n"],"mappings":";;;;;;;;;;AAeA,MAAM,QAAQ;AACd,MAAM,MAAM;AAGZ,MAAM,gBAAgB;CACpB,OAAO;CACP,OAAO;CACP,MAAM;CACN,SAAS;CACT,OAAO;CACP,OAAO;CACP,UAAU;CACV,SAAS;CACT,WAAW;AACZ;;;;AAKD,MAAM,SAAS;CACb,OAAO;CACP,MAAM;CACN,KAAK;CACL,QAAQ;CACR,WAAW;CACX,eAAe;AAChB;;;;AAKD,MAAM,aAAa;CACjB,OAAO;CACP,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;AACR;AA4CD,MAAM,cAAc;AACpB,MAAM,cAAc;;;;AAKpB,SAAS,YAAYA,OAAsB;AACzC,KAAI,UAAU,KAAM,QAAO;AAC3B,KAAI,SAAS,WACX,QAAO,WAAW;CAIpB,MAAM,WAAW,MAAM,MAAM,YAAY;AACzC,KAAI,UAAU;EACZ,MAAM,GAAG,GAAG,GAAG,EAAE,GAAG;AACpB,UAAQ,YAAY,EAAE,GAAG,EAAE,GAAG,EAAE;CACjC;C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,SAChD,YAAY,WAAW,CAAC,SAAS,MAAM,SACvC;GACJ,MAAM,sBAAsB,YACvB,YAAY,mBAAmB,CAAC,SACjC,YAAY,cAAc,CAAC,SAAS,MAAM,SAC1C;GAEJ,MAAM,cAAc,eAAe,OAAO,aAAa,iBAAiB;GACxE,MAAM,iBAAiB,kBAAkB,OACvC,gBAAgB,oBACjB;GAED,IAAI,UACD,EAAE,mBAAmB,EAAE,cAAc,GAAG,YAAY,GAAG,eAAe,GAAG,iBAAiB;AAG7F,OAAI,mBAAmB,QAAQ,SAAS,KAAK,CAC3C,UAAS,SACP,QACA,kBAAkB,gBAAgB,UAClC,QACD;AAGH,UAAO,SAAS;EACjB,OAAM;GACL,IAAI,UACD,EAAE,mBAAmB,EAAE,cAAc,GAAG,eAAe,GAAG,kBAAkB,GAAG,iBAAiB;AAGnG,OAAI,mBAAmB,QAAQ,SAAS,KAAK,CAC3C,UAAS,SACP,QACA,kBAAkB,gBAAgB,UAClC,QACD;AAGH,UAAO,SAAS;EACjB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCD,MAAaC,kBAAiC,oBAAoB"}
1
+ {"version":3,"file":"formatter.js","names":["color: Color","style: Style","categoryColorMap: CategoryColorMap","patterns: CategoryPattern[]","category: readonly string[]","prefix: readonly string[]","defaultIcons: Record<LogLevel, string>","iconMap: Record<LogLevel, string>","options: PrettyFormatterOptions","baseIconMap: Record<LogLevel, string>","resolvedLevelColors: Record<LogLevel, Color>","levelMappings: Record<string, Record<LogLevel, string>>","level: LogLevel","timestampFormatters: Record<string, (ts: number) => string>","timestampFn: ((ts: number) => string | null) | null","wordWrapWidth: number","allLevels: LogLevel[]","record: LogRecord","indentWidth: number","maxWidth: number","useColors: boolean","inspectOptions: InspectOptions","prettyFormatter: TextFormatter"],"sources":["../formatter.ts"],"sourcesContent":["import {\n getLogLevels,\n type LogLevel,\n type LogRecord,\n type TextFormatter,\n type TextFormatterOptions,\n} from \"@logtape/logtape\";\nimport { inspect, type InspectOptions } from \"#util\";\nimport { getOptimalWordWrapWidth } from \"./terminal.ts\";\nimport { truncateCategory, type TruncationStrategy } from \"./truncate.ts\";\nimport { getDisplayWidth, stripAnsi } from \"./wcwidth.ts\";\nimport { wrapText } from \"./wordwrap.ts\";\n\n/**\n * ANSI escape codes for styling\n */\nconst RESET = \"\\x1b[0m\";\nconst DIM = \"\\x1b[2m\";\n\n// Default true color values (referenced in JSDoc)\nconst defaultColors = {\n trace: \"rgb(167,139,250)\", // Light purple\n debug: \"rgb(96,165,250)\", // Light blue\n info: \"rgb(52,211,153)\", // Emerald\n warning: \"rgb(251,191,36)\", // Amber\n error: \"rgb(248,113,113)\", // Light red\n fatal: \"rgb(220,38,38)\", // Dark red\n category: \"rgb(100,116,139)\", // Slate\n message: \"rgb(148,163,184)\", // Light slate\n timestamp: \"rgb(100,116,139)\", // Slate\n} as const;\n\n/**\n * ANSI style codes\n */\nconst styles = {\n reset: RESET,\n bold: \"\\x1b[1m\",\n dim: DIM,\n italic: \"\\x1b[3m\",\n underline: \"\\x1b[4m\",\n strikethrough: \"\\x1b[9m\",\n} as const;\n\n/**\n * Standard ANSI colors (16-color)\n */\nconst ansiColors = {\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} as const;\n\n/**\n * Color type definition\n */\nexport type Color =\n | keyof typeof ansiColors\n | `rgb(${number},${number},${number})`\n | `#${string}`\n | null;\n\n/**\n * Category color mapping for prefix-based coloring.\n *\n * Maps category prefixes (as arrays) to colors. The formatter will match\n * categories against these prefixes and use the corresponding color.\n * Longer/more specific prefixes take precedence over shorter ones.\n *\n * @example\n * ```typescript\n * new Map([\n * [[\"app\", \"auth\"], \"#ff6b6b\"], // app.auth.* -> red\n * [[\"app\", \"db\"], \"#4ecdc4\"], // app.db.* -> teal\n * [[\"app\"], \"#45b7d1\"], // app.* (fallback) -> blue\n * [[\"lib\"], \"#96ceb4\"], // lib.* -> green\n * ])\n * ```\n */\nexport type CategoryColorMap = Map<readonly string[], Color>;\n\n/**\n * Internal representation of category prefix patterns\n */\ntype CategoryPattern = {\n prefix: readonly string[];\n color: Color;\n};\n\n/**\n * Style type definition - supports single styles, arrays of styles, or null\n */\nexport type Style = keyof typeof styles | (keyof typeof styles)[] | null;\n\n// Pre-compiled regex patterns for color parsing\nconst RGB_PATTERN = /^rgb\\((\\d+),(\\d+),(\\d+)\\)$/;\nconst HEX_PATTERN = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\n/**\n * Helper function to convert color to ANSI escape code\n */\nfunction colorToAnsi(color: Color): string {\n if (color === null) return \"\";\n if (color in ansiColors) {\n return ansiColors[color as keyof typeof ansiColors];\n }\n\n // Handle rgb() format\n const rgbMatch = color.match(RGB_PATTERN);\n if (rgbMatch) {\n const [, r, g, b] = rgbMatch;\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n\n // Handle hex format (#rrggbb or #rgb)\n const hexMatch = color.match(HEX_PATTERN);\n if (hexMatch) {\n let hex = hexMatch[1];\n // Convert 3-digit hex to 6-digit\n if (hex.length === 3) {\n hex = hex.split(\"\").map((c) => c + c).join(\"\");\n }\n const r = parseInt(hex.substr(0, 2), 16);\n const g = parseInt(hex.substr(2, 2), 16);\n const b = parseInt(hex.substr(4, 2), 16);\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n\n return \"\";\n}\n\n/**\n * Helper function to convert style to ANSI escape code\n */\nfunction styleToAnsi(style: Style): string {\n if (style === null) return \"\";\n if (Array.isArray(style)) {\n return style.map((s) => styles[s] || \"\").join(\"\");\n }\n return styles[style] || \"\";\n}\n\n/**\n * Converts a category color map to internal patterns and sorts them by specificity.\n * More specific (longer) prefixes come first for proper matching precedence.\n */\nfunction prepareCategoryPatterns(\n categoryColorMap: CategoryColorMap,\n): CategoryPattern[] {\n const patterns: CategoryPattern[] = [];\n\n for (const [prefix, color] of categoryColorMap) {\n patterns.push({ prefix, color });\n }\n\n // Sort by prefix length (descending) for most-specific-first matching\n return patterns.sort((a, b) => b.prefix.length - a.prefix.length);\n}\n\n/**\n * Matches a category against category color patterns.\n * Returns the color of the first matching pattern, or null if no match.\n */\nfunction matchCategoryColor(\n category: readonly string[],\n patterns: CategoryPattern[],\n): Color {\n for (const pattern of patterns) {\n if (categoryMatches(category, pattern.prefix)) {\n return pattern.color;\n }\n }\n return null;\n}\n\n/**\n * Checks if a category matches a prefix pattern.\n * A category matches if it starts with all segments of the prefix.\n */\nfunction categoryMatches(\n category: readonly string[],\n prefix: readonly string[],\n): boolean {\n if (prefix.length > category.length) {\n return false;\n }\n\n for (let i = 0; i < prefix.length; i++) {\n if (category[i] !== prefix[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Default icons for each log level\n */\nconst defaultIcons: Record<LogLevel, string> = {\n trace: \"🔍\",\n debug: \"🐛\",\n info: \"✨\",\n warning: \"⚡\",\n error: \"❌\",\n fatal: \"💀\",\n};\n\n/**\n * Normalize icon spacing to ensure consistent column alignment.\n *\n * All icons will be padded with spaces to match the width of the widest icon,\n * ensuring consistent prefix alignment across all log levels.\n *\n * @param iconMap The icon mapping to normalize\n * @returns A new icon map with consistent spacing\n */\nfunction normalizeIconSpacing(\n iconMap: Record<LogLevel, string>,\n): Record<LogLevel, string> {\n const entries = Object.entries(iconMap) as Array<[LogLevel, string]>;\n const maxWidth = Math.max(\n ...entries.map(([, icon]) => getDisplayWidth(icon)),\n );\n\n return Object.fromEntries(\n entries.map(([level, icon]) => [\n level,\n icon + \" \".repeat(maxWidth - getDisplayWidth(icon)),\n ]),\n ) as Record<LogLevel, string>;\n}\n\n/**\n * Configuration options for the pretty formatter.\n *\n * This interface extends the base text formatter options while providing\n * extensive customization options for visual styling, layout control, and\n * development-focused features. It offers granular control over colors,\n * styles, and formatting similar to the ANSI color formatter.\n *\n * @since 1.0.0\n */\nexport interface PrettyFormatterOptions\n extends Omit<TextFormatterOptions, \"category\" | \"value\" | \"format\"> {\n /**\n * Color for timestamp display when timestamps are enabled.\n *\n * Supports true color RGB values, hex colors, or ANSI color names.\n * Set to `null` to disable timestamp coloring.\n *\n * @example\n * ```typescript\n * timestampColor: \"#888888\" // Hex color\n * timestampColor: \"rgb(128,128,128)\" // RGB color\n * timestampColor: \"cyan\" // ANSI color name\n * timestampColor: null // No color\n * ```\n *\n * @default `\"rgb(100,116,139)\"` (slate gray)\n */\n readonly timestampColor?: Color;\n\n /**\n * Visual style applied to timestamp text.\n *\n * Controls text appearance like boldness, dimming, etc.\n * Supports single styles, multiple styles combined, or no styling.\n * Combines with `timestampColor` for full styling control.\n *\n * @example\n * ```typescript\n * timestampStyle: \"dim\" // Single style: dimmed text\n * timestampStyle: \"bold\" // Single style: bold text\n * timestampStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * timestampStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * timestampStyle: null // No styling\n * ```\n *\n * @default `\"dim\"`\n */\n readonly timestampStyle?: Style;\n\n /**\n * Custom colors for each log level.\n *\n * Allows fine-grained control over level appearance. Each level can have\n * its own color scheme. Unspecified levels use built-in defaults.\n * Set individual levels to `null` to disable coloring for that level.\n *\n * @example\n * ```typescript\n * levelColors: {\n * info: \"#00ff00\", // Bright green for info\n * error: \"#ff0000\", // Bright red for errors\n * warning: \"orange\", // ANSI orange for warnings\n * debug: null, // No color for debug\n * }\n * ```\n *\n * @default Built-in color scheme (purple trace, blue debug, green info, amber warning, red error, dark red fatal)\n */\n readonly levelColors?: Partial<Record<LogLevel, Color>>;\n\n /**\n * Visual style applied to log level text.\n *\n * Controls the appearance of the level indicator (e.g., \"info\", \"error\").\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to level-specific colors.\n *\n * @example\n * ```typescript\n * levelStyle: \"bold\" // Single style: bold level text\n * levelStyle: \"underline\" // Single style: underlined level text\n * levelStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * levelStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * levelStyle: null // No additional styling\n * ```\n *\n * @default `\"underline\"`\n */\n readonly levelStyle?: Style;\n\n /**\n * Icon configuration for each log level.\n *\n * Controls the emoji/symbol displayed before each log entry.\n * Provides visual quick-identification of log severity.\n *\n * - `true`: Use built-in emoji set (🔍 trace, 🐛 debug, ✨ info, ⚠️ warning, ❌ error, 💀 fatal)\n * - `false`: Disable all icons for clean text-only output\n * - Object: Custom icon mapping, falls back to defaults for unspecified levels\n *\n * @example\n * ```typescript\n * icons: true // Use default emoji set\n * icons: false // No icons\n * icons: {\n * info: \"ℹ️\", // Custom info icon\n * error: \"🔥\", // Custom error icon\n * warning: \"⚡\", // Custom warning icon\n * }\n * ```\n *\n * @default `true` (use default emoji icons)\n */\n readonly icons?: boolean | Partial<Record<LogLevel, string>>;\n\n /**\n * Character(s) used to separate category hierarchy levels.\n *\n * Categories are hierarchical (e.g., [\"app\", \"auth\", \"jwt\"]) and this\n * separator joins them for display (e.g., \"app.auth.jwt\").\n *\n * @example\n * ```typescript\n * categorySeparator: \"·\" // app·auth·jwt\n * categorySeparator: \".\" // app.auth.jwt\n * categorySeparator: \":\" // app:auth:jwt\n * categorySeparator: \" > \" // app > auth > jwt\n * categorySeparator: \"::\" // app::auth::jwt\n * ```\n *\n * @default `\"·\"` (interpunct)\n */\n readonly categorySeparator?: string;\n\n /**\n * Default color for category display.\n *\n * Used as fallback when no specific color is found in `categoryColorMap`.\n * Controls the visual appearance of the category hierarchy display.\n *\n * @example\n * ```typescript\n * categoryColor: \"#666666\" // Gray categories\n * categoryColor: \"blue\" // Blue categories\n * categoryColor: \"rgb(100,150,200)\" // Light blue categories\n * categoryColor: null // No coloring\n * ```\n *\n * @default `\"rgb(100,116,139)\"` (slate gray)\n */\n readonly categoryColor?: Color;\n\n /**\n * Category-specific color mapping based on prefixes.\n *\n * Maps category prefixes (as arrays) to colors for visual grouping.\n * More specific (longer) prefixes take precedence over shorter ones.\n * If no prefix matches, falls back to the default `categoryColor`.\n *\n * @example\n * ```typescript\n * new Map([\n * [[\"app\", \"auth\"], \"#ff6b6b\"], // app.auth.* -> red\n * [[\"app\", \"db\"], \"#4ecdc4\"], // app.db.* -> teal\n * [[\"app\"], \"#45b7d1\"], // app.* (fallback) -> blue\n * [[\"lib\"], \"#96ceb4\"], // lib.* -> green\n * ])\n * ```\n */\n readonly categoryColorMap?: CategoryColorMap;\n\n /**\n * Visual style applied to category text.\n *\n * Controls the appearance of the category hierarchy display.\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to category colors from `categoryColor` or `categoryColorMap`.\n *\n * @example\n * ```typescript\n * categoryStyle: \"dim\" // Single style: dimmed category text\n * categoryStyle: \"italic\" // Single style: italic category text\n * categoryStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * categoryStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * categoryStyle: null // No additional styling\n * ```\n *\n * @default `[\"dim\", \"italic\"]` (dimmed for subtle appearance)\n */\n readonly categoryStyle?: Style;\n\n /**\n * Maximum display width for category names.\n *\n * Controls layout consistency by limiting category width.\n * Long categories are truncated according to `categoryTruncate` strategy.\n *\n * @default `20`\n */\n readonly categoryWidth?: number;\n\n /**\n * Strategy for truncating long category names.\n *\n * When categories exceed `categoryWidth`, this controls how truncation works.\n * Smart truncation preserves important context while maintaining layout.\n *\n * - `\"middle\"`: Keep first and last parts (e.g., \"app.server…auth.jwt\")\n * - `\"end\"`: Truncate at the end (e.g., \"app.server.middleware…\")\n * - `false`: No truncation (ignores `categoryWidth`)\n *\n * @example\n * ```typescript\n * categoryTruncate: \"middle\" // app.server…jwt (preserves context)\n * categoryTruncate: \"end\" // app.server.midd… (linear truncation)\n * categoryTruncate: false // app.server.middleware.auth.jwt (full)\n * ```\n *\n * @default `\"middle\"` (smart context-preserving truncation)\n */\n readonly categoryTruncate?: TruncationStrategy;\n\n /**\n * Color for log message text content.\n *\n * Controls the visual appearance of the actual log message content.\n * Does not affect structured values, which use syntax highlighting.\n *\n * @example\n * ```typescript\n * messageColor: \"#ffffff\" // White message text\n * messageColor: \"green\" // Green message text\n * messageColor: \"rgb(200,200,200)\" // Light gray message text\n * messageColor: null // No coloring\n * ```\n *\n * @default `\"rgb(148,163,184)\"` (light slate gray)\n */\n readonly messageColor?: Color;\n\n /**\n * Visual style applied to log message text.\n *\n * Controls the appearance of the log message content.\n * Supports single styles, multiple styles combined, or no styling.\n * Applied in addition to `messageColor`.\n *\n * @example\n * ```typescript\n * messageStyle: \"dim\" // Single style: dimmed message text\n * messageStyle: \"italic\" // Single style: italic message text\n * messageStyle: [\"dim\", \"italic\"] // Multiple styles: dimmed + italic\n * messageStyle: [\"bold\", \"underline\"] // Multiple styles: bold + underlined\n * messageStyle: null // No additional styling\n * ```\n *\n * @default `\"dim\"` (dimmed for subtle readability)\n */\n readonly messageStyle?: Style;\n\n /**\n * Global color control for the entire formatter.\n *\n * Master switch to enable/disable all color output.\n * When disabled, produces clean monochrome output suitable for\n * non-color terminals or when colors are not desired.\n *\n * @example\n * ```typescript\n * colors: true // Full color output (default)\n * colors: false // Monochrome output only\n * ```\n *\n * @default `true` (colors enabled)\n */\n readonly colors?: boolean;\n\n /**\n * Column alignment for consistent visual layout.\n *\n * When enabled, ensures all log components (icons, levels, categories)\n * align consistently across multiple log entries, creating a clean\n * tabular appearance.\n *\n * @example\n * ```typescript\n * align: true // Aligned columns (default)\n * align: false // Compact, non-aligned output\n * ```\n *\n * @default `true` (alignment enabled)\n */\n readonly align?: boolean;\n\n /**\n * Configuration for structured value inspection and rendering.\n *\n * Controls how objects, arrays, and other complex values are displayed\n * within log messages. Uses Node.js `util.inspect()` style options.\n *\n * @example\n * ```typescript\n * inspectOptions: {\n * depth: 3, // Show 3 levels of nesting\n * colors: false, // Disable value syntax highlighting\n * compact: true, // Use compact object display\n * }\n * ```\n *\n * @default `{}` (use built-in defaults: depth=unlimited, colors=auto, compact=true)\n */\n readonly inspectOptions?: {\n /**\n * Maximum depth to traverse when inspecting nested objects.\n * @default Infinity (no depth limit)\n */\n readonly depth?: number;\n\n /**\n * Whether to use syntax highlighting colors for inspected values.\n * @default Inherited from global `colors` setting\n */\n readonly colors?: boolean;\n\n /**\n * Whether to use compact formatting for objects and arrays.\n * @default `true` (compact formatting)\n */\n readonly compact?: boolean;\n };\n\n /**\n * Configuration to always render structured data.\n *\n * If set to `true`, any structured data that is logged will\n * always be rendered. This can be very verbose. Make sure\n * to configure `inspectOptions` properly for your usecase.\n *\n * @default `false`\n * @since 1.1.0\n */\n readonly properties?: boolean;\n\n /**\n * Enable word wrapping for long messages.\n *\n * When enabled, long messages will be wrapped at the specified width,\n * with continuation lines aligned to the message column position.\n *\n * - `true`: Auto-detect terminal width when attached to a terminal,\n * fallback to 80 columns when not in a terminal or detection fails\n * - `number`: Use the specified width in columns\n * - `false`: Disable word wrapping\n *\n * @example\n * ```typescript\n * // Auto-detect terminal width (recommended)\n * wordWrap: true\n *\n * // Custom wrap width\n * wordWrap: 120\n *\n * // Disable word wrapping (default)\n * wordWrap: false\n * ```\n *\n * @default `true` (auto-detect terminal width)\n * @since 1.0.0\n */\n readonly wordWrap?: boolean | number;\n}\n\n/**\n * Creates a beautiful console formatter optimized for local development.\n *\n * This formatter provides a Signale-inspired visual design with colorful icons,\n * smart category truncation, dimmed styling, and perfect column alignment.\n * It's specifically designed for development environments that support true colors\n * and Unicode characters.\n *\n * The formatter features:\n * - Emoji icons for each log level (🔍 trace, 🐛 debug, ✨ info, etc.)\n * - True color support with rich color schemes\n * - Intelligent category truncation for long hierarchical categories\n * - Optional timestamp display with multiple formats\n * - Configurable alignment and styling options\n * - Enhanced value rendering with syntax highlighting\n *\n * @param options Configuration options for customizing the formatter behavior.\n * @returns A text formatter function that can be used with LogTape sinks.\n *\n * @example\n * ```typescript\n * import { configure } from \"@logtape/logtape\";\n * import { getConsoleSink } from \"@logtape/logtape/sink\";\n * import { getPrettyFormatter } from \"@logtape/pretty\";\n *\n * await configure({\n * sinks: {\n * console: getConsoleSink({\n * formatter: getPrettyFormatter({\n * timestamp: \"time\",\n * categoryWidth: 25,\n * icons: {\n * info: \"📘\",\n * error: \"🔥\"\n * }\n * })\n * })\n * }\n * });\n * ```\n *\n * @since 1.0.0\n */\nexport function getPrettyFormatter(\n options: PrettyFormatterOptions = {},\n): TextFormatter {\n // Extract options with defaults\n const {\n timestamp = \"none\",\n timestampColor = \"rgb(100,116,139)\",\n timestampStyle = \"dim\",\n level: levelFormat = \"full\",\n levelColors = {},\n levelStyle = \"underline\",\n icons = true,\n categorySeparator = \"·\",\n categoryColor = \"rgb(100,116,139)\",\n categoryColorMap = new Map(),\n categoryStyle = [\"dim\", \"italic\"],\n categoryWidth = 20,\n categoryTruncate = \"middle\",\n messageColor = \"rgb(148,163,184)\",\n messageStyle = \"dim\",\n colors: useColors = true,\n align = true,\n inspectOptions = {},\n properties = false,\n wordWrap = true,\n } = options;\n\n // Resolve icons\n const baseIconMap: Record<LogLevel, string> = icons === false\n ? { trace: \"\", debug: \"\", info: \"\", warning: \"\", error: \"\", fatal: \"\" }\n : icons === true\n ? defaultIcons\n : { ...defaultIcons, ...(icons as Partial<Record<LogLevel, string>>) };\n\n // Normalize icon spacing for consistent alignment\n const iconMap = normalizeIconSpacing(baseIconMap);\n\n // Resolve level colors with defaults\n const resolvedLevelColors: Record<LogLevel, Color> = {\n trace: defaultColors.trace,\n debug: defaultColors.debug,\n info: defaultColors.info,\n warning: defaultColors.warning,\n error: defaultColors.error,\n fatal: defaultColors.fatal,\n ...levelColors,\n };\n\n // Level formatter function with optimized mappings\n const levelMappings: Record<string, Record<LogLevel, string>> = {\n \"ABBR\": {\n trace: \"TRC\",\n debug: \"DBG\",\n info: \"INF\",\n warning: \"WRN\",\n error: \"ERR\",\n fatal: \"FTL\",\n },\n \"L\": {\n trace: \"T\",\n debug: \"D\",\n info: \"I\",\n warning: \"W\",\n error: \"E\",\n fatal: \"F\",\n },\n \"abbr\": {\n trace: \"trc\",\n debug: \"dbg\",\n info: \"inf\",\n warning: \"wrn\",\n error: \"err\",\n fatal: \"ftl\",\n },\n \"l\": {\n trace: \"t\",\n debug: \"d\",\n info: \"i\",\n warning: \"w\",\n error: \"e\",\n fatal: \"f\",\n },\n };\n\n const formatLevel = (level: LogLevel): string => {\n if (typeof levelFormat === \"function\") {\n return levelFormat(level);\n }\n\n if (levelFormat === \"FULL\") return level.toUpperCase();\n if (levelFormat === \"full\") return level;\n\n return levelMappings[levelFormat]?.[level] ?? level;\n };\n\n // Timestamp formatters lookup table\n const timestampFormatters: Record<string, (ts: number) => string> = {\n \"date-time-timezone\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \" +00:00\");\n },\n \"date-time-tz\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \" +00\");\n },\n \"date-time\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(\"T\", \" \").replace(\"Z\", \"\");\n },\n \"time-timezone\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \" +00:00\");\n },\n \"time-tz\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \" +00\");\n },\n \"time\": (ts) => {\n const iso = new Date(ts).toISOString();\n return iso.replace(/.*T/, \"\").replace(\"Z\", \"\");\n },\n \"date\": (ts) => new Date(ts).toISOString().replace(/T.*/, \"\"),\n \"rfc3339\": (ts) => new Date(ts).toISOString(),\n };\n\n // Resolve timestamp formatter\n let timestampFn: ((ts: number) => string | null) | null = null;\n if (timestamp === \"none\" || timestamp === \"disabled\") {\n timestampFn = null;\n } else if (typeof timestamp === \"function\") {\n timestampFn = timestamp;\n } else {\n timestampFn = timestampFormatters[timestamp as string] ?? null;\n }\n\n // Configure word wrap settings\n const wordWrapEnabled = wordWrap !== false;\n let wordWrapWidth: number;\n\n if (typeof wordWrap === \"number\") {\n wordWrapWidth = wordWrap;\n } else if (wordWrap === true) {\n // Auto-detect terminal width\n wordWrapWidth = getOptimalWordWrapWidth(80);\n } else {\n wordWrapWidth = 80; // Default fallback\n }\n\n // Prepare category color patterns for matching\n const categoryPatterns = prepareCategoryPatterns(categoryColorMap);\n\n // Calculate level width based on format\n const allLevels: LogLevel[] = [...getLogLevels()];\n const levelWidth = Math.max(...allLevels.map((l) => formatLevel(l).length));\n\n return (record: LogRecord): string => {\n // Calculate the prefix parts first to determine message column position\n const icon = iconMap[record.level] || \"\";\n const level = formatLevel(record.level);\n const categoryStr = truncateCategory(\n record.category,\n categoryWidth,\n categorySeparator,\n categoryTruncate,\n );\n\n // Format message with values - handle color reset/reapply for interpolated values\n let message = \"\";\n const messageColorCode = useColors ? colorToAnsi(messageColor) : \"\";\n const messageStyleCode = useColors ? styleToAnsi(messageStyle) : \"\";\n const messagePrefix = useColors\n ? `${messageStyleCode}${messageColorCode}`\n : \"\";\n\n for (let i = 0; i < record.message.length; i++) {\n if (i % 2 === 0) {\n message += record.message[i];\n } else {\n const value = record.message[i];\n const inspected = inspect(value, {\n colors: useColors,\n ...inspectOptions,\n });\n\n // Handle multiline interpolated values properly\n if (inspected.includes(\"\\n\")) {\n const lines = inspected.split(\"\\n\");\n\n const formattedLines = lines.map((line, index) => {\n if (index === 0) {\n // First line: reset formatting, add the line, then reapply\n if (useColors && (messageColorCode || messageStyleCode)) {\n return `${RESET}${line}${messagePrefix}`;\n } else {\n return line;\n }\n } else {\n // Continuation lines: just apply formatting, let wrapText handle indentation\n if (useColors && (messageColorCode || messageStyleCode)) {\n return `${line}${messagePrefix}`;\n } else {\n return line;\n }\n }\n });\n message += formattedLines.join(\"\\n\");\n } else {\n // Single line - handle normally\n if (useColors && (messageColorCode || messageStyleCode)) {\n message += `${RESET}${inspected}${messagePrefix}`;\n } else {\n message += inspected;\n }\n }\n }\n }\n\n // Parts are already calculated above\n\n // Determine category color (with prefix matching)\n const finalCategoryColor = useColors\n ? (matchCategoryColor(record.category, categoryPatterns) || categoryColor)\n : null;\n\n // Apply colors and styling\n const formattedIcon = icon;\n let formattedLevel = level;\n let formattedCategory = categoryStr;\n let formattedMessage = message;\n let formattedTimestamp = \"\";\n\n if (useColors) {\n // Apply level color and style\n const levelColorCode = colorToAnsi(resolvedLevelColors[record.level]);\n const levelStyleCode = styleToAnsi(levelStyle);\n formattedLevel = `${levelStyleCode}${levelColorCode}${level}${RESET}`;\n\n // Apply category color and style (with prefix matching)\n const categoryColorCode = colorToAnsi(finalCategoryColor);\n const categoryStyleCode = styleToAnsi(categoryStyle);\n formattedCategory =\n `${categoryStyleCode}${categoryColorCode}${categoryStr}${RESET}`;\n\n // Apply message color and style (already handled in message building above)\n formattedMessage = `${messagePrefix}${message}${RESET}`;\n }\n\n // Format timestamp if needed\n if (timestampFn) {\n const ts = timestampFn(record.timestamp);\n if (ts !== null) {\n if (useColors) {\n const timestampColorCode = colorToAnsi(timestampColor);\n const timestampStyleCode = styleToAnsi(timestampStyle);\n formattedTimestamp =\n `${timestampStyleCode}${timestampColorCode}${ts}${RESET} `;\n } else {\n formattedTimestamp = `${ts} `;\n }\n }\n }\n\n // Build the final output with alignment\n if (align) {\n // Calculate padding accounting for ANSI escape sequences\n const levelColorLength = useColors\n ? (colorToAnsi(resolvedLevelColors[record.level]).length +\n styleToAnsi(levelStyle).length + RESET.length)\n : 0;\n const categoryColorLength = useColors\n ? (colorToAnsi(finalCategoryColor).length +\n styleToAnsi(categoryStyle).length + RESET.length)\n : 0;\n\n const paddedLevel = formattedLevel.padEnd(levelWidth + levelColorLength);\n const paddedCategory = formattedCategory.padEnd(\n categoryWidth + categoryColorLength,\n );\n\n let result =\n `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} ${formattedMessage}`;\n const indentWidth = getDisplayWidth(\n stripAnsi(\n `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} `,\n ),\n );\n\n // Apply word wrapping if enabled, or if there are multiline interpolated values\n if (wordWrapEnabled || message.includes(\"\\n\")) {\n result = wrapText(\n result,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n indentWidth,\n );\n }\n\n if (properties) {\n result += formatProperties(\n record,\n indentWidth,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n useColors,\n inspectOptions,\n );\n }\n\n return result + \"\\n\";\n } else {\n let result =\n `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} ${formattedMessage}`;\n const indentWidth = getDisplayWidth(\n stripAnsi(\n `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} `,\n ),\n );\n\n // Apply word wrapping if enabled, or if there are multiline interpolated values\n if (wordWrapEnabled || message.includes(\"\\n\")) {\n result = wrapText(\n result,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n indentWidth,\n );\n }\n\n if (properties) {\n result += formatProperties(\n record,\n indentWidth,\n wordWrapEnabled ? wordWrapWidth : Infinity,\n useColors,\n inspectOptions,\n );\n }\n\n return result + \"\\n\";\n }\n };\n}\n\nfunction formatProperties(\n record: LogRecord,\n indentWidth: number,\n maxWidth: number,\n useColors: boolean,\n inspectOptions: InspectOptions,\n): string {\n let result = \"\";\n for (const prop in record.properties) {\n const propValue = record.properties[prop];\n const pad = indentWidth - getDisplayWidth(prop) - 2;\n result += \"\\n\" + wrapText(\n `${\" \".repeat(pad)}${useColors ? DIM : \"\"}${prop}:${\n useColors ? RESET : \"\"\n } ${inspect(propValue, { colors: useColors, ...inspectOptions })}`,\n maxWidth,\n indentWidth,\n );\n }\n return result;\n}\n\n/**\n * A pre-configured beautiful console formatter for local development.\n *\n * This is a ready-to-use instance of the pretty formatter with sensible defaults\n * for most development scenarios. It provides immediate visual enhancement to\n * your logs without requiring any configuration.\n *\n * Features enabled by default:\n * - Emoji icons for all log levels\n * - True color support with rich color schemes\n * - Dimmed text styling for better readability\n * - Smart category truncation (20 characters max)\n * - Perfect column alignment\n * - No timestamp display (cleaner for development)\n *\n * For custom configuration, use {@link getPrettyFormatter} instead.\n *\n * @example\n * ```typescript\n * import { configure } from \"@logtape/logtape\";\n * import { getConsoleSink } from \"@logtape/logtape/sink\";\n * import { prettyFormatter } from \"@logtape/pretty\";\n *\n * await configure({\n * sinks: {\n * console: getConsoleSink({\n * formatter: prettyFormatter\n * })\n * }\n * });\n * ```\n *\n * @since 1.0.0\n */\nexport const prettyFormatter: TextFormatter = getPrettyFormatter();\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,QAAQ;AACd,MAAM,MAAM;AAGZ,MAAM,gBAAgB;CACpB,OAAO;CACP,OAAO;CACP,MAAM;CACN,SAAS;CACT,OAAO;CACP,OAAO;CACP,UAAU;CACV,SAAS;CACT,WAAW;AACZ;;;;AAKD,MAAM,SAAS;CACb,OAAO;CACP,MAAM;CACN,KAAK;CACL,QAAQ;CACR,WAAW;CACX,eAAe;AAChB;;;;AAKD,MAAM,aAAa;CACjB,OAAO;CACP,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;AACR;AA4CD,MAAM,cAAc;AACpB,MAAM,cAAc;;;;AAKpB,SAAS,YAAYA,OAAsB;AACzC,KAAI,UAAU,KAAM,QAAO;AAC3B,KAAI,SAAS,WACX,QAAO,WAAW;CAIpB,MAAM,WAAW,MAAM,MAAM,YAAY;AACzC,KAAI,UAAU;EACZ,MAAM,GAAG,GAAG,GAAG,EAAE,GAAG;AACpB,UAAQ,YAAY,EAAE,GAAG,EAAE,GAAG,EAAE;CACjC;CAGD,MAAM,WAAW,MAAM,MAAM,YAAY;AACzC,KAAI,UAAU;EACZ,IAAI,MAAM,SAAS;AAEnB,MAAI,IAAI,WAAW,EACjB,OAAM,IAAI,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,KAAK,GAAG;EAEhD,MAAM,IAAI,SAAS,IAAI,OAAO,GAAG,EAAE,EAAE,GAAG;EACxC,MAAM,I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cwidth.cjs');
7
7
  *
8
8
  * @param text The text to wrap (may contain ANSI escape codes)
9
9
  * @param maxWidth Maximum width in terminal columns
10
- * @param messageContent The plain message content (used to find message start)
10
+ * @param indentWidth Indentation width for continuation lines
11
11
  * @returns Wrapped text with proper indentation
12
12
  */
13
- function wrapText(text, maxWidth, messageContent) {
13
+ function wrapText(text, maxWidth, indentWidth) {
14
14
  if (maxWidth <= 0) return text;
15
15
  const displayWidth = require_wcwidth.getDisplayWidth(text);
16
16
  if (displayWidth <= maxWidth && !text.includes("\n")) return text;
17
- const firstLineWords = messageContent.split(" ");
18
- const firstWord = firstLineWords[0];
19
- const plainText = require_wcwidth.stripAnsi(text);
20
- const messageStartIndex = plainText.indexOf(firstWord);
21
- let indentWidth = 0;
22
- if (messageStartIndex >= 0) {
23
- const prefixText = plainText.slice(0, messageStartIndex);
24
- indentWidth = require_wcwidth.getDisplayWidth(prefixText);
25
- }
26
17
  const indent = " ".repeat(Math.max(0, indentWidth));
27
18
  if (text.includes("\n")) {
28
19
  const lines = text.split("\n");
package/dist/wordwrap.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getDisplayWidth, stripAnsi } from "./wcwidth.js";
1
+ import { getDisplayWidth } from "./wcwidth.js";
2
2
 
3
3
  //#region wordwrap.ts
4
4
  /**
@@ -7,22 +7,13 @@ import { getDisplayWidth, stripAnsi } from "./wcwidth.js";
7
7
  *
8
8
  * @param text The text to wrap (may contain ANSI escape codes)
9
9
  * @param maxWidth Maximum width in terminal columns
10
- * @param messageContent The plain message content (used to find message start)
10
+ * @param indentWidth Indentation width for continuation lines
11
11
  * @returns Wrapped text with proper indentation
12
12
  */
13
- function wrapText(text, maxWidth, messageContent) {
13
+ function wrapText(text, maxWidth, indentWidth) {
14
14
  if (maxWidth <= 0) return text;
15
15
  const displayWidth = getDisplayWidth(text);
16
16
  if (displayWidth <= maxWidth && !text.includes("\n")) return text;
17
- const firstLineWords = messageContent.split(" ");
18
- const firstWord = firstLineWords[0];
19
- const plainText = stripAnsi(text);
20
- const messageStartIndex = plainText.indexOf(firstWord);
21
- let indentWidth = 0;
22
- if (messageStartIndex >= 0) {
23
- const prefixText = plainText.slice(0, messageStartIndex);
24
- indentWidth = getDisplayWidth(prefixText);
25
- }
26
17
  const indent = " ".repeat(Math.max(0, indentWidth));
27
18
  if (text.includes("\n")) {
28
19
  const lines = text.split("\n");
@@ -1 +1 @@
1
- {"version":3,"file":"wordwrap.js","names":["text: string","maxWidth: number","messageContent: string","wrappedLines: string[]","indent: string","lines: string[]"],"sources":["../wordwrap.ts"],"sourcesContent":["/**\n * @fileoverview\n * Word wrapping utilities for terminal output\n *\n * This module provides functions for wrapping text at specified widths\n * while preserving proper indentation and handling Unicode characters\n * correctly.\n */\n\nimport { getDisplayWidth, stripAnsi } from \"./wcwidth.ts\";\n\n/**\n * Wrap text at specified width with proper indentation for continuation lines.\n * Automatically detects the message start position from the first line.\n *\n * @param text The text to wrap (may contain ANSI escape codes)\n * @param maxWidth Maximum width in terminal columns\n * @param messageContent The plain message content (used to find message start)\n * @returns Wrapped text with proper indentation\n */\nexport function wrapText(\n text: string,\n maxWidth: number,\n messageContent: string,\n): string {\n if (maxWidth <= 0) return text;\n\n const displayWidth = getDisplayWidth(text);\n // If text has newlines (multiline interpolated values), always process it\n // even if it fits within the width\n if (displayWidth <= maxWidth && !text.includes(\"\\n\")) return text;\n\n // Find where the message content starts in the first line\n const firstLineWords = messageContent.split(\" \");\n const firstWord = firstLineWords[0];\n const plainText = stripAnsi(text);\n const messageStartIndex = plainText.indexOf(firstWord);\n\n // Calculate the display width of the text up to the message start\n // This is crucial for proper alignment when emojis are present\n let indentWidth = 0;\n if (messageStartIndex >= 0) {\n const prefixText = plainText.slice(0, messageStartIndex);\n indentWidth = getDisplayWidth(prefixText);\n }\n const indent = \" \".repeat(Math.max(0, indentWidth));\n\n // Check if text contains newlines (from interpolated values like Error objects)\n if (text.includes(\"\\n\")) {\n // Split by existing newlines and process each line\n const lines = text.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineDisplayWidth = getDisplayWidth(line);\n\n if (lineDisplayWidth <= maxWidth) {\n // Line doesn't need wrapping, but add indentation if it's not the first line\n if (i === 0) {\n wrappedLines.push(line);\n } else {\n wrappedLines.push(indent + line);\n }\n } else {\n // Line needs wrapping\n const wrappedLine = wrapSingleLine(line, maxWidth, indent);\n if (i === 0) {\n wrappedLines.push(wrappedLine);\n } else {\n // For continuation lines from interpolated values, add proper indentation\n const subLines = wrappedLine.split(\"\\n\");\n for (let j = 0; j < subLines.length; j++) {\n if (j === 0) {\n wrappedLines.push(indent + subLines[j]);\n } else {\n wrappedLines.push(subLines[j]);\n }\n }\n }\n }\n }\n\n return wrappedLines.join(\"\\n\");\n }\n\n // Process as a single line since log records should not have newlines in the formatted output\n return wrapSingleLine(text, maxWidth, indent);\n}\n\n/**\n * Wrap a single line of text (without existing newlines) at word boundaries.\n * Preserves ANSI escape codes and handles Unicode character widths correctly.\n *\n * @param text The text to wrap (single line, may contain ANSI codes)\n * @param maxWidth Maximum width in terminal columns\n * @param indent Indentation string for continuation lines\n * @returns Wrapped text with newlines and proper indentation\n */\nexport function wrapSingleLine(\n text: string,\n maxWidth: number,\n indent: string,\n): string {\n // Split text into chunks while preserving ANSI codes\n const lines: string[] = [];\n let currentLine = \"\";\n let currentDisplayWidth = 0;\n let i = 0;\n\n while (i < text.length) {\n // Check for ANSI escape sequence\n if (text[i] === \"\\x1b\" && text[i + 1] === \"[\") {\n // Find the end of the ANSI sequence\n let j = i + 2;\n while (j < text.length && text[j] !== \"m\") {\n j++;\n }\n if (j < text.length) {\n j++; // Include the 'm'\n currentLine += text.slice(i, j);\n i = j;\n continue;\n }\n }\n\n const char = text[i];\n\n // Check if adding this character would exceed the width\n if (currentDisplayWidth >= maxWidth && char !== \" \") {\n // Try to find a good break point (space) before the current position\n const breakPoint = currentLine.lastIndexOf(\" \");\n if (breakPoint > 0) {\n // Break at the space\n lines.push(currentLine.slice(0, breakPoint));\n currentLine = indent + currentLine.slice(breakPoint + 1) + char;\n currentDisplayWidth = getDisplayWidth(currentLine);\n } else {\n // No space found, hard break\n lines.push(currentLine);\n currentLine = indent + char;\n currentDisplayWidth = getDisplayWidth(currentLine);\n }\n } else {\n currentLine += char;\n // Recalculate display width properly for Unicode characters\n currentDisplayWidth = getDisplayWidth(currentLine);\n }\n\n i++;\n }\n\n if (currentLine.trim()) {\n lines.push(currentLine);\n }\n\n // Filter out empty lines (lines with only indentation/spaces)\n const filteredLines = lines.filter((line) => line.trim().length > 0);\n\n return filteredLines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,SAAgB,SACdA,MACAC,UACAC,gBACQ;AACR,KAAI,YAAY,EAAG,QAAO;CAE1B,MAAM,eAAe,gBAAgB,KAAK;AAG1C,KAAI,gBAAgB,aAAa,KAAK,SAAS,KAAK,CAAE,QAAO;CAG7D,MAAM,iBAAiB,eAAe,MAAM,IAAI;CAChD,MAAM,YAAY,eAAe;CACjC,MAAM,YAAY,UAAU,KAAK;CACjC,MAAM,oBAAoB,UAAU,QAAQ,UAAU;CAItD,IAAI,cAAc;AAClB,KAAI,qBAAqB,GAAG;EAC1B,MAAM,aAAa,UAAU,MAAM,GAAG,kBAAkB;AACxD,gBAAc,gBAAgB,WAAW;CAC1C;CACD,MAAM,SAAS,IAAI,OAAO,KAAK,IAAI,GAAG,YAAY,CAAC;AAGnD,KAAI,KAAK,SAAS,KAAK,EAAE;EAEvB,MAAM,QAAQ,KAAK,MAAM,KAAK;EAC9B,MAAMC,eAAyB,CAAE;AAEjC,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;GACrC,MAAM,OAAO,MAAM;GACnB,MAAM,mBAAmB,gBAAgB,KAAK;AAE9C,OAAI,oBAAoB,SAEtB,KAAI,MAAM,EACR,cAAa,KAAK,KAAK;OAEvB,cAAa,KAAK,SAAS,KAAK;QAE7B;IAEL,MAAM,cAAc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AAS,KAAK,MAAM,CAAC,SAAS,EAAE;AAEpE,QAAO,cAAc,KAAK,KAAK;AAChC"}
1
+ {"version":3,"file":"wordwrap.js","names":["text: string","maxWidth: number","indentWidth: number","wrappedLines: string[]","indent: string","lines: string[]"],"sources":["../wordwrap.ts"],"sourcesContent":["/**\n * @fileoverview\n * Word wrapping utilities for terminal output\n *\n * This module provides functions for wrapping text at specified widths\n * while preserving proper indentation and handling Unicode characters\n * correctly.\n */\n\nimport { getDisplayWidth } from \"./wcwidth.ts\";\n\n/**\n * Wrap text at specified width with proper indentation for continuation lines.\n * Automatically detects the message start position from the first line.\n *\n * @param text The text to wrap (may contain ANSI escape codes)\n * @param maxWidth Maximum width in terminal columns\n * @param indentWidth Indentation width for continuation lines\n * @returns Wrapped text with proper indentation\n */\nexport function wrapText(\n text: string,\n maxWidth: number,\n indentWidth: number,\n): string {\n if (maxWidth <= 0) return text;\n\n const displayWidth = getDisplayWidth(text);\n // If text has newlines (multiline interpolated values), always process it\n // even if it fits within the width\n if (displayWidth <= maxWidth && !text.includes(\"\\n\")) return text;\n\n const indent = \" \".repeat(Math.max(0, indentWidth));\n\n // Check if text contains newlines (from interpolated values like Error objects)\n if (text.includes(\"\\n\")) {\n // Split by existing newlines and process each line\n const lines = text.split(\"\\n\");\n const wrappedLines: string[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineDisplayWidth = getDisplayWidth(line);\n\n if (lineDisplayWidth <= maxWidth) {\n // Line doesn't need wrapping, but add indentation if it's not the first line\n if (i === 0) {\n wrappedLines.push(line);\n } else {\n wrappedLines.push(indent + line);\n }\n } else {\n // Line needs wrapping\n const wrappedLine = wrapSingleLine(line, maxWidth, indent);\n if (i === 0) {\n wrappedLines.push(wrappedLine);\n } else {\n // For continuation lines from interpolated values, add proper indentation\n const subLines = wrappedLine.split(\"\\n\");\n for (let j = 0; j < subLines.length; j++) {\n if (j === 0) {\n wrappedLines.push(indent + subLines[j]);\n } else {\n wrappedLines.push(subLines[j]);\n }\n }\n }\n }\n }\n\n return wrappedLines.join(\"\\n\");\n }\n\n // Process as a single line since log records should not have newlines in the formatted output\n return wrapSingleLine(text, maxWidth, indent);\n}\n\n/**\n * Wrap a single line of text (without existing newlines) at word boundaries.\n * Preserves ANSI escape codes and handles Unicode character widths correctly.\n *\n * @param text The text to wrap (single line, may contain ANSI codes)\n * @param maxWidth Maximum width in terminal columns\n * @param indent Indentation string for continuation lines\n * @returns Wrapped text with newlines and proper indentation\n */\nexport function wrapSingleLine(\n text: string,\n maxWidth: number,\n indent: string,\n): string {\n // Split text into chunks while preserving ANSI codes\n const lines: string[] = [];\n let currentLine = \"\";\n let currentDisplayWidth = 0;\n let i = 0;\n\n while (i < text.length) {\n // Check for ANSI escape sequence\n if (text[i] === \"\\x1b\" && text[i + 1] === \"[\") {\n // Find the end of the ANSI sequence\n let j = i + 2;\n while (j < text.length && text[j] !== \"m\") {\n j++;\n }\n if (j < text.length) {\n j++; // Include the 'm'\n currentLine += text.slice(i, j);\n i = j;\n continue;\n }\n }\n\n const char = text[i];\n\n // Check if adding this character would exceed the width\n if (currentDisplayWidth >= maxWidth && char !== \" \") {\n // Try to find a good break point (space) before the current position\n const breakPoint = currentLine.lastIndexOf(\" \");\n if (breakPoint > 0) {\n // Break at the space\n lines.push(currentLine.slice(0, breakPoint));\n currentLine = indent + currentLine.slice(breakPoint + 1) + char;\n currentDisplayWidth = getDisplayWidth(currentLine);\n } else {\n // No space found, hard break\n lines.push(currentLine);\n currentLine = indent + char;\n currentDisplayWidth = getDisplayWidth(currentLine);\n }\n } else {\n currentLine += char;\n // Recalculate display width properly for Unicode characters\n currentDisplayWidth = getDisplayWidth(currentLine);\n }\n\n i++;\n }\n\n if (currentLine.trim()) {\n lines.push(currentLine);\n }\n\n // Filter out empty lines (lines with only indentation/spaces)\n const filteredLines = lines.filter((line) => line.trim().length > 0);\n\n return filteredLines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,SAAgB,SAC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,GAAG,EAAE;AAC/B,QAAI;AACJ;GACD;EACF;EAED,MAAM,OAAO,KAAK;AAGlB,MAAI,uBAAuB,YAAY,SAAS,KAAK;GAEnD,MAAM,aAAa,YAAY,YAAY,IAAI;AAC/C,OAAI,aAAa,GAAG;AAElB,UAAM,KAAK,YAAY,MAAM,GAAG,WAAW,CAAC;AAC5C,kBAAc,SAAS,YAAY,MAAM,aAAa,EAAE,GAAG;AAC3D,0BAAsB,gBAAgB,YAAY;GACnD,OAAM;AAEL,UAAM,KAAK,YAAY;AACvB,kBAAc,SAAS;AACvB,0BAAsB,gBAAgB,YAAY;GACnD;EACF,OAAM;AACL,kBAAe;AAEf,yBAAsB,gBAAgB,YAAY;EACnD;AAED;CACD;AAED,KAAI,YAAY,MAAM,CACpB,OAAM,KAAK,YAAY;CAIzB,MAAM,gBAAgB,MAAM,OAAO,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EAAE;AAEpE,QAAO,cAAc,KAAK,KAAK;AAChC"}
package/formatter.test.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { suite } from "@alinea/suite";
2
+ import type { LogRecord } from "@logtape/logtape";
2
3
  import { assert } from "@std/assert/assert";
3
4
  import { assertEquals } from "@std/assert/equals";
4
5
  import { assertMatch } from "@std/assert/match";
5
6
  import { assertStringIncludes } from "@std/assert/string-includes";
6
- import type { LogRecord } from "@logtape/logtape";
7
7
  import {
8
8
  type CategoryColorMap,
9
9
  getPrettyFormatter,
@@ -17,6 +17,7 @@ function createLogRecord(
17
17
  category: string[],
18
18
  message: LogRecord["message"],
19
19
  timestamp: number = Date.now(),
20
+ properties: Record<string, unknown> = {},
20
21
  ): LogRecord {
21
22
  // Convert message array to template strings format for rawMessage
22
23
  const rawMessage = typeof message === "string"
@@ -28,7 +29,7 @@ function createLogRecord(
28
29
  category,
29
30
  message,
30
31
  rawMessage,
31
- properties: {},
32
+ properties,
32
33
  timestamp,
33
34
  };
34
35
  }
@@ -802,3 +803,29 @@ test("getPrettyFormatter() with multiline interpolated values (no align)", () =>
802
803
  }
803
804
  }
804
805
  });
806
+
807
+ test("properties set to true", () => {
808
+ const formatter = getPrettyFormatter({
809
+ properties: true,
810
+ colors: false,
811
+ inspectOptions: { colors: false },
812
+ });
813
+
814
+ const record = createLogRecord("info", ["test"], ["FooBar"], Date.now(), {
815
+ foo: "bar",
816
+ bar: "baz",
817
+ });
818
+ const result = formatter(record);
819
+
820
+ // Should contain multiple lines due to wrapping
821
+ const lines = result.split("\n");
822
+ assertEquals(lines.length, 4); // Normal log line + formatted properties + newline
823
+ assertEquals(
824
+ lines[1].trim(),
825
+ "Deno" in globalThis ? 'foo: "bar"' : "foo: 'bar'",
826
+ );
827
+ assertEquals(
828
+ lines[2].trim(),
829
+ "Deno" in globalThis ? 'bar: "baz"' : "bar: 'baz'",
830
+ );
831
+ });
package/formatter.ts CHANGED
@@ -1,13 +1,14 @@
1
- import type {
2
- LogLevel,
3
- LogRecord,
4
- TextFormatter,
5
- TextFormatterOptions,
1
+ import {
2
+ getLogLevels,
3
+ type LogLevel,
4
+ type LogRecord,
5
+ type TextFormatter,
6
+ type TextFormatterOptions,
6
7
  } from "@logtape/logtape";
7
- import { inspect } from "#util";
8
+ import { inspect, type InspectOptions } from "#util";
8
9
  import { getOptimalWordWrapWidth } from "./terminal.ts";
9
10
  import { truncateCategory, type TruncationStrategy } from "./truncate.ts";
10
- import { getDisplayWidth } from "./wcwidth.ts";
11
+ import { getDisplayWidth, stripAnsi } from "./wcwidth.ts";
11
12
  import { wrapText } from "./wordwrap.ts";
12
13
 
13
14
  /**
@@ -567,6 +568,18 @@ export interface PrettyFormatterOptions
567
568
  readonly compact?: boolean;
568
569
  };
569
570
 
571
+ /**
572
+ * Configuration to always render structured data.
573
+ *
574
+ * If set to `true`, any structured data that is logged will
575
+ * always be rendered. This can be very verbose. Make sure
576
+ * to configure `inspectOptions` properly for your usecase.
577
+ *
578
+ * @default `false`
579
+ * @since 1.1.0
580
+ */
581
+ readonly properties?: boolean;
582
+
570
583
  /**
571
584
  * Enable word wrapping for long messages.
572
585
  *
@@ -662,6 +675,7 @@ export function getPrettyFormatter(
662
675
  colors: useColors = true,
663
676
  align = true,
664
677
  inspectOptions = {},
678
+ properties = false,
665
679
  wordWrap = true,
666
680
  } = options;
667
681
 
@@ -790,14 +804,7 @@ export function getPrettyFormatter(
790
804
  const categoryPatterns = prepareCategoryPatterns(categoryColorMap);
791
805
 
792
806
  // Calculate level width based on format
793
- const allLevels: LogLevel[] = [
794
- "trace",
795
- "debug",
796
- "info",
797
- "warning",
798
- "error",
799
- "fatal",
800
- ];
807
+ const allLevels: LogLevel[] = [...getLogLevels()];
801
808
  const levelWidth = Math.max(...allLevels.map((l) => formatLevel(l).length));
802
809
 
803
810
  return (record: LogRecord): string => {
@@ -926,13 +933,28 @@ export function getPrettyFormatter(
926
933
 
927
934
  let result =
928
935
  `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} ${formattedMessage}`;
936
+ const indentWidth = getDisplayWidth(
937
+ stripAnsi(
938
+ `${formattedTimestamp}${formattedIcon} ${paddedLevel} ${paddedCategory} `,
939
+ ),
940
+ );
929
941
 
930
942
  // Apply word wrapping if enabled, or if there are multiline interpolated values
931
943
  if (wordWrapEnabled || message.includes("\n")) {
932
944
  result = wrapText(
933
945
  result,
934
946
  wordWrapEnabled ? wordWrapWidth : Infinity,
935
- message,
947
+ indentWidth,
948
+ );
949
+ }
950
+
951
+ if (properties) {
952
+ result += formatProperties(
953
+ record,
954
+ indentWidth,
955
+ wordWrapEnabled ? wordWrapWidth : Infinity,
956
+ useColors,
957
+ inspectOptions,
936
958
  );
937
959
  }
938
960
 
@@ -940,13 +962,28 @@ export function getPrettyFormatter(
940
962
  } else {
941
963
  let result =
942
964
  `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} ${formattedMessage}`;
965
+ const indentWidth = getDisplayWidth(
966
+ stripAnsi(
967
+ `${formattedTimestamp}${formattedIcon} ${formattedLevel} ${formattedCategory} `,
968
+ ),
969
+ );
943
970
 
944
971
  // Apply word wrapping if enabled, or if there are multiline interpolated values
945
972
  if (wordWrapEnabled || message.includes("\n")) {
946
973
  result = wrapText(
947
974
  result,
948
975
  wordWrapEnabled ? wordWrapWidth : Infinity,
949
- message,
976
+ indentWidth,
977
+ );
978
+ }
979
+
980
+ if (properties) {
981
+ result += formatProperties(
982
+ record,
983
+ indentWidth,
984
+ wordWrapEnabled ? wordWrapWidth : Infinity,
985
+ useColors,
986
+ inspectOptions,
950
987
  );
951
988
  }
952
989
 
@@ -955,6 +992,28 @@ export function getPrettyFormatter(
955
992
  };
956
993
  }
957
994
 
995
+ function formatProperties(
996
+ record: LogRecord,
997
+ indentWidth: number,
998
+ maxWidth: number,
999
+ useColors: boolean,
1000
+ inspectOptions: InspectOptions,
1001
+ ): string {
1002
+ let result = "";
1003
+ for (const prop in record.properties) {
1004
+ const propValue = record.properties[prop];
1005
+ const pad = indentWidth - getDisplayWidth(prop) - 2;
1006
+ result += "\n" + wrapText(
1007
+ `${" ".repeat(pad)}${useColors ? DIM : ""}${prop}:${
1008
+ useColors ? RESET : ""
1009
+ } ${inspect(propValue, { colors: useColors, ...inspectOptions })}`,
1010
+ maxWidth,
1011
+ indentWidth,
1012
+ );
1013
+ }
1014
+ return result;
1015
+ }
1016
+
958
1017
  /**
959
1018
  * A pre-configured beautiful console formatter for local development.
960
1019
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/pretty",
3
- "version": "1.1.0-dev.306+60b6894a",
3
+ "version": "1.1.0-dev.315+fc46f65c",
4
4
  "description": "Beautiful text formatter for LogTape—perfect for local development",
5
5
  "keywords": [
6
6
  "logging",
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "sideEffects": false,
77
77
  "peerDependencies": {
78
- "@logtape/logtape": "1.1.0-dev.306+60b6894a"
78
+ "@logtape/logtape": "1.1.0-dev.315+fc46f65c"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@alinea/suite": "^0.6.3",
package/wordwrap.test.ts CHANGED
@@ -6,14 +6,14 @@ import { wrapText } from "./wordwrap.ts";
6
6
  const test = suite(import.meta);
7
7
 
8
8
  test("wrapText() should not wrap short text", () => {
9
- const result = wrapText("short text", 80, "short text");
9
+ const result = wrapText("short text", 80, "short text".length);
10
10
  assertEquals(result, "short text");
11
11
  });
12
12
 
13
13
  test("wrapText() should wrap long text", () => {
14
14
  const text =
15
15
  "This is a very long line that should be wrapped at 40 characters maximum width for testing purposes.";
16
- const result = wrapText(text, 40, "This is a very long line");
16
+ const result = wrapText(text, 40, "This is a very long line".length);
17
17
 
18
18
  const lines = result.split("\n");
19
19
  assert(lines.length > 1, "Should have multiple lines");
@@ -27,7 +27,7 @@ test("wrapText() should wrap long text", () => {
27
27
  test("wrapText() should preserve ANSI codes", () => {
28
28
  const text =
29
29
  "\x1b[31mThis is a very long red line that should be wrapped while preserving the color codes\x1b[0m";
30
- const result = wrapText(text, 40, "This is a very long red line");
30
+ const result = wrapText(text, 40, "This is a very long red line".length);
31
31
 
32
32
  // Should contain ANSI codes
33
33
  assert(result.includes("\x1b[31m"), "Should preserve opening ANSI code");
@@ -37,7 +37,7 @@ test("wrapText() should preserve ANSI codes", () => {
37
37
  test("wrapText() should handle emojis correctly", () => {
38
38
  const text =
39
39
  "✨ info test This is a very long message that should wrap properly with emoji alignment";
40
- const result = wrapText(text, 40, "This is a very long message");
40
+ const result = wrapText(text, 40, "This is a very long message".length);
41
41
 
42
42
  const lines = result.split("\n");
43
43
  assert(lines.length > 1, "Should have multiple lines");
@@ -57,7 +57,7 @@ test("wrapText() should handle emojis correctly", () => {
57
57
  test("wrapText() should handle newlines in interpolated content", () => {
58
58
  const textWithNewlines =
59
59
  "Error occurred: Error: Something went wrong\n at line 1\n at line 2";
60
- const result = wrapText(textWithNewlines, 40, "Error occurred");
60
+ const result = wrapText(textWithNewlines, 40, "Error occurred".length);
61
61
 
62
62
  const lines = result.split("\n");
63
63
  assert(
@@ -71,8 +71,12 @@ test("wrapText() should calculate indentation based on display width", () => {
71
71
  const sparklesText = "✨ info test Message content here";
72
72
  const crossText = "❌ error test Message content here";
73
73
 
74
- const sparklesResult = wrapText(sparklesText, 25, "Message content here");
75
- const crossResult = wrapText(crossText, 25, "Message content here");
74
+ const sparklesResult = wrapText(
75
+ sparklesText,
76
+ 25,
77
+ "Message content here".length,
78
+ );
79
+ const crossResult = wrapText(crossText, 25, "Message content here".length);
76
80
 
77
81
  const sparklesLines = sparklesResult.split("\n");
78
82
  const crossLines = crossResult.split("\n");
@@ -93,13 +97,13 @@ test("wrapText() should calculate indentation based on display width", () => {
93
97
  });
94
98
 
95
99
  test("wrapText() should handle zero width", () => {
96
- const result = wrapText("any text", 0, "any text");
100
+ const result = wrapText("any text", 0, "any text".length);
97
101
  assertEquals(result, "any text");
98
102
  });
99
103
 
100
104
  test("wrapText() should break at word boundaries", () => {
101
105
  const text = "word1 word2 word3 word4 word5";
102
- const result = wrapText(text, 15, "word1 word2 word3");
106
+ const result = wrapText(text, 15, "word1 word2 word3".length);
103
107
 
104
108
  const lines = result.split("\n");
105
109
  // Should break at spaces, not in the middle of words
package/wordwrap.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * correctly.
8
8
  */
9
9
 
10
- import { getDisplayWidth, stripAnsi } from "./wcwidth.ts";
10
+ import { getDisplayWidth } from "./wcwidth.ts";
11
11
 
12
12
  /**
13
13
  * Wrap text at specified width with proper indentation for continuation lines.
@@ -15,13 +15,13 @@ import { getDisplayWidth, stripAnsi } from "./wcwidth.ts";
15
15
  *
16
16
  * @param text The text to wrap (may contain ANSI escape codes)
17
17
  * @param maxWidth Maximum width in terminal columns
18
- * @param messageContent The plain message content (used to find message start)
18
+ * @param indentWidth Indentation width for continuation lines
19
19
  * @returns Wrapped text with proper indentation
20
20
  */
21
21
  export function wrapText(
22
22
  text: string,
23
23
  maxWidth: number,
24
- messageContent: string,
24
+ indentWidth: number,
25
25
  ): string {
26
26
  if (maxWidth <= 0) return text;
27
27
 
@@ -30,19 +30,6 @@ export function wrapText(
30
30
  // even if it fits within the width
31
31
  if (displayWidth <= maxWidth && !text.includes("\n")) return text;
32
32
 
33
- // Find where the message content starts in the first line
34
- const firstLineWords = messageContent.split(" ");
35
- const firstWord = firstLineWords[0];
36
- const plainText = stripAnsi(text);
37
- const messageStartIndex = plainText.indexOf(firstWord);
38
-
39
- // Calculate the display width of the text up to the message start
40
- // This is crucial for proper alignment when emojis are present
41
- let indentWidth = 0;
42
- if (messageStartIndex >= 0) {
43
- const prefixText = plainText.slice(0, messageStartIndex);
44
- indentWidth = getDisplayWidth(prefixText);
45
- }
46
33
  const indent = " ".repeat(Math.max(0, indentWidth));
47
34
 
48
35
  // Check if text contains newlines (from interpolated values like Error objects)