searchkit
Version:
Search UI for Elasticsearch.
10 lines (9 loc) • 21.8 kB
JavaScript
;var SearchkitDefault=(()=>{var ee=Object.create;var x=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var ie=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ae=(t,e)=>{for(var r in e)x(t,r,{get:e[r],enumerable:!0})},j=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of re(e))!se.call(t,s)&&s!==r&&x(t,s,{get:()=>e[s],enumerable:!(n=te(e,s))||n.enumerable});return t};var oe=(t,e,r)=>(r=t!=null?ee(ne(t)):{},j(e||!t||!t.__esModule?x(r,"default",{value:t,enumerable:!0}):r,t)),ue=t=>j(x({},"__esModule",{value:!0}),t);var O=ie((Ve,B)=>{"use strict";var ce=function(e){return le(e)&&!ge(e)};function le(t){return!!t&&typeof t=="object"}function ge(t){var e=Object.prototype.toString.call(t);return e==="[object RegExp]"||e==="[object Date]"||he(t)}var fe=typeof Symbol=="function"&&Symbol.for,de=fe?Symbol.for("react.element"):60103;function he(t){return t.$$typeof===de}function pe(t){return Array.isArray(t)?[]:{}}function F(t,e){return e.clone!==!1&&e.isMergeableObject(t)?A(pe(t),t,e):t}function ye(t,e,r){return t.concat(e).map(function(n){return F(n,r)})}function me(t,e){if(!e.customMerge)return A;var r=e.customMerge(t);return typeof r=="function"?r:A}function be(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter(function(e){return Object.propertyIsEnumerable.call(t,e)}):[]}function v(t){return Object.keys(t).concat(be(t))}function N(t,e){try{return e in t}catch{return!1}}function Ae(t,e){return N(t,e)&&!(Object.hasOwnProperty.call(t,e)&&Object.propertyIsEnumerable.call(t,e))}function Fe(t,e,r){var n={};return r.isMergeableObject(t)&&v(t).forEach(function(s){n[s]=F(t[s],r)}),v(e).forEach(function(s){Ae(t,s)||(N(t,s)&&r.isMergeableObject(e[s])?n[s]=me(s,r)(t[s],e[s],r):n[s]=F(e[s],r))}),n}function A(t,e,r){r=r||{},r.arrayMerge=r.arrayMerge||ye,r.isMergeableObject=r.isMergeableObject||ce,r.cloneUnlessOtherwiseSpecified=F;var n=Array.isArray(e),s=Array.isArray(t),i=n===s;return i?n?r.arrayMerge(t,e,r):Fe(t,e,r):F(e,r)}A.all=function(e,r){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(n,s){return A(n,s,r)},{})};var Se=A;B.exports=Se});var Ke={};ae(Ke,{ESTransporter:()=>_,MatchFilter:()=>Qe,TermFilter:()=>C,default:()=>R});var J=oe(O());var C=(t,e)=>({term:{[t]:e}}),Qe=(t,e)=>({match:{[t]:e}});var S=(t,e)=>t.find(n=>typeof n=="string"?n===e:n.attribute===e)||null,Q=t=>typeof t!="string"&&!!t.nestedPath;var I=(t,e)=>{var n;let r=typeof e=="string"?e:e.attribute;return t.includes(r)?"string":((n=t.find(s=>(s==null?void 0:s.attribute)===r))==null?void 0:n.type)||"string"},H=(t,e)=>t.find(r=>typeof r=="string"?!1:r.attribute===e),w=t=>t.reduce((e,r)=>[...e,JSON.stringify({index:r.indexName}),`
`,JSON.stringify(r.body),`
`],[]).join("");var D=(t,e)=>{let{params:r={}}=t,{numericFilters:n}=r;return Array.isArray(n)?n.reduce((s,i)=>{let a,c,l,o,g="",u=i.match(/([\w\.\_\-]+)\s*(\=|\!\=|\>|\>\=|\<|\<\=)\s*(-?(?:\d+(?:\.\d*)?|\.\d+))/);if(u)[a,c,l,o]=u;else{if(u=i.match(/([\w\.\_\-]+):\s*(-?(?:\d+(?:\.\d*)?|\.\d+))\s*([Tt][Oo])\s*(-?(?:\d+(?:\.\d*)?|\.\d+))/),!u)throw new Error(`Numeric filter "${i}" could not be parsed. It should either be in the format "attributeName operator operand" or "attributeName: lowerBound TO upperBound"`);[a,c,o,l,g]=u}let f=M(e.facet_attributes||[],e.filter_attributes||[])[c],p=(h,m,b)=>{if(m==="=")return{term:{[h]:b}};if(m==="!=")return{bool:{must_not:{term:{[h]:b}}}};if(m===">")return{range:{[h]:{gt:b}}};if(m===">=")return{range:{[h]:{gte:b}}};if(m==="<")return{range:{[h]:{lt:b}}};if(m==="<=")return{range:{[h]:{lte:b}}};if(m.toUpperCase()==="TO")return{range:{[h]:{gte:b,lte:g}}}},y=[];if(f.nestedPath){let h=s.find(m=>m.nested.path===f.nestedPath);h?h.nested.query.bool.filter.push(p(f.nestedPath+"."+f.field,l,o)):y.push({nested:{path:f.nestedPath,inner_hits:{},query:{bool:{filter:[p(f.nestedPath+"."+f.field,l,o)]}}}})}else y.push(p(f.field,l,o));return[...s,...y]},[]):[]},M=(t,e)=>[...e,...t].reduce((r,n)=>{let s=typeof n=="string"?{attribute:n,field:n,type:"string"}:n;return{...r,[s.attribute]:s}},{}),L=(t,e)=>{let{params:r={}}=t,{facetFilters:n}=r;if(!Array.isArray(n))return[];let s=M(e.facet_attributes||[],e.filter_attributes||[]);return n.reduce((i,a)=>{if(Array.isArray(a))return[...i,{bool:{should:a.reduce((c,l)=>{let[o,g]=l.split(/:(.*)/),u=s[o];if(!u)throw new Error(`Facet "${o}" not found in configuration. Add configuration to either facet_attributes or filter_attributes.`);let d=u.field,f="filterQuery"in u&&u.filterQuery?u.filterQuery:C;if(Q(u)){let p=c.find(y=>y.nested&&y.nested.path===u.nestedPath);return p?(p.nested.query.bool.should.push(f(`${u.nestedPath}.${u.field}`,g)),c):[...c,{nested:{inner_hits:{},path:u.nestedPath,query:{bool:{should:[f(`${u.nestedPath}.${u.field}`,g)]}}}}]}return[...c,f(d,g)]},[])}}];if(typeof a=="string"){let[c,l]=a.split(/:(.*)/),o=s[c];if(!o)throw new Error(`Facet "${c}" not found in configuration. Add configuration to either facet_attributes or filter_attributes.`);let g="filterQuery"in o&&o.filterQuery?o.filterQuery:C;if(Q(o)&&o.nestedPath){let u=i.find(d=>d.nested&&d.nested.path===o.nestedPath+".");return u?(u.nested.query.bool.should.push(g(`${o.nestedPath}.${o.field}`,l)),i):[...i,{nested:{inner_hits:{},path:o.nestedPath,query:{bool:{should:[g(`${o.nestedPath}.${o.field}`,l)]}}}}]}return[...i,g(o.field,l)]}},[])},P=(t=[],e=[],r)=>{let n=/([\w\.\-]+)\:/gi,s=M(t,e);return r.replace(n,(i,a)=>{if(!s[a])throw new Error(`Attribute "${a}" is not defined as an attribute in the facet or filter search settings`);if(s[a].nestedPath)throw new Error(`Attribute "${a}" is a nested field and cannot be used as a filter. Nested fields are supported in facetFilers or numericFilters.`);return s[a].field+":"})},z=(t,e)=>{let{params:r={}}=t,{filters:n}=r;return!n||n===""?[]:[{query_string:{query:P(e.facet_attributes,e.filter_attributes,n)}}]},W=(t,e)=>{if(!e.geo_attribute)return[];let{params:r={}}=t,{aroundLatLng:n,aroundRadius:s,insideBoundingBox:i}=r;if(i)return[_e(i,e.geo_attribute)];if(n){let a=n.split(",");return[{geo_distance:{distance:s||"1000m",[e.geo_attribute]:{lat:a[0],lon:a[1]}}}]}return[]};function _e(t,e){let r=(n,s,i,a)=>({geo_bounding_box:{[e]:{top_right:{lat:n,lon:s},bottom_left:{lat:i,lon:a}}}});if(typeof t=="string"){let[n,s,i,a]=t.split(",");return r(parseFloat(n),parseFloat(s),parseFloat(i),parseFloat(a))}else if(Array.isArray(t))return{bool:{should:t.map(s=>{let[i,a,c,l]=s;return r(parseFloat(i),parseFloat(a),parseFloat(c),parseFloat(l))})}}}function U(t,e){if(e.sorting&&Object.keys(e.sorting).length>0){let r=Object.keys(e.sorting).find(i=>{if(t.indexName.endsWith(i))return!0});if(!r&&!e.sorting.default)return{};let n=r?e.sorting[r]:e.sorting.default,s=i=>{let a=i.nestedPath?`${i.nestedPath}.${i.field}`:i.field;if(i.nestedPath){let l={order:i.order,nested:{path:i.nestedPath}};return i.mode&&(l.mode=i.mode),{[a]:l}}let c=i.order;return i.mode?{[a]:{order:i.order,mode:i.mode}}:{[a]:c}};return{sort:Array.isArray(n)?n.map(s):s(n)}}return{}}function K(t,e){if(e.sorting&&Object.keys(e.sorting).length>0){let r=Object.keys(e.sorting).find(n=>{if(t.endsWith(n))return!0});if(r)return t.replace(r,"")}return t}var xe=t=>{let e=t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");return e=e.split("").map(r=>/[a-z]/.test(r)?`[${r}${r.toUpperCase()}]`:r).join(""),e=`${e}.*`,t.length>2&&(e=`([a-zA-Z]+ )+?${e}`),e},Ce=(t,e,r)=>{let n=r&&r.length>0?{include:xe(r)}:{};return{terms:{field:t,size:e,...n}}},$=(t,e,r)=>{let n={},s=typeof t!="string"&&"facetQuery"in t?t.facetQuery:Ce,i=(a,c)=>(typeof t=="string"||t.type==="string"?n={[a]:s(c,e,r)}:t.type==="numeric"&&(n={[a+"$_stats"]:{stats:{field:c}},[a+"$_entries"]:s(c,e,r)}),n);return typeof t=="string"?i(t,t):Q(t)?{[`${t.nestedPath}.`]:{nested:{path:t.nestedPath},aggs:i(t.attribute,`${t.nestedPath}.${t.field}`)}}:i(t.attribute,t.field)},we=(t,e,r)=>{let{params:n={},type:s}=t,{facets:i,maxValuesPerFacet:a,facetName:c,facetQuery:l}=n,o=a||10,g=e.facet_attributes||[];if(c){let u=S(g,c);return u?$(u,o,l):null}else if(Array.isArray(i)){let u=e.facet_attributes||[];return r.facetAttributesOrder&&(u=r.facetAttributesOrder.map(f=>S(e.facet_attributes||[],f)).filter(f=>f!==null)),(i[0]==="*"?u:i.map(f=>S(e.facet_attributes||[],f)).filter(f=>f!==null)).reduce((f,p)=>(0,J.default)(f,$(p,o,"")),{})||{}}else if(typeof i=="string"){let u=S(e.facet_attributes||[],i);return u?$(u,o,""):{}}};function Pe(t,e){return e.touched?{function_score:{query:{pinned:{ids:e.pinnedDocs,organic:t}},functions:e.boostFunctions}}:t}function Ee(t,e,r="AUTO:4,8"){let n=s=>e.map(i=>typeof i=="string"?i:`${i.field}^${(i.weight||1)*s}`);return{bool:{should:[{bool:{should:[{multi_match:{query:t,fields:n(1),fuzziness:r}},{multi_match:{query:t,fields:n(.5),type:"bool_prefix"}}]}},{multi_match:{query:t,type:"phrase",fields:n(2)}}]}}}var Re=(t,e,r,n)=>{var p,y,h;let s=r.query,i=e.search_attributes,a=e.fuzziness??"AUTO:4,8",c=[...L(t,e),...D(t,e),...z(t,e),...W(t,e),...((p=n==null?void 0:n.getBaseFilters)==null?void 0:p.call(n))||[],...r.baseFilters],l=typeof s=="string"&&s!==""?n!=null&&n.getQuery?n.getQuery(s,i,e):Ee(s,i,a):{match_all:{}},o=typeof(n==null?void 0:n.getKnnQuery)=="function",g=((y=n==null?void 0:n.getQuery)==null?void 0:y.call(n,s,i,e))===!1;(g||o&&s==="")&&(l={match_all:{}});let u={bool:{filter:c,must:r.touched?Pe(l,r):l}},d=null;if(o&&s!==""&&(d={filter:c,...((h=n==null?void 0:n.getKnnQuery)==null?void 0:h.call(n,s,i,e))||{}}),s!==""&&g&&o&&d)return{knn:d};let f=V(t);return{query:u,knn:d||void 0,rank:o&&!g&&f>0&&s!==""?{rrf:{window_size:f}}:void 0}},V=t=>{let{params:e={}}=t;return e.hitsPerPage==null?20:e.hitsPerPage},Me=(t,e)=>{let{params:r={}}=t,n=V(t);return{size:n,from:(r.page||0)*n}},$e=(t,e)=>{let{params:r={}}=t,{attributesToRetrieve:n}=r,s=new Set([...e.result_attributes||[],...e.highlight_attributes||[],...e.geo_attribute?[e.geo_attribute]:[]]),a=Object.keys(e.runtime_mappings||{}).reduce((c,l)=>{var o;return(o=e.result_attributes)!=null&&o.includes(l)?[l,...c]:c},[]);return{_source:{includes:Array.from(s)},...a.length>0?{fields:a}:{}}},E=t=>{let e={attribute:t,length:100};if(!t.includes(":"))return e;let r=t.match(/(.+)\:(\d+)/);return r?{attribute:r[1],length:parseInt(r[2])}:e},ke=(t,e)=>{var a,c;let{params:r={}}=t,{attributesToHighlight:n}=r,s=((a=e.highlight_attributes)==null?void 0:a.reduce((l,o)=>({...l,[o]:{number_of_fragments:0}}),{}))||{},i=((c=e.snippet_attributes)==null?void 0:c.reduce((l,o)=>({...l,[E(o).attribute]:{number_of_fragments:5,fragment_size:E(o).length}}),{}))||{};return Object.keys(s).length===0&&Object.keys(i).length===0?{}:{highlight:{pre_tags:["<em>"],post_tags:["</em>"],fields:{...s,...i}}}},Te=(t,e)=>e.runtime_mappings?{runtime_mappings:e.runtime_mappings}:{};function G(t,e,r,n){return{aggs:we(t,e,r),...Re(t,e,r,n),...Me(t,e),...$e(t,e),...ke(t,e),...U(t,e),...Te(t,e)}}function Y(t,e){let r=new RegExp(e,"gi");return t.replace(r,n=>`<em>${n}</em>`)}function je(t,e){return e.findIndex(r=>{if(r.indexOf("*")<0)return r===t;let n=r.replace(/[.+?^$|\{\}\(\)\[\]\\]/g,"\\$&");return new RegExp(`^${n.replace(/\*/g,".*")}$`).test(t)})>=0}function ve(t){let e={};for(let r in t){let n=r.split("."),s=e;for(let i=0;i<n.length-1;i++){let a=n[i];s[a]||(s[a]={}),s=s[a]}s[n[n.length-1]]=t[r]}return e}function Ne(t,e){return e.split(".").reduce((r,n)=>Array.isArray(r)?r.map(s=>s[n]):r&&Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0,t)}function k(t,e="<ais-highlight-0000000000>",r="<ais-highlight-0000000000/>",n=[]){let{_source:s={},highlight:i={}}=t,a={...s,...i},c=n.map(o=>E(o).attribute),l=Object.keys(a).reduce((o,g)=>{let u=Ne(s,g),d=i[g]||null;if(!je(g,c))return o;if(Array.isArray(u)&&!d)return{...o,[g]:u.map(f=>({matchLevel:"none",matchedWords:[],value:f.toString()}))};if(Array.isArray(u)&&d&&Array.isArray(d))return{...o,[g]:d.map(f=>({fullyHighlighted:!1,matchLevel:"full",matchedWords:Array.from(f.matchAll(/\<em\>(.*?)\<\/em\>/g)).map(y=>y[1]),value:f.toString().replace(/\<em\>/g,e).replace(/\<\/em\>/g,r)}))};if(!Array.isArray(u)&&d&&Array.isArray(d)||!u&&Array.isArray(d)&&d.length>0){let f=d[0],y={fullyHighlighted:!1,matchLevel:"full",matchedWords:Array.from(f.matchAll(/\<em\>(.*?)\<\/em\>/g)).map(h=>h[1]),value:f.toString().replace(/\<em\>/g,e).replace(/\<\/em\>/g,r)};return{...o,[g]:y}}return{...o,[g]:{matchLevel:"none",matchedWords:[],value:u!=null?u.toString():""}}},{});return ve(l)}var Be=(t,e,r)=>{let{hits:n}=t,{highlight_attributes:s=[],snippet_attributes:i=[]}=e;return n.hits.map(a=>{var c,l,o,g,u,d;return{objectID:a._id,_index:a._index,_score:a._score,...a._source||{},...a.fields||{},...a.inner_hits?{inner_hits:a.inner_hits}:{},...s.length>0?{_highlightResult:k(a,(c=r==null?void 0:r.params)==null?void 0:c.highlightPreTag,(l=r==null?void 0:r.params)==null?void 0:l.highlightPostTag,s)}:{},...i.length>0?{_snippetResult:k(a,(o=r==null?void 0:r.params)==null?void 0:o.highlightPreTag,(g=r==null?void 0:r.params)==null?void 0:g.highlightPostTag,e.snippet_attributes)}:{},...e.geo_attribute&&((u=a._source)!=null&&u[e.geo_attribute])?{_geoloc:Oe((d=a._source)==null?void 0:d[e.geo_attribute])}:{}}})};function Oe(t){if(typeof t=="string"){let[e,r]=t.split(",").map(n=>parseFloat(n));return{lat:e,lng:r}}else{if(Array.isArray(t))return{lat:t[0],lng:t[1]};if(typeof t=="object"&&"lat"in t&&"lon"in t)return{lat:parseFloat(t.lat),lng:parseFloat(t.lon)}}return null}var Ie=t=>t.buckets.reduce((e,r)=>({...e,[r.key]:r.doc_count}),{}),He=(t,e)=>{if(!(t!=null&&t.aggregations))return{};let r=Object.keys(t.aggregations).reduce((n,s)=>{let i=(t.aggregations||{})[s];if(s.endsWith(".")){let{doc_count:a,...c}=i;return{...n,...c}}return{...n,[s]:i}},{});return Object.keys(r).reduce((n,s)=>{let i=s.split("$")[0],a=I(e.facet_attributes||[],i),c=H(e.facet_attributes||[],i),l=c&&"facetResponse"in c&&(c==null?void 0:c.facetResponse)||Ie;if(a==="numeric"){let g=r[i+"$_stats"],{buckets:u}=r[i+"$_entries"];return{...n,facets:{...n.facets,[i]:l({buckets:u})},facets_stats:{...n.facets_stats,[i]:{min:g.min,avg:g.avg,max:g.max,sum:g.sum}}}}let{buckets:o}=r[i];return{...n,facets:{...n.facets,[i]:l({buckets:o})}}},{facets:{},facets_stats:{}})},De=(t,e)=>{var n,s;let r=(n=t.facet_attributes)==null?void 0:n.map(i=>typeof i=="string"?i:i.attribute);return{renderingContent:{facetOrdering:{facets:{order:e.facetAttributesOrder||r||[]},values:(s=t.facet_attributes)==null?void 0:s.reduce((i,a)=>{let c=typeof a=="string"?a:a.attribute;return e.facetAttributesOrder&&!e.facetAttributesOrder.includes(c)?i:{...i,[c]:{sortRemainingBy:"count"}}},{})}}}},Le=(t,e,r)=>{let{params:n={}}=e,{hitsPerPage:s=20,page:i=0}=n,{total:a}=t.hits,c=typeof a=="number"?a:a==null?void 0:a.value,l=s<=0?0:Math.ceil((typeof a=="number"?a:(a==null?void 0:a.value)||0)/s);return{hitsPerPage:s,processingTimeMS:t.took,nbHits:c,page:i,nbPages:l,query:r.query}};function T(t,e,r,n){try{return{appliedRules:n.ruleIds,exhaustiveNbHits:!0,exhaustiveFacetsCount:!0,exhaustiveTypo:!0,exhaustive:{facetsCount:!0,nbHits:!0,typo:!0},...Le(t,e,n),...De(r,n),...He(t,r),hits:Be(t,r,e),index:e.indexName,params:new URLSearchParams(e.params).toString(),...n.userData.length>0?{userData:n.userData}:{}}}catch{throw new Error("Error transforming Elasticsearch response for index")}}var Z=(t,e)=>{var c,l,o;let r=t.aggregations||{},n=(c=e==null?void 0:e.params)==null?void 0:c.facetName,s=((l=e.params)==null?void 0:l.highlightPreTag)||"<ais-highlight-0000000000>",i=((o=e.params)==null?void 0:o.highlightPostTag)||"<ais-highlight-0000000000/>",a=r[Object.keys(r)[0]];return a&&a[n]&&(a=a[n]),{facetHits:a.buckets.map(g=>({value:g.key,highlighted:Y(g.key,e.params.facetQuery||"").replace(/<\em>/g,s).replace(/<\/\em>/g,i),count:g.doc_count})),exhaustiveFacetsCount:!0,processingTimeMS:t.took}};var ze=t=>typeof btoa>"u"?Buffer.from(t.username+":"+t.password).toString("base64"):btoa(t.username+":"+t.password);function We(t){let e;return typeof atob>"u"?e=Buffer.from(t.split(":")[1],"base64").toString():e=atob(t.split(":")[1]).split("$"),`https://${e[1]}.${e[0]}`}var _=class{constructor(e,r){this.config=e;this.settings=r}createElasticsearchQueryFromRequest(e){return w(e)}async performNetworkRequest(e){if(this.config.host===void 0&&this.config.cloud_id===void 0)throw new Error("No Elasticsearch host or cloud_id specified. Please provide a host or cloud id in your Searchkit configuration.");let r=this.config.cloud_id?We(this.config.cloud_id):this.config.host;return fetch(`${r}/_msearch`,{headers:{...this.config.apiKey?{authorization:`ApiKey ${this.config.apiKey}`}:{},"content-type":"application/json",...this.config.headers||{},...this.config.auth?{Authorization:"Basic "+ze(this.config.auth)}:{}},body:this.createElasticsearchQueryFromRequest(e),method:"POST",...this.config.withCredentials?{credentials:"include"}:{}})}async msearch(e){var r,n,s,i,a,c;try{let o=await(await this.performNetworkRequest(e)).json();if(this.settings.debug&&(console.log("Elasticsearch response:"),console.log(JSON.stringify(o))),o.status>=500)throw console.error("Elasticsearch Internal Error: Check your elasticsearch instance to make sure it can recieve requests."),new Error(JSON.stringify(o));if(o.status===401)throw console.error("Cannot connect to Elasticsearch. Check your connection host and auth details (username/password or API Key required). You can also provide a custom Elasticsearch transporter to the API Client. See https://www.searchkit.co/docs/guides/setup-elasticsearch#connecting-with-usernamepassword for more details."),new Error(JSON.stringify(o));if(((n=(r=o.responses)==null?void 0:r[0])==null?void 0:n.status)===403)throw console.error("Auth Error: You do not have permission to access this index. Check you are calling the right index (specified in frontend) and your API Key permissions has access to the index."),new Error(JSON.stringify(o));if(o.status===404||((i=(s=o.responses)==null?void 0:s[0])==null?void 0:i.status)===404)throw console.error("Elasticsearch index not found. Check your index name and make sure it exists."),new Error(JSON.stringify(o));if(o.status===400||((c=(a=o.responses)==null?void 0:a[0])==null?void 0:c.status)===400)throw console.error(`Elasticsearch Bad Request.
1. Check your query and make sure it is valid.
2. Check the field mapping. See documentation to make sure you are using text types for searching and keyword fields for faceting
3. Turn on debug mode to see the Elasticsearch query and the error response.
`),new Error(JSON.stringify(o));return o.responses}catch(l){throw l}}};var X=t=>{if(!t)return[];if(typeof t=="string"){let[e,r]=t.split(/:(.*)/);return[{attribute:e,value:r}]}else return t.reduce((e,r)=>{if(typeof r=="string"){let[n,s]=r.split(/:(.*)/);return[...e,{attribute:n,value:s}]}return[...e,...X(r)]},[])},q=(t,e,r)=>{var a,c,l;let n={query:((a=e.params)==null?void 0:a.query)||"",context:((c=e.params)==null?void 0:c.ruleContexts)||[],filters:X((l=e.params)==null?void 0:l.facetFilters)},s=Ue(n,t||[]);return s.reduce((o,g)=>(g.actions.map(u=>{o.touched=!0,u.action==="PinnedResult"?o.pinnedDocs.push(...u.documentIds):u.action==="QueryRewrite"?o.query=u.query:u.action==="QueryBoost"?o.boostFunctions.push({filter:{query_string:{query:P(r.facet_attributes,r.filter_attributes,u.query)}},weight:u.weight}):u.action==="RenderUserData"?o.userData.push(JSON.parse(u.userData)):u.action==="RenderFacetsOrder"?o.facetAttributesOrder=u.facetAttributesOrder:u.action==="QueryFilter"&&o.baseFilters.push({query_string:{query:P(r.facet_attributes,r.filter_attributes,u.query)}})}),o),{ruleIds:s.map(o=>o.id),pinnedDocs:[],boostFunctions:[],query:n.query,userData:[],facetAttributesOrder:void 0,touched:!1,baseFilters:[]})},Ue=(t,e)=>e.filter(r=>r.conditions.find(n=>n.filter(s=>s.context==="query"&&s.match_type==="exact"?s.value===t.query:s.context==="query"&&s.match_type==="contains"?t.query.includes(s.value):s.context==="query"&&s.match_type==="prefix"?t.query.startsWith(s.value):s.context==="context"?s.value.some(i=>t.context.includes(i)):s.context==="filterPresent"?s.values.every(i=>t.filters.find(a=>a.attribute===i.attribute&&a.value===i.value)!==void 0):!1).length===n.length)!==void 0);var R=class{constructor(e,r={debug:!1}){this.config=e;this.settings=r;this.transporter="msearch"in e.connection?e.connection:new _(e.connection,r)}async performSearch(e){return this.settings.debug&&(console.log("Performing search with requests:"),console.log("POST /_msearch"),console.log(w(e))),await this.transporter.msearch(e)}async handleInstantSearchRequests(e,r){var c,l;if(!e||Array.isArray(e)===!1)throw console.log({instantsearchRequests:e}),new Error("No instantsearch requests provided. Check that the data you are providing from API request is correct. Likely you are not passing the request body correctly, its still a JSON string or the API is not a POST request.");let n=this.config.search_settings.query_rules||[],s=e.map(o=>q(n,o,this.config.search_settings)),i=e.map((o,g)=>({body:G(o,this.config.search_settings,s[g],r),request:o,indexName:K(o.indexName,this.config.search_settings)}));(c=r==null?void 0:r.hooks)!=null&&c.beforeSearch&&(i=await r.hooks.beforeSearch(i));let a=await this.performSearch(i);(l=r==null?void 0:r.hooks)!=null&&l.afterSearch&&(a=await r.hooks.afterSearch(i,a));try{return{results:a.map((g,u)=>{var d;return(d=e[u].params)!=null&&d.facetName?Z(g,e[u]):T(g,e[u],this.config.search_settings,s[u])})}}catch(o){throw console.error(o),new Error("Error transforming response. Check the afterSearch hook function is correct. Likely you are not returning the correct response object.")}}};return ue(Ke);})();
var Searchkit = SearchkitDefault.default
//# sourceMappingURL=index.global.js.map