From b159b44f7b9afae8a1ea72ca1e491cb3e5c6dd7f Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 17:16:17 +0200 Subject: [PATCH 01/52] doc(TODO): init my poor-man's issue tracker, as I don't want to worry about the overhead of using a third-party service for this at the moment. --- TODO | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 TODO diff --git a/TODO b/TODO new file mode 100644 index 0000000..5485e51 --- /dev/null +++ b/TODO @@ -0,0 +1,60 @@ +# TODO List for esm-logging + +This is a poor-man's issue tracker. I am not primarily a GitHub user so don't +want to commit to their issue tracking feature, but my primary SVC service +provider (Bitbucket) only offers paid integration into their issue tracker +(Jira). I don't have the time (and patience) at the moment to analyze the best +approach, so this file will have to suffice. + +It's a very simple concept: Track any issues (features, bugfixes, hotfixes) in +here, assign a sequential number to it and use that number when branching. + +I will try to develop a format so that I can parse the file later on, should I +decide to migrate to a real issue tracker. It's probably going to be Bugzilla, +but for that my html-theme-ref project needs to stabilize first. + +## Format Specification + +The file uses Markdown conventions for formatting headers and other text block +entitities, but SHOULD NOT be considered a Markdown file. That's why it has no +definitive file extension. + +Each issue entry follows a structured format for easier parsing and future +migration. Issues MUST be **appended** to this file and never moved, to +preserve Git diffing. + +### Issue Format + +``` +ID: [ISSUE-NUMBER] +Type: [feature/bugfix/hotfix] +Title: [Short title] +Status: [open/in-progress/done] +Priority: [low/medium/high] +Created: [YYYY-MM-DD] +Description: [Detailed explanation] + +--- +``` + +- ISSUE-NUMBERs must be sequential +- truncation of description must be indentended so that every line starts at the + same column +- issues must be started with two LF +- issues must be terminated with two LF, then `---` +- issues may have a free-text field (epilog), which must be started with two LF. + +## Issues + +ID: 1 +Type: feature +Title: string formatting utilities +Status: open +Priority: high +Created: 2025-05-01 +Description: implement utilities for formatting strings. The formatting should + be inspired by Python 3K PEP 3101 in addition to their standard + library utilities starting from ver. 3.7. Optimizations should + focus on V8 support. + +--- From 15e4a5f0e1e9ea8089118dc62923910a99081fc0 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 17:24:47 +0200 Subject: [PATCH 02/52] doc(TODO): add issue #2 --- TODO | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/TODO b/TODO index 5485e51..d510126 100644 --- a/TODO +++ b/TODO @@ -26,6 +26,7 @@ preserve Git diffing. ### Issue Format ``` + ID: [ISSUE-NUMBER] Type: [feature/bugfix/hotfix] Title: [Short title] @@ -58,3 +59,17 @@ Description: implement utilities for formatting strings. The formatting should focus on V8 support. --- + +ID: 2 +Type: feature +Title: describe development workflow in CONTRIBUTING.md +Status: open +Priority: medium +Created: 2025-05-01 +Description: It's a good idea to describe the development workflow, including + branching strategies earlier on, so that if someone is interested + in forking, they can pick up right away. It's not meant for + contributions though. I'm currently not interested in external + contributions. + +--- From fcf45f22a3c846e8c7f8bac410ba988f1bbc7042 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 17:44:07 +0200 Subject: [PATCH 03/52] todo(1): in-progress --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index d510126..c4f96b7 100644 --- a/TODO +++ b/TODO @@ -50,7 +50,7 @@ Description: [Detailed explanation] ID: 1 Type: feature Title: string formatting utilities -Status: open +Status: in-progress Priority: high Created: 2025-05-01 Description: implement utilities for formatting strings. The formatting should From f38f62f53e13128b59fae19b8d25855969f9f6c4 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 22:26:30 +0200 Subject: [PATCH 04/52] todo(3): open --- TODO | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/TODO b/TODO index c4f96b7..1185c15 100644 --- a/TODO +++ b/TODO @@ -73,3 +73,16 @@ Description: It's a good idea to describe the development workflow, including contributions. --- + +ID: 3 +Type: bugfix +Title: modularize testing further +Status: open +Priority: high +Created: 2025-05-01 +Description: Since I am going to implement unit tests as well as integration + tests and probably some benchmarks, it makes sense to introduce + another sub-level directory for each type of test, say + `tests/unit/`, `tests/integration`, etc. + +--- From 72248008b927159f9460b4c6ae293141fcb647bb Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 22:27:00 +0200 Subject: [PATCH 05/52] to-do(3): in-progress --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 1185c15..36adca3 100644 --- a/TODO +++ b/TODO @@ -77,7 +77,7 @@ Description: It's a good idea to describe the development workflow, including ID: 3 Type: bugfix Title: modularize testing further -Status: open +Status: in-progress Priority: high Created: 2025-05-01 Description: Since I am going to implement unit tests as well as integration From 07b1228ac075c71454672206e92cce46c6be8dfe Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 22:49:51 +0200 Subject: [PATCH 06/52] to-do(4): open --- TODO | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/TODO b/TODO index 36adca3..483b98c 100644 --- a/TODO +++ b/TODO @@ -77,7 +77,7 @@ Description: It's a good idea to describe the development workflow, including ID: 3 Type: bugfix Title: modularize testing further -Status: in-progress +Status: done Priority: high Created: 2025-05-01 Description: Since I am going to implement unit tests as well as integration @@ -86,3 +86,19 @@ Description: Since I am going to implement unit tests as well as integration `tests/unit/`, `tests/integration`, etc. --- + +ID: 4 +Type: feature +Title: migrate testing framework from Jest to Mocha +Status: open +Priority: high +Created: 2025-05-01 +Description: I really don't like behavior-driven testing, at least when it comes + to unit testing. It feels like Walldorf education... Where I need + to come up with an abstraction for describing my test. A function + has an input and gives an output. That's what I want to test. I'm + not trying to find the philosophical meaning of my functions... + Hopefully Mocha is the savior. I'm sticking to xUnit based testing + from now on. + +--- From f45e75aa5035a258bcd95c35bdcb96adc1cac8a6 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 22:50:14 +0200 Subject: [PATCH 07/52] to-do(4): in-progress --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 483b98c..ceb7fc8 100644 --- a/TODO +++ b/TODO @@ -90,7 +90,7 @@ Description: Since I am going to implement unit tests as well as integration ID: 4 Type: feature Title: migrate testing framework from Jest to Mocha -Status: open +Status: in-progress Priority: high Created: 2025-05-01 Description: I really don't like behavior-driven testing, at least when it comes From 9f4d9336d2c9ea17212da3c88dc53529637610ed Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 19:48:11 +0200 Subject: [PATCH 08/52] style(ci): add commands for removing test-reports Bitbucket Pipelines has some weird default behavior on how artifacts are archived and JUnit test-reports are parsed on every subsequent run, if the output was once an artifact. It's confusing to look at via the dashboard, hence I'm adding an override to remove them beforehand. --- bitbucket-pipelines.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bitbucket-pipelines.yml b/bitbucket-pipelines.yml index 9a9a7a3..f11a6e3 100644 --- a/bitbucket-pipelines.yml +++ b/bitbucket-pipelines.yml @@ -26,6 +26,7 @@ definitions: - build/debug/**/* - build/debug/* script: + - make clean - make build/debug CI=1 - step: &build-release name: Build (Release) @@ -35,6 +36,7 @@ definitions: - build/release/**/* - build/release/* script: + - make clean - make build/release CI=1 - step: &build-doc name: Build (Doc) @@ -44,6 +46,7 @@ definitions: - build/doc/**/* - build/doc/* script: + - make clean - make build/doc CI=1 - step: &dist name: Package @@ -52,6 +55,7 @@ definitions: artifacts: - dist/* script: + - rm -rvf test-reports/ - make dist CI=1 pipelines: default: From ab4ef2baab876038831985714efe898a8c814ba9 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 20:59:49 +0200 Subject: [PATCH 09/52] doc(README): init rudimentary README --- README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cbe213e..4f860b2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,33 @@ +# esm-logging +> This README is a stub. Working on it. Currently stabilizing the build + environment after that I'll make it nice around here. -* [Logging Cookbook](doc/logging-cookbook.md) +A quasi-port of the Python standard library logging module to ECMAScript. +# Why? + +First of, because logging is important. It is important for debugging purposes, +leading to faster and more resilient development, for traceability leading to +better security. Most logging libraries I've discovered didn't satisfy me, +introduced weird concepts and all in all just weren't great. Other programming +language ecosystems offer way nicer logging facilities. Take Rust for example, +or... Python! Python has PEP, giving it a very structured approach towards +implementing new features and that's also how its logging facilities came to be +([PEP 282](https://peps.python.org/pep-0282/)). Python's logging facilities are +implemented by the [logging]() module, which is part of the standard library and +has been since 2002. It was originally authored by Vinay Sajip + +# Roadmap + +- do a quasi-port of the logging module with minimal amount of adaption +- add documentation +- add support for asynchronous calls +- implement Open Cybersecurity Framework (OCSF) formatter +- implement (Browser) local storage handler as a replacement for file handler + +# Usage + +For the time being, please check out my [CI +service](https://bitbucket.org/byteb4rb1e/esm-logging/pipelines), for an idea on +how to build this. From f069a0f2e4f94aa19e74216b2db6fdf4b4420633 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 22:42:55 +0200 Subject: [PATCH 10/52] refactor(src): introduce submodules --- src/config.ts | 202 +++++++ src/filter.ts | 114 ++++ src/formatter.ts | 202 +++++++ src/handler.ts | 199 +++++++ src/index.ts | 1317 +-------------------------------------------- src/log-level.ts | 118 ++++ src/log-record.ts | 77 +++ src/logger.ts | 324 +++++++++++ src/manager.ts | 127 +++++ tests/test.ts | 52 +- 10 files changed, 1400 insertions(+), 1332 deletions(-) create mode 100644 src/config.ts create mode 100644 src/filter.ts create mode 100644 src/formatter.ts create mode 100644 src/handler.ts create mode 100644 src/log-level.ts create mode 100644 src/log-record.ts create mode 100644 src/logger.ts create mode 100644 src/manager.ts diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..594d01d --- /dev/null +++ b/src/config.ts @@ -0,0 +1,202 @@ + +import { MANAGER } from './manager'; +import { ValueError } from './helper/error'; +import { STYLES, Formatter } from './formatter'; +import { StreamHandler, FileHandler, Handler } from './handler'; +import { LogLevel } from './log-level'; + +//--------------------------------------------------------------------------- +// Configuration classes and functions +//--------------------------------------------------------------------------- + +/** + * options for basic configuration of logging module + */ +export interface BasicConfigOptions { + /* + * Specifies that a FileHandler be created, using the specified filename, + * rather than a StreamHandler. + */ + filename?: string; + + /** + * Specifies the mode to open the file, if filename is specified (if + * filemode is unspecified, it defaults to 'a') + */ + filemode?: string; + + /** + * Use the specified format string for the handler. + */ + format?: string; + + /** + * Use the specified date/time format. + * + */ + datefmt?: string; + + /** + * If a format string is specified, use this to specify the type of format + * string (possible values '%', '{', '$', for %-formatting, + * :meth:`str.format` and :class:`string.Template`- defaults to '%'). + * + * TODO: switch to enum + */ + style?: string; + + /** + * Set the root logger level to the specified level. + */ + level?: LogLevel; + + /** + * Use the specified stream to initialize the StreamHandler. Note that this + * argument is incompatible with 'filename' - if both are present, 'stream' + * is ignored. + * + * TODO: + */ + stream?: any; + + /** + * If specified, this should be an iterable of already created handlers, + * which will be added to the root logger. Any handler in the list which + * does not have a formatter assigned will be assigned the formatter created + * in this function. + */ + handlers?: Handler[]; + + /** + * If this keyword is specified as true, any existing handlers attached to + * the root logger are removed and closed, before carrying out the + * configuration as specified by the other arguments. + */ + force?: boolean; + + /** + * If specified together with a filename, this encoding is passed to the + * created FileHandler, causing it to be used when the file is opened. + */ + encoding?: string; + + /** + * If specified together with a filename, this value is + * passed to the created FileHandler, causing it to be used + * when the file is opened in text mode. If not specified, + * the default value is `backslashreplace`. + */ + errors?: string|null; +} + +/** + * Do basic configuration for the logging system. + * + * This function does nothing if the root logger already has handlers + * configured, unless the keyword argument *force* is set to ``True``. + * It is a convenience method intended for use by simple scripts + * to do one-shot configuration of the logging package. + * + * The default behaviour is to create a StreamHandler which writes to + * sys.stderr, set a formatter using the BASIC_FORMAT format string, and + * add the handler to the root logger. + * + * A number of optional keyword arguments may be specified, which can alter + * the default behaviour. + * + * Note that you could specify a stream created using open(filename, mode) + * rather than passing the filename and mode in. However, it should be + * remembered that StreamHandler does not close its stream (since it may be + * using sys.stdout or sys.stderr), whereas FileHandler closes its stream + * when the handler is closed. + * + * TODO: refactor logic, there apparently is some redundancy in the original + * code + */ +export function basicConfig(options: BasicConfigOptions) { + const force = options.force ?? false; + var encoding = options.encoding ?? undefined; + var errors: string|undefined = options.errors ?? 'backslashreplace'; + var handlers = options.handlers ?? []; + const filename = options.filename ?? null; + const stream = options.stream ?? null; + const filemode = options.filemode ?? 'a'; + const dateformat = options.filemode ?? null; + const style = options.filemode ?? '%'; + const level = options.level ?? null; + + if (!Object.keys(STYLES).includes(style)) { + throw new ValueError( + `style must be one of: ${Object.keys(STYLES).join(', ')}` + ); + } + + if (force) { + for (var i = 0; i < MANAGER.root.handlers.length; i += 1) { + let h: Handler = MANAGER.root.handlers[i]; + MANAGER.root.removeHandler(h); + h.close(); + } + } + + if (handlers.length == 0) { + if (handlers === null && stream && filename) { + throw new ValueError( + "'stream' and 'filename' should not be specified together" + ); + } + + else if (stream || filename) { + throw new ValueError( + "'stream' or 'filename' should not be specified together" + + "with 'handlers'" + ); + } + + if (handlers === null) { + var h: Handler; + + if (filename) { + if (filemode.match('b')) { errors = undefined } + else { encoding = 'utf-8' } + + h = new FileHandler({ + filename: filename, + filemode: filemode, + 'encoding': encoding, + errors: errors + }); + } + + else { h = new StreamHandler(stream) } + + handlers = [h]; + } + + for (var i = 0; i < handlers.length; i += 1) { + let h = handlers[i]; + + if (h.formatter === null) { + h.formatter = new Formatter({ + fmt: options.format ?? STYLES[style][1], + datefmt: dateformat, + style: style + }); + } + + MANAGER.root.addHandler(h); + } + + if (level !== null) { MANAGER.root.setLevel(level) } + + if (options) { + // runtime interface guard, please let me stay. 🥺 + // the interface does not allow for additional members, but the + // runtime environment has no concept of interfaces. We can stick to + // the original implementation + const keys = Object.keys(options).join(', '); + + throw new ValueError(`Unrecognised argument(s): ${keys}`); + } + } +} diff --git a/src/filter.ts b/src/filter.ts new file mode 100644 index 0000000..a6c26b2 --- /dev/null +++ b/src/filter.ts @@ -0,0 +1,114 @@ +import { LogRecord } from './log-record'; + +//--------------------------------------------------------------------------- +// Filter classes and functions +//--------------------------------------------------------------------------- + +export type FilterCallable = (record: LogRecord) => boolean; + +/** + * Filter instances are used to perform arbitrary filtering of LogRecords. + * + * Loggers and Handlers can optionally use Filter instances to filter records as + * desired. The base filter class only allows events which are below a certain + * point in the logger hierarchy. For example, a filter initialized with "A.B" + * will allow events logged by loggers "A.B", initialized with the empty string, + * all events are passed. + */ +export class Filter { + public readonly scope: string; + public readonly slen: number; + + /** + * Initialize with the name of the logger which ,together with its children, + * will have its events allowed through the filter. If no name is specified, + * allow every event. + * + * @param name - name of logging scope + */ + constructor(scope: string) { + this.scope = scope ?? ''; + this.slen = this.scope.length; + } + + /** + * Inspect a record, if it should be logged. + * + * Returns true if the record should be logged, or false otherwise. If + * deemed appropriate, the record may be modified in-place. + * + * @param - scope of log record to inspect + * @param - log record to inspect + */ + filter(record: LogRecord): boolean { + if (this.slen == 0 || this.scope == record.scope) { return true } + else if (!record.scope.substring(0, this.slen)) { return false } + return (record.scope[this.slen] == '.') + } +} + +export class Filterer { + filters: Filter[] = []; + + /** + * Add the specified filter to this handler. + * + * @param filter + */ + addFilter(filter: Filter) { + if (!this.filters.includes(filter)) { this.filters.push(filter) } + } + + /** + * Remove the specified filter from this handler. + * + * @param filter + */ + removeFilter(filter: Filter) { + if (this.filters.includes(filter)) { + this.filters.splice(this.filters.indexOf(filter), 1) + } + } + + /** + * Determine if a record is loggable by consulting all the filters. + * + * The default is to allow the record to be logged; any filter can veto this + * by returning a false value. + * If a filter attached to a handler returns a log record instance, then + * that instance is used in place of the original log record in any further + * processing of the event by that handler. + * If a filter returns any other true value, the original log record is used + * in any further processing of the event by that handler. + * + * If none of the filters return false values, this method returns a log + * record. + * + * If any of the filters return a false value, this method returns a false + * value. + * + * @param filter + */ + filter(record: LogRecord): LogRecord|null { + + for (var i = 0; i < this.filters.length; i += 1) { + let result: boolean|LogRecord = false; + + let filter = this.filters[i]; + + if (typeof (filter as Filter).filter == 'function') { + result = (filter as Filter).filter(record) + } + else { + result = (filter as unknown as FilterCallable)(record) + } + + if (!result) { return null } + + if ((result as any) instanceof LogRecord) { record = result as unknown as LogRecord } + } + + return record + } +} + diff --git a/src/formatter.ts b/src/formatter.ts new file mode 100644 index 0000000..7e0197c --- /dev/null +++ b/src/formatter.ts @@ -0,0 +1,202 @@ +import { MyError, ValueError } from './helper/error'; +import { LogRecord } from './log-record'; + +//--------------------------------------------------------------------------- +// Formatter classes and functions +//--------------------------------------------------------------------------- + +export interface PercentFormatterStyleOptions { + fmt?: string, + defaults: {[key: string]: any}; +} + +class PercentFormatterStyle { + public static defaultFormat = '%(message)s'; + public static asctimeFormat = '%(asctime)s'; + public static asctimeSearch = '%(asctime)'; + public static validationPattern = + /%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]/; + + private fmt: string; + private defaults: {[key: string]: any}; + + constructor(options: PercentFormatterStyleOptions) { + this.fmt = options.fmt ?? PercentFormatterStyle.defaultFormat; + this.defaults = options.defaults; + } + + usesTime(): boolean { + return this.fmt.match(PercentFormatterStyle.asctimeFormat) ? true : false + } + + /** + * Validate the input format, ensure it matches the correct style + */ + validate() { + if (!PercentFormatterStyle.validationPattern.test(this.fmt)) { + throw new ValueError( + `Invalid format '${this.fmt}' for ` + + `'${PercentFormatterStyle.defaultFormat[0]}'` + ) + } + } + + protected _format(record: LogRecord): string { + var defaults = this.defaults; + var values: {[key: string]: any}|null; + if (defaults) { values = {...this.defaults, ...Object.entries(record)} } + else { values = Object.entries(record) } + //TODO: implement formatting + return 'would do some formatting'; + } + + format(record: LogRecord): string { + try { + return this._format(record) + } + catch (e) { + throw new ValueError(`formatting field not found in record: ${e}`) + } + } +} + +const BASIC_FORMAT = '%(level)s:%(name)s:%(message)s'; + +export const STYLES: {[key: string]: [{ new(options: PercentFormatterStyleOptions): PercentFormatterStyle}, string]} = { + '%': [PercentFormatterStyle, BASIC_FORMAT], +} + +export interface FormatterOptions { + fmt?: string + datefmt?: any + style?: string + validate?: boolean + defaults?: {[key: string]: any} +} + +/** + * Formatter instances are used to convert a LogRecord to text. + * + * Formatters need to know how a LogRecord is constructed. They are + * responsible for converting a LogRecord to (usually) a string which can + * be interpreted by either a human or an external system. The base Formatter + * allows a formatting string to be specified. If none is supplied, the + * style-dependent default value, "%(message)s", "{message}", or + * "${message}", is used. + * + * The Formatter can be initialized with a format string which makes use of + * knowledge of the LogRecord attributes - e.g. the default value mentioned + * above makes use of the fact that the user's message and arguments are pre- + * formatted into a LogRecord's message attribute. Currently, the useful + * attributes in a LogRecord are described by: + * + * %(name)s Name of the logger (logging channel) + * %(levelno)s Numeric logging level for the message (DEBUG, INFO, + * WARNING, ERROR, CRITICAL) + * %(levelname)s Text logging level for the message ("DEBUG", "INFO", + * "WARNING", "ERROR", "CRITICAL") + * %(pathname)s Full pathname of the source file where the logging + * call was issued (if available) + * %(filename)s Filename portion of pathname + * %(module)s Module (name portion of filename) + * %(lineno)d Source line number where the logging call was issued + * (if available) + * %(funcName)s Function name + * %(created)f Time when the LogRecord was created (time.time_ns() / 1e9 + * return value) + * %(asctime)s Textual time when the LogRecord was created + * %(msecs)d Millisecond portion of the creation time + * %(relativeCreated)d Time in milliseconds when the LogRecord was created, + * relative to the time the logging module was loaded + * (typically at application startup time) + * %(thread)d Thread ID (if available) + * %(threadName)s Thread name (if available) + * %(taskName)s Task name (if available) + * %(process)d Process ID (if available) + * %(message)s The result of record.getMessage(), computed just as + * the record is emitted + */ +export class Formatter { + public static defaultTimeFormat = '%Y-%M'; + public static defaultMsecFormat = '%s,%30d'; + + protected style: any; + protected fmt: string; + protected datefmt: any; + + /** + * Initialize the formatter with specified format strings. + * + * Initialize the formatter either with the specified format string, or a + * default as described above. Allow for specialized date formatting with + * the optional datefmt argument. If datefmt is omitted, you get an + * ISO8601-like (or RFC 3339-like) format. + * + * Use a style parameter of '%', '{' or '$' to specify that you want to + * use one of %-formatting, :meth:`str.format` (``{}``) formatting or + * :class:`string.Template` formatting in your format string. + */ + constructor(options?: FormatterOptions) { + options = options ?? {}; + var style = options.style ?? '%'; + var validate = options.validate ?? true; + + if (!Object.keys(STYLES).includes(style ?? '')) { + throw new ValueError(`style must be one of: ${Object.keys(STYLES).join(', ')}`) + } + + this.style = new STYLES[style][0]({ + fmt: options.fmt, + defaults: options.defaults ?? {} + }); + + if (validate) { this.style.validate() } + + this.fmt = this.style.fmt; + + this.datefmt = options.datefmt; + } + + /** + * Return the creation time of the specified LogRecord as formatted text. + * + * This method should be called from format() by a formatter which + * wants to make use of a formatted time. This method can be overridden + * in formatters to provide for any specific requirement, but the + * basic behaviour is as follows: if datefmt (a string) is specified, + * it is used with time.strftime() to format the creation time of the + * record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. + * The resulting string is returned. This function uses a user-configurable + * function to convert the creation time to a tuple. By default, + * time.localtime() is used; to change this for a particular formatter + * instance, set the 'converter' attribute to a function with the same + * signature as time.localtime() or time.gmtime(). To change it for all + * formatters, for example if you want all logging times to be shown in GMT, + * set the 'converter' attribute in the Formatter class. + */ + formatTime(record: LogRecord, datefmt?: any): string { + + //TODO: record.created + if (datefmt) { + //TODO: time.strftime + } + else { + //TODO: time.strftime + } + + return 'some time'; + } + + /** + * Format and return the specified exception information as a string. + + * This default implementation just uses + * traceback.print_exception() + */ + formatError(ei: MyError): string { + //TODO + return 'some error'; + } +} + +export const DEFAULT_FORMATTER = new Formatter(); diff --git a/src/handler.ts b/src/handler.ts new file mode 100644 index 0000000..c75db06 --- /dev/null +++ b/src/handler.ts @@ -0,0 +1,199 @@ +import * as stream from 'stream'; + +import { LogLevel, checkLevel, NOTSET } from './log-level'; +import { LogRecord } from './log-record'; +import { Formatter, DEFAULT_FORMATTER } from './formatter'; +import { Filterer } from './filter'; +import { NotImplementedError } from './helper/error'; + +if (typeof window === 'undefined') { + const stream = require('stream'); +} +else { + const stream = require('./helper/stream'); +} + +//--------------------------------------------------------------------------- +// Handler classes and functions +//---------------------------------------------------------------------------- + +type Handlers = {[key: string]: Handler}; + +/** + * map of handler names to handlers + */ +const HANDLERS: Handlers = {}; + +/** + * added to allow handlers to be removed in reverse order of initialization + */ +const HANDLER_LIST: WeakRef[] = []; + +/** + * Add a handler to the internal cleanup list using a weak reference. + * + * @param handler - + */ +function addHandlerRef(handler: Handler) { + HANDLER_LIST.push(new WeakRef(handler)); +} + +/** + * Get a handler with the specified *name*, or None if there isn't one with + * that name. + */ +export function getHandlerByName(name: string): Handler|null { + return HANDLERS[name] ?? null +} + +/** + * Return all known handler names as an immutable set + */ +export function getHandlerNames(): Handlers { return Object.freeze(HANDLERS) } + +/** + * Handler instances dispatch logging events to specific destinations. + * + * The base handler class. Acts as a placeholder which defines the Handler + * interface. Handlers can optionally use Formatter instances to format + * records as desired. By default, no formatter is specified; in this case, + * the 'raw' message as determined by record.message is logged. + */ +export class Handler extends Filterer { + + protected _scope: string|null = null; + protected _formatter: Formatter|null = null; + protected _level: number; + protected _closed: boolean = false; + + /** + * Initializes the instance - basically setting the formatter to None + * and the filter list to empty + */ + constructor(level?: LogLevel) { + super(); + this._level = checkLevel(level ?? NOTSET); + // Add the handler to the global HANDLER_LIST (for cleanup on shutdown) + addHandlerRef(this); + } + + get level(): number { return this._level } + set level(level: LogLevel|string) { this.level = checkLevel(level) } + + get scope(): string|null { return this._scope } + set scope(scope: string) { this._scope = scope } + get closed(): boolean { return this._closed } + + /** + * Format the specified record. + * + * If a formatter is set, use it. Otherwise, use the default formatter for + * the module. + */ + format(record: LogRecord) { + var fmt: Formatter|null = null; + + if (this.formatter) { fmt = this.formatter } + else { fmt = DEFAULT_FORMATTER } + } + + /** + * Do whatever it takes to actually log the specified logging record. + * + * This version is intended to be implemented by subclasses and so raises a + * NotImplementedError. + */ + emit(record: LogRecord) { + throw new NotImplementedError( + 'emit must be implemented by Handler subclass' + ) + } + + /** + * Conditionally emit the specfied logging record. + * + * Emission depends on filters which may have been added to the handler. + * Wrap the actual emission of the record with acquisition/release of the + * I/O thread lock. + */ + handle(record: LogRecord) { + var rv = this.filter(record); + if ((rv as any) instanceof LogRecord) { + record = rv as unknown as LogRecord + } + if (rv) { + //locking here + this.emit(record) + } + } + + /** + * Tidy up any resources used by the handler + * + * This version removes the handler from an internal map of handlers, which + * is used for handler lookup by scope. Subclasses should ensure that this + * gets called from overriden close() methods. + */ + close() { + this._closed = true; + + if (this.scope && Object.keys(HANDLERS).includes(this.scope)) { + delete HANDLERS[this.scope] + } + } + + /** + * Handle errors which occur during an emit() call. + * + * This method should be called from handlers when an exception is + * encountered during an emit() call. If raiseExceptions is false, + * exceptions get silently ignored. This is what is mostly wanted + * for a logging system - most users will not care about errors in + * the logging system, they are more interested in application errors. + * You could, however, replace this with a custom handler if you wish. + * The record which was being processed is passed in to this method. + */ + handleError(record: LogRecord) { + throw new NotImplementedError( + 'still need to find portable way for stacktracing...' + ) + } + + set formatter(fmt: Formatter) { this._formatter = fmt } +} + +export interface FileHandlerOptions { + filename: string + filemode?: string + encoding?: string + errors?: string +} + +/** + * A handler class which writes logging records, appropriately formatted, + to a stream. Note that this class does not close the stream, as + sys.stdout or sys.stderr may be used. + */ +export class StreamHandler extends Handler { + constructor(stream?: stream.Writable) { + super(); + } +} + +export class FileHandler extends StreamHandler { + constructor(options: FileHandlerOptions) { + super(); + } +} + +/** + * This class is like a StreamHandler using sys.stderr, but always uses + * whatever sys.stderr is currently set to rather than the value of + * sys.stderr at handler construction time. + */ + export class StderrHandler extends Handler { + /** + * Initialize the handler. + */ + constructor(level: LogLevel) { super(level) } +} diff --git a/src/index.ts b/src/index.ts index e5f0039..c35e33c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -87,1321 +87,26 @@ * * @module logging */ -import { - NotImplementedError, - MyError, - ValueError, - KeyError, - StackTrace -} from './helper/error'; -import { MillisecondsSinceUnixEpoch } from './helper/datetime'; -import * as stream from 'stream'; -if (typeof window === 'undefined') { - const stream = require('stream'); -} -else { - const stream = require('./helper/stream'); -} +export * as config from './config'; +export * as filter from './filter'; +export * as formatter from './formatter'; +export * as handler from './handler'; +// screw community conventions, whoever came up with the idea of aliasing +// imports in pascal case, or camel case doesn't seem to care about naming +// collisions. I'm sticking to kebab case as this avoids naming collisions. +export * as log_level from './log-level'; +export * as log_record from './log-record'; +export * as logger from './logger'; +export * as manager from './manager'; -/*--------------------------------------------------------------------------- - Level related stuff - --------------------------------------------------------------------------- - Default levels and level names, these can be replaced with any positive set - of values having corresponding names. There is a pseudo-level, NOTSET, which - is only really there as a lower limit for user-defined levels. Handlers and - loggers are initialized with NOTSET so that they will log all messages, even - at user-defined levels. -*/ -export type LogLevel = number; -/** - * An indication that something unexpected happened, or that a problem might - * occur in the near future (e.g. ‘disk space low’). The software is still - * working as expected. - */ -export const CRITICAL = 50; -export const FATAL = CRITICAL; -/** - * Due to a more serious problem, the software has not been able to perform some - * function. - */ -export const ERROR = 40; -/** - * An indication that something unexpected happened, or that a problem might - * occur in the near future (e.g. ‘disk space low’). The software is still - * working as expected. - */ -export const WARNING = 30; -export const WARN = WARNING; -/** - * Confirmation that things are working as expected. - */ -export const INFO = 20; -/** - * Detailed information, typically only of interest to a developer trying to - * diagnose a problem. - */ -export const DEBUG = 10; -/** - * When set on a logger, indicates that ancestor loggers are to be consulted to - * determine the effective level. If that still resolves to NOTSET, then all - * events are logged. When set on a handler, all events are handled. - */ -export const NOTSET = 0; -const LEVELTONAME: {[key: number]: string} = { - [CRITICAL]: 'CRITICAL', - [ERROR]: 'ERROR', - [WARNING]: 'WARNING', - [INFO]: 'INFO', - [DEBUG]: 'DEBUG', - [NOTSET]: 'NOTSET' -} -const NAMETOLEVEL: {[key: string]: number} = { - CRITICAL: CRITICAL, - ERROR: ERROR, - WARNING: WARNING, - INFO: INFO, - DEBUG: DEBUG, - NOTSET: NOTSET, -} - -function getLevelNamesMapping() { - return Object.assign({}, NAMETOLEVEL); -} - -/** - * Return the textual or numeric representation of logging level 'level' - * - * @param level - */ -export function getLevelName(level: string|number): string|number { - var result: string|number = LEVELTONAME[level as number]; - if (result !== undefined) { return result } - result = NAMETOLEVEL[level as string]; - if (result !== undefined) { return result } - return `Level ${level}`; -} - -/** - * Associate 'levelName' with 'level' - * - * @param level - * @param levelName - */ -export function addLevelName(level: number, levelName: string) { - LEVELTONAME[level] = levelName; - NAMETOLEVEL[levelName] = level; -} - -function checkLevel(level: number|string): number { - var rv: number; - - if (typeof level == 'number') { rv = level } - - else if (typeof level == 'string') { - if (!Object.keys(NAMETOLEVEL).includes(level as string)) { - throw new Error(`Unknown level: ${level}`) - } - - rv = NAMETOLEVEL[level] - } - - else { - throw new Error(`Level not a number or valid string: ${level}`) - } - - return rv -} - -export type ExecutionInfo = [string, Error, StackTrace]; - -//--------------------------------------------------------------------------- -// The logging record -//--------------------------------------------------------------------------- - -/** - * options for instantiating a new log record - */ -export interface LogRecordOptions { - /** - * The numeric level of the logging event (such as 10 for DEBUG, 20 for - * INFO, etc). Note that this is converted to two attributes of the - * LogRecord: levelno for the numeric value and levelname for the - * corresponding level name. - */ - level: number, - file?: string, - /** - * The line number in the source file where the logging call was made. - */ - lno?: number, - /** - * The event description message, which can be a %-format string with - * placeholders for variable data, or an arbitrary object (see Using - * arbitrary objects as messages). - */ - msg: string, - /** - * Variable data to merge into the msg argument to obtain the event - * description. - */ - args?: any[], -} - -export type LogRecordFactory = { (name: string, options: LogRecordOptions): LogRecord }; - -/** - * LogRecord instances are created every time something is logged. They contain - * all the information pertinent to the event being logged. The main - * information parssed in is msg and args, which are combined using str(msg) % - * args to create the message field of the record. The record also includes - * information such as when the record was created, the source line where the - * logging call was made, and any exception information to be logged. - */ -export class LogRecord { - public readonly levelno: LogLevel; - public readonly levelname: string|LogLevel; - public readonly scope: string; - - public readonly created: MillisecondsSinceUnixEpoch = Date.now(); - - constructor(scope: string, options: LogRecordOptions) { - this.levelno = options.level; - this.levelname = getLevelName(options.level); - this.scope = scope; - } -} - -var logRecordFactory = (scope: string, options: LogRecordOptions) => { - return new LogRecord(scope, options) -}; - -/** - * Define which class use when instantiating log records. - * - * @param factory - A callable which will be called to instantiate a log record. - * Pass a clojure, if your factory is a class already. - */ -export function setLogRecordFactory(factory: LogRecordFactory) { - logRecordFactory = factory -} - -export function getLogRecordFactory(): LogRecordFactory { - return logRecordFactory -} - -//--------------------------------------------------------------------------- -// Formatter classes and functions -//--------------------------------------------------------------------------- - -export interface PercentFormatterStyleOptions { - fmt?: string, - defaults: {[key: string]: any}; -} - -class PercentFormatterStyle { - public static defaultFormat = '%(message)s'; - public static asctimeFormat = '%(asctime)s'; - public static asctimeSearch = '%(asctime)'; - public static validationPattern = - /%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]/; - - private fmt: string; - private defaults: {[key: string]: any}; - - constructor(options: PercentFormatterStyleOptions) { - this.fmt = options.fmt ?? PercentFormatterStyle.defaultFormat; - this.defaults = options.defaults; - } - - usesTime(): boolean { - return this.fmt.match(PercentFormatterStyle.asctimeFormat) ? true : false - } - - /** - * Validate the input format, ensure it matches the correct style - */ - validate() { - if (!PercentFormatterStyle.validationPattern.test(this.fmt)) { - throw new ValueError( - `Invalid format '${this.fmt}' for ` + - `'${PercentFormatterStyle.defaultFormat[0]}'` - ) - } - } - - protected _format(record: LogRecord): string { - var defaults = this.defaults; - var values: {[key: string]: any}|null; - if (defaults) { values = {...this.defaults, ...Object.entries(record)} } - else { values = Object.entries(record) } - //TODO: implement formatting - return 'would do some formatting'; - } - - format(record: LogRecord): string { - try { - return this._format(record) - } - catch (e) { - throw new ValueError(`formatting field not found in record: ${e}`) - } - } -} - -const BASIC_FORMAT = '%(level)s:%(name)s:%(message)s'; - -const STYLES: {[key: string]: [{ new(options: PercentFormatterStyleOptions): PercentFormatterStyle}, string]} = { - '%': [PercentFormatterStyle, BASIC_FORMAT], -} - -export interface FormatterOptions { - fmt?: string - datefmt?: any - style?: string - validate?: boolean - defaults?: {[key: string]: any} -} - -/** - * Formatter instances are used to convert a LogRecord to text. - * - * Formatters need to know how a LogRecord is constructed. They are - * responsible for converting a LogRecord to (usually) a string which can - * be interpreted by either a human or an external system. The base Formatter - * allows a formatting string to be specified. If none is supplied, the - * style-dependent default value, "%(message)s", "{message}", or - * "${message}", is used. - * - * The Formatter can be initialized with a format string which makes use of - * knowledge of the LogRecord attributes - e.g. the default value mentioned - * above makes use of the fact that the user's message and arguments are pre- - * formatted into a LogRecord's message attribute. Currently, the useful - * attributes in a LogRecord are described by: - * - * %(name)s Name of the logger (logging channel) - * %(levelno)s Numeric logging level for the message (DEBUG, INFO, - * WARNING, ERROR, CRITICAL) - * %(levelname)s Text logging level for the message ("DEBUG", "INFO", - * "WARNING", "ERROR", "CRITICAL") - * %(pathname)s Full pathname of the source file where the logging - * call was issued (if available) - * %(filename)s Filename portion of pathname - * %(module)s Module (name portion of filename) - * %(lineno)d Source line number where the logging call was issued - * (if available) - * %(funcName)s Function name - * %(created)f Time when the LogRecord was created (time.time_ns() / 1e9 - * return value) - * %(asctime)s Textual time when the LogRecord was created - * %(msecs)d Millisecond portion of the creation time - * %(relativeCreated)d Time in milliseconds when the LogRecord was created, - * relative to the time the logging module was loaded - * (typically at application startup time) - * %(thread)d Thread ID (if available) - * %(threadName)s Thread name (if available) - * %(taskName)s Task name (if available) - * %(process)d Process ID (if available) - * %(message)s The result of record.getMessage(), computed just as - * the record is emitted - */ -export class Formatter { - public static defaultTimeFormat = '%Y-%M'; - public static defaultMsecFormat = '%s,%30d'; - - protected style: any; - protected fmt: string; - protected datefmt: any; - - /** - * Initialize the formatter with specified format strings. - * - * Initialize the formatter either with the specified format string, or a - * default as described above. Allow for specialized date formatting with - * the optional datefmt argument. If datefmt is omitted, you get an - * ISO8601-like (or RFC 3339-like) format. - * - * Use a style parameter of '%', '{' or '$' to specify that you want to - * use one of %-formatting, :meth:`str.format` (``{}``) formatting or - * :class:`string.Template` formatting in your format string. - */ - constructor(options?: FormatterOptions) { - options = options ?? {}; - var style = options.style ?? '%'; - var validate = options.validate ?? true; - - if (!Object.keys(STYLES).includes(style ?? '')) { - throw new ValueError(`style must be one of: ${Object.keys(STYLES).join(', ')}`) - } - - this.style = new STYLES[style][0]({ - fmt: options.fmt, - defaults: options.defaults ?? {} - }); - - if (validate) { this.style.validate() } - - this.fmt = this.style.fmt; - - this.datefmt = options.datefmt; - } - - /** - * Return the creation time of the specified LogRecord as formatted text. - * - * This method should be called from format() by a formatter which - * wants to make use of a formatted time. This method can be overridden - * in formatters to provide for any specific requirement, but the - * basic behaviour is as follows: if datefmt (a string) is specified, - * it is used with time.strftime() to format the creation time of the - * record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. - * The resulting string is returned. This function uses a user-configurable - * function to convert the creation time to a tuple. By default, - * time.localtime() is used; to change this for a particular formatter - * instance, set the 'converter' attribute to a function with the same - * signature as time.localtime() or time.gmtime(). To change it for all - * formatters, for example if you want all logging times to be shown in GMT, - * set the 'converter' attribute in the Formatter class. - */ - formatTime(record: LogRecord, datefmt?: any): string { - - //TODO: record.created - if (datefmt) { - //TODO: time.strftime - } - else { - //TODO: time.strftime - } - - return 'some time'; - } - - /** - * Format and return the specified exception information as a string. - - * This default implementation just uses - * traceback.print_exception() - */ - formatError(ei: MyError): string { - //TODO - return 'some error'; - } -} - -const DEFAULT_FORMATTER = new Formatter(); - -//--------------------------------------------------------------------------- -// Filter classes and functions -//--------------------------------------------------------------------------- - -export type FilterCallable = (record: LogRecord) => boolean; - -/** - * Filter instances are used to perform arbitrary filtering of LogRecords. - * - * Loggers and Handlers can optionally use Filter instances to filter records as - * desired. The base filter class only allows events which are below a certain - * point in the logger hierarchy. For example, a filter initialized with "A.B" - * will allow events logged by loggers "A.B", initialized with the empty string, - * all events are passed. - */ -export class Filter { - public readonly scope: string; - public readonly slen: number; - - /** - * Initialize with the name of the logger which ,together with its children, - * will have its events allowed through the filter. If no name is specified, - * allow every event. - * - * @param name - name of logging scope - */ - constructor(scope: string) { - this.scope = scope ?? ''; - this.slen = this.scope.length; - } - - /** - * Inspect a record, if it should be logged. - * - * Returns true if the record should be logged, or false otherwise. If - * deemed appropriate, the record may be modified in-place. - * - * @param - scope of log record to inspect - * @param - log record to inspect - */ - filter(record: LogRecord): boolean { - if (this.slen == 0 || this.scope == record.scope) { return true } - else if (!record.scope.substring(0, this.slen)) { return false } - return (record.scope[this.slen] == '.') - } -} - -export class Filterer { - filters: Filter[] = []; - - /** - * Add the specified filter to this handler. - * - * @param filter - */ - addFilter(filter: Filter) { - if (!this.filters.includes(filter)) { this.filters.push(filter) } - } - - /** - * Remove the specified filter from this handler. - * - * @param filter - */ - removeFilter(filter: Filter) { - if (this.filters.includes(filter)) { - this.filters.splice(this.filters.indexOf(filter), 1) - } - } - - /** - * Determine if a record is loggable by consulting all the filters. - * - * The default is to allow the record to be logged; any filter can veto this - * by returning a false value. - * If a filter attached to a handler returns a log record instance, then - * that instance is used in place of the original log record in any further - * processing of the event by that handler. - * If a filter returns any other true value, the original log record is used - * in any further processing of the event by that handler. - * - * If none of the filters return false values, this method returns a log - * record. - * - * If any of the filters return a false value, this method returns a false - * value. - * - * @param filter - */ - filter(record: LogRecord): LogRecord|null { - - for (var i = 0; i < this.filters.length; i += 1) { - let result: boolean|LogRecord = false; - - let filter = this.filters[i]; - - if (typeof (filter as Filter).filter == 'function') { - result = (filter as Filter).filter(record) - } - else { - result = (filter as unknown as FilterCallable)(record) - } - - if (!result) { return null } - - if ((result as any) instanceof LogRecord) { record = result as unknown as LogRecord } - } - - return record - } -} - -var throwErrors: boolean = true; - -//--------------------------------------------------------------------------- -// Handler classes and functions -//---------------------------------------------------------------------------- - -type Handlers = {[key: string]: Handler}; - -/** - * map of handler names to handlers - */ -const HANDLERS: Handlers = {}; - -/** - * added to allow handlers to be removed in reverse order of initialization - */ -const HANDLER_LIST: WeakRef[] = []; - -/** - * Add a handler to the internal cleanup list using a weak reference. - * - * @param handler - - */ -function addHandlerRef(handler: Handler) { - HANDLER_LIST.push(new WeakRef(handler)); -} - -/** - * Get a handler with the specified *name*, or None if there isn't one with - * that name. - */ -export function getHandlerByName(name: string): Handler|null { - return HANDLERS[name] ?? null -} - -/** - * Return all known handler names as an immutable set - */ -export function getHandlerNames(): Handlers { return Object.freeze(HANDLERS) } - -/** - * Handler instances dispatch logging events to specific destinations. - * - * The base handler class. Acts as a placeholder which defines the Handler - * interface. Handlers can optionally use Formatter instances to format - * records as desired. By default, no formatter is specified; in this case, - * the 'raw' message as determined by record.message is logged. - */ -export class Handler extends Filterer { - - protected _scope: string|null = null; - protected _formatter: Formatter|null = null; - protected _level: number; - protected _closed: boolean = false; - - /** - * Initializes the instance - basically setting the formatter to None - * and the filter list to empty - */ - constructor(level?: LogLevel) { - super(); - this._level = checkLevel(level ?? NOTSET); - // Add the handler to the global HANDLER_LIST (for cleanup on shutdown) - addHandlerRef(this); - } - - get level(): number { return this._level } - set level(level: LogLevel|string) { this.level = checkLevel(level) } - - get scope(): string|null { return this._scope } - set scope(scope: string) { this._scope = scope } - get closed(): boolean { return this._closed } - - /** - * Format the specified record. - * - * If a formatter is set, use it. Otherwise, use the default formatter for - * the module. - */ - format(record: LogRecord) { - var fmt: Formatter|null = null; - - if (this.formatter) { fmt = this.formatter } - else { fmt = DEFAULT_FORMATTER } - } - - /** - * Do whatever it takes to actually log the specified logging record. - * - * This version is intended to be implemented by subclasses and so raises a - * NotImplementedError. - */ - emit(record: LogRecord) { - throw new NotImplementedError( - 'emit must be implemented by Handler subclass' - ) - } - - /** - * Conditionally emit the specfied logging record. - * - * Emission depends on filters which may have been added to the handler. - * Wrap the actual emission of the record with acquisition/release of the - * I/O thread lock. - */ - handle(record: LogRecord) { - var rv = this.filter(record); - if ((rv as any) instanceof LogRecord) { - record = rv as unknown as LogRecord - } - if (rv) { - //locking here - this.emit(record) - } - } - - /** - * Tidy up any resources used by the handler - * - * This version removes the handler from an internal map of handlers, which - * is used for handler lookup by scope. Subclasses should ensure that this - * gets called from overriden close() methods. - */ - close() { - this._closed = true; - - if (this.scope && Object.keys(HANDLERS).includes(this.scope)) { - delete HANDLERS[this.scope] - } - } - - /** - * Handle errors which occur during an emit() call. - * - * This method should be called from handlers when an exception is - * encountered during an emit() call. If raiseExceptions is false, - * exceptions get silently ignored. This is what is mostly wanted - * for a logging system - most users will not care about errors in - * the logging system, they are more interested in application errors. - * You could, however, replace this with a custom handler if you wish. - * The record which was being processed is passed in to this method. - */ - handleError(record: LogRecord) { - throw new NotImplementedError( - 'still need to find portable way for stacktracing...' - ) - } - - set formatter(fmt: Formatter) { this._formatter = fmt } -} - -export interface FileHandlerOptions { - filename: string - filemode?: string - encoding?: string - errors?: string -} - -/** - * A handler class which writes logging records, appropriately formatted, - to a stream. Note that this class does not close the stream, as - sys.stdout or sys.stderr may be used. - */ -export class StreamHandler extends Handler { - constructor(stream?: stream.Writable) { - super(); - } -} - -export class FileHandler extends StreamHandler { - constructor(options: FileHandlerOptions) { - super(); - } -} - -/** - * This class is like a StreamHandler using sys.stderr, but always uses - * whatever sys.stderr is currently set to rather than the value of - * sys.stderr at handler construction time. - */ - export class StderrHandler extends Handler { - /** - * Initialize the handler. - */ - constructor(level: LogLevel) { super(level) } -} - -const DEFAULT_LAST_RESORT = new StderrHandler(WARNING); - -export var lastResort = DEFAULT_LAST_RESORT; - -//--------------------------------------------------------------------------- -// Manager classes and functions -//--------------------------------------------------------------------------- - -/** - * Placeholder instance - */ -export class Placeholder { - protected loggers: Logger[] = []; - - /** - * initialize with the specified logger being a child of this placeholder. - */ - constructor(logger: Logger) { this.push(logger) } - - /** - * add the specified logger as a child of this placeholder - */ - public push(logger: Logger) { - if (!this.loggers.includes(logger)) { this.loggers.push(logger) } - } -} - -/** - * There is [under normal circumstances] just one Manager intance, which holds - * the hierarchy of loggers. - */ -export class Manager { - public readonly root: RootLogger; - protected _disable: number = 0; - public emittedNoHandlerWarning: boolean = false; - protected loggers: {[key: string]: Logger} = {}; - protected _loggerClass: LoggerClass|null = null; - protected _logRecordFactory: LogRecordFactory|null = null; - - public get disable(): number { return this._disable } - - public set disable(level: LogLevel) { this._disable = checkLevel(level) } - - /** - * Initialize the manager with the root node of the logger hierarchy - */ - constructor(root: RootLogger) { - this.root = root; - } - - /** - * Get a logger with the specified name (scope name), creating it, if it - * does not yet exist. This name is a dot-separated hierarchical name, such - * as "a", "a.b", "a.b.c" or similar. - * - * If a PlaceHolder existed for the specified name [i.e. the logger didn't - * exist but a child of it did], replace it with the created logger and fix - * up the parent/child references which pointed to the placeholder to now - * point to the logger. - */ - getLogger(scope: string) { - var rv: null|Logger = null; - - if (typeof scope != 'string') { - - rv = this.loggers[scope]; - - if (rv instanceof Placeholder) { - var ph = rv; - rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); - } - else { - rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); - this.loggers[scope] = rv; - } - } - } - - /** - * Set the class to be used when instantiating a logger with this Manager. - */ - set loggerClass(class_: LoggerClass) { - if (class_ !== Logger) { - if (!(class_.prototype instanceof Logger)) { - throw new TypeError("logger not derived from logging.Logger: ") - } - } - - this._loggerClass = class_; - } - - /** - * Set the factory to be used when instantiating a log record with this - * Manager. - */ - set logRecordFactory(factory: LogRecordFactory) { - this._logRecordFactory = factory; - } - - /** - * clear the cache for all loggers in loggerDict - */ - public clear() { - Object.values(this.loggers).forEach((logger) => { - logger.clear() - }); - } -} - -//--------------------------------------------------------------------------- -// Logger classes and functions -//--------------------------------------------------------------------------- - -export type LoggerClass = { new(): Logger }; - -/** - * context of a logging event/trigger - */ -export interface LogOptions{ - /** - * - */ - excInfo: ExecutionInfo|Error|null, - /** - * - */ - extra: {[key: string]: any}|null, - /** - * - */ - stackInfo: boolean, - /** - * - */ - stackLevel: number -} - -const DEFAULT_LOG_OPTIONS: LogOptions = Object.freeze({ - excInfo: null, - extra: null, - stackInfo: false, - stackLevel: 1 -}); - -/** - * Instances of the logger class represent a single logging channel. A 'logging - * channel' indicates an area of an application. Exactly how an 'area' is - * defined is up to the application developer. Since an application can have any - * number of areas, logging channels are identified by a unique string. - * Application areas can be nested (e.g. an area of input process might include - * sub-areas "read CSV file", "read XLS files" and "read Gnumeric files"). To - * cater for this natural nesting, channel ames are organized into a namespace - * hierarchy where levels are separated by periods, much like the Java or Python - * package namespace. So in the instance given above, channel names might be - * "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for - * the sub-levels. - * There is no arbitrary limit to the depth of nesting. - */ -export class Logger extends Filterer { - public readonly scope: string; - public _level: number; - private _manager: Manager|null = null; - public readonly parent: Logger|null = null; - public readonly propagate: boolean = true; - public readonly handlers: Handler[] = []; - public readonly disabled: boolean = false; - private cache: {[key: number]: boolean} = {}; - - /** - * Initialize the logger with a name and an optional level - * - * @param scope - - * @param level - - * @param manager - - */ - constructor( - scope: string, - level?: LogLevel, - ) { - super(); - - this.scope = scope; - this._level = checkLevel(level ?? NOTSET); - } - - public get level() { return this._level } - - public set level(level: LogLevel) { this._level = checkLevel(level) } - - public set manager(manager: Manager) { - if (this.manager) { - throw new ValueError('logger can only be assigned to manager once'); - } - } - - public setLevel(level: LogLevel) { - this.level = checkLevel(level); - - //this.manager.clearCache() - } - - /** - * Get the effective level for this logger. - * - * Loop through this logger and its parents in the logger hierarchy, looking - * for a non-zero logging level. Return the first one found. - */ - public getEffectiveLevel() { - var logger: Logger|null = this; - - while (logger) { - if (logger.level) { return logger.level } - logger = logger.parent; - } - - return NOTSET; - } - - /** - * Is this logger enabled for level 'level'? - */ - public isEnabledFor(level: LogLevel): boolean { - if (this.disabled) { return false } - - if (this.cache[level] === undefined && this.manager && this.manager.disable < level) { - return this.cache[level] = ( - level >= this.getEffectiveLevel() - ); - } - - return this.cache[level] = false; - } - - /** - * Log 'msg % args' with severity 'DEBUG' - * - * To pass exception information, use the keyword argument exc_info with - * a true value, e.g. - * - * ``` - * logger.debug("Houston, we have a thorny problem", { exc_info: true }) - * ``` - */ - public debug(msg: string, options?: LogOptions) { - if (this.isEnabledFor(DEBUG)) { this._log(DEBUG, msg, options) } - } - - /** - * A factory method which can be overriden in subclasses to create - * specialized LogRecords. - * - * - */ - protected makeRecord( - name: string, - level: LogLevel, - msg: string, - options: LogOptions, - ): LogRecord { - - var recordOptions: LogRecordOptions = { - level: level, - msg: msg, - }; - - var rv = logRecordFactory(name, recordOptions); - - if (options.extra !== null) { - Object.entries(options.extra!).forEach((item) => { - - var [k, v] = item; - - if (['message', 'asctime'].includes(k as string) || - (rv as {[key: string]: any}).keys().includes(k as string)) { - throw new KeyError('attempt to overwrite ${k} in LogRecord') - } - - (rv as any)[k] = options.extra![k as string] as any - }) - } - - return rv - } - - /** - * Low-level logging routine which creates a LogRecord and then calls the - * handlers of this logger to handle the record. - */ - protected _log(level: LogLevel, msg: string, options?: LogOptions) { - options = options ?? DEFAULT_LOG_OPTIONS; - options = { ...DEFAULT_LOG_OPTIONS, ...options }; - - var sinfo=null; - - if (options!.excInfo !== null) { - if (options!.excInfo instanceof Error) { - var excInfo: ExecutionInfo = [ - typeof options!.excInfo, - options!.excInfo, - options!.excInfo.stack! - ] - } - else if (!(options!.excInfo instanceof Array)) { - throw new NotImplementedError("would try to get the callee stack from the system. Probably will use stacktrace.js as this needs to be implemented browser-specific."); - } - } - - var record = this.makeRecord(this.scope, level, msg, options) - } - - /** - * Call the handlers for the specified record. - * - * This method is used for unpickled records received from a socket, as well - * as those created locally. Logger-level filtering is applied. - */ - protected handle(scope: string, record: LogRecord) { - if (this.disabled) { return } - var maybeRecord = this.filter(record); - if (!maybeRecord) { return } - if ((maybeRecord as any) instanceof LogRecord) { record = maybeRecord } - this.callHandlers(record) - } - - /** - * Pass a record to all relevant handlers. - * - * Loop through all handlers for this logger and its parents n the logger - * hierarchy. If no handler was found, output a one-off error message to - * sys.stderr. Stop searching up the hierarchy whenever a logger with the - * "propagate" attribute set to zero is found - that will be the last logger - * whose handlers are called. - */ - protected callHandlers(record: LogRecord) { - var c: Logger|null = this; - var found = 0; - - while (c) { - for (var i = 0; i < c.handlers.length; i += 1) { - let hdlr = c.handlers[i]; - - found = found + 1; - - if (record.levelno >= hdlr.level) { hdlr.handle(record) } - } - - if (!c.propagate) { c = null } - else { c = c.parent } - } - - if (found == 0) { - if (lastResort) { - if (record.levelno >= lastResort.level) { - lastResort.handle(record) - } - else if (throwErrors && (this.manager && !this.manager.emittedNoHandlerWarning)) { - console.error( - `No handlers could be found for logger ${this.scope}` - ); - - this.manager.emittedNoHandlerWarning = true; - } - } - } - } - - public clear() { - for (var property in this.cache) delete this.cache[property]; - } - - /** - * Remove the specified handler from this logger. - */ - public addHandler(hdlr: Handler) { - const i = this.handlers.indexOf(hdlr); - if (i === -1) { this.handlers.push(hdlr) } - } - - /** - * Remove the specified handler from this logger. - */ - public removeHandler(hdlr: Handler) { - const i = this.handlers.indexOf(hdlr); - if (i !== -1) { delete this.handlers[i] } - } -} - -/** - * A root logger is not that different to any other logger, except that it must - * have a logging level and there is only one instance of in a manager's - * hierarchy. - */ -class RootLogger extends Logger { - - constructor(level: LogLevel) { - super('root', level); - } -} - -var loggerClass = Logger; - -/** - * root logger (singleton) - */ -const ROOT = new RootLogger(WARNING); - -/** - * log manager (singleton) - */ -const MANAGER = new Manager(ROOT); - -//--------------------------------------------------------------------------- -// Configuration classes and functions -//--------------------------------------------------------------------------- - -/** - * options for basic configuration of logging module - */ -export interface BasicConfigOptions { - /* - * Specifies that a FileHandler be created, using the specified filename, - * rather than a StreamHandler. - */ - filename?: string; - - /** - * Specifies the mode to open the file, if filename is specified (if - * filemode is unspecified, it defaults to 'a') - */ - filemode?: string; - - /** - * Use the specified format string for the handler. - */ - format?: string; - - /** - * Use the specified date/time format. - * - */ - datefmt?: string; - - /** - * If a format string is specified, use this to specify the type of format - * string (possible values '%', '{', '$', for %-formatting, - * :meth:`str.format` and :class:`string.Template`- defaults to '%'). - * - * TODO: switch to enum - */ - style?: string; - - /** - * Set the root logger level to the specified level. - */ - level?: LogLevel; - - /** - * Use the specified stream to initialize the StreamHandler. Note that this - * argument is incompatible with 'filename' - if both are present, 'stream' - * is ignored. - * - * TODO: - */ - stream?: any; - - /** - * If specified, this should be an iterable of already created handlers, - * which will be added to the root logger. Any handler in the list which - * does not have a formatter assigned will be assigned the formatter created - * in this function. - */ - handlers?: Handler[]; - - /** - * If this keyword is specified as true, any existing handlers attached to - * the root logger are removed and closed, before carrying out the - * configuration as specified by the other arguments. - */ - force?: boolean; - - /** - * If specified together with a filename, this encoding is passed to the - * created FileHandler, causing it to be used when the file is opened. - */ - encoding?: string; - - /** - * If specified together with a filename, this value is - * passed to the created FileHandler, causing it to be used - * when the file is opened in text mode. If not specified, - * the default value is `backslashreplace`. - */ - errors?: string|null; -} - -/** - * Do basic configuration for the logging system. - * - * This function does nothing if the root logger already has handlers - * configured, unless the keyword argument *force* is set to ``True``. - * It is a convenience method intended for use by simple scripts - * to do one-shot configuration of the logging package. - * - * The default behaviour is to create a StreamHandler which writes to - * sys.stderr, set a formatter using the BASIC_FORMAT format string, and - * add the handler to the root logger. - * - * A number of optional keyword arguments may be specified, which can alter - * the default behaviour. - * - * Note that you could specify a stream created using open(filename, mode) - * rather than passing the filename and mode in. However, it should be - * remembered that StreamHandler does not close its stream (since it may be - * using sys.stdout or sys.stderr), whereas FileHandler closes its stream - * when the handler is closed. - * - * TODO: refactor logic, there apparently is some redundancy in the original - * code - */ -export function basicConfig(options: BasicConfigOptions) { - const force = options.force ?? false; - var encoding = options.encoding ?? undefined; - var errors: string|undefined = options.errors ?? 'backslashreplace'; - var handlers = options.handlers ?? []; - const filename = options.filename ?? null; - const stream = options.stream ?? null; - const filemode = options.filemode ?? 'a'; - const dateformat = options.filemode ?? null; - const style = options.filemode ?? '%'; - const level = options.level ?? null; - - if (!Object.keys(STYLES).includes(style)) { - throw new ValueError( - `style must be one of: ${Object.keys(STYLES).join(', ')}` - ); - } - - if (force) { - for (var i = 0; i < MANAGER.root.handlers.length; i += 1) { - let h: Handler = MANAGER.root.handlers[i]; - MANAGER.root.removeHandler(h); - h.close(); - } - } - - if (handlers.length == 0) { - if (handlers === null && stream && filename) { - throw new ValueError( - "'stream' and 'filename' should not be specified together" - ); - } - - else if (stream || filename) { - throw new ValueError( - "'stream' or 'filename' should not be specified together" + - "with 'handlers'" - ); - } - - if (handlers === null) { - var h: Handler; - - if (filename) { - if (filemode.match('b')) { errors = undefined } - else { encoding = 'utf-8' } - - h = new FileHandler({ - filename: filename, - filemode: filemode, - 'encoding': encoding, - errors: errors - }); - } - - else { h = new StreamHandler(stream) } - - handlers = [h]; - } - - for (var i = 0; i < handlers.length; i += 1) { - let h = handlers[i]; - - if (h.formatter === null) { - h.formatter = new Formatter({ - fmt: options.format ?? STYLES[style][1], - datefmt: dateformat, - style: style - }); - } - - MANAGER.root.addHandler(h); - } - - if (level !== null) { MANAGER.root.setLevel(level) } - - if (options) { - // runtime interface guard, please let me stay. 🥺 - // the interface does not allow for additional members, but the - // runtime environment has no concept of interfaces. We can stick to - // the original implementation - const keys = Object.keys(options).join(', '); - - throw new ValueError(`Unrecognised argument(s): ${keys}`); - } - } -} diff --git a/src/log-level.ts b/src/log-level.ts new file mode 100644 index 0000000..23014ba --- /dev/null +++ b/src/log-level.ts @@ -0,0 +1,118 @@ +/*--------------------------------------------------------------------------- + Level related stuff + --------------------------------------------------------------------------- + + Default levels and level names, these can be replaced with any positive set + of values having corresponding names. There is a pseudo-level, NOTSET, which + is only really there as a lower limit for user-defined levels. Handlers and + loggers are initialized with NOTSET so that they will log all messages, even + at user-defined levels. +*/ + +export type LogLevel = number; + +/** + * An indication that something unexpected happened, or that a problem might + * occur in the near future (e.g. ‘disk space low’). The software is still + * working as expected. + */ +export const CRITICAL = 50; +export const FATAL = CRITICAL; + +/** + * Due to a more serious problem, the software has not been able to perform some + * function. + */ +export const ERROR = 40; + +/** + * An indication that something unexpected happened, or that a problem might + * occur in the near future (e.g. ‘disk space low’). The software is still + * working as expected. + */ +export const WARNING = 30; +export const WARN = WARNING; + +/** + * Confirmation that things are working as expected. + */ +export const INFO = 20; + +/** + * Detailed information, typically only of interest to a developer trying to + * diagnose a problem. + */ +export const DEBUG = 10; + +/** + * When set on a logger, indicates that ancestor loggers are to be consulted to + * determine the effective level. If that still resolves to NOTSET, then all + * events are logged. When set on a handler, all events are handled. + */ +export const NOTSET = 0; + +const LEVELTONAME: {[key: number]: string} = { + [CRITICAL]: 'CRITICAL', + [ERROR]: 'ERROR', + [WARNING]: 'WARNING', + [INFO]: 'INFO', + [DEBUG]: 'DEBUG', + [NOTSET]: 'NOTSET' +} + +const NAMETOLEVEL: {[key: string]: number} = { + CRITICAL: CRITICAL, + ERROR: ERROR, + WARNING: WARNING, + INFO: INFO, + DEBUG: DEBUG, + NOTSET: NOTSET, +} + +function getLevelNamesMapping() { + return Object.assign({}, NAMETOLEVEL); +} + +/** + * Return the textual or numeric representation of logging level 'level' + * + * @param level + */ +export function getLevelName(level: string|number): string|number { + var result: string|number = LEVELTONAME[level as number]; + if (result !== undefined) { return result } + result = NAMETOLEVEL[level as string]; + if (result !== undefined) { return result } + return `Level ${level}`; +} + +/** + * Associate 'levelName' with 'level' + * + * @param level + * @param levelName + */ +export function addLevelName(level: number, levelName: string) { + LEVELTONAME[level] = levelName; + NAMETOLEVEL[levelName] = level; +} + +export function checkLevel(level: number|string): number { + var rv: number; + + if (typeof level == 'number') { rv = level } + + else if (typeof level == 'string') { + if (!Object.keys(NAMETOLEVEL).includes(level as string)) { + throw new Error(`Unknown level: ${level}`) + } + + rv = NAMETOLEVEL[level] + } + + else { + throw new Error(`Level not a number or valid string: ${level}`) + } + + return rv +} diff --git a/src/log-record.ts b/src/log-record.ts new file mode 100644 index 0000000..6c6f335 --- /dev/null +++ b/src/log-record.ts @@ -0,0 +1,77 @@ +import { getLevelName, LogLevel } from './log-level'; +import { MillisecondsSinceUnixEpoch } from './helper/datetime'; + +//--------------------------------------------------------------------------- +// The logging record +//--------------------------------------------------------------------------- + +/** + * options for instantiating a new log record + */ +export interface LogRecordOptions { + /** + * The numeric level of the logging event (such as 10 for DEBUG, 20 for + * INFO, etc). Note that this is converted to two attributes of the + * LogRecord: levelno for the numeric value and levelname for the + * corresponding level name. + */ + level: number, + file?: string, + /** + * The line number in the source file where the logging call was made. + */ + lno?: number, + /** + * The event description message, which can be a %-format string with + * placeholders for variable data, or an arbitrary object (see Using + * arbitrary objects as messages). + */ + msg: string, + /** + * Variable data to merge into the msg argument to obtain the event + * description. + */ + args?: any[], +} + +export type LogRecordFactory = { (name: string, options: LogRecordOptions): LogRecord }; + +/** + * LogRecord instances are created every time something is logged. They contain + * all the information pertinent to the event being logged. The main + * information parssed in is msg and args, which are combined using str(msg) % + * args to create the message field of the record. The record also includes + * information such as when the record was created, the source line where the + * logging call was made, and any exception information to be logged. + */ +export class LogRecord { + public readonly levelno: LogLevel; + public readonly levelname: string|LogLevel; + public readonly scope: string; + + public readonly created: MillisecondsSinceUnixEpoch = Date.now(); + + constructor(scope: string, options: LogRecordOptions) { + this.levelno = options.level; + this.levelname = getLevelName(options.level); + this.scope = scope; + } +} + +export var logRecordFactory = (scope: string, options: LogRecordOptions) => { + return new LogRecord(scope, options) +}; + +/** + * Define which class use when instantiating log records. + * + * @param factory - A callable which will be called to instantiate a log record. + * Pass a clojure, if your factory is a class already. + */ +export function setLogRecordFactory(factory: LogRecordFactory) { + logRecordFactory = factory +} + +export function getLogRecordFactory(): LogRecordFactory { + return logRecordFactory +} diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..8cdff06 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,324 @@ +import { + LogLevel, + DEBUG, + NOTSET, + WARNING, + checkLevel, +} from './log-level'; +import { + LogRecord, + logRecordFactory, + LogRecordOptions, +} from './log-record'; +import { Handler, StderrHandler } from './handler'; +import { + NotImplementedError, + KeyError, + ValueError, + StackTrace, +} from './helper/error'; +import { Manager } from './manager'; +import { Filterer } from './filter'; + +//--------------------------------------------------------------------------- +// Logger classes and functions +//--------------------------------------------------------------------------- + +export type ExecutionInfo = [string, Error, StackTrace]; + +export var throwErrors: boolean = true; + +export const DEFAULT_LAST_RESORT = new StderrHandler(WARNING); + +export var lastResort = DEFAULT_LAST_RESORT; + +export type LoggerClass = { new(): Logger }; + +/** + * context of a logging event/trigger + */ +export interface LogOptions{ + /** + * + */ + excInfo: ExecutionInfo|Error|null, + /** + * + */ + extra: {[key: string]: any}|null, + /** + * + */ + stackInfo: boolean, + /** + * + */ + stackLevel: number +} + +const DEFAULT_LOG_OPTIONS: LogOptions = Object.freeze({ + excInfo: null, + extra: null, + stackInfo: false, + stackLevel: 1 +}); + +/** + * Instances of the logger class represent a single logging channel. A 'logging + * channel' indicates an area of an application. Exactly how an 'area' is + * defined is up to the application developer. Since an application can have any + * number of areas, logging channels are identified by a unique string. + * Application areas can be nested (e.g. an area of input process might include + * sub-areas "read CSV file", "read XLS files" and "read Gnumeric files"). To + * cater for this natural nesting, channel ames are organized into a namespace + * hierarchy where levels are separated by periods, much like the Java or Python + * package namespace. So in the instance given above, channel names might be + * "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for + * the sub-levels. + * There is no arbitrary limit to the depth of nesting. + */ +export class Logger extends Filterer { + public readonly scope: string; + public _level: number; + private _manager: Manager|null = null; + public readonly parent: Logger|null = null; + public readonly propagate: boolean = true; + public readonly handlers: Handler[] = []; + public readonly disabled: boolean = false; + private cache: {[key: number]: boolean} = {}; + + /** + * Initialize the logger with a name and an optional level + * + * @param scope - + * @param level - + * @param manager - + */ + constructor( + scope: string, + level?: LogLevel, + ) { + super(); + + this.scope = scope; + this._level = checkLevel(level ?? NOTSET); + } + + public get level() { return this._level } + + public set level(level: LogLevel) { this._level = checkLevel(level) } + + public set manager(manager: Manager) { + if (this.manager) { + throw new ValueError('logger can only be assigned to manager once'); + } + } + + public setLevel(level: LogLevel) { + this.level = checkLevel(level); + + //this.manager.clearCache() + } + + /** + * Get the effective level for this logger. + * + * Loop through this logger and its parents in the logger hierarchy, looking + * for a non-zero logging level. Return the first one found. + */ + public getEffectiveLevel() { + var logger: Logger|null = this; + + while (logger) { + if (logger.level) { return logger.level } + logger = logger.parent; + } + + return NOTSET; + } + + /** + * Is this logger enabled for level 'level'? + */ + public isEnabledFor(level: LogLevel): boolean { + if (this.disabled) { return false } + + if (this.cache[level] === undefined && this.manager && this.manager.disable < level) { + return this.cache[level] = ( + level >= this.getEffectiveLevel() + ); + } + + return this.cache[level] = false; + } + + /** + * Log 'msg % args' with severity 'DEBUG' + * + * To pass exception information, use the keyword argument exc_info with + * a true value, e.g. + * + * ``` + * logger.debug("Houston, we have a thorny problem", { exc_info: true }) + * ``` + */ + public debug(msg: string, options?: LogOptions) { + if (this.isEnabledFor(DEBUG)) { this._log(DEBUG, msg, options) } + } + + /** + * A factory method which can be overriden in subclasses to create + * specialized LogRecords. + * + * + */ + protected makeRecord( + name: string, + level: LogLevel, + msg: string, + options: LogOptions, + ): LogRecord { + + var recordOptions: LogRecordOptions = { + level: level, + msg: msg, + }; + + var rv = logRecordFactory(name, recordOptions); + + if (options.extra !== null) { + Object.entries(options.extra!).forEach((item) => { + + var [k, v] = item; + + if (['message', 'asctime'].includes(k as string) || + (rv as {[key: string]: any}).keys().includes(k as string)) { + throw new KeyError('attempt to overwrite ${k} in LogRecord') + } + + (rv as any)[k] = options.extra![k as string] as any + }) + } + + return rv + } + + /** + * Low-level logging routine which creates a LogRecord and then calls the + * handlers of this logger to handle the record. + */ + protected _log(level: LogLevel, msg: string, options?: LogOptions) { + options = options ?? DEFAULT_LOG_OPTIONS; + options = { ...DEFAULT_LOG_OPTIONS, ...options }; + + var sinfo=null; + + if (options!.excInfo !== null) { + if (options!.excInfo instanceof Error) { + var excInfo: ExecutionInfo = [ + typeof options!.excInfo, + options!.excInfo, + options!.excInfo.stack! + ] + } + else if (!(options!.excInfo instanceof Array)) { + throw new NotImplementedError("would try to get the callee stack from the system. Probably will use stacktrace.js as this needs to be implemented browser-specific."); + } + } + + var record = this.makeRecord(this.scope, level, msg, options) + } + + /** + * Call the handlers for the specified record. + * + * This method is used for unpickled records received from a socket, as well + * as those created locally. Logger-level filtering is applied. + */ + protected handle(scope: string, record: LogRecord) { + if (this.disabled) { return } + var maybeRecord = this.filter(record); + if (!maybeRecord) { return } + if ((maybeRecord as any) instanceof LogRecord) { record = maybeRecord } + this.callHandlers(record) + } + + /** + * Pass a record to all relevant handlers. + * + * Loop through all handlers for this logger and its parents n the logger + * hierarchy. If no handler was found, output a one-off error message to + * sys.stderr. Stop searching up the hierarchy whenever a logger with the + * "propagate" attribute set to zero is found - that will be the last logger + * whose handlers are called. + */ + protected callHandlers(record: LogRecord) { + var c: Logger|null = this; + var found = 0; + + while (c) { + for (var i = 0; i < c.handlers.length; i += 1) { + let hdlr = c.handlers[i]; + + found = found + 1; + + if (record.levelno >= hdlr.level) { hdlr.handle(record) } + } + + if (!c.propagate) { c = null } + else { c = c.parent } + } + + if (found == 0) { + if (lastResort) { + if (record.levelno >= lastResort.level) { + lastResort.handle(record) + } + else if (throwErrors && (this.manager && !this.manager.emittedNoHandlerWarning)) { + console.error( + `No handlers could be found for logger ${this.scope}` + ); + + this.manager.emittedNoHandlerWarning = true; + } + } + } + } + + public clear() { + for (var property in this.cache) delete this.cache[property]; + } + + /** + * Remove the specified handler from this logger. + */ + public addHandler(hdlr: Handler) { + const i = this.handlers.indexOf(hdlr); + if (i === -1) { this.handlers.push(hdlr) } + } + + /** + * Remove the specified handler from this logger. + */ + public removeHandler(hdlr: Handler) { + const i = this.handlers.indexOf(hdlr); + if (i !== -1) { delete this.handlers[i] } + } +} + +/** + * A root logger is not that different to any other logger, except that it must + * have a logging level and there is only one instance of in a manager's + * hierarchy. + */ +export class RootLogger extends Logger { + + constructor(level: LogLevel) { + super('root', level); + } +} + +/** + * root logger (singleton) + */ +export const ROOT = new RootLogger(WARNING); diff --git a/src/manager.ts b/src/manager.ts new file mode 100644 index 0000000..c891849 --- /dev/null +++ b/src/manager.ts @@ -0,0 +1,127 @@ +import { + Logger, + LoggerClass, + RootLogger, + ROOT, +} from './logger'; +import { LogRecordFactory } from './log-record'; +import { + LogLevel, + NOTSET, + checkLevel, +} from './log-level' + + +//--------------------------------------------------------------------------- +// Manager classes and functions +//--------------------------------------------------------------------------- + +var loggerClass = Logger; + +/** + * Placeholder instance + */ +class Placeholder { + protected loggers: Logger[] = []; + + /** + * initialize with the specified logger being a child of this placeholder. + */ + constructor(logger: Logger) { this.push(logger) } + + /** + * add the specified logger as a child of this placeholder + */ + public push(logger: Logger) { + if (!this.loggers.includes(logger)) { this.loggers.push(logger) } + } +} + + +/** + * There is [under normal circumstances] just one Manager intance, which holds + * the hierarchy of loggers. + */ +export class Manager { + public readonly root: RootLogger; + protected _disable: number = 0; + public emittedNoHandlerWarning: boolean = false; + protected loggers: {[key: string]: Logger} = {}; + protected _loggerClass: LoggerClass|null = null; + protected _logRecordFactory: LogRecordFactory|null = null; + + public get disable(): number { return this._disable } + + public set disable(level: LogLevel) { this._disable = checkLevel(level) } + + /** + * Initialize the manager with the root node of the logger hierarchy + */ + constructor(root: RootLogger) { + this.root = root; + } + + /** + * Get a logger with the specified name (scope name), creating it, if it + * does not yet exist. This name is a dot-separated hierarchical name, such + * as "a", "a.b", "a.b.c" or similar. + * + * If a PlaceHolder existed for the specified name [i.e. the logger didn't + * exist but a child of it did], replace it with the created logger and fix + * up the parent/child references which pointed to the placeholder to now + * point to the logger. + */ + getLogger(scope: string) { + var rv: null|Logger = null; + + if (typeof scope != 'string') { + + rv = this.loggers[scope]; + + if (rv instanceof Placeholder) { + var ph = rv; + rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + } + else { + rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + this.loggers[scope] = rv; + } + } + } + + /** + * Set the class to be used when instantiating a logger with this Manager. + */ + set loggerClass(class_: LoggerClass) { + if (class_ !== Logger) { + if (!(class_.prototype instanceof Logger)) { + throw new TypeError("logger not derived from logging.Logger: ") + } + } + + this._loggerClass = class_; + } + + /** + * Set the factory to be used when instantiating a log record with this + * Manager. + */ + set logRecordFactory(factory: LogRecordFactory) { + this._logRecordFactory = factory; + } + + /** + * clear the cache for all loggers in loggerDict + */ + public clear() { + Object.values(this.loggers).forEach((logger) => { + logger.clear() + }); + } +} + + +/** + * log manager (singleton) + */ +export const MANAGER = new Manager(ROOT); diff --git a/tests/test.ts b/tests/test.ts index 208acdc..13ee6f7 100644 --- a/tests/test.ts +++ b/tests/test.ts @@ -2,7 +2,7 @@ import {expect, jest, test} from '@jest/globals'; describe('Logger', () => { it('can be instantiated', () => { - //const logger = new logging.Logger('test', 0); + //const logger = new logging.log_level.Logger('test', 0); }) }); @@ -17,56 +17,56 @@ describe('getLevelName', () => { it('numeric to textual representation of built-ins', () => { expect( - logging.getLevelName(logging.CRITICAL) + logging.log_level.getLevelName(logging.log_level.CRITICAL) ).toBe('CRITICAL'); expect( - logging.getLevelName(logging.FATAL) + logging.log_level.getLevelName(logging.log_level.FATAL) ).toBe('CRITICAL'); expect( - logging.getLevelName(logging.ERROR) + logging.log_level.getLevelName(logging.log_level.ERROR) ).toBe('ERROR'); expect( - logging.getLevelName(logging.WARNING) + logging.log_level.getLevelName(logging.log_level.WARNING) ).toBe('WARNING'); expect( - logging.getLevelName(logging.WARN) + logging.log_level.getLevelName(logging.log_level.WARN) ).toBe('WARNING'); expect( - logging.getLevelName(logging.INFO) + logging.log_level.getLevelName(logging.log_level.INFO) ).toBe('INFO'); expect( - logging.getLevelName(logging.DEBUG) + logging.log_level.getLevelName(logging.log_level.DEBUG) ).toBe('DEBUG'); expect( - logging.getLevelName(logging.NOTSET) + logging.log_level.getLevelName(logging.log_level.NOTSET) ).toBe('NOTSET'); }); it('textual to numeric representation of built-ins', () => { expect( - logging.getLevelName('CRITICAL') - ).toBe(logging.CRITICAL); + logging.log_level.getLevelName('CRITICAL') + ).toBe(logging.log_level.CRITICAL); expect( - logging.getLevelName('FATAL') + logging.log_level.getLevelName('FATAL') ).toBe(`Level FATAL`); expect( - logging.getLevelName('ERROR') - ).toBe(logging.ERROR); + logging.log_level.getLevelName('ERROR') + ).toBe(logging.log_level.ERROR); expect( - logging.getLevelName('WARNING') - ).toBe(logging.WARNING); + logging.log_level.getLevelName('WARNING') + ).toBe(logging.log_level.WARNING); expect( - logging.getLevelName('WARN') + logging.log_level.getLevelName('WARN') ).toBe('Level WARN'); expect( - logging.getLevelName('INFO') - ).toBe(logging.INFO); + logging.log_level.getLevelName('INFO') + ).toBe(logging.log_level.INFO); expect( - logging.getLevelName('DEBUG') - ).toBe(logging.DEBUG); + logging.log_level.getLevelName('DEBUG') + ).toBe(logging.log_level.DEBUG); expect( - logging.getLevelName('NOTSET') - ).toBe(logging.NOTSET); + logging.log_level.getLevelName('NOTSET') + ).toBe(logging.log_level.NOTSET); }); }); @@ -79,8 +79,8 @@ describe('addLevelName', () => { }); it('numeric to textual representation of built-ins', () => { - logging.addLevelName(80, 'FOOBAR'); - expect(logging.getLevelName(80)).toBe('FOOBAR'); - expect(logging.getLevelName('FOOBAR')).toBe(80); + logging.log_level.addLevelName(80, 'FOOBAR'); + expect(logging.log_level.getLevelName(80)).toBe('FOOBAR'); + expect(logging.log_level.getLevelName('FOOBAR')).toBe(80); }) }); From bcb65bfec54288d4573784dc1debbbacacf1ae7f Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 22:50:44 +0200 Subject: [PATCH 11/52] chore: fix package namespacing --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5d43e05..14d9fed 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "administratrix/esm-logging", + "name": "@administratrix/esm-logging", "version": "1.0.0", "description": "port of Python standard library logging module", "main": "lib/index.js", From b50586db8f0abdf5a158383559f80b7a8c945b75 Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 22:55:48 +0200 Subject: [PATCH 12/52] test(log_level): refactor --- tests/log-level.test.ts | 73 ++++++++++++++++++++++++++++++++++ tests/test.ts | 86 ----------------------------------------- 2 files changed, 73 insertions(+), 86 deletions(-) create mode 100644 tests/log-level.test.ts delete mode 100644 tests/test.ts diff --git a/tests/log-level.test.ts b/tests/log-level.test.ts new file mode 100644 index 0000000..2a7d386 --- /dev/null +++ b/tests/log-level.test.ts @@ -0,0 +1,73 @@ +import {expect, jest, test} from '@jest/globals'; +import * as log_level from '../src/log-level'; + +describe('Logger', () => { + it('can be instantiated', () => { + //const logger = new log_level.Logger('test', 0); + }) +}); + +describe('getLevelName', () => { + it('numeric to textual representation of built-ins', () => { + expect( + log_level.getLevelName(log_level.CRITICAL) + ).toBe('CRITICAL'); + expect( + log_level.getLevelName(log_level.FATAL) + ).toBe('CRITICAL'); + expect( + log_level.getLevelName(log_level.ERROR) + ).toBe('ERROR'); + expect( + log_level.getLevelName(log_level.WARNING) + ).toBe('WARNING'); + expect( + log_level.getLevelName(log_level.WARN) + ).toBe('WARNING'); + expect( + log_level.getLevelName(log_level.INFO) + ).toBe('INFO'); + expect( + log_level.getLevelName(log_level.DEBUG) + ).toBe('DEBUG'); + expect( + log_level.getLevelName(log_level.NOTSET) + ).toBe('NOTSET'); + }); + + it('textual to numeric representation of built-ins', () => { + expect( + log_level.getLevelName('CRITICAL') + ).toBe(log_level.CRITICAL); + expect( + log_level.getLevelName('FATAL') + ).toBe(`Level FATAL`); + expect( + log_level.getLevelName('ERROR') + ).toBe(log_level.ERROR); + expect( + log_level.getLevelName('WARNING') + ).toBe(log_level.WARNING); + expect( + log_level.getLevelName('WARN') + ).toBe('Level WARN'); + expect( + log_level.getLevelName('INFO') + ).toBe(log_level.INFO); + expect( + log_level.getLevelName('DEBUG') + ).toBe(log_level.DEBUG); + expect( + log_level.getLevelName('NOTSET') + ).toBe(log_level.NOTSET); + }); +}); + + +describe('addLevelName', () => { + it('numeric to textual representation of built-ins', () => { + log_level.addLevelName(80, 'FOOBAR'); + expect(log_level.getLevelName(80)).toBe('FOOBAR'); + expect(log_level.getLevelName('FOOBAR')).toBe(80); + }) +}); diff --git a/tests/test.ts b/tests/test.ts deleted file mode 100644 index 13ee6f7..0000000 --- a/tests/test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import {expect, jest, test} from '@jest/globals'; - -describe('Logger', () => { - it('can be instantiated', () => { - //const logger = new logging.log_level.Logger('test', 0); - }) -}); - -describe('getLevelName', () => { - var logging: any; - - beforeEach(() => { - // there are a couple of singletons, which I'm not yet sure if they need - // to be reloaded for every test case - logging = require('../src'); - }); - - it('numeric to textual representation of built-ins', () => { - expect( - logging.log_level.getLevelName(logging.log_level.CRITICAL) - ).toBe('CRITICAL'); - expect( - logging.log_level.getLevelName(logging.log_level.FATAL) - ).toBe('CRITICAL'); - expect( - logging.log_level.getLevelName(logging.log_level.ERROR) - ).toBe('ERROR'); - expect( - logging.log_level.getLevelName(logging.log_level.WARNING) - ).toBe('WARNING'); - expect( - logging.log_level.getLevelName(logging.log_level.WARN) - ).toBe('WARNING'); - expect( - logging.log_level.getLevelName(logging.log_level.INFO) - ).toBe('INFO'); - expect( - logging.log_level.getLevelName(logging.log_level.DEBUG) - ).toBe('DEBUG'); - expect( - logging.log_level.getLevelName(logging.log_level.NOTSET) - ).toBe('NOTSET'); - }); - - it('textual to numeric representation of built-ins', () => { - expect( - logging.log_level.getLevelName('CRITICAL') - ).toBe(logging.log_level.CRITICAL); - expect( - logging.log_level.getLevelName('FATAL') - ).toBe(`Level FATAL`); - expect( - logging.log_level.getLevelName('ERROR') - ).toBe(logging.log_level.ERROR); - expect( - logging.log_level.getLevelName('WARNING') - ).toBe(logging.log_level.WARNING); - expect( - logging.log_level.getLevelName('WARN') - ).toBe('Level WARN'); - expect( - logging.log_level.getLevelName('INFO') - ).toBe(logging.log_level.INFO); - expect( - logging.log_level.getLevelName('DEBUG') - ).toBe(logging.log_level.DEBUG); - expect( - logging.log_level.getLevelName('NOTSET') - ).toBe(logging.log_level.NOTSET); - }); -}); - - -describe('addLevelName', () => { - var logging: any; - - beforeEach(() => { - logging = require('../src'); - }); - - it('numeric to textual representation of built-ins', () => { - logging.log_level.addLevelName(80, 'FOOBAR'); - expect(logging.log_level.getLevelName(80)).toBe('FOOBAR'); - expect(logging.log_level.getLevelName('FOOBAR')).toBe(80); - }) -}); From e6beeec5940ee813741570ae2d3560c67b56ef7d Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Fri, 25 Apr 2025 22:59:27 +0200 Subject: [PATCH 13/52] chore: update typedoc --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 14d9fed..f63284f 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "jest-junit": "^16.0.0", "ts-jest": "^29.3.2", "ts-node": "^10.9.2", - "typedoc": "^0.27.9", + "typedoc": "^0.28.3", "typescript": "^5.8.3" }, "overrides": { From 31f2d6e6f93e15f775084e4cafd152e8252d6d1b Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 22:32:37 +0200 Subject: [PATCH 14/52] chore: move existing tests to sub-directory introducing sub-directories for each type of tests, so that they're easier to seperate. --- tests/{ => unit}/log-level.test.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{ => unit}/log-level.test.ts (100%) diff --git a/tests/log-level.test.ts b/tests/unit/log-level.test.ts similarity index 100% rename from tests/log-level.test.ts rename to tests/unit/log-level.test.ts From b7c69372193d8b113ff17aca6c734be423f03276 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:38:27 +0100 Subject: [PATCH 15/52] chore: add tiara-gitflow-spec as vendor submodule --- .gitmodules | 3 +++ vendor/tiara-gitflow-spec | 1 + 2 files changed, 4 insertions(+) create mode 100644 .gitmodules create mode 160000 vendor/tiara-gitflow-spec diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f8cc3a5 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/tiara-gitflow-spec"] + path = vendor/tiara-gitflow-spec + url = git@bitbucket.org:byteb4rb1e/tiara-gitflow-spec.git diff --git a/vendor/tiara-gitflow-spec b/vendor/tiara-gitflow-spec new file mode 160000 index 0000000..ee93479 --- /dev/null +++ b/vendor/tiara-gitflow-spec @@ -0,0 +1 @@ +Subproject commit ee93479edce1da28f4abf68a362427f8d3134f80 From 0cea450c0ab54fca8077f51b92df94d6d6962fba Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:38:36 +0100 Subject: [PATCH 16/52] chore: add eslint with typescript-eslint, align package.json scripts --- eslint.config.mjs | 7 + package-lock.json | 1252 ++++++++++++++++++++++++++++++++++++++++++++- package.json | 20 +- 3 files changed, 1261 insertions(+), 18 deletions(-) create mode 100644 eslint.config.mjs diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..e897ee3 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,7 @@ +import eslint from "@eslint/js"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + eslint.configs.recommended, + tseslint.configs.recommended, +); diff --git a/package-lock.json b/package-lock.json index 81eebd7..cfc546b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,13 +9,19 @@ "version": "1.0.0", "license": "UNLICENSED", "devDependencies": { + "@eslint/js": "^9.39.4", "@types/jest": "^29.5.14", + "eslint": "^9.39.4", "jest": "^29.7.0", "jest-junit": "^16.0.0", "ts-jest": "^29.3.2", "ts-node": "^10.9.2", "typedoc": "^0.28.3", - "typescript": "^5.8.3" + "typescript": "^5.8.3", + "typescript-eslint": "^8.57.0" + }, + "engines": { + "node": ">= 20.11.0" } }, "node_modules/@ampproject/remapping": { @@ -542,6 +548,214 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", + "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@gerrit0/mini-shiki": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/@gerrit0/mini-shiki/-/mini-shiki-3.3.0.tgz", @@ -556,6 +770,54 @@ "@shikijs/vscode-textmate": "^10.0.2" } }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -817,6 +1079,49 @@ } } }, + "node_modules/@jest/reporters/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/@jest/schemas": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", @@ -1124,6 +1429,12 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -1182,6 +1493,12 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, "node_modules/@types/node": { "version": "22.15.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.2.tgz", @@ -1223,12 +1540,290 @@ "dev": true, "license": "MIT" }, - "node_modules/acorn": { - "version": "8.14.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", - "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.57.0.tgz", + "integrity": "sha512-qeu4rTHR3/IaFORbD16gmjq9+rEs9fGKdX0kF6BKSfi+gCuG3RCKLlSBYzn/bGsY9Tj7KE/DAQStbp8AHJGHEQ==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.57.0", + "@typescript-eslint/type-utils": "8.57.0", + "@typescript-eslint/utils": "8.57.0", + "@typescript-eslint/visitor-keys": "8.57.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.57.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.57.0.tgz", + "integrity": "sha512-XZzOmihLIr8AD1b9hL9ccNMzEMWt/dE2u7NyTY9jJG6YNiNthaD5XtUHVF2uCXZ15ng+z2hT3MVuxnUYhq6k1g==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "8.57.0", + "@typescript-eslint/types": "8.57.0", + "@typescript-eslint/typescript-estree": "8.57.0", + "@typescript-eslint/visitor-keys": "8.57.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.57.0.tgz", + "integrity": "sha512-pR+dK0BlxCLxtWfaKQWtYr7MhKmzqZxuii+ZjuFlZlIGRZm22HnXFqa2eY+90MUz8/i80YJmzFGDUsi8dMOV5w==", + "dev": true, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.57.0", + "@typescript-eslint/types": "^8.57.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.57.0.tgz", + "integrity": "sha512-nvExQqAHF01lUM66MskSaZulpPL5pgy5hI5RfrxviLgzZVffB5yYzw27uK/ft8QnKXI2X0LBrHJFr1TaZtAibw==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.57.0", + "@typescript-eslint/visitor-keys": "8.57.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.57.0.tgz", + "integrity": "sha512-LtXRihc5ytjJIQEH+xqjB0+YgsV4/tW35XKX3GTZHpWtcC8SPkT/d4tqdf1cKtesryHm2bgp6l555NYcT2NLvA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.57.0.tgz", + "integrity": "sha512-yjgh7gmDcJ1+TcEg8x3uWQmn8ifvSupnPfjP21twPKrDP/pTHlEQgmKcitzF/rzPSmv7QjJ90vRpN4U+zoUjwQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.57.0", + "@typescript-eslint/typescript-estree": "8.57.0", + "@typescript-eslint/utils": "8.57.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.57.0.tgz", + "integrity": "sha512-dTLI8PEXhjUC7B9Kre+u0XznO696BhXcTlOn0/6kf1fHaQW8+VjJAVHJ3eTI14ZapTxdkOmc80HblPQLaEeJdg==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.57.0.tgz", + "integrity": "sha512-m7faHcyVg0BT3VdYTlX8GdJEM7COexXxS6KqGopxdtkQRvBanK377QDHr4W/vIPAR+ah9+B/RclSW5ldVniO1Q==", + "dev": true, + "dependencies": { + "@typescript-eslint/project-service": "8.57.0", + "@typescript-eslint/tsconfig-utils": "8.57.0", + "@typescript-eslint/types": "8.57.0", + "@typescript-eslint/visitor-keys": "8.57.0", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", + "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", + "dev": true, + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "dev": true, + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.57.0.tgz", + "integrity": "sha512-5iIHvpD3CZe06riAsbNxxreP+MuYgVUsV0n4bwLH//VJmgtt54sQeY2GszntJ4BjYCpMzrfVh2SBnUQTtys2lQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.57.0", + "@typescript-eslint/types": "8.57.0", + "@typescript-eslint/typescript-estree": "8.57.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.57.0.tgz", + "integrity": "sha512-zm6xx8UT/Xy2oSr2ZXD0pZo7Jx2XsCoID2IUh9YSTFRu7z+WdwYTRk6LhUftm1crwqbuoF6I8zAFeCMw0YjwDg==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.57.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, - "license": "MIT", "bin": { "acorn": "bin/acorn" }, @@ -1236,6 +1831,15 @@ "node": ">=0.4.0" } }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, "node_modules/acorn-walk": { "version": "8.3.4", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", @@ -1249,6 +1853,22 @@ "node": ">=0.4.0" } }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -1781,11 +2401,10 @@ } }, "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, - "license": "MIT", "dependencies": { "ms": "^2.1.3" }, @@ -1813,6 +2432,12 @@ } } }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -1946,6 +2571,190 @@ "node": ">=8" } }, + "node_modules/eslint": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", + "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/eslint/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", @@ -1960,6 +2769,48 @@ "node": ">=4" } }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -2017,6 +2868,12 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -2024,6 +2881,12 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, "node_modules/fb-watchman": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", @@ -2034,6 +2897,18 @@ "bser": "2.1.1" } }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/filelist": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", @@ -2084,6 +2959,25 @@ "node": ">=8" } }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.1.tgz", + "integrity": "sha512-IxfVbRFVlV8V/yRaGzk0UVIcsKKHMSfYw66T/u4nTwlWteQePsxe//LjudR1AMX4tZW3WFCh3Zqa/sjlqpbURQ==", + "dev": true + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -2101,6 +2995,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2193,6 +3093,18 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/globals": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", @@ -2250,6 +3162,40 @@ "node": ">=10.17.0" } }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/import-local": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", @@ -2280,6 +3226,23 @@ "node": ">=0.8.19" } }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", @@ -2303,6 +3266,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -2323,6 +3295,18 @@ "node": ">=6" } }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -3142,6 +4126,12 @@ "node": ">=6" } }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true + }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -3149,6 +4139,18 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -3162,6 +4164,15 @@ "node": ">=6" } }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "dependencies": { + "json-buffer": "3.0.1" + } + }, "node_modules/kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", @@ -3182,6 +4193,19 @@ "node": ">=6" } }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -3219,6 +4243,12 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -3435,6 +4465,15 @@ "node": ">=8" } }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -3451,6 +4490,23 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -3513,6 +4569,18 @@ "dev": true, "license": "BlueOak-1.0.0" }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -3542,6 +4610,15 @@ "node": ">=8" } }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -3629,6 +4706,15 @@ "node": ">=8" } }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/pretty-format": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", @@ -3671,6 +4757,15 @@ "node": ">= 6" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/punycode.js": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", @@ -4069,6 +5164,27 @@ "concat-map": "0.0.1" } }, + "node_modules/test-exclude/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/test-exclude/node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -4082,6 +5198,51 @@ "node": "*" } }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", @@ -4102,6 +5263,18 @@ "node": ">=8.0" } }, + "node_modules/ts-api-utils": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", + "integrity": "sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==", + "dev": true, + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/ts-jest": { "version": "29.3.2", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.3.2.tgz", @@ -4222,6 +5395,18 @@ } } }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -4299,6 +5484,29 @@ "node": ">=14.17" } }, + "node_modules/typescript-eslint": { + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.57.0.tgz", + "integrity": "sha512-W8GcigEMEeB07xEZol8oJ26rigm3+bfPHxHvwbYUlu1fUDsGuQ7Hiskx5xGW/xM4USc9Ephe3jtv7ZYPQntHeA==", + "dev": true, + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.57.0", + "@typescript-eslint/parser": "8.57.0", + "@typescript-eslint/typescript-estree": "8.57.0", + "@typescript-eslint/utils": "8.57.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, "node_modules/uc.micro": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", @@ -4344,6 +5552,15 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -4402,6 +5619,15 @@ "node": ">= 8" } }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", @@ -4503,6 +5729,12 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, "node_modules/write-file-atomic": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", diff --git a/package.json b/package.json index f63284f..7548b32 100644 --- a/package.json +++ b/package.json @@ -3,14 +3,15 @@ "version": "1.0.0", "description": "port of Python standard library logging module", "main": "lib/index.js", + "engines": { + "node": ">= 20.11.0" + }, "scripts": { - "test": "jest", - "build": "npm run build:release", - "build:release": "tsc", - "build:debug": "tsc -p tsconfig.debug.json", - "doc": "typedoc --entryPoints src/index.ts --html build/doc", - "publish_": "ts-node -P tsconfig.node.json scripts/publish.ts", - "dist": "ts-node -P tsconfig.node.json scripts/npm-pack.ts build/release dist" + "build/debug": "tsc -p tsconfig.debug.json", + "build/release": "tsc", + "build/doc": "typedoc", + "dist": "ts-node -P tsconfig.node.json scripts/npm-pack.ts build/release dist", + "test-reports/unit": "jest" }, "repository": { "type": "git", @@ -19,13 +20,16 @@ "author": "Tiara Rodney", "license": "UNLICENSED", "devDependencies": { + "@eslint/js": "^9.39.4", "@types/jest": "^29.5.14", + "eslint": "^9.39.4", "jest": "^29.7.0", "jest-junit": "^16.0.0", "ts-jest": "^29.3.2", "ts-node": "^10.9.2", "typedoc": "^0.28.3", - "typescript": "^5.8.3" + "typescript": "^5.8.3", + "typescript-eslint": "^8.57.0" }, "overrides": { "jest": { From 25ec89c3b44ec93befeceb953b19e8bcbf0cbd22 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:38:41 +0100 Subject: [PATCH 17/52] fix: correct jest roots and test import path --- jest.config.mjs | 2 +- tests/unit/log-level.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jest.config.mjs b/jest.config.mjs index 6590a36..b207977 100644 --- a/jest.config.mjs +++ b/jest.config.mjs @@ -19,5 +19,5 @@ export default { } ], ], - roots: ['./tests'] + roots: ['./tests/unit'] } diff --git a/tests/unit/log-level.test.ts b/tests/unit/log-level.test.ts index 2a7d386..6f1093f 100644 --- a/tests/unit/log-level.test.ts +++ b/tests/unit/log-level.test.ts @@ -1,5 +1,5 @@ import {expect, jest, test} from '@jest/globals'; -import * as log_level from '../src/log-level'; +import * as log_level from '../../src/log-level'; describe('Logger', () => { it('can be instantiated', () => { From 04e9768e89a7ff9c57fc94f8660832ab2fbd28b5 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:38:48 +0100 Subject: [PATCH 18/52] chore: convert TODO to MIME TODO format and add issues 5-9 --- TODO | 153 ++++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 100 insertions(+), 53 deletions(-) diff --git a/TODO b/TODO index ceb7fc8..345a13a 100644 --- a/TODO +++ b/TODO @@ -1,51 +1,5 @@ -# TODO List for esm-logging - -This is a poor-man's issue tracker. I am not primarily a GitHub user so don't -want to commit to their issue tracking feature, but my primary SVC service -provider (Bitbucket) only offers paid integration into their issue tracker -(Jira). I don't have the time (and patience) at the moment to analyze the best -approach, so this file will have to suffice. - -It's a very simple concept: Track any issues (features, bugfixes, hotfixes) in -here, assign a sequential number to it and use that number when branching. - -I will try to develop a format so that I can parse the file later on, should I -decide to migrate to a real issue tracker. It's probably going to be Bugzilla, -but for that my html-theme-ref project needs to stabilize first. - -## Format Specification - -The file uses Markdown conventions for formatting headers and other text block -entitities, but SHOULD NOT be considered a Markdown file. That's why it has no -definitive file extension. - -Each issue entry follows a structured format for easier parsing and future -migration. Issues MUST be **appended** to this file and never moved, to -preserve Git diffing. - -### Issue Format - -``` - -ID: [ISSUE-NUMBER] -Type: [feature/bugfix/hotfix] -Title: [Short title] -Status: [open/in-progress/done] -Priority: [low/medium/high] -Created: [YYYY-MM-DD] -Description: [Detailed explanation] - ---- -``` - -- ISSUE-NUMBERs must be sequential -- truncation of description must be indentended so that every line starts at the - same column -- issues must be started with two LF -- issues must be terminated with two LF, then `---` -- issues may have a free-text field (epilog), which must be started with two LF. - -## Issues +--ISSUE +Content-Type: application/issue ID: 1 Type: feature @@ -53,12 +7,14 @@ Title: string formatting utilities Status: in-progress Priority: high Created: 2025-05-01 +Relationships: Description: implement utilities for formatting strings. The formatting should be inspired by Python 3K PEP 3101 in addition to their standard library utilities starting from ver. 3.7. Optimizations should focus on V8 support. ---- +--ISSUE +Content-Type: application/issue ID: 2 Type: feature @@ -66,13 +22,15 @@ Title: describe development workflow in CONTRIBUTING.md Status: open Priority: medium Created: 2025-05-01 +Relationships: Description: It's a good idea to describe the development workflow, including branching strategies earlier on, so that if someone is interested in forking, they can pick up right away. It's not meant for contributions though. I'm currently not interested in external contributions. ---- +--ISSUE +Content-Type: application/issue ID: 3 Type: bugfix @@ -80,12 +38,14 @@ Title: modularize testing further Status: done Priority: high Created: 2025-05-01 +Relationships: Description: Since I am going to implement unit tests as well as integration tests and probably some benchmarks, it makes sense to introduce another sub-level directory for each type of test, say - `tests/unit/`, `tests/integration`, etc. + tests/unit/, tests/integration, etc. ---- +--ISSUE +Content-Type: application/issue ID: 4 Type: feature @@ -93,6 +53,7 @@ Title: migrate testing framework from Jest to Mocha Status: in-progress Priority: high Created: 2025-05-01 +Relationships: Description: I really don't like behavior-driven testing, at least when it comes to unit testing. It feels like Walldorf education... Where I need to come up with an abstraction for describing my test. A function @@ -101,4 +62,90 @@ Description: I really don't like behavior-driven testing, at least when it comes Hopefully Mocha is the savior. I'm sticking to xUnit based testing from now on. ---- +--ISSUE +Content-Type: application/issue + +ID: 5 +Type: bugfix +Title: fix critical bugs across core modules +Status: open +Priority: high +Created: 2026-03-13 +Relationships: +Description: multiple logic bugs prevent the library from functioning. + manager.ts getLogger() has an inverted type check and missing + return statement. config.ts basicConfig() assigns wrong option + fields (filemode instead of datefmt/style) and has unreachable + conditions. logger.ts isEnabledFor() always caches false, + _log() never calls handle(), and makeRecord() uses .keys() + instead of Object.keys(). handler.ts format() has no return + statement and is missing a formatter getter. + +--ISSUE +Content-Type: application/issue + +ID: 6 +Type: feature +Title: implement remaining Logger level methods +Status: open +Priority: high +Created: 2026-03-13 +Relationships: dependsOn:5 +Description: Logger only implements debug(). The info(), warning(), error(), + and critical() methods are missing entirely. The _log() method + also needs to be completed so it actually calls handle() after + creating the LogRecord. + +--ISSUE +Content-Type: application/issue + +ID: 7 +Type: feature +Title: implement Formatter subsystem +Status: open +Priority: high +Created: 2026-03-13 +Relationships: dependsOn:1 +Description: the three core Formatter methods are stubs returning placeholder + strings. PercentFormatterStyle._format() needs to perform actual + %-style field substitution against LogRecord attributes. + Formatter.formatTime() needs a JS Date/Intl-based implementation + replacing the Python time.strftime references. + Formatter.formatError() needs to format Error.stack into a + string. The datetime helper module is empty and needs time + formatting utilities. + +--ISSUE +Content-Type: application/issue + +ID: 8 +Type: feature +Title: implement browser-compatible Handler output +Status: open +Priority: high +Created: 2026-03-13 +Relationships: dependsOn:5 +Description: StreamHandler has no emit() implementation and its constructor + ignores the stream parameter. The helper/stream module is a + stub that needs a browser-compatible Writable interface backed + by console output. FileHandler should be dropped or gated behind + a Node.js environment check since browser environments have no + filesystem write access. A ConsoleHandler targeting the browser + console API (console.log/warn/error by level) is the primary + output target. + +--ISSUE +Content-Type: application/issue + +ID: 9 +Type: feature +Title: implement Manager logger hierarchy +Status: open +Priority: high +Created: 2026-03-13 +Relationships: dependsOn:5 +Description: Manager.getLogger() does not establish parent-child + relationships between loggers based on dot-separated names. + The Placeholder fixup logic is incomplete. Logger propagation + depends on this hierarchy being correctly built so that child + loggers forward records to parent handlers. From df0126693e7a6e51ee5e49133052aa3093925122 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:39:02 +0100 Subject: [PATCH 19/52] todo(5): in-progress Fix logic bugs across manager, config, logger, and handler modules. Manager.getLogger() has inverted type check and missing return. Config.basicConfig() assigns wrong option fields. Logger.isEnabledFor() always caches false, _log() never calls handle(). Handler.format() missing return and formatter getter. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 345a13a..8b14d4b 100644 --- a/TODO +++ b/TODO @@ -68,7 +68,7 @@ Content-Type: application/issue ID: 5 Type: bugfix Title: fix critical bugs across core modules -Status: open +Status: in-progress Priority: high Created: 2026-03-13 Relationships: From 03e3641e0359776d853cd6d83203e85f05978445 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:39:35 +0100 Subject: [PATCH 20/52] fix(manager): correct getLogger and implement hierarchy setup Fix inverted type check in getLogger() and add missing return statement. Implement _fixupParents() and _fixupChildren() to establish parent-child logger relationships based on dot-separated scope names. --- src/manager.ts | 73 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 63 insertions(+), 10 deletions(-) diff --git a/src/manager.ts b/src/manager.ts index c891849..32bc8c5 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -71,20 +71,73 @@ export class Manager { * up the parent/child references which pointed to the placeholder to now * point to the logger. */ - getLogger(scope: string) { - var rv: null|Logger = null; + getLogger(scope: string): Logger { + let rv: Logger; - if (typeof scope != 'string') { + if (scope in this.loggers) { + const existing = this.loggers[scope]; - rv = this.loggers[scope]; - - if (rv instanceof Placeholder) { - var ph = rv; - rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); - } - else { + if (existing instanceof Placeholder) { rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); this.loggers[scope] = rv; + this._fixupChildren(existing, rv); + } + else { + rv = existing; + } + } + else { + rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + this.loggers[scope] = rv; + this._fixupParents(rv); + } + + return rv; + } + + /** + * Ensure that there are either loggers or placeholders all the way from + * the specified logger to the root of the logger hierarchy. + */ + protected _fixupParents(logger: Logger) { + const name = logger.scope; + let i = name.lastIndexOf('.'); + let rv: Logger | null = null; + + while (i > 0 && !rv) { + const substr = name.substring(0, i); + + if (!(substr in this.loggers)) { + this.loggers[substr] = new Placeholder(logger) as unknown as Logger; + } + else { + const obj = this.loggers[substr]; + + if (obj instanceof Placeholder) { + obj.push(logger); + } + else { + rv = obj; + } + } + + i = name.lastIndexOf('.', i - 1); + } + + (logger as unknown as { parent: Logger }).parent = rv ?? this.root; + } + + /** + * Ensure that children of the placeholder ph are connected to the + * specified logger. + */ + protected _fixupChildren(ph: Placeholder, logger: Logger) { + const name = logger.scope; + + for (const c of ph.loggers) { + if (c.parent!.scope.substring(0, name.length) !== name) { + (logger as unknown as { parent: Logger }).parent = c.parent!; + (c as unknown as { parent: Logger }).parent = logger; } } } From 340b31bc50427df819e6a1248cff11f6ba06e148 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:40:05 +0100 Subject: [PATCH 21/52] fix(handler): add formatter getter, fix format() return, fix level setter Add missing getter for formatter property. Fix format() to return the formatted string instead of discarding it. Fix level setter to assign to _level instead of recursing infinitely. --- src/handler.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/handler.ts b/src/handler.ts index c75db06..24ff076 100644 --- a/src/handler.ts +++ b/src/handler.ts @@ -78,7 +78,7 @@ export class Handler extends Filterer { } get level(): number { return this._level } - set level(level: LogLevel|string) { this.level = checkLevel(level) } + set level(level: LogLevel|string) { this._level = checkLevel(level) } get scope(): string|null { return this._scope } set scope(scope: string) { this._scope = scope } @@ -90,11 +90,9 @@ export class Handler extends Filterer { * If a formatter is set, use it. Otherwise, use the default formatter for * the module. */ - format(record: LogRecord) { - var fmt: Formatter|null = null; - - if (this.formatter) { fmt = this.formatter } - else { fmt = DEFAULT_FORMATTER } + format(record: LogRecord): string { + const fmt = this.formatter ?? DEFAULT_FORMATTER; + return fmt.format(record); } /** @@ -159,6 +157,7 @@ export class Handler extends Filterer { ) } + get formatter(): Formatter|null { return this._formatter } set formatter(fmt: Formatter) { this._formatter = fmt } } From e76d8fb77bca448651c52f181889cf4493711d95 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:40:46 +0100 Subject: [PATCH 22/52] fix(logger): fix isEnabledFor, _log, makeRecord, and manager property Fix isEnabledFor() to correctly cache and return level check results instead of always caching false. Fix _log() to call handle() after creating the LogRecord. Fix makeRecord() to use Object.keys() and template literal. Add manager getter and fix setter to actually assign the value. --- src/logger.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/logger.ts b/src/logger.ts index 8cdff06..572f3a3 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -108,10 +108,13 @@ export class Logger extends Filterer { public set level(level: LogLevel) { this._level = checkLevel(level) } + public get manager(): Manager|null { return this._manager } + public set manager(manager: Manager) { - if (this.manager) { + if (this._manager) { throw new ValueError('logger can only be assigned to manager once'); } + this._manager = manager; } public setLevel(level: LogLevel) { @@ -143,13 +146,17 @@ export class Logger extends Filterer { public isEnabledFor(level: LogLevel): boolean { if (this.disabled) { return false } - if (this.cache[level] === undefined && this.manager && this.manager.disable < level) { - return this.cache[level] = ( - level >= this.getEffectiveLevel() - ); + if (level in this.cache) { + return this.cache[level]; } - return this.cache[level] = false; + if (this._manager && this._manager.disable >= level) { + this.cache[level] = false; + return false; + } + + this.cache[level] = level >= this.getEffectiveLevel(); + return this.cache[level]; } /** @@ -191,9 +198,9 @@ export class Logger extends Filterer { var [k, v] = item; - if (['message', 'asctime'].includes(k as string) || - (rv as {[key: string]: any}).keys().includes(k as string)) { - throw new KeyError('attempt to overwrite ${k} in LogRecord') + if (['message', 'asctime'].includes(k) || + Object.keys(rv).includes(k)) { + throw new KeyError(`attempt to overwrite ${k} in LogRecord`) } (rv as any)[k] = options.extra![k as string] as any @@ -226,7 +233,8 @@ export class Logger extends Filterer { } } - var record = this.makeRecord(this.scope, level, msg, options) + const record = this.makeRecord(this.scope, level, msg, options); + this.handle(this.scope, record); } /** From 9fed1ffe6b34b3bad0d12c048b8e656700a3b40b Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:41:29 +0100 Subject: [PATCH 23/52] fix(config): correct basicConfig option assignments and control flow Fix dateformat and style variables reading from wrong option fields (filemode instead of datefmt/style). Restructure control flow to match CPython logic: early return when handlers exist and force is not set, proper mutual exclusion of stream/filename/handlers args. Remove unreachable code block. --- src/config.ts | 98 +++++++++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 54 deletions(-) diff --git a/src/config.ts b/src/config.ts index 594d01d..d33cfa4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -121,8 +121,8 @@ export function basicConfig(options: BasicConfigOptions) { const filename = options.filename ?? null; const stream = options.stream ?? null; const filemode = options.filemode ?? 'a'; - const dateformat = options.filemode ?? null; - const style = options.filemode ?? '%'; + const dateformat = options.datefmt ?? null; + const style = options.style ?? '%'; const level = options.level ?? null; if (!Object.keys(STYLES).includes(style)) { @@ -139,64 +139,54 @@ export function basicConfig(options: BasicConfigOptions) { } } - if (handlers.length == 0) { - if (handlers === null && stream && filename) { + if (MANAGER.root.handlers.length > 0 && !force) { + return; + } + + if (handlers.length > 0) { + if (stream || filename) { + throw new ValueError( + "'stream' or 'filename' should not be specified together " + + "with 'handlers'" + ); + } + } + else { + if (stream && filename) { throw new ValueError( "'stream' and 'filename' should not be specified together" ); } - else if (stream || filename) { - throw new ValueError( - "'stream' or 'filename' should not be specified together" + - "with 'handlers'" - ); + if (filename) { + if (filemode.match('b')) { errors = undefined } + else { encoding = 'utf-8' } + + handlers = [new FileHandler({ + filename: filename, + filemode: filemode, + encoding: encoding, + errors: errors + })]; } - - if (handlers === null) { - var h: Handler; - - if (filename) { - if (filemode.match('b')) { errors = undefined } - else { encoding = 'utf-8' } - - h = new FileHandler({ - filename: filename, - filemode: filemode, - 'encoding': encoding, - errors: errors - }); - } - - else { h = new StreamHandler(stream) } - - handlers = [h]; - } - - for (var i = 0; i < handlers.length; i += 1) { - let h = handlers[i]; - - if (h.formatter === null) { - h.formatter = new Formatter({ - fmt: options.format ?? STYLES[style][1], - datefmt: dateformat, - style: style - }); - } - - MANAGER.root.addHandler(h); - } - - if (level !== null) { MANAGER.root.setLevel(level) } - - if (options) { - // runtime interface guard, please let me stay. 🥺 - // the interface does not allow for additional members, but the - // runtime environment has no concept of interfaces. We can stick to - // the original implementation - const keys = Object.keys(options).join(', '); - - throw new ValueError(`Unrecognised argument(s): ${keys}`); + else { + handlers = [new StreamHandler(stream)]; } } + + for (let i = 0; i < handlers.length; i += 1) { + const h = handlers[i]; + + if (h.formatter === null) { + h.formatter = new Formatter({ + fmt: options.format ?? STYLES[style][1], + datefmt: dateformat, + style: style + }); + } + + MANAGER.root.addHandler(h); + } + + if (level !== null) { MANAGER.root.setLevel(level) } } From 0b87f5516a4d6f0fc82c84ea3b3fa47ec6605a31 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:42:52 +0100 Subject: [PATCH 24/52] fix(formatter,manager): add Formatter.format(), fix Placeholder access Add format() method to Formatter class to delegate to the style's format method. Change Placeholder.loggers to public so Manager can access it for hierarchy fixup. --- src/formatter.ts | 14 ++++++++++++++ src/manager.ts | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/formatter.ts b/src/formatter.ts index 7e0197c..cf1d6e6 100644 --- a/src/formatter.ts +++ b/src/formatter.ts @@ -174,6 +174,20 @@ export class Formatter { * formatters, for example if you want all logging times to be shown in GMT, * set the 'converter' attribute in the Formatter class. */ + /** + * Format the specified record as text. + * + * The record's attribute dictionary is used as the operand to a string + * formatting operation which yields the returned string. Before the + * formatting operation, a couple of preparatory steps are carried out. + * The message attribute of the record is computed using LogRecord.getMessage(). + * If the formatting string uses the time, formatTime() is called to format + * the event time. + */ + format(record: LogRecord): string { + return this.style.format(record); + } + formatTime(record: LogRecord, datefmt?: any): string { //TODO: record.created diff --git a/src/manager.ts b/src/manager.ts index 32bc8c5..1d6828d 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -22,7 +22,7 @@ var loggerClass = Logger; * Placeholder instance */ class Placeholder { - protected loggers: Logger[] = []; + public loggers: Logger[] = []; /** * initialize with the specified logger being a child of this placeholder. From 3b6b116b00d6aa2384a700c7a3c21eff36d13896 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:49:12 +0100 Subject: [PATCH 25/52] test: add unit tests for handler, logger, manager, and config Cover Handler property accessors, format delegation, emit contract, and close lifecycle. Cover Logger level methods, isEnabledFor caching, manager property assignment, handler management, debug invocation, and makeRecord extra key collision. Cover Manager getLogger hierarchy setup, placeholder fixup, disable level, and loggerClass validation. Cover basicConfig option handling, force flag, mutual exclusion of stream/filename/handlers, and formatter assignment. --- tests/unit/config.test.ts | 93 +++++++++++++++++++ tests/unit/handler.test.ts | 92 +++++++++++++++++++ tests/unit/logger.test.ts | 181 +++++++++++++++++++++++++++++++++++++ tests/unit/manager.test.ts | 128 ++++++++++++++++++++++++++ 4 files changed, 494 insertions(+) create mode 100644 tests/unit/config.test.ts create mode 100644 tests/unit/handler.test.ts create mode 100644 tests/unit/logger.test.ts create mode 100644 tests/unit/manager.test.ts diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts new file mode 100644 index 0000000..e918ba5 --- /dev/null +++ b/tests/unit/config.test.ts @@ -0,0 +1,93 @@ +import {expect, jest, test} from '@jest/globals'; +import { basicConfig } from '../../src/config'; +import { MANAGER } from '../../src/manager'; +import { Handler } from '../../src/handler'; +import { LogRecord } from '../../src/log-record'; +import { Formatter } from '../../src/formatter'; +import { DEBUG, WARNING, ERROR } from '../../src/log-level'; +describe('basicConfig', () => { + beforeEach(() => { + MANAGER.root.handlers.splice(0, MANAGER.root.handlers.length); + }); + + test('adds a handler to the root logger', () => { + basicConfig({}); + expect(MANAGER.root.handlers.length).toBeGreaterThan(0); + }); + + test('sets root logger level', () => { + basicConfig({ level: DEBUG }); + expect(MANAGER.root.level).toBe(DEBUG); + }); + + test('does nothing when handlers already exist and force is false', () => { + basicConfig({ level: DEBUG }); + const handlerCount = MANAGER.root.handlers.length; + basicConfig({ level: ERROR }); + expect(MANAGER.root.handlers.length).toBe(handlerCount); + expect(MANAGER.root.level).toBe(DEBUG); + }); + + test('replaces handlers when force is true', () => { + basicConfig({ level: DEBUG }); + basicConfig({ level: ERROR, force: true }); + expect(MANAGER.root.level).toBe(ERROR); + }); + + test('throws on invalid style', () => { + expect(() => { + basicConfig({ style: 'X' }); + }).toThrow('style must be one of'); + }); + + test('throws when stream and filename both specified', () => { + expect(() => { + basicConfig({ + stream: process.stderr, + filename: 'test.log', + }); + }).toThrow('should not be specified together'); + }); + + test('throws when handlers and stream both specified', () => { + class TestHandler extends Handler { + emit(record: LogRecord) {} + } + expect(() => { + basicConfig({ + handlers: [new TestHandler()], + stream: process.stderr, + }); + }).toThrow('should not be specified together'); + }); + + test('uses provided handlers', () => { + class TestHandler extends Handler { + emit(record: LogRecord) {} + } + const handler = new TestHandler(); + basicConfig({ handlers: [handler] }); + expect(MANAGER.root.handlers).toContain(handler); + }); + + test('assigns formatter to handlers without one', () => { + class TestHandler extends Handler { + emit(record: LogRecord) {} + } + const handler = new TestHandler(); + expect(handler.formatter).toBeNull(); + basicConfig({ handlers: [handler] }); + expect(handler.formatter).not.toBeNull(); + }); + + test('preserves existing formatter on handlers', () => { + class TestHandler extends Handler { + emit(record: LogRecord) {} + } + const handler = new TestHandler(); + const fmt = new Formatter({ fmt: '%(message)s' }); + handler.formatter = fmt; + basicConfig({ handlers: [handler] }); + expect(handler.formatter).toBe(fmt); + }); +}); diff --git a/tests/unit/handler.test.ts b/tests/unit/handler.test.ts new file mode 100644 index 0000000..99a897a --- /dev/null +++ b/tests/unit/handler.test.ts @@ -0,0 +1,92 @@ +import {expect, jest, test} from '@jest/globals'; +import { Handler, StreamHandler, StderrHandler } from '../../src/handler'; +import { Formatter, DEFAULT_FORMATTER } from '../../src/formatter'; +import { LogRecord } from '../../src/log-record'; +import { DEBUG, WARNING, ERROR, NOTSET } from '../../src/log-level'; +function makeRecord(level: number, msg: string): LogRecord { + return new LogRecord('test', { level, msg }); +} + +describe('Handler', () => { + describe('constructor', () => { + test('defaults to NOTSET level', () => { + const h = new Handler(); + expect(h.level).toBe(NOTSET); + }); + + test('accepts a level argument', () => { + const h = new Handler(WARNING); + expect(h.level).toBe(WARNING); + }); + }); + + describe('level setter', () => { + test('sets the level without infinite recursion', () => { + const h = new Handler(); + h.level = ERROR; + expect(h.level).toBe(ERROR); + }); + }); + + describe('formatter', () => { + test('getter returns null when no formatter set', () => { + const h = new Handler(); + expect(h.formatter).toBeNull(); + }); + + test('getter returns assigned formatter', () => { + const h = new Handler(); + const fmt = new Formatter(); + h.formatter = fmt; + expect(h.formatter).toBe(fmt); + }); + }); + + describe('format', () => { + test('uses DEFAULT_FORMATTER when no formatter assigned', () => { + const h = new Handler(); + const record = makeRecord(DEBUG, 'hello'); + const result = h.format(record); + expect(typeof result).toBe('string'); + }); + + test('uses assigned formatter', () => { + const h = new Handler(); + const fmt = new Formatter({ fmt: '%(message)s' }); + h.formatter = fmt; + const record = makeRecord(DEBUG, 'hello'); + const result = h.format(record); + expect(typeof result).toBe('string'); + }); + + test('returns a string', () => { + const h = new Handler(); + const record = makeRecord(WARNING, 'test message'); + expect(typeof h.format(record)).toBe('string'); + }); + }); + + describe('emit', () => { + test('throws NotImplementedError on base class', () => { + const h = new Handler(); + const record = makeRecord(DEBUG, 'hello'); + expect(() => h.emit(record)).toThrow('emit must be implemented'); + }); + }); + + describe('close', () => { + test('sets closed to true', () => { + const h = new Handler(); + expect(h.closed).toBe(false); + h.close(); + expect(h.closed).toBe(true); + }); + }); +}); + +describe('StderrHandler', () => { + test('accepts a level', () => { + const h = new StderrHandler(ERROR); + expect(h.level).toBe(ERROR); + }); +}); diff --git a/tests/unit/logger.test.ts b/tests/unit/logger.test.ts new file mode 100644 index 0000000..c88e98a --- /dev/null +++ b/tests/unit/logger.test.ts @@ -0,0 +1,181 @@ +import {expect, jest, test} from '@jest/globals'; +import { Logger, RootLogger, ROOT } from '../../src/logger'; +import { Handler } from '../../src/handler'; +import { LogRecord } from '../../src/log-record'; +import { Formatter } from '../../src/formatter'; +import { Manager } from '../../src/manager'; +import { + DEBUG, + INFO, + WARNING, + ERROR, + CRITICAL, + NOTSET, +} from '../../src/log-level'; +import { MyError } from '../../src/helper/error'; + +describe('Logger', () => { + describe('constructor', () => { + test('sets scope and default level', () => { + const logger = new Logger('test'); + expect(logger.scope).toBe('test'); + expect(logger.level).toBe(NOTSET); + }); + + test('accepts explicit level', () => { + const logger = new Logger('test', WARNING); + expect(logger.level).toBe(WARNING); + }); + }); + + describe('setLevel', () => { + test('changes the level', () => { + const logger = new Logger('test'); + logger.setLevel(ERROR); + expect(logger.level).toBe(ERROR); + }); + }); + + describe('getEffectiveLevel', () => { + test('returns own level when set', () => { + const logger = new Logger('test', WARNING); + expect(logger.getEffectiveLevel()).toBe(WARNING); + }); + + test('returns NOTSET when no level set and no parent', () => { + const logger = new Logger('test'); + expect(logger.getEffectiveLevel()).toBe(NOTSET); + }); + }); + + describe('isEnabledFor', () => { + test('returns true when level meets effective level', () => { + const logger = new Logger('test', DEBUG); + expect(logger.isEnabledFor(WARNING)).toBe(true); + expect(logger.isEnabledFor(DEBUG)).toBe(true); + }); + + test('returns false when level is below effective level', () => { + const logger = new Logger('test', WARNING); + expect(logger.isEnabledFor(DEBUG)).toBe(false); + expect(logger.isEnabledFor(INFO)).toBe(false); + }); + + test('caches results for repeated calls', () => { + const logger = new Logger('test', WARNING); + const first = logger.isEnabledFor(DEBUG); + const second = logger.isEnabledFor(DEBUG); + expect(first).toBe(second); + }); + + test('respects manager disable level', () => { + const root = new RootLogger(WARNING); + const manager = new Manager(root); + const logger = manager.getLogger('test'); + logger.setLevel(DEBUG); + logger.manager = manager; + manager.disable = ERROR; + logger.clear(); + expect(logger.isEnabledFor(DEBUG)).toBe(false); + expect(logger.isEnabledFor(WARNING)).toBe(false); + expect(logger.isEnabledFor(CRITICAL)).toBe(true); + }); + }); + + describe('manager property', () => { + test('starts as null', () => { + const logger = new Logger('test'); + expect(logger.manager).toBeNull(); + }); + + test('can be assigned once', () => { + const logger = new Logger('test'); + const root = new RootLogger(WARNING); + const manager = new Manager(root); + logger.manager = manager; + expect(logger.manager).toBe(manager); + }); + + test('throws on second assignment', () => { + const logger = new Logger('test'); + const root = new RootLogger(WARNING); + const manager = new Manager(root); + logger.manager = manager; + expect(() => { logger.manager = manager }).toThrow('logger can only be assigned to manager once'); + }); + }); + + describe('addHandler / removeHandler', () => { + test('adds and removes handlers', () => { + const logger = new Logger('test'); + const handler = new Handler(DEBUG); + expect(logger.handlers.length).toBe(0); + logger.addHandler(handler); + expect(logger.handlers.length).toBe(1); + logger.removeHandler(handler); + }); + + test('does not add duplicate handlers', () => { + const logger = new Logger('test'); + const handler = new Handler(DEBUG); + logger.addHandler(handler); + logger.addHandler(handler); + expect(logger.handlers.length).toBe(1); + }); + }); + + describe('debug', () => { + test('invokes handler when level is DEBUG', () => { + const logger = new Logger('test', DEBUG); + const emitted: LogRecord[] = []; + + class TestHandler extends Handler { + emit(record: LogRecord) { emitted.push(record) } + } + + logger.addHandler(new TestHandler(DEBUG)); + logger.debug('test message'); + expect(emitted.length).toBe(1); + expect(emitted[0].scope).toBe('test'); + }); + + test('does not invoke handler when level is above DEBUG', () => { + const logger = new Logger('test', WARNING); + const emitted: LogRecord[] = []; + + class TestHandler extends Handler { + emit(record: LogRecord) { emitted.push(record) } + } + + logger.addHandler(new TestHandler(DEBUG)); + logger.debug('test message'); + expect(emitted.length).toBe(0); + }); + }); + + describe('makeRecord', () => { + test('throws KeyError when extra overwrites existing LogRecord key', () => { + const logger = new Logger('test', DEBUG); + expect(() => { + logger.debug('test', { + excInfo: null, + extra: { scope: 'override' }, + stackInfo: false, + stackLevel: 1, + }); + }).toThrow('attempt to overwrite scope in LogRecord'); + }); + }); +}); + +describe('RootLogger', () => { + test('has scope "root"', () => { + const root = new RootLogger(WARNING); + expect(root.scope).toBe('root'); + }); + + test('accepts a level', () => { + const root = new RootLogger(ERROR); + expect(root.level).toBe(ERROR); + }); +}); diff --git a/tests/unit/manager.test.ts b/tests/unit/manager.test.ts new file mode 100644 index 0000000..2df1fbb --- /dev/null +++ b/tests/unit/manager.test.ts @@ -0,0 +1,128 @@ +import {expect, jest, test} from '@jest/globals'; +import { Manager } from '../../src/manager'; +import { Logger, RootLogger } from '../../src/logger'; +import { WARNING, DEBUG, NOTSET } from '../../src/log-level'; + +function makeManager(): Manager { + return new Manager(new RootLogger(WARNING)); +} + +describe('Manager', () => { + describe('constructor', () => { + test('stores the root logger', () => { + const root = new RootLogger(WARNING); + const manager = new Manager(root); + expect(manager.root).toBe(root); + }); + }); + + describe('getLogger', () => { + test('returns a Logger instance', () => { + const manager = makeManager(); + const logger = manager.getLogger('app'); + expect(logger).toBeInstanceOf(Logger); + expect(logger.scope).toBe('app'); + }); + + test('returns the same logger for the same scope', () => { + const manager = makeManager(); + const a = manager.getLogger('app'); + const b = manager.getLogger('app'); + expect(a).toBe(b); + }); + + test('returns different loggers for different scopes', () => { + const manager = makeManager(); + const a = manager.getLogger('app'); + const b = manager.getLogger('lib'); + expect(a).not.toBe(b); + }); + + test('sets parent to root for top-level loggers', () => { + const manager = makeManager(); + const logger = manager.getLogger('app'); + expect(logger.parent).toBe(manager.root); + }); + + test('sets parent to existing parent logger', () => { + const manager = makeManager(); + const parent = manager.getLogger('app'); + const child = manager.getLogger('app.module'); + expect(child.parent).toBe(parent); + }); + + test('establishes hierarchy for deeply nested loggers', () => { + const manager = makeManager(); + const top = manager.getLogger('a'); + const mid = manager.getLogger('a.b'); + const leaf = manager.getLogger('a.b.c'); + expect(leaf.parent).toBe(mid); + expect(mid.parent).toBe(top); + expect(top.parent).toBe(manager.root); + }); + + test('creates placeholders for intermediate loggers', () => { + const manager = makeManager(); + const leaf = manager.getLogger('a.b.c'); + expect(leaf.parent).toBe(manager.root); + + const mid = manager.getLogger('a.b'); + expect(leaf.parent).toBe(mid); + expect(mid.parent).toBe(manager.root); + }); + + test('fixes up children when intermediate logger is created', () => { + const manager = makeManager(); + const leaf = manager.getLogger('a.b.c'); + const top = manager.getLogger('a'); + + expect(top.parent).toBe(manager.root); + + const mid = manager.getLogger('a.b'); + expect(leaf.parent).toBe(mid); + }); + }); + + describe('disable', () => { + test('defaults to 0', () => { + const manager = makeManager(); + expect(manager.disable).toBe(0); + }); + + test('can be set to a level', () => { + const manager = makeManager(); + manager.disable = WARNING; + expect(manager.disable).toBe(WARNING); + }); + }); + + describe('loggerClass', () => { + test('accepts Logger subclass', () => { + const manager = makeManager(); + class CustomLogger extends Logger {} + expect(() => { manager.loggerClass = CustomLogger as any }).not.toThrow(); + }); + + test('rejects non-Logger class', () => { + const manager = makeManager(); + class NotALogger {} + expect(() => { + manager.loggerClass = NotALogger as any; + }).toThrow(TypeError); + }); + + test('accepts Logger itself', () => { + const manager = makeManager(); + expect(() => { manager.loggerClass = Logger as any }).not.toThrow(); + }); + }); + + describe('clear', () => { + test('clears logger caches', () => { + const manager = makeManager(); + const logger = manager.getLogger('test'); + logger.isEnabledFor(DEBUG); + manager.clear(); + }); + }); +}); From 6e8257472363296f4d91258c4534fc61685b3564 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:50:37 +0100 Subject: [PATCH 26/52] todo(5): done Fixed logic bugs across manager, config, logger, handler, and formatter modules. Manager.getLogger() now correctly creates and returns loggers with hierarchy setup. Config.basicConfig() reads the correct option fields and has proper control flow. Logger isEnabledFor() caches correctly, _log() calls handle(), makeRecord() uses Object.keys(). Handler has working formatter getter, format() returns a string, and level setter no longer recurses. Formatter has a format() method. Added unit tests for all four modules. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 8b14d4b..c64e463 100644 --- a/TODO +++ b/TODO @@ -68,7 +68,7 @@ Content-Type: application/issue ID: 5 Type: bugfix Title: fix critical bugs across core modules -Status: in-progress +Status: done Priority: high Created: 2026-03-13 Relationships: From 7ef841ac4317bb2065428606a3623db09c56bca7 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:53:09 +0100 Subject: [PATCH 27/52] todo(6): in-progress Add info(), warning(), error(), and critical() methods to Logger. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index c64e463..67a8ca9 100644 --- a/TODO +++ b/TODO @@ -87,7 +87,7 @@ Content-Type: application/issue ID: 6 Type: feature Title: implement remaining Logger level methods -Status: open +Status: in-progress Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From 50df6b4c37594cdbdf13e1f56ee7e519d99fb33d Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:55:17 +0100 Subject: [PATCH 28/52] feat(logger): add info, warning, error, and critical methods --- src/logger.ts | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/logger.ts b/src/logger.ts index 572f3a3..f43d18d 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,8 +1,11 @@ import { LogLevel, DEBUG, - NOTSET, + INFO, WARNING, + ERROR, + CRITICAL, + NOTSET, checkLevel, } from './log-level'; import { @@ -173,6 +176,34 @@ export class Logger extends Filterer { if (this.isEnabledFor(DEBUG)) { this._log(DEBUG, msg, options) } } + /** + * Log 'msg % args' with severity 'INFO' + */ + public info(msg: string, options?: LogOptions) { + if (this.isEnabledFor(INFO)) { this._log(INFO, msg, options) } + } + + /** + * Log 'msg % args' with severity 'WARNING' + */ + public warning(msg: string, options?: LogOptions) { + if (this.isEnabledFor(WARNING)) { this._log(WARNING, msg, options) } + } + + /** + * Log 'msg % args' with severity 'ERROR' + */ + public error(msg: string, options?: LogOptions) { + if (this.isEnabledFor(ERROR)) { this._log(ERROR, msg, options) } + } + + /** + * Log 'msg % args' with severity 'CRITICAL' + */ + public critical(msg: string, options?: LogOptions) { + if (this.isEnabledFor(CRITICAL)) { this._log(CRITICAL, msg, options) } + } + /** * A factory method which can be overriden in subclasses to create * specialized LogRecords. From d95c8d37da4370f6b7062491a2d829272760383f Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:56:01 +0100 Subject: [PATCH 29/52] test(logger): add tests for info, warning, error, and critical methods --- tests/unit/logger.test.ts | 64 ++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/tests/unit/logger.test.ts b/tests/unit/logger.test.ts index c88e98a..db1eb75 100644 --- a/tests/unit/logger.test.ts +++ b/tests/unit/logger.test.ts @@ -124,32 +124,60 @@ describe('Logger', () => { }); }); - describe('debug', () => { - test('invokes handler when level is DEBUG', () => { - const logger = new Logger('test', DEBUG); - const emitted: LogRecord[] = []; + describe('level methods', () => { + let logger: Logger; + let emitted: LogRecord[]; - class TestHandler extends Handler { - emit(record: LogRecord) { emitted.push(record) } - } + class TestHandler extends Handler { + emit(record: LogRecord) { emitted.push(record) } + } + beforeEach(() => { + logger = new Logger('test', DEBUG); + emitted = []; logger.addHandler(new TestHandler(DEBUG)); - logger.debug('test message'); - expect(emitted.length).toBe(1); - expect(emitted[0].scope).toBe('test'); }); - test('does not invoke handler when level is above DEBUG', () => { - const logger = new Logger('test', WARNING); - const emitted: LogRecord[] = []; + test('debug emits at DEBUG level', () => { + logger.debug('msg'); + expect(emitted.length).toBe(1); + expect(emitted[0].levelno).toBe(DEBUG); + }); - class TestHandler extends Handler { - emit(record: LogRecord) { emitted.push(record) } - } + test('info emits at INFO level', () => { + logger.info('msg'); + expect(emitted.length).toBe(1); + expect(emitted[0].levelno).toBe(INFO); + }); - logger.addHandler(new TestHandler(DEBUG)); - logger.debug('test message'); + test('warning emits at WARNING level', () => { + logger.warning('msg'); + expect(emitted.length).toBe(1); + expect(emitted[0].levelno).toBe(WARNING); + }); + + test('error emits at ERROR level', () => { + logger.error('msg'); + expect(emitted.length).toBe(1); + expect(emitted[0].levelno).toBe(ERROR); + }); + + test('critical emits at CRITICAL level', () => { + logger.critical('msg'); + expect(emitted.length).toBe(1); + expect(emitted[0].levelno).toBe(CRITICAL); + }); + + test('level methods respect effective level', () => { + logger.setLevel(ERROR); + logger.clear(); + logger.debug('no'); + logger.info('no'); + logger.warning('no'); expect(emitted.length).toBe(0); + logger.error('yes'); + logger.critical('yes'); + expect(emitted.length).toBe(2); }); }); From fcfbd361535e8d63f643f2018642978894544e13 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:56:15 +0100 Subject: [PATCH 30/52] todo(6): done Added info(), warning(), error(), and critical() methods to Logger, each gated by isEnabledFor(). All level methods tested including effective level filtering. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 67a8ca9..3cb8d82 100644 --- a/TODO +++ b/TODO @@ -87,7 +87,7 @@ Content-Type: application/issue ID: 6 Type: feature Title: implement remaining Logger level methods -Status: in-progress +Status: done Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From 3f424137aca70f01cb60f9b845328459cd4d78b3 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:02:46 +0100 Subject: [PATCH 31/52] chore: add roadmap issues 10-13 Add issues for documentation, async support, OCSF formatter, and browser local storage handler from the README roadmap. --- TODO | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/TODO b/TODO index 3cb8d82..145ef93 100644 --- a/TODO +++ b/TODO @@ -149,3 +149,66 @@ Description: Manager.getLogger() does not establish parent-child The Placeholder fixup logic is incomplete. Logger propagation depends on this hierarchy being correctly built so that child loggers forward records to parent handlers. + +--ISSUE +Content-Type: application/issue + +ID: 10 +Type: feature +Title: add documentation +Status: open +Priority: medium +Created: 2026-03-13 +Relationships: +Description: write user-facing documentation covering module usage, API + reference, and configuration. The docs/ directory has stubs + (README.md, logging-cookbook.md) that need to be fleshed out. + TypeDoc generates API docs from source but a prose guide with + examples is needed for onboarding. + +--ISSUE +Content-Type: application/issue + +ID: 11 +Type: feature +Title: add support for asynchronous calls +Status: open +Priority: low +Created: 2026-03-13 +Relationships: +Description: introduce async-aware logging so that handlers which perform + I/O (e.g. network, storage) do not block the caller. This may + involve an AsyncHandler base class or async emit() overloads, + and consideration of how log record ordering is preserved + across concurrent async contexts. + +--ISSUE +Content-Type: application/issue + +ID: 12 +Type: feature +Title: implement OCSF formatter +Status: open +Priority: low +Created: 2026-03-13 +Relationships: +Description: implement a Formatter subclass that outputs log records in + Open Cybersecurity Schema Framework (OCSF) format. This + enables structured security event logging compatible with + SIEM systems and security analytics tooling. + +--ISSUE +Content-Type: application/issue + +ID: 13 +Type: feature +Title: implement browser local storage handler +Status: open +Priority: medium +Created: 2026-03-13 +Relationships: dependsOn:8 +Description: implement a Handler subclass that persists log records to + browser localStorage or IndexedDB as a replacement for + FileHandler in browser environments. Should support log + rotation by size or entry count to avoid exceeding storage + quotas. From 3dce9422aec7f77f4112ac2ed9761d460cc71dab Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:05:33 +0100 Subject: [PATCH 32/52] todo(7): in-progress Implement PercentFormatterStyle._format() with %-style field substitution, Formatter.formatTime() using JS Date/Intl, and Formatter.formatError() using Error.stack. Add datetime helpers. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 145ef93..c8e1e43 100644 --- a/TODO +++ b/TODO @@ -102,7 +102,7 @@ Content-Type: application/issue ID: 7 Type: feature Title: implement Formatter subsystem -Status: open +Status: in-progress Priority: high Created: 2026-03-13 Relationships: dependsOn:1 From c0ced4cda20fabae3f0b586aab630df8eebbb5e7 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:09:50 +0100 Subject: [PATCH 33/52] feat(log-record): add message, name, msg, args fields and getMessage --- src/log-record.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/log-record.ts b/src/log-record.ts index 6c6f335..cafca77 100644 --- a/src/log-record.ts +++ b/src/log-record.ts @@ -48,13 +48,32 @@ export class LogRecord { public readonly levelno: LogLevel; public readonly levelname: string|LogLevel; public readonly scope: string; + public readonly name: string; + public readonly msg: string; + public readonly args: any[]|undefined; + public message: string = ''; public readonly created: MillisecondsSinceUnixEpoch = Date.now(); + public asctime: string = ''; constructor(scope: string, options: LogRecordOptions) { this.levelno = options.level; this.levelname = getLevelName(options.level); this.scope = scope; + this.name = scope; + this.msg = options.msg; + this.args = options.args; + } + + getMessage(): string { + let msg = String(this.msg); + if (this.args && this.args.length > 0) { + msg = this.args.reduce( + (s, arg) => s.replace('%s', String(arg)), + msg + ); + } + return msg; } } From 7b9e88ef59b1350b6bd9aad651e0498ad0f6f26d Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:14:49 +0100 Subject: [PATCH 34/52] feat(formatter): implement %-style formatting, formatTime, formatError PercentFormatterStyle._format() now performs %(key)s/d/f substitution against LogRecord attributes. Formatter.format() sets record.message via getMessage() and conditionally calls formatTime() for asctime. formatTime() uses JS Date with strftime-style tokens (%Y,%m,%d,%H, %M,%S) or ISO8601 fallback. formatError() returns Error.stack. BASIC_FORMAT updated to use %(levelname)s. Fixed datefmt type in config.ts. --- src/config.ts | 2 +- src/formatter.ts | 151 ++++++++++++++++++++++++----------------------- 2 files changed, 77 insertions(+), 76 deletions(-) diff --git a/src/config.ts b/src/config.ts index d33cfa4..57ba2d1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -121,7 +121,7 @@ export function basicConfig(options: BasicConfigOptions) { const filename = options.filename ?? null; const stream = options.stream ?? null; const filemode = options.filemode ?? 'a'; - const dateformat = options.datefmt ?? null; + const dateformat = options.datefmt; const style = options.style ?? '%'; const level = options.level ?? null; diff --git a/src/formatter.ts b/src/formatter.ts index cf1d6e6..542d3ac 100644 --- a/src/formatter.ts +++ b/src/formatter.ts @@ -10,14 +10,20 @@ export interface PercentFormatterStyleOptions { defaults: {[key: string]: any}; } +/** + * %-style formatting for log records. + * + * Substitutes %(name)s, %(name)d, %(name)f placeholders from record + * attributes. + */ class PercentFormatterStyle { public static defaultFormat = '%(message)s'; public static asctimeFormat = '%(asctime)s'; public static asctimeSearch = '%(asctime)'; - public static validationPattern = + public static validationPattern = /%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]/; - private fmt: string; + public fmt: string; private defaults: {[key: string]: any}; constructor(options: PercentFormatterStyleOptions) { @@ -26,7 +32,7 @@ class PercentFormatterStyle { } usesTime(): boolean { - return this.fmt.match(PercentFormatterStyle.asctimeFormat) ? true : false + return this.fmt.indexOf(PercentFormatterStyle.asctimeSearch) >= 0; } /** @@ -42,12 +48,32 @@ class PercentFormatterStyle { } protected _format(record: LogRecord): string { - var defaults = this.defaults; - var values: {[key: string]: any}|null; - if (defaults) { values = {...this.defaults, ...Object.entries(record)} } - else { values = Object.entries(record) } - //TODO: implement formatting - return 'would do some formatting'; + const values: {[key: string]: any} = { + ...this.defaults, + ...(record as unknown as {[key: string]: any}), + }; + + return this.fmt.replace( + /%\((\w+)\)([#0+ -]*(?:\*|\d+)?(?:\.(?:\*|\d+))?[diouxefgcrsa%])/g, + (_match, key, spec) => { + if (!(key in values)) { + throw new ValueError(`formatting field not found in record: ${key}`); + } + const val = values[key]; + const conversion = spec[spec.length - 1]; + switch (conversion) { + case 'd': + case 'i': + return String(Math.floor(Number(val))); + case 'f': + return String(Number(val)); + case 's': + return String(val); + default: + return String(val); + } + } + ); } format(record: LogRecord): string { @@ -55,12 +81,13 @@ class PercentFormatterStyle { return this._format(record) } catch (e) { + if (e instanceof ValueError) { throw e } throw new ValueError(`formatting field not found in record: ${e}`) } } } -const BASIC_FORMAT = '%(level)s:%(name)s:%(message)s'; +const BASIC_FORMAT = '%(levelname)s:%(name)s:%(message)s'; export const STYLES: {[key: string]: [{ new(options: PercentFormatterStyleOptions): PercentFormatterStyle}, string]} = { '%': [PercentFormatterStyle, BASIC_FORMAT], @@ -68,7 +95,7 @@ export const STYLES: {[key: string]: [{ new(options: PercentFormatterStyleOption export interface FormatterOptions { fmt?: string - datefmt?: any + datefmt?: string style?: string validate?: boolean defaults?: {[key: string]: any} @@ -95,53 +122,26 @@ export interface FormatterOptions { * WARNING, ERROR, CRITICAL) * %(levelname)s Text logging level for the message ("DEBUG", "INFO", * "WARNING", "ERROR", "CRITICAL") - * %(pathname)s Full pathname of the source file where the logging - * call was issued (if available) - * %(filename)s Filename portion of pathname - * %(module)s Module (name portion of filename) - * %(lineno)d Source line number where the logging call was issued - * (if available) - * %(funcName)s Function name - * %(created)f Time when the LogRecord was created (time.time_ns() / 1e9 + * %(created)f Time when the LogRecord was created (Date.now() * return value) * %(asctime)s Textual time when the LogRecord was created - * %(msecs)d Millisecond portion of the creation time - * %(relativeCreated)d Time in milliseconds when the LogRecord was created, - * relative to the time the logging module was loaded - * (typically at application startup time) - * %(thread)d Thread ID (if available) - * %(threadName)s Thread name (if available) - * %(taskName)s Task name (if available) - * %(process)d Process ID (if available) * %(message)s The result of record.getMessage(), computed just as * the record is emitted */ export class Formatter { - public static defaultTimeFormat = '%Y-%M'; - public static defaultMsecFormat = '%s,%30d'; + public static defaultTimeFormat = 'YYYY-MM-DDTHH:mm:ss'; + public static defaultMsecFormat = '%s.%03d'; - protected style: any; + protected style: PercentFormatterStyle; protected fmt: string; - protected datefmt: any; + protected datefmt: string|undefined; - /** - * Initialize the formatter with specified format strings. - * - * Initialize the formatter either with the specified format string, or a - * default as described above. Allow for specialized date formatting with - * the optional datefmt argument. If datefmt is omitted, you get an - * ISO8601-like (or RFC 3339-like) format. - * - * Use a style parameter of '%', '{' or '$' to specify that you want to - * use one of %-formatting, :meth:`str.format` (``{}``) formatting or - * :class:`string.Template` formatting in your format string. - */ constructor(options?: FormatterOptions) { options = options ?? {}; - var style = options.style ?? '%'; - var validate = options.validate ?? true; + const style = options.style ?? '%'; + const validate = options.validate ?? true; - if (!Object.keys(STYLES).includes(style ?? '')) { + if (!Object.keys(STYLES).includes(style)) { throw new ValueError(`style must be one of: ${Object.keys(STYLES).join(', ')}`) } @@ -157,23 +157,10 @@ export class Formatter { this.datefmt = options.datefmt; } - /** - * Return the creation time of the specified LogRecord as formatted text. - * - * This method should be called from format() by a formatter which - * wants to make use of a formatted time. This method can be overridden - * in formatters to provide for any specific requirement, but the - * basic behaviour is as follows: if datefmt (a string) is specified, - * it is used with time.strftime() to format the creation time of the - * record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. - * The resulting string is returned. This function uses a user-configurable - * function to convert the creation time to a tuple. By default, - * time.localtime() is used; to change this for a particular formatter - * instance, set the 'converter' attribute to a function with the same - * signature as time.localtime() or time.gmtime(). To change it for all - * formatters, for example if you want all logging times to be shown in GMT, - * set the 'converter' attribute in the Formatter class. - */ + usesTime(): boolean { + return this.style.usesTime(); + } + /** * Format the specified record as text. * @@ -185,31 +172,45 @@ export class Formatter { * the event time. */ format(record: LogRecord): string { + record.message = record.getMessage(); + + if (this.usesTime()) { + record.asctime = this.formatTime(record, this.datefmt); + } + return this.style.format(record); } - formatTime(record: LogRecord, datefmt?: any): string { + /** + * Return the creation time of the specified LogRecord as formatted text. + * + * If datefmt is specified, it is used as a strftime-style format string. + * Supported tokens: %Y, %m, %d, %H, %M, %S. + * Otherwise, an ISO8601-like format is used. + */ + formatTime(record: LogRecord, datefmt?: string): string { + const dt = new Date(record.created); - //TODO: record.created if (datefmt) { - //TODO: time.strftime - } - else { - //TODO: time.strftime + return datefmt + .replace('%Y', String(dt.getFullYear())) + .replace('%m', String(dt.getMonth() + 1).padStart(2, '0')) + .replace('%d', String(dt.getDate()).padStart(2, '0')) + .replace('%H', String(dt.getHours()).padStart(2, '0')) + .replace('%M', String(dt.getMinutes()).padStart(2, '0')) + .replace('%S', String(dt.getSeconds()).padStart(2, '0')); } - return 'some time'; + const iso = dt.toISOString(); + return iso.replace('T', ' ').replace('Z', ''); } /** * Format and return the specified exception information as a string. - - * This default implementation just uses - * traceback.print_exception() */ formatError(ei: MyError): string { - //TODO - return 'some error'; + if (ei.stack) { return ei.stack } + return String(ei); } } From 3422cfb7998b6df04b64f4ba82a658212c76c440 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:22:10 +0100 Subject: [PATCH 35/52] test(formatter): add tests for formatting, formatTime, formatError Cover %-style substitution with %(name)s, %(levelno)d, %(levelname)s, multiple placeholders, unknown field errors, asctime population, ISO8601 and custom datefmt time formatting, Error.stack formatting, usesTime detection, and LogRecord.getMessage with %s arg substitution. --- tests/unit/formatter.test.ts | 143 +++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 tests/unit/formatter.test.ts diff --git a/tests/unit/formatter.test.ts b/tests/unit/formatter.test.ts new file mode 100644 index 0000000..c105629 --- /dev/null +++ b/tests/unit/formatter.test.ts @@ -0,0 +1,143 @@ +import {expect, jest, test} from '@jest/globals'; +import { Formatter, DEFAULT_FORMATTER } from '../../src/formatter'; +import { LogRecord } from '../../src/log-record'; +import { DEBUG, WARNING, INFO } from '../../src/log-level'; +import { MyError } from '../../src/helper/error'; + +function makeRecord(level: number, msg: string): LogRecord { + return new LogRecord('test.module', { level, msg }); +} + +describe('Formatter', () => { + describe('constructor', () => { + test('uses default format when no options given', () => { + const fmt = new Formatter(); + const record = makeRecord(WARNING, 'hello'); + const result = fmt.format(record); + expect(result).toBe('hello'); + }); + + test('accepts custom format string', () => { + const fmt = new Formatter({ fmt: '%(levelname)s - %(message)s' }); + const record = makeRecord(DEBUG, 'debug msg'); + expect(fmt.format(record)).toBe('DEBUG - debug msg'); + }); + + test('throws on invalid style', () => { + expect(() => new Formatter({ style: '{' })).toThrow('style must be one of'); + }); + }); + + describe('format', () => { + test('substitutes %(name)s with logger scope', () => { + const fmt = new Formatter({ fmt: '[%(name)s] %(message)s' }); + const record = makeRecord(INFO, 'test'); + expect(fmt.format(record)).toBe('[test.module] test'); + }); + + test('substitutes %(levelno)d with numeric level', () => { + const fmt = new Formatter({ fmt: '%(levelno)d: %(message)s' }); + const record = makeRecord(WARNING, 'warn'); + expect(fmt.format(record)).toBe('30: warn'); + }); + + test('substitutes %(levelname)s with level name', () => { + const fmt = new Formatter({ fmt: '%(levelname)s %(message)s' }); + const record = makeRecord(DEBUG, 'msg'); + expect(fmt.format(record)).toBe('DEBUG msg'); + }); + + test('handles multiple placeholders', () => { + const fmt = new Formatter({ + fmt: '%(levelname)s:%(name)s:%(levelno)d:%(message)s' + }); + const record = makeRecord(WARNING, 'multi'); + expect(fmt.format(record)).toBe('WARNING:test.module:30:multi'); + }); + + test('throws on unknown field', () => { + const fmt = new Formatter({ fmt: '%(nonexistent)s' }); + const record = makeRecord(DEBUG, 'test'); + expect(() => fmt.format(record)).toThrow('formatting field not found'); + }); + + test('populates asctime when format uses it', () => { + const fmt = new Formatter({ + fmt: '%(asctime)s %(message)s' + }); + const record = makeRecord(INFO, 'timed'); + const result = fmt.format(record); + expect(result).toContain('timed'); + expect(record.asctime.length).toBeGreaterThan(0); + }); + + test('does not populate asctime when format does not use it', () => { + const fmt = new Formatter({ fmt: '%(message)s' }); + const record = makeRecord(INFO, 'no time'); + fmt.format(record); + expect(record.asctime).toBe(''); + }); + }); + + describe('formatTime', () => { + test('returns ISO8601-like string by default', () => { + const fmt = new Formatter(); + const record = makeRecord(INFO, 'test'); + const result = fmt.formatTime(record); + expect(result).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/); + }); + + test('uses custom datefmt with strftime tokens', () => { + const fmt = new Formatter(); + const record = makeRecord(INFO, 'test'); + const result = fmt.formatTime(record, '%Y/%m/%d'); + expect(result).toMatch(/^\d{4}\/\d{2}\/\d{2}$/); + }); + }); + + describe('formatError', () => { + test('returns stack trace when available', () => { + const fmt = new Formatter(); + const err = new MyError('test error'); + const result = fmt.formatError(err); + expect(result).toContain('test error'); + expect(result).toContain('\n'); + }); + + test('returns string representation when no stack', () => { + const fmt = new Formatter(); + const err = new MyError('no stack'); + err.stack = undefined; + const result = fmt.formatError(err); + expect(result).toContain('no stack'); + }); + }); + + describe('usesTime', () => { + test('returns true when format contains asctime', () => { + const fmt = new Formatter({ fmt: '%(asctime)s %(message)s' }); + expect(fmt.usesTime()).toBe(true); + }); + + test('returns false when format does not contain asctime', () => { + const fmt = new Formatter({ fmt: '%(message)s' }); + expect(fmt.usesTime()).toBe(false); + }); + }); +}); + +describe('LogRecord.getMessage', () => { + test('returns the message string', () => { + const record = makeRecord(INFO, 'plain message'); + expect(record.getMessage()).toBe('plain message'); + }); + + test('substitutes %s args into message', () => { + const record = new LogRecord('test', { + level: INFO, + msg: 'hello %s, you have %s items', + args: ['world', '5'], + }); + expect(record.getMessage()).toBe('hello world, you have 5 items'); + }); +}); From 67803747c4480a44d997c268545a7e81996b5d5e Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:26:39 +0100 Subject: [PATCH 36/52] todo(7): done Implemented %-style field substitution in PercentFormatterStyle, JS Date-based formatTime with strftime token support and ISO8601 fallback, Error.stack-based formatError, and LogRecord.getMessage. Added message, name, msg, args fields to LogRecord. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index c8e1e43..490168d 100644 --- a/TODO +++ b/TODO @@ -102,7 +102,7 @@ Content-Type: application/issue ID: 7 Type: feature Title: implement Formatter subsystem -Status: in-progress +Status: done Priority: high Created: 2026-03-13 Relationships: dependsOn:1 From c297bb449940209829cb38d5acff979cf51e96fd Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:27:50 +0100 Subject: [PATCH 37/52] todo(8): in-progress Implement StreamHandler.emit(), ConsoleHandler for browser console API, and a browser-compatible stream abstraction. Design handler base with issue 13 (localStorage handler) in mind. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 490168d..4d06273 100644 --- a/TODO +++ b/TODO @@ -121,7 +121,7 @@ Content-Type: application/issue ID: 8 Type: feature Title: implement browser-compatible Handler output -Status: open +Status: in-progress Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From e6b7f021661a1c81949f9f4dd915d30191816916 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:29:09 +0100 Subject: [PATCH 38/52] feat(helper/stream): add browser-compatible Writable interface Define Writable interface, ConsoleWritable (console.log), and StderrWritable (console.error) as browser-safe stream abstractions. Export DEFAULT_STREAM backed by StderrWritable to match Python's sys.stderr default. --- src/helper/stream.ts | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/helper/stream.ts b/src/helper/stream.ts index 297e20c..4102cf4 100644 --- a/src/helper/stream.ts +++ b/src/helper/stream.ts @@ -1,2 +1,33 @@ +/** + * Minimal writable stream interface for browser compatibility. + * + * This abstracts over Node.js streams and browser console output, + * providing a common write target for handlers. + */ +export interface Writable { + write(data: string): void; +} -export type MillisecondsSinceUnixEpoch = number; +/** + * A Writable backed by console.log. + */ +export class ConsoleWritable implements Writable { + write(data: string): void { + console.log(data); + } +} + +/** + * A Writable backed by console.error (stderr equivalent). + */ +export class StderrWritable implements Writable { + write(data: string): void { + console.error(data); + } +} + +/** + * Default output stream. Uses console.error to match Python's default + * of writing to sys.stderr. + */ +export const DEFAULT_STREAM: Writable = new StderrWritable(); From 3a6332a8553d2e9da34559363fd82761db78697b Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 23:57:37 +0100 Subject: [PATCH 39/52] feat(handler): implement StreamHandler, ConsoleHandler, StderrHandler emit StreamHandler.emit() writes formatted output to a Writable stream. ConsoleHandler maps log levels to console.warn/error/log. StderrHandler emits via console.error. handleError() logs diagnostics instead of throwing. FileHandler throws NotImplementedError on construction. Removed Node.js stream import and conditional require() block. --- src/handler.ts | 125 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 83 insertions(+), 42 deletions(-) diff --git a/src/handler.ts b/src/handler.ts index 24ff076..e174133 100644 --- a/src/handler.ts +++ b/src/handler.ts @@ -1,17 +1,9 @@ -import * as stream from 'stream'; - -import { LogLevel, checkLevel, NOTSET } from './log-level'; +import { LogLevel, checkLevel, NOTSET, WARNING, ERROR } from './log-level'; import { LogRecord } from './log-record'; import { Formatter, DEFAULT_FORMATTER } from './formatter'; import { Filterer } from './filter'; import { NotImplementedError } from './helper/error'; - -if (typeof window === 'undefined') { - const stream = require('stream'); -} -else { - const stream = require('./helper/stream'); -} +import { Writable, DEFAULT_STREAM, StderrWritable } from './helper/stream'; //--------------------------------------------------------------------------- // Handler classes and functions @@ -22,7 +14,7 @@ type Handlers = {[key: string]: Handler}; /** * map of handler names to handlers */ -const HANDLERS: Handlers = {}; +const HANDLERS: Handlers = {}; /** * added to allow handlers to be removed in reverse order of initialization @@ -86,7 +78,7 @@ export class Handler extends Filterer { /** * Format the specified record. - * + * * If a formatter is set, use it. Otherwise, use the default formatter for * the module. */ @@ -115,14 +107,13 @@ export class Handler extends Filterer { * I/O thread lock. */ handle(record: LogRecord) { - var rv = this.filter(record); + const rv = this.filter(record); + if (!rv) { return } + let filtered = record; if ((rv as any) instanceof LogRecord) { - record = rv as unknown as LogRecord - } - if (rv) { - //locking here - this.emit(record) + filtered = rv as unknown as LogRecord } + this.emit(filtered) } /** @@ -144,23 +135,73 @@ export class Handler extends Filterer { * Handle errors which occur during an emit() call. * * This method should be called from handlers when an exception is - * encountered during an emit() call. If raiseExceptions is false, - * exceptions get silently ignored. This is what is mostly wanted - * for a logging system - most users will not care about errors in - * the logging system, they are more interested in application errors. - * You could, however, replace this with a custom handler if you wish. - * The record which was being processed is passed in to this method. + * encountered during an emit() call. */ handleError(record: LogRecord) { - throw new NotImplementedError( - 'still need to find portable way for stacktracing...' - ) + try { + console.error('--- Logging error ---'); + console.error('Error in handler for record:', record.scope, record.msg); + } + catch (_) { + // silently ignore errors in error handling + } } get formatter(): Formatter|null { return this._formatter } set formatter(fmt: Formatter) { this._formatter = fmt } } +/** + * A handler class which writes logging records, appropriately formatted, + * to a stream. Note that this class does not close the stream, as + * the default stream may be shared. + */ +export class StreamHandler extends Handler { + protected stream: Writable; + + constructor(stream?: Writable) { + super(); + this.stream = stream ?? DEFAULT_STREAM; + } + + emit(record: LogRecord) { + try { + const msg = this.format(record); + this.stream.write(msg); + } + catch (e) { + this.handleError(record); + } + } +} + +/** + * A handler class which writes logging records to the browser console, + * mapping log levels to the appropriate console method. + * + * This is the primary handler for browser environments. + */ +export class ConsoleHandler extends Handler { + emit(record: LogRecord) { + try { + const msg = this.format(record); + + if (record.levelno >= ERROR) { + console.error(msg); + } + else if (record.levelno >= WARNING) { + console.warn(msg); + } + else { + console.log(msg); + } + } + catch (e) { + this.handleError(record); + } + } +} + export interface FileHandlerOptions { filename: string filemode?: string @@ -168,20 +209,13 @@ export interface FileHandlerOptions { errors?: string } -/** - * A handler class which writes logging records, appropriately formatted, - to a stream. Note that this class does not close the stream, as - sys.stdout or sys.stderr may be used. - */ -export class StreamHandler extends Handler { - constructor(stream?: stream.Writable) { - super(); - } -} - export class FileHandler extends StreamHandler { constructor(options: FileHandlerOptions) { super(); + throw new NotImplementedError( + 'FileHandler is not available in browser environments. ' + + 'Use ConsoleHandler or a storage-backed handler instead.' + ); } } @@ -190,9 +224,16 @@ export class FileHandler extends StreamHandler { * whatever sys.stderr is currently set to rather than the value of * sys.stderr at handler construction time. */ - export class StderrHandler extends Handler { - /** - * Initialize the handler. - */ +export class StderrHandler extends Handler { constructor(level: LogLevel) { super(level) } + + emit(record: LogRecord) { + try { + const msg = this.format(record); + console.error(msg); + } + catch (e) { + this.handleError(record); + } + } } From 216d2b5892739f7f8678b38476e22659f44853ac Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 00:00:34 +0100 Subject: [PATCH 40/52] test(handler): add tests for StreamHandler, ConsoleHandler, StderrHandler Cover StreamHandler emit to custom Writable, default stream fallback, and error handling on write failure. Cover ConsoleHandler level-to- method mapping (error/warn/log). Cover StderrHandler console.error output. Cover FileHandler browser rejection. Cover Handler base class handleError not throwing. --- tests/unit/handler.test.ts | 141 ++++++++++++++++++++++++++++++++++--- 1 file changed, 130 insertions(+), 11 deletions(-) diff --git a/tests/unit/handler.test.ts b/tests/unit/handler.test.ts index 99a897a..cc22958 100644 --- a/tests/unit/handler.test.ts +++ b/tests/unit/handler.test.ts @@ -1,8 +1,16 @@ import {expect, jest, test} from '@jest/globals'; -import { Handler, StreamHandler, StderrHandler } from '../../src/handler'; +import { + Handler, + StreamHandler, + ConsoleHandler, + StderrHandler, + FileHandler, +} from '../../src/handler'; import { Formatter, DEFAULT_FORMATTER } from '../../src/formatter'; import { LogRecord } from '../../src/log-record'; -import { DEBUG, WARNING, ERROR, NOTSET } from '../../src/log-level'; +import { Writable } from '../../src/helper/stream'; +import { DEBUG, INFO, WARNING, ERROR, CRITICAL, NOTSET } from '../../src/log-level'; + function makeRecord(level: number, msg: string): LogRecord { return new LogRecord('test', { level, msg }); } @@ -50,15 +58,6 @@ describe('Handler', () => { expect(typeof result).toBe('string'); }); - test('uses assigned formatter', () => { - const h = new Handler(); - const fmt = new Formatter({ fmt: '%(message)s' }); - h.formatter = fmt; - const record = makeRecord(DEBUG, 'hello'); - const result = h.format(record); - expect(typeof result).toBe('string'); - }); - test('returns a string', () => { const h = new Handler(); const record = makeRecord(WARNING, 'test message'); @@ -82,6 +81,103 @@ describe('Handler', () => { expect(h.closed).toBe(true); }); }); + + describe('handleError', () => { + test('does not throw', () => { + const h = new Handler(); + const record = makeRecord(DEBUG, 'test'); + expect(() => h.handleError(record)).not.toThrow(); + }); + }); +}); + +describe('StreamHandler', () => { + test('writes formatted output to the stream', () => { + const written: string[] = []; + const stream: Writable = { write: (data: string) => { written.push(data) } }; + const h = new StreamHandler(stream); + const record = makeRecord(WARNING, 'stream test'); + h.emit(record); + expect(written.length).toBe(1); + expect(written[0]).toContain('stream test'); + }); + + test('uses default stream when none provided', () => { + const h = new StreamHandler(); + const record = makeRecord(DEBUG, 'default stream'); + expect(() => h.emit(record)).not.toThrow(); + }); + + test('calls handleError on emit failure', () => { + const stream: Writable = { + write: () => { throw new Error('write failed') } + }; + const h = new StreamHandler(stream); + const record = makeRecord(DEBUG, 'fail'); + expect(() => h.emit(record)).not.toThrow(); + }); +}); + +describe('ConsoleHandler', () => { + let origLog: typeof console.log; + let origWarn: typeof console.warn; + let origError: typeof console.error; + let logged: string[]; + let warned: string[]; + let errored: string[]; + + beforeEach(() => { + logged = []; + warned = []; + errored = []; + origLog = console.log; + origWarn = console.warn; + origError = console.error; + console.log = (...args: any[]) => { logged.push(args.join(' ')) }; + console.warn = (...args: any[]) => { warned.push(args.join(' ')) }; + console.error = (...args: any[]) => { errored.push(args.join(' ')) }; + }); + + afterEach(() => { + console.log = origLog; + console.warn = origWarn; + console.error = origError; + }); + + test('uses console.error for ERROR level', () => { + const h = new ConsoleHandler(); + h.emit(makeRecord(ERROR, 'error msg')); + expect(errored.length).toBe(1); + expect(errored[0]).toContain('error msg'); + }); + + test('uses console.error for CRITICAL level', () => { + const h = new ConsoleHandler(); + h.emit(makeRecord(CRITICAL, 'critical msg')); + expect(errored.length).toBe(1); + expect(errored[0]).toContain('critical msg'); + }); + + test('uses console.warn for WARNING level', () => { + const h = new ConsoleHandler(); + h.emit(makeRecord(WARNING, 'warn msg')); + expect(warned.length).toBe(1); + expect(warned[0]).toContain('warn msg'); + }); + + test('uses console.log for INFO level', () => { + const h = new ConsoleHandler(); + h.emit(makeRecord(INFO, 'info msg')); + expect(logged.length).toBe(1); + expect(logged[0]).toContain('info msg'); + }); + + test('uses console.log for DEBUG level', () => { + const h = new ConsoleHandler(); + h.emit(makeRecord(DEBUG, 'debug msg')); + expect(logged.length).toBe(1); + expect(logged[0]).toContain('debug msg'); + }); }); describe('StderrHandler', () => { @@ -89,4 +185,27 @@ describe('StderrHandler', () => { const h = new StderrHandler(ERROR); expect(h.level).toBe(ERROR); }); + + test('emits via console.error', () => { + const errored: string[] = []; + const origError = console.error; + console.error = (...args: any[]) => { errored.push(args.join(' ')) }; + try { + const h = new StderrHandler(DEBUG); + h.emit(makeRecord(WARNING, 'stderr test')); + expect(errored.length).toBe(1); + expect(errored[0]).toContain('stderr test'); + } + finally { + console.error = origError; + } + }); +}); + +describe('FileHandler', () => { + test('throws NotImplementedError on construction', () => { + expect(() => new FileHandler({ + filename: 'test.log' + })).toThrow('not available in browser'); + }); }); From 672b692013a0ea8e171f3a1ed8c0de521986bb85 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 00:00:50 +0100 Subject: [PATCH 41/52] todo(8): done Added browser-compatible Writable interface with ConsoleWritable and StderrWritable implementations. StreamHandler.emit() writes to a Writable stream. ConsoleHandler maps levels to console.warn/error/log. StderrHandler emits via console.error. FileHandler throws on construction in browser. Handler.handleError() logs diagnostics. Writable interface designed for extensibility (issue 13). --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 4d06273..30e7113 100644 --- a/TODO +++ b/TODO @@ -121,7 +121,7 @@ Content-Type: application/issue ID: 8 Type: feature Title: implement browser-compatible Handler output -Status: in-progress +Status: done Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From cfda9902f7450c6bbca75a623587998560a15e14 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 00:11:36 +0100 Subject: [PATCH 42/52] todo(9): in-progress Set manager on loggers created by getLogger(), verify propagation works end-to-end through the hierarchy. --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 30e7113..db94604 100644 --- a/TODO +++ b/TODO @@ -140,7 +140,7 @@ Content-Type: application/issue ID: 9 Type: feature Title: implement Manager logger hierarchy -Status: open +Status: in-progress Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From 94c7d4a1dacfc1aefd977ef971f98cc52508620e Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 00:23:09 +0100 Subject: [PATCH 43/52] feat(manager): set manager on created loggers, fix clear for placeholders getLogger() now assigns manager on newly created loggers so isEnabledFor can check manager.disable. When replacing a Placeholder, _fixupParents is also called to establish the parent chain. clear() skips Placeholder entries that lack a clear method. --- src/manager.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/manager.ts b/src/manager.ts index 1d6828d..ff73f5d 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -79,8 +79,10 @@ export class Manager { if (existing instanceof Placeholder) { rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + rv.manager = this; this.loggers[scope] = rv; this._fixupChildren(existing, rv); + this._fixupParents(rv); } else { rv = existing; @@ -88,6 +90,7 @@ export class Manager { } else { rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + rv.manager = this; this.loggers[scope] = rv; this._fixupParents(rv); } @@ -168,7 +171,9 @@ export class Manager { */ public clear() { Object.values(this.loggers).forEach((logger) => { - logger.clear() + if (!(logger instanceof Placeholder)) { + logger.clear(); + } }); } } From 5022a1e0bc24b933ee7fdd97192a4853891c7c4a Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 02:32:20 +0100 Subject: [PATCH 44/52] test(manager): add tests for manager assignment and propagation --- tests/unit/manager.test.ts | 83 +++++++++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/tests/unit/manager.test.ts b/tests/unit/manager.test.ts index 2df1fbb..43765da 100644 --- a/tests/unit/manager.test.ts +++ b/tests/unit/manager.test.ts @@ -1,7 +1,9 @@ import {expect, jest, test} from '@jest/globals'; import { Manager } from '../../src/manager'; import { Logger, RootLogger } from '../../src/logger'; -import { WARNING, DEBUG, NOTSET } from '../../src/log-level'; +import { Handler } from '../../src/handler'; +import { LogRecord } from '../../src/log-record'; +import { WARNING, DEBUG, INFO, NOTSET } from '../../src/log-level'; function makeManager(): Manager { return new Manager(new RootLogger(WARNING)); @@ -117,6 +119,79 @@ describe('Manager', () => { }); }); + describe('getLogger - manager assignment', () => { + test('sets manager on newly created loggers', () => { + const manager = makeManager(); + const logger = manager.getLogger('app'); + expect(logger.manager).toBe(manager); + }); + + test('sets manager on loggers created from placeholders', () => { + const manager = makeManager(); + manager.getLogger('a.b.c'); + const mid = manager.getLogger('a.b'); + expect(mid.manager).toBe(manager); + }); + + test('isEnabledFor respects manager.disable via getLogger', () => { + const manager = makeManager(); + const logger = manager.getLogger('app'); + logger.setLevel(DEBUG); + + expect(logger.isEnabledFor(DEBUG)).toBe(true); + + manager.disable = WARNING; + logger.clear(); + + expect(logger.isEnabledFor(DEBUG)).toBe(false); + expect(logger.isEnabledFor(WARNING)).toBe(false); + }); + }); + + describe('propagation through hierarchy', () => { + test('child logger propagates records to parent handler', () => { + const manager = makeManager(); + const parent = manager.getLogger('app'); + const child = manager.getLogger('app.module'); + + parent.setLevel(DEBUG); + child.setLevel(DEBUG); + + const emitted: string[] = []; + const handler = new (class extends Handler { + emit(record: LogRecord) { + emitted.push(record.msg); + } + })(DEBUG); + + parent.addHandler(handler); + child.info('propagated message'); + + expect(emitted).toContain('propagated message'); + }); + + test('child does not propagate to unrelated logger', () => { + const manager = makeManager(); + const unrelated = manager.getLogger('other'); + const child = manager.getLogger('app.module'); + + unrelated.setLevel(DEBUG); + child.setLevel(DEBUG); + + const emitted: string[] = []; + const handler = new (class extends Handler { + emit(record: LogRecord) { + emitted.push(record.msg); + } + })(DEBUG); + + unrelated.addHandler(handler); + child.info('should not reach'); + + expect(emitted).not.toContain('should not reach'); + }); + }); + describe('clear', () => { test('clears logger caches', () => { const manager = makeManager(); @@ -124,5 +199,11 @@ describe('Manager', () => { logger.isEnabledFor(DEBUG); manager.clear(); }); + + test('does not throw when placeholders exist', () => { + const manager = makeManager(); + manager.getLogger('a.b.c'); + expect(() => manager.clear()).not.toThrow(); + }); }); }); From 743e8ffc3b6d3f4aeef641d19482bf7e3a784f09 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 02:32:35 +0100 Subject: [PATCH 45/52] todo(9): done --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index db94604..0e0bf86 100644 --- a/TODO +++ b/TODO @@ -140,7 +140,7 @@ Content-Type: application/issue ID: 9 Type: feature Title: implement Manager logger hierarchy -Status: in-progress +Status: done Priority: high Created: 2026-03-13 Relationships: dependsOn:5 From 741b959820b7b38c9102d2824a4e9096f8bcd72c Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 02:34:31 +0100 Subject: [PATCH 46/52] todo(10): in-progress --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 0e0bf86..5ca2c9b 100644 --- a/TODO +++ b/TODO @@ -156,7 +156,7 @@ Content-Type: application/issue ID: 10 Type: feature Title: add documentation -Status: open +Status: in-progress Priority: medium Created: 2026-03-13 Relationships: From 1a74f2afa4438dd5fc94b1dafea6b0ddb9bfe94c Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 04:33:53 +0100 Subject: [PATCH 47/52] docs: add user guide, cookbook, and rewrite README --- README.md | 104 +++++++++--- docs/README.md | 334 ++++++++++++++++++++++++++++++++++++++- docs/logging-cookbook.md | 237 +++++++++++++++++++++++---- 3 files changed, 621 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 4f860b2..12ec9c7 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,89 @@ # esm-logging -> This README is a stub. Working on it. Currently stabilizing the build - environment after that I'll make it nice around here. +A quasi-port of the Python standard library +[logging](https://docs.python.org/3/library/logging.html) module to +ECMAScript. Browser-compatible, zero dependencies. -A quasi-port of the Python standard library logging module to ECMAScript. +## Why? -# Why? - -First of, because logging is important. It is important for debugging purposes, -leading to faster and more resilient development, for traceability leading to -better security. Most logging libraries I've discovered didn't satisfy me, -introduced weird concepts and all in all just weren't great. Other programming -language ecosystems offer way nicer logging facilities. Take Rust for example, -or... Python! Python has PEP, giving it a very structured approach towards +Logging is important. It is important for debugging purposes, leading to +faster and more resilient development, for traceability leading to better +security. Most logging libraries I've discovered didn't satisfy me, introduced +weird concepts and all in all just weren't great. Other programming language +ecosystems offer way nicer logging facilities. Take Rust for example, or... +Python! Python has PEP, giving it a very structured approach towards implementing new features and that's also how its logging facilities came to be -([PEP 282](https://peps.python.org/pep-0282/)). Python's logging facilities are -implemented by the [logging]() module, which is part of the standard library and -has been since 2002. It was originally authored by Vinay Sajip +([PEP 282](https://peps.python.org/pep-0282/)). Python's logging facilities +are implemented by the [logging](https://docs.python.org/3/library/logging.html) +module, which is part of the standard library and has been since 2002. It was +originally authored by Vinay Sajip. -# Roadmap +## Installation -- do a quasi-port of the logging module with minimal amount of adaption -- add documentation -- add support for asynchronous calls -- implement Open Cybersecurity Framework (OCSF) formatter -- implement (Browser) local storage handler as a replacement for file handler +```bash +npm install @administratrix/esm-logging +``` -# Usage +## Quick start -For the time being, please check out my [CI -service](https://bitbucket.org/byteb4rb1e/esm-logging/pipelines), for an idea on -how to build this. +```javascript +import * as logging from '@administratrix/esm-logging'; + +// one-shot configuration: sets up a console handler on the root logger +logging.config.basicConfig({ level: logging.log_level.INFO }); + +// create a logger for this module +const logger = logging.manager.MANAGER.getLogger('myapp'); + +logger.info('Application started'); +logger.warning('Something looks off'); +logger.error('Something went wrong'); +``` + +## Concepts + +The logging system is built around four core components: + +- **Loggers** expose the interface that application code uses directly. +- **Handlers** send log records to the appropriate destination (console, + stderr, custom writable streams). +- **Formatters** control the layout of log records in the final output. +- **Filters** provide fine-grained control over which records to output. + +Loggers are organized in a dot-separated hierarchy. A logger named `app.db` +is a child of the logger named `app`. Log records propagate up the hierarchy, +so a handler attached to `app` will also receive records from `app.db`. + +## Log levels + +| Constant | Value | Purpose | +|------------|-------|------------------------------------------| +| `CRITICAL` | 50 | A serious error, the program may not continue | +| `ERROR` | 40 | An error that prevented some operation | +| `WARNING` | 30 | Something unexpected, but the software still works | +| `INFO` | 20 | Confirmation that things work as expected | +| `DEBUG` | 10 | Detailed diagnostic information | +| `NOTSET` | 0 | All messages are processed | + +## Documentation + +See [docs/](docs/README.md) for the full user guide and +[docs/logging-cookbook.md](docs/logging-cookbook.md) for recipes and patterns. + +API reference can be generated with TypeDoc: + +```bash +npm run build/doc +``` + +## Roadmap + +- [x] quasi-port of the logging module with minimal adaptation +- [x] add documentation +- [ ] add support for asynchronous calls +- [ ] implement Open Cybersecurity Schema Framework (OCSF) formatter +- [ ] implement browser local storage handler as a replacement for file handler + +## License + +UNLICENSED diff --git a/docs/README.md b/docs/README.md index 776f875..d7eff57 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1 +1,333 @@ -The doc/README.md \ No newline at end of file +# esm-logging user guide + +This guide covers the `@administratrix/esm-logging` library, a quasi-port of +Python's `logging` module for ECMAScript. It targets browser environments and +provides hierarchical, configurable logging with formatters, handlers, and +filters. + +## Table of contents + +- [Basic usage](#basic-usage) +- [Loggers](#loggers) +- [Handlers](#handlers) +- [Formatters](#formatters) +- [Filters](#filters) +- [Configuration](#configuration) +- [Log record attributes](#log-record-attributes) + +## Basic usage + +The simplest way to start logging is with `basicConfig`: + +```javascript +import * as logging from '@administratrix/esm-logging'; + +logging.config.basicConfig({ + level: logging.log_level.DEBUG, + format: '%(levelname)s:%(name)s:%(message)s', +}); + +const logger = logging.manager.MANAGER.getLogger('myapp'); +logger.info('Hello, world'); +// output: INFO:myapp:Hello, world +``` + +`basicConfig` creates a `StreamHandler` writing to stderr (via +`console.error`) and attaches it to the root logger. It is a one-shot +function: calling it again has no effect unless you pass `force: true`. + +## Loggers + +Loggers are the entry point for emitting log records. They are organized in a +dot-separated hierarchy managed by a singleton `Manager`. + +### Creating loggers + +```javascript +const logger = logging.manager.MANAGER.getLogger('myapp'); +const childLogger = logging.manager.MANAGER.getLogger('myapp.db'); +``` + +Calling `getLogger` with the same scope always returns the same logger +instance. The hierarchy is established automatically: `myapp.db` is a child of +`myapp`. + +### Setting levels + +```javascript +logger.setLevel(logging.log_level.WARNING); +``` + +A logger only processes messages at or above its effective level. The +effective level is determined by walking up the parent chain until a logger +with a non-zero level is found. The root logger defaults to `WARNING`. + +### Logging methods + +Each level has a corresponding method: + +```javascript +logger.debug('Detailed diagnostic info'); +logger.info('Things are working'); +logger.warning('Something unexpected'); +logger.error('An operation failed'); +logger.critical('System is in trouble'); +``` + +### Propagation + +By default, log records propagate up the hierarchy. A record emitted by +`myapp.db` will be handled by handlers on `myapp.db`, then `myapp`, then the +root logger. This means you typically only need to configure handlers on the +root logger or on high-level loggers. + +### Checking if a level is enabled + +```javascript +if (logger.isEnabledFor(logging.log_level.DEBUG)) { + logger.debug('Expensive computation: ' + computeDebugInfo()); +} +``` + +This avoids the cost of building the message string when the level would be +filtered out anyway. + +## Handlers + +Handlers determine where log records go. A logger can have multiple handlers, +and each handler can have its own level and formatter. + +### Available handlers + +#### StreamHandler + +Writes formatted output to a `Writable` stream. Defaults to stderr (via +`console.error`). + +```javascript +import { StreamHandler } from '@administratrix/esm-logging/src/handler'; +import { ConsoleWritable } from '@administratrix/esm-logging/src/helper/stream'; + +const handler = new StreamHandler(new ConsoleWritable()); +logger.addHandler(handler); +``` + +#### ConsoleHandler + +Maps log levels to the appropriate browser console method: + +- `ERROR` and `CRITICAL` use `console.error` +- `WARNING` uses `console.warn` +- `DEBUG` and `INFO` use `console.log` + +```javascript +import { ConsoleHandler } from '@administratrix/esm-logging/src/handler'; + +const handler = new ConsoleHandler(); +handler.level = logging.log_level.DEBUG; +logger.addHandler(handler); +``` + +#### StderrHandler + +Always writes to `console.error`, regardless of level. Useful when you want +all output on stderr. + +```javascript +import { StderrHandler } from '@administratrix/esm-logging/src/handler'; + +const handler = new StderrHandler(logging.log_level.WARNING); +logger.addHandler(handler); +``` + +#### FileHandler + +Not available in browser environments. Throws `NotImplementedError` on +construction. Use `ConsoleHandler` or a storage-backed handler instead. + +### Handler methods + +```javascript +handler.level = logging.log_level.INFO; // only handle INFO and above +handler.formatter = myFormatter; // set a custom formatter +handler.close(); // release resources +``` + +### Custom handlers + +Subclass `Handler` and implement `emit(record)`: + +```javascript +import { Handler } from '@administratrix/esm-logging/src/handler'; + +class ArrayHandler extends Handler { + constructor() { + super(); + this.records = []; + } + + emit(record) { + this.records.push(this.format(record)); + } +} +``` + +## Formatters + +Formatters control how log records are rendered as strings. The default format +is `%(message)s` (just the message). The basic format used by `basicConfig` is +`%(levelname)s:%(name)s:%(message)s`. + +### Creating a formatter + +```javascript +import { Formatter } from '@administratrix/esm-logging/src/formatter'; + +const formatter = new Formatter({ + fmt: '%(asctime)s - %(levelname)s - %(name)s - %(message)s', + datefmt: '%Y-%m-%d %H:%M:%S', +}); + +handler.formatter = formatter; +``` + +### Format string placeholders + +Formatters use `%`-style substitution. Available placeholders correspond to +[log record attributes](#log-record-attributes): + +``` +%(name)s Logger scope name +%(levelno)d Numeric log level +%(levelname)s Text log level (DEBUG, INFO, etc.) +%(message)s The formatted message +%(asctime)s Human-readable timestamp +%(created)f Milliseconds since epoch (Date.now()) +``` + +### Date formatting + +The `datefmt` option accepts strftime-style tokens: + +| Token | Meaning | Example | +|-------|-----------------|---------| +| `%Y` | Four-digit year | 2026 | +| `%m` | Zero-padded month | 03 | +| `%d` | Zero-padded day | 14 | +| `%H` | Hour (24h) | 09 | +| `%M` | Minute | 05 | +| `%S` | Second | 30 | + +If `datefmt` is omitted, an ISO 8601-like format is used: +`2026-03-14 09:05:30.123`. + +## Filters + +Filters provide fine-grained control over which records get processed. They +can be attached to loggers or handlers. + +### Scope-based filtering + +A `Filter` initialized with a scope name only allows records from that scope +and its children: + +```javascript +import { Filter } from '@administratrix/esm-logging/src/filter'; + +const filter = new Filter('myapp.db'); +handler.addFilter(filter); +// only records from 'myapp.db' and 'myapp.db.*' will pass +``` + +A filter initialized with an empty string allows all records. + +### Custom filters + +Any object with a `filter(record)` method can be used: + +```javascript +handler.addFilter({ + filter(record) { + return record.levelno >= logging.log_level.WARNING; + } +}); +``` + +## Configuration + +### basicConfig + +`basicConfig` is a convenience function for simple, one-shot configuration of +the root logger: + +```javascript +logging.config.basicConfig({ + level: logging.log_level.DEBUG, + format: '%(asctime)s %(levelname)s %(message)s', + datefmt: '%Y-%m-%d %H:%M:%S', +}); +``` + +#### Options + +| Option | Type | Description | +|------------|------------|--------------------------------------------| +| `level` | `number` | Root logger level | +| `format` | `string` | Format string for the handler's formatter | +| `datefmt` | `string` | Date format string | +| `style` | `string` | Format style (`'%'` only, currently) | +| `handlers` | `Handler[]`| Pre-built handlers to attach | +| `stream` | `Writable` | Stream for the default StreamHandler | +| `force` | `boolean` | Remove existing handlers first | + +`stream` and `handlers` are mutually exclusive. + +### Manual configuration + +For more control, configure loggers and handlers directly: + +```javascript +const root = logging.manager.MANAGER.root; +const handler = new ConsoleHandler(); +handler.level = logging.log_level.DEBUG; +handler.formatter = new Formatter({ + fmt: '%(asctime)s [%(levelname)s] %(name)s: %(message)s', +}); +root.addHandler(handler); +root.setLevel(logging.log_level.DEBUG); +``` + +## Log record attributes + +A `LogRecord` carries the following attributes: + +| Attribute | Type | Description | +|-------------|----------|----------------------------------------| +| `scope` | `string` | Logger name that created the record | +| `name` | `string` | Same as `scope` | +| `levelno` | `number` | Numeric level (10, 20, 30, 40, 50) | +| `levelname` | `string` | Text level (`DEBUG`, `INFO`, etc.) | +| `msg` | `string` | The raw message template | +| `args` | `any[]` | Substitution arguments for `%s` in msg | +| `message` | `string` | The formatted message (set by formatter) | +| `created` | `number` | Milliseconds since Unix epoch | +| `asctime` | `string` | Formatted timestamp (set by formatter) | + +The `getMessage()` method on `LogRecord` performs `%s` argument substitution +on `msg` using `args`. + +## Module structure + +The library is organized into submodules, all re-exported from the main entry +point: + +| Import path | Contents | +|---------------|----------------------------------------------| +| `config` | `basicConfig()` | +| `filter` | `Filter`, `Filterer` | +| `formatter` | `Formatter`, `STYLES`, `DEFAULT_FORMATTER` | +| `handler` | `Handler`, `StreamHandler`, `ConsoleHandler`, `StderrHandler`, `FileHandler` | +| `log_level` | Level constants, `getLevelName()`, `checkLevel()` | +| `log_record` | `LogRecord`, factory functions | +| `logger` | `Logger`, `RootLogger`, `ROOT` | +| `manager` | `Manager`, `MANAGER` | diff --git a/docs/logging-cookbook.md b/docs/logging-cookbook.md index a0e5d9c..7d4e727 100644 --- a/docs/logging-cookbook.md +++ b/docs/logging-cookbook.md @@ -1,37 +1,216 @@ -# Using logging in multiple modules +# Logging cookbook -Multiple calls to `logging.getLogger('someLogger')` return a reference to the -same logger object. This is true not only within the same module, but also -across modules as long as it is in the same Python interpreter process. It is -true for references to the same object; additionally, application code can -define and configure a parent logger in one module and create (but not -configure) a child logger in a separate module, and all logger calls to the -child will pass up to the parent. Here is a main module: +Recipes and patterns for common logging tasks with `@administratrix/esm-logging`. -``javascript -import * as logging from 'eslib/logging'; -import * as my_module from './my_module'; +## Using logging across multiple modules -// create logger with 'spam_application' -var logger = logging.getLogger('spam_application'); -logger.setLevel(logging.DEBUG); +`getLogger` returns the same logger instance for a given scope name across +your entire application. Configure handlers on a parent logger and create +child loggers in each module: -// create file handler which logs even debug messages -var fh = logging.FileHandler('spam.log') -fh.setLevel(logging.DEBUG); +```javascript +// main.js +import * as logging from '@administratrix/esm-logging'; +import { ConsoleHandler } from '@administratrix/esm-logging/src/handler'; +import { Formatter } from '@administratrix/esm-logging/src/formatter'; +import { doWork } from './worker.js'; -// create console handler with a higher log level -var ch = logging.StreamHandler(); -ch.setLevel(logging.ERROR); +const logger = logging.manager.MANAGER.getLogger('myapp'); +logger.setLevel(logging.log_level.DEBUG); -// create formatter and add it to the handlers -var formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'); -fh.setFormatter(formatter); -ch.setFormatter(formatter); +const handler = new ConsoleHandler(); +handler.level = logging.log_level.DEBUG; +handler.formatter = new Formatter({ + fmt: '%(asctime)s - %(name)s - %(levelname)s - %(message)s', +}); +logger.addHandler(handler); -// add the handlers to the logger -logger.addHandler(fh); -logger.addHandler(ch); - -logger.info('creating an instance of auxiliary_module.Auxiliary') +logger.info('Application starting'); +doWork(); +logger.info('Application finished'); ``` + +```javascript +// worker.js +import * as logging from '@administratrix/esm-logging'; + +const logger = logging.manager.MANAGER.getLogger('myapp.worker'); + +export function doWork() { + logger.debug('Starting work'); + // ... do something ... + logger.info('Work completed'); +} +``` + +Because `myapp.worker` is a child of `myapp`, its records propagate up to the +handler configured on `myapp`. No handler configuration is needed in +`worker.js`. + +Output: + +``` +2026-03-14 10:00:00.000 - myapp - INFO - Application starting +2026-03-14 10:00:00.001 - myapp.worker - DEBUG - Starting work +2026-03-14 10:00:00.002 - myapp.worker - INFO - Work completed +2026-03-14 10:00:00.003 - myapp - INFO - Application finished +``` + +## Logging to multiple destinations + +Attach multiple handlers to a single logger, each with its own level and +formatter: + +```javascript +import * as logging from '@administratrix/esm-logging'; +import { ConsoleHandler, StderrHandler } from '@administratrix/esm-logging/src/handler'; +import { Formatter } from '@administratrix/esm-logging/src/formatter'; + +const logger = logging.manager.MANAGER.getLogger('myapp'); +logger.setLevel(logging.log_level.DEBUG); + +// console handler: shows everything with detailed format +const consoleHandler = new ConsoleHandler(); +consoleHandler.level = logging.log_level.DEBUG; +consoleHandler.formatter = new Formatter({ + fmt: '%(asctime)s [%(levelname)s] %(name)s: %(message)s', +}); +logger.addHandler(consoleHandler); + +// stderr handler: only errors, compact format +const errorHandler = new StderrHandler(logging.log_level.ERROR); +errorHandler.formatter = new Formatter({ + fmt: 'ERROR %(asctime)s %(name)s: %(message)s', + datefmt: '%Y-%m-%d %H:%M:%S', +}); +logger.addHandler(errorHandler); +``` + +## Using basicConfig for simple scripts + +For quick scripts, `basicConfig` sets up a handler on the root logger: + +```javascript +import * as logging from '@administratrix/esm-logging'; + +logging.config.basicConfig({ + level: logging.log_level.INFO, + format: '%(levelname)s: %(message)s', +}); + +const logger = logging.manager.MANAGER.getLogger('script'); +logger.info('Running'); +logger.warning('Check this'); +``` + +Output: + +``` +INFO: Running +WARNING: Check this +``` + +## Filtering records + +### By scope + +Only allow records from a specific part of the hierarchy: + +```javascript +import { Filter } from '@administratrix/esm-logging/src/filter'; + +const dbFilter = new Filter('myapp.db'); +handler.addFilter(dbFilter); +// handler now only processes records from 'myapp.db' and its children +``` + +### By custom criteria + +Use any object with a `filter(record)` method: + +```javascript +handler.addFilter({ + filter(record) { + // only pass records that contain 'important' in the message + return record.msg.includes('important'); + } +}); +``` + +## Custom formatters + +Create formatters with different format strings for different contexts: + +```javascript +import { Formatter } from '@administratrix/esm-logging/src/formatter'; + +// detailed format for development +const devFormatter = new Formatter({ + fmt: '%(asctime)s %(levelname)s %(name)s: %(message)s', + datefmt: '%H:%M:%S', +}); + +// compact format for production +const prodFormatter = new Formatter({ + fmt: '%(levelname)s:%(name)s:%(message)s', +}); +``` + +## Custom handlers + +Subclass `Handler` and implement `emit(record)`: + +```javascript +import { Handler } from '@administratrix/esm-logging/src/handler'; + +class BufferHandler extends Handler { + constructor(level) { + super(level); + this.buffer = []; + } + + emit(record) { + try { + this.buffer.push(this.format(record)); + if (this.buffer.length >= 100) { + this.flush(); + } + } catch (e) { + this.handleError(record); + } + } + + flush() { + // send buffered records somewhere + const batch = this.buffer.splice(0); + // ... process batch ... + } +} +``` + +## Disabling logging below a threshold + +The manager's `disable` property suppresses all logging at or below a given +level across all loggers: + +```javascript +import * as logging from '@administratrix/esm-logging'; + +// suppress DEBUG and INFO globally +logging.manager.MANAGER.disable = logging.log_level.INFO; +``` + +## Reconfiguring with force + +`basicConfig` only takes effect once. To reconfigure, use `force: true`: + +```javascript +logging.config.basicConfig({ + level: logging.log_level.DEBUG, + format: '%(asctime)s %(message)s', + force: true, +}); +``` + +This removes and closes all existing handlers on the root logger before +applying the new configuration. From b254922d3c800a5c4872d17eff5e13a7910cacc7 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 04:34:08 +0100 Subject: [PATCH 48/52] todo(10): done --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 5ca2c9b..4686732 100644 --- a/TODO +++ b/TODO @@ -156,7 +156,7 @@ Content-Type: application/issue ID: 10 Type: feature Title: add documentation -Status: in-progress +Status: done Priority: medium Created: 2026-03-13 Relationships: From 7479931714a2062ebe41eb841d18f237a89d67b9 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 04:39:24 +0100 Subject: [PATCH 49/52] todo(13): in-progress --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 4686732..72430ec 100644 --- a/TODO +++ b/TODO @@ -203,7 +203,7 @@ Content-Type: application/issue ID: 13 Type: feature Title: implement browser local storage handler -Status: open +Status: in-progress Priority: medium Created: 2026-03-13 Relationships: dependsOn:8 From 6fd8c22ceb631ab20a2ce0c9fbba60209338ab51 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 04:55:37 +0100 Subject: [PATCH 50/52] feat(handler): implement LocalStorageHandler with rotation --- src/handler.ts | 108 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/src/handler.ts b/src/handler.ts index e174133..6f66f50 100644 --- a/src/handler.ts +++ b/src/handler.ts @@ -219,6 +219,114 @@ export class FileHandler extends StreamHandler { } } +/** + * A handler that persists log records to browser localStorage. + * + * Records are stored as a JSON array of formatted strings under a + * configurable key. Log rotation is supported by entry count and/or + * byte size to avoid exceeding storage quotas. + */ +export interface LocalStorageHandlerOptions { + /** + * localStorage key to store entries under. + * Defaults to 'esm-logging'. + */ + key?: string; + + /** + * Maximum number of entries to retain. Oldest entries are discarded + * first. Set to 0 for no entry limit. Defaults to 1000. + */ + maxEntries?: number; + + /** + * Maximum size in bytes (as measured by the JSON-serialized string + * length). Oldest entries are discarded to stay within this limit. + * Set to 0 for no byte limit. Defaults to 0. + */ + maxBytes?: number; +} + +export class LocalStorageHandler extends Handler { + protected key: string; + protected maxEntries: number; + protected maxBytes: number; + + constructor(options?: LocalStorageHandlerOptions) { + super(); + + if (typeof localStorage === 'undefined') { + throw new NotImplementedError( + 'LocalStorageHandler requires a browser environment with localStorage' + ); + } + + this.key = options?.key ?? 'esm-logging'; + this.maxEntries = options?.maxEntries ?? 1000; + this.maxBytes = options?.maxBytes ?? 0; + } + + emit(record: LogRecord) { + try { + const msg = this.format(record); + const entries = this.getEntries(); + entries.push(msg); + this._rotate(entries); + this._setEntries(entries); + } + catch (e) { + this.handleError(record); + } + } + + /** + * Retrieve all stored log entries. + */ + getEntries(): string[] { + try { + const data = localStorage.getItem(this.key); + return data ? JSON.parse(data) : []; + } + catch { + return []; + } + } + + /** + * Remove all stored log entries. + */ + clearEntries() { + localStorage.removeItem(this.key); + } + + close() { + super.close(); + } + + /** + * Discard oldest entries to stay within maxEntries and maxBytes limits. + */ + protected _rotate(entries: string[]) { + if (this.maxEntries > 0) { + while (entries.length > this.maxEntries) { + entries.shift(); + } + } + + if (this.maxBytes > 0) { + while (entries.length > 0) { + const serialized = JSON.stringify(entries); + if (serialized.length <= this.maxBytes) { break } + entries.shift(); + } + } + } + + protected _setEntries(entries: string[]) { + localStorage.setItem(this.key, JSON.stringify(entries)); + } +} + /** * This class is like a StreamHandler using sys.stderr, but always uses * whatever sys.stderr is currently set to rather than the value of From 37fd6194c74c018a1dd260cc27ecf837556efa4c Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 04:57:32 +0100 Subject: [PATCH 51/52] test(handler): add tests for LocalStorageHandler --- tests/unit/local-storage-handler.test.ts | 158 +++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 tests/unit/local-storage-handler.test.ts diff --git a/tests/unit/local-storage-handler.test.ts b/tests/unit/local-storage-handler.test.ts new file mode 100644 index 0000000..a00b701 --- /dev/null +++ b/tests/unit/local-storage-handler.test.ts @@ -0,0 +1,158 @@ +import {expect, jest, test, beforeEach, afterEach} from '@jest/globals'; +import { LocalStorageHandler } from '../../src/handler'; +import { LogRecord } from '../../src/log-record'; +import { DEBUG, WARNING, ERROR } from '../../src/log-level'; + +// mock localStorage for Node/Jest environment +const store: {[key: string]: string} = {}; +const localStorageMock = { + getItem: (key: string): string | null => store[key] ?? null, + setItem: (key: string, value: string) => { store[key] = value }, + removeItem: (key: string) => { delete store[key] }, +}; + +function clearStore() { + for (const key of Object.keys(store)) { delete store[key] } +} + +function makeRecord(level: number, msg: string): LogRecord { + return new LogRecord('test', { level, msg }); +} + +beforeEach(() => { + clearStore(); + (globalThis as any).localStorage = localStorageMock; +}); + +afterEach(() => { + clearStore(); + delete (globalThis as any).localStorage; +}); + +describe('LocalStorageHandler', () => { + describe('constructor', () => { + test('uses default key and limits', () => { + const h = new LocalStorageHandler(); + expect(h.getEntries()).toEqual([]); + }); + + test('throws when localStorage is unavailable', () => { + delete (globalThis as any).localStorage; + expect(() => new LocalStorageHandler()).toThrow( + 'requires a browser environment' + ); + }); + + test('accepts custom options', () => { + const h = new LocalStorageHandler({ + key: 'custom-log', + maxEntries: 50, + maxBytes: 4096, + }); + h.emit(makeRecord(DEBUG, 'test')); + expect(store['custom-log']).toBeDefined(); + expect(store['esm-logging']).toBeUndefined(); + }); + }); + + describe('emit', () => { + test('stores formatted log entry', () => { + const h = new LocalStorageHandler(); + h.emit(makeRecord(WARNING, 'hello')); + const entries = h.getEntries(); + expect(entries.length).toBe(1); + expect(entries[0]).toContain('hello'); + }); + + test('appends multiple entries', () => { + const h = new LocalStorageHandler(); + h.emit(makeRecord(DEBUG, 'first')); + h.emit(makeRecord(DEBUG, 'second')); + h.emit(makeRecord(DEBUG, 'third')); + expect(h.getEntries().length).toBe(3); + }); + + test('persists across handler instances with same key', () => { + const h1 = new LocalStorageHandler({ key: 'shared' }); + h1.emit(makeRecord(DEBUG, 'from h1')); + + const h2 = new LocalStorageHandler({ key: 'shared' }); + const entries = h2.getEntries(); + expect(entries.length).toBe(1); + expect(entries[0]).toContain('from h1'); + }); + }); + + describe('rotation by entry count', () => { + test('discards oldest entries when maxEntries exceeded', () => { + const h = new LocalStorageHandler({ maxEntries: 3 }); + h.emit(makeRecord(DEBUG, 'msg-1')); + h.emit(makeRecord(DEBUG, 'msg-2')); + h.emit(makeRecord(DEBUG, 'msg-3')); + h.emit(makeRecord(DEBUG, 'msg-4')); + + const entries = h.getEntries(); + expect(entries.length).toBe(3); + expect(entries[0]).toContain('msg-2'); + expect(entries[2]).toContain('msg-4'); + }); + + test('maxEntries of 1 keeps only the latest', () => { + const h = new LocalStorageHandler({ maxEntries: 1 }); + h.emit(makeRecord(DEBUG, 'old')); + h.emit(makeRecord(DEBUG, 'new')); + + const entries = h.getEntries(); + expect(entries.length).toBe(1); + expect(entries[0]).toContain('new'); + }); + }); + + describe('rotation by byte size', () => { + test('discards oldest entries when maxBytes exceeded', () => { + const h = new LocalStorageHandler({ maxEntries: 0, maxBytes: 100 }); + // emit entries until we exceed the limit + for (let i = 0; i < 20; i++) { + h.emit(makeRecord(DEBUG, `message-${i}`)); + } + + const entries = h.getEntries(); + const serialized = JSON.stringify(entries); + expect(serialized.length).toBeLessThanOrEqual(100); + expect(entries.length).toBeGreaterThan(0); + }); + }); + + describe('getEntries', () => { + test('returns empty array when no entries', () => { + const h = new LocalStorageHandler(); + expect(h.getEntries()).toEqual([]); + }); + + test('returns empty array on corrupt data', () => { + store['esm-logging'] = 'not valid json{{{'; + const h = new LocalStorageHandler(); + expect(h.getEntries()).toEqual([]); + }); + }); + + describe('clearEntries', () => { + test('removes all stored entries', () => { + const h = new LocalStorageHandler(); + h.emit(makeRecord(DEBUG, 'to be cleared')); + expect(h.getEntries().length).toBe(1); + + h.clearEntries(); + expect(h.getEntries()).toEqual([]); + }); + }); + + describe('close', () => { + test('sets closed to true', () => { + const h = new LocalStorageHandler(); + expect(h.closed).toBe(false); + h.close(); + expect(h.closed).toBe(true); + }); + }); +}); From 5b29c67d0d0d9e3f411fdf59a7e5e3b128e9fbab Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Sat, 14 Mar 2026 05:02:55 +0100 Subject: [PATCH 52/52] todo(13): done --- TODO | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO b/TODO index 72430ec..1fad08e 100644 --- a/TODO +++ b/TODO @@ -203,7 +203,7 @@ Content-Type: application/issue ID: 13 Type: feature Title: implement browser local storage handler -Status: in-progress +Status: done Priority: medium Created: 2026-03-13 Relationships: dependsOn:8