@configdirector/nuxt-sdk 1.13.2 → 1.14.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.
Files changed (27) hide show
  1. package/dist/module.d.mts +43 -4
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/app/composables/useConfigDirectorClient.d.mts +1 -1
  4. package/dist/runtime/app/composables/useConfigDirectorClient.d.ts +1 -1
  5. package/dist/runtime/app/composables/useConfigDirectorClientHooks.d.mts +1 -1
  6. package/dist/runtime/app/composables/useConfigDirectorClientHooks.d.ts +1 -1
  7. package/dist/runtime/app/composables/useConfigDirectorContext.d.mts +1 -1
  8. package/dist/runtime/app/composables/useConfigDirectorContext.d.ts +1 -1
  9. package/dist/runtime/app/composables/useConfigDirectorValue.d.mts +1 -1
  10. package/dist/runtime/app/composables/useConfigDirectorValue.d.ts +1 -1
  11. package/dist/runtime/{native-values-CfhP0yLS.d.mts → native-values-Cq3SCmEH.d.mts} +49 -4
  12. package/dist/runtime/nitro/offline-values.d.mts +1 -1
  13. package/dist/runtime/nitro/offline-values.d.ts +1 -1
  14. package/dist/runtime/nitro/plugin.d.mts +9 -2
  15. package/dist/runtime/nitro/plugin.d.ts +9 -2
  16. package/dist/runtime/nitro/plugin.mjs +319 -82
  17. package/dist/runtime/plugin.client.mjs +191 -3
  18. package/dist/runtime/plugin.server.mjs +3 -0
  19. package/dist/runtime/server/composables/useConfigDirectorServerClient.d.mts +1 -1
  20. package/dist/runtime/server/composables/useConfigDirectorServerClient.d.ts +1 -1
  21. package/dist/runtime/server/composables/useConfigDirectorServerHooks.d.mts +1 -1
  22. package/dist/runtime/server/composables/useConfigDirectorServerHooks.d.ts +1 -1
  23. package/dist/runtime/{types-BvqduMQP.d.mts → types-BNw2c3C0.d.mts} +17 -3
  24. package/dist/runtime/{types-qDEc6g8R.d.mts → types-CYquNKWW.d.mts} +18 -3
  25. package/dist/testing.d.mts +78 -7
  26. package/dist/testing.mjs +158 -5
  27. package/package.json +2 -2
@@ -669,6 +669,24 @@ const offlineSourceOf = (connection) => {
669
669
  };
670
670
  //#endregion
671
671
  //#region ../shared/src/value-parser.ts
672
+ const NO_VARIATION_OR_ROLLOUT_SHARE = {
673
+ variation: void 0,
674
+ ruleId: void 0,
675
+ shareId: void 0
676
+ };
677
+ const variationOf = (configState) => {
678
+ const variation = configState.variation;
679
+ if (variation == null) return;
680
+ return variation.name ? {
681
+ id: variation.id,
682
+ name: variation.name
683
+ } : { id: variation.id };
684
+ };
685
+ const variationAndRolloutShareOf = (configState) => ({
686
+ variation: variationOf(configState),
687
+ ruleId: configState.ruleId ?? void 0,
688
+ shareId: configState.shareId ?? void 0
689
+ });
672
690
  const getRequestedType = (defaultValue) => {
673
691
  const baseType = typeof defaultValue;
674
692
  if (baseType === "object") try {
@@ -693,6 +711,13 @@ const configTypesNotReadableAsString = new Set([
693
711
  "float"
694
712
  ]);
695
713
  const parseConfigValue = (configState, defaultValue) => {
714
+ const valueAndReason = parseValueAndReason(configState, defaultValue);
715
+ return {
716
+ ...valueAndReason,
717
+ ...valueAndReason.usedDefault ? NO_VARIATION_OR_ROLLOUT_SHARE : variationAndRolloutShareOf(configState)
718
+ };
719
+ };
720
+ const parseValueAndReason = (configState, defaultValue) => {
696
721
  const value = configState.value;
697
722
  const requestedType = getRequestedType(defaultValue);
698
723
  if (value == null || value === "") return {
@@ -895,6 +920,7 @@ const discardingTelemetryClient = {
895
920
  updateContext: async () => {},
896
921
  evaluatedConfig: () => {},
897
922
  recordInvalidContext: () => {},
923
+ trackedEvent: () => {},
898
924
  close: async () => {}
899
925
  };
900
926
  //#endregion
@@ -1272,6 +1298,91 @@ const utf8ByteLength = (text) => {
1272
1298
  return bytes;
1273
1299
  };
1274
1300
  //#endregion
1301
+ //#region ../shared/src/telemetry/reported-context.ts
1302
+ const USER_CONTEXT_KIND = "user";
1303
+ const reportedContextOf = (context) => {
1304
+ const contextIdentifier = context?.anonymous ? void 0 : context?.id;
1305
+ if (contextIdentifier === void 0) return {};
1306
+ return {
1307
+ contextKind: context?.kind ?? USER_CONTEXT_KIND,
1308
+ contextIdentifier
1309
+ };
1310
+ };
1311
+ //#endregion
1312
+ //#region ../shared/src/telemetry/tracked-events.ts
1313
+ const TRACKED_EVENTS_PER_BATCH = 1e3;
1314
+ const NAME_MAXIMUM_CHARACTERS = 150;
1315
+ const NAME_MAXIMUM_UTF16_UNITS = NAME_MAXIMUM_CHARACTERS * 2;
1316
+ const DETAILS_MAXIMUM_TOP_LEVEL_KEYS = 20;
1317
+ const DETAILS_MAXIMUM_JSON_BYTES = 1024;
1318
+ const trackedEventWarningMessages = {
1319
+ "name-outside-the-character-limit": `[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to ${NAME_MAXIMUM_CHARACTERS} characters.`,
1320
+ "value-not-a-finite-number": "[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.",
1321
+ "details-not-reportable": `[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than ${DETAILS_MAXIMUM_TOP_LEVEL_KEYS} top-level keys, are larger than ${DETAILS_MAXIMUM_JSON_BYTES} bytes as JSON, or cannot be written as JSON.`,
1322
+ "batch-already-full": `[ConfigDirectorClient] A tracked event was not reported because ${TRACKED_EVENTS_PER_BATCH} tracked events are already waiting for the next telemetry batch.`
1323
+ };
1324
+ const logBatchWarnings = (logger, warnings) => {
1325
+ for (const warning of warnings) logger.warn(`${trackedEventWarningMessages[warning]} Further tracked events like it are not logged until the next telemetry batch is sent.`);
1326
+ };
1327
+ const isGiven = (option) => option !== void 0 && option !== null;
1328
+ const isNonArrayObject = (candidate) => typeof candidate === "object" && candidate !== null && !Array.isArray(candidate);
1329
+ const isWithinTheCharacterLimit = (name) => typeof name === "string" && name.length >= 1 && name.length <= NAME_MAXIMUM_UTF16_UNITS && Array.from(name).length <= NAME_MAXIMUM_CHARACTERS;
1330
+ const reportableValueOf = (value) => {
1331
+ if (!isGiven(value)) return { status: "not-given" };
1332
+ if (typeof value === "number" && Number.isFinite(value)) return {
1333
+ status: "reportable",
1334
+ fields: { value }
1335
+ };
1336
+ return {
1337
+ status: "left-out",
1338
+ warning: "value-not-a-finite-number"
1339
+ };
1340
+ };
1341
+ const jsonCopyWithinTheLimits = (details) => {
1342
+ if (!isNonArrayObject(details)) return;
1343
+ try {
1344
+ const json = JSON.stringify(details);
1345
+ if (typeof json !== "string" || utf8ByteLength(json) > DETAILS_MAXIMUM_JSON_BYTES) return;
1346
+ const copy = JSON.parse(json);
1347
+ return isNonArrayObject(copy) && Object.keys(copy).length <= DETAILS_MAXIMUM_TOP_LEVEL_KEYS ? copy : void 0;
1348
+ } catch {
1349
+ return;
1350
+ }
1351
+ };
1352
+ const reportableDetailsOf = (details) => {
1353
+ if (!isGiven(details)) return { status: "not-given" };
1354
+ const jsonCopy = jsonCopyWithinTheLimits(details);
1355
+ if (jsonCopy === void 0) return {
1356
+ status: "left-out",
1357
+ warning: "details-not-reportable"
1358
+ };
1359
+ return {
1360
+ status: "reportable",
1361
+ fields: { details: jsonCopy }
1362
+ };
1363
+ };
1364
+ const fieldsOf = (option) => option.status === "reportable" ? option.fields : void 0;
1365
+ const warningsOf = (...options) => options.flatMap((option) => option.status === "left-out" ? [option.warning] : []);
1366
+ const admitTrackedEvent = (call) => {
1367
+ if (!isWithinTheCharacterLimit(call.name)) return {
1368
+ outcome: "dropped",
1369
+ warnings: ["name-outside-the-character-limit"]
1370
+ };
1371
+ const value = reportableValueOf(call.options?.value);
1372
+ const details = reportableDetailsOf(call.options?.details);
1373
+ return {
1374
+ outcome: "admitted",
1375
+ entry: {
1376
+ name: call.name,
1377
+ ...reportedContextOf(call.context),
1378
+ ...fieldsOf(value),
1379
+ ...fieldsOf(details),
1380
+ happenedAt: call.happenedAt.toISOString()
1381
+ },
1382
+ warnings: warningsOf(value, details)
1383
+ };
1384
+ };
1385
+ //#endregion
1275
1386
  //#region ../js-client-core/src/cached-values.ts
1276
1387
  const ENTRY_FORMAT_VERSION = 2;
1277
1388
  const FIRST_ENTRY_FORMAT_VERSION = 1;
@@ -1794,12 +1905,16 @@ var DefaultConfigDirectorClient = class DefaultConfigDirectorClient {
1794
1905
  evaluatedValue: parseResult.parsedValue,
1795
1906
  evaluatedValueId: parseResult.parsedValueId,
1796
1907
  usedDefault: parseResult.usedDefault,
1797
- evaluationReason: reason
1908
+ evaluationReason: reason,
1909
+ ruleId: parseResult.ruleId,
1910
+ shareId: parseResult.shareId,
1911
+ variationId: parseResult.variation?.id
1798
1912
  });
1799
1913
  const evaluation = {
1800
1914
  key: configKey,
1801
1915
  value: parseResult.parsedValue,
1802
1916
  valueId: parseResult.parsedValueId ?? void 0,
1917
+ variation: parseResult.variation,
1803
1918
  isDefaultValue: parseResult.usedDefault,
1804
1919
  reason,
1805
1920
  context: this.context
@@ -1842,6 +1957,19 @@ var DefaultConfigDirectorClient = class DefaultConfigDirectorClient {
1842
1957
  unwatchAll() {
1843
1958
  this.handlersMap.clear();
1844
1959
  }
1960
+ track(eventName, options) {
1961
+ try {
1962
+ const context = this.currentContext;
1963
+ this.telemetryClient.trackedEvent(admitTrackedEvent({
1964
+ name: eventName,
1965
+ context,
1966
+ options,
1967
+ happenedAt: /* @__PURE__ */ new Date()
1968
+ }), context);
1969
+ } catch (error) {
1970
+ this.logger.warn("[ConfigDirectorClient] A tracked event was not reported because it could not be read: ", error);
1971
+ }
1972
+ }
1845
1973
  pauseNetwork() {
1846
1974
  switch (this.connectionPlan.kind) {
1847
1975
  case "stay-offline": return;
@@ -1901,6 +2029,41 @@ const mapToTelemetryValue = (ev) => {
1901
2029
  if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) return { value: stringValue };
1902
2030
  return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };
1903
2031
  };
2032
+ //#endregion
2033
+ //#region ../shared/src/telemetry/TrackedEventQueue.ts
2034
+ var TrackedEventQueue = class {
2035
+ entries = [];
2036
+ warningsRaisedThisBatch = /* @__PURE__ */ new Set();
2037
+ add(admission) {
2038
+ return this.warningsOfKeeping(admission).filter((warning) => this.isFirstThisBatch(warning));
2039
+ }
2040
+ absorb(entries) {
2041
+ this.entries.push(...entries);
2042
+ }
2043
+ takeBatch() {
2044
+ const batch = this.entries;
2045
+ this.clear();
2046
+ return batch;
2047
+ }
2048
+ clear() {
2049
+ this.entries = [];
2050
+ this.warningsRaisedThisBatch.clear();
2051
+ }
2052
+ warningsOfKeeping(admission) {
2053
+ switch (admission.outcome) {
2054
+ case "dropped": return admission.warnings;
2055
+ case "admitted":
2056
+ if (this.entries.length >= 1e3) return ["batch-already-full"];
2057
+ this.entries.push(admission.entry);
2058
+ return admission.warnings;
2059
+ }
2060
+ }
2061
+ isFirstThisBatch(warning) {
2062
+ if (this.warningsRaisedThisBatch.has(warning)) return false;
2063
+ this.warningsRaisedThisBatch.add(warning);
2064
+ return true;
2065
+ }
2066
+ };
1904
2067
  var InvalidContextSubmissions = class {
1905
2068
  countsByKindSample = /* @__PURE__ */ new Map();
1906
2069
  countBeyondSampleLimit = 0;
@@ -1966,6 +2129,7 @@ var WebWorkerTelemetryClient = class {
1966
2129
  pendingEvaluations = [];
1967
2130
  pendingEvaluationLimit;
1968
2131
  pendingInvalidContextSubmissions = new InvalidContextSubmissions();
2132
+ pendingTrackedEvents = new TrackedEventQueue();
1969
2133
  closePromise;
1970
2134
  closeResolve;
1971
2135
  closeTimer;
@@ -1998,7 +2162,7 @@ var WebWorkerTelemetryClient = class {
1998
2162
  return;
1999
2163
  }
2000
2164
  try {
2001
- return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v,y=new Promise(e=>{v=e}),b=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),x=e=>{try{self.postMessage(e)}catch{self.postMessage(b(e.payload.level,e.payload.message))}},S={debug:function(e,...t){x(b(`debug`,e,t))},info:function(e,...t){x(b(`info`,e,t))},warn:function(e,...t){x(b(`warn`,e,t))},error:function(e,...t){x(b(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){S.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(S.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){S.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:S,clientSession:y}),_.start();break;case`ClientSession`:v(t.payload);break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"], { type: "application/javascript" })));
2165
+ return new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError,a=e=>e>=55296&&e<=56319,o=e=>e>=56320&&e<=57343,s=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<=127?t+=1:r<=2047?t+=2:a(r)&&n+1<e.length&&o(e.charCodeAt(n+1))?(t+=4,n++):t+=3}return t};var c=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=JSON.stringify(e),n=await r(5e3,this.url,{method:`POST`,body:t,keepalive:s(t)<=32768},this.logger),i=this.isStatusFatal(n.status);return i?this.logger.warn(`[EventReporter] Received a fatal status response (${n.status}) from the telemetry endpoint. No more telemetry data will be sent.`):n.status===413&&this.logger.warn(`[EventReporter] The telemetry endpoint responded with status ${n.status}. The events in this report were discarded.`),{success:n.ok,fatalError:i}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429&&e!=413}},l=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},u=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}};let d={\"name-outside-the-character-limit\":`[ConfigDirectorClient] A tracked event was not reported because its name does not have 1 to 150 characters.`,\"value-not-a-finite-number\":`[ConfigDirectorClient] A tracked event was reported without its value because the value is not a finite number.`,\"details-not-reportable\":`[ConfigDirectorClient] A tracked event was reported without its details because they are not an object, have more than 20 top-level keys, are larger than 1024 bytes as JSON, or cannot be written as JSON.`,\"batch-already-full\":`[ConfigDirectorClient] A tracked event was not reported because 1000 tracked events are already waiting for the next telemetry batch.`},f=(e,t)=>{for(let n of t)e.warn(`${d[n]} Further tracked events like it are not logged until the next telemetry batch is sent.`)};var p=class{constructor(){this.entries=[],this.warningsRaisedThisBatch=new Set}add(e){return this.warningsOfKeeping(e).filter(e=>this.isFirstThisBatch(e))}absorb(e){this.entries.push(...e)}takeBatch(){let e=this.entries;return this.clear(),e}clear(){this.entries=[],this.warningsRaisedThisBatch.clear()}warningsOfKeeping(e){switch(e.outcome){case`dropped`:return e.warnings;case`admitted`:return this.entries.length>=1e3?[`batch-already-full`]:(this.entries.push(e.entry),e.warnings)}}isFirstThisBatch(e){return this.warningsRaisedThisBatch.has(e)?!1:(this.warningsRaisedThisBatch.add(e),!0)}},m=class{constructor(e){this.aggregator=new l,this.trackedEventQueue=new p,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new u(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}trackedEvent(e){this.collectEvents&&f(this.logger,this.trackedEventQueue.add(e))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear(),this.trackedEventQueue.clear()}dispose(){this.close()}},h=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},g=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},_=class extends m{constructor(e){super(e),this.invalidContextSubmissions=new g,this.reporter=new c(e),this.evaluationEventSnapshotPreprocessor=new h(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}absorbTrackedEventEntries(e){this.trackedEventQueue.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{trackedEvents:this.trackedEventQueue.takeBatch()},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let v=(e,t)=>new URL(e,t?.toString()),y=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},b=Math.ceil(128/Math.log2(62)),x=new TextEncoder,S=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,x.encode(e?.toString()??``));return y(new Uint8Array(t,0,16),b)},C,w,T=new Promise(e=>{w=e}),E=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),D=e=>{try{self.postMessage(e)}catch{self.postMessage(E(e.payload.level,e.payload.message))}},O={debug:function(e,...t){D(E(`debug`,e,t))},info:function(e,...t){D(E(`info`,e,t))},warn:function(e,...t){D(E(`warn`,e,t))},error:function(e,...t){D(E(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!C){O.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(O.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(C){O.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}C=new _({...t.payload,baseUrl:v(t.payload.baseUrl),urlFactory:v,valueIdGenerator:S,logger:O,clientSession:T}),C.start();break;case`ClientSession`:w(t.payload);break;case`EvaluatedConfigEvent`:C?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:C?.absorbInvalidContextSubmissions(t.payload.entries);break;case`TrackedEvent`:C?.trackedEvent(t.payload);break;case`TrackedEventEntries`:C?.absorbTrackedEventEntries(t.payload.entries);break;case`UpdateContext`:C?.updateContext(t.payload.context);break;case`Flush`:C?.forceFlush();break;case`Close`:(C?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"], { type: "application/javascript" })));
2002
2166
  } catch (error) {
2003
2167
  this.turnOff("[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: ", error);
2004
2168
  return;
@@ -2007,6 +2171,7 @@ var WebWorkerTelemetryClient = class {
2007
2171
  turnOff(warning, ...details) {
2008
2172
  this.turnedOff = true;
2009
2173
  this.pendingEvaluations.length = 0;
2174
+ this.pendingTrackedEvents.clear();
2010
2175
  this.logger.warn(warning, ...details);
2011
2176
  }
2012
2177
  startWorker() {
@@ -2027,8 +2192,18 @@ var WebWorkerTelemetryClient = class {
2027
2192
  for (const evaluation of this.pendingEvaluations) worker.postMessage(evaluation);
2028
2193
  this.pendingEvaluations.length = 0;
2029
2194
  this.forwardInvalidContextSubmissions(worker);
2195
+ this.forwardPendingTrackedEvents(worker);
2030
2196
  return worker;
2031
2197
  }
2198
+ forwardPendingTrackedEvents(worker) {
2199
+ const entries = this.pendingTrackedEvents.takeBatch();
2200
+ if (entries.length === 0) return;
2201
+ const entriesMessage = {
2202
+ type: "TrackedEventEntries",
2203
+ payload: { entries }
2204
+ };
2205
+ worker.postMessage(entriesMessage);
2206
+ }
2032
2207
  forwardClientSession(worker) {
2033
2208
  this.clientSession.then((clientSession) => {
2034
2209
  const clientSessionMessage = {
@@ -2073,6 +2248,18 @@ var WebWorkerTelemetryClient = class {
2073
2248
  this.pendingInvalidContextSubmissions.record(kindSample);
2074
2249
  this.forwardInvalidContextSubmissions(this.worker);
2075
2250
  }
2251
+ trackedEvent(admission) {
2252
+ if (this.turnedOff || this.closePromise) return;
2253
+ if (this.worker) {
2254
+ const trackedEventMessage = {
2255
+ type: "TrackedEvent",
2256
+ payload: admission
2257
+ };
2258
+ this.worker.postMessage(trackedEventMessage);
2259
+ return;
2260
+ }
2261
+ logBatchWarnings(this.logger, this.pendingTrackedEvents.add(admission));
2262
+ }
2076
2263
  sanitizeEvaluatedConfigEvent(event) {
2077
2264
  return {
2078
2265
  ...event,
@@ -2120,6 +2307,7 @@ var WebWorkerTelemetryClient = class {
2120
2307
  const worker = this.worker;
2121
2308
  if (!worker) {
2122
2309
  this.pendingEvaluations.length = 0;
2310
+ this.pendingTrackedEvents.clear();
2123
2311
  this.closePromise = Promise.resolve();
2124
2312
  return this.closePromise;
2125
2313
  }
@@ -2386,7 +2574,7 @@ const buildClient = async (configdirector, logger) => {
2386
2574
  return {
2387
2575
  client: createBrowserClient(configdirector?.clientSdkKey || void 0, {
2388
2576
  sdkName: "nuxt-sdk",
2389
- sdkVersion: "1.13.2"
2577
+ sdkVersion: "1.14.1"
2390
2578
  }, {
2391
2579
  metadata: {
2392
2580
  appName: configdirector?.appName,
@@ -179,6 +179,9 @@ var SsrClient = class {
179
179
  evaluate(configKey, defaultValue) {
180
180
  return this.serverClient.evaluate(configKey, defaultValue, this.suppliedContext);
181
181
  }
182
+ track(eventName, options) {
183
+ this.serverClient.track(eventName, this.suppliedContext, options);
184
+ }
182
185
  watch() {
183
186
  return () => {};
184
187
  }
@@ -1,4 +1,4 @@
1
- import { n as ConfigDirectorClient } from "../../types-qDEc6g8R.mjs";
1
+ import { n as ConfigDirectorClient } from "../../types-CYquNKWW.mjs";
2
2
 
3
3
  //#region src/runtime/server/composables/useConfigDirectorServerClient.d.ts
4
4
  declare const useConfigDirectorServerClient: () => ConfigDirectorClient;
@@ -1,4 +1,4 @@
1
- import { n as ConfigDirectorClient } from "../../types-qDEc6g8R.mjs";
1
+ import { n as ConfigDirectorClient } from "../../types-CYquNKWW.mjs";
2
2
 
3
3
  //#region src/runtime/server/composables/useConfigDirectorServerClient.d.ts
4
4
  declare const useConfigDirectorServerClient: () => ConfigDirectorClient;
@@ -1,4 +1,4 @@
1
- import { t as ClientHooks } from "../../types-qDEc6g8R.mjs";
1
+ import { t as ClientHooks } from "../../types-CYquNKWW.mjs";
2
2
 
3
3
  //#region src/runtime/server/composables/useConfigDirectorServerHooks.d.ts
4
4
  declare const useConfigDirectorServerHooks: (hooks: ClientHooks) => void;
@@ -1,4 +1,4 @@
1
- import { t as ClientHooks } from "../../types-qDEc6g8R.mjs";
1
+ import { t as ClientHooks } from "../../types-CYquNKWW.mjs";
2
2
 
3
3
  //#region src/runtime/server/composables/useConfigDirectorServerHooks.d.ts
4
4
  declare const useConfigDirectorServerHooks: (hooks: ClientHooks) => void;
@@ -1,4 +1,4 @@
1
- import { a as ConfigValueType, n as ConfigDirectorContext, r as ConfigEvaluation } from "./native-values-CfhP0yLS.mjs";
1
+ import { a as ConfigValueType, n as ConfigDirectorContext, r as ConfigEvaluation, s as TrackOptions } from "./native-values-Cq3SCmEH.mjs";
2
2
 
3
3
  //#region ../js-client-core/src/Emitter.d.ts
4
4
  type EventType = string | symbol;
@@ -115,8 +115,8 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
115
115
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
116
116
  /**
117
117
  * Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
118
- * was served and its value ID. Like every read, it fires `configEvaluated` and is counted in
119
- * telemetry.
118
+ * was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
119
+ * counted in telemetry.
120
120
  *
121
121
  * @returns The evaluation, whose `value` is what {@link getValue} returns
122
122
  * @param configKey The config key to evaluate
@@ -148,6 +148,20 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
148
148
  * Removes all subscribers from all config keys
149
149
  */
150
150
  unwatchAll(): void;
151
+ /**
152
+ * Reports to ConfigDirector that something happened for the current context, such as a completed
153
+ * checkout, so it can be counted. The event is sent with the next telemetry batch. `track` never
154
+ * throws, and does nothing in `offline` mode.
155
+ *
156
+ * An event counts for an experiment only when the current context has an `id`, the one the
157
+ * experiment's config was evaluated for. Before the client has a context, or for a context
158
+ * without an `id`, the event is still reported.
159
+ *
160
+ * @param eventName The name of the event, 1 to 150 characters. An event with any other name is
161
+ * not reported and a warning is logged.
162
+ * @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
163
+ */
164
+ track(eventName: string, options?: TrackOptions): void;
151
165
  /**
152
166
  * Pauses the network connection without clearing event handlers, watch handlers, or config
153
167
  * state. Intended for mobile environments where the OS may kill background connections (e.g.
@@ -1,4 +1,4 @@
1
- import { a as ConfigValueType, i as ConfigState, n as ConfigDirectorContext, r as ConfigEvaluation } from "./native-values-CfhP0yLS.mjs";
1
+ import { a as ConfigValueType, i as ConfigState, n as ConfigDirectorContext, r as ConfigEvaluation, s as TrackOptions } from "./native-values-Cq3SCmEH.mjs";
2
2
 
3
3
  //#region ../js-server-sdk/src/types.d.ts
4
4
  type ClientEvents = {
@@ -61,8 +61,8 @@ interface ConfigDirectorClient {
61
61
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
62
62
  /**
63
63
  * Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
64
- * was served and its value ID. Like every read, it fires `configEvaluated` and is counted in
65
- * telemetry.
64
+ * was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
65
+ * counted in telemetry.
66
66
  *
67
67
  * @returns The evaluation, whose `value` is what {@link getValue} returns
68
68
  * @param configKey The config key to evaluate
@@ -107,6 +107,21 @@ interface ConfigDirectorClient {
107
107
  context?: ConfigDirectorContext;
108
108
  configKeys?: string[];
109
109
  }): Record<string, ConfigState>;
110
+ /**
111
+ * Reports to ConfigDirector that something happened, such as a completed checkout, so it can be
112
+ * counted. The event is sent with the next telemetry batch. `track` never throws, and does nothing
113
+ * in `offline` mode.
114
+ *
115
+ * An event counts for an experiment only when it is tracked for a context with an `id`, the one
116
+ * the experiment's config was evaluated for. Without a context, or for a context without an
117
+ * `id`, the event is still reported.
118
+ *
119
+ * @param eventName The name of the event, 1 to 150 characters. An event with any other name is
120
+ * not reported and a warning is logged.
121
+ * @param context The context the event happened for (optional)
122
+ * @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
123
+ */
124
+ track(eventName: string, context?: ConfigDirectorContext, options?: TrackOptions): void;
110
125
  on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
111
126
  off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
112
127
  /**
@@ -21,24 +21,72 @@ interface ConfigDirectorLogger {
21
21
  }
22
22
  /**
23
23
  * Why an evaluation returned the value it did. `found-match` returns a value from ConfigDirector,
24
- * and `cached` a value kept on the device while a client SDK waits for live values. `value-missing`
24
+ * and `cached` a value kept on the device while a client SDK waits for live values.
25
+ * `rollout-skipped-no-identifier` returns the default targeting rule value: a server SDK skipped a
26
+ * percentage rollout because the context has no `id` to place it in a share. `value-missing`
25
27
  * returns the in-code default value because the config has no value. Every other reason returns the
26
28
  * in-code default value because of an error: the config does not exist (`config-state-missing`), no
27
29
  * values have arrived yet (`client-not-ready`), or the value cannot be read as the type of the in-code
28
30
  * default value.
29
31
  */
30
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
32
+ type EvaluationReason = "found-match" | "rollout-skipped-no-identifier" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
33
+ /**
34
+ * One of the values a config can serve, such as the control or a treatment of an experiment.
35
+ */
36
+ type Variation = {
37
+ /** The ID ConfigDirector assigned to the variation, which stays the same when it is renamed. */id: string; /** The variation's name, when it has one. */
38
+ name?: string;
39
+ };
31
40
  /**
32
41
  * One evaluation of a config: the value it returned, why, and the context it was evaluated for.
33
42
  */
34
43
  type ConfigEvaluation<T extends ConfigValueType = ConfigValueType> = {
35
44
  /** The config key that was evaluated. */key: string; /** The value returned, which is the in-code default value when {@link isDefaultValue} is `true`. */
36
45
  value: T; /** The ID ConfigDirector assigned to the value returned, when ConfigDirector sent one with it. */
37
- valueId?: string; /** Whether the evaluation returned the in-code default value. */
46
+ valueId?: string;
47
+ /**
48
+ * The variation that was served. It is `undefined` when the config has no variations or the
49
+ * in-code default value is returned.
50
+ */
51
+ variation?: Variation; /** Whether the evaluation returned the in-code default value. */
38
52
  isDefaultValue: boolean; /** Why the evaluation returned this value. */
39
53
  reason: EvaluationReason; /** The context the config was evaluated for, if any. */
40
54
  context?: ConfigDirectorContext;
41
55
  };
56
+ /**
57
+ * A value in the details of a tracked event: a string, a number, a boolean, or an array or object
58
+ * of such values.
59
+ */
60
+ type TrackedEventDetailValue = string | number | boolean | TrackedEventDetailValue[] | {
61
+ [key: string]: TrackedEventDetailValue;
62
+ };
63
+ /**
64
+ * Details of a tracked event, such as the plan a customer chose. Details with more than 20
65
+ * top-level keys, or larger than 1 KB as JSON, are left out and the event is still reported.
66
+ */
67
+ type TrackedEventDetails = {
68
+ [key: string]: TrackedEventDetailValue;
69
+ };
70
+ /**
71
+ * What a tracked event carries besides its name.
72
+ */
73
+ type TrackOptions = {
74
+ /**
75
+ * A number the event measures, such as an amount of money, a count or a duration. A value that
76
+ * is not a finite number is left out and the event is still reported.
77
+ */
78
+ value?: number; /** Details of the event. */
79
+ details?: TrackedEventDetails;
80
+ };
81
+ /**
82
+ * An event the code under test tracked, as a test client recorded it.
83
+ */
84
+ type TrackedEvent = {
85
+ /** The name the event was tracked with. */name: string; /** The context the event was tracked for, if any. */
86
+ context?: ConfigDirectorContext; /** The value the event was tracked with, when it is a finite number. */
87
+ value?: number; /** The details the event was tracked with, when they are within the limits. */
88
+ details?: TrackedEventDetails;
89
+ };
42
90
  /**
43
91
  * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
44
92
  * organization, that configs are evaluated for. This context will be used for targeting rules
@@ -195,8 +243,8 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
195
243
  getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
196
244
  /**
197
245
  * Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
198
- * was served and its value ID. Like every read, it fires `configEvaluated` and is counted in
199
- * telemetry.
246
+ * was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
247
+ * counted in telemetry.
200
248
  *
201
249
  * @returns The evaluation, whose `value` is what {@link getValue} returns
202
250
  * @param configKey The config key to evaluate
@@ -228,6 +276,20 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
228
276
  * Removes all subscribers from all config keys
229
277
  */
230
278
  unwatchAll(): void;
279
+ /**
280
+ * Reports to ConfigDirector that something happened for the current context, such as a completed
281
+ * checkout, so it can be counted. The event is sent with the next telemetry batch. `track` never
282
+ * throws, and does nothing in `offline` mode.
283
+ *
284
+ * An event counts for an experiment only when the current context has an `id`, the one the
285
+ * experiment's config was evaluated for. Before the client has a context, or for a context
286
+ * without an `id`, the event is still reported.
287
+ *
288
+ * @param eventName The name of the event, 1 to 150 characters. An event with any other name is
289
+ * not reported and a warning is logged.
290
+ * @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
291
+ */
292
+ track(eventName: string, options?: TrackOptions): void;
231
293
  /**
232
294
  * Pauses the network connection without clearing event handlers, watch handlers, or config
233
295
  * state. Intended for mobile environments where the OS may kill background connections (e.g.
@@ -267,7 +329,9 @@ type TestClientOptions = {
267
329
  */
268
330
  timeout?: number;
269
331
  /**
270
- * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
332
+ * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since the
333
+ * test client sends no telemetry, every tracked event that is not recorded as it was tracked logs
334
+ * a warning, rather than each cause once per telemetry batch.
271
335
  */
272
336
  logger?: ConfigDirectorLogger;
273
337
  };
@@ -336,6 +400,13 @@ interface TestClient {
336
400
  * the client connects without it. Resumes are not recorded.
337
401
  */
338
402
  readonly contextUpdates: ConfigDirectorContext[];
403
+ /**
404
+ * Every event the code under test tracked through the client, in call order, with the context
405
+ * the client had at that moment, as the SDK would report it: an event whose name does not have
406
+ * 1 to 150 characters is not recorded, and a value or details the SDK would leave out are missing
407
+ * from the record. The limit of 1,000 events per telemetry batch does not apply.
408
+ */
409
+ readonly trackedEvents: TrackedEvent[];
339
410
  }
340
411
  //#endregion
341
412
  //#region ../js-client-core/src/testing/installTestClient.d.ts
@@ -395,4 +466,4 @@ declare class ConfigDirectorValidationError extends Error {
395
466
  */
396
467
  declare const createTestClient: (options?: TestClientOptions) => TestClient;
397
468
  //#endregion
398
- export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, createTestClient, installTestClient };
469
+ export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, type TrackedEvent, type TrackedEventDetailValue, type TrackedEventDetails, createTestClient, installTestClient };