@krak-stack/registry 0.1.53 → 0.1.55

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.
@@ -4,13 +4,13 @@ import {
4
4
  Context as Context4,
5
5
  Crypto,
6
6
  DateTime as DateTime2,
7
- Effect as Effect7,
7
+ Effect as Effect8,
8
8
  Layer as Layer3,
9
- Option as Option5,
9
+ Option as Option6,
10
10
  Predicate,
11
11
  Redacted,
12
12
  References as References2,
13
- Schema as Schema8
13
+ Schema as Schema9
14
14
  } from "effect";
15
15
  import { HttpServerRequest } from "effect/http";
16
16
  import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
@@ -57,6 +57,16 @@ import {
57
57
 
58
58
  // ../../src/services/opentelemetry/schema.ts
59
59
  import { Schema as Schema2 } from "effect";
60
+ var BrowserAnalyticsPreference = Schema2.Struct({
61
+ version: Schema2.String,
62
+ choice: Schema2.Literals(["accepted", "declined"]),
63
+ revision: Schema2.String,
64
+ issuedAt: Schema2.Finite,
65
+ expiresAt: Schema2.Finite
66
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
67
+ var BrowserPrivacySignals = Schema2.Struct({
68
+ globalPrivacyControl: Schema2.optional(Schema2.Boolean)
69
+ }).annotate({ identifier: "BrowserPrivacySignals" });
60
70
  var BrowserWebVital = Schema2.Struct({
61
71
  name: Schema2.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
62
72
  id: Schema2.NonEmptyString.check(Schema2.isMaxLength(64)),
@@ -106,7 +116,9 @@ class OtlpEvents extends Context2.Service()("krakstack/opentelemetry/Events") {
106
116
  label: "OtlpEvents",
107
117
  body: (logRecords) => {
108
118
  const scopes = new Map;
109
- for (const { scopeName, ...record } of logRecords) {
119
+ for (const { scopeName, canExport, ...record } of logRecords) {
120
+ if (canExport && !canExport())
121
+ continue;
110
122
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
111
123
  const records = scopes.get(name);
112
124
  if (records)
@@ -383,10 +395,16 @@ var TrackEvent = Schema6.Union([
383
395
  target: AuditTarget
384
396
  })
385
397
  ]).annotate({ identifier: "TrackEvent" });
386
- var ListAudit = Schema6.Struct({
398
+ var EventQuery = Schema6.Struct({
399
+ ...Query.fields,
400
+ eventName: Schema6.optional(trackEventFields.name)
401
+ }).annotate({ identifier: "EventQuery" });
402
+ var EventQueryStandard = Schema6.toStandardSchemaV1(EventQuery);
403
+ var ListEvents = Schema6.Struct({
387
404
  organizationId: Schema6.NonEmptyString,
388
- ...Query.fields
389
- }).annotate({ identifier: "ListAudit" });
405
+ category: Schema6.Literals(["audit", "analytics"]),
406
+ ...EventQuery.fields
407
+ }).annotate({ identifier: "ListEvents" });
390
408
  var AuditSortId = Schema6.Literals([
391
409
  "time",
392
410
  "eventName",
@@ -498,15 +516,15 @@ var cloudflareGeolocation = (headers) => ({
498
516
  region: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
499
517
  city: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
500
518
  });
501
- var geolocationAttributes = (location) => {
519
+ var geolocationAttributes = (location2) => {
502
520
  const attributes = {};
503
- if (location?.country) {
504
- attributes["geo.country.iso_code"] = location.country;
505
- if (location.region)
506
- attributes["geo.region.iso_code"] = `${location.country}-${location.region}`;
521
+ if (location2?.country) {
522
+ attributes["geo.country.iso_code"] = location2.country;
523
+ if (location2.region)
524
+ attributes["geo.region.iso_code"] = `${location2.country}-${location2.region}`;
507
525
  }
508
- if (location?.city)
509
- attributes["geo.locality.name"] = location.city;
526
+ if (location2?.city)
527
+ attributes["geo.locality.name"] = location2.city;
510
528
  return attributes;
511
529
  };
512
530
  var deviceContext = (userAgent) => {
@@ -557,6 +575,25 @@ var migrateEvents = Migrator.make({})({
557
575
  table: "events_migrations"
558
576
  });
559
577
 
578
+ // ../../src/services/opentelemetry/consent.ts
579
+ import { Effect as Effect7, Option as Option5, Schema as Schema8 } from "effect";
580
+ var ANALYTICS_CONSENT_COOKIE = "krakstack_analytics_consent";
581
+ var ANALYTICS_NOTICE_VERSION = "1";
582
+ var lifetime = 180 * 24 * 60 * 60 * 1000;
583
+ var codec = Schema8.StringFromUriComponent.pipe(Schema8.decodeTo(Schema8.fromJsonString(BrowserAnalyticsPreference)));
584
+ var readCookie = (cookie) => cookie.split(";").map((part) => part.trim()).find((part) => part.startsWith(`${ANALYTICS_CONSENT_COOKIE}=`))?.slice(ANALYTICS_CONSENT_COOKIE.length + 1);
585
+ var analyticsPreference = (cookie, now = Date.now()) => {
586
+ const value = readCookie(cookie);
587
+ if (!value)
588
+ return;
589
+ const decoded = Schema8.decodeUnknownOption(codec)(value);
590
+ if (Option5.isNone(decoded))
591
+ return;
592
+ const preference = decoded.value;
593
+ return preference.version === ANALYTICS_NOTICE_VERSION && preference.issuedAt <= now && preference.expiresAt > now && preference.expiresAt - preference.issuedAt <= lifetime ? preference : undefined;
594
+ };
595
+ var hasAnalyticsConsent = (cookie, headers = {}) => analyticsPreference(cookie)?.choice === "accepted" && headers.dnt !== "1" && headers.dnt !== "yes" && headers["sec-gpc"] !== "1";
596
+
560
597
  // ../../src/services/events/index.ts
561
598
  var SESSION_TIMEOUT_MS = 30 * 60 * 1000;
562
599
  var identityAttributes = (identity) => {
@@ -576,19 +613,19 @@ var actorAttributeKeys = [
576
613
  "user.roles"
577
614
  ];
578
615
  var reservedBrowserAttribute = (key) => key.startsWith("app.user.") || key.startsWith("user.") || key.startsWith("app.actor.") || key.startsWith("app.auth.") || key.startsWith("app.audit.") || key.startsWith("app.executor.") || key === "app.access.channel";
579
- var Configuration = Schema8.Struct({
580
- serviceName: Schema8.NonEmptyString,
581
- origin: Schema8.URLFromString.check(Schema8.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
582
- geolocation: Schema8.optional(Schema8.Union([
583
- Schema8.Literal("cloudflare"),
584
- Schema8.declare((value) => Predicate.isFunction(value))
616
+ var Configuration = Schema9.Struct({
617
+ serviceName: Schema9.NonEmptyString,
618
+ origin: Schema9.URLFromString.check(Schema9.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
619
+ geolocation: Schema9.optional(Schema9.Union([
620
+ Schema9.Literal("cloudflare"),
621
+ Schema9.declare((value) => Predicate.isFunction(value))
585
622
  ])),
586
- secret: Schema8.String.check(Schema8.isMinLength(32))
623
+ secret: Schema9.String.check(Schema9.isMinLength(32))
587
624
  }).annotate({ identifier: "EventsConfiguration" });
588
625
 
589
- class EventsConfigurationError extends Schema8.TaggedError()("EventsConfigurationError", { message: Schema8.String }) {
626
+ class EventsConfigurationError extends Schema9.TaggedError()("EventsConfigurationError", { message: Schema9.String }) {
590
627
  }
591
- var codec = Schema8.fromJsonString(OtlpLogs);
628
+ var codec2 = Schema9.fromJsonString(OtlpLogs);
592
629
  var textAttribute = (record, key) => {
593
630
  const value = record.attributes.find((attribute) => attribute.key === key)?.value;
594
631
  return value && "stringValue" in value ? value.stringValue : undefined;
@@ -618,16 +655,16 @@ var eventContent = (record, source, compareTimestamp = source === "browser") =>
618
655
  "app.event.schema.version"
619
656
  ].includes(key) || key === "user.id" || key === "organization.id").sort((a, b) => a.key.localeCompare(b.key))
620
657
  });
621
- var dailyVisitorId = Effect7.fnUntraced(function* (input) {
622
- const crypto = yield* Crypto.Crypto;
658
+ var dailyVisitorId = Effect8.fnUntraced(function* (input) {
659
+ const crypto2 = yield* Crypto.Crypto;
623
660
  const encoder = new TextEncoder;
624
- const salt = yield* crypto.digest("SHA-256", encoder.encode(JSON.stringify([
661
+ const salt = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
625
662
  "analytics.visitor.salt.v2",
626
663
  Redacted.value(input.secret),
627
664
  input.serviceName,
628
665
  input.day
629
666
  ])));
630
- const digest = yield* crypto.digest("SHA-256", encoder.encode(JSON.stringify([
667
+ const digest = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
631
668
  "analytics.visitor.v2",
632
669
  input.serviceName,
633
670
  input.day,
@@ -639,19 +676,20 @@ var dailyVisitorId = Effect7.fnUntraced(function* (input) {
639
676
  });
640
677
 
641
678
  class Events extends Context4.Service()("krakstack/events/Events", {
642
- make: (options) => Effect7.gen(function* () {
643
- const crypto = yield* Crypto.Crypto;
679
+ make: (options) => Effect8.gen(function* () {
680
+ const crypto2 = yield* Crypto.Crypto;
644
681
  const telemetry = yield* Otlp;
682
+ const exporter = yield* OtlpEvents;
645
683
  const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
646
- const configuration = yield* Schema8.decodeUnknownEffect(Configuration)({
684
+ const configuration = yield* Schema9.decodeUnknownEffect(Configuration)({
647
685
  ...options,
648
686
  serviceName: OtlpResource3.serviceNameUnsafe(resource),
649
687
  secret: Redacted.value(options.secret)
650
- }).pipe(Effect7.mapError(() => new EventsConfigurationError({
688
+ }).pipe(Effect8.mapError(() => new EventsConfigurationError({
651
689
  message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
652
690
  })));
653
- const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
654
- const storage = Option5.isSome(client) ? yield* Effect7.gen(function* () {
691
+ const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
692
+ const storage = Option6.isSome(client) ? yield* Effect8.gen(function* () {
655
693
  const sql = client.value.withoutTransforms();
656
694
  if (!sql.onDialectOrElse({
657
695
  pg: () => true,
@@ -692,10 +730,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
692
730
  ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
693
731
  `
694
732
  });
695
- const persist = Effect7.fnUntraced(function* (input) {
733
+ const persist = Effect8.fnUntraced(function* (input) {
696
734
  const { record, payload, now, source } = input;
697
735
  const eventId = textAttribute(record, "log.record.uid");
698
- const payloadJson = yield* Schema8.encodeEffect(codec)(payload);
736
+ const payloadJson = yield* Schema9.encodeEffect(codec2)(payload);
699
737
  const inserted = yield* insertEvent({
700
738
  source,
701
739
  event_id: eventId,
@@ -709,10 +747,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
709
747
  anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
710
748
  payload_json: payloadJson
711
749
  });
712
- if (Option5.isSome(inserted))
750
+ if (Option6.isSome(inserted))
713
751
  return { eventId, inserted: true, record };
714
752
  const existing = yield* existingEvent({ source, eventId });
715
- const original = yield* Schema8.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
753
+ const original = yield* Schema9.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
716
754
  const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
717
755
  if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
718
756
  return yield* new EventConflictError({ eventId });
@@ -726,24 +764,24 @@ class Events extends Context4.Service()("krakstack/events/Events", {
726
764
  lockVisitor
727
765
  };
728
766
  }) : undefined;
729
- const resolveGeolocation = Effect7.fnUntraced(function* (request) {
730
- const location = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
731
- return yield* Schema8.decodeUnknownEffect(Schema8.NullOr(EventGeolocation))(location);
732
- }, Effect7.mapError(() => new EventGeolocationError({})));
733
- const resolveRequestContext = Effect7.fnUntraced(function* (request, now, location) {
767
+ const resolveGeolocation = Effect8.fnUntraced(function* (request) {
768
+ const location2 = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
769
+ return yield* Schema9.decodeUnknownEffect(Schema9.NullOr(EventGeolocation))(location2);
770
+ }, Effect8.mapError(() => new EventGeolocationError({})));
771
+ const resolveRequestContext = Effect8.fnUntraced(function* (request, now, location2) {
734
772
  const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
735
- const visitorId = location?.ip && userAgent ? yield* dailyVisitorId({
773
+ const visitorId = location2?.ip && userAgent ? yield* dailyVisitorId({
736
774
  serviceName: configuration.serviceName,
737
775
  secret: options.secret,
738
- ip: location.ip,
776
+ ip: location2.ip,
739
777
  userAgent,
740
778
  day: DateTime2.formatIsoDate(now)
741
- }).pipe(Effect7.provideService(Crypto.Crypto, crypto)) : undefined;
779
+ }).pipe(Effect8.provideService(Crypto.Crypto, crypto2)) : undefined;
742
780
  let sessionId;
743
781
  if (visitorId && storage) {
744
782
  yield* storage.lockVisitor(visitorId);
745
783
  const latest = yield* storage.latestSession({ visitorId });
746
- sessionId = Option5.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : yield* crypto.randomUUIDv7;
784
+ sessionId = Option6.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : yield* crypto2.randomUUIDv7;
747
785
  }
748
786
  const identity = {};
749
787
  if (visitorId)
@@ -752,34 +790,33 @@ class Events extends Context4.Service()("krakstack/events/Events", {
752
790
  identity["session.id"] = sessionId;
753
791
  return {
754
792
  ...deviceContext(userAgent),
755
- ...geolocationAttributes(location),
793
+ ...geolocationAttributes(location2),
756
794
  "analytics.identity.mode": visitorId ? "daily" : "unattributed",
757
795
  ...identity
758
796
  };
759
797
  });
760
- const track = Effect7.fn("Events.track")(function* (input) {
761
- const event = yield* Schema8.decodeUnknownEffect(TrackEvent)(input);
762
- const eventId = event.eventId ?? (yield* crypto.randomUUIDv7);
798
+ const track = Effect8.fn("Events.track")(function* (input) {
799
+ const event = yield* Schema9.decodeUnknownEffect(TrackEvent)(input);
800
+ const eventId = event.eventId ?? (yield* crypto2.randomUUIDv7);
763
801
  const category = event.category ?? "analytics";
764
- if (!storage)
765
- return yield* new EventsPersistenceError({
766
- operation: "persistence-disabled"
767
- });
768
802
  const receivedAt = yield* DateTime2.now;
769
803
  const now = DateTime2.toEpochMillis(receivedAt);
770
- const request = yield* Effect7.serviceOption(HttpServerRequest.HttpServerRequest);
804
+ const request = yield* Effect8.serviceOption(HttpServerRequest.HttpServerRequest);
771
805
  const annotations = yield* References2.CurrentLogAnnotations;
806
+ if (category === "analytics" && options.requireConsent && (Option6.isNone(request) || !hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers))) {
807
+ return { eventId, inserted: false };
808
+ }
772
809
  const hasIdentity = [
773
810
  "user.id",
774
811
  "organization.id",
775
812
  ...actorAttributeKeys
776
813
  ].some((key) => annotations[key] !== undefined);
777
- const identity = hasIdentity ? yield* Schema8.decodeUnknownEffect(EventIdentity)({
814
+ const identity = hasIdentity ? yield* Schema9.decodeUnknownEffect(EventIdentity)({
778
815
  userId: annotations["user.id"],
779
816
  organizationId: annotations["organization.id"]
780
817
  }) : event.identity;
781
818
  if (category === "audit") {
782
- yield* Schema8.decodeUnknownEffect(AuditAttribution)(annotations);
819
+ yield* Schema9.decodeUnknownEffect(AuditAttribution)(annotations);
783
820
  }
784
821
  const attributes = {};
785
822
  for (const [key, value] of Object.entries(event.properties ?? {})) {
@@ -788,7 +825,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
788
825
  attributes[name] = value;
789
826
  }
790
827
  Object.assign(attributes, identityAttributes(identity));
791
- Object.assign(attributes, Object.fromEntries(Object.entries(annotations).filter(([key]) => key !== "user.full_name" && key !== "user.name" && key !== "user.image" && key !== "app.user.image")));
828
+ Object.assign(attributes, Object.fromEntries(Object.entries(annotations).filter(([key]) => (category === "audit" || !["user.full_name", "user.name", "user.email"].includes(key)) && key !== "user.image" && key !== "app.user.image")));
792
829
  attributes["log.record.uid"] = eventId;
793
830
  if (event.category === "audit") {
794
831
  attributes["app.audit.target.id"] = event.target.id;
@@ -799,22 +836,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
799
836
  attributes["app.event.type"] = "track";
800
837
  attributes["app.event.source"] = "server";
801
838
  attributes["app.event.category"] = category;
802
- const span = yield* Effect7.currentSpan.pipe(Effect7.option);
803
- const location = Option5.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect7.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
839
+ const span = yield* Effect8.currentSpan.pipe(Effect8.option);
840
+ const location2 = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveGeolocation(request.value).pipe(Effect8.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
804
841
  const entry = {
805
842
  eventName: event.name,
806
843
  timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
807
844
  observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
808
845
  };
809
- return yield* Effect7.gen(function* () {
810
- const requestContext = Option5.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
811
- const validated = yield* Schema8.decodeUnknownEffect(EventLogRecord)({
846
+ return yield* Effect8.gen(function* () {
847
+ const requestContext = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveRequestContext(request.value, receivedAt, location2) : {};
848
+ const validated = yield* Schema9.decodeUnknownEffect(EventLogRecord)({
812
849
  ...entry,
813
850
  attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
814
- traceId: Option5.isSome(span) ? span.value.traceId : undefined,
815
- spanId: Option5.isSome(span) ? span.value.spanId : undefined
851
+ traceId: Option6.isSome(span) ? span.value.traceId : undefined,
852
+ spanId: Option6.isSome(span) ? span.value.spanId : undefined
816
853
  });
817
- return yield* storage.persist({
854
+ const result = storage ? yield* storage.persist({
818
855
  source: "server",
819
856
  compareTimestamp: event.timestamp !== undefined,
820
857
  record: validated,
@@ -832,13 +869,25 @@ class Events extends Context4.Service()("krakstack/events/Events", {
832
869
  }
833
870
  ]
834
871
  }
835
- });
836
- }).pipe(storage.sql.withTransaction, Effect7.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect7.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
872
+ }) : { eventId, inserted: false };
873
+ return {
874
+ ...result,
875
+ attributes: { ...requestContext, ...attributes }
876
+ };
877
+ }).pipe((effect) => storage ? storage.sql.withTransaction(effect) : effect, Effect8.tap((result) => !storage || result.inserted ? Otlp.event(event.name, result.attributes, {
878
+ messageId: result.eventId,
879
+ timestamp: event.timestamp ?? receivedAt
880
+ }).pipe(Effect8.provideService(OtlpEvents, {
881
+ push: (record) => exporter.push({
882
+ ...record,
883
+ scopeName: "krakstack.application.events"
884
+ })
885
+ }), Effect8.provideService(References2.CurrentLogAnnotations, {})) : Effect8.void), Effect8.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect8.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
837
886
  operation: "track"
838
887
  })));
839
888
  });
840
- const listAudit = Effect7.fn("Events.listAudit")(function* (input) {
841
- const request = yield* Schema8.decodeUnknownEffect(ListAudit)(input);
889
+ const list = Effect8.fn("Events.list")(function* (input) {
890
+ const request = yield* Schema9.decodeUnknownEffect(ListEvents)(input);
842
891
  if (!storage)
843
892
  return yield* new EventsPersistenceError({
844
893
  operation: "persistence-disabled"
@@ -861,21 +910,12 @@ class Events extends Context4.Service()("krakstack/events/Events", {
861
910
  actorType: text("app.actor.type"),
862
911
  actorId: text("app.actor.id")
863
912
  };
864
- const sort = yield* Effect7.forEach(request.sort ?? [], (part) => Effect7.gen(function* () {
865
- const id = yield* Schema8.decodeUnknownEffect(AuditSortId)(part.id);
913
+ const sort = yield* Effect8.forEach(request.sort ?? [], (part) => Effect8.gen(function* () {
914
+ const id = yield* Schema9.decodeUnknownEffect(AuditSortId)(part.id);
866
915
  return sql`${sortColumns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")}`;
867
916
  }));
868
- const category = sql.onDialectOrElse({
869
- pg: () => sql`jsonb_path_exists(payload_json, '$.resourceLogs[*].scopeLogs[*].logRecords[*].attributes[*] ? (@.key == "app.event.category" && @.value.stringValue == "audit")')`,
870
- orElse: () => sql`EXISTS (
871
- SELECT 1 FROM json_each(payload_json, '$.resourceLogs') AS resource,
872
- json_each(resource.value, '$.scopeLogs') AS scope,
873
- json_each(scope.value, '$.logRecords') AS record,
874
- json_each(record.value, '$.attributes') AS attribute
875
- WHERE json_extract(attribute.value, '$.key') = 'app.event.category'
876
- AND json_extract(attribute.value, '$.value.stringValue') = 'audit'
877
- )`
878
- });
917
+ const source = request.category === "audit" ? sql`AND source = 'server'` : sql``;
918
+ const event = request.eventName ? sql`AND event_name = ${request.eventName}` : sql``;
879
919
  const search = request.globalFilter?.trim();
880
920
  const filter = search ? sql`AND ${sql.or([
881
921
  sql`LOWER(event_name) LIKE ${`%${search.toLowerCase()}%`}`,
@@ -889,14 +929,14 @@ class Events extends Context4.Service()("krakstack/events/Events", {
889
929
  ].map((key) => sql`LOWER(${text(key)}) LIKE ${`%${search.toLowerCase()}%`}`)
890
930
  ])}` : sql``;
891
931
  const predicate = sql`service_name = ${configuration.serviceName} AND organization_id = ${request.organizationId}
892
- AND source = 'server' AND ${category} ${filter}`;
932
+ AND ${text("app.event.category")} = ${request.category} ${source} ${event} ${filter}`;
893
933
  const total = yield* SqlSchema.findOne({
894
- Request: ListAudit,
934
+ Request: ListEvents,
895
935
  Result: AuditCount,
896
936
  execute: () => sql`SELECT CAST(COUNT(*) AS INTEGER) AS total FROM events WHERE ${predicate}`
897
937
  })(request);
898
938
  const find = SqlSchema.findAll({
899
- Request: ListAudit,
939
+ Request: ListEvents,
900
940
  Result: StoredEventPayload,
901
941
  execute: () => sql`
902
942
  SELECT payload_json FROM events
@@ -906,7 +946,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
906
946
  `
907
947
  });
908
948
  const rows = yield* find(request);
909
- const data = yield* Effect7.forEach(rows, (row) => Schema8.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
949
+ const data = yield* Effect8.forEach(rows, (row) => Schema9.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
910
950
  return {
911
951
  data,
912
952
  meta: {
@@ -917,9 +957,30 @@ class Events extends Context4.Service()("krakstack/events/Events", {
917
957
  }
918
958
  };
919
959
  });
920
- const process = Effect7.fnUntraced(function* (body) {
960
+ const process = Effect8.fnUntraced(function* (body) {
921
961
  const request = yield* HttpServerRequest.HttpServerRequest;
922
- const payload = yield* Schema8.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
962
+ let payload = yield* Schema9.decodeUnknownEffect(codec2)(new TextDecoder().decode(body)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
963
+ if (options.requireConsent && !hasAnalyticsConsent(request.headers.cookie ?? "", request.headers)) {
964
+ payload = {
965
+ ...payload,
966
+ resourceLogs: payload.resourceLogs.map((resource) => ({
967
+ ...resource,
968
+ scopeLogs: resource.scopeLogs.filter((scope) => scope.scope?.name !== "krakstack.application.events").map((scope) => ({
969
+ ...scope,
970
+ logRecords: scope.logRecords.filter((record) => {
971
+ const parsed = Schema9.decodeUnknownOption(Schema9.Struct({
972
+ eventName: Schema9.optional(Schema9.String)
973
+ }))(record);
974
+ return Option6.isNone(parsed) || parsed.value.eventName !== "browser.web_vital";
975
+ })
976
+ }))
977
+ }))
978
+ };
979
+ return {
980
+ body: new TextEncoder().encode(yield* Schema9.encodeEffect(codec2)(payload).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })))),
981
+ persisted: false
982
+ };
983
+ }
923
984
  const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
924
985
  if (analyticsScopes.length === 0)
925
986
  return { body, persisted: false };
@@ -927,12 +988,12 @@ class Events extends Context4.Service()("krakstack/events/Events", {
927
988
  return yield* new OtlpProcessingError({ status: 403 });
928
989
  }
929
990
  const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
930
- const records = yield* Schema8.decodeUnknownEffect(Schema8.Array(EventLogRecord).check(Schema8.isMinLength(1), Schema8.isMaxLength(100)))(rawRecords).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
991
+ const records = yield* Schema9.decodeUnknownEffect(Schema9.Array(EventLogRecord).check(Schema9.isMinLength(1), Schema9.isMaxLength(100)))(rawRecords).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
931
992
  const now = yield* DateTime2.now;
932
993
  const nowMillis = DateTime2.toEpochMillis(now);
933
994
  for (const record of records) {
934
995
  const timestamp = BigInt(record.timeUnixNano) / 1000000n;
935
- if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option5.isNone(Schema8.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option5.isNone(Schema8.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option5.isNone(Schema8.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
996
+ if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option6.isNone(Schema9.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option6.isNone(Schema9.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option6.isNone(Schema9.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
936
997
  return yield* new OtlpProcessingError({ status: 400 });
937
998
  }
938
999
  }
@@ -942,18 +1003,18 @@ class Events extends Context4.Service()("krakstack/events/Events", {
942
1003
  "organization.id",
943
1004
  ...actorAttributeKeys
944
1005
  ].some((key) => annotations[key] !== undefined);
945
- const trustedIdentity = yield* (hasIdentity ? Schema8.decodeUnknownEffect(EventIdentity)({
1006
+ const trustedIdentity = yield* (hasIdentity ? Schema9.decodeUnknownEffect(EventIdentity)({
946
1007
  userId: annotations["user.id"],
947
1008
  organizationId: annotations["organization.id"]
948
- }) : options.identity ? options.identity(request).pipe(Effect7.flatMap(Schema8.decodeUnknownEffect(Schema8.NullOr(EventIdentity)))) : Effect7.succeed(null)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
949
- const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema8.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
1009
+ }) : options.identity ? options.identity(request).pipe(Effect8.flatMap(Schema9.decodeUnknownEffect(Schema9.NullOr(EventIdentity)))) : Effect8.succeed(null)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
1010
+ const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema9.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
950
1011
  const trustedAttributes = {
951
1012
  ...identityAttributes(trustedIdentity),
952
1013
  ...trustedActor
953
1014
  };
954
- const location = yield* resolveGeolocation(request).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
955
- const ingest = Effect7.gen(function* () {
956
- const requestContext = yield* resolveRequestContext(request, now, location);
1015
+ const location2 = yield* resolveGeolocation(request).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
1016
+ const ingest = Effect8.gen(function* () {
1017
+ const requestContext = yield* resolveRequestContext(request, now, location2);
957
1018
  let index = 0;
958
1019
  const resourceLogs = payload.resourceLogs.map((resource) => ({
959
1020
  ...resource,
@@ -991,7 +1052,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
991
1052
  if (scope.scope?.name !== "krakstack.application.events")
992
1053
  continue;
993
1054
  for (const raw of scope.logRecords) {
994
- const record = yield* Schema8.decodeUnknownEffect(EventLogRecord)(raw);
1055
+ const record = yield* Schema9.decodeUnknownEffect(EventLogRecord)(raw);
995
1056
  const persisted = yield* storage.persist({
996
1057
  source: "browser",
997
1058
  record,
@@ -1011,7 +1072,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1011
1072
  }
1012
1073
  }
1013
1074
  }
1014
- const encoded = yield* Schema8.encodeEffect(codec)({
1075
+ const encoded = yield* Schema9.encodeEffect(codec2)({
1015
1076
  ...payload,
1016
1077
  resourceLogs: resourceLogs.map((resource) => ({
1017
1078
  ...resource,
@@ -1024,22 +1085,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1024
1085
  const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
1025
1086
  return { body: new TextEncoder().encode(encoded), persisted };
1026
1087
  });
1027
- return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect7.mapError((error) => new OtlpProcessingError({
1088
+ return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect8.mapError((error) => new OtlpProcessingError({
1028
1089
  status: error._tag === "EventConflictError" ? 409 : 503
1029
1090
  })));
1030
1091
  });
1031
- return { process, track, listAudit };
1092
+ return { process, track, list };
1032
1093
  })
1033
1094
  }) {
1034
- static baseLayerWith = (options = {}) => Layer3.effect(this, Effect7.gen(function* () {
1095
+ static baseLayerWith = (options = {}) => Layer3.effect(this, Effect8.gen(function* () {
1035
1096
  const origin = options.origin ?? (yield* Config2.URL("VITE_SITE_URL").pipe(Config2.map((url) => url.origin)));
1036
1097
  const secret = options.secret ?? (yield* Config2.Redacted("APP_SECRET"));
1037
1098
  return yield* Events.make({ ...options, origin, secret });
1038
1099
  }));
1039
1100
  static baseLayer = this.baseLayerWith();
1040
- static layerWith = (options = {}) => this.baseLayerWith(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect7.gen(function* () {
1041
- const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
1042
- if (Option5.isNone(client))
1101
+ static layerWith = (options = {}) => this.baseLayerWith(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect8.gen(function* () {
1102
+ const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
1103
+ if (Option6.isNone(client))
1043
1104
  return;
1044
1105
  if (!client.value.onDialectOrElse({
1045
1106
  pg: () => true,
@@ -1050,7 +1111,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1050
1111
  message: "Events supports PostgreSQL and SQLite"
1051
1112
  });
1052
1113
  }
1053
- yield* migrateEvents.pipe(Effect7.provideService(SqlClient2.SqlClient, client.value));
1114
+ yield* migrateEvents.pipe(Effect8.provideService(SqlClient2.SqlClient, client.value));
1054
1115
  }))));
1055
1116
  static layer = this.layerWith();
1056
1117
  static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
@@ -1060,7 +1121,7 @@ export {
1060
1121
  EventLogRecord,
1061
1122
  Events,
1062
1123
  EventsConfigurationError,
1063
- ListAudit,
1124
+ ListEvents,
1064
1125
  SESSION_TIMEOUT_MS,
1065
1126
  TrackEvent,
1066
1127
  dailyVisitorId
@@ -72,7 +72,7 @@ export declare const TrackEvent: Schema.Union<readonly [Schema.Struct<{
72
72
  }>;
73
73
  }>]>;
74
74
  export type TrackEvent = typeof TrackEvent.Type;
75
- export declare const ListAudit: Schema.Struct<{
75
+ export declare const EventQuery: Schema.Struct<{
76
76
  readonly page: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
77
77
  readonly pageSize: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
78
78
  readonly globalFilter: Schema.optional<Schema.String>;
@@ -83,7 +83,57 @@ export declare const ListAudit: Schema.Struct<{
83
83
  readonly id: string;
84
84
  readonly direction: "asc" | "desc";
85
85
  }[]>>;
86
+ /** Exact, case-sensitive event name; combined with category and query filters. */
87
+ readonly eventName: Schema.optional<Schema.NonEmptyString>;
88
+ }>;
89
+ export type EventQuery = typeof EventQuery.Type;
90
+ export declare const EventQueryStandard: import("effect/StandardSchema").StandardSchemaV1<{
91
+ readonly page?: string | number | undefined;
92
+ readonly pageSize?: string | number | undefined;
93
+ readonly globalFilter?: string | undefined;
94
+ readonly sort?: readonly {
95
+ readonly id: string;
96
+ readonly direction: "asc" | "desc";
97
+ }[] | undefined;
98
+ readonly eventName?: string | undefined;
99
+ }, {
100
+ readonly page: number;
101
+ readonly pageSize: number;
102
+ readonly globalFilter?: string | undefined;
103
+ readonly sort?: readonly {
104
+ readonly id: string;
105
+ readonly direction: "asc" | "desc";
106
+ }[] | undefined;
107
+ readonly eventName?: string | undefined;
108
+ }> & Schema.Struct<{
109
+ readonly page: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
110
+ readonly pageSize: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
111
+ readonly globalFilter: Schema.optional<Schema.String>;
112
+ readonly sort: Schema.optional<Schema.declare<readonly {
113
+ readonly id: string;
114
+ readonly direction: "asc" | "desc";
115
+ }[], readonly {
116
+ readonly id: string;
117
+ readonly direction: "asc" | "desc";
118
+ }[]>>;
119
+ /** Exact, case-sensitive event name; combined with category and query filters. */
120
+ readonly eventName: Schema.optional<Schema.NonEmptyString>;
121
+ }>;
122
+ export declare const ListEvents: Schema.Struct<{
123
+ readonly page: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
124
+ readonly pageSize: Schema.decodeTo<Schema.Int, Schema.optional<Schema.Union<readonly [Schema.Number, Schema.NumberFromString]>>, never, never>;
125
+ readonly globalFilter: Schema.optional<Schema.String>;
126
+ readonly sort: Schema.optional<Schema.declare<readonly {
127
+ readonly id: string;
128
+ readonly direction: "asc" | "desc";
129
+ }[], readonly {
130
+ readonly id: string;
131
+ readonly direction: "asc" | "desc";
132
+ }[]>>;
133
+ /** Exact, case-sensitive event name; combined with category and query filters. */
134
+ readonly eventName: Schema.optional<Schema.NonEmptyString>;
86
135
  readonly organizationId: Schema.NonEmptyString;
136
+ readonly category: Schema.Literals<readonly ["audit", "analytics"]>;
87
137
  }>;
88
138
  export declare const AuditSortId: Schema.Literals<readonly ["time", "eventName", "recordType", "record", "actorType", "actorId"]>;
89
139
  export declare const AuditCount: Schema.Struct<{