@nuclia/core
Advanced tools
Comparing version 1.4.0 to 1.5.0
@@ -0,1 +1,23 @@ | ||
# 1.5.0 (2023-07-18) | ||
### Breaking changes | ||
- Remove `Search.SmartParagraph` interface as it's not used anymore | ||
- Rename `Search.SmartResult` interface to `Search.FieldResult` as `Smart` prefix doesn't make sense anymore | ||
- Load `SHORTENED_METADATA` by default on `getField` | ||
### Improvements | ||
- Add `SHORTENED_METADATA` type to `ExtractedDataTypes` | ||
- Add `selections` in field metadata | ||
- Update Learning configurations models | ||
- Update `LearningConfiguration` interface | ||
- Add `LearningConfigurationSchemas` and `LearningConfigurationSchema` interfaces | ||
- Add `resource_filters` property to `BaseSearchOptions` | ||
- Add `find` method to `resource` class | ||
### Bug fix | ||
- Add missing `generic` type in `shortToLongFieldType` and `getFieldTypeFromString` mappers | ||
# 1.4.0 (2023-06-23) | ||
@@ -2,0 +24,0 @@ |
@@ -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(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),x=Function.prototype.bind;function $(t,e){return x.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}(),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&&$(e.next,s),error:e.error&&$(e.error,s),complete:e.complete&&$(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(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 T({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 q(t){return t&&h(t.schedule)}function Y(t){return t[t.length-1]}function Z(t){return q(Y(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,xt=Object.keys;function $t(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=xt(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 Tt(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 Tt(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(Y(t))?t.pop():void 0}(t),r=$t(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&&(q(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 Y(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?ut(i[0]):Tt(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&&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,qt,Yt,Zt,Qt,te,ee,ne;!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"}(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"}(qt||(qt={})),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"}(Yt||(Yt={})),function(t){t.BASIC="basic",t.ORIGIN="origin",t.RELATIONS="relations",t.VALUES="values",t.EXTRACTED="extracted",t.ERRORS="errors",t.EXTRA="extra"}(Zt||(Zt={})),function(t){t.VALUE="value",t.EXTRACTED="extracted",t.ERROR="error"}(Qt||(Qt={})),function(t){t.TEXT="text",t.METADATA="metadata",t.LARGE_METADATA="large_metadata",t.VECTOR="vectors",t.LINK="link",t.FILE="file"}(te||(te={})),function(t){t.RESOURCES="RESOURCES",t.PARAGRAPHS="PARAGRAPHS"}(ee||(ee={})),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"}(ne||(ne={}));const re=524288,ie=new RegExp(/[^a-z0-9_-]/g),se=(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?ae(t,e,s,i,n.payload):oe(t,e,s,i))))),oe=(t,e,n,r)=>{const i={"content-type":r?.contentType||"application/octet-stream",...le(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})}})))},ae=(t,e,n,r,i)=>{let s=0,o=0,a=!1;const u=n.byteLength,c=Math.ceil(u/re),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+re);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+=re,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Ut((()=>(a=!0,bt({failed:!0})))))}))))))))))},ue=(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(ie,"_");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 se(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}})))},ce=(t,e,n,r)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":r?.contentType||"application/octet-stream",...le(r)};return t.rest.post("/processing/upload",n,i)},le=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};function he(t){return`/l/${t.labelset}/${t.label}`}function de(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}function fe(t){return`/e/${t.family}/${t.entity}`}function pe(t){const e=t.split("/");return{family:e[2],entity:e[3]}}var ge,be,ye;!function(t){t.created="created",t.modified="modified",t.title="title"}(ge||(ge={})),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"}(be||(be={})),function(t){var e,n,r;(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.FindScoreType||(t.FindScoreType={})).VECTOR="VECTOR",r.BM25="BM25",r.BOTH="BOTH"}(ye||(ye={}));const ve=(t,e,n,r,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=r||"":a.query=r||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=`${n}/find`;return(o?t.rest.get(`${h}?${Ae(a,l)}`,void 0,!0):t.rest.post(h,{...a,...l},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(`${h} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...a,...l}),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})})))},me=(t,e,n,r,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=r||"":a.query=r||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=o?t.rest.get(`${n}/search?${Ae(a,l)}`):t.rest.post(`${n}/search`,{...a,...l});return Ee(t,e,h)},we=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${r?Ae(i,r):""}`);return Ee(t,e,s)};function Ee(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 Ae=(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 ke;!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"}(ke||(ke={}));const Se="_END_";function xe(t,e,n,r=[],i=[ke.Features.PARAGRAPHS],s={}){let o,a,u=0,c="";return t.rest.getStream(`${e}/chat`,{query:n,context:r,show:[Zt.BASIC,Zt.VALUES],features:i.length>0?i:void 0,...s}).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(Se))){let t;if([c,t]=c.split(Se),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 $e=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),_e=(t,e,n,r,i)=>{const s=$e(i.filter((n=>Re(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=$e(i.filter((n=>Oe(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},Te=(t,e,n,r)=>{const i=$e(r.filter((n=>Oe(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},Re=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,Oe=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,Ie=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Ne=t=>t?Array.from(t).length:0;class Ce{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 Ie(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return Ie(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 Ue extends Ce{kb;uuid;nuclia;get path(){if(!this.uuid&&!this.slug)throw new Error("Resource must have either uuid or slug");return this.uuid?`/kb/${this.kb}/resource/${this.uuid}`:`/kb/${this.kb}/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=[Qt.VALUE],r=[te.TEXT,te.METADATA,te.LINK,te.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){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`)}setField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}upload(t,e,n,r){return se(this.nuclia,`${this.path}/file/${t}`,e,!!n,r)}batchUpload(t){return ue(this.nuclia,this.path,t,!0)}search(t,e=[],n){return me(this.nuclia,this.kb,this.path,t,e,n,!0)}setLabels(t,e,n,r){const i=_e(t,e,n,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,n){const r=Te(t,e,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:r}).pipe(Bt((()=>this.fieldmetadata=r)))}}var Pe,De;!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"}(Pe||(Pe={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(De||(De={}));class Le{value;extracted;error}class je{value;extracted;error}class Be{value;extracted;error}class Fe{value;extracted;error}class He{value;extracted;error}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 Pe.text:case Pe.file:case Pe.link:case Pe.keywordset:return`${t}s`;default:return null}};function Ke(t){return be[t]}function Ge(t){switch(t){case be.conversation:return Pe.conversation;case be.datetime:return Pe.datetime;case be.file:return Pe.file;case be.layout:return Pe.layout;case be.keywordset:return Pe.keywordset;case be.link:return Pe.link;case be.text:return Pe.text;default:return null}}function Me(t){switch(t){case Pe.file:return Pe.file;case Pe.link:return Pe.link;case Pe.text:return Pe.text;case Pe.layout:return Pe.layout;case Pe.conversation:return Pe.conversation;case Pe.datetime:return Pe.datetime;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 qe{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 Ye{account;nuclia;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=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],n=[te.TEXT,te.METADATA,te.LINK,te.FILE]){return this._getResource(t,void 0,e,n)}getResourceBySlug(t,e=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],n=[te.TEXT,te.METADATA,te.LINK,te.FILE]){return this._getResource(void 0,t,e,n)}_getResource(t,e,n=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],r=[te.TEXT,te.METADATA,te.LINK,te.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 Ue(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Ue(this.nuclia,this.id,t)}chat(t,e,n,r){return xe(this.nuclia,this.path,t,e,n,r)}find(t,e=[],n){return ve(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return me(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return we(this.nuclia,this.id,t,e)}suggest(t,e=!1){const n=`query=${encodeURIComponent(t)}${e?"&fields=a/title":""}`;return this.nuclia.rest.get(`${this.path}/suggest?${n}`).pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"suggestions"})))}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 Ue(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(!this.nuclia.options.account||!this.nuclia.options.kbSlug)throw new Error("Account and KB slug are required to get a temp token");return this.nuclia.rest.post(`/account/${this.nuclia.options.account}/kb/${this.nuclia.options.kbSlug}/ephemeral_tokens`,{}).pipe(mt((t=>t.token)))}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:""}`)}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ze extends Ye{admin;contrib;_training;get training(){return this._training||(this._training=new qe(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(){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}`)}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 se(this.nuclia,`/kb/${this.id}`,t,!!e,n)}batchUpload(t){return ue(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)}}class Qe{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/${e}`:`/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 ce(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 tn{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")||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),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 en{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 nn{options;auth;rest;db;currentShards={};events=new en;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 Ye(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 T({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 tn(this),this.db=new Qe(this)}}export{Vt as AccountBlockingState,Gt as Authentication,Jt as BlockedFeature,ke as Chat,He as ConversationFieldData,Qe as Db,ne as EventType,te as ExtractedDataTypes,Pe as FIELD_TYPE,Le as FileFieldData,Ht as JwtHelper,Be as KeywordSetFieldData,Ye as KnowledgeBox,ee as LabelSetKind,Fe as LinkFieldData,Mt as NUA_KEY,nn as Nuclia,De as RESOURCE_STATUS,Ce as ReadableResource,Ue as Resource,Qt as ResourceFieldProperties,Zt as ResourceProperties,tn as Rest,be as SHORT_FIELD_TYPE,ye as Search,ge as SortField,Xt as StatsPeriod,qt as StatsRange,Yt as StatsType,ae as TUSuploadFile,je as TextFieldData,qe as Training,Xe as TrainingExecutionStatus,Je as TrainingStatus,Ve as TrainingType,Ze as WritableKnowledgeBox,ue as batchUpload,we as catalog,xe as chat,$e as deDuplicateList,ve as find,We as getDataKeyFromFieldType,pe as getEntityFromFilter,Me as getFieldTypeFromString,le as getFileMetadata,fe as getFilterFromEntity,he as getFilterFromLabel,de as getLabelFromFilter,Ne as lengthUnicode,Ke as longToShortFieldType,ze as resourceToAlgoliaFormat,me as search,Te as setEntities,_e as setLabels,Ge as shortToLongFieldType,Ie as sliceUnicode,se as upload,oe as uploadFile,ce 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 S(t){t()}var k=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),x=Function.prototype.bind;function _(t,e){return x.call(t,e)}var T=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&&_(e.next,s),error:e.error&&_(e.error,s),complete:e.complete&&_(e.complete,s)}):i=e;return o.destination=new T(i),o}return e(n,t),n}(k);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 k||function(t){return t&&h(t.next)&&h(t.error)&&h(t.complete)}(r)&&y(r)?t:new $(t,e,n);return S((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}(k),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;S((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;S((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;S((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 q(t){return t&&h(t.schedule)}function Y(t){return t[t.length-1]}function Z(t){return q(Y(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,St=Object.getPrototypeOf,kt=Object.prototype,xt=Object.keys;function _t(t){if(1===t.length){var e=t[0];if(At(e))return{args:e,keys:null};if((r=e)&&"object"==typeof r&&St(r)===kt){var n=xt(e);return{args:n.map((function(t){return e[t]})),keys:n}}}var r;return{args:t,keys:null}}function Tt(t,e,n){return void 0===n&&(n=1/0),h(e)?Tt((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),Tt(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(Y(t))?t.pop():void 0}(t),r=_t(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&&(q(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 Y(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)?Tt(t,e,1):Tt(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&&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,qt,Yt,Zt,Qt,te,ee,ne;!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"}(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"}(qt||(qt={})),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"}(Yt||(Yt={})),function(t){t.BASIC="basic",t.ORIGIN="origin",t.RELATIONS="relations",t.VALUES="values",t.EXTRACTED="extracted",t.ERRORS="errors",t.EXTRA="extra"}(Zt||(Zt={})),function(t){t.VALUE="value",t.EXTRACTED="extracted",t.ERROR="error"}(Qt||(Qt={})),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"}(te||(te={})),function(t){t.RESOURCES="RESOURCES",t.PARAGRAPHS="PARAGRAPHS",t.SELECTIONS="SELECTIONS"}(ee||(ee={})),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"}(ne||(ne={}));const re=524288,ie=new RegExp(/[^a-z0-9_-]/g),se=(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?ae(t,e,s,i,n.payload):oe(t,e,s,i))))),oe=(t,e,n,r)=>{const i={"content-type":r?.contentType||"application/octet-stream",...le(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})}})))},ae=(t,e,n,r,i)=>{let s=0,o=0,a=!1;const u=n.byteLength,c=Math.ceil(u/re),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+re);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+=re,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Ut((()=>(a=!0,bt({failed:!0})))))}))))))))))},ue=(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(ie,"_");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 se(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(Tt((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}})))},ce=(t,e,n,r)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":r?.contentType||"application/octet-stream",...le(r)};return t.rest.post("/processing/upload",n,i)},le=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};function he(t){return`/l/${t.labelset}/${t.label}`}function de(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}function fe(t){return`/e/${t.family}/${t.entity}`}function pe(t){const e=t.split("/");return{family:e[2],entity:e[3]}}var ge,be,ye;!function(t){t.created="created",t.modified="modified",t.title="title"}(ge||(ge={})),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"}(be||(be={})),function(t){var e,n,r;(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.FindScoreType||(t.FindScoreType={})).VECTOR="VECTOR",r.BM25="BM25",r.BOTH="BOTH"}(ye||(ye={}));const ve=(t,e,n,r,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=r||"":a.query=r||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=`${n}/find`;return(o?t.rest.get(`${h}?${Ae(a,l)}`,void 0,!0):t.rest.post(h,{...a,...l},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(`${h} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...a,...l}),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})})))},me=(t,e,n,r,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=r||"":a.query=r||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=o?t.rest.get(`${n}/search?${Ae(a,l)}`):t.rest.post(`${n}/search`,{...a,...l});return Ee(t,e,h)},we=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${r?Ae(i,r):""}`);return Ee(t,e,s)};function Ee(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 Ae=(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 Se;!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"}(Se||(Se={}));const ke="_END_";function xe(t,e,n,r=[],i=[Se.Features.PARAGRAPHS],s={}){let o,a,u=0,c="";return t.rest.getStream(`${e}/chat`,{query:n,context:r,show:[Zt.BASIC,Zt.VALUES],features:i.length>0?i:void 0,...s}).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(ke))){let t;if([c,t]=c.split(ke),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 _e=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),Te=(t,e,n,r,i)=>{const s=_e(i.filter((n=>Re(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=_e(i.filter((n=>Oe(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},$e=(t,e,n,r)=>{const i=_e(r.filter((n=>Oe(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},Re=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,Oe=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,Ie=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Ne=t=>t?Array.from(t).length:0;class Ce{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 Ie(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return Ie(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 Ue extends Ce{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=[Qt.VALUE],r=[te.TEXT,te.SHORTENED_METADATA,te.LINK,te.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){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`)}setField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}upload(t,e,n,r){return se(this.nuclia,`${this.path}/file/${t}`,e,!!n,r)}batchUpload(t){return ue(this.nuclia,this.path,t,!0)}search(t,e=[],n){return me(this.nuclia,this.kb,this.path,t,e,n,!0)}find(t,e=[],n){return ve(this.nuclia,this.kb,this.kbPath,t,e,this.uuid?{...n,resource_filters:[this.uuid]}:n)}setLabels(t,e,n,r){const i=Te(t,e,n,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,n){const r=$e(t,e,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:r}).pipe(Bt((()=>this.fieldmetadata=r)))}}var Pe,De;!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"}(Pe||(Pe={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(De||(De={}));class Le{value;extracted;error}class je{value;extracted;error}class Be{value;extracted;error}class Fe{value;extracted;error}class He{value;extracted;error}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 Pe.text:case Pe.file:case Pe.link:case Pe.keywordset:return`${t}s`;default:return null}};function Ke(t){return be[t]}function Ge(t){switch(t){case be.conversation:return Pe.conversation;case be.datetime:return Pe.datetime;case be.file:return Pe.file;case be.layout:return Pe.layout;case be.keywordset:return Pe.keywordset;case be.link:return Pe.link;case be.text:return Pe.text;case be.generic:return Pe.generic;default:return null}}function Me(t){switch(t){case Pe.file:return Pe.file;case Pe.link:return Pe.link;case Pe.text:return Pe.text;case Pe.layout:return Pe.layout;case Pe.conversation:return Pe.conversation;case Pe.datetime:return Pe.datetime;case Pe.generic:return Pe.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 qe{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 Ye{account;nuclia;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=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],n=[te.TEXT,te.METADATA,te.LINK,te.FILE]){return this._getResource(t,void 0,e,n)}getResourceBySlug(t,e=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],n=[te.TEXT,te.METADATA,te.LINK,te.FILE]){return this._getResource(void 0,t,e,n)}_getResource(t,e,n=[Zt.BASIC,Zt.ORIGIN,Zt.RELATIONS,Zt.VALUES,Zt.EXTRACTED,Zt.ERRORS],r=[te.TEXT,te.METADATA,te.LINK,te.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 Ue(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Ue(this.nuclia,this.id,t)}chat(t,e,n,r){return xe(this.nuclia,this.path,t,e,n,r)}find(t,e=[],n){return ve(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return me(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return we(this.nuclia,this.id,t,e)}suggest(t,e=!1){const n=`query=${encodeURIComponent(t)}${e?"&fields=a/title":""}`;return this.nuclia.rest.get(`${this.path}/suggest?${n}`).pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"suggestions"})))}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 Ue(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(!this.nuclia.options.account||!this.nuclia.options.kbSlug)throw new Error("Account and KB slug are required to get a temp token");return this.nuclia.rest.post(`/account/${this.nuclia.options.account}/kb/${this.nuclia.options.kbSlug}/ephemeral_tokens`,{}).pipe(mt((t=>t.token)))}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:""}`)}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ze extends Ye{admin;contrib;_training;get training(){return this._training||(this._training=new qe(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(){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}`)}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 se(this.nuclia,`/kb/${this.id}`,t,!!e,n)}batchUpload(t){return ue(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)}}class Qe{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/${e}`:`/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 ce(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 tn{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")||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),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 en{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 nn{options;auth;rest;db;currentShards={};events=new en;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 Ye(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 tn(this),this.db=new Qe(this)}}export{Vt as AccountBlockingState,Gt as Authentication,Jt as BlockedFeature,Se as Chat,He as ConversationFieldData,Qe as Db,ne as EventType,te as ExtractedDataTypes,Pe as FIELD_TYPE,Le as FileFieldData,Ht as JwtHelper,Be as KeywordSetFieldData,Ye as KnowledgeBox,ee as LabelSetKind,Fe as LinkFieldData,Mt as NUA_KEY,nn as Nuclia,De as RESOURCE_STATUS,Ce as ReadableResource,Ue as Resource,Qt as ResourceFieldProperties,Zt as ResourceProperties,tn as Rest,be as SHORT_FIELD_TYPE,ye as Search,ge as SortField,Xt as StatsPeriod,qt as StatsRange,Yt as StatsType,ae as TUSuploadFile,je as TextFieldData,qe as Training,Xe as TrainingExecutionStatus,Je as TrainingStatus,Ve as TrainingType,Ze as WritableKnowledgeBox,ue as batchUpload,we as catalog,xe as chat,_e as deDuplicateList,ve as find,We as getDataKeyFromFieldType,pe as getEntityFromFilter,Me as getFieldTypeFromString,le as getFileMetadata,fe as getFilterFromEntity,he as getFilterFromLabel,de as getLabelFromFilter,Ne as lengthUnicode,Ke as longToShortFieldType,ze as resourceToAlgoliaFormat,me as search,$e as setEntities,Te as setLabels,Ge as shortToLongFieldType,Ie as sliceUnicode,se as upload,oe as uploadFile,ce as uploadToProcess}; |
@@ -160,3 +160,3 @@ export type AccountTypes = 'stash-basic' | 'stash-team' | 'stash-trial' | 'stash-developer' | 'stash-business' | 'stash-startup' | 'stash-enterprise'; | ||
export interface LearningConfigurations { | ||
[key: string]: LearningConfiguration; | ||
[key: string]: LearningConfiguration | LearningConfigurationSchemas; | ||
} | ||
@@ -167,5 +167,26 @@ export interface LearningConfiguration { | ||
name: string; | ||
user_key?: string; | ||
}[]; | ||
default: string; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
export interface LearningConfigurationSchemas { | ||
schemas: { | ||
[key: string]: LearningConfigurationSchema; | ||
}; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
export interface LearningConfigurationSchema { | ||
title: string; | ||
type: string; | ||
properties: { | ||
[key: string]: { | ||
title: string; | ||
type: string; | ||
}; | ||
}; | ||
required: string[]; | ||
} | ||
export type LearningConfigurationSet = { | ||
@@ -172,0 +193,0 @@ id: string; |
@@ -40,3 +40,3 @@ import { Observable } from 'rxjs'; | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -83,4 +83,4 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
} |
@@ -25,2 +25,3 @@ import type { Observable } from 'rxjs'; | ||
METADATA = "metadata", | ||
SHORTENED_METADATA = "shortened_metadata", | ||
LARGE_METADATA = "large_metadata", | ||
@@ -33,3 +34,4 @@ VECTOR = "vectors", | ||
RESOURCES = "RESOURCES", | ||
PARAGRAPHS = "PARAGRAPHS" | ||
PARAGRAPHS = "PARAGRAPHS", | ||
SELECTIONS = "SELECTIONS" | ||
} | ||
@@ -82,3 +84,3 @@ export declare enum EventType { | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -120,3 +122,3 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
@@ -130,3 +132,3 @@ } | ||
learning_configuration?: { | ||
[configId: string]: string; | ||
[configId: string]: any; | ||
}; | ||
@@ -133,0 +135,0 @@ } |
@@ -37,2 +37,3 @@ import { Observable } from 'rxjs'; | ||
private nuclia; | ||
get kbPath(): string; | ||
get path(): string; | ||
@@ -51,4 +52,5 @@ constructor(nuclia: INuclia, kb: string, data: IResource); | ||
search(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>; | ||
find(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>; | ||
setLabels(fieldId: string, fieldType: string, paragraphId: string, labels: Classification[]): Observable<void>; | ||
setEntities(fieldId: string, fieldType: string, entities: TokenAnnotation[]): Observable<void>; | ||
} |
@@ -195,5 +195,21 @@ export interface IResource { | ||
} | ||
export interface PageStructure { | ||
page: { | ||
width: number; | ||
height: number; | ||
}; | ||
tokens: PageToken[]; | ||
} | ||
export interface PageToken { | ||
x: number; | ||
y: number; | ||
width: number; | ||
height: number; | ||
text: string; | ||
line: number; | ||
} | ||
export interface FilePages { | ||
pages?: CloudLink[]; | ||
positions?: PagePositions[]; | ||
structures?: PageStructure[]; | ||
} | ||
@@ -283,3 +299,16 @@ export interface FileB64 { | ||
token?: UserTokenAnnotation[]; | ||
selections?: PageSelections[]; | ||
} | ||
export interface PageSelections { | ||
page: number; | ||
visual: VisualSelection[]; | ||
} | ||
export interface VisualSelection { | ||
label: string; | ||
top: number; | ||
left: number; | ||
right: number; | ||
bottom: number; | ||
token_ids: number[]; | ||
} | ||
export interface TokenAnnotation { | ||
@@ -286,0 +315,0 @@ token: string; |
import { Observable } from 'rxjs'; | ||
import type { IErrorResponse, INuclia } from '../../models'; | ||
import type { Search, SearchOptions } from './search.models'; | ||
export declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
export declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: (Search.Features | Search.ResourceFeatures)[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
export declare const search: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[] | Search.ResourceFeatures[], options?: SearchOptions, useGet?: boolean) => Observable<Search.Results | IErrorResponse>; | ||
export declare const catalog: (nuclia: INuclia, kbid: string, query: string, options?: SearchOptions) => Observable<Search.Results | IErrorResponse>; |
@@ -26,2 +26,3 @@ import type { ExtractedDataTypes, ResourceProperties } from '../kb'; | ||
field_type_filter?: FIELD_TYPE[]; | ||
resource_filters?: string[]; | ||
shards?: string[]; | ||
@@ -127,3 +128,3 @@ autofilter?: boolean; | ||
} | ||
interface SmartResult extends IResource { | ||
interface FieldResult extends IResource { | ||
paragraphs?: FindParagraph[]; | ||
@@ -133,5 +134,2 @@ field?: FieldId; | ||
} | ||
interface SmartParagraph extends Paragraph { | ||
sentences?: Sentence[]; | ||
} | ||
interface Suggestions { | ||
@@ -138,0 +136,0 @@ type: 'suggestions'; |
{ | ||
"name": "@nuclia/core", | ||
"version": "1.4.0", | ||
"version": "1.5.0", | ||
"description": "SDK allowing to integrate Nuclia services in your frontend application", | ||
@@ -5,0 +5,0 @@ "license": "MIT", |
@@ -5,3 +5,3 @@ # Nuclia JavaScript SDK | ||
The full documentation is available at [https://docs.nuclia.dev/docs/sdk/sdk_api](https://docs.nuclia.dev/docs/sdk/sdk_api). | ||
The full documentation is available at [https://docs.nuclia.dev/docs/docs/sdk/js_sdk_api](https://docs.nuclia.dev/docs/docs/sdk/js_sdk_api). | ||
@@ -8,0 +8,0 @@ ## Basic usage |
@@ -188,3 +188,3 @@ import { Observable } from 'rxjs'; | ||
interface LearningConfigurations { | ||
[key: string]: LearningConfiguration; | ||
[key: string]: LearningConfiguration | LearningConfigurationSchemas; | ||
} | ||
@@ -195,5 +195,26 @@ interface LearningConfiguration { | ||
name: string; | ||
user_key?: string; | ||
}[]; | ||
default: string; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
interface LearningConfigurationSchemas { | ||
schemas: { | ||
[key: string]: LearningConfigurationSchema; | ||
}; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
interface LearningConfigurationSchema { | ||
title: string; | ||
type: string; | ||
properties: { | ||
[key: string]: { | ||
title: string; | ||
type: string; | ||
}; | ||
}; | ||
required: string[]; | ||
} | ||
type LearningConfigurationSet = { | ||
@@ -448,5 +469,21 @@ id: string; | ||
} | ||
interface PageStructure { | ||
page: { | ||
width: number; | ||
height: number; | ||
}; | ||
tokens: PageToken[]; | ||
} | ||
interface PageToken { | ||
x: number; | ||
y: number; | ||
width: number; | ||
height: number; | ||
text: string; | ||
line: number; | ||
} | ||
interface FilePages { | ||
pages?: CloudLink[]; | ||
positions?: PagePositions[]; | ||
structures?: PageStructure[]; | ||
} | ||
@@ -536,3 +573,16 @@ interface FileB64 { | ||
token?: UserTokenAnnotation[]; | ||
selections?: PageSelections[]; | ||
} | ||
interface PageSelections { | ||
page: number; | ||
visual: VisualSelection[]; | ||
} | ||
interface VisualSelection { | ||
label: string; | ||
top: number; | ||
left: number; | ||
right: number; | ||
bottom: number; | ||
token_ids: number[]; | ||
} | ||
interface TokenAnnotation { | ||
@@ -694,2 +744,3 @@ token: string; | ||
field_type_filter?: FIELD_TYPE[]; | ||
resource_filters?: string[]; | ||
shards?: string[]; | ||
@@ -795,3 +846,3 @@ autofilter?: boolean; | ||
} | ||
interface SmartResult extends IResource { | ||
interface FieldResult extends IResource { | ||
paragraphs?: FindParagraph[]; | ||
@@ -801,5 +852,2 @@ field?: FieldId; | ||
} | ||
interface SmartParagraph extends Paragraph { | ||
sentences?: Sentence[]; | ||
} | ||
interface Suggestions { | ||
@@ -878,3 +926,3 @@ type: 'suggestions'; | ||
declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: (Search.Features | Search.ResourceFeatures)[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
declare const search: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[] | Search.ResourceFeatures[], options?: SearchOptions, useGet?: boolean) => Observable<Search.Results | IErrorResponse>; | ||
@@ -940,2 +988,3 @@ declare const catalog: (nuclia: INuclia, kbid: string, query: string, options?: SearchOptions) => Observable<Search.Results | IErrorResponse>; | ||
private nuclia; | ||
get kbPath(): string; | ||
get path(): string; | ||
@@ -954,2 +1003,3 @@ constructor(nuclia: INuclia, kb: string, data: IResource); | ||
search(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>; | ||
find(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>; | ||
setLabels(fieldId: string, fieldType: string, paragraphId: string, labels: Classification[]): Observable<void>; | ||
@@ -998,2 +1048,3 @@ setEntities(fieldId: string, fieldType: string, entities: TokenAnnotation[]): Observable<void>; | ||
METADATA = "metadata", | ||
SHORTENED_METADATA = "shortened_metadata", | ||
LARGE_METADATA = "large_metadata", | ||
@@ -1006,3 +1057,4 @@ VECTOR = "vectors", | ||
RESOURCES = "RESOURCES", | ||
PARAGRAPHS = "PARAGRAPHS" | ||
PARAGRAPHS = "PARAGRAPHS", | ||
SELECTIONS = "SELECTIONS" | ||
} | ||
@@ -1055,3 +1107,3 @@ declare enum EventType { | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -1093,3 +1145,3 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
@@ -1103,3 +1155,3 @@ } | ||
learning_configuration?: { | ||
[configId: string]: string; | ||
[configId: string]: any; | ||
}; | ||
@@ -1300,3 +1352,3 @@ } | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -1343,3 +1395,3 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
@@ -1608,2 +1660,2 @@ } | ||
export { Account, AccountBlockingState, AccountConfig, AccountCreation, AccountLimits, AccountLimitsPatchPayload, AccountStatus, AccountTypes, AuthTokens, Authentication, BaseSearchOptions, BlockedFeature, Chat, Classification, CloudLink, ComputedMetadata, ConversationField, ConversationFieldData, Counters, Db, Entities, EntitiesGroup, Entity, EntityPosition, EntityPositions, Event, EventList, EventType, ExtraMetadata, ExtractedData, ExtractedDataTypes, ExtractedText, FIELD_TYPE, FieldClassification, FieldComputedMetadata, FieldFullId, FieldId, FieldMetadata, FileB64, FileExtractedData, FileField, FileFieldData, FileFieldExtractedData, FileMetadata, FilePages, FileUploadStatus, FileWithMetadata, IAuthentication, ICreateResource, IDb, IError, IErrorResponse, IEvents, IFieldData, IKnowledgeBox, IKnowledgeBoxCreation, IKnowledgeBoxItem, INuclia, IResource, IRest, IStandaloneKb, IWritableKnowledgeBox, JwtHelper, JwtUser, KBRoles, KBStates, KeywordSetField, KeywordSetFieldData, KnowledgeBox, KnowledgeBoxCreation, Label, LabelSet, LabelSetKind, LabelSets, Language, LearningConfiguration, LearningConfigurationSet, LearningConfigurations, LinkExtractedData, LinkField, LinkFieldData, LinkFieldExtractedData, Message, MessageAttachment, MessageContent, Metadata, NUAClient, NUAClientPayload, NUA_KEY, NestedPosition, Nuclia, NucliaDBRole, NucliaOptions, Origin, PagePositions, Paragraph, ParagraphClassification, PositionedNER, PredictedToken, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, PromiseMapper, RESOURCE_STATUS, ReadableResource, Relation, RelationEntity, RelationEntityType, RelationType, Resource, ResourceData, ResourceField, ResourceFieldProperties, ResourceList, ResourcePagination, ResourceProperties, ResourceStatus, Rest, Row, RowsPreview, SHORT_FIELD_TYPE, Search, SearchOptions, Sentence, ServiceAccount, ServiceAccountCreation, ServiceAccountKey, Sheet, SortField, SortOption, SortOrder, StatsPeriod, StatsRange, StatsType, Synonyms, SynonymsPayload, TUSuploadFile, TextField, TextFieldData, TextFieldFormat, TextFormat, TokenAnnotation, Training, TrainingExecution, TrainingExecutionStatus, TrainingExecutionWithDuration, TrainingExecutions, TrainingLastExecution, TrainingStatus, TrainingTask, TrainingType, TypeParagraph, UpdateEntitiesGroupPayload, UploadResponse, UploadStatus, UserClassification, UserFieldMetadata, UserMetadata, UserTokenAnnotation, UserType, Welcome, WelcomeUser, WidgetFeatures, WritableKnowledgeBox, WriteFileField, batchUpload, catalog, chat, deDuplicateList, find, getDataKeyFromFieldType, getEntityFromFilter, getFieldTypeFromString, getFileMetadata, getFilterFromEntity, getFilterFromLabel, getLabelFromFilter, lengthUnicode, longToShortFieldType, resourceToAlgoliaFormat, search, setEntities, setLabels, shortToLongFieldType, sliceUnicode, upload, uploadFile, uploadToProcess }; | ||
export { Account, AccountBlockingState, AccountConfig, AccountCreation, AccountLimits, AccountLimitsPatchPayload, AccountStatus, AccountTypes, AuthTokens, Authentication, BaseSearchOptions, BlockedFeature, Chat, Classification, CloudLink, ComputedMetadata, ConversationField, ConversationFieldData, Counters, Db, Entities, EntitiesGroup, Entity, EntityPosition, EntityPositions, Event, EventList, EventType, ExtraMetadata, ExtractedData, ExtractedDataTypes, ExtractedText, FIELD_TYPE, FieldClassification, FieldComputedMetadata, FieldFullId, FieldId, FieldMetadata, FileB64, FileExtractedData, FileField, FileFieldData, FileFieldExtractedData, FileMetadata, FilePages, FileUploadStatus, FileWithMetadata, IAuthentication, ICreateResource, IDb, IError, IErrorResponse, IEvents, IFieldData, IKnowledgeBox, IKnowledgeBoxCreation, IKnowledgeBoxItem, INuclia, IResource, IRest, IStandaloneKb, IWritableKnowledgeBox, JwtHelper, JwtUser, KBRoles, KBStates, KeywordSetField, KeywordSetFieldData, KnowledgeBox, KnowledgeBoxCreation, Label, LabelSet, LabelSetKind, LabelSets, Language, LearningConfiguration, LearningConfigurationSchema, LearningConfigurationSchemas, LearningConfigurationSet, LearningConfigurations, LinkExtractedData, LinkField, LinkFieldData, LinkFieldExtractedData, Message, MessageAttachment, MessageContent, Metadata, NUAClient, NUAClientPayload, NUA_KEY, NestedPosition, Nuclia, NucliaDBRole, NucliaOptions, Origin, PagePositions, PageSelections, PageStructure, PageToken, Paragraph, ParagraphClassification, PositionedNER, PredictedToken, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, PromiseMapper, RESOURCE_STATUS, ReadableResource, Relation, RelationEntity, RelationEntityType, RelationType, Resource, ResourceData, ResourceField, ResourceFieldProperties, ResourceList, ResourcePagination, ResourceProperties, ResourceStatus, Rest, Row, RowsPreview, SHORT_FIELD_TYPE, Search, SearchOptions, Sentence, ServiceAccount, ServiceAccountCreation, ServiceAccountKey, Sheet, SortField, SortOption, SortOrder, StatsPeriod, StatsRange, StatsType, Synonyms, SynonymsPayload, TUSuploadFile, TextField, TextFieldData, TextFieldFormat, TextFormat, TokenAnnotation, Training, TrainingExecution, TrainingExecutionStatus, TrainingExecutionWithDuration, TrainingExecutions, TrainingLastExecution, TrainingStatus, TrainingTask, TrainingType, TypeParagraph, UpdateEntitiesGroupPayload, UploadResponse, UploadStatus, UserClassification, UserFieldMetadata, UserMetadata, UserTokenAnnotation, UserType, VisualSelection, Welcome, WelcomeUser, WidgetFeatures, WritableKnowledgeBox, WriteFileField, batchUpload, catalog, chat, deDuplicateList, find, getDataKeyFromFieldType, getEntityFromFilter, getFieldTypeFromString, getFileMetadata, getFilterFromEntity, getFilterFromLabel, getLabelFromFilter, lengthUnicode, longToShortFieldType, resourceToAlgoliaFormat, search, setEntities, setLabels, shortToLongFieldType, sliceUnicode, upload, uploadFile, uploadToProcess }; |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NucliaSDK={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};function r(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}var n=function(){return n=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},n.apply(this,arguments)};function i(t,e,r,n){return new(r||(r=Promise))((function(i,s){function o(t){try{u(n.next(t))}catch(t){s(t)}}function a(t){try{u(n.throw(t))}catch(t){s(t)}}function u(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}u((n=n.apply(t,e||[])).next())}))}function s(t,e){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function o(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,s=r.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}return o}function u(t,e,r){if(r||2===arguments.length)for(var n,i=0,s=e.length;i<s;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))}function c(t){return this instanceof c?(this.v=t,this):new c(t)}function l(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(t,e||[]),s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){i[t]&&(n[t]=function(e){return new Promise((function(r,n){s.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=i[t](e)).value instanceof c?Promise.resolve(r.value.v).then(u,l):h(s[0][2],r)}catch(t){h(s[0][3],t)}var r}function u(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 h(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,r=t[Symbol.asyncIterator];return r?r.call(t):(t=o(t),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(r){e[r]=t[r]&&function(e){return new Promise((function(n,i){(function(t,e,r,n){Promise.resolve(n).then((function(e){t({value:e,done:r})}),e)})(n,i,(e=t[r](e)).done,e.value)}))}}}function d(t){return"function"==typeof t}function p(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=p((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 g(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var b=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,r,n,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=o(s),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 s.remove(this);var h=this.initialTeardown;if(d(h))try{h()}catch(t){i=t instanceof f?t.errors:[t]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var g=o(p),b=g.next();!b.done;b=g.next()){var y=b.value;try{m(y)}catch(t){i=null!=i?i:[],t instanceof f?i=u(u([],a(i)),a(t.errors)):i.push(t)}}}catch(t){r={error:t}}finally{try{b&&!b.done&&(n=g.return)&&n.call(g)}finally{if(r)throw r.error}}}if(i)throw new f(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)m(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).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)&&g(e,t)},t.prototype.remove=function(e){var r=this._finalizers;r&&g(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),y=b.EMPTY;function v(t){return t instanceof b||t&&"closed"in t&&d(t.remove)&&d(t.add)&&d(t.unsubscribe)}function m(t){d(t)?t():t.unsubscribe()}var E={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},T={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,u([t,e],a(r)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function w(t){T.setTimeout((function(){throw t}))}function S(){}function _(t){t()}var A=function(t){function e(e){var r=t.call(this)||this;return r.isStopped=!1,e?(r.destination=e,v(e)&&e.add(r)):r.destination=I,r}return r(e,t),e.create=function(t,e,r){return new $(t,e,r)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(b),x=Function.prototype.bind;function k(t,e){return x.call(t,e)}var R=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){P(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){P(t)}else P(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){P(t)}},t}(),$=function(t){function e(e,r,n){var i,s,o=t.call(this)||this;d(e)||!e?i={next:null!=e?e:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:o&&E.useDeprecatedNextContext?((s=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},i={next:e.next&&k(e.next,s),error:e.error&&k(e.error,s),complete:e.complete&&k(e.complete,s)}):i=e;return o.destination=new R(i),o}return r(e,t),e}(A);function P(t){w(t)}var I={closed:!0,next:S,error:function(t){throw t},complete:S},O="function"==typeof Symbol&&Symbol.observable||"@@observable";function D(t){return t}var F=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(t,e,r){var n,i=this,s=(n=t)&&n instanceof A||function(t){return t&&d(t.next)&&d(t.error)&&d(t.complete)}(n)&&v(n)?t:new $(t,e,r);return _((function(){var t=i,e=t.operator,r=t.source;s.add(e?e.call(s,r):r?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 r=this;return new(e=L(e))((function(e,n){var i=new $({next:function(e){try{t(e)}catch(t){n(t),i.unsubscribe()}},error:n,complete:e});r.subscribe(i)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[O]=function(){return this},t.prototype.pipe=function(){for(var t,e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return(0===(t=e).length?D: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=L(t))((function(t,r){var n;e.subscribe((function(t){return n=t}),(function(t){return r(t)}),(function(){return t(n)}))}))},t.create=function(e){return new t(e)},t}();function L(t){var e;return null!==(e=null!=t?t:E.Promise)&&void 0!==e?e:Promise}function U(t){return function(e){if(function(t){return d(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 N(t,e,r,n,i){return new C(t,e,r,n,i)}var C=function(t){function e(e,r,n,i,s,o){var a=t.call(this,e)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=r?function(t){try{r(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=n?function(){try{n()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return r(e,t),e.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},e}(A),j=p((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),B=function(t){function e(){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 r(e,t),e.prototype.lift=function(t){var e=new H(this,this);return e.operator=t,e},e.prototype._throwIfClosed=function(){if(this.closed)throw new j},e.prototype.next=function(t){var e=this;_((function(){var r,n;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var i=o(e.currentObservers),s=i.next();!s.done;s=i.next()){s.value.next(t)}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}}}))},e.prototype.error=function(t){var e=this;_((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var r=e.observers;r.length;)r.shift().error(t)}}))},e.prototype.complete=function(){var t=this;_((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var e=this,r=this,n=r.hasError,i=r.isStopped,s=r.observers;return n||i?y:(this.currentObservers=null,s.push(t),new b((function(){e.currentObservers=null,g(s,t)})))},e.prototype._checkFinalizedStatuses=function(t){var e=this,r=e.hasError,n=e.thrownError,i=e.isStopped;r?t.error(n):i&&t.complete()},e.prototype.asObservable=function(){var t=new F;return t.source=this,t},e.create=function(t,e){return new H(t,e)},e}(F),H=function(t){function e(e,r){var n=t.call(this)||this;return n.destination=e,n.source=r,n}return r(e,t),e.prototype.next=function(t){var e,r;null===(r=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===r||r.call(e,t)},e.prototype.error=function(t){var e,r;null===(r=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===r||r.call(e,t)},e.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)},e.prototype._subscribe=function(t){var e,r;return null!==(r=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==r?r:y},e}(B),Y={now:function(){return(Y.delegate||Date).now()},delegate:void 0},K=function(t){function e(e,r,n){void 0===e&&(e=1/0),void 0===r&&(r=1/0),void 0===n&&(n=Y);var i=t.call(this)||this;return i._bufferSize=e,i._windowTime=r,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,e),i._windowTime=Math.max(1,r),i}return r(e,t),e.prototype.next=function(e){var r=this,n=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,o=r._timestampProvider,a=r._windowTime;n||(i.push(e),!s&&i.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),r=this._infiniteTimeWindow,n=this._buffer.slice(),i=0;i<n.length&&!t.closed;i+=r?1:2)t.next(n[i]);return this._checkFinalizedStatuses(t),e},e.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,r=t._timestampProvider,n=t._buffer,i=t._infiniteTimeWindow,s=(i?1:2)*e;if(e<1/0&&s<n.length&&n.splice(0,n.length-s),!i){for(var o=r.now(),a=0,u=1;u<n.length&&n[u]<=o;u+=2)a=u;a&&n.splice(0,a+1)}},e}(B),z=function(t){function e(e,r){return t.call(this)||this}return r(e,t),e.prototype.schedule=function(t,e){return this},e}(b),W=function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,u([t,e],a(r)))},G=function(t){return clearInterval(t)},M=function(t){function e(e,r){var n=t.call(this,e,r)||this;return n.scheduler=e,n.work=r,n.pending=!1,n}return r(e,t),e.prototype.schedule=function(t,e){var r;if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,i=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(i,n,e)),this.pending=!0,this.delay=e,this.id=null!==(r=this.id)&&void 0!==r?r:this.requestAsyncId(i,this.id,e),this},e.prototype.requestAsyncId=function(t,e,r){return void 0===r&&(r=0),W(t.flush.bind(t,this),r)},e.prototype.recycleAsyncId=function(t,e,r){if(void 0===r&&(r=0),null!=r&&this.delay===r&&!1===this.pending)return e;null!=e&&G(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(t,e);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var r,n=!1;try{this.work(t)}catch(t){n=!0,r=t||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),r},e.prototype.unsubscribe=function(){if(!this.closed){var e=this.id,r=this.scheduler,n=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,g(n,this),null!=e&&(this.id=this.recycleAsyncId(r,e,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(z),V=function(){function t(e,r){void 0===r&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(t,e,r){return void 0===e&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},t.now=Y.now,t}(),J=new(function(t){function e(e,r){void 0===r&&(r=V.now);var n=t.call(this,e,r)||this;return n.actions=[],n._active=!1,n}return r(e,t),e.prototype.flush=function(t){var e=this.actions;if(this._active)e.push(t);else{var r;this._active=!0;do{if(r=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,r){for(;t=e.shift();)t.unsubscribe();throw r}}},e}(V))(M),X=new F((function(t){return t.complete()}));function q(t){return t&&d(t.schedule)}function Z(t){return t[t.length-1]}function Q(t){return q(Z(t))?t.pop():void 0}var tt=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function et(t){return d(null==t?void 0:t.then)}function rt(t){return d(t[O])}function nt(t){return Symbol.asyncIterator&&d(null==t?void 0:t[Symbol.asyncIterator])}function it(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 st="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ot(t){return d(null==t?void 0:t[st])}function at(t){return l(this,arguments,(function(){var e,r,n;return s(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,c(e.read())];case 3:return r=i.sent(),n=r.value,r.done?[4,c(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,c(n)];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 ut(t){return d(null==t?void 0:t.getReader)}function ct(t){if(t instanceof F)return t;if(null!=t){if(rt(t))return i=t,new F((function(t){var e=i[O]();if(d(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(tt(t))return n=t,new F((function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()}));if(et(t))return r=t,new F((function(t){r.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,w)}));if(nt(t))return lt(t);if(ot(t))return e=t,new F((function(t){var r,n;try{for(var i=o(e),s=i.next();!s.done;s=i.next()){var a=s.value;if(t.next(a),t.closed)return}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}t.complete()}));if(ut(t))return lt(at(t))}var e,r,n,i;throw it(t)}function lt(t){return new F((function(e){(function(t,e){var r,n,o,a;return i(this,void 0,void 0,(function(){var i,u;return s(this,(function(s){switch(s.label){case 0:s.trys.push([0,5,6,11]),r=h(t),s.label=1;case 1:return[4,r.next()];case 2:if((n=s.sent()).done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];s.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=s.sent(),o={error:u},[3,11];case 6:return s.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:s.sent(),s.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 ht(t,e,r,n,i){void 0===n&&(n=0),void 0===i&&(i=!1);var s=e.schedule((function(){r(),i?t.add(this.schedule(null,n)):this.unsubscribe()}),n);if(t.add(s),!i)return s}function dt(t,e){return void 0===e&&(e=0),U((function(r,n){r.subscribe(N(n,(function(r){return ht(n,t,(function(){return n.next(r)}),e)}),(function(){return ht(n,t,(function(){return n.complete()}),e)}),(function(r){return ht(n,t,(function(){return n.error(r)}),e)})))}))}function pt(t,e){return void 0===e&&(e=0),U((function(r,n){n.add(t.schedule((function(){return r.subscribe(n)}),e))}))}function ft(t,e){if(!t)throw new Error("Iterable cannot be null");return new F((function(r){ht(r,e,(function(){var n=t[Symbol.asyncIterator]();ht(r,e,(function(){n.next().then((function(t){t.done?r.complete():r.next(t.value)}))}),0,!0)}))}))}function gt(t,e){if(null!=t){if(rt(t))return function(t,e){return ct(t).pipe(pt(e),dt(e))}(t,e);if(tt(t))return function(t,e){return new F((function(r){var n=0;return e.schedule((function(){n===t.length?r.complete():(r.next(t[n++]),r.closed||this.schedule())}))}))}(t,e);if(et(t))return function(t,e){return ct(t).pipe(pt(e),dt(e))}(t,e);if(nt(t))return ft(t,e);if(ot(t))return function(t,e){return new F((function(r){var n;return ht(r,e,(function(){n=t[st](),ht(r,e,(function(){var t,e,i;try{e=(t=n.next()).value,i=t.done}catch(t){return void r.error(t)}i?r.complete():r.next(e)}),0,!0)})),function(){return d(null==n?void 0:n.return)&&n.return()}}))}(t,e);if(ut(t))return function(t,e){return ft(at(t),e)}(t,e)}throw it(t)}function bt(t,e){return e?gt(t,e):ct(t)}function yt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return bt(t,Q(t))}function vt(t,e){var r=d(t)?t:function(){return t},n=function(t){return t.error(r())};return new F(e?function(t){return e.schedule(n,0,t)}:n)}var mt=p((function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Et(t,e){return U((function(r,n){var i=0;r.subscribe(N(n,(function(r){n.next(t.call(e,r,i++))})))}))}var Tt=Array.isArray;function wt(t){return Et((function(e){return function(t,e){return Tt(e)?t.apply(void 0,u([],a(e))):t(e)}(t,e)}))}var St=Array.isArray,_t=Object.getPrototypeOf,At=Object.prototype,xt=Object.keys;function kt(t){if(1===t.length){var e=t[0];if(St(e))return{args:e,keys:null};if((n=e)&&"object"==typeof n&&_t(n)===At){var r=xt(e);return{args:r.map((function(t){return e[t]})),keys:r}}}var n;return{args:t,keys:null}}function Rt(t,e,r){return void 0===r&&(r=1/0),d(e)?Rt((function(r,n){return Et((function(t,i){return e(r,t,n,i)}))(ct(t(r,n)))}),r):("number"==typeof e&&(r=e),U((function(e,n){return function(t,e,r,n,i,s,o,a){var u=[],c=0,l=0,h=!1,d=function(){!h||u.length||c||e.complete()},p=function(t){return c<n?f(t):u.push(t)},f=function(t){s&&e.next(t),c++;var a=!1;ct(r(t,l++)).subscribe(N(e,(function(t){null==i||i(t),s?p(t):e.next(t)}),(function(){a=!0}),void 0,(function(){if(a)try{c--;for(var t=function(){var t=u.shift();o?ht(e,o,(function(){return f(t)})):f(t)};u.length&&c<n;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(N(e,p,(function(){h=!0,d()}))),function(){null==a||a()}}(e,n,t,r)})))}function $t(t){return void 0===t&&(t=1/0),Rt(D,t)}function Pt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $t(1)(bt(t,Q(t)))}function It(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=function(t){return d(Z(t))?t.pop():void 0}(t),n=kt(t),i=n.args,s=n.keys,o=new F((function(t){var e=i.length;if(e)for(var r=new Array(e),n=e,o=e,a=function(e){var a=!1;ct(i[e]).subscribe(N(t,(function(t){a||(a=!0,o--),r[e]=t}),(function(){return n--}),void 0,(function(){n&&a||(o||t.next(s?function(t,e){return t.reduce((function(t,r,n){return t[r]=e[n],t}),{})}(s,r):r),t.complete())})))},u=0;u<e;u++)a(u);else t.complete()}));return r?o.pipe(wt(r)):o}function Ot(t,e,r){void 0===t&&(t=0),void 0===r&&(r=J);var n=-1;return null!=e&&(q(e)?r=e:n=e),new F((function(e){var i,s=(i=t)instanceof Date&&!isNaN(i)?+t-r.now():t;s<0&&(s=0);var o=0;return r.schedule((function(){e.closed||(e.next(o++),0<=n?this.schedule(void 0,n):e.complete())}),s)}))}function Dt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=Q(t),n=function(t,e){return"number"==typeof Z(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?ct(i[0]):$t(n)(bt(i,r)):X}function Ft(t,e){return U((function(r,n){var i=0;r.subscribe(N(n,(function(r){return t.call(e,r,i++)&&n.next(r)})))}))}function Lt(t){return U((function(e,r){var n,i=null,s=!1;i=e.subscribe(N(r,void 0,void 0,(function(o){n=ct(t(o,Lt(t)(e))),i?(i.unsubscribe(),i=null,n.subscribe(r)):s=!0}))),s&&(i.unsubscribe(),i=null,n.subscribe(r))}))}function Ut(t,e){return d(e)?Rt(t,e,1):Rt(t,1)}function Nt(t){return t<=0?function(){return X}:U((function(e,r){var n=0;e.subscribe(N(r,(function(e){++n<=t&&(r.next(e),t<=n&&r.complete())})))}))}function Ct(t){var e,r,n=1/0;return null!=t&&("object"==typeof t?(e=t.count,n=void 0===e?1/0:e,r=t.delay):n=t),n<=0?function(){return X}:U((function(t,e){var i,s=0,o=function(){if(null==i||i.unsubscribe(),i=null,null!=r){var t="number"==typeof r?Ot(r):ct(r(s)),n=N(e,(function(){n.unsubscribe(),a()}));t.subscribe(n)}else a()},a=function(){var r=!1;i=t.subscribe(N(e,void 0,(function(){++s<n?i?o():r=!0:e.complete()}))),r&&o()};a()}))}function jt(t,e){return U((function(r,n){var i=null,s=0,o=!1,a=function(){return o&&!i&&n.complete()};r.subscribe(N(n,(function(r){null==i||i.unsubscribe();var o=0,u=s++;ct(t(r,u)).subscribe(i=N(n,(function(t){return n.next(e?e(r,t,u,o++):t)}),(function(){i=null,a()})))}),(function(){o=!0,a()})))}))}function Bt(t,e,r){var n=d(t)||e||r?{next:t,error:e,complete:r}:t;return n?U((function(t,e){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var i=!0;t.subscribe(N(e,(function(t){var r;null===(r=n.next)||void 0===r||r.call(n,t),e.next(t)}),(function(){var t;i=!1,null===(t=n.complete)||void 0===t||t.call(n),e.complete()}),(function(t){var r;i=!1,null===(r=n.error)||void 0===r||r.call(n,t),e.error(t)}),(function(){var t,e;i&&(null===(t=n.unsubscribe)||void 0===t||t.call(n)),null===(e=n.finalize)||void 0===e||e.call(n)})))})):D}function Ht(t,e){void 0===e&&(e={});var r=e.selector,i=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]])}return r}(e,["selector"]);return new F((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?ct(r(t)).subscribe(N(e,void 0,(function(){a=!1,e.complete()}),h)):(a=!1,e.next(t),e.complete())})).catch(h),function(){a&&s.abort()}}))}class Yt{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 r,n,i=0,s=0;n=t.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?e+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);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 r=this.urlBase64Decode(e[1]);if(!r)throw new Error("Cannot decode the token.");return JSON.parse(r)}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 r=new Date(0);return r.setUTCSeconds(e.exp),r}isTokenExpired(t=this.token,e){if(null===t||""===t)return!0;const r=this.getTokenExpirationDate(t);return e=e||0,null===r||r.valueOf()<=(new Date).valueOf()+1e3*e}}const Kt="JWT_KEY",zt="JWT_REFRESH_KEY",Wt=216e5;class Gt{nuclia;_isAuthenticated=new K(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 r;switch(t){case"PUT":case"PATCH":case"POST":case"DELETE":r="WRITER";break;default:r="READER"}return"/kbs"===e||"PATCH"===t&&e?.startsWith("/kb")&&3===e?.split("/").length?r="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog")||e?.endsWith("/chat"))&&(r="READER"),r}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Ft((function(e,r){return t<=r}))),Ft((t=>!t)));var t}login(t,e,r){return this.fetch("/auth/login",{username:t,password:e},!1,r?{"X-STF-VALIDATION":r}:{}).pipe(Et((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(Kt),localStorage.removeItem(zt),this._isAuthenticated.next(!1)}refresh(){return this.fetch("/auth/refresh",{refresh_token:this.getRefreshToken()},!0,{}).pipe(Lt((t=>(this.logout(),vt(t)))),Et((t=>t.access_token?(this.storeTokens(t),!0):(this.logout(),!1))))}getToken(){return this.nuclia.options.public?"":localStorage.getItem(Kt)||""}setPassword(t){return this.fetch("/auth/setpassword",{password:t},!0,{}).pipe(Et((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 Yt(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(zt)||""}storeTokens(t){localStorage.setItem(Kt,t.access_token),localStorage.setItem(zt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new Yt(t),r=e.getTokenExpirationDate()?.getTime();if(r){const t=(new Date).getTime();if(r<t)this.logout();else{this._isAuthenticated.next(!0);const e=r-t<Wt?0:Wt;this.timerSubscription?.unsubscribe(),this.timerSubscription=Ot(e).pipe(jt((()=>this.refresh()))).subscribe()}}else this._isAuthenticated.next(!1)}else this._isAuthenticated.next(!1)}fetch(t,e,r,n){const i={"content-type":"application/json",...n};return r&&(i.Authorization=`Bearer ${this.getToken()}`),Ht(`${this.nuclia.backend}${t}`,{method:"POST",selector:t=>Promise.resolve(t),headers:i,body:JSON.stringify(e)}).pipe(jt((t=>t.ok?bt(t.clone().json()):vt(t))))}}const Mt="NUCLIA_NUA_KEY";var Vt,Jt,Xt,qt,Zt,Qt,te,ee,re,ne;t.AccountBlockingState=void 0,(Vt=t.AccountBlockingState||(t.AccountBlockingState={})).UNBLOCKED="unblocked",Vt.QUOTA="quota",Vt.MANAGER="manager",t.BlockedFeature=void 0,(Jt=t.BlockedFeature||(t.BlockedFeature={})).UPLOAD="upload",Jt.PROCESSING="processing",Jt.SEARCH="search",Jt.GENERATIVE="generative",t.StatsPeriod=void 0,(Xt=t.StatsPeriod||(t.StatsPeriod={})).DAY="day",Xt.WEEK="week",Xt.MONTH="month",Xt.YEAR="year",t.StatsRange=void 0,(qt=t.StatsRange||(t.StatsRange={})).anHour="1h",qt.twoHours="2h",qt.threeHours="3h",qt.sixHours="6h",qt.twelveHours="12h",qt.twentyFourHours="24h",qt.fortyHeightHours="48h",t.StatsType=void 0,(Zt=t.StatsType||(t.StatsType={})).PROCESSING_TIME="processing_time",Zt.SEARCHES="searches",Zt.CHARS="chars",Zt.MEDIA_SECONDS="media_seconds",Zt.BYTES="bytes",Zt.RESOURCES="resources",Zt.PAGES="pages",Zt.TRAIN_SECONDS="train_seconds",Zt.SUGGESTIONS="suggestions",Zt.DOCS_NO_MEDIA="docs_no_media",t.ResourceProperties=void 0,(Qt=t.ResourceProperties||(t.ResourceProperties={})).BASIC="basic",Qt.ORIGIN="origin",Qt.RELATIONS="relations",Qt.VALUES="values",Qt.EXTRACTED="extracted",Qt.ERRORS="errors",Qt.EXTRA="extra",t.ResourceFieldProperties=void 0,(te=t.ResourceFieldProperties||(t.ResourceFieldProperties={})).VALUE="value",te.EXTRACTED="extracted",te.ERROR="error",t.ExtractedDataTypes=void 0,(ee=t.ExtractedDataTypes||(t.ExtractedDataTypes={})).TEXT="text",ee.METADATA="metadata",ee.LARGE_METADATA="large_metadata",ee.VECTOR="vectors",ee.LINK="link",ee.FILE="file",t.LabelSetKind=void 0,(re=t.LabelSetKind||(t.LabelSetKind={})).RESOURCES="RESOURCES",re.PARAGRAPHS="PARAGRAPHS",t.EventType=void 0,(ne=t.EventType||(t.EventType={})).VISITED="VISITED",ne.MODIFIED="MODIFIED",ne.DELETED="DELETED",ne.NEW="NEW",ne.STARTED="STARTED",ne.STOPPED="STOPPED",ne.SEARCH="SEARCH",ne.PROCESSED="PROCESSED";const ie=524288,se=new RegExp(/[^a-z0-9_-]/g),oe=(t,e,r,n,i={})=>(i.contentType||r instanceof ArrayBuffer||(i.contentType="null"!==r?.type?r?.type:void 0),i.filename||r instanceof ArrayBuffer||(i.filename=r?.name),i.lang||r instanceof ArrayBuffer||(i.lang=r.lang),i.md5||r instanceof ArrayBuffer||(i.md5=r.md5),(r instanceof ArrayBuffer?yt(r):bt(r.arrayBuffer())).pipe(jt((s=>n?ue(t,e,s,i,r.payload):ae(t,e,s,i))))),ae=(t,e,r,n)=>{const i={"content-type":n?.contentType||"application/octet-stream",...he(n)};let s=1;const o=n?.rslug?`?rslug=${n.rslug}`:"";return t.rest.post(`${e}/upload${o}`,r,i,!0).pipe(Ct(),Ft((t=>0==s--||503!==t.status)),Nt(1),jt((t=>{try{switch(t.status){case 201:return bt(t.json()).pipe(Et((t=>({resource:t.uuid||"",field:t.field_id||"",completed:!0}))));case 409:return yt({conflict:!0});default:return yt({failed:!0})}}catch(t){return yt({failed:!0})}})))},ue=(t,e,r,n,i)=>{let s=0,o=0,a=!1;const u=r.byteLength,c=Math.ceil(u/ie),l={"upload-length":`${u}`,"tus-resumable":"1.0.0"},h=[];n?.filename&&h.push(`filename ${btoa(encodeURIComponent(n.filename))}`),n?.lang&&h.push(`language ${btoa(n.lang)}`),n?.md5&&h.push(`md5 ${btoa(n.md5)}`),h.push(`content_type ${btoa(n?.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(Ct(),Ft((t=>0==d--||503!==t.status)),Lt((t=>yt(t))),Nt(1),Ut((e=>Dt(yt(e).pipe(Ft((t=>201!==t.status||!t.headers.get("location"))),Et((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),yt(e).pipe(Ft((t=>201===t.status&&!!t.headers.get("location"))),Et((t=>t.headers.get("location"))),Ut((e=>function(t,e,r){if(null==e&&(e=t,t=0),e<=0)return X;var n=e+t;return new F(r?function(e){var i=t;return r.schedule((function(){i<n?(e.next(i++),this.schedule()):e.complete()}))}:function(e){for(var r=t;r<n&&!e.closed;)e.next(r++);e.complete()})}(0,c).pipe(Ut((()=>{const i=r.slice(s,s+ie);return o+=1,a?yt({failed:a}):t.rest.patch(e,i,{"content-type":n?.contentType||"application/octet-stream","upload-offset":`${s}`,"content-length":`${i.byteLength}`},!0).pipe(Et((t=>200!==t.status?(a=!0,{failed:a}):(s+=ie,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Lt((()=>(a=!0,yt({failed:!0})))))}))))))))))},ce=(t,e,r,n=!1)=>{const i=Array.from(r),s=i.reduce(((t,e)=>t+(e.size||0)),0),o=[],a=i.map((t=>({file:t,progress:0,uploaded:!1,failed:!1}))),u=i.map((r=>{let i=e;if(n){let t=r.name.toLowerCase().replace(se,"_");o.includes(t)&&(t+="_"+o.filter((e=>e.startsWith(t))).length),o.push(t),i=`${i}/file/${t}`}const s=r.lang;if(s){const t=r.payload||{};r.payload={...t,metadata:{...t?.metadata,language:s}}}return oe(t,i,r,!0,{}).pipe(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=Q(t);return U((function(e,n){(r?Pt(t,e,r):Pt(t,e)).subscribe(n)}))}({progress:0,completed:!1}),Et((t=>({status:t,file:r}))))}));return bt(u).pipe(Rt((t=>t),6),Et((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 r=a.filter((t=>t.failed)).length,n=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:r,conflicts:n}})))},le=(t,e,r,n)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":n?.contentType||"application/octet-stream",...he(n)};return t.rest.post("/processing/upload",r,i)},he=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 de,pe,fe,ge,be,ye;t.SortField=void 0,(de=t.SortField||(t.SortField={})).created="created",de.modified="modified",de.title="title",t.SHORT_FIELD_TYPE=void 0,(pe=t.SHORT_FIELD_TYPE||(t.SHORT_FIELD_TYPE={})).layout="l",pe.text="t",pe.file="f",pe.link="u",pe.datetime="d",pe.keywordset="k",pe.generic="a",pe.conversation="c",t.Search=void 0,fe=t.Search||(t.Search={}),(ge=fe.Features||(fe.Features={})).PARAGRAPH="paragraph",ge.DOCUMENT="document",ge.RELATIONS="relations",ge.VECTOR="vector",(be=fe.ResourceFeatures||(fe.ResourceFeatures={})).PARAGRAPH="paragraph",be.RELATIONS="relations",be.VECTOR="vector",(ye=fe.FindScoreType||(fe.FindScoreType={})).VECTOR="VECTOR",ye.BM25="BM25",ye.BOTH="BOTH";const ve=(t,e,r,n,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=n||"":a.query=n||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=`${r}/find`;return(o?t.rest.get(`${h}?${we(a,l)}`,void 0,!0):t.rest.post(h,{...a,...l},void 0,!0)).pipe(jt((e=>{const r=e.headers.get("X-Nuclia-Trace-Id")||"";return e.ok&&206!==e.status?bt(e.json().then((t=>({...t,searchId:r})),(()=>{console.warn(`${h} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...a,...l}),bt(e.json().then((t=>{throw{status:e.status,body:t}}),(()=>{throw{status:e.status}}))))})),Lt((t=>yt({type:"error",status:t.status,detail:t.detail,body:t.body}))),Et((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((r=>{"findResults"===r.type&&r.shards&&(t.currentShards={...t.currentShards,[e]:r.shards})})))},me=(t,e,r,n,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=n||"":a.query=n||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=o?t.rest.get(`${r}/search?${we(a,l)}`):t.rest.post(`${r}/search`,{...a,...l});return Te(t,e,h)},Ee=(t,e,r,n)=>{const i={};i.query=r||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${n?we(i,n):""}`);return Te(t,e,s)};function Te(t,e,r){return r.pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"searchResults"})),Bt((r=>{"searchResults"===r.type&&r.shards&&(t.currentShards={...t.currentShards,[e]:r.shards})})))}const we=(t,e)=>{Object.entries(e||{}).forEach((([e,r])=>{null!=r&&(Array.isArray(r)?t[e]=r.map((t=>`${t}`)):"object"==typeof r?Object.entries(r).forEach((([r,n])=>t[`${e}_${r}`]=`${n}`)):t[e]=`${r}`)}));const r=new URLSearchParams;return Object.entries(t).forEach((([t,e])=>Array.isArray(e)?e.forEach((e=>r.append(t,e))):r.append(t,e))),r.toString()};var Se,_e;t.Chat=void 0,function(t){t.PARAGRAPHS="paragraphs",t.RELATIONS="relations"}((Se=t.Chat||(t.Chat={})).Features||(Se.Features={})),(_e=Se.Author||(Se.Author={})).USER="USER",_e.NUCLIA="NUCLIA";const Ae="_END_";function xe(e,r,n,i=[],s=[t.Chat.Features.PARAGRAPHS],o={}){let a,u,c=0,l="";return e.rest.getStream(`${r}/chat`,{query:n,context:i,show:[t.ResourceProperties.BASIC,t.ResourceProperties.VALUES],features:s.length>0?s:void 0,...o}).pipe(Et((({data:t,incomplete:e,headers:r})=>{const n=r.get("X-Nuclia-Trace-Id")||"",i=r.get("NUCLIA-LEARNING-ID")||"";if(0===c&&t.length>=4&&(c=new DataView(t.buffer.slice(0,4)).getUint32(0)),!a&&c>0&&t.length>c+4){const e=t.slice(4,c+4);a=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}if(a&&(a.searchId=n),a&&t.length>c+4&&(l=(new TextDecoder).decode(t.slice(c+4).buffer),l.includes(Ae))){let t;if([l,t]=l.split(Ae),t)try{u=JSON.parse(atob(t)),a.relations=u}catch(t){console.warn(t)}}return{type:"answer",text:l,sources:a,incomplete:e,id:i}})),Lt((t=>yt({type:"error",status:t.status,detail:t.detail||""}))))}const ke=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),Re=(t,e,r,n,i)=>{const s=ke(i.filter((r=>Pe(r,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=ke(i.filter((r=>Ie(r,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==r)),a=i.filter((r=>r.field.field!==t||r.field.field_type!==e)),u=n.length>0?[...o,{key:r,classifications:n}]: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},$e=(t,e,r,n)=>{const i=ke(n.filter((r=>Ie(r,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),s=n.filter((r=>r.field.field!==t||r.field.field_type!==e));return r.length>0||i.length>0?[...s,{field:{field:t,field_type:e},token:r.length>0?r:void 0,paragraphs:i.length>0?i:void 0}]:s},Pe=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.token&&t.token.length>0,Ie=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.paragraphs&&t.paragraphs.length>0,Oe=(t,e,r)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,r).join("")):"";class De{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 r=this.data[t]?.[e];return r||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,r])=>(t[r]=(t[r]||[]).concat([e]),t)),{}))).reduce(((t,e)=>(Object.entries(e).forEach((([e,r])=>{t[e]=(t[e]||[]).concat(r)})),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,r)=>(r.classifications.forEach((r=>{const n=t.find((t=>t.label===r.label&&t.labelset===r.labelset)),i=e.find((t=>t.label===r.label&&t.labelset===r.labelset));n||i||t.push({...r,immutable:!0})})),t)),t)}getPositionedNamedEntities(t,e){const r=this.data[t]?.[e]?.extracted?.metadata?.metadata.positions;return r?Object.entries(r).reduce(((t,[e,r])=>{const n=e.split("/")[0];return r.position.forEach((e=>{t.push({entity:r.entity,family:n,...e})})),t}),[]):[]}formatTitle(t){t=t||"–";try{return decodeURIComponent(t)}catch(e){return t}}getParagraphText(t,e,r){return Oe(this.getFieldText(t,e),r.start,r.end)}getSentenceText(t,e,r){return Oe(this.getFieldText(t,e),r.start,r.end)}getFieldText(t,e){const r=`${t}-${e}`;if(!this.fieldTextsCache[r]){const n=this.getFieldData(`${t}s`,e);this.fieldTextsCache[r]=Array.from(n?.extracted?.text?.text||"")}return this.fieldTextsCache[r]}}class Fe extends De{kb;uuid;nuclia;get path(){if(!this.uuid&&!this.slug)throw new Error("Resource must have either uuid or slug");return this.uuid?`/kb/${this.kb}/resource/${this.uuid}`:`/kb/${this.kb}/slug/${this.slug}`}constructor(t,e,r){super(r),this.nuclia=t,this.kb=e,this.uuid=r.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(e,r,n=[t.ResourceFieldProperties.VALUE],i=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){const s=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this.path}/${e}/${r}?${s.join("&")}`)}getThumbnailsUrl(){return It(this.getThumbnails().filter((t=>t.uri)).map((t=>this.nuclia.rest.getObjectURL(t.uri))))}deleteField(t,e){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`)}setField(t,e,r){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,r)}upload(t,e,r,n){return oe(this.nuclia,`${this.path}/file/${t}`,e,!!r,n)}batchUpload(t){return ce(this.nuclia,this.path,t,!0)}search(t,e=[],r){return me(this.nuclia,this.kb,this.path,t,e,r,!0)}setLabels(t,e,r,n){const i=Re(t,e,r,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,r){const n=$e(t,e,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:n}).pipe(Bt((()=>this.fieldmetadata=n)))}}var Le,Ue;t.FIELD_TYPE=void 0,(Le=t.FIELD_TYPE||(t.FIELD_TYPE={})).text="text",Le.file="file",Le.link="link",Le.layout="layout",Le.conversation="conversation",Le.keywordset="keywordset",Le.datetime="datetime",Le.generic="generic",t.RESOURCE_STATUS=void 0,(Ue=t.RESOURCE_STATUS||(t.RESOURCE_STATUS={})).PENDING="PENDING",Ue.PROCESSED="PROCESSED",Ue.ERROR="ERROR";var Ne,Ce,je;t.TrainingType=void 0,(Ne=t.TrainingType||(t.TrainingType={})).classifier="classifier",Ne.resource_labeler="resource-labeler",Ne.paragraph_labeler="paragraph-labeler",Ne.ner="ner",t.TrainingStatus=void 0,(Ce=t.TrainingStatus||(t.TrainingStatus={})).finished="finished",Ce.not_running="not_running",Ce.running="running",Ce.started="started",Ce.stopped="stopped",t.TrainingExecutionStatus=void 0,(je=t.TrainingExecutionStatus||(t.TrainingExecutionStatus={})).succeeded="succeeded",je.failed="failed",je.stopped="stopped";class Be{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(e){return this.nuclia.rest.get(`${this.kb.path}/train/${e}/inspect`).pipe(Lt((()=>yt({task:"",status:t.TrainingStatus.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(Et((()=>!0)),Lt((()=>yt(!1))))}}class He{account;nuclia;get path(){return`/kb/${this.id}`}get fullpath(){return`${this.nuclia.regionalBackend}/v1/kb/${this.id}`}constructor(t,e,r){this.nuclia=t,this.account=e,Object.assign(this,r),!r.id&&r.uuid&&(this.id=r.uuid),!r.title&&r.slug&&(this.title=r.slug)}getEntities(t=!1){return this.nuclia.rest.get(`${this.path}/entitiesgroups?show_entities=${t}`).pipe(Et((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(Et((t=>t.synonyms)))}getLabels(){return this.nuclia.rest.get(`${this.path}/labelsets`).pipe(Et((t=>t?.labelsets||{})),Lt((()=>yt({}))))}getResource(e,r=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],n=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){return this._getResource(e,void 0,r,n)}getResourceBySlug(e,r=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],n=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){return this._getResource(void 0,e,r,n)}_getResource(e,r,n=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],i=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){const s=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this._getPath(e,r)}?${s.join("&")}`).pipe(Et((t=>new Fe(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Fe(this.nuclia,this.id,t)}chat(t,e,r,n){return xe(this.nuclia,this.path,t,e,r,n)}find(t,e=[],r){return ve(this.nuclia,this.id,this.path,t,e,r)}search(t,e=[],r){return me(this.nuclia,this.id,this.path,t,e,r)}catalog(t,e){return Ee(this.nuclia,this.id,t,e)}suggest(t,e=!1){const r=`query=${encodeURIComponent(t)}${e?"&fields=a/title":""}`;return this.nuclia.rest.get(`${this.path}/suggest?${r}`).pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"suggestions"})))}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 r=[t?`page=${t}`:"",e?`size=${e}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/resources${r?"?"+r:""}`).pipe(Et((t=>({resources:t.resources.map((t=>new Fe(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(!this.nuclia.options.account||!this.nuclia.options.kbSlug)throw new Error("Account and KB slug are required to get a temp token");return this.nuclia.rest.post(`/account/${this.nuclia.options.account}/kb/${this.nuclia.options.kbSlug}/ephemeral_tokens`,{}).pipe(Et((t=>t.token)))}listActivity(t,e,r){const n=[t?`type=${t}`:"",e?`page=${e}`:"",r?`size=${r}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/activity${n?"?"+n:""}`)}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ye extends He{admin;contrib;_training;get training(){return this._training||(this._training=new Be(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(){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}`)}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,r=!0,n){return this.createResource({links:{link:t},usermetadata:e,title:t.uri,icon:"application/stf-link",...n?{origin:n}:{}},r)}hasResource(t){return this.nuclia.rest.get(`${this.path}/slug/${t}`).pipe(Et((()=>!0)),Lt((()=>yt(!1))))}createOrUpdateResource(t,e=!0){return(t.slug?this.hasResource(t.slug):yt(!1)).pipe(jt((r=>r?this.getResourceFromData({id:"",slug:t.slug}).modify(t,e):this.createResource(t,e))))}upload(t,e,r){return oe(this.nuclia,`/kb/${this.id}`,t,!!e,r)}batchUpload(t){return ce(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 r=e.find((e=>e.title===t.title&&e.role===t.role));return r?yt(r):this.createServiceAccount(t).pipe(jt((()=>this.getServiceAccounts())),Et((e=>e.find((e=>e.title===t.title&&e.role===t.role)))))})),jt((t=>t?this.createKey(t.id,e):yt({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)}}class Ke{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(Et((t=>t.kbs)))}getKnowledgeBoxes(t){return this.nuclia.rest.get(`/account/${t}/kbs`)}getKnowledgeBox(t,e){if(t=t||this.nuclia.options.account){const r=e||this.nuclia.options.knowledgeBox||this.nuclia.options.kbSlug;if(!r)throw new Error("account and knowledgeBox must be defined in the Nuclia options");const n=this.nuclia.options.standalone?`/kb/${e}`:`/account/${t}/kb/${r}`;return this.nuclia.rest.get(n).pipe(jt((t=>this.nuclia.options.zone||this.nuclia.options.standalone?yt(t):this.nuclia.rest.getZoneSlug(t.zone).pipe(Bt((t=>this.nuclia.options.zone=t)),Et((()=>t))))),Et((e=>new Ye(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 yt(new Ye(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((r=>{const n=r.id||r.uuid;if(!n)throw"KnowledgeBox creation failed";return this.getKnowledgeBox(t,this.nuclia.options.standalone?n:e.slug)})))}getStats(e,r,n,i=t.StatsPeriod.DAY,s){const o=[`period=${i}`,`stats=${r}`];return s&&o.push(`utctime=${s}`),n&&o.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${e}/stats?${o.join("&")}`).pipe(Et((t=>t.data)),Ft((t=>!!t)))}upload(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /process");return le(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",r=t?void 0:this.getNUAHeader();return this.nuclia.rest.get(e,r)}getProcessingStats(t,e){const r=this.hasNUAClient();if(!e&&!r)throw new Error("NUA key or account id is needed to be able to call /processing/stats");const n=r?"/processing/stats"+(t?"?period="+t:""):`/processing/stats?account_id=${e}${t?"&period="+t:""}`,i=r?this.getNUAHeader():void 0;return this.nuclia.rest.get(n,i).pipe(Et((t=>t.data)))}getNUAActivity(t,e,r=0){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}/activity?page=${r}`)}getNUAClients(t){return this.nuclia.rest.get(`/account/${t}/nua_clients`).pipe(Et((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 r={...e};return r.webhook&&(r.processing_webhook={uri:r.webhook},delete r.webhook),this.nuclia.rest.post(`/account/${t}/nua_clients`,r).pipe(Lt((r=>{if(409===r.status&&e.client_id)return this.renewNUAClient(t,e.client_id);throw r})),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(Et((t=>t.tokens)))}}class ze{nuclia;zones;constructor(t){this.nuclia=t}get(t,e,r){return this.fetch("GET",t,void 0,e,r)}post(t,e,r,n,i){return this.fetch("POST",t,e,r,n,i)}put(t,e,r,n,i){return this.fetch("PUT",t,e,r,n,i)}patch(t,e,r,n,i){return this.fetch("PATCH",t,e,r,n,i)}delete(t,e,r){return this.fetch("DELETE",t,void 0,e,!0,r)}head(t,e){return this.fetch("HEAD",t,void 0,e,!0)}getHeaders(t,e,r,n=!1){const i=r&&r["x-stf-nuakey"]?{}:this.nuclia.auth.getAuthHeaders(t,e),s={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return n&&(s["x-synchronous"]=`${n}`),{...s,...r}}fetch(t,e,r,n,i,s=!1){const o=n&&n["content-type"];return bt(fetch(this.getFullUrl(e),{method:t,headers:this.getHeaders(t,e,n,s),body:o?r:JSON.stringify(r)}).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")||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?yt(this.zones):this.get("/zones").pipe(Et((t=>{const e=t.reduce(((t,e)=>(t[e.id]=e.slug,t)),{});return this.zones=e,e})))}getZoneSlug(t){return this.getZones().pipe(Et((e=>e[t])))}getObjectURL(t){return this.get(t,void 0,!0).pipe(jt((t=>bt(t.blob()))),Et((t=>URL.createObjectURL(t))))}getStream(t,e){return t=this.getFullUrl(t),new F((r=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),n=t.headers,i=t.status;if(e&&t.ok){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:s})=>{e&&(r.next({data:t,incomplete:!1,headers:n}),r.complete()),s&&(t=this.concat(t,s),r.next({data:t,incomplete:!0,headers:n}),i())}))};i()}else r.error({status:i}),r.complete()}))}))}concat(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}}class We{messages=new B;emit(t,e){this.messages.next({name:t,data:e})}on(t){return this.messages.asObservable().pipe(Ft((e=>e.name===t)),Et((t=>t.data)))}}t.Authentication=Gt,t.ConversationFieldData=class{value;extracted;error},t.Db=Ke,t.FileFieldData=class{value;extracted;error},t.JwtHelper=Yt,t.KeywordSetFieldData=class{value;extracted;error},t.KnowledgeBox=He,t.LinkFieldData=class{value;extracted;error},t.NUA_KEY=Mt,t.Nuclia=class{options;auth;rest;db;currentShards={};events=new We;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 He(this,"",{id:this.options.knowledgeBox,zone:this.options.zone||""})),this.readKb}get asyncKnowledgeBox(){return new Proxy(this.knowledgeBox,{get(t,e){const r=Reflect.get(t,e);return"function"==typeof r?(...e)=>function(t,e){var r="object"==typeof e;return new Promise((function(n,i){var s=new $({next:function(t){n(t),s.unsubscribe()},error:i,complete:function(){r?n(e.defaultValue):i(new mt)}});t.subscribe(s)}))}(r.bind(t)(...e)):r}})}constructor(t){this.options=t,this.auth=new Gt(this),this.rest=new ze(this),this.db=new Ke(this)}},t.ReadableResource=De,t.Resource=Fe,t.Rest=ze,t.TUSuploadFile=ue,t.TextFieldData=class{value;extracted;error},t.Training=Be,t.WritableKnowledgeBox=Ye,t.batchUpload=ce,t.catalog=Ee,t.chat=xe,t.deDuplicateList=ke,t.find=ve,t.getDataKeyFromFieldType=e=>{switch(e){case t.FIELD_TYPE.text:case t.FIELD_TYPE.file:case t.FIELD_TYPE.link:case t.FIELD_TYPE.keywordset:return`${e}s`;default:return null}},t.getEntityFromFilter=function(t){const e=t.split("/");return{family:e[2],entity:e[3]}},t.getFieldTypeFromString=function(e){switch(e){case t.FIELD_TYPE.file:return t.FIELD_TYPE.file;case t.FIELD_TYPE.link:return t.FIELD_TYPE.link;case t.FIELD_TYPE.text:return t.FIELD_TYPE.text;case t.FIELD_TYPE.layout:return t.FIELD_TYPE.layout;case t.FIELD_TYPE.conversation:return t.FIELD_TYPE.conversation;case t.FIELD_TYPE.datetime:return t.FIELD_TYPE.datetime;default:return null}},t.getFileMetadata=he,t.getFilterFromEntity=function(t){return`/e/${t.family}/${t.entity}`},t.getFilterFromLabel=function(t){return`/l/${t.labelset}/${t.label}`},t.getLabelFromFilter=function(t){const e=t.split("/");return{labelset:e[2],label:e[3]}},t.lengthUnicode=t=>t?Array.from(t).length:0,t.longToShortFieldType=function(e){return t.SHORT_FIELD_TYPE[e]},t.resourceToAlgoliaFormat=(t,e)=>{const r={title:t.title,fullText:t.getExtractedTexts().filter((t=>t)).map((t=>t.text))};t.getClassifications().forEach((t=>{t.labelset&&t.label&&(r[t.labelset]=t.label)}));const n=t.getThumbnails().filter((t=>!!t.uri)).map((t=>`${e}/v1${t.uri}`));return{...r,images:n,...t.getNamedEntities()}},t.search=me,t.setEntities=$e,t.setLabels=Re,t.shortToLongFieldType=function(e){switch(e){case t.SHORT_FIELD_TYPE.conversation:return t.FIELD_TYPE.conversation;case t.SHORT_FIELD_TYPE.datetime:return t.FIELD_TYPE.datetime;case t.SHORT_FIELD_TYPE.file:return t.FIELD_TYPE.file;case t.SHORT_FIELD_TYPE.layout:return t.FIELD_TYPE.layout;case t.SHORT_FIELD_TYPE.keywordset:return t.FIELD_TYPE.keywordset;case t.SHORT_FIELD_TYPE.link:return t.FIELD_TYPE.link;case t.SHORT_FIELD_TYPE.text:return t.FIELD_TYPE.text;default:return null}},t.sliceUnicode=Oe,t.upload=oe,t.uploadFile=ae,t.uploadToProcess=le})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NucliaSDK={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};function r(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}var n=function(){return n=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},n.apply(this,arguments)};function i(t,e,r,n){return new(r||(r=Promise))((function(i,s){function o(t){try{u(n.next(t))}catch(t){s(t)}}function a(t){try{u(n.throw(t))}catch(t){s(t)}}function u(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}u((n=n.apply(t,e||[])).next())}))}function s(t,e){var r,n,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(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=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++,n=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],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function o(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,s=r.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}return o}function u(t,e,r){if(r||2===arguments.length)for(var n,i=0,s=e.length;i<s;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))}function c(t){return this instanceof c?(this.v=t,this):new c(t)}function l(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(t,e||[]),s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(t){i[t]&&(n[t]=function(e){return new Promise((function(r,n){s.push([t,e,r,n])>1||a(t,e)}))})}function a(t,e){try{(r=i[t](e)).value instanceof c?Promise.resolve(r.value.v).then(u,l):h(s[0][2],r)}catch(t){h(s[0][3],t)}var r}function u(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 h(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,r=t[Symbol.asyncIterator];return r?r.call(t):(t=o(t),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(r){e[r]=t[r]&&function(e){return new Promise((function(n,i){(function(t,e,r,n){Promise.resolve(n).then((function(e){t({value:e,done:r})}),e)})(n,i,(e=t[r](e)).done,e.value)}))}}}function d(t){return"function"==typeof t}function p(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=p((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 g(t,e){if(t){var r=t.indexOf(e);0<=r&&t.splice(r,1)}}var b=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,r,n,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=o(s),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 s.remove(this);var h=this.initialTeardown;if(d(h))try{h()}catch(t){i=t instanceof f?t.errors:[t]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var g=o(p),b=g.next();!b.done;b=g.next()){var y=b.value;try{m(y)}catch(t){i=null!=i?i:[],t instanceof f?i=u(u([],a(i)),a(t.errors)):i.push(t)}}}catch(t){r={error:t}}finally{try{b&&!b.done&&(n=g.return)&&n.call(g)}finally{if(r)throw r.error}}}if(i)throw new f(i)}},t.prototype.add=function(e){var r;if(e&&e!==this)if(this.closed)m(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).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)&&g(e,t)},t.prototype.remove=function(e){var r=this._finalizers;r&&g(r,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),y=b.EMPTY;function v(t){return t instanceof b||t&&"closed"in t&&d(t.remove)&&d(t.add)&&d(t.unsubscribe)}function m(t){d(t)?t():t.unsubscribe()}var E={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},T={setTimeout:function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,u([t,e],a(r)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function S(t){T.setTimeout((function(){throw t}))}function w(){}function _(t){t()}var A=function(t){function e(e){var r=t.call(this)||this;return r.isStopped=!1,e?(r.destination=e,v(e)&&e.add(r)):r.destination=I,r}return r(e,t),e.create=function(t,e,r){return new $(t,e,r)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(b),x=Function.prototype.bind;function k(t,e){return x.call(t,e)}var R=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){P(t)}},t.prototype.error=function(t){var e=this.partialObserver;if(e.error)try{e.error(t)}catch(t){P(t)}else P(t)},t.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(t){P(t)}},t}(),$=function(t){function e(e,r,n){var i,s,o=t.call(this)||this;d(e)||!e?i={next:null!=e?e:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:o&&E.useDeprecatedNextContext?((s=Object.create(e)).unsubscribe=function(){return o.unsubscribe()},i={next:e.next&&k(e.next,s),error:e.error&&k(e.error,s),complete:e.complete&&k(e.complete,s)}):i=e;return o.destination=new R(i),o}return r(e,t),e}(A);function P(t){S(t)}var I={closed:!0,next:w,error:function(t){throw t},complete:w},O="function"==typeof Symbol&&Symbol.observable||"@@observable";function D(t){return t}var F=function(){function t(t){t&&(this._subscribe=t)}return t.prototype.lift=function(e){var r=new t;return r.source=this,r.operator=e,r},t.prototype.subscribe=function(t,e,r){var n,i=this,s=(n=t)&&n instanceof A||function(t){return t&&d(t.next)&&d(t.error)&&d(t.complete)}(n)&&v(n)?t:new $(t,e,r);return _((function(){var t=i,e=t.operator,r=t.source;s.add(e?e.call(s,r):r?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 r=this;return new(e=L(e))((function(e,n){var i=new $({next:function(e){try{t(e)}catch(t){n(t),i.unsubscribe()}},error:n,complete:e});r.subscribe(i)}))},t.prototype._subscribe=function(t){var e;return null===(e=this.source)||void 0===e?void 0:e.subscribe(t)},t.prototype[O]=function(){return this},t.prototype.pipe=function(){for(var t,e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return(0===(t=e).length?D: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=L(t))((function(t,r){var n;e.subscribe((function(t){return n=t}),(function(t){return r(t)}),(function(){return t(n)}))}))},t.create=function(e){return new t(e)},t}();function L(t){var e;return null!==(e=null!=t?t:E.Promise)&&void 0!==e?e:Promise}function N(t){return function(e){if(function(t){return d(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 C(t,e,r,n,i){return new U(t,e,r,n,i)}var U=function(t){function e(e,r,n,i,s,o){var a=t.call(this,e)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=r?function(t){try{r(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=n?function(){try{n()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,a}return r(e,t),e.prototype.unsubscribe=function(){var e;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&(null===(e=this.onFinalize)||void 0===e||e.call(this))}},e}(A),j=p((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),B=function(t){function e(){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 r(e,t),e.prototype.lift=function(t){var e=new H(this,this);return e.operator=t,e},e.prototype._throwIfClosed=function(){if(this.closed)throw new j},e.prototype.next=function(t){var e=this;_((function(){var r,n;if(e._throwIfClosed(),!e.isStopped){e.currentObservers||(e.currentObservers=Array.from(e.observers));try{for(var i=o(e.currentObservers),s=i.next();!s.done;s=i.next()){s.value.next(t)}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}}}))},e.prototype.error=function(t){var e=this;_((function(){if(e._throwIfClosed(),!e.isStopped){e.hasError=e.isStopped=!0,e.thrownError=t;for(var r=e.observers;r.length;)r.shift().error(t)}}))},e.prototype.complete=function(){var t=this;_((function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var e=t.observers;e.length;)e.shift().complete()}}))},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return(null===(t=this.observers)||void 0===t?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var e=this,r=this,n=r.hasError,i=r.isStopped,s=r.observers;return n||i?y:(this.currentObservers=null,s.push(t),new b((function(){e.currentObservers=null,g(s,t)})))},e.prototype._checkFinalizedStatuses=function(t){var e=this,r=e.hasError,n=e.thrownError,i=e.isStopped;r?t.error(n):i&&t.complete()},e.prototype.asObservable=function(){var t=new F;return t.source=this,t},e.create=function(t,e){return new H(t,e)},e}(F),H=function(t){function e(e,r){var n=t.call(this)||this;return n.destination=e,n.source=r,n}return r(e,t),e.prototype.next=function(t){var e,r;null===(r=null===(e=this.destination)||void 0===e?void 0:e.next)||void 0===r||r.call(e,t)},e.prototype.error=function(t){var e,r;null===(r=null===(e=this.destination)||void 0===e?void 0:e.error)||void 0===r||r.call(e,t)},e.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)},e.prototype._subscribe=function(t){var e,r;return null!==(r=null===(e=this.source)||void 0===e?void 0:e.subscribe(t))&&void 0!==r?r:y},e}(B),Y={now:function(){return(Y.delegate||Date).now()},delegate:void 0},K=function(t){function e(e,r,n){void 0===e&&(e=1/0),void 0===r&&(r=1/0),void 0===n&&(n=Y);var i=t.call(this)||this;return i._bufferSize=e,i._windowTime=r,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,e),i._windowTime=Math.max(1,r),i}return r(e,t),e.prototype.next=function(e){var r=this,n=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,o=r._timestampProvider,a=r._windowTime;n||(i.push(e),!s&&i.push(o.now()+a)),this._trimBuffer(),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var e=this._innerSubscribe(t),r=this._infiniteTimeWindow,n=this._buffer.slice(),i=0;i<n.length&&!t.closed;i+=r?1:2)t.next(n[i]);return this._checkFinalizedStatuses(t),e},e.prototype._trimBuffer=function(){var t=this,e=t._bufferSize,r=t._timestampProvider,n=t._buffer,i=t._infiniteTimeWindow,s=(i?1:2)*e;if(e<1/0&&s<n.length&&n.splice(0,n.length-s),!i){for(var o=r.now(),a=0,u=1;u<n.length&&n[u]<=o;u+=2)a=u;a&&n.splice(0,a+1)}},e}(B),z=function(t){function e(e,r){return t.call(this)||this}return r(e,t),e.prototype.schedule=function(t,e){return this},e}(b),W=function(t,e){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,u([t,e],a(r)))},G=function(t){return clearInterval(t)},M=function(t){function e(e,r){var n=t.call(this,e,r)||this;return n.scheduler=e,n.work=r,n.pending=!1,n}return r(e,t),e.prototype.schedule=function(t,e){var r;if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,i=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(i,n,e)),this.pending=!0,this.delay=e,this.id=null!==(r=this.id)&&void 0!==r?r:this.requestAsyncId(i,this.id,e),this},e.prototype.requestAsyncId=function(t,e,r){return void 0===r&&(r=0),W(t.flush.bind(t,this),r)},e.prototype.recycleAsyncId=function(t,e,r){if(void 0===r&&(r=0),null!=r&&this.delay===r&&!1===this.pending)return e;null!=e&&G(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(t,e);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var r,n=!1;try{this.work(t)}catch(t){n=!0,r=t||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),r},e.prototype.unsubscribe=function(){if(!this.closed){var e=this.id,r=this.scheduler,n=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,g(n,this),null!=e&&(this.id=this.recycleAsyncId(r,e,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(z),V=function(){function t(e,r){void 0===r&&(r=t.now),this.schedulerActionCtor=e,this.now=r}return t.prototype.schedule=function(t,e,r){return void 0===e&&(e=0),new this.schedulerActionCtor(this,t).schedule(r,e)},t.now=Y.now,t}(),J=new(function(t){function e(e,r){void 0===r&&(r=V.now);var n=t.call(this,e,r)||this;return n.actions=[],n._active=!1,n}return r(e,t),e.prototype.flush=function(t){var e=this.actions;if(this._active)e.push(t);else{var r;this._active=!0;do{if(r=t.execute(t.state,t.delay))break}while(t=e.shift());if(this._active=!1,r){for(;t=e.shift();)t.unsubscribe();throw r}}},e}(V))(M),X=new F((function(t){return t.complete()}));function q(t){return t&&d(t.schedule)}function Z(t){return t[t.length-1]}function Q(t){return q(Z(t))?t.pop():void 0}var tt=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function et(t){return d(null==t?void 0:t.then)}function rt(t){return d(t[O])}function nt(t){return Symbol.asyncIterator&&d(null==t?void 0:t[Symbol.asyncIterator])}function it(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 st="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ot(t){return d(null==t?void 0:t[st])}function at(t){return l(this,arguments,(function(){var e,r,n;return s(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,c(e.read())];case 3:return r=i.sent(),n=r.value,r.done?[4,c(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,c(n)];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 ut(t){return d(null==t?void 0:t.getReader)}function ct(t){if(t instanceof F)return t;if(null!=t){if(rt(t))return i=t,new F((function(t){var e=i[O]();if(d(e.subscribe))return e.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(tt(t))return n=t,new F((function(t){for(var e=0;e<n.length&&!t.closed;e++)t.next(n[e]);t.complete()}));if(et(t))return r=t,new F((function(t){r.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,S)}));if(nt(t))return lt(t);if(ot(t))return e=t,new F((function(t){var r,n;try{for(var i=o(e),s=i.next();!s.done;s=i.next()){var a=s.value;if(t.next(a),t.closed)return}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}t.complete()}));if(ut(t))return lt(at(t))}var e,r,n,i;throw it(t)}function lt(t){return new F((function(e){(function(t,e){var r,n,o,a;return i(this,void 0,void 0,(function(){var i,u;return s(this,(function(s){switch(s.label){case 0:s.trys.push([0,5,6,11]),r=h(t),s.label=1;case 1:return[4,r.next()];case 2:if((n=s.sent()).done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];s.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=s.sent(),o={error:u},[3,11];case 6:return s.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:s.sent(),s.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 ht(t,e,r,n,i){void 0===n&&(n=0),void 0===i&&(i=!1);var s=e.schedule((function(){r(),i?t.add(this.schedule(null,n)):this.unsubscribe()}),n);if(t.add(s),!i)return s}function dt(t,e){return void 0===e&&(e=0),N((function(r,n){r.subscribe(C(n,(function(r){return ht(n,t,(function(){return n.next(r)}),e)}),(function(){return ht(n,t,(function(){return n.complete()}),e)}),(function(r){return ht(n,t,(function(){return n.error(r)}),e)})))}))}function pt(t,e){return void 0===e&&(e=0),N((function(r,n){n.add(t.schedule((function(){return r.subscribe(n)}),e))}))}function ft(t,e){if(!t)throw new Error("Iterable cannot be null");return new F((function(r){ht(r,e,(function(){var n=t[Symbol.asyncIterator]();ht(r,e,(function(){n.next().then((function(t){t.done?r.complete():r.next(t.value)}))}),0,!0)}))}))}function gt(t,e){if(null!=t){if(rt(t))return function(t,e){return ct(t).pipe(pt(e),dt(e))}(t,e);if(tt(t))return function(t,e){return new F((function(r){var n=0;return e.schedule((function(){n===t.length?r.complete():(r.next(t[n++]),r.closed||this.schedule())}))}))}(t,e);if(et(t))return function(t,e){return ct(t).pipe(pt(e),dt(e))}(t,e);if(nt(t))return ft(t,e);if(ot(t))return function(t,e){return new F((function(r){var n;return ht(r,e,(function(){n=t[st](),ht(r,e,(function(){var t,e,i;try{e=(t=n.next()).value,i=t.done}catch(t){return void r.error(t)}i?r.complete():r.next(e)}),0,!0)})),function(){return d(null==n?void 0:n.return)&&n.return()}}))}(t,e);if(ut(t))return function(t,e){return ft(at(t),e)}(t,e)}throw it(t)}function bt(t,e){return e?gt(t,e):ct(t)}function yt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return bt(t,Q(t))}function vt(t,e){var r=d(t)?t:function(){return t},n=function(t){return t.error(r())};return new F(e?function(t){return e.schedule(n,0,t)}:n)}var mt=p((function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Et(t,e){return N((function(r,n){var i=0;r.subscribe(C(n,(function(r){n.next(t.call(e,r,i++))})))}))}var Tt=Array.isArray;function St(t){return Et((function(e){return function(t,e){return Tt(e)?t.apply(void 0,u([],a(e))):t(e)}(t,e)}))}var wt=Array.isArray,_t=Object.getPrototypeOf,At=Object.prototype,xt=Object.keys;function kt(t){if(1===t.length){var e=t[0];if(wt(e))return{args:e,keys:null};if((n=e)&&"object"==typeof n&&_t(n)===At){var r=xt(e);return{args:r.map((function(t){return e[t]})),keys:r}}}var n;return{args:t,keys:null}}function Rt(t,e,r){return void 0===r&&(r=1/0),d(e)?Rt((function(r,n){return Et((function(t,i){return e(r,t,n,i)}))(ct(t(r,n)))}),r):("number"==typeof e&&(r=e),N((function(e,n){return function(t,e,r,n,i,s,o,a){var u=[],c=0,l=0,h=!1,d=function(){!h||u.length||c||e.complete()},p=function(t){return c<n?f(t):u.push(t)},f=function(t){s&&e.next(t),c++;var a=!1;ct(r(t,l++)).subscribe(C(e,(function(t){null==i||i(t),s?p(t):e.next(t)}),(function(){a=!0}),void 0,(function(){if(a)try{c--;for(var t=function(){var t=u.shift();o?ht(e,o,(function(){return f(t)})):f(t)};u.length&&c<n;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(C(e,p,(function(){h=!0,d()}))),function(){null==a||a()}}(e,n,t,r)})))}function $t(t){return void 0===t&&(t=1/0),Rt(D,t)}function Pt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $t(1)(bt(t,Q(t)))}function It(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=function(t){return d(Z(t))?t.pop():void 0}(t),n=kt(t),i=n.args,s=n.keys,o=new F((function(t){var e=i.length;if(e)for(var r=new Array(e),n=e,o=e,a=function(e){var a=!1;ct(i[e]).subscribe(C(t,(function(t){a||(a=!0,o--),r[e]=t}),(function(){return n--}),void 0,(function(){n&&a||(o||t.next(s?function(t,e){return t.reduce((function(t,r,n){return t[r]=e[n],t}),{})}(s,r):r),t.complete())})))},u=0;u<e;u++)a(u);else t.complete()}));return r?o.pipe(St(r)):o}function Ot(t,e,r){void 0===t&&(t=0),void 0===r&&(r=J);var n=-1;return null!=e&&(q(e)?r=e:n=e),new F((function(e){var i,s=(i=t)instanceof Date&&!isNaN(i)?+t-r.now():t;s<0&&(s=0);var o=0;return r.schedule((function(){e.closed||(e.next(o++),0<=n?this.schedule(void 0,n):e.complete())}),s)}))}function Dt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=Q(t),n=function(t,e){return"number"==typeof Z(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?ct(i[0]):$t(n)(bt(i,r)):X}function Ft(t,e){return N((function(r,n){var i=0;r.subscribe(C(n,(function(r){return t.call(e,r,i++)&&n.next(r)})))}))}function Lt(t){return N((function(e,r){var n,i=null,s=!1;i=e.subscribe(C(r,void 0,void 0,(function(o){n=ct(t(o,Lt(t)(e))),i?(i.unsubscribe(),i=null,n.subscribe(r)):s=!0}))),s&&(i.unsubscribe(),i=null,n.subscribe(r))}))}function Nt(t,e){return d(e)?Rt(t,e,1):Rt(t,1)}function Ct(t){return t<=0?function(){return X}:N((function(e,r){var n=0;e.subscribe(C(r,(function(e){++n<=t&&(r.next(e),t<=n&&r.complete())})))}))}function Ut(t){var e,r,n=1/0;return null!=t&&("object"==typeof t?(e=t.count,n=void 0===e?1/0:e,r=t.delay):n=t),n<=0?function(){return X}:N((function(t,e){var i,s=0,o=function(){if(null==i||i.unsubscribe(),i=null,null!=r){var t="number"==typeof r?Ot(r):ct(r(s)),n=C(e,(function(){n.unsubscribe(),a()}));t.subscribe(n)}else a()},a=function(){var r=!1;i=t.subscribe(C(e,void 0,(function(){++s<n?i?o():r=!0:e.complete()}))),r&&o()};a()}))}function jt(t,e){return N((function(r,n){var i=null,s=0,o=!1,a=function(){return o&&!i&&n.complete()};r.subscribe(C(n,(function(r){null==i||i.unsubscribe();var o=0,u=s++;ct(t(r,u)).subscribe(i=C(n,(function(t){return n.next(e?e(r,t,u,o++):t)}),(function(){i=null,a()})))}),(function(){o=!0,a()})))}))}function Bt(t,e,r){var n=d(t)||e||r?{next:t,error:e,complete:r}:t;return n?N((function(t,e){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var i=!0;t.subscribe(C(e,(function(t){var r;null===(r=n.next)||void 0===r||r.call(n,t),e.next(t)}),(function(){var t;i=!1,null===(t=n.complete)||void 0===t||t.call(n),e.complete()}),(function(t){var r;i=!1,null===(r=n.error)||void 0===r||r.call(n,t),e.error(t)}),(function(){var t,e;i&&(null===(t=n.unsubscribe)||void 0===t||t.call(n)),null===(e=n.finalize)||void 0===e||e.call(n)})))})):D}function Ht(t,e){void 0===e&&(e={});var r=e.selector,i=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]])}return r}(e,["selector"]);return new F((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?ct(r(t)).subscribe(C(e,void 0,(function(){a=!1,e.complete()}),h)):(a=!1,e.next(t),e.complete())})).catch(h),function(){a&&s.abort()}}))}class Yt{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 r,n,i=0,s=0;n=t.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?e+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);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 r=this.urlBase64Decode(e[1]);if(!r)throw new Error("Cannot decode the token.");return JSON.parse(r)}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 r=new Date(0);return r.setUTCSeconds(e.exp),r}isTokenExpired(t=this.token,e){if(null===t||""===t)return!0;const r=this.getTokenExpirationDate(t);return e=e||0,null===r||r.valueOf()<=(new Date).valueOf()+1e3*e}}const Kt="JWT_KEY",zt="JWT_REFRESH_KEY",Wt=216e5;class Gt{nuclia;_isAuthenticated=new K(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 r;switch(t){case"PUT":case"PATCH":case"POST":case"DELETE":r="WRITER";break;default:r="READER"}return"/kbs"===e||"PATCH"===t&&e?.startsWith("/kb")&&3===e?.split("/").length?r="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog")||e?.endsWith("/chat"))&&(r="READER"),r}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Ft((function(e,r){return t<=r}))),Ft((t=>!t)));var t}login(t,e,r){return this.fetch("/auth/login",{username:t,password:e},!1,r?{"X-STF-VALIDATION":r}:{}).pipe(Et((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(Kt),localStorage.removeItem(zt),this._isAuthenticated.next(!1)}refresh(){return this.fetch("/auth/refresh",{refresh_token:this.getRefreshToken()},!0,{}).pipe(Lt((t=>(this.logout(),vt(t)))),Et((t=>t.access_token?(this.storeTokens(t),!0):(this.logout(),!1))))}getToken(){return this.nuclia.options.public?"":localStorage.getItem(Kt)||""}setPassword(t){return this.fetch("/auth/setpassword",{password:t},!0,{}).pipe(Et((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 Yt(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(zt)||""}storeTokens(t){localStorage.setItem(Kt,t.access_token),localStorage.setItem(zt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new Yt(t),r=e.getTokenExpirationDate()?.getTime();if(r){const t=(new Date).getTime();if(r<t)this.logout();else{this._isAuthenticated.next(!0);const e=r-t<Wt?0:Wt;this.timerSubscription?.unsubscribe(),this.timerSubscription=Ot(e).pipe(jt((()=>this.refresh()))).subscribe()}}else this._isAuthenticated.next(!1)}else this._isAuthenticated.next(!1)}fetch(t,e,r,n){const i={"content-type":"application/json",...n};return r&&(i.Authorization=`Bearer ${this.getToken()}`),Ht(`${this.nuclia.backend}${t}`,{method:"POST",selector:t=>Promise.resolve(t),headers:i,body:JSON.stringify(e)}).pipe(jt((t=>t.ok?bt(t.clone().json()):vt(t))))}}const Mt="NUCLIA_NUA_KEY";var Vt,Jt,Xt,qt,Zt,Qt,te,ee,re,ne;t.AccountBlockingState=void 0,(Vt=t.AccountBlockingState||(t.AccountBlockingState={})).UNBLOCKED="unblocked",Vt.QUOTA="quota",Vt.MANAGER="manager",t.BlockedFeature=void 0,(Jt=t.BlockedFeature||(t.BlockedFeature={})).UPLOAD="upload",Jt.PROCESSING="processing",Jt.SEARCH="search",Jt.GENERATIVE="generative",t.StatsPeriod=void 0,(Xt=t.StatsPeriod||(t.StatsPeriod={})).DAY="day",Xt.WEEK="week",Xt.MONTH="month",Xt.YEAR="year",t.StatsRange=void 0,(qt=t.StatsRange||(t.StatsRange={})).anHour="1h",qt.twoHours="2h",qt.threeHours="3h",qt.sixHours="6h",qt.twelveHours="12h",qt.twentyFourHours="24h",qt.fortyHeightHours="48h",t.StatsType=void 0,(Zt=t.StatsType||(t.StatsType={})).PROCESSING_TIME="processing_time",Zt.SEARCHES="searches",Zt.CHARS="chars",Zt.MEDIA_SECONDS="media_seconds",Zt.BYTES="bytes",Zt.RESOURCES="resources",Zt.PAGES="pages",Zt.TRAIN_SECONDS="train_seconds",Zt.SUGGESTIONS="suggestions",Zt.DOCS_NO_MEDIA="docs_no_media",t.ResourceProperties=void 0,(Qt=t.ResourceProperties||(t.ResourceProperties={})).BASIC="basic",Qt.ORIGIN="origin",Qt.RELATIONS="relations",Qt.VALUES="values",Qt.EXTRACTED="extracted",Qt.ERRORS="errors",Qt.EXTRA="extra",t.ResourceFieldProperties=void 0,(te=t.ResourceFieldProperties||(t.ResourceFieldProperties={})).VALUE="value",te.EXTRACTED="extracted",te.ERROR="error",t.ExtractedDataTypes=void 0,(ee=t.ExtractedDataTypes||(t.ExtractedDataTypes={})).TEXT="text",ee.METADATA="metadata",ee.SHORTENED_METADATA="shortened_metadata",ee.LARGE_METADATA="large_metadata",ee.VECTOR="vectors",ee.LINK="link",ee.FILE="file",t.LabelSetKind=void 0,(re=t.LabelSetKind||(t.LabelSetKind={})).RESOURCES="RESOURCES",re.PARAGRAPHS="PARAGRAPHS",re.SELECTIONS="SELECTIONS",t.EventType=void 0,(ne=t.EventType||(t.EventType={})).VISITED="VISITED",ne.MODIFIED="MODIFIED",ne.DELETED="DELETED",ne.NEW="NEW",ne.STARTED="STARTED",ne.STOPPED="STOPPED",ne.SEARCH="SEARCH",ne.PROCESSED="PROCESSED";const ie=524288,se=new RegExp(/[^a-z0-9_-]/g),oe=(t,e,r,n,i={})=>(i.contentType||r instanceof ArrayBuffer||(i.contentType="null"!==r?.type?r?.type:void 0),i.filename||r instanceof ArrayBuffer||(i.filename=r?.name),i.lang||r instanceof ArrayBuffer||(i.lang=r.lang),i.md5||r instanceof ArrayBuffer||(i.md5=r.md5),(r instanceof ArrayBuffer?yt(r):bt(r.arrayBuffer())).pipe(jt((s=>n?ue(t,e,s,i,r.payload):ae(t,e,s,i))))),ae=(t,e,r,n)=>{const i={"content-type":n?.contentType||"application/octet-stream",...he(n)};let s=1;const o=n?.rslug?`?rslug=${n.rslug}`:"";return t.rest.post(`${e}/upload${o}`,r,i,!0).pipe(Ut(),Ft((t=>0==s--||503!==t.status)),Ct(1),jt((t=>{try{switch(t.status){case 201:return bt(t.json()).pipe(Et((t=>({resource:t.uuid||"",field:t.field_id||"",completed:!0}))));case 409:return yt({conflict:!0});default:return yt({failed:!0})}}catch(t){return yt({failed:!0})}})))},ue=(t,e,r,n,i)=>{let s=0,o=0,a=!1;const u=r.byteLength,c=Math.ceil(u/ie),l={"upload-length":`${u}`,"tus-resumable":"1.0.0"},h=[];n?.filename&&h.push(`filename ${btoa(encodeURIComponent(n.filename))}`),n?.lang&&h.push(`language ${btoa(n.lang)}`),n?.md5&&h.push(`md5 ${btoa(n.md5)}`),h.push(`content_type ${btoa(n?.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(Ut(),Ft((t=>0==d--||503!==t.status)),Lt((t=>yt(t))),Ct(1),Nt((e=>Dt(yt(e).pipe(Ft((t=>201!==t.status||!t.headers.get("location"))),Et((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),yt(e).pipe(Ft((t=>201===t.status&&!!t.headers.get("location"))),Et((t=>t.headers.get("location"))),Nt((e=>function(t,e,r){if(null==e&&(e=t,t=0),e<=0)return X;var n=e+t;return new F(r?function(e){var i=t;return r.schedule((function(){i<n?(e.next(i++),this.schedule()):e.complete()}))}:function(e){for(var r=t;r<n&&!e.closed;)e.next(r++);e.complete()})}(0,c).pipe(Nt((()=>{const i=r.slice(s,s+ie);return o+=1,a?yt({failed:a}):t.rest.patch(e,i,{"content-type":n?.contentType||"application/octet-stream","upload-offset":`${s}`,"content-length":`${i.byteLength}`},!0).pipe(Et((t=>200!==t.status?(a=!0,{failed:a}):(s+=ie,{completed:o===c,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Lt((()=>(a=!0,yt({failed:!0})))))}))))))))))},ce=(t,e,r,n=!1)=>{const i=Array.from(r),s=i.reduce(((t,e)=>t+(e.size||0)),0),o=[],a=i.map((t=>({file:t,progress:0,uploaded:!1,failed:!1}))),u=i.map((r=>{let i=e;if(n){let t=r.name.toLowerCase().replace(se,"_");o.includes(t)&&(t+="_"+o.filter((e=>e.startsWith(t))).length),o.push(t),i=`${i}/file/${t}`}const s=r.lang;if(s){const t=r.payload||{};r.payload={...t,metadata:{...t?.metadata,language:s}}}return oe(t,i,r,!0,{}).pipe(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=Q(t);return N((function(e,n){(r?Pt(t,e,r):Pt(t,e)).subscribe(n)}))}({progress:0,completed:!1}),Et((t=>({status:t,file:r}))))}));return bt(u).pipe(Rt((t=>t),6),Et((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 r=a.filter((t=>t.failed)).length,n=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:r,conflicts:n}})))},le=(t,e,r,n)=>{const i={"x-stf-nuakey":`Bearer ${e}`,"content-type":n?.contentType||"application/octet-stream",...he(n)};return t.rest.post("/processing/upload",r,i)},he=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 de,pe,fe,ge,be,ye;t.SortField=void 0,(de=t.SortField||(t.SortField={})).created="created",de.modified="modified",de.title="title",t.SHORT_FIELD_TYPE=void 0,(pe=t.SHORT_FIELD_TYPE||(t.SHORT_FIELD_TYPE={})).layout="l",pe.text="t",pe.file="f",pe.link="u",pe.datetime="d",pe.keywordset="k",pe.generic="a",pe.conversation="c",t.Search=void 0,fe=t.Search||(t.Search={}),(ge=fe.Features||(fe.Features={})).PARAGRAPH="paragraph",ge.DOCUMENT="document",ge.RELATIONS="relations",ge.VECTOR="vector",(be=fe.ResourceFeatures||(fe.ResourceFeatures={})).PARAGRAPH="paragraph",be.RELATIONS="relations",be.VECTOR="vector",(ye=fe.FindScoreType||(fe.FindScoreType={})).VECTOR="VECTOR",ye.BM25="BM25",ye.BOTH="BOTH";const ve=(t,e,r,n,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=n||"":a.query=n||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=`${r}/find`;return(o?t.rest.get(`${h}?${Se(a,l)}`,void 0,!0):t.rest.post(h,{...a,...l},void 0,!0)).pipe(jt((e=>{const r=e.headers.get("X-Nuclia-Trace-Id")||"";return e.ok&&206!==e.status?bt(e.json().then((t=>({...t,searchId:r})),(()=>{console.warn(`${h} did not return a valid JSON`)}))):(206===e.status&&t.events?.emit("partial",{...a,...l}),bt(e.json().then((t=>{throw{status:e.status,body:t}}),(()=>{throw{status:e.status}}))))})),Lt((t=>yt({type:"error",status:t.status,detail:t.detail,body:t.body}))),Et((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((r=>{"findResults"===r.type&&r.shards&&(t.currentShards={...t.currentShards,[e]:r.shards})})))},me=(t,e,r,n,i=[],s,o)=>{const a={},{inTitleOnly:u,isAdvanced:c,...l}=s||{};c?a.advanced_query=n||"":a.query=n||"",a.features=i,u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const h=o?t.rest.get(`${r}/search?${Se(a,l)}`):t.rest.post(`${r}/search`,{...a,...l});return Te(t,e,h)},Ee=(t,e,r,n)=>{const i={};i.query=r||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${n?Se(i,n):""}`);return Te(t,e,s)};function Te(t,e,r){return r.pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"searchResults"})),Bt((r=>{"searchResults"===r.type&&r.shards&&(t.currentShards={...t.currentShards,[e]:r.shards})})))}const Se=(t,e)=>{Object.entries(e||{}).forEach((([e,r])=>{null!=r&&(Array.isArray(r)?t[e]=r.map((t=>`${t}`)):"object"==typeof r?Object.entries(r).forEach((([r,n])=>t[`${e}_${r}`]=`${n}`)):t[e]=`${r}`)}));const r=new URLSearchParams;return Object.entries(t).forEach((([t,e])=>Array.isArray(e)?e.forEach((e=>r.append(t,e))):r.append(t,e))),r.toString()};var we,_e;t.Chat=void 0,function(t){t.PARAGRAPHS="paragraphs",t.RELATIONS="relations"}((we=t.Chat||(t.Chat={})).Features||(we.Features={})),(_e=we.Author||(we.Author={})).USER="USER",_e.NUCLIA="NUCLIA";const Ae="_END_";function xe(e,r,n,i=[],s=[t.Chat.Features.PARAGRAPHS],o={}){let a,u,c=0,l="";return e.rest.getStream(`${r}/chat`,{query:n,context:i,show:[t.ResourceProperties.BASIC,t.ResourceProperties.VALUES],features:s.length>0?s:void 0,...o}).pipe(Et((({data:t,incomplete:e,headers:r})=>{const n=r.get("X-Nuclia-Trace-Id")||"",i=r.get("NUCLIA-LEARNING-ID")||"";if(0===c&&t.length>=4&&(c=new DataView(t.buffer.slice(0,4)).getUint32(0)),!a&&c>0&&t.length>c+4){const e=t.slice(4,c+4);a=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}if(a&&(a.searchId=n),a&&t.length>c+4&&(l=(new TextDecoder).decode(t.slice(c+4).buffer),l.includes(Ae))){let t;if([l,t]=l.split(Ae),t)try{u=JSON.parse(atob(t)),a.relations=u}catch(t){console.warn(t)}}return{type:"answer",text:l,sources:a,incomplete:e,id:i}})),Lt((t=>yt({type:"error",status:t.status,detail:t.detail||""}))))}const ke=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),Re=(t,e,r,n,i)=>{const s=ke(i.filter((r=>Pe(r,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=ke(i.filter((r=>Ie(r,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==r)),a=i.filter((r=>r.field.field!==t||r.field.field_type!==e)),u=n.length>0?[...o,{key:r,classifications:n}]: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},$e=(t,e,r,n)=>{const i=ke(n.filter((r=>Ie(r,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),s=n.filter((r=>r.field.field!==t||r.field.field_type!==e));return r.length>0||i.length>0?[...s,{field:{field:t,field_type:e},token:r.length>0?r:void 0,paragraphs:i.length>0?i:void 0}]:s},Pe=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.token&&t.token.length>0,Ie=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.paragraphs&&t.paragraphs.length>0,Oe=(t,e,r)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,r).join("")):"";class De{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 r=this.data[t]?.[e];return r||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,r])=>(t[r]=(t[r]||[]).concat([e]),t)),{}))).reduce(((t,e)=>(Object.entries(e).forEach((([e,r])=>{t[e]=(t[e]||[]).concat(r)})),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,r)=>(r.classifications.forEach((r=>{const n=t.find((t=>t.label===r.label&&t.labelset===r.labelset)),i=e.find((t=>t.label===r.label&&t.labelset===r.labelset));n||i||t.push({...r,immutable:!0})})),t)),t)}getPositionedNamedEntities(t,e){const r=this.data[t]?.[e]?.extracted?.metadata?.metadata.positions;return r?Object.entries(r).reduce(((t,[e,r])=>{const n=e.split("/")[0];return r.position.forEach((e=>{t.push({entity:r.entity,family:n,...e})})),t}),[]):[]}formatTitle(t){t=t||"–";try{return decodeURIComponent(t)}catch(e){return t}}getParagraphText(t,e,r){return Oe(this.getFieldText(t,e),r.start,r.end)}getSentenceText(t,e,r){return Oe(this.getFieldText(t,e),r.start,r.end)}getFieldText(t,e){const r=`${t}-${e}`;if(!this.fieldTextsCache[r]){const n=this.getFieldData(`${t}s`,e);this.fieldTextsCache[r]=Array.from(n?.extracted?.text?.text||"")}return this.fieldTextsCache[r]}}class Fe extends De{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,r){super(r),this.nuclia=t,this.kb=e,this.uuid=r.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(e,r,n=[t.ResourceFieldProperties.VALUE],i=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.SHORTENED_METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){const s=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this.path}/${e}/${r}?${s.join("&")}`)}getThumbnailsUrl(){return It(this.getThumbnails().filter((t=>t.uri)).map((t=>this.nuclia.rest.getObjectURL(t.uri))))}deleteField(t,e){return this.nuclia.rest.delete(`${this.path}/${t}/${e}`)}setField(t,e,r){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,r)}upload(t,e,r,n){return oe(this.nuclia,`${this.path}/file/${t}`,e,!!r,n)}batchUpload(t){return ce(this.nuclia,this.path,t,!0)}search(t,e=[],r){return me(this.nuclia,this.kb,this.path,t,e,r,!0)}find(t,e=[],r){return ve(this.nuclia,this.kb,this.kbPath,t,e,this.uuid?{...r,resource_filters:[this.uuid]}:r)}setLabels(t,e,r,n){const i=Re(t,e,r,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,r){const n=$e(t,e,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:n}).pipe(Bt((()=>this.fieldmetadata=n)))}}var Le,Ne;t.FIELD_TYPE=void 0,(Le=t.FIELD_TYPE||(t.FIELD_TYPE={})).text="text",Le.file="file",Le.link="link",Le.layout="layout",Le.conversation="conversation",Le.keywordset="keywordset",Le.datetime="datetime",Le.generic="generic",t.RESOURCE_STATUS=void 0,(Ne=t.RESOURCE_STATUS||(t.RESOURCE_STATUS={})).PENDING="PENDING",Ne.PROCESSED="PROCESSED",Ne.ERROR="ERROR";var Ce,Ue,je;t.TrainingType=void 0,(Ce=t.TrainingType||(t.TrainingType={})).classifier="classifier",Ce.resource_labeler="resource-labeler",Ce.paragraph_labeler="paragraph-labeler",Ce.ner="ner",t.TrainingStatus=void 0,(Ue=t.TrainingStatus||(t.TrainingStatus={})).finished="finished",Ue.not_running="not_running",Ue.running="running",Ue.started="started",Ue.stopped="stopped",t.TrainingExecutionStatus=void 0,(je=t.TrainingExecutionStatus||(t.TrainingExecutionStatus={})).succeeded="succeeded",je.failed="failed",je.stopped="stopped";class Be{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(e){return this.nuclia.rest.get(`${this.kb.path}/train/${e}/inspect`).pipe(Lt((()=>yt({task:"",status:t.TrainingStatus.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(Et((()=>!0)),Lt((()=>yt(!1))))}}class He{account;nuclia;get path(){return`/kb/${this.id}`}get fullpath(){return`${this.nuclia.regionalBackend}/v1/kb/${this.id}`}constructor(t,e,r){this.nuclia=t,this.account=e,Object.assign(this,r),!r.id&&r.uuid&&(this.id=r.uuid),!r.title&&r.slug&&(this.title=r.slug)}getEntities(t=!1){return this.nuclia.rest.get(`${this.path}/entitiesgroups?show_entities=${t}`).pipe(Et((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(Et((t=>t.synonyms)))}getLabels(){return this.nuclia.rest.get(`${this.path}/labelsets`).pipe(Et((t=>t?.labelsets||{})),Lt((()=>yt({}))))}getResource(e,r=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],n=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){return this._getResource(e,void 0,r,n)}getResourceBySlug(e,r=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],n=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){return this._getResource(void 0,e,r,n)}_getResource(e,r,n=[t.ResourceProperties.BASIC,t.ResourceProperties.ORIGIN,t.ResourceProperties.RELATIONS,t.ResourceProperties.VALUES,t.ResourceProperties.EXTRACTED,t.ResourceProperties.ERRORS],i=[t.ExtractedDataTypes.TEXT,t.ExtractedDataTypes.METADATA,t.ExtractedDataTypes.LINK,t.ExtractedDataTypes.FILE]){const s=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this._getPath(e,r)}?${s.join("&")}`).pipe(Et((t=>new Fe(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Fe(this.nuclia,this.id,t)}chat(t,e,r,n){return xe(this.nuclia,this.path,t,e,r,n)}find(t,e=[],r){return ve(this.nuclia,this.id,this.path,t,e,r)}search(t,e=[],r){return me(this.nuclia,this.id,this.path,t,e,r)}catalog(t,e){return Ee(this.nuclia,this.id,t,e)}suggest(t,e=!1){const r=`query=${encodeURIComponent(t)}${e?"&fields=a/title":""}`;return this.nuclia.rest.get(`${this.path}/suggest?${r}`).pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"suggestions"})))}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 r=[t?`page=${t}`:"",e?`size=${e}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/resources${r?"?"+r:""}`).pipe(Et((t=>({resources:t.resources.map((t=>new Fe(this.nuclia,this.id,t))),pagination:t.pagination}))))}getTempToken(){if(!this.nuclia.options.account||!this.nuclia.options.kbSlug)throw new Error("Account and KB slug are required to get a temp token");return this.nuclia.rest.post(`/account/${this.nuclia.options.account}/kb/${this.nuclia.options.kbSlug}/ephemeral_tokens`,{}).pipe(Et((t=>t.token)))}listActivity(t,e,r){const n=[t?`type=${t}`:"",e?`page=${e}`:"",r?`size=${r}`:""].filter((t=>t)).join("&");return this.nuclia.rest.get(`/kb/${this.id}/activity${n?"?"+n:""}`)}getConfiguration(){return this.nuclia.rest.get(`/kb/${this.id}/configuration`)}}class Ye extends He{admin;contrib;_training;get training(){return this._training||(this._training=new Be(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(){return this.nuclia.rest.delete(`/account/${this.account}/kb/${this.slug}`)}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,r=!0,n){return this.createResource({links:{link:t},usermetadata:e,title:t.uri,icon:"application/stf-link",...n?{origin:n}:{}},r)}hasResource(t){return this.nuclia.rest.get(`${this.path}/slug/${t}`).pipe(Et((()=>!0)),Lt((()=>yt(!1))))}createOrUpdateResource(t,e=!0){return(t.slug?this.hasResource(t.slug):yt(!1)).pipe(jt((r=>r?this.getResourceFromData({id:"",slug:t.slug}).modify(t,e):this.createResource(t,e))))}upload(t,e,r){return oe(this.nuclia,`/kb/${this.id}`,t,!!e,r)}batchUpload(t){return ce(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 r=e.find((e=>e.title===t.title&&e.role===t.role));return r?yt(r):this.createServiceAccount(t).pipe(jt((()=>this.getServiceAccounts())),Et((e=>e.find((e=>e.title===t.title&&e.role===t.role)))))})),jt((t=>t?this.createKey(t.id,e):yt({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)}}class Ke{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(Et((t=>t.kbs)))}getKnowledgeBoxes(t){return this.nuclia.rest.get(`/account/${t}/kbs`)}getKnowledgeBox(t,e){if(t=t||this.nuclia.options.account){const r=e||this.nuclia.options.knowledgeBox||this.nuclia.options.kbSlug;if(!r)throw new Error("account and knowledgeBox must be defined in the Nuclia options");const n=this.nuclia.options.standalone?`/kb/${e}`:`/account/${t}/kb/${r}`;return this.nuclia.rest.get(n).pipe(jt((t=>this.nuclia.options.zone||this.nuclia.options.standalone?yt(t):this.nuclia.rest.getZoneSlug(t.zone).pipe(Bt((t=>this.nuclia.options.zone=t)),Et((()=>t))))),Et((e=>new Ye(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 yt(new Ye(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((r=>{const n=r.id||r.uuid;if(!n)throw"KnowledgeBox creation failed";return this.getKnowledgeBox(t,this.nuclia.options.standalone?n:e.slug)})))}getStats(e,r,n,i=t.StatsPeriod.DAY,s){const o=[`period=${i}`,`stats=${r}`];return s&&o.push(`utctime=${s}`),n&&o.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${e}/stats?${o.join("&")}`).pipe(Et((t=>t.data)),Ft((t=>!!t)))}upload(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /process");return le(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",r=t?void 0:this.getNUAHeader();return this.nuclia.rest.get(e,r)}getProcessingStats(t,e){const r=this.hasNUAClient();if(!e&&!r)throw new Error("NUA key or account id is needed to be able to call /processing/stats");const n=r?"/processing/stats"+(t?"?period="+t:""):`/processing/stats?account_id=${e}${t?"&period="+t:""}`,i=r?this.getNUAHeader():void 0;return this.nuclia.rest.get(n,i).pipe(Et((t=>t.data)))}getNUAActivity(t,e,r=0){return this.nuclia.rest.get(`/account/${t}/nua_client/${e}/activity?page=${r}`)}getNUAClients(t){return this.nuclia.rest.get(`/account/${t}/nua_clients`).pipe(Et((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 r={...e};return r.webhook&&(r.processing_webhook={uri:r.webhook},delete r.webhook),this.nuclia.rest.post(`/account/${t}/nua_clients`,r).pipe(Lt((r=>{if(409===r.status&&e.client_id)return this.renewNUAClient(t,e.client_id);throw r})),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(Et((t=>t.tokens)))}}class ze{nuclia;zones;constructor(t){this.nuclia=t}get(t,e,r){return this.fetch("GET",t,void 0,e,r)}post(t,e,r,n,i){return this.fetch("POST",t,e,r,n,i)}put(t,e,r,n,i){return this.fetch("PUT",t,e,r,n,i)}patch(t,e,r,n,i){return this.fetch("PATCH",t,e,r,n,i)}delete(t,e,r){return this.fetch("DELETE",t,void 0,e,!0,r)}head(t,e){return this.fetch("HEAD",t,void 0,e,!0)}getHeaders(t,e,r,n=!1){const i=r&&r["x-stf-nuakey"]?{}:this.nuclia.auth.getAuthHeaders(t,e),s={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return n&&(s["x-synchronous"]=`${n}`),{...s,...r}}fetch(t,e,r,n,i,s=!1){const o=n&&n["content-type"];return bt(fetch(this.getFullUrl(e),{method:t,headers:this.getHeaders(t,e,n,s),body:o?r:JSON.stringify(r)}).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")||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?yt(this.zones):this.get("/zones").pipe(Et((t=>{const e=t.reduce(((t,e)=>(t[e.id]=e.slug,t)),{});return this.zones=e,e})))}getZoneSlug(t){return this.getZones().pipe(Et((e=>e[t])))}getObjectURL(t){return this.get(t,void 0,!0).pipe(jt((t=>bt(t.blob()))),Et((t=>URL.createObjectURL(t))))}getStream(t,e){return t=this.getFullUrl(t),new F((r=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),n=t.headers,i=t.status;if(e&&t.ok){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:s})=>{e&&(r.next({data:t,incomplete:!1,headers:n}),r.complete()),s&&(t=this.concat(t,s),r.next({data:t,incomplete:!0,headers:n}),i())}))};i()}else r.error({status:i}),r.complete()}))}))}concat(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}}class We{messages=new B;emit(t,e){this.messages.next({name:t,data:e})}on(t){return this.messages.asObservable().pipe(Ft((e=>e.name===t)),Et((t=>t.data)))}}t.Authentication=Gt,t.ConversationFieldData=class{value;extracted;error},t.Db=Ke,t.FileFieldData=class{value;extracted;error},t.JwtHelper=Yt,t.KeywordSetFieldData=class{value;extracted;error},t.KnowledgeBox=He,t.LinkFieldData=class{value;extracted;error},t.NUA_KEY=Mt,t.Nuclia=class{options;auth;rest;db;currentShards={};events=new We;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 He(this,"",{id:this.options.knowledgeBox,zone:this.options.zone||""})),this.readKb}get asyncKnowledgeBox(){return new Proxy(this.knowledgeBox,{get(t,e){const r=Reflect.get(t,e);return"function"==typeof r?(...e)=>function(t,e){var r="object"==typeof e;return new Promise((function(n,i){var s=new $({next:function(t){n(t),s.unsubscribe()},error:i,complete:function(){r?n(e.defaultValue):i(new mt)}});t.subscribe(s)}))}(r.bind(t)(...e)):r}})}constructor(t){this.options=t,this.auth=new Gt(this),this.rest=new ze(this),this.db=new Ke(this)}},t.ReadableResource=De,t.Resource=Fe,t.Rest=ze,t.TUSuploadFile=ue,t.TextFieldData=class{value;extracted;error},t.Training=Be,t.WritableKnowledgeBox=Ye,t.batchUpload=ce,t.catalog=Ee,t.chat=xe,t.deDuplicateList=ke,t.find=ve,t.getDataKeyFromFieldType=e=>{switch(e){case t.FIELD_TYPE.text:case t.FIELD_TYPE.file:case t.FIELD_TYPE.link:case t.FIELD_TYPE.keywordset:return`${e}s`;default:return null}},t.getEntityFromFilter=function(t){const e=t.split("/");return{family:e[2],entity:e[3]}},t.getFieldTypeFromString=function(e){switch(e){case t.FIELD_TYPE.file:return t.FIELD_TYPE.file;case t.FIELD_TYPE.link:return t.FIELD_TYPE.link;case t.FIELD_TYPE.text:return t.FIELD_TYPE.text;case t.FIELD_TYPE.layout:return t.FIELD_TYPE.layout;case t.FIELD_TYPE.conversation:return t.FIELD_TYPE.conversation;case t.FIELD_TYPE.datetime:return t.FIELD_TYPE.datetime;case t.FIELD_TYPE.generic:return t.FIELD_TYPE.generic;default:return null}},t.getFileMetadata=he,t.getFilterFromEntity=function(t){return`/e/${t.family}/${t.entity}`},t.getFilterFromLabel=function(t){return`/l/${t.labelset}/${t.label}`},t.getLabelFromFilter=function(t){const e=t.split("/");return{labelset:e[2],label:e[3]}},t.lengthUnicode=t=>t?Array.from(t).length:0,t.longToShortFieldType=function(e){return t.SHORT_FIELD_TYPE[e]},t.resourceToAlgoliaFormat=(t,e)=>{const r={title:t.title,fullText:t.getExtractedTexts().filter((t=>t)).map((t=>t.text))};t.getClassifications().forEach((t=>{t.labelset&&t.label&&(r[t.labelset]=t.label)}));const n=t.getThumbnails().filter((t=>!!t.uri)).map((t=>`${e}/v1${t.uri}`));return{...r,images:n,...t.getNamedEntities()}},t.search=me,t.setEntities=$e,t.setLabels=Re,t.shortToLongFieldType=function(e){switch(e){case t.SHORT_FIELD_TYPE.conversation:return t.FIELD_TYPE.conversation;case t.SHORT_FIELD_TYPE.datetime:return t.FIELD_TYPE.datetime;case t.SHORT_FIELD_TYPE.file:return t.FIELD_TYPE.file;case t.SHORT_FIELD_TYPE.layout:return t.FIELD_TYPE.layout;case t.SHORT_FIELD_TYPE.keywordset:return t.FIELD_TYPE.keywordset;case t.SHORT_FIELD_TYPE.link:return t.FIELD_TYPE.link;case t.SHORT_FIELD_TYPE.text:return t.FIELD_TYPE.text;case t.SHORT_FIELD_TYPE.generic:return t.FIELD_TYPE.generic;default:return null}},t.sliceUnicode=Oe,t.upload=oe,t.uploadFile=ae,t.uploadToProcess=le})); |
@@ -160,3 +160,3 @@ export type AccountTypes = 'stash-basic' | 'stash-team' | 'stash-trial' | 'stash-developer' | 'stash-business' | 'stash-startup' | 'stash-enterprise'; | ||
export interface LearningConfigurations { | ||
[key: string]: LearningConfiguration; | ||
[key: string]: LearningConfiguration | LearningConfigurationSchemas; | ||
} | ||
@@ -167,5 +167,26 @@ export interface LearningConfiguration { | ||
name: string; | ||
user_key?: string; | ||
}[]; | ||
default: string; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
export interface LearningConfigurationSchemas { | ||
schemas: { | ||
[key: string]: LearningConfigurationSchema; | ||
}; | ||
create: boolean; | ||
update: boolean; | ||
} | ||
export interface LearningConfigurationSchema { | ||
title: string; | ||
type: string; | ||
properties: { | ||
[key: string]: { | ||
title: string; | ||
type: string; | ||
}; | ||
}; | ||
required: string[]; | ||
} | ||
export type LearningConfigurationSet = { | ||
@@ -172,0 +193,0 @@ id: string; |
@@ -40,3 +40,3 @@ import { Observable } from 'rxjs'; | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -83,4 +83,4 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
} |
@@ -25,2 +25,3 @@ import type { Observable } from 'rxjs'; | ||
METADATA = "metadata", | ||
SHORTENED_METADATA = "shortened_metadata", | ||
LARGE_METADATA = "large_metadata", | ||
@@ -33,3 +34,4 @@ VECTOR = "vectors", | ||
RESOURCES = "RESOURCES", | ||
PARAGRAPHS = "PARAGRAPHS" | ||
PARAGRAPHS = "PARAGRAPHS", | ||
SELECTIONS = "SELECTIONS" | ||
} | ||
@@ -82,3 +84,3 @@ export declare enum EventType { | ||
getConfiguration(): Observable<{ | ||
[id: string]: string; | ||
[id: string]: any; | ||
}>; | ||
@@ -120,3 +122,3 @@ } | ||
setConfiguration(config: { | ||
[id: string]: string; | ||
[id: string]: any; | ||
}): Observable<void>; | ||
@@ -130,3 +132,3 @@ } | ||
learning_configuration?: { | ||
[configId: string]: string; | ||
[configId: string]: any; | ||
}; | ||
@@ -133,0 +135,0 @@ } |
@@ -37,2 +37,3 @@ import { Observable } from 'rxjs'; | ||
private nuclia; | ||
get kbPath(): string; | ||
get path(): string; | ||
@@ -51,4 +52,5 @@ constructor(nuclia: INuclia, kb: string, data: IResource); | ||
search(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>; | ||
find(query: string, features?: Search.ResourceFeatures[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>; | ||
setLabels(fieldId: string, fieldType: string, paragraphId: string, labels: Classification[]): Observable<void>; | ||
setEntities(fieldId: string, fieldType: string, entities: TokenAnnotation[]): Observable<void>; | ||
} |
@@ -195,5 +195,21 @@ export interface IResource { | ||
} | ||
export interface PageStructure { | ||
page: { | ||
width: number; | ||
height: number; | ||
}; | ||
tokens: PageToken[]; | ||
} | ||
export interface PageToken { | ||
x: number; | ||
y: number; | ||
width: number; | ||
height: number; | ||
text: string; | ||
line: number; | ||
} | ||
export interface FilePages { | ||
pages?: CloudLink[]; | ||
positions?: PagePositions[]; | ||
structures?: PageStructure[]; | ||
} | ||
@@ -283,3 +299,16 @@ export interface FileB64 { | ||
token?: UserTokenAnnotation[]; | ||
selections?: PageSelections[]; | ||
} | ||
export interface PageSelections { | ||
page: number; | ||
visual: VisualSelection[]; | ||
} | ||
export interface VisualSelection { | ||
label: string; | ||
top: number; | ||
left: number; | ||
right: number; | ||
bottom: number; | ||
token_ids: number[]; | ||
} | ||
export interface TokenAnnotation { | ||
@@ -286,0 +315,0 @@ token: string; |
import { Observable } from 'rxjs'; | ||
import type { IErrorResponse, INuclia } from '../../models'; | ||
import type { Search, SearchOptions } from './search.models'; | ||
export declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
export declare const find: (nuclia: INuclia, kbid: string, path: string, query: string, features?: (Search.Features | Search.ResourceFeatures)[], options?: SearchOptions, useGet?: boolean) => Observable<Search.FindResults | IErrorResponse>; | ||
export declare const search: (nuclia: INuclia, kbid: string, path: string, query: string, features?: Search.Features[] | Search.ResourceFeatures[], options?: SearchOptions, useGet?: boolean) => Observable<Search.Results | IErrorResponse>; | ||
export declare const catalog: (nuclia: INuclia, kbid: string, query: string, options?: SearchOptions) => Observable<Search.Results | IErrorResponse>; |
@@ -26,2 +26,3 @@ import type { ExtractedDataTypes, ResourceProperties } from '../kb'; | ||
field_type_filter?: FIELD_TYPE[]; | ||
resource_filters?: string[]; | ||
shards?: string[]; | ||
@@ -127,3 +128,3 @@ autofilter?: boolean; | ||
} | ||
interface SmartResult extends IResource { | ||
interface FieldResult extends IResource { | ||
paragraphs?: FindParagraph[]; | ||
@@ -133,5 +134,2 @@ field?: FieldId; | ||
} | ||
interface SmartParagraph extends Paragraph { | ||
sentences?: Sentence[]; | ||
} | ||
interface Suggestions { | ||
@@ -138,0 +136,0 @@ type: 'suggestions'; |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
300936
5538