@configdirector/react-web-sdk 1.10.1 → 1.11.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.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./installedTestClient-DW8iNFA5.cjs`),t={environmentId:`test-environment`,projectId:`test-project`},n=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var r=class{constructor(t,n){this.logger=t,this.emitter=new e.p,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(n)}get contextUpdates(){return[...this.recordedContexts]}setValue(e,n){let r=this.encode(e,n);this.configs.set(e,r),this.deliverIfConnected({...t,kind:`delta`,configs:{[e]:r}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){this.pendingHold?.attempt===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){this.pendingHold?.attempt===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,r){this.endAttempt();let i=n(r);if(!i)return this.connectNow();this.recordedContexts.push(e);let a=this.armed[i];switch(this.armed[i]=`nothing`,a){case`failure`:return this.failNow(r);case`hold`:return this.holdNow(i,r,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){this.attemptGeneration++,this.connected=!1,this.pendingHold?.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>this.pendingHold?.end(),n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(t){return new e.d(`Connection failed with status: 401. Error: the test client failed this ${t}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...t,kind:`full`,configs:Object.fromEntries(this.configs)}}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(t,n){return e.u(`test-config:${t}`,t,n,`test-value:${t}:${++this.revision}`)}},i=class{constructor(e,t){this.client=e,this.connection=t}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const a=(t,n)=>{let a=n?.logger??e.l(),o=new r(a,n?.values??{});return new i(new e.r(()=>e.c,`test-client`,t,{logger:a,connection:{timeout:n?.timeout}},{transport:o}),o)},o=t=>{let n=globalThis,r=n[e.t];return n[e.t]=t.client,()=>{n[e.t]=r}},s=e=>a({sdkName:`react-web-sdk`,sdkVersion:`1.10.1`},e);exports.ConfigDirectorConnectionError=e.d,exports.ConfigDirectorValidationError=e.f,exports.createTestClient=s,exports.installTestClient=o;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./installedTestClient-e5GGVvz6.cjs`),t=(e,t)=>({name:e.name,...t===void 0?{}:{context:t},...e.value===void 0?{}:{value:e.value},...e.details===void 0?{}:{details:e.details}});var n=class{constructor(e){this.logger=e,this.events=[]}record(n,r){switch(n.warnings.forEach(t=>this.logger.warn(e.g[t])),n.outcome){case`dropped`:return;case`admitted`:this.events.push(t(n.entry,r));return}}};const r={environmentId:`test-environment`,projectId:`test-project`},i=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var a=class{constructor(t,n){this.logger=t,this.emitter=new e.p,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(n)}get contextUpdates(){return[...this.recordedContexts]}setValue(e,t){let n=this.encode(e,t);this.configs.set(e,n),this.deliverIfConnected({...r,kind:`delta`,configs:{[e]:n}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){this.pendingHold?.attempt===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){this.pendingHold?.attempt===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,n){this.endAttempt();let r=i(n);if(!r)return this.connectNow();this.recordedContexts.push(e);let a=this.armed[r];switch(this.armed[r]=`nothing`,a){case`failure`:return this.failNow(n);case`hold`:return this.holdNow(r,n,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){this.attemptGeneration++,this.connected=!1,this.pendingHold?.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>this.pendingHold?.end(),n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(t){return new e.d(`Connection failed with status: 401. Error: the test client failed this ${t}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...r,kind:`full`,configs:Object.fromEntries(this.configs)}}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(t,n){return e.u(`test-config:${t}`,t,n,`test-value:${t}:${++this.revision}`)}},o=class{constructor(e,t,n){this.client=e,this.connection=t,this.trackedEvents=n}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const s=(t,r)=>{let i=r?.logger??e.l(),s=new a(i,r?.values??{}),c=new n(i);return new o(new e.r(()=>({...e.c,trackedEvent:(e,t)=>c.record(e,t)}),`test-client`,t,{logger:i,connection:{timeout:r?.timeout}},{transport:s}),s,c.events)},c=t=>{let n=globalThis,r=n[e.t];return n[e.t]=t.client,()=>{n[e.t]=r}},l=e=>s({sdkName:`react-web-sdk`,sdkVersion:`1.11.1`},e);exports.ConfigDirectorConnectionError=e.d,exports.ConfigDirectorValidationError=e.f,exports.createTestClient=l,exports.installTestClient=c;
@@ -1,4 +1,4 @@
1
- import { c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext } from "./types-CTTaCWsq.cjs";
1
+ import { b as TrackedEventDetails, c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext, v as TrackedEvent, y as TrackedEventDetailValue } from "./types-Bh2N89iB.cjs";
2
2
 
3
3
  //#region ../shared/src/errors.d.ts
4
4
  declare class ConfigDirectorConnectionError extends Error {
@@ -28,7 +28,9 @@ type TestClientOptions = {
28
28
  */
29
29
  timeout?: number;
30
30
  /**
31
- * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
31
+ * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since the
32
+ * test client sends no telemetry, every tracked event that is not recorded as it was tracked logs
33
+ * a warning, rather than each cause once per telemetry batch.
32
34
  */
33
35
  logger?: ConfigDirectorLogger;
34
36
  };
@@ -97,6 +99,13 @@ interface TestClient {
97
99
  * the client connects without it. Resumes are not recorded.
98
100
  */
99
101
  readonly contextUpdates: ConfigDirectorContext[];
102
+ /**
103
+ * Every event the code under test tracked through the client, in call order, with the context
104
+ * the client had at that moment, as the SDK would report it: an event whose name does not have
105
+ * 1 to 150 characters is not recorded, and a value or details the SDK would leave out are missing
106
+ * from the record. The limit of 1,000 events per telemetry batch does not apply.
107
+ */
108
+ readonly trackedEvents: TrackedEvent[];
100
109
  }
101
110
  //#endregion
102
111
  //#region ../js-client-core/src/testing/installTestClient.d.ts
@@ -146,5 +155,5 @@ declare const installTestClient: (testClient: TestClient) => (() => void);
146
155
  */
147
156
  declare const createTestClient: (options?: TestClientOptions) => TestClient;
148
157
  //#endregion
149
- export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, createTestClient, installTestClient };
158
+ 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 };
150
159
  //# sourceMappingURL=configdirector-react-client-testing.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-react-client-testing.d.cts","names":[],"sources":["../../shared/src/errors.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"mappings":";;;cAAa,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;;AAfd;;KCYY,iBAAA;EDZ4C;;;;;ECkBtD,MAAA,GAAS,YAAA;EDdoB;;;AAQ/B;ECWE,OAAA;;;;EAIA,MAAA,GAAS,oBAAA;AAAA;;;;;;;AAfX;;UA0BiB,UAAA;EAXc;;;;EAAA,SAgBpB,MAAA,EAAQ,oBAAA;EAhBR;;;AAWX;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;;;;;EAM7B,WAAA,CAAY,GAAA;EAiDkC;;;;EA3C9C,aAAA,CAAc,MAAA,EAAQ,YAAA;EAZb;;;;EAkBT,kBAAA;EANA;;;;EAYA,sBAAA;EAMA;;;;EAAA,kBAAA;EAyByB;;;;EAnBzB,iBAAA;;AC7DF;;;EDmEE,qBAAA;ECnEsD;;;;EDyEtD,iBAAA;EEpED;;;;;EAAA,SF2EU,cAAA,EAAgB,qBAAA;AAAA;;;;;ADxG3B;;;;;;;;;;;;AAYA;;;;;;;cEYa,iBAAA,GAAqB,UAAA,EAAY,UAAA;;;;;;;;;;;;;;AFZ9C;;;;;;;;;cGea,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
1
+ {"version":3,"file":"configdirector-react-client-testing.d.cts","names":[],"sources":["../../shared/src/errors.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"mappings":";;;cAAa,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;;AAfd;;KCmBY,iBAAA;EDnB4C;;;;;ECyBtD,MAAA,GAAS,YAAA;EDrBoB;;;AAQ/B;ECkBE,OAAA;;;;;;EAMA,MAAA,GAAS,oBAAA;AAAA;;;;;AAjBX;;;;UA4BiB,UAAA;EAtBN;;;;EAAA,SA2BA,MAAA,EAAQ,oBAAA;EAhBY;AAW/B;;;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;EAAA;;;;EAM7B,WAAA,CAAY,GAAA;EAyDwB;;;;EAnDpC,aAAA,CAAc,MAAA,EAAQ,YAAA;EAZO;;;;EAkB7B,kBAAA;EANsB;;;;EAYtB,sBAAA;EAYA;;;;EANA,kBAAA;EAiCS;;;;EA3BT,iBAAA;;;ACtEF;;ED4EE,qBAAA;EC5E4C;;;;EDkF5C,iBAAA;EE9EW;;;;;EAAA,SFqFF,cAAA,EAAgB,qBAAA;EErFoC;;;;;;EAAA,SF6FpD,aAAA,EAAe,YAAA;AAAA;;;;;ADzH1B;;;;;;;;;;;;AAYA;;;;;;;cEYa,iBAAA,GAAqB,UAAA,EAAY,UAAA;;;;;;;;;;;;;AFZ9C;;;;;;;;;;cGgBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
@@ -1,4 +1,4 @@
1
- import { c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext } from "./types-BcKqVLfU.mjs";
1
+ import { b as TrackedEventDetails, c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext, v as TrackedEvent, y as TrackedEventDetailValue } from "./types-DEvHIkvY.mjs";
2
2
 
3
3
  //#region ../shared/src/errors.d.ts
4
4
  declare class ConfigDirectorConnectionError extends Error {
@@ -28,7 +28,9 @@ type TestClientOptions = {
28
28
  */
29
29
  timeout?: number;
30
30
  /**
31
- * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
31
+ * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since the
32
+ * test client sends no telemetry, every tracked event that is not recorded as it was tracked logs
33
+ * a warning, rather than each cause once per telemetry batch.
32
34
  */
33
35
  logger?: ConfigDirectorLogger;
34
36
  };
@@ -97,6 +99,13 @@ interface TestClient {
97
99
  * the client connects without it. Resumes are not recorded.
98
100
  */
99
101
  readonly contextUpdates: ConfigDirectorContext[];
102
+ /**
103
+ * Every event the code under test tracked through the client, in call order, with the context
104
+ * the client had at that moment, as the SDK would report it: an event whose name does not have
105
+ * 1 to 150 characters is not recorded, and a value or details the SDK would leave out are missing
106
+ * from the record. The limit of 1,000 events per telemetry batch does not apply.
107
+ */
108
+ readonly trackedEvents: TrackedEvent[];
100
109
  }
101
110
  //#endregion
102
111
  //#region ../js-client-core/src/testing/installTestClient.d.ts
@@ -146,5 +155,5 @@ declare const installTestClient: (testClient: TestClient) => (() => void);
146
155
  */
147
156
  declare const createTestClient: (options?: TestClientOptions) => TestClient;
148
157
  //#endregion
149
- export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type NativeJsonValue as TestJsonValue, type NativeValue as TestValue, type NativeValues as TestValues, createTestClient, installTestClient };
158
+ 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 };
150
159
  //# sourceMappingURL=configdirector-react-client-testing.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-react-client-testing.d.mts","names":[],"sources":["../../shared/src/errors.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"mappings":";;;cAAa,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;;AAfd;;KCYY,iBAAA;EDZ4C;;;;;ECkBtD,MAAA,GAAS,YAAA;EDdoB;;;AAQ/B;ECWE,OAAA;;;;EAIA,MAAA,GAAS,oBAAA;AAAA;;;;;;;AAfX;;UA0BiB,UAAA;EAXc;;;;EAAA,SAgBpB,MAAA,EAAQ,oBAAA;EAhBR;;;AAWX;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;;;;;EAM7B,WAAA,CAAY,GAAA;EAiDkC;;;;EA3C9C,aAAA,CAAc,MAAA,EAAQ,YAAA;EAZb;;;;EAkBT,kBAAA;EANA;;;;EAYA,sBAAA;EAMA;;;;EAAA,kBAAA;EAyByB;;;;EAnBzB,iBAAA;;AC7DF;;;EDmEE,qBAAA;ECnEsD;;;;EDyEtD,iBAAA;EEpED;;;;;EAAA,SF2EU,cAAA,EAAgB,qBAAA;AAAA;;;;;ADxG3B;;;;;;;;;;;;AAYA;;;;;;;cEYa,iBAAA,GAAqB,UAAA,EAAY,UAAA;;;;;;;;;;;;;;AFZ9C;;;;;;;;;cGea,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
1
+ {"version":3,"file":"configdirector-react-client-testing.d.mts","names":[],"sources":["../../shared/src/errors.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"mappings":";;;cAAa,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;;AAfd;;KCmBY,iBAAA;EDnB4C;;;;;ECyBtD,MAAA,GAAS,YAAA;EDrBoB;;;AAQ/B;ECkBE,OAAA;;;;;;EAMA,MAAA,GAAS,oBAAA;AAAA;;;;;AAjBX;;;;UA4BiB,UAAA;EAtBN;;;;EAAA,SA2BA,MAAA,EAAQ,oBAAA;EAhBY;AAW/B;;;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,WAAA;EAAA;;;;EAM7B,WAAA,CAAY,GAAA;EAyDwB;;;;EAnDpC,aAAA,CAAc,MAAA,EAAQ,YAAA;EAZO;;;;EAkB7B,kBAAA;EANsB;;;;EAYtB,sBAAA;EAYA;;;;EANA,kBAAA;EAiCS;;;;EA3BT,iBAAA;;;ACtEF;;ED4EE,qBAAA;EC5E4C;;;;EDkF5C,iBAAA;EE9EW;;;;;EAAA,SFqFF,cAAA,EAAgB,qBAAA;EErFoC;;;;;;EAAA,SF6FpD,aAAA,EAAe,YAAA;AAAA;;;;;ADzH1B;;;;;;;;;;;;AAYA;;;;;;;cEYa,iBAAA,GAAqB,UAAA,EAAY,UAAA;;;;;;;;;;;;;AFZ9C;;;;;;;;;;cGgBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
@@ -1,2 +1,2 @@
1
- import{c as e,d as t,f as n,l as r,m as i,p as a,r as o,t as s,u as c}from"./installedTestClient-DVBA75Gd.mjs";const l={environmentId:`test-environment`,projectId:`test-project`},u=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var d=class{constructor(e,t){this.logger=e,this.emitter=new a,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(t)}get contextUpdates(){return[...this.recordedContexts]}setValue(e,t){let n=this.encode(e,t);this.configs.set(e,n),this.deliverIfConnected(i(i({},l),{},{kind:`delta`,configs:{[e]:n}}))}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,n){this.endAttempt();let r=u(n);if(!r)return this.connectNow();this.recordedContexts.push(e);let i=this.armed[r];switch(this.armed[r]=`nothing`,i){case`failure`:return this.failNow(n);case`hold`:return this.holdNow(r,n,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){var e;this.attemptGeneration++,this.connected=!1,(e=this.pendingHold)==null||e.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{var e;return(e=this.pendingHold)==null?void 0:e.end()},n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(e){return new t(`Connection failed with status: 401. Error: the test client failed this ${e}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return i(i({},l),{},{kind:`full`,configs:Object.fromEntries(this.configs)})}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(e,t){return c(`test-config:${e}`,e,t,`test-value:${e}:${++this.revision}`)}},f=class{constructor(e,t){this.client=e,this.connection=t}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const p=(t,n)=>{var i,a;let s=(i=n==null?void 0:n.logger)==null?r():i,c=new d(s,(a=n==null?void 0:n.values)==null?{}:a);return new f(new o(()=>e,`test-client`,t,{logger:s,connection:{timeout:n==null?void 0:n.timeout}},{transport:c}),c)},m=e=>{let t=globalThis,n=t[s];return t[s]=e.client,()=>{t[s]=n}},h=e=>p({sdkName:`react-web-sdk`,sdkVersion:`1.10.1`},e);export{t as ConfigDirectorConnectionError,n as ConfigDirectorValidationError,h as createTestClient,m as installTestClient};
1
+ import{_ as e,c as t,d as n,f as r,g as i,l as a,p as o,r as s,t as c,u as l}from"./installedTestClient-CtAa-JtW.mjs";const u=(t,n)=>e(e(e({name:t.name},n===void 0?{}:{context:n}),t.value===void 0?{}:{value:t.value}),t.details===void 0?{}:{details:t.details});var d=class{constructor(e){this.logger=e,this.events=[]}record(e,t){switch(e.warnings.forEach(e=>this.logger.warn(i[e])),e.outcome){case`dropped`:return;case`admitted`:this.events.push(u(e.entry,t));return}}};const f={environmentId:`test-environment`,projectId:`test-project`},p=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var m=class{constructor(e,t){this.logger=e,this.emitter=new o,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(t)}get contextUpdates(){return[...this.recordedContexts]}setValue(t,n){let r=this.encode(t,n);this.configs.set(t,r),this.deliverIfConnected(e(e({},f),{},{kind:`delta`,configs:{[t]:r}}))}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,n){this.endAttempt();let r=p(n);if(!r)return this.connectNow();this.recordedContexts.push(e);let i=this.armed[r];switch(this.armed[r]=`nothing`,i){case`failure`:return this.failNow(n);case`hold`:return this.holdNow(r,n,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){var e;this.attemptGeneration++,this.connected=!1,(e=this.pendingHold)==null||e.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{var e;return(e=this.pendingHold)==null?void 0:e.end()},n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(e){return new n(`Connection failed with status: 401. Error: the test client failed this ${e}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return e(e({},f),{},{kind:`full`,configs:Object.fromEntries(this.configs)})}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(e,t){return l(`test-config:${e}`,e,t,`test-value:${e}:${++this.revision}`)}},h=class{constructor(e,t,n){this.client=e,this.connection=t,this.trackedEvents=n}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const g=(n,r)=>{var i,o;let c=(i=r==null?void 0:r.logger)==null?a():i,l=new m(c,(o=r==null?void 0:r.values)==null?{}:o),u=new d(c);return new h(new s(()=>e(e({},t),{},{trackedEvent:(e,t)=>u.record(e,t)}),`test-client`,n,{logger:c,connection:{timeout:r==null?void 0:r.timeout}},{transport:l}),l,u.events)},_=e=>{let t=globalThis,n=t[c];return t[c]=e.client,()=>{t[c]=n}},v=e=>g({sdkName:`react-web-sdk`,sdkVersion:`1.11.1`},e);export{n as ConfigDirectorConnectionError,r as ConfigDirectorValidationError,v as createTestClient,_ as installTestClient};
2
2
  //# sourceMappingURL=configdirector-react-client-testing.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-react-client-testing.mjs","names":["createTestClient"],"sources":["../../js-client-core/src/testing/InMemoryConnection.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"sourcesContent":["import type {\n ClientConnectAction,\n ConfigDirectorContext,\n ConfigDirectorLogger,\n ConfigSet,\n ConfigState,\n Transport,\n TransportEvents,\n} from \"../types\";\nimport { Emitter } from \"../Emitter\";\nimport { ConfigDirectorConnectionError } from \"../errors\";\nimport type { TestValue, TestValues } from \"./values\";\nimport { nativeValueConfigState } from \"../native-values\";\n\ntype ControlledAttempt = \"initialize\" | \"updateContext\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n attempt: ControlledAttempt;\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nconst controlledAttemptFor = (reason: ClientConnectAction): ControlledAttempt | undefined => {\n switch (reason) {\n case \"initialization\":\n return \"initialize\";\n case \"context update\":\n return \"updateContext\";\n default:\n return undefined;\n }\n};\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new Emitter<TransportEvents>();\n private readonly configs = new Map<string, ConfigState>();\n private readonly recordedContexts: ConfigDirectorContext[] = [];\n private readonly pendingDeliveries: ConfigSet[] = [];\n private readonly armed: Record<ControlledAttempt, Armed> = { initialize: \"nothing\", updateContext: \"nothing\" };\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n private revision = 0;\n private attemptGeneration = 0;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.store(values);\n }\n\n public get contextUpdates(): ConfigDirectorContext[] {\n return [...this.recordedContexts];\n }\n\n public setValue(key: string, value: TestValue) {\n const configState = this.encode(key, value);\n this.configs.set(key, configState);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: configState } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((configState, key) => this.configs.set(key, configState));\n this.armed.initialize = \"nothing\";\n this.armed.updateContext = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold(attempt: ControlledAttempt) {\n this.armed[attempt] = \"hold\";\n }\n\n public complete(attempt: ControlledAttempt) {\n if (this.pendingHold?.attempt === attempt) {\n this.pendingHold.complete();\n } else if (this.armed[attempt] === \"hold\") {\n this.armed[attempt] = \"nothing\";\n }\n }\n\n public fail(attempt: ControlledAttempt) {\n if (this.pendingHold?.attempt === attempt) {\n this.pendingHold.fail();\n } else {\n this.armed[attempt] = \"failure\";\n }\n }\n\n public connect(context: ConfigDirectorContext, timeout: number, reason: ClientConnectAction): Promise<this> {\n this.endAttempt();\n const attempt = controlledAttemptFor(reason);\n if (!attempt) {\n return this.connectNow();\n }\n this.recordedContexts.push(context);\n const armed = this.armed[attempt];\n this.armed[attempt] = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow(reason);\n case \"hold\":\n return this.holdNow(attempt, reason, timeout);\n default:\n return this.connectNow();\n }\n }\n\n public on: Transport[\"on\"] = (name, handler) => this.emitter.on(name, handler);\n\n public off: Transport[\"off\"] = (name, handler) => this.emitter.off(name, handler);\n\n public clear() {\n this.emitter.clear();\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.clear();\n }\n\n private endAttempt() {\n this.attemptGeneration++;\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow(): Promise<this> {\n const connected = Promise.resolve(this);\n this.scheduleFirstDelivery();\n return connected;\n }\n\n private holdNow(attempt: ControlledAttempt, reason: ClientConnectAction, timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n attempt,\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n resolve(this);\n this.scheduleFirstDelivery();\n },\n fail: () => {\n release();\n const error = this.fatalError(reason);\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(reason: ClientConnectAction): Promise<this> {\n const error = this.fatalError(reason);\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError(reason: ClientConnectAction) {\n return new ConfigDirectorConnectionError(\n `Connection failed with status: 401. Error: the test client failed this ${reason}. This is an unrecoverable error, will not attempt to reconnect.`,\n 401,\n );\n }\n\n private scheduleFirstDelivery() {\n const generation = this.attemptGeneration;\n void Promise.resolve()\n .then(() => {})\n .then(() => {\n if (generation !== this.attemptGeneration) {\n return;\n }\n this.connected = true;\n this.deliver(this.fullUpdate());\n });\n }\n\n private deliverIfConnected(configSet: ConfigSet) {\n if (this.connected) {\n this.deliver(configSet);\n }\n }\n\n private deliver(configSet: ConfigSet) {\n this.pendingDeliveries.push(configSet);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configSet: ConfigSet) {\n try {\n this.emitter.emit(\"configSetReceived\", configSet);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigSet {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private store(values: TestValues) {\n this.encodeAll(values).forEach((configState, key) => this.configs.set(key, configState));\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigState> {\n const encoded = new Map<string, ConfigState>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, this.encode(key, value));\n }\n return encoded;\n }\n\n private encode(key: string, value: TestValue): ConfigState {\n return nativeValueConfigState(`test-config:${key}`, key, value, `test-value:${key}:${++this.revision}`);\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type { ConfigDirectorClient, ConfigDirectorContext, ConfigDirectorLogger, IdentifyingSdkOptions } from \"../types\";\nimport { discardingTelemetryClient } from \"../telemetry/discarding\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`).\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` or `updateContext` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing, watchers,\n * events, and readiness behave as they do against ConfigDirector. Only the network connection and\n * telemetry are replaced, so no request is ever made and nothing is left running after the client is\n * disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n\n /**\n * Makes the next `updateContext` wait until {@link completeContextUpdate} or\n * {@link failContextUpdate} is called, or until the client's timeout elapses.\n */\n holdContextUpdate(): void;\n\n /**\n * Delivers the stored values to a held `updateContext`, or disarms an armed hold that no\n * `updateContext` has picked up.\n */\n completeContextUpdate(): void;\n\n /**\n * Fails a held `updateContext` with an unrecoverable connection error, or arms the next\n * `updateContext` to fail.\n */\n failContextUpdate(): void;\n\n /**\n * The context of every `initialize` and `updateContext` call, in call order. `initialize` without\n * a context records an empty context, and so does a call whose context has an invalid kind, since\n * the client connects without it. Resumes are not recorded.\n */\n readonly contextUpdates: ConfigDirectorContext[];\n}\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold(\"initialize\");\n }\n\n public completeInitialization() {\n this.connection.complete(\"initialize\");\n }\n\n public failInitialization() {\n this.connection.fail(\"initialize\");\n }\n\n public holdContextUpdate() {\n this.connection.hold(\"updateContext\");\n }\n\n public completeContextUpdate() {\n this.connection.complete(\"updateContext\");\n }\n\n public failContextUpdate() {\n this.connection.fail(\"updateContext\");\n }\n\n public get contextUpdates(): ConfigDirectorContext[] {\n return this.connection.contextUpdates;\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const client = new DefaultConfigDirectorClient(\n () => discardingTelemetryClient,\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n { transport: connection },\n );\n return new InMemoryTestClient(client, connection);\n};\n","import { INSTALLED_TEST_CLIENT_SLOT, type InstalledTestClientSlot } from \"../installedTestClient\";\nimport type { TestClient } from \"./TestClient\";\n\n/**\n * Makes every `ConfigDirectorProvider` mounted without a `client` prop, and every client\n * `withProvider` would build, use `testClient.client` instead of building a client, until the\n * returned function uninstalls it. Construction props such as `sdkKey` are ignored while installed;\n * `context` and `hooks` apply to the installed client as they do for a `client` prop. A provider\n * reads the installed client when it is constructed, so install before rendering.\n *\n * Installing again replaces the installed test client. Each uninstall function restores the test\n * client that was installed when it was created, so nested installs are uninstalled in reverse order.\n *\n * @param testClient The test client whose `client` providers should use\n * @returns A function that uninstalls it\n *\n * @example\n * let uninstallTestClient: () => void;\n * beforeEach(() => {\n * testClient = createTestClient({ values: { \"new-checkout\": true } });\n * uninstallTestClient = installTestClient(testClient);\n * });\n * afterEach(() => uninstallTestClient());\n */\nexport const installTestClient = (testClient: TestClient): (() => void) => {\n const slot = globalThis as InstalledTestClientSlot;\n const previous = slot[INSTALLED_TEST_CLIENT_SLOT];\n slot[INSTALLED_TEST_CLIENT_SLOT] = testClient.client;\n return () => {\n slot[INSTALLED_TEST_CLIENT_SLOT] = previous;\n };\n};\n","import { createTestClient as createCoreTestClient } from \"@js-client-core/testing/index\";\nimport type { TestClient, TestClientOptions } from \"@js-client-core/testing/index\";\n\nexport { installTestClient } from \"@js-client-core/testing/index\";\nexport type { TestClient, TestClientOptions, TestValue, TestValues, TestJsonValue } from \"@js-client-core/testing/index\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server\n * that the test controls. No network connection is opened and no telemetry is sent. Render with\n * `<ConfigDirectorProvider client={testClient.client}>`, or install it with `installTestClient` for\n * components that render their own provider.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient } from \"@configdirector/react-web-sdk/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * render(\n * <ConfigDirectorProvider client={testClient.client}>\n * <Checkout />\n * </ConfigDirectorProvider>,\n * );\n * act(() => testClient.setValue(\"new-checkout\", false));\n */\nexport const createTestClient = (options?: TestClientOptions): TestClient => {\n return createCoreTestClient({ sdkName: \"react-web-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"configdirector-react-client-testing.mjs","names":["createTestClient"],"sources":["../../shared/src/telemetry/RecordedTrackedEvents.ts","../../js-client-core/src/testing/InMemoryConnection.ts","../../js-client-core/src/testing/TestClient.ts","../../js-client-core/src/testing/installTestClient.ts","../src/testing.ts"],"sourcesContent":["import type { ConfigDirectorContext, ConfigDirectorLogger, TrackedEvent } from \"../types\";\nimport { trackedEventWarningMessages } from \"./tracked-events\";\nimport type { TrackedEventAdmission, TrackedEventEntry } from \"./tracked-events\";\n\nconst recordedEventOf = (entry: TrackedEventEntry, context: ConfigDirectorContext | undefined): TrackedEvent => ({\n name: entry.name,\n ...(context === undefined ? {} : { context }),\n ...(entry.value === undefined ? {} : { value: entry.value }),\n ...(entry.details === undefined ? {} : { details: entry.details }),\n});\n\nexport class RecordedTrackedEvents {\n public readonly events: TrackedEvent[] = [];\n\n constructor(private readonly logger: ConfigDirectorLogger) {}\n\n public record(admission: TrackedEventAdmission, context: ConfigDirectorContext | undefined): void {\n admission.warnings.forEach((warning) => this.logger.warn(trackedEventWarningMessages[warning]));\n switch (admission.outcome) {\n case \"dropped\":\n return;\n case \"admitted\":\n this.events.push(recordedEventOf(admission.entry, context));\n return;\n }\n }\n}\n","import type {\n ClientConnectAction,\n ConfigDirectorContext,\n ConfigDirectorLogger,\n ConfigSet,\n ConfigState,\n Transport,\n TransportEvents,\n} from \"../types\";\nimport { Emitter } from \"../Emitter\";\nimport { ConfigDirectorConnectionError } from \"../errors\";\nimport type { TestValue, TestValues } from \"./values\";\nimport { nativeValueConfigState } from \"../native-values\";\n\ntype ControlledAttempt = \"initialize\" | \"updateContext\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n attempt: ControlledAttempt;\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nconst controlledAttemptFor = (reason: ClientConnectAction): ControlledAttempt | undefined => {\n switch (reason) {\n case \"initialization\":\n return \"initialize\";\n case \"context update\":\n return \"updateContext\";\n default:\n return undefined;\n }\n};\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new Emitter<TransportEvents>();\n private readonly configs = new Map<string, ConfigState>();\n private readonly recordedContexts: ConfigDirectorContext[] = [];\n private readonly pendingDeliveries: ConfigSet[] = [];\n private readonly armed: Record<ControlledAttempt, Armed> = { initialize: \"nothing\", updateContext: \"nothing\" };\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n private revision = 0;\n private attemptGeneration = 0;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.store(values);\n }\n\n public get contextUpdates(): ConfigDirectorContext[] {\n return [...this.recordedContexts];\n }\n\n public setValue(key: string, value: TestValue) {\n const configState = this.encode(key, value);\n this.configs.set(key, configState);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: configState } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((configState, key) => this.configs.set(key, configState));\n this.armed.initialize = \"nothing\";\n this.armed.updateContext = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold(attempt: ControlledAttempt) {\n this.armed[attempt] = \"hold\";\n }\n\n public complete(attempt: ControlledAttempt) {\n if (this.pendingHold?.attempt === attempt) {\n this.pendingHold.complete();\n } else if (this.armed[attempt] === \"hold\") {\n this.armed[attempt] = \"nothing\";\n }\n }\n\n public fail(attempt: ControlledAttempt) {\n if (this.pendingHold?.attempt === attempt) {\n this.pendingHold.fail();\n } else {\n this.armed[attempt] = \"failure\";\n }\n }\n\n public connect(context: ConfigDirectorContext, timeout: number, reason: ClientConnectAction): Promise<this> {\n this.endAttempt();\n const attempt = controlledAttemptFor(reason);\n if (!attempt) {\n return this.connectNow();\n }\n this.recordedContexts.push(context);\n const armed = this.armed[attempt];\n this.armed[attempt] = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow(reason);\n case \"hold\":\n return this.holdNow(attempt, reason, timeout);\n default:\n return this.connectNow();\n }\n }\n\n public on: Transport[\"on\"] = (name, handler) => this.emitter.on(name, handler);\n\n public off: Transport[\"off\"] = (name, handler) => this.emitter.off(name, handler);\n\n public clear() {\n this.emitter.clear();\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.clear();\n }\n\n private endAttempt() {\n this.attemptGeneration++;\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow(): Promise<this> {\n const connected = Promise.resolve(this);\n this.scheduleFirstDelivery();\n return connected;\n }\n\n private holdNow(attempt: ControlledAttempt, reason: ClientConnectAction, timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n attempt,\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n resolve(this);\n this.scheduleFirstDelivery();\n },\n fail: () => {\n release();\n const error = this.fatalError(reason);\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(reason: ClientConnectAction): Promise<this> {\n const error = this.fatalError(reason);\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError(reason: ClientConnectAction) {\n return new ConfigDirectorConnectionError(\n `Connection failed with status: 401. Error: the test client failed this ${reason}. This is an unrecoverable error, will not attempt to reconnect.`,\n 401,\n );\n }\n\n private scheduleFirstDelivery() {\n const generation = this.attemptGeneration;\n void Promise.resolve()\n .then(() => {})\n .then(() => {\n if (generation !== this.attemptGeneration) {\n return;\n }\n this.connected = true;\n this.deliver(this.fullUpdate());\n });\n }\n\n private deliverIfConnected(configSet: ConfigSet) {\n if (this.connected) {\n this.deliver(configSet);\n }\n }\n\n private deliver(configSet: ConfigSet) {\n this.pendingDeliveries.push(configSet);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configSet: ConfigSet) {\n try {\n this.emitter.emit(\"configSetReceived\", configSet);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigSet {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private store(values: TestValues) {\n this.encodeAll(values).forEach((configState, key) => this.configs.set(key, configState));\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigState> {\n const encoded = new Map<string, ConfigState>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, this.encode(key, value));\n }\n return encoded;\n }\n\n private encode(key: string, value: TestValue): ConfigState {\n return nativeValueConfigState(`test-config:${key}`, key, value, `test-value:${key}:${++this.revision}`);\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type {\n ConfigDirectorClient,\n ConfigDirectorContext,\n ConfigDirectorLogger,\n IdentifyingSdkOptions,\n TrackedEvent,\n} from \"../types\";\nimport { RecordedTrackedEvents } from \"@shared/telemetry/RecordedTrackedEvents\";\nimport { discardingTelemetryClient } from \"../telemetry/discarding\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`).\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` or `updateContext` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since the\n * test client sends no telemetry, every tracked event that is not recorded as it was tracked logs\n * a warning, rather than each cause once per telemetry batch.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing, watchers,\n * events, and readiness behave as they do against ConfigDirector. Only the network connection and\n * telemetry are replaced, so no request is ever made and nothing is left running after the client is\n * disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n\n /**\n * Makes the next `updateContext` wait until {@link completeContextUpdate} or\n * {@link failContextUpdate} is called, or until the client's timeout elapses.\n */\n holdContextUpdate(): void;\n\n /**\n * Delivers the stored values to a held `updateContext`, or disarms an armed hold that no\n * `updateContext` has picked up.\n */\n completeContextUpdate(): void;\n\n /**\n * Fails a held `updateContext` with an unrecoverable connection error, or arms the next\n * `updateContext` to fail.\n */\n failContextUpdate(): void;\n\n /**\n * The context of every `initialize` and `updateContext` call, in call order. `initialize` without\n * a context records an empty context, and so does a call whose context has an invalid kind, since\n * the client connects without it. Resumes are not recorded.\n */\n readonly contextUpdates: ConfigDirectorContext[];\n\n /**\n * Every event the code under test tracked through the client, in call order, with the context\n * the client had at that moment, as the SDK would report it: an event whose name does not have\n * 1 to 150 characters is not recorded, and a value or details the SDK would leave out are missing\n * from the record. The limit of 1,000 events per telemetry batch does not apply.\n */\n readonly trackedEvents: TrackedEvent[];\n}\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n public readonly trackedEvents: TrackedEvent[],\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold(\"initialize\");\n }\n\n public completeInitialization() {\n this.connection.complete(\"initialize\");\n }\n\n public failInitialization() {\n this.connection.fail(\"initialize\");\n }\n\n public holdContextUpdate() {\n this.connection.hold(\"updateContext\");\n }\n\n public completeContextUpdate() {\n this.connection.complete(\"updateContext\");\n }\n\n public failContextUpdate() {\n this.connection.fail(\"updateContext\");\n }\n\n public get contextUpdates(): ConfigDirectorContext[] {\n return this.connection.contextUpdates;\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const recordedTrackedEvents = new RecordedTrackedEvents(logger);\n const client = new DefaultConfigDirectorClient(\n () => ({\n ...discardingTelemetryClient,\n trackedEvent: (admission, context) => recordedTrackedEvents.record(admission, context),\n }),\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n { transport: connection },\n );\n return new InMemoryTestClient(client, connection, recordedTrackedEvents.events);\n};\n","import { INSTALLED_TEST_CLIENT_SLOT, type InstalledTestClientSlot } from \"../installedTestClient\";\nimport type { TestClient } from \"./TestClient\";\n\n/**\n * Makes every `ConfigDirectorProvider` mounted without a `client` prop, and every client\n * `withProvider` would build, use `testClient.client` instead of building a client, until the\n * returned function uninstalls it. Construction props such as `sdkKey` are ignored while installed;\n * `context` and `hooks` apply to the installed client as they do for a `client` prop. A provider\n * reads the installed client when it is constructed, so install before rendering.\n *\n * Installing again replaces the installed test client. Each uninstall function restores the test\n * client that was installed when it was created, so nested installs are uninstalled in reverse order.\n *\n * @param testClient The test client whose `client` providers should use\n * @returns A function that uninstalls it\n *\n * @example\n * let uninstallTestClient: () => void;\n * beforeEach(() => {\n * testClient = createTestClient({ values: { \"new-checkout\": true } });\n * uninstallTestClient = installTestClient(testClient);\n * });\n * afterEach(() => uninstallTestClient());\n */\nexport const installTestClient = (testClient: TestClient): (() => void) => {\n const slot = globalThis as InstalledTestClientSlot;\n const previous = slot[INSTALLED_TEST_CLIENT_SLOT];\n slot[INSTALLED_TEST_CLIENT_SLOT] = testClient.client;\n return () => {\n slot[INSTALLED_TEST_CLIENT_SLOT] = previous;\n };\n};\n","import { createTestClient as createCoreTestClient } from \"@js-client-core/testing/index\";\nimport type { TestClient, TestClientOptions } from \"@js-client-core/testing/index\";\n\nexport { installTestClient } from \"@js-client-core/testing/index\";\nexport type { TestClient, TestClientOptions, TestValue, TestValues, TestJsonValue } from \"@js-client-core/testing/index\";\nexport type { TrackedEvent, TrackedEventDetails, TrackedEventDetailValue } from \"@shared/types\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server\n * that the test controls. No network connection is opened and no telemetry is sent. Render with\n * `<ConfigDirectorProvider client={testClient.client}>`, or install it with `installTestClient` for\n * components that render their own provider.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient } from \"@configdirector/react-web-sdk/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * render(\n * <ConfigDirectorProvider client={testClient.client}>\n * <Checkout />\n * </ConfigDirectorProvider>,\n * );\n * act(() => testClient.setValue(\"new-checkout\", false));\n */\nexport const createTestClient = (options?: TestClientOptions): TestClient => {\n return createCoreTestClient({ sdkName: \"react-web-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"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"}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./installedTestClient-DW8iNFA5.cjs`);let l=require(`react`);l=s(l);let u=require(`react/jsx-runtime`);const d=l.default.createContext({status:`loading`}),f=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var p=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}},m=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{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`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:f({value:e.defaultValue,type:e.type}),evaluatedValue:f({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const h=(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`)},g=Math.ceil(128/Math.log2(62)),_=new TextEncoder,v=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,_.encode(e?.toString()??``));return h(new Uint8Array(t,0,16),g)},y=e=>{let t=c.o();if(!t)return;let n=e.then(e=>c.i+e);return{read:async()=>t.getItem(await n),write:async e=>t.setItem(await n,e),remove:async()=>t.removeItem(await n),sizeLimit:()=>c.a}},b=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),x=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return b(new Uint8Array(t))}},S=(e,t,n)=>c.r.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new m({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:c.s,valueIdGenerator:v,clientSession:a}),e,t,n,{sha256HexDigest:x(),platformCachingProvider:y});var C=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const w=e=>c.l(e,new C),T=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>T(e,t[n]));if(!E(e)||!E(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&T(e[n],t[n]))},E=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},D=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!T(t,e.context)?`updateContext`:`none`:`initialize`,O=(e,t)=>S(e,{sdkName:`react-web-sdk`,sdkVersion:`1.10.1`},t),k=e=>O(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??w(`warn`),hooks:e.hooks,caching:e.caching}),A=e=>`client`in e&&e.client!==void 0,j=e=>{if(A(e))return{client:e.client,owned:!1};let t=c.n();return t?{client:t,owned:!1}:{client:k(e),owned:!0}},M=async e=>{let t=c.n()??k({...e,logger:e.logger??w(`debug`)});switch(D(t,e.context)){case`initialize`:await t.initialize(e.context);break;case`updateContext`:await t.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[n,r]=(0,l.useState)(()=>({client:t,status:t.isReady?`ready`:`default`}));return(0,l.useEffect)(()=>{let e=()=>{r(e=>({...e,updatedAt:new Date}))},n=()=>{r(e=>e.status===`ready`?e:{...e,status:`ready`})};return t.on(`configsUpdated`,e),t.on(`clientReady`,n),t.isReady&&n(),()=>{t.off(`configsUpdated`,e),t.off(`clientReady`,n)}},[]),(0,u.jsx)(d.Provider,{value:n,children:e})}};var N=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e??{})){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const P=e=>e?.isReady?`ready`:`default`;var F=class extends l.Component{constructor(e){super(e),this.disposedOwnClient=!1;let t=j(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){let e=this.state.client;this.ownsClient&&this.disposedOwnClient&&(e=k(this.props),this.disposedOwnClient=!1,this.setState({client:e,status:`loading`})),this.handlers=new N(e),this.handlers.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),this.handlers.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.ownsClient||this.handlers.registerHooks(this.props.hooks),await this.connect(e,this.props.context)}async connect(e,t){switch(D(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:this.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}this.setState({status:P(e)})}async componentDidUpdate(e){A(e)&&A(this.props)&&e.client!==this.props.client&&w(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),T(e.context,this.props.context)||(this.setState({status:`loading`}),await this.state.client?.updateContext(this.props.context??{}),this.setState({status:P(this.state.client)}))}componentWillUnmount(){this.handlers?.removeAll(),this.handlers=void 0,this.ownsClient&&(this.state.client?.dispose(),this.disposedOwnClient=!0)}render(){return(0,u.jsx)(d.Provider,{value:this.state,children:this.props.children})}},I=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const L=()=>new I(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),R=(e,t)=>{let n=(0,l.useContext)(d);if(!n?.client)throw L();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},z=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw L();return{updateContext:async t=>{await e.client?.updateContext(t)}}},B=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw L();return{client:e.client}};exports.ConfigDirectorProvider=F,exports.createConsoleLogger=w,exports.useClient=B,exports.useConfigValue=R,exports.useContext=z,exports.withProvider=M;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./installedTestClient-e5GGVvz6.cjs`);let l=require(`react`);l=s(l);let u=require(`react/jsx-runtime`);const d=l.default.createContext({status:`loading`}),f=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}};var p=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}},m=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)}},h=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.pendingTrackedEvents=new m,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{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`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),this.forwardPendingTrackedEvents(e),e}}forwardPendingTrackedEvents(e){let t=this.pendingTrackedEvents.takeBatch();if(t.length===0)return;let n={type:`TrackedEventEntries`,payload:{entries:t}};e.postMessage(n)}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}trackedEvent(e){if(!(this.turnedOff||this.closePromise)){if(this.worker){let t={type:`TrackedEvent`,payload:e};this.worker.postMessage(t);return}c.h(this.logger,this.pendingTrackedEvents.add(e))}}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:f({value:e.defaultValue,type:e.type}),evaluatedValue:f({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const g=(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`)},_=Math.ceil(128/Math.log2(62)),v=new TextEncoder,y=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,v.encode(e?.toString()??``));return g(new Uint8Array(t,0,16),_)},b=e=>{let t=c.o();if(!t)return;let n=e.then(e=>c.i+e);return{read:async()=>t.getItem(await n),write:async e=>t.setItem(await n,e),remove:async()=>t.removeItem(await n),sizeLimit:()=>c.a}},x=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),S=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return x(new Uint8Array(t))}},C=(e,t,n)=>c.r.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new h({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:c.s,valueIdGenerator:y,clientSession:a}),e,t,n,{sha256HexDigest:S(),platformCachingProvider:b});var w=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const T=e=>c.l(e,new w),E=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>E(e,t[n]));if(!D(e)||!D(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&E(e[n],t[n]))},D=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},O=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!E(t,e.context)?`updateContext`:`none`:`initialize`,k=(e,t)=>C(e,{sdkName:`react-web-sdk`,sdkVersion:`1.11.1`},t),A=e=>k(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??T(`warn`),hooks:e.hooks,caching:e.caching}),j=e=>`client`in e&&e.client!==void 0,M=e=>{if(j(e))return{client:e.client,owned:!1};let t=c.n();return t?{client:t,owned:!1}:{client:A(e),owned:!0}},N=async e=>{let t=c.n()??A({...e,logger:e.logger??T(`debug`)});switch(O(t,e.context)){case`initialize`:await t.initialize(e.context);break;case`updateContext`:await t.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[n,r]=(0,l.useState)(()=>({client:t,status:t.isReady?`ready`:`default`}));return(0,l.useEffect)(()=>{let e=()=>{r(e=>({...e,updatedAt:new Date}))},n=()=>{r(e=>e.status===`ready`?e:{...e,status:`ready`})};return t.on(`configsUpdated`,e),t.on(`clientReady`,n),t.isReady&&n(),()=>{t.off(`configsUpdated`,e),t.off(`clientReady`,n)}},[]),(0,u.jsx)(d.Provider,{value:n,children:e})}};var P=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e??{})){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const F=e=>e?.isReady?`ready`:`default`;var I=class extends l.Component{constructor(e){super(e),this.disposedOwnClient=!1;let t=M(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){let e=this.state.client;this.ownsClient&&this.disposedOwnClient&&(e=A(this.props),this.disposedOwnClient=!1,this.setState({client:e,status:`loading`})),this.handlers=new P(e),this.handlers.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),this.handlers.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.ownsClient||this.handlers.registerHooks(this.props.hooks),await this.connect(e,this.props.context)}async connect(e,t){switch(O(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:this.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}this.setState({status:F(e)})}async componentDidUpdate(e){j(e)&&j(this.props)&&e.client!==this.props.client&&T(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),E(e.context,this.props.context)||(this.setState({status:`loading`}),await this.state.client?.updateContext(this.props.context??{}),this.setState({status:F(this.state.client)}))}componentWillUnmount(){this.handlers?.removeAll(),this.handlers=void 0,this.ownsClient&&(this.state.client?.dispose(),this.disposedOwnClient=!0)}render(){return(0,u.jsx)(d.Provider,{value:this.state,children:this.props.children})}},L=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const R=()=>new L(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),z=(e,t)=>{let n=(0,l.useContext)(d);if(!n?.client)throw R();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},B=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw R();return{updateContext:async t=>{await e.client?.updateContext(t)}}},V=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw R();return{client:e.client}};exports.ConfigDirectorProvider=I,exports.createConsoleLogger=T,exports.useClient=V,exports.useConfigValue=z,exports.useContext=B,exports.withProvider=N;
@@ -1,4 +1,4 @@
1
- import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, g as EvaluationReason, h as ConnectionMode, i as ConfigDirectorClient, m as ConfigValueType, n as CachingProvider, o as OfflineValues, p as ConfigEvaluation, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-CTTaCWsq.cjs";
1
+ import { _ as TrackOptions, a as OfflineValue, b as TrackedEventDetails, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, g as EvaluationReason, h as ConnectionMode, i as ConfigDirectorClient, m as ConfigValueType, n as CachingProvider, o as OfflineValues, p as ConfigEvaluation, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext, x as Variation, y as TrackedEventDetailValue } from "./types-Bh2N89iB.cjs";
2
2
  import * as _$react_jsx_runtime0 from "react/jsx-runtime";
3
3
  import { Component, PropsWithChildren, ReactNode } from "react";
4
4
 
@@ -113,5 +113,5 @@ declare const useClient: () => {
113
113
  //#region src/logger.d.ts
114
114
  declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
115
115
  //#endregion
116
- export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConfigEvaluation, type ConnectionMode, type EvaluationReason, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
116
+ export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConfigEvaluation, type ConnectionMode, type EvaluationReason, type OfflineValue, type OfflineValues, type TrackOptions, type TrackedEventDetailValue, type TrackedEventDetails, type Variation, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
117
117
  //# sourceMappingURL=configdirector-react-client.d.cts.map
@@ -1,4 +1,4 @@
1
- import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, g as EvaluationReason, h as ConnectionMode, i as ConfigDirectorClient, m as ConfigValueType, n as CachingProvider, o as OfflineValues, p as ConfigEvaluation, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-BcKqVLfU.mjs";
1
+ import { _ as TrackOptions, a as OfflineValue, b as TrackedEventDetails, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, g as EvaluationReason, h as ConnectionMode, i as ConfigDirectorClient, m as ConfigValueType, n as CachingProvider, o as OfflineValues, p as ConfigEvaluation, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext, x as Variation, y as TrackedEventDetailValue } from "./types-DEvHIkvY.mjs";
2
2
  import { Component, PropsWithChildren, ReactNode } from "react";
3
3
  import * as _$react_jsx_runtime0 from "react/jsx-runtime";
4
4
 
@@ -113,5 +113,5 @@ declare const useClient: () => {
113
113
  //#region src/logger.d.ts
114
114
  declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
115
115
  //#endregion
116
- export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConfigEvaluation, type ConnectionMode, type EvaluationReason, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
116
+ export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConfigEvaluation, type ConnectionMode, type EvaluationReason, type OfflineValue, type OfflineValues, type TrackOptions, type TrackedEventDetailValue, type TrackedEventDetails, type Variation, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
117
117
  //# sourceMappingURL=configdirector-react-client.d.mts.map
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,l as n,m as r,n as i,o as a,r as o,s}from"./installedTestClient-DVBA75Gd.mjs";import c,{Component as l,useContext as u,useEffect as d,useState as f}from"react";import{jsx as p}from"react/jsx-runtime";const m=c.createContext({status:`loading`}),h=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var g=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(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(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},_=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new g,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{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`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return r(r({},e),{},{defaultValue:h({value:e.defaultValue,type:e.type}),evaluatedValue:h({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const v=(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`)},y=Math.ceil(128/Math.log2(62)),b=new TextEncoder,x=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,b.encode((t=e==null?void 0:e.toString())==null?``:t));return v(new Uint8Array(n,0,16),y)},S=n=>{let r=a();if(!r)return;let i=n.then(e=>t+e);return{read:async()=>r.getItem(await i),write:async e=>r.setItem(await i,e),remove:async()=>r.removeItem(await i),sizeLimit:()=>e}},C=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),w=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return C(new Uint8Array(t))}},T=(e,t,n)=>o.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new _({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i==null?void 0:i.appName,appVersion:i==null?void 0:i.appVersion},logger:r,baseUrl:n,urlFactory:s,valueIdGenerator:x,clientSession:a}),e,t,n,{sha256HexDigest:w(),platformCachingProvider:S});var E=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const D=e=>n(e,new E),O=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>O(e,t[n]));if(!k(e)||!k(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&O(e[n],t[n]))},k=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},A=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!O(t,e.context)?`updateContext`:`none`:`initialize`,j=(e,t)=>T(e,{sdkName:`react-web-sdk`,sdkVersion:`1.10.1`},t),M=e=>{var t;return j(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?D(`warn`):t,hooks:e.hooks,caching:e.caching})},N=e=>`client`in e&&e.client!==void 0,P=e=>{if(N(e))return{client:e.client,owned:!1};let t=i();return t?{client:t,owned:!1}:{client:M(e),owned:!0}},F=async e=>{var t,n;let a=(t=i())==null?M(r(r({},e),{},{logger:(n=e.logger)==null?D(`debug`):n})):t;switch(A(a,e.context)){case`initialize`:await a.initialize(e.context);break;case`updateContext`:await a.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[t,n]=f(()=>({client:a,status:a.isReady?`ready`:`default`}));return d(()=>{let e=()=>{n(e=>r(r({},e),{},{updatedAt:new Date}))},t=()=>{n(e=>e.status===`ready`?e:r(r({},e),{},{status:`ready`}))};return a.on(`configsUpdated`,e),a.on(`clientReady`,t),a.isReady&&t(),()=>{a.off(`configsUpdated`,e),a.off(`clientReady`,t)}},[]),p(m.Provider,{value:t,children:e})}};var I=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e==null?{}:e)){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const L=e=>e!=null&&e.isReady?`ready`:`default`;var R=class extends l{constructor(e){super(e),this.disposedOwnClient=!1;let t=P(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){var e=this;let t=e.state.client;e.ownsClient&&e.disposedOwnClient&&(t=M(e.props),e.disposedOwnClient=!1,e.setState({client:t,status:`loading`})),e.handlers=new I(t),e.handlers.on(`configsUpdated`,()=>{e.setState({updatedAt:new Date})}),e.handlers.on(`clientReady`,()=>{e.setState({status:`ready`})}),e.ownsClient||e.handlers.registerHooks(e.props.hooks),await e.connect(t,e.props.context)}async connect(e,t){var n=this;switch(A(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:n.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}n.setState({status:L(e)})}async componentDidUpdate(e){var t=this;if(N(e)&&N(t.props)&&e.client!==t.props.client&&D(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),!O(e.context,t.props.context)){var n,r;t.setState({status:`loading`}),await((n=t.state.client)==null?void 0:n.updateContext((r=t.props.context)==null?{}:r)),t.setState({status:L(t.state.client)})}}componentWillUnmount(){var e;if((e=this.handlers)==null||e.removeAll(),this.handlers=void 0,this.ownsClient){var t;(t=this.state.client)==null||t.dispose(),this.disposedOwnClient=!0}}render(){return p(m.Provider,{value:this.state,children:this.props.children})}},z=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const B=()=>new z(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),V=(e,t)=>{let n=u(m);if(!(n!=null&&n.client))throw B();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},H=()=>{let e=u(m);if(!(e!=null&&e.client))throw B();return{updateContext:async t=>{var n;await((n=e.client)==null?void 0:n.updateContext(t))}}},U=()=>{let e=u(m);if(!(e!=null&&e.client))throw B();return{client:e.client}};export{R as ConfigDirectorProvider,D as createConsoleLogger,U as useClient,V as useConfigValue,H as useContext,F as withProvider};
1
+ import{_ as e,a as t,h as n,i as r,l as i,n as a,o,r as s,s as c}from"./installedTestClient-CtAa-JtW.mjs";import l,{Component as u,useContext as d,useEffect as f,useState as p}from"react";import{jsx as m}from"react/jsx-runtime";const h=l.createContext({status:`loading`}),g=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var _=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(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(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},v=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)}},y=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new _,this.pendingTrackedEvents=new v,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{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`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),this.forwardPendingTrackedEvents(e),e}}forwardPendingTrackedEvents(e){let t=this.pendingTrackedEvents.takeBatch();if(t.length===0)return;let n={type:`TrackedEventEntries`,payload:{entries:t}};e.postMessage(n)}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}trackedEvent(e){if(!(this.turnedOff||this.closePromise)){if(this.worker){let t={type:`TrackedEvent`,payload:e};this.worker.postMessage(t);return}n(this.logger,this.pendingTrackedEvents.add(e))}}sanitizeEvaluatedConfigEvent(t){return e(e({},t),{},{defaultValue:g({value:t.defaultValue,type:t.type}),evaluatedValue:g({value:t.evaluatedValue,valueId:t.evaluatedValueId,type:t.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.pendingTrackedEvents.clear(),this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const b=(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`)},x=Math.ceil(128/Math.log2(62)),S=new TextEncoder,C=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,S.encode((t=e==null?void 0:e.toString())==null?``:t));return b(new Uint8Array(n,0,16),x)},w=e=>{let n=o();if(!n)return;let i=e.then(e=>r+e);return{read:async()=>n.getItem(await i),write:async e=>n.setItem(await i,e),remove:async()=>n.removeItem(await i),sizeLimit:()=>t}},T=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),E=()=>{if(!(typeof crypto>`u`||crypto.subtle==null))return async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return T(new Uint8Array(t))}},D=(e,t,n)=>s.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new y({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i==null?void 0:i.appName,appVersion:i==null?void 0:i.appVersion},logger:r,baseUrl:n,urlFactory:c,valueIdGenerator:C,clientSession:a}),e,t,n,{sha256HexDigest:E(),platformCachingProvider:w});var O=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const k=e=>i(e,new O),A=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>A(e,t[n]));if(!j(e)||!j(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&A(e[n],t[n]))},j=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},M=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!A(t,e.context)?`updateContext`:`none`:`initialize`,N=(e,t)=>D(e,{sdkName:`react-web-sdk`,sdkVersion:`1.11.1`},t),P=e=>{var t;return N(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?k(`warn`):t,hooks:e.hooks,caching:e.caching})},F=e=>`client`in e&&e.client!==void 0,I=e=>{if(F(e))return{client:e.client,owned:!1};let t=a();return t?{client:t,owned:!1}:{client:P(e),owned:!0}},L=async t=>{var n,r;let i=(n=a())==null?P(e(e({},t),{},{logger:(r=t.logger)==null?k(`debug`):r})):n;switch(M(i,t.context)){case`initialize`:await i.initialize(t.context);break;case`updateContext`:await i.updateContext(t.context);break;case`none`:break}return({children:t})=>{let[n,r]=p(()=>({client:i,status:i.isReady?`ready`:`default`}));return f(()=>{let t=()=>{r(t=>e(e({},t),{},{updatedAt:new Date}))},n=()=>{r(t=>t.status===`ready`?t:e(e({},t),{},{status:`ready`}))};return i.on(`configsUpdated`,t),i.on(`clientReady`,n),i.isReady&&n(),()=>{i.off(`configsUpdated`,t),i.off(`clientReady`,n)}},[]),m(h.Provider,{value:n,children:t})}};var R=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e==null?{}:e)){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const z=e=>e!=null&&e.isReady?`ready`:`default`;var B=class extends u{constructor(e){super(e),this.disposedOwnClient=!1;let t=I(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){var e=this;let t=e.state.client;e.ownsClient&&e.disposedOwnClient&&(t=P(e.props),e.disposedOwnClient=!1,e.setState({client:t,status:`loading`})),e.handlers=new R(t),e.handlers.on(`configsUpdated`,()=>{e.setState({updatedAt:new Date})}),e.handlers.on(`clientReady`,()=>{e.setState({status:`ready`})}),e.ownsClient||e.handlers.registerHooks(e.props.hooks),await e.connect(t,e.props.context)}async connect(e,t){var n=this;switch(M(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:n.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}n.setState({status:z(e)})}async componentDidUpdate(e){var t=this;if(F(e)&&F(t.props)&&e.client!==t.props.client&&k(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),!A(e.context,t.props.context)){var n,r;t.setState({status:`loading`}),await((n=t.state.client)==null?void 0:n.updateContext((r=t.props.context)==null?{}:r)),t.setState({status:z(t.state.client)})}}componentWillUnmount(){var e;if((e=this.handlers)==null||e.removeAll(),this.handlers=void 0,this.ownsClient){var t;(t=this.state.client)==null||t.dispose(),this.disposedOwnClient=!0}}render(){return m(h.Provider,{value:this.state,children:this.props.children})}},V=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const H=()=>new V(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),U=(e,t)=>{let n=d(h);if(!(n!=null&&n.client))throw H();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},W=()=>{let e=d(h);if(!(e!=null&&e.client))throw H();return{updateContext:async t=>{var n;await((n=e.client)==null?void 0:n.updateContext(t))}}},G=()=>{let e=d(h);if(!(e!=null&&e.client))throw H();return{client:e.client}};export{B as ConfigDirectorProvider,k as createConsoleLogger,G as useClient,U as useConfigValue,W as useContext,L as withProvider};
2
2
  //# sourceMappingURL=configdirector-react-client.mjs.map