@holz/core 0.10.1-rc.7.sha-a01a6d1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -87,20 +87,20 @@ In this example, the log message describes a successful connection to a database
87
87
 
88
88
  In Holz, a `LogProcessor` function is responsible for processing log messages. The `createLogger` function takes this function as an argument. A `LogProcessor` is a plain function that takes a `Log` object, which contains the message, level, origin, and context of the log.
89
89
 
90
- Holz provides a set of off-the-shelf plugins for logging to various destinations, filtering, formatting, and more. You can also write your own plugins to suit your specific needs. These plugins can be combined into a `LogProcessor` function using the utility function `combine()`, allowing you to send a single log to multiple destinations.
90
+ Holz provides a set of off-the-shelf plugins for logging to various destinations, filtering, formatting, and more. You can also write your own plugins to suit your specific needs. These plugins can be combined into a `LogProcessor` function using the utility function `createGroup()`, allowing you to send a single log to multiple destinations.
91
91
 
92
92
  Holz's plugin system is designed to be flexible and extensible. If none of the provided plugins meet your needs, you can easily create your own plugin and still build on plugins from the rest of the ecosystem. Check out the [`@holz/logger`](https://github.com/PsychoLlama/holz/tree/main/packages/holz-logger) package for a bundled example of Holz's logging plugins.
93
93
 
94
- ## Functions
94
+ ## Functions (`@holz/core/functions`)
95
95
 
96
96
  In addition to the core `Logger` class, `@holz/core` provides some utility processors that you can use to extend the functionality of your logging solution. These processors are optional and can be combined with each other or with third-party processors as needed.
97
97
 
98
- ### `combine`
98
+ ### `createGroup`
99
99
 
100
- The `combine` processor takes an array of log processors and returns a single log processor that forwards each log to all of the input processors. This is useful when you want to send a single log to multiple log destinations.
100
+ Groups a set of destinations into a single processor. Logs fan out to each.
101
101
 
102
102
  ```typescript
103
- import { combine } from '@holz/core/functions';
103
+ import { createGroup } from '@holz/core/functions';
104
104
  import {
105
105
  consoleBackend,
106
106
  fileBackend,
@@ -108,18 +108,18 @@ import {
108
108
  } from './custom-processors';
109
109
 
110
110
  const logger = createLogger(
111
- combine([consoleBackend, fileBackend, logUploadService]),
111
+ createGroup([consoleBackend, fileBackend, logUploadService]),
112
112
  );
113
113
  ```
114
114
 
115
- ### `filter`
115
+ ### `createFilter`
116
116
 
117
- The `filter` processor takes a filter function and another log processor as input. If the filter function returns `true` for a log, it is forwarded to the second processor. If the filter function returns `false`, the log is discarded. This is useful when you want to selectively forward logs based on some criteria.
117
+ Accepts a filter function. Anything returning `false` is discarded.
118
118
 
119
119
  ```typescript
120
- import { filter } from '@holz/core/functions';
120
+ import { createFilter } from '@holz/core/functions';
121
121
 
122
- const debugLogFilter = filter(
122
+ const debugLogFilter = createFilter(
123
123
  (log) => log.level > level.debug,
124
124
  consoleProcessor,
125
125
  );
@@ -127,4 +127,125 @@ const debugLogFilter = filter(
127
127
  const logger = createLogger(debugLogFilter);
128
128
  ```
129
129
 
130
- Note that you can chain multiple filter processors together to create more complex filters.
130
+ ### `createValve`
131
+
132
+ Switches between buffering and streaming. Analogous to opening a valve on a hose.
133
+
134
+ #### Use Cases
135
+
136
+ - Buffer logs until a plugin finishes initializing.
137
+ - Pause uploads while offline and flush on reconnect.
138
+ - Wait to send logs until a user consents to telemetry.
139
+
140
+ #### Example
141
+
142
+ ```typescript
143
+ import { createValve } from '@holz/core/functions';
144
+
145
+ const { open, close, processor } = createValve({
146
+ // Start in buffered mode.
147
+ open: false,
148
+
149
+ // Buffer up to 1k logs. Beyond that, drop the oldest.
150
+ capacity: 1_000,
151
+
152
+ // Streaming: forward to this backend.
153
+ processor: persist,
154
+
155
+ // Batched: drain logs when the valve opens.
156
+ drain: (logs) => logs.forEach(persist),
157
+ });
158
+
159
+ const logger = createLogger(processor);
160
+
161
+ // Later: drain the buffer and stream logs going forward.
162
+ open();
163
+ ```
164
+
165
+ ### `createRouter`
166
+
167
+ Switches between log destinations dynamically.
168
+
169
+ #### Use Cases
170
+
171
+ - Fall back to local storage when uploads fail, and switch back once they recover.
172
+ - Swap backends when changing a diagnostics setting.
173
+ - Redirect logs to a file while a TUI owns the terminal.
174
+
175
+ #### Example
176
+
177
+ ```typescript
178
+ import { createRouter } from '@holz/core/functions';
179
+
180
+ const { select, processor } = createRouter(
181
+ // Start by sending logs to stderr.
182
+ 'stderr',
183
+
184
+ // Every possible destination, by name.
185
+ {
186
+ stderr: printToStderr,
187
+ file: writeToFile,
188
+ },
189
+ );
190
+
191
+ const logger = createLogger(processor);
192
+
193
+ // Later: send logs to the file instead of stderr.
194
+ select('file');
195
+ ```
196
+
197
+ ### `createBuffer`
198
+
199
+ Holds logs in a ring buffer until drained. Once `capacity` is reached, each new log overwrites the oldest.
200
+
201
+ #### Use Cases
202
+
203
+ - Hold startup logs until you know where to send them.
204
+ - Keep recent logs in memory to attach to crash reports.
205
+ - Collect logs during a test and assert on them afterward.
206
+
207
+ #### Example
208
+
209
+ ```typescript
210
+ import { createBuffer } from '@holz/core/functions';
211
+
212
+ const { drain, processor } = createBuffer({
213
+ // Buffer up to 1k logs. Beyond that, drop the oldest.
214
+ // Defaults to `Infinity`.
215
+ capacity: 1_000,
216
+ });
217
+
218
+ const logger = createLogger(processor);
219
+
220
+ // Later: empty the buffer and return its logs in arrival order.
221
+ const logs = drain();
222
+ ```
223
+
224
+ ### `createBatcher`
225
+
226
+ Groups logs into fixed-size batches and hands each full batch to a sink in one call.
227
+
228
+ #### Use Cases
229
+
230
+ - Upload logs in one request per batch instead of one per log.
231
+ - Write logs to IndexedDB or SQLite in one transaction per batch.
232
+ - Flush a partial batch before the process exits or the page unloads.
233
+
234
+ #### Example
235
+
236
+ ```typescript
237
+ import { createBatcher } from '@holz/core/functions';
238
+
239
+ const { drain, clear, processor } = createBatcher({
240
+ // Flush every 50 logs.
241
+ size: 50,
242
+
243
+ // Receives each batch in arrival order.
244
+ sink: upload,
245
+ });
246
+
247
+ const logger = createLogger(processor);
248
+
249
+ // Later: flush the partial batch before exiting.
250
+ drain();
251
+ ```
@@ -0,0 +1,55 @@
1
+ // src/functions/batcher.ts
2
+ var e = ({ size: e, sink: t }) => {
3
+ let n = [], r = () => {
4
+ if (n.length === 0) return;
5
+ let e = n;
6
+ n = [], t(e);
7
+ };
8
+ return {
9
+ processor: (t) => {
10
+ n.push(t), n.length >= e && r();
11
+ },
12
+ drain: r,
13
+ clear: () => {
14
+ n = [];
15
+ }
16
+ };
17
+ }, t = ({ capacity: e = Infinity } = {}) => {
18
+ let t = [], n = 0;
19
+ return {
20
+ processor: (r) => {
21
+ t.length < e ? t.push(r) : e > 0 && (t[n] = r, n = (n + 1) % e);
22
+ },
23
+ drain: () => {
24
+ let e = t.slice(n).concat(t.slice(0, n));
25
+ return t.length = 0, n = 0, e;
26
+ }
27
+ };
28
+ }, n = (e, t) => (n) => {
29
+ e(n) && t(n);
30
+ }, r = (e) => (t) => e.forEach((e) => e(t)), i = (e, t) => {
31
+ let n = t[e];
32
+ return {
33
+ processor: (e) => n(e),
34
+ select: (e) => {
35
+ n = t[e];
36
+ }
37
+ };
38
+ }, a = ({ capacity: e, drain: n, processor: r, open: a }) => {
39
+ let o = t({ capacity: e }), s = i(a ? "open" : "closed", {
40
+ closed: o.processor,
41
+ open: r
42
+ });
43
+ return {
44
+ processor: s.processor,
45
+ open: () => {
46
+ s.select("open");
47
+ let e = o.drain();
48
+ e.length > 0 && n(e);
49
+ },
50
+ close: () => {
51
+ s.select("closed");
52
+ }
53
+ };
54
+ };
55
+ export { t as a, n as i, i as n, e as o, r, a as t };
@@ -1,2 +1,2 @@
1
- import { n as combine, t as filter } from "./index-BwPlyye8.js";
2
- export { combine, filter };
1
+ import { a as createRouter, c as LogBuffer, d as LogBatcher, f as LogBatcherOptions, i as LogRouter, l as LogBufferOptions, n as LogValveOptions, o as createGroup, p as createBatcher, r as createValve, s as createFilter, t as LogValve, u as createBuffer } from "./index-BUa0qbx8.js";
2
+ export { type LogBatcher, type LogBatcherOptions, type LogBuffer, type LogBufferOptions, type LogRouter, type LogValve, type LogValveOptions, createBatcher, createBuffer, createFilter, createGroup, createRouter, createValve };
package/dist/functions.js CHANGED
@@ -1 +1 @@
1
- export { n as combine, t as filter } from "./functions-DALPLIbM.js";
1
+ export { o as createBatcher, a as createBuffer, i as createFilter, r as createGroup, n as createRouter, t as createValve } from "./functions--NrapiiE.js";
@@ -1,13 +1,13 @@
1
- import { a as LogContext, c as Logger, i as Log, l as level, n as combine$1, o as LogLevel, r as CustomContext, s as LogProcessor, t as filter$1 } from "./index-BwPlyye8.js";
1
+ import { _ as LogLevel, b as level, g as LogContext, h as Log, m as CustomContext, o as createGroup, s as createFilter, v as LogProcessor, y as Logger } from "./index-BUa0qbx8.js";
2
2
  /**
3
3
  * Create a new logger. The processor is up to you. There are plugins for
4
4
  * filtering, formatting, combining multiple processors together, and more.
5
5
  *
6
- * If you wish to use more than one processor, `combine(...)` them first.
6
+ * If you wish to use more than one processor, `createGroup(...)` them first.
7
7
  */
8
8
  export declare const createLogger: (processor: LogProcessor) => Logger;
9
- /** @deprecated Import from `@holz/core/functions` instead. */
10
- export declare const combine: typeof combine$1;
11
- /** @deprecated Import from `@holz/core/functions` instead. */
12
- export declare const filter: typeof filter$1;
9
+ /** @deprecated Use `createGroup` from `@holz/core/functions` instead. */
10
+ export declare const combine: typeof createGroup;
11
+ /** @deprecated Use `createFilter` from `@holz/core/functions` instead. */
12
+ export declare const filter: typeof createFilter;
13
13
  export { type CustomContext, type Log, type LogContext, type LogLevel, type LogProcessor, type Logger, level };
package/dist/holz-core.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as e, t } from "./functions-DALPLIbM.js";
1
+ import { i as e, r as t } from "./functions--NrapiiE.js";
2
2
  // src/types.ts
3
3
  var n = {
4
4
  fatal: 60,
@@ -40,5 +40,5 @@ var n = {
40
40
  error: o,
41
41
  fatal: o
42
42
  });
43
- }, i = (e) => r(e, []), a = e, o = t;
43
+ }, i = (e) => r(e, []), a = t, o = e;
44
44
  export { a as combine, i as createLogger, o as filter, n as level };
@@ -115,11 +115,54 @@ interface Logger {
115
115
  fatal: <Context extends StrictContext<Context>>(message: string, context?: Context) => void;
116
116
  }
117
117
  /**
118
- * Combine several log processors into a single log processor. Each one is
119
- * called in sequence. Useful for sending a single log to multiple log
120
- * destinations.
118
+ * Groups a log stream into fixed-size batches. Install
119
+ * {@link LogBatcher.processor} in a pipeline; each full batch is handed to
120
+ * the sink in one call.
121
121
  */
122
- declare const combine: (processors: Array<LogProcessor>) => LogProcessor;
122
+ interface LogBatcher {
123
+ /** The processor to install upstream. Flushes once a batch fills. */
124
+ processor: LogProcessor;
125
+ /** Flush the pending batch to the sink early. No-op when empty. */
126
+ drain: () => void;
127
+ /** Discard the pending batch without flushing it. */
128
+ clear: () => void;
129
+ }
130
+ /** Options for {@link createBatcher}. */
131
+ interface LogBatcherOptions {
132
+ /** How many logs make a full batch. */
133
+ size: number;
134
+ /** Receives each batch, in arrival order. */
135
+ sink: (logs: Log[]) => void;
136
+ }
137
+ /**
138
+ * Create a {@link LogBatcher}. Reach for it when a downstream benefits from
139
+ * receiving logs in bulk, e.g. one network request or transaction per batch.
140
+ */
141
+ declare const createBatcher: ({ size, sink }: LogBatcherOptions) => LogBatcher;
142
+ /**
143
+ * A bounded ring buffer over a log stream. Install {@link LogBuffer.processor}
144
+ * in a pipeline and collect what it held with {@link LogBuffer.drain}.
145
+ */
146
+ interface LogBuffer {
147
+ /** The processor to install upstream. Holds every log it receives. */
148
+ processor: LogProcessor;
149
+ /** Empty the buffer, returning the held logs in arrival order. */
150
+ drain: () => Log[];
151
+ }
152
+ /** Options for {@link createBuffer}. */
153
+ interface LogBufferOptions {
154
+ /**
155
+ * How many logs the buffer retains. Once full, each new log overwrites the
156
+ * oldest. A non-negative integer or `Infinity`; `0` keeps nothing,
157
+ * `Infinity` (the default) is unbounded.
158
+ */
159
+ capacity?: number;
160
+ }
161
+ /**
162
+ * Create a {@link LogBuffer}. Reach for it to hold logs until a consumer is
163
+ * ready to take them, e.g. as the initial destination of a router.
164
+ */
165
+ declare const createBuffer: ({ capacity }?: LogBufferOptions) => LogBuffer;
123
166
  /**
124
167
  * Filter logs based on a filter function. If the function returns true, the
125
168
  * log is kept and forwarded onto the next processor, otherwise it is
@@ -128,5 +171,69 @@ declare const combine: (processors: Array<LogProcessor>) => LogProcessor;
128
171
  * @param predicate Returns `true` to forward the log.
129
172
  * @param processor Where to send the log if it passes the filter.
130
173
  */
131
- declare const filter: (predicate: (log: Log) => boolean, processor: LogProcessor) => LogProcessor;
132
- export { LogContext as a, Logger as c, Log as i, level as l, combine as n, LogLevel as o, CustomContext as r, LogProcessor as s, filter as t };
174
+ declare const createFilter: (predicate: (log: Log) => boolean, processor: LogProcessor) => LogProcessor;
175
+ /**
176
+ * Group several log processors into a single log processor. Each log fans out
177
+ * to every processor, called in sequence. Useful for sending a single log to
178
+ * multiple log destinations.
179
+ */
180
+ declare const createGroup: (processors: Array<LogProcessor>) => LogProcessor;
181
+ /**
182
+ * Switches a log stream between named destinations. Install
183
+ * {@link LogRouter.processor} in a pipeline and pick where logs go with
184
+ * {@link LogRouter.select}. Exactly one destination receives each log.
185
+ */
186
+ interface LogRouter<Name extends string> {
187
+ /** The processor to install upstream. Forwards to the active destination. */
188
+ processor: LogProcessor;
189
+ /** Send subsequent logs to the named destination. */
190
+ select: (name: Name) => void;
191
+ }
192
+ /**
193
+ * Create a {@link LogRouter} over a fixed set of destinations, starting at
194
+ * `initial`. Reach for it when a stream's sink changes at runtime — e.g. a
195
+ * buffer until a backend is ready, then the backend.
196
+ */
197
+ declare const createRouter: <Name extends string>(initial: NoInfer<Name>, destinations: Record<Name, LogProcessor>) => LogRouter<Name>;
198
+ /**
199
+ * A gate over a log stream. Install {@link LogValve.processor} in a pipeline
200
+ * and control the flow with {@link LogValve.open} and {@link LogValve.close}.
201
+ *
202
+ * While open, logs stream straight through to the downstream processor. While
203
+ * closed, they're held in a ring buffer and released as a single batch the
204
+ * next time it opens.
205
+ */
206
+ interface LogValve {
207
+ /** The processor to install upstream. Forwards or buffers each log. */
208
+ processor: LogProcessor;
209
+ /** Flush buffered logs to the drain, then stream onward. */
210
+ open: () => void;
211
+ /** Begin buffering logs. */
212
+ close: () => void;
213
+ }
214
+ /** Options for {@link createValve}. */
215
+ interface LogValveOptions {
216
+ /**
217
+ * How many logs the buffer retains while closed. Once full, each new log
218
+ * overwrites the oldest. Defaults to `Infinity`.
219
+ */
220
+ capacity?: number;
221
+ /** Receives each log while the valve is open. */
222
+ processor: LogProcessor;
223
+ /**
224
+ * Receives everything buffered while closed, in arrival order, as one batch
225
+ * when the valve opens. Not called if nothing was buffered.
226
+ */
227
+ drain: (logs: Log[]) => void;
228
+ /**
229
+ * Whether the valve starts open. Required: the initial state is a decision
230
+ * every caller should make deliberately.
231
+ */
232
+ open: boolean;
233
+ }
234
+ /**
235
+ * Create a {@link LogValve}. Reach for it to hold logs while a downstream
236
+ * isn't ready, then release them all at once when it is.
237
+ */
238
+ declare const createValve: ({ capacity, drain, processor, open: startOpen }: LogValveOptions) => LogValve;
239
+ export { LogLevel as _, createRouter as a, level as b, LogBuffer as c, LogBatcher as d, LogBatcherOptions as f, LogContext as g, Log as h, LogRouter as i, LogBufferOptions as l, CustomContext as m, LogValveOptions as n, createGroup as o, createBatcher as p, createValve as r, createFilter as s, LogValve as t, createBuffer as u, LogProcessor as v, Logger as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holz/core",
3
- "version": "0.10.1-rc.7.sha-a01a6d1",
3
+ "version": "0.11.0",
4
4
  "description": "A structured and composable logger",
5
5
  "type": "module",
6
6
  "repository": {
@@ -50,5 +50,5 @@
50
50
  "vite": "^8.0.0",
51
51
  "vitest": "^5.0.0"
52
52
  },
53
- "gitHead": "a01a6d1c1041410bbad0df8f073894e27937cff4"
53
+ "gitHead": "1c7e11851f369f2a318cfd83386087af86186c5a"
54
54
  }
@@ -0,0 +1,61 @@
1
+ import type { Log, LogProcessor } from '../types';
2
+
3
+ /**
4
+ * Groups a log stream into fixed-size batches. Install
5
+ * {@link LogBatcher.processor} in a pipeline; each full batch is handed to
6
+ * the sink in one call.
7
+ */
8
+ export interface LogBatcher {
9
+ /** The processor to install upstream. Flushes once a batch fills. */
10
+ processor: LogProcessor;
11
+
12
+ /** Flush the pending batch to the sink early. No-op when empty. */
13
+ drain: () => void;
14
+
15
+ /** Discard the pending batch without flushing it. */
16
+ clear: () => void;
17
+ }
18
+
19
+ /** Options for {@link createBatcher}. */
20
+ export interface LogBatcherOptions {
21
+ /** How many logs make a full batch. */
22
+ size: number;
23
+
24
+ /** Receives each batch, in arrival order. */
25
+ sink: (logs: Log[]) => void;
26
+ }
27
+
28
+ /**
29
+ * Create a {@link LogBatcher}. Reach for it when a downstream benefits from
30
+ * receiving logs in bulk, e.g. one network request or transaction per batch.
31
+ */
32
+ export const createBatcher = ({
33
+ size,
34
+ sink,
35
+ }: LogBatcherOptions): LogBatcher => {
36
+ let pending: Log[] = [];
37
+
38
+ const drain = () => {
39
+ if (pending.length === 0) return;
40
+
41
+ // Swap before calling the sink. A throwing sink can't leave the batch to
42
+ // grow unbounded, and a log emitted from inside the sink starts the next
43
+ // batch instead of mutating the one being flushed.
44
+ const batch = pending;
45
+ pending = [];
46
+
47
+ sink(batch);
48
+ };
49
+
50
+ const processor: LogProcessor = (log) => {
51
+ pending.push(log);
52
+
53
+ if (pending.length >= size) drain();
54
+ };
55
+
56
+ const clear = () => {
57
+ pending = [];
58
+ };
59
+
60
+ return { processor, drain, clear };
61
+ };
@@ -0,0 +1,60 @@
1
+ import type { Log, LogProcessor } from '../types';
2
+
3
+ /**
4
+ * A bounded ring buffer over a log stream. Install {@link LogBuffer.processor}
5
+ * in a pipeline and collect what it held with {@link LogBuffer.drain}.
6
+ */
7
+ export interface LogBuffer {
8
+ /** The processor to install upstream. Holds every log it receives. */
9
+ processor: LogProcessor;
10
+
11
+ /** Empty the buffer, returning the held logs in arrival order. */
12
+ drain: () => Log[];
13
+ }
14
+
15
+ /** Options for {@link createBuffer}. */
16
+ export interface LogBufferOptions {
17
+ /**
18
+ * How many logs the buffer retains. Once full, each new log overwrites the
19
+ * oldest. A non-negative integer or `Infinity`; `0` keeps nothing,
20
+ * `Infinity` (the default) is unbounded.
21
+ */
22
+ capacity?: number;
23
+ }
24
+
25
+ /**
26
+ * Create a {@link LogBuffer}. Reach for it to hold logs until a consumer is
27
+ * ready to take them, e.g. as the initial destination of a router.
28
+ */
29
+ export const createBuffer = ({
30
+ capacity = Infinity,
31
+ }: LogBufferOptions = {}): LogBuffer => {
32
+ // Ring buffer that grows lazily up to `capacity`, then overwrites in place.
33
+ // Pushing keeps the array packed, and avoids a large up-front allocation
34
+ // when `capacity` is big or Infinity. `oldest` indexes the oldest entry
35
+ // (the next slot to overwrite once full); it stays 0 while growing.
36
+ const buffer: Log[] = [];
37
+ let oldest = 0;
38
+
39
+ const processor: LogProcessor = (log) => {
40
+ if (buffer.length < capacity) {
41
+ buffer.push(log);
42
+ } else if (capacity > 0) {
43
+ buffer[oldest] = log;
44
+ oldest = (oldest + 1) % capacity;
45
+ }
46
+ };
47
+
48
+ const drain = () => {
49
+ // The ring holds two contiguous runs, `oldest` to the end then the start
50
+ // up to `oldest`, so joining those slices restores arrival order.
51
+ const logs = buffer.slice(oldest).concat(buffer.slice(0, oldest));
52
+
53
+ buffer.length = 0;
54
+ oldest = 0;
55
+
56
+ return logs;
57
+ };
58
+
59
+ return { processor, drain };
60
+ };
@@ -8,7 +8,7 @@ import type { Log, LogProcessor } from '../types';
8
8
  * @param predicate Returns `true` to forward the log.
9
9
  * @param processor Where to send the log if it passes the filter.
10
10
  */
11
- export const filter =
11
+ export const createFilter =
12
12
  (predicate: (log: Log) => boolean, processor: LogProcessor): LogProcessor =>
13
13
  (log: Log) => {
14
14
  if (predicate(log)) {
@@ -0,0 +1,11 @@
1
+ import type { Log, LogProcessor } from '../types';
2
+
3
+ /**
4
+ * Group several log processors into a single log processor. Each log fans out
5
+ * to every processor, called in sequence. Useful for sending a single log to
6
+ * multiple log destinations.
7
+ */
8
+ export const createGroup =
9
+ (processors: Array<LogProcessor>): LogProcessor =>
10
+ (log: Log) =>
11
+ processors.forEach((processor) => processor(log));
@@ -1,2 +1,10 @@
1
- export { combine } from './combine';
2
- export { filter } from './filter';
1
+ export { createBatcher } from './batcher';
2
+ export type { LogBatcher, LogBatcherOptions } from './batcher';
3
+ export { createBuffer } from './buffer';
4
+ export type { LogBuffer, LogBufferOptions } from './buffer';
5
+ export { createFilter } from './filter';
6
+ export { createGroup } from './group';
7
+ export { createRouter } from './router';
8
+ export type { LogRouter } from './router';
9
+ export { createValve } from './valve';
10
+ export type { LogValve, LogValveOptions } from './valve';
@@ -0,0 +1,33 @@
1
+ import type { LogProcessor } from '../types';
2
+
3
+ /**
4
+ * Switches a log stream between named destinations. Install
5
+ * {@link LogRouter.processor} in a pipeline and pick where logs go with
6
+ * {@link LogRouter.select}. Exactly one destination receives each log.
7
+ */
8
+ export interface LogRouter<Name extends string> {
9
+ /** The processor to install upstream. Forwards to the active destination. */
10
+ processor: LogProcessor;
11
+
12
+ /** Send subsequent logs to the named destination. */
13
+ select: (name: Name) => void;
14
+ }
15
+
16
+ /**
17
+ * Create a {@link LogRouter} over a fixed set of destinations, starting at
18
+ * `initial`. Reach for it when a stream's sink changes at runtime — e.g. a
19
+ * buffer until a backend is ready, then the backend.
20
+ */
21
+ export const createRouter = <Name extends string>(
22
+ initial: NoInfer<Name>,
23
+ destinations: Record<Name, LogProcessor>,
24
+ ): LogRouter<Name> => {
25
+ let active = destinations[initial];
26
+
27
+ return {
28
+ processor: (log) => active(log),
29
+ select: (name) => {
30
+ active = destinations[name];
31
+ },
32
+ };
33
+ };
@@ -0,0 +1,81 @@
1
+ import type { Log, LogProcessor } from '../types';
2
+ import { createBuffer } from './buffer';
3
+ import { createRouter } from './router';
4
+
5
+ /**
6
+ * A gate over a log stream. Install {@link LogValve.processor} in a pipeline
7
+ * and control the flow with {@link LogValve.open} and {@link LogValve.close}.
8
+ *
9
+ * While open, logs stream straight through to the downstream processor. While
10
+ * closed, they're held in a ring buffer and released as a single batch the
11
+ * next time it opens.
12
+ */
13
+ export interface LogValve {
14
+ /** The processor to install upstream. Forwards or buffers each log. */
15
+ processor: LogProcessor;
16
+
17
+ /** Flush buffered logs to the drain, then stream onward. */
18
+ open: () => void;
19
+
20
+ /** Begin buffering logs. */
21
+ close: () => void;
22
+ }
23
+
24
+ /** Options for {@link createValve}. */
25
+ export interface LogValveOptions {
26
+ /**
27
+ * How many logs the buffer retains while closed. Once full, each new log
28
+ * overwrites the oldest. Defaults to `Infinity`.
29
+ */
30
+ capacity?: number;
31
+
32
+ /** Receives each log while the valve is open. */
33
+ processor: LogProcessor;
34
+
35
+ /**
36
+ * Receives everything buffered while closed, in arrival order, as one batch
37
+ * when the valve opens. Not called if nothing was buffered.
38
+ */
39
+ drain: (logs: Log[]) => void;
40
+
41
+ /**
42
+ * Whether the valve starts open. Required: the initial state is a decision
43
+ * every caller should make deliberately.
44
+ */
45
+ open: boolean;
46
+ }
47
+
48
+ /**
49
+ * Create a {@link LogValve}. Reach for it to hold logs while a downstream
50
+ * isn't ready, then release them all at once when it is.
51
+ */
52
+ export const createValve = ({
53
+ capacity,
54
+ drain,
55
+ processor,
56
+ open: startOpen,
57
+ }: LogValveOptions): LogValve => {
58
+ const buffer = createBuffer({ capacity });
59
+ const router = createRouter(startOpen ? 'open' : 'closed', {
60
+ closed: buffer.processor,
61
+ open: processor,
62
+ });
63
+
64
+ return {
65
+ processor: router.processor,
66
+
67
+ open: () => {
68
+ // Route before draining so a log emitted from inside `drain` streams
69
+ // straight through. `buffer.drain()` resets before returning, so it can't
70
+ // land in the batch already released.
71
+ router.select('open');
72
+
73
+ const logs = buffer.drain();
74
+ if (logs.length > 0) drain(logs);
75
+ },
76
+
77
+ close: () => {
78
+ router.select('closed');
79
+ },
80
+ };
81
+ };
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { combine as combineFn, filter as filterFn } from './functions';
1
+ import { createFilter, createGroup } from './functions';
2
2
 
3
- /** @deprecated Import from `@holz/core/functions` instead. */
4
- export const combine: typeof combineFn = combineFn;
3
+ /** @deprecated Use `createGroup` from `@holz/core/functions` instead. */
4
+ export const combine: typeof createGroup = createGroup;
5
5
 
6
- /** @deprecated Import from `@holz/core/functions` instead. */
7
- export const filter: typeof filterFn = filterFn;
6
+ /** @deprecated Use `createFilter` from `@holz/core/functions` instead. */
7
+ export const filter: typeof createFilter = createFilter;
8
8
 
9
9
  export { createLogger } from './logger';
10
10
  export { level } from './types';
package/src/logger.ts CHANGED
@@ -57,7 +57,7 @@ const createNamespacedLogger = (
57
57
  * Create a new logger. The processor is up to you. There are plugins for
58
58
  * filtering, formatting, combining multiple processors together, and more.
59
59
  *
60
- * If you wish to use more than one processor, `combine(...)` them first.
60
+ * If you wish to use more than one processor, `createGroup(...)` them first.
61
61
  */
62
62
  export const createLogger = (processor: LogProcessor): Logger =>
63
63
  createNamespacedLogger(processor, []);
@@ -1,5 +0,0 @@
1
- // src/functions/combine.ts
2
- var e = (e) => (t) => e.forEach((e) => e(t)), t = (e, t) => (n) => {
3
- e(n) && t(n);
4
- };
5
- export { e as n, t };
@@ -1,11 +0,0 @@
1
- import type { Log, LogProcessor } from '../types';
2
-
3
- /**
4
- * Combine several log processors into a single log processor. Each one is
5
- * called in sequence. Useful for sending a single log to multiple log
6
- * destinations.
7
- */
8
- export const combine =
9
- (processors: Array<LogProcessor>): LogProcessor =>
10
- (log: Log) =>
11
- processors.forEach((processor) => processor(log));