@plasius/analytics 1.3.2 → 1.4.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/dist/index.cjs CHANGED
@@ -9,9 +9,9 @@ var __export = (target, all) => {
9
9
  };
10
10
  var __copyProps = (to, from, except, desc) => {
11
11
  if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
12
+ for (let key2 of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
14
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
15
15
  }
16
16
  return to;
17
17
  };
@@ -21,7 +21,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AnalyticsProvider: () => AnalyticsProvider,
24
+ ProjectedSemanticJourneyAggregateStore: () => ProjectedSemanticJourneyAggregateStore,
25
+ SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES: () => SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES,
24
26
  SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION: () => SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
27
+ SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION: () => SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION,
25
28
  SEMANTIC_JOURNEY_RECEIPT_HEADER: () => SEMANTIC_JOURNEY_RECEIPT_HEADER,
26
29
  SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES: () => SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
27
30
  SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT: () => SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
@@ -45,10 +48,12 @@ __export(src_exports, {
45
48
  createProducerId: () => createProducerId,
46
49
  createRequestJourneyContext: () => createRequestJourneyContext,
47
50
  createSecureRandomHex: () => createSecureRandomHex,
51
+ createSemanticJourneyAggregateValidator: () => createSemanticJourneyAggregateValidator,
48
52
  createSemanticJourneyClient: () => createSemanticJourneyClient,
49
53
  createSpanId: () => createSpanId,
50
54
  createTraceId: () => createTraceId,
51
55
  defineJourneyEvent: () => defineJourneyEvent,
56
+ defineSemanticJourneyAggregatePolicy: () => defineSemanticJourneyAggregatePolicy,
52
57
  defineSemanticJourneyCatalog: () => defineSemanticJourneyCatalog,
53
58
  formatTraceparent: () => formatTraceparent,
54
59
  getJourneyEventDefinition: () => getJourneyEventDefinition,
@@ -57,6 +62,7 @@ __export(src_exports, {
57
62
  isJourneyToken: () => isJourneyToken,
58
63
  isProducerId: () => isProducerId,
59
64
  isSecureSemanticJourneyEndpoint: () => isSecureSemanticJourneyEndpoint,
65
+ isSemanticJourneyAggregatePolicy: () => isSemanticJourneyAggregatePolicy,
60
66
  isSemanticSource: () => isSemanticSource,
61
67
  isSemanticToken: () => isSemanticToken,
62
68
  isSpanId: () => isSpanId,
@@ -64,8 +70,10 @@ __export(src_exports, {
64
70
  observeSemanticJourneyInteractions: () => observeSemanticJourneyInteractions,
65
71
  parseSemanticJourneyReceipts: () => parseSemanticJourneyReceipts,
66
72
  parseTraceparent: () => parseTraceparent,
73
+ projectSemanticJourneyAggregateCounters: () => projectSemanticJourneyAggregateCounters,
67
74
  projectUsefulMetric: () => projectUsefulMetric,
68
75
  reconstructSemanticJourney: () => reconstructSemanticJourney,
76
+ semanticJourneyAggregateCounterKey: () => semanticJourneyAggregateCounterKey,
69
77
  serializeSemanticJourneyReceipts: () => serializeSemanticJourneyReceipts,
70
78
  useAnalytics: () => useAnalytics,
71
79
  useComponentInteractionTracker: () => useComponentInteractionTracker,
@@ -290,7 +298,8 @@ async function defaultTransport({
290
298
  endpoint,
291
299
  body,
292
300
  headers,
293
- keepalive
301
+ keepalive,
302
+ signal
294
303
  }) {
295
304
  if (typeof fetch !== "function") {
296
305
  return;
@@ -299,7 +308,8 @@ async function defaultTransport({
299
308
  method: "POST",
300
309
  headers,
301
310
  body,
302
- keepalive
311
+ keepalive,
312
+ signal
303
313
  });
304
314
  if (!response.ok) {
305
315
  throw new Error(`Analytics transport failed with status ${response.status}.`);
@@ -473,8 +483,8 @@ function sanitizeMultiline(value, maxLength) {
473
483
  function isPlainObject(value) {
474
484
  return value !== null && typeof value === "object" && !Array.isArray(value);
475
485
  }
476
- function shouldRedactContextKey(key, resolvedErrorReporting) {
477
- const loweredKey = key.trim().toLowerCase();
486
+ function shouldRedactContextKey(key2, resolvedErrorReporting) {
487
+ const loweredKey = key2.trim().toLowerCase();
478
488
  if (!loweredKey) {
479
489
  return false;
480
490
  }
@@ -554,10 +564,10 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
554
564
  }
555
565
  const sanitized = {};
556
566
  const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
557
- for (const [key, nestedValue] of entries) {
558
- const childPath = keyPath ? `${keyPath}.${key}` : key;
559
- if (shouldRedactContextKey(key, resolvedErrorReporting)) {
560
- sanitized[key] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
567
+ for (const [key2, nestedValue] of entries) {
568
+ const childPath = keyPath ? `${keyPath}.${key2}` : key2;
569
+ if (shouldRedactContextKey(key2, resolvedErrorReporting)) {
570
+ sanitized[key2] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
561
571
  pushIdentifier(
562
572
  identifiers,
563
573
  childPath,
@@ -566,7 +576,7 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
566
576
  );
567
577
  continue;
568
578
  }
569
- sanitized[key] = sanitizeContextValue(
579
+ sanitized[key2] = sanitizeContextValue(
570
580
  nestedValue,
571
581
  resolvedErrorReporting,
572
582
  depth + 1,
@@ -587,19 +597,19 @@ function sanitizeErrorContext(context, resolvedErrorReporting) {
587
597
  const identifiers = [];
588
598
  const seen = /* @__PURE__ */ new WeakSet();
589
599
  const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
590
- for (const [key, value] of entries) {
591
- if (shouldRedactContextKey(key, resolvedErrorReporting)) {
592
- sanitized[key] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
593
- pushIdentifier(identifiers, key, value, resolvedErrorReporting.maxMessageLength);
600
+ for (const [key2, value] of entries) {
601
+ if (shouldRedactContextKey(key2, resolvedErrorReporting)) {
602
+ sanitized[key2] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
603
+ pushIdentifier(identifiers, key2, value, resolvedErrorReporting.maxMessageLength);
594
604
  continue;
595
605
  }
596
- sanitized[key] = sanitizeContextValue(
606
+ sanitized[key2] = sanitizeContextValue(
597
607
  value,
598
608
  resolvedErrorReporting,
599
609
  1,
600
610
  seen,
601
611
  identifiers,
602
- key
612
+ key2
603
613
  );
604
614
  }
605
615
  return {
@@ -783,7 +793,7 @@ function readQueue(storageKey, fallbackConfig) {
783
793
  if (!Array.isArray(parsed)) {
784
794
  return [];
785
795
  }
786
- return parsed.filter(isStoredRecordCandidate).map((record) => normalizeStoredRecord(record, fallbackConfig));
796
+ return parsed.filter(isStoredRecordCandidate).map((record2) => normalizeStoredRecord(record2, fallbackConfig));
787
797
  } catch {
788
798
  return [];
789
799
  }
@@ -853,6 +863,7 @@ function createLocalSpaceAnalyticsClient(config) {
853
863
  let isFlushing = false;
854
864
  let flushQueuedAfterCurrent = false;
855
865
  let isDestroyed = false;
866
+ const transportController = new AbortController();
856
867
  const issueAggregates = /* @__PURE__ */ new Map();
857
868
  const persistQueue = () => writeQueue(resolvedConfig.storageKey, queue);
858
869
  const trimQueue = () => {
@@ -947,12 +958,12 @@ function createLocalSpaceAnalyticsClient(config) {
947
958
  return right.lastSeen - left.lastSeen;
948
959
  });
949
960
  };
950
- const enqueueRecord = (record) => {
951
- queue.push(record);
961
+ const enqueueRecord = (record2) => {
962
+ queue.push(record2);
952
963
  trimQueue();
953
964
  persistQueue();
954
- if (record.kind === "error" && record.error) {
955
- recordIssue(record.error, record.timestamp, true);
965
+ if (record2.kind === "error" && record2.error) {
966
+ recordIssue(record2.error, record2.timestamp, true);
956
967
  }
957
968
  if (queue.length >= resolvedConfig.batchSize) {
958
969
  void flush();
@@ -1019,12 +1030,14 @@ function createLocalSpaceAnalyticsClient(config) {
1019
1030
  body,
1020
1031
  headers: resolvedConfig.headers,
1021
1032
  // Normal flushes do not need fetch keepalive; unload/pagehide uses sendBeacon.
1022
- keepalive: false
1033
+ keepalive: false,
1034
+ signal: transportController.signal
1023
1035
  });
1036
+ if (transportController.signal.aborted) return;
1024
1037
  queue = queue.slice(events.length);
1025
1038
  persistQueue();
1026
1039
  } catch (error) {
1027
- resolvedConfig.onError?.(error);
1040
+ if (!transportController.signal.aborted) resolvedConfig.onError?.(error);
1028
1041
  } finally {
1029
1042
  isFlushing = false;
1030
1043
  if (flushQueuedAfterCurrent) {
@@ -1067,9 +1080,9 @@ function createLocalSpaceAnalyticsClient(config) {
1067
1080
  document.addEventListener("visibilitychange", handleVisibilityChange);
1068
1081
  window.addEventListener("pagehide", handlePageHide);
1069
1082
  }
1070
- for (const record of queue) {
1071
- if (record.kind === "error" && record.error) {
1072
- recordIssue(record.error, record.timestamp, false);
1083
+ for (const record2 of queue) {
1084
+ if (record2.kind === "error" && record2.error) {
1085
+ recordIssue(record2.error, record2.timestamp, false);
1073
1086
  }
1074
1087
  }
1075
1088
  startFlushTimer();
@@ -1088,7 +1101,7 @@ function createLocalSpaceAnalyticsClient(config) {
1088
1101
  const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
1089
1102
  const kind = event.kind === "error" ? "error" : "interaction";
1090
1103
  const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
1091
- const record = {
1104
+ const record2 = {
1092
1105
  id: createId("event"),
1093
1106
  component: event.component,
1094
1107
  action: event.action,
@@ -1105,7 +1118,7 @@ function createLocalSpaceAnalyticsClient(config) {
1105
1118
  context: createMergedContext(resolvedConfig, eventChannel, event.context),
1106
1119
  error: normalizedError
1107
1120
  };
1108
- enqueueRecord(record);
1121
+ enqueueRecord(record2);
1109
1122
  };
1110
1123
  const reportError = (report) => {
1111
1124
  if (isDestroyed || !resolvedConfig.enabled) {
@@ -1139,7 +1152,7 @@ function createLocalSpaceAnalyticsClient(config) {
1139
1152
  if (normalizedError.tags && normalizedError.tags.length > 0) {
1140
1153
  errorContext.errorTags = normalizedError.tags;
1141
1154
  }
1142
- const record = {
1155
+ const record2 = {
1143
1156
  id: createId("event"),
1144
1157
  component: normalizedError.boundary,
1145
1158
  action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
@@ -1153,7 +1166,7 @@ function createLocalSpaceAnalyticsClient(config) {
1153
1166
  context: createMergedContext(resolvedConfig, eventChannel, errorContext),
1154
1167
  error: normalizedError
1155
1168
  };
1156
- enqueueRecord(record);
1169
+ enqueueRecord(record2);
1157
1170
  };
1158
1171
  return {
1159
1172
  get source() {
@@ -1197,7 +1210,14 @@ function createLocalSpaceAnalyticsClient(config) {
1197
1210
  getConfig() {
1198
1211
  return resolvedConfig;
1199
1212
  },
1200
- destroy() {
1213
+ destroy(options) {
1214
+ if (options?.discard) {
1215
+ transportController.abort();
1216
+ queue = [];
1217
+ flushQueuedAfterCurrent = false;
1218
+ issueAggregates.clear();
1219
+ writeQueue(resolvedConfig.storageKey, []);
1220
+ }
1201
1221
  if (isDestroyed) {
1202
1222
  return;
1203
1223
  }
@@ -1414,13 +1434,13 @@ function isRecord(value) {
1414
1434
  }
1415
1435
  function getOwnStringKeys(value) {
1416
1436
  const keys = Reflect.ownKeys(value);
1417
- if (keys.some((key) => typeof key !== "string")) {
1437
+ if (keys.some((key2) => typeof key2 !== "string")) {
1418
1438
  return null;
1419
1439
  }
1420
1440
  return keys;
1421
1441
  }
1422
1442
  function hasOnlyFields(keys, allowed) {
1423
- return keys.every((key) => allowed.has(key));
1443
+ return keys.every((key2) => allowed.has(key2));
1424
1444
  }
1425
1445
  function sensitivityWords(value) {
1426
1446
  return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
@@ -1540,11 +1560,11 @@ function normalizeEventDefinition(candidate) {
1540
1560
  if (targetKeys === null || targetKeys.length !== 2 || !hasOnlyFields(targetKeys, TARGET_FIELDS) || !isSemanticToken(target.type) || !isSemanticToken(target.id) || looksSensitive(target.type) || looksSensitive(target.id)) {
1541
1561
  return invalidDefinition();
1542
1562
  }
1543
- const key = `${target.type}\0${target.id}`;
1544
- if (seenTargets.has(key)) {
1563
+ const key2 = `${target.type}\0${target.id}`;
1564
+ if (seenTargets.has(key2)) {
1545
1565
  return invalidDefinition();
1546
1566
  }
1547
- seenTargets.add(key);
1567
+ seenTargets.add(key2);
1548
1568
  targets.push(Object.freeze({ type: target.type, id: target.id }));
1549
1569
  }
1550
1570
  }
@@ -1726,12 +1746,12 @@ function createSecureRandomHex(byteLength2, randomBytes = webCryptoRandomBytes)
1726
1746
  if (!Number.isSafeInteger(byteLength2) || byteLength2 <= 0 || byteLength2 > MAX_RANDOM_BYTE_LENGTH) {
1727
1747
  throw new Error("Secure random byte length is invalid.");
1728
1748
  }
1729
- const bytes = randomBytes(byteLength2);
1730
- if (!(bytes instanceof Uint8Array) || bytes.byteLength !== byteLength2) {
1749
+ const bytes2 = randomBytes(byteLength2);
1750
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== byteLength2) {
1731
1751
  throw new Error("Secure random source returned invalid bytes.");
1732
1752
  }
1733
1753
  let result = "";
1734
- for (const byte of bytes) {
1754
+ for (const byte of bytes2) {
1735
1755
  result += byte.toString(16).padStart(2, "0");
1736
1756
  }
1737
1757
  return result;
@@ -1898,29 +1918,29 @@ var SemanticJourneyAggregateStore = class {
1898
1918
  }
1899
1919
  this.options = Object.freeze({ ...options });
1900
1920
  }
1901
- record(eventName, outcome, count = 1) {
1921
+ record(eventName, outcome, count2 = 1) {
1902
1922
  if (!isSemanticToken(eventName) || getJourneyEventDefinition(this.options.catalogue, eventName) === void 0 || !OUTCOMES2.has(outcome)) {
1903
1923
  invalidAggregate();
1904
1924
  }
1905
- normalizeLimit(count, 1, "counter increment");
1906
- const key = toCounterKey(eventName, outcome);
1907
- const existing = this.counters.get(key);
1908
- this.counters.set(key, Object.freeze({
1925
+ normalizeLimit(count2, 1, "counter increment");
1926
+ const key2 = toCounterKey(eventName, outcome);
1927
+ const existing = this.counters.get(key2);
1928
+ this.counters.set(key2, Object.freeze({
1909
1929
  eventName,
1910
1930
  outcome,
1911
- count: addSafeCount(existing?.count ?? 0, count)
1931
+ count: addSafeCount(existing?.count ?? 0, count2)
1912
1932
  }));
1913
1933
  }
1914
- recordDropped(count = 1) {
1934
+ recordDropped(count2 = 1) {
1915
1935
  this.dropped = addSafeCount(
1916
1936
  this.dropped,
1917
- normalizeLimit(count, 1, "dropped increment")
1937
+ normalizeLimit(count2, 1, "dropped increment")
1918
1938
  );
1919
1939
  }
1920
- recordCoalesced(count = 1) {
1940
+ recordCoalesced(count2 = 1) {
1921
1941
  this.coalesced = addSafeCount(
1922
1942
  this.coalesced,
1923
- normalizeLimit(count, 1, "coalesced increment")
1943
+ normalizeLimit(count2, 1, "coalesced increment")
1924
1944
  );
1925
1945
  }
1926
1946
  snapshot() {
@@ -1976,16 +1996,16 @@ var SemanticJourneyAggregateStore = class {
1976
1996
  }
1977
1997
  acknowledge(batch) {
1978
1998
  for (const acknowledged of batch.counters) {
1979
- const key = toCounterKey(acknowledged.eventName, acknowledged.outcome);
1980
- const current = this.counters.get(key);
1999
+ const key2 = toCounterKey(acknowledged.eventName, acknowledged.outcome);
2000
+ const current = this.counters.get(key2);
1981
2001
  if (!current) {
1982
2002
  continue;
1983
2003
  }
1984
2004
  const remaining = current.count - acknowledged.count;
1985
2005
  if (remaining > 0) {
1986
- this.counters.set(key, Object.freeze({ ...current, count: remaining }));
2006
+ this.counters.set(key2, Object.freeze({ ...current, count: remaining }));
1987
2007
  } else {
1988
- this.counters.delete(key);
2008
+ this.counters.delete(key2);
1989
2009
  }
1990
2010
  }
1991
2011
  this.dropped = Math.max(0, this.dropped - batch.dropped);
@@ -2004,6 +2024,395 @@ var SemanticJourneyAggregateStore = class {
2004
2024
  }
2005
2025
  };
2006
2026
 
2027
+ // src/journey/aggregate-policy.ts
2028
+ var SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION = "2.1-aggregate";
2029
+ var SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES = 64 * 1024;
2030
+ var policies = /* @__PURE__ */ new WeakSet();
2031
+ var outcomes = /* @__PURE__ */ new Set(["unknown", "success", "failure", "cancelled", "denied"]);
2032
+ var envelopeFields = ["schemaVersion", "batchId", "source", "channel", "runtime", "timeBucket", "policyVersion", "dropped", "coalesced", "counters"];
2033
+ var counterFields = ["eventName", "outcome", "count"];
2034
+ var projectedFields = [...counterFields, "view", "dimensions"];
2035
+ var encoder = new TextEncoder();
2036
+ function invalidPolicy() {
2037
+ throw new Error("Semantic aggregate policy is invalid.");
2038
+ }
2039
+ function invalidInput2() {
2040
+ throw new Error("Semantic aggregate input is invalid.");
2041
+ }
2042
+ function record(value, maxKeys = 32) {
2043
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2044
+ const prototype = Object.getPrototypeOf(value);
2045
+ if (prototype !== Object.prototype && prototype !== null) return false;
2046
+ const keys = Reflect.ownKeys(value);
2047
+ return keys.length <= maxKeys && keys.every((key2) => {
2048
+ const descriptor = Object.getOwnPropertyDescriptor(value, key2);
2049
+ return typeof key2 === "string" && descriptor?.enumerable && "value" in descriptor;
2050
+ });
2051
+ }
2052
+ function array(value, maximum) {
2053
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > maximum) return false;
2054
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
2055
+ for (let index = 0; index < value.length; index++) {
2056
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
2057
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) return false;
2058
+ }
2059
+ return true;
2060
+ }
2061
+ function exact(value, fields) {
2062
+ const keys = Object.keys(value);
2063
+ return keys.length === fields.length && keys.every((key2) => fields.includes(key2));
2064
+ }
2065
+ function count(value, minimum = 0) {
2066
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
2067
+ }
2068
+ function bindingKey(binding) {
2069
+ return `${binding.source}\0${binding.channel}\0${binding.runtime}`;
2070
+ }
2071
+ function isSemanticJourneyAggregatePolicy(value) {
2072
+ return typeof value === "object" && value !== null && policies.has(value);
2073
+ }
2074
+ function defineSemanticJourneyAggregatePolicy(catalogue, options) {
2075
+ try {
2076
+ if (!record(options) || Object.keys(options).some((key2) => !["bindings", "projections"].includes(key2)) || !array(options.bindings, 128) || options.bindings.length === 0) return invalidPolicy();
2077
+ const frozenCatalogue = defineSemanticJourneyCatalog(catalogue.definitions, { sources: catalogue.sources });
2078
+ const bindings = [];
2079
+ const seenBindings = /* @__PURE__ */ new Set();
2080
+ for (const candidate of options.bindings) {
2081
+ if (!record(candidate) || !exact(candidate, ["source", "channel", "runtime"]) || typeof candidate.source !== "string" || !frozenCatalogue.sources.includes(candidate.source) || !(candidate.channel === "frontend" && candidate.runtime === "browser" || candidate.channel === "backend" && candidate.runtime === "server")) return invalidPolicy();
2082
+ const binding = candidate;
2083
+ const key2 = bindingKey(binding);
2084
+ if (seenBindings.has(key2)) return invalidPolicy();
2085
+ seenBindings.add(key2);
2086
+ bindings.push(Object.freeze({ ...binding }));
2087
+ }
2088
+ const projections = /* @__PURE__ */ Object.create(null);
2089
+ const candidates = options.projections ?? {};
2090
+ if (!record(candidates, 2048)) return invalidPolicy();
2091
+ for (const [eventName, views] of Object.entries(candidates)) {
2092
+ const definition = getJourneyEventDefinition(frozenCatalogue, eventName);
2093
+ if (!definition || !record(views, 8) || Object.keys(views).length === 0) return invalidPolicy();
2094
+ const normalized = /* @__PURE__ */ Object.create(null);
2095
+ for (const [view, dimensions] of Object.entries(views)) {
2096
+ if (view === "total" || !array(dimensions, 4) || dimensions.length === 0 || new Set(dimensions).size !== dimensions.length) return invalidPolicy();
2097
+ defineSemanticJourneyCatalog({ "aggregate.view": {
2098
+ category: "state",
2099
+ attributes: { [view]: { type: "enum", values: ["registered"] } }
2100
+ } }, { sources: frozenCatalogue.sources });
2101
+ let cardinality = 1;
2102
+ const names = [];
2103
+ for (const dimension of dimensions) {
2104
+ const attribute = typeof dimension === "string" ? definition.attributes?.[dimension] : void 0;
2105
+ if (!attribute || attribute.type !== "enum") return invalidPolicy();
2106
+ cardinality *= attribute.values.length;
2107
+ if (cardinality > 4096) return invalidPolicy();
2108
+ names.push(dimension);
2109
+ }
2110
+ normalized[view] = Object.freeze(names.sort());
2111
+ }
2112
+ projections[eventName] = Object.freeze(normalized);
2113
+ }
2114
+ const policy = Object.freeze({ catalogue: frozenCatalogue, bindings: Object.freeze(bindings), projections: Object.freeze(projections) });
2115
+ policies.add(policy);
2116
+ return policy;
2117
+ } catch {
2118
+ return invalidPolicy();
2119
+ }
2120
+ }
2121
+ function projectSemanticJourneyAggregateCounters(policy, input, increment = 1) {
2122
+ try {
2123
+ if (!isSemanticJourneyAggregatePolicy(policy) || !count(increment, 1)) return invalidInput2();
2124
+ const event = validateSemanticJourneyEventInput(policy.catalogue, input);
2125
+ const base = { eventName: event.name, outcome: event.outcome, count: increment };
2126
+ const rows = [Object.freeze({ ...base, view: "total", dimensions: Object.freeze({}) })];
2127
+ for (const view of Object.keys(policy.projections[event.name] ?? {}).sort()) {
2128
+ const dimensions = /* @__PURE__ */ Object.create(null);
2129
+ const names = policy.projections[event.name][view];
2130
+ if (names.some((name) => event.attributes[name] === void 0)) continue;
2131
+ for (const name of names) dimensions[name] = event.attributes[name];
2132
+ rows.push(Object.freeze({ ...base, view, dimensions: Object.freeze(dimensions) }));
2133
+ }
2134
+ return Object.freeze(rows);
2135
+ } catch {
2136
+ return invalidInput2();
2137
+ }
2138
+ }
2139
+ function semanticJourneyAggregateCounterKey(counter) {
2140
+ if (!("view" in counter)) return JSON.stringify([counter.eventName, counter.outcome]);
2141
+ return JSON.stringify([
2142
+ counter.eventName,
2143
+ counter.outcome,
2144
+ counter.view,
2145
+ Object.keys(counter.dimensions).sort().map((key2) => [key2, counter.dimensions[key2]])
2146
+ ]);
2147
+ }
2148
+ function validCounter(policy, value, projected) {
2149
+ if (!record(value) || !exact(value, projected ? projectedFields : counterFields) || typeof value.eventName !== "string" || typeof value.outcome !== "string" || !outcomes.has(value.outcome) || !count(value.count, 1)) return false;
2150
+ const definition = getJourneyEventDefinition(policy.catalogue, value.eventName);
2151
+ if (!definition) return false;
2152
+ if (!projected) return true;
2153
+ if (typeof value.view !== "string" || !record(value.dimensions, 4)) return false;
2154
+ const dimensions = value.view === "total" ? [] : policy.projections[value.eventName]?.[value.view];
2155
+ if (!dimensions || !exact(value.dimensions, dimensions)) return false;
2156
+ for (const dimension of dimensions) {
2157
+ const attribute = definition.attributes?.[dimension];
2158
+ const supplied = value.dimensions[dimension];
2159
+ if (attribute?.type !== "enum" || typeof supplied !== "string" || !attribute.values.includes(supplied)) return false;
2160
+ }
2161
+ return true;
2162
+ }
2163
+ function createSemanticJourneyAggregateValidator(policy) {
2164
+ if (!isSemanticJourneyAggregatePolicy(policy)) return invalidPolicy();
2165
+ const bindings = new Set(policy.bindings.map(bindingKey));
2166
+ return (value) => {
2167
+ try {
2168
+ if (!record(value) || !exact(value, envelopeFields) || !["2.0-aggregate", "2.1-aggregate"].includes(value.schemaVersion) || !isEventId(value.batchId) || value.policyVersion !== "strict.v1" || typeof value.source !== "string" || value.source.length > 64 || !["frontend", "backend"].includes(value.channel) || !["browser", "server"].includes(value.runtime) || !bindings.has(bindingKey(value)) || typeof value.timeBucket !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:00:00\.000Z$/.test(value.timeBucket) || new Date(value.timeBucket).toISOString() !== value.timeBucket || !count(value.dropped) || !count(value.coalesced) || !array(value.counters, 500)) return false;
2169
+ const keys = /* @__PURE__ */ new Set();
2170
+ for (const counter of value.counters) {
2171
+ if (!validCounter(policy, counter, value.schemaVersion === "2.1-aggregate")) return false;
2172
+ const key2 = semanticJourneyAggregateCounterKey(counter);
2173
+ if (keys.has(key2)) return false;
2174
+ keys.add(key2);
2175
+ }
2176
+ return encoder.encode(JSON.stringify(value)).byteLength <= SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES;
2177
+ } catch {
2178
+ return false;
2179
+ }
2180
+ };
2181
+ }
2182
+
2183
+ // src/journey/projected-aggregate-store.ts
2184
+ var encoder2 = new TextEncoder();
2185
+ function invalid() {
2186
+ throw new Error("Semantic aggregate input is invalid.");
2187
+ }
2188
+ function bytes(value) {
2189
+ return encoder2.encode(JSON.stringify(value)).length;
2190
+ }
2191
+ function limit(value, fallback, minimum, maximum) {
2192
+ const selected = value ?? fallback;
2193
+ if (!Number.isSafeInteger(selected) || selected < minimum || selected > maximum) return invalid();
2194
+ return selected;
2195
+ }
2196
+ function hour(now) {
2197
+ if (!Number.isSafeInteger(now) || now < 0 || now > 253402300799999) return invalid();
2198
+ return new Date(Math.floor(now / 36e5) * 36e5).toISOString();
2199
+ }
2200
+ function add(left, right) {
2201
+ if (!Number.isSafeInteger(right) || right < 1 || !Number.isSafeInteger(left + right)) return invalid();
2202
+ return left + right;
2203
+ }
2204
+ function key(timeBucket, counter) {
2205
+ return `${timeBucket}\0${semanticJourneyAggregateCounterKey(counter)}`;
2206
+ }
2207
+ function minimumBatchBytes(options) {
2208
+ const envelope = {
2209
+ schemaVersion: "2.1-aggregate",
2210
+ batchId: "a".repeat(32),
2211
+ source: options.source,
2212
+ channel: options.channel,
2213
+ runtime: options.runtime,
2214
+ timeBucket: "9999-12-31T23:00:00.000Z",
2215
+ policyVersion: "strict.v1",
2216
+ dropped: Number.MAX_SAFE_INTEGER,
2217
+ coalesced: Number.MAX_SAFE_INTEGER
2218
+ };
2219
+ let minimum = bytes({ ...envelope, counters: [] });
2220
+ for (const [eventName, definition] of Object.entries(options.policy.catalogue.definitions)) {
2221
+ const base = { eventName, outcome: "cancelled", count: Number.MAX_SAFE_INTEGER };
2222
+ minimum = Math.max(minimum, bytes({ ...envelope, counters: [{ ...base, view: "total", dimensions: {} }] }));
2223
+ for (const [view, names] of Object.entries(options.policy.projections[eventName] ?? {})) {
2224
+ const dimensions = /* @__PURE__ */ Object.create(null);
2225
+ for (const name of names) {
2226
+ const attribute = definition.attributes?.[name];
2227
+ if (attribute?.type !== "enum") return invalid();
2228
+ dimensions[name] = attribute.values.reduce((longest, value) => bytes(value) > bytes(longest) ? value : longest);
2229
+ }
2230
+ minimum = Math.max(minimum, bytes({ ...envelope, counters: [{ ...base, view, dimensions }] }));
2231
+ }
2232
+ }
2233
+ return minimum;
2234
+ }
2235
+ var ProjectedSemanticJourneyAggregateStore = class {
2236
+ options;
2237
+ maxCounters;
2238
+ maxBytes;
2239
+ maxBatchBytes;
2240
+ minimumBatchBytes;
2241
+ maxAge;
2242
+ counters = /* @__PURE__ */ new Map();
2243
+ pendingBytes = 0;
2244
+ dropped = 0;
2245
+ coalesced = 0;
2246
+ diagnosticHour;
2247
+ diagnosticExpiry = 0;
2248
+ pending;
2249
+ constructor(options) {
2250
+ if (!isSemanticJourneyAggregatePolicy(options.policy) || !options.policy.bindings.some((binding) => binding.source === options.source && binding.channel === options.channel && binding.runtime === options.runtime)) invalid();
2251
+ this.maxCounters = limit(options.maxPendingCounters, 1e3, 1, 5e3);
2252
+ this.maxBytes = limit(options.maxPendingBytes, 1024 * 1024, 512, 8 * 1024 * 1024);
2253
+ this.minimumBatchBytes = minimumBatchBytes(options);
2254
+ this.maxBatchBytes = limit(options.maxBatchBytes, 48 * 1024, Math.max(512, this.minimumBatchBytes), 60 * 1024);
2255
+ this.maxAge = limit(options.maxAgeMs, 30 * 60 * 1e3, 1, 864e5);
2256
+ if (options.now !== void 0 && typeof options.now !== "function") invalid();
2257
+ this.options = Object.freeze({ ...options });
2258
+ }
2259
+ /** Return false on capacity pressure; never retain a partial set of views. */
2260
+ recordEvent(input, observedAt, increment = 1) {
2261
+ const timeBucket = hour(observedAt);
2262
+ const rows = projectSemanticJourneyAggregateCounters(this.options.policy, input, increment);
2263
+ this.prune(observedAt);
2264
+ const updates = [];
2265
+ let size = this.pendingBytes;
2266
+ let additions = 0;
2267
+ for (const row of rows) {
2268
+ const id = key(timeBucket, row);
2269
+ const existing = this.counters.get(id);
2270
+ const counter = Object.freeze({ ...row, count: add(existing?.counter.count ?? 0, increment) });
2271
+ const entry = {
2272
+ timeBucket,
2273
+ expiresAt: Math.min(existing?.expiresAt ?? Infinity, observedAt + this.maxAge),
2274
+ counter,
2275
+ // Conservative accounting includes duplicated key text and map bookkeeping.
2276
+ bytes: bytes(counter) + encoder2.encode(id).length + 64
2277
+ };
2278
+ size += entry.bytes - (existing?.bytes ?? 0);
2279
+ if (!existing) additions++;
2280
+ updates.push([id, entry]);
2281
+ }
2282
+ if (this.counters.size + additions > this.maxCounters || size > this.maxBytes) {
2283
+ this.diagnostic("dropped", increment, observedAt);
2284
+ return false;
2285
+ }
2286
+ for (const [id, entry] of updates) this.counters.set(id, entry);
2287
+ this.pendingBytes = size;
2288
+ return true;
2289
+ }
2290
+ recordDropped(increment = 1) {
2291
+ this.diagnostic("dropped", increment, this.now());
2292
+ }
2293
+ recordCoalesced(increment = 1) {
2294
+ this.diagnostic("coalesced", increment, this.now());
2295
+ }
2296
+ /** Read-only bounded diagnostics; never a persistence interface. */
2297
+ snapshot() {
2298
+ return Object.freeze({
2299
+ dropped: this.dropped,
2300
+ coalesced: this.coalesced,
2301
+ pendingCounters: this.counters.size,
2302
+ pendingBytes: this.pendingBytes,
2303
+ counters: Object.freeze(this.sorted().map((entry) => entry.counter))
2304
+ });
2305
+ }
2306
+ createBatch(options) {
2307
+ hour(options.nowEpochMs);
2308
+ if (!isEventId(options.batchId)) return invalid();
2309
+ const maxCounters = limit(options.maxCounters, 50, 1, 500);
2310
+ const maxBytes = limit(options.maxBytes, this.maxBatchBytes, Math.max(512, this.minimumBatchBytes), this.maxBatchBytes);
2311
+ this.prune(options.nowEpochMs);
2312
+ if (this.pending) return this.pending.batch;
2313
+ const entries = this.sorted();
2314
+ const earliest = entries[0]?.timeBucket;
2315
+ const timeBucket = earliest && this.diagnosticHour ? earliest < this.diagnosticHour ? earliest : this.diagnosticHour : earliest ?? this.diagnosticHour;
2316
+ if (!timeBucket) return null;
2317
+ const includeDiagnostics = timeBucket === this.diagnosticHour;
2318
+ const base = {
2319
+ schemaVersion: "2.1-aggregate",
2320
+ batchId: options.batchId,
2321
+ source: this.options.source,
2322
+ channel: this.options.channel,
2323
+ runtime: this.options.runtime,
2324
+ timeBucket,
2325
+ policyVersion: "strict.v1",
2326
+ dropped: includeDiagnostics ? this.dropped : 0,
2327
+ coalesced: includeDiagnostics ? this.coalesced : 0
2328
+ };
2329
+ const selected = [];
2330
+ let expiresAt = includeDiagnostics ? this.diagnosticExpiry : Infinity;
2331
+ for (const entry of entries) {
2332
+ if (entry.timeBucket !== timeBucket) continue;
2333
+ if (selected.length >= maxCounters || bytes({ ...base, counters: [...selected, entry.counter] }) > maxBytes) break;
2334
+ selected.push(entry.counter);
2335
+ expiresAt = Math.min(expiresAt, entry.expiresAt);
2336
+ }
2337
+ if (entries.some((entry) => entry.timeBucket === timeBucket) && selected.length === 0 || bytes({ ...base, counters: selected }) > maxBytes) return invalid();
2338
+ const batch = Object.freeze({ ...base, counters: Object.freeze(selected) });
2339
+ this.pending = { batch, expiresAt };
2340
+ return batch;
2341
+ }
2342
+ /** Check retry eligibility without extending the original snapshot's expiry. */
2343
+ isPendingBatch(batch, now) {
2344
+ this.prune(now);
2345
+ return this.pending?.batch === batch;
2346
+ }
2347
+ /** Only the exact issued snapshot may subtract counts, and only once. */
2348
+ acknowledge(batch) {
2349
+ if (this.pending?.batch !== batch) return;
2350
+ for (const counter of batch.counters) {
2351
+ const id = key(batch.timeBucket, counter);
2352
+ const current = this.counters.get(id);
2353
+ if (!current) continue;
2354
+ this.pendingBytes -= current.bytes;
2355
+ const remaining = current.counter.count - counter.count;
2356
+ if (remaining <= 0) this.counters.delete(id);
2357
+ else {
2358
+ const updatedCounter = Object.freeze({ ...current.counter, count: remaining });
2359
+ const updated = {
2360
+ ...current,
2361
+ counter: updatedCounter,
2362
+ bytes: bytes(updatedCounter) + encoder2.encode(id).length + 64
2363
+ };
2364
+ this.counters.set(id, updated);
2365
+ this.pendingBytes += updated.bytes;
2366
+ }
2367
+ }
2368
+ this.dropped = Math.max(0, this.dropped - batch.dropped);
2369
+ this.coalesced = Math.max(0, this.coalesced - batch.coalesced);
2370
+ if (!this.dropped && !this.coalesced) this.diagnosticHour = void 0;
2371
+ this.pending = void 0;
2372
+ }
2373
+ /** Discard aggregates and in-flight snapshot ownership; never flush. */
2374
+ clear() {
2375
+ this.counters.clear();
2376
+ this.pendingBytes = this.dropped = this.coalesced = this.diagnosticExpiry = 0;
2377
+ this.diagnosticHour = void 0;
2378
+ this.pending = void 0;
2379
+ }
2380
+ now() {
2381
+ return (this.options.now ?? Date.now)();
2382
+ }
2383
+ diagnostic(kind, increment, now) {
2384
+ const timeBucket = hour(now);
2385
+ this[kind] = add(this[kind], increment);
2386
+ if (!this.diagnosticHour) {
2387
+ this.diagnosticHour = timeBucket;
2388
+ this.diagnosticExpiry = now + this.maxAge;
2389
+ }
2390
+ }
2391
+ prune(now) {
2392
+ hour(now);
2393
+ if (this.pending && now >= this.pending.expiresAt) this.pending = void 0;
2394
+ if (this.diagnosticHour && now >= this.diagnosticExpiry) {
2395
+ this.dropped = this.coalesced = 0;
2396
+ this.diagnosticHour = void 0;
2397
+ }
2398
+ const expiredHours = new Set([...this.counters.values()].filter((entry) => now >= entry.expiresAt).map((entry) => entry.timeBucket));
2399
+ if (this.pending && expiredHours.has(this.pending.batch.timeBucket)) this.pending = void 0;
2400
+ for (const [id, entry] of this.counters) {
2401
+ if (!expiredHours.has(entry.timeBucket)) continue;
2402
+ this.counters.delete(id);
2403
+ this.pendingBytes -= entry.bytes;
2404
+ if (entry.counter.view === "total") this.diagnostic("dropped", entry.counter.count, now);
2405
+ }
2406
+ }
2407
+ sorted() {
2408
+ return [...this.counters.values()].sort((a, b) => {
2409
+ const left = key(a.timeBucket, a.counter);
2410
+ const right = key(b.timeBucket, b.counter);
2411
+ return left < right ? -1 : left > right ? 1 : 0;
2412
+ });
2413
+ }
2414
+ };
2415
+
2007
2416
  // src/journey/metrics.ts
2008
2417
  var durationBuckets = [
2009
2418
  [100, "lt100ms"],
@@ -2071,7 +2480,7 @@ function projectUsefulMetric(input) {
2071
2480
  const prototype = Object.getPrototypeOf(input);
2072
2481
  if (prototype !== Object.prototype && prototype !== null) return null;
2073
2482
  const keys = Reflect.ownKeys(input);
2074
- if (keys.length < 1 || keys.length > 2 || keys.some((key) => key !== "metric" && key !== "value")) return null;
2483
+ if (keys.length < 1 || keys.length > 2 || keys.some((key2) => key2 !== "metric" && key2 !== "value")) return null;
2075
2484
  const descriptors = Object.getOwnPropertyDescriptors(input);
2076
2485
  const metric = descriptors.metric;
2077
2486
  if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
@@ -2491,20 +2900,20 @@ function readDataRecord(value, allowedFields, requiredFields = /* @__PURE__ */ n
2491
2900
  return invalidRuntimeEvidence();
2492
2901
  }
2493
2902
  const keys = Reflect.ownKeys(value);
2494
- if (keys.length > maximumFields || keys.some((key) => typeof key !== "string")) {
2903
+ if (keys.length > maximumFields || keys.some((key2) => typeof key2 !== "string")) {
2495
2904
  return invalidRuntimeEvidence();
2496
2905
  }
2497
2906
  const stringKeys = keys;
2498
- if (allowedFields && stringKeys.some((key) => !allowedFields.has(key)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
2907
+ if (allowedFields && stringKeys.some((key2) => !allowedFields.has(key2)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
2499
2908
  return invalidRuntimeEvidence();
2500
2909
  }
2501
2910
  const result = /* @__PURE__ */ Object.create(null);
2502
- for (const key of stringKeys) {
2503
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2911
+ for (const key2 of stringKeys) {
2912
+ const descriptor = Object.getOwnPropertyDescriptor(value, key2);
2504
2913
  if (descriptor === void 0 || !("value" in descriptor)) {
2505
2914
  return invalidRuntimeEvidence();
2506
2915
  }
2507
- result[key] = descriptor.value;
2916
+ result[key2] = descriptor.value;
2508
2917
  }
2509
2918
  return result;
2510
2919
  }
@@ -2562,28 +2971,28 @@ function readOptionalIdentifier(value, validator) {
2562
2971
  return validator(value) ? value : invalidRuntimeEvidence();
2563
2972
  }
2564
2973
  function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2565
- const record = readDataRecord(
2974
+ const record2 = readDataRecord(
2566
2975
  candidate,
2567
2976
  EVENT_FIELDS,
2568
2977
  EVENT_REQUIRED_FIELDS,
2569
2978
  EVENT_FIELDS.size
2570
2979
  );
2571
- if (record.schemaVersion !== "2.0" || !isEventId(record.eventId) || !isJourneyId(record.journeyId) || !isTraceId(record.traceId) || !isSpanId(record.spanId) || !isProducerId(record.producerId) || !Number.isSafeInteger(record.producerSequence) || record.producerSequence < 1 || !Number.isSafeInteger(record.occurredAtEpochMs) || record.occurredAtEpochMs < 0 || !isSemanticSource(record.source) || !allowedSources.has(record.source) || !isValidChannelRuntime(record.channel, record.runtime)) {
2980
+ if (record2.schemaVersion !== "2.0" || !isEventId(record2.eventId) || !isJourneyId(record2.journeyId) || !isTraceId(record2.traceId) || !isSpanId(record2.spanId) || !isProducerId(record2.producerId) || !Number.isSafeInteger(record2.producerSequence) || record2.producerSequence < 1 || !Number.isSafeInteger(record2.occurredAtEpochMs) || record2.occurredAtEpochMs < 0 || !isSemanticSource(record2.source) || !allowedSources.has(record2.source) || !isValidChannelRuntime(record2.channel, record2.runtime)) {
2572
2981
  return invalidRuntimeEvidence();
2573
2982
  }
2574
- const parentSpanId = readOptionalIdentifier(record.parentSpanId, isSpanId);
2983
+ const parentSpanId = readOptionalIdentifier(record2.parentSpanId, isSpanId);
2575
2984
  const causedByEventId = readOptionalIdentifier(
2576
- record.causedByEventId,
2985
+ record2.causedByEventId,
2577
2986
  isEventId
2578
2987
  );
2579
2988
  const attributes = readDataRecord(
2580
- record.attributes,
2989
+ record2.attributes,
2581
2990
  void 0,
2582
2991
  /* @__PURE__ */ new Set(),
2583
2992
  MAX_EVENT_ATTRIBUTES2
2584
2993
  );
2585
2994
  const privacy = readDataRecord(
2586
- record.privacy,
2995
+ record2.privacy,
2587
2996
  PRIVACY_FIELDS,
2588
2997
  PRIVACY_FIELDS,
2589
2998
  PRIVACY_FIELDS.size
@@ -2592,9 +3001,9 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2592
3001
  return invalidRuntimeEvidence();
2593
3002
  }
2594
3003
  let target;
2595
- if (record.target !== void 0) {
3004
+ if (record2.target !== void 0) {
2596
3005
  const targetRecord = readDataRecord(
2597
- record.target,
3006
+ record2.target,
2598
3007
  TARGET_FIELDS2,
2599
3008
  TARGET_FIELDS2,
2600
3009
  TARGET_FIELDS2.size
@@ -2605,29 +3014,29 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2605
3014
  target = { type: targetRecord.type, id: targetRecord.id };
2606
3015
  }
2607
3016
  const input = {
2608
- name: record.name,
2609
- category: record.category,
2610
- phase: record.phase,
2611
- outcome: record.outcome,
2612
- ...record.modality === void 0 ? {} : { modality: record.modality },
3017
+ name: record2.name,
3018
+ category: record2.category,
3019
+ phase: record2.phase,
3020
+ outcome: record2.outcome,
3021
+ ...record2.modality === void 0 ? {} : { modality: record2.modality },
2613
3022
  ...target === void 0 ? {} : { target },
2614
3023
  attributes
2615
3024
  };
2616
3025
  const validated = validateSemanticJourneyEventInput(catalogue, input);
2617
3026
  return Object.freeze({
2618
3027
  schemaVersion: "2.0",
2619
- eventId: record.eventId,
2620
- journeyId: record.journeyId,
2621
- traceId: record.traceId,
2622
- spanId: record.spanId,
3028
+ eventId: record2.eventId,
3029
+ journeyId: record2.journeyId,
3030
+ traceId: record2.traceId,
3031
+ spanId: record2.spanId,
2623
3032
  ...parentSpanId === void 0 ? {} : { parentSpanId },
2624
3033
  ...causedByEventId === void 0 ? {} : { causedByEventId },
2625
- producerId: record.producerId,
2626
- producerSequence: record.producerSequence,
2627
- occurredAtEpochMs: record.occurredAtEpochMs,
2628
- source: record.source,
2629
- channel: record.channel,
2630
- runtime: record.runtime,
3034
+ producerId: record2.producerId,
3035
+ producerSequence: record2.producerSequence,
3036
+ occurredAtEpochMs: record2.occurredAtEpochMs,
3037
+ source: record2.source,
3038
+ channel: record2.channel,
3039
+ runtime: record2.runtime,
2631
3040
  name: validated.name,
2632
3041
  category: validated.category,
2633
3042
  phase: validated.phase,
@@ -2646,7 +3055,7 @@ function attributesEqual(left, right) {
2646
3055
  const leftKeys = Object.keys(left).sort(compareTokens);
2647
3056
  const rightKeys = Object.keys(right).sort(compareTokens);
2648
3057
  return leftKeys.length === rightKeys.length && leftKeys.every(
2649
- (key, index) => key === rightKeys[index] && Object.is(left[key], right[key])
3058
+ (key2, index) => key2 === rightKeys[index] && Object.is(left[key2], right[key2])
2650
3059
  );
2651
3060
  }
2652
3061
  function eventsEqual(left, right) {
@@ -2960,7 +3369,7 @@ function condensedCausalOrder(components) {
2960
3369
  }
2961
3370
  ready.sort(compareComponents);
2962
3371
  }
2963
- if (ordered.length !== components.reduce((count, item) => count + item.nodes.length, 0)) {
3372
+ if (ordered.length !== components.reduce((count2, item) => count2 + item.nodes.length, 0)) {
2964
3373
  return invalidRuntimeEvidence();
2965
3374
  }
2966
3375
  return ordered;
@@ -3292,6 +3701,7 @@ function resolveConfig2(config) {
3292
3701
  if (!config.catalogue.sources.includes(config.source)) {
3293
3702
  return invalidConfig();
3294
3703
  }
3704
+ if (config.aggregatePolicy !== void 0 && (!isSemanticJourneyAggregatePolicy(config.aggregatePolicy) || JSON.stringify(config.aggregatePolicy.catalogue) !== JSON.stringify(config.catalogue))) return invalidConfig();
3295
3705
  if (config.aggregateEndpoint !== void 0 && !isAllowedEndpoint(config.aggregateEndpoint, config.aggregateBaseUrl)) {
3296
3706
  return invalidConfig();
3297
3707
  }
@@ -3310,6 +3720,7 @@ function resolveConfig2(config) {
3310
3720
  );
3311
3721
  return {
3312
3722
  catalogue: config.catalogue,
3723
+ ...config.aggregatePolicy ? { aggregatePolicy: config.aggregatePolicy } : {},
3313
3724
  source: config.source,
3314
3725
  channel: resolveChannel2(config.channel, runtime),
3315
3726
  runtime,
@@ -3340,7 +3751,7 @@ function resolveConfig2(config) {
3340
3751
  ),
3341
3752
  maxBatchesPerFlush: resolveInteger(
3342
3753
  config.maxBatchesPerFlush,
3343
- DEFAULT_MAX_BATCHES_PER_FLUSH,
3754
+ config.aggregatePolicy ? 2 : DEFAULT_MAX_BATCHES_PER_FLUSH,
3344
3755
  1,
3345
3756
  MAX_BATCHES_PER_FLUSH
3346
3757
  ),
@@ -3418,11 +3829,11 @@ function jitteredDelay(attempt, config) {
3418
3829
  config.retryMaxDelayMs,
3419
3830
  config.retryBaseDelayMs * 2 ** attempt
3420
3831
  );
3421
- const bytes = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
3422
- if (!(bytes instanceof Uint8Array) || bytes.byteLength !== 2) {
3832
+ const bytes2 = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
3833
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== 2) {
3423
3834
  throw new Error("Semantic journey retry random source is invalid.");
3424
3835
  }
3425
- const sample = (bytes[0] ?? 0) << 8 | (bytes[1] ?? 0);
3836
+ const sample = (bytes2[0] ?? 0) << 8 | (bytes2[1] ?? 0);
3426
3837
  const factor = 0.5 + sample / 65535;
3427
3838
  return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
3428
3839
  }
@@ -3433,12 +3844,16 @@ function createSemanticJourneyClient(inputConfig) {
3433
3844
  } catch {
3434
3845
  return invalidConfig();
3435
3846
  }
3436
- const aggregateStore = new SemanticJourneyAggregateStore({
3437
- catalogue: config.catalogue,
3438
- source: config.source,
3439
- channel: config.channel,
3440
- runtime: config.runtime
3441
- });
3847
+ const binding = { source: config.source, channel: config.channel, runtime: config.runtime };
3848
+ const aggregateStore = config.aggregatePolicy ? new ProjectedSemanticJourneyAggregateStore({
3849
+ ...binding,
3850
+ policy: config.aggregatePolicy,
3851
+ maxPendingCounters: config.maxQueueEvents,
3852
+ maxPendingBytes: config.maxQueueBytes,
3853
+ maxBatchBytes: config.aggregateMaxBytes,
3854
+ maxAgeMs: config.maxEventAgeMs,
3855
+ now: config.now
3856
+ }) : new SemanticJourneyAggregateStore({ ...binding, catalogue: config.catalogue });
3442
3857
  const queue = [];
3443
3858
  const contextByEventId = /* @__PURE__ */ new Map();
3444
3859
  let episode;
@@ -3535,7 +3950,15 @@ function createSemanticJourneyClient(inputConfig) {
3535
3950
  droppedAttributeCount: validated.droppedAttributeCount
3536
3951
  })
3537
3952
  });
3538
- aggregateStore.record(event.name, event.outcome);
3953
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore) {
3954
+ if (!aggregateStore.recordEvent({
3955
+ name: validated.name,
3956
+ category: validated.category,
3957
+ phase: validated.phase,
3958
+ outcome: validated.outcome,
3959
+ attributes: validated.attributes
3960
+ }, nowEpochMs)) notifyDrop("queue-limit");
3961
+ } else aggregateStore.record(event.name, event.outcome);
3539
3962
  if (shouldCoalesce(
3540
3963
  queue[queue.length - 1]?.event,
3541
3964
  event,
@@ -3544,17 +3967,17 @@ function createSemanticJourneyClient(inputConfig) {
3544
3967
  aggregateStore.recordCoalesced();
3545
3968
  return void 0;
3546
3969
  }
3547
- const bytes = eventBytes(event);
3548
- if (bytes > config.maxQueueBytes) {
3970
+ const bytes2 = eventBytes(event);
3971
+ if (bytes2 > config.maxQueueBytes) {
3549
3972
  aggregateStore.recordDropped();
3550
3973
  notifyDrop("queue-limit");
3551
3974
  return void 0;
3552
3975
  }
3553
- while (queue.length >= config.maxQueueEvents || queueBytes + bytes > config.maxQueueBytes) {
3976
+ while (queue.length >= config.maxQueueEvents || queueBytes + bytes2 > config.maxQueueBytes) {
3554
3977
  removeFirstQueued("queue-limit");
3555
3978
  }
3556
- queue.push({ event, context: options.context, bytes });
3557
- queueBytes += bytes;
3979
+ queue.push({ event, context: options.context, bytes: bytes2 });
3980
+ queueBytes += bytes2;
3558
3981
  contextByEventId.set(event.eventId, options.context);
3559
3982
  if (usesLocalProducer) {
3560
3983
  currentEpisode.producerSequence = producerSequence;
@@ -3796,6 +4219,10 @@ function createSemanticJourneyClient(inputConfig) {
3796
4219
  if (destroyed || signal.aborted) {
3797
4220
  return "retained";
3798
4221
  }
4222
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && batch.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(batch, config.now())) {
4223
+ notifyDrop("expired");
4224
+ return "discarded";
4225
+ }
3799
4226
  try {
3800
4227
  await sendWithTimeout(batch, keepalive);
3801
4228
  return "sent";
@@ -3826,6 +4253,7 @@ function createSemanticJourneyClient(inputConfig) {
3826
4253
  const generation = aggregateGeneration;
3827
4254
  const signal = aggregateController.signal;
3828
4255
  for (let sentBatchCount = 0; sentBatchCount < config.maxBatchesPerFlush; sentBatchCount += 1) {
4256
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && pendingBatch?.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(pendingBatch, config.now())) pendingBatch = void 0;
3829
4257
  const batch = pendingBatch ?? aggregateStore.createBatch({
3830
4258
  batchId: createEventId(config.randomBytes),
3831
4259
  nowEpochMs: config.now(),
@@ -3843,7 +4271,9 @@ function createSemanticJourneyClient(inputConfig) {
3843
4271
  if (result === "retained") {
3844
4272
  return;
3845
4273
  }
3846
- aggregateStore.acknowledge(batch);
4274
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore) {
4275
+ if (batch.schemaVersion === "2.1-aggregate") aggregateStore.acknowledge(batch);
4276
+ } else if (batch.schemaVersion === "2.0-aggregate") aggregateStore.acknowledge(batch);
3847
4277
  pendingBatch = void 0;
3848
4278
  }
3849
4279
  };
@@ -4068,7 +4498,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
4068
4498
  // Annotate the CommonJS export names for ESM import in node:
4069
4499
  0 && (module.exports = {
4070
4500
  AnalyticsProvider,
4501
+ ProjectedSemanticJourneyAggregateStore,
4502
+ SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES,
4071
4503
  SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
4504
+ SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION,
4072
4505
  SEMANTIC_JOURNEY_RECEIPT_HEADER,
4073
4506
  SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
4074
4507
  SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
@@ -4092,10 +4525,12 @@ function useComponentInteractionTracker(component, baseContext = {}) {
4092
4525
  createProducerId,
4093
4526
  createRequestJourneyContext,
4094
4527
  createSecureRandomHex,
4528
+ createSemanticJourneyAggregateValidator,
4095
4529
  createSemanticJourneyClient,
4096
4530
  createSpanId,
4097
4531
  createTraceId,
4098
4532
  defineJourneyEvent,
4533
+ defineSemanticJourneyAggregatePolicy,
4099
4534
  defineSemanticJourneyCatalog,
4100
4535
  formatTraceparent,
4101
4536
  getJourneyEventDefinition,
@@ -4104,6 +4539,7 @@ function useComponentInteractionTracker(component, baseContext = {}) {
4104
4539
  isJourneyToken,
4105
4540
  isProducerId,
4106
4541
  isSecureSemanticJourneyEndpoint,
4542
+ isSemanticJourneyAggregatePolicy,
4107
4543
  isSemanticSource,
4108
4544
  isSemanticToken,
4109
4545
  isSpanId,
@@ -4111,8 +4547,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
4111
4547
  observeSemanticJourneyInteractions,
4112
4548
  parseSemanticJourneyReceipts,
4113
4549
  parseTraceparent,
4550
+ projectSemanticJourneyAggregateCounters,
4114
4551
  projectUsefulMetric,
4115
4552
  reconstructSemanticJourney,
4553
+ semanticJourneyAggregateCounterKey,
4116
4554
  serializeSemanticJourneyReceipts,
4117
4555
  useAnalytics,
4118
4556
  useComponentInteractionTracker,