@bloomreach/clarity-utils 1.0.14 → 1.0.16
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.
- package/dist/index.d.mts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.global.js +1 -1
- package/dist/index.js +59 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +59 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
type ClarityUtilsConfig = {
|
|
2
|
-
mode?: 'list' | 'length' | 'mixed' | 'score';
|
|
2
|
+
mode?: 'list' | 'length' | 'mixed' | 'score' | 'api';
|
|
3
3
|
locale?: string;
|
|
4
4
|
whiteList?: string[];
|
|
5
5
|
blackList?: string[];
|
|
@@ -11,6 +11,8 @@ type ClarityUtilsConfig = {
|
|
|
11
11
|
scoreCommonVerbs?: string[];
|
|
12
12
|
scoreStopwords?: string[];
|
|
13
13
|
scoreSupportWords?: string[];
|
|
14
|
+
apiBaseUrl?: string;
|
|
15
|
+
apiTimeoutMs?: number;
|
|
14
16
|
};
|
|
15
17
|
|
|
16
18
|
declare const clarityUtils: {
|
|
@@ -20,7 +22,7 @@ declare const clarityUtils: {
|
|
|
20
22
|
success: false;
|
|
21
23
|
error: unknown;
|
|
22
24
|
}>;
|
|
23
|
-
isSearch: (value: string, config?: ClarityUtilsConfig) => boolean
|
|
25
|
+
isSearch: (value: string, config?: ClarityUtilsConfig) => Promise<boolean>;
|
|
24
26
|
};
|
|
25
27
|
|
|
26
28
|
export { clarityUtils };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
type ClarityUtilsConfig = {
|
|
2
|
-
mode?: 'list' | 'length' | 'mixed' | 'score';
|
|
2
|
+
mode?: 'list' | 'length' | 'mixed' | 'score' | 'api';
|
|
3
3
|
locale?: string;
|
|
4
4
|
whiteList?: string[];
|
|
5
5
|
blackList?: string[];
|
|
@@ -11,6 +11,8 @@ type ClarityUtilsConfig = {
|
|
|
11
11
|
scoreCommonVerbs?: string[];
|
|
12
12
|
scoreStopwords?: string[];
|
|
13
13
|
scoreSupportWords?: string[];
|
|
14
|
+
apiBaseUrl?: string;
|
|
15
|
+
apiTimeoutMs?: number;
|
|
14
16
|
};
|
|
15
17
|
|
|
16
18
|
declare const clarityUtils: {
|
|
@@ -20,7 +22,7 @@ declare const clarityUtils: {
|
|
|
20
22
|
success: false;
|
|
21
23
|
error: unknown;
|
|
22
24
|
}>;
|
|
23
|
-
isSearch: (value: string, config?: ClarityUtilsConfig) => boolean
|
|
25
|
+
isSearch: (value: string, config?: ClarityUtilsConfig) => Promise<boolean>;
|
|
24
26
|
};
|
|
25
27
|
|
|
26
28
|
export { clarityUtils };
|
package/dist/index.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var tmp=(()=>{var y=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var A=(n,e)=>{for(var o in e)y(n,o,{get:e[o],enumerable:!0})},G=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of U(e))!B.call(n,r)&&r!==o&&y(n,r,{get:()=>e[r],enumerable:!(t=T(e,r))||t.enumerable});return n};var H=n=>G(y({},"__esModule",{value:!0}),n);var re={};A(re,{clarityUtils:()=>se});var z={questions:["who","what","when","where","why","how","which","can","should","could","would","will","have","has","is","are","do","does","did"],pronouns:["i","me","my","mine","we","us","our","you","your","it","he","him","his","she","her","they","them","their"],commonVerbs:["is","are","was","were","do","does","did","have","need","want","look","help","know","think","make","create","find","get","buy","use","install","fix","recommend","tell","show","compare","explain"],stopwords:["the","a","an","i","me","my","is","it","in","on","at","to","for","of","and","or","but","not","so","if","by","with","from","that","this","about"],support:["order","package","shipment","tracking","delivery","delayed","late","lost","missing","cancel","modify","return","exchange","refund","replacement","eligible","eligibility","warranty","damaged","broken","defective","wrong","incorrect","password","login","account","locked","verification","otp","loyalty","rewards","reward","points","point","promo","promos","promotion","promotions","coupon","coupons","discount","discounts","gift","gifts","shipping","payment","payments","billing","charged","charge","invoice","receipt","declined","size","sizing","fit","care","stock","restock","availability","sustainability","ethics","careers","privacy","terms","agent","representative","support","human","talk","speak","help","customer support","customer service","api","failure","server","technical","website","checkout","app","resume","chat","community","returns","where is my order","stores","store","repairs","repair"],contractions:{"won't":"will not","can't":"cannot","don't":"do not","doesn't":"does not","didn't":"did not","isn't":"is not","aren't":"are not","wasn't":"was not","weren't":"were not","haven't":"have not","hasn't":"has not","hadn't":"had not","wouldn't":"would not","shouldn't":"should not","couldn't":"could not","what's":"what is","what're":"what are","how's":"how is","where's":"where is","who's":"who is","that's":"that is","there's":"there is","it's":"it is","i'm":"i am","i'd":"i would","i'll":"i will","i've":"i have","we're":"we are","we've":"we have","we'd":"we would","they're":"they are","they've":"they have","you're":"you are","you've":"you have","you'd":"you would"}},I={questions:["wer","was","wann","wo","warum","wieso","weshalb","wie","welche","welcher","welches","kann","kannst","k\xF6nnen","soll","sollte","k\xF6nnte","w\xFCrde","wird","hat","habe","haben","ist","sind","tust","tun"],pronouns:["ich","mich","mir","mein","meine","meiner","meinen","wir","uns","unser","unsere","du","dich","dir","dein","deine","sie","ihnen","er","ihn","ihm","sein","seine","ihr","ihre","es"],commonVerbs:["ist","sind","war","waren","tut","tun","tat","taten","hat","habe","haben","hatte","hatten","brauche","brauchen","m\xF6chte","m\xF6chten","will","willst","wollen","suche","such","suchen","hilf","helfen","wei\xDF","denke","denken","mache","mach","machen","erstelle","erstellen","finde","find","finden","kaufe","kauf","kaufen","benutze","benutzen","installiere","installieren","repariere","reparieren","empfehle","empfiehl","empfehlen","sage","sag","sagen","zeige","zeig","zeigen","vergleiche","vergleich","vergleichen","erkl\xE4re","erkl\xE4r","erkl\xE4ren"],stopwords:["der","die","das","den","dem","des","ein","eine","einen","einer","eines","ich","mich","mein","ist","es","in","an","auf","zu","f\xFCr","von","und","oder","aber","nicht","also","falls","mit","aus","dass","dieser","diese","dieses","\xFCber"],support:["bestellung","bestellungen","paket","sendung","versand","lieferung","tracking","verz\xF6gert","versp\xE4tet","verloren","fehlt","fehlend","stornieren","storno","\xE4ndern","r\xFCcksendung","r\xFCckgabe","retoure","umtausch","r\xFCckerstattung","erstattung","ersatz","berechtigt","anspruch","garantie","besch\xE4digt","kaputt","defekt","falsch","fehlerhaft","passwort","anmelden","login","konto","gesperrt","verifizierung","otp","treue","treueprogramm","pr\xE4mien","punkte","aktion","gutschein","rabatt","geschenk","geschenkkarte","versandkosten","zahlung","abrechnung","belastet","rechnung","beleg","quittung","abgelehnt","gr\xF6\xDFe","passform","pflege","lager","verf\xFCgbarkeit","nachhaltigkeit","ethik","karriere","datenschutz","bedingungen","agb","mitarbeiter","vertreter","support","mensch","sprechen","reden","hilfe","kundensupport","kundenservice","api","fehler","server","technisch","webseite","kasse","app","r\xFCckgabe","zur\xFCckgeben","bestellstatus","lieferstatus","wo ist meine bestellung","filialen","reparaturen"]},D={questions:["qui","que","quoi","quand","o\xF9","pourquoi","comment","combien","quel","quelle","quels","quelles","peux","peut","peuvent","dois","doit","devrait","pourrait","aurait","sera","est","sont","fait","font","ai","as","a","avons","avez","ont"],pronouns:["je","moi","mon","ma","mes","mien","mienne","nous","notre","nos","n\xF4tre","tu","te","toi","ton","ta","tes","vous","votre","vos","il","lui","son","sa","ses","elle","ils","elles","leur","leurs"],commonVerbs:["est","sont","\xE9tait","\xE9taient","fait","font","faisait","ai","as","a","avons","avez","ont","avait","avaient","besoin","veux","veut","voulons","voulez","veulent","cherche","cherchons","cherchez","aide","aider","sais","sait","savez","savons","pense","pensons","pensez","fais","faisons","faites","cr\xE9e","cr\xE9er","trouve","trouver","ach\xE8te","acheter","utilise","utiliser","installe","installer","r\xE9pare","r\xE9parer","recommande","recommander","dis","dites","montre","montrer","compare","comparer","explique","expliquer","voudrais","voir"],stopwords:["le","la","les","un","une","des","du","au","aux","je","me","mon","est","il","elle","dans","sur","\xE0","pour","de","et","ou","mais","pas","donc","si","par","avec","depuis","que","ce","cette","ces"],support:["commande","commandes","colis","envoi","exp\xE9dition","livraison","suivi","retard\xE9","retard","perdu","manquant","annuler","annulation","modifier","retour","retours","\xE9change","remboursement","remplacement","\xE9ligible","\xE9ligibilit\xE9","garantie","endommag\xE9","cass\xE9","d\xE9fectueux","incorrect","erron\xE9","mot de passe","motdepasse","connexion","identifiant","compte","verrouill\xE9","v\xE9rification","otp","fid\xE9lit\xE9","r\xE9compenses","points","promo","promotion","coupon","remise","r\xE9duction","cadeau","paiement","facturation","factur\xE9","facture","re\xE7u","refus\xE9","taille","pointure","ajustement","entretien","stock","disponibilit\xE9","durabilit\xE9","\xE9thique","carri\xE8res","confidentialit\xE9","conditions","agent","repr\xE9sentant","support","humain","parler","aide","support client","service client","api","panne","serveur","technique","site","paiement","app","application","remboursement","retard","site web","question","concernant","couverture","bris\xE9","article","\xE9changer","probl\xE8me","carte","cr\xE9dit","transaction","\xE9chou\xE9e","login","marche","ab\xEEm\xE9e","d'aide","service","client","assistance","tracking","endommage","communaut\xE9","demander","\xE9tiquette","\xE9tudiants","enseignants","rabais","militaires","g\xE9rer","\xE9changes","o\xF9 est ma commande","boutiques","r\xE9parations"],elisionPrefixes:["j","n","qu","l","d","c","m","t","s"]},K={questions:["chi","cosa","che","quando","dove","perch\xE9","perch\xE8","come","quanto","quanti","quante","quale","quali","posso","pu\xF2","possono","devo","deve","dovrebbe","potrebbe","vorrebbe","sar\xE0","ho","ha","hanno","\xE8","sono","fa","fanno","fai"],pronouns:["io","mi","me","mio","mia","miei","mie","noi","ci","nostro","nostra","nostri","nostre","tu","ti","te","tuo","tua","tuoi","tue","voi","vi","vostro","vostra","vostri","vostre","lui","lei","suo","sua","suoi","sue","loro"],commonVerbs:["\xE8","sono","era","erano","fa","fanno","faceva","ha","ho","hai","abbiamo","avete","hanno","aveva","avevano","bisogno","voglio","vuole","vogliamo","volete","vogliono","cerco","cerca","cerchiamo","cercate","aiuto","aiuta","aiutami","aiutare","so","sa","sappiamo","sapete","spieghi","spiega","spiego","spiegate","spieghiamo","penso","pensa","pensiamo","faccio","facciamo","fate","creo","creare","trovo","trova","trovami","trovare","compro","compra","comprami","comprare","uso","usare","installo","installare","riparo","riparare","raccomando","raccomanda","raccomandami","raccomandare","dimmi","dire","mostra","mostrami","mostrare","confronto","confronta","confrontami","confrontare","spiego","spiega","spiegami","spiegare","sto","cercando"],stopwords:["il","lo","la","i","gli","le","un","uno","una","io","mi","mio","\xE8","in","su","a","per","di","da","e","ed","o","ma","non","cos\xEC","se","con","che","questo","questa","questi","queste"],support:["ordine","ordini","pacco","spedizione","consegna","tracciamento","ritardato","ritardo","perso","mancante","annullare","annullamento","modificare","reso","resi","cambio","rimborso","sostituzione","idoneo","idoneit\xE0","garanzia","danneggiato","rotto","difettoso","sbagliato","errato","password","accesso","login","account","bloccato","verifica","otp","fedelt\xE0","premi","punti","promozione","promo","coupon","sconto","regalo","pagamento","fatturazione","addebitato","fattura","ricevuta","rifiutato","taglia","misura","vestibilit\xE0","cura","scorta","disponibilit\xE0","sostenibilit\xE0","etica","carriere","privacy","termini","agente","rappresentante","supporto","umano","parlare","aiuto","assistenza clienti","servizio clienti","api","guasto","server","tecnico","sito","checkout","app","assistenza","restituzione","stato ordine","cambi","dov'\xE8 il mio ordine","negozi","riparazioni"],elisionPrefixes:["c","l","d","un","m","t","s","all","nell","dell","sull","quell"]},M={questions:["wie","wat","wanneer","waar","waarom","hoe","hoeveel","welke","welk","kan","kunt","kunnen","zou","zal","moet","heb","heeft","hebben","is","zijn","doe","doet","doen"],pronouns:["ik","mij","me","mijn","wij","we","ons","onze","jij","je","jou","jouw","u","uw","hij","hem","zijn","zij","ze","haar","hen","hun","het"],commonVerbs:["is","zijn","was","waren","doet","doe","doen","deed","deden","heb","heeft","hebben","had","hadden","nodig","wil","willen","wilde","zoek","zoeken","help","helpen","weet","weten","denk","denken","maak","maken","maakte","cre\xEBer","cre\xEBren","vind","vinden","vond","koop","kopen","gebruik","gebruiken","installeer","installeren","repareer","repareren","raad","aanraden","vertel","vertellen","toon","tonen","vergelijk","vergelijken","leg","uitleggen"],stopwords:["de","het","een","ik","mij","mijn","is","in","op","aan","naar","voor","van","en","of","maar","niet","dus","als","door","met","vanaf","dat","dit","deze","die","over"],support:["bestelling","bestellingen","pakket","zending","verzending","levering","tracking","vertraagd","laat","verloren","ontbrekend","annuleren","wijzigen","retour","retourneren","ruil","terugbetaling","restitutie","vervanging","geschikt","geschiktheid","garantie","beschadigd","kapot","defect","verkeerd","onjuist","wachtwoord","inloggen","login","account","geblokkeerd","verificatie","otp","loyaliteit","beloningen","punten","promo","promotie","kortingsbon","korting","cadeau","cadeaubon","verzending","betaling","facturering","gefactureerd","factuur","bonnetje","kassabon","geweigerd","maat","pasvorm","verzorging","voorraad","beschikbaarheid","duurzaamheid","ethiek","carri\xE8res","privacy","voorwaarden","medewerker","vertegenwoordiger","ondersteuning","mens","praten","spreken","hulp","klantenondersteuning","api","storing","server","technisch","website","afrekenen","app","klantenservice","bestelstatus","terugsturen","ruilen","waar is mijn bestelling","winkels","reparaties"]},E={questions:["qui\xE9n","quien","qu\xE9","que","cu\xE1ndo","cuando","d\xF3nde","donde","porqu\xE9","porque","c\xF3mo","como","cu\xE1l","cual","cu\xE1les","cuales","cu\xE1nto","cuanto","cu\xE1ntos","puedo","puede","pueden","podr\xEDa","deber\xEDa","ser\xEDa","ha","han","es","son","hace","hacen"],pronouns:["yo","me","m\xED","mi","m\xEDo","m\xEDa","m\xEDos","m\xEDas","nosotros","nosotras","nos","nuestro","nuestra","nuestros","nuestras","t\xFA","tu","te","ti","tuyo","tuya","tuyos","tuyas","usted","ustedes","vosotros","vosotras","vuestro","vuestra","\xE9l","ella","su","sus","suyo","suya","ellos","ellas","les","los","las","le","la","lo","mu\xE9strame"],commonVerbs:["es","son","era","eran","est\xE1","est\xE1n","hace","hacen","hac\xEDa","ha","he","has","hemos","hab\xE9is","han","hab\xEDa","hab\xEDan","necesito","necesita","necesitamos","necesitan","quiero","quiere","queremos","quer\xE9is","quieren","busco","busca","b\xFAscame","buscamos","buscan","ayuda","ay\xFAdame","ayudar","s\xE9","sabe","sabemos","saben","pienso","piensa","pensamos","hago","hacemos","creo","crear","encuentro","encuentra","encu\xE9ntrame","encontrar","compro","compra","c\xF3mprame","comprar","uso","usar","instalo","instalar","reparo","reparar","recomiendo","recomienda","recomi\xE9ndame","recomendar","dime","decir","muestra","mu\xE9strame","mostrar","comparo","compara","comparar","explico","explica","expl\xEDcame","explicar"],stopwords:["el","la","los","las","un","una","unos","unas","yo","me","mi","es","en","a","al","para","de","del","y","e","o","u","pero","no","as\xED","si","por","con","desde","que","este","esta","estos","estas","sobre"],support:["pedido","pedidos","paquete","env\xEDo","entrega","seguimiento","retrasado","tarde","perdido","faltante","cancelar","cancelaci\xF3n","modificar","devoluci\xF3n","devoluciones","cambio","reembolso","reemplazo","elegible","elegibilidad","garant\xEDa","da\xF1ado","roto","defectuoso","incorrecto","equivocado","contrase\xF1a","acceso","login","cuenta","bloqueada","bloqueado","verificaci\xF3n","otp","fidelidad","recompensas","puntos","promo","promoci\xF3n","cup\xF3n","descuento","regalo","env\xEDo","pago","facturaci\xF3n","cobrado","cargo","factura","recibo","rechazado","talla","tama\xF1o","ajuste","cuidado","inventario","disponibilidad","sostenibilidad","\xE9tica","carreras","privacidad","t\xE9rminos","agente","representante","soporte","humano","hablar","ayuda","soporte al cliente","servicio al cliente","api","fallo","servidor","t\xE9cnico","sitio","pago","app","atenci\xF3n al cliente","estado del pedido","devolver","empleo","trabajo","caracter\xEDstica","art\xEDculo","pregunta","igualan","c\xF3digo","promocional","funciona","sobre","promociones","descuentos","actuales","tengo","militares","agotado","cambios","d\xF3nde est\xE1 mi pedido","tiendas","reparaciones"]},V={"en-gb":z,"en-us":z,"en-ca":z,"de-de":I,"fr-fr":D,"fr-ca":D,"it-it":K,"nl-nl":M,"es-es":E,"es-us":E},_="en-us",f=n=>{var e,o;return(o=V[(e=n==null?void 0:n.toLowerCase())!=null?e:_])!=null?o:V[_]};var q=n=>!/\w/.test(n),F=n=>n.normalize("NFD").replace(/[̀-ͯ]/g,""),X=(n,e)=>{if(!e||e.length===0)return n;let o=new RegExp(`\\b(${e.join("|")})['\u2019](?=[\\p{L}\\p{N}])`,"giu");return n.replace(o,"$1' ")},Y=(n,e)=>e?n.replace(/[\p{L}\p{N}_'’]+/gu,o=>{var r,s;let t=o.replace(/’/g,"'");return(s=(r=e[t])!=null?r:e[o])!=null?s:o}):n,p=(n,e)=>{var s;let o=f(e),t=X(n,o.elisionPrefixes);return(s=Y(t,o.contractions).match(/[\p{L}\p{N}_'’]+|[^\s\p{L}\p{N}_'’]/gu))!=null?s:[]},m=n=>{let e=[],o=n.tokens.map(F);for(let t of n.phrases){let r=t.split(/\s+/).filter(Boolean).map(F);if(r.length!==0){if(r.length===1){o.includes(r[0])&&e.push(t);continue}for(let s=0;s<=o.length-r.length;s++){let a=!0;for(let i=0;i<r.length;i++)if(o[s+i]!==r[i]){a=!1;break}if(a){e.push(t);break}}}}return e},J=n=>n.reduce((e,o)=>e+o.split(/\s+/).filter(Boolean).length,0);var L=(n,e)=>{if(!e.maxLength)return console.log(" checkLength \u2192 true (no maxLength configured)"),!0;let o=p(n).length,t=o<=e.maxLength;return console.log(` checkLength \u2192 ${t} (wordCount=${o} maxLength=${e.maxLength})`),t};var Z=(n,e)=>{var o;for(let t of(o=e.blackPunctSet)!=null?o:[])if(n.includes(t))return console.log(` punct "${t}" found in sentence \u2192 false (blacklisted)`),!1;return!0},ee=(n,e)=>{var t,r,s,a,i,u,d;if((t=e.blackWordSet)!=null&&t.has(n))return console.log(` word "${n}" \u2192 false (blacklisted)`),!1;if(((s=(r=e.whiteSet)==null?void 0:r.size)!=null?s:0)>0||((i=(a=e.whiteList)==null?void 0:a.length)!=null?i:0)>0){let l=!!((u=e.whiteSet)!=null&&u.has(n)||(d=e.whiteList)!=null&&d.some(c=>c.toLowerCase()===n));return console.log(` word "${n}" \u2192 ${l} (whitelist check)`),l}return console.log(` word "${n}" \u2192 true`),!0},O=(n,e)=>Z(n,e)&&p(n).every(o=>ee(o,e));var x=(n,e)=>{var W,$,j,R,P;let o=p(n,e.locale);if(o.length===0)return!0;let t=f(e.locale),r=(W=e.scoreQuestionWords)!=null?W:t.questions,s=($=e.scorePronouns)!=null?$:t.pronouns,a=(j=e.scoreCommonVerbs)!=null?j:t.commonVerbs,i=(R=e.scoreStopwords)!=null?R:t.stopwords,u=(P=e.scoreSupportWords)!=null?P:t.support,d=m({tokens:o,phrases:u});if(d.length>0)return console.log(` [A] support words: found [${d.join(", ")}] \u2192 conversational (override)`),!1;let l=0,c=0;o.length<=3?(l+=2,console.log(` [B] token count: word count=${o.length} \u22643 \u2192 keyword +2`)):o.length>=6?(c+=2,console.log(` [B] token count: word count=${o.length} \u22656 \u2192 conversational +2`)):console.log(` [B] token count: word count=${o.length} (no score)`);let h=m({tokens:o,phrases:r});h.length>0?(c+=2,console.log(` [C] question words: found [${h.join(", ")}] \u2192 conversational +2`)):console.log(" [C] question words: none");let g=m({tokens:o,phrases:s});g.length>0?(c+=1,console.log(` [D] pronouns: found [${g.join(", ")}] \u2192 conversational +1`)):console.log(" [D] pronouns: none");let C=m({tokens:o,phrases:a});C.length>0?(c+=2,console.log(` [E] common verbs: found [${C.join(", ")}] \u2192 conversational +2`)):console.log(" [E] common verbs: none"),n.includes("?")?(c+=3,console.log(" [F] question mark: found \u2192 conversational +3")):console.log(" [F] question mark: none");let b=J(m({tokens:o,phrases:i})),w=b/o.length;w>.4?(c+=2,console.log(` [G] stopword ratio: ${w.toFixed(2)} (${b}/${o.length}) >0.4 \u2192 conversational +2`)):(l+=1,console.log(` [G] stopword ratio: ${w.toFixed(2)} (${b}/${o.length}) \u22640.4 \u2192 keyword +1`));let k=o.reduce((N,Q)=>N+Q.length,0)/o.length;k>=6?(l+=1,console.log(` [H] avg token length: ${k.toFixed(2)} \u22656 \u2192 keyword +1`)):console.log(` [H] avg token length: ${k.toFixed(2)} (no score)`);let S=l>=c;return console.log(` scores: keyword=${l} conversational=${c} \u2192 ${S?"keyword":"conversational"}`),S};var v={},oe=async n=>{v={...n};let e=new Set,o=new Set,t=new Set;try{return await Promise.all([n.whiteListJson?fetch(n.whiteListJson).then(r=>r.json()).then(r=>{r.forEach(s=>t.add(s.toLowerCase()))}):null,n.blackListJson?fetch(n.blackListJson).then(r=>r.json()).then(r=>{r.forEach(s=>{let a=s.toLowerCase();q(a)?e.add(a):o.add(a)})}):null]),v={...v,blackJsonPunctSet:e,blackJsonWordSet:o,whiteSet:t},{success:!0}}catch(r){return{success:!1,error:r}}},ne=n=>{var o,t,r;let e={...v,...n!=null?n:{}};return e.blackPunctSet=new Set([...(o=e.blackJsonPunctSet)!=null?o:[]]),e.blackWordSet=new Set([...(t=e.blackJsonWordSet)!=null?t:[]]),(r=e.blackList)==null||r.forEach(s=>{var i,u;let a=s.toLowerCase();q(a)?(i=e.blackPunctSet)==null||i.add(a):(u=e.blackWordSet)==null||u.add(a)}),e.scoreQuestionWords&&(e.scoreQuestionWords=e.scoreQuestionWords.map(s=>s.toLowerCase())),e.scorePronouns&&(e.scorePronouns=e.scorePronouns.map(s=>s.toLowerCase())),e.scoreCommonVerbs&&(e.scoreCommonVerbs=e.scoreCommonVerbs.map(s=>s.toLowerCase())),e.scoreStopwords&&(e.scoreStopwords=e.scoreStopwords.map(s=>s.toLowerCase())),e.scoreSupportWords&&(e.scoreSupportWords=e.scoreSupportWords.map(s=>s.toLowerCase())),e},te=(n,e)=>{var a,i,u,d,l,c,h,g;let o=ne(e),t=n.toLowerCase(),r=p(t);console.group(`[isSearch] "${n}" | mode=${o.mode} | tokens=[${r.join(", ")}] | locale=${o.locale}`),(o.mode==="mixed"||o.mode==="list")&&console.log(`lists: blackWordSet=${(i=(a=o.blackWordSet)==null?void 0:a.size)!=null?i:0} blackPunctSet=${(d=(u=o.blackPunctSet)==null?void 0:u.size)!=null?d:0} whiteSet=${(c=(l=o.whiteSet)==null?void 0:l.size)!=null?c:0} whiteList=${(g=(h=o.whiteList)==null?void 0:h.length)!=null?g:0}`);let s;return o.mode==="length"?s=L(t,o):o.mode==="mixed"?s=O(t,o)&&L(t,o):o.mode==="score"?s=x(t,o):s=x(t,o),console.log(`\u2192 Result: ${s}`),console.groupEnd(),s},se={setup:oe,isSearch:te};return H(re);})();
|
|
1
|
+
"use strict";var tmp=(()=>{var y=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var G=(n,e)=>{for(var o in e)y(n,o,{get:e[o],enumerable:!0})},K=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of B(e))!H.call(n,r)&&r!==o&&y(n,r,{get:()=>e[r],enumerable:!(t=Q(e,r))||t.enumerable});return n};var M=n=>K(y({},"__esModule",{value:!0}),n);var de={};G(de,{clarityUtils:()=>ue});var z={questions:["who","what","when","where","why","how","which","can","should","could","would","will","have","has","is","are","do","does","did"],pronouns:["i","me","my","mine","we","us","our","you","your","it","he","him","his","she","her","they","them","their"],commonVerbs:["is","are","was","were","do","does","did","have","need","want","look","help","know","think","make","create","find","get","buy","use","install","fix","recommend","tell","show","compare","explain"],stopwords:["the","a","an","i","me","my","is","it","in","on","at","to","for","of","and","or","but","not","so","if","by","with","from","that","this","about"],support:["order","package","shipment","tracking","delivery","delayed","late","lost","missing","cancel","modify","return","exchange","refund","replacement","eligible","eligibility","warranty","damaged","broken","defective","wrong","incorrect","password","login","account","locked","verification","otp","loyalty","rewards","reward","points","point","promo","promos","promotion","promotions","coupon","coupons","discount","discounts","gift","gifts","shipping","payment","payments","billing","charged","charge","invoice","receipt","declined","size","sizing","fit","care","stock","restock","availability","sustainability","ethics","careers","privacy","terms","agent","representative","support","human","talk","speak","help","customer support","customer service","api","failure","server","technical","website","checkout","app","resume","chat","community","returns","where is my order","stores","store","repairs","repair"],contractions:{"won't":"will not","can't":"cannot","don't":"do not","doesn't":"does not","didn't":"did not","isn't":"is not","aren't":"are not","wasn't":"was not","weren't":"were not","haven't":"have not","hasn't":"has not","hadn't":"had not","wouldn't":"would not","shouldn't":"should not","couldn't":"could not","what's":"what is","what're":"what are","how's":"how is","where's":"where is","who's":"who is","that's":"that is","there's":"there is","it's":"it is","i'm":"i am","i'd":"i would","i'll":"i will","i've":"i have","we're":"we are","we've":"we have","we'd":"we would","they're":"they are","they've":"they have","you're":"you are","you've":"you have","you'd":"you would"}},Y={questions:["wer","was","wann","wo","warum","wieso","weshalb","wie","welche","welcher","welches","kann","kannst","k\xF6nnen","soll","sollte","k\xF6nnte","w\xFCrde","wird","hat","habe","haben","ist","sind","tust","tun"],pronouns:["ich","mich","mir","mein","meine","meiner","meinen","wir","uns","unser","unsere","du","dich","dir","dein","deine","sie","ihnen","er","ihn","ihm","sein","seine","ihr","ihre","es"],commonVerbs:["ist","sind","war","waren","tut","tun","tat","taten","hat","habe","haben","hatte","hatten","brauche","brauchen","m\xF6chte","m\xF6chten","will","willst","wollen","suche","such","suchen","hilf","helfen","wei\xDF","denke","denken","mache","mach","machen","erstelle","erstellen","finde","find","finden","kaufe","kauf","kaufen","benutze","benutzen","installiere","installieren","repariere","reparieren","empfehle","empfiehl","empfehlen","sage","sag","sagen","zeige","zeig","zeigen","vergleiche","vergleich","vergleichen","erkl\xE4re","erkl\xE4r","erkl\xE4ren"],stopwords:["der","die","das","den","dem","des","ein","eine","einen","einer","eines","ich","mich","mein","ist","es","in","an","auf","zu","f\xFCr","von","und","oder","aber","nicht","also","falls","mit","aus","dass","dieser","diese","dieses","\xFCber"],support:["bestellung","bestellungen","paket","sendung","versand","lieferung","tracking","verz\xF6gert","versp\xE4tet","verloren","fehlt","fehlend","stornieren","storno","\xE4ndern","r\xFCcksendung","r\xFCckgabe","retoure","umtausch","r\xFCckerstattung","erstattung","ersatz","berechtigt","anspruch","garantie","besch\xE4digt","kaputt","defekt","falsch","fehlerhaft","passwort","anmelden","login","konto","gesperrt","verifizierung","otp","treue","treueprogramm","pr\xE4mien","punkte","aktion","aktionen","gutschein","rabatt","rabatte","geschenk","geschenkkarte","versandkosten","zahlung","abrechnung","belastet","rechnung","beleg","quittung","abgelehnt","gr\xF6\xDFe","passform","pflege","lager","verf\xFCgbarkeit","nachhaltigkeit","ethik","karriere","datenschutz","bedingungen","agb","mitarbeiter","vertreter","support","mensch","sprechen","reden","hilfe","kundensupport","kundenservice","api","fehler","server","technisch","webseite","kasse","app","r\xFCckgabe","zur\xFCckgeben","bestellstatus","lieferstatus","wo ist meine bestellung","filialen","reparaturen"]},D={questions:["qui","que","quoi","quand","o\xF9","pourquoi","comment","combien","quel","quelle","quels","quelles","peux","peut","peuvent","dois","doit","devrait","pourrait","aurait","sera","est","sont","fait","font","ai","as","a","avons","avez","ont"],pronouns:["je","moi","mon","ma","mes","mien","mienne","nous","notre","nos","n\xF4tre","tu","te","toi","ton","ta","tes","vous","votre","vos","il","lui","son","sa","ses","elle","ils","elles","leur","leurs"],commonVerbs:["est","sont","\xE9tait","\xE9taient","fait","font","faisait","ai","as","a","avons","avez","ont","avait","avaient","besoin","veux","veut","voulons","voulez","veulent","cherche","cherchons","cherchez","aide","aider","sais","sait","savez","savons","pense","pensons","pensez","fais","faisons","faites","cr\xE9e","cr\xE9er","trouve","trouver","ach\xE8te","acheter","utilise","utiliser","installe","installer","r\xE9pare","r\xE9parer","recommande","recommander","dis","dites","montre","montrer","compare","comparer","explique","expliquer","voudrais","voir"],stopwords:["le","la","les","un","une","des","du","au","aux","je","me","mon","est","il","elle","dans","sur","\xE0","pour","de","et","ou","mais","pas","donc","si","par","avec","depuis","que","ce","cette","ces"],support:["commande","commandes","colis","envoi","exp\xE9dition","livraison","suivi","retard\xE9","retard","perdu","manquant","annuler","annulation","modifier","retour","retours","\xE9change","remboursement","remplacement","\xE9ligible","\xE9ligibilit\xE9","garantie","endommag\xE9","cass\xE9","d\xE9fectueux","incorrect","erron\xE9","mot de passe","motdepasse","connexion","identifiant","compte","verrouill\xE9","v\xE9rification","otp","fid\xE9lit\xE9","r\xE9compenses","points","promo","promotion","promotions","coupon","remise","r\xE9duction","r\xE9ductions","cadeau","collaboration","collaborations","paiement","facturation","factur\xE9","facture","re\xE7u","refus\xE9","taille","pointure","ajustement","entretien","stock","disponibilit\xE9","durabilit\xE9","\xE9thique","carri\xE8res","confidentialit\xE9","conditions","agent","repr\xE9sentant","support","humain","parler","aide","support client","service client","api","panne","serveur","technique","site","paiement","app","application","remboursement","retard","site web","question","concernant","couverture","bris\xE9","article","\xE9changer","probl\xE8me","carte","cr\xE9dit","transaction","\xE9chou\xE9e","login","marche","ab\xEEm\xE9e","d'aide","service","client","assistance","tracking","endommage","communaut\xE9","demander","\xE9tiquette","\xE9tudiants","enseignants","rabais","militaires","g\xE9rer","\xE9changes","o\xF9 est ma commande","boutiques","r\xE9parations"],elisionPrefixes:["j","n","qu","l","d","c","m","t","s"]},X={questions:["chi","cosa","che","quando","dove","perch\xE9","perch\xE8","come","quanto","quanti","quante","quale","quali","posso","pu\xF2","possono","devo","deve","dovrebbe","potrebbe","vorrebbe","sar\xE0","ho","ha","hanno","\xE8","sono","fa","fanno","fai"],pronouns:["io","mi","me","mio","mia","miei","mie","noi","ci","nostro","nostra","nostri","nostre","tu","ti","te","tuo","tua","tuoi","tue","voi","vi","vostro","vostra","vostri","vostre","lui","lei","suo","sua","suoi","sue","loro"],commonVerbs:["\xE8","sono","era","erano","fa","fanno","faceva","ha","ho","hai","abbiamo","avete","hanno","aveva","avevano","bisogno","voglio","vuole","vogliamo","volete","vogliono","cerco","cerca","cerchiamo","cercate","aiuto","aiuta","aiutami","aiutare","so","sa","sappiamo","sapete","spieghi","spiega","spiego","spiegate","spieghiamo","penso","pensa","pensiamo","faccio","facciamo","fate","creo","creare","trovo","trova","trovami","trovare","compro","compra","comprami","comprare","uso","usare","installo","installare","riparo","riparare","raccomando","raccomanda","raccomandami","raccomandare","dimmi","dire","mostra","mostrami","mostrare","confronto","confronta","confrontami","confrontare","spiego","spiega","spiegami","spiegare","sto","cercando"],stopwords:["il","lo","la","i","gli","le","un","uno","una","io","mi","mio","\xE8","in","su","a","per","di","da","e","ed","o","ma","non","cos\xEC","se","con","che","questo","questa","questi","queste"],support:["ordine","ordini","pacco","spedizione","consegna","tracciamento","ritardato","ritardo","perso","mancante","annullare","annullamento","modificare","reso","resi","cambio","rimborso","sostituzione","idoneo","idoneit\xE0","garanzia","danneggiato","rotto","difettoso","sbagliato","errato","password","accesso","login","account","bloccato","verifica","otp","fedelt\xE0","premi","punti","promozione","promozioni","promo","coupon","sconto","sconti","regalo","collaborazione","collaborazioni","pagamento","fatturazione","addebitato","fattura","ricevuta","rifiutato","taglia","misura","vestibilit\xE0","cura","scorta","disponibilit\xE0","sostenibilit\xE0","etica","carriere","privacy","termini","agente","rappresentante","supporto","umano","parlare","aiuto","assistenza clienti","servizio clienti","api","guasto","server","tecnico","sito","checkout","app","assistenza","restituzione","stato ordine","cambi","dov'\xE8 il mio ordine","negozi","riparazioni"],elisionPrefixes:["c","l","d","un","m","t","s","all","nell","dell","sull","quell"]},Z={questions:["wie","wat","wanneer","waar","waarom","hoe","hoeveel","welke","welk","kan","kunt","kunnen","zou","zal","moet","heb","heeft","hebben","is","zijn","doe","doet","doen"],pronouns:["ik","mij","me","mijn","wij","we","ons","onze","jij","je","jou","jouw","u","uw","hij","hem","zijn","zij","ze","haar","hen","hun","het"],commonVerbs:["is","zijn","was","waren","doet","doe","doen","deed","deden","heb","heeft","hebben","had","hadden","nodig","wil","willen","wilde","zoek","zoeken","help","helpen","weet","weten","denk","denken","maak","maken","maakte","cre\xEBer","cre\xEBren","vind","vinden","vond","koop","kopen","gebruik","gebruiken","installeer","installeren","repareer","repareren","raad","aanraden","vertel","vertellen","toon","tonen","vergelijk","vergelijken","leg","uitleggen"],stopwords:["de","het","een","ik","mij","mijn","is","in","op","aan","naar","voor","van","en","of","maar","niet","dus","als","door","met","vanaf","dat","dit","deze","die","over"],support:["bestelling","bestellingen","pakket","zending","verzending","levering","tracking","vertraagd","laat","verloren","ontbrekend","annuleren","wijzigen","retour","retourneren","ruil","terugbetaling","restitutie","vervanging","geschikt","geschiktheid","garantie","beschadigd","kapot","defect","verkeerd","onjuist","wachtwoord","inloggen","login","account","geblokkeerd","verificatie","otp","loyaliteit","beloningen","punten","promo","promotie","aanbieding","aanbiedingen","kortingsbon","korting","kortingen","cadeau","cadeaubon","samenwerking","samenwerkingen","verzending","betaling","facturering","gefactureerd","factuur","bonnetje","kassabon","geweigerd","maat","pasvorm","verzorging","voorraad","beschikbaarheid","duurzaamheid","ethiek","carri\xE8res","privacy","voorwaarden","medewerker","vertegenwoordiger","ondersteuning","mens","praten","spreken","hulp","klantenondersteuning","api","storing","server","technisch","website","afrekenen","app","klantenservice","bestelstatus","terugsturen","ruilen","waar is mijn bestelling","winkels","reparaties"]},E={questions:["qui\xE9n","quien","qu\xE9","que","cu\xE1ndo","cuando","d\xF3nde","donde","porqu\xE9","porque","c\xF3mo","como","cu\xE1l","cual","cu\xE1les","cuales","cu\xE1nto","cuanto","cu\xE1ntos","puedo","puede","pueden","podr\xEDa","deber\xEDa","ser\xEDa","ha","han","es","son","hace","hacen"],pronouns:["yo","me","m\xED","mi","m\xEDo","m\xEDa","m\xEDos","m\xEDas","nosotros","nosotras","nos","nuestro","nuestra","nuestros","nuestras","t\xFA","tu","te","ti","tuyo","tuya","tuyos","tuyas","usted","ustedes","vosotros","vosotras","vuestro","vuestra","\xE9l","ella","su","sus","suyo","suya","ellos","ellas","les","los","las","le","la","lo","mu\xE9strame"],commonVerbs:["es","son","era","eran","est\xE1","est\xE1n","hace","hacen","hac\xEDa","ha","he","has","hemos","hab\xE9is","han","hab\xEDa","hab\xEDan","necesito","necesita","necesitamos","necesitan","quiero","quiere","queremos","quer\xE9is","quieren","busco","busca","b\xFAscame","buscamos","buscan","ayuda","ay\xFAdame","ayudar","s\xE9","sabe","sabemos","saben","pienso","piensa","pensamos","hago","hacemos","creo","crear","encuentro","encuentra","encu\xE9ntrame","encontrar","compro","compra","c\xF3mprame","comprar","uso","usar","instalo","instalar","reparo","reparar","recomiendo","recomienda","recomi\xE9ndame","recomendar","dime","decir","muestra","mu\xE9strame","mostrar","comparo","compara","comparar","explico","explica","expl\xEDcame","explicar"],stopwords:["el","la","los","las","un","una","unos","unas","yo","me","mi","es","en","a","al","para","de","del","y","e","o","u","pero","no","as\xED","si","por","con","desde","que","este","esta","estos","estas","sobre"],support:["pedido","pedidos","paquete","env\xEDo","entrega","seguimiento","retrasado","tarde","perdido","faltante","cancelar","cancelaci\xF3n","modificar","devoluci\xF3n","devoluciones","cambio","reembolso","reemplazo","elegible","elegibilidad","garant\xEDa","da\xF1ado","roto","defectuoso","incorrecto","equivocado","contrase\xF1a","acceso","login","cuenta","bloqueada","bloqueado","verificaci\xF3n","otp","fidelidad","recompensas","puntos","promo","promoci\xF3n","cup\xF3n","descuento","regalo","colaboraci\xF3n","colaboraciones","env\xEDo","pago","facturaci\xF3n","cobrado","cargo","factura","recibo","rechazado","talla","tama\xF1o","ajuste","cuidado","inventario","disponibilidad","sostenibilidad","\xE9tica","carreras","privacidad","t\xE9rminos","agente","representante","soporte","humano","hablar","ayuda","soporte al cliente","servicio al cliente","api","fallo","servidor","t\xE9cnico","sitio","pago","app","atenci\xF3n al cliente","estado del pedido","devolver","empleo","trabajo","caracter\xEDstica","art\xEDculo","pregunta","igualan","c\xF3digo","promocional","funciona","sobre","promociones","descuentos","actuales","tengo","militares","agotado","cambios","d\xF3nde est\xE1 mi pedido","tiendas","reparaciones"]},_={"en-gb":z,"en-us":z,"en-ca":z,"de-de":Y,"fr-fr":D,"fr-ca":D,"it-it":X,"nl-nl":Z,"es-es":E,"es-us":E},A="en-us",f=n=>{var e,o;return(o=_[(e=n==null?void 0:n.toLowerCase())!=null?e:A])!=null?o:_[A]};var q=n=>!/\w/.test(n),T=n=>n.normalize("NFD").replace(/[̀-ͯ]/g,""),ee=(n,e)=>{if(!e||e.length===0)return n;let o=new RegExp(`\\b(${e.join("|")})['\u2019](?=[\\p{L}\\p{N}])`,"giu");return n.replace(o,"$1' ")},oe=(n,e)=>e?n.replace(/[\p{L}\p{N}_'’]+/gu,o=>{var r,s;let t=o.replace(/’/g,"'");return(s=(r=e[t])!=null?r:e[o])!=null?s:o}):n,p=(n,e)=>{var s;let o=f(e),t=ee(n,o.elisionPrefixes);return(s=oe(t,o.contractions).match(/[\p{L}\p{N}_'’]+|[^\s\p{L}\p{N}_'’]/gu))!=null?s:[]},m=n=>{let e=[],o=n.tokens.map(T);for(let t of n.phrases){let r=t.split(/\s+/).filter(Boolean).map(T);if(r.length!==0){if(r.length===1){o.includes(r[0])&&e.push(t);continue}for(let s=0;s<=o.length-r.length;s++){let a=!0;for(let i=0;i<r.length;i++)if(o[s+i]!==r[i]){a=!1;break}if(a){e.push(t);break}}}}return e},O=n=>n.reduce((e,o)=>e+o.split(/\s+/).filter(Boolean).length,0),ne="BR:CLARITY",te="chatId",re="0.0.2",V=n=>{var e,o,t;try{let r=JSON.parse((e=n.getItem(ne))!=null?e:"{}");return(t=(o=r==null?void 0:r[te])==null?void 0:o[re])==null?void 0:t.CHAT_ID}catch{return}},I=()=>{var n;if(typeof window!="undefined")return(n=V(window.localStorage))!=null?n:V(window.sessionStorage)};var F=async(n,e)=>{var s;if(!e.apiBaseUrl)return console.log(" checkApi \u2192 true (no apiUrl configured)"),!0;let o=await fetch(`${e.apiBaseUrl}/cocoaas/public/api/query-classifier`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:n,chatId:I()}),signal:AbortSignal.timeout((s=e.apiTimeoutMs)!=null?s:3e3)});if(!o.ok)throw new Error(`query-classifier request failed: ${o.status}`);let t=await o.json(),r=t.label.toLowerCase()==="search";return console.log(` checkApi \u2192 label=${t.label} probability=${t.probability} \u2192 ${r}`),r};var C=(n,e)=>{if(!e.maxLength)return console.log(" checkLength \u2192 true (no maxLength configured)"),!0;let o=p(n).length,t=o<=e.maxLength;return console.log(` checkLength \u2192 ${t} (wordCount=${o} maxLength=${e.maxLength})`),t};var se=(n,e)=>{var o;for(let t of(o=e.blackPunctSet)!=null?o:[])if(n.includes(t))return console.log(` punct "${t}" found in sentence \u2192 false (blacklisted)`),!1;return!0},ae=(n,e)=>{var t,r,s,a,i,u,d;if((t=e.blackWordSet)!=null&&t.has(n))return console.log(` word "${n}" \u2192 false (blacklisted)`),!1;if(((s=(r=e.whiteSet)==null?void 0:r.size)!=null?s:0)>0||((i=(a=e.whiteList)==null?void 0:a.length)!=null?i:0)>0){let l=!!((u=e.whiteSet)!=null&&u.has(n)||(d=e.whiteList)!=null&&d.some(c=>c.toLowerCase()===n));return console.log(` word "${n}" \u2192 ${l} (whitelist check)`),l}return console.log(` word "${n}" \u2192 true`),!0},N=(n,e)=>se(n,e)&&p(n).every(o=>ae(o,e));var S=(n,e)=>{var $,W,j,R,P;let o=p(n,e.locale);if(o.length===0)return!0;let t=f(e.locale),r=($=e.scoreQuestionWords)!=null?$:t.questions,s=(W=e.scorePronouns)!=null?W:t.pronouns,a=(j=e.scoreCommonVerbs)!=null?j:t.commonVerbs,i=(R=e.scoreStopwords)!=null?R:t.stopwords,u=(P=e.scoreSupportWords)!=null?P:t.support,d=m({tokens:o,phrases:u});if(d.length>0)return console.log(` [A] support words: found [${d.join(", ")}] \u2192 conversational (override)`),!1;let l=0,c=0;o.length<=3?(l+=2,console.log(` [B] token count: word count=${o.length} \u22643 \u2192 keyword +2`)):o.length>=6?(c+=2,console.log(` [B] token count: word count=${o.length} \u22656 \u2192 conversational +2`)):console.log(` [B] token count: word count=${o.length} (no score)`);let h=m({tokens:o,phrases:r});h.length>0?(c+=2,console.log(` [C] question words: found [${h.join(", ")}] \u2192 conversational +2`)):console.log(" [C] question words: none");let g=m({tokens:o,phrases:s});g.length>0?(c+=1,console.log(` [D] pronouns: found [${g.join(", ")}] \u2192 conversational +1`)):console.log(" [D] pronouns: none");let L=m({tokens:o,phrases:a});L.length>0?(c+=2,console.log(` [E] common verbs: found [${L.join(", ")}] \u2192 conversational +2`)):console.log(" [E] common verbs: none"),n.includes("?")?(c+=3,console.log(" [F] question mark: found \u2192 conversational +3")):console.log(" [F] question mark: none");let w=O(m({tokens:o,phrases:i})),v=w/o.length;v>.4?(c+=2,console.log(` [G] stopword ratio: ${v.toFixed(2)} (${w}/${o.length}) >0.4 \u2192 conversational +2`)):(l+=1,console.log(` [G] stopword ratio: ${v.toFixed(2)} (${w}/${o.length}) \u22640.4 \u2192 keyword +1`));let k=o.reduce((J,U)=>J+U.length,0)/o.length;k>=6?(l+=1,console.log(` [H] avg token length: ${k.toFixed(2)} \u22656 \u2192 keyword +1`)):console.log(` [H] avg token length: ${k.toFixed(2)} (no score)`);let x=l>=c;return console.log(` scores: keyword=${l} conversational=${c} \u2192 ${x?"keyword":"conversational"}`),x};var b={},ie=async n=>{b={...n};let e=new Set,o=new Set,t=new Set;try{return await Promise.all([n.whiteListJson?fetch(n.whiteListJson).then(r=>r.json()).then(r=>{r.forEach(s=>t.add(s.toLowerCase()))}):null,n.blackListJson?fetch(n.blackListJson).then(r=>r.json()).then(r=>{r.forEach(s=>{let a=s.toLowerCase();q(a)?e.add(a):o.add(a)})}):null]),b={...b,blackJsonPunctSet:e,blackJsonWordSet:o,whiteSet:t},{success:!0}}catch(r){return{success:!1,error:r}}},ce=n=>{var o,t,r;let e={...b,...n!=null?n:{}};return e.blackPunctSet=new Set([...(o=e.blackJsonPunctSet)!=null?o:[]]),e.blackWordSet=new Set([...(t=e.blackJsonWordSet)!=null?t:[]]),(r=e.blackList)==null||r.forEach(s=>{var i,u;let a=s.toLowerCase();q(a)?(i=e.blackPunctSet)==null||i.add(a):(u=e.blackWordSet)==null||u.add(a)}),e.scoreQuestionWords&&(e.scoreQuestionWords=e.scoreQuestionWords.map(s=>s.toLowerCase())),e.scorePronouns&&(e.scorePronouns=e.scorePronouns.map(s=>s.toLowerCase())),e.scoreCommonVerbs&&(e.scoreCommonVerbs=e.scoreCommonVerbs.map(s=>s.toLowerCase())),e.scoreStopwords&&(e.scoreStopwords=e.scoreStopwords.map(s=>s.toLowerCase())),e.scoreSupportWords&&(e.scoreSupportWords=e.scoreSupportWords.map(s=>s.toLowerCase())),e},le=async(n,e)=>{var a,i,u,d,l,c,h,g;let o=ce(e),t=n.toLowerCase(),r=p(t);console.group(`[isSearch] "${n}" | mode=${o.mode} | tokens=[${r.join(", ")}] | locale=${o.locale}`),(o.mode==="mixed"||o.mode==="list")&&console.log(`lists: blackWordSet=${(i=(a=o.blackWordSet)==null?void 0:a.size)!=null?i:0} blackPunctSet=${(d=(u=o.blackPunctSet)==null?void 0:u.size)!=null?d:0} whiteSet=${(c=(l=o.whiteSet)==null?void 0:l.size)!=null?c:0} whiteList=${(g=(h=o.whiteList)==null?void 0:h.length)!=null?g:0}`);let s;return o.mode==="length"?s=C(t,o):o.mode==="mixed"?s=N(t,o)&&C(t,o):o.mode==="score"?s=S(t,o):o.mode==="api"?s=await F(t,o):s=S(t,o),console.log(`\u2192 Result: ${s}`),console.groupEnd(),s},ue={setup:ie,isSearch:le};return M(de);})();
|
|
2
2
|
window.clarityUtils=tmp.clarityUtils;
|
package/dist/index.js
CHANGED
|
@@ -469,8 +469,10 @@ var DE_WORDS = {
|
|
|
469
469
|
"pr\xE4mien",
|
|
470
470
|
"punkte",
|
|
471
471
|
"aktion",
|
|
472
|
+
"aktionen",
|
|
472
473
|
"gutschein",
|
|
473
474
|
"rabatt",
|
|
475
|
+
"rabatte",
|
|
474
476
|
"geschenk",
|
|
475
477
|
"geschenkkarte",
|
|
476
478
|
// Versand / Zahlung / Abrechnung
|
|
@@ -732,10 +734,14 @@ var FR_WORDS = {
|
|
|
732
734
|
"points",
|
|
733
735
|
"promo",
|
|
734
736
|
"promotion",
|
|
737
|
+
"promotions",
|
|
735
738
|
"coupon",
|
|
736
739
|
"remise",
|
|
737
740
|
"r\xE9duction",
|
|
741
|
+
"r\xE9ductions",
|
|
738
742
|
"cadeau",
|
|
743
|
+
"collaboration",
|
|
744
|
+
"collaborations",
|
|
739
745
|
// Livraison / paiement / facturation
|
|
740
746
|
"paiement",
|
|
741
747
|
"facturation",
|
|
@@ -1039,10 +1045,14 @@ var IT_WORDS = {
|
|
|
1039
1045
|
"premi",
|
|
1040
1046
|
"punti",
|
|
1041
1047
|
"promozione",
|
|
1048
|
+
"promozioni",
|
|
1042
1049
|
"promo",
|
|
1043
1050
|
"coupon",
|
|
1044
1051
|
"sconto",
|
|
1052
|
+
"sconti",
|
|
1045
1053
|
"regalo",
|
|
1054
|
+
"collaborazione",
|
|
1055
|
+
"collaborazioni",
|
|
1046
1056
|
// Spedizione / pagamento / fatturazione
|
|
1047
1057
|
"pagamento",
|
|
1048
1058
|
"fatturazione",
|
|
@@ -1270,10 +1280,15 @@ var NL_WORDS = {
|
|
|
1270
1280
|
"punten",
|
|
1271
1281
|
"promo",
|
|
1272
1282
|
"promotie",
|
|
1283
|
+
"aanbieding",
|
|
1284
|
+
"aanbiedingen",
|
|
1273
1285
|
"kortingsbon",
|
|
1274
1286
|
"korting",
|
|
1287
|
+
"kortingen",
|
|
1275
1288
|
"cadeau",
|
|
1276
1289
|
"cadeaubon",
|
|
1290
|
+
"samenwerking",
|
|
1291
|
+
"samenwerkingen",
|
|
1277
1292
|
// Verzending / betaling / facturering
|
|
1278
1293
|
"verzending",
|
|
1279
1294
|
"betaling",
|
|
@@ -1564,6 +1579,8 @@ var ES_WORDS = {
|
|
|
1564
1579
|
"cup\xF3n",
|
|
1565
1580
|
"descuento",
|
|
1566
1581
|
"regalo",
|
|
1582
|
+
"colaboraci\xF3n",
|
|
1583
|
+
"colaboraciones",
|
|
1567
1584
|
// Envío / pago / facturación
|
|
1568
1585
|
"env\xEDo",
|
|
1569
1586
|
"pago",
|
|
@@ -1697,6 +1714,45 @@ var matchPhrases = (a) => {
|
|
|
1697
1714
|
return matched;
|
|
1698
1715
|
};
|
|
1699
1716
|
var countPhraseTokens = (phrases) => phrases.reduce((sum, p) => sum + p.split(/\s+/).filter(Boolean).length, 0);
|
|
1717
|
+
var CHAT_STORAGE_KEY = "BR:CLARITY";
|
|
1718
|
+
var CHAT_ID_NAMESPACE = "chatId";
|
|
1719
|
+
var CHAT_ID_VERSION = "0.0.2";
|
|
1720
|
+
var readChatIdFromStorage = (storage) => {
|
|
1721
|
+
var _a, _b, _c;
|
|
1722
|
+
try {
|
|
1723
|
+
const parsed = JSON.parse((_a = storage.getItem(CHAT_STORAGE_KEY)) != null ? _a : "{}");
|
|
1724
|
+
return (_c = (_b = parsed == null ? void 0 : parsed[CHAT_ID_NAMESPACE]) == null ? void 0 : _b[CHAT_ID_VERSION]) == null ? void 0 : _c.CHAT_ID;
|
|
1725
|
+
} catch {
|
|
1726
|
+
return void 0;
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
var getChatId = () => {
|
|
1730
|
+
var _a;
|
|
1731
|
+
if (typeof window === "undefined") return void 0;
|
|
1732
|
+
return (_a = readChatIdFromStorage(window.localStorage)) != null ? _a : readChatIdFromStorage(window.sessionStorage);
|
|
1733
|
+
};
|
|
1734
|
+
|
|
1735
|
+
// src/modes/api.ts
|
|
1736
|
+
var checkApi = async (value, c) => {
|
|
1737
|
+
var _a;
|
|
1738
|
+
if (!c.apiBaseUrl) {
|
|
1739
|
+
console.log(" checkApi \u2192 true (no apiUrl configured)");
|
|
1740
|
+
return true;
|
|
1741
|
+
}
|
|
1742
|
+
const res = await fetch(`${c.apiBaseUrl}/cocoaas/public/api/query-classifier`, {
|
|
1743
|
+
method: "POST",
|
|
1744
|
+
headers: { "Content-Type": "application/json" },
|
|
1745
|
+
body: JSON.stringify({ text: value, chatId: getChatId() }),
|
|
1746
|
+
signal: AbortSignal.timeout((_a = c.apiTimeoutMs) != null ? _a : 3e3)
|
|
1747
|
+
});
|
|
1748
|
+
if (!res.ok) {
|
|
1749
|
+
throw new Error(`query-classifier request failed: ${res.status}`);
|
|
1750
|
+
}
|
|
1751
|
+
const data = await res.json();
|
|
1752
|
+
const result = data.label.toLowerCase() === "search";
|
|
1753
|
+
console.log(` checkApi \u2192 label=${data.label} probability=${data.probability} \u2192 ${result}`);
|
|
1754
|
+
return result;
|
|
1755
|
+
};
|
|
1700
1756
|
|
|
1701
1757
|
// src/modes/length.ts
|
|
1702
1758
|
var checkLength = (value, c) => {
|
|
@@ -1872,7 +1928,7 @@ var resolveConfig = (config) => {
|
|
|
1872
1928
|
if (merged.scoreSupportWords) merged.scoreSupportWords = merged.scoreSupportWords.map((s) => s.toLowerCase());
|
|
1873
1929
|
return merged;
|
|
1874
1930
|
};
|
|
1875
|
-
var isSearch = (value, config) => {
|
|
1931
|
+
var isSearch = async (value, config) => {
|
|
1876
1932
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
1877
1933
|
const c = resolveConfig(config);
|
|
1878
1934
|
const lower = value.toLowerCase();
|
|
@@ -1890,6 +1946,8 @@ var isSearch = (value, config) => {
|
|
|
1890
1946
|
result = checkList(lower, c) && checkLength(lower, c);
|
|
1891
1947
|
} else if (c.mode === "score") {
|
|
1892
1948
|
result = scoreQuery(lower, c);
|
|
1949
|
+
} else if (c.mode === "api") {
|
|
1950
|
+
result = await checkApi(lower, c);
|
|
1893
1951
|
} else {
|
|
1894
1952
|
result = scoreQuery(lower, c);
|
|
1895
1953
|
}
|