ReviewOS

also looking at this

stacks/ts-aax

chore: enhance logging

#55
Merged cab-mikee wants to merge chore/enhance-logging into main
12 files +379 -9

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

package.jsonmodified+1-1
Changes to package.json
@@ -70,7 +70,7 @@
7070 "buddy-bot": "^0.9.7",
7171 "bumpp": "^10.1.0",
7272 "bun-git-hooks": "^0.2.19",
73 "bun-plugin-dtsx": "^0.21.12",\
73 "bun-plugin-dtsx": "^0.21.12",
7474 "bunfig": "^0.8.5",
7575 "changelogen": "^0.6.2",
7676 "typescript": "^5.9.2"
src/converter.tsmodified+35-7
Changes to src/converter.ts
@@ -4,7 +4,7 @@ import path from 'node:path'
44import { config } from './config'
55import { getActivationBytesFromAudibleCli } from './utils/activation'
66import { checkFFmpeg, runFFmpeg } from './utils/ffmpeg'
7import { logger } from './utils/logger'
7import { logger, reportError } from './utils/logger'
88import { getBookMetadata } from './utils/metadata'
99
1010function generateOutputPath(metadata: any, options: ConversionOptions): string {
@@ -71,7 +71,16 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion
7171 // Check for ffmpeg
7272 const ffmpegAvailable = await checkFFmpeg()
7373 if (!ffmpegAvailable) {
74 logger.error('FFmpeg is not available. Please install FFmpeg and try again.')
74 reportError(new Error('FFmpeg is not available'), {
75 heading: 'FFmpeg not found. Required for conversion.',
76 details: 'The converter requires FFmpeg to decrypt and transcode AAX files.',
77 hints: [
78 'Install on macOS: brew install ffmpeg',
79 'Install on Linux: use your package manager (e.g., apt install ffmpeg)',
80 'Install on Windows: https://ffmpeg.org/download.html',
81 'Alternatively set ffmpegPath in aax.config.ts to your ffmpeg binary',
82 ],
83 })
7584 return {
7685 success: false,
7786 error: 'FFmpeg not found. Required for conversion.',
@@ -83,9 +92,15 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion
8392 const activationCode = options.activationCode || config.activationCode || await getActivationBytesFromAudibleCli()
8493
8594 if (!activationCode) {
86 logger.error('No activation code provided for decryption.')
87 logger.info('You can specify an activation code with the -c option or set it in your config.')
88 logger.info('To auto-detect activation code, run "aax setup-audible" first.')
95 reportError(new Error('Missing activation code'), {
96 heading: 'No activation code provided for decryption.',
97 details: 'Audible AAX files require an 8-character activation code (activation bytes) to decrypt.',
98 hints: [
99 'Provide activationCode in options or in aax.config.ts',
100 'Use Audible CLI to fetch: audible activation-bytes (run audible quickstart first)',
101 'Try environment overrides and run again with AAX_LOG_LEVEL=debug for more output',
102 ],
103 })
89104 return {
90105 success: false,
91106 error: 'No activation code provided. This is required to convert AAX files.',
@@ -231,7 +246,15 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion
231246 }
232247 }
233248
234 logger.error('Conversion failed. Check the logs for details.')
249 reportError(new Error('Conversion failed'), {
250 heading: 'Conversion failed.',
251 details: 'FFmpeg returned a non-zero exit code.',
252 hints: [
253 'Verify the activation code is correct (case sensitive)',
254 'Try running with AAX_LOG_LEVEL=debug to see the FFmpeg command and output',
255 'Ensure input file is a valid AAX and not corrupted',
256 ],
257 })
235258 return {
236259 success: false,
237260 error: `FFmpeg conversion failed: ${output}`,
@@ -239,7 +262,12 @@ export async function convertAAX(options: ConversionOptions): Promise<Conversion
239262 }
240263 }
241264 catch (error) {
242 logger.error(`Error during conversion: ${(error as Error).message}`)
265 reportError(error, {
266 heading: 'Unexpected error during conversion.',
267 hints: [
268 'Re-run with AAX_LOG_LEVEL=debug to include stack traces',
269 ],
270 })
243271 return {
244272 success: false,
245273 error: `Error during conversion: ${(error as Error).message}`,
src/utils/logger.tsmodified+63-1
Changes to src/utils/logger.ts
@@ -1,9 +1,16 @@
1import process from 'node:process'
12import { Logger } from '@stacksjs/clarity'
23
4// Determine log level via env (falls back to info). Only allow levels supported by clarity Logger
5const envLevel = (process.env.AAX_LOG_LEVEL || '').toLowerCase()
6const allowedLevels = ['error', 'info', 'debug'] as const
7type AllowedLevel = typeof allowedLevels[number]
8const level: AllowedLevel = (allowedLevels as readonly string[]).includes(envLevel) ? (envLevel as AllowedLevel) : 'info'
9
310// Create a logger instance with a fancy UI
411export const logger: Logger = new Logger('aax', {
512 fancy: true,
6 level: 'info',
13 level,
714 showTags: true,
815})
916
@@ -73,3 +80,58 @@ export function formatTime(ms: number): string {
7380
7481 return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
7582}
83
84/**
85 * Report an error with optional heading, details and hints.
86 * In debug mode (AAX_LOG_LEVEL=debug or AAX_DEBUG=1), also prints stack traces when available.
87 */
88export function reportError(
89 error: unknown,
90 options?: {
91 heading?: string
92 details?: string
93 hints?: string[]
94 },
95): void {
96 const isDebug = level === 'debug' || process.env.AAX_DEBUG === '1'
97
98 const heading = options?.heading
99 const details = options?.details
100 const hints = options?.hints || []
101
102 // Extract message/stack from various error shapes
103 const errObj = normalizeError(error)
104
105 if (heading)
106 logger.error(heading)
107
108 if (errObj.message)
109 logger.error(errObj.message)
110
111 if (details)
112 logger.warn(details)
113
114 for (const hint of hints)
115 logger.warn(`Hint: ${hint}`)
116
117 if (isDebug && errObj.stack)
118 logger.debug(errObj.stack)
119}
120
121/**
122 * Normalize unknown errors to a consistent shape.
123 */
124export function normalizeError(error: unknown): { message: string; stack?: string } {
125 if (error instanceof Error) {
126 return { message: error.message, stack: error.stack }
127 }
128 if (typeof error === 'string') {
129 return { message: error }
130 }
131 try {
132 return { message: JSON.stringify(error) }
133 }
134 catch {
135 return { message: String(error) }
136 }
137}