@yieldkit/logger 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +256 -2
  3. package/dist/callback-logger.d.ts +78 -0
  4. package/dist/callback-logger.js +104 -0
  5. package/dist/config.d.ts +29 -0
  6. package/dist/config.js +264 -0
  7. package/dist/context.d.ts +60 -0
  8. package/dist/context.js +100 -0
  9. package/dist/crash.d.ts +114 -0
  10. package/dist/crash.js +215 -0
  11. package/dist/credentials.d.ts +57 -0
  12. package/dist/credentials.js +267 -0
  13. package/dist/error.d.ts +27 -0
  14. package/dist/error.js +173 -0
  15. package/dist/formatters.d.ts +53 -0
  16. package/dist/formatters.js +137 -0
  17. package/dist/index.d.ts +16 -0
  18. package/dist/index.js +15 -0
  19. package/dist/layer.d.ts +31 -0
  20. package/dist/layer.js +78 -0
  21. package/dist/line-cap.d.ts +6 -0
  22. package/dist/line-cap.js +367 -0
  23. package/dist/log-fan-out.d.ts +24 -0
  24. package/dist/log-fan-out.js +83 -0
  25. package/dist/metrics.d.ts +19 -0
  26. package/dist/metrics.js +45 -0
  27. package/dist/omit-undefined.js +10 -0
  28. package/dist/otlp/flush.d.ts +8 -0
  29. package/dist/otlp/flush.js +11 -0
  30. package/dist/otlp/index.d.ts +4 -0
  31. package/dist/otlp/index.js +4 -0
  32. package/dist/otlp/telemetry.d.ts +86 -0
  33. package/dist/otlp/telemetry.js +230 -0
  34. package/dist/otlp/tracing.d.ts +11 -0
  35. package/dist/otlp/tracing.js +13 -0
  36. package/dist/redact-cause.js +92 -0
  37. package/dist/redact-walk.d.ts +19 -0
  38. package/dist/redact-walk.js +290 -0
  39. package/dist/redact.d.ts +104 -0
  40. package/dist/redact.js +271 -0
  41. package/dist/request-id.d.ts +21 -0
  42. package/dist/request-id.js +28 -0
  43. package/dist/testing/index.d.ts +55 -0
  44. package/dist/testing/index.js +42 -0
  45. package/dist/types.d.ts +212 -0
  46. package/docs/callback-logger.md +38 -0
  47. package/docs/configuration.md +56 -0
  48. package/docs/crash-and-startup.md +57 -0
  49. package/docs/durations-and-request-ids.md +30 -0
  50. package/docs/formats.md +78 -0
  51. package/docs/logging.md +53 -0
  52. package/docs/redaction.md +87 -0
  53. package/docs/telemetry.md +78 -0
  54. package/docs/testing.md +60 -0
  55. package/package.json +74 -3
@@ -0,0 +1,230 @@
1
+ import { resolveRedaction } from "../formatters.js";
2
+ import { logExportSinkLayer } from "../log-fan-out.js";
3
+ import { Config, Duration, Effect, Layer, Option, Schema, Tracer } from "effect";
4
+ import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/observability";
5
+ // src/otlp/telemetry.ts
6
+ /**
7
+ * Resource attribute that names the deployment environment.
8
+ */
9
+ const ENVIRONMENT_ATTRIBUTE = "deployment.environment.name";
10
+ /**
11
+ * Exporter name that sends a signal over OTLP.
12
+ */
13
+ const EXPORTER_OTLP = "otlp";
14
+ /**
15
+ * Separator between the entries of an `OTEL_<SIGNAL>_EXPORTER` list.
16
+ */
17
+ const EXPORTER_LIST_SEPARATOR = ",";
18
+ /**
19
+ * `OTEL_SDK_DISABLED` value, in any case, that turns every signal off. Any other value leaves them
20
+ * on, as the OpenTelemetry specification says.
21
+ */
22
+ const SDK_DISABLED_VALUE = "true";
23
+ /**
24
+ * `OTEL_EXPORTER_OTLP_*_TIMEOUT` text: blank or a whole number of milliseconds.
25
+ */
26
+ const TIMEOUT_PATTERN = /^\s*\d*\s*$/;
27
+ /**
28
+ * Parses an `OTEL_EXPORTER_OTLP_*_COMPRESSION` value in any case. Blank is unset; anything other
29
+ * than `gzip` or `none` returns `undefined`.
30
+ */
31
+ const parseCompression = (raw) => {
32
+ const value = raw.trim().toLowerCase();
33
+ if (value === "") return Option.none();
34
+ if (value === "gzip" || value === "none") return Option.some(value);
35
+ };
36
+ /**
37
+ * `OTEL_EXPORTER_OTLP_*_COMPRESSION` text that {@link parseCompression} accepts.
38
+ */
39
+ const CompressionText = Schema.String.check(Schema.makeFilter((value) => parseCompression(value) !== void 0, { message: "Expected gzip or none" }));
40
+ /**
41
+ * `OTEL_EXPORTER_OTLP_*_TIMEOUT` text: blank or whole milliseconds.
42
+ */
43
+ const TimeoutText = Schema.String.check(Schema.makeFilter((value) => TIMEOUT_PATTERN.test(value), { message: "Expected a whole number of milliseconds" }));
44
+ /**
45
+ * Trailing slash, if any, at the end of a base collector path, replaced by `/v1/<signal>`.
46
+ */
47
+ const TRAILING_SLASH_PATTERN = /\/?$/;
48
+ /**
49
+ * Collector URL that must use `http:` or `https:`.
50
+ */
51
+ const HttpEndpoint = Schema.URLFromString.check(Schema.makeFilter((url) => url.protocol === "http:" || url.protocol === "https:", { message: "Expected an HTTP or HTTPS collector URL" }));
52
+ /**
53
+ * Empty string or an HTTP(S) collector URL. A blank env var stays empty.
54
+ */
55
+ const OptionalEndpoint = Schema.Trim.pipe(Schema.decodeTo(Schema.Union([Schema.Literal(""), HttpEndpoint])));
56
+ /**
57
+ * Exports traces, metrics and logs over OTLP/HTTP to the collector named by the OTEL_* variables,
58
+ * and provides the `OtlpExporter.Flusher` shared by all three. Closing the layer's scope flushes
59
+ * the last batches.
60
+ *
61
+ * - `OTEL_SDK_DISABLED=true` (any case) turns every signal off.
62
+ * - Each signal uses `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` as is, or `OTEL_EXPORTER_OTLP_ENDPOINT`
63
+ * with `/v1/<signal>` appended. With neither set, the signal is off.
64
+ * - `OTEL_<SIGNAL>_EXPORTER` is a comma-separated list; the signal is on when the list is blank or
65
+ * includes `otlp` (`otlp,console` keeps it on, `none` turns it off). `signals.<signal>: false`
66
+ * turns it off whatever the environment says.
67
+ * - Requests carry `OTEL_EXPORTER_OTLP_<SIGNAL>_HEADERS` or `OTEL_EXPORTER_OTLP_HEADERS`
68
+ * (`key=value,key2=value2`, values percent-decoded) unless `headers` is set, use
69
+ * `OTEL_EXPORTER_OTLP[_<SIGNAL>]_COMPRESSION` (`gzip` or `none`), and wait at most
70
+ * `OTEL_EXPORTER_OTLP[_<SIGNAL>]_TIMEOUT` milliseconds for the last export on shutdown.
71
+ *
72
+ * Log records reach the exporter through the fan-out logger installed by `LoggerLive` and
73
+ * `makeLoggerLayer`, after the logger's redaction, so log export needs one of them, and only
74
+ * records logged by code this layer is provided to are exported. The current loggers are not
75
+ * replaced. With every signal off, the layer provides a `Flusher` whose `flush` does nothing. An
76
+ * endpoint that is not an HTTP(S) URL, a compression other than `gzip` or `none`, or a timeout that
77
+ * is not an integer fails with `ConfigError`.
78
+ */
79
+ const telemetryLayer = (options) => Layer.unwrap(Effect.gen(function* () {
80
+ if (yield* Config.String("OTEL_SDK_DISABLED").pipe(Config.withDefault(""), Config.map((value) => value.trim().toLowerCase() === SDK_DISABLED_VALUE))) return OtlpExporter.layerFlusher;
81
+ const base = optionalEndpoint("OTEL_EXPORTER_OTLP_ENDPOINT");
82
+ const traces = yield* signalEndpoint("traces", base, options.signals);
83
+ const metrics = yield* signalEndpoint("metrics", base, options.signals);
84
+ const logs = yield* signalEndpoint("logs", base, options.signals);
85
+ if (traces === void 0 && metrics === void 0 && logs === void 0) return OtlpExporter.layerFlusher;
86
+ const resource = yield* resolveResource(options);
87
+ const redaction = resolveRedaction(options.redaction);
88
+ return Layer.mergeAll(tracesLayer(traces, resource, yield* exportSettings("traces", options), redaction), metricsLayer(metrics, resource, yield* exportSettings("metrics", options)), logsLayer(logs, resource, yield* exportSettings("logs", options))).pipe(Layer.provide(serializationLayer(options.serialization)));
89
+ }));
90
+ /**
91
+ * Reads `key` as an optional collector URL. A missing variable is an empty string.
92
+ */
93
+ const optionalEndpoint = (key) => Config.schema(OptionalEndpoint, key).pipe(Config.withDefault(""));
94
+ /**
95
+ * Tells whether the `OTEL_<SIGNAL>_EXPORTER` list allows the signal: it is missing or blank, or one
96
+ * of its comma-separated entries is `otlp` (any case).
97
+ */
98
+ const exporterEnabled = (signal) => Config.String(`OTEL_${signal.toUpperCase()}_EXPORTER`).pipe(Config.withDefault(""), Config.map((value) => {
99
+ const names = value.split(EXPORTER_LIST_SEPARATOR).map((name) => name.trim().toLowerCase()).filter((name) => name !== "");
100
+ return names.length === 0 || names.includes(EXPORTER_OTLP);
101
+ }));
102
+ /**
103
+ * Reads an OTEL_* header list (`key=value,key2=value2`, values percent-decoded). Whitespace around
104
+ * each name and value is dropped, as the OpenTelemetry list format allows (`a=1, b=2`).
105
+ */
106
+ const headersConfig = (key) => Config.Record(Schema.String, Schema.StringFromUriComponent, key, { trim: true });
107
+ /**
108
+ * Reads a compression variable. Blank is unset.
109
+ */
110
+ const compressionConfig = (key) => Config.schema(CompressionText, key).pipe(Config.map((raw) => parseCompression(raw) ?? Option.none()));
111
+ /**
112
+ * Reads a timeout variable in milliseconds. Blank is unset.
113
+ */
114
+ const timeoutConfig = (key) => Config.schema(TimeoutText, key).pipe(Config.map((raw) => raw.trim() === "" ? Option.none() : Option.some(Number(raw.trim()))));
115
+ /**
116
+ * Reads a header list. Blank is unset.
117
+ */
118
+ const headersOptionConfig = (key) => Config.String(key).pipe(Config.withDefault(""), Config.flatMap((raw) => raw.trim() === "" ? Config.succeed(Option.none()) : headersConfig(key).pipe(Config.map(Option.some))));
119
+ /**
120
+ * Reads the signal's variable `OTEL_EXPORTER_OTLP_<SIGNAL>_<SUFFIX>`, falling back to
121
+ * `OTEL_EXPORTER_OTLP_<SUFFIX>`. A missing or blank variable counts as unset.
122
+ */
123
+ const signalOrBase = (signal, suffix, read) => Config.all({
124
+ specific: Config.option(read(`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_${suffix}`)),
125
+ base: Config.option(read(`OTEL_EXPORTER_OTLP_${suffix}`))
126
+ }).pipe(Config.map(({ specific, base }) => Option.orElse(Option.flatten(specific), () => Option.flatten(base))));
127
+ /**
128
+ * Reads the headers, compression and shutdown timeout of one signal. `options.headers` wins over
129
+ * the header variables.
130
+ */
131
+ const exportSettings = Effect.fnUntraced(function* (signal, options) {
132
+ const headers = options.headers ?? Option.getOrUndefined(yield* signalOrBase(signal, "HEADERS", headersOptionConfig));
133
+ const compression = yield* signalOrBase(signal, "COMPRESSION", compressionConfig);
134
+ const timeout = yield* signalOrBase(signal, "TIMEOUT", timeoutConfig);
135
+ return {
136
+ headers,
137
+ compression: Option.getOrUndefined(compression),
138
+ shutdownTimeout: Option.getOrUndefined(Option.map(timeout, (ms) => Duration.millis(ms)))
139
+ };
140
+ });
141
+ /**
142
+ * Resolves the collector URL for one signal, or `undefined` when the signal is off in code, set to
143
+ * `none`, or has no endpoint. The signal endpoint is used as is; otherwise `/v1/<signal>` replaces
144
+ * the trailing slash of a copy of `base`. `base` is read only when the signal has no endpoint of
145
+ * its own, so an invalid base URL fails only when an enabled signal falls back to it.
146
+ */
147
+ const signalEndpoint = Effect.fnUntraced(function* (signal, base, signals) {
148
+ if (signals?.[signal] === false) return;
149
+ if (!(yield* exporterEnabled(signal))) return;
150
+ const specific = yield* optionalEndpoint(`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_ENDPOINT`);
151
+ if (specific !== "") return specific.href;
152
+ const baseUrl = yield* base;
153
+ if (baseUrl === "") return;
154
+ const url = new URL(baseUrl.href);
155
+ url.pathname = url.pathname.replace(TRAILING_SLASH_PATTERN, `/v1/${signal}`);
156
+ return url.href;
157
+ });
158
+ /**
159
+ * Builds the resource from `options`. `deployment.environment.name` comes from
160
+ * `options.environment` or `NODE_ENV`, and is left out when `OTEL_RESOURCE_ATTRIBUTES` already sets
161
+ * it, because explicit attributes would otherwise override the operator's value. Keys that have no
162
+ * value are left out so they never shadow the OTEL_* variables.
163
+ */
164
+ const resolveResource = Effect.fnUntraced(function* (options) {
165
+ const nodeEnv = yield* Config.String("NODE_ENV").pipe(Config.withDefault(""));
166
+ const environment = options.environment ?? (nodeEnv.trim() === "" ? void 0 : nodeEnv);
167
+ const operatorAttributes = yield* Config.Record(Schema.StringFromUriComponent, Schema.StringFromUriComponent, "OTEL_RESOURCE_ATTRIBUTES", {
168
+ trim: true,
169
+ keepEmptyValues: true
170
+ }).pipe(Config.withDefault(void 0));
171
+ const operatorSetEnvironment = operatorAttributes !== void 0 && Object.hasOwn(operatorAttributes, ENVIRONMENT_ATTRIBUTE);
172
+ const attributes = {};
173
+ if (environment !== void 0 && !operatorSetEnvironment) attributes[ENVIRONMENT_ATTRIBUTE] = environment;
174
+ const resource = {
175
+ serviceName: options.serviceName,
176
+ attributes
177
+ };
178
+ if (options.serviceVersion === void 0) return resource;
179
+ return {
180
+ ...resource,
181
+ serviceVersion: options.serviceVersion
182
+ };
183
+ });
184
+ /**
185
+ * Exports spans to `url` through a redacting tracer, or provides only the shared flusher when `url`
186
+ * is undefined. Effect's OTLP tracer renders a failed span's cause into its status message and
187
+ * `exception` events without going through a logger, so the tracer itself sanitizes exit causes and
188
+ * attributes.
189
+ */
190
+ const tracesLayer = (url, resource, settings, redaction) => {
191
+ if (url === void 0) return OtlpExporter.layerFlusher;
192
+ const tracer = OtlpTracer.make({
193
+ url,
194
+ resource,
195
+ ...settings
196
+ }).pipe(Effect.map(redaction.withTracerRedaction));
197
+ return Layer.effect(Tracer.Tracer, tracer).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
198
+ };
199
+ /**
200
+ * Exports metrics to `url`, or provides only the shared flusher when `url` is undefined.
201
+ */
202
+ const metricsLayer = (url, resource, settings) => {
203
+ if (url === void 0) return OtlpExporter.layerFlusher;
204
+ return OtlpMetrics.layer({
205
+ url,
206
+ resource,
207
+ ...settings
208
+ });
209
+ };
210
+ /**
211
+ * Exports log records to `url` through an OTLP logger added to the log export sinks, or provides
212
+ * only the shared flusher when `url` is undefined. Records arrive already redacted by the logger
213
+ * layer's fan-out logger. The sink stops taking records before its exporter flushes on shutdown.
214
+ */
215
+ const logsLayer = (url, resource, settings) => {
216
+ if (url === void 0) return OtlpExporter.layerFlusher;
217
+ return logExportSinkLayer(OtlpLogger.make({
218
+ url,
219
+ resource,
220
+ ...settings
221
+ })).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
222
+ };
223
+ /**
224
+ * Picks the OTLP body encoding. Protobuf unless `json` is asked for.
225
+ */
226
+ const serializationLayer = (serialization) => {
227
+ if (serialization === "json") return OtlpSerialization.layerJson;
228
+ return OtlpSerialization.layerProtobuf;
229
+ };
230
+ export { telemetryLayer };
@@ -0,0 +1,11 @@
1
+ import { TelemetryOptions } from "./telemetry.js";
2
+ import { Config, Layer } from "effect";
3
+ import { OtlpExporter } from "effect/observability";
4
+ import { HttpClient } from "effect/http";
5
+ /**
6
+ * `telemetryLayer` with `serviceName` as the only required option. It exports traces, metrics and
7
+ * logs whenever a collector is configured, provides the shared `OtlpExporter.Flusher`, and fails
8
+ * with `ConfigError` on an invalid endpoint or exporter value. See `telemetryLayer` for the
9
+ * variables it reads.
10
+ */
11
+ export declare const tracingLayer: (serviceName: string, options?: Omit<TelemetryOptions, 'serviceName'>) => Layer.Layer<OtlpExporter.Flusher, Config.ConfigError, HttpClient.HttpClient>;
@@ -0,0 +1,13 @@
1
+ import { telemetryLayer } from "./telemetry.js";
2
+ // src/otlp/tracing.ts
3
+ /**
4
+ * `telemetryLayer` with `serviceName` as the only required option. It exports traces, metrics and
5
+ * logs whenever a collector is configured, provides the shared `OtlpExporter.Flusher`, and fails
6
+ * with `ConfigError` on an invalid endpoint or exporter value. See `telemetryLayer` for the
7
+ * variables it reads.
8
+ */
9
+ const tracingLayer = (serviceName, options = {}) => telemetryLayer({
10
+ ...options,
11
+ serviceName
12
+ });
13
+ export { tracingLayer };
@@ -0,0 +1,92 @@
1
+ import { CIRCULAR_LOG_VALUE, TRUNCATED_LOG_VALUE, UNSERIALIZABLE_LOG_VALUE, redactWalkValue, startWalk, withVisible } from "./redact-walk.js";
2
+ import { Cause, Context } from "effect";
3
+ // src/redact-cause.ts
4
+ /**
5
+ * Returns an `Error`'s `message` as text Effect can render. A string is kept, a missing message
6
+ * becomes empty, and any other value (which Effect would print as raw JSON) is redacted like a log
7
+ * field and written as JSON.
8
+ */
9
+ const safeMessage = (walk, message, depth) => {
10
+ if (typeof message === "string") return message;
11
+ if (message === void 0) return "";
12
+ return JSON.stringify(redactWalkValue(walk, message, depth + 1));
13
+ };
14
+ /**
15
+ * Returns what a fail or die value may render as: a `Redactable` value's redacted form, then an
16
+ * `Error` copied as {@link RenderedError} with its `cause` chain made safe the same way (cycles
17
+ * cut, capped at {@link MAX_REDACT_DEPTH} levels), and any other value redacted like a log field.
18
+ * The text of an `Error` is kept as it is here; it is scrubbed once after rendering. Never throws.
19
+ */
20
+ const safeThrown = (walk, value, depth) => withVisible(value, (visible) => {
21
+ try {
22
+ if (!(visible instanceof Error)) return redactWalkValue(walk, visible, depth);
23
+ if (walk.ancestors.has(visible)) return CIRCULAR_LOG_VALUE;
24
+ if (depth > 8) return TRUNCATED_LOG_VALUE;
25
+ walk.ancestors.add(visible);
26
+ try {
27
+ const nested = visible.cause;
28
+ return {
29
+ name: visible.name,
30
+ message: safeMessage(walk, visible.message, depth),
31
+ stack: visible.stack,
32
+ cause: nested === void 0 ? void 0 : safeThrown(walk, nested, depth + 1)
33
+ };
34
+ } finally {
35
+ walk.ancestors.delete(visible);
36
+ }
37
+ } catch {
38
+ return UNSERIALIZABLE_LOG_VALUE;
39
+ }
40
+ });
41
+ /**
42
+ * Builds an `Error` without capturing a stack trace, which its caller replaces anyway; capturing
43
+ * one costs more than the rest of the stand-in. Where `Error.stackTraceLimit` cannot be set (a
44
+ * locked-down runtime), the trace is captured as usual.
45
+ */
46
+ const errorWithoutTrace = (message) => {
47
+ const limit = Error.stackTraceLimit;
48
+ try {
49
+ Error.stackTraceLimit = 0;
50
+ } catch {
51
+ return new Error(message);
52
+ }
53
+ try {
54
+ return new Error(message);
55
+ } finally {
56
+ Error.stackTraceLimit = limit;
57
+ }
58
+ };
59
+ /**
60
+ * Renders one fail or die value, with its value made safe (see {@link safeThrown}) and its stack
61
+ * frames, the way Effect renders it with `includeCauseInStack`, then scrubs that text once with
62
+ * `rules`. The result is an `Error` whose `stack`, `message` and `name` are scrubbed, so rendering
63
+ * it again (by a logger, or by `Cause.prettyErrors` in an OTLP exporter) prints the same text.
64
+ */
65
+ const renderScrubbed = (rules, reason, value) => {
66
+ const safe = safeThrown(startWalk(rules), value, 0);
67
+ const annotations = Cause.reasonAnnotations(reason);
68
+ const pretty = Cause.prettyErrors(Cause.fromReasons([Cause.makeDieReason(safe).annotate(annotations)]), { includeCauseInStack: true })[0];
69
+ const message = rules.redactText(pretty?.message ?? "");
70
+ const standIn = errorWithoutTrace(message);
71
+ standIn.name = rules.redactText(pretty?.name ?? "Error");
72
+ standIn.stack = rules.redactText(pretty?.stack ?? `${standIn.name}: ${message}`);
73
+ return standIn;
74
+ };
75
+ /**
76
+ * Returns `cause` with every fail and die value replaced by a stand-in `Error` that renders as the
77
+ * original reason did, after its value was made safe and the rendered text was scrubbed once with
78
+ * `rules` (see {@link renderScrubbed}). The stack frames are part of that text, so the stand-in
79
+ * drops the `Cause.StackTrace` annotation and keeps the others. Interrupt reasons and an empty
80
+ * cause are kept as they are. Sanitizing a sanitized cause gives the same rendering.
81
+ */
82
+ const sanitizeCauseWith = (rules, cause) => {
83
+ if (cause.reasons.length === 0) return cause;
84
+ return Cause.fromReasons(cause.reasons.map((reason) => {
85
+ if (Cause.isInterruptReason(reason)) return reason;
86
+ const value = Cause.isFailReason(reason) ? reason.error : reason.defect;
87
+ const standIn = renderScrubbed(rules, reason, value);
88
+ const annotations = Context.omit(Cause.StackTrace)(Cause.reasonAnnotations(reason));
89
+ return (Cause.isFailReason(reason) ? Cause.makeFailReason(standIn) : Cause.makeDieReason(standIn)).annotate(annotations);
90
+ }));
91
+ };
92
+ export { sanitizeCauseWith };
@@ -0,0 +1,19 @@
1
+ import { Redacted } from "effect";
2
+ /**
3
+ * Written in place of a value that cannot be read or copied: a `toJSON` or getter that throws, a
4
+ * revoked `Proxy`, or a key that cannot be turned into a string.
5
+ */
6
+ export declare const UNSERIALIZABLE_LOG_VALUE = "[Unserializable]";
7
+ /**
8
+ * A value after redaction: strings are masked, other primitives, plain `Date` and `Redacted` values
9
+ * pass through, a function has become {@link FUNCTION_LOG_VALUE}, and every other object has become
10
+ * a plain array or record whose members are redacted the same way. It holds no `Error`, `Map` or
11
+ * `Set`, and no object with `toJSON` other than a `Date`.
12
+ */
13
+ export type RedactedLogValue = string | number | boolean | bigint | symbol | null | undefined | Date | Redacted.Redacted<unknown> | ReadonlyArray<RedactedLogValue> | RedactedLogRecord;
14
+ /**
15
+ * Plain object built by the redaction walk: own string keys, each holding a redacted value.
16
+ */
17
+ export interface RedactedLogRecord {
18
+ readonly [key: string]: RedactedLogValue;
19
+ }
@@ -0,0 +1,290 @@
1
+ import { REDACTED_LOG_VALUE } from "./credentials.js";
2
+ import { Redactable, Redacted } from "effect";
3
+ // src/redact-walk.ts
4
+ /**
5
+ * Written in place of an object that is already being copied higher up the same path.
6
+ */
7
+ const CIRCULAR_LOG_VALUE = "[Circular]";
8
+ /**
9
+ * Written in place of a value nested deeper than {@link MAX_REDACT_DEPTH}, or reached after the
10
+ * walk used up {@link MAX_REDACT_NODES}.
11
+ */
12
+ const TRUNCATED_LOG_VALUE = "[Truncated]";
13
+ /**
14
+ * Written in place of a value that cannot be read or copied: a `toJSON` or getter that throws, a
15
+ * revoked `Proxy`, or a key that cannot be turned into a string.
16
+ */
17
+ const UNSERIALIZABLE_LOG_VALUE = "[Unserializable]";
18
+ /**
19
+ * Written in place of a function, so its source text is never written and a callable `Proxy` never
20
+ * reaches a formatter.
21
+ */
22
+ const FUNCTION_LOG_VALUE = "[Function]";
23
+ /**
24
+ * Most values one walk visits, masked values included. When it runs out, the rest of the array or
25
+ * record being copied is replaced by one {@link TRUNCATED_LOG_VALUE}, so the cost of one log call
26
+ * stays bounded whatever the value's shape.
27
+ */
28
+ const MAX_REDACT_NODES = 1e4;
29
+ /**
30
+ * Most items copied from one array or `Set`, and entries from one `Map`, `Error` or object. The
31
+ * rest is summarized by one marker (`[4000 more items]`).
32
+ */
33
+ const MAX_REDACT_ITEMS = 1e3;
34
+ /**
35
+ * The one key that a plain assignment would treat as the prototype instead of data.
36
+ */
37
+ const PROTO_KEY = "__proto__";
38
+ /**
39
+ * Key of the marker entry added to a record whose entries were cut at {@link MAX_REDACT_ITEMS}.
40
+ */
41
+ const MORE_ENTRIES_KEY = "[more]";
42
+ /**
43
+ * Most `Redactable` layers unwrapped in a row, in case a redacted form is itself `Redactable`.
44
+ */
45
+ const MAX_REDACTABLE_UNWRAPS = 3;
46
+ /**
47
+ * Prototype shared by every real `Redacted` value. An object that only carries the
48
+ * `~effect/Redacted` key (such as parsed JSON) does not have it.
49
+ */
50
+ const REDACTED_PROTOTYPE = Object.getPrototypeOf(Redacted.make(""));
51
+ /**
52
+ * Starts a walk with `rules`, nothing visited and a full node budget.
53
+ */
54
+ const startWalk = (rules) => ({
55
+ rules,
56
+ ancestors: /* @__PURE__ */ new Set(),
57
+ remainingNodes: MAX_REDACT_NODES
58
+ });
59
+ /**
60
+ * Calls `read` with what may be logged of `value`: the redacted form of a `Redactable` value
61
+ * (Effect's `[Redactable.symbolRedactable]` protocol, read in the current fiber's context),
62
+ * unwrapped up to {@link MAX_REDACTABLE_UNWRAPS} times, or `value` itself. A form that is still
63
+ * `Redactable` after that is passed as {@link TRUNCATED_LOG_VALUE}, and one that throws as
64
+ * {@link UNSERIALIZABLE_LOG_VALUE}, so `read` never sees a `Redactable` value. This is the one
65
+ * place every sink (the walk, causes, error summaries and log context) reveals a `Redactable`. It
66
+ * throws only what `read` throws.
67
+ */
68
+ const withVisible = (value, read) => {
69
+ let visible = value;
70
+ try {
71
+ for (let unwraps = 0; Redactable.isRedactable(visible); unwraps += 1) visible = unwraps >= MAX_REDACTABLE_UNWRAPS ? TRUNCATED_LOG_VALUE : Redactable.getRedacted(visible);
72
+ } catch {
73
+ visible = UNSERIALIZABLE_LOG_VALUE;
74
+ }
75
+ return read(visible);
76
+ };
77
+ /**
78
+ * Turns a `Map` key into the string written for it. A key whose `toString` throws becomes
79
+ * {@link UNSERIALIZABLE_LOG_VALUE}.
80
+ */
81
+ const mapKeyText = (key) => {
82
+ if (typeof key === "string") return key;
83
+ try {
84
+ return String(key);
85
+ } catch {
86
+ return UNSERIALIZABLE_LOG_VALUE;
87
+ }
88
+ };
89
+ /**
90
+ * Reads the own enumerable string-keyed properties of `value` one at a time, so a getter that
91
+ * throws hides only its own property (as {@link UNSERIALIZABLE_LOG_VALUE}).
92
+ */
93
+ const ownEntries = (value, limit = Number.POSITIVE_INFINITY) => Object.keys(value).slice(0, limit).map((key) => {
94
+ try {
95
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
96
+ return [key, descriptor?.get === void 0 ? descriptor?.value : descriptor.get.call(value)];
97
+ } catch {
98
+ return [key, UNSERIALIZABLE_LOG_VALUE];
99
+ }
100
+ });
101
+ /**
102
+ * Lists the properties copied from an Error: `name`, `message`, its own enumerable properties (up
103
+ * to {@link MAX_REDACT_ITEMS}) and its `cause`. The runtime defines `cause` as non-enumerable, so
104
+ * it is added explicitly.
105
+ */
106
+ const errorEntries = (error) => {
107
+ const entries = [
108
+ ["name", error.name],
109
+ ["message", error.message],
110
+ ...ownEntries(error, MAX_REDACT_ITEMS)
111
+ ];
112
+ if (Object.hasOwn(error, "cause") && !Object.keys(error).includes("cause")) entries.push(["cause", error.cause]);
113
+ return entries;
114
+ };
115
+ /**
116
+ * Tells whether `value` is a primitive other than a string, which the walk returns as it is.
117
+ */
118
+ const isPassThrough = (value) => typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "symbol" || value === void 0 || value === null;
119
+ /**
120
+ * Redacts `value` at `depth`. Never throws: an object that cannot be read becomes
121
+ * {@link UNSERIALIZABLE_LOG_VALUE}, and every value past the walk's node budget becomes
122
+ * {@link TRUNCATED_LOG_VALUE}.
123
+ */
124
+ const redactWalkValue = (walk, value, depth) => {
125
+ walk.remainingNodes -= 1;
126
+ if (walk.remainingNodes < 0) return TRUNCATED_LOG_VALUE;
127
+ if (typeof value === "string") return walk.rules.redactText(value);
128
+ if (isPassThrough(value)) return value;
129
+ try {
130
+ return redactObjectValue(walk, value, depth);
131
+ } catch {
132
+ return UNSERIALIZABLE_LOG_VALUE;
133
+ }
134
+ };
135
+ /**
136
+ * Returns `[<type> <n> bytes]` for binary data (an `ArrayBuffer`, `SharedArrayBuffer`, typed array,
137
+ * `DataView` or `Buffer`), or `undefined` for anything else. Binary data is summarized rather than
138
+ * copied, because copying it costs one entry per byte.
139
+ */
140
+ const binarySummary = (value) => {
141
+ if (ArrayBuffer.isView(value)) return `[${binaryTag(value)} ${String(value.byteLength)} bytes]`;
142
+ if (value instanceof ArrayBuffer || typeof SharedArrayBuffer === "function" && value instanceof SharedArrayBuffer) return `[${binaryTag(value)} ${String(value.byteLength)} bytes]`;
143
+ };
144
+ /**
145
+ * Returns the built-in type name of binary data (`Uint8Array`, `DataView`, `ArrayBuffer`), which a
146
+ * subclass such as Node's `Buffer` reports too.
147
+ */
148
+ const binaryTag = (value) => Object.prototype.toString.call(value).slice(8, -1);
149
+ /**
150
+ * Redacts one object or function: a `Redactable` value is replaced by its redacted form (see
151
+ * {@link withVisible}), then `Redacted` values, functions ({@link FUNCTION_LOG_VALUE}), `Date` and
152
+ * binary values, then cycles and depth, then the rule for its kind. A `Date` subclass is copied to
153
+ * a plain `Date`, so its own `toJSON` or `Symbol.toPrimitive` never runs in a formatter. Any step
154
+ * may throw (a revoked `Proxy` throws on every check); the caller turns that into
155
+ * {@link UNSERIALIZABLE_LOG_VALUE}.
156
+ */
157
+ const redactObjectValue = (walk, value, depth) => {
158
+ if (Redactable.isRedactable(value)) return withVisible(value, (visible) => redactWalkValue(walk, visible, depth + 1));
159
+ if (Redacted.isRedacted(value)) return Object.getPrototypeOf(value) === REDACTED_PROTOTYPE ? value : REDACTED_LOG_VALUE;
160
+ if (typeof value === "function") return FUNCTION_LOG_VALUE;
161
+ if (value instanceof Date) return new Date(Date.prototype.getTime.call(value));
162
+ const binary = binarySummary(value);
163
+ if (binary !== void 0) return binary;
164
+ if (walk.ancestors.has(value)) return CIRCULAR_LOG_VALUE;
165
+ if (depth > 8) return TRUNCATED_LOG_VALUE;
166
+ walk.ancestors.add(value);
167
+ try {
168
+ return redactObject(walk, value, depth);
169
+ } finally {
170
+ walk.ancestors.delete(value);
171
+ }
172
+ };
173
+ /**
174
+ * Copies up to {@link MAX_REDACT_ITEMS} items of an array or `Set`, then a `[n more items]` marker.
175
+ * Items are redacted by their own content; a list is never read as name/value pairs. When the
176
+ * walk's budget runs out, the rest of the list becomes one {@link TRUNCATED_LOG_VALUE}.
177
+ */
178
+ const redactItems = (walk, items, total, depth) => {
179
+ const copied = [];
180
+ for (let index = 0; index < items.length; index += 1) {
181
+ if (walk.remainingNodes <= 0) {
182
+ copied.push(TRUNCATED_LOG_VALUE);
183
+ return copied;
184
+ }
185
+ copied.push(redactWalkValue(walk, items[index], depth + 1));
186
+ }
187
+ if (total > items.length) copied.push(`[${String(total - items.length)} more items]`);
188
+ return copied;
189
+ };
190
+ /**
191
+ * Returns the first {@link MAX_REDACT_ITEMS} values of `iterable` without reading the rest.
192
+ */
193
+ const takeItems = (iterable) => {
194
+ const taken = [];
195
+ for (const item of iterable) {
196
+ if (taken.length >= 1e3) break;
197
+ taken.push(item);
198
+ }
199
+ return taken;
200
+ };
201
+ /**
202
+ * Copies one object that is already on the ancestor path, picking the rule for its kind.
203
+ */
204
+ const redactObject = (walk, value, depth) => {
205
+ if (Array.isArray(value)) {
206
+ const items = value;
207
+ return redactItems(walk, items.slice(0, MAX_REDACT_ITEMS), items.length, depth);
208
+ }
209
+ if (value instanceof Error) return redactWalkEntries(walk, errorEntries(value), depth);
210
+ if (value instanceof Map) {
211
+ const entries = takeItems(value).map(([key, item]) => [mapKeyText(key), item]);
212
+ return withMoreEntries(redactWalkEntries(walk, entries, depth), value.size - entries.length);
213
+ }
214
+ if (value instanceof Set) return redactItems(walk, takeItems(value), value.size, depth);
215
+ const fromJson = redactToJson(walk, value, depth);
216
+ if (fromJson !== void 0) return fromJson.value;
217
+ return redactWalkRecord(walk, value, depth);
218
+ };
219
+ /**
220
+ * Redacts the first {@link MAX_REDACT_ITEMS} own entries of `record` and marks the rest with a
221
+ * `[more]` entry. Unlike {@link redactWalkValue}, it never calls the record's `toJSON`, so it suits
222
+ * a value that is always a plain record, such as the log annotations.
223
+ */
224
+ const redactWalkRecord = (walk, record, depth) => withMoreEntries(redactWalkEntries(walk, ownEntries(record, MAX_REDACT_ITEMS), depth), Object.keys(record).length - MAX_REDACT_ITEMS);
225
+ /**
226
+ * Adds a `[more]: '[n more entries]'` marker to `record` when `more` entries were left out.
227
+ */
228
+ const withMoreEntries = (record, more) => more > 0 ? {
229
+ ...record,
230
+ [MORE_ENTRIES_KEY]: `[${String(more)} more entries]`
231
+ } : record;
232
+ /**
233
+ * Returns the redacted result of `value.toJSON()`, boxed so an `undefined` result still counts.
234
+ * Returns `undefined` when there is no `toJSON` or it returns `value` itself.
235
+ */
236
+ const redactToJson = (walk, value, depth) => {
237
+ const toJson = value.toJSON;
238
+ if (typeof toJson !== "function") return;
239
+ let json;
240
+ try {
241
+ json = toJson.call(value);
242
+ } catch {
243
+ return { value: UNSERIALIZABLE_LOG_VALUE };
244
+ }
245
+ if (json === value) return;
246
+ return { value: redactWalkValue(walk, json, depth + 1) };
247
+ };
248
+ /**
249
+ * Builds a plain object from `entries`, judging each value by its key (see
250
+ * {@link redactWalkEntry}). Keys are written as they are, as own data properties, so a `__proto__`
251
+ * key stays data. When the walk's budget runs out, the remaining entries are left out and a
252
+ * `[more]: '[Truncated]'` entry marks the cut.
253
+ */
254
+ const redactWalkEntries = (walk, entries, depth) => {
255
+ const record = {};
256
+ for (const [key, item] of entries) {
257
+ if (walk.remainingNodes <= 0) {
258
+ writeEntry(record, MORE_ENTRIES_KEY, TRUNCATED_LOG_VALUE);
259
+ return record;
260
+ }
261
+ writeEntry(record, key, redactWalkEntry(walk, key, item, depth));
262
+ }
263
+ return record;
264
+ };
265
+ /**
266
+ * Writes `value` under `key` as an own data property, so a `__proto__` key stays data.
267
+ */
268
+ const writeEntry = (record, key, value) => {
269
+ if (key === PROTO_KEY) Object.defineProperty(record, key, {
270
+ value,
271
+ enumerable: true,
272
+ writable: true,
273
+ configurable: true
274
+ });
275
+ else record[key] = value;
276
+ };
277
+ /**
278
+ * Redacts one property value: written as {@link REDACTED_LOG_VALUE} when the rules mask it under
279
+ * `key` (see `CredentialRules.masksEntry`), otherwise redacted by its own content. A masked value
280
+ * counts against the walk's budget like a copied one, so a graph of shared records full of
281
+ * sensitive keys is bounded too.
282
+ */
283
+ const redactWalkEntry = (walk, key, item, depth) => {
284
+ if (walk.rules.masksEntry(key, item)) {
285
+ walk.remainingNodes -= 1;
286
+ return walk.remainingNodes < 0 ? TRUNCATED_LOG_VALUE : REDACTED_LOG_VALUE;
287
+ }
288
+ return redactWalkValue(walk, item, depth + 1);
289
+ };
290
+ export { CIRCULAR_LOG_VALUE, FUNCTION_LOG_VALUE, MAX_REDACT_ITEMS, MAX_REDACT_NODES, TRUNCATED_LOG_VALUE, UNSERIALIZABLE_LOG_VALUE, ownEntries, redactWalkEntries, redactWalkEntry, redactWalkRecord, redactWalkValue, startWalk, withVisible };