@plasius/analytics 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -1
- package/dist/index.cjs +524 -98
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +103 -3
- package/dist/index.d.ts +103 -3
- package/dist/index.js +513 -95
- package/dist/index.js.map +1 -1
- package/dist/{metrics-B7L9phdM.d.cts → metrics-DhAg1PSO.d.cts} +1 -1
- package/dist/{metrics-B7L9phdM.d.ts → metrics-DhAg1PSO.d.ts} +1 -1
- package/dist/metrics.d.cts +1 -1
- package/dist/metrics.d.ts +1 -1
- package/package.json +2 -2
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
|
|
13
|
-
if (!__hasOwnProp.call(to,
|
|
14
|
-
__defProp(to,
|
|
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,
|
|
@@ -475,8 +483,8 @@ function sanitizeMultiline(value, maxLength) {
|
|
|
475
483
|
function isPlainObject(value) {
|
|
476
484
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
477
485
|
}
|
|
478
|
-
function shouldRedactContextKey(
|
|
479
|
-
const loweredKey =
|
|
486
|
+
function shouldRedactContextKey(key2, resolvedErrorReporting) {
|
|
487
|
+
const loweredKey = key2.trim().toLowerCase();
|
|
480
488
|
if (!loweredKey) {
|
|
481
489
|
return false;
|
|
482
490
|
}
|
|
@@ -556,10 +564,10 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
|
|
|
556
564
|
}
|
|
557
565
|
const sanitized = {};
|
|
558
566
|
const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
|
|
559
|
-
for (const [
|
|
560
|
-
const childPath = keyPath ? `${keyPath}.${
|
|
561
|
-
if (shouldRedactContextKey(
|
|
562
|
-
sanitized[
|
|
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;
|
|
563
571
|
pushIdentifier(
|
|
564
572
|
identifiers,
|
|
565
573
|
childPath,
|
|
@@ -568,7 +576,7 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
|
|
|
568
576
|
);
|
|
569
577
|
continue;
|
|
570
578
|
}
|
|
571
|
-
sanitized[
|
|
579
|
+
sanitized[key2] = sanitizeContextValue(
|
|
572
580
|
nestedValue,
|
|
573
581
|
resolvedErrorReporting,
|
|
574
582
|
depth + 1,
|
|
@@ -589,19 +597,19 @@ function sanitizeErrorContext(context, resolvedErrorReporting) {
|
|
|
589
597
|
const identifiers = [];
|
|
590
598
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
591
599
|
const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
|
|
592
|
-
for (const [
|
|
593
|
-
if (shouldRedactContextKey(
|
|
594
|
-
sanitized[
|
|
595
|
-
pushIdentifier(identifiers,
|
|
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);
|
|
596
604
|
continue;
|
|
597
605
|
}
|
|
598
|
-
sanitized[
|
|
606
|
+
sanitized[key2] = sanitizeContextValue(
|
|
599
607
|
value,
|
|
600
608
|
resolvedErrorReporting,
|
|
601
609
|
1,
|
|
602
610
|
seen,
|
|
603
611
|
identifiers,
|
|
604
|
-
|
|
612
|
+
key2
|
|
605
613
|
);
|
|
606
614
|
}
|
|
607
615
|
return {
|
|
@@ -785,7 +793,7 @@ function readQueue(storageKey, fallbackConfig) {
|
|
|
785
793
|
if (!Array.isArray(parsed)) {
|
|
786
794
|
return [];
|
|
787
795
|
}
|
|
788
|
-
return parsed.filter(isStoredRecordCandidate).map((
|
|
796
|
+
return parsed.filter(isStoredRecordCandidate).map((record2) => normalizeStoredRecord(record2, fallbackConfig));
|
|
789
797
|
} catch {
|
|
790
798
|
return [];
|
|
791
799
|
}
|
|
@@ -950,12 +958,12 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
950
958
|
return right.lastSeen - left.lastSeen;
|
|
951
959
|
});
|
|
952
960
|
};
|
|
953
|
-
const enqueueRecord = (
|
|
954
|
-
queue.push(
|
|
961
|
+
const enqueueRecord = (record2) => {
|
|
962
|
+
queue.push(record2);
|
|
955
963
|
trimQueue();
|
|
956
964
|
persistQueue();
|
|
957
|
-
if (
|
|
958
|
-
recordIssue(
|
|
965
|
+
if (record2.kind === "error" && record2.error) {
|
|
966
|
+
recordIssue(record2.error, record2.timestamp, true);
|
|
959
967
|
}
|
|
960
968
|
if (queue.length >= resolvedConfig.batchSize) {
|
|
961
969
|
void flush();
|
|
@@ -1072,9 +1080,9 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1072
1080
|
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
1073
1081
|
window.addEventListener("pagehide", handlePageHide);
|
|
1074
1082
|
}
|
|
1075
|
-
for (const
|
|
1076
|
-
if (
|
|
1077
|
-
recordIssue(
|
|
1083
|
+
for (const record2 of queue) {
|
|
1084
|
+
if (record2.kind === "error" && record2.error) {
|
|
1085
|
+
recordIssue(record2.error, record2.timestamp, false);
|
|
1078
1086
|
}
|
|
1079
1087
|
}
|
|
1080
1088
|
startFlushTimer();
|
|
@@ -1093,7 +1101,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1093
1101
|
const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
|
|
1094
1102
|
const kind = event.kind === "error" ? "error" : "interaction";
|
|
1095
1103
|
const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
|
|
1096
|
-
const
|
|
1104
|
+
const record2 = {
|
|
1097
1105
|
id: createId("event"),
|
|
1098
1106
|
component: event.component,
|
|
1099
1107
|
action: event.action,
|
|
@@ -1110,7 +1118,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1110
1118
|
context: createMergedContext(resolvedConfig, eventChannel, event.context),
|
|
1111
1119
|
error: normalizedError
|
|
1112
1120
|
};
|
|
1113
|
-
enqueueRecord(
|
|
1121
|
+
enqueueRecord(record2);
|
|
1114
1122
|
};
|
|
1115
1123
|
const reportError = (report) => {
|
|
1116
1124
|
if (isDestroyed || !resolvedConfig.enabled) {
|
|
@@ -1144,7 +1152,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1144
1152
|
if (normalizedError.tags && normalizedError.tags.length > 0) {
|
|
1145
1153
|
errorContext.errorTags = normalizedError.tags;
|
|
1146
1154
|
}
|
|
1147
|
-
const
|
|
1155
|
+
const record2 = {
|
|
1148
1156
|
id: createId("event"),
|
|
1149
1157
|
component: normalizedError.boundary,
|
|
1150
1158
|
action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
|
|
@@ -1158,7 +1166,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1158
1166
|
context: createMergedContext(resolvedConfig, eventChannel, errorContext),
|
|
1159
1167
|
error: normalizedError
|
|
1160
1168
|
};
|
|
1161
|
-
enqueueRecord(
|
|
1169
|
+
enqueueRecord(record2);
|
|
1162
1170
|
};
|
|
1163
1171
|
return {
|
|
1164
1172
|
get source() {
|
|
@@ -1426,13 +1434,13 @@ function isRecord(value) {
|
|
|
1426
1434
|
}
|
|
1427
1435
|
function getOwnStringKeys(value) {
|
|
1428
1436
|
const keys = Reflect.ownKeys(value);
|
|
1429
|
-
if (keys.some((
|
|
1437
|
+
if (keys.some((key2) => typeof key2 !== "string")) {
|
|
1430
1438
|
return null;
|
|
1431
1439
|
}
|
|
1432
1440
|
return keys;
|
|
1433
1441
|
}
|
|
1434
1442
|
function hasOnlyFields(keys, allowed) {
|
|
1435
|
-
return keys.every((
|
|
1443
|
+
return keys.every((key2) => allowed.has(key2));
|
|
1436
1444
|
}
|
|
1437
1445
|
function sensitivityWords(value) {
|
|
1438
1446
|
return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
|
|
@@ -1552,11 +1560,11 @@ function normalizeEventDefinition(candidate) {
|
|
|
1552
1560
|
if (targetKeys === null || targetKeys.length !== 2 || !hasOnlyFields(targetKeys, TARGET_FIELDS) || !isSemanticToken(target.type) || !isSemanticToken(target.id) || looksSensitive(target.type) || looksSensitive(target.id)) {
|
|
1553
1561
|
return invalidDefinition();
|
|
1554
1562
|
}
|
|
1555
|
-
const
|
|
1556
|
-
if (seenTargets.has(
|
|
1563
|
+
const key2 = `${target.type}\0${target.id}`;
|
|
1564
|
+
if (seenTargets.has(key2)) {
|
|
1557
1565
|
return invalidDefinition();
|
|
1558
1566
|
}
|
|
1559
|
-
seenTargets.add(
|
|
1567
|
+
seenTargets.add(key2);
|
|
1560
1568
|
targets.push(Object.freeze({ type: target.type, id: target.id }));
|
|
1561
1569
|
}
|
|
1562
1570
|
}
|
|
@@ -1738,12 +1746,12 @@ function createSecureRandomHex(byteLength2, randomBytes = webCryptoRandomBytes)
|
|
|
1738
1746
|
if (!Number.isSafeInteger(byteLength2) || byteLength2 <= 0 || byteLength2 > MAX_RANDOM_BYTE_LENGTH) {
|
|
1739
1747
|
throw new Error("Secure random byte length is invalid.");
|
|
1740
1748
|
}
|
|
1741
|
-
const
|
|
1742
|
-
if (!(
|
|
1749
|
+
const bytes2 = randomBytes(byteLength2);
|
|
1750
|
+
if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== byteLength2) {
|
|
1743
1751
|
throw new Error("Secure random source returned invalid bytes.");
|
|
1744
1752
|
}
|
|
1745
1753
|
let result = "";
|
|
1746
|
-
for (const byte of
|
|
1754
|
+
for (const byte of bytes2) {
|
|
1747
1755
|
result += byte.toString(16).padStart(2, "0");
|
|
1748
1756
|
}
|
|
1749
1757
|
return result;
|
|
@@ -1910,29 +1918,29 @@ var SemanticJourneyAggregateStore = class {
|
|
|
1910
1918
|
}
|
|
1911
1919
|
this.options = Object.freeze({ ...options });
|
|
1912
1920
|
}
|
|
1913
|
-
record(eventName, outcome,
|
|
1921
|
+
record(eventName, outcome, count2 = 1) {
|
|
1914
1922
|
if (!isSemanticToken(eventName) || getJourneyEventDefinition(this.options.catalogue, eventName) === void 0 || !OUTCOMES2.has(outcome)) {
|
|
1915
1923
|
invalidAggregate();
|
|
1916
1924
|
}
|
|
1917
|
-
normalizeLimit(
|
|
1918
|
-
const
|
|
1919
|
-
const existing = this.counters.get(
|
|
1920
|
-
this.counters.set(
|
|
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({
|
|
1921
1929
|
eventName,
|
|
1922
1930
|
outcome,
|
|
1923
|
-
count: addSafeCount(existing?.count ?? 0,
|
|
1931
|
+
count: addSafeCount(existing?.count ?? 0, count2)
|
|
1924
1932
|
}));
|
|
1925
1933
|
}
|
|
1926
|
-
recordDropped(
|
|
1934
|
+
recordDropped(count2 = 1) {
|
|
1927
1935
|
this.dropped = addSafeCount(
|
|
1928
1936
|
this.dropped,
|
|
1929
|
-
normalizeLimit(
|
|
1937
|
+
normalizeLimit(count2, 1, "dropped increment")
|
|
1930
1938
|
);
|
|
1931
1939
|
}
|
|
1932
|
-
recordCoalesced(
|
|
1940
|
+
recordCoalesced(count2 = 1) {
|
|
1933
1941
|
this.coalesced = addSafeCount(
|
|
1934
1942
|
this.coalesced,
|
|
1935
|
-
normalizeLimit(
|
|
1943
|
+
normalizeLimit(count2, 1, "coalesced increment")
|
|
1936
1944
|
);
|
|
1937
1945
|
}
|
|
1938
1946
|
snapshot() {
|
|
@@ -1988,16 +1996,16 @@ var SemanticJourneyAggregateStore = class {
|
|
|
1988
1996
|
}
|
|
1989
1997
|
acknowledge(batch) {
|
|
1990
1998
|
for (const acknowledged of batch.counters) {
|
|
1991
|
-
const
|
|
1992
|
-
const current = this.counters.get(
|
|
1999
|
+
const key2 = toCounterKey(acknowledged.eventName, acknowledged.outcome);
|
|
2000
|
+
const current = this.counters.get(key2);
|
|
1993
2001
|
if (!current) {
|
|
1994
2002
|
continue;
|
|
1995
2003
|
}
|
|
1996
2004
|
const remaining = current.count - acknowledged.count;
|
|
1997
2005
|
if (remaining > 0) {
|
|
1998
|
-
this.counters.set(
|
|
2006
|
+
this.counters.set(key2, Object.freeze({ ...current, count: remaining }));
|
|
1999
2007
|
} else {
|
|
2000
|
-
this.counters.delete(
|
|
2008
|
+
this.counters.delete(key2);
|
|
2001
2009
|
}
|
|
2002
2010
|
}
|
|
2003
2011
|
this.dropped = Math.max(0, this.dropped - batch.dropped);
|
|
@@ -2016,6 +2024,395 @@ var SemanticJourneyAggregateStore = class {
|
|
|
2016
2024
|
}
|
|
2017
2025
|
};
|
|
2018
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
|
+
|
|
2019
2416
|
// src/journey/metrics.ts
|
|
2020
2417
|
var durationBuckets = [
|
|
2021
2418
|
[100, "lt100ms"],
|
|
@@ -2083,7 +2480,7 @@ function projectUsefulMetric(input) {
|
|
|
2083
2480
|
const prototype = Object.getPrototypeOf(input);
|
|
2084
2481
|
if (prototype !== Object.prototype && prototype !== null) return null;
|
|
2085
2482
|
const keys = Reflect.ownKeys(input);
|
|
2086
|
-
if (keys.length < 1 || keys.length > 2 || keys.some((
|
|
2483
|
+
if (keys.length < 1 || keys.length > 2 || keys.some((key2) => key2 !== "metric" && key2 !== "value")) return null;
|
|
2087
2484
|
const descriptors = Object.getOwnPropertyDescriptors(input);
|
|
2088
2485
|
const metric = descriptors.metric;
|
|
2089
2486
|
if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
|
|
@@ -2503,20 +2900,20 @@ function readDataRecord(value, allowedFields, requiredFields = /* @__PURE__ */ n
|
|
|
2503
2900
|
return invalidRuntimeEvidence();
|
|
2504
2901
|
}
|
|
2505
2902
|
const keys = Reflect.ownKeys(value);
|
|
2506
|
-
if (keys.length > maximumFields || keys.some((
|
|
2903
|
+
if (keys.length > maximumFields || keys.some((key2) => typeof key2 !== "string")) {
|
|
2507
2904
|
return invalidRuntimeEvidence();
|
|
2508
2905
|
}
|
|
2509
2906
|
const stringKeys = keys;
|
|
2510
|
-
if (allowedFields && stringKeys.some((
|
|
2907
|
+
if (allowedFields && stringKeys.some((key2) => !allowedFields.has(key2)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
|
|
2511
2908
|
return invalidRuntimeEvidence();
|
|
2512
2909
|
}
|
|
2513
2910
|
const result = /* @__PURE__ */ Object.create(null);
|
|
2514
|
-
for (const
|
|
2515
|
-
const descriptor = Object.getOwnPropertyDescriptor(value,
|
|
2911
|
+
for (const key2 of stringKeys) {
|
|
2912
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key2);
|
|
2516
2913
|
if (descriptor === void 0 || !("value" in descriptor)) {
|
|
2517
2914
|
return invalidRuntimeEvidence();
|
|
2518
2915
|
}
|
|
2519
|
-
result[
|
|
2916
|
+
result[key2] = descriptor.value;
|
|
2520
2917
|
}
|
|
2521
2918
|
return result;
|
|
2522
2919
|
}
|
|
@@ -2574,28 +2971,28 @@ function readOptionalIdentifier(value, validator) {
|
|
|
2574
2971
|
return validator(value) ? value : invalidRuntimeEvidence();
|
|
2575
2972
|
}
|
|
2576
2973
|
function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
2577
|
-
const
|
|
2974
|
+
const record2 = readDataRecord(
|
|
2578
2975
|
candidate,
|
|
2579
2976
|
EVENT_FIELDS,
|
|
2580
2977
|
EVENT_REQUIRED_FIELDS,
|
|
2581
2978
|
EVENT_FIELDS.size
|
|
2582
2979
|
);
|
|
2583
|
-
if (
|
|
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)) {
|
|
2584
2981
|
return invalidRuntimeEvidence();
|
|
2585
2982
|
}
|
|
2586
|
-
const parentSpanId = readOptionalIdentifier(
|
|
2983
|
+
const parentSpanId = readOptionalIdentifier(record2.parentSpanId, isSpanId);
|
|
2587
2984
|
const causedByEventId = readOptionalIdentifier(
|
|
2588
|
-
|
|
2985
|
+
record2.causedByEventId,
|
|
2589
2986
|
isEventId
|
|
2590
2987
|
);
|
|
2591
2988
|
const attributes = readDataRecord(
|
|
2592
|
-
|
|
2989
|
+
record2.attributes,
|
|
2593
2990
|
void 0,
|
|
2594
2991
|
/* @__PURE__ */ new Set(),
|
|
2595
2992
|
MAX_EVENT_ATTRIBUTES2
|
|
2596
2993
|
);
|
|
2597
2994
|
const privacy = readDataRecord(
|
|
2598
|
-
|
|
2995
|
+
record2.privacy,
|
|
2599
2996
|
PRIVACY_FIELDS,
|
|
2600
2997
|
PRIVACY_FIELDS,
|
|
2601
2998
|
PRIVACY_FIELDS.size
|
|
@@ -2604,9 +3001,9 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
|
2604
3001
|
return invalidRuntimeEvidence();
|
|
2605
3002
|
}
|
|
2606
3003
|
let target;
|
|
2607
|
-
if (
|
|
3004
|
+
if (record2.target !== void 0) {
|
|
2608
3005
|
const targetRecord = readDataRecord(
|
|
2609
|
-
|
|
3006
|
+
record2.target,
|
|
2610
3007
|
TARGET_FIELDS2,
|
|
2611
3008
|
TARGET_FIELDS2,
|
|
2612
3009
|
TARGET_FIELDS2.size
|
|
@@ -2617,29 +3014,29 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
|
2617
3014
|
target = { type: targetRecord.type, id: targetRecord.id };
|
|
2618
3015
|
}
|
|
2619
3016
|
const input = {
|
|
2620
|
-
name:
|
|
2621
|
-
category:
|
|
2622
|
-
phase:
|
|
2623
|
-
outcome:
|
|
2624
|
-
...
|
|
3017
|
+
name: record2.name,
|
|
3018
|
+
category: record2.category,
|
|
3019
|
+
phase: record2.phase,
|
|
3020
|
+
outcome: record2.outcome,
|
|
3021
|
+
...record2.modality === void 0 ? {} : { modality: record2.modality },
|
|
2625
3022
|
...target === void 0 ? {} : { target },
|
|
2626
3023
|
attributes
|
|
2627
3024
|
};
|
|
2628
3025
|
const validated = validateSemanticJourneyEventInput(catalogue, input);
|
|
2629
3026
|
return Object.freeze({
|
|
2630
3027
|
schemaVersion: "2.0",
|
|
2631
|
-
eventId:
|
|
2632
|
-
journeyId:
|
|
2633
|
-
traceId:
|
|
2634
|
-
spanId:
|
|
3028
|
+
eventId: record2.eventId,
|
|
3029
|
+
journeyId: record2.journeyId,
|
|
3030
|
+
traceId: record2.traceId,
|
|
3031
|
+
spanId: record2.spanId,
|
|
2635
3032
|
...parentSpanId === void 0 ? {} : { parentSpanId },
|
|
2636
3033
|
...causedByEventId === void 0 ? {} : { causedByEventId },
|
|
2637
|
-
producerId:
|
|
2638
|
-
producerSequence:
|
|
2639
|
-
occurredAtEpochMs:
|
|
2640
|
-
source:
|
|
2641
|
-
channel:
|
|
2642
|
-
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,
|
|
2643
3040
|
name: validated.name,
|
|
2644
3041
|
category: validated.category,
|
|
2645
3042
|
phase: validated.phase,
|
|
@@ -2658,7 +3055,7 @@ function attributesEqual(left, right) {
|
|
|
2658
3055
|
const leftKeys = Object.keys(left).sort(compareTokens);
|
|
2659
3056
|
const rightKeys = Object.keys(right).sort(compareTokens);
|
|
2660
3057
|
return leftKeys.length === rightKeys.length && leftKeys.every(
|
|
2661
|
-
(
|
|
3058
|
+
(key2, index) => key2 === rightKeys[index] && Object.is(left[key2], right[key2])
|
|
2662
3059
|
);
|
|
2663
3060
|
}
|
|
2664
3061
|
function eventsEqual(left, right) {
|
|
@@ -2972,7 +3369,7 @@ function condensedCausalOrder(components) {
|
|
|
2972
3369
|
}
|
|
2973
3370
|
ready.sort(compareComponents);
|
|
2974
3371
|
}
|
|
2975
|
-
if (ordered.length !== components.reduce((
|
|
3372
|
+
if (ordered.length !== components.reduce((count2, item) => count2 + item.nodes.length, 0)) {
|
|
2976
3373
|
return invalidRuntimeEvidence();
|
|
2977
3374
|
}
|
|
2978
3375
|
return ordered;
|
|
@@ -3304,6 +3701,7 @@ function resolveConfig2(config) {
|
|
|
3304
3701
|
if (!config.catalogue.sources.includes(config.source)) {
|
|
3305
3702
|
return invalidConfig();
|
|
3306
3703
|
}
|
|
3704
|
+
if (config.aggregatePolicy !== void 0 && (!isSemanticJourneyAggregatePolicy(config.aggregatePolicy) || JSON.stringify(config.aggregatePolicy.catalogue) !== JSON.stringify(config.catalogue))) return invalidConfig();
|
|
3307
3705
|
if (config.aggregateEndpoint !== void 0 && !isAllowedEndpoint(config.aggregateEndpoint, config.aggregateBaseUrl)) {
|
|
3308
3706
|
return invalidConfig();
|
|
3309
3707
|
}
|
|
@@ -3322,6 +3720,7 @@ function resolveConfig2(config) {
|
|
|
3322
3720
|
);
|
|
3323
3721
|
return {
|
|
3324
3722
|
catalogue: config.catalogue,
|
|
3723
|
+
...config.aggregatePolicy ? { aggregatePolicy: config.aggregatePolicy } : {},
|
|
3325
3724
|
source: config.source,
|
|
3326
3725
|
channel: resolveChannel2(config.channel, runtime),
|
|
3327
3726
|
runtime,
|
|
@@ -3352,7 +3751,7 @@ function resolveConfig2(config) {
|
|
|
3352
3751
|
),
|
|
3353
3752
|
maxBatchesPerFlush: resolveInteger(
|
|
3354
3753
|
config.maxBatchesPerFlush,
|
|
3355
|
-
DEFAULT_MAX_BATCHES_PER_FLUSH,
|
|
3754
|
+
config.aggregatePolicy ? 2 : DEFAULT_MAX_BATCHES_PER_FLUSH,
|
|
3356
3755
|
1,
|
|
3357
3756
|
MAX_BATCHES_PER_FLUSH
|
|
3358
3757
|
),
|
|
@@ -3430,11 +3829,11 @@ function jitteredDelay(attempt, config) {
|
|
|
3430
3829
|
config.retryMaxDelayMs,
|
|
3431
3830
|
config.retryBaseDelayMs * 2 ** attempt
|
|
3432
3831
|
);
|
|
3433
|
-
const
|
|
3434
|
-
if (!(
|
|
3832
|
+
const bytes2 = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
|
|
3833
|
+
if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== 2) {
|
|
3435
3834
|
throw new Error("Semantic journey retry random source is invalid.");
|
|
3436
3835
|
}
|
|
3437
|
-
const sample = (
|
|
3836
|
+
const sample = (bytes2[0] ?? 0) << 8 | (bytes2[1] ?? 0);
|
|
3438
3837
|
const factor = 0.5 + sample / 65535;
|
|
3439
3838
|
return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
|
|
3440
3839
|
}
|
|
@@ -3445,12 +3844,16 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3445
3844
|
} catch {
|
|
3446
3845
|
return invalidConfig();
|
|
3447
3846
|
}
|
|
3448
|
-
const
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
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 });
|
|
3454
3857
|
const queue = [];
|
|
3455
3858
|
const contextByEventId = /* @__PURE__ */ new Map();
|
|
3456
3859
|
let episode;
|
|
@@ -3547,7 +3950,15 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3547
3950
|
droppedAttributeCount: validated.droppedAttributeCount
|
|
3548
3951
|
})
|
|
3549
3952
|
});
|
|
3550
|
-
aggregateStore
|
|
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);
|
|
3551
3962
|
if (shouldCoalesce(
|
|
3552
3963
|
queue[queue.length - 1]?.event,
|
|
3553
3964
|
event,
|
|
@@ -3556,17 +3967,17 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3556
3967
|
aggregateStore.recordCoalesced();
|
|
3557
3968
|
return void 0;
|
|
3558
3969
|
}
|
|
3559
|
-
const
|
|
3560
|
-
if (
|
|
3970
|
+
const bytes2 = eventBytes(event);
|
|
3971
|
+
if (bytes2 > config.maxQueueBytes) {
|
|
3561
3972
|
aggregateStore.recordDropped();
|
|
3562
3973
|
notifyDrop("queue-limit");
|
|
3563
3974
|
return void 0;
|
|
3564
3975
|
}
|
|
3565
|
-
while (queue.length >= config.maxQueueEvents || queueBytes +
|
|
3976
|
+
while (queue.length >= config.maxQueueEvents || queueBytes + bytes2 > config.maxQueueBytes) {
|
|
3566
3977
|
removeFirstQueued("queue-limit");
|
|
3567
3978
|
}
|
|
3568
|
-
queue.push({ event, context: options.context, bytes });
|
|
3569
|
-
queueBytes +=
|
|
3979
|
+
queue.push({ event, context: options.context, bytes: bytes2 });
|
|
3980
|
+
queueBytes += bytes2;
|
|
3570
3981
|
contextByEventId.set(event.eventId, options.context);
|
|
3571
3982
|
if (usesLocalProducer) {
|
|
3572
3983
|
currentEpisode.producerSequence = producerSequence;
|
|
@@ -3808,6 +4219,10 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3808
4219
|
if (destroyed || signal.aborted) {
|
|
3809
4220
|
return "retained";
|
|
3810
4221
|
}
|
|
4222
|
+
if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && batch.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(batch, config.now())) {
|
|
4223
|
+
notifyDrop("expired");
|
|
4224
|
+
return "discarded";
|
|
4225
|
+
}
|
|
3811
4226
|
try {
|
|
3812
4227
|
await sendWithTimeout(batch, keepalive);
|
|
3813
4228
|
return "sent";
|
|
@@ -3838,6 +4253,7 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3838
4253
|
const generation = aggregateGeneration;
|
|
3839
4254
|
const signal = aggregateController.signal;
|
|
3840
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;
|
|
3841
4257
|
const batch = pendingBatch ?? aggregateStore.createBatch({
|
|
3842
4258
|
batchId: createEventId(config.randomBytes),
|
|
3843
4259
|
nowEpochMs: config.now(),
|
|
@@ -3855,7 +4271,9 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3855
4271
|
if (result === "retained") {
|
|
3856
4272
|
return;
|
|
3857
4273
|
}
|
|
3858
|
-
aggregateStore
|
|
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);
|
|
3859
4277
|
pendingBatch = void 0;
|
|
3860
4278
|
}
|
|
3861
4279
|
};
|
|
@@ -4080,7 +4498,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
|
|
|
4080
4498
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4081
4499
|
0 && (module.exports = {
|
|
4082
4500
|
AnalyticsProvider,
|
|
4501
|
+
ProjectedSemanticJourneyAggregateStore,
|
|
4502
|
+
SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES,
|
|
4083
4503
|
SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
|
|
4504
|
+
SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION,
|
|
4084
4505
|
SEMANTIC_JOURNEY_RECEIPT_HEADER,
|
|
4085
4506
|
SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
|
|
4086
4507
|
SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
|
|
@@ -4104,10 +4525,12 @@ function useComponentInteractionTracker(component, baseContext = {}) {
|
|
|
4104
4525
|
createProducerId,
|
|
4105
4526
|
createRequestJourneyContext,
|
|
4106
4527
|
createSecureRandomHex,
|
|
4528
|
+
createSemanticJourneyAggregateValidator,
|
|
4107
4529
|
createSemanticJourneyClient,
|
|
4108
4530
|
createSpanId,
|
|
4109
4531
|
createTraceId,
|
|
4110
4532
|
defineJourneyEvent,
|
|
4533
|
+
defineSemanticJourneyAggregatePolicy,
|
|
4111
4534
|
defineSemanticJourneyCatalog,
|
|
4112
4535
|
formatTraceparent,
|
|
4113
4536
|
getJourneyEventDefinition,
|
|
@@ -4116,6 +4539,7 @@ function useComponentInteractionTracker(component, baseContext = {}) {
|
|
|
4116
4539
|
isJourneyToken,
|
|
4117
4540
|
isProducerId,
|
|
4118
4541
|
isSecureSemanticJourneyEndpoint,
|
|
4542
|
+
isSemanticJourneyAggregatePolicy,
|
|
4119
4543
|
isSemanticSource,
|
|
4120
4544
|
isSemanticToken,
|
|
4121
4545
|
isSpanId,
|
|
@@ -4123,8 +4547,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
|
|
|
4123
4547
|
observeSemanticJourneyInteractions,
|
|
4124
4548
|
parseSemanticJourneyReceipts,
|
|
4125
4549
|
parseTraceparent,
|
|
4550
|
+
projectSemanticJourneyAggregateCounters,
|
|
4126
4551
|
projectUsefulMetric,
|
|
4127
4552
|
reconstructSemanticJourney,
|
|
4553
|
+
semanticJourneyAggregateCounterKey,
|
|
4128
4554
|
serializeSemanticJourneyReceipts,
|
|
4129
4555
|
useAnalytics,
|
|
4130
4556
|
useComponentInteractionTracker,
|