@brainfish-ai/components 0.30.5 → 0.30.6
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/chat-search.d.ts +11 -1
- package/dist/esm/chunks/{ChatSearch.BLZiMiJ3.js → ChatSearch.B3MthUTR.js} +46 -46
- package/dist/esm/chunks/ChatSearch.B3MthUTR.js.map +1 -0
- package/dist/esm/chunks/formatDate.D2xEZm8f.js.map +1 -1
- package/dist/esm/components/chat-search.js +1 -1
- package/dist/esm/global.css +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/stats.html +1 -1
- package/package.json +4 -4
- package/dist/esm/chunks/ChatSearch.BLZiMiJ3.js.map +0 -1
|
@@ -5,35 +5,35 @@ import e,{useState as t,useCallback as r,useMemo as n,useContext as a,createCont
|
|
|
5
5
|
|| ${c} === "boolean" || ${s} === null`).assign(d,n._`[${s}]`)}}a.else(),u(e),a.endIf(),a.if(n._`${d} !== undefined`,()=>{a.assign(s,d),function({gen:e,parentData:t,parentDataProperty:r},a){e.if(n._`${t} !== undefined`,()=>e.assign(n._`${t}[${r}]`,a))}(e,d)})}(e,r,d):u(e)})}return m};const i=new Set(["string","number","integer","boolean","null"]);function c(e,t,r,a=s.Correct){const o=a===s.Correct?n.operators.EQ:n.operators.NEQ;let i;switch(e){case"null":return n._`${t} ${o} null`;case"array":i=n._`Array.isArray(${t})`;break;case"object":i=n._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=c(n._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=c();break;default:return n._`typeof ${t} ${o} ${e}`}return a===s.Correct?i:(0,n.not)(i);function c(e=n.nil){return(0,n.and)(n._`typeof ${t} == "number"`,e,r?n._`isFinite(${t})`:n.nil)}}function l(e,t,r,s){if(1===e.length)return c(e[0],t,r,s);let o;const i=(0,a.toHash)(e);if(i.array&&i.object){const e=n._`typeof ${t} != "object"`;o=i.null?e:n._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else o=n.nil;i.number&&delete i.integer;for(const a in i)o=(0,n.and)(o,c(a,t,r,s));return o}rt.checkDataType=c,rt.checkDataTypes=l;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?n._`{type: ${e}}`:n._`{type: ${t}}`};function u(e){const t=function(e){const{gen:t,data:r,schema:n}=e,s=(0,a.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:e}}(e);(0,r.reportError)(t,d)}return rt.reportTypeError=u,rt}var dt,ut={};function mt(){if(dt)return ut;dt=1,Object.defineProperty(ut,"__esModule",{value:!0}),ut.assignDefaults=void 0;const e=/*@__PURE__*/Qe(),t=/*@__PURE__*/He();function r(r,n,a){const{gen:s,compositeRule:o,data:i,opts:c}=r;if(void 0===a)return;const l=e._`${i}${(0,e.getProperty)(n)}`;if(o)return void(0,t.checkStrictMode)(r,`default is ignored for: ${l}`);let d=e._`${l} === undefined`;"empty"===c.useDefaults&&(d=e._`${d} || ${l} === null || ${l} === ""`),s.if(d,e._`${l} = ${(0,e.stringify)(a)}`)}return ut.assignDefaults=function(e,t){const{properties:n,items:a}=e.schema;if("object"===t&&n)for(const s in n)r(e,s,n[s].default);else"array"===t&&Array.isArray(a)&&a.forEach((t,n)=>r(e,n,t.default))},ut}var pt,ht,ft={},gt={};function yt(){if(pt)return gt;pt=1,Object.defineProperty(gt,"__esModule",{value:!0}),gt.validateUnion=gt.validateArray=gt.usePattern=gt.callValidateCode=gt.schemaProperties=gt.allSchemaProperties=gt.noPropertyInData=gt.propertyInData=gt.isOwnProperty=gt.hasPropFunc=gt.reportMissingProp=gt.checkMissingProp=gt.checkReportMissingProp=void 0;const e=/*@__PURE__*/Qe(),t=/*@__PURE__*/He(),r=/*@__PURE__*/Xe(),n=/*@__PURE__*/He();function a(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,n){return e._`${a(t)}.call(${r}, ${n})`}function o(t,r,n,a){const o=e._`${r}${(0,e.getProperty)(n)} === undefined`;return a?(0,e.or)(o,(0,e.not)(s(t,r,n))):o}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}gt.checkReportMissingProp=function(t,r){const{gen:n,data:a,it:s}=t;n.if(o(n,a,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},gt.checkMissingProp=function({gen:t,data:r,it:{opts:n}},a,s){return(0,e.or)(...a.map(a=>(0,e.and)(o(t,r,a,n.ownProperties),e._`${s} = ${a}`)))},gt.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},gt.hasPropFunc=a,gt.isOwnProperty=s,gt.propertyInData=function(t,r,n,a){const o=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return a?e._`${o} && ${s(t,r,n)}`:o},gt.noPropertyInData=o,gt.allSchemaProperties=i,gt.schemaProperties=function(e,r){return i(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},gt.callValidateCode=function({schemaCode:t,data:n,it:{gen:a,topSchemaRef:s,schemaPath:o,errorPath:i},it:c},l,d,u){const m=u?e._`${t}, ${n}, ${s}${o}`:n,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const h=e._`${m}, ${a.object(...p)}`;return d!==e.nil?e._`${l}.call(${d}, ${h})`:e._`${l}(${h})`};const c=e._`new RegExp`;return gt.usePattern=function({gen:t,it:{opts:r}},a){const s=r.unicodeRegExp?"u":"",{regExp:o}=r.code,i=o(a,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===o.code?c:(0,n.useFunc)(t,o)}(${a}, ${s})`})},gt.validateArray=function(r){const{gen:n,data:a,keyword:s,it:o}=r,i=n.name("valid");if(o.allErrors){const e=n.let("valid",!0);return c(()=>n.assign(e,!1)),e}return n.var(i,!0),c(()=>n.break()),i;function c(o){const c=n.const("len",e._`${a}.length`);n.forRange("i",0,c,a=>{r.subschema({keyword:s,dataProp:a,dataPropType:t.Type.Num},i),n.if((0,e.not)(i),o)})}},gt.validateUnion=function(r){const{gen:n,schema:a,keyword:s,it:o}=r;if(!Array.isArray(a))throw new Error("ajv implementation error");if(a.some(e=>(0,t.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;const i=n.let("valid",!1),c=n.name("_valid");n.block(()=>a.forEach((t,a)=>{const o=r.subschema({keyword:s,schemaProp:a,compositeRule:!0},c);n.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(o,c)||n.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},gt}function vt(){if(ht)return ft;ht=1,Object.defineProperty(ft,"__esModule",{value:!0}),ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;const e=/*@__PURE__*/Qe(),t=/*@__PURE__*/Xe(),r=/*@__PURE__*/yt(),n=/*@__PURE__*/Ye();function a(t){const{gen:r,data:n,it:a}=t;r.if(a.parentData,()=>r.assign(n,e._`${a.parentData}[${a.parentDataProperty}]`))}function s(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return ft.macroKeywordCode=function(t,r){const{gen:n,keyword:a,schema:o,parentSchema:i,it:c}=t,l=r.macro.call(c.self,o,i,c),d=s(n,a,l);!1!==c.opts.validateSchema&&c.self.validateSchema(l,!0);const u=n.name("valid");t.subschema({schema:l,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${a}`,topSchemaRef:d,compositeRule:!0},u),t.pass(u,()=>t.error(!0))},ft.funcKeywordCode=function(o,i){var c;const{gen:l,keyword:d,schema:u,parentSchema:m,$data:p,it:h}=o;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(h,i);const f=!p&&i.compile?i.compile.call(h.self,u,m,h):i.validate,g=s(l,d,f),y=l.let("valid");function v(n=(i.async?e._`await `:e.nil)){const a=h.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);l.assign(y,e._`${n}${(0,r.callValidateCode)(o,g,a,s)}`,i.modifying)}function w(t){var r;l.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:y),t)}o.block$data(y,function(){if(!1===i.errors)v(),i.modifying&&a(o),w(()=>o.error());else{const r=i.async?function(){const t=l.let("ruleErrs",null);return l.try(()=>v(e._`await `),r=>l.assign(y,!1).if(e._`${r} instanceof ${h.ValidationError}`,()=>l.assign(t,e._`${r}.errors`),()=>l.throw(r))),t}():function(){const t=e._`${g}.errors`;return l.assign(t,null),v(e.nil),t}();i.modifying&&a(o),w(()=>function(r,a){const{gen:s}=r;s.if(e._`Array.isArray(${a})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${a} : ${t.default.vErrors}.concat(${a})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)},()=>r.error())}(o,r))}}),o.ok(null!==(c=i.valid)&&void 0!==c?c:y)},ft.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},ft.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},a,s){if(Array.isArray(a.keyword)?!a.keyword.includes(s):a.keyword!==s)throw new Error("ajv implementation error");const o=a.dependencies;if(null==o?void 0:o.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(a.validateSchema){if(!a.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},ft}var wt,bt={};function Et(){if(wt)return bt;wt=1,Object.defineProperty(bt,"__esModule",{value:!0}),bt.extendSubschemaMode=bt.extendSubschemaData=bt.getSubschema=void 0;const e=/*@__PURE__*/Qe(),t=/*@__PURE__*/He();return bt.getSubschema=function(r,{keyword:n,schemaProp:a,schema:s,schemaPath:o,errSchemaPath:i,topSchemaRef:c}){if(void 0!==n&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){const s=r.schema[n];return void 0===a?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${n}`}:{schema:s[a],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}${(0,e.getProperty)(a)}`,errSchemaPath:`${r.errSchemaPath}/${n}/${(0,t.escapeFragment)(a)}`}}if(void 0!==s){if(void 0===o||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:o,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},bt.extendSubschemaData=function(r,n,{dataProp:a,dataPropType:s,data:o,dataTypes:i,propertyName:c}){if(void 0!==o&&void 0!==a)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:l}=n;if(void 0!==a){const{errorPath:o,dataPathArr:i,opts:c}=n;d(l.let("data",e._`${n.data}${(0,e.getProperty)(a)}`,!0)),r.errorPath=e.str`${o}${(0,t.getErrorPath)(a,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${a}`,r.dataPathArr=[...i,r.parentDataProperty]}if(void 0!==o){d(o instanceof e.Name?o:l.let("data",o,!0)),void 0!==c&&(r.propertyName=c)}function d(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}i&&(r.dataTypes=i)},bt.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:s}){void 0!==n&&(e.compositeRule=n),void 0!==a&&(e.createErrors=a),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},bt}var $t,xt,_t={};var kt,Nt,Ct,It,St={exports:{}};function Pt(){if(kt)return St.exports;kt=1;var e=St.exports=function(e,r,n){"function"==typeof r&&(n=r,r={}),t(r,"function"==typeof(n=r.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function t(n,a,s,o,i,c,l,d,u,m){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var p in a(o,i,c,l,d,u,m),o){var h=o[p];if(Array.isArray(h)){if(p in e.arrayKeywords)for(var f=0;f<h.length;f++)t(n,a,s,h[f],i+"/"+p+"/"+f,c,i,p,o,f)}else if(p in e.propsKeywords){if(h&&"object"==typeof h)for(var g in h)t(n,a,s,h[g],i+"/"+p+"/"+r(g),c,i,p,o,g)}else(p in e.keywords||n.allKeys&&!(p in e.skipKeywords))&&t(n,a,s,h,i+"/"+p,c,i,p,o)}s(o,i,c,l,d,u,m)}}function r(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},St.exports}function Tt(){if(Nt)return _t;Nt=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.getSchemaRefs=_t.resolveUrl=_t.normalizeId=_t._getFullPath=_t.getFullPath=_t.inlineRef=void 0;const e=/*@__PURE__*/He(),t=(xt||(xt=1,$t=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,a,s;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(a=n;0!==a--;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(s=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(a=n;0!==a--;)if(!Object.prototype.hasOwnProperty.call(r,s[a]))return!1;for(a=n;0!==a--;){var o=s[a];if(!e(t[o],r[o]))return!1}return!0}return t!=t&&r!=r}),$t),r=Pt(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);_t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!s(e):!!t&&o(e)<=t)};const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(e){for(const t in e){if(a.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(s))return!0;if("object"==typeof r&&s(r))return!0}return!1}function o(t){let r=0;for(const a in t){if("$ref"===a)return 1/0;if(r++,!n.has(a)&&("object"==typeof t[a]&&(0,e.eachItem)(t[a],e=>r+=o(e)),r===1/0))return 1/0}return r}function i(e,t="",r){!1!==r&&(t=d(t));const n=e.parse(t);return c(e,n)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}_t.getFullPath=i,_t._getFullPath=c;const l=/#\/?$/;function d(e){return e?e.replace(l,""):""}_t.normalizeId=d,_t.resolveUrl=function(e,t,r){return r=d(r),e.resolve(t,r)};const u=/^[a-z_][-a-z0-9._]*$/i;return _t.getSchemaRefs=function(e,n){if("boolean"==typeof e)return{};const{schemaId:a,uriResolver:s}=this.opts,o=d(e[a]||n),c={"":o},l=i(s,o,!1),m={},p=new Set;return r(e,{allKeys:!0},(e,t,r,n)=>{if(void 0===n)return;const s=l+t;let o=c[n];function i(t){const r=this.opts.uriResolver.resolve;if(t=d(o?r(o,t):t),p.has(t))throw f(t);p.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?h(e,n.schema,t):t!==d(s)&&("#"===t[0]?(h(e,m[t],t),m[t]=e):this.refs[t]=s),t}function g(e){if("string"==typeof e){if(!u.test(e))throw new Error(`invalid anchor "${e}"`);i.call(this,`#${e}`)}}"string"==typeof e[a]&&(o=i.call(this,e[a])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=o}),m;function h(e,r,n){if(void 0!==r&&!t(e,r))throw f(n)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},_t}function At(){if(Ct)return Ve;Ct=1,Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.getData=Ve.KeywordCxt=Ve.validateFunctionCode=void 0;const e=/*@__PURE__*/et(),t=/*@__PURE__*/lt(),r=/*@__PURE__*/ct(),n=/*@__PURE__*/lt(),a=/*@__PURE__*/mt(),s=/*@__PURE__*/vt(),o=/*@__PURE__*/Et(),i=/*@__PURE__*/Qe(),c=/*@__PURE__*/Xe(),l=/*@__PURE__*/Tt(),d=/*@__PURE__*/He(),u=/*@__PURE__*/Ye();function m({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},s){a.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(i._`"use strict"; ${p(r,a)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,a),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(a)}`,n.$async,()=>e.code(p(r,a)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function h(t,r){g(t)&&(y(t),f(t))?function(e,t){const{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&w(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,l.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=n.const("_errs",c.default.errors);v(e,s),n.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function f({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function g(e){return"boolean"!=typeof e.schema}function y(e){(0,d.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return b(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);b(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function w({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){const s=r.$comment;if(!0===a.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof a.$comment){const r=i.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${a}.schema)`)}}function b(e,t,a,s){const{gen:o,schema:l,data:u,allErrors:m,opts:p,self:h}=e,{RULES:f}=h;function g(d){(0,r.shouldUseGroup)(l,d)&&(d.type?(o.if((0,n.checkDataType)(d.type,u,p.strictNumbers)),E(e,d),1===t.length&&t[0]===d.type&&a&&(o.else(),(0,n.reportTypeError)(e)),o.endIf()):E(e,d),m||o.if(i._`${c.default.errors} === ${s||0}`))}!l.$ref||!p.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(l,f)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{x(e.dataTypes,t)||_(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)x(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&_(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const a in n){const s=n[a];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>$(t,e))&&_(e,`missing type "${r.join(",")}" for keyword "${a}"`)}}}(e,e.dataTypes)}(e,t),o.block(()=>{for(const e of f.rules)g(e);g(f.post)})):o.block(()=>N(e,"$ref",f.all.$ref.definition))}function E(e,t){const{gen:n,schema:s,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,r.shouldUseRule)(s,n)&&N(e,n.keyword,n.definition,t.type)})}function $(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function x(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function _(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}Ve.validateFunctionCode=function(t){g(t)&&(y(t),f(t))?function(e){const{schema:t,opts:r,gen:n}=e;m(e,()=>{r.$comment&&t.$comment&&w(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,d.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${a}(${c.default.vErrors})`)):(t.assign(i._`${n}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);n instanceof i.Name&&e.assign(i._`${t}.items`,n)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):m(t,()=>(0,e.topBoolOrEmptySchema)(t))};class k{constructor(e,t,r){if((0,s.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",S(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,i.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?u.reportExtraError:u.reportError)(this,this.def.error,t)}$dataError(){(0,u.reportError)(this,this.def.$dataError||u.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,u.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:a,def:s}=this;r.if((0,i.or)(i._`${n} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:a,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,n.checkDataTypes)(e,t,s.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}(),function(){if(a.validateSchema){const r=e.scopeValue("validate$data",{ref:a.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,o.getSubschema)(this.it,e);(0,o.extendSubschemaData)(r,this.it,e),(0,o.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return h(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=d.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=d.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function N(e,t,r,n){const a=new k(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,s.funcKeywordCode)(a,r):"macro"in r?(0,s.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(a,r)}Ve.KeywordCxt=k;const C=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function S(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!C.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,s=c.default.rootData}else{const o=I.exec(e);if(!o)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+o[1];if(a=o[2],"#"===a){if(i>=t)throw new Error(u("property/index",i));return n[t-i]}if(i>t)throw new Error(u("data",i));if(s=r[t-i],!a)return s}let o=s;const l=a.split("/");for(const c of l)c&&(s=i._`${s}${(0,i.getProperty)((0,d.unescapeJsonPointer)(c))}`,o=i._`${o} && ${s}`);return o;function u(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return Ve.getData=S,Ve}var Rt=(It||(It=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=K,n=/*@__PURE__*/Qe(),a=/*@__PURE__*/De(),s=/*@__PURE__*/At(),o=/*@__PURE__*/Ye(),i=/*@__PURE__*/Xe(),c="errorMessage",l=new r.Name("emUsed"),d={required:"missingProperty",dependencies:"property",dependentRequired:"property"},u=/\$\{[^}]+\}/,m=/\$\{([^}]+)\}/g,p=/^""\s*\+\s*|\s*\+\s*""$/g;function h(e){return{keyword:c,schemaType:["string","object"],post:!0,code(t){const{gen:h,data:f,schema:g,schemaValue:y,it:v}=t;if(!1===v.createErrors)return;const w=g,b=n.strConcat(i.default.instancePath,v.errorPath);function E(e,t){return n.and(r._`${e}.keyword !== ${c}`,r._`!${e}.${l}`,r._`${e}.instancePath === ${b}`,r._`${e}.keyword in ${t}`,r._`${e}.schemaPath.indexOf(${v.errSchemaPath}) === 0`,r._`/^\\/[^\\/]*$/.test(${e}.schemaPath.slice(${v.errSchemaPath.length}))`)}function $(e,t){const r=[];for(const n in e){const e=t[n];u.test(e)&&r.push([n,_(e)])}return h.object(...r)}function x(e){return u.test(e)?new a._Code(a.safeStringify(e).replace(m,(e,t)=>`" + JSON.stringify(${s.getData(t,v)}) + "`).replace(p,"")):r.stringify(e)}function _(e){return r._`function(){return ${x(e)}}`}h.if(r._`${i.default.errors} > 0`,()=>{if("object"==typeof w){const[a,s]=function(e){let t,r;for(const n in e){if("properties"===n||"items"===n)continue;const a=e[n];if("object"==typeof a){t||(t={});const e=t[n]={};for(const t in a)e[t]=[]}else r||(r={}),r[n]=[]}return[t,r]}(w);s&&function(n){const a=h.const("emErrors",r.stringify(n)),s=h.const("templates",$(n,g));h.forOf("err",i.default.vErrors,e=>h.if(E(e,a),()=>h.code(r._`${a}[${e}.keyword].push(${e})`).assign(r._`${e}.${l}`,!0)));const{singleError:c}=e;if(c){const e=h.let("message",r._`""`),n=h.let("paramsErrors",r._`[]`);d(t=>{h.if(e,()=>h.code(r._`${e} += ${"string"==typeof c?c:";"}`)),h.code(r._`${e} += ${u(t)}`),h.assign(n,r._`${n}.concat(${a}[${t}])`)}),o.reportError(t,{message:e,params:r._`{errors: ${n}}`})}else d(e=>o.reportError(t,{message:u(e),params:r._`{errors: ${a}[${e}]}`}));function d(e){h.forIn("key",a,t=>h.if(r._`${a}[${t}].length`,()=>e(t)))}function u(e){return r._`${e} in ${s} ? ${s}[${e}]() : ${y}[${e}]`}}(s),a&&function(e){const n=h.const("emErrors",r.stringify(e)),a=[];for(const t in e)a.push([t,$(e[t],g[t])]);const s=h.const("templates",h.object(...a)),c=h.scopeValue("obj",{ref:d,code:r.stringify(d)}),u=h.let("emPropParams"),m=h.let("emParamsErrors");h.forOf("err",i.default.vErrors,e=>h.if(E(e,n),()=>{h.assign(u,r._`${c}[${e}.keyword]`),h.assign(m,r._`${n}[${e}.keyword][${e}.params[${u}]]`),h.if(m,()=>h.code(r._`${m}.push(${e})`).assign(r._`${e}.${l}`,!0))})),h.forIn("key",n,e=>h.forIn("keyProp",r._`${n}[${e}]`,a=>{h.assign(m,r._`${n}[${e}][${a}]`),h.if(r._`${m}.length`,()=>{const n=h.const("tmpl",r._`${s}[${e}] && ${s}[${e}][${a}]`);o.reportError(t,{message:r._`${n} ? ${n}() : ${y}[${e}][${a}]`,params:r._`{errors: ${m}}`})})}))}(a),function(e){const{props:a,items:s}=e;if(!a&&!s)return;const d=r._`typeof ${f} == "object"`,u=r._`Array.isArray(${f})`,m=h.let("emErrors");let p,v;const w=h.let("templates");function E(e,t){h.assign(m,r.stringify(e)),h.assign(w,$(e,t))}a&&s?(p=h.let("emChildKwd"),h.if(d),h.if(u,()=>{E(s,g.items),h.assign(p,r.str`items`)},()=>{E(a,g.properties),h.assign(p,r.str`properties`)}),v=r._`[${p}]`):s?(h.if(u),E(s,g.items),v=r._`.items`):a&&(h.if(n.and(d,n.not(u))),E(a,g.properties),v=r._`.properties`),h.forOf("err",i.default.vErrors,e=>function(e,t,a){h.if(n.and(r._`${e}.keyword !== ${c}`,r._`!${e}.${l}`,r._`${e}.instancePath.indexOf(${b}) === 0`),()=>{const n=h.scopeValue("pattern",{ref:/^\/([^/]*)(?:\/|$)/,code:r._`new RegExp("^\\\/([^/]*)(?:\\\/|$)")`}),s=h.const("emMatches",r._`${n}.exec(${e}.instancePath.slice(${b}.length))`),o=h.const("emChild",r._`${s} && ${s}[1].replace(/~1/g, "/").replace(/~0/g, "~")`);h.if(r._`${o} !== undefined && ${o} in ${t}`,()=>a(o))})}(e,m,t=>h.code(r._`${m}[${t}].push(${e})`).assign(r._`${e}.${l}`,!0))),h.forIn("key",m,e=>h.if(r._`${m}[${e}].length`,()=>{o.reportError(t,{message:r._`${e} in ${w} ? ${w}[${e}]() : ${y}${v}[${e}]`,params:r._`{errors: ${m}[${e}]}`}),h.assign(r._`${i.default.vErrors}[${i.default.errors}-1].instancePath`,r._`${b} + "/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`)})),h.endIf()}(function({properties:e,items:t}){const r={};if(e){r.props={};for(const t in e)r.props[t]=[]}if(t){r.items={};for(let e=0;e<t.length;e++)r.items[e]=[]}return r}(w))}const a="string"==typeof w?w:w._;a&&function(e){const a=h.const("emErrs",r._`[]`);h.forOf("err",i.default.vErrors,e=>h.if(function(e){return n.and(r._`${e}.keyword !== ${c}`,r._`!${e}.${l}`,n.or(r._`${e}.instancePath === ${b}`,n.and(r._`${e}.instancePath.indexOf(${b}) === 0`,r._`${e}.instancePath[${b}.length] === "/"`)),r._`${e}.schemaPath.indexOf(${v.errSchemaPath}) === 0`,r._`${e}.schemaPath[${v.errSchemaPath}.length] === "/"`)}(e),()=>h.code(r._`${a}.push(${e})`).assign(r._`${e}.${l}`,!0))),h.if(r._`${a}.length`,()=>o.reportError(t,{message:x(e),params:r._`{errors: ${a}}`}))}(a),e.keepErrors||function(){const e=h.const("emErrs",r._`[]`);h.forOf("err",i.default.vErrors,t=>h.if(r._`!${t}.${l}`,()=>h.code(r._`${e}.push(${t})`))),h.assign(i.default.vErrors,e).assign(i.default.errors,r._`${e}.length`)}()})},metaSchema:{anyOf:[{type:"string"},{type:"object",properties:{properties:{$ref:"#/$defs/stringMap"},items:{$ref:"#/$defs/stringList"},required:{$ref:"#/$defs/stringOrMap"},dependencies:{$ref:"#/$defs/stringOrMap"}},additionalProperties:{type:"string"}}],$defs:{stringMap:{type:"object",additionalProperties:{type:"string"}},stringOrMap:{anyOf:[{type:"string"},{$ref:"#/$defs/stringMap"}]},stringList:{type:"array",items:{type:"string"}}}}}}const f=(e,t={})=>{if(!e.opts.allErrors)throw new Error("ajv-errors: Ajv option allErrors must be true");if(e.opts.jsPropertySyntax)throw new Error("ajv-errors: ajv option jsPropertySyntax is not supported");return e.addKeyword(h(t))};t.default=f,e.exports=f,e.exports.default=f}(Re,Re.exports)),Re.exports);const jt=/*@__PURE__*/B(Rt);var Ot=function(e,t){for(var r={},n=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var n=e.instancePath.substring(1).replace(/\//g,".");if(r[n]||(r[n]={message:e.message,type:e.keyword}),t){var a=r[n].types,s=a&&a[e.keyword];r[n]=U(n,t,r,e.keyword,s?[].concat(s,e.message||""):e.message)}},a=function(){var t=e[s];"errorMessage"===t.keyword?t.params.errors.forEach(function(e){e.message=t.message,n(e)}):n(t)},s=0;s<e.length;s+=1)a();return r},Dt=function(e,t,r){return void 0===r&&(r={}),function(n,a,s){try{var o=new K(Object.assign({},{allErrors:!0,validateSchema:!0},t));jt(o);var i=o.compile(Object.assign({$async:r&&"async"===r.mode},e)),c=i(n);return s.shouldUseNativeValidation&&V({},s),Promise.resolve(c?{values:n,errors:{}}:{values:{},errors:q(Ot(i.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)})}catch(l){return Promise.reject(l)}}};function zt({block:t}){const r=e.useMemo(()=>function(e){const t=structuredClone(e);t.errorMessage="This field is required";for(const[r,n]of Object.entries(t.properties??{}))t.required?.includes(r)&&"string"===n.type&&(n.minLength=n.minLength||1,n.errorMessage=n.errorMessage||{minLength:"This field is required"}),"number"===n.type&&(n.errorMessage=n.errorMessage||{type:"Please enter a valid number"});return t}(t.schema),[t.schema]),{inputs:n=[],initialValues:a,state:s}=t,o="ready"===s,i="processing"===s,c="completed"===s,l=Object.entries(a).reduce((e,[t,r])=>("string"==typeof r&&""===r.trim()||(e[t]=r),e),{}),{register:d,control:u,handleSubmit:m,formState:{errors:p}}=Q({defaultValues:l,resolver:Dt(r,{removeAdditional:!0})}),h=n.map(t=>{const{name:r,required:n,schema:a,ui:s}=t,i=`${a.title??r}${n?"*":""}`,c=a.description,l=p[r],m=l?.message;let h=c?String(c):null;l&&(h=c?/* @__PURE__ */e.createElement(e.Fragment,null,c," - ",/* @__PURE__ */e.createElement("span",{className:"italic"},m)):m);const f=s?.type||"text",g={valueAsNumber:"number"===f||void 0};/* @__PURE__ */
|
|
6
6
|
return e.createElement("div",{key:r,className:"py-2 flex flex-col gap-2"},/* @__PURE__ */e.createElement(G,{htmlFor:r},i),"datepicker"===f?/* @__PURE__ */e.createElement(M,{control:u,name:r,render:({field:t})=>/* @__PURE__ */e.createElement(Y,{date:t.value&&"string"==typeof t.value?new Date(t.value):void 0,setDate:e=>{e?t.onChange(e.toISOString()):t.onChange(void 0)},className:Z("!bg-transparent",{"border-red-600":!!l})})}):"textarea"===f?/* @__PURE__ */e.createElement(W,{disabled:!o,rows:2,maxLength:1e4,className:Z("!bg-transparent",{"border-red-600":!!l}),...d(r,g),"aria-invalid":!!l,"aria-required":n}):"select"===f?/* @__PURE__ */e.createElement(M,{control:u,name:r,render:({field:t})=>/* @__PURE__ */e.createElement(J,{options:a.oneOf?.map(e=>({label:e.title,value:e.const}))??[],className:Z("!bg-transparent",{"border-red-600":!!l}),value:t.value,onChange:e=>t.onChange(e)})}):/* @__PURE__ */e.createElement(H,{type:f,disabled:!o,className:Z({"border-red-600":!!l}),...d(r,g),"aria-invalid":!!l,"aria-required":n}),h&&/* @__PURE__ */e.createElement("span",{className:Z("flex text-sm leading-6 font-medium gap-1.5 items-center",{"text-red-600 dark:text-white":!!l})},l&&/* @__PURE__ */e.createElement(w,{weight:"fill",size:20,className:"inline-block align-middle text-red-600"}),
|
|
7
7
|
/* @__PURE__ */e.createElement("span",null,h)))});/* @__PURE__ */
|
|
8
|
-
return e.createElement("div",{className:"relative"},/* @__PURE__ */e.createElement("form",{className:"flex flex-col justify-stretch",onSubmit:e=>(e.preventDefault(),t.onSubmit&&m(t.onSubmit)(e),!1)},h,/* @__PURE__ */e.createElement("div",{className:"mt-4"},/* @__PURE__ */e.createElement(v,{type:"submit",variant:"dark",disabled:!o,className:"w-full rounded-s"},o&&"Submit",i&&"Processing...",c&&"Completed"))))}function Lt({block:e}){return null}const Ft=({text:e=""}={})=>({id:ee(),type:"markdown-text",text:e}),Ut=e=>"markdown-text"===e.type,Qt=e=>e.filter(Ut).map(e=>e.text).join("\n\n---\n\n"),Mt=e=>"action-input-form"===e.type,Vt="answers/set_answers",qt="answers/clear_all",Kt="answers/create_empty_answer",Bt="answers/append_block",Ht="answers/append_stream_chunk",Gt="answers/update_search_results",Wt="answers/set_follow_up_questions",Jt="answers/finish_streaming",Zt="answers/set_error_state",Xt="answers/set_user_feedback",Yt="answers/clear_user_feedback",er="answers/mark_as_uncertain",tr="answers/no_articles_found",rr="answers/request_action_inputs",nr="answers/invoke_action",ar="answers/add_action_buttons",sr="answers/set_awaiting_knowledge_group",or="answers/set_knowledge_group_selected",ir=()=>({type:qt}),
|
|
9
|
-
return e.createElement(
|
|
8
|
+
return e.createElement("div",{className:"relative"},/* @__PURE__ */e.createElement("form",{className:"flex flex-col justify-stretch",onSubmit:e=>(e.preventDefault(),t.onSubmit&&m(t.onSubmit)(e),!1)},h,/* @__PURE__ */e.createElement("div",{className:"mt-4"},/* @__PURE__ */e.createElement(v,{type:"submit",variant:"dark",disabled:!o,className:"w-full rounded-s"},o&&"Submit",i&&"Processing...",c&&"Completed"))))}function Lt({block:e}){return null}const Ft=({text:e=""}={})=>({id:ee(),type:"markdown-text",text:e}),Ut=e=>"markdown-text"===e.type,Qt=e=>e.filter(Ut).map(e=>e.text).join("\n\n---\n\n"),Mt=e=>"action-input-form"===e.type,Vt="answers/set_answers",qt="answers/clear_all",Kt="answers/create_empty_answer",Bt="answers/append_block",Ht="answers/append_stream_chunk",Gt="answers/update_search_results",Wt="answers/set_follow_up_questions",Jt="answers/finish_streaming",Zt="answers/set_error_state",Xt="answers/set_user_feedback",Yt="answers/clear_user_feedback",er="answers/mark_as_uncertain",tr="answers/no_articles_found",rr="answers/request_action_inputs",nr="answers/invoke_action",ar="answers/add_action_buttons",sr="answers/set_awaiting_knowledge_group",or="answers/set_knowledge_group_selected",ir="answers/set_status_message",cr=()=>({type:qt}),lr=({searchQueryId:e,results:t,index:r,state:n})=>({type:Gt,payload:{searchQueryId:e,results:t,index:r,state:n}}),dr=({text:e,index:t})=>({type:Ht,payload:{text:e,index:t}}),ur=({error:e,index:t})=>({type:Zt,payload:{error:e,index:t}}),mr=({index:e}={})=>({type:Jt,payload:{index:e}}),pr=({uncertaintyText:e,index:t})=>({type:er,payload:{uncertaintyText:e,index:t}}),hr=({index:e}={})=>({type:nr,payload:{index:e}}),fr=({index:e}={})=>({type:tr,payload:{index:e}}),gr=({message:e,index:t})=>({type:ir,payload:{message:e,index:t}}),yr=({searchIntentId:e,actionId:t,inputs:r,schema:n,initialValues:a,onSubmit:s,index:o})=>({type:rr,payload:{searchIntentId:e,actionId:t,inputs:r,schema:n,initialValues:a,onSubmit:s,index:o}}),vr=({searchIntentId:e,actions:t,index:r})=>({type:ar,payload:{searchIntentId:e,actions:t,index:r}}),wr=(e,t)=>e.at(t??-1),br=e=>e.blocks.filter(Ut).at(-1),Er=[],$r=(e,t)=>{switch(t.type){case Vt:return e.length=0,void e.push(...t.payload.answers);case qt:return void(e.length=0);case Kt:return void e.push({id:"pending-"+ee(),state:"fetching-search-results",question:t.payload.query,blocks:[Ft()],isUncertain:!1,attachments:t.payload.attachments});case Gt:{const r=wr(e,t.payload.index);return void(r&&(r.searchQueryId=t.payload.searchQueryId,r.searchResults=t.payload.results,r.state=t.payload.state||"fetching-stream"))}case Ht:{const r=wr(e,t.payload.index),n=r&&br(r);return void(r&&!r.isUncertain&&n&&Ut(n)&&(r.state="streaming",n.text+=t.payload.text,delete r.statusMessage))}case Zt:{const r=wr(e,t.payload.index??-1),n=r&&br(r);return void(n&&Ut(n)&&(n.text=t.payload.error,r.state="completed",r.hasError=!0,delete r.statusMessage))}case Bt:{const r=wr(e,t.payload.index);return void(r&&r.blocks.push(t.payload.block))}case Jt:{const r=wr(e,t.payload.index);if(r){("streaming"===r.state||"fetching-search-results"===r.state||"fetching-stream"===r.state)&&(r.state="completed"),delete r.statusMessage}return}case er:{const r=wr(e,t.payload.index),n=r&&br(r);return void(r&&n&&Ut(n)&&(r.isUncertain=!0,n.text=t.payload.uncertaintyText))}case Xt:{const r=wr(e,t.payload.index);return void(r&&(r.feedback=t.payload.feedback))}case Yt:{const r=wr(e,t.payload.index);return void(r&&delete r.feedback)}case rr:{const r=wr(e,t.payload.index);return void(r&&(r.state="getting-action-inputs",r.searchIntentId=t.payload.searchIntentId,r.blocks.push((({actionId:e,initialValues:t,onSubmit:r,inputs:n,schema:a})=>({id:ee(),type:"action-input-form",state:"ready",actionId:e,initialValues:t,onSubmit:r,inputs:n,schema:a}))({actionId:t.payload.actionId,schema:t.payload.schema,initialValues:t.payload.initialValues,onSubmit:t.payload.onSubmit,inputs:t.payload.inputs}))))}case ar:{const r=wr(e,t.payload.index);return void(r&&(r.searchIntentId=t.payload.searchIntentId,r.actions=t.payload.actions.map(e=>({...e,type:e.type})),r.blocks.push({id:ee(),type:"action-buttons"})))}case nr:{const r=wr(e,t.payload.index);if(!r)return;const n=r.blocks.findIndex(Mt);return-1!==n&&(r.state="fetching-stream",r.blocks.splice(n,1,Ft())),void delete r.statusMessage}case Wt:{const r=wr(e,t.payload.index);return void(r&&(r.followUpQuestions=t.payload.questions))}case tr:{const r=wr(e,t.payload.index),n=r&&br(r);return n&&Ut(n)&&(n.text+="No articles found."),void(r&&(r.state="completed"))}case sr:{const r=wr(e,t.payload.index);return void(r&&(r.state="awaiting-knowledge-group"))}case or:{const r=wr(e,t.payload.index);return void(r&&(r.state="fetching-search-results"))}case ir:{const r=wr(e,t.payload.index);return void(r&&(r.statusMessage=t.payload.message))}default:throw new Error(`Answer List Reducer: unknown action type '${t.type}'`)}},xr="conversation",_r=s(void 0),kr=({children:a,searchPath:s,contentTypeEndpoint:o,widgetKey:i})=>{const[c,l]=t(""),[d,u]=t(""),[m,p]=t(""),[h,f]=t(!1),[g,y]=t(!1),[v,w]=te($r,Er),[b,E]=t(0),[$,x]=t(!1),[_,k]=t(""),[N,C]=t(!1),{conversationId:I,setConversationId:S,clearConversationId:P}=((e,n)=>{const a=re(xr),[s,o]=t(a??void 0);return{conversationId:s,setConversationId:r(t=>{const r=new URL(window.location.href);e&&(r.pathname=e),t?r.searchParams.set(xr,t):r.searchParams.delete(xr);const a=r.toString();window.history.replaceState({...window.history.state,newUrl:a,url:a},"",a),o(t),"undefined"!=typeof window&&window.parent!==window&&window.parent.postMessage({type:"CONVERSATION_CHANGED",conversationId:t,widgetKey:n},"*")},[e,n]),clearConversationId:r(()=>{const e=new URL(window.location.href);e.searchParams.delete(xr);const t=e.toString();window.history.replaceState({...window.history.state,newUrl:t,url:t},"",t),o(void 0),"undefined"!=typeof window&&window.parent!==window&&window.parent.postMessage({type:"CONVERSATION_CHANGED",conversationId:"",widgetKey:n},"*")},[n])}})(s,i),T=n(()=>({query:c,setQuery:l,queryId:d,setQueryId:u,followUpQuery:m,setFollowUpQuery:p,isSearching:h,setIsSearching:f,showResults:g,setShowResults:y,answers:v,answerListDispatch:w,activeAnswerIndex:b,setActiveAnswerIndex:E,conversationId:I,setConversationId:S,clearConversationId:P,isLoadingConversation:$,setIsLoadingConversation:x,loadError:_,setLoadError:k,showMobileCloseWidgetButton:N,setShowMobileCloseWidgetButton:C,contentTypeEndpoint:o}),[c,d,m,h,g,v,w,b,I,S,P,$,_,N,o]);/* @__PURE__ */
|
|
9
|
+
return e.createElement(_r.Provider,{value:T},a)},Nr=()=>{const e=a(_r);if(!e)throw new Error("useChatSearch must be used within a ChatSearchProvider");return e};function Cr({block:t,redirectRules:r,state:n}){const{contentTypeEndpoint:a}=Nr();if(!t.text||""===t.text.trim())/* @__PURE__ */
|
|
10
10
|
return e.createElement("div",{className:"w-full py-4"},/* @__PURE__ */e.createElement("div",{className:"space-y-4"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement("div",{className:"h-4 rounded w-3/4 shimmer"}),/* @__PURE__ */e.createElement("div",{className:"h-4 rounded w-full shimmer"}),/* @__PURE__ */e.createElement("div",{className:"h-4 rounded w-5/6 shimmer"}))));const{text:s}=t;/* @__PURE__ */
|
|
11
|
-
return e.createElement("div",{className:"w-full"},/* @__PURE__ */e.createElement("div",{className:"prose prose-sm max-w-none text-foreground"},/* @__PURE__ */e.createElement(z,{message:{content:s},redirectRules:r,isStreaming:"streaming"===n,contentTypeEndpoint:a})))}function
|
|
12
|
-
return e.createElement(
|
|
11
|
+
return e.createElement("div",{className:"w-full"},/* @__PURE__ */e.createElement("div",{className:"prose prose-sm max-w-none text-foreground"},/* @__PURE__ */e.createElement(z,{message:{content:s},redirectRules:r,isStreaming:"streaming"===n,contentTypeEndpoint:a})))}function Ir({block:t,redirectRules:r,state:n}){switch(t.type){case"markdown-text":/* @__PURE__ */
|
|
12
|
+
return e.createElement(Cr,{block:t,redirectRules:r,state:n});case"action-buttons":/* @__PURE__ */
|
|
13
13
|
return e.createElement(Lt,{block:t});case"action-input-form":/* @__PURE__ */
|
|
14
|
-
return e.createElement(zt,{block:t});default:return null}}const
|
|
14
|
+
return e.createElement(zt,{block:t});default:return null}}const Sr={xs:{container:"size-12",spinner:"size-3",close:"top-0.5 right-0.5 p-0.5",closeIcon:"size-2"},sm:{container:"size-16",spinner:"size-4",close:"top-0.5 right-0.5 p-0.5",closeIcon:"size-2.5"},md:{container:"size-20",spinner:"size-5",close:"top-1 right-1 p-1",closeIcon:"size-3"}};function Pr({items:t,size:r="sm",onRemove:n,className:a}){if(0===t.length)return null;const s=Sr[r];/* @__PURE__ */
|
|
15
15
|
return e.createElement("div",{className:Z("flex gap-2 overflow-x-auto",a)},t.map(t=>/* @__PURE__ */e.createElement("div",{key:t.id,className:Z("relative group rounded-lg overflow-hidden flex-shrink-0",s.container)},/* @__PURE__ */e.createElement("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:Z(!t.url&&"pointer-events-none")},
|
|
16
16
|
/* @__PURE__ */e.createElement("img",{src:t.src,alt:t.alt||"Attachment",className:"w-full h-full object-cover"})),"uploading"===t.status&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40"},/* @__PURE__ */e.createElement("div",{className:Z("animate-spin rounded-full border-[2.5px] border-black/30 border-t-white",s.spinner)})),n&&/* @__PURE__ */e.createElement("button",{onClick:()=>n(t.id),className:Z("absolute rounded-full opacity-0","group-hover:opacity-100 transition-opacity duration-200","hover:bg-black/70 bg-black/50",s.close)},
|
|
17
|
-
/* @__PURE__ */e.createElement(b,{className:Z("text-white",s.closeIcon),"aria-label":"Remove attachment"})))))}const
|
|
18
|
-
/* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border divide-y divide-dark-300"},t.map((t,n)=>{const a=e=>{r(t,e)},s=`${t.label}-${n}`.replace(/\s+/g,"-");switch(t.type){case
|
|
19
|
-
return e.createElement(
|
|
20
|
-
return e.createElement(
|
|
21
|
-
return e.createElement(
|
|
22
|
-
return e.createElement(
|
|
23
|
-
return e.createElement(
|
|
24
|
-
return e.createElement(
|
|
25
|
-
return e.createElement(
|
|
26
|
-
return e.createElement(
|
|
27
|
-
return e.createElement(
|
|
28
|
-
return e.createElement("div",{className:"p-4"},/* @__PURE__ */e.createElement(
|
|
17
|
+
/* @__PURE__ */e.createElement(b,{className:Z("text-white",s.closeIcon),"aria-label":"Remove attachment"})))))}const Tr=d(v);function Ar({groups:t,onGroupSelect:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full px-4 py-3"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground mb-2 text-right"},"Please select an option"),/* @__PURE__ */e.createElement("div",{className:"flex flex-wrap justify-end gap-2"},t.map((t,n)=>/* @__PURE__ */e.createElement(Tr,{key:t.id,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:.05*n},onClick:()=>r(t),variant:"outline",className:"border-border font-normal h-auto rounded-full px-4 py-1.5 text-sm"},t.name)))):null}var Rr=/* @__PURE__ */(e=>(e.CallPhone="call_phone",e.OpenUrl="open_url",e.SendEmail="send_email",e.RunCallback="run_callback",e.LaunchIntercomChat="launch_intercom_chat",e.LaunchZendeskChat="launch_zendesk_chat",e.LaunchZendeskMessenger="launch_zendesk_messenger",e.LaunchFreshdesk="launch_freshdesk",e.LaunchSupportTicketForm="launch_support_ticket_form",e.LaunchZendeskSunshineChat="launch_zendesk_sunshine_chat",e))(Rr||{}),jr=/* @__PURE__ */(e=>(e.Link="link",e.Email="email",e.Phone="phone",e.Callback="callback",e.Function="function",e.ZendeskChat="zendesk_chat",e.ZendeskMessenger="zendesk_messenger",e.IntercomChat="intercom_chat",e.Freshdesk="freshdesk",e.ZendeskSunshineChat="zendesk_sunshine_chat",e))(jr||{});const Or=d(v),Dr=()=>{window.Brainfish?.HelpWidget?.close&&window.Brainfish.HelpWidget.close()},zr=({icon:t,label:r,index:n,onClick:a,showArrowOut:s=!1,asChild:o=!1,children:i})=>/* @__PURE__ */e.createElement(Or,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},className:"w-full text-left h-12 text-base [&_svg]:size-6",variant:"ghost",onClick:a,asChild:o},o?i:/* @__PURE__ */e.createElement(e.Fragment,null,t&&/* @__PURE__ */e.createElement(ae,{iconName:t}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},r),s&&/* @__PURE__ */e.createElement(ae,{iconName:"ArrowSquareOut"}))),Lr=({href:t,icon:r,label:n,index:a,onClick:s})=>/* @__PURE__ */e.createElement(zr,{icon:r,label:n,index:a,onClick:s,asChild:!0},/* @__PURE__ */e.createElement("a",{href:t,target:"_blank",rel:"noopener noreferrer"},r&&/* @__PURE__ */e.createElement(ae,{iconName:r}),/* @__PURE__ */e.createElement("span",{className:"flex-grow"},n),/* @__PURE__ */e.createElement(ae,{iconName:"ArrowSquareOut"}))),Fr=({nextBestActions:t,onActionClick:r})=>t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
|
|
18
|
+
/* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border divide-y divide-dark-300"},t.map((t,n)=>{const a=e=>{r(t,e)},s=`${t.label}-${n}`.replace(/\s+/g,"-");switch(t.type){case jr.Email:/* @__PURE__ */
|
|
19
|
+
return e.createElement(Lr,{key:s,href:`mailto:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case jr.Link:/* @__PURE__ */
|
|
20
|
+
return e.createElement(Lr,{key:s,href:L(t.value),icon:t.icon,label:t.label,index:n,onClick:()=>a()});case jr.Phone:/* @__PURE__ */
|
|
21
|
+
return e.createElement(Lr,{key:s,href:`tel:${t.value}`,icon:t.icon,label:t.label,index:n,onClick:()=>a()});case jr.ZendeskChat:/* @__PURE__ */
|
|
22
|
+
return e.createElement(zr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(Dr(),window.zE("webWidget","open"),a(!0)):(console.error("Zendesk Chat is not loaded. Make sure you've included the Zendesk Chat script in your website."),a(!1))}});case jr.ZendeskMessenger:/* @__PURE__ */
|
|
23
|
+
return e.createElement(zr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.zE?(Dr(),window.zE("messenger","open"),a(!0)):(console.error("Zendesk Messenger is not loaded. Make sure you've included the Zendesk Messenger script in your website."),a(!1))}});case jr.IntercomChat:/* @__PURE__ */
|
|
24
|
+
return e.createElement(zr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.Intercom?(Dr(),window.Intercom("show"),a(!0)):(console.error("Intercom is not loaded. Make sure you've included the Intercom script in your website."),a(!1))}});case jr.Freshdesk:/* @__PURE__ */
|
|
25
|
+
return e.createElement(zr,{key:s,icon:t.icon,label:t.label,index:n,onClick:()=>{window.fcWidget?(Dr(),setTimeout(()=>{window.fcWidget.open(),window.fcWidget.show()},300),a(!0)):(console.error("Freshdesk is not loaded. Make sure you've included the Freshdesk script in your website."),a(!1))}});case jr.ZendeskSunshineChat:/* @__PURE__ */
|
|
26
|
+
return e.createElement(zr,{key:s,icon:"CalendarBlank",label:t.label,index:n,onClick:()=>a()});default:/* @__PURE__ */
|
|
27
|
+
return e.createElement(zr,{key:s,icon:"ArrowCircleRight",label:t.label,index:n,onClick:()=>a(),showArrowOut:!0})}}))):null,Ur=({actions:r,nextBestActions:n,isLastAnswer:a,handleActionClick:s,searchQueryId:o,searchIntentId:i,question:c,answer:l})=>{const d=r&&r.length>0,u=n&&a&&n.length>0,[m]=t(d||u);if(!m)return null;let p=[];if(d&&(p=r.map(e=>{const t={...e,searchIntentId:i},r=(e=>{const t={[Rr.CallPhone]:{type:jr.Phone,icon:"Phone",getValue:e=>e.action?.options?.phoneNumber||e.id,getLabel:e=>e.action?.options?.title||e.type},[Rr.SendEmail]:{type:jr.Email,icon:"EnvelopeSimple",getValue:e=>e.action?.options?.to||e.id,getLabel:e=>e.action?.options?.title||e.type},[Rr.OpenUrl]:{type:jr.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type},[Rr.RunCallback]:{type:jr.Callback,icon:"Sparkle",getValue:e=>JSON.stringify({actionId:e.id,searchIntentId:e.searchIntentId}),getLabel:e=>e.action?.options?.title||"Run Action"},[Rr.LaunchZendeskChat]:{type:jr.ZendeskChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[Rr.LaunchZendeskMessenger]:{type:jr.ZendeskMessenger,icon:"ChatCircleDots",getValue:e=>e.action?.options?.embedKey||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[Rr.LaunchIntercomChat]:{type:jr.IntercomChat,icon:"ChatCircleDots",getValue:e=>e.action?.options?.appId||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[Rr.LaunchFreshdesk]:{type:jr.Freshdesk,icon:"ChatCircleDots",getValue:e=>e.action?.options?.token||e.id,getLabel:e=>e.action?.options?.title||"Chat with us"},[Rr.LaunchSupportTicketForm]:{type:jr.Link,icon:"Notepad",getValue:e=>e.action?.options?.formUrl||e.id,getLabel:e=>e.action?.options?.title||"Submit a ticket"},[Rr.LaunchZendeskSunshineChat]:{type:jr.ZendeskSunshineChat,icon:"CalendarBlank",getValue:e=>JSON.stringify({actionId:e.id,requireConfirmation:Boolean(e.action?.options?.requireConfirmation)}),getLabel:e=>e.action?.options?.title||"Speak to an expert"}},r=t[e.type]||{type:jr.Link,icon:"Link",getValue:e=>e.action?.options?.url||e.id,getLabel:e=>e.action?.options?.title||e.type};return r})(t);return{id:e.id,label:r.getLabel(t),type:r.type,icon:r.icon,value:r.getValue(t)}})),u){const e=n.filter(e=>!p.some(t=>t.type===e.type));p=p.concat(e)}/* @__PURE__ */
|
|
28
|
+
return e.createElement("div",{className:"p-4"},/* @__PURE__ */e.createElement(Fr,{nextBestActions:p,onActionClick:(e,t)=>{e&&s?.({action:e,searchQueryId:o||"",query:c,answer:l,success:t})}}))},Qr=()=>{const{showResults:e,answers:t}=Nr();return Boolean(e||t.length>0)},Mr=({loadConversationEndpoint:e,headers:t,mergedTextConfig:n})=>{const{setIsLoadingConversation:a,setShowResults:s,answerListDispatch:o,conversationId:i,setConversationId:c,clearConversationId:l,setLoadError:d}=Nr(),u=r(r=>{if(!e)return;a(!0),a(!0),s(!0);const i=new AbortController;return ge({endpoint:e,conversationId:r,headers:t,signal:i.signal}).then(({data:e})=>{const t=e.map(e=>({id:e.searchQueryId,state:"completed",question:e.question,isUncertain:X(e.answer).uncertain,searchQueryId:e.searchQueryId,searchIntentId:e.searchIntentId,blocks:e.answer.split("---").map(e=>Ft({text:e.trim()}))}));o((({answers:e})=>({type:Vt,payload:{answers:e}}))({answers:t})),c(r),s(!0)}).catch(e=>{console.error("Error loading conversation:",e),o(cr()),l(),s(!1),d(n.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment.")}).finally(()=>{a(!1)}),()=>i.abort("Conversation loader aborted")},[e,a,s,t,o,c,d,n.errorText]);return ne(()=>{let e;return i&&(console.log("loading conversation",i),e=u(i)),()=>e?.()}),{loadConversationById:u}},Vr={"image/jpeg":"image","image/png":"image","image/gif":"image","image/webp":"image"};let qr=0;function Kr({index:r,blocks:n=[],question:a,searchResults:s,state:o="completed",searchQueryId:i,searchIntentId:c,hideCitations:l=!1,feedback:d,onFeedback:u,disableFeedback:m=!1,textConfig:p={},redirectRules:w,attachments:b=[],actions:k,handleActionClick:N,nextBestActions:C,isLastAnswer:I,onFeedbackReasonSubmit:S,hasError:P=!1,knowledgeSourceGroups:T,onKnowledgeGroupSelect:A,statusMessage:R}){const[j,O]=t(!1),[D,z]=t(!1),F=Qt(n),U="awaiting-knowledge-group"===o,Q=("fetching-search-results"===o||"fetching-stream"===o)&&1===n.length,M="fetching-search-results"===o,V="getting-action-inputs"===o||"completed"===o||U,q="completed"===o,K=P&&q,B=R??p.loadingAnswerText;/* @__PURE__ */
|
|
29
29
|
return e.createElement("div",{className:"rounded-lg relative mx-auto overflow-hidden bg-card border border-primary","data-name":"SearchResults","data-index":r},
|
|
30
|
-
/* @__PURE__ */e.createElement("div",{className:"px-4 pt-4 pb-2"},/* @__PURE__ */e.createElement("div",{className:"flex items-start justify-between gap-2 min-h-9"},/* @__PURE__ */e.createElement("div",{className:"flex gap-1"},/* @__PURE__ */e.createElement(le,{loading:!
|
|
31
|
-
/* @__PURE__ */e.createElement(
|
|
30
|
+
/* @__PURE__ */e.createElement("div",{className:"px-4 pt-4 pb-2"},/* @__PURE__ */e.createElement("div",{className:"flex items-start justify-between gap-2 min-h-9"},/* @__PURE__ */e.createElement("div",{className:"flex gap-1"},/* @__PURE__ */e.createElement(le,{loading:!V}),/* @__PURE__ */e.createElement("h2",{className:"leading-normal font-semibold m-0 text-foreground self-center text-lg"},a)),q&&!K&&/* @__PURE__ */e.createElement(h,null,/* @__PURE__ */e.createElement(f,null,/* @__PURE__ */e.createElement(g,{asChild:!0},/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(F)}catch(e){console.warn("Clipboard API failed, using fallback:",e);const r=document.createElement("textarea");r.value=F,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.focus(),r.select();try{document.execCommand("copy")}catch(t){console.error("Fallback: Oops, unable to copy",t)}document.body.removeChild(r)}O(!0),setTimeout(()=>O(!1),2e3)})()},className:"-mt-1 flex-shrink-0"},j?/* @__PURE__ */e.createElement(E,{className:"text-feedback-positive",weight:"bold"}):/* @__PURE__ */e.createElement($,{className:"text-secondary-foreground",weight:"bold"}))),/* @__PURE__ */e.createElement(y,null,/* @__PURE__ */e.createElement("p",null,j?"Copied!":"Copy"))))),/* @__PURE__ */e.createElement(Pr,{items:b.map((e,t)=>({id:`${t}`,src:e.url,url:e.url,alt:e.filename})),size:"xs",className:"mt-2"})),Q&&/* @__PURE__ */e.createElement("div",{className:"px-4 pt-0 pb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},M?p.loadingSearchText:B)),U&&T&&A?/* @__PURE__ */e.createElement(Ar,{groups:T,onGroupSelect:A}):/* @__PURE__ */e.createElement("div",{className:"flex flex-col"},n?.map((t,r)=>/* @__PURE__ */e.createElement("div",{key:r,className:Z("px-4 pt-0 pb-2 border-b last:border-b-0 border-dashed",K&&"text-muted-foreground")},
|
|
31
|
+
/* @__PURE__ */e.createElement(Ir,{block:t,redirectRules:w,state:o})))),q&&!K&&/* @__PURE__ */e.createElement(Ur,{actions:k,nextBestActions:C,isLastAnswer:I,handleActionClick:N,searchQueryId:i||"",searchIntentId:c,question:a,answer:F}),q&&!m&&!K&&/* @__PURE__ */e.createElement("div",{className:"p-4 pt-0"},/* @__PURE__ */e.createElement(ce,{feedback:d,onFeedback:e=>{u&&i&&u(e)},textConfig:p,disabled:m,feedbackReasonLength:500,feedbackReasonPlaceholder:"What could we have done better? Your feedback is valuable to us...",onFeedbackReasonSubmit:S,feedbackReasonThankYouText:"Thank you for your feedback!"})),!l&&s&&s.length>0&&/* @__PURE__ */e.createElement("div",{className:"overflow-hidden bg-card border-dashed border-0 border-t-2"},/* @__PURE__ */e.createElement(se,{open:D,onOpenChange:z,className:"w-full"},/* @__PURE__ */e.createElement("div",null,/* @__PURE__ */e.createElement(oe,{asChild:!0},/* @__PURE__ */e.createElement(v,{variant:"secondary",className:"w-full justify-between h-11","data-name":"RelatedSources"},/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement("span",{className:"font-medium truncate text-base"},"Sources")),/* @__PURE__ */e.createElement(x,{className:"size-4 flex-shrink-0 transition-transform duration-200 text-secondary-foreground "+(D?"rotate-180":""),weight:"bold"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Toggle")))),/* @__PURE__ */e.createElement(ie,{className:"divide-y divide-dark-300 overflow-hidden CollapsibleContent"},s.map(t=>/* @__PURE__ */e.createElement("a",{key:t.id,href:L(t.url),target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-3 transition-colors duration-200 hover:bg-accent bg-card text-foreground"},
|
|
32
32
|
/* @__PURE__ */e.createElement("span",{className:"flex-grow truncate"},t.title),
|
|
33
|
-
/* @__PURE__ */e.createElement(_,{className:"size-4 flex-shrink-0 text-secondary-foreground",weight:"bold"})))))))}const
|
|
34
|
-
/* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border"},/* @__PURE__ */e.createElement("h3",{className:"px-4 py-3 border-b border-b-dark-300 font-bold"},"Follow-up questions"),t.map((t,n)=>n<3?/* @__PURE__ */e.createElement(
|
|
33
|
+
/* @__PURE__ */e.createElement(_,{className:"size-4 flex-shrink-0 text-secondary-foreground",weight:"bold"})))))))}const Br=d(v);function Hr({questions:t,onQuestionClick:r}){return t.length?/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-full"},
|
|
34
|
+
/* @__PURE__ */e.createElement("div",{className:"rounded-lg overflow-hidden bg-card border"},/* @__PURE__ */e.createElement("h3",{className:"px-4 py-3 border-b border-b-dark-300 font-bold"},"Follow-up questions"),t.map((t,n)=>n<3?/* @__PURE__ */e.createElement(Br,{key:n,initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.1*n},onClick:()=>r(t),variant:"ghost",className:"w-full text-left"},
|
|
35
35
|
/* @__PURE__ */e.createElement("span",{className:"flex-grow"},t),
|
|
36
|
-
/* @__PURE__ */e.createElement(k,{className:"",weight:"bold"})):null))):null}function
|
|
36
|
+
/* @__PURE__ */e.createElement(k,{className:"",weight:"bold"})):null))):null}function Gr({questions:r,activeIndex:n,onNavigate:a,offset:s}){const[o,c]=t(n);i(()=>{c(n)},[n]);const l=r.length,m=(()=>{const e=[];let t=null;const r=r=>{null!==t&&r-t>1&&e.push("ellipsis"),e.push(r),t=r};r(0);for(let a=Math.max(1,n-2);a<=Math.min(l-2,n+2);a++)r(a);return l>1&&r(l-1),e})();/* @__PURE__ */
|
|
37
37
|
return e.createElement("nav",{"aria-label":"Question timeline navigation",className:"fixed left-4 top-1/2 -translate-y-1/2 z-40 flex flex-col gap-3",style:{...s?{left:`${s}px`}:{}}},
|
|
38
38
|
/* @__PURE__ */e.createElement(d.div,{className:"flex flex-col items-center space-y-3",role:"list",initial:!1,animate:{y:0},transition:{type:"spring",stiffness:300,damping:30}},
|
|
39
39
|
/* @__PURE__ */e.createElement(u,null,m.map((t,s)=>{if("ellipsis"===t)/* @__PURE__ */
|
|
@@ -41,14 +41,14 @@ return e.createElement(d.div,{key:`ellipsis-${s}`,className:"h-8 flex items-cent
|
|
|
41
41
|
/* @__PURE__ */e.createElement(N,{className:"size-4 text-foreground"}));const i=t,c=r[i];/* @__PURE__ */
|
|
42
42
|
return e.createElement(d.div,{key:i,className:"relative group isolate",role:"listitem",initial:{opacity:0,y:o>n?-20:20},animate:{opacity:1,y:0},exit:{opacity:0,y:o>n?20:-20},transition:{duration:.2},layout:!0},
|
|
43
43
|
/* @__PURE__ */e.createElement(h,{delayDuration:100},/* @__PURE__ */e.createElement(f,null,/* @__PURE__ */e.createElement(g,{asChild:!0},/* @__PURE__ */e.createElement("button",{onClick:()=>a(i),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||a(i)},className:Z("flex items-center justify-center size-8 rounded-full transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 hover:opacity-90 cursor-pointer ring-primary ",i===n?"bg-primary text-primary-foreground":"bg-stone-300 text-zinc-800"),"aria-label":`Navigate to question ${i+1}: ${c}`,"aria-current":i===n?"step":void 0},i+1)),/* @__PURE__ */e.createElement(y,{side:"right",sideOffset:8,bgColor:"--bfc-card",className:"max-w-[300px] text-card-foreground border-foreground/35"},
|
|
44
|
-
/* @__PURE__ */e.createElement("p",{className:"break-words leading-relaxed"},c)))))}))))}function
|
|
45
|
-
return e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement(ue,{id:"include-page",checked:t,onCheckedChange:a,disabled:r||n}),/* @__PURE__ */e.createElement("label",{htmlFor:"include-page",className:"text-sm text-foreground flex items-center gap-2"},"Include page",r&&/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-3 border-2 border-t-transparent border-primary"})))}const
|
|
44
|
+
/* @__PURE__ */e.createElement("p",{className:"break-words leading-relaxed"},c)))))}))))}function Wr({value:t,loading:r,disabled:n,onToggle:a}){/* @__PURE__ */
|
|
45
|
+
return e.createElement("div",{className:"flex items-center gap-2"},/* @__PURE__ */e.createElement(ue,{id:"include-page",checked:t,onCheckedChange:a,disabled:r||n}),/* @__PURE__ */e.createElement("label",{htmlFor:"include-page",className:"text-sm text-foreground flex items-center gap-2"},"Include page",r&&/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-3 border-2 border-t-transparent border-primary"})))}const Jr=e.forwardRef(({query:r,onQueryChange:n,onSearch:a,textConfig:s,collections:c=[],currentCollectionId:l,onCollectionChange:m,allowedRegions:p=[],onRegionChange:h,apiKey:f,fetchRegionConfig:g,enableFileAttachment:y=!1,attachedFiles:w=[],isUploading:b=!1,onAddFiles:E,onRemoveFile:$,isSearching:x=!1,autocompleteSuggestions:_=[],onAutocompleteSuggestionSelect:N,isAgentAssist:A=!1,includePageEnabled:R=!1,includePageLoading:j=!1,includePageDisabled:O=!1,onIncludePageToggle:D},z)=>{const L=o(null),[F,U]=t(!1),[Q,M]=t(!1),V=he("showIncludePageToggle",!1),q=[{value:"all",label:"All regions",icon:/* @__PURE__ */e.createElement(C,{className:"size-4"})},...p.map(t=>{const r=de(t);return{value:t,label:r?.name||t,icon:/* @__PURE__ */e.createElement("img",{alt:`${r?.name||t}`,src:`https://purecatamphetamine.github.io/country-flag-icons/3x2/${t}.svg`,className:"w-5"})}})],K=e.useCallback(async t=>{if(!f||!g)return console.warn("No apiKey or fetchRegionConfig provided, falling back to current collections"),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}));try{const r=await g(f,t);return(r?.settings?.collections||[]).map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}catch(r){return console.error("Error fetching collections for region:",r),c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})}))}},[f,g,c]);i(()=>{const e=e=>{e.target.closest(".suggestions-dropdown")||U(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),i(()=>{r.trim()&&U(!0)},[r]);const B=F&&r.trim()&&_.length>0,H={hidden:{opacity:0,x:-4},visible:{opacity:1,x:0,transition:{duration:.2}}};/* @__PURE__ */
|
|
46
46
|
return e.createElement("div",{className:"relative w-full","data-name":"PrimarySearch"},/* @__PURE__ */e.createElement("div",{className:Z("relative w-full overflow-hidden bg-background border border-border transition-all",B?"rounded-t-md":"rounded-md",Q&&y&&"ring-2 ring-primary"),onDrop:e=>{if(e.preventDefault(),M(!1),!y||!E)return;const t=Array.from(e.dataTransfer.files);t.length>0&&E(t)},onDragOver:e=>{e.preventDefault(),y&&M(!0)},onDragLeave:()=>{M(!1)},onPaste:e=>{if(!y||!E)return;const t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),E(t))}},Q&&y&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 z-10 flex items-center justify-center rounded-md",style:{backgroundColor:"color-mix(in srgb, var(--bfc-card) 90%, transparent)"}},
|
|
47
|
-
/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),y&&/* @__PURE__ */e.createElement(
|
|
47
|
+
/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),y&&/* @__PURE__ */e.createElement(Pr,{items:w.map(e=>({id:e.id,src:e.preview,url:e.publicUrl,status:e.status})),size:"md",onRemove:$,className:"pt-3 px-3 bg-card"}),
|
|
48
48
|
/* @__PURE__ */e.createElement("div",{className:"p-3 flex items-center bg-card","data-name":"search-input"},/* @__PURE__ */e.createElement(S,{className:"h-5 w-5 mr-2 text-muted-foreground","aria-hidden":!0,role:"presentation"}),/* @__PURE__ */e.createElement("textarea",{ref:z,value:r,onChange:e=>{var t;n(e.target.value),(t=e.target).style.height="auto",t.style.height=`${t.scrollHeight}px`},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||b||(e.preventDefault(),a())},onFocus:()=>U(!0),placeholder:s.searchPlaceholder,className:Z("w-full resize-none !outline-none text-base py-1 min-h-9","overflow-hidden border-none bg-transparent shadow-none","placeholder:text-gray-400 text-dark-900 !ring-0"),rows:1}),x&&/* @__PURE__ */e.createElement("div",{className:"flex items-center justify-center ml-2"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 border-2 border-t-transparent border-primary"}))),!B&&/* @__PURE__ */e.createElement("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border"},/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2"},y&&/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement("input",{type:"file",ref:L,accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:e=>{e.target.files&&E?.(Array.from(e.target.files)),e.target.value=""}}),/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",className:"rounded-md size-8 hover:bg-opacity-80 disabled:opacity-50",onClick:()=>L.current?.click(),disabled:w.length>=5,"aria-label":s.attachImageText},
|
|
49
49
|
/* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),/* @__PURE__ */e.createElement("div",{className:"flex gap-1","data-name":"collections-dropdown"},p.length>0&&c.length>0?
|
|
50
50
|
/* @__PURE__ */e.createElement(pe,{firstLevelItems:q,fetchSecondLevelItems:K,onSelectionChange:(e,t)=>{e&&h&&h(e.value),t&&m&&m(t.value)},firstLevelLabel:"Region",secondLevelLabel:"Collection",firstLevelPlaceholder:"All documents",className:"min-w-[200px]",displayLabel:!1}):c.length>0?
|
|
51
|
-
/* @__PURE__ */e.createElement(me,{options:c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})})),value:"all"===l?void 0:l,defaultValueLabel:"All documents",placeholder:"Select collection",noResultsLabel:"No collections found",dropdownWidth:200,onChange:e=>m?.(e)}):null),A&&D&&V&&/* @__PURE__ */e.createElement(
|
|
51
|
+
/* @__PURE__ */e.createElement(me,{options:c.map(t=>({value:t.id,label:t.name,icon:t.siteEnabled?/* @__PURE__ */e.createElement(C,{className:"size-4"}):/* @__PURE__ */e.createElement(I,{className:"size-4"})})),value:"all"===l?void 0:l,defaultValueLabel:"All documents",placeholder:"Select collection",noResultsLabel:"No collections found",dropdownWidth:200,onChange:e=>m?.(e)}):null),A&&D&&V&&/* @__PURE__ */e.createElement(Wr,{value:R,loading:j,disabled:O,onToggle:D})),/* @__PURE__ */e.createElement("div",{className:"flex items-center","data-name":"search-button"},/* @__PURE__ */e.createElement(v,{size:"sm",disabled:!r||x||b,"aria-disabled":!r||x||b,className:"rounded-md size-8 disabled:opacity-50 bg-primary",onClick:a},x?/* @__PURE__ */e.createElement("div",{className:"flex items-center",role:"status","aria-live":"polite"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 border-2 border-t-transparent border-white","aria-hidden":"true"}),/* @__PURE__ */e.createElement("span",{className:"sr-only"},"Loading")):/* @__PURE__ */e.createElement(T,{className:"text-primary-foreground",size:16,weight:"bold","aria-label":"Submit question"}))))),/* @__PURE__ */e.createElement(u,{mode:"wait"},B&&/* @__PURE__ */e.createElement(d.div,{variants:{hidden:{opacity:0,scale:.95,transformOrigin:"top"},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:500,damping:30,mass:.5}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:"easeOut"}}},initial:"hidden",animate:"visible",exit:"exit",className:Z("suggestions-dropdown absolute","left-0 right-0 z-50","overflow-hidden bg-card","border-border border border-t-0 rounded-b-md shadow-md -mt-px","md:relative")},
|
|
52
52
|
/* @__PURE__ */e.createElement(d.div,{variants:H},r.trim()&&/* @__PURE__ */e.createElement("div",{role:"option","aria-selected":!1,tabIndex:0,className:Z("px-4 py-3","cursor-pointer","flex items-center gap-3","transition-colors duration-200","hover:bg-dark-100/50 text-foreground bg-dark-200","border-b border border-border"),onClick:()=>{a(),U(!1)},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),a(),U(!1))}},
|
|
53
53
|
/* @__PURE__ */e.createElement(S,{className:"size-4 flex-shrink-0 text-secondary-foreground"}),
|
|
54
54
|
/* @__PURE__ */e.createElement("span",{className:"text-[15px]"},r),
|
|
@@ -56,41 +56,41 @@ return e.createElement("div",{className:"relative w-full","data-name":"PrimarySe
|
|
|
56
56
|
/* @__PURE__ */e.createElement(d.div,{variants:{visible:{transition:{staggerChildren:.03,delayChildren:.05}}},initial:"hidden",animate:"visible"},_.map(t=>/* @__PURE__ */e.createElement(d.div,{key:t.id,variants:H,role:"option","aria-selected":!1,tabIndex:0,className:"px-4 py-3 cursor-pointer flex items-center gap-3 transition-colors duration-200 hover:bg-dark-300 text-foreground",onClick:()=>{N?.(t),U(!1)},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),N?.(t),U(!1))}},
|
|
57
57
|
/* @__PURE__ */e.createElement(S,{className:"size-4 flex-shrink-0 text-secondary-foreground"}),
|
|
58
58
|
/* @__PURE__ */e.createElement("span",{className:"text-[15px]"},t.question),
|
|
59
|
-
/* @__PURE__ */e.createElement("div",{className:"ml-auto flex items-center"},/* @__PURE__ */e.createElement(k,{className:"size-4 text-secondary-foreground"}))))))))});
|
|
60
|
-
return e.createElement(d.footer,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:
|
|
59
|
+
/* @__PURE__ */e.createElement("div",{className:"ml-auto flex items-center"},/* @__PURE__ */e.createElement(k,{className:"size-4 text-secondary-foreground"}))))))))});Jr.displayName="PrimarySearch";const Zr="_followUpSearchBar_x7ads_1",Xr=e.forwardRef(({initialQuery:r="",onQueryChange:n,isSearching:a,handleFollowUpSearch:s,textConfig:c,enableFileAttachment:l=!1,attachedFiles:u=[],isUploading:m=!1,onAddFiles:p,onRemoveFile:h,disabled:f=!1},g)=>{const[y,w]=t(r),[b,E]=t(!1),$=o(null),x=o(null);i(()=>{$.current&&($.current.style.height="inherit",$.current.style.height=`${$.current.scrollHeight}px`)},[y]),i(()=>{w(r)},[r]);const _=f||a||!y.trim()||m;/* @__PURE__ */
|
|
60
|
+
return e.createElement(d.footer,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:Zr},
|
|
61
61
|
/* @__PURE__ */e.createElement("div",{className:"container flex items-center justify-center p-3"},/* @__PURE__ */e.createElement("div",{className:Z("relative flex w-full flex-col rounded bg-card border border-dark-400",b&&l&&"ring-2 ring-primary"),onDrop:e=>{if(e.preventDefault(),E(!1),!l||!p)return;const t=Array.from(e.dataTransfer.files);t.length>0&&p(t)},onDragOver:e=>{e.preventDefault(),l&&E(!0)},onDragLeave:()=>{E(!1)},onPaste:e=>{if(!l||!p)return;const t=Array.from(e.clipboardData.files);t.length>0&&(e.preventDefault(),p(t))}},b&&l&&/* @__PURE__ */e.createElement("div",{className:"absolute inset-0 z-10 flex items-center justify-center rounded",style:{backgroundColor:"color-mix(in srgb, var(--bfc-card) 90%, transparent)"}},
|
|
62
|
-
/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),l&&/* @__PURE__ */e.createElement(
|
|
62
|
+
/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-muted-foreground"},"Drop images here to attach")),l&&/* @__PURE__ */e.createElement(Pr,{items:u.map(e=>({id:e.id,src:e.preview,url:e.publicUrl,status:e.status})),size:"sm",onRemove:h,className:"pt-2 px-2"}),
|
|
63
63
|
/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 px-2"},l&&/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement("input",{type:"file",ref:x,accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:e=>{e.target.files&&p?.(Array.from(e.target.files)),e.target.value=""}}),/* @__PURE__ */e.createElement(v,{variant:"ghost",size:"icon",className:"rounded-md size-7 hover:bg-opacity-80 disabled:opacity-50 shrink-0",onClick:()=>x.current?.click(),disabled:f||u.length>=5,"aria-label":c.attachImageText},
|
|
64
|
-
/* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),!l&&/* @__PURE__ */e.createElement("div",{className:"size-6 flex flex-shrink-0 justify-center items-center"},/* @__PURE__ */e.createElement(S,{className:"size-5 text-secondary-foreground"})),/* @__PURE__ */e.createElement(W,{ref:e=>{$.current=e,"function"==typeof g?g(e):g&&"current"in g&&(g.current=e)},value:y,onChange:e=>{w(e.target.value)},onBlur:()=>{y!==r&&n(y)},onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey&&!_){e.preventDefault();const t=y;n(t),s(t),w("")}},placeholder:c.followUpPlaceholder,disabled:f,className:"min-h-11 w-full resize-none border-0 shadow-none bg-transparent px-0 py-2.5 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:opacity-50 disabled:cursor-not-allowed",rows:1}),/* @__PURE__ */e.createElement(v,{type:"button",size:"icon",disabled:_,onClick:()=>{const e=y;n(e),s(e),w("")},className:Z("size-8 shrink-0 rounded",y?"bg-primary text-primary-foreground":"bg-dark-400 text-white")},a?/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 sm:size-5 border-2 border-dark/40 !border-t-foreground"}):/* @__PURE__ */e.createElement(T,{className:"size-6"}))))))});function
|
|
64
|
+
/* @__PURE__ */e.createElement(P,{weight:"regular",className:"size-4 text-secondary-foreground"}))),!l&&/* @__PURE__ */e.createElement("div",{className:"size-6 flex flex-shrink-0 justify-center items-center"},/* @__PURE__ */e.createElement(S,{className:"size-5 text-secondary-foreground"})),/* @__PURE__ */e.createElement(W,{ref:e=>{$.current=e,"function"==typeof g?g(e):g&&"current"in g&&(g.current=e)},value:y,onChange:e=>{w(e.target.value)},onBlur:()=>{y!==r&&n(y)},onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey&&!_){e.preventDefault();const t=y;n(t),s(t),w("")}},placeholder:c.followUpPlaceholder,disabled:f,className:"min-h-11 w-full resize-none border-0 shadow-none bg-transparent px-0 py-2.5 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:opacity-50 disabled:cursor-not-allowed",rows:1}),/* @__PURE__ */e.createElement(v,{type:"button",size:"icon",disabled:_,onClick:()=>{const e=y;n(e),s(e),w("")},className:Z("size-8 shrink-0 rounded",y?"bg-primary text-primary-foreground":"bg-dark-400 text-white")},a?/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-4 sm:size-5 border-2 border-dark/40 !border-t-foreground"}):/* @__PURE__ */e.createElement(T,{className:"size-6"}))))))});function Yr({headerText:t,onToggleSizeButtonClick:r,onBackButtonClick:n,onCloseWidgetClick:a,isSearchWidget:s,onHistoryButtonClick:o,onHistoryBackClick:i,showHistory:c,hasUnreadConversations:l,className:u,showHistoryButton:m,...p}){const h=Qr(),[f,g]=e.useState(!1),{isSearching:y,showMobileCloseWidgetButton:w}=Nr();/* @__PURE__ */
|
|
65
65
|
return e.createElement("div",{className:Z("w-full px-3 py-4 flex items-center justify-between","bg-primary h-14 leading-6","md:hidden","@3xl:bg-transparent @3xl:h-auto @3xl:leading-normal","@3xl:justify-center @3xl:space-y-4 @3xl:p-0",s?"hidden bg-transparent":"",u),...p},
|
|
66
66
|
/* @__PURE__ */e.createElement(d.h2,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.3},className:Z("m-0 text-primary-foreground @3xl:text-foreground flex gap-1 items-center font-bold text-base",s?"":"@3xl:text-5xl")},(c||h)&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:c?i:n,"aria-label":"Go back",className:Z("shrink-0 text-primary-foreground",s?"":"@3xl:hidden"),disabled:y},
|
|
67
67
|
/* @__PURE__ */e.createElement(A,null)),
|
|
68
68
|
/* @__PURE__ */e.createElement("span",null,c?"History":t)),
|
|
69
69
|
/* @__PURE__ */e.createElement("div",{className:"@3xl:hidden shrink-0","data-name":"HeaderButtons"},!w&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:()=>{g(e=>!e),r()},"aria-label":f?"Collapse widget":"Expand widget",className:"text-primary-foreground device-touch:hidden device-desktop:inline-flex device-desktop-touch:inline-flex"},f?/* @__PURE__ */e.createElement(R,null):/* @__PURE__ */e.createElement(j,null)),m&&/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:o,"aria-label":"Conversation history",className:"relative text-primary-foreground"},
|
|
70
70
|
/* @__PURE__ */e.createElement(O,null),l&&!c&&/* @__PURE__ */e.createElement("span",{className:"absolute top-1 right-1 size-2 rounded-full bg-red-500"})),/* @__PURE__ */e.createElement(v,{size:"icon",variant:"ghost",onClick:a,"aria-label":"Close widget",className:"text-primary-foreground"},
|
|
71
|
-
/* @__PURE__ */e.createElement(b,null))))}
|
|
71
|
+
/* @__PURE__ */e.createElement(b,null))))}Xr.displayName="FollowUpSearchBar";const en={headerText:"How can we help you today?",searchPlaceholder:"Ask a question or type a search term here ...",attachImageText:"Attach image",allDocumentsText:"All documents",loadingSearchText:"Searching for relevant content...",loadingAnswerText:"Crafting a response...",errorText:"Sorry, we were unable to process the request right now. Please try again in a moment.",followUpPlaceholder:"Type your response or follow-up",positiveAnswerText:"Helpful",negativeAnswerText:"Not helpful",uncertaintyFallbackText:{en:"Sorry, I can't find a clear answer to your question. Please try rephrasing or check the related sources below.",es:"Lo siento, no puedo encontrar una respuesta clara. Intente reformular la pregunta o consulte las fuentes relacionadas.",fr:"Désolé, je ne trouve pas de réponse claire. Essayez de reformuler ou consultez les sources connexes.",de:"Entschuldigung, ich finde keine klare Antwort. Versuchen Sie es anders zu formulieren oder sehen Sie sich die verwandten Quellen an.",it:"Mi dispiace, non trovo una risposta chiara. Prova a riformulare o consulta le fonti correlate.",pt:"Desculpe, não encontro uma resposta clara. Tente reformular ou consulte as fontes relacionadas.",nl:"Sorry, ik kan geen duidelijk antwoord vinden. Probeer het anders te formuleren of bekijk de gerelateerde bronnen.",pl:"Przepraszam, nie znajduję jasnej odpowiedzi. Spróbuj przeformułować pytanie lub sprawdź powiązane źródła.",ru:"Извините, я не могу найти четкого ответа. Попробуйте переформулировать или ознакомьтесь со связанными источниками.",ja:"申し訳ありませんが、明確な回答が見つかりません。質問の言い換えや、関連ソースをご確認ください。",ko:"죄송합니다. 명확한 답변을 찾을 수 없습니다. 질문을 다시 작성하거나 관련 소스를 확인해 주세요.",zh:"抱歉,找不到明确的答案。请尝试重新表述或查看相关来源。","zh-TW":"抱歉,找不到明確的答案。請嘗試重新表述或查看相關來源。"}};function tn({toasts:t,onDismiss:r}){/* @__PURE__ */
|
|
72
72
|
return e.createElement("div",{className:"fixed top-4 left-4 right-4 z-50 flex flex-col gap-2 pointer-events-none"},/* @__PURE__ */e.createElement(u,null,t.map(t=>/* @__PURE__ */e.createElement(d.div,{key:t.id,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.2},className:"pointer-events-auto flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-3 text-sm text-foreground shadow-lg"},
|
|
73
73
|
/* @__PURE__ */e.createElement("span",{className:"flex-1"},t.message),
|
|
74
74
|
/* @__PURE__ */e.createElement("button",{onClick:()=>r(t.id),className:"shrink-0 rounded-full p-0.5 hover:bg-muted transition-colors","aria-label":"Dismiss"},
|
|
75
|
-
/* @__PURE__ */e.createElement(Ie,{className:"size-3.5"}))))))}const
|
|
76
|
-
/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center gap-4"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-8 border-2 border-t-transparent border-primary"}),/* @__PURE__ */e.createElement("p",{className:"text-sm text-secondary-foreground"},"Loading conversation...")));function
|
|
75
|
+
/* @__PURE__ */e.createElement(Ie,{className:"size-3.5"}))))))}const rn=()=>/* @__PURE__ */e.createElement(d.div,{key:"loading",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"w-full flex items-center justify-center py-20","data-name":"loading"},
|
|
76
|
+
/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center gap-4"},/* @__PURE__ */e.createElement("div",{className:"animate-spin rounded-full size-8 border-2 border-t-transparent border-primary"}),/* @__PURE__ */e.createElement("p",{className:"text-sm text-secondary-foreground"},"Loading conversation...")));function nn({isHandoff:t,agentAvatarUrl:r}){return t?r?/* @__PURE__ */e.createElement("img",{src:r,className:"h-8 w-8 shrink-0 rounded-full object-cover",alt:"Agent avatar"}):/* @__PURE__ */e.createElement(D,{size:32,className:"text-primary"}):/* @__PURE__ */e.createElement(Se,{className:"border border-neutral-200 rounded-full"})}function an({item:t,onSelect:r}){/* @__PURE__ */
|
|
77
77
|
return e.createElement("button",{onClick:()=>r({conversationId:t.conversationId,isHandoff:t.isHandoff??!1,isCompleted:"completed"===t.status}),className:Z("w-full flex items-center gap-3 p-3 rounded-lg bg-card text-left","hover:bg-accent transition-colors","border-l-4 border-transparent hover:border-primary/40")},
|
|
78
|
-
/* @__PURE__ */e.createElement("div",{className:"relative shrink-0"},/* @__PURE__ */e.createElement(
|
|
79
|
-
/* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function
|
|
80
|
-
return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const
|
|
78
|
+
/* @__PURE__ */e.createElement("div",{className:"relative shrink-0"},/* @__PURE__ */e.createElement(nn,{isHandoff:t.isHandoff,agentAvatarUrl:t.agentAvatarUrl}),t.hasUnread&&/* @__PURE__ */e.createElement("span",{className:"absolute top-0 right-0 size-2 rounded-full bg-red-500"})),
|
|
79
|
+
/* @__PURE__ */e.createElement("div",{className:"flex flex-col min-w-0"},/* @__PURE__ */e.createElement("span",{className:"text-sm font-medium truncate"},t.title),/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground truncate"},t.subtitle?`${t.subtitle} replied • ${t.timestamp}`:t.timestamp)))}function sn({title:t,items:r,onSelect:n,isReadOnly:a=!1}){return 0===r.length?null:/* @__PURE__ */e.createElement("section",null,/* @__PURE__ */e.createElement("div",{className:"flex items-center gap-2 mb-2"},/* @__PURE__ */e.createElement("p",{className:"text-sm text-muted-foreground"},t),a&&/* @__PURE__ */e.createElement("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground"},"View only")),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2"},r.map(t=>/* @__PURE__ */e.createElement(an,{key:t.conversationId,item:t,onSelect:n}))))}function on(){/* @__PURE__ */
|
|
80
|
+
return e.createElement("div",{className:"w-full flex items-center gap-3 p-3 rounded-lg bg-card animate-pulse"},/* @__PURE__ */e.createElement("div",{className:"size-8 rounded-full bg-muted shrink-0"}),/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 flex-1 min-w-0"},/* @__PURE__ */e.createElement("div",{className:"h-3.5 bg-muted rounded w-3/4"}),/* @__PURE__ */e.createElement("div",{className:"h-3 bg-muted rounded w-1/2"})))}const cn=()=>{};function ln({conversations:t,isLoading:r,onSelectConversation:n}){const a=n??cn,s=t.filter(e=>"active"===e.status),o=t.filter(e=>"completed"===e.status);return r?/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-2 px-3 py-4 overflow-hidden"},/* @__PURE__ */e.createElement("div",{className:"h-4 w-16 bg-muted rounded animate-pulse mb-2"}),[...Array(3)].map((t,r)=>/* @__PURE__ */e.createElement(on,{key:r}))):/* @__PURE__ */e.createElement("div",{className:"flex flex-col gap-4 px-3 py-4 min-h-full"},/* @__PURE__ */e.createElement(sn,{title:"Active",items:s,onSelect:a}),/* @__PURE__ */e.createElement(sn,{title:"Previous",items:o,onSelect:a,isReadOnly:!0}),0===t.length&&/* @__PURE__ */e.createElement("div",{className:"flex flex-col items-center justify-center gap-3 mt-16 text-center px-6"},/* @__PURE__ */e.createElement(Se,{size:40,className:"text-muted-foreground opacity-40"}),/* @__PURE__ */e.createElement("p",{className:"text-sm font-medium text-foreground"},"No Threads yet"),/* @__PURE__ */e.createElement("p",{className:"text-xs text-muted-foreground"},"Start a conversation and it will appear here.")))}function dn({onStartNewConversation:t,message:r="This conversation is closed. Messages are read-only."}){/* @__PURE__ */
|
|
81
81
|
return e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"bg-card shadow-top-soft"},
|
|
82
|
-
/* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const ln="enableHistoryTab",dn=[p],un=[m],mn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},pn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,knowledgeSourceGroups:ne},se)=>{const{answers:oe,answerListDispatch:ie,query:ce,setQuery:le,followUpQuery:de,setFollowUpQuery:ue,isSearching:me,setIsSearching:pe,showResults:fe,setShowResults:ge,activeAnswerIndex:Ie,setActiveAnswerIndex:Se,conversationId:Ae,setConversationId:Re,clearConversationId:je,isLoadingConversation:Oe,setShowMobileCloseWidgetButton:De}=_r(),ze={...Xr,...S},Le=he("enableFileAttachment",!1),Fe=_||Le,Ue=he(ln,!1),{toasts:Qe,showToast:Me,dismissToast:Ve}=function(e=3e3){const[n,a]=t([]),s=o(0),i=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:i,dismissToast:c}}(),qe=r(()=>{let e=Ae;return e||(e=ye(),Re(e)),e},[Ae,Re]),{attachedFiles:Ke,isUploading:Be,addFiles:He,removeFile:Ge,clearAttachedFiles:We,getUploadedAttachments:Je}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>Qr[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++Mr,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:Qr[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:qe,onError:Me}),[Ze,Xe]=t(s),[Ye,et]=t(m),[tt,rt]=t(!0),nt=o(null),at=o(null),st=o(null),ot=o([]),it=o(null),ct=o(null),lt=o(null),dt=o(null),ut=o(null),{suggestions:mt}=$e({query:ce,endpoint:$||"",allowedRegions:V,collectionId:Ze,headers:I,conversationId:Ae,delay:300}),{loadConversationById:pt}=Ur({loadConversationEndpoint:E,headers:I,mergedTextConfig:ze}),{showHistory:ht,setShowHistory:ft,conversations:gt,isLoadingHistory:yt,hasUnreadConversations:vt,isViewOnly:wt,setIsViewOnly:bt,handleSelectConversation:Et,completeActiveConversations:$t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=o(null),x=o(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);i(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),i(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Ue,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,headers:I,userData:U??void 0,currentConversationId:Ae,loadConversationById:pt,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:xt,scrollToAnswer:_t}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ot,it,dt),{subscribeToStateChanges:kt}=(()=>{const e=o([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=_r();return i(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,handleIncludePageToggle:St,fetchPageContext:Pt}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,o]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),o(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),o(!1)}catch(t){console.error("Failed to toggle include page:",t),o(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return i(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(o(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{ut.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&ut.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("answer-text-chunk"===e.type){a+=e.content,ie(lr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=ze.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ie(mr({uncertaintyText:e}))}}"answer-error"===e.type&&ie(dr({error:ze.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ie(gr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ie(fr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ie(pr()),At({searchQueryId:t,conversationId:r,parameters:n})):Rt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ie(cr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(ut.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{ut.current===e&&(ut.current=null,e.releaseLock())}},At=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ie((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ie(dr({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(ur())}},Rt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ie(pr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(dr({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(ur()),pe(!1)}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ie(pr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(dr({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(ur()),pe(!1)}},Ot=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Ze,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ie(cr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Dt=async({searchQuery:e=ce.trim(),event:t})=>{if(!e)return;const r=Ae||ye();Re(r);const n=Je();We(),pe(!0),ge(!0),Se(oe.length),xt(),ie((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),lt.current?.focus();const a=await Pt(r,e);if(ne&&ne.length>0&&!nt.current)return at.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ie((({index:e}={})=>({type:sr,payload:{index:e}}))()),void pe(!1);try{const s={...U},o=nt.current?.collectionIds,i=await Ot({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await At({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ie(hr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ie(dr({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}},zt=async e=>{nt.current=e;const t=at.current;if(t){at.current=null,ie((({index:e}={})=>({type:or,payload:{index:e}}))()),pe(!0);try{const r=await Ot({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await At({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ie(hr())}catch(r){console.error("Error generating answer after group selection:",r),ie(dr({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}}},Lt=e=>{if($t(),bt(!1),Y?.(),ut.current){const e=ut.current;ut.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}pe(!1),le(""),ue(""),ge(!1),ie(ir()),Se(0),We(),je(),nt.current=null,at.current=null,R?.("New Thread Created",{oldConversationId:Ae}),st.current&&(st.current.style.height="auto"),e&&(le(e),Dt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(se,()=>({createNewThread:Lt,showFollowUpThread:e=>{rt(e)},subscribeToStateChanges:kt,focusSearchField:()=>ct.current?.focus()||lt.current?.focus(),showCloseButton:(e=!0)=>{De(e)},loadConversation:pt})),i(()=>{Xe(s)},[s]),i(()=>{et(m)},[m]);const Ft=async(e,t,r)=>{if(w){ie((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Ae}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Ae,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ie((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Ut=async e=>{const t=void 0!==e?e:de;t.trim()&&(le(t),ue(""),await Dt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};i(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(le(""),ue(""),ge(!1),ie(ir()),Se(0),We(),st.current&&(st.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Mt=e=>{R?.("Follow-up Question Clicked",{conversationId:Ae,question:e}),Dt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Vt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Ae,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(oe,Ae);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return i(()=>{const e=it.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=fe&&tt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return fe?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,fe,tt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
|
|
83
|
-
/* @__PURE__ */e.createElement(
|
|
82
|
+
/* @__PURE__ */e.createElement("div",{className:"container flex flex-col items-center justify-center p-3 gap-2 text-center"},/* @__PURE__ */e.createElement("span",{className:"text-xs text-muted-foreground"},r),/* @__PURE__ */e.createElement("p",{className:"m-0 text-sm font-medium text-foreground"},"Still need help?"),/* @__PURE__ */e.createElement("button",{type:"button",onClick:t,className:"h-8 rounded-md px-4 text-sm bg-primary text-primary-foreground"},"Start new conversation")))}const un="enableHistoryTab",mn=[p],pn=[m],hn={p:({children:t})=>/* @__PURE__ */e.createElement("span",null,t)},fn=c(({suggestions:n=[],collections:a=[],selectedCollectionId:s,onCollectionChange:c,selectedRegion:m,onRegionChange:p,apiKey:h,fetchRegionConfig:f,searchEndpoint:g,answerStreamEndpoint:y,uploadEndpoint:v,feedbackEndpoint:w,feedbackReasonEndpoint:b,loadConversationEndpoint:E,autocompleteEndpoint:$,disableFollowUpQuestions:x=!1,enableFileAttachment:_=!1,disableFeedback:k=!1,disclaimer:N,offset:C=0,headers:I,textConfig:S={},followUpQuestionsEndpoint:P,className:T,onToggleSizeButtonClick:A,trackEvent:R,onCloseWidget:j,isWidgetMode:O=!0,nextBestActions:D,bodyActionButtons:z,onNextBestActionClick:L,userData:U,redirectRules:Q,secretAttributes:M,allowedRegions:V,style:q,isSearchWidget:K=!1,isAgentAssist:B=!1,hideCitations:H=!1,conversationInlineSlot:G,liveHumanAgentChatSlot:W,reconnectHandoff:J,resetHandoff:Y,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,knowledgeSourceGroups:ne},se)=>{const{answers:oe,answerListDispatch:ie,query:ce,setQuery:le,followUpQuery:de,setFollowUpQuery:ue,isSearching:me,setIsSearching:pe,showResults:fe,setShowResults:ge,activeAnswerIndex:Ie,setActiveAnswerIndex:Se,conversationId:Ae,setConversationId:Re,clearConversationId:je,isLoadingConversation:Oe,setShowMobileCloseWidgetButton:De}=Nr(),ze={...en,...S},Le=he("enableFileAttachment",!1),Fe=_||Le,Ue=he(un,!1),{toasts:Qe,showToast:Me,dismissToast:Ve}=function(e=3e3){const[n,a]=t([]),s=o(0),i=r(t=>{const r=++s.current;a(e=>[...e,{id:r,message:t}]),setTimeout(()=>{a(e=>e.filter(e=>e.id!==r))},e)},[e]),c=r(e=>{a(t=>t.filter(t=>t.id!==e))},[]);return{toasts:n,showToast:i,dismissToast:c}}(),qe=r(()=>{let e=Ae;return e||(e=ye(),Re(e)),e},[Ae,Re]),{attachedFiles:Ke,isUploading:Be,addFiles:He,removeFile:Ge,clearAttachedFiles:We,getUploadedAttachments:Je}=function({uploadEndpoint:e,headers:n,getConversationId:a,onError:s}){const[o,i]=t([]),c=r(e=>{i(t=>{const r=t.find(t=>t.id===e);return r&&URL.revokeObjectURL(r.preview),t.filter(t=>t.id!==e)})},[]),l=r(t=>{if(0===t.length)return;const r=t.filter(e=>Vr[e.type]?!(e.size>10485760&&(s?.(`Image "${e.name}" exceeds the 10MB size limit.`),1)):(s?.("Image type is not supported. Please use JPEG, PNG, GIF, or WebP."),!1)),c=5-o.length;if(0===c)return void s?.("Maximum 5 images reached.");const l=r.slice(0,c);if(0===l.length)return;if(l.length<r.length&&s?.("Maximum 5 images. Some images were not attached."),!e)return console.error("[useFileAttachment] uploadEndpoint is not configured — file attachment is unavailable."),void s?.("Something went wrong. Please try again later.");const d=l.map(e=>({id:"file-"+ ++qr,file:e,preview:URL.createObjectURL(e),status:"uploading",attachmentType:Vr[e.type]}));i(e=>[...e,...d]);const u=a();d.forEach(t=>{(async()=>{try{const{publicUrl:r}=await ve({endpoint:e,conversationId:u,file:t.file,headers:n});i(e=>e.map(e=>e.id===t.id?{...e,status:"uploaded",publicUrl:r}:e))}catch(r){console.error("Upload failed:",r),s?.(`Failed to upload "${t.file.name}". Please try again.`),i(e=>{const r=e.find(e=>e.id===t.id);return r&&URL.revokeObjectURL(r.preview),e.filter(e=>e.id!==t.id)})}})()})},[o,e,n,a,s]),d=r(()=>{o.forEach(e=>URL.revokeObjectURL(e.preview)),i([])},[o]),u=r(()=>o.filter(e=>"uploaded"===e.status&&e.publicUrl).map(e=>({type:e.attachmentType,url:e.publicUrl,filename:e.file.name})),[o]),m=o.some(e=>"uploading"===e.status);return{attachedFiles:o,isUploading:m,addFiles:l,removeFile:c,clearAttachedFiles:d,getUploadedAttachments:u}}({uploadEndpoint:v,headers:I,getConversationId:qe,onError:Me}),[Ze,Xe]=t(s),[Ye,et]=t(m),[tt,rt]=t(!0),nt=o(null),at=o(null),st=o(null),ot=o([]),it=o(null),ct=o(null),lt=o(null),dt=o(null),ut=o(null),{suggestions:mt}=$e({query:ce,endpoint:$||"",allowedRegions:V,collectionId:Ze,headers:I,conversationId:Ae,delay:300}),{loadConversationById:pt}=Mr({loadConversationEndpoint:E,headers:I,mergedTextConfig:ze}),{showHistory:ht,setShowHistory:ft,conversations:gt,isLoadingHistory:yt,hasUnreadConversations:vt,isViewOnly:wt,setIsViewOnly:bt,handleSelectConversation:Et,completeActiveConversations:$t}=function({enabled:e=!1,conversationHistoryEndpoint:n,markConversationReadEndpoint:a,markConversationCompletedEndpoint:s,headers:c,userData:l,currentConversationId:d,loadConversationById:u,reconnectHandoff:m,resetHandoff:p}){const[h,f]=t(!1),[g,y]=t([]),[v,w]=t(!1),[b,E]=t(!1),$=o(null),x=o(c);x.current=c;const _=g.some(e=>e.hasUnread),k=l?.userId,N=c?.["x-bf-fingerprint"],C=!(!k&&!N);i(()=>{if(!e||!n||!C)return;let t=!1;return we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}),()=>{t=!0}},[n,C,k,N]),i(()=>{if(!(e&&h&&n&&C))return;let t=!1;return w(!0),we({endpoint:n,headers:x.current,externalUserId:k}).then(e=>{t||y(e)}).catch(()=>{t||y([])}).finally(()=>{t||w(!1)}),()=>{t=!0}},[e,h,n,C,k,N]);const I=r(({conversationId:e,isHandoff:t,isCompleted:r})=>{d&&!b&&($.current=d),u(e),E(r),t?m?.(e):p?.(),a&&be({endpoint:a,conversationId:e,headers:x.current}).catch(()=>{}),f(!1)},[e,d,b,u,m,p,a]),S=r(()=>{if(!s)return;const e=g.filter(e=>"active"===e.status).map(e=>e.conversationId),t=new Set([$.current,b?null:d,...e].filter(e=>!!e));y(e=>e.map(e=>t.has(e.conversationId)?{...e,status:"completed"}:e)),t.forEach(e=>{Ee({endpoint:s,conversationId:e,headers:x.current}).catch(()=>{})}),$.current=null},[s,d,b,g]);return{showHistory:h,setShowHistory:f,conversations:g,isLoadingHistory:v,hasUnreadConversations:_,isViewOnly:b,setIsViewOnly:E,handleSelectConversation:I,completeActiveConversations:S}}({enabled:Ue,conversationHistoryEndpoint:ee,markConversationReadEndpoint:te,markConversationCompletedEndpoint:re,headers:I,userData:U??void 0,currentConversationId:Ae,loadConversationById:pt,reconnectHandoff:J,resetHandoff:Y}),{scrollToLastAnswer:xt,scrollToAnswer:_t}=((e,t,r)=>({scrollToLastAnswer:()=>{requestAnimationFrame(()=>{const r=e.current?.[e.current.length-1],n=t.current;if(r&&n){const e=r.getBoundingClientRect(),t=n.getBoundingClientRect(),a=n.scrollTop+(e.top-t.top)-80;n.scrollTo({top:a,behavior:"smooth"})}})},scrollToAnswer:r=>{requestAnimationFrame(()=>{const n=e.current?.[r],a=t.current;if(n&&a){const e=n.getBoundingClientRect(),t=a.getBoundingClientRect(),r=a.scrollTop+(e.top-t.top)-80;a.scrollTo({top:r,behavior:"smooth"})}})},scrollToBottom:()=>{setTimeout(()=>{r?.current&&t.current&&r.current.scrollIntoView({behavior:"smooth",block:"end"})},200)}}))(ot,it,dt),{subscribeToStateChanges:kt}=(()=>{const e=o([]),{showResults:t,answers:r,isLoadingConversation:n,loadError:a}=Nr();return i(()=>{const s={showResults:t,answers:r,isLoading:n,error:a};e.current.forEach(e=>e(s))},[t,r,n,a]),{subscribeToStateChanges:s=>(e.current.push(s),s({showResults:t,answers:r,isLoading:n,error:a}),()=>{e.current=e.current.filter(e=>e!==s)})}})(),{includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,handleIncludePageToggle:St,fetchPageContext:Pt}=(({isAgentAssist:e,apiKey:n,trackEvent:a})=>{const[s,o]=t(!1),[c,l]=t(!1),[d,u]=t(!1),m=r((e,t=5e3)=>new Promise((r,a)=>{const s=ye();let o;const i=e=>{e.data.requestId===s&&(clearTimeout(o),window.removeEventListener("message",i),r(e.data))};o=setTimeout(()=>{window.removeEventListener("message",i),a(new Error("Request timeout"))},t),window.addEventListener("message",i),window.parent.postMessage({...e,requestId:s,widgetKey:n},"*")}),[n]),p=r(async e=>{l(!0);try{if(e){if(!(await m({type:"REQUEST_PAGE_PERMISSION"})).granted)throw a?.("Include Page Permission Denied",{}),new Error("Permission denied");window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!0,widgetKey:n},"*"),a?.("Include Page Enabled",{}),o(!0)}else window.parent.postMessage({type:"UPDATE_PAGE_TOGGLE_STATE",enabled:!1,widgetKey:n},"*"),a?.("Include Page Disabled",{}),o(!1)}catch(t){console.error("Failed to toggle include page:",t),o(!1)}finally{l(!1)}},[n,m,a]),h=r(async(t,r)=>{if(s&&e&&!d)try{l(!0);const e=await m({type:"REQUEST_PAGE_CONTENT"},5e3);return e.success&&e.content?(a?.("Page Content Included",{conversationId:t,searchQuery:r,contentLength:e.content.length}),[{type:"text",text:`I am currently viewing this web page:\n\n${e.content}`}]):void 0}catch(n){return console.error("Failed to fetch page content:",n),void a?.("Page Content Fetch Failed",{conversationId:t,searchQuery:r})}finally{l(!1)}},[s,e,d,m,a]);return i(()=>{if(!e)return;const t=e=>{const t=e.data;"INCLUDE_PAGE_STATE"===t.type&&(o(t.enabled||!1),u(t.disabled||!1))};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)},[e]),{includePageEnabled:s,includePageLoading:c,includePageDisabled:d,handleIncludePageToggle:p,fetchPageContext:h}})({isAgentAssist:B,apiKey:h??"unknown",trackEvent:R}),Tt=async({reader:e,searchQueryId:t,conversationId:r,onFirstEvent:n})=>{ut.current=e;let a="";try{let s,o,i=!1,c=!0,l=!1;for(;({done:i,value:o}=await e.read()),!i&&ut.current===e;){c&&(c=!1,n?.());const e=(new TextDecoder).decode(o).split(/\n\n/).filter(e=>e.startsWith("data: ")).map(e=>e.replace(/^data: /,"").trim());for(const n of e)try{if("[DONE]"===n)continue;const e=JSON.parse(n);if("status-message"===e.type&&ie(gr({message:e.message})),"answer-text-chunk"===e.type){a+=e.content,ie(dr({text:e.content}));const t=X(a);if(l=t.uncertain,l){const e=ze.uncertaintyFallbackText?.[t.language??"en"]??a??"I don't know.";ie(pr({uncertaintyText:e}))}}"answer-error"===e.type&&ie(ur({error:ze.errorText||e.message})),"action-buttons"===e.type&&(s=e.searchIntentId,ie(vr({searchIntentId:s,actions:e.actions}))),"get-action-inputs"===e.type&&(s=e.searchIntentId,ie(yr({searchIntentId:e.searchIntentId,inputs:e.inputs,actionId:e.actionId,schema:e.schema,initialValues:e.values,onSubmit:async n=>{if("client_execution"===e.actionType){const o=await(a=e.actionKey,s=n,new Promise(e=>{const t=crypto.randomUUID(),r=n=>{n.data.messageId===t&&"CLIENT_EXECUTION_RESULT"===n.data.type&&(window.removeEventListener("message",r),e(n.data.result))};window.addEventListener("message",r),window.parent.postMessage({type:"CLIENT_EXECUTION",messageId:t,actionKey:a,inputs:s},"*"),setTimeout(()=>{window.removeEventListener("message",r),e({success:!1,reason:`Client Action handler with key ${a} timed out`})},5e3)}));return jt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,results:o})}var a,s;return"run_workflow"===e.actionType?(ie(hr()),At({searchQueryId:t,conversationId:r,parameters:n})):Rt({searchQueryId:t,conversationId:r,searchIntentId:e.searchIntentId,actionId:e.actionId,parameters:n})}}))),"citations"===e.type&&ie(lr({searchQueryId:t,results:e.data,state:"completed"}))}catch{console.warn("Failed to parse answer stream block")}}return{answer:a,searchIntentId:s,isUncertain:l}}catch(s){if(ut.current!==e)return{answer:"",searchIntentId:void 0,isUncertain:!1};throw s}finally{ut.current===e&&(ut.current=null,e.releaseLock())}},At=async({searchQueryId:e,conversationId:t,context:r,attachments:n,parameters:a})=>{try{const s=(async(e,t)=>{if(P&&!x)try{return await Ce({endpoint:P,searchQueryId:e,headers:I,conversationId:t})}catch(r){return void console.error("Error fetching follow-up questions:",r)}})(e),o=await Ne({endpoint:y,headers:I,body:{type:"generate-for-query",conversationId:t,searchQueryId:e,profileId:U?.userId,...r&&{context:r},...n?.length&&{attachments:n},...a&&{parameters:a}}}),i=o.body?.getReader();if(!i)return;const{answer:c,searchIntentId:l,isUncertain:d}=await Tt({reader:i,searchQueryId:e,conversationId:t,onFirstEvent:()=>{R?.("First Streamed Answer Chunk Received",{conversationId:t,searchQueryId:e})}});if(!c)return;s.then(e=>{e&&e.length>0&&!l&&ie((({questions:e,index:t})=>({type:Wt,payload:{questions:e,index:t}}))({questions:e}))}),R?.(d?"Answer Not Found":"Answer Found",{conversationId:t,searchQueryId:e})}catch(s){console.error("Error generating answer for query:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr())}},Rt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,parameters:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"invoke-action",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,parameters:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},jt=async({searchQueryId:e,searchIntentId:t,conversationId:r,actionId:n,results:a})=>{ie(hr());try{const s=await Ne({endpoint:y,headers:I,body:{type:"client-execution-result",conversationId:r,searchQueryId:e,searchIntentId:t,actionId:n,results:a,profileId:U?.userId}}),o=s.body?.getReader();if(!o)return;await Tt({reader:o,searchQueryId:e})}catch(s){console.error("Error generating answer for action:",s),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{ie(mr()),pe(!1)}},Ot=async({searchQuery:e,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,knowledgeGroupCollectionIds:s})=>{const o=s??Ze,i=await ke({endpoint:g,query:e,collectionId:o,headers:I,conversationId:t,attributes:r,secretAttributes:n,allowedRegions:a,source:B?"agent_assist":void 0});if(0!==i.results.length||i.isAgenticResponse)return ie(lr({searchQueryId:i.searchQueryId,results:i.results})),i.searchQueryId;R?.("No Articles Found",{conversationId:t,searchQuery:e})},Dt=async({searchQuery:e=ce.trim(),event:t})=>{if(!e)return;const r=Ae||ye();Re(r);const n=Je();We(),pe(!0),ge(!0),Se(oe.length),xt(),ie((({id:e,query:t,attachments:r})=>({type:Kt,payload:{id:e,query:t,attachments:r}}))({query:e,attachments:n})),await Promise.resolve(),lt.current?.focus();const a=await Pt(r,e);if(ne&&ne.length>0&&!nt.current)return at.current={searchQuery:e,conversationId:r,attributes:{...U},secretAttributes:M,allowedRegions:V,pageContext:a??void 0,fileAttachments:n.length>0?n:void 0},ie((({index:e}={})=>({type:sr,payload:{index:e}}))()),void pe(!1);try{const s={...U},o=nt.current?.collectionIds,i=await Ot({searchQuery:e,conversationId:r,attributes:s,secretAttributes:M,allowedRegions:V,knowledgeGroupCollectionIds:o});i?(t&&R?.(t.name,{conversationId:r,searchQuery:e,searchQueryId:i,...t.metaData}),await At({searchQueryId:i,conversationId:r,context:a,attachments:n.length>0?n:void 0})):ie(fr())}catch(s){console.error("Error generating answer:",s),t&&R?.(`${t.name} - Search Error`,{conversationId:r,searchQuery:e,...t.metaData}),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}},zt=async e=>{nt.current=e;const t=at.current;if(t){at.current=null,ie((({index:e}={})=>({type:or,payload:{index:e}}))()),pe(!0);try{const r=await Ot({searchQuery:t.searchQuery,conversationId:t.conversationId,attributes:t.attributes,secretAttributes:t.secretAttributes,allowedRegions:t.allowedRegions,knowledgeGroupCollectionIds:e.collectionIds});r?(R?.("Knowledge Group Selected",{conversationId:t.conversationId,searchQuery:t.searchQuery,searchQueryId:r,knowledgeGroupId:e.id,knowledgeGroupName:e.name}),await At({searchQueryId:r,conversationId:t.conversationId,context:t.pageContext,attachments:t.fileAttachments})):ie(fr())}catch(r){console.error("Error generating answer after group selection:",r),ie(ur({error:ze.errorText||"Sorry, we were unable to process the request right now. Please try again in a moment."}))}finally{pe(!1)}}},Lt=e=>{if($t(),bt(!1),Y?.(),ut.current){const e=ut.current;ut.current=null,function(e){try{e.cancel().catch(e=>{console.warn("Error cancelling stream reader:",e)});try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}catch(r){console.warn("Error cancelling stream reader:",r);try{e.releaseLock()}catch(t){console.warn("Error releasing stream reader lock:",t)}}}(e)}pe(!1),le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),je(),nt.current=null,at.current=null,R?.("New Thread Created",{oldConversationId:Ae}),st.current&&(st.current.style.height="auto"),e&&(le(e),Dt({searchQuery:e,event:{name:"New Thread Created with Query"}}))};l(se,()=>({createNewThread:Lt,showFollowUpThread:e=>{rt(e)},subscribeToStateChanges:kt,focusSearchField:()=>ct.current?.focus()||lt.current?.focus(),showCloseButton:(e=!0)=>{De(e)},loadConversation:pt})),i(()=>{Xe(s)},[s]),i(()=>{et(m)},[m]);const Ft=async(e,t,r)=>{if(w){ie((({feedback:e,index:t})=>({type:Xt,payload:{feedback:e,index:t}}))({feedback:e,index:r}));try{await _e({endpoint:w,searchQueryId:t,response:e,headers:I,conversationId:Ae}),R?.("accept"===e?"Answer Accepted":"Answer Rejected",{conversationId:Ae,searchQueryId:t})}catch(n){console.error("Error sending feedback:",n),ie((({index:e}={})=>({type:Yt,payload:{index:e}}))({index:r}))}}},Ut=async e=>{const t=void 0!==e?e:de;t.trim()&&(le(t),ue(""),await Dt({searchQuery:t,event:{name:"Follow-up Search Field Submitted"}}))};i(()=>{const e=()=>{new URLSearchParams(window.location.search).get("conversation")||(le(""),ue(""),ge(!1),ie(cr()),Se(0),We(),st.current&&(st.current.style.height="auto"))};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);const Mt=e=>{R?.("Follow-up Question Clicked",{conversationId:Ae,question:e}),Dt({searchQuery:e,event:{name:"Follow-up Question Clicked"}})},Vt=({action:e,searchQueryId:t,query:r,answer:n})=>{R?.("Next Best Action Clicked",{conversationId:Ae,searchQueryId:t,action:e.label});const a=((e,t)=>({conversationId:t,messages:e.map(e=>({question:e.question,answer:Qt(e.blocks)}))}))(oe,Ae);L?.({action:e,searchQueryId:t,query:r,answer:n,conversation:a})};return i(()=>{const e=it.current;if(!e||!K)return;let t=0,r=null;const n=()=>{const r=(()=>{const t=e.firstElementChild,r=t?.scrollHeight??e.scrollHeight,n=document.querySelector('[data-name="BrandFooter"]')?.clientHeight??0,a=document.querySelector('[data-name="Header"]')?.clientHeight??0,s=fe&&tt?70:0,o=document.querySelector('[data-name="ChatSearch"]')?.clientHeight??0,i=r+n+s+a+32;return fe?Math.max(i,o):i})();r>0&&r!==t&&(t=r,window.parent.postMessage({type:"RESIZE_IFRAME",height:r,widgetKey:h},"*"))},a=setTimeout(n,100),s=new ResizeObserver(()=>{null!==r&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{n(),r=null})}),o=e.firstElementChild;return o&&s.observe(o),s.observe(e),()=>{clearTimeout(a),null!==r&&cancelAnimationFrame(r),s.disconnect()}},[K,h,fe,tt]),/* @__PURE__ */e.createElement("div",{className:Z("w-full relative h-dvh flex flex-col justify-between @container","md:h-auto md:p-4 md:bg-dark-100",T),"data-name":"ChatSearch",style:q},
|
|
83
|
+
/* @__PURE__ */e.createElement(tn,{toasts:Qe,onDismiss:Ve}),(O||!fe)&&/* @__PURE__ */e.createElement(Yr,{showHistoryButton:Ue,isSearchWidget:K,"data-name":"Header",headerText:ze.headerText,onToggleSizeButtonClick:()=>{A?.()},onBackButtonClick:()=>{Lt()},onCloseWidgetClick:()=>j?.(),showHistory:ht,hasUnreadConversations:vt,onHistoryButtonClick:()=>ft(!0),onHistoryBackClick:()=>ft(!1),className:Z("@3xl:mb-4",{"!block":fe&&K})}),
|
|
84
84
|
/* @__PURE__ */e.createElement(Pe,{className:"w-full relative h-auto flex-grow [&>[data-radix-scroll-area-viewport]>div:first-child]:!block",ref:it},
|
|
85
|
-
/* @__PURE__ */e.createElement(u,null,ht?/* @__PURE__ */e.createElement(
|
|
86
|
-
/* @__PURE__ */e.createElement(
|
|
85
|
+
/* @__PURE__ */e.createElement(u,null,ht?/* @__PURE__ */e.createElement(ln,{conversations:gt,isLoading:yt,onSelectConversation:Et}):Oe?/* @__PURE__ */e.createElement(rn,null):fe?/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"results",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5},className:"w-full max-w-[100vw] space-y-4 p-3 md:p-0"},oe.map((t,r)=>/* @__PURE__ */e.createElement(d.div,{key:r,ref:e=>ot.current[r]=e,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.1*r},className:"space-y-4 last:!mb-8"},
|
|
86
|
+
/* @__PURE__ */e.createElement(Kr,{index:r,blocks:t.blocks,question:t.question,attachments:t.attachments,state:t.state,searchResults:t.searchResults,searchQueryId:t.searchQueryId,searchIntentId:t.searchIntentId,hideCitations:H,feedback:t.feedback,onFeedback:e=>{Ft(e,t.searchQueryId,r)},disableFeedback:k,textConfig:ze,redirectRules:Q,nextBestActions:D,actions:t.actions,handleActionClick:Vt,isLastAnswer:r===oe.length-1,onFeedbackReasonSubmit:e=>{(async(e,t)=>{if(b)try{await xe({endpoint:b,searchQueryId:t,reason:e,headers:I})}catch(r){console.error("Error sending feedback reason:",r)}})(e,t.searchQueryId)},hasError:t.hasError,statusMessage:t.statusMessage,knowledgeSourceGroups:ne,onKnowledgeGroupSelect:e=>{zt(e)}}),r===oe.length-1&&!x&&t.followUpQuestions&&"completed"===t.state&&!t.hasError&&/* @__PURE__ */e.createElement(Hr,{questions:t.followUpQuestions,onQuestionClick:Mt}))))):/* @__PURE__ */e.createElement(e.Fragment,null,/* @__PURE__ */e.createElement(d.div,{key:"search",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5},className:"w-full md:space-y-4"},
|
|
87
87
|
/* @__PURE__ */e.createElement("div",{className:Z("pb-4",K?"bg-transparent p-3 md:p-0":"px-3 bg-primary md:p-0 md:bg-transparent")},
|
|
88
88
|
/* @__PURE__ */e.createElement(d.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.4}},
|
|
89
|
-
/* @__PURE__ */e.createElement(
|
|
90
|
-
/* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:Ae,question:e.question}),void pt(e.conversationId);Dt({searchQuery:e.question,event:{name:"Suggested Question Clicked"}})},title:ze.suggestionsTitle}),O&&z&&z.length>0&&/* @__PURE__ */e.createElement("div",{className:"mt-4 mb-4 px-3 @3xl:px-0"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement(
|
|
89
|
+
/* @__PURE__ */e.createElement(Jr,{ref:ct,query:ce,onQueryChange:e=>{var t;le(e),st.current&&((t=st.current).style.height="auto",t.style.height=`${t.scrollHeight}px`)},onSearch:()=>{(async(e=ce.trim())=>{await Dt({searchQuery:e,event:{name:"Primary Field Search Submitted"}})})()},textConfig:ze,collections:a,currentCollectionId:Ze,onCollectionChange:e=>{Xe(e),c?.(e)},allowedRegions:V,currentRegion:Ye,onRegionChange:e=>{et(e),p?.(e),R?.("Region Changed",{region:e,conversationId:Ae})},apiKey:h,fetchRegionConfig:f,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,isSearching:me,autocompleteSuggestions:mt,onAutocompleteSuggestionSelect:e=>{Dt({searchQuery:e.question,event:{name:"Autocomplete Suggestion Clicked"}})},isAgentAssist:B,includePageEnabled:Nt,includePageLoading:Ct,includePageDisabled:It,onIncludePageToggle:St}))),
|
|
90
|
+
/* @__PURE__ */e.createElement(Te,{suggestions:n,onQuestionClick:e=>{if(e.conversationId)return R?.("Recent Conversation Clicked",{conversationId:Ae,question:e.question}),void pt(e.conversationId);Dt({searchQuery:e.question,event:{name:"Suggested Question Clicked"}})},title:ze.suggestionsTitle}),O&&z&&z.length>0&&/* @__PURE__ */e.createElement("div",{className:"mt-4 mb-4 px-3 @3xl:px-0"},/* @__PURE__ */e.createElement("div",{className:"space-y-3"},/* @__PURE__ */e.createElement(Fr,{nextBestActions:z||[],onActionClick:e=>Vt({action:e,searchQueryId:"",query:"",answer:""})})))))),fe&&oe.length>1&&/* @__PURE__ */e.createElement("div",{className:"hidden lg:block"},/* @__PURE__ */e.createElement(Gr,{questions:oe.map(e=>e.question),activeIndex:Ie,onNavigate:e=>{Se(e),_t(e)},offset:C})),N&&O&&!(fe&&tt)&&/* @__PURE__ */e.createElement("div",{"data-name":"disclaimer",className:Z("mt-2 px-3 @3xl:px-0 text-xs text-dark-500 flex items-center gap-1 justify-center text-center w-full md:static md:mt-4 md:text-left md:flex md:gap-4 leading-5",K?"static mb-2 md:text-left [&>svg]:flex-shrink-0":"absolute bottom-12")},
|
|
91
91
|
/* @__PURE__ */e.createElement(ae,{iconName:"Info",className:"size-4"}),
|
|
92
|
-
/* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:
|
|
92
|
+
/* @__PURE__ */e.createElement(F,{className:"[&_a]:underline [&_a:hover]:no-underline",remarkPlugins:mn,rehypePlugins:pn,components:hn},N)),null!=G&&fe&&!ht&&/* @__PURE__ */e.createElement("div",{className:"-mt-6 w-full max-w-[100vw] px-3 pb-0 pt-0 text-foreground md:px-0"},G),
|
|
93
93
|
/* @__PURE__ */e.createElement("div",{ref:dt})),fe&&tt&&!wt&&!W&&!ht&&(()=>{const t=oe.some(e=>"awaiting-knowledge-group"===e.state);/* @__PURE__ */
|
|
94
|
-
return e.createElement(
|
|
95
|
-
/* @__PURE__ */e.createElement(
|
|
96
|
-
//# sourceMappingURL=ChatSearch.
|
|
94
|
+
return e.createElement(Xr,{ref:lt,initialQuery:de,onQueryChange:ue,isSearching:me,handleFollowUpSearch:Ut,textConfig:ze,enableFileAttachment:Fe,attachedFiles:Ke,isUploading:Be,onAddFiles:He,onRemoveFile:Ge,disabled:t})})(),fe&&wt&&!W&&!ht&&/* @__PURE__ */e.createElement(dn,{onStartNewConversation:()=>Lt()}),!ht&&W)});fn.displayName="ChatSearch";const gn=c(({featureFlags:t,...r},n)=>/* @__PURE__ */e.createElement(fe,{flags:t},/* @__PURE__ */e.createElement(kr,{searchPath:r.searchPath,contentTypeEndpoint:r.contentTypeEndpoint,widgetKey:r.apiKey},
|
|
95
|
+
/* @__PURE__ */e.createElement(fn,{...r,ref:n}))));gn.displayName="ChatSearch";export{gn as C,dn as R,kr as a,Qr as b,Nr as u};
|
|
96
|
+
//# sourceMappingURL=ChatSearch.B3MthUTR.js.map
|