Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@nuclia/core

Package Overview
Dependencies
Maintainers
3
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuclia/core - npm Package Compare versions

Comparing version 1.3.0 to 1.3.1

14

CHANGELOG.md

@@ -0,5 +1,15 @@

# 1.3.1 (2023-05-02)
### Improvements
- Add `title` and `color` properties to `UpdateEntitiesGroupPayload` model
- Update `Account` and `AccountLimits` models
- Create `AccountBlockingState` and `BlockedFeature` models for the new `blocking_state` and `blocked_features` properties in `Account`
- Support `predict/tokens` endpoint
# 1.3.0 (2023-04-18)
### Breaking changes
- Rename `setEntitiesGroup` into `createEntitiesGroup` and call the new POST `/kb/{kbid}/entitiesgroups` endpoint replacing deprecated POST to `/kb/{kbid}/entitiesgroups/{group}`
- Rename `setEntitiesGroup` into `createEntitiesGroup` and call the new POST `/kb/{kbid}/entitiesgroups` endpoint replacing deprecated POST to `/kb/{kbid}/entitiesgroups/{group}`
- Add method `updateEntitiesGroup` allowing to PATCH existing entity groups using the new `UpdateEntitiesGroupPayload` payload.

@@ -18,3 +28,3 @@

- Add `error` property in `IFieldData` and corresponding `IError` interface
- catch error and return an empty label set on `kb.getLabels` method
- catch error and return an empty label set on `kb.getLabels` method
- Add common `IErrorResponse` interface

@@ -21,0 +31,0 @@ - Better error management for search, find, catalog and suggest endpoints

2

esm/index.js

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

var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},t(e,n)};function e(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},n.apply(this,arguments)};function r(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{a(r.next(t))}catch(t){o(t)}}function u(t){try{a(r.throw(t))}catch(t){o(t)}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,u)}a((r=r.apply(t,e||[])).next())}))}function i(t,e){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(u){return function(a){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return s.label++,{value:u[1],done:!1};case 5:s.label++,r=u[1],u=[0];continue;case 7:u=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){s=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){s.label=u[1];break}if(6===u[0]&&s.label<i[1]){s.label=i[1],i=u;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(u);break}i[2]&&s.ops.pop(),s.trys.pop();continue}u=e.call(t,s)}catch(t){u=[6,t],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,a])}}}function o(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 s(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,o=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function u(t,e,n){if(n||2===arguments.length)for(var r,i=0,o=e.length;i<o;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 a(t){return this instanceof a?(this.v=t,this):new a(t)}function c(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(t,e||[]),o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(t){i[t]&&(r[t]=function(e){return new Promise((function(n,r){o.push([t,e,n,r])>1||u(t,e)}))})}function u(t,e){try{(n=i[t](e)).value instanceof a?Promise.resolve(n.value.v).then(c,l):h(o[0][2],n)}catch(t){h(o[0][3],t)}var n}function c(t){u("next",t)}function l(t){u("throw",t)}function h(t,e){t(e),o.shift(),o.length&&u(o[0][0],o[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=o(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 f(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 d=f((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 a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=o(a),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 a.remove(this);var f=this.initialTeardown;if(h(f))try{f()}catch(t){i=t instanceof d?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{v(y)}catch(t){i=null!=i?i:[],t instanceof d?i=u(u([],s(i)),s(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 d(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,u([t,e],s(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function E(t){w.setTimeout((function(){throw t}))}function S(){}function A(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(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,o,s=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}:s&&m.useDeprecatedNextContext?((o=Object.create(e)).unsubscribe=function(){return s.unsubscribe()},i={next:e.next&&_(e.next,o),error:e.error&&_(e.error,o),complete:e.complete&&_(e.complete,o)}):i=e;return s.destination=new $(i),s}return e(n,t),n}(k);function R(t){E(t)}var O={closed:!0,next:S,error:function(t){throw t},complete:S},I="function"==typeof Symbol&&Symbol.observable||"@@observable";function C(t){return t}var N=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,o=(r=t)&&r instanceof k||function(t){return t&&h(t.next)&&h(t.error)&&h(t.complete)}(r)&&y(r)?t:new T(t,e,n);return A((function(){var t=i,e=t.operator,n=t.source;o.add(e?e.call(o,n):n?i._subscribe(o):i._trySubscribe(o))})),o},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?C: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,o,s){var u=t.call(this,e)||this;return u.onFinalize=o,u.shouldUnsubscribe=s,u._next=n?function(t){try{n(t)}catch(t){e.error(t)}}:t.prototype._next,u._error=i?function(t){try{i(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,u._complete=r?function(){try{r()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,u}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=f((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;A((function(){var n,r;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){n={error:t}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}}))},n.prototype.error=function(t){var e=this;A((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;A((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,o=n.observers;return r||i?b:(this.currentObservers=null,o.push(t),new g((function(){e.currentObservers=null,p(o,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 N;return t.source=this,t},n.create=function(t,e){return new F(t,e)},n}(N),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),z={now:function(){return(z.delegate||Date).now()},delegate:void 0},H=function(t){function n(e,n,r){void 0===e&&(e=1/0),void 0===n&&(n=1/0),void 0===r&&(r=z);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,o=n._infiniteTimeWindow,s=n._timestampProvider,u=n._windowTime;r||(i.push(e),!o&&i.push(s.now()+u)),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,o=(i?1:2)*e;if(e<1/0&&o<r.length&&r.splice(0,r.length-o),!i){for(var s=n.now(),u=0,a=1;a<r.length&&r[a]<=s;a+=2)u=a;u&&r.splice(0,u+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),G=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,u([t,e],s(n)))},K=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),G(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&&K(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=z.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 N((function(t){return t.complete()}));function Y(t){return t&&h(t.schedule)}function q(t){return t[t.length-1]}function Z(t){return Y(q(t))?t.pop():void 0}var Q=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function tt(t){return h(null==t?void 0:t.then)}function et(t){return h(t[I])}function nt(t){return Symbol.asyncIterator&&h(null==t?void 0:t[Symbol.asyncIterator])}function rt(t){return new TypeError("You provided "+(null!==t&&"object"==typeof t?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var it="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ot(t){return h(null==t?void 0:t[it])}function st(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,a(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,a(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,a(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 ut(t){return h(null==t?void 0:t.getReader)}function at(t){if(t instanceof N)return t;if(null!=t){if(et(t))return i=t,new N((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 N((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 N((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(ot(t))return e=t,new N((function(t){var n,r;try{for(var i=o(e),s=i.next();!s.done;s=i.next()){var u=s.value;if(t.next(u),t.closed)return}}catch(t){n={error:t}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}t.complete()}));if(ut(t))return ct(st(t))}var e,n,r,i;throw rt(t)}function ct(t){return new N((function(e){(function(t,e){var n,o,s,u;return r(this,void 0,void 0,(function(){var r,a;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((o=i.sent()).done)return[3,4];if(r=o.value,e.next(r),e.closed)return[2];i.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=i.sent(),s={error:a},[3,11];case 6:return i.trys.push([6,,9,10]),o&&!o.done&&(u=n.return)?[4,u.call(n)]:[3,8];case 7:i.sent(),i.label=8;case 8:return[3,10];case 9:if(s)throw s.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 o=e.schedule((function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()}),r);if(t.add(o),!i)return o}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 ft(t,e){return void 0===e&&(e=0),P((function(n,r){r.add(t.schedule((function(){return n.subscribe(r)}),e))}))}function dt(t,e){if(!t)throw new Error("Iterable cannot be null");return new N((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 at(t).pipe(ft(e),ht(e))}(t,e);if(Q(t))return function(t,e){return new N((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 at(t).pipe(ft(e),ht(e))}(t,e);if(nt(t))return dt(t,e);if(ot(t))return function(t,e){return new N((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(ut(t))return function(t,e){return dt(st(t),e)}(t,e)}throw rt(t)}function gt(t,e){return e?pt(t,e):at(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 N(e?function(t){return e.schedule(r,0,t)}:r)}var vt=f((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,u([],s(e))):t(e)}(t,e)}))}var St=Array.isArray,At=Object.getPrototypeOf,kt=Object.prototype,xt=Object.keys;function _t(t){if(1===t.length){var e=t[0];if(St(e))return{args:e,keys:null};if((r=e)&&"object"==typeof r&&At(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 $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)}))(at(t(n,r)))}),n):("number"==typeof e&&(n=e),P((function(e,r){return function(t,e,n,r,i,o,s,u){var a=[],c=0,l=0,h=!1,f=function(){!h||a.length||c||e.complete()},d=function(t){return c<r?p(t):a.push(t)},p=function(t){o&&e.next(t),c++;var u=!1;at(n(t,l++)).subscribe(D(e,(function(t){null==i||i(t),o?d(t):e.next(t)}),(function(){u=!0}),void 0,(function(){if(u)try{c--;for(var t=function(){var t=a.shift();s?lt(e,s,(function(){return p(t)})):p(t)};a.length&&c<r;)t();f()}catch(t){e.error(t)}})))};return t.subscribe(D(e,d,(function(){h=!0,f()}))),function(){null==u||u()}}(e,r,t,n)})))}function Tt(t){return void 0===t&&(t=1/0),$t(C,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(q(t))?t.pop():void 0}(t),r=_t(t),i=r.args,o=r.keys,s=new N((function(t){var e=i.length;if(e)for(var n=new Array(e),r=e,s=e,u=function(e){var u=!1;at(i[e]).subscribe(D(t,(function(t){u||(u=!0,s--),n[e]=t}),(function(){return r--}),void 0,(function(){r&&u||(s||t.next(o?function(t,e){return t.reduce((function(t,n,r){return t[n]=e[r],t}),{})}(o,n):n),t.complete())})))},a=0;a<e;a++)u(a);else t.complete()}));return n?s.pipe(Et(n)):s}function It(t,e,n){void 0===t&&(t=0),void 0===n&&(n=J);var r=-1;return null!=e&&(Y(e)?n=e:r=e),new N((function(e){var i,o=(i=t)instanceof Date&&!isNaN(i)?+t-n.now():t;o<0&&(o=0);var s=0;return n.schedule((function(){e.closed||(e.next(s++),0<=r?this.schedule(void 0,r):e.complete())}),o)}))}function Ct(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Z(t),r=function(t,e){return"number"==typeof q(t)?t.pop():e}(t,1/0),i=t;return i.length?1===i.length?at(i[0]):Tt(r)(gt(i,n)):X}function Nt(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,o=!1;i=e.subscribe(D(n,void 0,void 0,(function(s){r=at(t(s,Ut(t)(e))),i?(i.unsubscribe(),i=null,r.subscribe(n)):o=!0}))),o&&(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,o=0,s=function(){if(null==i||i.unsubscribe(),i=null,null!=n){var t="number"==typeof n?It(n):at(n(o)),r=D(e,(function(){r.unsubscribe(),u()}));t.subscribe(r)}else u()},u=function(){var n=!1;i=t.subscribe(D(e,void 0,(function(){++o<r?i?s():n=!0:e.complete()}))),n&&s()};u()}))}function jt(t,e){return P((function(n,r){var i=null,o=0,s=!1,u=function(){return s&&!i&&r.complete()};n.subscribe(D(r,(function(n){null==i||i.unsubscribe();var s=0,a=o++;at(t(n,a)).subscribe(i=D(r,(function(t){return r.next(e?e(n,t,a,s++):t)}),(function(){i=null,u()})))}),(function(){s=!0,u()})))}))}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)})))})):C}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 N((function(e){var o=new AbortController,s=o.signal,u=!0,a=i.signal;if(a)if(a.aborted)o.abort();else{var c=function(){s.aborted||o.abort()};a.addEventListener("abort",c),e.add((function(){return a.removeEventListener("abort",c)}))}var l=n(n({},i),{signal:s}),h=function(t){u=!1,e.error(t)};return fetch(t,l).then((function(t){r?at(r(t)).subscribe(D(e,void 0,(function(){u=!1,e.complete()}),h)):(u=!1,e.next(t),e.complete())})).catch(h),function(){u&&o.abort()}}))}class zt{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,o=0;r=t.charAt(o++);~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 Ht="JWT_KEY",Wt="JWT_REFRESH_KEY",Gt=216e5;class Kt{nuclia;_isAuthenticated=new H(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-STF-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?n="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog"))&&(n="READER"),n}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Nt((function(e,n){return t<=n}))),Nt((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(Ht),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(Ht)||""}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 zt(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(Wt)||""}storeTokens(t){localStorage.setItem(Ht,t.access_token),localStorage.setItem(Wt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new zt(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<Gt?0:Gt;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",Vt="NUCLIA_NUA_CLIENT";var Jt,Xt,Yt,qt,Zt,Qt,te,ee;!function(t){t.DAY="day",t.WEEK="week",t.MONTH="month",t.YEAR="year"}(Jt||(Jt={})),function(t){t.anHour="1h",t.twoHours="2h",t.threeHours="3h",t.sixHours="6h",t.twelveHours="12h",t.twentyFourHours="24h",t.fortyHeightHours="48h"}(Xt||(Xt={})),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"}(qt||(qt={})),function(t){t.VALUE="value",t.EXTRACTED="extracted",t.ERROR="error"}(Zt||(Zt={})),function(t){t.TEXT="text",t.METADATA="metadata",t.LARGE_METADATA="large_metadata",t.VECTOR="vectors",t.LINK="link",t.FILE="file"}(Qt||(Qt={})),function(t){t.RESOURCES="RESOURCES",t.PARAGRAPHS="PARAGRAPHS"}(te||(te={})),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"}(ee||(ee={}));const ne=524288,re=new RegExp(/[^a-z0-9_-]/g),ie=(t,e,n,r,i={})=>(i.contentType||n instanceof ArrayBuffer||(i.contentType=n?.type),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((o=>r?se(t,e,o,i,n.payload):oe(t,e,o,i))))),oe=(t,e,n,r)=>{const i={"content-type":r?.contentType||"application/octet-stream",...ce(r)};let o=1;const s=r?.rslug?`?rslug=${r.rslug}`:"";return t.rest.post(`${e}/upload${s}`,n,i).pipe(Lt(),Nt((t=>0==o--||503!==t.status)),Dt(1),jt((t=>{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})}})))},se=(t,e,n,r,i)=>{let o=0,s=!1;const u=n.byteLength,a=Math.ceil(u/ne),c={"upload-length":`${u}`,"tus-resumable":"1.0.0"},l=[];r?.filename&&l.push(`filename ${btoa(encodeURIComponent(r.filename))}`),r?.lang&&l.push(`language ${btoa(r.lang)}`),r?.md5&&l.push(`md5 ${btoa(r.md5)}`),l.push(`content_type ${btoa(r?.contentType||"application/octet-stream")}`),l.length>0&&(c["upload-metadata"]=l.join(","));let h=1;return t.rest.post(`${e}/tusupload`,i,c,!0).pipe(Lt(),Nt((t=>0==h--||503!==t.status)),Ut((t=>bt(t))),Dt(1),Pt((e=>Ct(bt(e).pipe(Nt((t=>201!==t.status||!t.headers.get("location"))),mt((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),bt(e).pipe(Nt((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 N(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,a).pipe(Pt((()=>{const i=n.slice(o,o+ne);return s?bt({failed:s}):t.rest.patch(e,i,{"content-type":r?.contentType||"application/octet-stream","upload-offset":`${o}`,"content-length":`${i.byteLength}`},!0).pipe(mt((t=>200!==t.status?(s=!0,{failed:s}):(o+=ne,{completed:o>=u,progress:o>=u?100:Math.min(Math.floor(o/u*100),100)}))),Ut((()=>bt({failed:!0}))))}))))))))))},ue=(t,e,n,r=!1)=>{const i=Array.from(n),o=i.reduce(((t,e)=>t+(e.size||0)),0),s=[],u=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(re,"_");s.includes(t)&&(t+="_"+s.filter((e=>e.startsWith(t))).length),s.push(t),i=`${i}/file/${t}`}const o=n.lang;if(o){const t=n.payload||{};n.payload={...t,metadata:{...t?.metadata,language:o}}}return ie(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=u.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=u.filter((t=>t.failed)).length,r=u.filter((t=>t.conflicts)).length,i=u.filter((t=>t.uploaded)).length,s=i+n===u.length,a=Math.round(u.reduce(((t,e)=>t+e.file.size*e.progress/100),0)/o*100);return{files:u,progress:a,completed:s,uploaded:i,failed:n,conflicts:r}})))},ae=(t,e,n)=>{const r={"x-stf-nuakey":`Bearer ${localStorage.getItem(Mt)}`,"content-type":n?.contentType||"application/octet-stream",...ce(n)};return t.rest.post("/processing/upload",e,r)},ce=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 le(t){return`/l/${t.labelset}/${t.label}`}function he(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}var fe,de,pe;!function(t){t.created="created",t.modified="modified",t.title="title"}(fe||(fe={})),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"}(de||(de={})),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"}(pe||(pe={}));const ge=(t,e,n,r,i=[],o,s)=>{const u={};o?.isAdvanced?u.advanced_query=r||"":u.query=r||"",u.features=i;const{inTitleOnly:a,...c}=o||{};a&&(u.fields=["a/title"]),u.shards=t.currentShards?.[e]||[];return(s?t.rest.get(`${n}/find?${me(u,c)}`):t.rest.post(`${n}/find`,{...u,...c})).pipe(Ut((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((n=>{"findResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))},be=(t,e,n,r,i=[],o,s)=>{const u={};u.query=r||"",u.features=i;const{inTitleOnly:a,...c}=o||{};a&&(u.fields=["a/title"]),u.shards=t.currentShards?.[e]||[];const l=s?t.rest.get(`${n}/search?${me(u,c)}`):t.rest.post(`${n}/search`,{...u,...c});return ve(t,e,l)},ye=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const o=t.rest.get(`/kb/${e}/catalog?${r?me(i,r):""}`);return ve(t,e,o)};function ve(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 me=(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 we;!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"}(we||(we={}));const Ee="_END_";function Se(t,e,n,r=[],i=[we.Features.PARAGRAPHS]){let o,s=0,u="";return t.rest.getStream(`${e}/chat`,{query:n,context:r,show:[qt.BASIC,qt.VALUES],features:i.length>0?i:void 0}).pipe(mt((({data:t,incomplete:e,headers:n})=>{const r=n.get("NUCLIA-LEARNING-ID")||"";if(0===s&&t.length>=4&&(s=new DataView(t.buffer.slice(0,4)).getUint32(0)),!o&&s>0&&t.length>s+4){const e=t.slice(4,s+4);o=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}return o&&t.length>s+4&&(u=(new TextDecoder).decode(t.slice(s+4).buffer),u.includes(Ee)&&(u=u.split(Ee)[0])),{text:u,sources:o,incomplete:e,id:r}})))}const Ae=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),ke=(t,e,n,r,i)=>{const o=Ae(i.filter((n=>_e(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),s=Ae(i.filter((n=>$e(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==n)),u=i.filter((n=>n.field.field!==t||n.field.field_type!==e)),a=r.length>0?[...s,{key:n,classifications:r}]:s;return o.length>0||a.length>0?[...u,{field:{field:t,field_type:e},token:o.length>0?o:void 0,paragraphs:a.length>0?a:void 0}]:u},xe=(t,e,n,r)=>{const i=Ae(r.filter((n=>$e(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),o=r.filter((n=>n.field.field!==t||n.field.field_type!==e));return n.length>0||i.length>0?[...o,{field:{field:t,field_type:e},token:n.length>0?n:void 0,paragraphs:i.length>0?i:void 0}]:o},_e=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,$e=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,Te=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Re=t=>t?Array.from(t).length:0;class Oe{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 Te(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return Te(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 Ie extends Oe{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=[Zt.VALUE],r=[Qt.TEXT,Qt.METADATA,Qt.LINK,Qt.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}`)}addField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}updateField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}upload(t,e,n,r){return ie(this.nuclia,`${this.path}/file/${t}`,e,!!n,r)}batchUpload(t){return ue(this.nuclia,this.path,t,!0)}search(t,e=[],n){return be(this.nuclia,this.kb,this.path,t,e,n,!0)}setLabels(t,e,n,r){const i=ke(t,e,n,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,n){const r=xe(t,e,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:r}).pipe(Bt((()=>this.fieldmetadata=r)))}}var Ce,Ne;!function(t){t.text="text",t.file="file",t.link="link",t.layout="layout",t.conversation="conversation",t.keywordset="keywordset",t.datetime="datetime"}(Ce||(Ce={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(Ne||(Ne={}));class Ue{value;extracted;error}class Pe{value;extracted;error}class De{value;extracted;error}class Le{value;extracted;error}const je=(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()}},Be=t=>{switch(t){case Ce.text:case Ce.file:case Ce.link:case Ce.keywordset:return`${t}s`;default:return null}};function Fe(t){return de[t]}function ze(t){switch(t){case de.conversation:return Ce.conversation;case de.datetime:return Ce.datetime;case de.file:return Ce.file;case de.layout:return Ce.layout;case de.keywordset:return Ce.keywordset;case de.link:return Ce.link;case de.text:return Ce.text;default:return null}}function He(t){switch(t){case Ce.file:return Ce.file;case Ce.link:return Ce.link;case Ce.text:return Ce.text;case Ce.layout:return Ce.layout;case Ce.conversation:return Ce.conversation;case Ce.datetime:return Ce.datetime;default:return null}}var We,Ge,Ke;!function(t){t.classifier="classifier",t.resource_labeler="resource-labeler",t.paragraph_labeler="paragraph-labeler",t.ner="ner"}(We||(We={})),function(t){t.finished="finished",t.not_running="not_running",t.running="running",t.started="started",t.stopped="stopped"}(Ge||(Ge={})),function(t){t.succeeded="succeeded",t.failed="failed",t.stopped="stopped"}(Ke||(Ke={}));class Me{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:Ge.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 Ve{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=[qt.BASIC,qt.ORIGIN,qt.RELATIONS,qt.VALUES,qt.EXTRACTED,qt.ERRORS],n=[Qt.TEXT,Qt.METADATA,Qt.LINK,Qt.FILE]){return this._getResource(t,void 0,e,n)}getResourceBySlug(t,e=[qt.BASIC,qt.ORIGIN,qt.RELATIONS,qt.VALUES,qt.EXTRACTED,qt.ERRORS],n=[Qt.TEXT,Qt.METADATA,Qt.LINK,Qt.FILE]){return this._getResource(void 0,t,e,n)}_getResource(t,e,n=[qt.BASIC,qt.ORIGIN,qt.RELATIONS,qt.VALUES,qt.EXTRACTED,qt.ERRORS],r=[Qt.TEXT,Qt.METADATA,Qt.LINK,Qt.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 Ie(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Ie(this.nuclia,this.id,t)}chat(t,e,n){return Se(this.nuclia,this.path,t,e,n)}find(t,e=[],n){return ge(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return be(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return ye(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 Ie(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 Je extends Ve{admin;contrib;_training;get training(){return this._training||(this._training=new Me(this,this.nuclia)),this._training}modify(t){return this.nuclia.rest.patch(`/account/${this.account}/kb/${this.slug}`,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 ie(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})}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 Xe{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 Je(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 Je(this.nuclia,"",{id:this.nuclia.options.knowledgeBox,zone:this.nuclia.options.zone}))}createKnowledgeBox(t,e){return this.nuclia.rest.post(`/account/${t}/kbs`,e).pipe(Bt((t=>{if(!t.id)throw"KnowledgeBox creation failed"})),jt((()=>this.getKnowledgeBox(t,e.slug))))}getStats(t,e,n,r=Jt.DAY,i){const o=[`period=${r}`,`stats=${e}`];return i&&o.push(`utctime=${i}`),n&&o.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${t}/stats?${o.join("&")}`).pipe(mt((t=>t.data)),Nt((t=>!!t)))}upload(t){if(!this.hasNUAClient())throw new Error("NUA key is needed to be able to call /process");return ae(this.nuclia,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!!localStorage.getItem(Vt)&&!!localStorage.getItem(Mt)}getNUAHeader(){return{"x-stf-nuakey":`Bearer ${localStorage.getItem(Mt)}`}}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&&(localStorage.setItem(Mt,t.token),localStorage.setItem(Vt,t.client_id))})))}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")}}class Ye{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),o={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return r&&(o["x-synchronous"]=`${r}`),{...o,...n}}fetch(t,e,n,r,i,o=!1){const s=r&&r["content-type"];return Ft(this.getFullUrl(e),{selector:t=>Promise.resolve(t),headers:this.getHeaders(t,e,r,o),method:t,body:s?n:JSON.stringify(n)}).pipe(jt((t=>t.ok?i?bt(t):gt(t.clone().json().catch((()=>t.text()))):yt((()=>t)))))}getFullUrl(t){return`${t.startsWith("/account")||t.startsWith("/user")||t.startsWith("/auth")||t.startsWith("/zones")||t.startsWith("/billing")||t.includes("/activity")||this.nuclia.options.standalone?this.nuclia.backend:this.nuclia.regionalBackend}${t.startsWith("/auth")||t.startsWith("/export")||t.startsWith("/billing")?"":"/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 N((n=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),r=t.headers;if(e){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:o})=>{e&&(n.next({data:t,incomplete:!1,headers:r}),n.complete()),o&&(t=this.concat(t,o),n.next({data:t,incomplete:!0,headers:r}),i())}))};i()}else n.next({data:new Uint8Array,incomplete:!1,headers:r}),n.complete()}))}))}concat(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}}class qe{options;auth;rest;db;currentShards={};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)throw new Error("zone and knowledge box id must be defined in the Nuclia options");return this.readKb||(this.readKb=new Ve(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 o=new T({next:function(t){r(t),o.unsubscribe()},error:i,complete:function(){n?r(e.defaultValue):i(new vt)}});t.subscribe(o)}))}(n.bind(t)(...e)):n}})}constructor(t){this.options=t,this.auth=new Kt(this),this.rest=new Ye(this),this.db=new Xe(this)}}export{Kt as Authentication,we as Chat,Xe as Db,ee as EventType,Qt as ExtractedDataTypes,Ce as FIELD_TYPE,Ue as FileFieldData,zt as JwtHelper,De as KeywordSetFieldData,Ve as KnowledgeBox,te as LabelSetKind,Le as LinkFieldData,Vt as NUA_CLIENT,Mt as NUA_KEY,qe as Nuclia,Ne as RESOURCE_STATUS,Oe as ReadableResource,Ie as Resource,Zt as ResourceFieldProperties,qt as ResourceProperties,Ye as Rest,de as SHORT_FIELD_TYPE,pe as Search,fe as SortField,Jt as StatsPeriod,Xt as StatsRange,Yt as StatsType,se as TUSuploadFile,Pe as TextFieldData,Me as Training,Ke as TrainingExecutionStatus,Ge as TrainingStatus,We as TrainingType,Je as WritableKnowledgeBox,ue as batchUpload,ye as catalog,Se as chat,Ae as deDuplicateList,ge as find,Be as getDataKeyFromFieldType,He as getFieldTypeFromString,ce as getFileMetadata,le as getFilterFromLabel,he as getLabelFromFilter,Re as lengthUnicode,Fe as longToShortFieldType,je as resourceToAlgoliaFormat,be as search,xe as setEntities,ke as setLabels,ze as shortToLongFieldType,Te as sliceUnicode,ie as upload,oe as uploadFile,ae 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{a(r.next(t))}catch(t){s(t)}}function u(t){try{a(r.throw(t))}catch(t){s(t)}}function a(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(o,u)}a((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:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function u(u){return function(a){return function(u){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==u[0]&&2!==u[0])){o=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){o.label=u[1];break}if(6===u[0]&&o.label<i[1]){o.label=i[1],i=u;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(u);break}i[2]&&o.ops.pop(),o.trys.pop();continue}u=e.call(t,o)}catch(t){u=[6,t],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([u,a])}}}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 u(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 a(t){return this instanceof a?(this.v=t,this):new a(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||u(t,e)}))})}function u(t,e){try{(n=i[t](e)).value instanceof a?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){u("next",t)}function l(t){u("throw",t)}function h(t,e){t(e),s.shift(),s.length&&u(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 f(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 d=f((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 a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=s(a),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 a.remove(this);var f=this.initialTeardown;if(h(f))try{f()}catch(t){i=t instanceof d?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 d?i=u(u([],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 d(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,u([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(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}(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 U=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(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=C(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=C(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 C(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 u=t.call(this,e)||this;return u.onFinalize=s,u.shouldUnsubscribe=o,u._next=n?function(t){try{n(t)}catch(t){e.error(t)}}:t.prototype._next,u._error=i?function(t){try{i(t)}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._error,u._complete=r?function(){try{r()}catch(t){e.error(t)}finally{this.unsubscribe()}}:t.prototype._complete,u}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=f((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 U;return t.source=this,t},n.create=function(t,e){return new F(t,e)},n}(U),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),z={now:function(){return(z.delegate||Date).now()},delegate:void 0},H=function(t){function n(e,n,r){void 0===e&&(e=1/0),void 0===n&&(n=1/0),void 0===r&&(r=z);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,u=n._windowTime;r||(i.push(e),!s&&i.push(o.now()+u)),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(),u=0,a=1;a<r.length&&r[a]<=o;a+=2)u=a;u&&r.splice(0,u+1)}},n}(B),K=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),W=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,u([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),W(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}(K),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=z.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 U((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,a(e.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,a(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,a(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 ut(t){return h(null==t?void 0:t.getReader)}function at(t){if(t instanceof U)return t;if(null!=t){if(et(t))return i=t,new U((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 U((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 U((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 U((function(t){var n,r;try{for(var i=s(e),o=i.next();!o.done;o=i.next()){var u=o.value;if(t.next(u),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(ut(t))return ct(ot(t))}var e,n,r,i;throw rt(t)}function ct(t){return new U((function(e){(function(t,e){var n,s,o,u;return r(this,void 0,void 0,(function(){var r,a;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 a=i.sent(),o={error:a},[3,11];case 6:return i.trys.push([6,,9,10]),s&&!s.done&&(u=n.return)?[4,u.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 ft(t,e){return void 0===e&&(e=0),P((function(n,r){r.add(t.schedule((function(){return n.subscribe(r)}),e))}))}function dt(t,e){if(!t)throw new Error("Iterable cannot be null");return new U((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 at(t).pipe(ft(e),ht(e))}(t,e);if(Q(t))return function(t,e){return new U((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 at(t).pipe(ft(e),ht(e))}(t,e);if(nt(t))return dt(t,e);if(st(t))return function(t,e){return new U((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(ut(t))return function(t,e){return dt(ot(t),e)}(t,e)}throw rt(t)}function gt(t,e){return e?pt(t,e):at(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 U(e?function(t){return e.schedule(r,0,t)}:r)}var vt=f((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,u([],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 $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)}))(at(t(n,r)))}),n):("number"==typeof e&&(n=e),P((function(e,r){return function(t,e,n,r,i,s,o,u){var a=[],c=0,l=0,h=!1,f=function(){!h||a.length||c||e.complete()},d=function(t){return c<r?p(t):a.push(t)},p=function(t){s&&e.next(t),c++;var u=!1;at(n(t,l++)).subscribe(D(e,(function(t){null==i||i(t),s?d(t):e.next(t)}),(function(){u=!0}),void 0,(function(){if(u)try{c--;for(var t=function(){var t=a.shift();o?lt(e,o,(function(){return p(t)})):p(t)};a.length&&c<r;)t();f()}catch(t){e.error(t)}})))};return t.subscribe(D(e,d,(function(){h=!0,f()}))),function(){null==u||u()}}(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 U((function(t){var e=i.length;if(e)for(var n=new Array(e),r=e,o=e,u=function(e){var u=!1;at(i[e]).subscribe(D(t,(function(t){u||(u=!0,o--),n[e]=t}),(function(){return r--}),void 0,(function(){r&&u||(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())})))},a=0;a<e;a++)u(a);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 U((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?at(i[0]):Tt(r)(gt(i,n)):X}function Ut(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 Ct(t){return P((function(e,n){var r,i=null,s=!1;i=e.subscribe(D(n,void 0,void 0,(function(o){r=at(t(o,Ct(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):at(n(s)),r=D(e,(function(){r.unsubscribe(),u()}));t.subscribe(r)}else u()},u=function(){var n=!1;i=t.subscribe(D(e,void 0,(function(){++s<r?i?o():n=!0:e.complete()}))),n&&o()};u()}))}function jt(t,e){return P((function(n,r){var i=null,s=0,o=!1,u=function(){return o&&!i&&r.complete()};n.subscribe(D(r,(function(n){null==i||i.unsubscribe();var o=0,a=s++;at(t(n,a)).subscribe(i=D(r,(function(t){return r.next(e?e(n,t,a,o++):t)}),(function(){i=null,u()})))}),(function(){o=!0,u()})))}))}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 U((function(e){var s=new AbortController,o=s.signal,u=!0,a=i.signal;if(a)if(a.aborted)s.abort();else{var c=function(){o.aborted||s.abort()};a.addEventListener("abort",c),e.add((function(){return a.removeEventListener("abort",c)}))}var l=n(n({},i),{signal:o}),h=function(t){u=!1,e.error(t)};return fetch(t,l).then((function(t){r?at(r(t)).subscribe(D(e,void 0,(function(){u=!1,e.complete()}),h)):(u=!1,e.next(t),e.complete())})).catch(h),function(){u&&s.abort()}}))}class zt{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 Ht="JWT_KEY",Kt="JWT_REFRESH_KEY",Wt=216e5;class Gt{nuclia;_isAuthenticated=new H(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-STF-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?n="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog"))&&(n="READER"),n}isAuthenticated(){return this._isAuthenticated.asObservable()}hasLoggedOut(){return this.isAuthenticated().pipe((t=1,Ut((function(e,n){return t<=n}))),Ut((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(Ht),localStorage.removeItem(Kt),this._isAuthenticated.next(!1)}refresh(){return this.fetch("/auth/refresh",{refresh_token:this.getRefreshToken()},!0,{}).pipe(Ct((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(Ht)||""}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 zt(t).getJWTUser()}return null}getRefreshToken(){return localStorage.getItem(Kt)||""}storeTokens(t){localStorage.setItem(Ht,t.access_token),localStorage.setItem(Kt,t.refresh_token),this.checkTokenExpiration()}checkTokenExpiration(){const t=this.getToken();if(t){const e=new zt(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<Wt?0:Wt;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"}(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=n?.type),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?ue(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(),Ut((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})}})))},ue=(t,e,n,r,i)=>{let s=0,o=!1;const u=n.byteLength,a=Math.ceil(u/re),c={"upload-length":`${u}`,"tus-resumable":"1.0.0"},l=[];r?.filename&&l.push(`filename ${btoa(encodeURIComponent(r.filename))}`),r?.lang&&l.push(`language ${btoa(r.lang)}`),r?.md5&&l.push(`md5 ${btoa(r.md5)}`),l.push(`content_type ${btoa(r?.contentType||"application/octet-stream")}`),l.length>0&&(c["upload-metadata"]=l.join(","));let h=1;return t.rest.post(`${e}/tusupload`,i,c,!0).pipe(Lt(),Ut((t=>0==h--||503!==t.status)),Ct((t=>bt(t))),Dt(1),Pt((e=>Nt(bt(e).pipe(Ut((t=>201!==t.status||!t.headers.get("location"))),mt((t=>409===t.status?{conflict:!0,failed:!0}:{failed:!0}))),bt(e).pipe(Ut((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 U(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,a).pipe(Pt((()=>{const i=n.slice(s,s+re);return o?bt({failed:o}):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?(o=!0,{failed:o}):(s+=re,{completed:s>=u,progress:s>=u?100:Math.min(Math.floor(s/u*100),100)}))),Ct((()=>bt({failed:!0}))))}))))))))))},ae=(t,e,n,r=!1)=>{const i=Array.from(n),s=i.reduce(((t,e)=>t+(e.size||0)),0),o=[],u=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=u.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=u.filter((t=>t.failed)).length,r=u.filter((t=>t.conflicts)).length,i=u.filter((t=>t.uploaded)).length,o=i+n===u.length,a=Math.round(u.reduce(((t,e)=>t+e.file.size*e.progress/100),0)/s*100);return{files:u,progress:a,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 fe(t){const e=t.split("/");return{labelset:e[2],label:e[3]}}var de,pe,ge;!function(t){t.created="created",t.modified="modified",t.title="title"}(de||(de={})),function(t){t.layout="l",t.text="t",t.file="f",t.link="u",t.datetime="d",t.keywordset="k",t.generic="a",t.conversation="c"}(pe||(pe={})),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"}(ge||(ge={}));const be=(t,e,n,r,i=[],s,o)=>{const u={},{inTitleOnly:a,isAdvanced:c,...l}=s||{};c?u.advanced_query=r||"":u.query=r||"",u.features=i,a&&(u.fields=["a/title"]),u.shards=t.currentShards?.[e]||[];return(o?t.rest.get(`${n}/find?${we(u,l)}`):t.rest.post(`${n}/find`,{...u,...l})).pipe(Ct((t=>bt({type:"error",status:t.status,detail:t.detail}))),mt((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((n=>{"findResults"===n.type&&n.shards&&(t.currentShards={...t.currentShards,[e]:n.shards})})))},ye=(t,e,n,r,i=[],s,o)=>{const u={},{inTitleOnly:a,isAdvanced:c,...l}=s||{};c?u.advanced_query=r||"":u.query=r||"",u.features=i,a&&(u.fields=["a/title"]),u.shards=t.currentShards?.[e]||[];const h=o?t.rest.get(`${n}/search?${we(u,l)}`):t.rest.post(`${n}/search`,{...u,...l});return me(t,e,h)},ve=(t,e,n,r)=>{const i={};i.query=n||"",i.shards=t.currentShards?.[e]||[];const s=t.rest.get(`/kb/${e}/catalog?${r?we(i,r):""}`);return me(t,e,s)};function me(t,e,n){return n.pipe(Ct((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 we=(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 Ee;!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"}(Ee||(Ee={}));const Ae="_END_";function Se(t,e,n,r=[],i=[Ee.Features.PARAGRAPHS],s={}){let o,u=0,a="";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("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)))}return o&&t.length>u+4&&(a=(new TextDecoder).decode(t.slice(u+4).buffer),a.includes(Ae)&&(a=a.split(Ae)[0])),{text:a,sources:o,incomplete:e,id:r}})))}const ke=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),xe=(t,e,n,r,i)=>{const s=ke(i.filter((n=>$e(n,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),o=ke(i.filter((n=>Te(n,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])).filter((t=>t.key!==n)),u=i.filter((n=>n.field.field!==t||n.field.field_type!==e)),a=r.length>0?[...o,{key:n,classifications:r}]:o;return s.length>0||a.length>0?[...u,{field:{field:t,field_type:e},token:s.length>0?s:void 0,paragraphs:a.length>0?a:void 0}]:u},_e=(t,e,n,r)=>{const i=ke(r.filter((n=>Te(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},$e=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.token&&t.token.length>0,Te=(t,e,n)=>t.field.field===e&&t.field.field_type===n&&t.paragraphs&&t.paragraphs.length>0,Re=(t,e,n)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,n).join("")):"",Oe=t=>t?Array.from(t).length:0;class Ie{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 Re(this.getFieldText(t,e),n.start,n.end)}getSentenceText(t,e,n){return Re(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 Ne extends Ie{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}`)}addField(t,e,n){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,n)}updateField(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 ae(this.nuclia,this.path,t,!0)}search(t,e=[],n){return ye(this.nuclia,this.kb,this.path,t,e,n,!0)}setLabels(t,e,n,r){const i=xe(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 Ue,Ce;!function(t){t.text="text",t.file="file",t.link="link",t.layout="layout",t.conversation="conversation",t.keywordset="keywordset",t.datetime="datetime"}(Ue||(Ue={})),function(t){t.PENDING="PENDING",t.PROCESSED="PROCESSED",t.ERROR="ERROR"}(Ce||(Ce={}));class Pe{value;extracted;error}class De{value;extracted;error}class Le{value;extracted;error}class je{value;extracted;error}const Be=(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()}},Fe=t=>{switch(t){case Ue.text:case Ue.file:case Ue.link:case Ue.keywordset:return`${t}s`;default:return null}};function ze(t){return pe[t]}function He(t){switch(t){case pe.conversation:return Ue.conversation;case pe.datetime:return Ue.datetime;case pe.file:return Ue.file;case pe.layout:return Ue.layout;case pe.keywordset:return Ue.keywordset;case pe.link:return Ue.link;case pe.text:return Ue.text;default:return null}}function Ke(t){switch(t){case Ue.file:return Ue.file;case Ue.link:return Ue.link;case Ue.text:return Ue.text;case Ue.layout:return Ue.layout;case Ue.conversation:return Ue.conversation;case Ue.datetime:return Ue.datetime;default:return null}}var We,Ge,Me;!function(t){t.classifier="classifier",t.resource_labeler="resource-labeler",t.paragraph_labeler="paragraph-labeler",t.ner="ner"}(We||(We={})),function(t){t.finished="finished",t.not_running="not_running",t.running="running",t.started="started",t.stopped="stopped"}(Ge||(Ge={})),function(t){t.succeeded="succeeded",t.failed="failed",t.stopped="stopped"}(Me||(Me={}));class Ve{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(Ct((()=>bt({task:"",status:Ge.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)),Ct((()=>bt(!1))))}}class Je{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||{})),Ct((()=>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 Ne(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Ne(this.nuclia,this.id,t)}chat(t,e,n,r){return Se(this.nuclia,this.path,t,e,n,r)}find(t,e=[],n){return be(this.nuclia,this.id,this.path,t,e,n)}search(t,e=[],n){return ye(this.nuclia,this.id,this.path,t,e,n)}catalog(t,e){return ve(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(Ct((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 Ne(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 Xe extends Je{admin;contrib;_training;get training(){return this._training||(this._training=new Ve(this,this.nuclia)),this._training}modify(t){return this.nuclia.rest.patch(`/account/${this.account}/kb/${this.slug}`,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)),Ct((()=>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 ae(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 Xe(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 Xe(this.nuclia,"",{id:this.nuclia.options.knowledgeBox,zone:this.nuclia.options.zone}))}createKnowledgeBox(t,e){return this.nuclia.rest.post(`/account/${t}/kbs`,e).pipe(Bt((t=>{if(!t.id)throw"KnowledgeBox creation failed"})),jt((()=>this.getKnowledgeBox(t,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)),Ut((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(Ct((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 Ye{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`)})):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 U((n=>{fetch(t,{method:"POST",headers:this.getHeaders("POST",t),body:JSON.stringify(e)}).then((t=>{const e=t.body?.getReader(),r=t.headers;if(e){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.next({data:new Uint8Array,incomplete:!1,headers:r}),n.complete()}))}))}concat(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}}class Ze{options;auth;rest;db;currentShards={};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)throw new Error("zone and knowledge box id must be defined in the Nuclia options");return this.readKb||(this.readKb=new Je(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 Ye(this),this.db=new qe(this)}}export{Vt as AccountBlockingState,Gt as Authentication,Jt as BlockedFeature,Ee as Chat,qe as Db,ne as EventType,te as ExtractedDataTypes,Ue as FIELD_TYPE,Pe as FileFieldData,zt as JwtHelper,Le as KeywordSetFieldData,Je as KnowledgeBox,ee as LabelSetKind,je as LinkFieldData,Mt as NUA_KEY,Ze as Nuclia,Ce as RESOURCE_STATUS,Ie as ReadableResource,Ne as Resource,Qt as ResourceFieldProperties,Zt as ResourceProperties,Ye as Rest,pe as SHORT_FIELD_TYPE,ge as Search,de as SortField,Xt as StatsPeriod,qt as StatsRange,Yt as StatsType,ue as TUSuploadFile,De as TextFieldData,Ve as Training,Me as TrainingExecutionStatus,Ge as TrainingStatus,We as TrainingType,Xe as WritableKnowledgeBox,ae as batchUpload,ve as catalog,Se as chat,ke as deDuplicateList,be as find,Fe as getDataKeyFromFieldType,Ke as getFieldTypeFromString,le as getFileMetadata,he as getFilterFromLabel,fe as getLabelFromFilter,Oe as lengthUnicode,ze as longToShortFieldType,Be as resourceToAlgoliaFormat,ye as search,_e as setEntities,xe as setLabels,He as shortToLongFieldType,Re as sliceUnicode,se as upload,oe as uploadFile,ce as uploadToProcess};
import { Observable } from 'rxjs';
import type { IDb, INuclia } from '../models';
import type { LearningConfigurations } from './db.models';
import type { LearningConfigurations, PredictedToken } from './db.models';
import { Account, AccountCreation, AccountStatus, NUAClient, NUAClientPayload, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome } from './db.models';

@@ -32,2 +32,3 @@ import type { EventList, IKnowledgeBoxItem, KnowledgeBoxCreation } from './kb';

hasNUAClient(): boolean;
getNUAKey(): string;
getNUAHeader(): {

@@ -46,2 +47,3 @@ 'x-stf-nuakey': string;

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}
export type AccountTypes = 'stash-basic' | 'stash-team' | 'stash-trial' | 'stash-developer' | 'stash-business' | 'stash-startup' | 'stash-enterprise';
export declare const NUA_KEY = "NUCLIA_NUA_KEY";
export declare const NUA_CLIENT = "NUCLIA_NUA_CLIENT";
export interface Account {

@@ -18,7 +17,23 @@ id: string;

limits: AccountLimits;
blocking_state: AccountBlockingState;
blocked_features: BlockedFeature[];
}
export interface AccountConfig {
g_speech_to_text: boolean;
indexer_slow_replicas: number;
max_dedicated_processors: number;
}
export interface AccountLimits {
processing: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
upload: {

@@ -28,8 +43,26 @@ upload_limit_max_media_file_size: number;

};
processing: {
usage: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
}
export declare enum AccountBlockingState {
UNBLOCKED = "unblocked",
QUOTA = "quota",
MANAGER = "manager"
}
export declare enum BlockedFeature {
UPLOAD = "upload",
PROCESSING = "processing",
SEARCH = "search",
GENERATIVE = "generative"
}
export interface AccountCreation {

@@ -139,1 +172,7 @@ slug: string;

}[];
export interface PredictedToken {
text: string;
ner: string;
start: number;
end: number;
}

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

import { FileMetadata, FileWithMetadata, UploadStatus } from '../upload';
import type { Chat } from '../search';
import type { BaseSearchOptions, Chat } from '../search';
import { Search, SearchOptions } from '../search';

@@ -30,3 +30,3 @@ import { Training } from '../training';

getResourceFromData(data: IResource): Resource;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;
find(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>;

@@ -79,2 +79,5 @@ search(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>;

}>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
deleteKey(saId: string, saKeyId: string): Observable<void>;

@@ -81,0 +84,0 @@ setConfiguration(config: {

@@ -108,2 +108,5 @@ import type { Observable } from 'rxjs';

deleteServiceAccount(saId: string): Observable<void>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
createKey(saId: string, expires: string): Observable<{

@@ -143,2 +146,4 @@ token: string;

export interface UpdateEntitiesGroupPayload {
title?: string;
color?: string;
add: {

@@ -145,0 +150,0 @@ [key: string]: Entity;

import { Observable } from 'rxjs';
import type { INuclia } from '../../models';
import { Chat } from './chat.models';
export declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
import type { BaseSearchOptions } from './search.models';
export declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;

@@ -15,12 +15,5 @@ import type { ExtractedDataTypes, ResourceProperties } from '../kb';

}
export interface SearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
export interface BaseSearchOptions {
fields?: string[];
filters?: string[];
fields?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
min_score?: number;

@@ -33,4 +26,13 @@ range_creation_start?: string;

extracted?: ExtractedDataTypes[];
field_type?: FIELD_TYPE[];
field_type_filter?: FIELD_TYPE[];
shards?: string[];
}
export interface SearchOptions extends BaseSearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
with_status?: ResourceStatus;

@@ -37,0 +39,0 @@ with_duplicates?: boolean;

@@ -43,5 +43,5 @@ import { Observable } from 'rxjs';

export declare const batchUpload: (nuclia: INuclia, path: string, files: FileList | File[] | FileWithMetadata[], isResource?: boolean) => Observable<UploadStatus>;
export declare const uploadToProcess: (nuclia: INuclia, file: File, metadata?: FileMetadata) => Observable<string>;
export declare const uploadToProcess: (nuclia: INuclia, nuaKey: string, file: File, metadata?: FileMetadata) => Observable<string>;
export declare const getFileMetadata: (metadata: FileMetadata | undefined) => {
[key: string]: string;
};
import type { Observable } from 'rxjs';
import type { AuthTokens, JwtUser } from './auth';
import type { Account, AccountCreation, AccountStatus, AccountTypes, EventList, IKnowledgeBoxItem, IStandaloneKb, KnowledgeBox, KnowledgeBoxCreation, LearningConfigurations, NUAClient, NUAClientPayload, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome, WritableKnowledgeBox } from './db';
import type { Account, AccountCreation, AccountStatus, AccountTypes, EventList, IKnowledgeBoxItem, IStandaloneKb, KnowledgeBox, KnowledgeBoxCreation, LearningConfigurations, NUAClient, NUAClientPayload, PredictedToken, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome, WritableKnowledgeBox } from './db';
export interface INuclia {

@@ -98,2 +98,3 @@ options: NucliaOptions;

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}

@@ -104,2 +105,3 @@ export interface NucliaOptions {

apiKey?: string;
nuaKey?: string;
account?: string;

@@ -106,0 +108,0 @@ accountType?: AccountTypes;

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

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

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

declare const NUA_KEY = "NUCLIA_NUA_KEY";
declare const NUA_CLIENT = "NUCLIA_NUA_CLIENT";
interface Account {

@@ -47,7 +46,23 @@ id: string;

limits: AccountLimits;
blocking_state: AccountBlockingState;
blocked_features: BlockedFeature[];
}
interface AccountConfig {
g_speech_to_text: boolean;
indexer_slow_replicas: number;
max_dedicated_processors: number;
}
interface AccountLimits {
processing: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
upload: {

@@ -57,8 +72,26 @@ upload_limit_max_media_file_size: number;

};
processing: {
usage: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
}
declare enum AccountBlockingState {
UNBLOCKED = "unblocked",
QUOTA = "quota",
MANAGER = "manager"
}
declare enum BlockedFeature {
UPLOAD = "upload",
PROCESSING = "processing",
SEARCH = "search",
GENERATIVE = "generative"
}
interface AccountCreation {

@@ -168,2 +201,8 @@ slug: string;

}[];
interface PredictedToken {
text: string;
ner: string;
start: number;
end: number;
}

@@ -209,3 +248,3 @@ interface UploadResponse {

declare const batchUpload: (nuclia: INuclia, path: string, files: FileList | File[] | FileWithMetadata[], isResource?: boolean) => Observable<UploadStatus>;
declare const uploadToProcess: (nuclia: INuclia, file: File, metadata?: FileMetadata) => Observable<string>;
declare const uploadToProcess: (nuclia: INuclia, nuaKey: string, file: File, metadata?: FileMetadata) => Observable<string>;
declare const getFileMetadata: (metadata: FileMetadata | undefined) => {

@@ -591,12 +630,5 @@ [key: string]: string;

}
interface SearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
interface BaseSearchOptions {
fields?: string[];
filters?: string[];
fields?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
min_score?: number;

@@ -609,4 +641,13 @@ range_creation_start?: string;

extracted?: ExtractedDataTypes[];
field_type?: FIELD_TYPE[];
field_type_filter?: FIELD_TYPE[];
shards?: string[];
}
interface SearchOptions extends BaseSearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
with_status?: ResourceStatus;

@@ -809,3 +850,3 @@ with_duplicates?: boolean;

declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;

@@ -983,2 +1024,5 @@ interface ReadableResource extends IResource {

deleteServiceAccount(saId: string): Observable<void>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
createKey(saId: string, expires: string): Observable<{

@@ -1018,2 +1062,4 @@ token: string;

interface UpdateEntitiesGroupPayload {
title?: string;
color?: string;
add: {

@@ -1179,3 +1225,3 @@ [key: string]: Entity;

getResourceFromData(data: IResource): Resource;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;
find(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>;

@@ -1228,2 +1274,5 @@ search(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>;

}>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
deleteKey(saId: string, saKeyId: string): Observable<void>;

@@ -1259,2 +1308,3 @@ setConfiguration(config: {

hasNUAClient(): boolean;
getNUAKey(): string;
getNUAHeader(): {

@@ -1273,2 +1323,3 @@ 'x-stf-nuakey': string;

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}

@@ -1370,2 +1421,3 @@

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}

@@ -1376,2 +1428,3 @@ interface NucliaOptions {

apiKey?: string;
nuaKey?: string;
account?: string;

@@ -1482,2 +1535,2 @@ accountType?: AccountTypes;

export { Account, AccountConfig, AccountCreation, AccountLimits, AccountStatus, AccountTypes, AuthTokens, Authentication, Chat, Classification, CloudLink, ComputedMetadata, Counters, Db, Entities, EntitiesGroup, Entity, EntityPositions, Event, EventList, EventType, ExtractedData, ExtractedDataTypes, ExtractedText, FIELD_TYPE, FieldClassification, FieldComputedMetadata, FieldFullId, FieldId, FieldMetadata, FileB64, FileExtractedData, FileField, FileFieldData, FileFieldExtractedData, FileMetadata, FilePages, FileUploadStatus, FileWithMetadata, IAuthentication, ICreateResource, IDb, IError, IErrorResponse, 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, Metadata, NUAClient, NUAClientPayload, NUA_CLIENT, NUA_KEY, NestedPosition, Nuclia, NucliaDBRole, NucliaOptions, Origin, PagePositions, Paragraph, ParagraphClassification, PositionedNER, 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, 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, getFieldTypeFromString, getFileMetadata, getFilterFromLabel, getLabelFromFilter, lengthUnicode, longToShortFieldType, resourceToAlgoliaFormat, search, setEntities, setLabels, shortToLongFieldType, sliceUnicode, upload, uploadFile, uploadToProcess };
export { Account, AccountBlockingState, AccountConfig, AccountCreation, AccountLimits, AccountStatus, AccountTypes, AuthTokens, Authentication, BaseSearchOptions, BlockedFeature, Chat, Classification, CloudLink, ComputedMetadata, Counters, Db, Entities, EntitiesGroup, Entity, EntityPositions, Event, EventList, EventType, ExtractedData, ExtractedDataTypes, ExtractedText, FIELD_TYPE, FieldClassification, FieldComputedMetadata, FieldFullId, FieldId, FieldMetadata, FileB64, FileExtractedData, FileField, FileFieldData, FileFieldExtractedData, FileMetadata, FilePages, FileUploadStatus, FileWithMetadata, IAuthentication, ICreateResource, IDb, IError, IErrorResponse, 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, 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, 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, getFieldTypeFromString, getFileMetadata, 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,o){function s(t){try{u(n.next(t))}catch(t){o(t)}}function a(t){try{u(n.throw(t))}catch(t){o(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(s,a)}u((n=n.apply(t,e||[])).next())}))}function o(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)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 s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}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 s(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,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function u(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i<o;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||[]),o=[];return n={},s("next"),s("throw"),s("return"),n[Symbol.asyncIterator]=function(){return this},n;function s(t){i[t]&&(n[t]=function(e){return new Promise((function(r,n){o.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(o[0][2],r)}catch(t){h(o[0][3],t)}var r}function u(t){a("next",t)}function l(t){a("throw",t)}function h(t,e){t(e),o.shift(),o.length&&a(o[0][0],o[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=s(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 o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var c=s(o),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 o.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=s(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 x=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),A=Function.prototype.bind;function k(t,e){return A.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,o,s=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}:s&&E.useDeprecatedNextContext?((o=Object.create(e)).unsubscribe=function(){return s.unsubscribe()},i={next:e.next&&k(e.next,o),error:e.error&&k(e.error,o),complete:e.complete&&k(e.complete,o)}):i=e;return s.destination=new R(i),s}return r(e,t),e}(x);function P(t){S(t)}var I={closed:!0,next:w,error:function(t){throw t},complete:w},D="function"==typeof Symbol&&Symbol.observable||"@@observable";function O(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,o=(n=t)&&n instanceof x||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;o.add(e?e.call(o,r):r?i._subscribe(o):i._trySubscribe(o))})),o},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[D]=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?O: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 C(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 U(t,e,r,n,i){return new N(t,e,r,n,i)}var N=function(t){function e(e,r,n,i,o,s){var a=t.call(this,e)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,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}(x),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=s(e.currentObservers),o=i.next();!o.done;o=i.next()){o.value.next(t)}}catch(t){r={error:t}}finally{try{o&&!o.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,o=r.observers;return n||i?y:(this.currentObservers=null,o.push(t),new b((function(){e.currentObservers=null,g(o,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},z=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,o=r._infiniteTimeWindow,s=r._timestampProvider,a=r._windowTime;n||(i.push(e),!o&&i.push(s.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,o=(i?1:2)*e;if(e<1/0&&o<n.length&&n.splice(0,n.length-o),!i){for(var s=r.now(),a=0,u=1;u<n.length&&n[u]<=s;u+=2)a=u;a&&n.splice(0,a+1)}},e}(B),K=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)))},M=function(t){return clearInterval(t)},G=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&&M(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}(K),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))(G),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[D])}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 ot="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function st(t){return d(null==t?void 0:t[ot])}function at(t){return l(this,arguments,(function(){var e,r,n;return o(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[D]();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(st(t))return e=t,new F((function(t){var r,n;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){r={error:t}}finally{try{o&&!o.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,s,a;return i(this,void 0,void 0,(function(){var i,u;return o(this,(function(o){switch(o.label){case 0:o.trys.push([0,5,6,11]),r=h(t),o.label=1;case 1:return[4,r.next()];case 2:if((n=o.sent()).done)return[3,4];if(i=n.value,e.next(i),e.closed)return[2];o.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=o.sent(),s={error:u},[3,11];case 6:return o.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:o.sent(),o.label=8;case 8:return[3,10];case 9:if(s)throw s.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 o=e.schedule((function(){r(),i?t.add(this.schedule(null,n)):this.unsubscribe()}),n);if(t.add(o),!i)return o}function dt(t,e){return void 0===e&&(e=0),C((function(r,n){r.subscribe(U(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),C((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(st(t))return function(t,e){return new F((function(r){var n;return ht(r,e,(function(){n=t[ot](),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 C((function(r,n){var i=0;r.subscribe(U(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,xt=Object.prototype,At=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)===xt){var r=At(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),C((function(e,n){return function(t,e,r,n,i,o,s,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){o&&e.next(t),c++;var a=!1;ct(r(t,l++)).subscribe(U(e,(function(t){null==i||i(t),o?p(t):e.next(t)}),(function(){a=!0}),void 0,(function(){if(a)try{c--;for(var t=function(){var t=u.shift();s?ht(e,s,(function(){return f(t)})):f(t)};u.length&&c<n;)t();d()}catch(t){e.error(t)}})))};return t.subscribe(U(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(O,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,o=n.keys,s=new F((function(t){var e=i.length;if(e)for(var r=new Array(e),n=e,s=e,a=function(e){var a=!1;ct(i[e]).subscribe(U(t,(function(t){a||(a=!0,s--),r[e]=t}),(function(){return n--}),void 0,(function(){n&&a||(s||t.next(o?function(t,e){return t.reduce((function(t,r,n){return t[r]=e[n],t}),{})}(o,r):r),t.complete())})))},u=0;u<e;u++)a(u);else t.complete()}));return r?s.pipe(St(r)):s}function Dt(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,o=(i=t)instanceof Date&&!isNaN(i)?+t-r.now():t;o<0&&(o=0);var s=0;return r.schedule((function(){e.closed||(e.next(s++),0<=n?this.schedule(void 0,n):e.complete())}),o)}))}function Ot(){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 C((function(r,n){var i=0;r.subscribe(U(n,(function(r){return t.call(e,r,i++)&&n.next(r)})))}))}function Lt(t){return C((function(e,r){var n,i=null,o=!1;i=e.subscribe(U(r,void 0,void 0,(function(s){n=ct(t(s,Lt(t)(e))),i?(i.unsubscribe(),i=null,n.subscribe(r)):o=!0}))),o&&(i.unsubscribe(),i=null,n.subscribe(r))}))}function Ct(t,e){return d(e)?Rt(t,e,1):Rt(t,1)}function Ut(t){return t<=0?function(){return X}:C((function(e,r){var n=0;e.subscribe(U(r,(function(e){++n<=t&&(r.next(e),t<=n&&r.complete())})))}))}function Nt(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}:C((function(t,e){var i,o=0,s=function(){if(null==i||i.unsubscribe(),i=null,null!=r){var t="number"==typeof r?Dt(r):ct(r(o)),n=U(e,(function(){n.unsubscribe(),a()}));t.subscribe(n)}else a()},a=function(){var r=!1;i=t.subscribe(U(e,void 0,(function(){++o<n?i?s():r=!0:e.complete()}))),r&&s()};a()}))}function jt(t,e){return C((function(r,n){var i=null,o=0,s=!1,a=function(){return s&&!i&&n.complete()};r.subscribe(U(n,(function(r){null==i||i.unsubscribe();var s=0,u=o++;ct(t(r,u)).subscribe(i=U(n,(function(t){return n.next(e?e(r,t,u,s++):t)}),(function(){i=null,a()})))}),(function(){s=!0,a()})))}))}function Bt(t,e,r){var n=d(t)||e||r?{next:t,error:e,complete:r}:t;return n?C((function(t,e){var r;null===(r=n.subscribe)||void 0===r||r.call(n);var i=!0;t.subscribe(U(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)})))})):O}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 o=new AbortController,s=o.signal,a=!0,u=i.signal;if(u)if(u.aborted)o.abort();else{var c=function(){s.aborted||o.abort()};u.addEventListener("abort",c),e.add((function(){return u.removeEventListener("abort",c)}))}var l=n(n({},i),{signal:s}),h=function(t){a=!1,e.error(t)};return fetch(t,l).then((function(t){r?ct(r(t)).subscribe(U(e,void 0,(function(){a=!1,e.complete()}),h)):(a=!1,e.next(t),e.complete())})).catch(h),function(){a&&o.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,o=0;n=t.charAt(o++);~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 zt="JWT_KEY",Kt="JWT_REFRESH_KEY",Wt=216e5;class Mt{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-STF-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?r="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog"))&&(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(zt),localStorage.removeItem(Kt),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(zt)||""}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(Kt)||""}storeTokens(t){localStorage.setItem(zt,t.access_token),localStorage.setItem(Kt,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=Dt(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 Gt="NUCLIA_NUA_KEY",Vt="NUCLIA_NUA_CLIENT";var Jt,Xt,qt,Zt,Qt,te,ee,re;t.StatsPeriod=void 0,(Jt=t.StatsPeriod||(t.StatsPeriod={})).DAY="day",Jt.WEEK="week",Jt.MONTH="month",Jt.YEAR="year",t.StatsRange=void 0,(Xt=t.StatsRange||(t.StatsRange={})).anHour="1h",Xt.twoHours="2h",Xt.threeHours="3h",Xt.sixHours="6h",Xt.twelveHours="12h",Xt.twentyFourHours="24h",Xt.fortyHeightHours="48h",t.StatsType=void 0,(qt=t.StatsType||(t.StatsType={})).PROCESSING_TIME="processing_time",qt.SEARCHES="searches",qt.CHARS="chars",qt.MEDIA_SECONDS="media_seconds",qt.BYTES="bytes",qt.RESOURCES="resources",qt.PAGES="pages",qt.TRAIN_SECONDS="train_seconds",qt.SUGGESTIONS="suggestions",qt.DOCS_NO_MEDIA="docs_no_media",t.ResourceProperties=void 0,(Zt=t.ResourceProperties||(t.ResourceProperties={})).BASIC="basic",Zt.ORIGIN="origin",Zt.RELATIONS="relations",Zt.VALUES="values",Zt.EXTRACTED="extracted",Zt.ERRORS="errors",t.ResourceFieldProperties=void 0,(Qt=t.ResourceFieldProperties||(t.ResourceFieldProperties={})).VALUE="value",Qt.EXTRACTED="extracted",Qt.ERROR="error",t.ExtractedDataTypes=void 0,(te=t.ExtractedDataTypes||(t.ExtractedDataTypes={})).TEXT="text",te.METADATA="metadata",te.LARGE_METADATA="large_metadata",te.VECTOR="vectors",te.LINK="link",te.FILE="file",t.LabelSetKind=void 0,(ee=t.LabelSetKind||(t.LabelSetKind={})).RESOURCES="RESOURCES",ee.PARAGRAPHS="PARAGRAPHS",t.EventType=void 0,(re=t.EventType||(t.EventType={})).VISITED="VISITED",re.MODIFIED="MODIFIED",re.DELETED="DELETED",re.NEW="NEW",re.STARTED="STARTED",re.STOPPED="STOPPED",re.SEARCH="SEARCH",re.PROCESSED="PROCESSED";const ne=524288,ie=new RegExp(/[^a-z0-9_-]/g),oe=(t,e,r,n,i={})=>(i.contentType||r instanceof ArrayBuffer||(i.contentType=r?.type),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((o=>n?ae(t,e,o,i,r.payload):se(t,e,o,i))))),se=(t,e,r,n)=>{const i={"content-type":n?.contentType||"application/octet-stream",...le(n)};let o=1;const s=n?.rslug?`?rslug=${n.rslug}`:"";return t.rest.post(`${e}/upload${s}`,r,i).pipe(Nt(),Ft((t=>0==o--||503!==t.status)),Ut(1),jt((t=>{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})}})))},ae=(t,e,r,n,i)=>{let o=0,s=!1;const a=r.byteLength,u=Math.ceil(a/ne),c={"upload-length":`${a}`,"tus-resumable":"1.0.0"},l=[];n?.filename&&l.push(`filename ${btoa(encodeURIComponent(n.filename))}`),n?.lang&&l.push(`language ${btoa(n.lang)}`),n?.md5&&l.push(`md5 ${btoa(n.md5)}`),l.push(`content_type ${btoa(n?.contentType||"application/octet-stream")}`),l.length>0&&(c["upload-metadata"]=l.join(","));let h=1;return t.rest.post(`${e}/tusupload`,i,c,!0).pipe(Nt(),Ft((t=>0==h--||503!==t.status)),Lt((t=>yt(t))),Ut(1),Ct((e=>Ot(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"))),Ct((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,u).pipe(Ct((()=>{const i=r.slice(o,o+ne);return s?yt({failed:s}):t.rest.patch(e,i,{"content-type":n?.contentType||"application/octet-stream","upload-offset":`${o}`,"content-length":`${i.byteLength}`},!0).pipe(Et((t=>200!==t.status?(s=!0,{failed:s}):(o+=ne,{completed:o>=a,progress:o>=a?100:Math.min(Math.floor(o/a*100),100)}))),Lt((()=>yt({failed:!0}))))}))))))))))},ue=(t,e,r,n=!1)=>{const i=Array.from(r),o=i.reduce(((t,e)=>t+(e.size||0)),0),s=[],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(ie,"_");s.includes(t)&&(t+="_"+s.filter((e=>e.startsWith(t))).length),s.push(t),i=`${i}/file/${t}`}const o=r.lang;if(o){const t=r.payload||{};r.payload={...t,metadata:{...t?.metadata,language:o}}}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 C((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,s=i+r===a.length,u=Math.round(a.reduce(((t,e)=>t+e.file.size*e.progress/100),0)/o*100);return{files:a,progress:u,completed:s,uploaded:i,failed:r,conflicts:n}})))},ce=(t,e,r)=>{const n={"x-stf-nuakey":`Bearer ${localStorage.getItem(Gt)}`,"content-type":r?.contentType||"application/octet-stream",...le(r)};return t.rest.post("/processing/upload",e,n)},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};var he,de,pe,fe,ge,be;t.SortField=void 0,(he=t.SortField||(t.SortField={})).created="created",he.modified="modified",he.title="title",t.SHORT_FIELD_TYPE=void 0,(de=t.SHORT_FIELD_TYPE||(t.SHORT_FIELD_TYPE={})).layout="l",de.text="t",de.file="f",de.link="u",de.datetime="d",de.keywordset="k",de.generic="a",de.conversation="c",t.Search=void 0,pe=t.Search||(t.Search={}),(fe=pe.Features||(pe.Features={})).PARAGRAPH="paragraph",fe.DOCUMENT="document",fe.RELATIONS="relations",fe.VECTOR="vector",(ge=pe.ResourceFeatures||(pe.ResourceFeatures={})).PARAGRAPH="paragraph",ge.RELATIONS="relations",ge.VECTOR="vector",(be=pe.FindScoreType||(pe.FindScoreType={})).VECTOR="VECTOR",be.BM25="BM25",be.BOTH="BOTH";const ye=(t,e,r,n,i=[],o,s)=>{const a={};o?.isAdvanced?a.advanced_query=n||"":a.query=n||"",a.features=i;const{inTitleOnly:u,...c}=o||{};u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];return(s?t.rest.get(`${r}/find?${Te(a,c)}`):t.rest.post(`${r}/find`,{...a,...c})).pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"findResults"})),Bt((r=>{"findResults"===r.type&&r.shards&&(t.currentShards={...t.currentShards,[e]:r.shards})})))},ve=(t,e,r,n,i=[],o,s)=>{const a={};a.query=n||"",a.features=i;const{inTitleOnly:u,...c}=o||{};u&&(a.fields=["a/title"]),a.shards=t.currentShards?.[e]||[];const l=s?t.rest.get(`${r}/search?${Te(a,c)}`):t.rest.post(`${r}/search`,{...a,...c});return Ee(t,e,l)},me=(t,e,r,n)=>{const i={};i.query=r||"",i.shards=t.currentShards?.[e]||[];const o=t.rest.get(`/kb/${e}/catalog?${n?Te(i,n):""}`);return Ee(t,e,o)};function Ee(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 Te=(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,we;t.Chat=void 0,function(t){t.PARAGRAPHS="paragraphs",t.RELATIONS="relations"}((Se=t.Chat||(t.Chat={})).Features||(Se.Features={})),(we=Se.Author||(Se.Author={})).USER="USER",we.NUCLIA="NUCLIA";const _e="_END_";function xe(e,r,n,i=[],o=[t.Chat.Features.PARAGRAPHS]){let s,a=0,u="";return e.rest.getStream(`${r}/chat`,{query:n,context:i,show:[t.ResourceProperties.BASIC,t.ResourceProperties.VALUES],features:o.length>0?o:void 0}).pipe(Et((({data:t,incomplete:e,headers:r})=>{const n=r.get("NUCLIA-LEARNING-ID")||"";if(0===a&&t.length>=4&&(a=new DataView(t.buffer.slice(0,4)).getUint32(0)),!s&&a>0&&t.length>a+4){const e=t.slice(4,a+4);s=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}return s&&t.length>a+4&&(u=(new TextDecoder).decode(t.slice(a+4).buffer),u.includes(_e)&&(u=u.split(_e)[0])),{text:u,sources:s,incomplete:e,id:n}})))}const Ae=t=>[...new Set([...t].map((t=>JSON.stringify(t))))].map((t=>JSON.parse(t))),ke=(t,e,r,n,i)=>{const o=Ae(i.filter((r=>$e(r,t,e))).map((t=>t.token)).reduce(((t,e)=>t.concat(e)),[])),s=Ae(i.filter((r=>Pe(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?[...s,{key:r,classifications:n}]:s;return o.length>0||u.length>0?[...a,{field:{field:t,field_type:e},token:o.length>0?o:void 0,paragraphs:u.length>0?u:void 0}]:a},Re=(t,e,r,n)=>{const i=Ae(n.filter((r=>Pe(r,t,e))).map((t=>t.paragraphs)).reduce(((t,e)=>t.concat(e)),[])),o=n.filter((r=>r.field.field!==t||r.field.field_type!==e));return r.length>0||i.length>0?[...o,{field:{field:t,field_type:e},token:r.length>0?r:void 0,paragraphs:i.length>0?i:void 0}]:o},$e=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.token&&t.token.length>0,Pe=(t,e,r)=>t.field.field===e&&t.field.field_type===r&&t.paragraphs&&t.paragraphs.length>0,Ie=(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 Ie(this.getFieldText(t,e),r.start,r.end)}getSentenceText(t,e,r){return Ie(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 Oe 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 o=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this.path}/${e}/${r}?${o.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}`)}addField(t,e,r){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,r)}updateField(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 ue(this.nuclia,this.path,t,!0)}search(t,e=[],r){return ve(this.nuclia,this.kb,this.path,t,e,r,!0)}setLabels(t,e,r,n){const i=ke(t,e,r,n,this.fieldmetadata||[]);return this.modify({fieldmetadata:i}).pipe(Bt((()=>this.fieldmetadata=i)))}setEntities(t,e,r){const n=Re(t,e,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:n}).pipe(Bt((()=>this.fieldmetadata=n)))}}var Fe,Le;t.FIELD_TYPE=void 0,(Fe=t.FIELD_TYPE||(t.FIELD_TYPE={})).text="text",Fe.file="file",Fe.link="link",Fe.layout="layout",Fe.conversation="conversation",Fe.keywordset="keywordset",Fe.datetime="datetime",t.RESOURCE_STATUS=void 0,(Le=t.RESOURCE_STATUS||(t.RESOURCE_STATUS={})).PENDING="PENDING",Le.PROCESSED="PROCESSED",Le.ERROR="ERROR";var Ce,Ue,Ne;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,(Ne=t.TrainingExecutionStatus||(t.TrainingExecutionStatus={})).succeeded="succeeded",Ne.failed="failed",Ne.stopped="stopped";class je{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 Be{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 o=[...n.map((t=>`show=${t}`)),...i.map((t=>`extracted=${t}`))];return this.nuclia.rest.get(`${this._getPath(e,r)}?${o.join("&")}`).pipe(Et((t=>new Oe(this.nuclia,this.id,t))))}_getPath(t,e){return t?`${this.path}/resource/${t}`:`${this.path}/slug/${e}`}getResourceFromData(t){return new Oe(this.nuclia,this.id,t)}chat(t,e,r){return xe(this.nuclia,this.path,t,e,r)}find(t,e=[],r){return ye(this.nuclia,this.id,this.path,t,e,r)}search(t,e=[],r){return ve(this.nuclia,this.id,this.path,t,e,r)}catalog(t,e){return me(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 Oe(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 He extends Be{admin;contrib;_training;get training(){return this._training||(this._training=new je(this,this.nuclia)),this._training}modify(t){return this.nuclia.rest.patch(`/account/${this.account}/kb/${this.slug}`,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 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})}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 Ye{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 He(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 He(this.nuclia,"",{id:this.nuclia.options.knowledgeBox,zone:this.nuclia.options.zone}))}createKnowledgeBox(t,e){return this.nuclia.rest.post(`/account/${t}/kbs`,e).pipe(Bt((t=>{if(!t.id)throw"KnowledgeBox creation failed"})),jt((()=>this.getKnowledgeBox(t,e.slug))))}getStats(e,r,n,i=t.StatsPeriod.DAY,o){const s=[`period=${i}`,`stats=${r}`];return o&&s.push(`utctime=${o}`),n&&s.push(`knowledgebox=${n}`),this.nuclia.rest.get(`/account/${e}/stats?${s.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 ce(this.nuclia,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!!localStorage.getItem(Vt)&&!!localStorage.getItem(Gt)}getNUAHeader(){return{"x-stf-nuakey":`Bearer ${localStorage.getItem(Gt)}`}}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&&(localStorage.setItem(Gt,t.token),localStorage.setItem(Vt,t.client_id))})))}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")}}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),o={"content-type":"application/json","x-ndb-client":this.nuclia.options.client||"web",...i};return n&&(o["x-synchronous"]=`${n}`),{...o,...r}}fetch(t,e,r,n,i,o=!1){const s=n&&n["content-type"];return Ht(this.getFullUrl(e),{selector:t=>Promise.resolve(t),headers:this.getHeaders(t,e,n,o),method:t,body:s?r:JSON.stringify(r)}).pipe(jt((t=>t.ok?i?yt(t):bt(t.clone().json().catch((()=>t.text()))):vt((()=>t)))))}getFullUrl(t){return`${t.startsWith("/account")||t.startsWith("/user")||t.startsWith("/auth")||t.startsWith("/zones")||t.startsWith("/billing")||t.includes("/activity")||this.nuclia.options.standalone?this.nuclia.backend:this.nuclia.regionalBackend}${t.startsWith("/auth")||t.startsWith("/export")||t.startsWith("/billing")?"":"/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;if(e){let t=new Uint8Array;const i=()=>{e.read().then((({done:e,value:o})=>{e&&(r.next({data:t,incomplete:!1,headers:n}),r.complete()),o&&(t=this.concat(t,o),r.next({data:t,incomplete:!0,headers:n}),i())}))};i()}else r.next({data:new Uint8Array,incomplete:!1,headers:n}),r.complete()}))}))}concat(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}}t.Authentication=Mt,t.Db=Ye,t.FileFieldData=class{value;extracted;error},t.JwtHelper=Yt,t.KeywordSetFieldData=class{value;extracted;error},t.KnowledgeBox=Be,t.LinkFieldData=class{value;extracted;error},t.NUA_CLIENT=Vt,t.NUA_KEY=Gt,t.Nuclia=class{options;auth;rest;db;currentShards={};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)throw new Error("zone and knowledge box id must be defined in the Nuclia options");return this.readKb||(this.readKb=new Be(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 o=new $({next:function(t){n(t),o.unsubscribe()},error:i,complete:function(){r?n(e.defaultValue):i(new mt)}});t.subscribe(o)}))}(r.bind(t)(...e)):r}})}constructor(t){this.options=t,this.auth=new Mt(this),this.rest=new ze(this),this.db=new Ye(this)}},t.ReadableResource=De,t.Resource=Oe,t.Rest=ze,t.TUSuploadFile=ae,t.TextFieldData=class{value;extracted;error},t.Training=je,t.WritableKnowledgeBox=He,t.batchUpload=ue,t.catalog=me,t.chat=xe,t.deDuplicateList=Ae,t.find=ye,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.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=le,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=ve,t.setEntities=Re,t.setLabels=ke,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=Ie,t.upload=oe,t.uploadFile=se,t.uploadToProcess=ce}));
!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},D="function"==typeof Symbol&&Symbol.observable||"@@observable";function O(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[D]=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?O: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),B=p((function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})),j=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 B},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}(j),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}(j),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[D])}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[D]();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),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 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),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(O,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(St(r)):o}function Dt(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 Ot(){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?Dt(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 Bt(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 jt(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)})))})):O}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-STF-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?r="MANAGER":(e?.endsWith("/search")||e?.endsWith("/find")||e?.endsWith("/catalog"))&&(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(jt((()=>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=Dt(e).pipe(Bt((()=>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(Bt((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",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=r?.type),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(Bt((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),Bt((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=!1;const a=r.byteLength,u=Math.ceil(a/ie),c={"upload-length":`${a}`,"tus-resumable":"1.0.0"},l=[];n?.filename&&l.push(`filename ${btoa(encodeURIComponent(n.filename))}`),n?.lang&&l.push(`language ${btoa(n.lang)}`),n?.md5&&l.push(`md5 ${btoa(n.md5)}`),l.push(`content_type ${btoa(n?.contentType||"application/octet-stream")}`),l.length>0&&(c["upload-metadata"]=l.join(","));let h=1;return t.rest.post(`${e}/tusupload`,i,c,!0).pipe(Ct(),Ft((t=>0==h--||503!==t.status)),Lt((t=>yt(t))),Nt(1),Ut((e=>Ot(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,u).pipe(Ut((()=>{const i=r.slice(s,s+ie);return o?yt({failed:o}):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?(o=!0,{failed:o}):(s+=ie,{completed:s>=a,progress:s>=a?100:Math.min(Math.floor(s/a*100),100)}))),Lt((()=>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=i+r===a.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]||[];return(o?t.rest.get(`${r}/find?${Se(a,l)}`):t.rest.post(`${r}/find`,{...a,...l})).pipe(Lt((t=>yt({type:"error",status:t.status,detail:t.detail}))),Et((t=>"error"===t.type?t:{...t,type:"findResults"})),jt((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"})),jt((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=0,c="";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("NUCLIA-LEARNING-ID")||"";if(0===u&&t.length>=4&&(u=new DataView(t.buffer.slice(0,4)).getUint32(0)),!a&&u>0&&t.length>u+4){const e=t.slice(4,u+4);a=JSON.parse(atob((new TextDecoder).decode(e.buffer)))}return a&&t.length>u+4&&(c=(new TextDecoder).decode(t.slice(u+4).buffer),c.includes(Ae)&&(c=c.split(Ae)[0])),{text:c,sources:a,incomplete:e,id:n}})))}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,De=(t,e,r)=>t?(Array.isArray(t)||(t=Array.from(t)),t.slice(e,r).join("")):"";class Oe{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 De(this.getFieldText(t,e),r.start,r.end)}getSentenceText(t,e,r){return De(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 Oe{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}`)}addField(t,e,r){return this.nuclia.rest.put(`${this.path}/${t}/${e}`,r)}updateField(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(jt((()=>this.fieldmetadata=i)))}setEntities(t,e,r){const n=$e(t,e,r,this.fieldmetadata||[]);return this.modify({fieldmetadata:n}).pipe(jt((()=>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",t.RESOURCE_STATUS=void 0,(Ue=t.RESOURCE_STATUS||(t.RESOURCE_STATUS={})).PENDING="PENDING",Ue.PROCESSED="PROCESSED",Ue.ERROR="ERROR";var Ne,Ce,Be;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,(Be=t.TrainingExecutionStatus||(t.TrainingExecutionStatus={})).succeeded="succeeded",Be.failed="failed",Be.stopped="stopped";class je{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 je(this,this.nuclia)),this._training}modify(t){return this.nuclia.rest.patch(`/account/${this.account}/kb/${this.slug}`,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(Bt((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(Bt((e=>{const r=e.find((e=>e.title===t.title&&e.role===t.role));return r?yt(r):this.createServiceAccount(t).pipe(Bt((()=>this.getServiceAccounts())),Et((e=>e.find((e=>e.title===t.title&&e.role===t.role)))))})),Bt((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(Bt((t=>this.nuclia.options.zone||this.nuclia.options.standalone?yt(t):this.nuclia.rest.getZoneSlug(t.zone).pipe(jt((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(`/account/${t}/kbs`,e).pipe(jt((t=>{if(!t.id)throw"KnowledgeBox creation failed"})),Bt((()=>this.getKnowledgeBox(t,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(Bt((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})),jt((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`)})):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(Bt((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;if(e){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.next({data:new Uint8Array,incomplete:!1,headers:n}),r.complete()}))}))}concat(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}}t.Authentication=Gt,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={};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)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=Oe,t.Resource=Fe,t.Rest=ze,t.TUSuploadFile=ue,t.TextFieldData=class{value;extracted;error},t.Training=je,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.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.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=De,t.upload=oe,t.uploadFile=ae,t.uploadToProcess=le}));
import { Observable } from 'rxjs';
import type { IDb, INuclia } from '../models';
import type { LearningConfigurations } from './db.models';
import type { LearningConfigurations, PredictedToken } from './db.models';
import { Account, AccountCreation, AccountStatus, NUAClient, NUAClientPayload, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome } from './db.models';

@@ -32,2 +32,3 @@ import type { EventList, IKnowledgeBoxItem, KnowledgeBoxCreation } from './kb';

hasNUAClient(): boolean;
getNUAKey(): string;
getNUAHeader(): {

@@ -46,2 +47,3 @@ 'x-stf-nuakey': string;

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}
export type AccountTypes = 'stash-basic' | 'stash-team' | 'stash-trial' | 'stash-developer' | 'stash-business' | 'stash-startup' | 'stash-enterprise';
export declare const NUA_KEY = "NUCLIA_NUA_KEY";
export declare const NUA_CLIENT = "NUCLIA_NUA_CLIENT";
export interface Account {

@@ -18,7 +17,23 @@ id: string;

limits: AccountLimits;
blocking_state: AccountBlockingState;
blocked_features: BlockedFeature[];
}
export interface AccountConfig {
g_speech_to_text: boolean;
indexer_slow_replicas: number;
max_dedicated_processors: number;
}
export interface AccountLimits {
processing: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
upload: {

@@ -28,8 +43,26 @@ upload_limit_max_media_file_size: number;

};
processing: {
usage: {
monthly_limit_chars_processed: number;
monthly_limit_docs_no_media_processed: number;
monthly_limit_hosted_answers_generated: number;
monthly_limit_hosted_searches_performed: number;
monthly_limit_media_seconds_processed: number;
monthly_limit_non_media_files_processed: number;
monthly_limit_paragraphs_processed: number;
monthly_limit_paragraphs_stored: number;
monthly_limit_self_hosted_answers_generated: number;
monthly_limit_self_hosted_searches_performed: number;
};
}
export declare enum AccountBlockingState {
UNBLOCKED = "unblocked",
QUOTA = "quota",
MANAGER = "manager"
}
export declare enum BlockedFeature {
UPLOAD = "upload",
PROCESSING = "processing",
SEARCH = "search",
GENERATIVE = "generative"
}
export interface AccountCreation {

@@ -139,1 +172,7 @@ slug: string;

}[];
export interface PredictedToken {
text: string;
ner: string;
start: number;
end: number;
}

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

import { FileMetadata, FileWithMetadata, UploadStatus } from '../upload';
import type { Chat } from '../search';
import type { BaseSearchOptions, Chat } from '../search';
import { Search, SearchOptions } from '../search';

@@ -30,3 +30,3 @@ import { Training } from '../training';

getResourceFromData(data: IResource): Resource;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
chat(query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;
find(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.FindResults | IErrorResponse>;

@@ -79,2 +79,5 @@ search(query: string, features?: Search.Features[], options?: SearchOptions): Observable<Search.Results | IErrorResponse>;

}>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
deleteKey(saId: string, saKeyId: string): Observable<void>;

@@ -81,0 +84,0 @@ setConfiguration(config: {

@@ -108,2 +108,5 @@ import type { Observable } from 'rxjs';

deleteServiceAccount(saId: string): Observable<void>;
createKeyForService(data: ServiceAccountCreation, expires: string): Observable<{
token: string;
}>;
createKey(saId: string, expires: string): Observable<{

@@ -143,2 +146,4 @@ token: string;

export interface UpdateEntitiesGroupPayload {
title?: string;
color?: string;
add: {

@@ -145,0 +150,0 @@ [key: string]: Entity;

import { Observable } from 'rxjs';
import type { INuclia } from '../../models';
import { Chat } from './chat.models';
export declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[]): Observable<Chat.Answer>;
import type { BaseSearchOptions } from './search.models';
export declare function chat(nuclia: INuclia, path: string, query: string, context?: Chat.ContextEntry[], features?: Chat.Features[], options?: BaseSearchOptions): Observable<Chat.Answer>;

@@ -15,12 +15,5 @@ import type { ExtractedDataTypes, ResourceProperties } from '../kb';

}
export interface SearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
export interface BaseSearchOptions {
fields?: string[];
filters?: string[];
fields?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
min_score?: number;

@@ -33,4 +26,13 @@ range_creation_start?: string;

extracted?: ExtractedDataTypes[];
field_type?: FIELD_TYPE[];
field_type_filter?: FIELD_TYPE[];
shards?: string[];
}
export interface SearchOptions extends BaseSearchOptions {
inTitleOnly?: boolean;
isAdvanced?: boolean;
highlight?: boolean;
faceted?: string[];
sort?: SortOption;
page_number?: number;
page_size?: number;
with_status?: ResourceStatus;

@@ -37,0 +39,0 @@ with_duplicates?: boolean;

@@ -43,5 +43,5 @@ import { Observable } from 'rxjs';

export declare const batchUpload: (nuclia: INuclia, path: string, files: FileList | File[] | FileWithMetadata[], isResource?: boolean) => Observable<UploadStatus>;
export declare const uploadToProcess: (nuclia: INuclia, file: File, metadata?: FileMetadata) => Observable<string>;
export declare const uploadToProcess: (nuclia: INuclia, nuaKey: string, file: File, metadata?: FileMetadata) => Observable<string>;
export declare const getFileMetadata: (metadata: FileMetadata | undefined) => {
[key: string]: string;
};
import type { Observable } from 'rxjs';
import type { AuthTokens, JwtUser } from './auth';
import type { Account, AccountCreation, AccountStatus, AccountTypes, EventList, IKnowledgeBoxItem, IStandaloneKb, KnowledgeBox, KnowledgeBoxCreation, LearningConfigurations, NUAClient, NUAClientPayload, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome, WritableKnowledgeBox } from './db';
import type { Account, AccountCreation, AccountStatus, AccountTypes, EventList, IKnowledgeBoxItem, IStandaloneKb, KnowledgeBox, KnowledgeBoxCreation, LearningConfigurations, NUAClient, NUAClientPayload, PredictedToken, ProcessingPullResponse, ProcessingPushResponse, ProcessingStat, ProcessingStatusResponse, StatsPeriod, StatsRange, StatsType, Welcome, WritableKnowledgeBox } from './db';
export interface INuclia {

@@ -98,2 +98,3 @@ options: NucliaOptions;

getLearningConfigurations(): Observable<LearningConfigurations>;
predictTokens(text: string): Observable<PredictedToken[]>;
}

@@ -104,2 +105,3 @@ export interface NucliaOptions {

apiKey?: string;
nuaKey?: string;
account?: string;

@@ -106,0 +108,0 @@ accountType?: AccountTypes;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc