@momentumcms/plugins-otel 0.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## 0.1.1 (2026-02-16)
2
+
3
+ This was a version bump only for plugins-otel to align it with other projects, there were no code changes.
4
+
5
+ ## 0.1.0 (2026-02-16)
6
+
7
+ This was a version bump only for plugins-otel to align it with other projects, there were no code changes.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present Momentum CMS Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.cjs ADDED
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // libs/plugins/otel/src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ otelPlugin: () => otelPlugin
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+
27
+ // libs/plugins/otel/src/lib/otel-plugin.ts
28
+ var import_api = require("@opentelemetry/api");
29
+
30
+ // libs/logger/src/lib/log-level.ts
31
+ var LOG_LEVEL_VALUES = {
32
+ debug: 0,
33
+ info: 1,
34
+ warn: 2,
35
+ error: 3,
36
+ fatal: 4,
37
+ silent: 5
38
+ };
39
+ function shouldLog(messageLevel, configuredLevel) {
40
+ return LOG_LEVEL_VALUES[messageLevel] >= LOG_LEVEL_VALUES[configuredLevel];
41
+ }
42
+
43
+ // libs/logger/src/lib/ansi-colors.ts
44
+ var ANSI = {
45
+ reset: "\x1B[0m",
46
+ bold: "\x1B[1m",
47
+ dim: "\x1B[2m",
48
+ // Foreground colors
49
+ red: "\x1B[31m",
50
+ green: "\x1B[32m",
51
+ yellow: "\x1B[33m",
52
+ blue: "\x1B[34m",
53
+ magenta: "\x1B[35m",
54
+ cyan: "\x1B[36m",
55
+ white: "\x1B[37m",
56
+ gray: "\x1B[90m",
57
+ // Background colors
58
+ bgRed: "\x1B[41m",
59
+ bgYellow: "\x1B[43m"
60
+ };
61
+ function colorize(text, ...codes) {
62
+ if (codes.length === 0)
63
+ return text;
64
+ return `${codes.join("")}${text}${ANSI.reset}`;
65
+ }
66
+ function supportsColor() {
67
+ if (process.env["FORCE_COLOR"] === "1")
68
+ return true;
69
+ if (process.env["NO_COLOR"] !== void 0)
70
+ return false;
71
+ if (process.env["TERM"] === "dumb")
72
+ return false;
73
+ return process.stdout.isTTY === true;
74
+ }
75
+
76
+ // libs/logger/src/lib/formatters.ts
77
+ var LEVEL_COLORS = {
78
+ debug: [ANSI.dim, ANSI.gray],
79
+ info: [ANSI.cyan],
80
+ warn: [ANSI.yellow],
81
+ error: [ANSI.red],
82
+ fatal: [ANSI.bold, ANSI.white, ANSI.bgRed]
83
+ };
84
+ function padLevel(level) {
85
+ return level.toUpperCase().padEnd(5);
86
+ }
87
+ function formatTimestamp(date) {
88
+ const y = date.getFullYear();
89
+ const mo = String(date.getMonth() + 1).padStart(2, "0");
90
+ const d = String(date.getDate()).padStart(2, "0");
91
+ const h = String(date.getHours()).padStart(2, "0");
92
+ const mi = String(date.getMinutes()).padStart(2, "0");
93
+ const s = String(date.getSeconds()).padStart(2, "0");
94
+ const ms = String(date.getMilliseconds()).padStart(3, "0");
95
+ return `${y}-${mo}-${d} ${h}:${mi}:${s}.${ms}`;
96
+ }
97
+ function formatData(data) {
98
+ const entries = Object.entries(data);
99
+ if (entries.length === 0)
100
+ return "";
101
+ return " " + entries.map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
102
+ }
103
+ function prettyFormatter(entry) {
104
+ const useColor = supportsColor();
105
+ const level = entry.level;
106
+ const ts = formatTimestamp(entry.timestamp);
107
+ const levelStr = padLevel(entry.level);
108
+ const ctx = `[${entry.context}]`;
109
+ const msg = entry.message;
110
+ const enrichmentStr = entry.enrichments ? formatData(entry.enrichments) : "";
111
+ const dataStr = entry.data ? formatData(entry.data) : "";
112
+ const extra = `${enrichmentStr}${dataStr}`;
113
+ if (useColor) {
114
+ const colors = LEVEL_COLORS[level];
115
+ const coloredLevel = colorize(levelStr, ...colors);
116
+ const coloredCtx = colorize(ctx, ANSI.magenta);
117
+ const coloredTs = colorize(ts, ANSI.gray);
118
+ return `${coloredTs} ${coloredLevel} ${coloredCtx} ${msg}${extra}
119
+ `;
120
+ }
121
+ return `${ts} ${levelStr} ${ctx} ${msg}${extra}
122
+ `;
123
+ }
124
+ function jsonFormatter(entry) {
125
+ const output = {
126
+ timestamp: entry.timestamp.toISOString(),
127
+ level: entry.level,
128
+ context: entry.context,
129
+ message: entry.message
130
+ };
131
+ if (entry.enrichments && Object.keys(entry.enrichments).length > 0) {
132
+ Object.assign(output, entry.enrichments);
133
+ }
134
+ if (entry.data && Object.keys(entry.data).length > 0) {
135
+ output["data"] = entry.data;
136
+ }
137
+ return JSON.stringify(output) + "\n";
138
+ }
139
+
140
+ // libs/logger/src/lib/logger-config.types.ts
141
+ function resolveLoggingConfig(config) {
142
+ return {
143
+ level: config?.level ?? "info",
144
+ format: config?.format ?? "pretty",
145
+ timestamps: config?.timestamps ?? true,
146
+ output: config?.output ?? ((msg) => {
147
+ process.stdout.write(msg);
148
+ }),
149
+ errorOutput: config?.errorOutput ?? ((msg) => {
150
+ process.stderr.write(msg);
151
+ })
152
+ };
153
+ }
154
+
155
+ // libs/logger/src/lib/logger.ts
156
+ var ERROR_LEVELS = /* @__PURE__ */ new Set(["warn", "error", "fatal"]);
157
+ var MomentumLogger = class _MomentumLogger {
158
+ static {
159
+ this.enrichers = [];
160
+ }
161
+ constructor(context, config) {
162
+ this.context = context;
163
+ this.config = isResolvedConfig(config) ? config : resolveLoggingConfig(config);
164
+ this.formatter = this.config.format === "json" ? jsonFormatter : prettyFormatter;
165
+ }
166
+ debug(message, data) {
167
+ this.log("debug", message, data);
168
+ }
169
+ info(message, data) {
170
+ this.log("info", message, data);
171
+ }
172
+ warn(message, data) {
173
+ this.log("warn", message, data);
174
+ }
175
+ error(message, data) {
176
+ this.log("error", message, data);
177
+ }
178
+ fatal(message, data) {
179
+ this.log("fatal", message, data);
180
+ }
181
+ /**
182
+ * Creates a child logger with a sub-context.
183
+ * e.g., `Momentum:DB` → `Momentum:DB:Migrate`
184
+ */
185
+ child(subContext) {
186
+ return new _MomentumLogger(`${this.context}:${subContext}`, this.config);
187
+ }
188
+ /**
189
+ * Registers a global enricher that adds extra fields to all log entries.
190
+ */
191
+ static registerEnricher(enricher) {
192
+ _MomentumLogger.enrichers.push(enricher);
193
+ }
194
+ /**
195
+ * Removes a previously registered enricher.
196
+ */
197
+ static removeEnricher(enricher) {
198
+ const index = _MomentumLogger.enrichers.indexOf(enricher);
199
+ if (index >= 0) {
200
+ _MomentumLogger.enrichers.splice(index, 1);
201
+ }
202
+ }
203
+ /**
204
+ * Clears all registered enrichers. Primarily for testing.
205
+ */
206
+ static clearEnrichers() {
207
+ _MomentumLogger.enrichers.length = 0;
208
+ }
209
+ log(level, message, data) {
210
+ if (!shouldLog(level, this.config.level))
211
+ return;
212
+ const enrichments = this.collectEnrichments();
213
+ const entry = {
214
+ timestamp: /* @__PURE__ */ new Date(),
215
+ level,
216
+ context: this.context,
217
+ message,
218
+ data,
219
+ enrichments: Object.keys(enrichments).length > 0 ? enrichments : void 0
220
+ };
221
+ const formatted = this.formatter(entry);
222
+ if (ERROR_LEVELS.has(level)) {
223
+ this.config.errorOutput(formatted);
224
+ } else {
225
+ this.config.output(formatted);
226
+ }
227
+ }
228
+ collectEnrichments() {
229
+ const result = {};
230
+ for (const enricher of _MomentumLogger.enrichers) {
231
+ Object.assign(result, enricher.enrich());
232
+ }
233
+ return result;
234
+ }
235
+ };
236
+ function isResolvedConfig(config) {
237
+ if (!config)
238
+ return false;
239
+ return typeof config.level === "string" && typeof config.format === "string" && typeof config.timestamps === "boolean" && // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- type guard narrows union
240
+ typeof config.output === "function" && // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- type guard narrows union
241
+ typeof config.errorOutput === "function";
242
+ }
243
+
244
+ // libs/plugins/otel/src/lib/otel-plugin.ts
245
+ var OtelLogEnricher = class {
246
+ enrich() {
247
+ const span = import_api.trace.getActiveSpan();
248
+ if (!span) {
249
+ return {};
250
+ }
251
+ const spanContext = span.spanContext();
252
+ return {
253
+ traceId: spanContext.traceId,
254
+ spanId: spanContext.spanId
255
+ };
256
+ }
257
+ };
258
+ function otelPlugin(config = {}) {
259
+ const { serviceName = "momentum-cms", enrichLogs = true, attributes = {}, operations } = config;
260
+ let tracer;
261
+ let enricher = null;
262
+ return {
263
+ name: "otel",
264
+ onInit({ collections, logger }) {
265
+ tracer = import_api.trace.getTracer(serviceName);
266
+ logger.info(`OpenTelemetry tracing enabled (service: ${serviceName})`);
267
+ if (enrichLogs) {
268
+ enricher = new OtelLogEnricher();
269
+ MomentumLogger.registerEnricher(enricher);
270
+ logger.info("Log enricher registered for trace/span IDs");
271
+ }
272
+ for (const collection of collections) {
273
+ injectTracingHooks(collection, tracer, attributes, operations);
274
+ }
275
+ logger.info(`Tracing hooks injected into ${collections.length} collections`);
276
+ },
277
+ onShutdown({ logger }) {
278
+ if (enricher) {
279
+ MomentumLogger.removeEnricher(enricher);
280
+ enricher = null;
281
+ }
282
+ logger.info("OpenTelemetry plugin shut down");
283
+ }
284
+ };
285
+ }
286
+ function injectTracingHooks(collection, tracer, attributes, operationFilter) {
287
+ collection.hooks = collection.hooks ?? {};
288
+ const beforeChangeHook = (args) => {
289
+ const operation = args.operation ?? "create";
290
+ if (operationFilter && !operationFilter.includes(operation)) {
291
+ return args.data;
292
+ }
293
+ const span = tracer.startSpan(`${collection.slug}.${operation}`, {
294
+ attributes: {
295
+ "momentum.collection": collection.slug,
296
+ "momentum.operation": operation,
297
+ ...attributes
298
+ }
299
+ });
300
+ if (args.data) {
301
+ args.data["__otelSpan"] = span;
302
+ }
303
+ return args.data;
304
+ };
305
+ const afterChangeHook = (args) => {
306
+ const doc = args.doc ?? args.data ?? {};
307
+ const span = doc["__otelSpan"];
308
+ if (span && typeof span === "object" && "end" in span) {
309
+ const typedSpan = span;
310
+ typedSpan.setStatus({ code: import_api.SpanStatusCode.OK });
311
+ typedSpan.end();
312
+ }
313
+ if (args.doc) {
314
+ delete args.doc["__otelSpan"];
315
+ }
316
+ };
317
+ const beforeDeleteHook = (args) => {
318
+ if (operationFilter && !operationFilter.includes("delete")) {
319
+ return;
320
+ }
321
+ const span = tracer.startSpan(`${collection.slug}.delete`, {
322
+ attributes: {
323
+ "momentum.collection": collection.slug,
324
+ "momentum.operation": "delete",
325
+ "momentum.documentId": args.doc?.["id"] ? String(args.doc["id"]) : "unknown",
326
+ ...attributes
327
+ }
328
+ });
329
+ if (args.doc) {
330
+ args.doc["__otelSpan"] = span;
331
+ }
332
+ };
333
+ const afterDeleteHook = (args) => {
334
+ const doc = args.doc ?? {};
335
+ const span = doc["__otelSpan"];
336
+ if (span && typeof span === "object" && "end" in span) {
337
+ const typedSpan = span;
338
+ typedSpan.setStatus({ code: import_api.SpanStatusCode.OK });
339
+ typedSpan.end();
340
+ }
341
+ };
342
+ const existingBeforeChange = collection.hooks.beforeChange ?? [];
343
+ collection.hooks.beforeChange = [beforeChangeHook, ...existingBeforeChange];
344
+ const existingAfterChange = collection.hooks.afterChange ?? [];
345
+ collection.hooks.afterChange = [...existingAfterChange, afterChangeHook];
346
+ const existingBeforeDelete = collection.hooks.beforeDelete ?? [];
347
+ collection.hooks.beforeDelete = [beforeDeleteHook, ...existingBeforeDelete];
348
+ const existingAfterDelete = collection.hooks.afterDelete ?? [];
349
+ collection.hooks.afterDelete = [...existingAfterDelete, afterDeleteHook];
350
+ }
351
+ // Annotate the CommonJS export names for ESM import in node:
352
+ 0 && (module.exports = {
353
+ otelPlugin
354
+ });
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@momentumcms/plugins-otel",
3
+ "version": "0.0.1",
4
+ "description": "OpenTelemetry observability plugin for Momentum CMS",
5
+ "license": "MIT",
6
+ "author": "Momentum CMS Contributors",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/momentum-cms/momentum-cms.git",
10
+ "directory": "libs/plugins/otel"
11
+ },
12
+ "homepage": "https://github.com/momentum-cms/momentum-cms#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/momentum-cms/momentum-cms/issues"
15
+ },
16
+ "keywords": [
17
+ "cms",
18
+ "momentum-cms",
19
+ "opentelemetry",
20
+ "observability",
21
+ "tracing",
22
+ "metrics"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "type": "commonjs",
28
+ "main": "./index.cjs",
29
+ "types": "./src/index.d.ts",
30
+ "peerDependencies": {
31
+ "@momentumcms/core": "0.0.1",
32
+ "@momentumcms/logger": "0.0.1",
33
+ "@momentumcms/plugins-core": "0.0.1",
34
+ "@opentelemetry/api": "^1.0.0"
35
+ },
36
+ "dependencies": {}
37
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { otelPlugin } from './lib/otel-plugin';
2
+ export type { OtelPluginConfig } from './lib/otel-plugin.types';
@@ -0,0 +1,30 @@
1
+ /**
2
+ * OpenTelemetry Tracing Plugin
3
+ *
4
+ * Injects tracing spans into collection hooks and optionally
5
+ * enriches log entries with trace/span IDs.
6
+ *
7
+ * Requires @opentelemetry/api as a peer dependency.
8
+ * The user is responsible for setting up the OTel SDK (exporters, etc.).
9
+ * This plugin only creates spans using the OTel API.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { otelPlugin } from '@momentumcms/plugins/otel';
14
+ *
15
+ * export default defineMomentumConfig({
16
+ * plugins: [
17
+ * otelPlugin({ serviceName: 'my-cms' }),
18
+ * ],
19
+ * });
20
+ * ```
21
+ */
22
+ import type { MomentumPlugin } from '@momentumcms/plugins/core';
23
+ import type { OtelPluginConfig } from './otel-plugin.types';
24
+ /**
25
+ * Creates an OpenTelemetry tracing plugin.
26
+ *
27
+ * @param config - Plugin configuration
28
+ * @returns MomentumPlugin instance
29
+ */
30
+ export declare function otelPlugin(config?: OtelPluginConfig): MomentumPlugin;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * OTel Plugin Configuration Types
3
+ */
4
+ /**
5
+ * Configuration for the OpenTelemetry plugin.
6
+ */
7
+ export interface OtelPluginConfig {
8
+ /** Service name for traces. @default 'momentum-cms' */
9
+ serviceName?: string;
10
+ /** Whether to enrich logs with trace/span IDs. @default true */
11
+ enrichLogs?: boolean;
12
+ /** Custom attributes to add to all spans */
13
+ attributes?: Record<string, string>;
14
+ /** Collection operations to trace. @default all */
15
+ operations?: Array<'create' | 'update' | 'delete' | 'find'>;
16
+ }