@contractspec/lib.observability 1.56.0 → 1.57.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/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # @contractspec/lib.observability
2
2
 
3
+ ## 1.57.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8ecf3c1: Add typed PostHog read APIs and readers across contracts, providers, metering, evolution, analytics, observability, and examples.
8
+ - ad9d10a: feat: improve posthog integration
9
+ - 11a5a05: feat: improve product intent
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [8ecf3c1]
14
+ - Updated dependencies [47c48c2]
15
+ - Updated dependencies [a119963]
16
+ - Updated dependencies [4651e06]
17
+ - Updated dependencies [ad9d10a]
18
+ - Updated dependencies [11a5a05]
19
+ - @contractspec/lib.contracts@1.57.0
20
+ - @contractspec/lib.lifecycle@1.57.0
21
+
22
+ ## 1.56.1
23
+
24
+ ### Patch Changes
25
+
26
+ - fix: improve publish config
27
+ - Updated dependencies
28
+ - @contractspec/lib.lifecycle@1.56.1
29
+
3
30
  ## 1.56.0
4
31
 
5
32
  ### Minor Changes
package/dist/index.d.mts CHANGED
@@ -10,4 +10,6 @@ import { TracingMiddlewareOptions, createTracingMiddleware } from "./tracing/mid
10
10
  import { IntentDetector, IntentSignal, IntentSignalType } from "./intent/detector.mjs";
11
11
  import { EvolutionPipeline, EvolutionPipelineEvent, EvolutionPipelineOptions } from "./pipeline/evolution-pipeline.mjs";
12
12
  import { LifecycleKpiPipeline, LifecycleKpiPipelineOptions, LifecyclePipelineEvent } from "./pipeline/lifecycle-pipeline.mjs";
13
- export { AlertManager, AnomalyDetector, type AnomalySignal, type AnomalyThresholds, BaselineCalculator, EvolutionPipeline, type EvolutionPipelineEvent, type EvolutionPipelineOptions, IntentAggregator, type IntentAggregatorSnapshot, IntentDetector, type IntentSignal, type IntentSignalType, LifecycleKpiPipeline, type LifecycleKpiPipelineOptions, type LifecyclePipelineEvent, type LogEntry, type LogLevel, Logger, type RootCauseAnalysis, RootCauseAnalyzer, type TelemetrySample, type TracingMiddlewareOptions, createCounter, createHistogram, createTracingMiddleware, createUpDownCounter, getMeter, getTracer, logger, standardMetrics, traceAsync, traceSync };
13
+ import { PosthogTelemetryProvider, PosthogTelemetryProviderOptions } from "./telemetry/posthog-telemetry.mjs";
14
+ import { PosthogBaselineReader } from "./telemetry/posthog-baseline-reader.mjs";
15
+ export { AlertManager, AnomalyDetector, type AnomalySignal, type AnomalyThresholds, BaselineCalculator, EvolutionPipeline, type EvolutionPipelineEvent, type EvolutionPipelineOptions, IntentAggregator, type IntentAggregatorSnapshot, IntentDetector, type IntentSignal, type IntentSignalType, LifecycleKpiPipeline, type LifecycleKpiPipelineOptions, type LifecyclePipelineEvent, type LogEntry, type LogLevel, Logger, PosthogBaselineReader, PosthogTelemetryProvider, type PosthogTelemetryProviderOptions, type RootCauseAnalysis, RootCauseAnalyzer, type TelemetrySample, type TracingMiddlewareOptions, createCounter, createHistogram, createTracingMiddleware, createUpDownCounter, getMeter, getTracer, logger, standardMetrics, traceAsync, traceSync };
package/dist/index.mjs CHANGED
@@ -6,9 +6,11 @@ import { IntentAggregator } from "./intent/aggregator.mjs";
6
6
  import { IntentDetector } from "./intent/detector.mjs";
7
7
  import { EvolutionPipeline } from "./pipeline/evolution-pipeline.mjs";
8
8
  import { LifecycleKpiPipeline } from "./pipeline/lifecycle-pipeline.mjs";
9
+ import { PosthogTelemetryProvider } from "./telemetry/posthog-telemetry.mjs";
10
+ import { PosthogBaselineReader } from "./telemetry/posthog-baseline-reader.mjs";
9
11
  import { BaselineCalculator } from "./anomaly/baseline-calculator.mjs";
10
12
  import { AnomalyDetector } from "./anomaly/anomaly-detector.mjs";
11
13
  import { RootCauseAnalyzer } from "./anomaly/root-cause-analyzer.mjs";
12
14
  import { AlertManager } from "./anomaly/alert-manager.mjs";
13
15
 
14
- export { AlertManager, AnomalyDetector, BaselineCalculator, EvolutionPipeline, IntentAggregator, IntentDetector, LifecycleKpiPipeline, Logger, RootCauseAnalyzer, createCounter, createHistogram, createTracingMiddleware, createUpDownCounter, getMeter, getTracer, logger, standardMetrics, traceAsync, traceSync };
16
+ export { AlertManager, AnomalyDetector, BaselineCalculator, EvolutionPipeline, IntentAggregator, IntentDetector, LifecycleKpiPipeline, Logger, PosthogBaselineReader, PosthogTelemetryProvider, RootCauseAnalyzer, createCounter, createHistogram, createTracingMiddleware, createUpDownCounter, getMeter, getTracer, logger, standardMetrics, traceAsync, traceSync };
@@ -0,0 +1,31 @@
1
+ import { AggregatedOperationMetrics, OperationSequence, TelemetrySample } from "../intent/aggregator.mjs";
2
+ import { AnalyticsReader, DateRangeInput } from "@contractspec/lib.contracts/integrations/providers/analytics";
3
+
4
+ //#region src/telemetry/posthog-baseline-reader.d.ts
5
+ interface ReadTelemetrySamplesInput {
6
+ operations?: {
7
+ name: string;
8
+ version: string;
9
+ }[];
10
+ dateRange?: DateRangeInput;
11
+ limit?: number;
12
+ }
13
+ interface PosthogBaselineReaderOptions {
14
+ eventPrefix?: string;
15
+ }
16
+ declare class PosthogBaselineReader {
17
+ private readonly reader;
18
+ private readonly eventPrefix;
19
+ constructor(reader: AnalyticsReader, options?: PosthogBaselineReaderOptions);
20
+ readSamples(input: ReadTelemetrySamplesInput): Promise<TelemetrySample[]>;
21
+ readAggregatedMetrics(operation: {
22
+ name: string;
23
+ version: string;
24
+ }, windowDays?: number): Promise<AggregatedOperationMetrics | null>;
25
+ readOperationSequences(dateRange?: DateRangeInput): Promise<OperationSequence[]>;
26
+ private readTopErrors;
27
+ private queryHogQL;
28
+ }
29
+ //#endregion
30
+ export { PosthogBaselineReader, PosthogBaselineReaderOptions, ReadTelemetrySamplesInput };
31
+ //# sourceMappingURL=posthog-baseline-reader.d.mts.map
@@ -0,0 +1,266 @@
1
+ //#region src/telemetry/posthog-baseline-reader.ts
2
+ var PosthogBaselineReader = class {
3
+ reader;
4
+ eventPrefix;
5
+ constructor(reader, options = {}) {
6
+ this.reader = reader;
7
+ this.eventPrefix = options.eventPrefix ?? "observability";
8
+ }
9
+ async readSamples(input) {
10
+ return mapTelemetrySamples(await this.queryHogQL({
11
+ query: [
12
+ "select",
13
+ " properties.operation as operationName,",
14
+ " properties.version as version,",
15
+ " properties.durationMs as durationMs,",
16
+ " properties.success as success,",
17
+ " properties.errorCode as errorCode,",
18
+ " properties.tenantId as tenantId,",
19
+ " properties.traceId as traceId,",
20
+ " properties.metadata as metadata,",
21
+ " distinct_id as actorId,",
22
+ " timestamp as timestamp",
23
+ "from events",
24
+ `where ${buildOperationWhereClause(this.eventPrefix, input)}`,
25
+ "order by timestamp desc",
26
+ `limit ${input.limit ?? 1e3}`
27
+ ].join("\n"),
28
+ values: buildOperationValues(input)
29
+ }));
30
+ }
31
+ async readAggregatedMetrics(operation, windowDays = 7) {
32
+ const dateRange = buildWindowRange(windowDays);
33
+ const stats = mapAggregatedMetrics(await this.queryHogQL({
34
+ query: [
35
+ "select",
36
+ " count() as totalCalls,",
37
+ " avg(properties.durationMs) as averageLatencyMs,",
38
+ " quantile(0.95)(properties.durationMs) as p95LatencyMs,",
39
+ " quantile(0.99)(properties.durationMs) as p99LatencyMs,",
40
+ " max(properties.durationMs) as maxLatencyMs,",
41
+ " sum(if(properties.success = 1, 1, 0)) as successCount,",
42
+ " sum(if(properties.success = 0, 1, 0)) as errorCount",
43
+ "from events",
44
+ `where ${buildOperationWhereClause(this.eventPrefix, {
45
+ operations: [operation],
46
+ dateRange
47
+ })}`
48
+ ].join("\n"),
49
+ values: buildOperationValues({
50
+ operations: [operation],
51
+ dateRange
52
+ })
53
+ }), operation, dateRange);
54
+ if (!stats) return null;
55
+ const topErrors = await this.readTopErrors(operation, dateRange);
56
+ return {
57
+ ...stats,
58
+ topErrors
59
+ };
60
+ }
61
+ async readOperationSequences(dateRange) {
62
+ return mergeSequences(await this.queryHogQL({
63
+ query: [
64
+ "select",
65
+ " properties.sequences as sequences",
66
+ "from events",
67
+ `where event = {eventName}`,
68
+ dateRange?.from ? "and timestamp >= {dateFrom}" : "",
69
+ dateRange?.to ? "and timestamp < {dateTo}" : "",
70
+ "order by timestamp desc",
71
+ "limit 50"
72
+ ].filter(Boolean).join("\n"),
73
+ values: {
74
+ eventName: `${this.eventPrefix}.window`,
75
+ dateFrom: toIsoString(dateRange?.from),
76
+ dateTo: toIsoString(dateRange?.to)
77
+ }
78
+ }));
79
+ }
80
+ async readTopErrors(operation, dateRange) {
81
+ return mapRows(await this.queryHogQL({
82
+ query: [
83
+ "select",
84
+ " properties.errorCode as errorCode,",
85
+ " count() as errorCount",
86
+ "from events",
87
+ `where ${buildOperationWhereClause(this.eventPrefix, {
88
+ operations: [operation],
89
+ dateRange
90
+ })} and properties.success = 0`,
91
+ "group by errorCode",
92
+ "order by errorCount desc",
93
+ "limit 5"
94
+ ].join("\n"),
95
+ values: buildOperationValues({
96
+ operations: [operation],
97
+ dateRange
98
+ })
99
+ })).reduce((acc, row) => {
100
+ const code = asString(row.errorCode);
101
+ if (!code) return acc;
102
+ acc[code] = asNumber(row.errorCount);
103
+ return acc;
104
+ }, {});
105
+ }
106
+ async queryHogQL(input) {
107
+ if (!this.reader.queryHogQL) throw new Error("Analytics reader does not support HogQL queries.");
108
+ return this.reader.queryHogQL(input);
109
+ }
110
+ };
111
+ function buildOperationWhereClause(eventPrefix, input) {
112
+ const clauses = [`event = '${eventPrefix}.operation'`];
113
+ if (input.operations?.length) clauses.push(`(${buildOperationFilters(input.operations)})`);
114
+ if (input.dateRange?.from) clauses.push("timestamp >= {dateFrom}");
115
+ if (input.dateRange?.to) clauses.push("timestamp < {dateTo}");
116
+ return clauses.join(" and ");
117
+ }
118
+ function buildOperationValues(input) {
119
+ const values = {
120
+ dateFrom: toIsoString(input.dateRange?.from),
121
+ dateTo: toIsoString(input.dateRange?.to)
122
+ };
123
+ input.operations?.forEach((op, index) => {
124
+ values[`operationName${index}`] = op.name;
125
+ values[`operationVersion${index}`] = op.version;
126
+ });
127
+ return values;
128
+ }
129
+ function buildOperationFilters(operations) {
130
+ return operations.map((_op, index) => `(properties.operation = {operationName${index}} and properties.version = {operationVersion${index}})`).join(" or ");
131
+ }
132
+ function mapTelemetrySamples(result) {
133
+ return mapRows(result).flatMap((row) => {
134
+ const operationName = asString(row.operationName);
135
+ const version = asString(row.version);
136
+ const timestamp = asDate(row.timestamp);
137
+ if (!operationName || !version || !timestamp) return [];
138
+ return [{
139
+ operation: {
140
+ name: operationName,
141
+ version
142
+ },
143
+ durationMs: asNumber(row.durationMs),
144
+ success: asBoolean(row.success),
145
+ timestamp,
146
+ errorCode: asOptionalString(row.errorCode) ?? void 0,
147
+ tenantId: asOptionalString(row.tenantId) ?? void 0,
148
+ traceId: asOptionalString(row.traceId) ?? void 0,
149
+ actorId: asOptionalString(row.actorId) ?? void 0,
150
+ metadata: isRecord(row.metadata) ? row.metadata : void 0
151
+ }];
152
+ });
153
+ }
154
+ function mapAggregatedMetrics(result, operation, dateRange) {
155
+ const row = mapRows(result)[0];
156
+ if (!row) return null;
157
+ const totalCalls = asNumber(row.totalCalls);
158
+ if (!totalCalls) return null;
159
+ const successCount = asNumber(row.successCount);
160
+ const errorCount = asNumber(row.errorCount);
161
+ const windowStart = toDate(dateRange.from) ?? /* @__PURE__ */ new Date();
162
+ const windowEnd = toDate(dateRange.to) ?? /* @__PURE__ */ new Date();
163
+ return {
164
+ operation,
165
+ totalCalls,
166
+ successRate: totalCalls ? successCount / totalCalls : 0,
167
+ errorRate: totalCalls ? errorCount / totalCalls : 0,
168
+ averageLatencyMs: asNumber(row.averageLatencyMs),
169
+ p95LatencyMs: asNumber(row.p95LatencyMs),
170
+ p99LatencyMs: asNumber(row.p99LatencyMs),
171
+ maxLatencyMs: asNumber(row.maxLatencyMs),
172
+ windowStart,
173
+ windowEnd,
174
+ topErrors: {}
175
+ };
176
+ }
177
+ function mergeSequences(result) {
178
+ const rows = mapRows(result);
179
+ const merged = /* @__PURE__ */ new Map();
180
+ rows.forEach((row) => {
181
+ const sequences = row.sequences;
182
+ if (!Array.isArray(sequences)) return;
183
+ sequences.forEach((sequence) => {
184
+ if (!isRecord(sequence)) return;
185
+ const steps = Array.isArray(sequence.steps) ? sequence.steps.filter((step) => typeof step === "string") : [];
186
+ if (steps.length === 0) return;
187
+ const tenantId = typeof sequence.tenantId === "string" ? sequence.tenantId : void 0;
188
+ const count = typeof sequence.count === "number" && Number.isFinite(sequence.count) ? sequence.count : 0;
189
+ const key = `${tenantId ?? "global"}:${steps.join(">")}`;
190
+ const existing = merged.get(key);
191
+ if (existing) existing.count += count;
192
+ else merged.set(key, {
193
+ steps,
194
+ tenantId,
195
+ count
196
+ });
197
+ });
198
+ });
199
+ return [...merged.values()];
200
+ }
201
+ function mapRows(result) {
202
+ if (!Array.isArray(result.results) || !Array.isArray(result.columns)) return [];
203
+ const columns = result.columns;
204
+ return result.results.flatMap((row) => {
205
+ if (!Array.isArray(row)) return [];
206
+ const record = {};
207
+ columns.forEach((column, index) => {
208
+ record[column] = row[index];
209
+ });
210
+ return [record];
211
+ });
212
+ }
213
+ function buildWindowRange(windowDays) {
214
+ const windowEnd = /* @__PURE__ */ new Date();
215
+ return {
216
+ from: /* @__PURE__ */ new Date(windowEnd.getTime() - windowDays * 24 * 60 * 60 * 1e3),
217
+ to: windowEnd
218
+ };
219
+ }
220
+ function asString(value) {
221
+ if (typeof value === "string" && value.trim()) return value;
222
+ if (typeof value === "number") return String(value);
223
+ return null;
224
+ }
225
+ function asOptionalString(value) {
226
+ if (typeof value === "string") return value;
227
+ if (typeof value === "number") return String(value);
228
+ return null;
229
+ }
230
+ function asNumber(value) {
231
+ if (typeof value === "number" && Number.isFinite(value)) return value;
232
+ if (typeof value === "string" && value.trim()) {
233
+ const parsed = Number(value);
234
+ if (Number.isFinite(parsed)) return parsed;
235
+ }
236
+ return 0;
237
+ }
238
+ function asBoolean(value) {
239
+ if (typeof value === "boolean") return value;
240
+ if (typeof value === "number") return value !== 0;
241
+ if (typeof value === "string") return value.toLowerCase() === "true";
242
+ return false;
243
+ }
244
+ function asDate(value) {
245
+ if (value instanceof Date) return value;
246
+ if (typeof value === "string" || typeof value === "number") {
247
+ const date = new Date(value);
248
+ if (!Number.isNaN(date.getTime())) return date;
249
+ }
250
+ return null;
251
+ }
252
+ function toIsoString(value) {
253
+ if (!value) return void 0;
254
+ return typeof value === "string" ? value : value.toISOString();
255
+ }
256
+ function toDate(value) {
257
+ if (!value) return null;
258
+ return value instanceof Date ? value : new Date(value);
259
+ }
260
+ function isRecord(value) {
261
+ return typeof value === "object" && value !== null;
262
+ }
263
+
264
+ //#endregion
265
+ export { PosthogBaselineReader };
266
+ //# sourceMappingURL=posthog-baseline-reader.mjs.map
@@ -0,0 +1,19 @@
1
+ import { IntentAggregatorSnapshot, TelemetrySample } from "../intent/aggregator.mjs";
2
+ import { AnalyticsProvider } from "@contractspec/lib.contracts/integrations/providers/analytics";
3
+
4
+ //#region src/telemetry/posthog-telemetry.d.ts
5
+ interface PosthogTelemetryProviderOptions {
6
+ eventPrefix?: string;
7
+ includeMetadata?: boolean;
8
+ }
9
+ declare class PosthogTelemetryProvider {
10
+ private readonly provider;
11
+ private readonly eventPrefix;
12
+ private readonly includeMetadata;
13
+ constructor(provider: AnalyticsProvider, options?: PosthogTelemetryProviderOptions);
14
+ captureSample(sample: TelemetrySample): Promise<void>;
15
+ captureSnapshot(snapshot: IntentAggregatorSnapshot): Promise<void>;
16
+ }
17
+ //#endregion
18
+ export { PosthogTelemetryProvider, PosthogTelemetryProviderOptions };
19
+ //# sourceMappingURL=posthog-telemetry.d.mts.map
@@ -0,0 +1,61 @@
1
+ //#region src/telemetry/posthog-telemetry.ts
2
+ var PosthogTelemetryProvider = class {
3
+ provider;
4
+ eventPrefix;
5
+ includeMetadata;
6
+ constructor(provider, options = {}) {
7
+ this.provider = provider;
8
+ this.eventPrefix = options.eventPrefix ?? "observability";
9
+ this.includeMetadata = options.includeMetadata ?? false;
10
+ }
11
+ async captureSample(sample) {
12
+ await this.provider.capture({
13
+ distinctId: sample.actorId ?? sample.tenantId ?? "unknown",
14
+ event: `${this.eventPrefix}.operation`,
15
+ timestamp: sample.timestamp,
16
+ properties: {
17
+ operation: sample.operation.name,
18
+ version: sample.operation.version,
19
+ durationMs: sample.durationMs,
20
+ success: sample.success,
21
+ errorCode: sample.errorCode ?? null,
22
+ tenantId: sample.tenantId ?? null,
23
+ traceId: sample.traceId ?? null,
24
+ ...this.includeMetadata && sample.metadata ? { metadata: sample.metadata } : {}
25
+ }
26
+ });
27
+ }
28
+ async captureSnapshot(snapshot) {
29
+ await this.provider.capture({
30
+ distinctId: "system",
31
+ event: `${this.eventPrefix}.window`,
32
+ timestamp: snapshot.windowEnd ?? /* @__PURE__ */ new Date(),
33
+ properties: {
34
+ sampleCount: snapshot.sampleCount,
35
+ metricsCount: snapshot.metrics.length,
36
+ sequencesCount: snapshot.sequences.length,
37
+ windowStart: snapshot.windowStart?.toISOString() ?? null,
38
+ windowEnd: snapshot.windowEnd?.toISOString() ?? null,
39
+ ...this.includeMetadata ? {
40
+ metrics: snapshot.metrics.map((metric) => ({
41
+ operation: metric.operation.name,
42
+ version: metric.operation.version,
43
+ totalCalls: metric.totalCalls,
44
+ successRate: metric.successRate,
45
+ errorRate: metric.errorRate,
46
+ averageLatencyMs: metric.averageLatencyMs,
47
+ p95LatencyMs: metric.p95LatencyMs,
48
+ p99LatencyMs: metric.p99LatencyMs,
49
+ maxLatencyMs: metric.maxLatencyMs,
50
+ topErrors: metric.topErrors
51
+ })),
52
+ sequences: snapshot.sequences
53
+ } : {}
54
+ }
55
+ });
56
+ }
57
+ };
58
+
59
+ //#endregion
60
+ export { PosthogTelemetryProvider };
61
+ //# sourceMappingURL=posthog-telemetry.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contractspec/lib.observability",
3
- "version": "1.56.0",
3
+ "version": "1.57.0",
4
4
  "description": "OpenTelemetry-based observability primitives",
5
5
  "keywords": [
6
6
  "contractspec",
@@ -25,14 +25,15 @@
25
25
  "test": "bun test"
26
26
  },
27
27
  "dependencies": {
28
- "@contractspec/lib.lifecycle": "1.56.0"
28
+ "@contractspec/lib.lifecycle": "1.57.0",
29
+ "@contractspec/lib.contracts": "1.57.0"
29
30
  },
30
31
  "peerDependencies": {
31
32
  "@opentelemetry/api": "*"
32
33
  },
33
34
  "devDependencies": {
34
- "@contractspec/tool.tsdown": "1.56.0",
35
- "@contractspec/tool.typescript": "1.56.0",
35
+ "@contractspec/tool.tsdown": "1.57.0",
36
+ "@contractspec/tool.typescript": "1.57.0",
36
37
  "typescript": "^5.9.3"
37
38
  },
38
39
  "exports": {
@@ -47,6 +48,8 @@
47
48
  "./metrics": "./dist/metrics/index.mjs",
48
49
  "./pipeline/evolution-pipeline": "./dist/pipeline/evolution-pipeline.mjs",
49
50
  "./pipeline/lifecycle-pipeline": "./dist/pipeline/lifecycle-pipeline.mjs",
51
+ "./telemetry/posthog-baseline-reader": "./dist/telemetry/posthog-baseline-reader.mjs",
52
+ "./telemetry/posthog-telemetry": "./dist/telemetry/posthog-telemetry.mjs",
50
53
  "./tracing": "./dist/tracing/index.mjs",
51
54
  "./tracing/middleware": "./dist/tracing/middleware.mjs",
52
55
  "./*": "./*"
@@ -65,6 +68,7 @@
65
68
  "./metrics": "./dist/metrics/index.mjs",
66
69
  "./pipeline/evolution-pipeline": "./dist/pipeline/evolution-pipeline.mjs",
67
70
  "./pipeline/lifecycle-pipeline": "./dist/pipeline/lifecycle-pipeline.mjs",
71
+ "./telemetry/posthog-baseline-reader": "./dist/telemetry/posthog-baseline-reader.mjs",
68
72
  "./tracing": "./dist/tracing/index.mjs",
69
73
  "./tracing/middleware": "./dist/tracing/middleware.mjs",
70
74
  "./*": "./*"