New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nuclia/core

Package Overview
Dependencies
Maintainers
3
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuclia/core - npm Package Compare versions

Comparing version

to
1.6.5

6

CHANGELOG.md

@@ -0,1 +1,7 @@

# 1.6.5 (2023-10-19)
### Bug fix
- Prevent `/chat` endpoint to be called twice when using `chat` method with a callback.
# 1.6.4 (2023-10-17)

@@ -2,0 +8,0 @@

2

esm/index.js

@@ -1,1 +0,1 @@

var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(t){try{u(r.next(t))}catch(t){s(t)}}function a(t){try{u(r.throw(t))}catch(t){s(t)}}function u(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(o,a)}u((r=r.apply(t,e||[])).next())}))}function i(t,e){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(u){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function s(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function a(t,e,n){if(n||2===arguments.length)for(var r,i=0,s=e.length;i<s;i++)!r&&i in e||(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return t.concat(r||Array.prototype.slice.call(e))}function u(t){return this instanceof u?(this.v=t,this):new u(t)}function c(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(t){i[t]&&(r[t]=function(e){return new Promise((function(n,r){s.push([t,e,n,r])>1||a(t,e)}))})}function a(t,e){try{(n=i[t](e)).value instanceof u?Promise.resolve(n.value.v).then(c,l):h(s[0][2],n)}catch(t){h(s[0][3],t)}var n}function c(t){a("next",t)}function l(t){a("throw",t)}function h(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}}function l(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=s(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,i){(function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)})(r,i,(e=t[n](e)).done,e.value)}))}}}function h(t){return"function"==typeof t}function d(t){var e=t((function(t){Error.call(t),t.stack=(new Error).stack}));return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var f=d((function(t){return function(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}}));function p(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var g=function(){function t(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}var e;return t.prototype.unsubscribe=function(){var t,e,n,r,i;if(!this.closed){this.closed=!0;var u=this._parentage;if(u)if(this._parentage=null,Array.isArray(u))try{for(var c=s(u),l=c.next();!l.done;l=c.next()){l.value.remove(this)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(e=c.return)&&e.call(c)}finally{if(t)throw t.error}}else u.remove(this);var d=this.initialTeardown;if(h(d))try{d()}catch(t){i=t instanceof f?t.errors:[t]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var g=s(p),b=g.next();!b.done;b=g.next()){var y=b.value;try{v(y)}catch(t){i=null!=i?i:[],t instanceof f?i=a(a([],o(i)),o(t.errors)):i.push(t)}}}catch(t){n={error:t}}finally{try{b&&!b.done&&(r=g.return)&&r.call(g)}finally{if(n)throw n.error}}}if(i)throw new f(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)v(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(e)}},t.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},t.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},t.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&p(e,t)},t.prototype.remove=function(e){var n=this._finalizers;n&&p(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),b=g.EMPTY;function y(t){return t instanceof g||t&&"closed"in t&&h(t.remove)&&h(t.add)&&h(t.unsubscribe)}function v(t){h(t)?t():t.unsubscribe()}var m={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},w={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,a([t,e],o(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function E(t){w.setTimeout((function(){throw t}))}function A(){}function k(t){t()}var S=function(t){function n(e){var n=t.call(this)||this;return n.isStopped=!1,e?(n.destination=e,y(e)&&e.add(n)):n.destination=O,n}return e(n,t),n.create=function(t,e,n){return new $(t,e,n)},n.prototype.next=function(t){this.isStopped||this._next(t)},n.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},n.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},n.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},n.prototype._next=function(t){this.destination.next(t)},n.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},n.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},n}(g),T=Function.prototype.bind;function x(t,e){return T.call(t,e)}var _=function(){function t(t){this.partialObserver=t}return t.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(t){R(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){R(t)}else R(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){R(t)}},t}(),$=function(t){function n(e,n,r){var i,s,o=t.call(this)||this;h(e)||!e?i={next:null!=e?e:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&m.useDeprecatedNextContext?((s=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},i={next:e.next&&x(e.next,s),error:e.error&&x(e.error,s),complete:e.complete&&x(e.complete,s)}):i=e;return o.destination=new _(i),o}return e(n,t),n}(S);function R(t){E(t)}var O={closed:!0,next:A,error:function(t){throw t},complete:A},I="function"==typeof Symbol&&Symbol.observable||"@@observable";function N(t){return t}var C=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r,i=this,s=(r=t)&&r instanceof S||function(t){return t&&h(t.next)&&h(t.error)&&h(t.complete)}(r)&&y(r)?t:new $(t,e,n);return k((function(){var t=i,e=t.operator,n=t.source;s.add(e?e.call(s,n):n?i._subscribe(s):i._trySubscribe(s))})),s},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=U(e))((function(e,r){var i=new $({next:function(e){try{t(e)}catch(t){r(t),i.unsubscribe()}},error:r,complete:e});n.subscribe(i)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[I]=function(){return this},t.prototype.pipe=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return(0===(t=e).length?N:1===t.length?t[0]:function(e){return t.reduce((function(t,e){return e(t)}),e)})(this)},t.prototype.toPromise=function(t){var e=this;return new(t=U(t))((function(t,n){var r;e.subscribe((function(t){return r=t}),(function(t){return n(t)}),(function(){return t(r)}))}))},t.create=function(e){return new t(e)},t}();function U(t){var e;return null!==(e=null!=t?t:m.Promise)&&void 0!==e?e:Promise}function P(t){return function(e){if(function(t){return h(null==t?void 0:t.lift)}(e))return e.lift((function(e){try{return t(e,this)}catch(t){this.error(t)}}));throw new TypeError("Unable to lift unknown Observable type")}}function D(t,e,n,r,i){return new L(t,e,n,r,i)}var L=function(t){function n(e,n,r,i,s,o){var a=t.call(this,e)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=n?function(t){try{n(t)}catch(t){e.error(t)}}:t.prototype._next,a._error=i?function(t){try{i(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,a._complete=r?function(){try{r()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return e(n,t),n.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},n}(S),j=d((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),B=function(t){function n(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return e(n,t),n.prototype.lift=function(t){var e=new F(this,this);return e.operator=t,e},n.prototype._throwIfClosed=function(){if(this.closed)throw new j},n.prototype.next=function(t){var e=this;k((function(){var n,r;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var i=s(e.currentObservers),o=i.next();!o.done;o=i.next()){o.value.next(t)}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}}))},n.prototype.error=function(t){var e=this;k((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var n=e.observers;n.length;)n.shift().error(t)}}))},n.prototype.complete=function(){var t=this;k((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},n.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(n.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),n.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},n.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},n.prototype._innerSubscribe=function(t){var e=this,n=this,r=n.hasError,i=n.isStopped,s=n.observers;return r||i?b:(this.currentObservers=null,s.push(t),new g((function(){e.currentObservers=null,p(s,t)})))},n.prototype._checkFinalizedStatuses=function(t){var e=this,n=e.hasError,r=e.thrownError,i=e.isStopped;n?t.error(r):i&&t.complete()},n.prototype.asObservable=function(){var t=new C;return t.source=this,t},n.create=function(t,e){return new F(t,e)},n}(C),F=function(t){function n(e,n){var r=t.call(this)||this;return r.destination=e,r.source=n,r}return e(n,t),n.prototype.next=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===n||n.call(e,t)},n.prototype.error=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===n||n.call(e,t)},n.prototype.complete=function(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)},n.prototype._subscribe=function(t){var e,n;return null!==(n=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==n?n:b},n}(B),H={now:function(){return(H.delegate||Date).now()},delegate:void 0},z=function(t){function n(e,n,r){void 0===e&&(e=1/0),void 0===n&&(n=1/0),void 0===r&&(r=H);var i=t.call(this)||this;return i._bufferSize=e,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,e),i._windowTime=Math.max(1,n),i}return e(n,t),n.prototype.next=function(e){var n=this,r=n.isStopped,i=n._buffer,s=n._infiniteTimeWindow,o=n._timestampProvider,a=n._windowTime;r||(i.push(e),!s&&i.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},n.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),n=this._infiniteTimeWindow,r=this._buffer.slice(),i=0;i<r.length&&!t.closed;i+=n?1:2)t.next(r[i]);return this._checkFinalizedStatuses(t),e},n.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,n=t._timestampProvider,r=t._buffer,i=t._infiniteTimeWindow,s=(i?1:2)*e;if(e<1/0&&s<r.length&&r.splice(0,r.length-s),!i){for(var o=n.now(),a=0,u=1;u<r.length&&r[u]<=o;u+=2)a=u;a&&r.splice(0,a+1)}},n}(B),W=function(t){function n(e,n){return t.call(this)||this}return e(n,t),n.prototype.schedule=function(t,e){return this},n}(g),K=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,a([t,e],o(n)))},G=function(t){return clearInterval(t)},M=function(t){function n(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return e(n,t),n.prototype.schedule=function(t,e){var n;if(void 0===e&&(e=0),this.closed)return this;this.state=t;var r=this.id,i=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(i,r,e)),this.pending=!0,this.delay=e,this.id=null!==(n=this.id)&&void 0!==n?n:this.requestAsyncId(i,this.id,e),this},n.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),K(t.flush.bind(t,this),n)},n.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return e;null!=e&&G(e)},n.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},n.prototype._execute=function(t,e){var n,r=!1;try{this.work(t)}catch(t){r=!0,n=t||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},n.prototype.unsubscribe=function(){if(!this.closed){var e=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,p(r,this),null!=e&&(this.id=this.recycleAsyncId(n,e,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},n}(W),V=function(){function t(e,n){void 0===n&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.schedulerActionCtor(this,t).schedule(n,e)},t.now=H.now,t}(),J=new(function(t){function n(e,n){void 0===n&&(n=V.now);var r=t.call(this,e,n)||this;return r.actions=[],r._active=!1,r}return e(n,t),n.prototype.flush=function(t){var e=this.actions;if(this._active)e.push(t);else{var n;this._active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},n}(V))(M),X=new C((function(t){return t.complete()}));function Y(t){return t&&h(t.schedule)}function q(t){return t[t.length-1]}function Z(t){return Y(q(t))?t.pop():void 0}var Q=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function tt(t){return h(null==t?void 0:t.then)}function et(t){return h(t[I])}function nt(t){return Symbol.asyncIterator&&h(null==t?void 0:t[Symbol.asyncIterator])}function rt(t){return new TypeError("You provided "+(null!==t&&"object"==typeof t?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var it="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function st(t){return h(null==t?void 0:t[it])}function ot(t){return c(this,arguments,(function(){var e,n,r;return i(this,(function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,u(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,u(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,u(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}}))}))}function at(t){return h(null==t?void 0:t.getReader)}function ut(t){if(t instanceof C)return t;if(null!=t){if(et(t))return i=t,new C((function(t){var e=i[I]();if(h(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(Q(t))return r=t,new C((function(t){for(var e=0;e<r.length&&!t.closed;e++)t.next(r[e]);t.complete()}));if(tt(t))return n=t,new C((function(t){n.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,E)}));if(nt(t))return ct(t);if(st(t))return e=t,new C((function(t){var n,r;try{for(var i=s(e),o=i.next();!o.done;o=i.next()){var a=o.value;if(t.next(a),t.closed)return}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}t.complete()}));if(at(t))return ct(ot(t))}var e,n,r,i;throw rt(t)}function ct(t){return new C((function(e){(function(t,e){var n,s,o,a;return r(this,void 0,void 0,(function(){var r,u;return i(this,(function(i){switch(i.label){case 0:i.trys.push([0,5,6,11]),n=l(t),i.label=1;case 1:return[4,n.next()];case 2:if((s=i.sent()).done)return[3,4];if(r=s.value,e.next(r),e.closed)return[2];i.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=i.sent(),o={error:u},[3,11];case 6:return i.trys.push([6,,9,10]),s&&!s.done&&(a=n.return)?[4,a.call(n)]:[3,8];case 7:i.sent(),i.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}}))}))})(t,e).catch((function(t){return e.error(t)}))}))}function lt(t,e,n,r,i){void 0===r&&(r=0),void 0===i&&(i=!1);var s=e.schedule((function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()}),r);if(t.add(s),!i)return s}function ht(t,e){return void 0===e&&(e=0),P((function(n,r){n.subscribe(D(r,(function(n){return lt(r,t,(function(){return r.next(n)}),e)}),(function(){return lt(r,t,(function(){return r.complete()}),e)}),(function(n){return lt(r,t,(function(){return r.error(n)}),e)})))}))}function dt(t,e){return void 0===e&&(e=0),P((function(n,r){r.add(t.schedule((function(){return n.subscribe(r)}),e))}))}function ft(t,e){if(!t)throw new Error("Iterable cannot be null");return new C((function(n){lt(n,e,(function(){var r=t[Symbol.asyncIterator]();lt(n,e,(function(){r.next().then((function(t){t.done?n.complete():n.next(t.value)}))}),0,!0)}))}))}function pt(t,e){if(null!=t){if(et(t))return function(t,e){return ut(t).pipe(dt(e),ht(e))}(t,e);if(Q(t))return function(t,e){return new C((function(n){var r=0;return e.schedule((function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())}))}))}(t,e);if(tt(t))return function(t,e){return ut(t).pipe(dt(e),ht(e))}(t,e);if(nt(t))return ft(t,e);if(st(t))return function(t,e){return new C((function(n){var r;return lt(n,e,(function(){r=t[it](),lt(n,e,(function(){var t,e,i;try{e=(t=r.next()).value,i=t.done}catch(t){return void n.error(t)}i?n.complete():n.next(e)}),0,!0)})),function(){return h(null==r?void 0:r.return)&&r.return()}}))}(t,e);if(at(t))return function(t,e){return ft(ot(t),e)}(t,e)}throw rt(t)}function gt(t,e){return e?pt(t,e):ut(t)}function bt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return gt(t,Z(t))}function yt(t,e){var n=h(t)?t:function(){return t},r=function(t){return t.error(n())};return new C(e?function(t){return e.schedule(r,0,t)}:r)}var vt=d((function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}}));function mt(t,e){return P((function(n,r){var i=0;n.subscribe(D(r,(function(n){r.next(t.call(e,n,i++))})))}))}var wt=Array.isArray;function Et(t){return mt((function(e){return function(t,e){return wt(e)?t.apply(void 0,a([],o(e))):t(e)}(t,e)}))}var At=Array.isArray,kt=Object.getPrototypeOf,St=Object.prototype,Tt=Object.keys;function xt(t){if(1===t.length){var e=t[0];if(At(e))return{args:e,keys:null};if((r=e)&&"object"==typeof r&&kt(r)===St){var n=Tt(e);return{args:n.map((function(t){return e[t]})),keys:n}}}var r;return{args:t,keys:null}}function _t(t,e,n){return void 0===n&&(n=1/0),h(e)?_t((function(n,r){return mt((function(t,i){return e(n,t,r,i)}))(ut(t(n,r)))}),n):("number"==typeof e&&(n=e),P((function(e,r){return function(t,e,n,r,i,s,o,a){var u=[],c=0,l=0,h=!1,d=function(){!h||u.length||c||e.complete()},f=function(t){return c<r?p(t):u.push(t)},p=function(t){s&&e.next(t),c++;var a=!1;ut(n(t,l++)).subscribe(D(e,(function(t){null==i||i(t),s?f(t):e.next(t)}),(function(){a=!0}),void 0,(function(){if(a)try{c--;for(var t=function(){var t=u.shift();o?lt(e,o,(function(){return p(t)})):p(t)};u.length&&c<r;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(D(e,f,(function(){h=!0,d()}))),function(){null==a||a()}}(e,r,t,n)})))}function $t(t){return void 0===t&&(t=1/0),_t(N,t)}function Rt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $t(1)(gt(t,Z(t)))}function Ot(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=function(t){return h(q(t))?t.pop():void 0}(t),r=xt(t),i=r.args,s=r.keys,o=new C((function(t){var e=i.length;if(e)for(var n=new Array(e),r=e,o=e,a=function(e){var a=!1;ut(i[e]).subscribe(D(t,(function(t){a||(a=!0,o--),n[e]=t}),(function(){return r--}),void 0,(function(){r&&a||(o||t.next(s?function(t,e){return t.reduce((function(t,n,r){return t[n]=e[r],t}),{})}(s,n):n),t.complete())})))},u=0;u<e;u++)a(u);else t.complete()}));return n?o.pipe(Et(n)):o}function It(t,e,n){void 0===t&&(t=0),void 0===n&&(n=J);var r=-1;return null!=e&&(Y(e)?n=e:r=e),new C((function(e){var i,s=(i=t)instanceof Date&&!isNaN(i)?+t-n.now():t;s<0&&(s=0);var o=0;return n.schedule((function(){e.closed||(e.next(o++),0<=r?this.schedule(void 0,r):e.complete())}),s)}))}function Nt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Z(t),r=function(t,e){return"number"==typeof q(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?ut(i[0]):$t(r)(gt(i,n)):X}function Ct(t,e){return P((function(n,r){var i=0;n.subscribe(D(r,(function(n){return t.call(e,n,i++)&&r.next(n)})))}))}function Ut(t){return P((function(e,n){var r,i=null,s=!1;i=e.subscribe(D(n,void 0,void 0,(function(o){r=ut(t(o,Ut(t)(e))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function Pt(t,e){return h(e)?_t(t,e,1):_t(t,1)}function Dt(t){return t<=0?function(){return X}:P((function(e,n){var r=0;e.subscribe(D(n,(function(e){++r<=t&&(n.next(e),t<=r&&n.complete())})))}))}function Lt(t){var e,n,r=1/0;return null!=t&&("object"==typeof t?(e=t.count,r=void 0===e?1/0:e,n=t.delay):r=t),r<=0?function(){return X}:P((function(t,e){var i,s=0,o=function(){if(null==i||i.unsubscribe(),i=null,null!=n){var t="number"==typeof n?It(n):ut(n(s)),r=D(e,(function(){r.unsubscribe(),a()}));t.subscribe(r)}else a()},a=function(){var n=!1;i=t.subscribe(D(e,void 0,(function(){++s<r?i?o():n=!0:e.complete()}))),n&&o()};a()}))}function jt(t,e){return P((function(n,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};n.subscribe(D(r,(function(n){null==i||i.unsubscribe();var o=0,u=s++;ut(t(n,u)).subscribe(i=D(r,(function(t){return r.next(e?e(n,t,u,o++):t)}),(function(){i=null,a()})))}),(function(){o=!0,a()})))}))}function Bt(t,e,n){var r=h(t)||e||n?{next:t,error:e,complete:n}:t;return r?P((function(t,e){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;t.subscribe(D(e,(function(t){var n;null===(n=r.next)||void 0===n||n.call(r,t),e.next(t)}),(function(){var t;i=!1,null===(t=r.complete)||void 0===t||t.call(r),e.complete()}),(function(t){var n;i=!1,null===(n=r.error)||void 0===n||n.call(r,t),e.error(t)}),(function(){var t,e;i&&(null===(t=r.unsubscribe)||void 0===t||t.call(r)),null===(e=r.finalize)||void 0===e||e.call(r)})))})):N}function Ft(t,e){void 0===e&&(e={});var r=e.selector,i=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]])}return n}(e,["selector"]);return new C((function(e){var s=new AbortController,o=s.signal,a=!0,u=i.signal;if(u)if(u.aborted)s.abort();else{var c=function(){o.aborted||s.abort()};u.addEventListener("abort",c),e.add((function(){return u.removeEventListener("abort",c)}))}var l=n(n({},i),{signal:o}),h=function(t){a=!1,e.error(t)};return fetch(t,l).then((function(t){r?ut(r(t)).subscribe(D(e,void 0,(function(){a=!1,e.complete()}),h)):(a=!1,e.next(t),e.complete())})).catch(h),function(){a&&s.abort()}}))}class Ht{token;constructor(t){this.token=t}urlBase64Decode(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("Illegal base64url string!")}return this.b64DecodeUnicode(e)}b64decode(t){let e="";if((t=String(t).replace(/=+$/,"")).length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let n,r,i=0,s=0;r=t.charAt(s++);~r&&(n=i%4?64*n+r:r,i++%4)?e+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return e}b64DecodeUnicode(t){return decodeURIComponent(Array.prototype.map.call(this.b64decode(t),(t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2))).join(""))}decodeToken(t=this.token){if(null===t)return null;const e=t.split(".");if(3!==e.length)throw new Error("The inspected token doesn't appear to be a JWT. Check to make sure it has three parts and see https://jwt.io for more.");const n=this.urlBase64Decode(e[1]);if(!n)throw new Error("Cannot decode the token.");return JSON.parse(n)}getJWTUser(t=this.token){let e;try{e=this.decodeToken(t)}catch(t){return null}return e}getTokenExpirationDate(t=this.token){const e=this.getJWTUser(t);if(!e)return null;const n=new Date(0);return n.setUTCSeconds(e.exp),n}isTokenExpired(t=this.token,e){if(null===t||""===t)return!0;const n=this.getTokenExpirationDate(t);return e=e||0,null===n||n.valueOf()<=(new Date).valueOf()+1e3*e}}const zt="JWT_KEY",Wt="JWT_REFRESH_KEY",Kt=216e5;class Gt{nuclia;_isAuthenticated=new z(1);timerSubscription;constructor(t){this.nuclia=t,this.nuclia.options.knowledgeBox?this._isAuthenticated.next(!0):this.checkTokenExpiration()}getAuthHeaders(t,e){return this.nuclia.options.standalone?{"X-NUCLIADB-ROLES":this.getNucliaDbRole(t,e)}:this.nuclia.options.apiKey?{"X-NUCLIA-SERVICEACCOUNT":`Bearer ${this.nuclia.options.apiKey}`}:this.getToken()?{Authorization:`Bearer ${this.getToken()}`}:{}}getNucliaDbRole(t,e){let n;switch(t){case"PUT":case"PATCH":case"POST":case"DELETE":n="WRITER";break;default:n="READER"}return"/kbs"===e||("PATCH"===t||"DELETE"===t)&&e?.startsWith("/kb")&&3===e?.split("/").length?n="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog")||e?.endsWith("/chat"))&&(n="READER"),n}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Ct((function(e,n){return t<=n}))),Ct((t=>!t)));var t}login(t,e,n){return this.fetch("/auth/login",{username:t,password:e},!1,n?{"X-STF-VALIDATION":n}:{}).pipe(mt((t=>this.authenticate(t))))}authenticate(t){return t.access_token?(this.storeTokens(t),this._isAuthenticated.next(!0),!0):(this._isAuthenticated.next(!1),!1)}logout(){this.fetch("/auth/logout",{},!0,{}).subscribe(),localStorage.removeItem(zt),localStorage.removeItem(Wt),this._isAuthenticated.next(!1)}refresh(){return this.fetch("/auth/refresh",{refresh_token:this.getRefreshToken()},!0,{}).pipe(Ut((t=>(this.logout(),yt(t)))),mt((t=>t.access_token?(this.storeTokens(t),!0):(this.logout(),!1))))}getToken(){return this.nuclia.options.public?"":localStorage.getItem(zt)||""}setPassword(t){return this.fetch("/auth/setpassword",{password:t},!0,{}).pipe(mt((t=>this.authenticate(t))))}deleteAuthenticatedUser(){return this.nuclia.rest.delete("/user").pipe(Bt((()=>this.storeTokens({access_token:"",refresh_token:""}))))}getJWTUser(){const t=this.getToken();if(t){return new Ht(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(Wt)||""}storeTokens(t){localStorage.setItem(zt,t.access_token),localStorage.setItem(Wt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new Ht(t),n=e.getTokenExpirationDate()?.getTime();if(n){const t=(new Date).getTime();if(n<t)this.logout();else{this._isAuthenticated.next(!0);const e=n-t<Kt?0:Kt;this.timerSubscription?.unsubscribe(),this.timerSubscription=It(e).pipe(jt((()=>this.refresh()))).subscribe()}}else this._isAuthenticated.next(!1)}else this._isAuthenticated.next(!1)}fetch(t,e,n,r){const i={"content-type":"application/json",...r};return n&&(i.Authorization=`Bearer ${this.getToken()}`),Ft(`${this.nuclia.backend}${t}`,{method:"POST",selector:t=>Promise.resolve(t),headers:i,body:JSON.stringify(e)}).pipe(jt((t=>t.ok?gt(t.clone().json()):yt(t))))}}const Mt="NUCLIA_NUA_KEY";var Vt,Jt,Xt,Yt,qt;!function(t){t.UNBLOCKED="unblocked",t.QUOTA="quota",t.MANAGER="manager"}(Vt||(Vt={})),function(t){t.UPLOAD="upload",t.PROCESSING="processing",t.SEARCH="search",t.GENERATIVE="generative",t.TRAINING="training",t.PUBLIC_UPLOAD="public_upload",t.PUBLIC_PROCESSING="public_processing",t.PUBLIC_SEARCH="public_search",t.PUBLIC_GENERATIVE="public_generative"}(Jt||(Jt={})),function(t){t.DAY="day",t.WEEK="week",t.MONTH="month",t.YEAR="year"}(Xt||(Xt={})),function(t){t.anHour="1h",t.twoHours="2h",t.threeHours="3h",t.sixHours="6h",t.twelveHours="12h",t.twentyFourHours="24h",t.fortyHeightHours="48h"}(Yt||(Yt={})),function(t){t.PROCESSING_TIME="processing_time",t.SEARCHES="searches",t.CHARS="chars",t.MEDIA_SECONDS="media_seconds",t.BYTES="bytes",t.RESOURCES="resources",t.PAGES="pages",t.TRAIN_SECONDS="train_seconds",t.SUGGESTIONS="suggestions",t.DOCS_NO_MEDIA="docs_no_media"}(qt||(qt={}));const Zt="user_prompts";var Qt;!function(t){t.BASIC="basic",t.ORIGIN="origin",t.RELATIONS="relations",t.VALUES="values",t.EXTRACTED="extracted",t.ERRORS="errors",t.EXTRA="extra"}(Qt||(Qt={}));const te=524288,ee=new RegExp(/[^a-z0-9_-]/g),ne=(t,e,n,r,i={})=>(i.contentType||n instanceof ArrayBuffer||(i.contentType="null"!==n?.type?n?.type:void 0),i.filename||n instanceof ArrayBuffer||(i.filename=n?.name),i.lang||n instanceof ArrayBuffer||(i.lang=n.lang),i.md5||n instanceof ArrayBuffer||(i.md5=n.md5),(n instanceof ArrayBuffer?bt(n):gt(n.arrayBuffer())).pipe(jt((s=>r?ie(t,e,s,i,n.payload):re(t,e,s,i))))),re=(t,e,n,r)=>{const i={"content-type":r?.contentType||"application/octet-stream",...ae(r)};let s=1;const o=r?.rslug?`?rslug=${r.rslug}`:"";return t.rest.post(`${e}/upload${o}`,n,i,!0).pipe(Lt(),Ct((t=>0==s--||503!==t.status)),Dt(1),jt((t=>{try{switch(t.status){case 201:return gt(t.json()).pipe(mt((t=>({resource:t.uuid||"",field:t.field_id||"",completed:!0}))));case 409:return bt({conflict:!0});default:return bt({failed:!0})}}catch(t){return bt({failed:!0})}})))},ie=(t,e,n,r,i)=>{let s=0,o=0,a=!1;const u=n.byteLength,c=Math.ceil(u/te),l={"upload-length":`${u}`,"tus-resumable":"1.0.0"},h=[];r?.filename&&h.push(`filename ${btoa(encodeURIComponent(r.filename))}`),r?.lang&&h.push(`language ${btoa(r.lang)}`),r?.md5&&h.push(`md5 ${btoa(r.md5)}`),h.push(`content_type ${btoa(r?.contentType||"application/octet-stream")}`),h.length>0&&(l["upload-metadata"]=h.join(","));let d=1;return t.rest.post(`${e}/tusupload`,i,l,!0).pipe(Lt(),Ct((t=>0==d--||503!==t.status)),Ut((t=>bt(t))),Dt(1),Pt((e=>Nt(bt(e).pipe(Ct((t=>201!==t.status||!t.headers.get("location"))),mt((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),bt(e).pipe(Ct((t=>201===t.status&&!!t.headers.get("location"))),mt((t=>t.headers.get("location"))),Pt((e=>function(t,e,n){if(null==e&&(e=t,t=0),e<=0)return X;var r=e+t;return new C(n?function(e){var i=t;return n.schedule((function(){i<r?(e.next(i++),this.schedule()):e.complete()}))}:function(e){for(var n=t;n<r&&!e.closed;)e.next(n++);e.complete()})}(0,c).pipe(Pt((()=>{const i=n.slice(s,s+te);return o+=1,a?bt({failed:a}):t.rest.patch(e,i,{"content-type":r?.contentType||"application/octet-stream","upload-offset":`${s}`,"content-length":`${i.byteLength}`},!0).pipe(mt((t=>200!==t.status?(a=!0,{failed:a}):(s+=te,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Ut((()=>(a=!0,bt({failed:!0})))))}))))))))))},se=(t,e,n,r=!1)=>{const i=Array.from(n),s=i.reduce(((t,e)=>t+(e.size||0)),0),o=[],a=i.map((t=>({file:t,progress:0,uploaded:!1,failed:!1})));return gt(i.map((n=>{let i=e;if(r){let t=n.name.toLowerCase().replace(ee,"_");o.includes(t)&&(t+="_"+o.filter((e=>e.startsWith(t))).length),o.push(t),i=`${i}/file/${t}`}const s=n.lang;if(s){const t=n.payload||{};n.payload={...t,metadata:{...t?.metadata,language:s}}}return ne(t,i,n,!0,{}).pipe(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Z(t);return P((function(e,r){(n?Rt(t,e,n):Rt(t,e)).subscribe(r)}))}({progress:0,completed:!1}),mt((t=>({status:t,file:n}))))}))).pipe(_t((t=>t),6),mt((t=>{const e=a.find((e=>e.file===t.file));t.status.failed&&(e.failed=!0),t.status.conflict&&(e.conflicts=!0),t.status.completed&&(e.uploaded=!0),t.status.failed||t.status.conflict||t.status.completed?e.progress=100:e.progress=t.status.progress||0;const n=a.filter((t=>t.failed)).length,r=a.filter((t=>t.conflicts)).length,i=a.filter((t=>t.uploaded)).length,o=0===a.filter((t=>!t.failed&&!t.uploaded)).length,u=Math.round(a.reduce(((t,e)=>t+e.file.size*e.progress/100),0)/s*100);return{files:a,progress:u,completed:o,uploaded:i,failed:n,conflicts:r}})))},oe=(t,e,n,r)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":r?.contentType||"application/octet-stream",...ae(r)};return t.rest.post("/processing/upload",n,i)},ae=t=>{const e={};return t?.filename&&(e["x-filename"]=encodeURIComponent(t.filename)),t?.md5&&(e["x-md5"]=t.md5),t?.lang&&(e["x-language"]=t.lang),e};var ue,ce,le,he,de,fe,pe;!function(t){t.text="text",t.file="file",t.link="link",t.layout="layout",t.conversation="conversation",t.keywordset="keywordset",t.datetime="datetime",t.generic="generic"}(ue||(ue={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(ce||(ce={}));class ge{value;extracted;error}class be{value;extracted;error}class ye{value;extracted;error}class ve{value;extracted;error}class me{value;extracted;error}function we(t){return`/l/${t.labelset}/${t.label}`}function Ee(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}function Ae(t){return`/e/${t.family}/${t.entity}`}function ke(t){const e=t.split("/");return{family:e[2],entity:e[3]}}!function(t){t.VALUE="value",t.EXTRACTED="extracted",t.ERROR="error"}(le||(le={})),function(t){t.TEXT="text",t.METADATA="metadata",t.SHORTENED_METADATA="shortened_metadata",t.LARGE_METADATA="large_metadata",t.VECTOR="vectors",t.LINK="link",t.FILE="file"}(he||(he={})),function(t){t.created="created",t.modified="modified",t.title="title"}(de||(de={})),function(t){t.layout="l",t.text="t",t.file="f",t.link="u",t.datetime="d",t.keywordset="k",t.generic="a",t.conversation="c"}(fe||(fe={})),function(t){var e,n,r,i;(e=t.Features||(t.Features={})).PARAGRAPH="paragraph",e.DOCUMENT="document",e.RELATIONS="relations",e.VECTOR="vector",(n=t.ResourceFeatures||(t.ResourceFeatures={})).PARAGRAPH="paragraph",n.RELATIONS="relations",n.VECTOR="vector",(r=t.SuggestionFeatures||(t.SuggestionFeatures={})).PARAGRAPH="paragraph",r.ENTITIES="entities",r.INTENT="intent",(i=t.FindScoreType||(t.FindScoreType={})).VECTOR="VECTOR",i.BM25="BM25",i.BOTH="BOTH"}(pe||(pe={}));const Se=(t,e,n,r,i=[],s,o)=>{const{inTitleOnly:a,...u}=s||{},c={query:r||"",features:i};a&&(c.fields=["a/title"]),c.shards=t.currentShards?.[e]||[];const l=`${n}/find`;return(o?t.rest.get(`${l}?${Re(c,u)}`,void 0,!0):t.rest.post(l,{...c,...u},void 0,!0)).pipe(jt((e=>{const n=e.headers.get("X-Nuclia-Trace-Id")||"";return e.ok&&206!==e.status?gt(e.json().then((t=>({...t,searchId:n})),(()=>{console.warn(`${l} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...c,...u}),gt(e.json().then((t=>{throw{status:e.status,body:t}}),(()=>{throw{status:e.status}}))))})),Ut((t=>bt({type:"error",status:t.status,detail:t.detail,body:t.body}))),mt((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((n=>{"findResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))},Te=(t,e,n,r,i=[],s,o)=>{const{inTitleOnly:a,...u}=s||{},c={query:r||"",features:i};a&&(c.fields=["a/title"]),c.shards=t.currentShards?.[e]||[];const l=o?t.rest.get(`${n}/search?${Re(c,u)}`):t.rest.post(`${n}/search`,{...c,...u});return $e(t,e,l)},xe=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${r?Re(i,r):""}`);return $e(t,e,s)},_e=(t,e,n,r,i,s)=>{const o={query:r||"",features:s};return i&&(o.fields=["a/title"]),t.rest.get(`${n}/suggest?${Re(o,{})}`).pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"suggestions"})))};function $e(t,e,n){return n.pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"searchResults"})),Bt((n=>{"searchResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))}const Re=(t,e)=>{Object.entries(e||{}).forEach((([e,n])=>{null!=n&&(Array.isArray(n)?t[e]=n.map((t=>`${t}`)):"object"==typeof n?Object.entries(n).forEach((([n,r])=>t[`${e}_${n}`]=`${r}`)):t[e]=`${n}`)}));const n=new URLSearchParams;return Object.entries(t).forEach((([t,e])=>Array.isArray(e)?e.forEach((e=>n.append(t,e))):n.append(t,e))),n.toString()};var Oe;!function(t){var e,n;(e=t.Features||(t.Features={})).PARAGRAPHS="paragraphs",e.RELATIONS="relations",(n=t.Author||(t.Author={})).USER="USER",n.NUCLIA="NUCLIA"}(Oe||(Oe={}));const Ie="_END_";function Ne(t,e,n,r=[],i=[Oe.Features.PARAGRAPHS],s={}){let o,a,u=0,c="";const{synchronous:l,...h}=s,d=`${e}/chat`,f={query:n,context:r,show:[Qt.BASIC,Qt.VALUES],features:i.length>0?i:void 0,...h};return l?t.rest.post(d,f,void 0,void 0,!0).pipe(mt((({answer:t,relations:e,results:n})=>({type:"answer",text:t,sources:{...n,relations:e},incomplete:!1,id:""})))):t.rest.getStream(d,f).pipe(mt((({data:t,incomplete:e,headers:n})=>{const r=n.get("X-Nuclia-Trace-Id")||"",i=n.get("NUCLIA-LEARNING-ID")||"";if(0===u&&t.length>=4&&(u=new DataView(t.buffer.slice(0,4)).getUint32(0)),!o&&u>0&&t.length>u+4){const e=t.slice(4,u+4);o=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}if(o&&(o.searchId=r),o&&t.length>u+4&&(c=(new TextDecoder).decode(t.slice(u+4).buffer),c.includes(Ie))){let t;if([c,t]=c.split(Ie),t)try{a=JSON.parse(atob(t)),o.relations=a}catch(t){console.warn(t)}}return{type:"answer",text:c,sources:o,incomplete:e,id:i}})),Ut((t=>bt({type:"error",status:t.status,detail:t.detail||""}))))}const Ce=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),Ue=(t,e,n,r,i)=>{const s=Ce(i.filter((n=>De(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=Ce(i.filter((n=>Le(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==n)),a=i.filter((n=>n.field.field!==t||n.field.field_type!==e)),u=r.length>0?[...o,{key:n,classifications:r}]:o;return s.length>0||u.length>0?[...a,{field:{field:t,field_type:e},token:s.length>0?s:void 0,paragraphs:u.length>0?u:void 0}]:a},Pe=(t,e,n,r)=>{const i=Ce(r.filter((n=>Le(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),s=r.filter((n=>n.field.field!==t||n.field.field_type!==e));return n.length>0||i.length>0?[...s,{field:{field:t,field_type:e},token:n.length>0?n:void 0,paragraphs:i.length>0?i:void 0}]:s},De=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,Le=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,je=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Be=t=>t?Array.from(t).length:0;class Fe{data={};fieldTextsCache={};constructor(t){t.data||(t.data={}),Object.assign(this,{...t,title:this.formatTitle(t.title)})}getFields(t=["files","links","texts","keywordsets"]){return Object.entries(this.data).filter((([e])=>t.includes(e))).map((([,t])=>t)).filter((t=>!!t)).map((t=>Object.values(t))).reduce(((t,e)=>t.concat(e)),[])}getFieldData(t,e){const n=this.data[t]?.[e];return n||void 0}getExtractedSummaries(){return this.getFields().filter((t=>t.extracted?.metadata?.metadata?.summary)).map((t=>t.extracted.metadata.metadata.summary))}getExtractedTexts(){return this.getFields().filter((t=>t.extracted?.text)).map((t=>t.extracted.text))}getFiles(){return this.getFields(["files"]).filter((t=>!!t&&!!t.value&&!!t.value.file)).map((t=>t.value.file))}getThumbnails(){return this.getFields(["files"]).map((t=>t.extracted?.file?.file_thumbnail)).concat(this.getFields(["links"]).map((t=>t.extracted?.link?.link_thumbnail))).filter((t=>!!t))}getAnnotatedEntities(){return(this.fieldmetadata||[]).filter((t=>t.token&&t.token.length>0)).map((t=>t.token)).reduce(((t,e)=>(e.filter((t=>!t.cancelled_by_user)).forEach((e=>{t[e.klass]||(t[e.klass]=[]),t[e.klass].push(e.token)})),t)),{})}getNamedEntities(){return this.getFields().filter((t=>t.extracted?.metadata?.metadata?.ner)).map((t=>Object.entries(t.extracted.metadata.metadata.ner).reduce(((t,[e,n])=>(t[n]=(t[n]||[]).concat([e]),t)),{}))).reduce(((t,e)=>(Object.entries(e).forEach((([e,n])=>{t[e]=(t[e]||[]).concat(n)})),t)),{})}getClassifications(){const t=(this.usermetadata?.classifications||[]).filter((t=>!t.cancelled_by_user)),e=(this.usermetadata?.classifications||[]).filter((t=>t.cancelled_by_user));return(this.computedmetadata?.field_classifications||[]).reduce(((t,n)=>(n.classifications.forEach((n=>{const r=t.find((t=>t.label===n.label&&t.labelset===n.labelset)),i=e.find((t=>t.label===n.label&&t.labelset===n.labelset));r||i||t.push({...n,immutable:!0})})),t)),t)}getPositionedNamedEntities(t,e){const n=this.data[t]?.[e]?.extracted?.metadata?.metadata.positions;return n?Object.entries(n).reduce(((t,[e,n])=>{const r=e.split("/")[0];return n.position.forEach((e=>{t.push({entity:n.entity,family:r,...e})})),t}),[]):[]}formatTitle(t){t=t||"–";try{return decodeURIComponent(t)}catch(e){return t}}getParagraphText(t,e,n){return je(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return je(this.getFieldText(t,e),n.start,n.end)}getFieldText(t,e){const n=`${t}-${e}`;if(!this.fieldTextsCache[n]){const r=this.getFieldData(`${t}s`,e);this.fieldTextsCache[n]=Array.from(r?.extracted?.text?.text||"")}return this.fieldTextsCache[n]}}class He extends Fe{kb;uuid;nuclia;get kbPath(){return`/kb/${this.kb}`}get path(){if(!this.uuid&&!this.slug)throw new Error("Resource must have either uuid or slug");return this.uuid?`${this.kbPath}/resource/${this.uuid}`:`${this.kbPath}/slug/${this.slug}`}constructor(t,e,n){super(n),this.nuclia=t,this.kb=e,this.uuid=n.id}modify(t,e=!0){return this.nuclia.rest.patch(this.path,t,void 0,void 0,e)}delete(t=!0){return this.nuclia.rest.delete(this.path,void 0,t)}reprocess(){return this.nuclia.rest.post(`${this.path}/reprocess`,{},void 0,void 0,!0)}getField(t,e,n=[le.VALUE],r=[he.TEXT,he.SHORTENED_METADATA,he.LINK,he.FILE]){const i=[...n.map((t=>`show=${t}`)),...r.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this.path}/${t}/${e}?${i.join("&")}`)}getThumbnailsUrl(){return Ot(this.getThumbnails().filter((t=>t.uri)).map((t=>this.nuclia.rest.getObjectURL(t.uri))))}deleteField(t,e,n=!1){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`,void 0,n)}setField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}upload(t,e,n,r){return ne(this.nuclia,`${this.path}/file/${t}`,e,!!n,r)}batchUpload(t){return se(this.nuclia,this.path,t,!0)}search(t,e=[],n){return Te(this.nuclia,this.kb,this.path,t,e,n,!0)}find(t,e=[],n){return Se(this.nuclia,this.kb,this.kbPath,t,e,this.uuid?{...n,resource_filters:[this.uuid]}:n)}setLabels(t,e,n,r){const i=Ue(t,e,n,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,n){const r=Pe(t,e,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:r}).pipe(Bt((()=>this.fieldmetadata=r)))}}const ze=(t,e)=>{const n={title:t.title,fullText:t.getExtractedTexts().filter((t=>t)).map((t=>t.text))};t.getClassifications().forEach((t=>{t.labelset&&t.label&&(n[t.labelset]=t.label)}));const r=t.getThumbnails().filter((t=>!!t.uri)).map((t=>`${e}/v1${t.uri}`));return{...n,images:r,...t.getNamedEntities()}},We=t=>{switch(t){case ue.text:case ue.file:case ue.link:case ue.keywordset:return`${t}s`;default:return null}};function Ke(t){return fe[t]}function Ge(t){switch(t){case fe.conversation:return ue.conversation;case fe.datetime:return ue.datetime;case fe.file:return ue.file;case fe.layout:return ue.layout;case fe.keywordset:return ue.keywordset;case fe.link:return ue.link;case fe.text:return ue.text;case fe.generic:return ue.generic;default:return null}}function Me(t){switch(t){case ue.file:return ue.file;case ue.link:return ue.link;case ue.text:return ue.text;case ue.layout:return ue.layout;case ue.conversation:return ue.conversation;case ue.datetime:return ue.datetime;case ue.generic:return ue.generic;default:return null}}var Ve,Je,Xe;!function(t){t.classifier="classifier",t.resource_labeler="resource-labeler",t.paragraph_labeler="paragraph-labeler",t.ner="ner"}(Ve||(Ve={})),function(t){t.finished="finished",t.not_running="not_running",t.running="running",t.started="started",t.stopped="stopped"}(Je||(Je={})),function(t){t.succeeded="succeeded",t.failed="failed",t.stopped="stopped"}(Xe||(Xe={}));class Ye{kb;nuclia;constructor(t,e){this.kb=t,this.nuclia=e}start(t,e){return this.nuclia.rest.post(`${this.kb.path}/train/${t}/start`,e||{})}stop(t){return this.nuclia.rest.post(`${this.kb.path}/train/${t}/stop`,{})}getStatus(t){return this.nuclia.rest.get(`${this.kb.path}/train/${t}/inspect`).pipe(Ut((()=>bt({task:"",status:Je.not_running}))))}getExecutions(t=0){return this.nuclia.rest.get(`${this.kb.path}/train/executions?page=${t}`)}hasModel(t){return this.nuclia.rest.get(`${this.kb.path}/train/${t}/model/model/nuclia.json`).pipe(mt((()=>!0)),Ut((()=>bt(!1))))}}class qe{account;nuclia;tempToken;get path(){return`/kb/${this.id}`}get fullpath(){return`${this.nuclia.regionalBackend}/v1/kb/${this.id}`}constructor(t,e,n){this.nuclia=t,this.account=e,Object.assign(this,n),!n.id&&n.uuid&&(this.id=n.uuid),!n.title&&n.slug&&(this.title=n.slug)}getEntities(t=!1){return this.nuclia.rest.get(`${this.path}/entitiesgroups?show_entities=${t}`).pipe(mt((t=>t.groups)))}getEntitiesGroup(t){return this.nuclia.rest.get(`${this.path}/entitiesgroup/${t}`)}getSynonyms(){return this.nuclia.rest.get(`${this.path}/custom-synonyms`).pipe(mt((t=>t.synonyms)))}getLabels(){return this.nuclia.rest.get(`${this.path}/labelsets`).pipe(mt((t=>t?.labelsets||{})),Ut((()=>bt({}))))}getResource(t,e=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],n=[he.TEXT,he.METADATA,he.LINK,he.FILE]){return this._getResource(t,void 0,e,n)}getResourceBySlug(t,e=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],n=[he.TEXT,he.METADATA,he.LINK,he.FILE]){return this._getResource(void 0,t,e,n)}_getResource(t,e,n=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],r=[he.TEXT,he.METADATA,he.LINK,he.FILE]){const i=[...n.map((t=>`show=${t}`)),...r.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this._getPath(t,e)}?${i.join("&")}`).pipe(mt((t=>new He(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new He(this.nuclia,this.id,t)}chat(t,e,n,r,i){const s=Ne(this.nuclia,this.path,t,e,n,r);return i&&s.subscribe((t=>i(t))),s}find(t,e=[],n){return Se(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return Te(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return xe(this.nuclia,this.id,t,e)}suggest(t,e=!1,n=[]){return _e(this.nuclia,this.id,this.path,t,e,n)}feedback(t,e){return this.nuclia.rest.post(`${this.path}/feedback`,{ident:t,good:e,task:"CHAT",feedback:""})}counters(){return this.nuclia.rest.get(`/kb/${this.id}/counters`)}listResources(t,e){const n=[t?`page=${t}`:"",e?`size=${e}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/resources${n?"?"+n:""}`).pipe(mt((t=>({resources:t.resources.map((t=>new He(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(this.tempToken&&this.tempToken.expiration>Date.now())return bt(this.tempToken.token);const t=this.account||this.nuclia.options.account,e=this.slug||this.nuclia.options.kbSlug;let n;if(this.nuclia.options.standalone)n=this.nuclia.rest.get("/temp-access-token");else{if(!t||!e)throw new Error("Account and KB slug are required to get a temp token");n=this.nuclia.rest.post(`/account/${t}/kb/${e}/ephemeral_tokens`,{})}return n.pipe(mt((t=>t.token)),Bt((t=>this.tempToken={token:t,expiration:Date.now()+3e5})))}listActivity(t,e,n){const r=[t?`type=${t}`:"",e?`page=${e}`:"",n?`size=${n}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/activity${r?"?"+r:""}`)}listActivityDownloads(t){return this.nuclia.rest.get(`/kb/${this.id}/activity/downloads?type=${t}`)}downloadActivity(t,e){return this.nuclia.rest.get(`/kb/${this.id}/activity/download?type=${t}&month=${e}`,{},!0).pipe(jt((t=>gt(t.blob()))))}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ze extends qe{admin;contrib;_training;get training(){return this._training||(this._training=new Ye(this,this.nuclia)),this._training}modify(t){const e="local"===this.account?`/kb/${this.id}`:`/account/${this.account}/kb/${this.slug}`;return this.nuclia.rest.patch(e,t)}publish(t){return this.modify({state:t?"PUBLISHED":"PRIVATE"})}delete(){const t="local"===this.account?`/kb/${this.id}`:`/account/${this.account}/kb/${this.slug}`;return this.nuclia.rest.delete(t)}createEntitiesGroup(t,e){return this.nuclia.rest.post(`${this.path}/entitiesgroups`,{...e,group:t})}updateEntitiesGroup(t,e){return this.nuclia.rest.patch(`${this.path}/entitiesgroup/${t}`,e)}deleteEntitiesGroup(t){return this.nuclia.rest.delete(`${this.path}/entitiesgroup/${t}`)}setLabelSet(t,e){return this.nuclia.rest.post(`${this.path}/labelset/${t}`,e)}deleteLabelSet(t){return this.nuclia.rest.delete(`${this.path}/labelset/${t}`)}setSynonyms(t){return this.nuclia.rest.put(`${this.path}/custom-synonyms`,{synonyms:t})}deleteAllSynonyms(){return this.nuclia.rest.delete(`${this.path}/custom-synonyms`)}createResource(t,e=!0){return this.nuclia.rest.post(`${this.path}/resources`,t,void 0,void 0,e)}createLinkResource(t,e,n=!0,r){return this.createResource({links:{link:t},usermetadata:e,title:t.uri,icon:"application/stf-link",...r?{origin:r}:{}},n)}hasResource(t){return this.nuclia.rest.get(`${this.path}/slug/${t}`).pipe(mt((()=>!0)),Ut((()=>bt(!1))))}createOrUpdateResource(t,e=!0){return(t.slug?this.hasResource(t.slug):bt(!1)).pipe(jt((n=>n?this.getResourceFromData({id:"",slug:t.slug}).modify(t,e):this.createResource(t,e))))}upload(t,e,n){return ne(this.nuclia,`/kb/${this.id}`,t,!!e,n)}batchUpload(t){return se(this.nuclia,`/kb/${this.id}`,t,!1)}getServiceAccounts(){return this.nuclia.rest.get(`/account/${this.account}/kb/${this.slug}/service_accounts`)}createServiceAccount(t){return this.nuclia.rest.post(`/account/${this.account}/kb/${this.slug}/service_accounts`,t)}deleteServiceAccount(t){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}/service_account/${t}`)}createKey(t,e){return this.nuclia.rest.post(`/account/${this.account}/kb/${this.slug}/service_account/${t}/keys`,{expires:e})}createKeyForService(t,e){return this.getServiceAccounts().pipe(jt((e=>{const n=e.find((e=>e.title===t.title&&e.role===t.role));return n?bt(n):this.createServiceAccount(t).pipe(jt((()=>this.getServiceAccounts())),mt((e=>e.find((e=>e.title===t.title&&e.role===t.role)))))})),jt((t=>t?this.createKey(t.id,e):bt({token:""}))))}deleteKey(t,e){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}/service_account/${t}/key/${e}`)}setConfiguration(t){return this.nuclia.rest.patch(`/kb/${this.id}/configuration`,t)}}var Qe,tn;!function(t){t.RESOURCES="RESOURCES",t.PARAGRAPHS="PARAGRAPHS",t.SELECTIONS="SELECTIONS"}(Qe||(Qe={})),function(t){t.VISITED="VISITED",t.MODIFIED="MODIFIED",t.DELETED="DELETED",t.NEW="NEW",t.STARTED="STARTED",t.STOPPED="STOPPED",t.SEARCH="SEARCH",t.PROCESSED="PROCESSED",t.CHAT="CHAT"}(tn||(tn={}));class en{nuclia;constructor(t){this.nuclia=t}getAccounts(){return this.nuclia.rest.get("/accounts")}createAccount(t){return this.nuclia.rest.post("/accounts",t)}modifyAccount(t,e){return this.nuclia.rest.patch(`/account/${t}`,e)}deleteAccount(t){return this.nuclia.rest.delete(`/account/${t}`)}getAccountStatus(t){return this.nuclia.rest.get(`/account/${t}/status`)}getWelcome(){return this.nuclia.rest.get("/user/welcome")}getAccount(t){if(!(t=t||this.nuclia.options.account))throw new Error("Account is not set");return this.nuclia.rest.get(`/account/${t}`)}getStandaloneKbs(){return this.nuclia.rest.get("/kbs").pipe(mt((t=>t.kbs)))}getKnowledgeBoxes(t){return this.nuclia.rest.get(`/account/${t}/kbs`)}getKnowledgeBox(t,e){if(t=t||this.nuclia.options.account){const n=e||this.nuclia.options.knowledgeBox||this.nuclia.options.kbSlug;if(!n)throw new Error("account and knowledgeBox must be defined in the Nuclia options");const r=this.nuclia.options.standalone?`/kb/${n}`:`/account/${t}/kb/${n}`;return this.nuclia.rest.get(r).pipe(jt((t=>this.nuclia.options.zone||this.nuclia.options.standalone?bt(t):this.nuclia.rest.getZoneSlug(t.zone).pipe(Bt((t=>this.nuclia.options.zone=t)),mt((()=>t))))),mt((e=>new Ze(this.nuclia,t,e))))}if(!this.nuclia.options.knowledgeBox||!this.nuclia.options.zone)throw new Error("zone must be defined in the Nuclia options");return bt(new Ze(this.nuclia,"",{id:this.nuclia.options.knowledgeBox,zone:this.nuclia.options.zone}))}createKnowledgeBox(t,e){return this.nuclia.rest.post(this.nuclia.options.standalone?"/kbs":`/account/${t}/kbs`,e).pipe(jt((n=>{const r=n.id||n.uuid;if(!r)throw"KnowledgeBox creation failed";return this.getKnowledgeBox(t,this.nuclia.options.standalone?r:e.slug)})))}getStats(t,e,n,r=Xt.DAY,i){const s=[`period=${r}`,`stats=${e}`];return i&&s.push(`utctime=${i}`),n&&s.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${t}/stats?${s.join("&")}`).pipe(mt((t=>t.data)),Ct((t=>!!t)))}upload(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /process");return oe(this.nuclia,this.getNUAKey(),t,{md5:t.md5}).pipe(jt((t=>this.nuclia.rest.post("/processing/push",{filefield:{file:t}},this.getNUAHeader()))))}pull(){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /processing");return this.nuclia.rest.get("/processing/pull",this.getNUAHeader())}getProcessingStatus(t){if(!t){if(!this.hasNUAClient())throw new Error("NUA key or account id is needed to be able to call /processing/status")}const e=t?`/processing/status?account_id=${t}`:"/processing/status",n=t?void 0:this.getNUAHeader();return this.nuclia.rest.get(e,n)}getProcessingStats(t,e){const n=this.hasNUAClient();if(!e&&!n)throw new Error("NUA key or account id is needed to be able to call /processing/stats");const r=n?"/processing/stats"+(t?"?period="+t:""):`/processing/stats?account_id=${e}${t?"&period="+t:""}`,i=n?this.getNUAHeader():void 0;return this.nuclia.rest.get(r,i).pipe(mt((t=>t.data)))}getNUAActivity(t,e,n=0){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}/activity?page=${n}`)}getNUAClients(t){return this.nuclia.rest.get(`/account/${t}/nua_clients`).pipe(mt((t=>t.clients)))}getNUAClient(t,e){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}`)}hasNUAClient(){return!!this.getNUAKey()}getNUAKey(){return this.nuclia.options.nuaKey||""}getNUAHeader(){return{"x-stf-nuakey":`Bearer ${this.getNUAKey()}`}}createNUAClient(t,e){const n={...e};return n.webhook&&(n.processing_webhook={uri:n.webhook},delete n.webhook),this.nuclia.rest.post(`/account/${t}/nua_clients`,n).pipe(Ut((n=>{if(409===n.status&&e.client_id)return this.renewNUAClient(t,e.client_id);throw n})),Bt((t=>{"desktop"===this.nuclia.options.client&&(this.nuclia.options.nuaKey=t.token,localStorage.setItem(Mt,t.token))})))}renewNUAClient(t,e){return this.nuclia.rest.put(`/account/${t}/nua_client/${e}/key`,{})}deleteNUAClient(t,e){return this.nuclia.rest.delete(`/account/${t}/nua_client/${e}`)}getLearningConfigurations(){return this.nuclia.rest.get("/learning/configuration/schema")}predictTokens(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /predict");return this.nuclia.rest.get(`/predict/tokens?text=${encodeURIComponent(t)}`,this.getNUAHeader()).pipe(mt((t=>t.tokens)))}}class nn{nuclia;zones;constructor(t){this.nuclia=t}get(t,e,n){return this.fetch("GET",t,void 0,e,n)}post(t,e,n,r,i){return this.fetch("POST",t,e,n,r,i)}put(t,e,n,r,i){return this.fetch("PUT",t,e,n,r,i)}patch(t,e,n,r,i){return this.fetch("PATCH",t,e,n,r,i)}delete(t,e,n){return this.fetch("DELETE",t,void 0,e,!0,n)}head(t,e){return this.fetch("HEAD",t,void 0,e,!0)}getHeaders(t,e,n,r=!1){const i=n&&n["x-stf-nuakey"]?{}:this.nuclia.auth.getAuthHeaders(t,e),s={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return r&&(s["x-synchronous"]=`${r}`),{...s,...n}}fetch(t,e,n,r,i,s=!1){const o=r&&r["content-type"];return gt(fetch(this.getFullUrl(e),{method:t,headers:this.getHeaders(t,e,r,s),body:o?n:JSON.stringify(n)}).then((t=>t.ok?i?t:t.json().then((t=>t),(()=>{console.warn(`${e} did not return a valid JSON`)})):(this.nuclia.events?.emit("api-error",{status:t.status,path:this.getFullUrl(e)}),t.json().then((e=>{throw{status:t.status,body:e}}),(()=>{throw{status:t.status}}))))))}getFullUrl(t){return`${t.startsWith("/account")||t.startsWith("/user")||t.startsWith("/auth")||t.startsWith("/zones")||t.startsWith("/billing")||t.startsWith("/configuration")||t.startsWith("/manage")||t.includes("/activity")&&!t.includes("/activity/download")||this.nuclia.options.standalone?this.nuclia.backend:this.nuclia.regionalBackend}${t.startsWith("/auth")||t.startsWith("/export")||t.startsWith("/billing")||t.startsWith("/configuration")||t.startsWith("/manage")?"":"/v1"}${t}`}getZones(){return this.zones?bt(this.zones):this.get("/zones").pipe(mt((t=>{const e=t.reduce(((t,e)=>(t[e.id]=e.slug,t)),{});return this.zones=e,e})))}getZoneSlug(t){return this.getZones().pipe(mt((e=>e[t])))}getObjectURL(t){return this.get(t,void 0,!0).pipe(jt((t=>gt(t.blob()))),mt((t=>URL.createObjectURL(t))))}getStream(t,e){return t=this.getFullUrl(t),new C((n=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t,void 0),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),r=t.headers,i=t.status;if(e&&t.ok){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:s})=>{e&&(n.next({data:t,incomplete:!1,headers:r}),n.complete()),s&&(t=this.concat(t,s),n.next({data:t,incomplete:!0,headers:r}),i())}))};i()}else n.error({status:i}),n.complete()}))}))}concat(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}}class rn{messages=new B;emit(t,e){this.messages.next({name:t,data:e})}on(t){return this.messages.asObservable().pipe(Ct((e=>e.name===t)),mt((t=>t.data)))}}class sn{options;auth;rest;db;currentShards={};events=new rn;readKb;get backend(){return this.options.backend}get regionalBackend(){return this.options.backend.replace("//",`//${this.options.zone}.`)}get knowledgeBox(){if(!this.options.knowledgeBox||!this.options.zone&&!this.options.standalone)throw new Error("zone and knowledge box id must be defined in the Nuclia options");return this.readKb||(this.readKb=new qe(this,"",{id:this.options.knowledgeBox,zone:this.options.zone||""})),this.readKb}get asyncKnowledgeBox(){return new Proxy(this.knowledgeBox,{get(t,e){const n=Reflect.get(t,e);return"function"==typeof n?(...e)=>function(t,e){var n="object"==typeof e;return new Promise((function(r,i){var s=new $({next:function(t){r(t),s.unsubscribe()},error:i,complete:function(){n?r(e.defaultValue):i(new vt)}});t.subscribe(s)}))}(n.bind(t)(...e)):n}})}constructor(t){this.options=t,this.auth=new Gt(this),this.rest=new nn(this),this.db=new en(this)}}export{Vt as AccountBlockingState,Gt as Authentication,Jt as BlockedFeature,Oe as Chat,me as ConversationFieldData,en as Db,tn as EventType,he as ExtractedDataTypes,ue as FIELD_TYPE,ge as FileFieldData,Ht as JwtHelper,ye as KeywordSetFieldData,qe as KnowledgeBox,Qe as LabelSetKind,ve as LinkFieldData,Mt as NUA_KEY,sn as Nuclia,ce as RESOURCE_STATUS,Fe as ReadableResource,He as Resource,le as ResourceFieldProperties,Qt as ResourceProperties,nn as Rest,fe as SHORT_FIELD_TYPE,pe as Search,de as SortField,Xt as StatsPeriod,Yt as StatsRange,qt as StatsType,ie as TUSuploadFile,be as TextFieldData,Ye as Training,Xe as TrainingExecutionStatus,Je as TrainingStatus,Ve as TrainingType,Zt as USER_PROMPTS,Ze as WritableKnowledgeBox,se as batchUpload,xe as catalog,Ne as chat,Ce as deDuplicateList,Se as find,We as getDataKeyFromFieldType,ke as getEntityFromFilter,Me as getFieldTypeFromString,ae as getFileMetadata,Ae as getFilterFromEntity,we as getFilterFromLabel,Ee as getLabelFromFilter,Be as lengthUnicode,Ke as longToShortFieldType,ze as resourceToAlgoliaFormat,Te as search,Pe as setEntities,Ue as setLabels,Ge as shortToLongFieldType,je as sliceUnicode,_e as suggest,ne as upload,re as uploadFile,oe as uploadToProcess};
var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(t){try{u(r.next(t))}catch(t){s(t)}}function a(t){try{u(r.throw(t))}catch(t){s(t)}}function u(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(o,a)}u((r=r.apply(t,e||[])).next())}))}function i(t,e){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(u){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function s(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,s=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function a(t,e,n){if(n||2===arguments.length)for(var r,i=0,s=e.length;i<s;i++)!r&&i in e||(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return t.concat(r||Array.prototype.slice.call(e))}function u(t){return this instanceof u?(this.v=t,this):new u(t)}function c(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(t){i[t]&&(r[t]=function(e){return new Promise((function(n,r){s.push([t,e,n,r])>1||a(t,e)}))})}function a(t,e){try{(n=i[t](e)).value instanceof u?Promise.resolve(n.value.v).then(c,l):h(s[0][2],n)}catch(t){h(s[0][3],t)}var n}function c(t){a("next",t)}function l(t){a("throw",t)}function h(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}}function l(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=s(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,i){(function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)})(r,i,(e=t[n](e)).done,e.value)}))}}}function h(t){return"function"==typeof t}function d(t){var e=t((function(t){Error.call(t),t.stack=(new Error).stack}));return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var f=d((function(t){return function(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}}));function p(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var g=function(){function t(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}var e;return t.prototype.unsubscribe=function(){var t,e,n,r,i;if(!this.closed){this.closed=!0;var u=this._parentage;if(u)if(this._parentage=null,Array.isArray(u))try{for(var c=s(u),l=c.next();!l.done;l=c.next()){l.value.remove(this)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(e=c.return)&&e.call(c)}finally{if(t)throw t.error}}else u.remove(this);var d=this.initialTeardown;if(h(d))try{d()}catch(t){i=t instanceof f?t.errors:[t]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var g=s(p),b=g.next();!b.done;b=g.next()){var y=b.value;try{v(y)}catch(t){i=null!=i?i:[],t instanceof f?i=a(a([],o(i)),o(t.errors)):i.push(t)}}}catch(t){n={error:t}}finally{try{b&&!b.done&&(r=g.return)&&r.call(g)}finally{if(n)throw n.error}}}if(i)throw new f(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)v(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(e)}},t.prototype._hasParent=function(t){var e=this._parentage;return e===t||Array.isArray(e)&&e.includes(t)},t.prototype._addParent=function(t){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(t),e):e?[e,t]:t},t.prototype._removeParent=function(t){var e=this._parentage;e===t?this._parentage=null:Array.isArray(e)&&p(e,t)},t.prototype.remove=function(e){var n=this._finalizers;n&&p(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),b=g.EMPTY;function y(t){return t instanceof g||t&&"closed"in t&&h(t.remove)&&h(t.add)&&h(t.unsubscribe)}function v(t){h(t)?t():t.unsubscribe()}var m={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},w={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,a([t,e],o(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function E(t){w.setTimeout((function(){throw t}))}function A(){}function k(t){t()}var S=function(t){function n(e){var n=t.call(this)||this;return n.isStopped=!1,e?(n.destination=e,y(e)&&e.add(n)):n.destination=O,n}return e(n,t),n.create=function(t,e,n){return new $(t,e,n)},n.prototype.next=function(t){this.isStopped||this._next(t)},n.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},n.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},n.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},n.prototype._next=function(t){this.destination.next(t)},n.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},n.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},n}(g),T=Function.prototype.bind;function x(t,e){return T.call(t,e)}var _=function(){function t(t){this.partialObserver=t}return t.prototype.next=function(t){var e=this.partialObserver;if(e.next)try{e.next(t)}catch(t){R(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){R(t)}else R(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){R(t)}},t}(),$=function(t){function n(e,n,r){var i,s,o=t.call(this)||this;h(e)||!e?i={next:null!=e?e:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&m.useDeprecatedNextContext?((s=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},i={next:e.next&&x(e.next,s),error:e.error&&x(e.error,s),complete:e.complete&&x(e.complete,s)}):i=e;return o.destination=new _(i),o}return e(n,t),n}(S);function R(t){E(t)}var O={closed:!0,next:A,error:function(t){throw t},complete:A},I="function"==typeof Symbol&&Symbol.observable||"@@observable";function N(t){return t}var C=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r,i=this,s=(r=t)&&r instanceof S||function(t){return t&&h(t.next)&&h(t.error)&&h(t.complete)}(r)&&y(r)?t:new $(t,e,n);return k((function(){var t=i,e=t.operator,n=t.source;s.add(e?e.call(s,n):n?i._subscribe(s):i._trySubscribe(s))})),s},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){t.error(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=U(e))((function(e,r){var i=new $({next:function(e){try{t(e)}catch(t){r(t),i.unsubscribe()}},error:r,complete:e});n.subscribe(i)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[I]=function(){return this},t.prototype.pipe=function(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return(0===(t=e).length?N:1===t.length?t[0]:function(e){return t.reduce((function(t,e){return e(t)}),e)})(this)},t.prototype.toPromise=function(t){var e=this;return new(t=U(t))((function(t,n){var r;e.subscribe((function(t){return r=t}),(function(t){return n(t)}),(function(){return t(r)}))}))},t.create=function(e){return new t(e)},t}();function U(t){var e;return null!==(e=null!=t?t:m.Promise)&&void 0!==e?e:Promise}function P(t){return function(e){if(function(t){return h(null==t?void 0:t.lift)}(e))return e.lift((function(e){try{return t(e,this)}catch(t){this.error(t)}}));throw new TypeError("Unable to lift unknown Observable type")}}function D(t,e,n,r,i){return new L(t,e,n,r,i)}var L=function(t){function n(e,n,r,i,s,o){var a=t.call(this,e)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=n?function(t){try{n(t)}catch(t){e.error(t)}}:t.prototype._next,a._error=i?function(t){try{i(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,a._complete=r?function(){try{r()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return e(n,t),n.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;t.prototype.unsubscribe.call(this),!n&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},n}(S),j=d((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),B=function(t){function n(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return e(n,t),n.prototype.lift=function(t){var e=new F(this,this);return e.operator=t,e},n.prototype._throwIfClosed=function(){if(this.closed)throw new j},n.prototype.next=function(t){var e=this;k((function(){var n,r;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var i=s(e.currentObservers),o=i.next();!o.done;o=i.next()){o.value.next(t)}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}}))},n.prototype.error=function(t){var e=this;k((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var n=e.observers;n.length;)n.shift().error(t)}}))},n.prototype.complete=function(){var t=this;k((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},n.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(n.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),n.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},n.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},n.prototype._innerSubscribe=function(t){var e=this,n=this,r=n.hasError,i=n.isStopped,s=n.observers;return r||i?b:(this.currentObservers=null,s.push(t),new g((function(){e.currentObservers=null,p(s,t)})))},n.prototype._checkFinalizedStatuses=function(t){var e=this,n=e.hasError,r=e.thrownError,i=e.isStopped;n?t.error(r):i&&t.complete()},n.prototype.asObservable=function(){var t=new C;return t.source=this,t},n.create=function(t,e){return new F(t,e)},n}(C),F=function(t){function n(e,n){var r=t.call(this)||this;return r.destination=e,r.source=n,r}return e(n,t),n.prototype.next=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===n||n.call(e,t)},n.prototype.error=function(t){var e,n;null===(n=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===n||n.call(e,t)},n.prototype.complete=function(){var t,e;null===(e=null===(t=this.destination)||void 0===t?void 0:t.complete)||void 0===e||e.call(t)},n.prototype._subscribe=function(t){var e,n;return null!==(n=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==n?n:b},n}(B),H={now:function(){return(H.delegate||Date).now()},delegate:void 0},z=function(t){function n(e,n,r){void 0===e&&(e=1/0),void 0===n&&(n=1/0),void 0===r&&(r=H);var i=t.call(this)||this;return i._bufferSize=e,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,e),i._windowTime=Math.max(1,n),i}return e(n,t),n.prototype.next=function(e){var n=this,r=n.isStopped,i=n._buffer,s=n._infiniteTimeWindow,o=n._timestampProvider,a=n._windowTime;r||(i.push(e),!s&&i.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},n.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),n=this._infiniteTimeWindow,r=this._buffer.slice(),i=0;i<r.length&&!t.closed;i+=n?1:2)t.next(r[i]);return this._checkFinalizedStatuses(t),e},n.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,n=t._timestampProvider,r=t._buffer,i=t._infiniteTimeWindow,s=(i?1:2)*e;if(e<1/0&&s<r.length&&r.splice(0,r.length-s),!i){for(var o=n.now(),a=0,u=1;u<r.length&&r[u]<=o;u+=2)a=u;a&&r.splice(0,a+1)}},n}(B),W=function(t){function n(e,n){return t.call(this)||this}return e(n,t),n.prototype.schedule=function(t,e){return this},n}(g),K=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,a([t,e],o(n)))},G=function(t){return clearInterval(t)},M=function(t){function n(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return e(n,t),n.prototype.schedule=function(t,e){var n;if(void 0===e&&(e=0),this.closed)return this;this.state=t;var r=this.id,i=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(i,r,e)),this.pending=!0,this.delay=e,this.id=null!==(n=this.id)&&void 0!==n?n:this.requestAsyncId(i,this.id,e),this},n.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),K(t.flush.bind(t,this),n)},n.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return e;null!=e&&G(e)},n.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},n.prototype._execute=function(t,e){var n,r=!1;try{this.work(t)}catch(t){r=!0,n=t||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},n.prototype.unsubscribe=function(){if(!this.closed){var e=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,p(r,this),null!=e&&(this.id=this.recycleAsyncId(n,e,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},n}(W),V=function(){function t(e,n){void 0===n&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.schedulerActionCtor(this,t).schedule(n,e)},t.now=H.now,t}(),J=new(function(t){function n(e,n){void 0===n&&(n=V.now);var r=t.call(this,e,n)||this;return r.actions=[],r._active=!1,r}return e(n,t),n.prototype.flush=function(t){var e=this.actions;if(this._active)e.push(t);else{var n;this._active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},n}(V))(M),X=new C((function(t){return t.complete()}));function Y(t){return t&&h(t.schedule)}function q(t){return t[t.length-1]}function Z(t){return Y(q(t))?t.pop():void 0}var Q=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function tt(t){return h(null==t?void 0:t.then)}function et(t){return h(t[I])}function nt(t){return Symbol.asyncIterator&&h(null==t?void 0:t[Symbol.asyncIterator])}function rt(t){return new TypeError("You provided "+(null!==t&&"object"==typeof t?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var it="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function st(t){return h(null==t?void 0:t[it])}function ot(t){return c(this,arguments,(function(){var e,n,r;return i(this,(function(i){switch(i.label){case 0:e=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,u(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,u(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,u(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}}))}))}function at(t){return h(null==t?void 0:t.getReader)}function ut(t){if(t instanceof C)return t;if(null!=t){if(et(t))return i=t,new C((function(t){var e=i[I]();if(h(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(Q(t))return r=t,new C((function(t){for(var e=0;e<r.length&&!t.closed;e++)t.next(r[e]);t.complete()}));if(tt(t))return n=t,new C((function(t){n.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,E)}));if(nt(t))return ct(t);if(st(t))return e=t,new C((function(t){var n,r;try{for(var i=s(e),o=i.next();!o.done;o=i.next()){var a=o.value;if(t.next(a),t.closed)return}}catch(t){n={error:t}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}t.complete()}));if(at(t))return ct(ot(t))}var e,n,r,i;throw rt(t)}function ct(t){return new C((function(e){(function(t,e){var n,s,o,a;return r(this,void 0,void 0,(function(){var r,u;return i(this,(function(i){switch(i.label){case 0:i.trys.push([0,5,6,11]),n=l(t),i.label=1;case 1:return[4,n.next()];case 2:if((s=i.sent()).done)return[3,4];if(r=s.value,e.next(r),e.closed)return[2];i.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=i.sent(),o={error:u},[3,11];case 6:return i.trys.push([6,,9,10]),s&&!s.done&&(a=n.return)?[4,a.call(n)]:[3,8];case 7:i.sent(),i.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}}))}))})(t,e).catch((function(t){return e.error(t)}))}))}function lt(t,e,n,r,i){void 0===r&&(r=0),void 0===i&&(i=!1);var s=e.schedule((function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()}),r);if(t.add(s),!i)return s}function ht(t,e){return void 0===e&&(e=0),P((function(n,r){n.subscribe(D(r,(function(n){return lt(r,t,(function(){return r.next(n)}),e)}),(function(){return lt(r,t,(function(){return r.complete()}),e)}),(function(n){return lt(r,t,(function(){return r.error(n)}),e)})))}))}function dt(t,e){return void 0===e&&(e=0),P((function(n,r){r.add(t.schedule((function(){return n.subscribe(r)}),e))}))}function ft(t,e){if(!t)throw new Error("Iterable cannot be null");return new C((function(n){lt(n,e,(function(){var r=t[Symbol.asyncIterator]();lt(n,e,(function(){r.next().then((function(t){t.done?n.complete():n.next(t.value)}))}),0,!0)}))}))}function pt(t,e){if(null!=t){if(et(t))return function(t,e){return ut(t).pipe(dt(e),ht(e))}(t,e);if(Q(t))return function(t,e){return new C((function(n){var r=0;return e.schedule((function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())}))}))}(t,e);if(tt(t))return function(t,e){return ut(t).pipe(dt(e),ht(e))}(t,e);if(nt(t))return ft(t,e);if(st(t))return function(t,e){return new C((function(n){var r;return lt(n,e,(function(){r=t[it](),lt(n,e,(function(){var t,e,i;try{e=(t=r.next()).value,i=t.done}catch(t){return void n.error(t)}i?n.complete():n.next(e)}),0,!0)})),function(){return h(null==r?void 0:r.return)&&r.return()}}))}(t,e);if(at(t))return function(t,e){return ft(ot(t),e)}(t,e)}throw rt(t)}function gt(t,e){return e?pt(t,e):ut(t)}function bt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return gt(t,Z(t))}function yt(t,e){var n=h(t)?t:function(){return t},r=function(t){return t.error(n())};return new C(e?function(t){return e.schedule(r,0,t)}:r)}var vt=d((function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}}));function mt(t,e){return P((function(n,r){var i=0;n.subscribe(D(r,(function(n){r.next(t.call(e,n,i++))})))}))}var wt=Array.isArray;function Et(t){return mt((function(e){return function(t,e){return wt(e)?t.apply(void 0,a([],o(e))):t(e)}(t,e)}))}var At=Array.isArray,kt=Object.getPrototypeOf,St=Object.prototype,Tt=Object.keys;function xt(t){if(1===t.length){var e=t[0];if(At(e))return{args:e,keys:null};if((r=e)&&"object"==typeof r&&kt(r)===St){var n=Tt(e);return{args:n.map((function(t){return e[t]})),keys:n}}}var r;return{args:t,keys:null}}function _t(t,e,n){return void 0===n&&(n=1/0),h(e)?_t((function(n,r){return mt((function(t,i){return e(n,t,r,i)}))(ut(t(n,r)))}),n):("number"==typeof e&&(n=e),P((function(e,r){return function(t,e,n,r,i,s,o,a){var u=[],c=0,l=0,h=!1,d=function(){!h||u.length||c||e.complete()},f=function(t){return c<r?p(t):u.push(t)},p=function(t){s&&e.next(t),c++;var a=!1;ut(n(t,l++)).subscribe(D(e,(function(t){null==i||i(t),s?f(t):e.next(t)}),(function(){a=!0}),void 0,(function(){if(a)try{c--;for(var t=function(){var t=u.shift();o?lt(e,o,(function(){return p(t)})):p(t)};u.length&&c<r;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(D(e,f,(function(){h=!0,d()}))),function(){null==a||a()}}(e,r,t,n)})))}function $t(t){return void 0===t&&(t=1/0),_t(N,t)}function Rt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $t(1)(gt(t,Z(t)))}function Ot(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=function(t){return h(q(t))?t.pop():void 0}(t),r=xt(t),i=r.args,s=r.keys,o=new C((function(t){var e=i.length;if(e)for(var n=new Array(e),r=e,o=e,a=function(e){var a=!1;ut(i[e]).subscribe(D(t,(function(t){a||(a=!0,o--),n[e]=t}),(function(){return r--}),void 0,(function(){r&&a||(o||t.next(s?function(t,e){return t.reduce((function(t,n,r){return t[n]=e[r],t}),{})}(s,n):n),t.complete())})))},u=0;u<e;u++)a(u);else t.complete()}));return n?o.pipe(Et(n)):o}function It(t,e,n){void 0===t&&(t=0),void 0===n&&(n=J);var r=-1;return null!=e&&(Y(e)?n=e:r=e),new C((function(e){var i,s=(i=t)instanceof Date&&!isNaN(i)?+t-n.now():t;s<0&&(s=0);var o=0;return n.schedule((function(){e.closed||(e.next(o++),0<=r?this.schedule(void 0,r):e.complete())}),s)}))}function Nt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Z(t),r=function(t,e){return"number"==typeof q(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?ut(i[0]):$t(r)(gt(i,n)):X}function Ct(t,e){return P((function(n,r){var i=0;n.subscribe(D(r,(function(n){return t.call(e,n,i++)&&r.next(n)})))}))}function Ut(t){return P((function(e,n){var r,i=null,s=!1;i=e.subscribe(D(n,void 0,void 0,(function(o){r=ut(t(o,Ut(t)(e))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function Pt(t,e){return h(e)?_t(t,e,1):_t(t,1)}function Dt(t){return t<=0?function(){return X}:P((function(e,n){var r=0;e.subscribe(D(n,(function(e){++r<=t&&(n.next(e),t<=r&&n.complete())})))}))}function Lt(t){var e,n,r=1/0;return null!=t&&("object"==typeof t?(e=t.count,r=void 0===e?1/0:e,n=t.delay):r=t),r<=0?function(){return X}:P((function(t,e){var i,s=0,o=function(){if(null==i||i.unsubscribe(),i=null,null!=n){var t="number"==typeof n?It(n):ut(n(s)),r=D(e,(function(){r.unsubscribe(),a()}));t.subscribe(r)}else a()},a=function(){var n=!1;i=t.subscribe(D(e,void 0,(function(){++s<r?i?o():n=!0:e.complete()}))),n&&o()};a()}))}function jt(t,e){return P((function(n,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};n.subscribe(D(r,(function(n){null==i||i.unsubscribe();var o=0,u=s++;ut(t(n,u)).subscribe(i=D(r,(function(t){return r.next(e?e(n,t,u,o++):t)}),(function(){i=null,a()})))}),(function(){o=!0,a()})))}))}function Bt(t,e,n){var r=h(t)||e||n?{next:t,error:e,complete:n}:t;return r?P((function(t,e){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;t.subscribe(D(e,(function(t){var n;null===(n=r.next)||void 0===n||n.call(r,t),e.next(t)}),(function(){var t;i=!1,null===(t=r.complete)||void 0===t||t.call(r),e.complete()}),(function(t){var n;i=!1,null===(n=r.error)||void 0===n||n.call(r,t),e.error(t)}),(function(){var t,e;i&&(null===(t=r.unsubscribe)||void 0===t||t.call(r)),null===(e=r.finalize)||void 0===e||e.call(r)})))})):N}function Ft(t,e){void 0===e&&(e={});var r=e.selector,i=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]])}return n}(e,["selector"]);return new C((function(e){var s=new AbortController,o=s.signal,a=!0,u=i.signal;if(u)if(u.aborted)s.abort();else{var c=function(){o.aborted||s.abort()};u.addEventListener("abort",c),e.add((function(){return u.removeEventListener("abort",c)}))}var l=n(n({},i),{signal:o}),h=function(t){a=!1,e.error(t)};return fetch(t,l).then((function(t){r?ut(r(t)).subscribe(D(e,void 0,(function(){a=!1,e.complete()}),h)):(a=!1,e.next(t),e.complete())})).catch(h),function(){a&&s.abort()}}))}class Ht{token;constructor(t){this.token=t}urlBase64Decode(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("Illegal base64url string!")}return this.b64DecodeUnicode(e)}b64decode(t){let e="";if((t=String(t).replace(/=+$/,"")).length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let n,r,i=0,s=0;r=t.charAt(s++);~r&&(n=i%4?64*n+r:r,i++%4)?e+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return e}b64DecodeUnicode(t){return decodeURIComponent(Array.prototype.map.call(this.b64decode(t),(t=>"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2))).join(""))}decodeToken(t=this.token){if(null===t)return null;const e=t.split(".");if(3!==e.length)throw new Error("The inspected token doesn't appear to be a JWT. Check to make sure it has three parts and see https://jwt.io for more.");const n=this.urlBase64Decode(e[1]);if(!n)throw new Error("Cannot decode the token.");return JSON.parse(n)}getJWTUser(t=this.token){let e;try{e=this.decodeToken(t)}catch(t){return null}return e}getTokenExpirationDate(t=this.token){const e=this.getJWTUser(t);if(!e)return null;const n=new Date(0);return n.setUTCSeconds(e.exp),n}isTokenExpired(t=this.token,e){if(null===t||""===t)return!0;const n=this.getTokenExpirationDate(t);return e=e||0,null===n||n.valueOf()<=(new Date).valueOf()+1e3*e}}const zt="JWT_KEY",Wt="JWT_REFRESH_KEY",Kt=216e5;class Gt{nuclia;_isAuthenticated=new z(1);timerSubscription;constructor(t){this.nuclia=t,this.nuclia.options.knowledgeBox?this._isAuthenticated.next(!0):this.checkTokenExpiration()}getAuthHeaders(t,e){return this.nuclia.options.standalone?{"X-NUCLIADB-ROLES":this.getNucliaDbRole(t,e)}:this.nuclia.options.apiKey?{"X-NUCLIA-SERVICEACCOUNT":`Bearer ${this.nuclia.options.apiKey}`}:this.getToken()?{Authorization:`Bearer ${this.getToken()}`}:{}}getNucliaDbRole(t,e){let n;switch(t){case"PUT":case"PATCH":case"POST":case"DELETE":n="WRITER";break;default:n="READER"}return"/kbs"===e||("PATCH"===t||"DELETE"===t)&&e?.startsWith("/kb")&&3===e?.split("/").length?n="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog")||e?.endsWith("/chat"))&&(n="READER"),n}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Ct((function(e,n){return t<=n}))),Ct((t=>!t)));var t}login(t,e,n){return this.fetch("/auth/login",{username:t,password:e},!1,n?{"X-STF-VALIDATION":n}:{}).pipe(mt((t=>this.authenticate(t))))}authenticate(t){return t.access_token?(this.storeTokens(t),this._isAuthenticated.next(!0),!0):(this._isAuthenticated.next(!1),!1)}logout(){this.fetch("/auth/logout",{},!0,{}).subscribe(),localStorage.removeItem(zt),localStorage.removeItem(Wt),this._isAuthenticated.next(!1)}refresh(){return this.fetch("/auth/refresh",{refresh_token:this.getRefreshToken()},!0,{}).pipe(Ut((t=>(this.logout(),yt(t)))),mt((t=>t.access_token?(this.storeTokens(t),!0):(this.logout(),!1))))}getToken(){return this.nuclia.options.public?"":localStorage.getItem(zt)||""}setPassword(t){return this.fetch("/auth/setpassword",{password:t},!0,{}).pipe(mt((t=>this.authenticate(t))))}deleteAuthenticatedUser(){return this.nuclia.rest.delete("/user").pipe(Bt((()=>this.storeTokens({access_token:"",refresh_token:""}))))}getJWTUser(){const t=this.getToken();if(t){return new Ht(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(Wt)||""}storeTokens(t){localStorage.setItem(zt,t.access_token),localStorage.setItem(Wt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new Ht(t),n=e.getTokenExpirationDate()?.getTime();if(n){const t=(new Date).getTime();if(n<t)this.logout();else{this._isAuthenticated.next(!0);const e=n-t<Kt?0:Kt;this.timerSubscription?.unsubscribe(),this.timerSubscription=It(e).pipe(jt((()=>this.refresh()))).subscribe()}}else this._isAuthenticated.next(!1)}else this._isAuthenticated.next(!1)}fetch(t,e,n,r){const i={"content-type":"application/json",...r};return n&&(i.Authorization=`Bearer ${this.getToken()}`),Ft(`${this.nuclia.backend}${t}`,{method:"POST",selector:t=>Promise.resolve(t),headers:i,body:JSON.stringify(e)}).pipe(jt((t=>t.ok?gt(t.clone().json()):yt(t))))}}const Mt="NUCLIA_NUA_KEY";var Vt,Jt,Xt,Yt,qt;!function(t){t.UNBLOCKED="unblocked",t.QUOTA="quota",t.MANAGER="manager"}(Vt||(Vt={})),function(t){t.UPLOAD="upload",t.PROCESSING="processing",t.SEARCH="search",t.GENERATIVE="generative",t.TRAINING="training",t.PUBLIC_UPLOAD="public_upload",t.PUBLIC_PROCESSING="public_processing",t.PUBLIC_SEARCH="public_search",t.PUBLIC_GENERATIVE="public_generative"}(Jt||(Jt={})),function(t){t.DAY="day",t.WEEK="week",t.MONTH="month",t.YEAR="year"}(Xt||(Xt={})),function(t){t.anHour="1h",t.twoHours="2h",t.threeHours="3h",t.sixHours="6h",t.twelveHours="12h",t.twentyFourHours="24h",t.fortyHeightHours="48h"}(Yt||(Yt={})),function(t){t.PROCESSING_TIME="processing_time",t.SEARCHES="searches",t.CHARS="chars",t.MEDIA_SECONDS="media_seconds",t.BYTES="bytes",t.RESOURCES="resources",t.PAGES="pages",t.TRAIN_SECONDS="train_seconds",t.SUGGESTIONS="suggestions",t.DOCS_NO_MEDIA="docs_no_media"}(qt||(qt={}));const Zt="user_prompts";var Qt;!function(t){t.BASIC="basic",t.ORIGIN="origin",t.RELATIONS="relations",t.VALUES="values",t.EXTRACTED="extracted",t.ERRORS="errors",t.EXTRA="extra"}(Qt||(Qt={}));const te=524288,ee=new RegExp(/[^a-z0-9_-]/g),ne=(t,e,n,r,i={})=>(i.contentType||n instanceof ArrayBuffer||(i.contentType="null"!==n?.type?n?.type:void 0),i.filename||n instanceof ArrayBuffer||(i.filename=n?.name),i.lang||n instanceof ArrayBuffer||(i.lang=n.lang),i.md5||n instanceof ArrayBuffer||(i.md5=n.md5),(n instanceof ArrayBuffer?bt(n):gt(n.arrayBuffer())).pipe(jt((s=>r?ie(t,e,s,i,n.payload):re(t,e,s,i))))),re=(t,e,n,r)=>{const i={"content-type":r?.contentType||"application/octet-stream",...ae(r)};let s=1;const o=r?.rslug?`?rslug=${r.rslug}`:"";return t.rest.post(`${e}/upload${o}`,n,i,!0).pipe(Lt(),Ct((t=>0==s--||503!==t.status)),Dt(1),jt((t=>{try{switch(t.status){case 201:return gt(t.json()).pipe(mt((t=>({resource:t.uuid||"",field:t.field_id||"",completed:!0}))));case 409:return bt({conflict:!0});default:return bt({failed:!0})}}catch(t){return bt({failed:!0})}})))},ie=(t,e,n,r,i)=>{let s=0,o=0,a=!1;const u=n.byteLength,c=Math.ceil(u/te),l={"upload-length":`${u}`,"tus-resumable":"1.0.0"},h=[];r?.filename&&h.push(`filename ${btoa(encodeURIComponent(r.filename))}`),r?.lang&&h.push(`language ${btoa(r.lang)}`),r?.md5&&h.push(`md5 ${btoa(r.md5)}`),h.push(`content_type ${btoa(r?.contentType||"application/octet-stream")}`),h.length>0&&(l["upload-metadata"]=h.join(","));let d=1;return t.rest.post(`${e}/tusupload`,i,l,!0).pipe(Lt(),Ct((t=>0==d--||503!==t.status)),Ut((t=>bt(t))),Dt(1),Pt((e=>Nt(bt(e).pipe(Ct((t=>201!==t.status||!t.headers.get("location"))),mt((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),bt(e).pipe(Ct((t=>201===t.status&&!!t.headers.get("location"))),mt((t=>t.headers.get("location"))),Pt((e=>function(t,e,n){if(null==e&&(e=t,t=0),e<=0)return X;var r=e+t;return new C(n?function(e){var i=t;return n.schedule((function(){i<r?(e.next(i++),this.schedule()):e.complete()}))}:function(e){for(var n=t;n<r&&!e.closed;)e.next(n++);e.complete()})}(0,c).pipe(Pt((()=>{const i=n.slice(s,s+te);return o+=1,a?bt({failed:a}):t.rest.patch(e,i,{"content-type":r?.contentType||"application/octet-stream","upload-offset":`${s}`,"content-length":`${i.byteLength}`},!0).pipe(mt((t=>200!==t.status?(a=!0,{failed:a}):(s+=te,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Ut((()=>(a=!0,bt({failed:!0})))))}))))))))))},se=(t,e,n,r=!1)=>{const i=Array.from(n),s=i.reduce(((t,e)=>t+(e.size||0)),0),o=[],a=i.map((t=>({file:t,progress:0,uploaded:!1,failed:!1})));return gt(i.map((n=>{let i=e;if(r){let t=n.name.toLowerCase().replace(ee,"_");o.includes(t)&&(t+="_"+o.filter((e=>e.startsWith(t))).length),o.push(t),i=`${i}/file/${t}`}const s=n.lang;if(s){const t=n.payload||{};n.payload={...t,metadata:{...t?.metadata,language:s}}}return ne(t,i,n,!0,{}).pipe(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Z(t);return P((function(e,r){(n?Rt(t,e,n):Rt(t,e)).subscribe(r)}))}({progress:0,completed:!1}),mt((t=>({status:t,file:n}))))}))).pipe(_t((t=>t),6),mt((t=>{const e=a.find((e=>e.file===t.file));t.status.failed&&(e.failed=!0),t.status.conflict&&(e.conflicts=!0),t.status.completed&&(e.uploaded=!0),t.status.failed||t.status.conflict||t.status.completed?e.progress=100:e.progress=t.status.progress||0;const n=a.filter((t=>t.failed)).length,r=a.filter((t=>t.conflicts)).length,i=a.filter((t=>t.uploaded)).length,o=0===a.filter((t=>!t.failed&&!t.uploaded)).length,u=Math.round(a.reduce(((t,e)=>t+e.file.size*e.progress/100),0)/s*100);return{files:a,progress:u,completed:o,uploaded:i,failed:n,conflicts:r}})))},oe=(t,e,n,r)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":r?.contentType||"application/octet-stream",...ae(r)};return t.rest.post("/processing/upload",n,i)},ae=t=>{const e={};return t?.filename&&(e["x-filename"]=encodeURIComponent(t.filename)),t?.md5&&(e["x-md5"]=t.md5),t?.lang&&(e["x-language"]=t.lang),e};var ue,ce,le,he,de,fe,pe;!function(t){t.text="text",t.file="file",t.link="link",t.layout="layout",t.conversation="conversation",t.keywordset="keywordset",t.datetime="datetime",t.generic="generic"}(ue||(ue={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(ce||(ce={}));class ge{value;extracted;error}class be{value;extracted;error}class ye{value;extracted;error}class ve{value;extracted;error}class me{value;extracted;error}function we(t){return`/l/${t.labelset}/${t.label}`}function Ee(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}function Ae(t){return`/e/${t.family}/${t.entity}`}function ke(t){const e=t.split("/");return{family:e[2],entity:e[3]}}!function(t){t.VALUE="value",t.EXTRACTED="extracted",t.ERROR="error"}(le||(le={})),function(t){t.TEXT="text",t.METADATA="metadata",t.SHORTENED_METADATA="shortened_metadata",t.LARGE_METADATA="large_metadata",t.VECTOR="vectors",t.LINK="link",t.FILE="file"}(he||(he={})),function(t){t.created="created",t.modified="modified",t.title="title"}(de||(de={})),function(t){t.layout="l",t.text="t",t.file="f",t.link="u",t.datetime="d",t.keywordset="k",t.generic="a",t.conversation="c"}(fe||(fe={})),function(t){var e,n,r,i;(e=t.Features||(t.Features={})).PARAGRAPH="paragraph",e.DOCUMENT="document",e.RELATIONS="relations",e.VECTOR="vector",(n=t.ResourceFeatures||(t.ResourceFeatures={})).PARAGRAPH="paragraph",n.RELATIONS="relations",n.VECTOR="vector",(r=t.SuggestionFeatures||(t.SuggestionFeatures={})).PARAGRAPH="paragraph",r.ENTITIES="entities",r.INTENT="intent",(i=t.FindScoreType||(t.FindScoreType={})).VECTOR="VECTOR",i.BM25="BM25",i.BOTH="BOTH"}(pe||(pe={}));const Se=(t,e,n,r,i=[],s,o)=>{const{inTitleOnly:a,...u}=s||{},c={query:r||"",features:i};a&&(c.fields=["a/title"]),c.shards=t.currentShards?.[e]||[];const l=`${n}/find`;return(o?t.rest.get(`${l}?${Re(c,u)}`,void 0,!0):t.rest.post(l,{...c,...u},void 0,!0)).pipe(jt((e=>{const n=e.headers.get("X-Nuclia-Trace-Id")||"";return e.ok&&206!==e.status?gt(e.json().then((t=>({...t,searchId:n})),(()=>{console.warn(`${l} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...c,...u}),gt(e.json().then((t=>{throw{status:e.status,body:t}}),(()=>{throw{status:e.status}}))))})),Ut((t=>bt({type:"error",status:t.status,detail:t.detail,body:t.body}))),mt((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((n=>{"findResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))},Te=(t,e,n,r,i=[],s,o)=>{const{inTitleOnly:a,...u}=s||{},c={query:r||"",features:i};a&&(c.fields=["a/title"]),c.shards=t.currentShards?.[e]||[];const l=o?t.rest.get(`${n}/search?${Re(c,u)}`):t.rest.post(`${n}/search`,{...c,...u});return $e(t,e,l)},xe=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${r?Re(i,r):""}`);return $e(t,e,s)},_e=(t,e,n,r,i,s)=>{const o={query:r||"",features:s};return i&&(o.fields=["a/title"]),t.rest.get(`${n}/suggest?${Re(o,{})}`).pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"suggestions"})))};function $e(t,e,n){return n.pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"searchResults"})),Bt((n=>{"searchResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))}const Re=(t,e)=>{Object.entries(e||{}).forEach((([e,n])=>{null!=n&&(Array.isArray(n)?t[e]=n.map((t=>`${t}`)):"object"==typeof n?Object.entries(n).forEach((([n,r])=>t[`${e}_${n}`]=`${r}`)):t[e]=`${n}`)}));const n=new URLSearchParams;return Object.entries(t).forEach((([t,e])=>Array.isArray(e)?e.forEach((e=>n.append(t,e))):n.append(t,e))),n.toString()};var Oe;!function(t){var e,n;(e=t.Features||(t.Features={})).PARAGRAPHS="paragraphs",e.RELATIONS="relations",(n=t.Author||(t.Author={})).USER="USER",n.NUCLIA="NUCLIA"}(Oe||(Oe={}));const Ie="_END_";function Ne(t,e,n,r=[],i=[Oe.Features.PARAGRAPHS],s={}){let o,a,u=0,c="";const{synchronous:l,...h}=s,d=`${e}/chat`,f={query:n,context:r,show:[Qt.BASIC,Qt.VALUES],features:i.length>0?i:void 0,...h};return l?t.rest.post(d,f,void 0,void 0,!0).pipe(mt((({answer:t,relations:e,results:n})=>({type:"answer",text:t,sources:{...n,relations:e},incomplete:!1,id:""})))):t.rest.getStream(d,f).pipe(mt((({data:t,incomplete:e,headers:n})=>{const r=n.get("X-Nuclia-Trace-Id")||"",i=n.get("NUCLIA-LEARNING-ID")||"";if(0===u&&t.length>=4&&(u=new DataView(t.buffer.slice(0,4)).getUint32(0)),!o&&u>0&&t.length>u+4){const e=t.slice(4,u+4);o=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}if(o&&(o.searchId=r),o&&t.length>u+4&&(c=(new TextDecoder).decode(t.slice(u+4).buffer),c.includes(Ie))){let t;if([c,t]=c.split(Ie),t)try{a=JSON.parse(atob(t)),o.relations=a}catch(t){console.warn(t)}}return{type:"answer",text:c,sources:o,incomplete:e,id:i}})),Ut((t=>bt({type:"error",status:t.status,detail:t.detail||""}))))}const Ce=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),Ue=(t,e,n,r,i)=>{const s=Ce(i.filter((n=>De(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=Ce(i.filter((n=>Le(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==n)),a=i.filter((n=>n.field.field!==t||n.field.field_type!==e)),u=r.length>0?[...o,{key:n,classifications:r}]:o;return s.length>0||u.length>0?[...a,{field:{field:t,field_type:e},token:s.length>0?s:void 0,paragraphs:u.length>0?u:void 0}]:a},Pe=(t,e,n,r)=>{const i=Ce(r.filter((n=>Le(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),s=r.filter((n=>n.field.field!==t||n.field.field_type!==e));return n.length>0||i.length>0?[...s,{field:{field:t,field_type:e},token:n.length>0?n:void 0,paragraphs:i.length>0?i:void 0}]:s},De=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,Le=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,je=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Be=t=>t?Array.from(t).length:0;class Fe{data={};fieldTextsCache={};constructor(t){t.data||(t.data={}),Object.assign(this,{...t,title:this.formatTitle(t.title)})}getFields(t=["files","links","texts","keywordsets"]){return Object.entries(this.data).filter((([e])=>t.includes(e))).map((([,t])=>t)).filter((t=>!!t)).map((t=>Object.values(t))).reduce(((t,e)=>t.concat(e)),[])}getFieldData(t,e){const n=this.data[t]?.[e];return n||void 0}getExtractedSummaries(){return this.getFields().filter((t=>t.extracted?.metadata?.metadata?.summary)).map((t=>t.extracted.metadata.metadata.summary))}getExtractedTexts(){return this.getFields().filter((t=>t.extracted?.text)).map((t=>t.extracted.text))}getFiles(){return this.getFields(["files"]).filter((t=>!!t&&!!t.value&&!!t.value.file)).map((t=>t.value.file))}getThumbnails(){return this.getFields(["files"]).map((t=>t.extracted?.file?.file_thumbnail)).concat(this.getFields(["links"]).map((t=>t.extracted?.link?.link_thumbnail))).filter((t=>!!t))}getAnnotatedEntities(){return(this.fieldmetadata||[]).filter((t=>t.token&&t.token.length>0)).map((t=>t.token)).reduce(((t,e)=>(e.filter((t=>!t.cancelled_by_user)).forEach((e=>{t[e.klass]||(t[e.klass]=[]),t[e.klass].push(e.token)})),t)),{})}getNamedEntities(){return this.getFields().filter((t=>t.extracted?.metadata?.metadata?.ner)).map((t=>Object.entries(t.extracted.metadata.metadata.ner).reduce(((t,[e,n])=>(t[n]=(t[n]||[]).concat([e]),t)),{}))).reduce(((t,e)=>(Object.entries(e).forEach((([e,n])=>{t[e]=(t[e]||[]).concat(n)})),t)),{})}getClassifications(){const t=(this.usermetadata?.classifications||[]).filter((t=>!t.cancelled_by_user)),e=(this.usermetadata?.classifications||[]).filter((t=>t.cancelled_by_user));return(this.computedmetadata?.field_classifications||[]).reduce(((t,n)=>(n.classifications.forEach((n=>{const r=t.find((t=>t.label===n.label&&t.labelset===n.labelset)),i=e.find((t=>t.label===n.label&&t.labelset===n.labelset));r||i||t.push({...n,immutable:!0})})),t)),t)}getPositionedNamedEntities(t,e){const n=this.data[t]?.[e]?.extracted?.metadata?.metadata.positions;return n?Object.entries(n).reduce(((t,[e,n])=>{const r=e.split("/")[0];return n.position.forEach((e=>{t.push({entity:n.entity,family:r,...e})})),t}),[]):[]}formatTitle(t){t=t||"–";try{return decodeURIComponent(t)}catch(e){return t}}getParagraphText(t,e,n){return je(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return je(this.getFieldText(t,e),n.start,n.end)}getFieldText(t,e){const n=`${t}-${e}`;if(!this.fieldTextsCache[n]){const r=this.getFieldData(`${t}s`,e);this.fieldTextsCache[n]=Array.from(r?.extracted?.text?.text||"")}return this.fieldTextsCache[n]}}class He extends Fe{kb;uuid;nuclia;get kbPath(){return`/kb/${this.kb}`}get path(){if(!this.uuid&&!this.slug)throw new Error("Resource must have either uuid or slug");return this.uuid?`${this.kbPath}/resource/${this.uuid}`:`${this.kbPath}/slug/${this.slug}`}constructor(t,e,n){super(n),this.nuclia=t,this.kb=e,this.uuid=n.id}modify(t,e=!0){return this.nuclia.rest.patch(this.path,t,void 0,void 0,e)}delete(t=!0){return this.nuclia.rest.delete(this.path,void 0,t)}reprocess(){return this.nuclia.rest.post(`${this.path}/reprocess`,{},void 0,void 0,!0)}getField(t,e,n=[le.VALUE],r=[he.TEXT,he.SHORTENED_METADATA,he.LINK,he.FILE]){const i=[...n.map((t=>`show=${t}`)),...r.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this.path}/${t}/${e}?${i.join("&")}`)}getThumbnailsUrl(){return Ot(this.getThumbnails().filter((t=>t.uri)).map((t=>this.nuclia.rest.getObjectURL(t.uri))))}deleteField(t,e,n=!1){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`,void 0,n)}setField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}upload(t,e,n,r){return ne(this.nuclia,`${this.path}/file/${t}`,e,!!n,r)}batchUpload(t){return se(this.nuclia,this.path,t,!0)}search(t,e=[],n){return Te(this.nuclia,this.kb,this.path,t,e,n,!0)}find(t,e=[],n){return Se(this.nuclia,this.kb,this.kbPath,t,e,this.uuid?{...n,resource_filters:[this.uuid]}:n)}setLabels(t,e,n,r){const i=Ue(t,e,n,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,n){const r=Pe(t,e,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:r}).pipe(Bt((()=>this.fieldmetadata=r)))}}const ze=(t,e)=>{const n={title:t.title,fullText:t.getExtractedTexts().filter((t=>t)).map((t=>t.text))};t.getClassifications().forEach((t=>{t.labelset&&t.label&&(n[t.labelset]=t.label)}));const r=t.getThumbnails().filter((t=>!!t.uri)).map((t=>`${e}/v1${t.uri}`));return{...n,images:r,...t.getNamedEntities()}},We=t=>{switch(t){case ue.text:case ue.file:case ue.link:case ue.keywordset:return`${t}s`;default:return null}};function Ke(t){return fe[t]}function Ge(t){switch(t){case fe.conversation:return ue.conversation;case fe.datetime:return ue.datetime;case fe.file:return ue.file;case fe.layout:return ue.layout;case fe.keywordset:return ue.keywordset;case fe.link:return ue.link;case fe.text:return ue.text;case fe.generic:return ue.generic;default:return null}}function Me(t){switch(t){case ue.file:return ue.file;case ue.link:return ue.link;case ue.text:return ue.text;case ue.layout:return ue.layout;case ue.conversation:return ue.conversation;case ue.datetime:return ue.datetime;case ue.generic:return ue.generic;default:return null}}var Ve,Je,Xe;!function(t){t.classifier="classifier",t.resource_labeler="resource-labeler",t.paragraph_labeler="paragraph-labeler",t.ner="ner"}(Ve||(Ve={})),function(t){t.finished="finished",t.not_running="not_running",t.running="running",t.started="started",t.stopped="stopped"}(Je||(Je={})),function(t){t.succeeded="succeeded",t.failed="failed",t.stopped="stopped"}(Xe||(Xe={}));class Ye{kb;nuclia;constructor(t,e){this.kb=t,this.nuclia=e}start(t,e){return this.nuclia.rest.post(`${this.kb.path}/train/${t}/start`,e||{})}stop(t){return this.nuclia.rest.post(`${this.kb.path}/train/${t}/stop`,{})}getStatus(t){return this.nuclia.rest.get(`${this.kb.path}/train/${t}/inspect`).pipe(Ut((()=>bt({task:"",status:Je.not_running}))))}getExecutions(t=0){return this.nuclia.rest.get(`${this.kb.path}/train/executions?page=${t}`)}hasModel(t){return this.nuclia.rest.get(`${this.kb.path}/train/${t}/model/model/nuclia.json`).pipe(mt((()=>!0)),Ut((()=>bt(!1))))}}class qe{account;nuclia;tempToken;get path(){return`/kb/${this.id}`}get fullpath(){return`${this.nuclia.regionalBackend}/v1/kb/${this.id}`}constructor(t,e,n){this.nuclia=t,this.account=e,Object.assign(this,n),!n.id&&n.uuid&&(this.id=n.uuid),!n.title&&n.slug&&(this.title=n.slug)}getEntities(t=!1){return this.nuclia.rest.get(`${this.path}/entitiesgroups?show_entities=${t}`).pipe(mt((t=>t.groups)))}getEntitiesGroup(t){return this.nuclia.rest.get(`${this.path}/entitiesgroup/${t}`)}getSynonyms(){return this.nuclia.rest.get(`${this.path}/custom-synonyms`).pipe(mt((t=>t.synonyms)))}getLabels(){return this.nuclia.rest.get(`${this.path}/labelsets`).pipe(mt((t=>t?.labelsets||{})),Ut((()=>bt({}))))}getResource(t,e=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],n=[he.TEXT,he.METADATA,he.LINK,he.FILE]){return this._getResource(t,void 0,e,n)}getResourceBySlug(t,e=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],n=[he.TEXT,he.METADATA,he.LINK,he.FILE]){return this._getResource(void 0,t,e,n)}_getResource(t,e,n=[Qt.BASIC,Qt.ORIGIN,Qt.RELATIONS,Qt.VALUES,Qt.EXTRACTED,Qt.ERRORS],r=[he.TEXT,he.METADATA,he.LINK,he.FILE]){const i=[...n.map((t=>`show=${t}`)),...r.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this._getPath(t,e)}?${i.join("&")}`).pipe(mt((t=>new He(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new He(this.nuclia,this.id,t)}chat(t,e,n,r,i){const s=Ne(this.nuclia,this.path,t,e,n,r);return i?(s.subscribe((t=>i(t))),bt(null)):s}find(t,e=[],n){return Se(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return Te(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return xe(this.nuclia,this.id,t,e)}suggest(t,e=!1,n=[]){return _e(this.nuclia,this.id,this.path,t,e,n)}feedback(t,e){return this.nuclia.rest.post(`${this.path}/feedback`,{ident:t,good:e,task:"CHAT",feedback:""})}counters(){return this.nuclia.rest.get(`/kb/${this.id}/counters`)}listResources(t,e){const n=[t?`page=${t}`:"",e?`size=${e}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/resources${n?"?"+n:""}`).pipe(mt((t=>({resources:t.resources.map((t=>new He(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(this.tempToken&&this.tempToken.expiration>Date.now())return bt(this.tempToken.token);const t=this.account||this.nuclia.options.account,e=this.slug||this.nuclia.options.kbSlug;let n;if(this.nuclia.options.standalone)n=this.nuclia.rest.get("/temp-access-token");else{if(!t||!e)throw new Error("Account and KB slug are required to get a temp token");n=this.nuclia.rest.post(`/account/${t}/kb/${e}/ephemeral_tokens`,{})}return n.pipe(mt((t=>t.token)),Bt((t=>this.tempToken={token:t,expiration:Date.now()+3e5})))}listActivity(t,e,n){const r=[t?`type=${t}`:"",e?`page=${e}`:"",n?`size=${n}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/activity${r?"?"+r:""}`)}listActivityDownloads(t){return this.nuclia.rest.get(`/kb/${this.id}/activity/downloads?type=${t}`)}downloadActivity(t,e){return this.nuclia.rest.get(`/kb/${this.id}/activity/download?type=${t}&month=${e}`,{},!0).pipe(jt((t=>gt(t.blob()))))}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ze extends qe{admin;contrib;_training;get training(){return this._training||(this._training=new Ye(this,this.nuclia)),this._training}modify(t){const e="local"===this.account?`/kb/${this.id}`:`/account/${this.account}/kb/${this.slug}`;return this.nuclia.rest.patch(e,t)}publish(t){return this.modify({state:t?"PUBLISHED":"PRIVATE"})}delete(){const t="local"===this.account?`/kb/${this.id}`:`/account/${this.account}/kb/${this.slug}`;return this.nuclia.rest.delete(t)}createEntitiesGroup(t,e){return this.nuclia.rest.post(`${this.path}/entitiesgroups`,{...e,group:t})}updateEntitiesGroup(t,e){return this.nuclia.rest.patch(`${this.path}/entitiesgroup/${t}`,e)}deleteEntitiesGroup(t){return this.nuclia.rest.delete(`${this.path}/entitiesgroup/${t}`)}setLabelSet(t,e){return this.nuclia.rest.post(`${this.path}/labelset/${t}`,e)}deleteLabelSet(t){return this.nuclia.rest.delete(`${this.path}/labelset/${t}`)}setSynonyms(t){return this.nuclia.rest.put(`${this.path}/custom-synonyms`,{synonyms:t})}deleteAllSynonyms(){return this.nuclia.rest.delete(`${this.path}/custom-synonyms`)}createResource(t,e=!0){return this.nuclia.rest.post(`${this.path}/resources`,t,void 0,void 0,e)}createLinkResource(t,e,n=!0,r){return this.createResource({links:{link:t},usermetadata:e,title:t.uri,icon:"application/stf-link",...r?{origin:r}:{}},n)}hasResource(t){return this.nuclia.rest.get(`${this.path}/slug/${t}`).pipe(mt((()=>!0)),Ut((()=>bt(!1))))}createOrUpdateResource(t,e=!0){return(t.slug?this.hasResource(t.slug):bt(!1)).pipe(jt((n=>n?this.getResourceFromData({id:"",slug:t.slug}).modify(t,e):this.createResource(t,e))))}upload(t,e,n){return ne(this.nuclia,`/kb/${this.id}`,t,!!e,n)}batchUpload(t){return se(this.nuclia,`/kb/${this.id}`,t,!1)}getServiceAccounts(){return this.nuclia.rest.get(`/account/${this.account}/kb/${this.slug}/service_accounts`)}createServiceAccount(t){return this.nuclia.rest.post(`/account/${this.account}/kb/${this.slug}/service_accounts`,t)}deleteServiceAccount(t){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}/service_account/${t}`)}createKey(t,e){return this.nuclia.rest.post(`/account/${this.account}/kb/${this.slug}/service_account/${t}/keys`,{expires:e})}createKeyForService(t,e){return this.getServiceAccounts().pipe(jt((e=>{const n=e.find((e=>e.title===t.title&&e.role===t.role));return n?bt(n):this.createServiceAccount(t).pipe(jt((()=>this.getServiceAccounts())),mt((e=>e.find((e=>e.title===t.title&&e.role===t.role)))))})),jt((t=>t?this.createKey(t.id,e):bt({token:""}))))}deleteKey(t,e){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}/service_account/${t}/key/${e}`)}setConfiguration(t){return this.nuclia.rest.patch(`/kb/${this.id}/configuration`,t)}}var Qe,tn;!function(t){t.RESOURCES="RESOURCES",t.PARAGRAPHS="PARAGRAPHS",t.SELECTIONS="SELECTIONS"}(Qe||(Qe={})),function(t){t.VISITED="VISITED",t.MODIFIED="MODIFIED",t.DELETED="DELETED",t.NEW="NEW",t.STARTED="STARTED",t.STOPPED="STOPPED",t.SEARCH="SEARCH",t.PROCESSED="PROCESSED",t.CHAT="CHAT"}(tn||(tn={}));class en{nuclia;constructor(t){this.nuclia=t}getAccounts(){return this.nuclia.rest.get("/accounts")}createAccount(t){return this.nuclia.rest.post("/accounts",t)}modifyAccount(t,e){return this.nuclia.rest.patch(`/account/${t}`,e)}deleteAccount(t){return this.nuclia.rest.delete(`/account/${t}`)}getAccountStatus(t){return this.nuclia.rest.get(`/account/${t}/status`)}getWelcome(){return this.nuclia.rest.get("/user/welcome")}getAccount(t){if(!(t=t||this.nuclia.options.account))throw new Error("Account is not set");return this.nuclia.rest.get(`/account/${t}`)}getStandaloneKbs(){return this.nuclia.rest.get("/kbs").pipe(mt((t=>t.kbs)))}getKnowledgeBoxes(t){return this.nuclia.rest.get(`/account/${t}/kbs`)}getKnowledgeBox(t,e){if(t=t||this.nuclia.options.account){const n=e||this.nuclia.options.knowledgeBox||this.nuclia.options.kbSlug;if(!n)throw new Error("account and knowledgeBox must be defined in the Nuclia options");const r=this.nuclia.options.standalone?`/kb/${n}`:`/account/${t}/kb/${n}`;return this.nuclia.rest.get(r).pipe(jt((t=>this.nuclia.options.zone||this.nuclia.options.standalone?bt(t):this.nuclia.rest.getZoneSlug(t.zone).pipe(Bt((t=>this.nuclia.options.zone=t)),mt((()=>t))))),mt((e=>new Ze(this.nuclia,t,e))))}if(!this.nuclia.options.knowledgeBox||!this.nuclia.options.zone)throw new Error("zone must be defined in the Nuclia options");return bt(new Ze(this.nuclia,"",{id:this.nuclia.options.knowledgeBox,zone:this.nuclia.options.zone}))}createKnowledgeBox(t,e){return this.nuclia.rest.post(this.nuclia.options.standalone?"/kbs":`/account/${t}/kbs`,e).pipe(jt((n=>{const r=n.id||n.uuid;if(!r)throw"KnowledgeBox creation failed";return this.getKnowledgeBox(t,this.nuclia.options.standalone?r:e.slug)})))}getStats(t,e,n,r=Xt.DAY,i){const s=[`period=${r}`,`stats=${e}`];return i&&s.push(`utctime=${i}`),n&&s.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${t}/stats?${s.join("&")}`).pipe(mt((t=>t.data)),Ct((t=>!!t)))}upload(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /process");return oe(this.nuclia,this.getNUAKey(),t,{md5:t.md5}).pipe(jt((t=>this.nuclia.rest.post("/processing/push",{filefield:{file:t}},this.getNUAHeader()))))}pull(){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /processing");return this.nuclia.rest.get("/processing/pull",this.getNUAHeader())}getProcessingStatus(t){if(!t){if(!this.hasNUAClient())throw new Error("NUA key or account id is needed to be able to call /processing/status")}const e=t?`/processing/status?account_id=${t}`:"/processing/status",n=t?void 0:this.getNUAHeader();return this.nuclia.rest.get(e,n)}getProcessingStats(t,e){const n=this.hasNUAClient();if(!e&&!n)throw new Error("NUA key or account id is needed to be able to call /processing/stats");const r=n?"/processing/stats"+(t?"?period="+t:""):`/processing/stats?account_id=${e}${t?"&period="+t:""}`,i=n?this.getNUAHeader():void 0;return this.nuclia.rest.get(r,i).pipe(mt((t=>t.data)))}getNUAActivity(t,e,n=0){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}/activity?page=${n}`)}getNUAClients(t){return this.nuclia.rest.get(`/account/${t}/nua_clients`).pipe(mt((t=>t.clients)))}getNUAClient(t,e){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}`)}hasNUAClient(){return!!this.getNUAKey()}getNUAKey(){return this.nuclia.options.nuaKey||""}getNUAHeader(){return{"x-stf-nuakey":`Bearer ${this.getNUAKey()}`}}createNUAClient(t,e){const n={...e};return n.webhook&&(n.processing_webhook={uri:n.webhook},delete n.webhook),this.nuclia.rest.post(`/account/${t}/nua_clients`,n).pipe(Ut((n=>{if(409===n.status&&e.client_id)return this.renewNUAClient(t,e.client_id);throw n})),Bt((t=>{"desktop"===this.nuclia.options.client&&(this.nuclia.options.nuaKey=t.token,localStorage.setItem(Mt,t.token))})))}renewNUAClient(t,e){return this.nuclia.rest.put(`/account/${t}/nua_client/${e}/key`,{})}deleteNUAClient(t,e){return this.nuclia.rest.delete(`/account/${t}/nua_client/${e}`)}getLearningConfigurations(){return this.nuclia.rest.get("/learning/configuration/schema")}predictTokens(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /predict");return this.nuclia.rest.get(`/predict/tokens?text=${encodeURIComponent(t)}`,this.getNUAHeader()).pipe(mt((t=>t.tokens)))}}class nn{nuclia;zones;constructor(t){this.nuclia=t}get(t,e,n){return this.fetch("GET",t,void 0,e,n)}post(t,e,n,r,i){return this.fetch("POST",t,e,n,r,i)}put(t,e,n,r,i){return this.fetch("PUT",t,e,n,r,i)}patch(t,e,n,r,i){return this.fetch("PATCH",t,e,n,r,i)}delete(t,e,n){return this.fetch("DELETE",t,void 0,e,!0,n)}head(t,e){return this.fetch("HEAD",t,void 0,e,!0)}getHeaders(t,e,n,r=!1){const i=n&&n["x-stf-nuakey"]?{}:this.nuclia.auth.getAuthHeaders(t,e),s={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return r&&(s["x-synchronous"]=`${r}`),{...s,...n}}fetch(t,e,n,r,i,s=!1){const o=r&&r["content-type"];return gt(fetch(this.getFullUrl(e),{method:t,headers:this.getHeaders(t,e,r,s),body:o?n:JSON.stringify(n)}).then((t=>t.ok?i?t:t.json().then((t=>t),(()=>{console.warn(`${e} did not return a valid JSON`)})):(this.nuclia.events?.emit("api-error",{status:t.status,path:this.getFullUrl(e)}),t.json().then((e=>{throw{status:t.status,body:e}}),(()=>{throw{status:t.status}}))))))}getFullUrl(t){return`${t.startsWith("/account")||t.startsWith("/user")||t.startsWith("/auth")||t.startsWith("/zones")||t.startsWith("/billing")||t.startsWith("/configuration")||t.startsWith("/manage")||t.includes("/activity")&&!t.includes("/activity/download")||this.nuclia.options.standalone?this.nuclia.backend:this.nuclia.regionalBackend}${t.startsWith("/auth")||t.startsWith("/export")||t.startsWith("/billing")||t.startsWith("/configuration")||t.startsWith("/manage")?"":"/v1"}${t}`}getZones(){return this.zones?bt(this.zones):this.get("/zones").pipe(mt((t=>{const e=t.reduce(((t,e)=>(t[e.id]=e.slug,t)),{});return this.zones=e,e})))}getZoneSlug(t){return this.getZones().pipe(mt((e=>e[t])))}getObjectURL(t){return this.get(t,void 0,!0).pipe(jt((t=>gt(t.blob()))),mt((t=>URL.createObjectURL(t))))}getStream(t,e){return t=this.getFullUrl(t),new C((n=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t,void 0),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),r=t.headers,i=t.status;if(e&&t.ok){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:s})=>{e&&(n.next({data:t,incomplete:!1,headers:r}),n.complete()),s&&(t=this.concat(t,s),n.next({data:t,incomplete:!0,headers:r}),i())}))};i()}else n.error({status:i}),n.complete()}))}))}concat(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}}class rn{messages=new B;emit(t,e){this.messages.next({name:t,data:e})}on(t){return this.messages.asObservable().pipe(Ct((e=>e.name===t)),mt((t=>t.data)))}}class sn{options;auth;rest;db;currentShards={};events=new rn;readKb;get backend(){return this.options.backend}get regionalBackend(){return this.options.backend.replace("//",`//${this.options.zone}.`)}get knowledgeBox(){if(!this.options.knowledgeBox||!this.options.zone&&!this.options.standalone)throw new Error("zone and knowledge box id must be defined in the Nuclia options");return this.readKb||(this.readKb=new qe(this,"",{id:this.options.knowledgeBox,zone:this.options.zone||""})),this.readKb}get asyncKnowledgeBox(){return new Proxy(this.knowledgeBox,{get(t,e){const n=Reflect.get(t,e);return"function"==typeof n?(...e)=>function(t,e){var n="object"==typeof e;return new Promise((function(r,i){var s=new $({next:function(t){r(t),s.unsubscribe()},error:i,complete:function(){n?r(e.defaultValue):i(new vt)}});t.subscribe(s)}))}(n.bind(t)(...e)):n}})}constructor(t){this.options=t,this.auth=new Gt(this),this.rest=new nn(this),this.db=new en(this)}}export{Vt as AccountBlockingState,Gt as Authentication,Jt as BlockedFeature,Oe as Chat,me as ConversationFieldData,en as Db,tn as EventType,he as ExtractedDataTypes,ue as FIELD_TYPE,ge as FileFieldData,Ht as JwtHelper,ye as KeywordSetFieldData,qe as KnowledgeBox,Qe as LabelSetKind,ve as LinkFieldData,Mt as NUA_KEY,sn as Nuclia,ce as RESOURCE_STATUS,Fe as ReadableResource,He as Resource,le as ResourceFieldProperties,Qt as ResourceProperties,nn as Rest,fe as SHORT_FIELD_TYPE,pe as Search,de as SortField,Xt as StatsPeriod,Yt as StatsRange,qt as StatsType,ie as TUSuploadFile,be as TextFieldData,Ye as Training,Xe as TrainingExecutionStatus,Je as TrainingStatus,Ve as TrainingType,Zt as USER_PROMPTS,Ze as WritableKnowledgeBox,se as batchUpload,xe as catalog,Ne as chat,Ce as deDuplicateList,Se as find,We as getDataKeyFromFieldType,ke as getEntityFromFilter,Me as getFieldTypeFromString,ae as getFileMetadata,Ae as getFilterFromEntity,we as getFilterFromLabel,Ee as getLabelFromFilter,Be as lengthUnicode,Ke as longToShortFieldType,ze as resourceToAlgoliaFormat,Te as search,Pe as setEntities,Ue as setLabels,Ge as shortToLongFieldType,je as sliceUnicode,_e as suggest,ne as upload,re as uploadFile,oe as uploadToProcess};

@@ -98,3 +98,3 @@ import { Observable } from 'rxjs';

chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions): Observable<Chat.Answer | IErrorResponse>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions, callback?: (answer: Chat.Answer | IErrorResponse) => void): Observable<Chat.Answer | IErrorResponse>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions, callback?: (answer: Chat.Answer | IErrorResponse) => void): Observable<null>;
/**

@@ -101,0 +101,0 @@ * Performs a find operation in the Knowledge Box, which is the recommended way to search for results.

{
"name": "@nuclia/core",
"version": "1.6.4",
"version": "1.6.5",
"description": "SDK allowing to integrate Nuclia services in your frontend application",

@@ -5,0 +5,0 @@ "license": "MIT",

@@ -98,3 +98,3 @@ import { Observable } from 'rxjs';

chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions): Observable<Chat.Answer | IErrorResponse>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions, callback?: (answer: Chat.Answer | IErrorResponse) => void): Observable<Chat.Answer | IErrorResponse>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: ChatOptions, callback?: (answer: Chat.Answer | IErrorResponse) => void): Observable<null>;
/**

@@ -101,0 +101,0 @@ * Performs a find operation in the Knowledge Box, which is the recommended way to search for results.

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display