@krak-stack/registry 0.1.50 → 0.1.52

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 (31) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +16 -424
  3. package/dist/components/ui/data-table.d.ts +20 -1
  4. package/dist/components/ui/data-table.js +52 -1
  5. package/dist/lib/docs.js +2 -2
  6. package/dist/services/agent/client/index.js +1 -1
  7. package/dist/services/events/browser.d.ts +26 -0
  8. package/dist/services/events/browser.js +579 -0
  9. package/dist/services/events/client/audit-log-table.d.ts +53 -0
  10. package/dist/services/events/client/audit-log-table.js +3655 -0
  11. package/dist/services/events/index.d.ts +215 -0
  12. package/dist/services/events/index.js +1046 -0
  13. package/dist/services/events/migrations.d.ts +4 -0
  14. package/dist/services/events/migrations.js +42 -0
  15. package/dist/services/events/record.d.ts +3 -0
  16. package/dist/services/events/record.js +14 -0
  17. package/dist/services/events/request-context.d.ts +6 -0
  18. package/dist/services/events/schema.d.ts +237 -0
  19. package/dist/services/events/schema.js +361 -0
  20. package/dist/services/opentelemetry/api.d.ts +3 -1
  21. package/dist/services/opentelemetry/api.js +133 -64
  22. package/dist/services/opentelemetry/browser.d.ts +17 -20
  23. package/dist/services/opentelemetry/browser.js +58 -162
  24. package/dist/services/opentelemetry/events.d.ts +3 -1
  25. package/dist/services/opentelemetry/{server.d.ts → index.d.ts} +8 -5
  26. package/dist/services/opentelemetry/{server.js → index.js} +66 -48
  27. package/dist/services/opentelemetry/processor.d.ts +19 -0
  28. package/dist/services/opentelemetry/schema.d.ts +8 -20
  29. package/dist/services/opentelemetry/web-vitals.d.ts +15 -0
  30. package/dist/services/opentelemetry/web-vitals.js +229 -0
  31. package/package.json +35 -5
@@ -1,5 +1,7 @@
1
1
  import { Config, Layer } from "effect";
2
2
  import { HttpRouter } from "effect/http";
3
+ import { Otlp } from "./index.js";
4
+ export { OtlpLogsProcessor, OtlpProcessingError } from "./processor.js";
3
5
  export declare class HttpApiOtlp {
4
- static readonly layer: Layer.Layer<import("effect/FileSystem").FileSystem | import("effect/observability/OtlpExporter").Flusher | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("./events.js").OtlpEvents | import("effect/Path").Path, Config.ConfigError, HttpRouter.HttpRouter>;
6
+ static readonly layer: Layer.Layer<import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/Path").Path, Config.ConfigError, HttpRouter.HttpRouter | Otlp>;
5
7
  }
@@ -1,5 +1,5 @@
1
1
  // ../../src/services/opentelemetry/api.ts
2
- import { Config as Config2, Effect as Effect3, Layer as Layer3, Schema as Schema4 } from "effect";
2
+ import { Config as Config2, Effect as Effect4, Layer as Layer3, Option as Option2, Schema as Schema5, Stream } from "effect";
3
3
  import {
4
4
  FetchHttpClient as FetchHttpClient2,
5
5
  HttpClient,
@@ -11,10 +11,15 @@ import {
11
11
  HttpServerResponse
12
12
  } from "effect/http";
13
13
 
14
- // ../../src/services/opentelemetry/server.ts
15
- import { Config, Effect as Effect2, Layer as Layer2, Schema as Schema3 } from "effect";
14
+ // ../../src/services/opentelemetry/index.ts
15
+ import { Config, Context as Context2, Effect as Effect2, Layer as Layer2, Schema as Schema3 } from "effect";
16
16
  import { FetchHttpClient } from "effect/http";
17
- import { Otlp, OtlpExporter as OtlpExporter2, OtlpSerialization as OtlpSerialization2 } from "effect/observability";
17
+ import {
18
+ Otlp as EffectOtlp,
19
+ OtlpExporter as OtlpExporter2,
20
+ OtlpResource as OtlpResource2,
21
+ OtlpSerialization as OtlpSerialization2
22
+ } from "effect/observability";
18
23
 
19
24
  // ../../src/services/opentelemetry/events.ts
20
25
  import {
@@ -35,6 +40,21 @@ import {
35
40
 
36
41
  // ../../src/services/opentelemetry/schema.ts
37
42
  import { Schema } from "effect";
43
+ var BrowserWebVital = Schema.Struct({
44
+ name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
45
+ id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
46
+ value: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
47
+ delta: Schema.Finite,
48
+ rating: Schema.Literals(["good", "needs-improvement", "poor"]),
49
+ navigationType: Schema.Literals([
50
+ "navigate",
51
+ "reload",
52
+ "back-forward",
53
+ "back-forward-cache",
54
+ "prerender",
55
+ "restore"
56
+ ])
57
+ }).annotate({ identifier: "BrowserWebVital" });
38
58
  var EventAttributeValue = Schema.Union([
39
59
  Schema.String,
40
60
  Schema.Finite,
@@ -57,17 +77,6 @@ var TelemetryEvent = Schema.Struct({
57
77
  properties: Schema.optional(EventAttributesSchema),
58
78
  options: Schema.optional(EventOptionsSchema)
59
79
  }).annotate({ identifier: "TelemetryEvent" });
60
- var PageEvent = Schema.Struct({
61
- name: Schema.optional(Schema.NonEmptyString),
62
- category: Schema.optional(Schema.NonEmptyString),
63
- path: Schema.optional(Schema.NonEmptyString),
64
- properties: Schema.optional(EventAttributesSchema),
65
- options: Schema.optional(EventOptionsSchema)
66
- }).annotate({ identifier: "PageEvent" });
67
- var BrowserIdentity = Schema.Struct({
68
- userId: Schema.optional(Schema.NonEmptyString),
69
- organizationId: Schema.optional(Schema.NonEmptyString)
70
- }).annotate({ identifier: "BrowserTelemetryIdentity" });
71
80
 
72
81
  // ../../src/services/opentelemetry/events.ts
73
82
  class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
@@ -78,27 +87,36 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
78
87
  return yield* OtlpExporter.make({
79
88
  ...options,
80
89
  label: "OtlpEvents",
81
- body: (logRecords) => [
82
- serialization.logs({
83
- resourceLogs: [
84
- {
85
- resource,
86
- scopeLogs: [
87
- {
88
- scope: { name: "krakstack.events" },
89
- logRecords
90
- }
91
- ]
92
- }
93
- ]
94
- }),
95
- Effect.void
96
- ]
90
+ body: (logRecords) => {
91
+ const scopes = new Map;
92
+ for (const { scopeName, ...record } of logRecords) {
93
+ const name = scopeName ?? options.scopeName ?? "krakstack.events";
94
+ const records = scopes.get(name);
95
+ if (records)
96
+ records.push(record);
97
+ else
98
+ scopes.set(name, [record]);
99
+ }
100
+ return [
101
+ serialization.logs({
102
+ resourceLogs: [
103
+ {
104
+ resource,
105
+ scopeLogs: Array.from(scopes, ([name, records]) => ({
106
+ scope: { name },
107
+ logRecords: records
108
+ }))
109
+ }
110
+ ]
111
+ }),
112
+ Effect.void
113
+ ];
114
+ }
97
115
  });
98
116
  }));
99
117
  }
100
- var track = Effect.fnUntraced(function* (name, properties, options) {
101
- const event = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
118
+ var event = Effect.fnUntraced(function* (name, properties, options) {
119
+ const decoded = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
102
120
  name,
103
121
  properties,
104
122
  options
@@ -106,20 +124,20 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
106
124
  const events = yield* OtlpEvents;
107
125
  const clock = yield* Clock.Clock;
108
126
  const observedTime = clock.currentTimeNanosUnsafe().toString();
109
- const timestamp = event.options?.timestamp ? (BigInt(DateTime.toEpochMillis(event.options.timestamp)) * 1000000n).toString() : observedTime;
127
+ const timestamp = decoded.options?.timestamp ? (BigInt(DateTime.toEpochMillis(decoded.options.timestamp)) * 1000000n).toString() : observedTime;
110
128
  const span = yield* Effect.currentSpan.pipe(Effect.option);
111
- const attributes = { ...event.options?.context, ...event.properties };
112
- if (event.options?.userId)
113
- attributes["user.id"] = event.options.userId;
114
- if (event.options?.anonymousId)
115
- attributes["analytics.anonymous_id"] = event.options.anonymousId;
116
- if (event.options?.sessionId)
117
- attributes["session.id"] = event.options.sessionId;
118
- if (event.options?.messageId)
119
- attributes["log.record.uid"] = event.options.messageId;
129
+ const attributes = { ...decoded.options?.context, ...decoded.properties };
130
+ if (decoded.options?.userId)
131
+ attributes["user.id"] = decoded.options.userId;
132
+ if (decoded.options?.anonymousId)
133
+ attributes["analytics.anonymous_id"] = decoded.options.anonymousId;
134
+ if (decoded.options?.sessionId)
135
+ attributes["session.id"] = decoded.options.sessionId;
136
+ if (decoded.options?.messageId)
137
+ attributes["log.record.uid"] = decoded.options.messageId;
120
138
  const annotations = yield* References.CurrentLogAnnotations;
121
139
  events.push({
122
- eventName: event.name,
140
+ eventName: decoded.name,
123
141
  timeUnixNano: timestamp,
124
142
  observedTimeUnixNano: observedTime,
125
143
  severityNumber: 9,
@@ -133,7 +151,7 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
133
151
  });
134
152
  });
135
153
 
136
- // ../../src/services/opentelemetry/server.ts
154
+ // ../../src/services/opentelemetry/index.ts
137
155
  var ServerEventsLive = Layer2.unwrap(Effect2.gen(function* () {
138
156
  const disabled = yield* Config.Boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false));
139
157
  const exporters = yield* Config.Array(Schema3.String, "OTEL_LOGS_EXPORTER").pipe(Config.withDefault([]));
@@ -158,9 +176,18 @@ var ServerEventsLive = Layer2.unwrap(Effect2.gen(function* () {
158
176
  });
159
177
  }).pipe(Effect2.orDie));
160
178
 
161
- class ServerOtlp {
162
- static track = track;
163
- static layer = Layer2.mergeAll(Otlp.layerFromConfig(), ServerEventsLive).pipe(Layer2.provideMerge(OtlpExporter2.layerFlusher), Layer2.provide(OtlpSerialization2.layerJson), Layer2.provide(FetchHttpClient.layer));
179
+ class Otlp extends Context2.Service()("krakstack/opentelemetry/Otlp") {
180
+ static event = event;
181
+ static layer = Layer2.mergeAll(Layer2.succeed(this, { resource: OtlpResource2.fromConfig() }), EffectOtlp.layerFromConfig(), ServerEventsLive).pipe(Layer2.provideMerge(OtlpExporter2.layerFlusher), Layer2.provide(OtlpSerialization2.layerJson), Layer2.provide(FetchHttpClient.layer));
182
+ }
183
+
184
+ // ../../src/services/opentelemetry/processor.ts
185
+ import { Context as Context3, Schema as Schema4 } from "effect";
186
+
187
+ class OtlpProcessingError extends Schema4.TaggedError()("OtlpProcessingError", { status: Schema4.Literals([400, 403, 409, 413, 503]) }) {
188
+ }
189
+
190
+ class OtlpLogsProcessor extends Context3.Service()("krakstack/opentelemetry/OtlpLogsProcessor") {
164
191
  }
165
192
 
166
193
  // ../../src/services/opentelemetry/api.ts
@@ -169,37 +196,79 @@ var otlpProxyPaths = [
169
196
  "/api/otel/v1/metrics",
170
197
  "/api/otel/v1/logs"
171
198
  ];
172
- var exporterConfig = (signal) => Config2.Array(Schema4.String, `OTEL_${signal}_EXPORTER`).pipe(Config2.map((exporters) => exporters.map((exporter) => exporter.toLowerCase().trim())), Config2.withDefault([]));
173
- var proxyOtlp = (baseUrl, signal) => Effect3.gen(function* () {
199
+ var exporterConfig = (signal) => Config2.Array(Schema5.String, `OTEL_${signal}_EXPORTER`).pipe(Config2.map((exporters) => exporters.map((exporter) => exporter.toLowerCase().trim())), Config2.withDefault([]));
200
+ var readProcessorBody = Effect4.fnUntraced(function* () {
201
+ const incoming = yield* HttpServerRequest.HttpServerRequest;
202
+ const collected = yield* incoming.stream.pipe(Stream.mapError(() => new OtlpProcessingError({ status: 400 })), Stream.runFoldEffect(() => ({
203
+ chunks: [],
204
+ size: 0
205
+ }), (state, chunk) => {
206
+ const size = state.size + chunk.byteLength;
207
+ if (size > 64 * 1024)
208
+ return Effect4.fail(new OtlpProcessingError({ status: 413 }));
209
+ state.chunks.push(chunk);
210
+ state.size = size;
211
+ return Effect4.succeed(state);
212
+ }));
213
+ const bytes = new Uint8Array(collected.size);
214
+ let offset = 0;
215
+ for (const chunk of collected.chunks) {
216
+ bytes.set(chunk, offset);
217
+ offset += chunk.byteLength;
218
+ }
219
+ return bytes;
220
+ });
221
+ var proxyOtlp = (baseUrl, signal, processor) => Effect4.gen(function* () {
174
222
  const incoming = yield* HttpServerRequest.HttpServerRequest;
175
223
  const client = yield* HttpClient.HttpClient;
176
224
  const contentType = incoming.headers["content-type"] ?? "application/json";
177
- const body = new Uint8Array(yield* incoming.arrayBuffer);
178
- const request = HttpClientRequest.get(baseUrl).pipe(HttpClientRequest.appendUrl(`/v1/${signal}`), HttpClientRequest.setMethod("POST"), HttpClientRequest.bodyUint8Array(body, contentType));
179
- const upstream = yield* client.execute(request);
180
- const responseBody = new Uint8Array(yield* upstream.arrayBuffer);
181
- return HttpServerResponse.uint8Array(responseBody, {
182
- status: upstream.status,
183
- contentType: upstream.headers["content-type"],
184
- headers: {
185
- "retry-after": upstream.headers["retry-after"]
225
+ const processLogs = signal === "logs" && Option2.isSome(processor);
226
+ if (processLogs && contentType.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") {
227
+ return HttpServerResponse.empty({ status: 415 });
228
+ }
229
+ const bytes = processLogs ? yield* readProcessorBody() : new Uint8Array(yield* incoming.arrayBuffer);
230
+ const processed = processLogs ? yield* processor.value.process(bytes) : { body: bytes, persisted: false };
231
+ const request = HttpClientRequest.get(baseUrl).pipe(HttpClientRequest.appendUrl(`/v1/${signal}`), HttpClientRequest.setMethod("POST"), HttpClientRequest.bodyUint8Array(processed.body, contentType));
232
+ const forward = Effect4.gen(function* () {
233
+ const upstream = yield* client.execute(request);
234
+ const responseBody = new Uint8Array(yield* upstream.arrayBuffer);
235
+ if (processed.persisted) {
236
+ if (upstream.status < 200 || upstream.status >= 300)
237
+ yield* Effect4.logWarning("Collector rejected persisted analytics", {
238
+ status: upstream.status
239
+ });
240
+ return HttpServerResponse.jsonUnsafe({});
186
241
  }
242
+ return HttpServerResponse.uint8Array(responseBody, {
243
+ status: upstream.status,
244
+ contentType: upstream.headers["content-type"],
245
+ headers: {
246
+ "retry-after": upstream.headers["retry-after"]
247
+ }
248
+ });
187
249
  });
188
- }).pipe(Effect3.withTracerEnabled(false), HttpMiddleware.withLoggerDisabled, Effect3.catch((error) => Effect3.logError("Failed to proxy browser telemetry", error).pipe(Effect3.as(HttpServerResponse.empty({ status: 502 })))), Effect3.provide(FetchHttpClient2.layer));
189
- var otlpProxyLayer = Layer3.unwrap(Effect3.gen(function* () {
250
+ if (!processed.persisted)
251
+ return yield* forward;
252
+ return yield* forward.pipe(Effect4.timeout("5 seconds"), Effect4.catch((error) => Effect4.logWarning("Collector delivery failed after analytics commit", error).pipe(Effect4.as(HttpServerResponse.jsonUnsafe({})))));
253
+ }).pipe(Effect4.withTracerEnabled(false), HttpMiddleware.withLoggerDisabled, Effect4.catchTag("OtlpProcessingError", (error) => Effect4.succeed(HttpServerResponse.empty({ status: error.status }))), Effect4.catch((error) => Effect4.logError("Failed to proxy browser telemetry", error).pipe(Effect4.as(HttpServerResponse.empty({ status: 502 })))), Effect4.provide(FetchHttpClient2.layer));
254
+ var otlpProxyLayer = Layer3.unwrap(Effect4.gen(function* () {
255
+ yield* Otlp;
190
256
  const baseUrl = yield* Config2.URL("OTEL_EXPORTER_OTLP_ENDPOINT");
257
+ const processor = yield* Effect4.serviceOption(OtlpLogsProcessor);
191
258
  const exporters = yield* Config2.all({
192
259
  logs: exporterConfig("LOGS"),
193
260
  metrics: exporterConfig("METRICS"),
194
261
  traces: exporterConfig("TRACES")
195
262
  });
196
- return Layer3.mergeAll(exporters.traces.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[0], proxyOtlp(baseUrl, "traces")) : Layer3.empty, exporters.metrics.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[1], proxyOtlp(baseUrl, "metrics")) : Layer3.empty, exporters.logs.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[2], proxyOtlp(baseUrl, "logs")) : Layer3.empty);
263
+ return Layer3.mergeAll(exporters.traces.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[0], proxyOtlp(baseUrl, "traces", processor)) : Layer3.empty, exporters.metrics.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[1], proxyOtlp(baseUrl, "metrics", processor)) : Layer3.empty, exporters.logs.includes("otlp") ? HttpRouter.add("POST", otlpProxyPaths[2], proxyOtlp(baseUrl, "logs", processor)) : Layer3.empty);
197
264
  }));
198
265
  var serverServices = HttpServer.layerServices.pipe(Layer3.provideMerge(HttpMiddleware.layerTracerDisabledForUrls(otlpProxyPaths)));
199
266
 
200
267
  class HttpApiOtlp {
201
- static layer = Layer3.mergeAll(ServerOtlp.layer, otlpProxyLayer, serverServices);
268
+ static layer = Layer3.mergeAll(otlpProxyLayer, serverServices);
202
269
  }
203
270
  export {
204
- HttpApiOtlp
271
+ HttpApiOtlp,
272
+ OtlpLogsProcessor,
273
+ OtlpProcessingError
205
274
  };
@@ -1,15 +1,7 @@
1
- import { Context, Effect, Layer, Ref, Schema } from "effect";
1
+ import { Effect, Layer, Schema } from "effect";
2
2
  import { type Otlp, OtlpExporter, OtlpLogger, OtlpMetrics, OtlpTracer } from "effect/observability";
3
3
  import { OtlpEvents, type EventExportOptions } from "./events.js";
4
- import { BrowserIdentity, type EventAttributes, type EventOptions, type PageOptions } from "./schema.js";
5
- export type { BrowserIdentity, EventAttributes, EventOptions, PageOptions, } from "./schema.js";
6
- declare const BrowserIdentityState_base: Context.ServiceClass<BrowserIdentityState, "krakstack/opentelemetry/BrowserIdentity", Ref.Ref<{
7
- readonly userId?: string | undefined;
8
- readonly organizationId?: string | undefined;
9
- }>>;
10
- declare class BrowserIdentityState extends BrowserIdentityState_base {
11
- static readonly layer: Layer.Layer<BrowserIdentityState, never, never>;
12
- }
4
+ export type { EventAttributes, EventOptions } from "./schema.js";
13
5
  type OtlpOptions = Parameters<typeof Otlp.layerJson>[0];
14
6
  type SignalOptions<Options> = Omit<Options, "url" | "resource" | "headers">;
15
7
  export interface BrowserOtlpOptions {
@@ -21,16 +13,21 @@ export interface BrowserOtlpOptions {
21
13
  readonly traces?: false | SignalOptions<Parameters<typeof OtlpTracer.layer>[0]>;
22
14
  readonly metrics?: false | SignalOptions<Parameters<typeof OtlpMetrics.layer>[0]>;
23
15
  readonly logs?: false | SignalOptions<Parameters<typeof OtlpLogger.layer>[0]>;
24
- readonly events?: false | (EventExportOptions & {
25
- /** Initial page and pathname changes; enabled by default. */
26
- readonly pageViews?: boolean;
27
- });
16
+ /** Named OTLP log events; no automatic page tracking or analytics enrichment. */
17
+ readonly events?: false | EventExportOptions;
28
18
  }
29
19
  export declare class BrowserOtlp {
30
- /** Uses the active browser layer; invalid identity warns without failing or changing state. */
31
- static readonly identify: (identity: BrowserIdentity | null) => Effect.Effect<void, never, never>;
32
- static readonly track: (name: string, properties?: EventAttributes, options?: EventOptions) => Effect.Effect<void, Schema.SchemaError, never>;
33
- static readonly page: (options?: PageOptions) => Effect.Effect<void, Schema.SchemaError, never>;
34
- static readonly pageView: (options?: PageOptions) => Effect.Effect<void, Schema.SchemaError, never>;
35
- static readonly layer: ({ attributes, baseUrl, logs, events, metrics, serviceName, serviceVersion, traces, headers, }: BrowserOtlpOptions) => Layer.Layer<BrowserIdentityState | OtlpExporter.Flusher | OtlpEvents, never, never>;
20
+ static readonly event: (name: string, properties?: {
21
+ readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
22
+ } | undefined, options?: {
23
+ readonly userId?: string | undefined;
24
+ readonly anonymousId?: string | undefined;
25
+ readonly sessionId?: string | undefined;
26
+ readonly messageId?: string | undefined;
27
+ readonly timestamp?: import("effect/DateTime").Utc | undefined;
28
+ readonly context?: {
29
+ readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
30
+ } | undefined;
31
+ } | undefined) => Effect.Effect<void, Schema.SchemaError, OtlpEvents>;
32
+ static readonly layer: ({ attributes, baseUrl, logs, events, metrics, serviceName, serviceVersion, traces, headers, }: BrowserOtlpOptions) => Layer.Layer<OtlpExporter.Flusher | OtlpEvents, never, never>;
36
33
  }
@@ -1,15 +1,5 @@
1
1
  // ../../src/services/opentelemetry/browser.ts
2
- import {
3
- Context as Context2,
4
- Effect as Effect2,
5
- FiberSet,
6
- Layer as Layer2,
7
- Predicate,
8
- Ref,
9
- References as References2,
10
- Schema as Schema3,
11
- Stream
12
- } from "effect";
2
+ import { Effect as Effect2, FiberSet, Layer as Layer2, Predicate, Schema as Schema3, Stream } from "effect";
13
3
  import { FetchHttpClient, HttpClientRequest } from "effect/http";
14
4
  import {
15
5
  OtlpExporter as OtlpExporter2,
@@ -38,6 +28,21 @@ import {
38
28
 
39
29
  // ../../src/services/opentelemetry/schema.ts
40
30
  import { Schema } from "effect";
31
+ var BrowserWebVital = Schema.Struct({
32
+ name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
33
+ id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
34
+ value: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
35
+ delta: Schema.Finite,
36
+ rating: Schema.Literals(["good", "needs-improvement", "poor"]),
37
+ navigationType: Schema.Literals([
38
+ "navigate",
39
+ "reload",
40
+ "back-forward",
41
+ "back-forward-cache",
42
+ "prerender",
43
+ "restore"
44
+ ])
45
+ }).annotate({ identifier: "BrowserWebVital" });
41
46
  var EventAttributeValue = Schema.Union([
42
47
  Schema.String,
43
48
  Schema.Finite,
@@ -60,17 +65,6 @@ var TelemetryEvent = Schema.Struct({
60
65
  properties: Schema.optional(EventAttributesSchema),
61
66
  options: Schema.optional(EventOptionsSchema)
62
67
  }).annotate({ identifier: "TelemetryEvent" });
63
- var PageEvent = Schema.Struct({
64
- name: Schema.optional(Schema.NonEmptyString),
65
- category: Schema.optional(Schema.NonEmptyString),
66
- path: Schema.optional(Schema.NonEmptyString),
67
- properties: Schema.optional(EventAttributesSchema),
68
- options: Schema.optional(EventOptionsSchema)
69
- }).annotate({ identifier: "PageEvent" });
70
- var BrowserIdentity = Schema.Struct({
71
- userId: Schema.optional(Schema.NonEmptyString),
72
- organizationId: Schema.optional(Schema.NonEmptyString)
73
- }).annotate({ identifier: "BrowserTelemetryIdentity" });
74
68
 
75
69
  // ../../src/services/opentelemetry/events.ts
76
70
  class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
@@ -81,27 +75,36 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
81
75
  return yield* OtlpExporter.make({
82
76
  ...options,
83
77
  label: "OtlpEvents",
84
- body: (logRecords) => [
85
- serialization.logs({
86
- resourceLogs: [
87
- {
88
- resource,
89
- scopeLogs: [
90
- {
91
- scope: { name: "krakstack.events" },
92
- logRecords
93
- }
94
- ]
95
- }
96
- ]
97
- }),
98
- Effect.void
99
- ]
78
+ body: (logRecords) => {
79
+ const scopes = new Map;
80
+ for (const { scopeName, ...record } of logRecords) {
81
+ const name = scopeName ?? options.scopeName ?? "krakstack.events";
82
+ const records = scopes.get(name);
83
+ if (records)
84
+ records.push(record);
85
+ else
86
+ scopes.set(name, [record]);
87
+ }
88
+ return [
89
+ serialization.logs({
90
+ resourceLogs: [
91
+ {
92
+ resource,
93
+ scopeLogs: Array.from(scopes, ([name, records]) => ({
94
+ scope: { name },
95
+ logRecords: records
96
+ }))
97
+ }
98
+ ]
99
+ }),
100
+ Effect.void
101
+ ];
102
+ }
100
103
  });
101
104
  }));
102
105
  }
103
- var track = Effect.fnUntraced(function* (name, properties, options) {
104
- const event = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
106
+ var event = Effect.fnUntraced(function* (name, properties, options) {
107
+ const decoded = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
105
108
  name,
106
109
  properties,
107
110
  options
@@ -109,20 +112,20 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
109
112
  const events = yield* OtlpEvents;
110
113
  const clock = yield* Clock.Clock;
111
114
  const observedTime = clock.currentTimeNanosUnsafe().toString();
112
- const timestamp = event.options?.timestamp ? (BigInt(DateTime.toEpochMillis(event.options.timestamp)) * 1000000n).toString() : observedTime;
115
+ const timestamp = decoded.options?.timestamp ? (BigInt(DateTime.toEpochMillis(decoded.options.timestamp)) * 1000000n).toString() : observedTime;
113
116
  const span = yield* Effect.currentSpan.pipe(Effect.option);
114
- const attributes = { ...event.options?.context, ...event.properties };
115
- if (event.options?.userId)
116
- attributes["user.id"] = event.options.userId;
117
- if (event.options?.anonymousId)
118
- attributes["analytics.anonymous_id"] = event.options.anonymousId;
119
- if (event.options?.sessionId)
120
- attributes["session.id"] = event.options.sessionId;
121
- if (event.options?.messageId)
122
- attributes["log.record.uid"] = event.options.messageId;
117
+ const attributes = { ...decoded.options?.context, ...decoded.properties };
118
+ if (decoded.options?.userId)
119
+ attributes["user.id"] = decoded.options.userId;
120
+ if (decoded.options?.anonymousId)
121
+ attributes["analytics.anonymous_id"] = decoded.options.anonymousId;
122
+ if (decoded.options?.sessionId)
123
+ attributes["session.id"] = decoded.options.sessionId;
124
+ if (decoded.options?.messageId)
125
+ attributes["log.record.uid"] = decoded.options.messageId;
123
126
  const annotations = yield* References.CurrentLogAnnotations;
124
127
  events.push({
125
- eventName: event.name,
128
+ eventName: decoded.name,
126
129
  timeUnixNano: timestamp,
127
130
  observedTimeUnixNano: observedTime,
128
131
  severityNumber: 9,
@@ -137,10 +140,6 @@ var track = Effect.fnUntraced(function* (name, properties, options) {
137
140
  });
138
141
 
139
142
  // ../../src/services/opentelemetry/browser.ts
140
- class BrowserIdentityState extends Context2.Service()("krakstack/opentelemetry/BrowserIdentity") {
141
- static layer = Layer2.effect(this, Ref.make({}));
142
- }
143
-
144
143
  class BrowserReportedError extends Schema3.TaggedError()("BrowserReportedError", {
145
144
  type: Schema3.Literals(["window.error", "unhandledrejection"]),
146
145
  message: Schema3.String,
@@ -197,124 +196,21 @@ var BrowserLifecycleFlushingLive = Layer2.effectDiscard(Effect2.gen(function* ()
197
196
  globalThis.removeEventListener("pagehide", flush);
198
197
  }));
199
198
  }));
200
- var browserEffects = {
201
- identify: Effect2.fnUntraced(function* (input) {
202
- const identity = yield* Schema3.decodeUnknownEffect(BrowserIdentity)(input === null ? {} : input);
203
- const state = yield* BrowserIdentityState;
204
- yield* Ref.set(state, identity);
205
- }),
206
- track: Effect2.fnUntraced(function* (name, properties, options) {
207
- const state = yield* BrowserIdentityState;
208
- const identity = yield* Ref.get(state);
209
- const annotations = {};
210
- if (identity.userId)
211
- annotations["user.id"] = identity.userId;
212
- if (identity.organizationId)
213
- annotations["organization.id"] = identity.organizationId;
214
- const scoped = yield* References2.CurrentLogAnnotations;
215
- yield* track(name, properties, options).pipe(Effect2.annotateLogs({ ...annotations, ...scoped }));
216
- }),
217
- page: Effect2.fnUntraced(function* (input = {}) {
218
- const page = yield* Schema3.decodeUnknownEffect(PageEvent)(input);
219
- const properties = { ...page.properties };
220
- if (page.name)
221
- properties["analytics.page.name"] = page.name;
222
- if (page.category)
223
- properties["analytics.page.category"] = page.category;
224
- properties["url.path"] = (page.path ?? globalThis.location.pathname).split(/[?#]/, 1)[0] ?? "/";
225
- yield* browserEffects.track("browser.page_view", properties, page.options);
226
- })
227
- };
228
- var browserClients = [];
229
- var runBrowser = (program) => Effect2.suspend(() => {
230
- const client = browserClients.at(-1);
231
- if (!client)
232
- return Effect2.void;
233
- return program.pipe(Effect2.provideService(BrowserIdentityState, client.identity), Effect2.provideService(OtlpEvents, client.events));
234
- });
235
- var BrowserClientLive = Layer2.effectDiscard(Effect2.gen(function* () {
236
- const identity = yield* BrowserIdentityState;
237
- const events = yield* OtlpEvents;
238
- yield* Effect2.acquireRelease(Effect2.sync(() => {
239
- const client = { identity, events };
240
- browserClients.push(client);
241
- return client;
242
- }), (client) => Effect2.sync(() => {
243
- const index = browserClients.indexOf(client);
244
- if (index !== -1)
245
- browserClients.splice(index, 1);
246
- }));
247
- }));
248
- var pageViewListeners = new Set;
249
- var stopPageViewTracking;
250
- var subscribePageViews = (listener) => {
251
- if (pageViewListeners.size === 0) {
252
- const history = globalThis.history;
253
- const pushState = history.pushState;
254
- const replaceState = history.replaceState;
255
- const notify = () => {
256
- for (const onPage of pageViewListeners)
257
- onPage();
258
- };
259
- const trackedPushState = (...args) => {
260
- pushState.apply(history, args);
261
- notify();
262
- };
263
- const trackedReplaceState = (...args) => {
264
- replaceState.apply(history, args);
265
- notify();
266
- };
267
- history.pushState = trackedPushState;
268
- history.replaceState = trackedReplaceState;
269
- globalThis.addEventListener("popstate", notify);
270
- stopPageViewTracking = () => {
271
- globalThis.removeEventListener("popstate", notify);
272
- if (history.pushState === trackedPushState)
273
- history.pushState = pushState;
274
- if (history.replaceState === trackedReplaceState)
275
- history.replaceState = replaceState;
276
- };
277
- }
278
- pageViewListeners.add(listener);
279
- return () => {
280
- pageViewListeners.delete(listener);
281
- if (pageViewListeners.size === 0) {
282
- stopPageViewTracking?.();
283
- stopPageViewTracking = undefined;
284
- }
285
- };
286
- };
287
- var BrowserPageViewsLive = Layer2.effectDiscard(Effect2.gen(function* () {
288
- const fibers = yield* FiberSet.make();
289
- const run = yield* FiberSet.runtime(fibers)();
290
- let previousPath = globalThis.location.pathname;
291
- yield* Effect2.acquireRelease(Effect2.sync(() => subscribePageViews(() => {
292
- const path = globalThis.location.pathname;
293
- if (path === previousPath)
294
- return;
295
- previousPath = path;
296
- run(browserEffects.page({ path }).pipe(Effect2.ignore));
297
- })), (unsubscribe) => Effect2.sync(unsubscribe));
298
- yield* browserEffects.page({ path: previousPath }).pipe(Effect2.ignore);
299
- }));
300
199
 
301
200
  class BrowserOtlp {
302
- static identify = (identity) => runBrowser(browserEffects.identify(identity)).pipe(Effect2.catch(() => Effect2.logWarning("Invalid browser telemetry identity; keeping previous identity")));
303
- static track = (name, properties, options) => runBrowser(browserEffects.track(name, properties, options));
304
- static page = (options) => runBrowser(browserEffects.page(options));
305
- static pageView = BrowserOtlp.page;
201
+ static event = event;
306
202
  static layer = ({
307
203
  attributes,
308
204
  baseUrl = "/api/otel",
309
205
  logs = false,
310
- events = false,
206
+ events = {},
311
207
  metrics = false,
312
208
  serviceName,
313
209
  serviceVersion,
314
210
  traces = {},
315
211
  headers
316
212
  }) => {
317
- const { pageViews = true, ...eventOptions } = events === false ? {} : events;
213
+ const eventOptions = events === false ? undefined : events;
318
214
  const resource = { attributes, serviceName, serviceVersion };
319
215
  const request = HttpClientRequest.get(baseUrl);
320
216
  const signalUrl = (signal) => HttpClientRequest.appendUrl(request, `/v1/${signal}`).url;
@@ -346,7 +242,7 @@ class BrowserOtlp {
346
242
  resource,
347
243
  headers
348
244
  }) : Layer2.empty).pipe(Layer2.provideMerge(OtlpExporter2.layerFlusher), Layer2.provide(OtlpSerialization2.layerJson), Layer2.provide(FetchHttpClient.layer));
349
- return Layer2.mergeAll(BrowserClientLive, BrowserLifecycleFlushingLive, events !== false && pageViews ? BrowserPageViewsLive : Layer2.empty, traces !== false ? BrowserExceptionTrackingLive : Layer2.empty).pipe(Layer2.provideMerge(Layer2.merge(BrowserIdentityState.layer, exporters)));
245
+ return Layer2.mergeAll(BrowserLifecycleFlushingLive, traces !== false ? BrowserExceptionTrackingLive : Layer2.empty).pipe(Layer2.provideMerge(exporters));
350
246
  };
351
247
  }
352
248
  export {
@@ -2,6 +2,7 @@ import { Context, DateTime, Effect, Layer, Schema } from "effect";
2
2
  import { OtlpExporter, OtlpResource, OtlpSerialization } from "effect/observability";
3
3
  type ExporterOptions = Pick<Parameters<typeof OtlpExporter.make>[0], "url" | "headers" | "exportInterval" | "maxBatchSize" | "shutdownTimeout"> & {
4
4
  readonly resource?: Parameters<typeof OtlpResource.fromConfig>[0];
5
+ readonly scopeName?: string;
5
6
  };
6
7
  export type EventExportOptions = Partial<Pick<ExporterOptions, "exportInterval" | "maxBatchSize" | "shutdownTimeout">>;
7
8
  declare const OtlpEvents_base: Context.ServiceClass<OtlpEvents, "krakstack/opentelemetry/Events", {
@@ -12,6 +13,7 @@ export declare class OtlpEvents extends OtlpEvents_base {
12
13
  static readonly layer: (options: ExporterOptions) => Layer.Layer<OtlpEvents, never, OtlpExporter.Flusher | import("effect/http/HttpClient").HttpClient | OtlpSerialization.OtlpSerialization>;
13
14
  }
14
15
  interface EventRecord {
16
+ readonly scopeName?: string;
15
17
  readonly eventName: string;
16
18
  readonly timeUnixNano: string;
17
19
  readonly observedTimeUnixNano: string;
@@ -22,7 +24,7 @@ interface EventRecord {
22
24
  readonly spanId?: string;
23
25
  }
24
26
  /** Emits an INFO event without creating a tracing span or persisting identity. */
25
- export declare const track: (name: string, properties?: {
27
+ export declare const event: (name: string, properties?: {
26
28
  readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
27
29
  } | undefined, options?: {
28
30
  readonly userId?: string | undefined;