ug-js-sdk 3.0.50 → 3.0.51

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.
@@ -95,8 +95,13 @@ export class VADManager extends EventEmitter {
95
95
  stopAnalysis() {
96
96
  this.clearSilenceTimer();
97
97
  if (this.vadModel) {
98
- this.vadModel.pause();
99
- this.logger.debug('VAD analysis stopped (MicVAD)');
98
+ try {
99
+ this.vadModel.pause();
100
+ this.logger.debug('VAD analysis stopped (MicVAD)');
101
+ }
102
+ catch (error) {
103
+ // Silently ignore errors during pause - vad-web may already be partially cleaned up
104
+ }
100
105
  }
101
106
  }
102
107
  startSilenceTimer() {
@@ -117,17 +122,27 @@ export class VADManager extends EventEmitter {
117
122
  try {
118
123
  this.logger.debug('Disposing VADManager...');
119
124
  this.isDisposed = true;
120
- this.stopAnalysis();
125
+ // Clear timer and listeners first
126
+ this.clearSilenceTimer();
127
+ this.removeAllListeners();
128
+ // Clear stream reference before disposing model to prevent race conditions
129
+ this.currentStream = null;
121
130
  // Clean up VAD model
122
131
  if (this.vadModel) {
132
+ // Try to pause first (stopAnalysis now handles errors gracefully)
133
+ this.stopAnalysis();
134
+ // Then try to destroy
123
135
  if (typeof this.vadModel.destroy === 'function') {
124
- this.vadModel.destroy();
136
+ try {
137
+ this.vadModel.destroy();
138
+ this.logger.debug('VAD model destroyed');
139
+ }
140
+ catch (error) {
141
+ // Silently ignore errors during destroy - vad-web may already be partially cleaned up
142
+ }
125
143
  }
126
144
  this.vadModel = null;
127
145
  }
128
- this.currentStream = null;
129
- this.clearSilenceTimer();
130
- this.removeAllListeners();
131
146
  this.logger.debug('VADManager disposed');
132
147
  }
133
148
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"VADManager.js","sourceRoot":"","sources":["../../../src/ug-core/user-input-manager/VADManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAI3D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,aAAa,EAAE,eAAe;IAC9B,OAAO,EAAE,SAAS;CACV,CAAA;AAEV,MAAM,OAAO,UAAW,SAAQ,YAAY;IAClC,QAAQ,GAAQ,IAAI,CAAA;IACpB,YAAY,GAAkB,IAAI,CAAA;IAClC,gBAAgB,CAAQ;IACxB,uBAAuB,CAAQ;IAC/B,uBAAuB,CAAQ;IAC/B,WAAW,CAAQ;IACnB,UAAU,GAAG,KAAK,CAAA;IAClB,aAAa,GAAuB,IAAI,CAAA;IAEhD,YACE,mBAA2B,GAAG,EAC9B,0BAAkC,GAAG,EACrC,0BAAkC,IAAI,EACtC,cAAsB,GAAG,CAAC,0CAA0C;;QAEpE,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,EAAE,QAAQ,EAAE,eAAe,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAA;QACnF,KAAK,CAAC,MAAM,CAAC,CAAA;QACb,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;IAChC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,MAAmB;QAClC,IAAI,IAAI,CAAC,UAAU;YAAE,OAAM;QAE3B,IAAI,CAAC,aAAa,GAAG,MAAM,CAAA;QAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kEAAkE,CAAC,CAAA;QACrF,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,GAAG,CAAC;YAChC,+CAA+C;YAC/C,SAAS,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,aAAc;YAC1C,WAAW,EAAE,KAAK,IAAI,EAAE;gBACtB,yDAAyD;YAC3D,CAAC;YACD,YAAY,EAAE,KAAK,EAAE,cAA2B,EAAE,EAAE,CAAC,cAAc;YACnE,WAAW,EAAE,KAAK;YAClB,aAAa,EAAE,mBAAmB,EAAE,sBAAsB;YAC1D,gBAAgB,EAAE,mBAAmB,EAAE,sBAAsB;YAC7D,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,aAAa,EAAE,KAAK,IAAI,EAAE;gBACxB,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAA;gBACnC,IAAI,CAAC,iBAAiB,EAAE,CAAA;gBACxB,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA;gBAC1E,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,WAAW,EAAE,KAAK,EAAE,KAAmB,EAAE,EAAE;gBACzC,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAA;gBACjC,IAAI,CAAC,iBAAiB,EAAE,CAAA;gBACxB,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA;gBAC3E,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,YAAY,EAAE,KAAK,IAAI,EAAE;gBACvB,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAA;gBACrC,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;gBAC1F,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,gBAAgB,EAAE,KAAK,EAAE,KAA0B,EAAE,EAAE;gBACrD,4CAA4C;gBAC5C,6CAA6C;YAC/C,CAAC;SACF,CAAC,CAAA;QAEF,qDAAqD;QACrD,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAA;YACjF,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;gBAC3C,QAAQ,CAAC,OAAO,EAAE,CAAA;YACpB,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,KAAK,EAAE,CAAA;YAClB,CAAC;YACD,OAAM;QACR,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,0DAA0D,IAAI,CAAC,gBAAgB,6BAA6B,IAAI,CAAC,uBAAuB,6BAA6B,IAAI,CAAC,uBAAuB,iBAAiB,IAAI,CAAC,WAAW,EAAE,CACrO,CAAA;IACH,CAAC;IAED,aAAa;QACX,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;YACrB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAA;QACpD,CAAC;IACH,CAAC;IAED,YAAY;QACV,IAAI,CAAC,iBAAiB,EAAE,CAAA;QACxB,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;YACrB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAA;QACpD,CAAC;IACH,CAAC;IAED,iBAAiB;QACf,IAAI,IAAI,CAAC,YAAY;YAAE,OAAM;QAC7B,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE;YAC/C,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACzC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QAC1B,CAAC,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAA;IAC3B,CAAC;IAED,iBAAiB;QACf,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;YAC/B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QAC1B,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAA;YAC5C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;YACtB,IAAI,CAAC,YAAY,EAAE,CAAA;YAEnB,qBAAqB;YACrB,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAClB,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;oBAChD,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;gBACzB,CAAC;gBACD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;YACtB,CAAC;YAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAA;YACzB,IAAI,CAAC,iBAAiB,EAAE,CAAA;YACxB,IAAI,CAAC,kBAAkB,EAAE,CAAA;YACzB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAA;QAC1C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAA;QAC7D,CAAC;IACH,CAAC;CACF"}
1
+ {"version":3,"file":"VADManager.js","sourceRoot":"","sources":["../../../src/ug-core/user-input-manager/VADManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAI3D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,aAAa,EAAE,eAAe;IAC9B,OAAO,EAAE,SAAS;CACV,CAAA;AAEV,MAAM,OAAO,UAAW,SAAQ,YAAY;IAClC,QAAQ,GAAQ,IAAI,CAAA;IACpB,YAAY,GAAkB,IAAI,CAAA;IAClC,gBAAgB,CAAQ;IACxB,uBAAuB,CAAQ;IAC/B,uBAAuB,CAAQ;IAC/B,WAAW,CAAQ;IACnB,UAAU,GAAG,KAAK,CAAA;IAClB,aAAa,GAAuB,IAAI,CAAA;IAEhD,YACE,mBAA2B,GAAG,EAC9B,0BAAkC,GAAG,EACrC,0BAAkC,IAAI,EACtC,cAAsB,GAAG,CAAC,0CAA0C;;QAEpE,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,EAAE,QAAQ,EAAE,eAAe,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAA;QACnF,KAAK,CAAC,MAAM,CAAC,CAAA;QACb,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAA;QACxC,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,uBAAuB,GAAG,uBAAuB,CAAA;QACtD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;IAChC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,MAAmB;QAClC,IAAI,IAAI,CAAC,UAAU;YAAE,OAAM;QAE3B,IAAI,CAAC,aAAa,GAAG,MAAM,CAAA;QAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kEAAkE,CAAC,CAAA;QACrF,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,GAAG,CAAC;YAChC,+CAA+C;YAC/C,SAAS,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,aAAc;YAC1C,WAAW,EAAE,KAAK,IAAI,EAAE;gBACtB,yDAAyD;YAC3D,CAAC;YACD,YAAY,EAAE,KAAK,EAAE,cAA2B,EAAE,EAAE,CAAC,cAAc;YACnE,WAAW,EAAE,KAAK;YAClB,aAAa,EAAE,mBAAmB,EAAE,sBAAsB;YAC1D,gBAAgB,EAAE,mBAAmB,EAAE,sBAAsB;YAC7D,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,aAAa,EAAE,KAAK,IAAI,EAAE;gBACxB,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAA;gBACnC,IAAI,CAAC,iBAAiB,EAAE,CAAA;gBACxB,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA;gBAC1E,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,WAAW,EAAE,KAAK,EAAE,KAAmB,EAAE,EAAE;gBACzC,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAA;gBACjC,IAAI,CAAC,iBAAiB,EAAE,CAAA;gBACxB,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA;gBAC3E,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,YAAY,EAAE,KAAK,IAAI,EAAE;gBACvB,IAAI,IAAI,CAAC,UAAU;oBAAE,OAAM;gBAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAA;gBACrC,MAAM,KAAK,GAA0B,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;gBAC1F,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAA;YACxD,CAAC;YACD,gBAAgB,EAAE,KAAK,EAAE,KAA0B,EAAE,EAAE;gBACrD,4CAA4C;gBAC5C,6CAA6C;YAC/C,CAAC;SACF,CAAC,CAAA;QAEF,qDAAqD;QACrD,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAA;YACjF,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;gBAC3C,QAAQ,CAAC,OAAO,EAAE,CAAA;YACpB,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,KAAK,EAAE,CAAA;YAClB,CAAC;YACD,OAAM;QACR,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,0DAA0D,IAAI,CAAC,gBAAgB,6BAA6B,IAAI,CAAC,uBAAuB,6BAA6B,IAAI,CAAC,uBAAuB,iBAAiB,IAAI,CAAC,WAAW,EAAE,CACrO,CAAA;IACH,CAAC;IAED,aAAa;QACX,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;YACrB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAA;QACpD,CAAC;IACH,CAAC;IAED,YAAY;QACV,IAAI,CAAC,iBAAiB,EAAE,CAAA;QACxB,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,IAAI,CAAC;gBACH,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAA;gBACrB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAA;YACpD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,oFAAoF;YACtF,CAAC;QACH,CAAC;IACH,CAAC;IAED,iBAAiB;QACf,IAAI,IAAI,CAAC,YAAY;YAAE,OAAM;QAC7B,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE;YAC/C,MAAM,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACzC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QAC1B,CAAC,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAA;IAC3B,CAAC;IAED,iBAAiB;QACf,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;YAC/B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QAC1B,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAA;YAC5C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;YAEtB,kCAAkC;YAClC,IAAI,CAAC,iBAAiB,EAAE,CAAA;YACxB,IAAI,CAAC,kBAAkB,EAAE,CAAA;YAEzB,2EAA2E;YAC3E,IAAI,CAAC,aAAa,GAAG,IAAI,CAAA;YAEzB,qBAAqB;YACrB,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAClB,kEAAkE;gBAClE,IAAI,CAAC,YAAY,EAAE,CAAA;gBAEnB,sBAAsB;gBACtB,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;oBAChD,IAAI,CAAC;wBACH,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;wBACvB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAA;oBAC1C,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,sFAAsF;oBACxF,CAAC;gBACH,CAAC;gBACD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;YACtB,CAAC;YAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAA;QAC1C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAA;QAC7D,CAAC;IACH,CAAC;CACF"}
@@ -181,4 +181,4 @@ g¹¯´™†ì±Ñp·¯Æúj!Ùê3û|©Ña°9èóPSà‡j¨ÎZ®%Wç–Ç&Õ¹
181
181
  CU¡ÍÌ]Âuf¸i^ÍN¸<ößiIÒzWš’HÈDŒkœòPë­Kã.í»+{J¸…V0¸“J¸“J¸Ã³“J#’ŠÄ8+KÉA¥NA–ú¬ Í)šôš¼¡%°|ù(‹JPs S±E¯j=M-˜2އ[6+Ïû¿²h$ɳ0˜= ê™L,§D1ÌJÈB„„rÚœ YÏxSžòRFxž¤ŒÚK+šÐÃ:„‚&öôê˜GºŸ´;̈ú‚Ïà7Кr´Í6I)ó÷~~àrOŠy­E \ÔfËøª¬ÓFܧìpQ¯{‘¨EO:.ÆÔEÊm‘¢Ä‘¹#{±
182
182
  r÷|‹ú–“
183
183
  Œ*ÔàñT'’ 8KpLjúwù@Q(HÎj{”¥¦Sٝ01TÀ–7F<˜â„<$êÐÉSLVa·ËE–k´&[[ʉׇzôEtF@Ë9KV©ÇEÙK¬)„GŽ4WېWv3ýn§ÁçÂxârjŠzš= €phˆx˜d„t”lŒ|\=}-M¥ìÉÜ\¾Ù%Á?vqš³¾Ãð6†æø Ç]\C"…3ú¹ï5ÞÞçpXç)z²^Rû÷üoõ‚{µ(âw]WT½Ïm§Cö›4&t]Ât[bìÓ®\%óêëÌÔfìW´@¨ÁÚ_ª÷n xV½é9]Mà˝àUß Í/»äµÝ<½äÙÝåáýõaY¿DÅìZÀìØüÛ£üÞÿÍ$Z-×8Ò\ Üb½RLhuñ®äâøþsBV_»ë»Um3
184
- ½ÇaztŸÅò¬¼Åâ`});var S={a:x};this.setModule=t=>{e.setModule(v,t)},this.getModule=()=>e.getModule(v),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,S)).then(e=>{const r=e.exports;var s;!function(e){m=e.m,g=e.n,y=e.p,w=e.q,b=e.r,_=e.s,$=e.t}(r),s=(i=r.k).buffer,new Int8Array(s),new Int16Array(s),t=new Uint8Array(s),new Uint16Array(s),new Int32Array(s),n=new Uint32Array(s),new Float32Array(s),new Float64Array(s),new BigInt64Array(s),new BigUint64Array(s),function(e){e.l()}(r),a()}),this.ready=new Promise(e=>{a=e}).then(()=>{this.HEAP=i.buffer,this.malloc=m,this.free=g,this.mpeg_decoder_feed=w,this.mpeg_decoder_read=b,this.mpeg_frame_decoder_create=y,this.mpeg_frame_decoder_destroy=_}),this)}function x(e={}){return this._init=()=>(new this._WASMAudioDecoderCommon).instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._sampleRate=0,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputSize,Float32Array);const n=this._common.allocateTypedArray(1,Uint32Array);this._samplesDecodedPtr=this._common.allocateTypedArray(1,Uint32Array),this._sampleRatePtr=this._common.allocateTypedArray(1,Uint32Array),this._errorStringPtr=this._common.allocateTypedArray(1,Uint32Array);const i=this._common.wasm.mpeg_frame_decoder_create(n.ptr,!1===e.enableGapless?0:1);if(i)throw Error(this._getErrorMessage(i));this._decoder=n.buf[0]}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this._getErrorMessage=e=>e+" "+this._common.codeToString(this._errorStringPtr.buf[0]),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.mpeg_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder),this._common.free()},this.decode=e=>{let t=[],n=[],i=0;if(!(e instanceof Uint8Array))throw Error("Data to decode must be Uint8Array. Instead got "+typeof e);e:for(let r=0,s=0;r<e.length;r+=s){const a=e.subarray(r,this._input.len+r);s=a.length,this._inputBytes+=s,this._input.buf.set(a);let o=this._common.wasm.mpeg_decoder_feed(this._decoder,this._input.ptr,s);if(-10!==o)for(;;){this._samplesDecodedPtr.buf[0]=0,o=this._common.wasm.mpeg_decoder_read(this._decoder,this._output.ptr,this._output.len,this._samplesDecodedPtr.ptr,this._sampleRatePtr.ptr,this._errorStringPtr.ptr);const e=this._samplesDecodedPtr.buf[0];if(this._outputSamples+=e,e&&(i+=e,t.push([this._output.buf.slice(0,e),this._output.buf.slice(e,2*e)])),-11!=o){if(-10===o)continue e;if(o){const e=this._getErrorMessage(o);console.error("mpg123-decoder: "+e),this._common.addError(n,e,0,this._frameNumber,this._inputBytes,this._outputSamples)}}}}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this.decodeFrame=e=>{const t=this.decode(e);return this._frameNumber++,t},this.decodeFrames=e=>{let t=[],n=[],i=0,r=0;for(;r<e.length;){const s=this.decodeFrame(e[r++]);t.push(s.channelData),n=n.concat(s.errors),i+=s.samplesDecoded}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this._isWebWorker=x.isWebWorker,this._WASMAudioDecoderCommon=x.WASMAudioDecoderCommon||$,this._EmscriptenWASM=x.EmscriptenWASM||v,this._module=x.module,this._inputSize=65536,this._outputSize=92448,this._ready=this._init(),this}class S extends u{MIN_CHUNKS_TO_PROCESS=2;FLUSH_DELAY_MS=450;audioContext;currentSource=null;playbackQueue=[];mp3Decoder=null;scheduledPlayTime=0;playbackStartTime=0;chunkQueue=[];isProcessingQueue=!1;frameExtractor=new g;totalFramesDecoded=0;totalFramesFailed=0;totalFramesExtracted=0;isPlayingState=!1;isPausedState=!1;stopped=!1;frameBuffer=[];chunkAccumulator=[];flushTimeout=null;isAudioComplete=!1;timing;isScheduling=!1;allAudioPlayed=!1;constructor(){super(new o({category:"🎵 AudioPlayer",style:"color: #4caf50; font-weight: bold; font-size: larger"})),this.audioContext=new AudioContext,this.timing=new w(()=>this.getCurrentTime(),()=>this.getQueueLength(),()=>this.getRemainingAudioSeconds(),1e3),this.setupTimingListeners()}setupTimingListeners(){this.timing.on("about-to-complete",async()=>{await this.emit(p.AboutToComplete)})}async initialize(){this.audioContext||(this.audioContext=new AudioContext,this.logger.debug("AudioContext created by user gesture")),"suspended"===this.audioContext.state&&(this.audioContext.resume(),this.logger.debug("AudioContext resumed by user gesture")),this.mp3Decoder||(this.logger.debug("Initializing MP3 decoder..."),this.mp3Decoder=new x,await this.mp3Decoder.ready,this.logger.debug("MP3 decoder ready")),this.resetState()}resetState(){this.currentSource&&(this.currentSource.onended=null,this.currentSource.stop(),this.currentSource=null),this.playbackQueue=[],this.scheduledPlayTime=0,this.playbackStartTime=0,this.chunkQueue=[],this.isProcessingQueue=!1,this.frameExtractor=new g,this.isPlayingState=!1,this.isPausedState=!1,this.stopped=!1,this.frameBuffer=[],this.chunkAccumulator=[],this.isAudioComplete=!1,this.totalFramesDecoded=0,this.totalFramesFailed=0,this.totalFramesExtracted=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.reset(),this.allAudioPlayed=!1}reset(){this.resetState()}enqueue(e){this.logger.debug("Enqueue: received chunk"),this.allAudioPlayed=!1,this.chunkQueue.push({base64String:e}),this.processChunkQueue(),this.isAudioComplete||(this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(()=>{this.logger.debug("auto-flush timer fired"),this.flush()},this.FLUSH_DELAY_MS))}markComplete(){this.logger.debug("markComplete: no more audio will be added"),this.isAudioComplete=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.onAudioComplete(),this.flush();const e=this.frameExtractor.extractRemainingFrames();e.length>0&&(this.logger.debug("markComplete: Found additional frames after flush",{count:e.length}),this.totalFramesExtracted+=e.length,this.decodeAudioFrames(e).then(t=>{if(t){this.totalFramesDecoded+=e.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(t),this.emit(p.Enqueued,{duration:t.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}).catch(t=>{this.totalFramesFailed+=e.length,this.logger.error("Failed to decode final remaining frames after markComplete",t)}));const t=this.frameExtractor.getRemainingBufferSize();t>0&&this.logger.warn("markComplete: Extractor buffer still has data after final extraction",{remainingBytes:t}),this.allAudioPlayed&&(this.logger.debug("markComplete: All audio was already played, emitting Finished."),this.isPlayingState=!1,this.emit(p.Finished))}async processChunkQueue(){if(!this.isProcessingQueue){this.isProcessingQueue=!0;try{for(;this.chunkQueue.length>0;){const{base64String:e}=this.chunkQueue.shift();if(this.chunkAccumulator.push(e),this.chunkAccumulator.length>=this.MIN_CHUNKS_TO_PROCESS){const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e)}}}finally{this.isProcessingQueue=!1}}}decodeBase64ToUint8Array(e){const t="undefined"!=typeof atob?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}combineArrays(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async decodeAudioFrames(e){if(0===e.length)return null;if(!this.mp3Decoder)throw new Error("MP3 decoder not initialized. Call initialize() first.");const t=[];let n=0,i=0,r=0,s=0;for(let a=0;a<e.length;a++){const o=e[a];if(o.length<2||255!==o[0]||224&~o[1])this.logger.warn(`Frame ${a} doesn't start with valid sync word, skipping`,{firstBytes:Array.from(o.slice(0,4)),frameLength:o.length}),s++;else try{const e=this.mp3Decoder.decodeFrame(o);if(e.errors&&e.errors.length>0&&this.logger.warn(`Frame ${a} decoded with errors`,{errors:e.errors.map(e=>e.message||String(e)),frameLength:o.length}),0===e.samplesDecoded){this.logger.warn(`Frame ${a} decoded but produced 0 samples`,{frameLength:o.length,errors:e.errors?.map(e=>e.message||String(e))}),s++;continue}if(0===n?n=e.sampleRate:e.sampleRate!==n&&this.logger.warn(`Frame ${a} has different sample rate: ${e.sampleRate} vs ${n}`),0===t.length)for(let n=0;n<e.channelData.length;n++)t.push([]);for(let n=0;n<e.channelData.length;n++)n<t.length&&t[n].push(e.channelData[n]);i+=e.samplesDecoded,r++}catch(e){this.logger.error(`Failed to decode frame ${a}`,{error:e instanceof Error?e.message:String(e),frameLength:o.length,firstBytes:Array.from(o.slice(0,4))}),s++}}if(0===r)return this.logger.error("All frames failed to decode",{totalFrames:e.length}),null;s>0&&this.logger.warn("Some frames failed to decode",{successful:r,failed:s,total:e.length});const a=[];for(let e=0;e<t.length;e++){const n=new Float32Array(i);let r=0;for(const i of t[e])n.set(i,r),r+=i.length;a.push(n)}const o=this.audioContext.createBuffer(a.length,i,n);for(let e=0;e<a.length;e++)o.getChannelData(e).set(a[e]);return this.logger.debug("Decoded frames",{successful:r,failed:s,totalSamples:i,sampleRate:n,duration:o.duration.toFixed(3)}),o}async play(){this.isPlayingState||0===this.playbackQueue.length?this.logger.debug("Play called but already playing or queue is empty."):(this.isPlayingState=!0,this.stopped=!1,this.isPausedState=!1,this.isPausedState?this.scheduledPlayTime=this.audioContext.currentTime:(this.scheduledPlayTime=this.audioContext.currentTime,this.playbackStartTime=this.audioContext.currentTime),this.logger.debug(`Playback starting. Start time: ${this.playbackStartTime}`),this.schedulePlayback(),await this.emit(p.Playing))}schedulePlayback(){if(this.isScheduling||0===this.playbackQueue.length||this.stopped)return;this.isScheduling=!0,this.currentSource&&(this.currentSource.onended=null);let e=null;for(;this.playbackQueue.length>0;){const t=this.playbackQueue.shift(),n=this.audioContext.createBufferSource();n.buffer=t,n.connect(this.audioContext.destination),this.scheduledPlayTime<this.audioContext.currentTime&&(this.logger.debug(`Adjusting scheduledPlayTime from ${this.scheduledPlayTime} to current time ${this.audioContext.currentTime}`),this.scheduledPlayTime=this.audioContext.currentTime),this.logger.debug(`Scheduling buffer of duration ${t.duration}s to start at ${this.scheduledPlayTime} (context time: ${this.audioContext.currentTime})`),n.start(this.scheduledPlayTime),this.scheduledPlayTime+=t.duration,e=n}e&&(this.currentSource=e,e.onended=()=>{this.logger.debug(`Buffer finished playing. Context time: ${this.audioContext.currentTime}, isPaused: ${this.isPausedState}, stopped: ${this.stopped}`),this.stopped||this.isPausedState||(this.playbackQueue.length>0?(this.logger.debug("More buffers in queue, scheduling next batch."),this.schedulePlayback()):this.isAudioComplete?(this.logger.debug("Last scheduled audio buffer finished and audio is complete."),this.isPlayingState=!1,this.emit(p.Finished)):(this.logger.debug("All scheduled audio has been played, but not marked as complete yet."),this.allAudioPlayed=!0))}),this.isScheduling=!1}async pause(){this.currentSource&&this.isPlayingState&&(this.isPausedState=!0,this.isPlayingState=!1,this.audioContext.suspend(),await this.emit(p.Paused))}async resume(){this.isPausedState&&(this.logger.debug("Resume called, resuming playback."),this.isPausedState=!1,this.isPlayingState=!0,this.audioContext.resume(),this.schedulePlayback(),await this.emit(p.Playing))}async stop(){this.stopped=!0,this.resetState(),await this.emit(p.Stopped)}getCurrentTime(){return this.isPlayingState?1e3*(this.audioContext.currentTime-this.playbackStartTime):0}getQueueLength(){return this.playbackQueue.length}getRemainingAudioSeconds(){const e=this.playbackQueue.reduce((e,t)=>e+t.duration,0);let t=0;return(this.isPlayingState||this.isPausedState)&&this.scheduledPlayTime>0&&(t=Math.max(0,this.scheduledPlayTime-this.audioContext.currentTime)),e+t}async decodeAndEnqueueChunks(e){if(0===e.length)return void this.logger.debug("decodeAndEnqueueChunks: no chunks to decode");let t=[];for(const n of e){const e=this.decodeBase64ToUint8Array(n),{frames:i,remainingData:r}=this.frameExtractor.feedAndExtractCompleteFrames(e);t=t.concat(i),this.totalFramesExtracted+=i.length,r.length>0&&this.logger.debug("Chunk ended with incomplete frame",{remainingBytes:r.length,framesExtracted:i.length})}if(this.logger.debug("decodeAndEnqueueChunks: total frames to decode",t.length),t.length>0){const e=t.map(e=>e.length).reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});this.logger.debug("Frame sizes distribution",e);try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.logger.debug("decodeAndEnqueueChunks: enqueued audioBuffer, duration",e.duration,"frames decoded",t.length),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode audio frames",e),this.logger.error("Lost frames",{count:t.length,sizes:t.map(e=>e.length)})}}else this.logger.debug("decodeAndEnqueueChunks: no frames to decode")}async flush(){this.logger.debug("Flushing",{chunks:this.chunkAccumulator.length});const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e);const t=this.frameExtractor.extractRemainingFrames();if(t.length>0){this.logger.debug("Flush: Found complete frames in extractor buffer",{count:t.length}),this.totalFramesExtracted+=t.length;try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode remaining frames after flush",e)}}}resetAboutToComplete(){this.timing.reset()}getFrameStats(){return{totalFramesExtracted:this.totalFramesExtracted,totalFramesDecoded:this.totalFramesDecoded,totalFramesFailed:this.totalFramesFailed,extractorRemainingBufferSize:this.frameExtractor.getRemainingBufferSize()}}dispose(){if(this.logger.debug("Disposing AudioPlayer..."),this.stopped=!0,this.isPlayingState=!1,this.isPausedState=!1,this.currentSource){this.currentSource.onended=null;try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing&&this.timing.reset(),this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.mp3Decoder=null,this.resetState(),this.removeAllListeners(),this.logger.debug("AudioPlayer disposed")}destroy(){this.dispose()}}const T="wordChange",k="subtitleChange";class E extends u{getCurrentTime;subtitleQueue=[];rafId=null;isPlaying=!1;cumulativeOffset=0;tickDebugLast=0;state={currentLine:null,nextLine:null,globalWordIndex:-1};constructor(e){super(new o({category:"🎬 SubtitleManager",style:"color: #e91e63; font-weight: bold; font-size: larger"})),this.getCurrentTime=e,this._resetState()}enqueue(e){this.logger.debug("Enqueue subtitle",{subtitle:e,queueLength:this.subtitleQueue.length});const{wordBoundaries:t,wordStartTimesMs:n}=this._computeWordBoundariesAndStartTimes(e.characters,e.start_times_ms),i={...e,wordBoundaries:t,wordStartTimesMs:n};this.subtitleQueue.push(i),this.isPlaying||1!==this.subtitleQueue.length||(this.logger.debug("Reset globalWordIndex to -1 (initial enqueue)"),this.state.globalWordIndex=-1),this.isPlaying&&!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),this._emitSubtitleChange())}async play(){this.isPlaying?this.logger.debug("Play called but already playing"):(this.logger.debug("Play called, starting playback"),this.isPlaying=!0,await this.emit("playing"),this.subtitleQueue.length>0&&(this._prepareState(),await this._emitSubtitleChange()),this.rafId=requestAnimationFrame(this._tick))}async pause(){this.logger.debug("Pause called"),this.isPlaying=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),await this.emit("paused")}clearQueue(){this.logger.debug("Clear queue"),this._resetState(),this.pause()}reset(){this._resetState()}_resetState(){this.subtitleQueue=[],this.cumulativeOffset=0,this.rafId=null,this.isPlaying=!1,this.tickDebugLast=0,this.state={currentLine:null,nextLine:null,globalWordIndex:-1}}_subtitleDuration(e){const{start_times_ms:t,durations_ms:n}=e;if(!t.length||!n.length)return 0;const i=t.length-1;return t[i]+n[i]}_applyOffset(e,t){return e.map(e=>e+t)}_prepareState(){if(!this.subtitleQueue.length)return;const e=this.subtitleQueue[0];e.adjustedWordStartTimesMs=this._applyOffset(e.wordStartTimesMs,this.cumulativeOffset);const t=this.subtitleQueue[1]||null;if(t){const n=this.cumulativeOffset+this._subtitleDuration(e);t.adjustedWordStartTimesMs=this._applyOffset(t.wordStartTimesMs,n)}this.state.currentLine=e,this.state.nextLine=t,this.logger.debug("Prepared state",{cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!e,hasNextLine:!!t,firstFewAdjusted:e.adjustedWordStartTimesMs?.slice(0,3)})}_computeWordBoundariesAndStartTimes(e,t){const n=[],i=[];let r=null;for(let s=0;s<e.length;s++){const a=e[s];if(" "!==a&&null===r&&(r=s),(" "===a||s===e.length-1)&&null!==r){const e=" "===a?s-1:s;n.push({start:r,end:e}),i.push(t[r]),r=null}}return{wordBoundaries:n,wordStartTimesMs:i}}_calculateGlobalWordIndex(e){let t=-1;const{currentLine:n,nextLine:i}=this.state;if(n?.adjustedWordStartTimesMs)for(let i=0;i<n.adjustedWordStartTimesMs.length&&e>=n.adjustedWordStartTimesMs[i];i++)t=i;if(i?.adjustedWordStartTimesMs){const r=n?.wordBoundaries.length||0;for(let n=0;n<i.adjustedWordStartTimesMs.length&&e>=i.adjustedWordStartTimesMs[n];n++)t=r+n}return t}_decodeGlobalIndex(e){if(e<0)return{lineIndex:0,wordIndex:-1};const t=this.state.currentLine?.wordBoundaries.length||0;return e<t?{lineIndex:0,wordIndex:e}:{lineIndex:1,wordIndex:e-t}}_isFinished(e,t,n){return t>n+this._subtitleDuration(e)}_buildWordChangeEvent(e){const{lineIndex:t,wordIndex:n}=this._decodeGlobalIndex(e),{currentLine:i,nextLine:r}=this.state,s=e=>e?{characters:e.characters,wordBoundaries:e.wordBoundaries}:null;let a;if(0===t&&i&&n>=0){const e=i.wordBoundaries[n];a=i.characters.slice(e.start,e.end+1).join("")}else if(1===t&&r&&n>=0){const e=r.wordBoundaries[n];a=r.characters.slice(e.start,e.end+1).join("")}return{globalWordIndex:e,currentLineIndex:t,wordIndexInLine:n,word:a,currentLineData:s(i),nextLineData:s(r)}}_buildSubtitleChangeEvent(){const e=e=>e?.adjustedWordStartTimesMs?{characters:e.characters,wordBoundaries:e.wordBoundaries,adjustedWordStartTimesMs:e.adjustedWordStartTimesMs}:null;return{currentLine:e(this.state.currentLine),nextLine:e(this.state.nextLine)}}async _emitWordChange(e){const t=this._buildWordChangeEvent(e);this.logger.debug("Word change",{globalWordIndex:e,lineIndex:t.currentLineIndex,wordIndex:t.wordIndexInLine,word:t.word}),await this.emit(T,t)}async _emitSubtitleChange(){const e=this._buildSubtitleChangeEvent();this.logger.debug("Subtitle change",{hasCurrentLine:!!e.currentLine,hasNextLine:!!e.nextLine}),await this.emit(k,e)}_tick=async()=>{if(!this.isPlaying||0===this.subtitleQueue.length)return;!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),await this._emitSubtitleChange());const e=this.getCurrentTime();this.state.currentLine||this._prepareState(),e-this.tickDebugLast>=3e3&&(this.logger.debug("Tick debug",{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!this.state.currentLine,hasNextLine:!!this.state.nextLine}),this.tickDebugLast=e);const t=this._calculateGlobalWordIndex(e);t!==this.state.globalWordIndex&&(this.state.globalWordIndex=t,await this._emitWordChange(t));const n=this.subtitleQueue[0],i=this.subtitleQueue[1]||null;let r=0;if(i){const t=this.cumulativeOffset+this._subtitleDuration(n);this._isFinished(i,e,t)&&(r=2)}else n&&this._isFinished(n,e,this.cumulativeOffset)&&(r=1);if(r>0){this.logger.debug(`Subtitle batch finished. Advancing ${r} lines.`,{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset});const t=this.subtitleQueue.splice(0,r);for(const e of t)this.cumulativeOffset+=this._subtitleDuration(e),await this.emit("subtitleFinished",e);if(!(this.subtitleQueue.length>0))return this.logger.debug("Queue empty, pausing"),this.state.globalWordIndex=-1,await this._emitWordChange(-1),void await this.pause();this._prepareState(),await this._emitSubtitleChange()}this.rafId=requestAnimationFrame(this._tick)}}class C extends u{scheduledEvents=[];masterClock;constructor(e){super(new o({category:"👄 VisemeScheduler",style:"color: #f44336; font-weight: bold; font-size: larger"})),this.masterClock=e}enqueue(e){this.scheduledEvents.push(...e),this.scheduleEvents()}async play(){await this.emit(f.Playing)}async pause(){await this.emit(f.Paused)}scheduleEvents(){this.masterClock.currentTime,this.scheduledEvents.forEach(e=>{setTimeout(async()=>{await this.emit(f.Viseme,e)})})}}class I extends u{animationLayers=new Map;layerPriority=["mouth","facial","body","idle"];thinkToggle=!1;constructor(){super(new o({category:"🧒 AvatarManager",style:r}))}playIdle(){this.playAnimation("body_idle",0,!0)}playListen(){this.playAnimation("body_idle_listen",0,!0)}playTalk(){this.playAnimation("body_talk_to_user_loop",0,!0)}playThink(){const e=this.thinkToggle?"body_idle_think2":"body_idle_think";this.thinkToggle=!this.thinkToggle,this.playAnimation(e,0,!0)}playLaugh(){this.playAnimation("body_laugh",0,!0)}playWaving(){this.playAnimation("body_waving",0,!1)}playViseme(e){this.playAnimation(e,1,!1)}async playAnimation(e,t=0,n=!0){this.animationLayers.set(t,e),await this.emit(m.AnimationChanged,{name:e,layer:t,loop:n}),this.logger.debug(`Playing animation: ${e} on layer ${t} (loop: ${n})`)}async stopAnimation(e=0){this.animationLayers.delete(e),await this.emit(m.AnimationStopped,{layer:e})}dispose(){try{this.logger.debug("Disposing AvatarManager..."),this.animationLayers.clear(),this.thinkToggle=!1,this.removeAllListeners(),this.logger.debug("AvatarManager disposed")}catch(e){this.logger.warn("Error while disposing AvatarManager",e)}}}const A="playing",R="playbackError",M="subtitleWordChange",O="subtitleChange",z="imageChange",P="finished",B="avatarAnimationChanged";class D extends u{capabilities;audioPlayer;visemeScheduler;subtitleManager;isPaused=!0;hasStarted=!1;avatarManager;constructor(e){super(new o({category:"🎪 PlaybackManager",style:r})),this.capabilities=e,this.audioPlayer=new S,this.visemeScheduler=new C(new AudioContext),this.subtitleManager=new E(()=>this.audioPlayer.getCurrentTime()),this.avatarManager=new I,this.avatarManager.on("animation-changed",async e=>{await this.emit(B,e)}),this.setupChildListeners(),this.resetState()}setupChildListeners(){this.audioPlayer.on(p.Ready,()=>{this.isPaused&&!this.hasStarted?(this.logger.debug("Ready event received, starting playback"),this.play()):this.logger.debug("Ready event received but already playing or paused, ignoring")}),this.audioPlayer.on(p.AboutToComplete,async()=>{this.logger.debug("Audio about to complete"),await this.emit("aboutToComplete")}),this.audioPlayer.on(p.Error,async e=>{await this.emit(R,{source:"audio",error:e})}),this.audioPlayer.on(p.Finished,async()=>{await this.emit(P),this.reset()}),this.subtitleManager.on(T,async e=>{await this.emit(M,e)}),this.subtitleManager.on(k,async e=>{await this.emit(O,e)})}resetState(){this.isPaused=!0,this.hasStarted=!1}async initialize(){this.logger.debug("Initialized",this.capabilities),this.isPaused=!0,this.hasStarted=!1,await this.audioPlayer.initialize()}handleMessage(e){"audio"===e.event||"subtitles"===e.event||"viseme"===e.event?this.enqueue(e):"audio_complete"===e.event?this.markAudioComplete():"image"===e.event&&this.emit(z,e)}enqueue(e){if(this.capabilities.audio&&"audio"===e.event){const t=e;this.audioPlayer.enqueue(t.audio)}}markAudioComplete(){this.logger.debug("Marking audio as complete"),this.capabilities.audio&&this.audioPlayer.markComplete()}async play(){this.isPaused=!1,this.hasStarted=!0,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.play():Promise.resolve()]),await this.emit(A)}async pause(){this.isPaused=!0,this.audioPlayer.pause(),this.visemeScheduler.pause(),this.subtitleManager.pause(),this.avatarManager.playIdle(),await this.emit("paused")}async resume(){this.isPaused&&(this.isPaused=!1,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.resume():Promise.resolve()]),await this.emit(A))}async resumeAudioContext(){"function"==typeof this.audioPlayer.resumeAudioContext&&await this.audioPlayer.resumeAudioContext()}getRemainingAudioSeconds(){return this.audioPlayer?.getRemainingAudioSeconds()??0}reset(){this.resetState(),this.audioPlayer?.reset(),this.subtitleManager?.reset(),this.avatarManager.playIdle()}resetAboutToComplete(){this.audioPlayer?.resetAboutToComplete()}dispose(){this.logger.debug("Disposing PlaybackManager...");try{this.isPaused=!0,this.hasStarted=!1,this.audioPlayer?.pause(),this.visemeScheduler?.pause(),this.subtitleManager?.pause(),this.avatarManager?.playIdle()}catch(e){this.logger.warn("Error pausing components during dispose",e)}try{this.audioPlayer&&"function"==typeof this.audioPlayer.dispose&&this.audioPlayer.dispose()}catch(e){this.logger.warn("Error disposing audioPlayer",e)}try{this.avatarManager&&"function"==typeof this.avatarManager.dispose&&this.avatarManager.dispose()}catch(e){this.logger.warn("Error disposing avatarManager",e)}try{this.subtitleManager?.reset(),this.removeAllListeners()}catch(e){this.logger.warn("Error resetting subtitleManager or removing listeners",e)}this.logger.debug("PlaybackManager disposed")}wireVADToAvatar(e){e.on(Sn.StateChange,e=>{"userSpeaking"===e.newState?this.avatarManager.playListen():"listening"===e.newState&&this.avatarManager.playIdle()})}wireConversationStateToAvatar(e){e.on(Sn.StateChange,e=>{"waiting"===e.newState&&this.avatarManager.playThink()})}}var U=n(937);const L="voiceActivity";class N extends u{vadModel=null;silenceTimer=null;silenceTimeoutMs;positiveSpeechThreshold;negativeSpeechThreshold;minSpeechMs;isDisposed=!1;currentStream=null;constructor(e=300,t=.5,n=.35,i=100){super(new o({category:"🎤 VADManager",style:s})),this.silenceTimeoutMs=e,this.positiveSpeechThreshold=t,this.negativeSpeechThreshold=n,this.minSpeechMs=i}async initialize(e){if(this.isDisposed)return;this.currentStream=e,this.logger.debug("You may need to close the browser console for this to initialize");const t=await U.Jl.new({getStream:async()=>this.currentStream,pauseStream:async()=>{},resumeStream:async e=>e,startOnLoad:!1,baseAssetPath:"/static/binaries/",onnxWASMBasePath:"/static/binaries/",positiveSpeechThreshold:this.positiveSpeechThreshold,negativeSpeechThreshold:this.negativeSpeechThreshold,minSpeechMs:this.minSpeechMs,onSpeechStart:async()=>{this.isDisposed||(this.logger.debug("Speech started"),this.clearSilenceTimer(),await this.emit(L,{isSpeaking:!0,confidence:1}))},onSpeechEnd:async e=>{this.isDisposed||(this.logger.debug("Speech ended"),this.startSilenceTimer(),await this.emit(L,{isSpeaking:!1,confidence:1}))},onVADMisfire:async()=>{this.isDisposed||(this.logger.debug("Misfire detected"),await this.emit(L,{isSpeaking:!1,confidence:0,misfire:!0}))},onFrameProcessed:async e=>{}});if(this.isDisposed)return this.logger.debug("VADManager disposed during initialization, cleaning up model"),void("function"==typeof t.destroy?t.destroy():t.pause());this.vadModel=t,this.logger.debug(`VAD Manager initialized (MicVAD) with silenceTimeoutMs=${this.silenceTimeoutMs}, positiveSpeechThreshold=${this.positiveSpeechThreshold}, negativeSpeechThreshold=${this.negativeSpeechThreshold}, minSpeechMs=${this.minSpeechMs}`)}startAnalysis(){this.vadModel&&(this.vadModel.start(),this.logger.debug("VAD analysis started (MicVAD)"))}stopAnalysis(){this.clearSilenceTimer(),this.vadModel&&(this.vadModel.pause(),this.logger.debug("VAD analysis stopped (MicVAD)"))}startSilenceTimer(){this.silenceTimer||(this.silenceTimer=window.setTimeout(async()=>{await this.emit("silence"),this.silenceTimer=null},this.silenceTimeoutMs))}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}dispose(){try{this.logger.debug("Disposing VADManager..."),this.isDisposed=!0,this.stopAnalysis(),this.vadModel&&("function"==typeof this.vadModel.destroy&&this.vadModel.destroy(),this.vadModel=null),this.currentStream=null,this.clearSilenceTimer(),this.removeAllListeners(),this.logger.debug("VADManager disposed")}catch(e){this.logger.warn("Error while disposing VADManager",e)}}}const H="user-input",F="user-speaking",q="user-silence",V={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let W;const j=new Uint8Array(16),G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function K(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!W){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");W=crypto.getRandomValues.bind(crypto)}return W(j)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=i[e];return t}return function(e,t=0){return(G[e[t+0]]+G[e[t+1]]+G[e[t+2]]+G[e[t+3]]+"-"+G[e[t+4]]+G[e[t+5]]+"-"+G[e[t+6]]+G[e[t+7]]+"-"+G[e[t+8]]+G[e[t+9]]+"-"+G[e[t+10]]+G[e[t+11]]+G[e[t+12]]+G[e[t+13]]+G[e[t+14]]+G[e[t+15]]).toLowerCase()}(i)}class Q{websocket=null;handlers;serverUrl;constructor(e,t){this.serverUrl=e,this.handlers=t}connect(){this.websocket=new WebSocket(this.serverUrl),this.setupHandlers()}disconnect(){this.websocket&&(this.websocket.onmessage=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket.close(1e3,"Client initiated disconnect"),this.websocket=null)}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("Cant send. WebSocket is not open");this.websocket.send(JSON.stringify(e))}isReady(){return this.websocket?.readyState===WebSocket.OPEN}setupHandlers(){this.websocket&&(this.websocket.onopen=()=>{this.handlers.onOpen&&this.handlers.onOpen()},this.websocket.onmessage=e=>{const t=JSON.parse(e.data);this.handlers.onMessage&&this.handlers.onMessage(t)},this.websocket.onerror=e=>{this.handlers.onError&&this.handlers.onError(e)},this.websocket.onclose=()=>{this.handlers.onClose&&this.handlers.onClose()})}}function J(e,t){return function(){return e.apply(t,arguments)}}const{toString:X}=Object.prototype,{getPrototypeOf:Z}=Object,{iterator:Y,toStringTag:ee}=Symbol,te=(ne=Object.create(null),e=>{const t=X.call(e);return ne[t]||(ne[t]=t.slice(8,-1).toLowerCase())});var ne;const ie=e=>(e=e.toLowerCase(),t=>te(t)===e),re=e=>t=>typeof t===e,{isArray:se}=Array,ae=re("undefined");function oe(e){return null!==e&&!ae(e)&&null!==e.constructor&&!ae(e.constructor)&&de(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ue=ie("ArrayBuffer"),le=re("string"),de=re("function"),he=re("number"),ce=e=>null!==e&&"object"==typeof e,pe=e=>{if("object"!==te(e))return!1;const t=Z(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||ee in e||Y in e)},fe=ie("Date"),me=ie("File"),ge=ie("Blob"),ye=ie("FileList"),we=ie("URLSearchParams"),[be,_e,$e,ve]=["ReadableStream","Request","Response","Headers"].map(ie);function xe(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),se(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(oe(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function Se(e,t){if(oe(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:n.g,ke=e=>!ae(e)&&e!==Te,Ee=(Ce="undefined"!=typeof Uint8Array&&Z(Uint8Array),e=>Ce&&e instanceof Ce);var Ce;const Ie=ie("HTMLFormElement"),Ae=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Re=ie("RegExp"),Me=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};xe(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)},Oe=ie("AsyncFunction"),ze=(Pe="function"==typeof setImmediate,Be=de(Te.postMessage),Pe?setImmediate:Be?(De=`axios@${Math.random()}`,Ue=[],Te.addEventListener("message",({source:e,data:t})=>{e===Te&&t===De&&Ue.length&&Ue.shift()()},!1),e=>{Ue.push(e),Te.postMessage(De,"*")}):e=>setTimeout(e));var Pe,Be,De,Ue;const Le="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Te):"undefined"!=typeof process&&process.nextTick||ze,Ne={isArray:se,isArrayBuffer:ue,isBuffer:oe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||de(e.append)&&("formdata"===(t=te(e))||"object"===t&&de(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ue(e.buffer),t},isString:le,isNumber:he,isBoolean:e=>!0===e||!1===e,isObject:ce,isPlainObject:pe,isEmptyObject:e=>{if(!ce(e)||oe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:be,isRequest:_e,isResponse:$e,isHeaders:ve,isUndefined:ae,isDate:fe,isFile:me,isBlob:ge,isRegExp:Re,isFunction:de,isStream:e=>ce(e)&&de(e.pipe),isURLSearchParams:we,isTypedArray:Ee,isFileList:ye,forEach:xe,merge:function e(){const{caseless:t,skipUndefined:n}=ke(this)&&this||{},i={},r=(r,s)=>{const a=t&&Se(i,s)||s;pe(i[a])&&pe(r)?i[a]=e(i[a],r):pe(r)?i[a]=e({},r):se(r)?i[a]=r.slice():n&&ae(r)||(i[a]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&xe(arguments[e],r);return i},extend:(e,t,n,{allOwnKeys:i}={})=>(xe(t,(t,i)=>{n&&de(t)?e[i]=J(t,n):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&Z(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:te,kindOfTest:ie,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(se(e))return e;let t=e.length;if(!he(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Y]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:Ie,hasOwnProperty:Ae,hasOwnProp:Ae,reduceDescriptors:Me,freezeMethods:e=>{Me(e,(t,n)=>{if(de(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];de(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach(e=>{n[e]=!0})};return se(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Se,global:Te,isContextDefined:ke,isSpecCompliantForm:function(e){return!!(e&&de(e.append)&&"FormData"===e[ee]&&e[Y])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(ce(e)){if(t.indexOf(e)>=0)return;if(oe(e))return e;if(!("toJSON"in e)){t[i]=e;const r=se(e)?[]:{};return xe(e,(e,t)=>{const s=n(e,i+1);!ae(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:Oe,isThenable:e=>e&&(ce(e)||de(e))&&de(e.then)&&de(e.catch),setImmediate:ze,asap:Le,isIterable:e=>null!=e&&de(e[Y])};function He(e,t,n,i,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}Ne.inherits(He,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ne.toJSONObject(this.config),code:this.code,status:this.status}}});const Fe=He.prototype,qe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{qe[e]={value:e}}),Object.defineProperties(He,qe),Object.defineProperty(Fe,"isAxiosError",{value:!0}),He.from=(e,t,n,i,r,s)=>{const a=Object.create(Fe);Ne.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e);const o=e&&e.message?e.message:"Error",u=null==t&&e?e.code:t;return He.call(a,o,u,n,i,r),e&&null==a.cause&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",s&&Object.assign(a,s),a};const Ve=He;function We(e){return Ne.isPlainObject(e)||Ne.isArray(e)}function je(e){return Ne.endsWith(e,"[]")?e.slice(0,-2):e}function Ge(e,t,n){return e?e.concat(t).map(function(e,t){return e=je(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Ke=Ne.toFlatObject(Ne,{},null,function(e){return/^is[A-Z]/.test(e)}),Qe=function(e,t,n){if(!Ne.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=Ne.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Ne.isUndefined(t[e])})).metaTokens,r=n.visitor||l,s=n.dots,a=n.indexes,o=(n.Blob||"undefined"!=typeof Blob&&Blob)&&Ne.isSpecCompliantForm(t);if(!Ne.isFunction(r))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(Ne.isDate(e))return e.toISOString();if(Ne.isBoolean(e))return e.toString();if(!o&&Ne.isBlob(e))throw new Ve("Blob is not supported. Use a Buffer instead.");return Ne.isArrayBuffer(e)||Ne.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,n,r){let o=e;if(e&&!r&&"object"==typeof e)if(Ne.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else if(Ne.isArray(e)&&function(e){return Ne.isArray(e)&&!e.some(We)}(e)||(Ne.isFileList(e)||Ne.endsWith(n,"[]"))&&(o=Ne.toArray(e)))return n=je(n),o.forEach(function(e,i){!Ne.isUndefined(e)&&null!==e&&t.append(!0===a?Ge([n],i,s):null===a?n:n+"[]",u(e))}),!1;return!!We(e)||(t.append(Ge(r,n,s),u(e)),!1)}const d=[],h=Object.assign(Ke,{defaultVisitor:l,convertValue:u,isVisitable:We});if(!Ne.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!Ne.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+i.join("."));d.push(n),Ne.forEach(n,function(n,s){!0===(!(Ne.isUndefined(n)||null===n)&&r.call(t,n,Ne.isString(s)?s.trim():s,i,h))&&e(n,i?i.concat(s):[s])}),d.pop()}}(e),t};function Je(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Xe(e,t){this._pairs=[],e&&Qe(e,this,t)}const Ze=Xe.prototype;Ze.append=function(e,t){this._pairs.push([e,t])},Ze.toString=function(e){const t=e?function(t){return e.call(this,t,Je)}:Je;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};const Ye=Xe;function et(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function tt(e,t,n){if(!t)return e;const i=n&&n.encode||et;Ne.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):Ne.isURLSearchParams(t)?t.toString():new Ye(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}const nt=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ne.forEach(this.handlers,function(t){null!==t&&e(t)})}},it={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ye,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},st="undefined"!=typeof window&&"undefined"!=typeof document,at="object"==typeof navigator&&navigator||void 0,ot=st&&(!at||["ReactNative","NativeScript","NS"].indexOf(at.product)<0),ut="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,lt=st&&window.location.href||"http://localhost",dt={...i,...rt},ht=function(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;return s=!s&&Ne.isArray(i)?i.length:s,o?(Ne.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a):(i[s]&&Ne.isObject(i[s])||(i[s]=[]),t(e,n,i[s],r)&&Ne.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!a)}if(Ne.isFormData(e)&&Ne.isFunction(e.entries)){const n={};return Ne.forEachEntry(e,(e,i)=>{t(function(e){return Ne.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null},ct={transitional:it,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=Ne.isObject(e);if(r&&Ne.isHTMLForm(e)&&(e=new FormData(e)),Ne.isFormData(e))return i?JSON.stringify(ht(e)):e;if(Ne.isArrayBuffer(e)||Ne.isBuffer(e)||Ne.isStream(e)||Ne.isFile(e)||Ne.isBlob(e)||Ne.isReadableStream(e))return e;if(Ne.isArrayBufferView(e))return e.buffer;if(Ne.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Qe(e,new dt.classes.URLSearchParams,{visitor:function(e,t,n,i){return dt.isNode&&Ne.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=Ne.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Qe(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e){if(Ne.isString(e))try{return(0,JSON.parse)(e),Ne.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ct.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(Ne.isResponse(e)||Ne.isReadableStream(e))return e;if(e&&Ne.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n){if("SyntaxError"===e.name)throw Ve.from(e,Ve.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dt.classes.FormData,Blob:dt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ne.forEach(["delete","get","head","post","put","patch"],e=>{ct.headers[e]={}});const pt=ct,ft=Ne.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mt=Symbol("internals");function gt(e){return e&&String(e).trim().toLowerCase()}function yt(e){return!1===e||null==e?e:Ne.isArray(e)?e.map(yt):String(e)}function wt(e,t,n,i,r){return Ne.isFunction(i)?i.call(this,t,n):(r&&(t=n),Ne.isString(t)?Ne.isString(i)?-1!==t.indexOf(i):Ne.isRegExp(i)?i.test(t):void 0:void 0)}class bt{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=gt(t);if(!r)throw new Error("header name must be a non-empty string");const s=Ne.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=yt(e))}const s=(e,t)=>Ne.forEach(e,(e,n)=>r(e,n,t));if(Ne.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Ne.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),n=e.substring(0,r).trim().toLowerCase(),i=e.substring(r+1).trim(),!n||t[n]&&ft[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)}),t})(e),t);else if(Ne.isObject(e)&&Ne.isIterable(e)){let n,i,r={};for(const t of e){if(!Ne.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?Ne.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,n);return this}get(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(Ne.isFunction(t))return t.call(this,e,n);if(Ne.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);return!(!n||void 0===this[n]||t&&!wt(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=gt(e)){const r=Ne.findKey(n,e);!r||t&&!wt(0,n[r],r,t)||(delete n[r],i=!0)}}return Ne.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!wt(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return Ne.forEach(this,(i,r)=>{const s=Ne.findKey(n,r);if(s)return t[s]=yt(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=yt(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ne.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&Ne.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[mt]=this[mt]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=gt(e);t[i]||(function(e,t){const n=Ne.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})})}(n,e),t[i]=!0)}return Ne.isArray(e)?e.forEach(i):i(e),this}}bt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ne.reduceDescriptors(bt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),Ne.freezeMethods(bt);const _t=bt;function $t(e,t){const n=this||pt,i=t||n,r=_t.from(i.headers);let s=i.data;return Ne.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function vt(e){return!(!e||!e.__CANCEL__)}function xt(e,t,n){Ve.call(this,null==e?"canceled":e,Ve.ERR_CANCELED,t,n),this.name="CanceledError"}Ne.inherits(xt,Ve,{__CANCEL__:!0});const St=xt;function Tt(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Ve("Request failed with status code "+n.status,[Ve.ERR_BAD_REQUEST,Ve.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}const kt=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const u=Date.now(),l=i[a];r||(r=u),n[s]=o,i[s]=u;let d=a,h=0;for(;d!==s;)h+=n[d++],d%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),u-r<t)return;const c=l&&u-l;return c?Math.round(1e3*h/c):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,u=r(o);i=s,e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:u||void 0,estimated:u&&a&&s<=a?(a-s)/u:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},Et=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ct=e=>(...t)=>Ne.asap(()=>e(...t)),It=dt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,dt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(dt.origin),dt.navigator&&/(msie|trident)/i.test(dt.navigator.userAgent)):()=>!0,At=dt.hasStandardBrowserEnv?{write(e,t,n,i,r,s,a){if("undefined"==typeof document)return;const o=[`${e}=${encodeURIComponent(t)}`];Ne.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),Ne.isString(i)&&o.push(`path=${i}`),Ne.isString(r)&&o.push(`domain=${r}`),!0===s&&o.push("secure"),Ne.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function Rt(e,t,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Mt=e=>e instanceof _t?{...e}:e;function Ot(e,t){t=t||{};const n={};function i(e,t,n,i){return Ne.isPlainObject(e)&&Ne.isPlainObject(t)?Ne.merge.call({caseless:i},e,t):Ne.isPlainObject(t)?Ne.merge({},t):Ne.isArray(t)?t.slice():t}function r(e,t,n,r){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!Ne.isUndefined(t))return i(void 0,t)}function a(e,t){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(n,r,s){return s in t?i(n,r):s in e?i(void 0,n):void 0}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(Mt(e),Mt(t),0,!0)};return Ne.forEach(Object.keys({...e,...t}),function(i){const s=u[i]||r,a=s(e[i],t[i],i);Ne.isUndefined(a)&&s!==o||(n[i]=a)}),n}const zt=e=>{const t=Ot({},e);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:s,headers:a,auth:o}=t;if(t.headers=a=_t.from(a),t.url=tt(Rt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&a.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),Ne.isFormData(n))if(dt.hasStandardBrowserEnv||dt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(Ne.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,n])=>{t.includes(e.toLowerCase())&&a.set(e,n)})}if(dt.hasStandardBrowserEnv&&(i&&Ne.isFunction(i)&&(i=i(t)),i||!1!==i&&It(t.url))){const e=r&&s&&At.read(s);e&&a.set(r,e)}return t},Pt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=zt(e);let r=i.data;const s=_t.from(i.headers).normalize();let a,o,u,l,d,{responseType:h,onUploadProgress:c,onDownloadProgress:p}=i;function f(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const i=_t.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Tt(function(e){t(e),f()},function(e){n(e),f()},{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(n(new Ve("Request aborted",Ve.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new Ve(i,Ve.ERR_NETWORK,e,m);r.event=t||null,n(r),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||it;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Ve(t,r.clarifyTimeoutError?Ve.ETIMEDOUT:Ve.ECONNABORTED,e,m)),m=null},void 0===r&&s.setContentType(null),"setRequestHeader"in m&&Ne.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Ne.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),h&&"json"!==h&&(m.responseType=i.responseType),p&&([u,d]=kt(p,!0),m.addEventListener("progress",u)),c&&m.upload&&([o,l]=kt(c),m.upload.addEventListener("progress",o),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(a=t=>{m&&(n(!t||t.type?new St(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===dt.protocols.indexOf(y)?n(new Ve("Unsupported protocol "+y+":",Ve.ERR_BAD_REQUEST,e)):m.send(r||null)})},Bt=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ve?t:new St(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Ve(`timeout ${t} of ms exceeded`,Ve.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>Ne.asap(a),o}},Dt=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},Ut=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}}(e))yield*Dt(n,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(e){throw o(e),e}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},{isFunction:Lt}=Ne,Nt=(({Request:e,Response:t})=>({Request:e,Response:t}))(Ne.global),{ReadableStream:Ht,TextEncoder:Ft}=Ne.global,qt=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Vt=e=>{e=Ne.merge.call({skipUndefined:!0},Nt,e);const{fetch:t,Request:n,Response:i}=e,r=t?Lt(t):"function"==typeof fetch,s=Lt(n),a=Lt(i);if(!r)return!1;const o=r&&Lt(Ht),u=r&&("function"==typeof Ft?(l=new Ft,e=>l.encode(e)):async e=>new Uint8Array(await new n(e).arrayBuffer()));var l;const d=s&&o&&qt(()=>{let e=!1;const t=new n(dt.origin,{body:new Ht,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),h=a&&o&&qt(()=>Ne.isReadableStream(new i("").body)),c={stream:h&&(e=>e.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!c[e]&&(c[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new Ve(`Response type '${e}' is not supported`,Ve.ERR_NOT_SUPPORT,n)})});return async e=>{let{url:r,method:a,data:o,signal:l,cancelToken:p,timeout:f,onDownloadProgress:m,onUploadProgress:g,responseType:y,headers:w,withCredentials:b="same-origin",fetchOptions:_}=zt(e),$=t||fetch;y=y?(y+"").toLowerCase():"text";let v=Bt([l,p&&p.toAbortSignal()],f),x=null;const S=v&&v.unsubscribe&&(()=>{v.unsubscribe()});let T;try{if(g&&d&&"get"!==a&&"head"!==a&&0!==(T=await(async(e,t)=>{const i=Ne.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(Ne.isBlob(e))return e.size;if(Ne.isSpecCompliantForm(e)){const t=new n(dt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ne.isArrayBufferView(e)||Ne.isArrayBuffer(e)?e.byteLength:(Ne.isURLSearchParams(e)&&(e+=""),Ne.isString(e)?(await u(e)).byteLength:void 0)})(t):i})(w,o))){let e,t=new n(r,{method:"POST",body:o,duplex:"half"});if(Ne.isFormData(o)&&(e=t.headers.get("content-type"))&&w.setContentType(e),t.body){const[e,n]=Et(T,kt(Ct(g)));o=Ut(t.body,65536,e,n)}}Ne.isString(b)||(b=b?"include":"omit");const t=s&&"credentials"in n.prototype,l={..._,signal:v,method:a.toUpperCase(),headers:w.normalize().toJSON(),body:o,duplex:"half",credentials:t?b:void 0};x=s&&new n(r,l);let p=await(s?$(x,_):$(r,l));const f=h&&("stream"===y||"response"===y);if(h&&(m||f&&S)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=p[t]});const t=Ne.toFiniteNumber(p.headers.get("content-length")),[n,r]=m&&Et(t,kt(Ct(m),!0))||[];p=new i(Ut(p.body,65536,n,()=>{r&&r(),S&&S()}),e)}y=y||"text";let k=await c[Ne.findKey(c,y)||"text"](p,e);return!f&&S&&S(),await new Promise((t,n)=>{Tt(t,n,{data:k,headers:_t.from(p.headers),status:p.status,statusText:p.statusText,config:e,request:x})})}catch(t){if(S&&S(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new Ve("Network Error",Ve.ERR_NETWORK,e,x),{cause:t.cause||t});throw Ve.from(t,t&&t.code,e,x)}}},Wt=new Map,jt=e=>{let t=e&&e.env||{};const{fetch:n,Request:i,Response:r}=t,s=[i,r,n];let a,o,u=s.length,l=Wt;for(;u--;)a=s[u],o=l.get(a),void 0===o&&l.set(a,o=u?new Map:Vt(t)),l=o;return o},Gt=(jt(),{http:null,xhr:Pt,fetch:{get:jt}});Ne.forEach(Gt,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const Kt=e=>`- ${e}`,Qt=e=>Ne.isFunction(e)||null===e||!1===e,Jt=function(e,t){e=Ne.isArray(e)?e:[e];const{length:n}=e;let i,r;const s={};for(let a=0;a<n;a++){let n;if(i=e[a],r=i,!Qt(i)&&(r=Gt[(n=String(i)).toLowerCase()],void 0===r))throw new Ve(`Unknown adapter '${n}'`);if(r&&(Ne.isFunction(r)||(r=r.get(t))))break;s[n||"#"+a]=r}if(!r){const e=Object.entries(s).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=n?e.length>1?"since :\n"+e.map(Kt).join("\n"):" "+Kt(e[0]):"as no adapter specified";throw new Ve("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r};function Xt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new St(null,e)}function Zt(e){return Xt(e),e.headers=_t.from(e.headers),e.data=$t.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Jt(e.adapter||pt.adapter,e)(e).then(function(t){return Xt(e),t.data=$t.call(e,e.transformResponse,t),t.headers=_t.from(t.headers),t},function(t){return vt(t)||(Xt(e),t&&t.response&&(t.response.data=$t.call(e,e.transformResponse,t.response),t.response.headers=_t.from(t.response.headers))),Promise.reject(t)})}const Yt="1.13.2",en={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{en[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const tn={};en.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Yt+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Ve(i(r," has been removed"+(t?" in "+t:"")),Ve.ERR_DEPRECATED);return t&&!tn[r]&&(tn[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},en.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const nn={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Ve("options must be an object",Ve.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new Ve("option "+s+" must be "+n,Ve.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Ve("Unknown option "+s,Ve.ERR_BAD_OPTION)}},validators:en},rn=nn.validators;class sn{constructor(e){this.defaults=e||{},this.interceptors={request:new nt,response:new nt}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+n):e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Ot(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&nn.assertOptions(n,{silentJSONParsing:rn.transitional(rn.boolean),forcedJSONParsing:rn.transitional(rn.boolean),clarifyTimeoutError:rn.transitional(rn.boolean)},!1),null!=i&&(Ne.isFunction(i)?t.paramsSerializer={serialize:i}:nn.assertOptions(i,{encode:rn.function,serialize:rn.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),nn.assertOptions(t,{baseUrl:rn.spelling("baseURL"),withXsrfToken:rn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&Ne.merge(r.common,r[t.method]);r&&Ne.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=_t.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))});const u=[];let l;this.interceptors.response.forEach(function(e){u.push(e.fulfilled,e.rejected)});let d,h=0;if(!o){const e=[Zt.bind(this),void 0];for(e.unshift(...a),e.push(...u),d=e.length,l=Promise.resolve(t);h<d;)l=l.then(e[h++],e[h++]);return l}d=a.length;let c=t;for(;h<d;){const e=a[h++],t=a[h++];try{c=e(c)}catch(e){t.call(this,e);break}}try{l=Zt.call(this,c)}catch(e){return Promise.reject(e)}for(h=0,d=u.length;h<d;)l=l.then(u[h++],u[h++]);return l}getUri(e){return tt(Rt((e=Ot(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Ne.forEach(["delete","get","head","options"],function(e){sn.prototype[e]=function(t,n){return this.request(Ot(n||{},{method:e,url:t,data:(n||{}).data}))}}),Ne.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Ot(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}sn.prototype[e]=t(),sn.prototype[e+"Form"]=t(!0)});const an=sn;class on{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{n.subscribe(e),t=e}).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e(function(e,i,r){n.reason||(n.reason=new St(e,i,r),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new on(function(t){e=t}),cancel:e}}}const un=on,ln={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ln).forEach(([e,t])=>{ln[t]=e});const dn=ln,hn=function e(t){const n=new an(t),i=J(an.prototype.request,n);return Ne.extend(i,an.prototype,n,{allOwnKeys:!0}),Ne.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Ot(t,n))},i}(pt);hn.Axios=an,hn.CanceledError=St,hn.CancelToken=un,hn.isCancel=vt,hn.VERSION=Yt,hn.toFormData=Qe,hn.AxiosError=Ve,hn.Cancel=hn.CanceledError,hn.all=function(e){return Promise.all(e)},hn.spread=function(e){return function(t){return e.apply(null,t)}},hn.isAxiosError=function(e){return Ne.isObject(e)&&!0===e.isAxiosError},hn.mergeConfig=Ot,hn.AxiosHeaders=_t,hn.formToJSON=e=>ht(Ne.isHTMLForm(e)?new FormData(e):e),hn.getAdapter=Jt,hn.HttpStatusCode=dn,hn.default=hn;const cn=hn,pn=class{static setItem(e,t){localStorage.setItem(e,t)}static setWithExpiry(e,t,n=33e5){const i={value:t,expiry:Date.now()+n};try{localStorage.setItem(e,JSON.stringify(i))}catch{}}static getWithExpiry(e){const t=localStorage.getItem(e);if(!t)return null;let n=null;try{n=JSON.parse(t)}catch(t){throw localStorage.removeItem(e),t}const i="number"==typeof n.expiry?n.expiry:0;return Date.now()>i?(localStorage.removeItem(e),null):n.value}static removeItem(e){localStorage.removeItem(e)}},fn=class{_authToken;_requestId=null;apiUrl;_apiKey;_federatedId=null;apiClient;constructor({apiUrl:e,apiKey:t,federatedId:n}){this.apiUrl=e,this._apiKey=t,this._federatedId=n,this._authToken=pn.getWithExpiry("authToken")||void 0,this.apiClient=cn.create({baseURL:this.apiUrl,headers:{Authorization:`Bearer ${this.authToken}`}}),this.setInterceptors()}async login(){if(!Boolean(pn.getWithExpiry("authToken")||this.authToken))try{await this.loginWithApiKey()}catch(e){throw console.error("Failed to authenticate with client credentials.",e),pn.removeItem("authToken"),this._authToken=void 0,e}}setInterceptors(){this.apiClient.interceptors.request.use(async e=>(e.url?.includes("/auth/login")||this.login(),e),e=>Promise.reject(e)),this.apiClient.interceptors.response.use(e=>(this.updatedRequestFromResponse(e),e),e=>(e.response&&this.updatedRequestFromResponse(e.response),Promise.reject(e))),this.apiClient.interceptors.response.use(e=>e,this.handleError.bind(this)),this.apiClient.interceptors.response.use(e=>e,e=>{if(e.response)try{return JSON.stringify(e.response.data),cn.isAxiosError(e)&&401===e.response?.status&&(pn.removeItem("authToken"),this._authToken=void 0),Promise.reject(e)}catch(e){return console.error(e),Promise.reject(e)}return Promise.reject(e)})}async verifyAuthentication(){await this.getMe()}updatedRequestFromResponse(e){return this.updateRequestId(e.headers["x-request-id"]??""),e}handleError(e){return Promise.reject(e)}get authToken(){return this._authToken}set authToken(e){e?pn.setWithExpiry("authToken",e):pn.removeItem("authToken"),this._authToken=e,this.apiClient&&(this.apiClient.defaults.headers.Authorization=`Bearer ${e}`)}get requestId(){return this._requestId}updateRequestId(e){e&&(this._requestId=e)}async loginWithApiKey(){const e=await this.apiClient.post("/auth/login",{api_key:this._apiKey,federated_id:this._federatedId});return this.authToken=e.data.access_token,this.apiClient.defaults.headers.common.Authorization=`Bearer ${this.authToken}`,this.authToken||""}async getMe(){return(await this.apiClient.get("/users/me")).data}async generateImage(e){const{provider:t,...n}=e,i=`/images/generate/${t}`;return(await this.apiClient.post(i,n)).data}async generateImageWithBria(e){return(await this.apiClient.post("/images/generate/bria",e)).data}async generateImageWithReplicate(e){return(await this.apiClient.post("/images/generate/replicate",e)).data}async getAvailableModels(){return(await this.apiClient.get("/images/models")).data}},mn={sampling_rate:48e3,mime_type:"audio/mpeg"};class gn extends u{config;wsConnection=null;_api=null;pendingRequests=new Map;constructor(e){super(new o({category:"🗣️ConversationNetwork",style:"color: #607d8b; font-weight: bold; font-size: larger"})),this.config=e,this._api=new fn({apiUrl:e.apiUrl,apiKey:e.apiKey,federatedId:e.federatedId})}async initialize(){try{await this._api.login()}catch(e){const t=e.response?.data?.error||e.message||"Authentication failed",n=e.response?.data?.traceback;n?this.logger.error("Authentication failed:",t,"\nTraceback:",n):this.logger.error("Authentication failed:",t);const i=new Error(t);throw n&&(i.traceback=n),i}}async connect(){let e=this.config.apiUrl.replace(/\/api\/?$/,"")+"/interact";this.wsConnection=new Q(e,this.getWebSocketHandlers()),this.wsConnection.connect(),await this.waitForWebSocketReady(1e4),this.logger.debug("Network connections established - Authenticating next...")}async waitForWebSocketReady(e){return new Promise((t,n)=>{if(!this.wsConnection)return void n(new Error("WebSocket connection not initialized"));if(this.wsConnection.isReady())return void t();const i=setTimeout(()=>{n(new Error(`WebSocket connection timeout after ${e}ms`))},e),r=()=>{this.wsConnection?.isReady()?(clearTimeout(i),t()):setTimeout(r,50)};r()})}getWebSocketHandlers(){return{onOpen:async()=>{try{await this.authenticate(),await this.setConfiguration(),this.emit(c),await this.interact({text:".",uid:"",kind:"interact",type:"stream"})}catch(e){const t=e?.error||String(e);this.emit(d,new Error(t))}},onMessage:async e=>{if(e.uid&&this.pendingRequests.has(e.uid)){const t=this.pendingRequests.get(e.uid);if(t)if(t.isStream)"close"===e.kind?(clearTimeout(t.timeout),t.resolve(e),this.pendingRequests.delete(e.uid)):"error"===e.kind?(this.logger.error(e.error),this.emit(d,new Error(e.error))):this.emit(l,e);else{if(clearTimeout(t.timeout),"error"===e.kind){const n=e;this.logger.error(n?.error),t.reject(n.error)}else t.resolve(e);this.pendingRequests.delete(e.uid),this.emit(l,e)}}else"interact"===e.kind?this.emit(l,e):"error"===e.kind?(this.logger.error(e.error),await this.emit(d,e.error)):this.logger.warn("Received message without a matching request UID",e)},onError:async e=>{await this.emit(d,e)},onClose:async()=>{await this.emit(h)}}}async makeRequest(e,t=5e4){return this.makeRequestInternal(e,t,!1)}async makeStreamRequest(e,t=5e4){return this.makeRequestInternal(e,t,!0)}async makeRequestInternal(e,t,n){if(!this.wsConnection?.isReady())throw new Error("WebSocket not ready");var i,r,s;e.uid=!V.randomUUID||r||i?K(i,r,s):V.randomUUID(),e.client_start_time=(new Date).toISOString();const a=new Promise((i,r)=>{const s=setTimeout(()=>{this.pendingRequests.delete(e.uid),r(new Error(`Request ${e.uid} timed out after ${t}ms`))},t);this.pendingRequests.set(e.uid,{resolve:i,reject:r,timeout:s,isStream:n})});return this.wsConnection.send(e),a}async authenticate(){const e={type:"request",kind:"authenticate",access_token:this._api.authToken,uid:"",metadata:this.config.metadata};await this.makeRequest(e)}updateConfig(e){this.config=e}async updateRemoteConfiguration(e){this.updateConfig(e),await this.setConfiguration()}async setConfiguration(){const e={type:"request",kind:"set_configuration",config:{prompt:this.config.prompt,voice_profile:this.config.voiceProfile,utilities:this.config.utilities,safety_policy:this.config.safetyPolicy},uid:""};await this.makeRequest(e)}async addAudio(e){const t={type:"request",kind:"add_audio",audio:e,uid:"",config:mn};await this.makeRequest(t)}async clearAudio(){await this.makeRequest({type:"request",kind:"clear_audio",uid:""})}async checkTurn(){await this.makeRequest({type:"request",kind:"check_turn",uid:""})}async generateImage(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImage(e)).image}}async generateImageWithBria(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithBria(e)).image}}async generateImageWithReplicate(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithReplicate(e)).image}}async getAvailableModels(){return{kind:"get_available_models",uid:"",models:(await this._api.getAvailableModels()).models}}async interact(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async interactAudio(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async disconnect(){this.wsConnection?.disconnect()}isReady(){return this.wsConnection?.isReady()||!1}async send(e){"audio"!==e.type?this.logger.warn("ConversationNetwork.send is deprecated. Use specific methods instead."):await this.addAudio(e.audio)}}class yn{mediaRecorder=null;mimeType;onAudioData;timeslice;logger=new o({category:"🎤 MediaRecorderFallback",style:a});constructor(e,t,n=100){this.mimeType=e,this.onAudioData=t,this.timeslice=n}initialize(e){this.logger.debug("Initializing MediaRecorder for audio processing"),this.mediaRecorder=new MediaRecorder(e,{mimeType:this.mimeType}),this.logger.debug("MediaRecorder created, state:",this.mediaRecorder.state),this.mediaRecorder.ondataavailable=e=>{this.logger.debug("ondataavailable called, size:",e.data.size),e.data.size>0&&e.data.arrayBuffer().then(e=>{this.onAudioData(e)})}}start(){this.mediaRecorder&&"inactive"===this.mediaRecorder.state&&(this.mediaRecorder.start(this.timeslice),this.logger.debug(`MediaRecorder started with ${this.timeslice}ms timeslice`))}stop(){this.mediaRecorder&&"inactive"!==this.mediaRecorder.state&&(this.mediaRecorder.stop(),this.logger.debug("MediaRecorder stopped"))}}const wn="audio-data",bn="error";class _n extends u{mediaStream=null;audioContext=null;workletNode=null;mediaRecorder=null;recording=!1;config;useMediaRecorder=!1;mediaRecorderFallback=null;audioBuffer=[];bufferingMode=!1;MIME_TYPE="audio/webm;codecs=opus";constructor(e={}){super(new o({category:"🎤 AudioRecorder",style:a})),this.config={sampleRate:41e3,channels:1,bitDepth:16,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,timeslice:100,...e}}async initialize(e){try{this.logger.debug("Initializing..."),await this.setupAudioContext(),await this.loadAudioWorklet(),this.mediaStream=e,this.useMediaRecorder&&(this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream)),this.logger.debug("Initialized successfully")}catch(e){throw this.logger.error("Failed to initialize",e),e}}async start(){if(this.recording)this.logger.warn("Recording already in progress");else{if(this.audioContext&&"suspended"===this.audioContext.state)try{await this.audioContext.resume(),this.logger.debug("AudioContext resumed successfully at start of recording.")}catch(e){this.logger.error("Failed to resume AudioContext:",e);const t=new Error("The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developer.chrome.com/blog/autoplay/#web_audio");throw await this.emit(bn,t),t}this.audioContext||(await this.setupAudioContext(),await this.loadAudioWorklet());try{if(this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext before starting recording..."),await this.audioContext.resume()),!this.mediaStream)throw new Error("AudioRecorder: mediaStream must be set via initialize(stream) before starting recording.");this.logger.debug("setupMediaStream complete"),await this.setupAudioProcessing(),this.logger.debug("setupAudioProcessing complete"),this.recording=!0,await this.emit("recording-started"),this.logger.debug("Audio recording started")}catch(e){throw this.logger.error("Failed to start recording",e),await this.emit(bn,e),e}}}async stop(){if(this.logger.debug("Stopping recording..."),this.recording)try{await this.cleanup(),this.recording=!1,await this.emit("recording-stopped"),this.logger.debug("Audio recording stopped")}catch(e){throw this.logger.error("Failed to stop recording",e),await this.emit(bn,e),e}else this.logger.warn("No recording in progress")}isRecording(){return this.recording}enableBufferingMode(){this.logger.debug("Buffering mode enabled"),this.bufferingMode=!0,this.audioBuffer=[]}disableBufferingMode(){this.logger.debug("Buffering mode disabled"),this.bufferingMode=!1}getBufferedAudio(){return[...this.audioBuffer]}clearBuffer(){const e=this.audioBuffer.length;this.logger.debug(`Audio buffer cleared (Was ${e})`),this.audioBuffer=[]}async resumeAudioContext(){this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, state:",this.audioContext.state))}async setupMediaRecorder(){this.logger.debug("Setting up MediaRecorder fallback..."),this.useMediaRecorder=!0}async setupAudioContext(){this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=new AudioContext({sampleRate:this.config.sampleRate,latencyHint:"interactive"}),this.logger.debug("AudioContext created, state:",this.audioContext.state)),"suspended"===this.audioContext.state&&(this.logger.debug("Resuming suspended AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, new state:",this.audioContext.state))}async loadAudioWorklet(){if(!this.audioContext)throw new Error("AudioContext not initialized");return this.setupMediaRecorder()}async setupAudioProcessing(){if(this.logger.debug("setupAudioProcessing called, useMediaRecorder:",this.useMediaRecorder),!this.audioContext||!this.mediaStream)throw new Error("AudioContext or MediaStream not initialized");if(this.useMediaRecorder)this.logger.debug("Using MediaRecorder fallback branch"),this.mediaRecorderFallback&&(this.logger.debug("Stopping existing MediaRecorderFallback before creating new one"),this.mediaRecorderFallback.stop()),this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream),this.mediaRecorderFallback.start();else{this.logger.debug("Using AudioWorklet for audio processing");const e=this.audioContext.createMediaStreamSource(this.mediaStream);this.workletNode=new AudioWorkletNode(this.audioContext,"audio-recording-processor",{processorOptions:{sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth}}),e.connect(this.workletNode),this.workletNode.port.onmessage=e=>{const{type:t,data:n}=e.data;t===wn&&this.handleAudioData(n)}}}async handleAudioData(e){let t=new Uint8Array(e),n=t.findIndex(e=>0!==e);if(-1===n)return void this.logger.warn("Skipping all-zero audio packet");n>0&&(this.logger.debug(`Trimming ${n} leading zero bytes from audio packet`),t=t.slice(n),e=t.buffer);const i=Array.from(t.slice(0,8));this.logger.debug(`Audio chunk: size=${e.byteLength}, first bytes=${i.join(",")}`),this.bufferingMode?(this.logger.debug(`Buffered audio chunk, buffer size: ${this.audioBuffer.length+1}`),this.audioBuffer.push(e)):await this.emit(wn,e)}async cleanup(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder=null),this.mediaRecorderFallback&&(this.mediaRecorderFallback.stop(),this.mediaRecorderFallback=null),this.audioBuffer=[],this.bufferingMode=!1,this.logger.debug("Audio buffer cleared during cleanup")}async preInitialize(){try{await this.setupAudioContext(),await this.loadAudioWorklet(),this.logger.debug("Pre-initialization complete")}catch(e){this.logger.error("Pre-initialization failed",e)}}isInitialized(){return null!==this.mediaStream}dispose(){try{this.logger.debug("Disposing AudioRecorder..."),this.recording&&this.stop(),this.cleanup(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.audioContext=null),this.mediaStream=null,this.removeAllListeners(),this.logger.debug("AudioRecorder disposed")}catch(e){this.logger.warn("Error while disposing AudioRecorder",e)}}}class $n extends u{capabilities;vadManager;network;recordingConfig;audioRecorder=null;isStopped=!0;mediaStream=null;isInputCompleteSent=!1;debugMode=!1;capturedAudioChunks=[];constructor(e,t,n,i){super(new o({category:"🎩 UserInputManager",style:"color: #2196f3; font-weight: bold; font-size: larger"})),this.capabilities=e,this.vadManager=t,this.network=n,this.recordingConfig=i,this.setupListeners(),this.capabilities.audio&&(this.audioRecorder=new _n(i),this.setupRecorderListeners())}async initialize(e){await this.reinitializeAudio(e)}async reinitializeAudio(e){if(this.capabilities.audio){if(e&&(this.mediaStream=e),!this.mediaStream){const e={echoCancellation:this.recordingConfig?.echoCancellation,noiseSuppression:this.recordingConfig?.noiseSuppression,autoGainControl:this.recordingConfig?.autoGainControl,sampleRate:this.recordingConfig?.sampleRate,channelCount:this.recordingConfig?.channels};Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:e})}await this.vadManager.initialize(this.mediaStream),await(this.audioRecorder?.initialize(this.mediaStream))}}async start(e=!1){if(this.isStopped){this.isStopped=!1;try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.debugMode&&(this.capturedAudioChunks=[],this.logger.debug("Cleared captured audio chunks for new interaction")),this.capabilities.audio&&(e?this.logger.debug("Skipping VAD startup to reduce CPU contention during playback"):this.vadManager.startAnalysis(),await this.startRecording())}}startVAD(){this.capabilities.audio&&!this.isStopped&&(this.logger.debug("Starting VAD analysis"),this.vadManager.startAnalysis())}async stop(){return!this.isStopped&&(this.logger.debug("Stopping User Input..."),this.isStopped=!0,this.capabilities.audio&&(this.vadManager.stopAnalysis(),await this.stopRecording()),!0)}async updateCapabilities(e){this.capabilities=e,this.logger.debug("Input capabilities updated",this.capabilities),this.capabilities.audio&&!this.audioRecorder?(this.audioRecorder=new _n(this.recordingConfig),this.setupRecorderListeners(),await this.reinitializeAudio()):!this.capabilities.audio&&this.audioRecorder&&(this.vadManager.stopAnalysis(),await this.audioRecorder.stop(),this.audioRecorder=null,this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null))}async stopRecording(){this.capabilities.audio&&this.audioRecorder?.isRecording()&&await this.audioRecorder.stop()}async startRecording(){this.capabilities.audio&&this.audioRecorder?(this.audioRecorder.isInitialized()||(this.logger.warn("AudioRecorder not initialized, reinitializing..."),await this.reinitializeAudio()),await this.audioRecorder.start()):this.logger.info("Will not start recording, audio capabilities are not enabled or audio recorder is not initialized")}isRecording(){return this.capabilities.audio&&(this.audioRecorder?.isRecording()||!1)}enableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.enableBufferingMode()}disableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.disableBufferingMode()}getBufferedAudio(){return this.audioRecorder?.getBufferedAudio()||[]}clearAudioBuffer(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.clearBuffer()}async flushBufferedAudio(){this.disableAudioBuffering();const e=this.getBufferedAudio();if(this.clearAudioBuffer(),e.length>0){this.logger.debug(`Flushing ${e.length} buffered audio chunks`);for(const t of e)await this.sendAudio(t)}}async sendAudio(e){if(this.isStopped)return;this.logger.debug("sendAudio called, size:",e.byteLength),this.debugMode&&(this.capturedAudioChunks.push(e),this.logger.debug(`Captured audio chunk for debug (${this.capturedAudioChunks.length} total chunks)`));const t=this.arrayBufferToBase64(e);await this.network.addAudio(t)}arrayBufferToBase64(e){let t="";const n=new Uint8Array(e),i=n.byteLength;for(let e=0;e<i;e++)t+=String.fromCharCode(n[e]);return btoa(t)}async interact(e){await this.network.interact(e)}async sendInputComplete(){this.isStopped||this.isInputCompleteSent||(this.isInputCompleteSent=!0,await this.emit(H,{type:"input_complete"}))}reset(){this.isInputCompleteSent=!1,this.debugMode&&this.capturedAudioChunks.length>0&&(this.logger.debug(`Clearing ${this.capturedAudioChunks.length} captured audio chunks on reset`),this.capturedAudioChunks=[])}dispose(){try{this.logger.debug("Disposing UserInputManager..."),this.isStopped=!0,this.vadManager&&(this.vadManager.stopAnalysis(),"function"==typeof this.vadManager.dispose&&this.vadManager.dispose()),this.capabilities.audio&&this.audioRecorder?.isRecording()&&this.audioRecorder.stop(),this.audioRecorder&&"function"==typeof this.audioRecorder.dispose&&this.audioRecorder.dispose(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null),this.removeAllListeners(),this.logger.debug("UserInputManager disposed")}catch(e){this.logger.warn("Error while disposing UserInputManager",e)}}setupListeners(){this.capabilities.audio&&(this.vadManager.on("voiceActivity",async e=>{e&&!this.isStopped&&(e.isSpeaking?await this.emit(F):await this.emit(q))}),this.vadManager.on("silence",async()=>{await this.sendInputComplete(),await this.network.checkTurn()}))}setupRecorderListeners(){this.audioRecorder&&this.audioRecorder.on(wn,e=>{this.sendAudio(e).catch(e=>{this.logger.error("Failed to send audio chunk",e)})})}async resumeAudioContext(){this.capabilities.audio&&this.audioRecorder&&await this.audioRecorder.resumeAudioContext()}enableDebugMode(){this.debugMode=!0,this.capturedAudioChunks=[],this.logger.info("Debug mode enabled - audio chunks will be captured")}disableDebugMode(){this.debugMode=!1,this.logger.info("Debug mode disabled")}clearCapturedAudio(){this.capturedAudioChunks=[],this.logger.info("Captured audio chunks cleared")}downloadCapturedAudio(e="captured-audio.webm"){if(0===this.capturedAudioChunks.length)return void this.logger.warn("No audio chunks captured to download");this.logger.info(`Downloading ${this.capturedAudioChunks.length} captured audio chunks as ${e}`);const t=new Blob(this.capturedAudioChunks,{type:"audio/webm;codecs=opus"}),n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n),this.logger.info("Download completed")}getCapturedAudioInfo(){const e=this.capturedAudioChunks.reduce((e,t)=>e+t.byteLength,0);return{chunkCount:this.capturedAudioChunks.length,totalSize:e}}}class vn{static DEFAULT_START_COMMAND="[start conversation]";static DEFAULT_PAUSE_RESUME_COMMAND="[resume after short pause]";static DEFAULT_LONG_PAUSE_RESUME_COMMAND="[resume after long break]";static DEFAULT_ERROR_RESUME_COMMAND="[resume after error]";startCommand=vn.DEFAULT_START_COMMAND;pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND;longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND;errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND;set(e,t,n,i){this.startCommand=e??vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=t??vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=n??vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=i??vn.DEFAULT_ERROR_RESUME_COMMAND}setDefault(){this.startCommand=vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND}}class xn{deps;static DEFAULT_MAX_RETRY_COUNT=3;currentRetryCount=0;isRetrying=!1;maxRetryCount;constructor(e){this.deps=e,this.maxRetryCount=e.maxRetryCount??xn.DEFAULT_MAX_RETRY_COUNT}async attemptRecovery(e){if(this.deps.logger.info("Attempting silent recovery for error type: "+e),!["network_timeout","network_error","server_error"].includes(e))return!1;if(!this.deps.isConnected())return this.deps.logger.info("Network is not connected, skipping retry"),!1;if(this.currentRetryCount>=this.maxRetryCount)return!1;if(this.isRetrying)return!1;this.currentRetryCount++,this.isRetrying=!0,this.deps.logger.info(`Attempting silent retry ${this.currentRetryCount}/${this.maxRetryCount} with error resume command`);try{return await this.deps.sendText(this.deps.conversationCommands.errorResumeCommand),this.isRetrying=!1,!0}catch(t){return this.deps.logger.error(`Retry attempt ${this.currentRetryCount} failed`,t),this.isRetrying=!1,this.currentRetryCount<this.maxRetryCount&&await this.attemptRecovery(e)}}resetRetryCount(){this.currentRetryCount=0,this.isRetrying=!1}getCurrentRetryCount(){return this.currentRetryCount}}const Sn={StateChange:"stateChange"};class Tn extends u{state="idle";network;vadManager;userInputManager;playbackManager;config;interactionCompletePending=!1;mediaStream=null;isTextOnly=!1;isDisposed=!1;isTransitioning=!1;pausedFromState=null;errorRetryHandler;isSimulateErrorsDebugMode=!1;conversationCommands=new vn;constructor(e){const t=new o({category:"🧞 ConversationManager",style:s});super(t),this.setConfiguration(e);const n={...e,...e.apiKey&&{apiKey:e.apiKey.slice(0,4)+"..."},...e.federatedId&&{federatedId:e.federatedId.slice(0,4)+"..."}};t.info("Initializing with config",n),this.network=new gn(this.config),this.vadManager=new N,this.userInputManager=new $n(this.config.inputCapabilities,this.vadManager,this.network,e.recordingConfig),this.playbackManager=new D(this.config.capabilities),this.playbackManager.wireVADToAvatar(this),this.playbackManager.wireConversationStateToAvatar(this),this.setupEventListeners(),this.errorRetryHandler=new xn({logger:this.logger,conversationCommands:this.conversationCommands,sendText:e=>this.sendText(e),isConnected:()=>this.isConnected(),maxRetryCount:3}),this.setState("uninitialized")}async setConfiguration(e){if(this.config={...e,capabilities:e.capabilities||{audio:!0,viseme:!0,subtitles:!0,avatar:!0},inputCapabilities:e.inputCapabilities||{audio:!0,text:!0},hooks:{...this.config?.hooks||{},...e.hooks},onInputUtilities:e.onInputUtilities??this.config?.onInputUtilities,onInputNonBlockingUtilities:e.onInputNonBlockingUtilities??this.config?.onInputNonBlockingUtilities,onOutputUtilities:e.onOutputUtilities??this.config?.onOutputUtilities},this.network&&(this.network.updateConfig(this.config),this.network.isReady())){this.logger.debug("Updating remote configuration");try{await this.network.updateRemoteConfiguration(this.config),this.logger.debug("Remote configuration updated successfully")}catch(e){this.logger.error("Failed to update remote configuration",e)}}}async initialize(){try{if(this.logger.debug("Initializing..."),this.setState("initializing"),await this.network.initialize(),await this.playbackManager.initialize(),this.config.inputCapabilities?.audio&&!this.mediaStream){const e=this.config.recordingConfig,t={echoCancellation:e?.echoCancellation,noiseSuppression:e?.noiseSuppression,autoGainControl:e?.autoGainControl,sampleRate:e?.sampleRate,channelCount:e?.channels};Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:t})}await this.userInputManager.initialize(this.mediaStream??void 0),await this.network.connect(),this.logger.debug("Initialized successfully"),this.setState("waiting")}catch(e){this.handleError("server_error",e)}}async startListening(){if("idle"!==this.state)throw new Error(`Cannot start listening from state: ${this.state}`);try{await this.userInputManager.start(),this.setState("listening")}catch(e){this.handleError("mic_denied",e)}}async stopListening(){this.logger.debug("stopListening called from state:",this.state),await this.userInputManager.stop()||this.setState("waiting")}async sendText(e){return this.interact({text:e,kind:"interact",type:"stream",uid:"",language_code:this.config.languageCode})}async generateImage(e){return this.network.generateImage(e)}async generateImageWithBria(e){return this.network.generateImageWithBria(e)}async generateImageWithReplicate(e){return this.network.generateImageWithReplicate(e)}async getAvailableModels(){return this.network.getAvailableModels()}async interact(e){if(!this.network.isReady()){const e="Network is not ready, cannot send text. probably disconnected";return this.logger.error(e),void await this.handleError("network_timeout",new Error(e))}if("idle"===this.state||"listening"===this.state||"processing_complete"===this.state||"error"===this.state)try{if(this.playbackManager.reset(),this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.setState("waiting"),await this.userInputManager.interact(e)}catch(e){this.logger.error("Error sending text message",e),await this.handleError("network_timeout",e)}}async interrupt(){this.playbackManager.pause(),await this.setState("interrupted")}async pause(){if(this.isTransitioning)this.logger.debug("Pause ignored: transition already in progress");else if("playing"===this.state||"processing_complete"===this.state||"listening"===this.state||"userSpeaking"===this.state){this.isTransitioning=!0;try{if(this.pausedFromState=this.state,"listening"===this.state||"userSpeaking"===this.state){this.logger.debug("Pausing from listening/speaking state, stopping input and clearing audio"),await this.userInputManager.stop(),this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio()}catch(e){this.logger.warn("Failed to clear server audio buffer on pause",e)}}else this.playbackManager.pause();await this.setState("paused")}finally{this.isTransitioning=!1}}else this.logger.warn(`Cannot pause from state: ${this.state}`)}async resume(){if(this.isTransitioning)this.logger.debug("Resume ignored: transition already in progress");else if("paused"===this.state||"processing_complete"===this.state){this.isTransitioning=!0;try{const e=this.playbackManager.getRemainingAudioSeconds()>0,t="listening"===this.pausedFromState||"userSpeaking"===this.pausedFromState;if(e){this.logger.debug("Resuming playback with buffered audio");try{await this.playbackManager.resume(),await this.setState("playing")}catch(e){this.logger.error("Failed to resume playback, falling back to listening",e),await this.userInputManager.start(),await this.setState("listening")}}else if(t){this.logger.debug("Resuming from listening pause, restarting recording");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to restart recording after pause",e),await this.handleError("mic_denied",e)}}else this.logger.debug("No buffered audio to resume, going to listening state"),this.interactionCompletePending?(this.interactionCompletePending=!1,await this.handleInteractionComplete()):await this.setState("listening")}finally{this.pausedFromState=null,this.isTransitioning=!1}}else this.logger.warn(`Cannot resume from state: ${this.state}`)}async forceInputComplete(){"userSpeaking"===this.state||"listening"===this.state?await this.userInputManager.sendInputComplete():this.logger.warn(`Cannot force input complete from state: ${this.state}`)}async stop(){await this.userInputManager.stop(),this.playbackManager.pause(),await this.network.disconnect(),await this.setState("idle")}async dispose(){if(this.isDisposed)this.logger.warn("ConversationManager already disposed");else{this.logger.debug("Disposing ConversationManager..."),this.isDisposed=!0,this.userInputManager?.removeAllListeners(),this.playbackManager?.removeAllListeners(),this.network?.removeAllListeners(),this.state="idle";try{this.userInputManager&&"function"==typeof this.userInputManager.dispose?this.userInputManager.dispose():(await this.userInputManager.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null)),this.playbackManager&&"function"==typeof this.playbackManager.dispose&&this.playbackManager.dispose(),await this.network.disconnect(),this.removeAllListeners(),this.logger.debug("ConversationManager disposed successfully")}catch(e){this.logger.warn("Error while disposing ConversationManager",e)}}}async setState(e){if(this.isDisposed)return;if(this.state===e)return;const t=this.state;this.state=e,this.config.hooks.onStateChange?.(e),await this.emit(Sn.StateChange,{oldState:t,newState:e}),this.logger.debug(`State transition: ${t} -> ${e}`)}setupEventListeners(){this.userInputManager.on(H,async e=>{await this.network.send(e),"input_complete"===e.type&&await this.setState("waiting")}),this.playbackManager.on(M,e=>{this.config.hooks.onSubtitleHighlight?.(e)}),this.playbackManager.on(O,e=>{this.config.hooks.onSubtitleChange?.(e)}),this.playbackManager.on(z,e=>{this.config.hooks.onImageChange?.(e)}),this.playbackManager.on(B,e=>{this.config.hooks.onAvatarAnimationChanged?.(e)}),this.userInputManager.on(F,async()=>{await this.setState("userSpeaking")}),this.userInputManager.on(q,async()=>{await this.setState("listening")}),this.network.on(c,async()=>{this.config.hooks.onNetworkStatusChange?.(!0)}),this.network.on(h,async()=>{this.config.hooks.onNetworkStatusChange?.(!1)}),this.network.on(l,async e=>{if("interact"===e.kind&&"text"===e.event&&this.config.hooks.onTextMessage?.(e),"data"===e.event&&this.config.hooks.onDataMessage?.(e),"interact"===e.kind&&"safety_policy"===e.event&&this.config.hooks.onSafetyEvent?.(e),"check_turn"===e.kind&&!1===e.is_user_still_speaking){if(this.logger.debug(`check_turn handler: state is ${this.state}`),"playing"===this.state||"paused"===this.state)return void this.logger.debug("check_turn received while playing / paused, ignoring.");await this.stopListening();try{if(this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.network.interactAudio({uid:"",kind:"interact",type:"stream",on_input_non_blocking:this.config.onInputNonBlockingUtilities,on_input:this.config.onInputUtilities,on_output:this.config.onOutputUtilities,language_code:this.config.languageCode})}catch(e){this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.logger.error("Error in interactAudio",e),await this.handleError("network_timeout",e)}}"interact"===e.kind&&"interaction_complete"===e.event&&(this.errorRetryHandler.resetRetryCount(),"playing"===this.state||"paused"===this.state?(this.logger.debug("Interaction complete received while playing / paused, deferring."),this.interactionCompletePending=!0,await this.setState("processing_complete")):await this.handleInteractionComplete()),"interaction_error"===e.type&&this.handleError("server_error",new Error(e.error||"Unknown server interaction error")),"string"===e.type&&this.config.hooks.onStringMessage?.(e),this.playbackManager.handleMessage(e)}),this.network.on(d,async e=>{this.handleError("network_error",e)}),this.playbackManager.on(R,async e=>{this.handleError("decode_error",e)}),this.playbackManager.on(A,async()=>{await this.setState("playing")}),this.playbackManager.on(P,async()=>{if(this.interactionCompletePending)this.logger.debug("Playback finished, processing deferred interaction complete."),this.interactionCompletePending=!1,await this.handleInteractionComplete();else if("playing"===this.state){this.logger.debug("Playback finished, starting recording now (no overlap)"),this.userInputManager.reset();try{await this.userInputManager.start(),await this.setState("listening"),this.logger.debug("Recording started successfully after playback")}catch(e){this.logger.error("Failed to start recording after playback",e),await this.setState("idle")}}})}async handleError(e,t){await this.setState("error"),this.logger.error("handleError called with type: "+e+" and error: "+t.message);let n=!1;try{n=await this.errorRetryHandler.attemptRecovery(e)}catch(e){this.logger.error("Error during recovery attempt",e),n=!1}if(n)return void this.logger.debug("Error recovery succeeded, not raising error");const i={type:e,message:t.message,originalError:t};this.config.hooks.onError?.(i),this.logger.error(`Conversation error: ${e}`,t)}async handleInteractionComplete(){this.logger.debug("Interaction complete received"),this.playbackManager.resetAboutToComplete();try{if(this.userInputManager.reset(),this.userInputManager.isRecording())await this.setState("listening");else{this.logger.debug("Starting recording after interaction complete");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to start recording",e),await this.setState("idle")}}}catch(e){this.logger.error("Failed to handle interaction complete",e),await this.handleError("network_timeout",e)}}async toggleTextOnlyInput(e){this.isTextOnly=e,await this.updateInputCapabilities()}isConnected(){return this.network.isReady()}enableAudioDebugMode(){this.userInputManager.enableDebugMode(),this.logger.info("Audio debug mode enabled")}disableAudioDebugMode(){this.userInputManager.disableDebugMode(),this.logger.info("Audio debug mode disabled")}downloadCapturedAudio(e){this.userInputManager.downloadCapturedAudio(e)}clearCapturedAudio(){this.userInputManager.clearCapturedAudio()}getCapturedAudioInfo(){return this.userInputManager.getCapturedAudioInfo()}async updateInputCapabilities(){this.logger.debug(`Updating input capabilities, textOnly: ${this.isTextOnly}`),this.config.inputCapabilities={...this.config.inputCapabilities,audio:!this.isTextOnly,text:this.isTextOnly},await this.userInputManager.updateCapabilities(this.config.inputCapabilities),this.isTextOnly?await this.userInputManager.stopRecording():"idle"===this.state&&await this.startListening()}}export{S as AudioPlayer,vn as ConversationCommands,Tn as ConversationManager};
184
+ ½ÇaztŸÅò¬¼Åâ`});var S={a:x};this.setModule=t=>{e.setModule(v,t)},this.getModule=()=>e.getModule(v),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,S)).then(e=>{const r=e.exports;var s;!function(e){m=e.m,g=e.n,y=e.p,w=e.q,b=e.r,_=e.s,$=e.t}(r),s=(i=r.k).buffer,new Int8Array(s),new Int16Array(s),t=new Uint8Array(s),new Uint16Array(s),new Int32Array(s),n=new Uint32Array(s),new Float32Array(s),new Float64Array(s),new BigInt64Array(s),new BigUint64Array(s),function(e){e.l()}(r),a()}),this.ready=new Promise(e=>{a=e}).then(()=>{this.HEAP=i.buffer,this.malloc=m,this.free=g,this.mpeg_decoder_feed=w,this.mpeg_decoder_read=b,this.mpeg_frame_decoder_create=y,this.mpeg_frame_decoder_destroy=_}),this)}function x(e={}){return this._init=()=>(new this._WASMAudioDecoderCommon).instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._sampleRate=0,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputSize,Float32Array);const n=this._common.allocateTypedArray(1,Uint32Array);this._samplesDecodedPtr=this._common.allocateTypedArray(1,Uint32Array),this._sampleRatePtr=this._common.allocateTypedArray(1,Uint32Array),this._errorStringPtr=this._common.allocateTypedArray(1,Uint32Array);const i=this._common.wasm.mpeg_frame_decoder_create(n.ptr,!1===e.enableGapless?0:1);if(i)throw Error(this._getErrorMessage(i));this._decoder=n.buf[0]}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this._getErrorMessage=e=>e+" "+this._common.codeToString(this._errorStringPtr.buf[0]),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.mpeg_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder),this._common.free()},this.decode=e=>{let t=[],n=[],i=0;if(!(e instanceof Uint8Array))throw Error("Data to decode must be Uint8Array. Instead got "+typeof e);e:for(let r=0,s=0;r<e.length;r+=s){const a=e.subarray(r,this._input.len+r);s=a.length,this._inputBytes+=s,this._input.buf.set(a);let o=this._common.wasm.mpeg_decoder_feed(this._decoder,this._input.ptr,s);if(-10!==o)for(;;){this._samplesDecodedPtr.buf[0]=0,o=this._common.wasm.mpeg_decoder_read(this._decoder,this._output.ptr,this._output.len,this._samplesDecodedPtr.ptr,this._sampleRatePtr.ptr,this._errorStringPtr.ptr);const e=this._samplesDecodedPtr.buf[0];if(this._outputSamples+=e,e&&(i+=e,t.push([this._output.buf.slice(0,e),this._output.buf.slice(e,2*e)])),-11!=o){if(-10===o)continue e;if(o){const e=this._getErrorMessage(o);console.error("mpg123-decoder: "+e),this._common.addError(n,e,0,this._frameNumber,this._inputBytes,this._outputSamples)}}}}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this.decodeFrame=e=>{const t=this.decode(e);return this._frameNumber++,t},this.decodeFrames=e=>{let t=[],n=[],i=0,r=0;for(;r<e.length;){const s=this.decodeFrame(e[r++]);t.push(s.channelData),n=n.concat(s.errors),i+=s.samplesDecoded}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this._isWebWorker=x.isWebWorker,this._WASMAudioDecoderCommon=x.WASMAudioDecoderCommon||$,this._EmscriptenWASM=x.EmscriptenWASM||v,this._module=x.module,this._inputSize=65536,this._outputSize=92448,this._ready=this._init(),this}class S extends u{MIN_CHUNKS_TO_PROCESS=2;FLUSH_DELAY_MS=450;audioContext;currentSource=null;playbackQueue=[];mp3Decoder=null;scheduledPlayTime=0;playbackStartTime=0;chunkQueue=[];isProcessingQueue=!1;frameExtractor=new g;totalFramesDecoded=0;totalFramesFailed=0;totalFramesExtracted=0;isPlayingState=!1;isPausedState=!1;stopped=!1;frameBuffer=[];chunkAccumulator=[];flushTimeout=null;isAudioComplete=!1;timing;isScheduling=!1;allAudioPlayed=!1;constructor(){super(new o({category:"🎵 AudioPlayer",style:"color: #4caf50; font-weight: bold; font-size: larger"})),this.audioContext=new AudioContext,this.timing=new w(()=>this.getCurrentTime(),()=>this.getQueueLength(),()=>this.getRemainingAudioSeconds(),1e3),this.setupTimingListeners()}setupTimingListeners(){this.timing.on("about-to-complete",async()=>{await this.emit(p.AboutToComplete)})}async initialize(){this.audioContext||(this.audioContext=new AudioContext,this.logger.debug("AudioContext created by user gesture")),"suspended"===this.audioContext.state&&(this.audioContext.resume(),this.logger.debug("AudioContext resumed by user gesture")),this.mp3Decoder||(this.logger.debug("Initializing MP3 decoder..."),this.mp3Decoder=new x,await this.mp3Decoder.ready,this.logger.debug("MP3 decoder ready")),this.resetState()}resetState(){this.currentSource&&(this.currentSource.onended=null,this.currentSource.stop(),this.currentSource=null),this.playbackQueue=[],this.scheduledPlayTime=0,this.playbackStartTime=0,this.chunkQueue=[],this.isProcessingQueue=!1,this.frameExtractor=new g,this.isPlayingState=!1,this.isPausedState=!1,this.stopped=!1,this.frameBuffer=[],this.chunkAccumulator=[],this.isAudioComplete=!1,this.totalFramesDecoded=0,this.totalFramesFailed=0,this.totalFramesExtracted=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.reset(),this.allAudioPlayed=!1}reset(){this.resetState()}enqueue(e){this.logger.debug("Enqueue: received chunk"),this.allAudioPlayed=!1,this.chunkQueue.push({base64String:e}),this.processChunkQueue(),this.isAudioComplete||(this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(()=>{this.logger.debug("auto-flush timer fired"),this.flush()},this.FLUSH_DELAY_MS))}markComplete(){this.logger.debug("markComplete: no more audio will be added"),this.isAudioComplete=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.onAudioComplete(),this.flush();const e=this.frameExtractor.extractRemainingFrames();e.length>0&&(this.logger.debug("markComplete: Found additional frames after flush",{count:e.length}),this.totalFramesExtracted+=e.length,this.decodeAudioFrames(e).then(t=>{if(t){this.totalFramesDecoded+=e.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(t),this.emit(p.Enqueued,{duration:t.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}).catch(t=>{this.totalFramesFailed+=e.length,this.logger.error("Failed to decode final remaining frames after markComplete",t)}));const t=this.frameExtractor.getRemainingBufferSize();t>0&&this.logger.warn("markComplete: Extractor buffer still has data after final extraction",{remainingBytes:t}),this.allAudioPlayed&&(this.logger.debug("markComplete: All audio was already played, emitting Finished."),this.isPlayingState=!1,this.emit(p.Finished))}async processChunkQueue(){if(!this.isProcessingQueue){this.isProcessingQueue=!0;try{for(;this.chunkQueue.length>0;){const{base64String:e}=this.chunkQueue.shift();if(this.chunkAccumulator.push(e),this.chunkAccumulator.length>=this.MIN_CHUNKS_TO_PROCESS){const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e)}}}finally{this.isProcessingQueue=!1}}}decodeBase64ToUint8Array(e){const t="undefined"!=typeof atob?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}combineArrays(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async decodeAudioFrames(e){if(0===e.length)return null;if(!this.mp3Decoder)throw new Error("MP3 decoder not initialized. Call initialize() first.");const t=[];let n=0,i=0,r=0,s=0;for(let a=0;a<e.length;a++){const o=e[a];if(o.length<2||255!==o[0]||224&~o[1])this.logger.warn(`Frame ${a} doesn't start with valid sync word, skipping`,{firstBytes:Array.from(o.slice(0,4)),frameLength:o.length}),s++;else try{const e=this.mp3Decoder.decodeFrame(o);if(e.errors&&e.errors.length>0&&this.logger.warn(`Frame ${a} decoded with errors`,{errors:e.errors.map(e=>e.message||String(e)),frameLength:o.length}),0===e.samplesDecoded){this.logger.warn(`Frame ${a} decoded but produced 0 samples`,{frameLength:o.length,errors:e.errors?.map(e=>e.message||String(e))}),s++;continue}if(0===n?n=e.sampleRate:e.sampleRate!==n&&this.logger.warn(`Frame ${a} has different sample rate: ${e.sampleRate} vs ${n}`),0===t.length)for(let n=0;n<e.channelData.length;n++)t.push([]);for(let n=0;n<e.channelData.length;n++)n<t.length&&t[n].push(e.channelData[n]);i+=e.samplesDecoded,r++}catch(e){this.logger.error(`Failed to decode frame ${a}`,{error:e instanceof Error?e.message:String(e),frameLength:o.length,firstBytes:Array.from(o.slice(0,4))}),s++}}if(0===r)return this.logger.error("All frames failed to decode",{totalFrames:e.length}),null;s>0&&this.logger.warn("Some frames failed to decode",{successful:r,failed:s,total:e.length});const a=[];for(let e=0;e<t.length;e++){const n=new Float32Array(i);let r=0;for(const i of t[e])n.set(i,r),r+=i.length;a.push(n)}const o=this.audioContext.createBuffer(a.length,i,n);for(let e=0;e<a.length;e++)o.getChannelData(e).set(a[e]);return this.logger.debug("Decoded frames",{successful:r,failed:s,totalSamples:i,sampleRate:n,duration:o.duration.toFixed(3)}),o}async play(){this.isPlayingState||0===this.playbackQueue.length?this.logger.debug("Play called but already playing or queue is empty."):(this.isPlayingState=!0,this.stopped=!1,this.isPausedState=!1,this.isPausedState?this.scheduledPlayTime=this.audioContext.currentTime:(this.scheduledPlayTime=this.audioContext.currentTime,this.playbackStartTime=this.audioContext.currentTime),this.logger.debug(`Playback starting. Start time: ${this.playbackStartTime}`),this.schedulePlayback(),await this.emit(p.Playing))}schedulePlayback(){if(this.isScheduling||0===this.playbackQueue.length||this.stopped)return;this.isScheduling=!0,this.currentSource&&(this.currentSource.onended=null);let e=null;for(;this.playbackQueue.length>0;){const t=this.playbackQueue.shift(),n=this.audioContext.createBufferSource();n.buffer=t,n.connect(this.audioContext.destination),this.scheduledPlayTime<this.audioContext.currentTime&&(this.logger.debug(`Adjusting scheduledPlayTime from ${this.scheduledPlayTime} to current time ${this.audioContext.currentTime}`),this.scheduledPlayTime=this.audioContext.currentTime),this.logger.debug(`Scheduling buffer of duration ${t.duration}s to start at ${this.scheduledPlayTime} (context time: ${this.audioContext.currentTime})`),n.start(this.scheduledPlayTime),this.scheduledPlayTime+=t.duration,e=n}e&&(this.currentSource=e,e.onended=()=>{this.logger.debug(`Buffer finished playing. Context time: ${this.audioContext.currentTime}, isPaused: ${this.isPausedState}, stopped: ${this.stopped}`),this.stopped||this.isPausedState||(this.playbackQueue.length>0?(this.logger.debug("More buffers in queue, scheduling next batch."),this.schedulePlayback()):this.isAudioComplete?(this.logger.debug("Last scheduled audio buffer finished and audio is complete."),this.isPlayingState=!1,this.emit(p.Finished)):(this.logger.debug("All scheduled audio has been played, but not marked as complete yet."),this.allAudioPlayed=!0))}),this.isScheduling=!1}async pause(){this.currentSource&&this.isPlayingState&&(this.isPausedState=!0,this.isPlayingState=!1,this.audioContext.suspend(),await this.emit(p.Paused))}async resume(){this.isPausedState&&(this.logger.debug("Resume called, resuming playback."),this.isPausedState=!1,this.isPlayingState=!0,this.audioContext.resume(),this.schedulePlayback(),await this.emit(p.Playing))}async stop(){this.stopped=!0,this.resetState(),await this.emit(p.Stopped)}getCurrentTime(){return this.isPlayingState?1e3*(this.audioContext.currentTime-this.playbackStartTime):0}getQueueLength(){return this.playbackQueue.length}getRemainingAudioSeconds(){const e=this.playbackQueue.reduce((e,t)=>e+t.duration,0);let t=0;return(this.isPlayingState||this.isPausedState)&&this.scheduledPlayTime>0&&(t=Math.max(0,this.scheduledPlayTime-this.audioContext.currentTime)),e+t}async decodeAndEnqueueChunks(e){if(0===e.length)return void this.logger.debug("decodeAndEnqueueChunks: no chunks to decode");let t=[];for(const n of e){const e=this.decodeBase64ToUint8Array(n),{frames:i,remainingData:r}=this.frameExtractor.feedAndExtractCompleteFrames(e);t=t.concat(i),this.totalFramesExtracted+=i.length,r.length>0&&this.logger.debug("Chunk ended with incomplete frame",{remainingBytes:r.length,framesExtracted:i.length})}if(this.logger.debug("decodeAndEnqueueChunks: total frames to decode",t.length),t.length>0){const e=t.map(e=>e.length).reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});this.logger.debug("Frame sizes distribution",e);try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.logger.debug("decodeAndEnqueueChunks: enqueued audioBuffer, duration",e.duration,"frames decoded",t.length),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode audio frames",e),this.logger.error("Lost frames",{count:t.length,sizes:t.map(e=>e.length)})}}else this.logger.debug("decodeAndEnqueueChunks: no frames to decode")}async flush(){this.logger.debug("Flushing",{chunks:this.chunkAccumulator.length});const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e);const t=this.frameExtractor.extractRemainingFrames();if(t.length>0){this.logger.debug("Flush: Found complete frames in extractor buffer",{count:t.length}),this.totalFramesExtracted+=t.length;try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode remaining frames after flush",e)}}}resetAboutToComplete(){this.timing.reset()}getFrameStats(){return{totalFramesExtracted:this.totalFramesExtracted,totalFramesDecoded:this.totalFramesDecoded,totalFramesFailed:this.totalFramesFailed,extractorRemainingBufferSize:this.frameExtractor.getRemainingBufferSize()}}dispose(){if(this.logger.debug("Disposing AudioPlayer..."),this.stopped=!0,this.isPlayingState=!1,this.isPausedState=!1,this.currentSource){this.currentSource.onended=null;try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing&&this.timing.reset(),this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.mp3Decoder=null,this.resetState(),this.removeAllListeners(),this.logger.debug("AudioPlayer disposed")}destroy(){this.dispose()}}const T="wordChange",k="subtitleChange";class E extends u{getCurrentTime;subtitleQueue=[];rafId=null;isPlaying=!1;cumulativeOffset=0;tickDebugLast=0;state={currentLine:null,nextLine:null,globalWordIndex:-1};constructor(e){super(new o({category:"🎬 SubtitleManager",style:"color: #e91e63; font-weight: bold; font-size: larger"})),this.getCurrentTime=e,this._resetState()}enqueue(e){this.logger.debug("Enqueue subtitle",{subtitle:e,queueLength:this.subtitleQueue.length});const{wordBoundaries:t,wordStartTimesMs:n}=this._computeWordBoundariesAndStartTimes(e.characters,e.start_times_ms),i={...e,wordBoundaries:t,wordStartTimesMs:n};this.subtitleQueue.push(i),this.isPlaying||1!==this.subtitleQueue.length||(this.logger.debug("Reset globalWordIndex to -1 (initial enqueue)"),this.state.globalWordIndex=-1),this.isPlaying&&!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),this._emitSubtitleChange())}async play(){this.isPlaying?this.logger.debug("Play called but already playing"):(this.logger.debug("Play called, starting playback"),this.isPlaying=!0,await this.emit("playing"),this.subtitleQueue.length>0&&(this._prepareState(),await this._emitSubtitleChange()),this.rafId=requestAnimationFrame(this._tick))}async pause(){this.logger.debug("Pause called"),this.isPlaying=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),await this.emit("paused")}clearQueue(){this.logger.debug("Clear queue"),this._resetState(),this.pause()}reset(){this._resetState()}_resetState(){this.subtitleQueue=[],this.cumulativeOffset=0,this.rafId=null,this.isPlaying=!1,this.tickDebugLast=0,this.state={currentLine:null,nextLine:null,globalWordIndex:-1}}_subtitleDuration(e){const{start_times_ms:t,durations_ms:n}=e;if(!t.length||!n.length)return 0;const i=t.length-1;return t[i]+n[i]}_applyOffset(e,t){return e.map(e=>e+t)}_prepareState(){if(!this.subtitleQueue.length)return;const e=this.subtitleQueue[0];e.adjustedWordStartTimesMs=this._applyOffset(e.wordStartTimesMs,this.cumulativeOffset);const t=this.subtitleQueue[1]||null;if(t){const n=this.cumulativeOffset+this._subtitleDuration(e);t.adjustedWordStartTimesMs=this._applyOffset(t.wordStartTimesMs,n)}this.state.currentLine=e,this.state.nextLine=t,this.logger.debug("Prepared state",{cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!e,hasNextLine:!!t,firstFewAdjusted:e.adjustedWordStartTimesMs?.slice(0,3)})}_computeWordBoundariesAndStartTimes(e,t){const n=[],i=[];let r=null;for(let s=0;s<e.length;s++){const a=e[s];if(" "!==a&&null===r&&(r=s),(" "===a||s===e.length-1)&&null!==r){const e=" "===a?s-1:s;n.push({start:r,end:e}),i.push(t[r]),r=null}}return{wordBoundaries:n,wordStartTimesMs:i}}_calculateGlobalWordIndex(e){let t=-1;const{currentLine:n,nextLine:i}=this.state;if(n?.adjustedWordStartTimesMs)for(let i=0;i<n.adjustedWordStartTimesMs.length&&e>=n.adjustedWordStartTimesMs[i];i++)t=i;if(i?.adjustedWordStartTimesMs){const r=n?.wordBoundaries.length||0;for(let n=0;n<i.adjustedWordStartTimesMs.length&&e>=i.adjustedWordStartTimesMs[n];n++)t=r+n}return t}_decodeGlobalIndex(e){if(e<0)return{lineIndex:0,wordIndex:-1};const t=this.state.currentLine?.wordBoundaries.length||0;return e<t?{lineIndex:0,wordIndex:e}:{lineIndex:1,wordIndex:e-t}}_isFinished(e,t,n){return t>n+this._subtitleDuration(e)}_buildWordChangeEvent(e){const{lineIndex:t,wordIndex:n}=this._decodeGlobalIndex(e),{currentLine:i,nextLine:r}=this.state,s=e=>e?{characters:e.characters,wordBoundaries:e.wordBoundaries}:null;let a;if(0===t&&i&&n>=0){const e=i.wordBoundaries[n];a=i.characters.slice(e.start,e.end+1).join("")}else if(1===t&&r&&n>=0){const e=r.wordBoundaries[n];a=r.characters.slice(e.start,e.end+1).join("")}return{globalWordIndex:e,currentLineIndex:t,wordIndexInLine:n,word:a,currentLineData:s(i),nextLineData:s(r)}}_buildSubtitleChangeEvent(){const e=e=>e?.adjustedWordStartTimesMs?{characters:e.characters,wordBoundaries:e.wordBoundaries,adjustedWordStartTimesMs:e.adjustedWordStartTimesMs}:null;return{currentLine:e(this.state.currentLine),nextLine:e(this.state.nextLine)}}async _emitWordChange(e){const t=this._buildWordChangeEvent(e);this.logger.debug("Word change",{globalWordIndex:e,lineIndex:t.currentLineIndex,wordIndex:t.wordIndexInLine,word:t.word}),await this.emit(T,t)}async _emitSubtitleChange(){const e=this._buildSubtitleChangeEvent();this.logger.debug("Subtitle change",{hasCurrentLine:!!e.currentLine,hasNextLine:!!e.nextLine}),await this.emit(k,e)}_tick=async()=>{if(!this.isPlaying||0===this.subtitleQueue.length)return;!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),await this._emitSubtitleChange());const e=this.getCurrentTime();this.state.currentLine||this._prepareState(),e-this.tickDebugLast>=3e3&&(this.logger.debug("Tick debug",{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!this.state.currentLine,hasNextLine:!!this.state.nextLine}),this.tickDebugLast=e);const t=this._calculateGlobalWordIndex(e);t!==this.state.globalWordIndex&&(this.state.globalWordIndex=t,await this._emitWordChange(t));const n=this.subtitleQueue[0],i=this.subtitleQueue[1]||null;let r=0;if(i){const t=this.cumulativeOffset+this._subtitleDuration(n);this._isFinished(i,e,t)&&(r=2)}else n&&this._isFinished(n,e,this.cumulativeOffset)&&(r=1);if(r>0){this.logger.debug(`Subtitle batch finished. Advancing ${r} lines.`,{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset});const t=this.subtitleQueue.splice(0,r);for(const e of t)this.cumulativeOffset+=this._subtitleDuration(e),await this.emit("subtitleFinished",e);if(!(this.subtitleQueue.length>0))return this.logger.debug("Queue empty, pausing"),this.state.globalWordIndex=-1,await this._emitWordChange(-1),void await this.pause();this._prepareState(),await this._emitSubtitleChange()}this.rafId=requestAnimationFrame(this._tick)}}class C extends u{scheduledEvents=[];masterClock;constructor(e){super(new o({category:"👄 VisemeScheduler",style:"color: #f44336; font-weight: bold; font-size: larger"})),this.masterClock=e}enqueue(e){this.scheduledEvents.push(...e),this.scheduleEvents()}async play(){await this.emit(f.Playing)}async pause(){await this.emit(f.Paused)}scheduleEvents(){this.masterClock.currentTime,this.scheduledEvents.forEach(e=>{setTimeout(async()=>{await this.emit(f.Viseme,e)})})}}class I extends u{animationLayers=new Map;layerPriority=["mouth","facial","body","idle"];thinkToggle=!1;constructor(){super(new o({category:"🧒 AvatarManager",style:r}))}playIdle(){this.playAnimation("body_idle",0,!0)}playListen(){this.playAnimation("body_idle_listen",0,!0)}playTalk(){this.playAnimation("body_talk_to_user_loop",0,!0)}playThink(){const e=this.thinkToggle?"body_idle_think2":"body_idle_think";this.thinkToggle=!this.thinkToggle,this.playAnimation(e,0,!0)}playLaugh(){this.playAnimation("body_laugh",0,!0)}playWaving(){this.playAnimation("body_waving",0,!1)}playViseme(e){this.playAnimation(e,1,!1)}async playAnimation(e,t=0,n=!0){this.animationLayers.set(t,e),await this.emit(m.AnimationChanged,{name:e,layer:t,loop:n}),this.logger.debug(`Playing animation: ${e} on layer ${t} (loop: ${n})`)}async stopAnimation(e=0){this.animationLayers.delete(e),await this.emit(m.AnimationStopped,{layer:e})}dispose(){try{this.logger.debug("Disposing AvatarManager..."),this.animationLayers.clear(),this.thinkToggle=!1,this.removeAllListeners(),this.logger.debug("AvatarManager disposed")}catch(e){this.logger.warn("Error while disposing AvatarManager",e)}}}const A="playing",R="playbackError",M="subtitleWordChange",O="subtitleChange",z="imageChange",P="finished",B="avatarAnimationChanged";class D extends u{capabilities;audioPlayer;visemeScheduler;subtitleManager;isPaused=!0;hasStarted=!1;avatarManager;constructor(e){super(new o({category:"🎪 PlaybackManager",style:r})),this.capabilities=e,this.audioPlayer=new S,this.visemeScheduler=new C(new AudioContext),this.subtitleManager=new E(()=>this.audioPlayer.getCurrentTime()),this.avatarManager=new I,this.avatarManager.on("animation-changed",async e=>{await this.emit(B,e)}),this.setupChildListeners(),this.resetState()}setupChildListeners(){this.audioPlayer.on(p.Ready,()=>{this.isPaused&&!this.hasStarted?(this.logger.debug("Ready event received, starting playback"),this.play()):this.logger.debug("Ready event received but already playing or paused, ignoring")}),this.audioPlayer.on(p.AboutToComplete,async()=>{this.logger.debug("Audio about to complete"),await this.emit("aboutToComplete")}),this.audioPlayer.on(p.Error,async e=>{await this.emit(R,{source:"audio",error:e})}),this.audioPlayer.on(p.Finished,async()=>{await this.emit(P),this.reset()}),this.subtitleManager.on(T,async e=>{await this.emit(M,e)}),this.subtitleManager.on(k,async e=>{await this.emit(O,e)})}resetState(){this.isPaused=!0,this.hasStarted=!1}async initialize(){this.logger.debug("Initialized",this.capabilities),this.isPaused=!0,this.hasStarted=!1,await this.audioPlayer.initialize()}handleMessage(e){"audio"===e.event||"subtitles"===e.event||"viseme"===e.event?this.enqueue(e):"audio_complete"===e.event?this.markAudioComplete():"image"===e.event&&this.emit(z,e)}enqueue(e){if(this.capabilities.audio&&"audio"===e.event){const t=e;this.audioPlayer.enqueue(t.audio)}}markAudioComplete(){this.logger.debug("Marking audio as complete"),this.capabilities.audio&&this.audioPlayer.markComplete()}async play(){this.isPaused=!1,this.hasStarted=!0,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.play():Promise.resolve()]),await this.emit(A)}async pause(){this.isPaused=!0,this.audioPlayer.pause(),this.visemeScheduler.pause(),this.subtitleManager.pause(),this.avatarManager.playIdle(),await this.emit("paused")}async resume(){this.isPaused&&(this.isPaused=!1,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.resume():Promise.resolve()]),await this.emit(A))}async resumeAudioContext(){"function"==typeof this.audioPlayer.resumeAudioContext&&await this.audioPlayer.resumeAudioContext()}getRemainingAudioSeconds(){return this.audioPlayer?.getRemainingAudioSeconds()??0}reset(){this.resetState(),this.audioPlayer?.reset(),this.subtitleManager?.reset(),this.avatarManager.playIdle()}resetAboutToComplete(){this.audioPlayer?.resetAboutToComplete()}dispose(){this.logger.debug("Disposing PlaybackManager...");try{this.isPaused=!0,this.hasStarted=!1,this.audioPlayer?.pause(),this.visemeScheduler?.pause(),this.subtitleManager?.pause(),this.avatarManager?.playIdle()}catch(e){this.logger.warn("Error pausing components during dispose",e)}try{this.audioPlayer&&"function"==typeof this.audioPlayer.dispose&&this.audioPlayer.dispose()}catch(e){this.logger.warn("Error disposing audioPlayer",e)}try{this.avatarManager&&"function"==typeof this.avatarManager.dispose&&this.avatarManager.dispose()}catch(e){this.logger.warn("Error disposing avatarManager",e)}try{this.subtitleManager?.reset(),this.removeAllListeners()}catch(e){this.logger.warn("Error resetting subtitleManager or removing listeners",e)}this.logger.debug("PlaybackManager disposed")}wireVADToAvatar(e){e.on(Sn.StateChange,e=>{"userSpeaking"===e.newState?this.avatarManager.playListen():"listening"===e.newState&&this.avatarManager.playIdle()})}wireConversationStateToAvatar(e){e.on(Sn.StateChange,e=>{"waiting"===e.newState&&this.avatarManager.playThink()})}}var U=n(937);const L="voiceActivity";class N extends u{vadModel=null;silenceTimer=null;silenceTimeoutMs;positiveSpeechThreshold;negativeSpeechThreshold;minSpeechMs;isDisposed=!1;currentStream=null;constructor(e=300,t=.5,n=.35,i=100){super(new o({category:"🎤 VADManager",style:s})),this.silenceTimeoutMs=e,this.positiveSpeechThreshold=t,this.negativeSpeechThreshold=n,this.minSpeechMs=i}async initialize(e){if(this.isDisposed)return;this.currentStream=e,this.logger.debug("You may need to close the browser console for this to initialize");const t=await U.Jl.new({getStream:async()=>this.currentStream,pauseStream:async()=>{},resumeStream:async e=>e,startOnLoad:!1,baseAssetPath:"/static/binaries/",onnxWASMBasePath:"/static/binaries/",positiveSpeechThreshold:this.positiveSpeechThreshold,negativeSpeechThreshold:this.negativeSpeechThreshold,minSpeechMs:this.minSpeechMs,onSpeechStart:async()=>{this.isDisposed||(this.logger.debug("Speech started"),this.clearSilenceTimer(),await this.emit(L,{isSpeaking:!0,confidence:1}))},onSpeechEnd:async e=>{this.isDisposed||(this.logger.debug("Speech ended"),this.startSilenceTimer(),await this.emit(L,{isSpeaking:!1,confidence:1}))},onVADMisfire:async()=>{this.isDisposed||(this.logger.debug("Misfire detected"),await this.emit(L,{isSpeaking:!1,confidence:0,misfire:!0}))},onFrameProcessed:async e=>{}});if(this.isDisposed)return this.logger.debug("VADManager disposed during initialization, cleaning up model"),void("function"==typeof t.destroy?t.destroy():t.pause());this.vadModel=t,this.logger.debug(`VAD Manager initialized (MicVAD) with silenceTimeoutMs=${this.silenceTimeoutMs}, positiveSpeechThreshold=${this.positiveSpeechThreshold}, negativeSpeechThreshold=${this.negativeSpeechThreshold}, minSpeechMs=${this.minSpeechMs}`)}startAnalysis(){this.vadModel&&(this.vadModel.start(),this.logger.debug("VAD analysis started (MicVAD)"))}stopAnalysis(){if(this.clearSilenceTimer(),this.vadModel)try{this.vadModel.pause(),this.logger.debug("VAD analysis stopped (MicVAD)")}catch(e){}}startSilenceTimer(){this.silenceTimer||(this.silenceTimer=window.setTimeout(async()=>{await this.emit("silence"),this.silenceTimer=null},this.silenceTimeoutMs))}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}dispose(){try{if(this.logger.debug("Disposing VADManager..."),this.isDisposed=!0,this.clearSilenceTimer(),this.removeAllListeners(),this.currentStream=null,this.vadModel){if(this.stopAnalysis(),"function"==typeof this.vadModel.destroy)try{this.vadModel.destroy(),this.logger.debug("VAD model destroyed")}catch(e){}this.vadModel=null}this.logger.debug("VADManager disposed")}catch(e){this.logger.warn("Error while disposing VADManager",e)}}}const H="user-input",F="user-speaking",q="user-silence",V={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let W;const j=new Uint8Array(16),G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function K(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!W){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");W=crypto.getRandomValues.bind(crypto)}return W(j)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=i[e];return t}return function(e,t=0){return(G[e[t+0]]+G[e[t+1]]+G[e[t+2]]+G[e[t+3]]+"-"+G[e[t+4]]+G[e[t+5]]+"-"+G[e[t+6]]+G[e[t+7]]+"-"+G[e[t+8]]+G[e[t+9]]+"-"+G[e[t+10]]+G[e[t+11]]+G[e[t+12]]+G[e[t+13]]+G[e[t+14]]+G[e[t+15]]).toLowerCase()}(i)}class Q{websocket=null;handlers;serverUrl;constructor(e,t){this.serverUrl=e,this.handlers=t}connect(){this.websocket=new WebSocket(this.serverUrl),this.setupHandlers()}disconnect(){this.websocket&&(this.websocket.onmessage=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket.close(1e3,"Client initiated disconnect"),this.websocket=null)}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("Cant send. WebSocket is not open");this.websocket.send(JSON.stringify(e))}isReady(){return this.websocket?.readyState===WebSocket.OPEN}setupHandlers(){this.websocket&&(this.websocket.onopen=()=>{this.handlers.onOpen&&this.handlers.onOpen()},this.websocket.onmessage=e=>{const t=JSON.parse(e.data);this.handlers.onMessage&&this.handlers.onMessage(t)},this.websocket.onerror=e=>{this.handlers.onError&&this.handlers.onError(e)},this.websocket.onclose=()=>{this.handlers.onClose&&this.handlers.onClose()})}}function J(e,t){return function(){return e.apply(t,arguments)}}const{toString:X}=Object.prototype,{getPrototypeOf:Z}=Object,{iterator:Y,toStringTag:ee}=Symbol,te=(ne=Object.create(null),e=>{const t=X.call(e);return ne[t]||(ne[t]=t.slice(8,-1).toLowerCase())});var ne;const ie=e=>(e=e.toLowerCase(),t=>te(t)===e),re=e=>t=>typeof t===e,{isArray:se}=Array,ae=re("undefined");function oe(e){return null!==e&&!ae(e)&&null!==e.constructor&&!ae(e.constructor)&&de(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ue=ie("ArrayBuffer"),le=re("string"),de=re("function"),he=re("number"),ce=e=>null!==e&&"object"==typeof e,pe=e=>{if("object"!==te(e))return!1;const t=Z(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||ee in e||Y in e)},fe=ie("Date"),me=ie("File"),ge=ie("Blob"),ye=ie("FileList"),we=ie("URLSearchParams"),[be,_e,$e,ve]=["ReadableStream","Request","Response","Headers"].map(ie);function xe(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),se(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(oe(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function Se(e,t){if(oe(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:n.g,ke=e=>!ae(e)&&e!==Te,Ee=(Ce="undefined"!=typeof Uint8Array&&Z(Uint8Array),e=>Ce&&e instanceof Ce);var Ce;const Ie=ie("HTMLFormElement"),Ae=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Re=ie("RegExp"),Me=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};xe(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)},Oe=ie("AsyncFunction"),ze=(Pe="function"==typeof setImmediate,Be=de(Te.postMessage),Pe?setImmediate:Be?(De=`axios@${Math.random()}`,Ue=[],Te.addEventListener("message",({source:e,data:t})=>{e===Te&&t===De&&Ue.length&&Ue.shift()()},!1),e=>{Ue.push(e),Te.postMessage(De,"*")}):e=>setTimeout(e));var Pe,Be,De,Ue;const Le="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Te):"undefined"!=typeof process&&process.nextTick||ze,Ne={isArray:se,isArrayBuffer:ue,isBuffer:oe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||de(e.append)&&("formdata"===(t=te(e))||"object"===t&&de(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ue(e.buffer),t},isString:le,isNumber:he,isBoolean:e=>!0===e||!1===e,isObject:ce,isPlainObject:pe,isEmptyObject:e=>{if(!ce(e)||oe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:be,isRequest:_e,isResponse:$e,isHeaders:ve,isUndefined:ae,isDate:fe,isFile:me,isBlob:ge,isRegExp:Re,isFunction:de,isStream:e=>ce(e)&&de(e.pipe),isURLSearchParams:we,isTypedArray:Ee,isFileList:ye,forEach:xe,merge:function e(){const{caseless:t,skipUndefined:n}=ke(this)&&this||{},i={},r=(r,s)=>{const a=t&&Se(i,s)||s;pe(i[a])&&pe(r)?i[a]=e(i[a],r):pe(r)?i[a]=e({},r):se(r)?i[a]=r.slice():n&&ae(r)||(i[a]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&xe(arguments[e],r);return i},extend:(e,t,n,{allOwnKeys:i}={})=>(xe(t,(t,i)=>{n&&de(t)?e[i]=J(t,n):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&Z(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:te,kindOfTest:ie,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(se(e))return e;let t=e.length;if(!he(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Y]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:Ie,hasOwnProperty:Ae,hasOwnProp:Ae,reduceDescriptors:Me,freezeMethods:e=>{Me(e,(t,n)=>{if(de(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];de(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach(e=>{n[e]=!0})};return se(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Se,global:Te,isContextDefined:ke,isSpecCompliantForm:function(e){return!!(e&&de(e.append)&&"FormData"===e[ee]&&e[Y])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(ce(e)){if(t.indexOf(e)>=0)return;if(oe(e))return e;if(!("toJSON"in e)){t[i]=e;const r=se(e)?[]:{};return xe(e,(e,t)=>{const s=n(e,i+1);!ae(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:Oe,isThenable:e=>e&&(ce(e)||de(e))&&de(e.then)&&de(e.catch),setImmediate:ze,asap:Le,isIterable:e=>null!=e&&de(e[Y])};function He(e,t,n,i,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}Ne.inherits(He,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ne.toJSONObject(this.config),code:this.code,status:this.status}}});const Fe=He.prototype,qe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{qe[e]={value:e}}),Object.defineProperties(He,qe),Object.defineProperty(Fe,"isAxiosError",{value:!0}),He.from=(e,t,n,i,r,s)=>{const a=Object.create(Fe);Ne.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e);const o=e&&e.message?e.message:"Error",u=null==t&&e?e.code:t;return He.call(a,o,u,n,i,r),e&&null==a.cause&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",s&&Object.assign(a,s),a};const Ve=He;function We(e){return Ne.isPlainObject(e)||Ne.isArray(e)}function je(e){return Ne.endsWith(e,"[]")?e.slice(0,-2):e}function Ge(e,t,n){return e?e.concat(t).map(function(e,t){return e=je(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Ke=Ne.toFlatObject(Ne,{},null,function(e){return/^is[A-Z]/.test(e)}),Qe=function(e,t,n){if(!Ne.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=Ne.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Ne.isUndefined(t[e])})).metaTokens,r=n.visitor||l,s=n.dots,a=n.indexes,o=(n.Blob||"undefined"!=typeof Blob&&Blob)&&Ne.isSpecCompliantForm(t);if(!Ne.isFunction(r))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(Ne.isDate(e))return e.toISOString();if(Ne.isBoolean(e))return e.toString();if(!o&&Ne.isBlob(e))throw new Ve("Blob is not supported. Use a Buffer instead.");return Ne.isArrayBuffer(e)||Ne.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,n,r){let o=e;if(e&&!r&&"object"==typeof e)if(Ne.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else if(Ne.isArray(e)&&function(e){return Ne.isArray(e)&&!e.some(We)}(e)||(Ne.isFileList(e)||Ne.endsWith(n,"[]"))&&(o=Ne.toArray(e)))return n=je(n),o.forEach(function(e,i){!Ne.isUndefined(e)&&null!==e&&t.append(!0===a?Ge([n],i,s):null===a?n:n+"[]",u(e))}),!1;return!!We(e)||(t.append(Ge(r,n,s),u(e)),!1)}const d=[],h=Object.assign(Ke,{defaultVisitor:l,convertValue:u,isVisitable:We});if(!Ne.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!Ne.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+i.join("."));d.push(n),Ne.forEach(n,function(n,s){!0===(!(Ne.isUndefined(n)||null===n)&&r.call(t,n,Ne.isString(s)?s.trim():s,i,h))&&e(n,i?i.concat(s):[s])}),d.pop()}}(e),t};function Je(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Xe(e,t){this._pairs=[],e&&Qe(e,this,t)}const Ze=Xe.prototype;Ze.append=function(e,t){this._pairs.push([e,t])},Ze.toString=function(e){const t=e?function(t){return e.call(this,t,Je)}:Je;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};const Ye=Xe;function et(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function tt(e,t,n){if(!t)return e;const i=n&&n.encode||et;Ne.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):Ne.isURLSearchParams(t)?t.toString():new Ye(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}const nt=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ne.forEach(this.handlers,function(t){null!==t&&e(t)})}},it={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ye,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},st="undefined"!=typeof window&&"undefined"!=typeof document,at="object"==typeof navigator&&navigator||void 0,ot=st&&(!at||["ReactNative","NativeScript","NS"].indexOf(at.product)<0),ut="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,lt=st&&window.location.href||"http://localhost",dt={...i,...rt},ht=function(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;return s=!s&&Ne.isArray(i)?i.length:s,o?(Ne.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a):(i[s]&&Ne.isObject(i[s])||(i[s]=[]),t(e,n,i[s],r)&&Ne.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!a)}if(Ne.isFormData(e)&&Ne.isFunction(e.entries)){const n={};return Ne.forEachEntry(e,(e,i)=>{t(function(e){return Ne.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null},ct={transitional:it,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=Ne.isObject(e);if(r&&Ne.isHTMLForm(e)&&(e=new FormData(e)),Ne.isFormData(e))return i?JSON.stringify(ht(e)):e;if(Ne.isArrayBuffer(e)||Ne.isBuffer(e)||Ne.isStream(e)||Ne.isFile(e)||Ne.isBlob(e)||Ne.isReadableStream(e))return e;if(Ne.isArrayBufferView(e))return e.buffer;if(Ne.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Qe(e,new dt.classes.URLSearchParams,{visitor:function(e,t,n,i){return dt.isNode&&Ne.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=Ne.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Qe(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e){if(Ne.isString(e))try{return(0,JSON.parse)(e),Ne.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ct.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(Ne.isResponse(e)||Ne.isReadableStream(e))return e;if(e&&Ne.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n){if("SyntaxError"===e.name)throw Ve.from(e,Ve.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dt.classes.FormData,Blob:dt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ne.forEach(["delete","get","head","post","put","patch"],e=>{ct.headers[e]={}});const pt=ct,ft=Ne.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mt=Symbol("internals");function gt(e){return e&&String(e).trim().toLowerCase()}function yt(e){return!1===e||null==e?e:Ne.isArray(e)?e.map(yt):String(e)}function wt(e,t,n,i,r){return Ne.isFunction(i)?i.call(this,t,n):(r&&(t=n),Ne.isString(t)?Ne.isString(i)?-1!==t.indexOf(i):Ne.isRegExp(i)?i.test(t):void 0:void 0)}class bt{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=gt(t);if(!r)throw new Error("header name must be a non-empty string");const s=Ne.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=yt(e))}const s=(e,t)=>Ne.forEach(e,(e,n)=>r(e,n,t));if(Ne.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Ne.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),n=e.substring(0,r).trim().toLowerCase(),i=e.substring(r+1).trim(),!n||t[n]&&ft[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)}),t})(e),t);else if(Ne.isObject(e)&&Ne.isIterable(e)){let n,i,r={};for(const t of e){if(!Ne.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?Ne.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,n);return this}get(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(Ne.isFunction(t))return t.call(this,e,n);if(Ne.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);return!(!n||void 0===this[n]||t&&!wt(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=gt(e)){const r=Ne.findKey(n,e);!r||t&&!wt(0,n[r],r,t)||(delete n[r],i=!0)}}return Ne.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!wt(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return Ne.forEach(this,(i,r)=>{const s=Ne.findKey(n,r);if(s)return t[s]=yt(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=yt(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ne.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&Ne.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[mt]=this[mt]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=gt(e);t[i]||(function(e,t){const n=Ne.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})})}(n,e),t[i]=!0)}return Ne.isArray(e)?e.forEach(i):i(e),this}}bt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ne.reduceDescriptors(bt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),Ne.freezeMethods(bt);const _t=bt;function $t(e,t){const n=this||pt,i=t||n,r=_t.from(i.headers);let s=i.data;return Ne.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function vt(e){return!(!e||!e.__CANCEL__)}function xt(e,t,n){Ve.call(this,null==e?"canceled":e,Ve.ERR_CANCELED,t,n),this.name="CanceledError"}Ne.inherits(xt,Ve,{__CANCEL__:!0});const St=xt;function Tt(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Ve("Request failed with status code "+n.status,[Ve.ERR_BAD_REQUEST,Ve.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}const kt=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const u=Date.now(),l=i[a];r||(r=u),n[s]=o,i[s]=u;let d=a,h=0;for(;d!==s;)h+=n[d++],d%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),u-r<t)return;const c=l&&u-l;return c?Math.round(1e3*h/c):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,u=r(o);i=s,e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:u||void 0,estimated:u&&a&&s<=a?(a-s)/u:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},Et=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ct=e=>(...t)=>Ne.asap(()=>e(...t)),It=dt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,dt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(dt.origin),dt.navigator&&/(msie|trident)/i.test(dt.navigator.userAgent)):()=>!0,At=dt.hasStandardBrowserEnv?{write(e,t,n,i,r,s,a){if("undefined"==typeof document)return;const o=[`${e}=${encodeURIComponent(t)}`];Ne.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),Ne.isString(i)&&o.push(`path=${i}`),Ne.isString(r)&&o.push(`domain=${r}`),!0===s&&o.push("secure"),Ne.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function Rt(e,t,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Mt=e=>e instanceof _t?{...e}:e;function Ot(e,t){t=t||{};const n={};function i(e,t,n,i){return Ne.isPlainObject(e)&&Ne.isPlainObject(t)?Ne.merge.call({caseless:i},e,t):Ne.isPlainObject(t)?Ne.merge({},t):Ne.isArray(t)?t.slice():t}function r(e,t,n,r){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!Ne.isUndefined(t))return i(void 0,t)}function a(e,t){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(n,r,s){return s in t?i(n,r):s in e?i(void 0,n):void 0}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(Mt(e),Mt(t),0,!0)};return Ne.forEach(Object.keys({...e,...t}),function(i){const s=u[i]||r,a=s(e[i],t[i],i);Ne.isUndefined(a)&&s!==o||(n[i]=a)}),n}const zt=e=>{const t=Ot({},e);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:s,headers:a,auth:o}=t;if(t.headers=a=_t.from(a),t.url=tt(Rt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&a.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),Ne.isFormData(n))if(dt.hasStandardBrowserEnv||dt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(Ne.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,n])=>{t.includes(e.toLowerCase())&&a.set(e,n)})}if(dt.hasStandardBrowserEnv&&(i&&Ne.isFunction(i)&&(i=i(t)),i||!1!==i&&It(t.url))){const e=r&&s&&At.read(s);e&&a.set(r,e)}return t},Pt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=zt(e);let r=i.data;const s=_t.from(i.headers).normalize();let a,o,u,l,d,{responseType:h,onUploadProgress:c,onDownloadProgress:p}=i;function f(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const i=_t.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Tt(function(e){t(e),f()},function(e){n(e),f()},{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(n(new Ve("Request aborted",Ve.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new Ve(i,Ve.ERR_NETWORK,e,m);r.event=t||null,n(r),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||it;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Ve(t,r.clarifyTimeoutError?Ve.ETIMEDOUT:Ve.ECONNABORTED,e,m)),m=null},void 0===r&&s.setContentType(null),"setRequestHeader"in m&&Ne.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Ne.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),h&&"json"!==h&&(m.responseType=i.responseType),p&&([u,d]=kt(p,!0),m.addEventListener("progress",u)),c&&m.upload&&([o,l]=kt(c),m.upload.addEventListener("progress",o),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(a=t=>{m&&(n(!t||t.type?new St(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===dt.protocols.indexOf(y)?n(new Ve("Unsupported protocol "+y+":",Ve.ERR_BAD_REQUEST,e)):m.send(r||null)})},Bt=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ve?t:new St(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Ve(`timeout ${t} of ms exceeded`,Ve.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>Ne.asap(a),o}},Dt=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},Ut=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}}(e))yield*Dt(n,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(e){throw o(e),e}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},{isFunction:Lt}=Ne,Nt=(({Request:e,Response:t})=>({Request:e,Response:t}))(Ne.global),{ReadableStream:Ht,TextEncoder:Ft}=Ne.global,qt=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Vt=e=>{e=Ne.merge.call({skipUndefined:!0},Nt,e);const{fetch:t,Request:n,Response:i}=e,r=t?Lt(t):"function"==typeof fetch,s=Lt(n),a=Lt(i);if(!r)return!1;const o=r&&Lt(Ht),u=r&&("function"==typeof Ft?(l=new Ft,e=>l.encode(e)):async e=>new Uint8Array(await new n(e).arrayBuffer()));var l;const d=s&&o&&qt(()=>{let e=!1;const t=new n(dt.origin,{body:new Ht,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),h=a&&o&&qt(()=>Ne.isReadableStream(new i("").body)),c={stream:h&&(e=>e.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!c[e]&&(c[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new Ve(`Response type '${e}' is not supported`,Ve.ERR_NOT_SUPPORT,n)})});return async e=>{let{url:r,method:a,data:o,signal:l,cancelToken:p,timeout:f,onDownloadProgress:m,onUploadProgress:g,responseType:y,headers:w,withCredentials:b="same-origin",fetchOptions:_}=zt(e),$=t||fetch;y=y?(y+"").toLowerCase():"text";let v=Bt([l,p&&p.toAbortSignal()],f),x=null;const S=v&&v.unsubscribe&&(()=>{v.unsubscribe()});let T;try{if(g&&d&&"get"!==a&&"head"!==a&&0!==(T=await(async(e,t)=>{const i=Ne.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(Ne.isBlob(e))return e.size;if(Ne.isSpecCompliantForm(e)){const t=new n(dt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ne.isArrayBufferView(e)||Ne.isArrayBuffer(e)?e.byteLength:(Ne.isURLSearchParams(e)&&(e+=""),Ne.isString(e)?(await u(e)).byteLength:void 0)})(t):i})(w,o))){let e,t=new n(r,{method:"POST",body:o,duplex:"half"});if(Ne.isFormData(o)&&(e=t.headers.get("content-type"))&&w.setContentType(e),t.body){const[e,n]=Et(T,kt(Ct(g)));o=Ut(t.body,65536,e,n)}}Ne.isString(b)||(b=b?"include":"omit");const t=s&&"credentials"in n.prototype,l={..._,signal:v,method:a.toUpperCase(),headers:w.normalize().toJSON(),body:o,duplex:"half",credentials:t?b:void 0};x=s&&new n(r,l);let p=await(s?$(x,_):$(r,l));const f=h&&("stream"===y||"response"===y);if(h&&(m||f&&S)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=p[t]});const t=Ne.toFiniteNumber(p.headers.get("content-length")),[n,r]=m&&Et(t,kt(Ct(m),!0))||[];p=new i(Ut(p.body,65536,n,()=>{r&&r(),S&&S()}),e)}y=y||"text";let k=await c[Ne.findKey(c,y)||"text"](p,e);return!f&&S&&S(),await new Promise((t,n)=>{Tt(t,n,{data:k,headers:_t.from(p.headers),status:p.status,statusText:p.statusText,config:e,request:x})})}catch(t){if(S&&S(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new Ve("Network Error",Ve.ERR_NETWORK,e,x),{cause:t.cause||t});throw Ve.from(t,t&&t.code,e,x)}}},Wt=new Map,jt=e=>{let t=e&&e.env||{};const{fetch:n,Request:i,Response:r}=t,s=[i,r,n];let a,o,u=s.length,l=Wt;for(;u--;)a=s[u],o=l.get(a),void 0===o&&l.set(a,o=u?new Map:Vt(t)),l=o;return o},Gt=(jt(),{http:null,xhr:Pt,fetch:{get:jt}});Ne.forEach(Gt,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const Kt=e=>`- ${e}`,Qt=e=>Ne.isFunction(e)||null===e||!1===e,Jt=function(e,t){e=Ne.isArray(e)?e:[e];const{length:n}=e;let i,r;const s={};for(let a=0;a<n;a++){let n;if(i=e[a],r=i,!Qt(i)&&(r=Gt[(n=String(i)).toLowerCase()],void 0===r))throw new Ve(`Unknown adapter '${n}'`);if(r&&(Ne.isFunction(r)||(r=r.get(t))))break;s[n||"#"+a]=r}if(!r){const e=Object.entries(s).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=n?e.length>1?"since :\n"+e.map(Kt).join("\n"):" "+Kt(e[0]):"as no adapter specified";throw new Ve("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r};function Xt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new St(null,e)}function Zt(e){return Xt(e),e.headers=_t.from(e.headers),e.data=$t.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Jt(e.adapter||pt.adapter,e)(e).then(function(t){return Xt(e),t.data=$t.call(e,e.transformResponse,t),t.headers=_t.from(t.headers),t},function(t){return vt(t)||(Xt(e),t&&t.response&&(t.response.data=$t.call(e,e.transformResponse,t.response),t.response.headers=_t.from(t.response.headers))),Promise.reject(t)})}const Yt="1.13.2",en={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{en[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const tn={};en.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Yt+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Ve(i(r," has been removed"+(t?" in "+t:"")),Ve.ERR_DEPRECATED);return t&&!tn[r]&&(tn[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},en.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const nn={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Ve("options must be an object",Ve.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new Ve("option "+s+" must be "+n,Ve.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Ve("Unknown option "+s,Ve.ERR_BAD_OPTION)}},validators:en},rn=nn.validators;class sn{constructor(e){this.defaults=e||{},this.interceptors={request:new nt,response:new nt}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+n):e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Ot(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&nn.assertOptions(n,{silentJSONParsing:rn.transitional(rn.boolean),forcedJSONParsing:rn.transitional(rn.boolean),clarifyTimeoutError:rn.transitional(rn.boolean)},!1),null!=i&&(Ne.isFunction(i)?t.paramsSerializer={serialize:i}:nn.assertOptions(i,{encode:rn.function,serialize:rn.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),nn.assertOptions(t,{baseUrl:rn.spelling("baseURL"),withXsrfToken:rn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&Ne.merge(r.common,r[t.method]);r&&Ne.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=_t.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))});const u=[];let l;this.interceptors.response.forEach(function(e){u.push(e.fulfilled,e.rejected)});let d,h=0;if(!o){const e=[Zt.bind(this),void 0];for(e.unshift(...a),e.push(...u),d=e.length,l=Promise.resolve(t);h<d;)l=l.then(e[h++],e[h++]);return l}d=a.length;let c=t;for(;h<d;){const e=a[h++],t=a[h++];try{c=e(c)}catch(e){t.call(this,e);break}}try{l=Zt.call(this,c)}catch(e){return Promise.reject(e)}for(h=0,d=u.length;h<d;)l=l.then(u[h++],u[h++]);return l}getUri(e){return tt(Rt((e=Ot(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Ne.forEach(["delete","get","head","options"],function(e){sn.prototype[e]=function(t,n){return this.request(Ot(n||{},{method:e,url:t,data:(n||{}).data}))}}),Ne.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Ot(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}sn.prototype[e]=t(),sn.prototype[e+"Form"]=t(!0)});const an=sn;class on{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{n.subscribe(e),t=e}).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e(function(e,i,r){n.reason||(n.reason=new St(e,i,r),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new on(function(t){e=t}),cancel:e}}}const un=on,ln={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ln).forEach(([e,t])=>{ln[t]=e});const dn=ln,hn=function e(t){const n=new an(t),i=J(an.prototype.request,n);return Ne.extend(i,an.prototype,n,{allOwnKeys:!0}),Ne.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Ot(t,n))},i}(pt);hn.Axios=an,hn.CanceledError=St,hn.CancelToken=un,hn.isCancel=vt,hn.VERSION=Yt,hn.toFormData=Qe,hn.AxiosError=Ve,hn.Cancel=hn.CanceledError,hn.all=function(e){return Promise.all(e)},hn.spread=function(e){return function(t){return e.apply(null,t)}},hn.isAxiosError=function(e){return Ne.isObject(e)&&!0===e.isAxiosError},hn.mergeConfig=Ot,hn.AxiosHeaders=_t,hn.formToJSON=e=>ht(Ne.isHTMLForm(e)?new FormData(e):e),hn.getAdapter=Jt,hn.HttpStatusCode=dn,hn.default=hn;const cn=hn,pn=class{static setItem(e,t){localStorage.setItem(e,t)}static setWithExpiry(e,t,n=33e5){const i={value:t,expiry:Date.now()+n};try{localStorage.setItem(e,JSON.stringify(i))}catch{}}static getWithExpiry(e){const t=localStorage.getItem(e);if(!t)return null;let n=null;try{n=JSON.parse(t)}catch(t){throw localStorage.removeItem(e),t}const i="number"==typeof n.expiry?n.expiry:0;return Date.now()>i?(localStorage.removeItem(e),null):n.value}static removeItem(e){localStorage.removeItem(e)}},fn=class{_authToken;_requestId=null;apiUrl;_apiKey;_federatedId=null;apiClient;constructor({apiUrl:e,apiKey:t,federatedId:n}){this.apiUrl=e,this._apiKey=t,this._federatedId=n,this._authToken=pn.getWithExpiry("authToken")||void 0,this.apiClient=cn.create({baseURL:this.apiUrl,headers:{Authorization:`Bearer ${this.authToken}`}}),this.setInterceptors()}async login(){if(!Boolean(pn.getWithExpiry("authToken")||this.authToken))try{await this.loginWithApiKey()}catch(e){throw console.error("Failed to authenticate with client credentials.",e),pn.removeItem("authToken"),this._authToken=void 0,e}}setInterceptors(){this.apiClient.interceptors.request.use(async e=>(e.url?.includes("/auth/login")||this.login(),e),e=>Promise.reject(e)),this.apiClient.interceptors.response.use(e=>(this.updatedRequestFromResponse(e),e),e=>(e.response&&this.updatedRequestFromResponse(e.response),Promise.reject(e))),this.apiClient.interceptors.response.use(e=>e,this.handleError.bind(this)),this.apiClient.interceptors.response.use(e=>e,e=>{if(e.response)try{return JSON.stringify(e.response.data),cn.isAxiosError(e)&&401===e.response?.status&&(pn.removeItem("authToken"),this._authToken=void 0),Promise.reject(e)}catch(e){return console.error(e),Promise.reject(e)}return Promise.reject(e)})}async verifyAuthentication(){await this.getMe()}updatedRequestFromResponse(e){return this.updateRequestId(e.headers["x-request-id"]??""),e}handleError(e){return Promise.reject(e)}get authToken(){return this._authToken}set authToken(e){e?pn.setWithExpiry("authToken",e):pn.removeItem("authToken"),this._authToken=e,this.apiClient&&(this.apiClient.defaults.headers.Authorization=`Bearer ${e}`)}get requestId(){return this._requestId}updateRequestId(e){e&&(this._requestId=e)}async loginWithApiKey(){const e=await this.apiClient.post("/auth/login",{api_key:this._apiKey,federated_id:this._federatedId});return this.authToken=e.data.access_token,this.apiClient.defaults.headers.common.Authorization=`Bearer ${this.authToken}`,this.authToken||""}async getMe(){return(await this.apiClient.get("/users/me")).data}async generateImage(e){const{provider:t,...n}=e,i=`/images/generate/${t}`;return(await this.apiClient.post(i,n)).data}async generateImageWithBria(e){return(await this.apiClient.post("/images/generate/bria",e)).data}async generateImageWithReplicate(e){return(await this.apiClient.post("/images/generate/replicate",e)).data}async getAvailableModels(){return(await this.apiClient.get("/images/models")).data}},mn={sampling_rate:48e3,mime_type:"audio/mpeg"};class gn extends u{config;wsConnection=null;_api=null;pendingRequests=new Map;constructor(e){super(new o({category:"🗣️ConversationNetwork",style:"color: #607d8b; font-weight: bold; font-size: larger"})),this.config=e,this._api=new fn({apiUrl:e.apiUrl,apiKey:e.apiKey,federatedId:e.federatedId})}async initialize(){try{await this._api.login()}catch(e){const t=e.response?.data?.error||e.message||"Authentication failed",n=e.response?.data?.traceback;n?this.logger.error("Authentication failed:",t,"\nTraceback:",n):this.logger.error("Authentication failed:",t);const i=new Error(t);throw n&&(i.traceback=n),i}}async connect(){let e=this.config.apiUrl.replace(/\/api\/?$/,"")+"/interact";this.wsConnection=new Q(e,this.getWebSocketHandlers()),this.wsConnection.connect(),await this.waitForWebSocketReady(1e4),this.logger.debug("Network connections established - Authenticating next...")}async waitForWebSocketReady(e){return new Promise((t,n)=>{if(!this.wsConnection)return void n(new Error("WebSocket connection not initialized"));if(this.wsConnection.isReady())return void t();const i=setTimeout(()=>{n(new Error(`WebSocket connection timeout after ${e}ms`))},e),r=()=>{this.wsConnection?.isReady()?(clearTimeout(i),t()):setTimeout(r,50)};r()})}getWebSocketHandlers(){return{onOpen:async()=>{try{await this.authenticate(),await this.setConfiguration(),this.emit(c),await this.interact({text:".",uid:"",kind:"interact",type:"stream"})}catch(e){const t=e?.error||String(e);this.emit(d,new Error(t))}},onMessage:async e=>{if(e.uid&&this.pendingRequests.has(e.uid)){const t=this.pendingRequests.get(e.uid);if(t)if(t.isStream)"close"===e.kind?(clearTimeout(t.timeout),t.resolve(e),this.pendingRequests.delete(e.uid)):"error"===e.kind?(this.logger.error(e.error),this.emit(d,new Error(e.error))):this.emit(l,e);else{if(clearTimeout(t.timeout),"error"===e.kind){const n=e;this.logger.error(n?.error),t.reject(n.error)}else t.resolve(e);this.pendingRequests.delete(e.uid),this.emit(l,e)}}else"interact"===e.kind?this.emit(l,e):"error"===e.kind?(this.logger.error(e.error),await this.emit(d,e.error)):this.logger.warn("Received message without a matching request UID",e)},onError:async e=>{await this.emit(d,e)},onClose:async()=>{await this.emit(h)}}}async makeRequest(e,t=5e4){return this.makeRequestInternal(e,t,!1)}async makeStreamRequest(e,t=5e4){return this.makeRequestInternal(e,t,!0)}async makeRequestInternal(e,t,n){if(!this.wsConnection?.isReady())throw new Error("WebSocket not ready");var i,r,s;e.uid=!V.randomUUID||r||i?K(i,r,s):V.randomUUID(),e.client_start_time=(new Date).toISOString();const a=new Promise((i,r)=>{const s=setTimeout(()=>{this.pendingRequests.delete(e.uid),r(new Error(`Request ${e.uid} timed out after ${t}ms`))},t);this.pendingRequests.set(e.uid,{resolve:i,reject:r,timeout:s,isStream:n})});return this.wsConnection.send(e),a}async authenticate(){const e={type:"request",kind:"authenticate",access_token:this._api.authToken,uid:"",metadata:this.config.metadata};await this.makeRequest(e)}updateConfig(e){this.config=e}async updateRemoteConfiguration(e){this.updateConfig(e),await this.setConfiguration()}async setConfiguration(){const e={type:"request",kind:"set_configuration",config:{prompt:this.config.prompt,voice_profile:this.config.voiceProfile,utilities:this.config.utilities,safety_policy:this.config.safetyPolicy},uid:""};await this.makeRequest(e)}async addAudio(e){const t={type:"request",kind:"add_audio",audio:e,uid:"",config:mn};await this.makeRequest(t)}async clearAudio(){await this.makeRequest({type:"request",kind:"clear_audio",uid:""})}async checkTurn(){await this.makeRequest({type:"request",kind:"check_turn",uid:""})}async generateImage(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImage(e)).image}}async generateImageWithBria(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithBria(e)).image}}async generateImageWithReplicate(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithReplicate(e)).image}}async getAvailableModels(){return{kind:"get_available_models",uid:"",models:(await this._api.getAvailableModels()).models}}async interact(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async interactAudio(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async disconnect(){this.wsConnection?.disconnect()}isReady(){return this.wsConnection?.isReady()||!1}async send(e){"audio"!==e.type?this.logger.warn("ConversationNetwork.send is deprecated. Use specific methods instead."):await this.addAudio(e.audio)}}class yn{mediaRecorder=null;mimeType;onAudioData;timeslice;logger=new o({category:"🎤 MediaRecorderFallback",style:a});constructor(e,t,n=100){this.mimeType=e,this.onAudioData=t,this.timeslice=n}initialize(e){this.logger.debug("Initializing MediaRecorder for audio processing"),this.mediaRecorder=new MediaRecorder(e,{mimeType:this.mimeType}),this.logger.debug("MediaRecorder created, state:",this.mediaRecorder.state),this.mediaRecorder.ondataavailable=e=>{this.logger.debug("ondataavailable called, size:",e.data.size),e.data.size>0&&e.data.arrayBuffer().then(e=>{this.onAudioData(e)})}}start(){this.mediaRecorder&&"inactive"===this.mediaRecorder.state&&(this.mediaRecorder.start(this.timeslice),this.logger.debug(`MediaRecorder started with ${this.timeslice}ms timeslice`))}stop(){this.mediaRecorder&&"inactive"!==this.mediaRecorder.state&&(this.mediaRecorder.stop(),this.logger.debug("MediaRecorder stopped"))}}const wn="audio-data",bn="error";class _n extends u{mediaStream=null;audioContext=null;workletNode=null;mediaRecorder=null;recording=!1;config;useMediaRecorder=!1;mediaRecorderFallback=null;audioBuffer=[];bufferingMode=!1;MIME_TYPE="audio/webm;codecs=opus";constructor(e={}){super(new o({category:"🎤 AudioRecorder",style:a})),this.config={sampleRate:41e3,channels:1,bitDepth:16,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,timeslice:100,...e}}async initialize(e){try{this.logger.debug("Initializing..."),await this.setupAudioContext(),await this.loadAudioWorklet(),this.mediaStream=e,this.useMediaRecorder&&(this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream)),this.logger.debug("Initialized successfully")}catch(e){throw this.logger.error("Failed to initialize",e),e}}async start(){if(this.recording)this.logger.warn("Recording already in progress");else{if(this.audioContext&&"suspended"===this.audioContext.state)try{await this.audioContext.resume(),this.logger.debug("AudioContext resumed successfully at start of recording.")}catch(e){this.logger.error("Failed to resume AudioContext:",e);const t=new Error("The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developer.chrome.com/blog/autoplay/#web_audio");throw await this.emit(bn,t),t}this.audioContext||(await this.setupAudioContext(),await this.loadAudioWorklet());try{if(this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext before starting recording..."),await this.audioContext.resume()),!this.mediaStream)throw new Error("AudioRecorder: mediaStream must be set via initialize(stream) before starting recording.");this.logger.debug("setupMediaStream complete"),await this.setupAudioProcessing(),this.logger.debug("setupAudioProcessing complete"),this.recording=!0,await this.emit("recording-started"),this.logger.debug("Audio recording started")}catch(e){throw this.logger.error("Failed to start recording",e),await this.emit(bn,e),e}}}async stop(){if(this.logger.debug("Stopping recording..."),this.recording)try{await this.cleanup(),this.recording=!1,await this.emit("recording-stopped"),this.logger.debug("Audio recording stopped")}catch(e){throw this.logger.error("Failed to stop recording",e),await this.emit(bn,e),e}else this.logger.warn("No recording in progress")}isRecording(){return this.recording}enableBufferingMode(){this.logger.debug("Buffering mode enabled"),this.bufferingMode=!0,this.audioBuffer=[]}disableBufferingMode(){this.logger.debug("Buffering mode disabled"),this.bufferingMode=!1}getBufferedAudio(){return[...this.audioBuffer]}clearBuffer(){const e=this.audioBuffer.length;this.logger.debug(`Audio buffer cleared (Was ${e})`),this.audioBuffer=[]}async resumeAudioContext(){this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, state:",this.audioContext.state))}async setupMediaRecorder(){this.logger.debug("Setting up MediaRecorder fallback..."),this.useMediaRecorder=!0}async setupAudioContext(){this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=new AudioContext({sampleRate:this.config.sampleRate,latencyHint:"interactive"}),this.logger.debug("AudioContext created, state:",this.audioContext.state)),"suspended"===this.audioContext.state&&(this.logger.debug("Resuming suspended AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, new state:",this.audioContext.state))}async loadAudioWorklet(){if(!this.audioContext)throw new Error("AudioContext not initialized");return this.setupMediaRecorder()}async setupAudioProcessing(){if(this.logger.debug("setupAudioProcessing called, useMediaRecorder:",this.useMediaRecorder),!this.audioContext||!this.mediaStream)throw new Error("AudioContext or MediaStream not initialized");if(this.useMediaRecorder)this.logger.debug("Using MediaRecorder fallback branch"),this.mediaRecorderFallback&&(this.logger.debug("Stopping existing MediaRecorderFallback before creating new one"),this.mediaRecorderFallback.stop()),this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream),this.mediaRecorderFallback.start();else{this.logger.debug("Using AudioWorklet for audio processing");const e=this.audioContext.createMediaStreamSource(this.mediaStream);this.workletNode=new AudioWorkletNode(this.audioContext,"audio-recording-processor",{processorOptions:{sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth}}),e.connect(this.workletNode),this.workletNode.port.onmessage=e=>{const{type:t,data:n}=e.data;t===wn&&this.handleAudioData(n)}}}async handleAudioData(e){let t=new Uint8Array(e),n=t.findIndex(e=>0!==e);if(-1===n)return void this.logger.warn("Skipping all-zero audio packet");n>0&&(this.logger.debug(`Trimming ${n} leading zero bytes from audio packet`),t=t.slice(n),e=t.buffer);const i=Array.from(t.slice(0,8));this.logger.debug(`Audio chunk: size=${e.byteLength}, first bytes=${i.join(",")}`),this.bufferingMode?(this.logger.debug(`Buffered audio chunk, buffer size: ${this.audioBuffer.length+1}`),this.audioBuffer.push(e)):await this.emit(wn,e)}async cleanup(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder=null),this.mediaRecorderFallback&&(this.mediaRecorderFallback.stop(),this.mediaRecorderFallback=null),this.audioBuffer=[],this.bufferingMode=!1,this.logger.debug("Audio buffer cleared during cleanup")}async preInitialize(){try{await this.setupAudioContext(),await this.loadAudioWorklet(),this.logger.debug("Pre-initialization complete")}catch(e){this.logger.error("Pre-initialization failed",e)}}isInitialized(){return null!==this.mediaStream}dispose(){try{this.logger.debug("Disposing AudioRecorder..."),this.recording&&this.stop(),this.cleanup(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.audioContext=null),this.mediaStream=null,this.removeAllListeners(),this.logger.debug("AudioRecorder disposed")}catch(e){this.logger.warn("Error while disposing AudioRecorder",e)}}}class $n extends u{capabilities;vadManager;network;recordingConfig;audioRecorder=null;isStopped=!0;mediaStream=null;isInputCompleteSent=!1;debugMode=!1;capturedAudioChunks=[];constructor(e,t,n,i){super(new o({category:"🎩 UserInputManager",style:"color: #2196f3; font-weight: bold; font-size: larger"})),this.capabilities=e,this.vadManager=t,this.network=n,this.recordingConfig=i,this.setupListeners(),this.capabilities.audio&&(this.audioRecorder=new _n(i),this.setupRecorderListeners())}async initialize(e){await this.reinitializeAudio(e)}async reinitializeAudio(e){if(this.capabilities.audio){if(e&&(this.mediaStream=e),!this.mediaStream){const e={echoCancellation:this.recordingConfig?.echoCancellation,noiseSuppression:this.recordingConfig?.noiseSuppression,autoGainControl:this.recordingConfig?.autoGainControl,sampleRate:this.recordingConfig?.sampleRate,channelCount:this.recordingConfig?.channels};Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:e})}await this.vadManager.initialize(this.mediaStream),await(this.audioRecorder?.initialize(this.mediaStream))}}async start(e=!1){if(this.isStopped){this.isStopped=!1;try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.debugMode&&(this.capturedAudioChunks=[],this.logger.debug("Cleared captured audio chunks for new interaction")),this.capabilities.audio&&(e?this.logger.debug("Skipping VAD startup to reduce CPU contention during playback"):this.vadManager.startAnalysis(),await this.startRecording())}}startVAD(){this.capabilities.audio&&!this.isStopped&&(this.logger.debug("Starting VAD analysis"),this.vadManager.startAnalysis())}async stop(){return!this.isStopped&&(this.logger.debug("Stopping User Input..."),this.isStopped=!0,this.capabilities.audio&&(this.vadManager.stopAnalysis(),await this.stopRecording()),!0)}async updateCapabilities(e){this.capabilities=e,this.logger.debug("Input capabilities updated",this.capabilities),this.capabilities.audio&&!this.audioRecorder?(this.audioRecorder=new _n(this.recordingConfig),this.setupRecorderListeners(),await this.reinitializeAudio()):!this.capabilities.audio&&this.audioRecorder&&(this.vadManager.stopAnalysis(),await this.audioRecorder.stop(),this.audioRecorder=null,this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null))}async stopRecording(){this.capabilities.audio&&this.audioRecorder?.isRecording()&&await this.audioRecorder.stop()}async startRecording(){this.capabilities.audio&&this.audioRecorder?(this.audioRecorder.isInitialized()||(this.logger.warn("AudioRecorder not initialized, reinitializing..."),await this.reinitializeAudio()),await this.audioRecorder.start()):this.logger.info("Will not start recording, audio capabilities are not enabled or audio recorder is not initialized")}isRecording(){return this.capabilities.audio&&(this.audioRecorder?.isRecording()||!1)}enableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.enableBufferingMode()}disableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.disableBufferingMode()}getBufferedAudio(){return this.audioRecorder?.getBufferedAudio()||[]}clearAudioBuffer(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.clearBuffer()}async flushBufferedAudio(){this.disableAudioBuffering();const e=this.getBufferedAudio();if(this.clearAudioBuffer(),e.length>0){this.logger.debug(`Flushing ${e.length} buffered audio chunks`);for(const t of e)await this.sendAudio(t)}}async sendAudio(e){if(this.isStopped)return;this.logger.debug("sendAudio called, size:",e.byteLength),this.debugMode&&(this.capturedAudioChunks.push(e),this.logger.debug(`Captured audio chunk for debug (${this.capturedAudioChunks.length} total chunks)`));const t=this.arrayBufferToBase64(e);await this.network.addAudio(t)}arrayBufferToBase64(e){let t="";const n=new Uint8Array(e),i=n.byteLength;for(let e=0;e<i;e++)t+=String.fromCharCode(n[e]);return btoa(t)}async interact(e){await this.network.interact(e)}async sendInputComplete(){this.isStopped||this.isInputCompleteSent||(this.isInputCompleteSent=!0,await this.emit(H,{type:"input_complete"}))}reset(){this.isInputCompleteSent=!1,this.debugMode&&this.capturedAudioChunks.length>0&&(this.logger.debug(`Clearing ${this.capturedAudioChunks.length} captured audio chunks on reset`),this.capturedAudioChunks=[])}dispose(){try{this.logger.debug("Disposing UserInputManager..."),this.isStopped=!0,this.vadManager&&(this.vadManager.stopAnalysis(),"function"==typeof this.vadManager.dispose&&this.vadManager.dispose()),this.capabilities.audio&&this.audioRecorder?.isRecording()&&this.audioRecorder.stop(),this.audioRecorder&&"function"==typeof this.audioRecorder.dispose&&this.audioRecorder.dispose(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null),this.removeAllListeners(),this.logger.debug("UserInputManager disposed")}catch(e){this.logger.warn("Error while disposing UserInputManager",e)}}setupListeners(){this.capabilities.audio&&(this.vadManager.on("voiceActivity",async e=>{e&&!this.isStopped&&(e.isSpeaking?await this.emit(F):await this.emit(q))}),this.vadManager.on("silence",async()=>{await this.sendInputComplete(),await this.network.checkTurn()}))}setupRecorderListeners(){this.audioRecorder&&this.audioRecorder.on(wn,e=>{this.sendAudio(e).catch(e=>{this.logger.error("Failed to send audio chunk",e)})})}async resumeAudioContext(){this.capabilities.audio&&this.audioRecorder&&await this.audioRecorder.resumeAudioContext()}enableDebugMode(){this.debugMode=!0,this.capturedAudioChunks=[],this.logger.info("Debug mode enabled - audio chunks will be captured")}disableDebugMode(){this.debugMode=!1,this.logger.info("Debug mode disabled")}clearCapturedAudio(){this.capturedAudioChunks=[],this.logger.info("Captured audio chunks cleared")}downloadCapturedAudio(e="captured-audio.webm"){if(0===this.capturedAudioChunks.length)return void this.logger.warn("No audio chunks captured to download");this.logger.info(`Downloading ${this.capturedAudioChunks.length} captured audio chunks as ${e}`);const t=new Blob(this.capturedAudioChunks,{type:"audio/webm;codecs=opus"}),n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n),this.logger.info("Download completed")}getCapturedAudioInfo(){const e=this.capturedAudioChunks.reduce((e,t)=>e+t.byteLength,0);return{chunkCount:this.capturedAudioChunks.length,totalSize:e}}}class vn{static DEFAULT_START_COMMAND="[start conversation]";static DEFAULT_PAUSE_RESUME_COMMAND="[resume after short pause]";static DEFAULT_LONG_PAUSE_RESUME_COMMAND="[resume after long break]";static DEFAULT_ERROR_RESUME_COMMAND="[resume after error]";startCommand=vn.DEFAULT_START_COMMAND;pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND;longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND;errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND;set(e,t,n,i){this.startCommand=e??vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=t??vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=n??vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=i??vn.DEFAULT_ERROR_RESUME_COMMAND}setDefault(){this.startCommand=vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND}}class xn{deps;static DEFAULT_MAX_RETRY_COUNT=3;currentRetryCount=0;isRetrying=!1;maxRetryCount;constructor(e){this.deps=e,this.maxRetryCount=e.maxRetryCount??xn.DEFAULT_MAX_RETRY_COUNT}async attemptRecovery(e){if(this.deps.logger.info("Attempting silent recovery for error type: "+e),!["network_timeout","network_error","server_error"].includes(e))return!1;if(!this.deps.isConnected())return this.deps.logger.info("Network is not connected, skipping retry"),!1;if(this.currentRetryCount>=this.maxRetryCount)return!1;if(this.isRetrying)return!1;this.currentRetryCount++,this.isRetrying=!0,this.deps.logger.info(`Attempting silent retry ${this.currentRetryCount}/${this.maxRetryCount} with error resume command`);try{return await this.deps.sendText(this.deps.conversationCommands.errorResumeCommand),this.isRetrying=!1,!0}catch(t){return this.deps.logger.error(`Retry attempt ${this.currentRetryCount} failed`,t),this.isRetrying=!1,this.currentRetryCount<this.maxRetryCount&&await this.attemptRecovery(e)}}resetRetryCount(){this.currentRetryCount=0,this.isRetrying=!1}getCurrentRetryCount(){return this.currentRetryCount}}const Sn={StateChange:"stateChange"};class Tn extends u{state="idle";network;vadManager;userInputManager;playbackManager;config;interactionCompletePending=!1;mediaStream=null;isTextOnly=!1;isDisposed=!1;isTransitioning=!1;pausedFromState=null;errorRetryHandler;isSimulateErrorsDebugMode=!1;conversationCommands=new vn;constructor(e){const t=new o({category:"🧞 ConversationManager",style:s});super(t),this.setConfiguration(e);const n={...e,...e.apiKey&&{apiKey:e.apiKey.slice(0,4)+"..."},...e.federatedId&&{federatedId:e.federatedId.slice(0,4)+"..."}};t.info("Initializing with config",n),this.network=new gn(this.config),this.vadManager=new N,this.userInputManager=new $n(this.config.inputCapabilities,this.vadManager,this.network,e.recordingConfig),this.playbackManager=new D(this.config.capabilities),this.playbackManager.wireVADToAvatar(this),this.playbackManager.wireConversationStateToAvatar(this),this.setupEventListeners(),this.errorRetryHandler=new xn({logger:this.logger,conversationCommands:this.conversationCommands,sendText:e=>this.sendText(e),isConnected:()=>this.isConnected(),maxRetryCount:3}),this.setState("uninitialized")}async setConfiguration(e){if(this.config={...e,capabilities:e.capabilities||{audio:!0,viseme:!0,subtitles:!0,avatar:!0},inputCapabilities:e.inputCapabilities||{audio:!0,text:!0},hooks:{...this.config?.hooks||{},...e.hooks},onInputUtilities:e.onInputUtilities??this.config?.onInputUtilities,onInputNonBlockingUtilities:e.onInputNonBlockingUtilities??this.config?.onInputNonBlockingUtilities,onOutputUtilities:e.onOutputUtilities??this.config?.onOutputUtilities},this.network&&(this.network.updateConfig(this.config),this.network.isReady())){this.logger.debug("Updating remote configuration");try{await this.network.updateRemoteConfiguration(this.config),this.logger.debug("Remote configuration updated successfully")}catch(e){this.logger.error("Failed to update remote configuration",e)}}}async initialize(){try{if(this.logger.debug("Initializing..."),this.setState("initializing"),await this.network.initialize(),await this.playbackManager.initialize(),this.config.inputCapabilities?.audio&&!this.mediaStream){const e=this.config.recordingConfig,t={echoCancellation:e?.echoCancellation,noiseSuppression:e?.noiseSuppression,autoGainControl:e?.autoGainControl,sampleRate:e?.sampleRate,channelCount:e?.channels};Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:t})}await this.userInputManager.initialize(this.mediaStream??void 0),await this.network.connect(),this.logger.debug("Initialized successfully"),this.setState("waiting")}catch(e){this.handleError("server_error",e)}}async startListening(){if("idle"!==this.state)throw new Error(`Cannot start listening from state: ${this.state}`);try{await this.userInputManager.start(),this.setState("listening")}catch(e){this.handleError("mic_denied",e)}}async stopListening(){this.logger.debug("stopListening called from state:",this.state),await this.userInputManager.stop()||this.setState("waiting")}async sendText(e){return this.interact({text:e,kind:"interact",type:"stream",uid:"",language_code:this.config.languageCode})}async generateImage(e){return this.network.generateImage(e)}async generateImageWithBria(e){return this.network.generateImageWithBria(e)}async generateImageWithReplicate(e){return this.network.generateImageWithReplicate(e)}async getAvailableModels(){return this.network.getAvailableModels()}async interact(e){if(!this.network.isReady()){const e="Network is not ready, cannot send text. probably disconnected";return this.logger.error(e),void await this.handleError("network_timeout",new Error(e))}if("idle"===this.state||"listening"===this.state||"processing_complete"===this.state||"error"===this.state)try{if(this.playbackManager.reset(),this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.setState("waiting"),await this.userInputManager.interact(e)}catch(e){this.logger.error("Error sending text message",e),await this.handleError("network_timeout",e)}}async interrupt(){this.playbackManager.pause(),await this.setState("interrupted")}async pause(){if(this.isTransitioning)this.logger.debug("Pause ignored: transition already in progress");else if("playing"===this.state||"processing_complete"===this.state||"listening"===this.state||"userSpeaking"===this.state){this.isTransitioning=!0;try{if(this.pausedFromState=this.state,"listening"===this.state||"userSpeaking"===this.state){this.logger.debug("Pausing from listening/speaking state, stopping input and clearing audio"),await this.userInputManager.stop(),this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio()}catch(e){this.logger.warn("Failed to clear server audio buffer on pause",e)}}else this.playbackManager.pause();await this.setState("paused")}finally{this.isTransitioning=!1}}else this.logger.warn(`Cannot pause from state: ${this.state}`)}async resume(){if(this.isTransitioning)this.logger.debug("Resume ignored: transition already in progress");else if("paused"===this.state||"processing_complete"===this.state){this.isTransitioning=!0;try{const e=this.playbackManager.getRemainingAudioSeconds()>0,t="listening"===this.pausedFromState||"userSpeaking"===this.pausedFromState;if(e){this.logger.debug("Resuming playback with buffered audio");try{await this.playbackManager.resume(),await this.setState("playing")}catch(e){this.logger.error("Failed to resume playback, falling back to listening",e),await this.userInputManager.start(),await this.setState("listening")}}else if(t){this.logger.debug("Resuming from listening pause, restarting recording");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to restart recording after pause",e),await this.handleError("mic_denied",e)}}else this.logger.debug("No buffered audio to resume, going to listening state"),this.interactionCompletePending?(this.interactionCompletePending=!1,await this.handleInteractionComplete()):await this.setState("listening")}finally{this.pausedFromState=null,this.isTransitioning=!1}}else this.logger.warn(`Cannot resume from state: ${this.state}`)}async forceInputComplete(){"userSpeaking"===this.state||"listening"===this.state?await this.userInputManager.sendInputComplete():this.logger.warn(`Cannot force input complete from state: ${this.state}`)}async stop(){await this.userInputManager.stop(),this.playbackManager.pause(),await this.network.disconnect(),await this.setState("idle")}async dispose(){if(this.isDisposed)this.logger.warn("ConversationManager already disposed");else{this.logger.debug("Disposing ConversationManager..."),this.isDisposed=!0,this.userInputManager?.removeAllListeners(),this.playbackManager?.removeAllListeners(),this.network?.removeAllListeners(),this.state="idle";try{this.userInputManager&&"function"==typeof this.userInputManager.dispose?this.userInputManager.dispose():(await this.userInputManager.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null)),this.playbackManager&&"function"==typeof this.playbackManager.dispose&&this.playbackManager.dispose(),await this.network.disconnect(),this.removeAllListeners(),this.logger.debug("ConversationManager disposed successfully")}catch(e){this.logger.warn("Error while disposing ConversationManager",e)}}}async setState(e){if(this.isDisposed)return;if(this.state===e)return;const t=this.state;this.state=e,this.config.hooks.onStateChange?.(e),await this.emit(Sn.StateChange,{oldState:t,newState:e}),this.logger.debug(`State transition: ${t} -> ${e}`)}setupEventListeners(){this.userInputManager.on(H,async e=>{await this.network.send(e),"input_complete"===e.type&&await this.setState("waiting")}),this.playbackManager.on(M,e=>{this.config.hooks.onSubtitleHighlight?.(e)}),this.playbackManager.on(O,e=>{this.config.hooks.onSubtitleChange?.(e)}),this.playbackManager.on(z,e=>{this.config.hooks.onImageChange?.(e)}),this.playbackManager.on(B,e=>{this.config.hooks.onAvatarAnimationChanged?.(e)}),this.userInputManager.on(F,async()=>{await this.setState("userSpeaking")}),this.userInputManager.on(q,async()=>{await this.setState("listening")}),this.network.on(c,async()=>{this.config.hooks.onNetworkStatusChange?.(!0)}),this.network.on(h,async()=>{this.config.hooks.onNetworkStatusChange?.(!1)}),this.network.on(l,async e=>{if("interact"===e.kind&&"text"===e.event&&this.config.hooks.onTextMessage?.(e),"data"===e.event&&this.config.hooks.onDataMessage?.(e),"interact"===e.kind&&"safety_policy"===e.event&&this.config.hooks.onSafetyEvent?.(e),"check_turn"===e.kind&&!1===e.is_user_still_speaking){if(this.logger.debug(`check_turn handler: state is ${this.state}`),"playing"===this.state||"paused"===this.state)return void this.logger.debug("check_turn received while playing / paused, ignoring.");await this.stopListening();try{if(this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.network.interactAudio({uid:"",kind:"interact",type:"stream",on_input_non_blocking:this.config.onInputNonBlockingUtilities,on_input:this.config.onInputUtilities,on_output:this.config.onOutputUtilities,language_code:this.config.languageCode})}catch(e){this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.logger.error("Error in interactAudio",e),await this.handleError("network_timeout",e)}}"interact"===e.kind&&"interaction_complete"===e.event&&(this.errorRetryHandler.resetRetryCount(),"playing"===this.state||"paused"===this.state?(this.logger.debug("Interaction complete received while playing / paused, deferring."),this.interactionCompletePending=!0,await this.setState("processing_complete")):await this.handleInteractionComplete()),"interaction_error"===e.type&&this.handleError("server_error",new Error(e.error||"Unknown server interaction error")),"string"===e.type&&this.config.hooks.onStringMessage?.(e),this.playbackManager.handleMessage(e)}),this.network.on(d,async e=>{this.handleError("network_error",e)}),this.playbackManager.on(R,async e=>{this.handleError("decode_error",e)}),this.playbackManager.on(A,async()=>{await this.setState("playing")}),this.playbackManager.on(P,async()=>{if(this.interactionCompletePending)this.logger.debug("Playback finished, processing deferred interaction complete."),this.interactionCompletePending=!1,await this.handleInteractionComplete();else if("playing"===this.state){this.logger.debug("Playback finished, starting recording now (no overlap)"),this.userInputManager.reset();try{await this.userInputManager.start(),await this.setState("listening"),this.logger.debug("Recording started successfully after playback")}catch(e){this.logger.error("Failed to start recording after playback",e),await this.setState("idle")}}})}async handleError(e,t){await this.setState("error"),this.logger.error("handleError called with type: "+e+" and error: "+t.message);let n=!1;try{n=await this.errorRetryHandler.attemptRecovery(e)}catch(e){this.logger.error("Error during recovery attempt",e),n=!1}if(n)return void this.logger.debug("Error recovery succeeded, not raising error");const i={type:e,message:t.message,originalError:t};this.config.hooks.onError?.(i),this.logger.error(`Conversation error: ${e}`,t)}async handleInteractionComplete(){this.logger.debug("Interaction complete received"),this.playbackManager.resetAboutToComplete();try{if(this.userInputManager.reset(),this.userInputManager.isRecording())await this.setState("listening");else{this.logger.debug("Starting recording after interaction complete");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to start recording",e),await this.setState("idle")}}}catch(e){this.logger.error("Failed to handle interaction complete",e),await this.handleError("network_timeout",e)}}async toggleTextOnlyInput(e){this.isTextOnly=e,await this.updateInputCapabilities()}isConnected(){return this.network.isReady()}enableAudioDebugMode(){this.userInputManager.enableDebugMode(),this.logger.info("Audio debug mode enabled")}disableAudioDebugMode(){this.userInputManager.disableDebugMode(),this.logger.info("Audio debug mode disabled")}downloadCapturedAudio(e){this.userInputManager.downloadCapturedAudio(e)}clearCapturedAudio(){this.userInputManager.clearCapturedAudio()}getCapturedAudioInfo(){return this.userInputManager.getCapturedAudioInfo()}async updateInputCapabilities(){this.logger.debug(`Updating input capabilities, textOnly: ${this.isTextOnly}`),this.config.inputCapabilities={...this.config.inputCapabilities,audio:!this.isTextOnly,text:this.isTextOnly},await this.userInputManager.updateCapabilities(this.config.inputCapabilities),this.isTextOnly?await this.userInputManager.stopRecording():"idle"===this.state&&await this.startListening()}}export{S as AudioPlayer,vn as ConversationCommands,Tn as ConversationManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ug-js-sdk",
3
- "version": "3.0.50",
3
+ "version": "3.0.51",
4
4
  "description": "JavaScript SDK for building conversational AI experiences with voice, text, avatars, and real-time interactions",
5
5
  "main": "dist/ug-js-sdk.mjs",
6
6
  "module": "dist/ug-js-sdk.mjs",