@sinequa/atomic 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- (function(o,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(o=typeof globalThis<"u"?globalThis:o||self,g(o.atomic={}))})(this,(function(o){"use strict";function g(e){if(typeof CustomEvent>"u"||typeof dispatchEvent>"u")return;const t=new CustomEvent("authenticated",{bubbles:!0,cancelable:!1,detail:{authenticated:e}});dispatchEvent(t)}const w={credentials:()=>({kind:"credentials"}),sso:()=>({kind:"sso"}),oauth:e=>({kind:"oauth",provider:e}),saml:e=>({kind:"saml",provider:e}),bearer:e=>({kind:"bearer",token:e}),unknown:()=>({kind:"unknown"})};function ae(e,t){const{useCredentials:r,useSSO:n,useSAML:a}=e;return a&&t.autoSAMLProvider?w.saml(t.autoSAMLProvider):r&&n?w.unknown():r?w.credentials():n?w.sso():t.authMode??w.unknown()}const u={loginPath:"/login",createRoutes:!1,authMode:w.unknown()};Object.defineProperties(u,{useCredentials:{enumerable:!1,configurable:!0,get(){const e=u.authMode?.kind;return e==="credentials"||e==="unknown"}},useSSO:{enumerable:!1,configurable:!0,get(){const e=u.authMode?.kind;return e==="sso"||e==="unknown"}},useSAML:{enumerable:!1,configurable:!0,get(){return u.authMode?.kind==="saml"}}});function p(e){const{useCredentials:t,useSSO:r,useSAML:n,authMode:a,...s}=e;if(Object.assign(u,s),a!==void 0){u.authMode=a;return}(t!==void 0||r!==void 0||n!==void 0)&&(u.authMode=ae({useCredentials:t,useSSO:r,useSAML:n},u))}const J={store:{},getItem(e){return this.store[e]??null},setItem(e,t){this.store[e]=t.toString()},removeItem(e){delete this.store[e]},clear(){this.store={}}},W=J;function Je(e){return typeof window>"u"||!window.localStorage?J.getItem(e):window.localStorage.getItem(e)}function We(e){typeof window>"u"||!window.localStorage?J.removeItem(e):window.localStorage.removeItem(e)}function x(e){return typeof window>"u"||!window.sessionStorage?W.getItem(e):window.sessionStorage.getItem(e)}function X(e,t){typeof window>"u"||!window.sessionStorage?W.setItem(e,t):window.sessionStorage.setItem(e,t)}function D(e){typeof window>"u"||!window.sessionStorage?W.removeItem(e):window.sessionStorage.removeItem(e)}const oe=/.*:\(?([><=\d\-.AND ]+)\)?/;function xe(e,t){return!e?.items||e?.items?.length===0?[]:e.items.reduce((a,s)=>{if(!s.value||s.value==="")return a;const i=se(s,e.column);return a.push({operator:i.operator,value:i.value,display:s.display||i.display,filters:i.filters,disabled:s.count===0,hidden:s.count===0&&e.isDistribution?!t:!1}),a},[])}function se(e,t){const r=t,n=e.value.match(oe);if(n?.[1]){const s=(n?.[1].split(" AND ")).map(i=>{const l=i.indexOf(">=")!==-1?"gte":"lt",c=i.substring(i.indexOf(" ")+1);return{field:r,operator:l,value:c,display:e.display||e.value}});if(s.length===2)return{field:r,operator:"and",filters:s,value:e.value,display:s[0].display||s[0].value};if(s.length===1)return{...s[0],field:r};throw new Error("Failed to parse distribution expression")}return{field:r,operator:"eq",value:e.value,display:e.display}}function Xe(e,t,r){return e.valuesAreExpressions?t.display===r.display:t.value===r.value}function ie(e){return e.items&&(e.items=e.items.map(t=>ie(t))),e.items&&e.items.some(t=>t.$selected||t.$opened)&&(e.$opened=!0),e}function Ye(e,t){const r=[];if(e.length>0){const n=new Map,s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").normalize("NFD").replace(/[\u0300-\u036f]/g,""),i=new RegExp("\\b"+s,"i");e.forEach(l=>{if(l.display.length>1){const c=l.display.normalize("NFD").replace(/[\u0300-\u036f]/g,""),h=i.exec(c);ce(r,n,"/",l.display,+(l.frequency||0),1,(h?.index||0)+t.length)}})}return r}function ce(e,t,r,n,a,s,i){const l=n.indexOf("/",r.length),c=n.substring(0,l+1);let h=t.get(c);if(!h){const C=c.replace(/^\/|\/$/g,"");h={value:n.substring(r.length,l),count:a,items:[],hasChildren:!1,$level:s,$opened:i>=c.length,$path:C},t.set(c,h),e.push(h)}c.length<n.length&&(h.hasChildren=!0,ce(h.items,t,c,n,a,s+1,i))}function Ke(e,t){return e.reduce((r,n)=>(t(n)?r.true.push(n):r.false.push(n),r),{true:[],false:[]})}const Ze=/(([\+\-])?\(([^\)]+)\))|(([\+\-])?\[([^\]]+)\])|(([\+\-])?\"([^\"]+)\")|(([\+\-])?\/([^\/]+)\/)|(([\+\-])?(\S+))/g,Ee=2,le=3,Te=5,ue=6,et=8,de=9,tt=11,fe=12,rt=14,he=15;function F(e){if(!e)return[];const t=[],r=e.matchAll(Ze);for(let n of r)n[le]?t.push({type:"group",value:n[le],op:n[Ee]}):n[ue]?t.push({type:"adjacent",value:n[ue],op:n[Te]}):n[de]?t.push({type:"exact",value:n[de],op:n[et]}):n[fe]?t.push({type:"regex",value:n[fe],op:n[tt]}):n[he]&&t.push({type:"token",value:n[he],op:n[rt]});return t}function B(e){return e.map(t=>{const r=t.op||"";switch(t.type){case"group":return`${r}(${t.value})`;case"adjacent":return`${r}[${t.value}]`;case"exact":return`${r}"${t.value}"`;case"regex":return`${r}/${t.value}/`;case"token":return`${r}${t.value}`}}).join(" ")}function nt(e,t,r){let n=F(e);for(let a of t)n.push({type:"adjacent",value:a,op:r});return B(n)}function at(e,t){const r=F(t),n=r.findIndex(a=>a.value===e);return n!==-1?(r.splice(n,1),t=B(r)):t}function ot(e){const t=F(e).filter(r=>r.type!=="adjacent");return B(t)}function st(e){return F(e).filter(t=>t.type==="adjacent").map(t=>t.value)}function it(e,t,r){const n=new Intl.RelativeTimeFormat(e,{numeric:"auto"}),{offset:a,unit:s,isFuture:i}=ge(t,r);return n.format(a*(i?1:-1),s)}function ge(e,t){const r=new Date(e),n=t?new Date(t):new Date,a=Math.abs(n.getTime()-r.getTime());return{offset:Math.floor(a/(1e3*60*60*24)),unit:"day",isFuture:r>n}}function ct(e){const t=e.target;return t&&t.nodeName!=="INPUT"&&t.nodeName!=="TEXTAREA"}function lt(e){if(e===void 0)return;const{q:t,f:r,p:n,s:a,t:s,n:i,b:l}=U(e),[c]=e.split("?");return{path:c,text:t,filters:r?Y(r):void 0,page:n?parseInt(n,10):void 0,sort:a,tab:s,name:i,basket:l}}function ut(e){if(!e)return"";const{text:t,filters:r,page:n,sort:a,tab:s,name:i,basket:l}=e,c={};t&&(c.q=t),r&&(c.f=JSON.stringify(r)),n&&(c.p=n.toString()),a&&(c.s=a),s&&(c.t=s),i&&(c.n=i),l&&(c.b=l);const h=new URLSearchParams(c).toString();return h||""}function dt(e){if(e===void 0)return[];const{f:t}=U(e);return Y(t)}function Y(e){const t=decodeURIComponent(e);try{return JSON.parse(t??"[]")}catch{return console.error(`Error parsing filters from URI: ${e}`),[]}}function U(e){const t=e.split("?")[1];if(t===void 0)return{};const r=new URLSearchParams(t);return Object.fromEntries(r)}function ft(e){const{q:t=""}=U(e);return t}function ht(e){const{id:t}=U(e);return decodeURIComponent(t)}function gt(e){const{p:t="0"}=U(e);return parseInt(t,10)}function mt(e){const{t}=U(e);return t}function wt(e,t){if(!e)return e;let r=0;const n=e.length;let a=0;if(e[a]==="["){for(;a<n&&/[0-9]/.test(e[a]);)a++;e[a]==="]"&&(r=a+1)}const s=K(e,r,!1);if(!s)return e;const i=t.charCodeAt(0),l=t.charCodeAt(1);let c=s;for(;c;)if(i===c.lang1&&l===c.lang2){const C=K(e,c.end+4,!0);return e.substring(C.start,C.end)}else c=K(e,c.end+4,!1);const h=e.substring(s.start,s.end);return h||e}function K(e,t,r){for(let n=t,a=e.length-3;n<a;n++)if(e[n]==="["&&e[n+3]==="]")return{start:t,end:n,lang1:e.charCodeAt(n+1),lang2:e.charCodeAt(n+2)};if(r)return{start:t,end:e.length,lang1:-1,lang2:-1}}function _t(e,t){const{useLocale:r,useLocaleAsPrefix:n,indexFile:a,path:s,folder:i}=t,l=r?`${e}/`:null,c=n?`${e}.${a}`:a??"";return[s,i,`${l||""}${c}`].filter(h=>h!==void 0).join("/")}function Q(e){const t=new CustomEvent("notification",{bubbles:!0,cancelable:!1,detail:e});dispatchEvent(t)}const St={success:(e,t)=>{Q({type:"success",message:e,options:t})},info:(e,t)=>{Q({type:"info",message:e,options:t})},warning:(e,t)=>{Q({type:"warning",message:e,options:t})},error:(e,t)=>{Q({type:"error",message:e,options:t})}};var Z=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(Z||{});let j={level:1,enableConsoleOutput:!0};function kt(e){j={...j,...e}}function V(e,t,r){if(e<j.level)return;const a=`${`[${Z[e]}]`} ${t}`;if(j.enableConsoleOutput)switch(e){case 0:console.debug(a,r||"");break;case 1:console.info(a,r||"");break;case 2:console.warn(a,r||"");break;case 3:console.error(a,r||"");break}}function $(e,t){V(0,e,t)}function O(e,t){V(1,e,t)}function N(e,t){V(2,e,t)}function f(e,t){V(3,e,t)}function A(e){const t=H(),r=new Headers(e);r.append("Sinequa-Force-Camel-Case","true"),r.append("accept","application/json"),t&&r.append("Sinequa-csrf-token",t);const{userOverride:n,userOverrideActive:a,bearerToken:s}=u;return s&&r.append("Authorization",`Bearer ${s}`),n&&a&&(r.append("sinequa-override-user",n.username),r.append("sinequa-override-domain",n.domain)),r}class P extends Error{status;constructor(t,r){super(t),this.name="ApiError",this.status=r}}class E extends P{constructor(t="Server error"){super(t,500),this.name="ServerError"}}class me extends P{constructor(t="Request timed out"){super(t,408),this.name="TimeoutError"}}class z extends P{constructor(t="Unauthorized access"){super(t,401),this.name="UnauthorizedError"}}async function y(e,t="json"){const r=e.headers.get("sinequa-jwt-refresh");if(r!==null&&M(r),e.status===200)switch(t){case"arraybuffer":return await e.arrayBuffer();case"blob":return await e.blob();case"text":return await e.text();default:return await e.json()}if(e.status===401){if(u.userOverrideActive){let n={};try{n=await e.clone().json()}catch{}throw N("Unauthorized access attempt with user override",{endpoint:e.url,error:n}),new z(n.errorMessage??n.message??"Unauthorized... User override failed.")}return await T(e,401)}return e.status===500?(f("Server error occurred",{endpoint:e.url}),await T(e,500)):(N(`Unexpected response status: ${e.status}`,{endpoint:e.url}),await T(e,e.status))}async function T(e,t){try{const{done:r,value:n}=await e.body?.getReader().read()||{done:!0,value:void 0};if(r||!n)throw t===401?new z:t===500?new E:new P(`Request failed with status ${t}`,t);const a=JSON.parse(new TextDecoder().decode(n));throw new Error(a.errorMessage||a.message||`Request failed with status ${t}`,{cause:{errorCode:a.errorCode,errorCodeTest:a.errorCodeTest}})}catch(r){throw r instanceof P?r:t===401?new z(r.message):t===500?new E(r.message):new P(r.message??`Request failed with status ${t}`,t)}}async function we(e,t,r){const n=A(r?.headers),{backendUrl:a}=u,s=t?`?${new URLSearchParams(t)}`:"",i=a?`${a}/${e}${s}`:`${e}${s}`;$(`Making DELETE request to: ${i}`);try{const l=await fetch(i,{method:"DELETE",credentials:"include",headers:n});return y(l,r?.responseType)}catch(l){throw f("Error making DELETE request:",l),l}}async function S(e,t,r){const n=A(r?.headers),{backendUrl:a}=u,s=t?`?${new URLSearchParams(t)}`:"";e.startsWith("plugin")&&(e=`api/v1/${e}`);const i=a?`${a}/${e}${s}`:`${e}${s}`;$(`Making GET request to: ${i}`);try{const l=await fetch(i,{method:"GET",credentials:"include",headers:n,signal:r?.signal});return y(l,r?.responseType)}catch(l){throw f("Error making GET request:",l),l}}async function _e(e,t,r){const n=A(r?.headers);n.append("content-type","application/json");const{app:a,backendUrl:s}=u,i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0},l=s?`${s}/${e}`:`${e}`;$(`Making PATCH request to: ${l}`);try{const c=await fetch(l,{method:"PATCH",headers:n,credentials:"include",body:JSON.stringify(i)});return y(c,r?.responseType)}catch(c){throw f("Error making PATCH request:",c),c}}async function d(e,t,r){const n=A(r?.headers),{app:a,backendUrl:s}=u;n.has("Content-Type")||n.set("Content-Type","application/json");const i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0};e.startsWith("plugin")&&(e=`api/v1/${e}`);const l=s?`${s}/${e}`:`${e}`;$(`Making POST request to: ${l}`);try{const c=await fetch(l,{method:"POST",headers:n,credentials:"include",body:JSON.stringify(i),signal:r?.signal});return y(c,r?.responseType)}catch(c){throw f("Error making POST request:",c),c}}async function pt(e,t,r){const n=A(r?.headers),{app:a,backendUrl:s}=u,i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0},l=`${s}/${e}`;$(`Making PUT request to: ${l}`);try{const c=await fetch(l,{method:"PUT",headers:n,credentials:"include",body:JSON.stringify(i)});return y(c,r?.responseType)}catch(c){throw f("Error making PUT request:",c),c}}function b(e){const t=new AbortController,{signal:r}=t;return e&&setTimeout(()=>{r.aborted||t.abort(new me(`Request timed out after ${e}ms`))},e),{controller:t,signal:r}}function ee(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function bt(e){const t=ee(e);return!!t&&t.getTime()<=Date.now()}function vt(e,t=7){const r=ee(e);if(!r)return!1;const n=Date.now(),a=n+t*24*60*60*1e3,s=r.getTime();return s>n&&s<=a}async function Ct(e,t=0,r=1e3){let n;for(let a=0;a<=t;a++)try{return await e()}catch(s){if(n=s,s instanceof P&&s.status>=400&&s.status<500&&s.status!==429||s instanceof DOMException&&s.name==="AbortError")throw s;a<t&&(N(`Retrying request (${a+1}/${t})`,{error:s}),await new Promise(i=>setTimeout(i,r)))}throw n}function Pt(e,t,r){if(!e||!t)return;if(r){const s=Object.keys(t.queries).find(c=>c===r?.toLowerCase());let i;s&&(i=t.queries[s]);const l=(i?.columnsInfo?.columns||[])?.find(c=>c.aliases?.split(",")?.includes(e));if(l)return l.name}const n=t.indexes?._?.columns,a=Object.entries(n).find(s=>s[1].aliases?.includes(e));if(a)return a[0]}var v=(e=>(e.None="None",e.Search_FirstPage="Search_FirstPage",e.Search_Text="Search_Text",e.Search_Refine="Search_Refine",e.Search_Select_Item="Search_Select_Item",e.Search_Select_Custom="Search_Select_Custom",e.Search_Select_Concept="Search_Select_Concept",e.Search_Select_Correction="Search_Select_Correction",e.Search_GotoPage="Search_GotoPage",e.Search_GotoTab="Search_GotoTab",e.Search_DisplayResult="Search_DisplayResult",e.Search_RemoveResult="Search_RemoveResult",e.Search_RemoveAdvanced="Search_RemoveAdvanced",e.Search_SavedQuery="Search_SavedQuery",e.Search_WebService="Search_WebService",e.Search_DidYouMean_Original="Search_DidYouMean_Original",e.Search_DidYouMean_Correction="Search_DidYouMean_Correction",e.Search_ExportCSV="Search_ExportCSV",e.Search_SavedQuery_ExportCSV="Search_SavedQuery_ExportCSV",e.Search_Selection_ExportCSV="Search_Selection_ExportCSV",e.Search_AlertQuery="Search_AlertQuery",e.Search_Select_AnalyticsItem="Search_Select_AnalyticsItem",e.Search_Sort="Search_Sort",e.Search_Exit_Logout="Search_Exit_Logout",e.Search_Timeline_Usage="Search_Timeline_Usage",e.Search_AutoComplete="Search_Autocomplete",e.Search_Login_Success="Login_Success_Form",e.Search_QueryIntent_Detected="Search_QueryIntent_Detected",e.SavedQuery_Add="SavedQuery_Add",e.SavedQuery_Delete="SavedQuery_Delete",e.SavedQuery_DeleteAll="SavedQuery_DeleteAll",e.SavedQuery_Rename="SavedQuery_Rename",e.Alert_Edit="Alert_Edit",e.Alert_Delete="Alert_Delete",e.Alert_DeleteAll="Alert_DeleteAll",e.Link_Display="Link_Display",e.Link_Click="Link_Click",e.Basket_Add="Basket_Add",e.Basket_Delete="Basket_Delete",e.Basket_DeleteAll="Basket_DeleteAll",e.Basket_Rename="Basket_Rename",e.Basket_AddDoc="Basket_AddDoc",e.Basket_RemoveDoc="Basket_RemoveDoc",e.Basket_Open="Basket_Open",e.Basket_ExportCSV="Basket_ExportCSV",e.Label_Add="Label_Add",e.Label_Delete="Label_Delete",e.Label_Rename="Label_Rename",e.Label_Open="Label_Open",e.Label_AddDoc="Label_AddDoc",e.Label_RemoveDoc="Label_RemoveDoc",e.Label_ExportCSV="Label_ExportCSV",e.Label_Menu_ExportCSV="Label_Menu_ExportCSV",e.Rating_Set="Rating_Set",e.Rating_Delete="Rating_Delete",e.Doc_Preview="Doc_Preview",e.Doc_CacheHtml="Doc_CacheHtml",e.Doc_CachePdf="Doc_CachePdf",e.Doc_CacheOriginal="Doc_CacheOriginal",e.Doc_Url1="Doc_Url1",e.Doc_Url2="Doc_Url2",e.Preview_Close="Preview_Close",e.Click_ResultLink="Click_ResultLink",e.Click_ResultLink1="Click_ResultLink1",e.Click_ResultLink2="Click_ResultLink2",e.Click_ResultLink3="Click_ResultLink3",e.Click_ResultLink4="Click_ResultLink4",e.Click_ResultLink5="Click_ResultLink5",e.Click_ResultLink6="Click_ResultLink6",e.Click_ResultLink7="Click_ResultLink7",e.Click_ResultLink8="Click_ResultLink8",e.Click_ResultLink9="Click_ResultLink9",e.Click_ResultLink10="Click_ResultLink10",e.Click_PreviewLink1="Click_PreviewLink1",e.Click_PreviewLink2="Click_PreviewLink2",e.Click_PreviewLink3="Click_PreviewLink3",e.Click_PreviewLink4="Click_PreviewLink4",e.Click_PreviewLink5="Click_PreviewLink5",e.Click_PreviewLink6="Click_PreviewLink6",e.Click_PreviewLink7="Click_PreviewLink7",e.Click_PreviewLink8="Click_PreviewLink8",e.Click_PreviewLink9="Click_PreviewLink9",e.Click_PreviewLink10="Click_PreviewLink10",e.RFM_ClickSet="RFM_ClickSet",e.RFM_ClickReset="RFM_ClickReset",e.RFM_Like="RFM_Like",e.RFM_LikeReset="RFM_LikeReset",e.RFM_Dislike="RFM_Dislike",e.RFM_Important="RFM_Important",e.RFM_ImportantReset="RFM_ImportantReset",e.RFM_Ban="RFM_Ban",e.Navigation_Exit="Navigation_Exit",e.Navigation_Return="Navigation_Return",e.Navigation_Route="Navigation_Route",e.Answer_Display="Answer_Display",e.Answer_Click="Answer_Click",e.Answer_Result="Answer_Result",e.Answer_Liked="Answer_Liked",e.Answer_Disliked="Answer_Disliked",e.Answer_Liked_Cancelled="Answer_Liked_Cancelled",e.Answer_Disliked_Cancelled="Answer_Disliked_Cancelled",e.TopPassages_Display="TopPassages_Display",e.TopPassages_Click="TopPassages_Click",e.UserSettings_Reset="UserSettings_Reset",e.Change_Password_Failed="change.password.failed",e.Change_Password_Success_Form="change.password.success.form",e.Forgot_Password_Request="forgot.password.request",e.Login_Denied="login.denied",e.Login_Success_Form="login.success.form",e.Send_Reset_Password_Link="send.reset.password.link",e.Xrest_ChangePassword="xrest.changepassword",e))(v||{}),m=(e=>(e[e.none=0]="none",e[e.bool=1]="bool",e[e.date=2]="date",e[e.dateTime=3]="dateTime",e[e.time=4]="time",e[e.unsigned=5]="unsigned",e[e.integer=6]="integer",e[e.float=7]="float",e[e.double=8]="double",e[e.dates=9]="dates",e[e.dateTimes=10]="dateTimes",e[e.times=11]="times",e[e.varchar=12]="varchar",e[e.binary=13]="binary",e[e.string=14]="string",e[e.csv=15]="csv",e))(m||{}),k=(e=>(e[e.none=0]="none",e[e.a=2053]="a",e[e.c=4]="c",e[e.d=8]="d",e[e.e=2068]="e",e[e.i=256]="i",e[e.l=2052]="l",e[e.n=8192]="n",e[e.t=524292]="t",e[e.x=8388608]="x",e[e.z=33554432]="z",e[e.f_ordinal=8192]="f_ordinal",e[e.f_multidates=8192]="f_multidates",e[e.f_varchar=33554432]="f_varchar",e[e.f_binary=33562624]="f_binary",e[e.f_string=33562888]="f_string",e[e.f_csv=42477853]="f_csv",e[e.f_overridable=33554696]="f_overridable",e))(k||{});const yt="1.0";var Se=(e=>(e[e.Original=0]="Original",e[e.Corrected=1]="Corrected",e))(Se||{}),ke=(e=>(e[e.none=0]="none",e[e.positiveRate=1]="positiveRate",e[e.mainlyPosRate=2]="mainlyPosRate",e[e.unrate=4]="unrate",e[e.mainlyNegRate=8]="mainlyNegRate",e[e.negativeRate=16]="negativeRate",e[e.all=31]="all",e[e.positiveOnly=7]="positiveOnly",e[e.negativeOnly=28]="negativeOnly",e[e.personalAll=21]="personalAll",e[e.personalPosOnly=5]="personalPosOnly",e[e.personalNegOnly=20]="personalNegOnly",e))(ke||{});function Rt(e){if(!e)return m.none;switch(e.toLocaleLowerCase()){case"bool":case"boolean":return m.bool;case"date":return m.date;case"datetime":return m.dateTime;case"time":return m.time;case"unsigned":return m.unsigned;case"integer":return m.integer;case"float":return m.float;case"double":return m.double;case"dates":return m.dates;case"datetimes":return m.dateTimes;case"times":return m.times;case"varchar":return m.varchar;case"binary":return m.binary;case"string":return m.string;case"csv":return m.csv;default:return m.none}}function Lt(e){switch(e){case"a":return k.a;case"c":return k.c;case"d":return k.d;case"e":return k.e;case"i":return k.i;case"l":return k.l;case"n":return k.n;case"t":return k.t;case"x":return k.x;case"z":return k.z;default:return k.none}}function Ut(e){let t=k.none;if(e)for(const r of e)t|=Lt(r);return t}function _(e,t,r,n){const a=Rt(t),s=Ut(r||"");return{name:e,type:t,typeModifier:r,eType:a,eTypeModifier:s,aliases:n}}const Ot={id:_("id","string"),text:_("text","varchar"),documentlanguages:_("documentlanguages","csv","ci",["language"]),databasealias:_("databasealias","varchar"),globalrelevance:_("globalrelevance","double"),matchingpartnames:_("matchingpartnames","csv"),matchlocations:_("matchlocations","csv"),matchlocationsperpartname:_("matchlocationsperpartname","varchar"),extracts:_("extracts","csv"),extractsperpartname:_("extractsperpartname","varchar"),extractslocations:_("extractslocations","csv"),documentweight:_("documentweight","varchar"),groupcount:_("groupcount","integer"),accesslists:_("accesslists","varchar",void 0,["accessLists"])};function pe(e){return e.filter(t=>!!t)}const $t={eq:(e,t)=>({field:e,operator:"eq",value:t}),neq:(e,t)=>({field:e,operator:"neq",value:t}),gt:(e,t)=>({field:e,operator:"gt",value:t}),gte:(e,t)=>({field:e,operator:"gte",value:t}),lt:(e,t)=>({field:e,operator:"lt",value:t}),lte:(e,t)=>({field:e,operator:"lte",value:t}),like:(e,t)=>({field:e,operator:"like",value:t}),contains:(e,t)=>({field:e,operator:"contains",value:t}),regex:(e,t)=>({field:e,operator:"regex",value:t}),isNull:e=>({field:e,operator:"null"}),isNotNull:e=>({field:e,operator:"notnull"}),in:(e,t)=>({field:e,operator:"in",values:t}),between:(e,t,r)=>({field:e,operator:"between",start:t,end:r}),and:(...e)=>be("and",e),or:(...e)=>be("or",e),not:(...e)=>{const t=pe(e);return t.length?{operator:"not",filters:t}:void 0}};function be(e,t){const r=pe(t);return r.length===0?void 0:r.length===1?r[0]:{operator:e,filters:r}}function At(e,t){let r=e[t];return r===void 0?[]:(typeof r=="string"&&(r=String(r).split(",")),Array.isArray(r)?r.map(n=>{if(typeof n=="string")return n.trim();if(typeof n=="object"&&n!==null&&"display"in n)return n.display.trim()}).filter(n=>n!==void 0):[String(r).trim()])}function It(e,t){let r=e[t];if(r===void 0)return[];if(typeof r=="string"&&(r=String(r).split(",")),Array.isArray(r))return r.map(a=>{if(typeof a=="string")return{display:a.trim(),value:a.trim()};if(typeof a=="object"&&a!==null&&"display"in a){const s=a.display.trim(),i="value"in a?String(a.value).trim():s;return{display:s,value:i}}}).filter(a=>a!==void 0);const n=String(r).trim();return[{display:n,value:n}]}function q(e){return e!==null&&typeof e=="object"}function ve(e){return q(e)&&Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function Ce(e){return q(e)&&Object.prototype.toString.call(e)==="[object Blob]"}function Pe(e){return Object.prototype.toString.call(e)==="[object Date]"}function ye(e){return typeof e=="string"}function Dt(e){return(q(e)||Array.isArray(e))&&!ve(e)&&!Ce(e)&&!ye(e)}function Re(e){return e?(e.getHours()*60*60+e.getMinutes()*60+e.getSeconds())*1e3+e.getMilliseconds():0}function Le(e=!0){let t=Date.now();return(e?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx":"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx").replace(/[xy]/g,n=>{const a=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n==="x"?a:a&3|8).toString(16)})}function Ft(e){if(!e)return"``";if(e=String(e),e.search(/[\\`]/)===-1)return`\`${e}\``;const t=["`"];for(let r=0,n=e.length;r<n;r++){const a=e[r];(a==="\\"||a==="`")&&t.push("\\"),t.push(a)}return t.push("`"),t.join("")}function Nt(e){if(typeof crypto<"u"&&crypto.subtle&&typeof crypto.subtle.digest=="function")try{return crypto.subtle.digest("SHA-512",new TextEncoder().encode(e)).then(t=>Array.prototype.map.call(new Uint8Array(t),r=>`00${r.toString(16)}`.slice(-2)).join("")).catch(()=>Promise.resolve(te(e)))}catch{return Promise.resolve(te(e))}return Promise.resolve(te(e))}function te(e){let n=2166136261;for(let C=0;C<e.length;C++)n^=e.charCodeAt(C),n=n*16777619>>>0;const a=n.toString(16).padStart(8,"0"),s=((n^2863311530)>>>0).toString(16).padStart(8,"0"),i=((n^1431655765)>>>0).toString(16).padStart(8,"0"),l=((n^3435973836)>>>0).toString(16).padStart(8,"0"),c=a+s+i+l;return(c+c+c+c).substring(0,128)}let re,Ue;function I(e,t=!0){let r=qt(e.$auditRecord);r&&(Oe(r),t&&$e(r)),e.$auditRecord=r}function qt(e){if(!e)return;let t;if(Array.isArray(e))t=e;else if(q(e)){const r=e;if(r.auditEvents||r.mlAuditEvents)return r;t=[e]}return{auditEvents:t}}function Oe(e){const t=Mt();return e.auditEvents?.forEach(r=>{r.detail||(r.detail={}),r.detail.sessionid=t}),e}function $e(e){const t=typeof window<"u"?decodeURIComponent(window.location.href):"http://localhost";return e?.auditEvents?.forEach(r=>{r.detail||(r.detail={}),r.detail.url=t}),e}function Mt(){return(!re||Bt())&&(re=Le()),Ue=new Date,re}function Bt(){return new Date().getTime()-Ue.getTime()>600*1e3}async function Qt(e,t=!0){const r={event:v.None,$auditRecord:e};return I(r,t),d("api/v1/audit.notify",r)}const jt={notify:Qt};async function Vt(e,t,r){const n=e.items?.length||0,a=10,s={query:{...t,action:"aggregate",aggregations:{[e.name]:{skip:n,count:a}}},$auditRecord:{auditEvents:[r]}};I(s);const i=await d("api/v1/query",s),l=await y(i),{aggregations:c}=l,h=c[0];return h.$hasMore=h.items.length>a,h.items=[...e.items,...h.items],Promise.resolve(h)}function Ae(e,t){if(e.authMode?.kind==="credentials")return w.credentials();if(e.bearerToken)return w.bearer(e.bearerToken);const r=e.autoOAuthProvider||t?.autoOAuthProvider;if(r)return w.oauth(r);const n=e.autoSAMLProvider||t?.autoSAMLProvider;return n?w.saml(n):w.unknown()}async function zt(e){const t=e||u.app,r=new URLSearchParams({app:t||""});return S("api/v1/app",r)}async function Ie(){const{app:e}=u,t=new URLSearchParams({app:e||"",preLogin:"true"});return S("api/v1/app",t)}function De(){let{backendUrl:e,app:t}=u;if(typeof window<"u"){if(e||(e=window.location.origin),!t){const r=window.location.pathname.match(/\/app(?:-debug)?\/([^/#]+)/);r&&(t=r[1])}p({backendUrl:e,app:t})}return u.authMode?.kind==="credentials"?(p({authMode:w.credentials(),autoOAuthProvider:void 0,autoSAMLProvider:void 0,bearerToken:void 0}),Promise.resolve({})):Ie().then(r=>{const n=Ae(u,r);return p({authMode:n,autoOAuthProvider:u.autoOAuthProvider||r.autoOAuthProvider,autoSAMLProvider:u.autoSAMLProvider||r.autoSAMLProvider}),r}).catch(r=>{throw f("atomic:fetchAppPreLogin error",r),r})}const Gt=De;async function Ht(e,t,r={}){const n=`api/v1/search.dataset/${e}/${t}`,a=await d(n,{parameters:r}),s=t[0].toLowerCase()+t.slice(1),i=a.datasets[s];if("errorCode"in i&&"errorMessage"in i)throw new Error(i.errorMessage);return i}async function Jt(e,t){const r=`api/v1/search.dataset/${e}`,{parameters:n={},datasets:a=[]}=t;return(await d(r,{parameters:n,datasets:a})).datasets}async function Wt(e){return await S(`api/v1/search.dataset/${e}`)}async function xt(e,t=!0,r){try{return(await d("api/v1/labels",{action:"list",q:e,public:t,locale:r,localize:!1})).labels}catch(n){throw f("Error in fetchLabels",n),n}}async function Xt(){try{const{app:e=""}=u,t=new URLSearchParams({app:e,action:"getUserRights"});return S("api/v1/labels",t)}catch(e){throw f("Error in getUserRights",e),e}}async function Yt(e,t,r=!0){try{const n={action:"add",labels:e,ids:t,public:r,$auditRecord:{auditEvents:[{type:v.Label_AddDoc,detail:{public:r,label:e?e.toString():null,doccount:t?t.length:0}}],mlAuditEvents:[{actionType:"addToLabel",documentIds:t}]}};return d("api/v1/labels",n)}catch(n){throw f("Error in add",n),n}}async function Kt(e,t,r=!0){try{const n={action:"remove",labels:e,ids:t,public:r,$auditRecord:{auditEvents:[{type:v.Label_RemoveDoc,detail:{public:r,label:e?e.toString():null,doccount:t?t.length:0}}],mlAuditEvents:[{actionType:"removeFromLabel",documentIds:t}]}};return d("api/v1/labels",n)}catch(n){throw f("Error in remove",n),n}}async function Zt(e,t,r=!0){try{const n={action:"rename",labels:e,newLabel:t,public:r,auditEvents:{type:v.Label_Rename,detail:{public:r,oldlabel:e?e.toString():null,label:t}}};return d("api/v1/labels",n)}catch(n){throw f("Error in rename",n),n}}async function Et(e,t=!0){try{const r={action:"delete",labels:e,public:t,auditEvents:{type:v.Label_Delete,detail:{public:t,label:e?e.toString():null}}};return d("api/v1/labels",r)}catch(r){throw f("Error in deleteLabels",r),r}}async function Tt(e,t,r=!0){try{const n={action:"bulkAdd",labels:e,query:t,public:r,auditEvents:{type:v.Label_Add,detail:{public:r,label:e?e.toString():null,query:t!==null?t.name:null}}};return d("api/v1/labels",n)}catch(n){throw f("Error in bulkAdd",n),n}}async function er(e,t,r=!0){try{const n={action:"bulkRemove",labels:e,query:t,public:r,auditEvents:{type:v.Label_Delete,detail:{public:r,label:e?e.toString():null,query:t!==null?t.name:null}}};return d("api/v1/labels",n)}catch(n){throw f("Error in bulkRemove",n),n}}const tr={getUserRights:Xt,add:Yt,remove:Kt,rename:Zt,delete:Et,bulkAdd:Tt,bulkRemove:er};async function rr(e,t){if(typeof window>"u")return d("api/v1/preview",{action:"get",id:e,query:t});const r=`${window.location.origin}${window.location.pathname}`,n={name:t?.name,text:t?.text};return d("api/v1/preview",{action:"get",id:e,query:n,browserUrl:r})}async function nr(e){const t=new Headers;t.append("content-type","text");const r=await fetch(e,{method:"GET",headers:t});y(r)}async function Fe(){const e=new URLSearchParams({action:"get",noAutoAuthentication:"true"});return S("api/v1/principal",e)}async function Ne(e){const t={noAutoAuthentication:"true",...e},r=new URLSearchParams;return Object.entries(t).forEach(([n,a])=>{a!==void 0&&r.append(n,String(a))}),S("api/v1/principal/list",r)}async function qe(e){if(!e)return Promise.reject(new Error("userid is required"));const t=new URLSearchParams({action:"userid",noAutoAuthentication:"true",userid:e});return S("api/v1/principal",t)}async function Me(e){if(e.length===0)return Promise.reject(new Error("userids is required"));const t=new URLSearchParams({noAutoAuthentication:"true",userids:[...e].join(",")});return S("api/v1/principal/userids",t)}const ar={principal:{get:Fe,list:Ne,userid:qe,userids:Me}},Be=11;async function or(e,t,r){const a=await d("api/v1/query",{query:e,$auditRecord:t,queryIntentData:r});a.aggregations.forEach(i=>{i.$hasMore=!1,!i.isDistribution&&!i.isTree&&i.items&&(i.$hasMore=i.items.length===Be),i.isTree&&i.items&&G(i)}),a.records?.map(i=>Object.assign(i,{value:i.title,type:"default"}));const s={...a,nextPage:a.page<Math.ceil(a.rowCount/a.pageSize)?a.page+1:void 0,previousPage:a.page>1?a.page-1:void 0};return Promise.resolve(s)}async function sr(e,t,r){const{app:n=""}=u,a={methods:[],mode:t,propagateErrors:!0,$auditRecord:{auditEvents:[r]}};for(const l of e)a.methods.push({method:"query",app:n,query:l});const s=await d("api/v1/multi",a);s.results.forEach(l=>{l.aggregations.forEach(c=>{c.$hasMore=!1,!c.isDistribution&&!c.isTree&&c.items&&(c.$hasMore=c.items.length===Be),c.isTree&&G(c)})}),s.results.forEach(l=>l.records?.map(c=>Object.assign(c,{value:c.title,type:"default"})));const i=s.results.map(l=>({...l,nextPage:l.page<Math.ceil(l.rowCount/l.pageSize)?l.page+1:void 0,previousPage:l.page>1?l.page-1:void 0}));return Promise.resolve(i)}function G(e,t="",r=0){let n=[];return e.items&&e.items.forEach(a=>{let s=t?`${t}/${a.value}`:a.value,i=r+1;n.push({path:s,level:i}),a.$path=s,a.$level=i,a.hasChildren?n=n.concat(G(a,s,i)):a.hasChildren=!1}),n}async function ir({model:e,appName:t,query:r,article:n}){const{webservice:a,format:s,maxcount:i,exportedColumns:l,export:c}=e,h={app:t,webservice:a,query:r,type:c,format:s,maxcount:i,exportedColumns:l,$auditRecord:{auditEvents:[{type:"Search_ExportCSV",detail:{resultid:n?n.id:void 0}}]}};return I(h),await d("api/v1/search.queryexport",h,{responseType:"blob"})}async function cr(e){return(await d("api/v1/queryintent",{query:e}))?.intents}async function lr(e,t,r){return(await d("api/v1/similardocuments",{sourceDocumentId:e,query:{name:t}},{signal:r})).data}async function ur(e,t){return(await d("api/v1/query.links",{webservice:e,query:t}))?.links?.map(a=>({...a,query:t}))}function dr(e,t){if(typeof e=="number")return`${e}`;if(Pe(e))return fr(e);if(typeof e=="boolean")return e?"true":"false";if(e===null)return"null";if(Array.isArray(e)){const r=[];return e.forEach(n=>{r.length>0&&r.push(","),n?typeof n=="string"?r.push(n):r.push(n.display||n.value||""):r.push("null")}),r.splice(0,0,"["),r.push("]"),r.join("")}return e}function fr(e){if(!e)return"";try{if(Re(e)===0)return new Intl.DateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit"}).format(e);{const t=new Intl.DateTimeFormat("en-CA").format(e),r=new Intl.DateTimeFormat("en-CA",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(e);return`${t} ${r}`}}catch{return"Invalid date"}}async function hr(e,t,r,n,a){const{app:s}=u,i={app:s||"",suggestQuery:e,text:t,filter:r,kinds:n,showSource:a};try{return(await d("api/v1/search.suggest",i)).suggests}catch(l){throw console.error("Error fetching suggestions:",l),l}}async function gr(e,t,r,n){const{app:a}=u;return(await d("api/v1/suggestquery",{app:a||"",suggestQuery:e,text:t,query:r,kinds:n})).suggests}async function mr(e,t,r){if(!t)return Promise.resolve([]);const{app:n}=u,s=await d("api/v1/suggestfield",{app:n||"",text:e,fields:t,query:r});return s.suggests.forEach(i=>{i.display=dr(i.display)}),s.suggests}async function wr(e,t,r,n,a,s){return d("api/v1/doc.textchunks",{id:e,textChunks:t,highlights:r,query:n,leftSentencesCount:a,rightSentencesCount:s})}async function _r(){const{app:e}=u,t=new URLSearchParams({app:e||"",action:"load"});return S("api/v1/usersettings",t)}async function Qe(e,t){const r={action:"save",userSettings:e,$auditRecord:{auditEvents:[t]}};return I(r),d("api/v1/usersettings",r)}async function Sr(e,t){const n={action:"patch",userSettings:e,$auditRecord:t?{auditEvents:[t]}:void 0};return I(n),d("api/v1/usersettings",n)}async function kr(){return Qe({},{type:"UserSettings_Reset"})}async function pr(e,t){return d("api/v2/security/password/change",{newPassword:e,currentPassword:t})}async function br(e){const t="api/v2/security/password/ask-reset-email",n={changePasswordRedirectUrl:`${window.location.origin}/login?mode=changepassword`,userName:e};return d(t,n)}async function vr(e){return await S(`api/v2/user-profile/${e}`)}async function Cr(e){return await d("api/v2/user-profile",e)}async function Pr(e,t,r){return await _e(`api/v2/user-profile/${e.data?.id}/${t}/${r}`,e)}async function yr(e,t,r){try{return(await we(`api/v2/user-profile/${e.data?.id}/${t}/${r}`)).success===!0}catch{return!1}}async function Rr(){return await S("api/v2/version")}const R=1e4,L="sinequa-auth-redirect-attempt",je=async()=>{const{autoOAuthProvider:e}=u;if(!e)throw new Error("autoOAuthProvider is not configured in globalConfig");if(typeof window>"u")try{const{signal:r}=b(R);return await d("security.oauth",{action:"getcode",provider:e,tokenInCookie:!0,originalUrl:"http://localhost"},{signal:r})}catch(r){throw f("Failed to authenticate with OAuth",r),r}const t={action:"getcode",provider:e,tokenInCookie:!0,originalUrl:window.location.href};try{const{signal:r}=b(R),n=await d("api/v1/security.oauth",t,{signal:r});if(n.redirectUrl){const a=new URL(n.redirectUrl,window.location.origin);if(a.protocol==="https:"||a.protocol==="http:"){if(x(L))throw D(L),new Error(`OAuth sign-in with provider "${e}" did not establish a session — its callback is likely not authorized for this application.`);X(L,"1"),window.location.href=a.href}}return n}catch(r){throw f("Failed to authenticate with OAuth",r),r}},Ve=async()=>{const{autoSAMLProvider:e}=u;if(!e)throw new Error("autoSAMLProvider is not configured in globalConfig");if(typeof window>"u")try{const{signal:r}=b(R);return await d("security.saml",{action:"getresponse",provider:e,tokenInCookie:!0,originalUrl:"http://localhost"},{signal:r})}catch(r){throw f("Failed to authenticate with SAML",r),r}const t={action:"getresponse",provider:e,tokenInCookie:!0,originalUrl:window.location.href};try{const{signal:r}=b(R),n=await d("api/v1/security.saml",t,{signal:r});if(n.redirectUrl){const a=new URL(n.redirectUrl,window.location.origin);if(a.protocol==="https:"||a.protocol==="http:"){if(x(L))throw D(L),new Error(`SAML sign-in with provider "${e}" did not establish a session — its callback is likely not authorized for this application.`);X(L,"1"),window.location.href=a.href}}return n}catch(r){throw f("Failed to authenticate with SAML",r),r}},M=e=>X("sinequa-credentials",JSON.stringify({data:{csrfToken:e}})),ze=async()=>{try{const{signal:e}=b(R),t=await S("api/v1/challenge?action=getCsrfToken&suppressErrors=true",void 0,{signal:e});if(t?.csrfToken)return M(t.csrfToken),t.csrfToken;throw new Error("No CSRF token returned")}catch(e){throw f("Failed to get CSRF token",e),e}};async function ne(e){if(e){const{username:t,password:r}=e,n={action:"get",tokenInCookie:!0,user:t,password:r,noUserOverride:!0,noAutoAuthentication:!0};try{const{signal:a}=b(R),s=await d("api/v1/security.webtoken",n,{signal:a});return s?.csrfToken?(M(s.csrfToken),s.csrfToken):null}catch(a){throw f("Failed to get JWT",a),a}}else{const t={action:"get",tokenInCookie:!0,noUserOverride:!0,noAutoAuthentication:!1},{bearerToken:r}=u;if(!r)throw new Error("Bearer token is required in globalConfig for credentialless JWT retrieval.");const n=new Headers;n.append("Sinequa-Force-Camel-Case","true"),n.append("accept","application/json"),n.append("Content-Type","application/json"),n.append("Authorization",`Bearer ${r}`);try{const{signal:a}=b(R),s=await d("api/v1/security.webtoken",t,{headers:n,signal:a});return s?.csrfToken?(M(s.csrfToken),s.csrfToken):null}catch(a){throw f("Failed to get JWT without credentials",a),a}}}const H=()=>{const e=x("sinequa-credentials");if(e)try{const n=JSON.parse(e).data?.csrfToken;if(n)return n}catch(r){N("Failed to parse session storage credentials, falling back to local storage",r)}const t=Je("csrfToken");return t||null},Lr=async e=>{if(e){const{username:r,password:n}=e;return!r||!n?(f("Credentials are required for authentication"),g(!1),!1):Ur({username:r,password:n})}const t=u.authMode??w.unknown();if(t.kind==="credentials")return g(!1),!1;if(t.kind==="bearer")return Or();if(H())return p({isRedirectUrl:!1}),D(L),g(!0),!0;try{if(O("Checking for an existing session via CSRF token retrieval"),await ze())return O("User already authenticated (existing session / SSO)"),D(L),t.kind==="unknown"&&p({authMode:w.sso()}),g(!0),!0}catch{}switch(t.kind){case"oauth":return O("Initiating OAuth authentication flow"),await je(),g(!1),!1;case"saml":return O("Initiating SAML authentication flow"),await Ve(),g(!1),!1;case"sso":return g(!1),!1;default:return p({authMode:w.credentials()}),g(!1),!1}};async function Ur(e){O("Attempting authentication using credentials"),p({authMode:w.credentials()});const{userOverrideActive:t,userOverride:r}=u;p({userOverrideActive:!1,userOverride:void 0});try{await ne(e)}catch(n){throw g(!1),n}return p({userOverrideActive:t,userOverride:r}),g(!0),!0}async function Or(){try{if(O("Attempting authentication using bearer token"),await ne())return g(!0),!0}catch(e){throw f("Bearer authentication failed",e),g(!1),e}return g(!1),!1}const Ge=async()=>{const e=new URLSearchParams({action:"deleteWebTokenCookie",noUserOverride:"true",noAutoAuthentication:"true"}),{signal:t}=b(R);return S("api/v1/challenge",e,{signal:t})};async function $r(){const{userOverrideActive:e}=u;if(He(),!e)try{const{methodresult:t,logoutUrl:r}=await Ge();if(t==="ok")return r;f("logout failed")}catch(t){f("logout failed",t)}}function He(){We("csrfToken"),D("sinequa-credentials"),g(!1)}const Ar=()=>!!H();o.API=ar,o.ApiError=P,o.Audit=jt,o.AuditEventType=v,o.AuthMode=w,o.DidYouMeanKind=Se,o.EngineType=m,o.EngineTypeModifier=k,o.LogLevel=Z,o.MINIMUM_COMPATIBLE_SERVER_API_VERSION=yt,o.RFMDisplay=ke,o.ServerError=E,o.TimeoutError=me,o.UnauthorizedError=z,o.addAuditAdditionalInfo=I,o.addConcepts=nt,o.addSessionId=Oe,o.addUrl=$e,o.aggItemRegex=oe,o.aggregationItemStrictCompare=Xe,o.appInitializerFn=Gt,o.bisect=Ke,o.buildPathsAndLevels=G,o.clearSessionTokens=He,o.configureLogger=kt,o.createHeaders=A,o.createTimeoutController=b,o.createUserProfile=Cr,o.debug=$,o.del=we,o.deleteUserProfileProperty=yr,o.deleteUserSettings=kr,o.deleteWebTokenCookie=Ge,o.detectAuthMode=Ae,o.emitAuthenticatedEvent=g,o.error=f,o.escapeExpr=Ft,o.expiresSoon=vt,o.extraColumns=Ot,o.fetchAggregation=Vt,o.fetchApp=zt,o.fetchAppPreLogin=Ie,o.fetchBulkQuery=sr,o.fetchChangePassword=pr,o.fetchDataset=Ht,o.fetchDatasetList=Wt,o.fetchDatasets=Jt,o.fetchLabels=xt,o.fetchPreview=rr,o.fetchPreviewUrl=nr,o.fetchPrincipal=Fe,o.fetchPrincipalList=Ne,o.fetchPrincipalUserid=qe,o.fetchPrincipalUserids=Me,o.fetchQuery=or,o.fetchQueryExport=ir,o.fetchQueryIntent=cr,o.fetchSendPasswordResetEmail=br,o.fetchSimilarDocuments=lr,o.fetchSponsoredLinks=ur,o.fetchSuggest=hr,o.fetchSuggestField=mr,o.fetchSuggestQuery=gr,o.fetchTextChunks=wr,o.fetchUserProfile=vr,o.fetchUserSettings=_r,o.fetchVersion=Rr,o.filter=$t,o.get=S,o.getConcepts=st,o.getCsrfToken=ze,o.getFiltersFromURI=Y,o.getFiltersFromUrl=dt,o.getHelpIndexUrl=_t,o.getIdFromUrl=ht,o.getJWToken=ne,o.getMetadata=At,o.getMetadataWithValues=It,o.getOffsetFromDates=ge,o.getQueryPageFromUrl=gt,o.getQueryParamsFromUrl=lt,o.getQueryTabFromUrl=mt,o.getQueryTextFromUrl=ft,o.getRelativeDate=it,o.getTime=Re,o.getToken=H,o.getUrlParamsFromQueryParams=ut,o.globalConfig=u,o.guid=Le,o.handleResponse=y,o.info=O,o.initializeAppConfig=De,o.isArrayBuffer=ve,o.isAuthenticated=Ar,o.isBlob=Ce,o.isDate=Pe,o.isExpired=bt,o.isJsonable=Dt,o.isNotInputEvent=ct,o.isObject=q,o.isString=ye,o.labels=tr,o.legacyBooleansToAuthMode=ae,o.login=Lr,o.logout=$r,o.makeColumn=_,o.notify=St,o.openParentNodes=ie,o.parseText=F,o.parseValueAndOperatorFromItem=se,o.patch=_e,o.patchUserProfile=Pr,o.patchUserSettings=Sr,o.post=d,o.put=pt,o.queryParamsFromUrl=U,o.removeConcept=at,o.removeConcepts=ot,o.resolveToColumnName=Pt,o.rewriteText=B,o.saveUserSettings=Qe,o.setGlobalConfig=p,o.setToken=M,o.sha512=Nt,o.suggestionsToTreeAggregationNodes=Ye,o.sysLang=wt,o.toDate=ee,o.translateAggregationToDateOptions=xe,o.tryOAuthAuthentication=je,o.trySAMLAuthentication=Ve,o.warn=N,o.withRetry=Ct,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(o,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(o=typeof globalThis<"u"?globalThis:o||self,g(o.atomic={}))})(this,(function(o){"use strict";function g(e){if(typeof CustomEvent>"u"||typeof dispatchEvent>"u")return;const t=new CustomEvent("authenticated",{bubbles:!0,cancelable:!1,detail:{authenticated:e}});dispatchEvent(t)}const w={credentials:()=>({kind:"credentials"}),sso:()=>({kind:"sso"}),oauth:e=>({kind:"oauth",provider:e}),saml:e=>({kind:"saml",provider:e}),bearer:e=>({kind:"bearer",token:e}),unknown:()=>({kind:"unknown"})};function oe(e,t){const{useCredentials:r,useSSO:n,useSAML:a}=e;return a&&t.autoSAMLProvider?w.saml(t.autoSAMLProvider):r&&n?w.unknown():r?w.credentials():n?w.sso():t.authMode??w.unknown()}const u={loginPath:"/login",createRoutes:!1,authMode:w.unknown()};Object.defineProperties(u,{useCredentials:{enumerable:!1,configurable:!0,get(){const e=u.authMode?.kind;return e==="credentials"||e==="unknown"}},useSSO:{enumerable:!1,configurable:!0,get(){const e=u.authMode?.kind;return e==="sso"||e==="unknown"}},useSAML:{enumerable:!1,configurable:!0,get(){return u.authMode?.kind==="saml"}}});function p(e){const{useCredentials:t,useSSO:r,useSAML:n,authMode:a,...s}=e;if(Object.assign(u,s),a!==void 0){u.authMode=a;return}(t!==void 0||r!==void 0||n!==void 0)&&(u.authMode=oe({useCredentials:t,useSSO:r,useSAML:n},u))}const J={store:{},getItem(e){return this.store[e]??null},setItem(e,t){this.store[e]=t.toString()},removeItem(e){delete this.store[e]},clear(){this.store={}}},W=J;function We(e){return typeof window>"u"||!window.localStorage?J.getItem(e):window.localStorage.getItem(e)}function xe(e){typeof window>"u"||!window.localStorage?J.removeItem(e):window.localStorage.removeItem(e)}function x(e){return typeof window>"u"||!window.sessionStorage?W.getItem(e):window.sessionStorage.getItem(e)}function X(e,t){typeof window>"u"||!window.sessionStorage?W.setItem(e,t):window.sessionStorage.setItem(e,t)}function A(e){typeof window>"u"||!window.sessionStorage?W.removeItem(e):window.sessionStorage.removeItem(e)}const se=/.*:\(?([><=\d\-.AND ]+)\)?/;function Xe(e,t){return!e?.items||e?.items?.length===0?[]:e.items.reduce((a,s)=>{if(!s.value||s.value==="")return a;const i=ie(s,e.column);return a.push({operator:i.operator,value:i.value,display:s.display||i.display,filters:i.filters,disabled:s.count===0,hidden:s.count===0&&e.isDistribution?!t:!1}),a},[])}function ie(e,t){const r=t,n=e.value.match(se);if(n?.[1]){const s=(n?.[1].split(" AND ")).map(i=>{const l=i.indexOf(">=")!==-1?"gte":"lt",c=i.substring(i.indexOf(" ")+1);return{field:r,operator:l,value:c,display:e.display||e.value}});if(s.length===2)return{field:r,operator:"and",filters:s,value:e.value,display:s[0].display||s[0].value};if(s.length===1)return{...s[0],field:r};throw new Error("Failed to parse distribution expression")}return{field:r,operator:"eq",value:e.value,display:e.display}}function Ye(e,t,r){return e.valuesAreExpressions?t.display===r.display:t.value===r.value}function ce(e){return e.items&&(e.items=e.items.map(t=>ce(t))),e.items&&e.items.some(t=>t.$selected||t.$opened)&&(e.$opened=!0),e}function Ke(e,t){const r=[];if(e.length>0){const n=new Map,s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").normalize("NFD").replace(/[\u0300-\u036f]/g,""),i=new RegExp("\\b"+s,"i");e.forEach(l=>{if(l.display.length>1){const c=l.display.normalize("NFD").replace(/[\u0300-\u036f]/g,""),h=i.exec(c);le(r,n,"/",l.display,+(l.frequency||0),1,(h?.index||0)+t.length)}})}return r}function le(e,t,r,n,a,s,i){const l=n.indexOf("/",r.length),c=n.substring(0,l+1);let h=t.get(c);if(!h){const R=c.replace(/^\/|\/$/g,"");h={value:n.substring(r.length,l),count:a,items:[],hasChildren:!1,$level:s,$opened:i>=c.length,$path:R},t.set(c,h),e.push(h)}c.length<n.length&&(h.hasChildren=!0,le(h.items,t,c,n,a,s+1,i))}function Ze(e,t){return e.reduce((r,n)=>(t(n)?r.true.push(n):r.false.push(n),r),{true:[],false:[]})}const Ee=/(([\+\-])?\(([^\)]+)\))|(([\+\-])?\[([^\]]+)\])|(([\+\-])?\"([^\"]+)\")|(([\+\-])?\/([^\/]+)\/)|(([\+\-])?(\S+))/g,Te=2,ue=3,et=5,de=6,tt=8,fe=9,rt=11,he=12,nt=14,ge=15;function F(e){if(!e)return[];const t=[],r=e.matchAll(Ee);for(let n of r)n[ue]?t.push({type:"group",value:n[ue],op:n[Te]}):n[de]?t.push({type:"adjacent",value:n[de],op:n[et]}):n[fe]?t.push({type:"exact",value:n[fe],op:n[tt]}):n[he]?t.push({type:"regex",value:n[he],op:n[rt]}):n[ge]&&t.push({type:"token",value:n[ge],op:n[nt]});return t}function B(e){return e.map(t=>{const r=t.op||"";switch(t.type){case"group":return`${r}(${t.value})`;case"adjacent":return`${r}[${t.value}]`;case"exact":return`${r}"${t.value}"`;case"regex":return`${r}/${t.value}/`;case"token":return`${r}${t.value}`}}).join(" ")}function at(e,t,r){let n=F(e);for(let a of t)n.push({type:"adjacent",value:a,op:r});return B(n)}function ot(e,t){const r=F(t),n=r.findIndex(a=>a.value===e);return n!==-1?(r.splice(n,1),t=B(r)):t}function st(e){const t=F(e).filter(r=>r.type!=="adjacent");return B(t)}function it(e){return F(e).filter(t=>t.type==="adjacent").map(t=>t.value)}function ct(e,t,r){const n=new Intl.RelativeTimeFormat(e,{numeric:"auto"}),{offset:a,unit:s,isFuture:i}=me(t,r);return n.format(a*(i?1:-1),s)}function me(e,t){const r=new Date(e),n=t?new Date(t):new Date,a=Math.abs(n.getTime()-r.getTime());return{offset:Math.floor(a/(1e3*60*60*24)),unit:"day",isFuture:r>n}}function lt(e){const t=e.target;return t&&t.nodeName!=="INPUT"&&t.nodeName!=="TEXTAREA"}function ut(e){if(e===void 0)return;const{q:t,f:r,p:n,s:a,t:s,n:i,b:l}=O(e),[c]=e.split("?");return{path:c,text:t,filters:r?Y(r):void 0,page:n?parseInt(n,10):void 0,sort:a,tab:s,name:i,basket:l}}function dt(e){if(!e)return"";const{text:t,filters:r,page:n,sort:a,tab:s,name:i,basket:l}=e,c={};t&&(c.q=t),r&&(c.f=JSON.stringify(r)),n&&(c.p=n.toString()),a&&(c.s=a),s&&(c.t=s),i&&(c.n=i),l&&(c.b=l);const h=new URLSearchParams(c).toString();return h||""}function ft(e){if(e===void 0)return[];const{f:t}=O(e);return Y(t)}function Y(e){const t=decodeURIComponent(e);try{return JSON.parse(t??"[]")}catch{return console.error(`Error parsing filters from URI: ${e}`),[]}}function O(e){const t=e.split("?")[1];if(t===void 0)return{};const r=new URLSearchParams(t);return Object.fromEntries(r)}function ht(e){const{q:t=""}=O(e);return t}function gt(e){const{id:t}=O(e);return decodeURIComponent(t)}function mt(e){const{p:t="0"}=O(e);return parseInt(t,10)}function wt(e){const{t}=O(e);return t}function _t(e,t){if(!e)return e;let r=0;const n=e.length;let a=0;if(e[a]==="["){for(;a<n&&/[0-9]/.test(e[a]);)a++;e[a]==="]"&&(r=a+1)}const s=K(e,r,!1);if(!s)return e;const i=t.charCodeAt(0),l=t.charCodeAt(1);let c=s;for(;c;)if(i===c.lang1&&l===c.lang2){const R=K(e,c.end+4,!0);return e.substring(R.start,R.end)}else c=K(e,c.end+4,!1);const h=e.substring(s.start,s.end);return h||e}function K(e,t,r){for(let n=t,a=e.length-3;n<a;n++)if(e[n]==="["&&e[n+3]==="]")return{start:t,end:n,lang1:e.charCodeAt(n+1),lang2:e.charCodeAt(n+2)};if(r)return{start:t,end:e.length,lang1:-1,lang2:-1}}function St(e,t){const{useLocale:r,useLocaleAsPrefix:n,indexFile:a,path:s,folder:i}=t,l=r?`${e}/`:null,c=n?`${e}.${a}`:a??"";return[s,i,`${l||""}${c}`].filter(h=>h!==void 0).join("/")}function Q(e){const t=new CustomEvent("notification",{bubbles:!0,cancelable:!1,detail:e});dispatchEvent(t)}const kt={success:(e,t)=>{Q({type:"success",message:e,options:t})},info:(e,t)=>{Q({type:"info",message:e,options:t})},warning:(e,t)=>{Q({type:"warning",message:e,options:t})},error:(e,t)=>{Q({type:"error",message:e,options:t})}};var Z=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(Z||{});let j={level:1,enableConsoleOutput:!0};function pt(e){j={...j,...e}}function V(e,t,r){if(e<j.level)return;const a=`${`[${Z[e]}]`} ${t}`;if(j.enableConsoleOutput)switch(e){case 0:console.debug(a,r||"");break;case 1:console.info(a,r||"");break;case 2:console.warn(a,r||"");break;case 3:console.error(a,r||"");break}}function $(e,t){V(0,e,t)}function b(e,t){V(1,e,t)}function N(e,t){V(2,e,t)}function f(e,t){V(3,e,t)}function I(e){const t=H(),r=new Headers(e);r.append("Sinequa-Force-Camel-Case","true"),r.append("accept","application/json"),t&&r.append("Sinequa-csrf-token",t);const{userOverride:n,userOverrideActive:a,bearerToken:s}=u;return s&&r.append("Authorization",`Bearer ${s}`),n&&a&&(r.append("sinequa-override-user",n.username),r.append("sinequa-override-domain",n.domain)),r}class L extends Error{status;constructor(t,r){super(t),this.name="ApiError",this.status=r}}class E extends L{constructor(t="Server error"){super(t,500),this.name="ServerError"}}class we extends L{constructor(t="Request timed out"){super(t,408),this.name="TimeoutError"}}class z extends L{constructor(t="Unauthorized access"){super(t,401),this.name="UnauthorizedError"}}async function U(e,t="json"){const r=e.headers.get("sinequa-jwt-refresh");if(r!==null&&M(r),e.status===200)switch(t){case"arraybuffer":return await e.arrayBuffer();case"blob":return await e.blob();case"text":return await e.text();default:return await e.json()}if(e.status===401){if(u.userOverrideActive){let n={};try{n=await e.clone().json()}catch{}throw N("Unauthorized access attempt with user override",{endpoint:e.url,error:n}),new z(n.errorMessage??n.message??"Unauthorized... User override failed.")}return await T(e,401)}return e.status===500?(f("Server error occurred",{endpoint:e.url}),await T(e,500)):(N(`Unexpected response status: ${e.status}`,{endpoint:e.url}),await T(e,e.status))}async function T(e,t){try{const{done:r,value:n}=await e.body?.getReader().read()||{done:!0,value:void 0};if(r||!n)throw t===401?new z:t===500?new E:new L(`Request failed with status ${t}`,t);const a=JSON.parse(new TextDecoder().decode(n));throw new Error(a.errorMessage||a.message||`Request failed with status ${t}`,{cause:{errorCode:a.errorCode,errorCodeTest:a.errorCodeTest}})}catch(r){throw r instanceof L?r:t===401?new z(r.message):t===500?new E(r.message):new L(r.message??`Request failed with status ${t}`,t)}}async function _e(e,t,r){const n=I(r?.headers),{backendUrl:a}=u,s=t?`?${new URLSearchParams(t)}`:"",i=a?`${a}/${e}${s}`:`${e}${s}`;$(`Making DELETE request to: ${i}`);try{const l=await fetch(i,{method:"DELETE",credentials:"include",headers:n});return U(l,r?.responseType)}catch(l){throw f("Error making DELETE request:",l),l}}async function _(e,t,r){const n=I(r?.headers),{backendUrl:a}=u,s=t?`?${new URLSearchParams(t)}`:"";e.startsWith("plugin")&&(e=`api/v1/${e}`);const i=a?`${a}/${e}${s}`:`${e}${s}`;$(`Making GET request to: ${i}`);try{const l=await fetch(i,{method:"GET",credentials:"include",headers:n,signal:r?.signal,redirect:r?.redirect});return U(l,r?.responseType)}catch(l){throw f("Error making GET request:",l),l}}async function Se(e,t,r){const n=I(r?.headers);n.append("content-type","application/json");const{app:a,backendUrl:s}=u,i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0},l=s?`${s}/${e}`:`${e}`;$(`Making PATCH request to: ${l}`);try{const c=await fetch(l,{method:"PATCH",headers:n,credentials:"include",body:JSON.stringify(i)});return U(c,r?.responseType)}catch(c){throw f("Error making PATCH request:",c),c}}async function d(e,t,r){const n=I(r?.headers),{app:a,backendUrl:s}=u;n.has("Content-Type")||n.set("Content-Type","application/json");const i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0};e.startsWith("plugin")&&(e=`api/v1/${e}`);const l=s?`${s}/${e}`:`${e}`;$(`Making POST request to: ${l}`);try{const c=await fetch(l,{method:"POST",headers:n,credentials:"include",body:JSON.stringify(i),signal:r?.signal});return U(c,r?.responseType)}catch(c){throw f("Error making POST request:",c),c}}async function bt(e,t,r){const n=I(r?.headers),{app:a,backendUrl:s}=u,i={app:a,...t,locale:t.locale||navigator.language,noUserOverride:!0,noAutoAuthentication:!0},l=`${s}/${e}`;$(`Making PUT request to: ${l}`);try{const c=await fetch(l,{method:"PUT",headers:n,credentials:"include",body:JSON.stringify(i)});return U(c,r?.responseType)}catch(c){throw f("Error making PUT request:",c),c}}function v(e){const t=new AbortController,{signal:r}=t;return e&&setTimeout(()=>{r.aborted||t.abort(new we(`Request timed out after ${e}ms`))},e),{controller:t,signal:r}}function ee(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function vt(e){const t=ee(e);return!!t&&t.getTime()<=Date.now()}function Ct(e,t=7){const r=ee(e);if(!r)return!1;const n=Date.now(),a=n+t*24*60*60*1e3,s=r.getTime();return s>n&&s<=a}async function yt(e,t=0,r=1e3){let n;for(let a=0;a<=t;a++)try{return await e()}catch(s){if(n=s,s instanceof L&&s.status>=400&&s.status<500&&s.status!==429||s instanceof DOMException&&s.name==="AbortError")throw s;a<t&&(N(`Retrying request (${a+1}/${t})`,{error:s}),await new Promise(i=>setTimeout(i,r)))}throw n}function Pt(e,t,r){if(!e||!t)return;if(r){const s=Object.keys(t.queries).find(c=>c===r?.toLowerCase());let i;s&&(i=t.queries[s]);const l=(i?.columnsInfo?.columns||[])?.find(c=>c.aliases?.split(",")?.includes(e));if(l)return l.name}const n=t.indexes?._?.columns,a=Object.entries(n).find(s=>s[1].aliases?.includes(e));if(a)return a[0]}var C=(e=>(e.None="None",e.Search_FirstPage="Search_FirstPage",e.Search_Text="Search_Text",e.Search_Refine="Search_Refine",e.Search_Select_Item="Search_Select_Item",e.Search_Select_Custom="Search_Select_Custom",e.Search_Select_Concept="Search_Select_Concept",e.Search_Select_Correction="Search_Select_Correction",e.Search_GotoPage="Search_GotoPage",e.Search_GotoTab="Search_GotoTab",e.Search_DisplayResult="Search_DisplayResult",e.Search_RemoveResult="Search_RemoveResult",e.Search_RemoveAdvanced="Search_RemoveAdvanced",e.Search_SavedQuery="Search_SavedQuery",e.Search_WebService="Search_WebService",e.Search_DidYouMean_Original="Search_DidYouMean_Original",e.Search_DidYouMean_Correction="Search_DidYouMean_Correction",e.Search_ExportCSV="Search_ExportCSV",e.Search_SavedQuery_ExportCSV="Search_SavedQuery_ExportCSV",e.Search_Selection_ExportCSV="Search_Selection_ExportCSV",e.Search_AlertQuery="Search_AlertQuery",e.Search_Select_AnalyticsItem="Search_Select_AnalyticsItem",e.Search_Sort="Search_Sort",e.Search_Exit_Logout="Search_Exit_Logout",e.Search_Timeline_Usage="Search_Timeline_Usage",e.Search_AutoComplete="Search_Autocomplete",e.Search_Login_Success="Login_Success_Form",e.Search_QueryIntent_Detected="Search_QueryIntent_Detected",e.SavedQuery_Add="SavedQuery_Add",e.SavedQuery_Delete="SavedQuery_Delete",e.SavedQuery_DeleteAll="SavedQuery_DeleteAll",e.SavedQuery_Rename="SavedQuery_Rename",e.Alert_Edit="Alert_Edit",e.Alert_Delete="Alert_Delete",e.Alert_DeleteAll="Alert_DeleteAll",e.Link_Display="Link_Display",e.Link_Click="Link_Click",e.Basket_Add="Basket_Add",e.Basket_Delete="Basket_Delete",e.Basket_DeleteAll="Basket_DeleteAll",e.Basket_Rename="Basket_Rename",e.Basket_AddDoc="Basket_AddDoc",e.Basket_RemoveDoc="Basket_RemoveDoc",e.Basket_Open="Basket_Open",e.Basket_ExportCSV="Basket_ExportCSV",e.Label_Add="Label_Add",e.Label_Delete="Label_Delete",e.Label_Rename="Label_Rename",e.Label_Open="Label_Open",e.Label_AddDoc="Label_AddDoc",e.Label_RemoveDoc="Label_RemoveDoc",e.Label_ExportCSV="Label_ExportCSV",e.Label_Menu_ExportCSV="Label_Menu_ExportCSV",e.Rating_Set="Rating_Set",e.Rating_Delete="Rating_Delete",e.Doc_Preview="Doc_Preview",e.Doc_CacheHtml="Doc_CacheHtml",e.Doc_CachePdf="Doc_CachePdf",e.Doc_CacheOriginal="Doc_CacheOriginal",e.Doc_Url1="Doc_Url1",e.Doc_Url2="Doc_Url2",e.Preview_Close="Preview_Close",e.Click_ResultLink="Click_ResultLink",e.Click_ResultLink1="Click_ResultLink1",e.Click_ResultLink2="Click_ResultLink2",e.Click_ResultLink3="Click_ResultLink3",e.Click_ResultLink4="Click_ResultLink4",e.Click_ResultLink5="Click_ResultLink5",e.Click_ResultLink6="Click_ResultLink6",e.Click_ResultLink7="Click_ResultLink7",e.Click_ResultLink8="Click_ResultLink8",e.Click_ResultLink9="Click_ResultLink9",e.Click_ResultLink10="Click_ResultLink10",e.Click_PreviewLink1="Click_PreviewLink1",e.Click_PreviewLink2="Click_PreviewLink2",e.Click_PreviewLink3="Click_PreviewLink3",e.Click_PreviewLink4="Click_PreviewLink4",e.Click_PreviewLink5="Click_PreviewLink5",e.Click_PreviewLink6="Click_PreviewLink6",e.Click_PreviewLink7="Click_PreviewLink7",e.Click_PreviewLink8="Click_PreviewLink8",e.Click_PreviewLink9="Click_PreviewLink9",e.Click_PreviewLink10="Click_PreviewLink10",e.RFM_ClickSet="RFM_ClickSet",e.RFM_ClickReset="RFM_ClickReset",e.RFM_Like="RFM_Like",e.RFM_LikeReset="RFM_LikeReset",e.RFM_Dislike="RFM_Dislike",e.RFM_Important="RFM_Important",e.RFM_ImportantReset="RFM_ImportantReset",e.RFM_Ban="RFM_Ban",e.Navigation_Exit="Navigation_Exit",e.Navigation_Return="Navigation_Return",e.Navigation_Route="Navigation_Route",e.Answer_Display="Answer_Display",e.Answer_Click="Answer_Click",e.Answer_Result="Answer_Result",e.Answer_Liked="Answer_Liked",e.Answer_Disliked="Answer_Disliked",e.Answer_Liked_Cancelled="Answer_Liked_Cancelled",e.Answer_Disliked_Cancelled="Answer_Disliked_Cancelled",e.TopPassages_Display="TopPassages_Display",e.TopPassages_Click="TopPassages_Click",e.UserSettings_Reset="UserSettings_Reset",e.Change_Password_Failed="change.password.failed",e.Change_Password_Success_Form="change.password.success.form",e.Forgot_Password_Request="forgot.password.request",e.Login_Denied="login.denied",e.Login_Success_Form="login.success.form",e.Send_Reset_Password_Link="send.reset.password.link",e.Xrest_ChangePassword="xrest.changepassword",e))(C||{}),m=(e=>(e[e.none=0]="none",e[e.bool=1]="bool",e[e.date=2]="date",e[e.dateTime=3]="dateTime",e[e.time=4]="time",e[e.unsigned=5]="unsigned",e[e.integer=6]="integer",e[e.float=7]="float",e[e.double=8]="double",e[e.dates=9]="dates",e[e.dateTimes=10]="dateTimes",e[e.times=11]="times",e[e.varchar=12]="varchar",e[e.binary=13]="binary",e[e.string=14]="string",e[e.csv=15]="csv",e))(m||{}),k=(e=>(e[e.none=0]="none",e[e.a=2053]="a",e[e.c=4]="c",e[e.d=8]="d",e[e.e=2068]="e",e[e.i=256]="i",e[e.l=2052]="l",e[e.n=8192]="n",e[e.t=524292]="t",e[e.x=8388608]="x",e[e.z=33554432]="z",e[e.f_ordinal=8192]="f_ordinal",e[e.f_multidates=8192]="f_multidates",e[e.f_varchar=33554432]="f_varchar",e[e.f_binary=33562624]="f_binary",e[e.f_string=33562888]="f_string",e[e.f_csv=42477853]="f_csv",e[e.f_overridable=33554696]="f_overridable",e))(k||{});const Rt="1.0";var ke=(e=>(e[e.Original=0]="Original",e[e.Corrected=1]="Corrected",e))(ke||{}),pe=(e=>(e[e.none=0]="none",e[e.positiveRate=1]="positiveRate",e[e.mainlyPosRate=2]="mainlyPosRate",e[e.unrate=4]="unrate",e[e.mainlyNegRate=8]="mainlyNegRate",e[e.negativeRate=16]="negativeRate",e[e.all=31]="all",e[e.positiveOnly=7]="positiveOnly",e[e.negativeOnly=28]="negativeOnly",e[e.personalAll=21]="personalAll",e[e.personalPosOnly=5]="personalPosOnly",e[e.personalNegOnly=20]="personalNegOnly",e))(pe||{});function Lt(e){if(!e)return m.none;switch(e.toLocaleLowerCase()){case"bool":case"boolean":return m.bool;case"date":return m.date;case"datetime":return m.dateTime;case"time":return m.time;case"unsigned":return m.unsigned;case"integer":return m.integer;case"float":return m.float;case"double":return m.double;case"dates":return m.dates;case"datetimes":return m.dateTimes;case"times":return m.times;case"varchar":return m.varchar;case"binary":return m.binary;case"string":return m.string;case"csv":return m.csv;default:return m.none}}function Ut(e){switch(e){case"a":return k.a;case"c":return k.c;case"d":return k.d;case"e":return k.e;case"i":return k.i;case"l":return k.l;case"n":return k.n;case"t":return k.t;case"x":return k.x;case"z":return k.z;default:return k.none}}function Ot(e){let t=k.none;if(e)for(const r of e)t|=Ut(r);return t}function S(e,t,r,n){const a=Lt(t),s=Ot(r||"");return{name:e,type:t,typeModifier:r,eType:a,eTypeModifier:s,aliases:n}}const At={id:S("id","string"),text:S("text","varchar"),documentlanguages:S("documentlanguages","csv","ci",["language"]),databasealias:S("databasealias","varchar"),globalrelevance:S("globalrelevance","double"),matchingpartnames:S("matchingpartnames","csv"),matchlocations:S("matchlocations","csv"),matchlocationsperpartname:S("matchlocationsperpartname","varchar"),extracts:S("extracts","csv"),extractsperpartname:S("extractsperpartname","varchar"),extractslocations:S("extractslocations","csv"),documentweight:S("documentweight","varchar"),groupcount:S("groupcount","integer"),accesslists:S("accesslists","varchar",void 0,["accessLists"])};function be(e){return e.filter(t=>!!t)}const $t={eq:(e,t)=>({field:e,operator:"eq",value:t}),neq:(e,t)=>({field:e,operator:"neq",value:t}),gt:(e,t)=>({field:e,operator:"gt",value:t}),gte:(e,t)=>({field:e,operator:"gte",value:t}),lt:(e,t)=>({field:e,operator:"lt",value:t}),lte:(e,t)=>({field:e,operator:"lte",value:t}),like:(e,t)=>({field:e,operator:"like",value:t}),contains:(e,t)=>({field:e,operator:"contains",value:t}),regex:(e,t)=>({field:e,operator:"regex",value:t}),isNull:e=>({field:e,operator:"null"}),isNotNull:e=>({field:e,operator:"notnull"}),in:(e,t)=>({field:e,operator:"in",values:t}),between:(e,t,r)=>({field:e,operator:"between",start:t,end:r}),and:(...e)=>ve("and",e),or:(...e)=>ve("or",e),not:(...e)=>{const t=be(e);return t.length?{operator:"not",filters:t}:void 0}};function ve(e,t){const r=be(t);return r.length===0?void 0:r.length===1?r[0]:{operator:e,filters:r}}function It(e,t){let r=e[t];return r===void 0?[]:(typeof r=="string"&&(r=String(r).split(",")),Array.isArray(r)?r.map(n=>{if(typeof n=="string")return n.trim();if(typeof n=="object"&&n!==null&&"display"in n)return n.display.trim()}).filter(n=>n!==void 0):[String(r).trim()])}function Dt(e,t){let r=e[t];if(r===void 0)return[];if(typeof r=="string"&&(r=String(r).split(",")),Array.isArray(r))return r.map(a=>{if(typeof a=="string")return{display:a.trim(),value:a.trim()};if(typeof a=="object"&&a!==null&&"display"in a){const s=a.display.trim(),i="value"in a?String(a.value).trim():s;return{display:s,value:i}}}).filter(a=>a!==void 0);const n=String(r).trim();return[{display:n,value:n}]}function q(e){return e!==null&&typeof e=="object"}function Ce(e){return q(e)&&Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function ye(e){return q(e)&&Object.prototype.toString.call(e)==="[object Blob]"}function Pe(e){return Object.prototype.toString.call(e)==="[object Date]"}function Re(e){return typeof e=="string"}function Ft(e){return(q(e)||Array.isArray(e))&&!Ce(e)&&!ye(e)&&!Re(e)}function Le(e){return e?(e.getHours()*60*60+e.getMinutes()*60+e.getSeconds())*1e3+e.getMilliseconds():0}function Ue(e=!0){let t=Date.now();return(e?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx":"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx").replace(/[xy]/g,n=>{const a=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n==="x"?a:a&3|8).toString(16)})}function Nt(e){if(!e)return"``";if(e=String(e),e.search(/[\\`]/)===-1)return`\`${e}\``;const t=["`"];for(let r=0,n=e.length;r<n;r++){const a=e[r];(a==="\\"||a==="`")&&t.push("\\"),t.push(a)}return t.push("`"),t.join("")}function qt(e){if(typeof crypto<"u"&&crypto.subtle&&typeof crypto.subtle.digest=="function")try{return crypto.subtle.digest("SHA-512",new TextEncoder().encode(e)).then(t=>Array.prototype.map.call(new Uint8Array(t),r=>`00${r.toString(16)}`.slice(-2)).join("")).catch(()=>Promise.resolve(te(e)))}catch{return Promise.resolve(te(e))}return Promise.resolve(te(e))}function te(e){let n=2166136261;for(let R=0;R<e.length;R++)n^=e.charCodeAt(R),n=n*16777619>>>0;const a=n.toString(16).padStart(8,"0"),s=((n^2863311530)>>>0).toString(16).padStart(8,"0"),i=((n^1431655765)>>>0).toString(16).padStart(8,"0"),l=((n^3435973836)>>>0).toString(16).padStart(8,"0"),c=a+s+i+l;return(c+c+c+c).substring(0,128)}let re,Oe;function D(e,t=!0){let r=Mt(e.$auditRecord);r&&(Ae(r),t&&$e(r)),e.$auditRecord=r}function Mt(e){if(!e)return;let t;if(Array.isArray(e))t=e;else if(q(e)){const r=e;if(r.auditEvents||r.mlAuditEvents)return r;t=[e]}return{auditEvents:t}}function Ae(e){const t=Bt();return e.auditEvents?.forEach(r=>{r.detail||(r.detail={}),r.detail.sessionid=t}),e}function $e(e){const t=typeof window<"u"?decodeURIComponent(window.location.href):"http://localhost";return e?.auditEvents?.forEach(r=>{r.detail||(r.detail={}),r.detail.url=t}),e}function Bt(){return(!re||Qt())&&(re=Ue()),Oe=new Date,re}function Qt(){return new Date().getTime()-Oe.getTime()>600*1e3}async function jt(e,t=!0){const r={event:C.None,$auditRecord:e};return D(r,t),d("api/v1/audit.notify",r)}const Vt={notify:jt};async function zt(e,t,r){const n=e.items?.length||0,a=10,s={query:{...t,action:"aggregate",aggregations:{[e.name]:{skip:n,count:a}}},$auditRecord:{auditEvents:[r]}};D(s);const i=await d("api/v1/query",s),l=await U(i),{aggregations:c}=l,h=c[0];return h.$hasMore=h.items.length>a,h.items=[...e.items,...h.items],Promise.resolve(h)}function Ie(e,t){if(e.authMode?.kind==="credentials")return w.credentials();if(e.bearerToken)return w.bearer(e.bearerToken);const r=e.autoOAuthProvider||t?.autoOAuthProvider;if(r)return w.oauth(r);const n=e.autoSAMLProvider||t?.autoSAMLProvider;return n?w.saml(n):w.unknown()}async function Gt(e){const t=e||u.app,r=new URLSearchParams({app:t||""});return _("api/v1/app",r)}async function De(){const{app:e}=u,t=new URLSearchParams({app:e||"",preLogin:"true"});return _("api/v1/app",t)}function Fe(){let{backendUrl:e,app:t}=u;if(typeof window<"u"){if(e||(e=window.location.origin),!t){const r=window.location.pathname.match(/\/app(?:-debug)?\/([^/#]+)/);r&&(t=r[1])}p({backendUrl:e,app:t})}return u.authMode?.kind==="credentials"?(p({authMode:w.credentials(),autoOAuthProvider:void 0,autoSAMLProvider:void 0,bearerToken:void 0}),Promise.resolve({})):De().then(r=>{const n=Ie(u,r);return p({authMode:n,autoOAuthProvider:u.autoOAuthProvider||r.autoOAuthProvider,autoSAMLProvider:u.autoSAMLProvider||r.autoSAMLProvider}),r}).catch(r=>{throw f("atomic:fetchAppPreLogin error",r),r})}const Ht=Fe;async function Jt(e,t,r={}){const n=`api/v1/search.dataset/${e}/${t}`,a=await d(n,{parameters:r}),s=t[0].toLowerCase()+t.slice(1),i=a.datasets[s];if("errorCode"in i&&"errorMessage"in i)throw new Error(i.errorMessage);return i}async function Wt(e,t){const r=`api/v1/search.dataset/${e}`,{parameters:n={},datasets:a=[]}=t;return(await d(r,{parameters:n,datasets:a})).datasets}async function xt(e){return await _(`api/v1/search.dataset/${e}`)}async function Xt(e,t=!0,r){try{return(await d("api/v1/labels",{action:"list",q:e,public:t,locale:r,localize:!1})).labels}catch(n){throw f("Error in fetchLabels",n),n}}async function Yt(){try{const{app:e=""}=u,t=new URLSearchParams({app:e,action:"getUserRights"});return _("api/v1/labels",t)}catch(e){throw f("Error in getUserRights",e),e}}async function Kt(e,t,r=!0){try{const n={action:"add",labels:e,ids:t,public:r,$auditRecord:{auditEvents:[{type:C.Label_AddDoc,detail:{public:r,label:e?e.toString():null,doccount:t?t.length:0}}],mlAuditEvents:[{actionType:"addToLabel",documentIds:t}]}};return d("api/v1/labels",n)}catch(n){throw f("Error in add",n),n}}async function Zt(e,t,r=!0){try{const n={action:"remove",labels:e,ids:t,public:r,$auditRecord:{auditEvents:[{type:C.Label_RemoveDoc,detail:{public:r,label:e?e.toString():null,doccount:t?t.length:0}}],mlAuditEvents:[{actionType:"removeFromLabel",documentIds:t}]}};return d("api/v1/labels",n)}catch(n){throw f("Error in remove",n),n}}async function Et(e,t,r=!0){try{const n={action:"rename",labels:e,newLabel:t,public:r,auditEvents:{type:C.Label_Rename,detail:{public:r,oldlabel:e?e.toString():null,label:t}}};return d("api/v1/labels",n)}catch(n){throw f("Error in rename",n),n}}async function Tt(e,t=!0){try{const r={action:"delete",labels:e,public:t,auditEvents:{type:C.Label_Delete,detail:{public:t,label:e?e.toString():null}}};return d("api/v1/labels",r)}catch(r){throw f("Error in deleteLabels",r),r}}async function er(e,t,r=!0){try{const n={action:"bulkAdd",labels:e,query:t,public:r,auditEvents:{type:C.Label_Add,detail:{public:r,label:e?e.toString():null,query:t!==null?t.name:null}}};return d("api/v1/labels",n)}catch(n){throw f("Error in bulkAdd",n),n}}async function tr(e,t,r=!0){try{const n={action:"bulkRemove",labels:e,query:t,public:r,auditEvents:{type:C.Label_Delete,detail:{public:r,label:e?e.toString():null,query:t!==null?t.name:null}}};return d("api/v1/labels",n)}catch(n){throw f("Error in bulkRemove",n),n}}const rr={getUserRights:Yt,add:Kt,remove:Zt,rename:Et,delete:Tt,bulkAdd:er,bulkRemove:tr};async function nr(e,t){if(typeof window>"u")return d("api/v1/preview",{action:"get",id:e,query:t});const r=`${window.location.origin}${window.location.pathname}`,n={name:t?.name,text:t?.text};return d("api/v1/preview",{action:"get",id:e,query:n,browserUrl:r})}async function ar(e){const t=new Headers;t.append("content-type","text");const r=await fetch(e,{method:"GET",headers:t});U(r)}async function Ne(){const e=new URLSearchParams({action:"get",noAutoAuthentication:"true"});return _("api/v1/principal",e)}async function qe(e){const t={noAutoAuthentication:"true",...e},r=new URLSearchParams;return Object.entries(t).forEach(([n,a])=>{a!==void 0&&r.append(n,String(a))}),_("api/v1/principal/list",r)}async function Me(e){if(!e)return Promise.reject(new Error("userid is required"));const t=new URLSearchParams({action:"userid",noAutoAuthentication:"true",userid:e});return _("api/v1/principal",t)}async function Be(e){if(e.length===0)return Promise.reject(new Error("userids is required"));const t=new URLSearchParams({noAutoAuthentication:"true",userids:[...e].join(",")});return _("api/v1/principal/userids",t)}const or={principal:{get:Ne,list:qe,userid:Me,userids:Be}},Qe=11;async function sr(e,t,r){const a=await d("api/v1/query",{query:e,$auditRecord:t,queryIntentData:r});a.aggregations.forEach(i=>{i.$hasMore=!1,!i.isDistribution&&!i.isTree&&i.items&&(i.$hasMore=i.items.length===Qe),i.isTree&&i.items&&G(i)}),a.records?.map(i=>Object.assign(i,{value:i.title,type:"default"}));const s={...a,nextPage:a.page<Math.ceil(a.rowCount/a.pageSize)?a.page+1:void 0,previousPage:a.page>1?a.page-1:void 0};return Promise.resolve(s)}async function ir(e,t,r){const{app:n=""}=u,a={methods:[],mode:t,propagateErrors:!0,$auditRecord:{auditEvents:[r]}};for(const l of e)a.methods.push({method:"query",app:n,query:l});const s=await d("api/v1/multi",a);s.results.forEach(l=>{l.aggregations.forEach(c=>{c.$hasMore=!1,!c.isDistribution&&!c.isTree&&c.items&&(c.$hasMore=c.items.length===Qe),c.isTree&&G(c)})}),s.results.forEach(l=>l.records?.map(c=>Object.assign(c,{value:c.title,type:"default"})));const i=s.results.map(l=>({...l,nextPage:l.page<Math.ceil(l.rowCount/l.pageSize)?l.page+1:void 0,previousPage:l.page>1?l.page-1:void 0}));return Promise.resolve(i)}function G(e,t="",r=0){let n=[];return e.items&&e.items.forEach(a=>{let s=t?`${t}/${a.value}`:a.value,i=r+1;n.push({path:s,level:i}),a.$path=s,a.$level=i,a.hasChildren?n=n.concat(G(a,s,i)):a.hasChildren=!1}),n}async function cr({model:e,appName:t,query:r,article:n}){const{webservice:a,format:s,maxcount:i,exportedColumns:l,export:c}=e,h={app:t,webservice:a,query:r,type:c,format:s,maxcount:i,exportedColumns:l,$auditRecord:{auditEvents:[{type:"Search_ExportCSV",detail:{resultid:n?n.id:void 0}}]}};return D(h),await d("api/v1/search.queryexport",h,{responseType:"blob"})}async function lr(e){return(await d("api/v1/queryintent",{query:e}))?.intents}async function ur(e,t,r){return(await d("api/v1/similardocuments",{sourceDocumentId:e,query:{name:t}},{signal:r})).data}async function dr(e,t){return(await d("api/v1/query.links",{webservice:e,query:t}))?.links?.map(a=>({...a,query:t}))}function fr(e,t){if(typeof e=="number")return`${e}`;if(Pe(e))return hr(e);if(typeof e=="boolean")return e?"true":"false";if(e===null)return"null";if(Array.isArray(e)){const r=[];return e.forEach(n=>{r.length>0&&r.push(","),n?typeof n=="string"?r.push(n):r.push(n.display||n.value||""):r.push("null")}),r.splice(0,0,"["),r.push("]"),r.join("")}return e}function hr(e){if(!e)return"";try{if(Le(e)===0)return new Intl.DateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit"}).format(e);{const t=new Intl.DateTimeFormat("en-CA").format(e),r=new Intl.DateTimeFormat("en-CA",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(e);return`${t} ${r}`}}catch{return"Invalid date"}}async function gr(e,t,r,n,a){const{app:s}=u,i={app:s||"",suggestQuery:e,text:t,filter:r,kinds:n,showSource:a};try{return(await d("api/v1/search.suggest",i)).suggests}catch(l){throw console.error("Error fetching suggestions:",l),l}}async function mr(e,t,r,n){const{app:a}=u;return(await d("api/v1/suggestquery",{app:a||"",suggestQuery:e,text:t,query:r,kinds:n})).suggests}async function wr(e,t,r){if(!t)return Promise.resolve([]);const{app:n}=u,s=await d("api/v1/suggestfield",{app:n||"",text:e,fields:t,query:r});return s.suggests.forEach(i=>{i.display=fr(i.display)}),s.suggests}async function _r(e,t,r,n,a,s){return d("api/v1/doc.textchunks",{id:e,textChunks:t,highlights:r,query:n,leftSentencesCount:a,rightSentencesCount:s})}async function Sr(){const{app:e}=u,t=new URLSearchParams({app:e||"",action:"load"});return _("api/v1/usersettings",t)}async function je(e,t){const r={action:"save",userSettings:e,$auditRecord:{auditEvents:[t]}};return D(r),d("api/v1/usersettings",r)}async function kr(e,t){const n={action:"patch",userSettings:e,$auditRecord:t?{auditEvents:[t]}:void 0};return D(n),d("api/v1/usersettings",n)}async function pr(){return je({},{type:"UserSettings_Reset"})}async function br(e,t){return d("api/v2/security/password/change",{newPassword:e,currentPassword:t})}async function vr(e){const t="api/v2/security/password/ask-reset-email",n={changePasswordRedirectUrl:`${window.location.origin}/login?mode=changepassword`,userName:e};return d(t,n)}async function Cr(e){return await _(`api/v2/user-profile/${e}`)}async function yr(e){return await d("api/v2/user-profile",e)}async function Pr(e,t,r){return await Se(`api/v2/user-profile/${e.data?.id}/${t}/${r}`,e)}async function Rr(e,t,r){try{return(await _e(`api/v2/user-profile/${e.data?.id}/${t}/${r}`)).success===!0}catch{return!1}}async function Lr(){return await _("api/v2/version")}const y=1e4,P="sinequa-auth-redirect-attempt",Ve=async()=>{const{autoOAuthProvider:e}=u;if(!e)throw new Error("autoOAuthProvider is not configured in globalConfig");if(typeof window>"u")try{const{signal:r}=v(y);return await d("security.oauth",{action:"getcode",provider:e,tokenInCookie:!0,originalUrl:"http://localhost"},{signal:r})}catch(r){throw f("Failed to authenticate with OAuth",r),r}const t={action:"getcode",provider:e,tokenInCookie:!0,originalUrl:window.location.href};try{const{signal:r}=v(y),n=await d("api/v1/security.oauth",t,{signal:r});if(n.redirectUrl){const a=new URL(n.redirectUrl,window.location.origin);if(a.protocol==="https:"||a.protocol==="http:"){if(x(P))throw A(P),new Error(`OAuth sign-in with provider "${e}" did not establish a session — its callback is likely not authorized for this application.`);X(P,"1"),window.location.href=a.href}}return n}catch(r){throw f("Failed to authenticate with OAuth",r),r}},ze=async()=>{const{autoSAMLProvider:e}=u;if(!e)throw new Error("autoSAMLProvider is not configured in globalConfig");if(typeof window>"u")try{const{signal:r}=v(y);return await d("security.saml",{action:"getresponse",provider:e,tokenInCookie:!0,originalUrl:"http://localhost"},{signal:r})}catch(r){throw f("Failed to authenticate with SAML",r),r}const t={action:"getresponse",provider:e,tokenInCookie:!0,originalUrl:window.location.href};try{const{signal:r}=v(y),n=await d("api/v1/security.saml",t,{signal:r});if(n.redirectUrl){const a=new URL(n.redirectUrl,window.location.origin);if(a.protocol==="https:"||a.protocol==="http:"){if(x(P))throw A(P),new Error(`SAML sign-in with provider "${e}" did not establish a session — its callback is likely not authorized for this application.`);X(P,"1"),window.location.href=a.href}}return n}catch(r){throw f("Failed to authenticate with SAML",r),r}},M=e=>X("sinequa-credentials",JSON.stringify({data:{csrfToken:e}})),ne=async()=>{try{const{signal:e}=v(y),t=await _("api/v1/challenge?action=getCsrfToken&suppressErrors=true",void 0,{signal:e});if(t?.csrfToken)return M(t.csrfToken),t.csrfToken;throw new Error("No CSRF token returned")}catch(e){throw f("Failed to get CSRF token",e),e}};async function ae(e){if(e){const{username:t,password:r}=e,n={action:"get",tokenInCookie:!0,user:t,password:r,noUserOverride:!0,noAutoAuthentication:!0};try{const{signal:a}=v(y),s=await d("api/v1/security.webtoken",n,{signal:a});return s?.csrfToken?(M(s.csrfToken),s.csrfToken):null}catch(a){throw f("Failed to get JWT",a),a}}else{const t={action:"get",tokenInCookie:!0,noUserOverride:!0,noAutoAuthentication:!1},{bearerToken:r}=u;if(!r)throw new Error("Bearer token is required in globalConfig for credentialless JWT retrieval.");const n=new Headers;n.append("Sinequa-Force-Camel-Case","true"),n.append("accept","application/json"),n.append("Content-Type","application/json"),n.append("Authorization",`Bearer ${r}`);try{const{signal:a}=v(y),s=await d("api/v1/security.webtoken",t,{headers:n,signal:a});return s?.csrfToken?(M(s.csrfToken),s.csrfToken):null}catch(a){throw f("Failed to get JWT without credentials",a),a}}}const H=()=>{const e=x("sinequa-credentials");if(e)try{const n=JSON.parse(e).data?.csrfToken;if(n)return n}catch(r){N("Failed to parse session storage credentials, falling back to local storage",r)}const t=We("csrfToken");return t||null},Ge=async()=>{try{const{signal:e}=v(y);return await _("api/v1/principal",new URLSearchParams({action:"get"}),{signal:e,redirect:"manual"}),b("Server auto-authenticated the user (OIDC)"),!0}catch{return!1}},Ur=async e=>{if(e){const{username:r,password:n}=e;return!r||!n?(f("Credentials are required for authentication"),g(!1),!1):Or({username:r,password:n})}const t=u.authMode??w.unknown();if(t.kind==="credentials")return g(!1),!1;if(t.kind==="bearer")return Ar();if(H())return p({isRedirectUrl:!1}),A(P),g(!0),!0;try{if(b("Checking for an existing session via CSRF token retrieval"),await ne())return b("User already authenticated (existing session / SSO)"),A(P),t.kind==="unknown"&&p({authMode:w.sso()}),g(!0),!0}catch{}switch(t.kind){case"oauth":return b("Initiating OAuth authentication flow"),await Ve(),g(!1),!1;case"saml":return b("Initiating SAML authentication flow"),await ze(),g(!1),!1;case"sso":return g(!1),!1;default:{if(b("No provider declared — probing for server-side auto-authentication (OIDC)"),await Ge())try{if(await ne())return b("User auto-authenticated by the server (OIDC)"),A(P),p({authMode:w.sso()}),g(!0),!0}catch{}return p({authMode:w.credentials()}),g(!1),!1}}};async function Or(e){b("Attempting authentication using credentials"),p({authMode:w.credentials()});const{userOverrideActive:t,userOverride:r}=u;p({userOverrideActive:!1,userOverride:void 0});try{await ae(e)}catch(n){throw g(!1),n}return p({userOverrideActive:t,userOverride:r}),g(!0),!0}async function Ar(){try{if(b("Attempting authentication using bearer token"),await ae())return g(!0),!0}catch(e){throw f("Bearer authentication failed",e),g(!1),e}return g(!1),!1}const He=async()=>{const e=new URLSearchParams({action:"deleteWebTokenCookie",noUserOverride:"true",noAutoAuthentication:"true"}),{signal:t}=v(y);return _("api/v1/challenge",e,{signal:t})};async function $r(){const{userOverrideActive:e}=u;if(Je(),!e)try{const{methodresult:t,logoutUrl:r}=await He();if(t==="ok")return r;f("logout failed")}catch(t){f("logout failed",t)}}function Je(){xe("csrfToken"),A("sinequa-credentials"),g(!1)}const Ir=()=>!!H();o.API=or,o.ApiError=L,o.Audit=Vt,o.AuditEventType=C,o.AuthMode=w,o.DidYouMeanKind=ke,o.EngineType=m,o.EngineTypeModifier=k,o.LogLevel=Z,o.MINIMUM_COMPATIBLE_SERVER_API_VERSION=Rt,o.RFMDisplay=pe,o.ServerError=E,o.TimeoutError=we,o.UnauthorizedError=z,o.addAuditAdditionalInfo=D,o.addConcepts=at,o.addSessionId=Ae,o.addUrl=$e,o.aggItemRegex=se,o.aggregationItemStrictCompare=Ye,o.appInitializerFn=Ht,o.bisect=Ze,o.buildPathsAndLevels=G,o.clearSessionTokens=Je,o.configureLogger=pt,o.createHeaders=I,o.createTimeoutController=v,o.createUserProfile=yr,o.debug=$,o.del=_e,o.deleteUserProfileProperty=Rr,o.deleteUserSettings=pr,o.deleteWebTokenCookie=He,o.detectAuthMode=Ie,o.emitAuthenticatedEvent=g,o.error=f,o.escapeExpr=Nt,o.expiresSoon=Ct,o.extraColumns=At,o.fetchAggregation=zt,o.fetchApp=Gt,o.fetchAppPreLogin=De,o.fetchBulkQuery=ir,o.fetchChangePassword=br,o.fetchDataset=Jt,o.fetchDatasetList=xt,o.fetchDatasets=Wt,o.fetchLabels=Xt,o.fetchPreview=nr,o.fetchPreviewUrl=ar,o.fetchPrincipal=Ne,o.fetchPrincipalList=qe,o.fetchPrincipalUserid=Me,o.fetchPrincipalUserids=Be,o.fetchQuery=sr,o.fetchQueryExport=cr,o.fetchQueryIntent=lr,o.fetchSendPasswordResetEmail=vr,o.fetchSimilarDocuments=ur,o.fetchSponsoredLinks=dr,o.fetchSuggest=gr,o.fetchSuggestField=wr,o.fetchSuggestQuery=mr,o.fetchTextChunks=_r,o.fetchUserProfile=Cr,o.fetchUserSettings=Sr,o.fetchVersion=Lr,o.filter=$t,o.get=_,o.getConcepts=it,o.getCsrfToken=ne,o.getFiltersFromURI=Y,o.getFiltersFromUrl=ft,o.getHelpIndexUrl=St,o.getIdFromUrl=gt,o.getJWToken=ae,o.getMetadata=It,o.getMetadataWithValues=Dt,o.getOffsetFromDates=me,o.getQueryPageFromUrl=mt,o.getQueryParamsFromUrl=ut,o.getQueryTabFromUrl=wt,o.getQueryTextFromUrl=ht,o.getRelativeDate=ct,o.getTime=Le,o.getToken=H,o.getUrlParamsFromQueryParams=dt,o.globalConfig=u,o.guid=Ue,o.handleResponse=U,o.info=b,o.initializeAppConfig=Fe,o.isArrayBuffer=Ce,o.isAuthenticated=Ir,o.isBlob=ye,o.isDate=Pe,o.isExpired=vt,o.isJsonable=Ft,o.isNotInputEvent=lt,o.isObject=q,o.isString=Re,o.labels=rr,o.legacyBooleansToAuthMode=oe,o.login=Ur,o.logout=$r,o.makeColumn=S,o.notify=kt,o.openParentNodes=ce,o.parseText=F,o.parseValueAndOperatorFromItem=ie,o.patch=Se,o.patchUserProfile=Pr,o.patchUserSettings=kr,o.post=d,o.put=bt,o.queryParamsFromUrl=O,o.removeConcept=ot,o.removeConcepts=st,o.resolveToColumnName=Pt,o.rewriteText=B,o.saveUserSettings=je,o.setGlobalConfig=p,o.setToken=M,o.sha512=qt,o.suggestionsToTreeAggregationNodes=Ke,o.sysLang=_t,o.toDate=ee,o.translateAggregationToDateOptions=Xe,o.tryAutoAuthentication=Ge,o.tryOAuthAuthentication=Ve,o.trySAMLAuthentication=ze,o.warn=N,o.withRetry=yt,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
@@ -1,5 +1,5 @@
1
1
  export { emitAuthenticatedEvent } from "./events";
2
2
  export { tryOAuthAuthentication, trySAMLAuthentication } from "./providers";
3
- export { clearSessionTokens, detectAuthMode, isAuthenticated, login, logout, } from "./session";
3
+ export { clearSessionTokens, detectAuthMode, isAuthenticated, login, logout, tryAutoAuthentication, } from "./session";
4
4
  export { deleteWebTokenCookie, getCsrfToken, getJWToken, getToken, setToken, } from "./tokens";
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAGlD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAE5E,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,KAAK,EACL,MAAM,GACP,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,QAAQ,GACT,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAGlD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAE5E,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,KAAK,EACL,MAAM,EACN,qBAAqB,GACtB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,QAAQ,GACT,MAAM,UAAU,CAAC"}
@@ -1,5 +1,6 @@
1
1
  export { detectAuthMode } from "./detect-auth-mode";
2
2
  export { login } from "./login";
3
3
  export { clearSessionTokens, logout } from "./logout";
4
+ export { tryAutoAuthentication } from "./try-auto-authentication";
4
5
  export { isAuthenticated } from "./user-authentication";
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/authentication/session/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/authentication/session/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../../src/authentication/session/login.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAU/C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,KAAK,GAAU,cAAc,WAAW,KAAG,OAAO,CAAC,OAAO,CA4EtE,CAAC"}
1
+ {"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../../src/authentication/session/login.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAW/C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,KAAK,GAAU,cAAc,WAAW,KAAG,OAAO,CAAC,OAAO,CAuGtE,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Probes the server for **auto-authentication** (e.g. OIDC) before falling back to the credentials
3
+ * form.
4
+ *
5
+ * Unlike {@link getCsrfToken} — which calls the challenge endpoint with `suppressErrors=true` and
6
+ * therefore never triggers the server-side auth challenge — and unlike {@link fetchPrincipal} — which
7
+ * sends `noAutoAuthentication=true` to explicitly disable it — this probe hits a protected endpoint
8
+ * **allowing the server to auto-authenticate**. When the user already has a valid IdP session, the
9
+ * server completes the handshake and answers `200`; otherwise it answers `401` (or redirects to the
10
+ * IdP, which we do not follow — see `redirect: "manual"` below).
11
+ *
12
+ * A successful `200` also carries the `sinequa-jwt-refresh` header, which `handleResponse` feeds into
13
+ * `setToken`, so the session becomes usable immediately.
14
+ *
15
+ * @returns `true` when the server auto-authenticated the user (`200`), `false` otherwise (401,
16
+ * redirect, timeout or any network error). Never throws.
17
+ */
18
+ export declare const tryAutoAuthentication: () => Promise<boolean>;
19
+ //# sourceMappingURL=try-auto-authentication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"try-auto-authentication.d.ts","sourceRoot":"","sources":["../../../src/authentication/session/try-auto-authentication.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,qBAAqB,QAAa,OAAO,CAAC,OAAO,CAgB7D,CAAC"}
@@ -7,11 +7,15 @@ import type { API_ENDPOINTS } from "../../../types";
7
7
  * @param options - Additional options for the request.
8
8
  * @param options.headers - Custom headers to include in the request.
9
9
  * @param options.responseType - The expected type of response data.
10
+ * @param options.redirect - How to handle a redirect response (defaults to the browser's `follow`).
11
+ * Pass `"manual"` to avoid following a cross-origin redirect (e.g. an auth challenge to an IdP),
12
+ * which would otherwise surface as a CORS network error.
10
13
  * @returns A Promise that resolves to the response data of type T.
11
14
  */
12
15
  export declare function get<T>(endpoint: API_ENDPOINTS, params?: URLSearchParams, options?: {
13
16
  headers?: Headers;
14
17
  responseType?: "arraybuffer" | "blob" | "json" | "text";
15
18
  signal?: AbortSignal;
19
+ redirect?: RequestRedirect;
16
20
  }): Promise<T>;
17
21
  //# sourceMappingURL=get.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"get.d.ts","sourceRoot":"","sources":["../../../../src/web-api/helpers/methods/get.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAKpD;;;;;;;;;GASG;AACH,wBAAsB,GAAG,CAAC,CAAC,EACzB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,YAAY,CAAC,EAAE,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACxD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GACA,OAAO,CAAC,CAAC,CAAC,CA8BZ"}
1
+ {"version":3,"file":"get.d.ts","sourceRoot":"","sources":["../../../../src/web-api/helpers/methods/get.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAKpD;;;;;;;;;;;;GAYG;AACH,wBAAsB,GAAG,CAAC,CAAC,EACzB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,eAAe,EACxB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,YAAY,CAAC,EAAE,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACxD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,CAAC,EAAE,eAAe,CAAC;CAC5B,GACA,OAAO,CAAC,CAAC,CAAC,CA+BZ"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sinequa/atomic",
3
3
  "private": false,
4
- "version": "2.0.1",
4
+ "version": "2.0.2",
5
5
  "type": "module",
6
6
  "main": "./dist/atomic.umd.cjs",
7
7
  "module": "./dist/atomic.js",