@ubercode/chronicler 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/constants.ts","../src/core/errors.ts","../src/core/backend.ts","../src/core/reserved.ts","../src/core/context.ts","../src/core/fields.ts","../src/core/events.ts","../src/core/validation.ts","../src/core/chronicle.ts"],"names":[],"mappings":";;;AAQO,IAAM,UAAA,GAAa;AAAA,EACxB,KAAA,EAAO,CAAA;AAAA;AAAA,EACP,QAAA,EAAU,CAAA;AAAA;AAAA,EACV,KAAA,EAAO,CAAA;AAAA;AAAA,EACP,KAAA,EAAO,CAAA;AAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA;AAAA,EACP,KAAA,EAAO;AAAA;AACT,CAAA;AAWO,IAAM,uBAAA,GAA0B,MAAA,CAAO,IAAA,CAAK,UAAU,CAAA;AAKtD,IAAM,8BAAA,GAAiC,IAAI,EAAA,GAAK,GAAA;AAKhD,IAAM,YAAA,GAAe,GAAA;AAMrB,IAAM,iBAAA,GAAoB,GAAA;AAK1B,IAAM,wBAAA,GAA2B,GAAA;AAKjC,IAAM,sBAAA,GAAyB,EAAA;AAK/B,IAAM,+BAAA,GAAkC,GAAA;;;AChDxC,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAChC,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;;;ACjBA,IAAM,iBAAA,GAAqD;AAAA,EACzD,KAAA,EAAO,OAAA;AA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;AAAE,GAChC,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * Global constants used throughout Chronicler\n */\n\n/**\n * Log level priority mapping\n * Lower numbers = higher priority/severity\n */\nexport const LOG_LEVELS = {\n fatal: 0, // System is unusable\n critical: 1, // Critical conditions requiring immediate attention\n alert: 2, // Action must be taken immediately\n error: 3, // Error conditions\n warn: 4, // Warning conditions\n audit: 5, // Audit trail events (compliance, security)\n info: 6, // Informational messages\n debug: 7, // Debug-level messages\n trace: 8, // Trace-level messages (very verbose)\n} as const;\n\n/**\n * Union of all valid log level names, derived from {@link LOG_LEVELS}.\n */\nexport type LogLevel = keyof typeof LOG_LEVELS;\n\n/**\n * All required log levels that backends must implement.\n * Derived from LOG_LEVELS keys to prevent drift.\n */\nexport const DEFAULT_REQUIRED_LEVELS = Object.keys(LOG_LEVELS) as readonly LogLevel[];\n\n/**\n * Default correlation timeout in milliseconds (5 minutes)\n */\nexport const DEFAULT_CORRELATION_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Root fork ID for the base chronicle instance\n */\nexport const ROOT_FORK_ID = '0';\n\n/**\n * Separator used in hierarchical fork IDs\n * @example '1.1', '1.2.3'\n */\nexport const FORK_ID_SEPARATOR = '.';\n\n/**\n * Default maximum number of context keys per ContextStore\n */\nexport const DEFAULT_MAX_CONTEXT_KEYS = 100;\n\n/**\n * Default maximum fork nesting depth\n */\nexport const DEFAULT_MAX_FORK_DEPTH = 10;\n\n/**\n * Default maximum number of active (uncompleted) correlations\n */\nexport const DEFAULT_MAX_ACTIVE_CORRELATIONS = 1000;\n","export type ChroniclerErrorCode =\r\n | 'UNSUPPORTED_LOG_LEVEL'\r\n | 'RESERVED_FIELD'\r\n | 'BACKEND_METHOD'\r\n | 'FORK_DEPTH_EXCEEDED'\r\n | 'CORRELATION_LIMIT_EXCEEDED'\r\n | 'FIELD_VALIDATION';\r\n\r\n/**\r\n * Typed error class for Chronicler configuration and runtime failures.\r\n * Uses a discriminator `code` to identify the specific error category.\r\n */\r\nexport class ChroniclerError extends Error {\r\n readonly code: ChroniclerErrorCode;\r\n\r\n /**\r\n * @param code - Machine-readable error category discriminator\r\n * @param message - Human-readable description of the error\r\n */\r\n constructor(code: ChroniclerErrorCode, message: string) {\r\n super(message);\r\n this.name = 'ChroniclerError';\r\n this.code = code;\r\n }\r\n}\r\n","import { DEFAULT_REQUIRED_LEVELS, type LogLevel } from './constants';\nimport { ChroniclerError } from './errors';\nimport type { ValidationMetadata } from './validation';\n\ntype ConsoleMethod = 'error' | 'warn' | 'info' | 'debug';\n\n/** Maps each Chronicler log level to its corresponding console method. */\nconst CONSOLE_LEVEL_MAP: Record<LogLevel, ConsoleMethod> = {\n fatal: 'error',\n critical: 'error',\n alert: 'error',\n error: 'error',\n warn: 'warn',\n audit: 'info',\n info: 'info',\n debug: 'debug',\n trace: 'debug',\n};\n\n/** Ordered fallback chains for backend levels — tried sequentially when a level handler is missing. */\nconst LEVEL_FALLBACK_CHAINS: Record<LogLevel, readonly LogLevel[]> = {\n fatal: ['critical', 'error', 'warn', 'info'],\n critical: ['error', 'warn', 'info'],\n alert: ['error', 'warn', 'info'],\n error: ['warn', 'info'],\n warn: ['info'],\n audit: ['info'],\n info: [],\n debug: ['info'],\n trace: ['debug', 'info'],\n};\n\nexport interface LogPayload {\n readonly eventKey: string;\n readonly fields: Record<string, unknown>;\n readonly correlationId: string;\n readonly forkId: string;\n readonly metadata: Record<string, unknown>;\n readonly timestamp: string;\n readonly _validation?: ValidationMetadata;\n}\n\nexport type LogBackend = Record<LogLevel, (message: string, payload: LogPayload) => void>;\n\n/**\n * Call a backend logger method.\n *\n * Backend exceptions are caught and reported to `console.error` so that\n * logging never crashes the caller. Only missing backend methods (a\n * configuration error) still throw.\n *\n * @param backend - Logger object\n * @param level - Log level\n * @param message - Log message\n * @param payload - Log payload\n * @throws {ChroniclerError} `BACKEND_METHOD` if the backend does not support the log level\n */\nexport const callBackendMethod = (\n backend: LogBackend,\n level: LogLevel,\n message: string,\n payload: LogPayload,\n): void => {\n if (typeof backend[level] !== 'function') {\n throw new ChroniclerError('BACKEND_METHOD', `Backend does not support log level: ${level}`);\n }\n try {\n backend[level](message, payload);\n } catch (err: unknown) {\n console.error(\n '[chronicler] Backend error during log emission:',\n err instanceof Error ? err.message : 'Unknown error',\n );\n }\n};\n\n/**\n * Create a zero-config backend that logs to the console.\n *\n * Maps each of the 9 Chronicler levels to the appropriate `console` method:\n * fatal/critical/alert/error → `console.error`, warn → `console.warn`,\n * audit/info → `console.info`, debug/trace → `console.debug`.\n *\n * @returns A fully populated LogBackend using console methods for all levels\n */\nexport const createConsoleBackend = (): LogBackend => {\n const backend = {} as LogBackend;\n for (const level of DEFAULT_REQUIRED_LEVELS) {\n const method = CONSOLE_LEVEL_MAP[level];\n // eslint-disable-next-line no-console -- createConsoleBackend: console IS the backend\n backend[level] = (message: string, payload: LogPayload) => console[method](message, payload);\n }\n return backend;\n};\n\n/**\n * Create a backend from a partial set of handlers.\n *\n * For each missing level, the fallback chain is tried in order (e.g. `fatal` →\n * `critical` → `error` → `warn` → `info`). If no fallback is provided either,\n * the corresponding `console` method is used.\n *\n * @param partial - Partial backend with handlers for a subset of log levels\n * @returns A fully populated LogBackend with fallbacks applied for missing levels\n */\nexport const createBackend = (partial: Partial<LogBackend>): LogBackend => {\n const backend = {} as LogBackend;\n for (const level of DEFAULT_REQUIRED_LEVELS) {\n if (typeof partial[level] === 'function') {\n backend[level] = partial[level];\n continue;\n }\n const fallback = LEVEL_FALLBACK_CHAINS[level].find((fb) => typeof partial[fb] === 'function');\n if (fallback) {\n backend[level] = partial[fallback]!;\n } else {\n const method = CONSOLE_LEVEL_MAP[level];\n // eslint-disable-next-line no-console -- createBackend fallback: console IS the fallback backend\n backend[level] = (message: string, payload: LogPayload) => console[method](message, payload);\n }\n }\n return backend;\n};\n\n/**\n * A routing rule that pairs a backend with an optional filter.\n *\n * When `filter` is omitted the backend receives all events.\n * When provided, the backend only receives events for which `filter` returns `true`.\n */\nexport interface BackendRoute {\n readonly backend: LogBackend;\n readonly filter?: (level: LogLevel, payload: LogPayload) => boolean;\n}\n\n/**\n * Create a backend that routes events to multiple backends based on filter rules.\n *\n * Each route pairs a backend with an optional filter function. Events are\n * dispatched to every route whose filter matches (or to all routes without a\n * filter). This enables splitting logs into separate streams — for example,\n * maintenance/debug logs to stdout and audit events to a dedicated store.\n *\n * @param routes - One or more backend routes with optional filters\n * @returns A single LogBackend that fans out to the matching routes\n * @throws {Error} If no routes are provided\n *\n * @example\n * ```typescript\n * const router = createRouterBackend([\n * { backend: consoleBackend, filter: (level, payload) => !payload.eventKey.startsWith('audit.') },\n * { backend: auditBackend, filter: (level, payload) => payload.eventKey.startsWith('audit.') },\n * ]);\n *\n * const chronicle = createChronicle({ backend: router, metadata: { appName: 'my-app' } });\n * ```\n */\nexport const createRouterBackend = (routes: BackendRoute[]): LogBackend => {\n if (routes.length === 0) {\n throw new Error('createRouterBackend requires at least one route.');\n }\n const backend = {} as LogBackend;\n for (const level of DEFAULT_REQUIRED_LEVELS) {\n backend[level] = (message: string, payload: LogPayload) => {\n for (const route of routes) {\n if (!route.filter || route.filter(level, payload)) {\n callBackendMethod(route.backend, level, message, payload);\n }\n }\n };\n }\n return backend;\n};\n","/** Reserved top-level field names that cannot be used in user context or metadata. */\nexport const RESERVED_TOP_LEVEL_FIELDS = [\n 'eventKey',\n 'level',\n 'message',\n 'correlationId',\n 'forkId',\n 'timestamp',\n 'fields',\n '_validation',\n] as const;\n\nexport type ReservedTopLevelField = (typeof RESERVED_TOP_LEVEL_FIELDS)[number];\n\n/** Set for O(1) lookup during validation. */\nconst TOP_LEVEL_SET = new Set<string>(RESERVED_TOP_LEVEL_FIELDS);\n\n/**\n * Check if a key is a reserved top-level field.\n *\n * @param key - Field name to check against the reserved set\n * @returns True if the key is reserved and must not be used in user context or metadata\n */\nexport const isReservedTopLevelField = (key: string): key is ReservedTopLevelField =>\n TOP_LEVEL_SET.has(key);\n\n/**\n * Check a record for reserved keys and return array of violations\n * @param record - Object to check\n * @returns Array of reserved keys found in the record\n */\nexport const assertNoReservedKeys = (record: Record<string, unknown>): string[] => {\n const invalid: string[] = [];\n for (const key of Object.keys(record)) {\n if (isReservedTopLevelField(key)) {\n invalid.push(key);\n }\n }\n return invalid;\n};\n","import { isReservedTopLevelField } from './reserved';\n\n/** Type guard for context-safe primitive values. */\nconst isSimpleValue = (value: unknown): value is string | number | boolean | null =>\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean';\n\n/** Object prototype keys blocked to prevent prototype pollution. */\nconst DANGEROUS_KEYS = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n 'toString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__',\n]);\n\nexport type ContextValue = string | number | boolean | null;\n\nexport type ContextRecord = Record<string, ContextValue>;\n\nexport interface ContextCollisionDetail {\n readonly key: string;\n readonly existingValue: ContextValue;\n readonly attemptedValue: ContextValue;\n}\n\nexport interface ContextValidationResult {\n readonly reserved: string[];\n readonly collisionDetails: ContextCollisionDetail[];\n readonly dropped: string[];\n}\n\n/**\n * Sanitize and validate context input\n *\n * **Validation Strategy:**\n * - Returns validation results rather than throwing errors\n * - Logs should succeed even with invalid metadata\n * - Validation errors are reported via system events and _validation metadata\n *\n * **Collision Handling:**\n * - When a key exists with a different value, the ORIGINAL value is preserved\n * - The attempted new value is rejected\n * - A collision detail is recorded for system event emission\n *\n * **Reserved Fields:**\n * - Reserved field attempts are silently dropped\n * - A warning is recorded for system event emission\n *\n * @param context - New context to add\n * @param existingContext - Current context (for collision detection)\n * @returns Sanitized context and validation results\n *\n * @see {@link ContextValidationResult} for validation result structure\n */\n/* eslint-disable complexity -- validation branches are each a distinct concern */\nexport const sanitizeContextInput = (\n context: ContextRecord,\n existingContext: ContextRecord = {},\n maxNewKeys = Infinity,\n): {\n context: ContextRecord;\n validation: ContextValidationResult;\n} => {\n const sanitized: ContextRecord = {};\n const reserved: string[] = [];\n const collisionDetails: ContextCollisionDetail[] = [];\n const dropped: string[] = [];\n let acceptedCount = 0;\n\n for (const [key, rawValue] of Object.entries(context)) {\n if (isReservedTopLevelField(key)) {\n reserved.push(key);\n continue;\n }\n\n if (DANGEROUS_KEYS.has(key)) {\n reserved.push(key);\n continue;\n }\n\n // Invalid type (object, array, undefined, etc.) - skip this key\n if (!isSimpleValue(rawValue)) continue;\n\n if (Object.hasOwn(existingContext, key) || Object.hasOwn(sanitized, key)) {\n const existingValue = (\n Object.hasOwn(sanitized, key) ? sanitized[key] : existingContext[key]\n )!;\n collisionDetails.push({ key, existingValue, attemptedValue: rawValue });\n continue;\n }\n\n if (acceptedCount >= maxNewKeys) {\n dropped.push(key);\n continue;\n }\n\n sanitized[key] = rawValue;\n acceptedCount++;\n }\n\n return { context: sanitized, validation: { reserved, collisionDetails, dropped } };\n};\n/* eslint-enable complexity */\n\n/**\n * Immutable-snapshot context store for structured log metadata.\n *\n * Context is accumulated over time via {@link add}. Collisions (duplicate keys\n * with different values) preserve the original value and are reported via the\n * returned {@link ContextValidationResult}. Reserved field names are silently\n * dropped.\n */\nexport class ContextStore {\n private readonly context: ContextRecord = {};\n private readonly maxKeys: number;\n\n constructor(initial: ContextRecord = {}, maxKeys = Infinity) {\n this.maxKeys = maxKeys;\n const { context } = sanitizeContextInput(initial, {}, maxKeys);\n this.context = context;\n }\n\n /**\n * Merge new context into the store.\n *\n * @param raw - Key-value pairs to add\n * @returns Validation result with any collisions or reserved field attempts\n */\n add(raw: ContextRecord): ContextValidationResult {\n const remaining = Math.max(0, this.maxKeys - Object.keys(this.context).length);\n const { context, validation } = sanitizeContextInput(raw, this.context, remaining);\n // Intentional mutation: `readonly` prevents reassignment but allows property addition\n Object.assign(this.context, context);\n return validation;\n }\n\n /**\n * Return a shallow copy of the current context.\n *\n * @returns A new object containing all accumulated context key-value pairs\n */\n snapshot(): ContextRecord {\n return { ...this.context };\n }\n}\n","/**\n * Field type definitions with compile-time type safety\n */\n\n/**\n * Field builder with compile-time type inference\n */\nexport interface FieldBuilder<T extends string, R extends boolean> {\n readonly _type: T;\n readonly _required: R;\n readonly _doc: string | undefined;\n}\n\n/**\n * Field builder with optional marker\n */\nexport interface OptionalFieldBuilder<T extends string> extends FieldBuilder<T, false> {\n readonly doc: (description: string) => OptionalFieldBuilder<T>;\n}\n\n/**\n * Field builder with required marker (default)\n */\nexport interface RequiredFieldBuilder<T extends string> extends FieldBuilder<T, true> {\n readonly optional: () => OptionalFieldBuilder<T>;\n readonly doc: (description: string) => RequiredFieldBuilder<T>;\n}\n\nfunction makeOptional<T extends string>(type: T, doc: string | undefined): OptionalFieldBuilder<T> {\n return {\n _type: type,\n _required: false as const,\n _doc: doc,\n doc: (description: string) => makeOptional(type, description),\n };\n}\n\nfunction makeRequired<T extends string>(type: T, doc: string | undefined): RequiredFieldBuilder<T> {\n return {\n _type: type,\n _required: true as const,\n _doc: doc,\n optional: () => makeOptional(type, doc),\n doc: (description: string) => makeRequired(type, description),\n };\n}\n\n/**\n * Field type builders — use these to define fields in events.\n *\n * @example\n * ```typescript\n * const event = defineEvent({\n * key: 'user.created',\n * level: 'info',\n * message: 'User created',\n * fields: {\n * userId: field.string().doc('User ID'),\n * age: field.number().optional().doc('User age'),\n * isActive: field.boolean(),\n * error: field.error().optional(),\n * },\n * });\n * ```\n */\nexport const field = {\n string: (): RequiredFieldBuilder<'string'> => makeRequired('string', undefined),\n number: (): RequiredFieldBuilder<'number'> => makeRequired('number', undefined),\n boolean: (): RequiredFieldBuilder<'boolean'> => makeRequired('boolean', undefined),\n error: (): RequiredFieldBuilder<'error'> => makeRequired('error', undefined),\n} as const;\n\n/**\n * Utility type to simplify intersections\n */\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * Infer the TypeScript type from a field builder\n */\nexport type InferFieldType<F> =\n F extends FieldBuilder<infer T, boolean>\n ? T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'error'\n ? Error | string\n : never\n : never;\n\n/**\n * Build required fields object\n */\ntype BuildRequired<F extends Record<string, FieldBuilder<string, boolean>>> = {\n [K in keyof F as F[K]['_required'] extends true ? K : never]: InferFieldType<F[K]>;\n};\n\n/**\n * Build optional fields object\n */\ntype BuildOptional<F extends Record<string, FieldBuilder<string, boolean>>> = {\n [K in keyof F as F[K]['_required'] extends false ? K : never]?: InferFieldType<F[K]>;\n};\n\n/**\n * Infer complete field types from field builders\n * Required fields become required properties, optional fields become optional\n */\nexport type InferFields<F extends Record<string, FieldBuilder<string, boolean>>> = Simplify<\n BuildRequired<F> & BuildOptional<F>\n>;\n","import { DEFAULT_CORRELATION_TIMEOUT_MS, type LogLevel } from './constants';\nimport { field, type FieldBuilder, type InferFields } from './fields';\n\n/**\n * Event definition with compile-time type safety\n */\nexport interface EventDefinition<\n Key extends string = string,\n Fields extends Record<string, FieldBuilder<string, boolean>> = Record<\n string,\n FieldBuilder<string, boolean>\n >,\n> {\n readonly key: Key;\n readonly level: LogLevel;\n readonly message: string;\n readonly doc?: string;\n readonly fields?: Fields;\n}\n\n/**\n * Helper to extract field types from an event definition\n */\nexport type EventFields<E> =\n E extends EventDefinition<string, infer F>\n ? F extends Record<string, FieldBuilder<string, boolean>>\n ? InferFields<F>\n : Record<string, never>\n : never;\n\nexport type EventRecord = Record<\n string,\n EventDefinition<string, Record<string, FieldBuilder<string, boolean>>>\n>;\n\nexport interface SystemEventGroup {\n readonly key: string;\n readonly type: 'system';\n readonly doc?: string;\n readonly events?: EventRecord;\n readonly groups?: Record<string, SystemEventGroup | CorrelationEventGroup>;\n}\n\nexport interface CorrelationEventGroup {\n readonly key: string;\n readonly type: 'correlation';\n readonly doc?: string;\n readonly timeout?: number;\n readonly events?: EventRecord;\n readonly groups?: Record<string, SystemEventGroup | CorrelationEventGroup>;\n}\n\n/** Field definitions for auto-generated correlation lifecycle events. */\nconst correlationAutoFields = {\n start: {},\n complete: {\n duration: field.number().optional().doc('Duration of the correlation in milliseconds'),\n },\n fail: {\n duration: field.number().optional().doc('Duration of the correlation in milliseconds'),\n error: field.error().optional().doc('Error that caused the failure'),\n },\n timeout: {},\n};\n\nexport type CorrelationAutoEvents = {\n [Key in keyof typeof correlationAutoFields]: EventDefinition<\n string,\n (typeof correlationAutoFields)[Key]\n >;\n};\n\ntype WithAutoEvents<Event extends EventRecord | undefined> = (Event extends EventRecord\n ? Event\n : Record<never, EventDefinition<string, Record<string, FieldBuilder<string, boolean>>>>) &\n CorrelationAutoEvents;\n\n/** Maximum allowed length for event keys to prevent unbounded key sizes. */\nconst MAX_EVENT_KEY_LENGTH = 256;\n\nconst EVENT_KEY_RE = /^[a-z][a-zA-Z0-9]*(\\.[a-z][a-zA-Z0-9]*)*$/;\n\n/** Validate an event or group key against length and format constraints. */\nconst validateEventKey = (key: string, label: string): void => {\n if (key.length > MAX_EVENT_KEY_LENGTH) {\n throw new Error(\n `${label} key \"${key.slice(0, 50)}...\" exceeds maximum length of ${MAX_EVENT_KEY_LENGTH} characters.`,\n );\n }\n if (!EVENT_KEY_RE.test(key)) {\n throw new Error(\n `Invalid ${label} key \"${key}\". Keys must be dotted camelCase identifiers (e.g. \"user.created\", \"http.request.started\").`,\n );\n }\n};\n\n/**\n * Define an event with compile-time type safety.\n *\n * `as const` is **not required** — `defineEvent` uses TypeScript `const` generic\n * parameters (TS 5.0+), so literal types and field builders are narrowed automatically.\n * You may still add `as const` if you prefer, but it has no effect.\n *\n * @example\n * ```typescript\n * const userCreated = defineEvent({\n * key: 'user.created',\n * level: 'info',\n * message: 'User created',\n * doc: 'Emitted when a new user is created',\n * fields: {\n * userId: field.string().doc('User ID'),\n * email: field.string(),\n * age: field.number().optional(),\n * },\n * });\n * ```\n *\n * @param event - Event definition with key, level, message, optional doc and fields\n * @returns The same event definition, typed for compile-time inference\n * @throws {Error} If the event key does not match the required dotted camelCase format\n */\nexport const defineEvent = <\n const Key extends string,\n const Fields extends Record<string, FieldBuilder<string, boolean>>,\n>(\n event: EventDefinition<Key, Fields>,\n): EventDefinition<Key, Fields> => {\n validateEventKey(event.key, 'Event');\n return event;\n};\n\n/**\n * Auto-prefix event keys in a group's events with `${groupKey}.${propertyName}`\n * when the event's key doesn't already start with `${groupKey}.`.\n * Existing fully-qualified keys pass through unchanged.\n *\n * @param groupKey - The parent group's key used as prefix\n * @param events - Record of events to prefix (may be undefined)\n * @returns New event record with prefixed keys, or undefined if input was undefined\n */\nconst prefixEventKeys = (\n groupKey: string,\n events: EventRecord | undefined,\n): EventRecord | undefined => {\n if (!events) return events;\n const result: EventRecord = {};\n for (const [name, event] of Object.entries(events)) {\n if (event.key.startsWith(`${groupKey}.`)) {\n result[name] = event;\n } else {\n result[name] = { ...event, key: `${groupKey}.${name}` };\n }\n }\n return result;\n};\n\n/**\n * Define a system or correlation event group for organizational purposes.\n *\n * Groups provide a namespace hierarchy for events. For correlation groups,\n * prefer {@link defineCorrelationGroup} which adds automatic lifecycle events.\n *\n * @param group - Event group definition (system or correlation)\n * @returns The same group definition, typed for compile-time inference\n */\nexport const defineEventGroup = <Group extends SystemEventGroup | CorrelationEventGroup>(\n group: Group,\n): Group => {\n validateEventKey(group.key, 'Group');\n const prefixed = prefixEventKeys(group.key, group.events);\n if (prefixed !== group.events) {\n return { ...group, events: prefixed } as Group;\n }\n return group;\n};\n\n/** Build the four auto-generated lifecycle events for a correlation group. */\nconst buildAutoEvents = (groupKey: string): CorrelationAutoEvents => ({\n start: {\n key: `${groupKey}.start`,\n level: 'info',\n message: `${groupKey} started`,\n doc: 'Auto-generated correlation start event',\n },\n complete: {\n key: `${groupKey}.complete`,\n level: 'info',\n message: `${groupKey} completed`,\n doc: 'Auto-generated correlation completion event',\n fields: correlationAutoFields.complete,\n },\n fail: {\n key: `${groupKey}.fail`,\n level: 'error',\n message: `${groupKey} failed`,\n doc: 'Auto-generated correlation failure event',\n fields: correlationAutoFields.fail,\n },\n timeout: {\n key: `${groupKey}.timeout`,\n level: 'warn',\n message: `${groupKey} timed out`,\n doc: 'Auto-generated correlation timeout event',\n },\n});\n\n/**\n * Define a correlation event group with automatic lifecycle events\n *\n * **What is a correlation group?**\n * A correlation represents a logical unit of work with a defined lifecycle\n * (start, complete, timeout). Common examples: HTTP requests, batch jobs, workflows.\n *\n * **Automatic events added:**\n * - `{key}.start` - Emitted when startCorrelation() is called\n * - `{key}.complete` - Emitted when complete() is called (includes duration)\n * - `{key}.fail` - Emitted when fail() is called (includes duration and error)\n * - `{key}.timeout` - Emitted if no activity within timeout period\n *\n * **Timeout behavior:**\n * - Defaults to 5 minutes (300,000ms) if not specified\n * - Timer resets on ANY activity (log events, fork creation)\n * - Set to 0 to disable timeout\n *\n * **Type safety:**\n * TypeScript will infer all event keys and field types. The return type\n * includes both your events and the auto-generated lifecycle events.\n *\n * @param group - Correlation group definition\n * @returns Normalized group with auto-events and default timeout\n *\n * @example\n * ```typescript\n * const requestGroup = defineCorrelationGroup({\n * key: 'api.request',\n * doc: 'HTTP request lifecycle',\n * timeout: 30_000, // 30 seconds\n * events: {\n * validated: defineEvent({\n * key: 'api.request.validated',\n * level: 'debug',\n * message: 'Request validated',\n * doc: 'Validation passed',\n * }),\n * processed: defineEvent({\n * key: 'api.request.processed',\n * level: 'info',\n * message: 'Request processed',\n * doc: 'Processing complete',\n * fields: { statusCode: { type: 'number', required: true } },\n * }),\n * },\n * });\n *\n * // Auto-events available:\n * // - requestGroup.events.start\n * // - requestGroup.events.complete\n * // - requestGroup.events.timeout\n * // - requestGroup.events.validated (your event)\n * // - requestGroup.events.processed (your event)\n * ```\n */\nexport const defineCorrelationGroup = <Group extends CorrelationEventGroup>(\n group: Group,\n): Omit<Group, 'events' | 'timeout'> & {\n events: WithAutoEvents<Group['events']>;\n timeout: number;\n} => {\n validateEventKey(group.key, 'Group');\n const autoEvents = buildAutoEvents(group.key);\n const prefixed = prefixEventKeys(group.key, group.events) ?? {};\n\n const autoKeys = Object.keys(autoEvents);\n const conflicts = autoKeys.filter((k) => Object.hasOwn(prefixed, k));\n if (conflicts.length > 0) {\n throw new Error(\n `Correlation group \"${group.key}\" defines events that collide with auto-generated lifecycle events: ${conflicts.join(', ')}. Rename these events to avoid the conflict.`,\n );\n }\n\n return {\n ...group,\n timeout: group.timeout ?? DEFAULT_CORRELATION_TIMEOUT_MS,\n events: {\n ...prefixed,\n ...autoEvents,\n } as WithAutoEvents<Group['events']>,\n };\n};\n","import type { EventDefinition, EventFields } from './events';\nimport type { FieldBuilder } from './fields';\n\nexport interface ValidationMetadata {\n readonly missingFields?: string[];\n readonly typeErrors?: string[];\n readonly invalidValues?: string[];\n readonly unknownFields?: string[];\n}\n\ninterface FieldValidationResult {\n readonly missingFields: string[];\n readonly typeErrors: string[];\n readonly invalidValues: string[];\n readonly unknownFields: string[];\n readonly normalizedFields: Record<string, unknown>;\n}\n\n/** Matches ANSI escape sequences (CSI, OSC, etc.) for sanitization. */\nconst ANSI_ESCAPE_RE = /\\x1b(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g;\n\n/** Matches carriage return and newline characters for sanitization. */\nconst NEWLINE_RE = /[\\r\\n]/g;\n\n/**\n * Sanitize a string value to prevent log injection.\n * Strips ANSI escape sequences and replaces newlines with a visible placeholder.\n */\nconst sanitizeString = (value: string): string =>\n value.replace(ANSI_ESCAPE_RE, '').replace(NEWLINE_RE, '\\\\n');\n\n/**\n * Sanitize string values in an untyped fields record.\n * Used by the `log()` escape hatch to apply the same sanitization as typed events.\n */\nexport const sanitizeLogFields = (fields: Record<string, unknown>): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(fields)) {\n result[key] = typeof value === 'string' ? sanitizeString(value) : value;\n }\n return result;\n};\n\n/** Result of checking a runtime value against an expected field type. */\ntype TypeCheckResult = 'ok' | 'type_error' | 'invalid_value';\n\n/** Check if a runtime value matches the expected field type. */\n// eslint-disable-next-line complexity -- switch arms for each field type are inherently branchy\nconst checkFieldType = (value: unknown, type: string): TypeCheckResult => {\n switch (type) {\n case 'error':\n return value instanceof Error || typeof value === 'string' ? 'ok' : 'type_error';\n case 'string':\n return typeof value === 'string' ? 'ok' : 'type_error';\n case 'number':\n if (typeof value !== 'number') return 'type_error';\n return Number.isFinite(value) ? 'ok' : 'invalid_value';\n case 'boolean':\n return typeof value === 'boolean' ? 'ok' : 'type_error';\n default:\n // Unknown field type — always fail validation so new types\n // surface as type errors until this switch is updated.\n return 'type_error';\n }\n};\n\n/**\n * Validate event fields against their definitions and normalize values.\n *\n * @param event - Event definition containing field schemas to validate against\n * @param payload - User-provided field values to validate\n * @returns Validation result with missing fields, type errors, unknown fields, and normalized values\n */\n/* eslint-disable max-lines-per-function, complexity -- field validation checks missing/type/unknown/sanitization in one pass */\nexport const validateFields = <\n E extends EventDefinition<string, Record<string, FieldBuilder<string, boolean>>>,\n>(\n event: E,\n payload: EventFields<E>,\n): FieldValidationResult => {\n const providedFields = (payload ?? {}) as Record<string, unknown>;\n const normalizedFields: Record<string, unknown> = {};\n const missingFields: string[] = [];\n const typeErrors: string[] = [];\n const invalidValues: string[] = [];\n const unknownFields: string[] = [];\n\n const fieldBuilders = event.fields ?? ({} as Record<string, FieldBuilder<string, boolean>>);\n const definedFieldNames = new Set(Object.keys(fieldBuilders));\n\n for (const [name, builder] of Object.entries(fieldBuilders)) {\n const value = providedFields[name];\n\n // Extract metadata from builder (runtime info)\n const fieldType = builder._type;\n const isRequired = builder._required;\n\n if (value === undefined || value === null) {\n if (isRequired) {\n missingFields.push(name);\n }\n continue;\n }\n\n const typeCheck = checkFieldType(value, fieldType);\n if (typeCheck === 'type_error') {\n typeErrors.push(name);\n continue;\n }\n if (typeCheck === 'invalid_value') {\n invalidValues.push(name);\n continue;\n }\n\n if (fieldType === 'error') {\n try {\n // checkFieldType('error') guarantees value is Error | string\n normalizedFields[name] =\n value instanceof Error\n ? (value.stack ?? value.message)\n : typeof value === 'string'\n ? value\n : '[unknown error]';\n } catch {\n normalizedFields[name] = '[unserializable error]';\n }\n } else if (fieldType === 'string' && typeof value === 'string') {\n normalizedFields[name] = sanitizeString(value);\n } else {\n normalizedFields[name] = value;\n }\n }\n\n // Pass through extra fields not in the event definition, filtering non-serializable values\n for (const [name, value] of Object.entries(providedFields)) {\n if (!definedFieldNames.has(name) && value !== undefined && value !== null) {\n unknownFields.push(name);\n if (typeof value === 'function' || typeof value === 'symbol') {\n continue;\n }\n if (typeof value === 'string') {\n normalizedFields[name] = sanitizeString(value);\n } else {\n normalizedFields[name] = value;\n }\n }\n }\n\n return { missingFields, typeErrors, invalidValues, unknownFields, normalizedFields };\n};\n/* eslint-enable max-lines-per-function, complexity */\n\n/**\n * Build validation metadata from field validation results, omitting empty arrays.\n *\n * @param fieldValidation - Result from {@link validateFields} containing validation issues\n * @returns Validation metadata object, or undefined if there are no issues\n */\nexport const buildValidationMetadata = (\n fieldValidation: FieldValidationResult,\n): ValidationMetadata | undefined => {\n const entries = Object.entries({\n missingFields: fieldValidation.missingFields,\n typeErrors: fieldValidation.typeErrors,\n invalidValues: fieldValidation.invalidValues,\n unknownFields: fieldValidation.unknownFields,\n }).filter(([, v]) => Array.isArray(v) && v.length > 0);\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n","import {\n callBackendMethod,\n createConsoleBackend,\n type LogBackend,\n type LogPayload,\n} from './backend';\nimport {\n DEFAULT_MAX_ACTIVE_CORRELATIONS,\n DEFAULT_MAX_CONTEXT_KEYS,\n DEFAULT_MAX_FORK_DEPTH,\n DEFAULT_REQUIRED_LEVELS,\n FORK_ID_SEPARATOR,\n LOG_LEVELS,\n type LogLevel,\n ROOT_FORK_ID,\n} from './constants';\nimport { type ContextRecord, ContextStore, type ContextValidationResult } from './context';\nimport { ChroniclerError } from './errors';\nimport {\n type CorrelationAutoEvents,\n type CorrelationEventGroup,\n defineCorrelationGroup,\n type EventDefinition,\n type EventFields,\n type EventRecord,\n} from './events';\nimport { assertNoReservedKeys } from './reserved';\nimport { buildValidationMetadata, sanitizeLogFields, validateFields } from './validation';\n\nexport interface ChroniclerLimits {\n readonly maxContextKeys?: number;\n /**\n * Maximum fork nesting depth. A depth of N means N levels of nesting\n * from root (e.g. depth 3 allows root → child → grandchild → great-grandchild).\n * Defaults to {@link DEFAULT_MAX_FORK_DEPTH}.\n */\n readonly maxForkDepth?: number;\n readonly maxActiveCorrelations?: number;\n}\n\nexport interface ChroniclerConfig {\n readonly backend?: LogBackend;\n readonly metadata: ContextRecord;\n readonly correlationIdGenerator?: () => string;\n readonly limits?: ChroniclerLimits;\n /**\n * When `true`, throws a `ChroniclerError` with code `FIELD_VALIDATION`\n * for field validation errors (missing required fields, type mismatches).\n * Useful for CI/CD enforcement. Defaults to `false`.\n */\n readonly strict?: boolean;\n /**\n * Minimum log level to emit. Events below this level are silently dropped.\n * Uses priority ordering: fatal(0) > critical(1) > ... > trace(8).\n * Defaults to `'trace'` (all events emitted).\n */\n readonly minLevel?: LogLevel;\n}\n\ninterface ResolvedLimits {\n readonly maxContextKeys: number;\n readonly maxForkDepth: number;\n readonly maxActiveCorrelations: number;\n}\n\ninterface ResolvedChroniclerConfig {\n readonly backend: LogBackend;\n readonly limits: ResolvedLimits;\n readonly minLevel: number;\n readonly strict?: boolean | undefined;\n}\n\nexport interface Chronicler {\n /** Emit a typed event. Fields are validated against the event definition. */\n event<E extends EventDefinition>(event: E, fields: EventFields<E>): void;\n\n /**\n * Untyped escape hatch — log at any level without a pre-defined event.\n * Useful for incremental adoption or ad-hoc debugging.\n */\n log(level: LogLevel, message: string, fields?: Record<string, unknown>): void;\n\n /** Add key-value context that is attached to all subsequent events. */\n addContext(context: ContextRecord): ContextValidationResult;\n\n /** Start a correlation — a logical unit of work with lifecycle events. */\n startCorrelation(group: CorrelationEventGroup, metadata?: ContextRecord): CorrelationChronicle;\n\n /** Create an isolated child chronicle that inherits context. */\n fork(context?: ContextRecord): Chronicler;\n}\n\n/**\n * A correlation represents a logical unit of work with a defined lifecycle.\n *\n * Unlike a root Chronicler, a correlation:\n * - Has a single shared correlation ID for all events\n * - Has lifecycle events (start, complete, fail, timeout)\n * - Can timeout if not completed within the configured duration\n * - Cannot start nested correlations (use fork() for parallel work within a correlation)\n */\nexport interface CorrelationChronicle {\n /** Emit a typed event within this correlation. */\n event<E extends EventDefinition>(event: E, fields: EventFields<E>): void;\n\n /**\n * Untyped escape hatch — log at any level without a pre-defined event.\n * Useful for incremental adoption or ad-hoc debugging.\n */\n log(level: LogLevel, message: string, fields?: Record<string, unknown>): void;\n\n /** Add key-value context that is attached to all subsequent events. */\n addContext(context: ContextRecord): ContextValidationResult;\n\n /** Create an isolated child chronicle that inherits context. */\n fork(context?: ContextRecord): Chronicler;\n\n /** Mark the correlation as successfully completed. Emits the `.complete` event. */\n complete(fields?: Record<string, unknown>): void;\n\n /** Mark the correlation as failed. Emits the `.fail` event at error level. */\n fail(error?: unknown, fields?: Record<string, unknown>): void;\n\n /** Mark the correlation as timed out. Called automatically by the timer. */\n timeout(): void;\n}\n\ninterface BuildPayloadArgs {\n readonly contextStore: ContextStore;\n readonly eventDef: EventDefinition;\n readonly fields: Record<string, unknown>;\n readonly currentCorrelationId: () => string;\n readonly forkId: string;\n readonly strict?: boolean | undefined;\n}\n\n/**\n * Build a complete log payload from event definition and runtime data.\n * @internal\n * @param args - Payload construction arguments including context, event, and fields\n * @returns Assembled log payload ready for backend emission\n */\nconst buildPayload = (args: BuildPayloadArgs): LogPayload => {\n const fieldValidation = validateFields(args.eventDef, args.fields);\n\n if (args.strict) {\n const issues: string[] = [];\n if (fieldValidation.missingFields.length > 0) {\n issues.push(`missing required fields: ${fieldValidation.missingFields.join(', ')}`);\n }\n if (fieldValidation.typeErrors.length > 0) {\n issues.push(`type errors on fields: ${fieldValidation.typeErrors.join(', ')}`);\n }\n if (fieldValidation.invalidValues.length > 0) {\n issues.push(`invalid values on fields: ${fieldValidation.invalidValues.join(', ')}`);\n }\n if (issues.length > 0) {\n throw new ChroniclerError(\n 'FIELD_VALIDATION',\n `Event \"${args.eventDef.key}\" failed validation: ${issues.join('; ')}`,\n );\n }\n }\n\n const validationMetadata = buildValidationMetadata(fieldValidation);\n\n return {\n eventKey: args.eventDef.key,\n fields: fieldValidation.normalizedFields,\n correlationId: args.currentCorrelationId(),\n forkId: args.forkId,\n metadata: args.contextStore.snapshot(),\n timestamp: new Date().toISOString(),\n ...(validationMetadata ? { _validation: validationMetadata } : {}),\n };\n};\n\n/** Compute fork nesting depth from a dotted fork ID. */\nconst forkDepthFromId = (forkId: string): number =>\n forkId === ROOT_FORK_ID ? 0 : forkId.split(FORK_ID_SEPARATOR).length;\n\n/**\n * Derive the next child fork ID and enforce depth limits.\n * @throws {ChroniclerError} `FORK_DEPTH_EXCEEDED` if the new depth exceeds maxDepth\n */\nconst nextForkId = (parentForkId: string, counter: number, maxDepth: number): string => {\n const childForkId =\n parentForkId === ROOT_FORK_ID\n ? String(counter)\n : `${parentForkId}${FORK_ID_SEPARATOR}${counter}`;\n const depth = forkDepthFromId(childForkId);\n if (depth > maxDepth) {\n throw new ChroniclerError(\n 'FORK_DEPTH_EXCEEDED',\n `Fork depth ${depth} exceeds maximum allowed depth of ${maxDepth}`,\n );\n }\n return childForkId;\n};\n\ninterface ChronicleHooks {\n readonly onActivity?: () => void;\n}\n\ntype NormalizedCorrelationGroup = Omit<CorrelationEventGroup, 'events' | 'timeout'> & {\n readonly timeout: number;\n readonly events: EventRecord & CorrelationAutoEvents;\n};\n\n/** Guard: returns true if the group has already been processed by defineCorrelationGroup. */\nconst isAlreadyNormalized = (group: CorrelationEventGroup): group is NormalizedCorrelationGroup =>\n typeof group.timeout === 'number' && group.events !== undefined && 'start' in group.events;\n\n/** Normalize a correlation group, skipping if already processed to avoid collision false-positives. */\nconst resolveCorrelationGroup = (group: CorrelationEventGroup): NormalizedCorrelationGroup =>\n isAlreadyNormalized(group)\n ? group\n : (defineCorrelationGroup(group) as NormalizedCorrelationGroup);\n\ninterface ChronicleInstanceArgs {\n readonly config: ResolvedChroniclerConfig;\n readonly contextStore: ContextStore;\n /** Returns the current correlation ID for this chronicle. */\n readonly currentCorrelationId: () => string;\n /** Creates NEW correlation IDs for startCorrelation(). */\n readonly correlationIdGenerator: () => string;\n readonly forkId: string;\n readonly hooks?: ChronicleHooks;\n readonly activeCorrelations?: { count: number };\n}\n\n// eslint-disable-next-line max-lines-per-function -- Accepted deviation: object-literal constructor, splitting reduces readability\nconst createChronicleInstance = (args: ChronicleInstanceArgs): Chronicler => {\n const {\n config,\n contextStore,\n currentCorrelationId,\n correlationIdGenerator,\n forkId,\n hooks = {},\n activeCorrelations = { count: 0 },\n } = args;\n /** Monotonically increasing counter for generating unique child fork IDs. */\n let forkCounter = 0;\n\n return {\n event(eventDef, fields) {\n if (LOG_LEVELS[eventDef.level] > config.minLevel) return;\n const payload = buildPayload({\n contextStore,\n eventDef,\n // Deliberate type erasure: EventFields<E> → Record<string, unknown>\n fields: fields as Record<string, unknown>,\n currentCorrelationId,\n forkId,\n strict: config.strict,\n });\n callBackendMethod(config.backend, eventDef.level, eventDef.message, payload);\n hooks.onActivity?.();\n },\n log(level, message, fields = {}) {\n if (LOG_LEVELS[level] > config.minLevel) return;\n const payload: LogPayload = {\n eventKey: '',\n fields: sanitizeLogFields(fields),\n correlationId: currentCorrelationId(),\n forkId,\n metadata: contextStore.snapshot(),\n timestamp: new Date().toISOString(),\n };\n callBackendMethod(config.backend, level, message, payload);\n hooks.onActivity?.();\n },\n addContext(context) {\n return contextStore.add(context);\n },\n fork(extraContext = {}) {\n forkCounter++;\n const childForkId = nextForkId(forkId, forkCounter, config.limits.maxForkDepth);\n const forkStore = new ContextStore(contextStore.snapshot(), config.limits.maxContextKeys);\n const forkChronicle = createChronicleInstance({\n config,\n contextStore: forkStore,\n currentCorrelationId,\n correlationIdGenerator,\n forkId: childForkId,\n hooks,\n activeCorrelations,\n });\n if (Object.keys(extraContext).length > 0) {\n forkChronicle.addContext(extraContext);\n }\n return forkChronicle;\n },\n startCorrelation(group, metadata = {}) {\n if (activeCorrelations.count >= config.limits.maxActiveCorrelations) {\n throw new ChroniclerError(\n 'CORRELATION_LIMIT_EXCEEDED',\n `Active correlation limit of ${config.limits.maxActiveCorrelations} exceeded`,\n );\n }\n const definedGroup = resolveCorrelationGroup(group);\n activeCorrelations.count++;\n const correlationStore = new ContextStore(\n contextStore.snapshot(),\n config.limits.maxContextKeys,\n );\n if (Object.keys(metadata).length > 0) {\n correlationStore.add(metadata);\n }\n const correlationId = correlationIdGenerator();\n return new CorrelationChronicleImpl({\n config,\n group: definedGroup,\n contextStore: correlationStore,\n currentCorrelationId: () => correlationId,\n correlationIdGenerator,\n forkId,\n activeCorrelations,\n });\n },\n };\n};\n\n/**\n * Auto-reset timeout for correlation groups.\n * Resets on any activity; invokes callback if idle for the configured duration.\n */\nexport class CorrelationTimer {\n private timeoutId: NodeJS.Timeout | undefined;\n\n constructor(\n private readonly timeout: number,\n private readonly onTimeout: () => void,\n ) {}\n\n start(): void {\n this.clear();\n if (this.timeout > 0) {\n this.timeoutId = setTimeout(this.onTimeout, this.timeout);\n this.timeoutId.unref();\n }\n }\n\n /** Reset the timer (keep-alive on activity). */\n touch(): void {\n this.start();\n }\n\n clear(): void {\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n }\n}\n\ninterface CorrelationChronicleArgs {\n readonly config: ResolvedChroniclerConfig;\n readonly group: NormalizedCorrelationGroup;\n readonly contextStore: ContextStore;\n readonly currentCorrelationId: () => string;\n readonly correlationIdGenerator: () => string;\n readonly forkId: string;\n readonly activeCorrelations?: { count: number };\n}\n\nclass CorrelationChronicleImpl implements CorrelationChronicle {\n private readonly config: ResolvedChroniclerConfig;\n private readonly contextStore: ContextStore;\n private readonly currentCorrelationId: () => string;\n private readonly correlationIdGenerator: () => string;\n private readonly forkId: string;\n private readonly activeCorrelations: { count: number };\n private readonly timer: CorrelationTimer;\n private completed = false;\n private readonly startedAt = Date.now();\n private readonly autoEvents: CorrelationAutoEvents;\n private forkCounter = 0;\n\n constructor(args: CorrelationChronicleArgs) {\n this.config = args.config;\n this.contextStore = args.contextStore;\n this.currentCorrelationId = args.currentCorrelationId;\n this.correlationIdGenerator = args.correlationIdGenerator;\n this.forkId = args.forkId;\n this.activeCorrelations = args.activeCorrelations ?? { count: 0 };\n this.timer = new CorrelationTimer(args.group.timeout, () => this.timeout());\n this.autoEvents = args.group.events as CorrelationAutoEvents;\n this.timer.start();\n this.emitAutoEvent(this.autoEvents.start, {});\n }\n\n event<E extends EventDefinition>(eventDef: E, fields: EventFields<E>): void {\n if (this.completed) return;\n if (LOG_LEVELS[eventDef.level] > this.config.minLevel) return;\n const payload = buildPayload({\n contextStore: this.contextStore,\n eventDef,\n // Deliberate type erasure: EventFields<E> → Record<string, unknown>\n fields: fields as Record<string, unknown>,\n currentCorrelationId: this.currentCorrelationId,\n forkId: this.forkId,\n strict: this.config.strict,\n });\n callBackendMethod(this.config.backend, eventDef.level, eventDef.message, payload);\n this.timer.touch();\n }\n\n log(level: LogLevel, message: string, fields: Record<string, unknown> = {}): void {\n if (this.completed) return;\n if (LOG_LEVELS[level] > this.config.minLevel) return;\n const payload: LogPayload = {\n eventKey: '',\n fields: sanitizeLogFields(fields),\n correlationId: this.currentCorrelationId(),\n forkId: this.forkId,\n metadata: this.contextStore.snapshot(),\n timestamp: new Date().toISOString(),\n };\n callBackendMethod(this.config.backend, level, message, payload);\n this.timer.touch();\n }\n\n addContext(context: ContextRecord): ContextValidationResult {\n return this.contextStore.add(context);\n }\n\n fork(extraContext: ContextRecord = {}): Chronicler {\n this.forkCounter++;\n const childForkId = nextForkId(this.forkId, this.forkCounter, this.config.limits.maxForkDepth);\n const forkStore = new ContextStore(\n this.contextStore.snapshot(),\n this.config.limits.maxContextKeys,\n );\n\n const forkChronicle = createChronicleInstance({\n config: this.config,\n contextStore: forkStore,\n currentCorrelationId: this.currentCorrelationId,\n correlationIdGenerator: this.correlationIdGenerator,\n forkId: childForkId,\n hooks: { onActivity: () => this.timer.touch() },\n activeCorrelations: this.activeCorrelations,\n });\n\n if (Object.keys(extraContext).length > 0) {\n forkChronicle.addContext(extraContext);\n }\n\n return forkChronicle;\n }\n\n complete(fields: Record<string, unknown> = {}): void {\n if (!this.finalize()) return;\n this.emitAutoEvent(this.autoEvents.complete, {\n duration: Date.now() - this.startedAt,\n ...fields,\n });\n }\n\n fail(error?: unknown, fields: Record<string, unknown> = {}): void {\n if (!this.finalize()) return;\n this.emitAutoEvent(this.autoEvents.fail, {\n duration: Date.now() - this.startedAt,\n error,\n ...fields,\n });\n }\n\n timeout(): void {\n if (!this.finalize()) return;\n this.emitAutoEvent(this.autoEvents.timeout, {});\n }\n\n /** Mark correlation as done: decrement counter, clear timer. Returns false if already completed. */\n private finalize(): boolean {\n if (this.completed) return false;\n this.activeCorrelations.count--;\n this.completed = true;\n this.timer.clear();\n return true;\n }\n\n private emitAutoEvent(eventDef: EventDefinition, fields: Record<string, unknown>): void {\n if (LOG_LEVELS[eventDef.level] > this.config.minLevel) return;\n const payload = buildPayload({\n contextStore: this.contextStore,\n eventDef,\n fields,\n currentCorrelationId: this.currentCorrelationId,\n forkId: this.forkId,\n strict: this.config.strict,\n });\n callBackendMethod(this.config.backend, eventDef.level, eventDef.message, payload);\n }\n}\n\n/** Validate and resolve user-provided config into fully-resolved internal config. */\nconst resolveChroniclerConfig = (\n config: ChroniclerConfig,\n // eslint-disable-next-line complexity -- config resolution requires checking all option paths\n): { resolved: ResolvedChroniclerConfig; correlationIdGenerator: () => string } => {\n const resolvedBackend = config.backend ?? createConsoleBackend();\n\n const missingLevels = DEFAULT_REQUIRED_LEVELS.filter(\n (level) => typeof resolvedBackend[level] !== 'function',\n );\n if (missingLevels.length > 0) {\n throw new ChroniclerError(\n 'UNSUPPORTED_LOG_LEVEL',\n `Log backend is missing level(s): ${missingLevels.join(', ')}. A valid backend must implement all 9 levels: ${DEFAULT_REQUIRED_LEVELS.join(', ')}. Use createBackend() for automatic fallback handling.`,\n );\n }\n\n const reservedMetadata = assertNoReservedKeys(config.metadata);\n if (reservedMetadata.length > 0) {\n throw new ChroniclerError(\n 'RESERVED_FIELD',\n `Reserved fields cannot be used in metadata: ${reservedMetadata.join(', ')}`,\n );\n }\n\n const resolvedLimits: ResolvedLimits = {\n maxContextKeys: config.limits?.maxContextKeys ?? DEFAULT_MAX_CONTEXT_KEYS,\n maxForkDepth: config.limits?.maxForkDepth ?? DEFAULT_MAX_FORK_DEPTH,\n maxActiveCorrelations: config.limits?.maxActiveCorrelations ?? DEFAULT_MAX_ACTIVE_CORRELATIONS,\n };\n\n return {\n resolved: {\n backend: resolvedBackend,\n limits: resolvedLimits,\n minLevel: LOG_LEVELS[config.minLevel ?? 'trace'],\n strict: config.strict,\n },\n correlationIdGenerator: config.correlationIdGenerator ?? (() => crypto.randomUUID()),\n };\n};\n\n/**\n * Create a root Chronicler instance.\n *\n * This is the main entry point for the library. The returned `Chronicler`\n * can log events, add context, start correlations, and create forks.\n *\n * @param config - Chronicler configuration with optional backend, metadata, and optional correlation settings\n * @returns A configured `Chronicler` instance\n * @throws {ChroniclerError} `UNSUPPORTED_LOG_LEVEL` if the backend is missing required methods\n * @throws {ChroniclerError} `RESERVED_FIELD` if `config.metadata` contains reserved field names\n */\nexport const createChronicle = (config: ChroniclerConfig): Chronicler => {\n const { resolved, correlationIdGenerator } = resolveChroniclerConfig(config);\n const baseContextStore = new ContextStore(config.metadata, resolved.limits.maxContextKeys);\n\n return createChronicleInstance({\n config: resolved,\n contextStore: baseContextStore,\n currentCorrelationId: () => '',\n correlationIdGenerator,\n forkId: ROOT_FORK_ID,\n /** Shared mutable counter tracking uncompleted correlations for limit enforcement. */\n activeCorrelations: { count: 0 },\n });\n};\n"]}
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Global constants used throughout Chronicler
3
+ */
4
+ /**
5
+ * Log level priority mapping
6
+ * Lower numbers = higher priority/severity
7
+ */
8
+ declare const LOG_LEVELS: {
9
+ readonly fatal: 0;
10
+ readonly critical: 1;
11
+ readonly alert: 2;
12
+ readonly error: 3;
13
+ readonly warn: 4;
14
+ readonly audit: 5;
15
+ readonly info: 6;
16
+ readonly debug: 7;
17
+ readonly trace: 8;
18
+ };
19
+ /**
20
+ * Union of all valid log level names, derived from {@link LOG_LEVELS}.
21
+ */
22
+ type LogLevel = keyof typeof LOG_LEVELS;
23
+
24
+ /**
25
+ * Field type definitions with compile-time type safety
26
+ */
27
+ /**
28
+ * Field builder with compile-time type inference
29
+ */
30
+ interface FieldBuilder<T extends string, R extends boolean> {
31
+ readonly _type: T;
32
+ readonly _required: R;
33
+ readonly _doc: string | undefined;
34
+ }
35
+ /**
36
+ * Field builder with optional marker
37
+ */
38
+ interface OptionalFieldBuilder<T extends string> extends FieldBuilder<T, false> {
39
+ readonly doc: (description: string) => OptionalFieldBuilder<T>;
40
+ }
41
+ /**
42
+ * Field builder with required marker (default)
43
+ */
44
+ interface RequiredFieldBuilder<T extends string> extends FieldBuilder<T, true> {
45
+ readonly optional: () => OptionalFieldBuilder<T>;
46
+ readonly doc: (description: string) => RequiredFieldBuilder<T>;
47
+ }
48
+ /**
49
+ * Field type builders — use these to define fields in events.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const event = defineEvent({
54
+ * key: 'user.created',
55
+ * level: 'info',
56
+ * message: 'User created',
57
+ * fields: {
58
+ * userId: field.string().doc('User ID'),
59
+ * age: field.number().optional().doc('User age'),
60
+ * isActive: field.boolean(),
61
+ * error: field.error().optional(),
62
+ * },
63
+ * });
64
+ * ```
65
+ */
66
+ declare const field: {
67
+ readonly string: () => RequiredFieldBuilder<"string">;
68
+ readonly number: () => RequiredFieldBuilder<"number">;
69
+ readonly boolean: () => RequiredFieldBuilder<"boolean">;
70
+ readonly error: () => RequiredFieldBuilder<"error">;
71
+ };
72
+ /**
73
+ * Utility type to simplify intersections
74
+ */
75
+ type Simplify<T> = {
76
+ [K in keyof T]: T[K];
77
+ } & {};
78
+ /**
79
+ * Infer the TypeScript type from a field builder
80
+ */
81
+ type InferFieldType<F> = F extends FieldBuilder<infer T, boolean> ? T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'error' ? Error | string : never : never;
82
+ /**
83
+ * Build required fields object
84
+ */
85
+ type BuildRequired<F extends Record<string, FieldBuilder<string, boolean>>> = {
86
+ [K in keyof F as F[K]['_required'] extends true ? K : never]: InferFieldType<F[K]>;
87
+ };
88
+ /**
89
+ * Build optional fields object
90
+ */
91
+ type BuildOptional<F extends Record<string, FieldBuilder<string, boolean>>> = {
92
+ [K in keyof F as F[K]['_required'] extends false ? K : never]?: InferFieldType<F[K]>;
93
+ };
94
+ /**
95
+ * Infer complete field types from field builders
96
+ * Required fields become required properties, optional fields become optional
97
+ */
98
+ type InferFields<F extends Record<string, FieldBuilder<string, boolean>>> = Simplify<BuildRequired<F> & BuildOptional<F>>;
99
+
100
+ /**
101
+ * Event definition with compile-time type safety
102
+ */
103
+ interface EventDefinition<Key extends string = string, Fields extends Record<string, FieldBuilder<string, boolean>> = Record<string, FieldBuilder<string, boolean>>> {
104
+ readonly key: Key;
105
+ readonly level: LogLevel;
106
+ readonly message: string;
107
+ readonly doc?: string;
108
+ readonly fields?: Fields;
109
+ }
110
+ /**
111
+ * Helper to extract field types from an event definition
112
+ */
113
+ type EventFields<E> = E extends EventDefinition<string, infer F> ? F extends Record<string, FieldBuilder<string, boolean>> ? InferFields<F> : Record<string, never> : never;
114
+ type EventRecord = Record<string, EventDefinition<string, Record<string, FieldBuilder<string, boolean>>>>;
115
+ interface SystemEventGroup {
116
+ readonly key: string;
117
+ readonly type: 'system';
118
+ readonly doc?: string;
119
+ readonly events?: EventRecord;
120
+ readonly groups?: Record<string, SystemEventGroup | CorrelationEventGroup>;
121
+ }
122
+ interface CorrelationEventGroup {
123
+ readonly key: string;
124
+ readonly type: 'correlation';
125
+ readonly doc?: string;
126
+ readonly timeout?: number;
127
+ readonly events?: EventRecord;
128
+ readonly groups?: Record<string, SystemEventGroup | CorrelationEventGroup>;
129
+ }
130
+ /** Field definitions for auto-generated correlation lifecycle events. */
131
+ declare const correlationAutoFields: {
132
+ start: {};
133
+ complete: {
134
+ duration: OptionalFieldBuilder<"number">;
135
+ };
136
+ fail: {
137
+ duration: OptionalFieldBuilder<"number">;
138
+ error: OptionalFieldBuilder<"error">;
139
+ };
140
+ timeout: {};
141
+ };
142
+ type CorrelationAutoEvents = {
143
+ [Key in keyof typeof correlationAutoFields]: EventDefinition<string, (typeof correlationAutoFields)[Key]>;
144
+ };
145
+ type WithAutoEvents<Event extends EventRecord | undefined> = (Event extends EventRecord ? Event : Record<never, EventDefinition<string, Record<string, FieldBuilder<string, boolean>>>>) & CorrelationAutoEvents;
146
+ /**
147
+ * Define an event with compile-time type safety.
148
+ *
149
+ * `as const` is **not required** — `defineEvent` uses TypeScript `const` generic
150
+ * parameters (TS 5.0+), so literal types and field builders are narrowed automatically.
151
+ * You may still add `as const` if you prefer, but it has no effect.
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * const userCreated = defineEvent({
156
+ * key: 'user.created',
157
+ * level: 'info',
158
+ * message: 'User created',
159
+ * doc: 'Emitted when a new user is created',
160
+ * fields: {
161
+ * userId: field.string().doc('User ID'),
162
+ * email: field.string(),
163
+ * age: field.number().optional(),
164
+ * },
165
+ * });
166
+ * ```
167
+ *
168
+ * @param event - Event definition with key, level, message, optional doc and fields
169
+ * @returns The same event definition, typed for compile-time inference
170
+ * @throws {Error} If the event key does not match the required dotted camelCase format
171
+ */
172
+ declare const defineEvent: <const Key extends string, const Fields extends Record<string, FieldBuilder<string, boolean>>>(event: EventDefinition<Key, Fields>) => EventDefinition<Key, Fields>;
173
+ /**
174
+ * Define a system or correlation event group for organizational purposes.
175
+ *
176
+ * Groups provide a namespace hierarchy for events. For correlation groups,
177
+ * prefer {@link defineCorrelationGroup} which adds automatic lifecycle events.
178
+ *
179
+ * @param group - Event group definition (system or correlation)
180
+ * @returns The same group definition, typed for compile-time inference
181
+ */
182
+ declare const defineEventGroup: <Group extends SystemEventGroup | CorrelationEventGroup>(group: Group) => Group;
183
+ /**
184
+ * Define a correlation event group with automatic lifecycle events
185
+ *
186
+ * **What is a correlation group?**
187
+ * A correlation represents a logical unit of work with a defined lifecycle
188
+ * (start, complete, timeout). Common examples: HTTP requests, batch jobs, workflows.
189
+ *
190
+ * **Automatic events added:**
191
+ * - `{key}.start` - Emitted when startCorrelation() is called
192
+ * - `{key}.complete` - Emitted when complete() is called (includes duration)
193
+ * - `{key}.fail` - Emitted when fail() is called (includes duration and error)
194
+ * - `{key}.timeout` - Emitted if no activity within timeout period
195
+ *
196
+ * **Timeout behavior:**
197
+ * - Defaults to 5 minutes (300,000ms) if not specified
198
+ * - Timer resets on ANY activity (log events, fork creation)
199
+ * - Set to 0 to disable timeout
200
+ *
201
+ * **Type safety:**
202
+ * TypeScript will infer all event keys and field types. The return type
203
+ * includes both your events and the auto-generated lifecycle events.
204
+ *
205
+ * @param group - Correlation group definition
206
+ * @returns Normalized group with auto-events and default timeout
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * const requestGroup = defineCorrelationGroup({
211
+ * key: 'api.request',
212
+ * doc: 'HTTP request lifecycle',
213
+ * timeout: 30_000, // 30 seconds
214
+ * events: {
215
+ * validated: defineEvent({
216
+ * key: 'api.request.validated',
217
+ * level: 'debug',
218
+ * message: 'Request validated',
219
+ * doc: 'Validation passed',
220
+ * }),
221
+ * processed: defineEvent({
222
+ * key: 'api.request.processed',
223
+ * level: 'info',
224
+ * message: 'Request processed',
225
+ * doc: 'Processing complete',
226
+ * fields: { statusCode: { type: 'number', required: true } },
227
+ * }),
228
+ * },
229
+ * });
230
+ *
231
+ * // Auto-events available:
232
+ * // - requestGroup.events.start
233
+ * // - requestGroup.events.complete
234
+ * // - requestGroup.events.timeout
235
+ * // - requestGroup.events.validated (your event)
236
+ * // - requestGroup.events.processed (your event)
237
+ * ```
238
+ */
239
+ declare const defineCorrelationGroup: <Group extends CorrelationEventGroup>(group: Group) => Omit<Group, "events" | "timeout"> & {
240
+ events: WithAutoEvents<Group["events"]>;
241
+ timeout: number;
242
+ };
243
+
244
+ interface ValidationMetadata {
245
+ readonly missingFields?: string[];
246
+ readonly typeErrors?: string[];
247
+ readonly invalidValues?: string[];
248
+ readonly unknownFields?: string[];
249
+ }
250
+
251
+ interface LogPayload {
252
+ readonly eventKey: string;
253
+ readonly fields: Record<string, unknown>;
254
+ readonly correlationId: string;
255
+ readonly forkId: string;
256
+ readonly metadata: Record<string, unknown>;
257
+ readonly timestamp: string;
258
+ readonly _validation?: ValidationMetadata;
259
+ }
260
+ type LogBackend = Record<LogLevel, (message: string, payload: LogPayload) => void>;
261
+ /**
262
+ * Create a zero-config backend that logs to the console.
263
+ *
264
+ * Maps each of the 9 Chronicler levels to the appropriate `console` method:
265
+ * fatal/critical/alert/error → `console.error`, warn → `console.warn`,
266
+ * audit/info → `console.info`, debug/trace → `console.debug`.
267
+ *
268
+ * @returns A fully populated LogBackend using console methods for all levels
269
+ */
270
+ declare const createConsoleBackend: () => LogBackend;
271
+ /**
272
+ * Create a backend from a partial set of handlers.
273
+ *
274
+ * For each missing level, the fallback chain is tried in order (e.g. `fatal` →
275
+ * `critical` → `error` → `warn` → `info`). If no fallback is provided either,
276
+ * the corresponding `console` method is used.
277
+ *
278
+ * @param partial - Partial backend with handlers for a subset of log levels
279
+ * @returns A fully populated LogBackend with fallbacks applied for missing levels
280
+ */
281
+ declare const createBackend: (partial: Partial<LogBackend>) => LogBackend;
282
+ /**
283
+ * A routing rule that pairs a backend with an optional filter.
284
+ *
285
+ * When `filter` is omitted the backend receives all events.
286
+ * When provided, the backend only receives events for which `filter` returns `true`.
287
+ */
288
+ interface BackendRoute {
289
+ readonly backend: LogBackend;
290
+ readonly filter?: (level: LogLevel, payload: LogPayload) => boolean;
291
+ }
292
+ /**
293
+ * Create a backend that routes events to multiple backends based on filter rules.
294
+ *
295
+ * Each route pairs a backend with an optional filter function. Events are
296
+ * dispatched to every route whose filter matches (or to all routes without a
297
+ * filter). This enables splitting logs into separate streams — for example,
298
+ * maintenance/debug logs to stdout and audit events to a dedicated store.
299
+ *
300
+ * @param routes - One or more backend routes with optional filters
301
+ * @returns A single LogBackend that fans out to the matching routes
302
+ * @throws {Error} If no routes are provided
303
+ *
304
+ * @example
305
+ * ```typescript
306
+ * const router = createRouterBackend([
307
+ * { backend: consoleBackend, filter: (level, payload) => !payload.eventKey.startsWith('audit.') },
308
+ * { backend: auditBackend, filter: (level, payload) => payload.eventKey.startsWith('audit.') },
309
+ * ]);
310
+ *
311
+ * const chronicle = createChronicle({ backend: router, metadata: { appName: 'my-app' } });
312
+ * ```
313
+ */
314
+ declare const createRouterBackend: (routes: BackendRoute[]) => LogBackend;
315
+
316
+ type ContextValue = string | number | boolean | null;
317
+ type ContextRecord = Record<string, ContextValue>;
318
+ interface ContextCollisionDetail {
319
+ readonly key: string;
320
+ readonly existingValue: ContextValue;
321
+ readonly attemptedValue: ContextValue;
322
+ }
323
+ interface ContextValidationResult {
324
+ readonly reserved: string[];
325
+ readonly collisionDetails: ContextCollisionDetail[];
326
+ readonly dropped: string[];
327
+ }
328
+
329
+ interface ChroniclerLimits {
330
+ readonly maxContextKeys?: number;
331
+ /**
332
+ * Maximum fork nesting depth. A depth of N means N levels of nesting
333
+ * from root (e.g. depth 3 allows root → child → grandchild → great-grandchild).
334
+ * Defaults to {@link DEFAULT_MAX_FORK_DEPTH}.
335
+ */
336
+ readonly maxForkDepth?: number;
337
+ readonly maxActiveCorrelations?: number;
338
+ }
339
+ interface ChroniclerConfig {
340
+ readonly backend?: LogBackend;
341
+ readonly metadata: ContextRecord;
342
+ readonly correlationIdGenerator?: () => string;
343
+ readonly limits?: ChroniclerLimits;
344
+ /**
345
+ * When `true`, throws a `ChroniclerError` with code `FIELD_VALIDATION`
346
+ * for field validation errors (missing required fields, type mismatches).
347
+ * Useful for CI/CD enforcement. Defaults to `false`.
348
+ */
349
+ readonly strict?: boolean;
350
+ /**
351
+ * Minimum log level to emit. Events below this level are silently dropped.
352
+ * Uses priority ordering: fatal(0) > critical(1) > ... > trace(8).
353
+ * Defaults to `'trace'` (all events emitted).
354
+ */
355
+ readonly minLevel?: LogLevel;
356
+ }
357
+ interface Chronicler {
358
+ /** Emit a typed event. Fields are validated against the event definition. */
359
+ event<E extends EventDefinition>(event: E, fields: EventFields<E>): void;
360
+ /**
361
+ * Untyped escape hatch — log at any level without a pre-defined event.
362
+ * Useful for incremental adoption or ad-hoc debugging.
363
+ */
364
+ log(level: LogLevel, message: string, fields?: Record<string, unknown>): void;
365
+ /** Add key-value context that is attached to all subsequent events. */
366
+ addContext(context: ContextRecord): ContextValidationResult;
367
+ /** Start a correlation — a logical unit of work with lifecycle events. */
368
+ startCorrelation(group: CorrelationEventGroup, metadata?: ContextRecord): CorrelationChronicle;
369
+ /** Create an isolated child chronicle that inherits context. */
370
+ fork(context?: ContextRecord): Chronicler;
371
+ }
372
+ /**
373
+ * A correlation represents a logical unit of work with a defined lifecycle.
374
+ *
375
+ * Unlike a root Chronicler, a correlation:
376
+ * - Has a single shared correlation ID for all events
377
+ * - Has lifecycle events (start, complete, fail, timeout)
378
+ * - Can timeout if not completed within the configured duration
379
+ * - Cannot start nested correlations (use fork() for parallel work within a correlation)
380
+ */
381
+ interface CorrelationChronicle {
382
+ /** Emit a typed event within this correlation. */
383
+ event<E extends EventDefinition>(event: E, fields: EventFields<E>): void;
384
+ /**
385
+ * Untyped escape hatch — log at any level without a pre-defined event.
386
+ * Useful for incremental adoption or ad-hoc debugging.
387
+ */
388
+ log(level: LogLevel, message: string, fields?: Record<string, unknown>): void;
389
+ /** Add key-value context that is attached to all subsequent events. */
390
+ addContext(context: ContextRecord): ContextValidationResult;
391
+ /** Create an isolated child chronicle that inherits context. */
392
+ fork(context?: ContextRecord): Chronicler;
393
+ /** Mark the correlation as successfully completed. Emits the `.complete` event. */
394
+ complete(fields?: Record<string, unknown>): void;
395
+ /** Mark the correlation as failed. Emits the `.fail` event at error level. */
396
+ fail(error?: unknown, fields?: Record<string, unknown>): void;
397
+ /** Mark the correlation as timed out. Called automatically by the timer. */
398
+ timeout(): void;
399
+ }
400
+ /**
401
+ * Create a root Chronicler instance.
402
+ *
403
+ * This is the main entry point for the library. The returned `Chronicler`
404
+ * can log events, add context, start correlations, and create forks.
405
+ *
406
+ * @param config - Chronicler configuration with optional backend, metadata, and optional correlation settings
407
+ * @returns A configured `Chronicler` instance
408
+ * @throws {ChroniclerError} `UNSUPPORTED_LOG_LEVEL` if the backend is missing required methods
409
+ * @throws {ChroniclerError} `RESERVED_FIELD` if `config.metadata` contains reserved field names
410
+ */
411
+ declare const createChronicle: (config: ChroniclerConfig) => Chronicler;
412
+
413
+ type ChroniclerErrorCode = 'UNSUPPORTED_LOG_LEVEL' | 'RESERVED_FIELD' | 'BACKEND_METHOD' | 'FORK_DEPTH_EXCEEDED' | 'CORRELATION_LIMIT_EXCEEDED' | 'FIELD_VALIDATION';
414
+ /**
415
+ * Typed error class for Chronicler configuration and runtime failures.
416
+ * Uses a discriminator `code` to identify the specific error category.
417
+ */
418
+ declare class ChroniclerError extends Error {
419
+ readonly code: ChroniclerErrorCode;
420
+ /**
421
+ * @param code - Machine-readable error category discriminator
422
+ * @param message - Human-readable description of the error
423
+ */
424
+ constructor(code: ChroniclerErrorCode, message: string);
425
+ }
426
+
427
+ export { type BackendRoute, type Chronicler, type ChroniclerConfig, ChroniclerError, type ChroniclerErrorCode, type ChroniclerLimits, type ContextCollisionDetail, type ContextRecord, type ContextValidationResult, type CorrelationChronicle, type CorrelationEventGroup, type EventDefinition, type EventFields, type FieldBuilder, type InferFieldType, type InferFields, type LogBackend, type LogLevel, type LogPayload, type SystemEventGroup, createBackend, createChronicle, createConsoleBackend, createRouterBackend, defineCorrelationGroup, defineEvent, defineEventGroup, field };