@utilia-os/widget 1.0.0

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.
@@ -0,0 +1,2 @@
1
+ var UtiliaWidget=function(t){"use strict";function e(t,e){return function(){return t.apply(e,arguments)}}const{toString:n}=Object.prototype,{getPrototypeOf:i}=Object,{iterator:r,toStringTag:s}=Symbol,a=(t=>e=>{const i=n.call(e);return t[i]||(t[i]=i.slice(8,-1).toLowerCase())})(Object.create(null)),o=t=>(t=t.toLowerCase(),e=>a(e)===t),l=t=>e=>typeof e===t,{isArray:c}=Array,d=l("undefined");function u(t){return null!==t&&!d(t)&&null!==t.constructor&&!d(t.constructor)&&m(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const h=o("ArrayBuffer");const p=l("string"),m=l("function"),g=l("number"),f=t=>null!==t&&"object"==typeof t,b=t=>{if("object"!==a(t))return!1;const e=i(t);return!(null!==e&&e!==Object.prototype&&null!==Object.getPrototypeOf(e)||s in t||r in t)},y=o("Date"),x=o("File"),w=o("Blob"),v=o("FileList"),E=o("URLSearchParams"),[C,A,S,k]=["ReadableStream","Request","Response","Headers"].map(o);function R(t,e,{allOwnKeys:n=!1}={}){if(null==t)return;let i,r;if("object"!=typeof t&&(t=[t]),c(t))for(i=0,r=t.length;i<r;i++)e.call(null,t[i],i,t);else{if(u(t))return;const r=n?Object.getOwnPropertyNames(t):Object.keys(t),s=r.length;let a;for(i=0;i<s;i++)a=r[i],e.call(null,t[a],a,t)}}function N(t,e){if(u(t))return null;e=e.toLowerCase();const n=Object.keys(t);let i,r=n.length;for(;r-- >0;)if(i=n[r],e===i.toLowerCase())return i;return null}const T="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,O=t=>!d(t)&&t!==T;const I=(t=>e=>t&&e instanceof t)("undefined"!=typeof Uint8Array&&i(Uint8Array)),L=o("HTMLFormElement"),D=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),U=o("RegExp"),P=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),i={};R(n,(n,r)=>{let s;!1!==(s=e(n,r,t))&&(i[r]=s||n)}),Object.defineProperties(t,i)};const F=o("AsyncFunction"),B=(j="function"==typeof setImmediate,_=m(T.postMessage),j?setImmediate:_?(z=`axios@${Math.random()}`,M=[],T.addEventListener("message",({source:t,data:e})=>{t===T&&e===z&&M.length&&M.shift()()},!1),t=>{M.push(t),T.postMessage(z,"*")}):t=>setTimeout(t));var j,_,z,M;const q="undefined"!=typeof queueMicrotask?queueMicrotask.bind(T):"undefined"!=typeof process&&process.nextTick||B,$={isArray:c,isArrayBuffer:h,isBuffer:u,isFormData:t=>{let e;return t&&("function"==typeof FormData&&t instanceof FormData||m(t.append)&&("formdata"===(e=a(t))||"object"===e&&m(t.toString)&&"[object FormData]"===t.toString()))},isArrayBufferView:function(t){let e;return e="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&h(t.buffer),e},isString:p,isNumber:g,isBoolean:t=>!0===t||!1===t,isObject:f,isPlainObject:b,isEmptyObject:t=>{if(!f(t)||u(t))return!1;try{return 0===Object.keys(t).length&&Object.getPrototypeOf(t)===Object.prototype}catch(e){return!1}},isReadableStream:C,isRequest:A,isResponse:S,isHeaders:k,isUndefined:d,isDate:y,isFile:x,isBlob:w,isRegExp:U,isFunction:m,isStream:t=>f(t)&&m(t.pipe),isURLSearchParams:E,isTypedArray:I,isFileList:v,forEach:R,merge:function t(){const{caseless:e,skipUndefined:n}=O(this)&&this||{},i={},r=(r,s)=>{const a=e&&N(i,s)||s;b(i[a])&&b(r)?i[a]=t(i[a],r):b(r)?i[a]=t({},r):c(r)?i[a]=r.slice():n&&d(r)||(i[a]=r)};for(let s=0,a=arguments.length;s<a;s++)arguments[s]&&R(arguments[s],r);return i},extend:(t,n,i,{allOwnKeys:r}={})=>(R(n,(n,r)=>{i&&m(n)?t[r]=e(n,i):t[r]=n},{allOwnKeys:r}),t),trim:t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:t=>(65279===t.charCodeAt(0)&&(t=t.slice(1)),t),inherits:(t,e,n,i)=>{t.prototype=Object.create(e.prototype,i),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},toFlatObject:(t,e,n,r)=>{let s,a,o;const l={};if(e=e||{},null==t)return e;do{for(s=Object.getOwnPropertyNames(t),a=s.length;a-- >0;)o=s[a],r&&!r(o,t,e)||l[o]||(e[o]=t[o],l[o]=!0);t=!1!==n&&i(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},kindOf:a,kindOfTest:o,endsWith:(t,e,n)=>{t=String(t),(void 0===n||n>t.length)&&(n=t.length),n-=e.length;const i=t.indexOf(e,n);return-1!==i&&i===n},toArray:t=>{if(!t)return null;if(c(t))return t;let e=t.length;if(!g(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},forEachEntry:(t,e)=>{const n=(t&&t[r]).call(t);let i;for(;(i=n.next())&&!i.done;){const n=i.value;e.call(t,n[0],n[1])}},matchAll:(t,e)=>{let n;const i=[];for(;null!==(n=t.exec(e));)i.push(n);return i},isHTMLForm:L,hasOwnProperty:D,hasOwnProp:D,reduceDescriptors:P,freezeMethods:t=>{P(t,(e,n)=>{if(m(t)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=t[n];m(i)&&(e.enumerable=!1,"writable"in e?e.writable=!1:e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(t,e)=>{const n={},i=t=>{t.forEach(t=>{n[t]=!0})};return c(t)?i(t):i(String(t).split(e)),n},toCamelCase:t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,e,n){return e.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(t,e)=>null!=t&&Number.isFinite(t=+t)?t:e,findKey:N,global:T,isContextDefined:O,isSpecCompliantForm:function(t){return!!(t&&m(t.append)&&"FormData"===t[s]&&t[r])},toJSONObject:t=>{const e=new Array(10),n=(t,i)=>{if(f(t)){if(e.indexOf(t)>=0)return;if(u(t))return t;if(!("toJSON"in t)){e[i]=t;const r=c(t)?[]:{};return R(t,(t,e)=>{const s=n(t,i+1);!d(s)&&(r[e]=s)}),e[i]=void 0,r}}return t};return n(t,0)},isAsyncFn:F,isThenable:t=>t&&(f(t)||m(t))&&m(t.then)&&m(t.catch),setImmediate:B,asap:q,isIterable:t=>null!=t&&m(t[r])};function W(t,e,n,i,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}$.inherits(W,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$.toJSONObject(this.config),code:this.code,status:this.status}}});const H=W.prototype,K={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{K[t]={value:t}}),Object.defineProperties(W,K),Object.defineProperty(H,"isAxiosError",{value:!0}),W.from=(t,e,n,i,r,s)=>{const a=Object.create(H);$.toFlatObject(t,a,function(t){return t!==Error.prototype},t=>"isAxiosError"!==t);const o=t&&t.message?t.message:"Error",l=null==e&&t?t.code:e;return W.call(a,o,l,n,i,r),t&&null==a.cause&&Object.defineProperty(a,"cause",{value:t,configurable:!0}),a.name=t&&t.name||"Error",s&&Object.assign(a,s),a};function V(t){return $.isPlainObject(t)||$.isArray(t)}function J(t){return $.endsWith(t,"[]")?t.slice(0,-2):t}function G(t,e,n){return t?t.concat(e).map(function(t,e){return t=J(t),!n&&e?"["+t+"]":t}).join(n?".":""):e}const X=$.toFlatObject($,{},null,function(t){return/^is[A-Z]/.test(t)});function Y(t,e,n){if(!$.isObject(t))throw new TypeError("target must be an object");e=e||new FormData;const i=(n=$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(t,e){return!$.isUndefined(e[t])})).metaTokens,r=n.visitor||c,s=n.dots,a=n.indexes,o=(n.Blob||"undefined"!=typeof Blob&&Blob)&&$.isSpecCompliantForm(e);if(!$.isFunction(r))throw new TypeError("visitor must be a function");function l(t){if(null===t)return"";if($.isDate(t))return t.toISOString();if($.isBoolean(t))return t.toString();if(!o&&$.isBlob(t))throw new W("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(t)||$.isTypedArray(t)?o&&"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}function c(t,n,r){let o=t;if(t&&!r&&"object"==typeof t)if($.endsWith(n,"{}"))n=i?n:n.slice(0,-2),t=JSON.stringify(t);else if($.isArray(t)&&function(t){return $.isArray(t)&&!t.some(V)}(t)||($.isFileList(t)||$.endsWith(n,"[]"))&&(o=$.toArray(t)))return n=J(n),o.forEach(function(t,i){!$.isUndefined(t)&&null!==t&&e.append(!0===a?G([n],i,s):null===a?n:n+"[]",l(t))}),!1;return!!V(t)||(e.append(G(r,n,s),l(t)),!1)}const d=[],u=Object.assign(X,{defaultVisitor:c,convertValue:l,isVisitable:V});if(!$.isObject(t))throw new TypeError("data must be an object");return function t(n,i){if(!$.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+i.join("."));d.push(n),$.forEach(n,function(n,s){!0===(!($.isUndefined(n)||null===n)&&r.call(e,n,$.isString(s)?s.trim():s,i,u))&&t(n,i?i.concat(s):[s])}),d.pop()}}(t),e}function Z(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(t){return e[t]})}function Q(t,e){this._pairs=[],t&&Y(t,this,e)}const tt=Q.prototype;function et(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function nt(t,e,n){if(!e)return t;const i=n&&n.encode||et;$.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(e,n):$.isURLSearchParams(e)?e.toString():new Q(e,n).toString(i),s){const e=t.indexOf("#");-1!==e&&(t=t.slice(0,e)),t+=(-1===t.indexOf("?")?"?":"&")+s}return t}tt.append=function(t,e){this._pairs.push([t,e])},tt.toString=function(t){const e=t?function(e){return t.call(this,e,Z)}:Z;return this._pairs.map(function(t){return e(t[0])+"="+e(t[1])},"").join("&")};class it{constructor(){this.handlers=[]}use(t,e,n){return this.handlers.push({fulfilled:t,rejected:e,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){$.forEach(this.handlers,function(e){null!==e&&t(e)})}}const rt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},st={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Q,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},at="undefined"!=typeof window&&"undefined"!=typeof document,ot="object"==typeof navigator&&navigator||void 0,lt=at&&(!ot||["ReactNative","NativeScript","NS"].indexOf(ot.product)<0),ct="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,dt=at&&window.location.href||"http://localhost",ut={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:at,hasStandardBrowserEnv:lt,hasStandardBrowserWebWorkerEnv:ct,navigator:ot,origin:dt},Symbol.toStringTag,{value:"Module"})),...st};function ht(t){function e(t,n,i,r){let s=t[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=t.length;if(s=!s&&$.isArray(i)?i.length:s,o)return $.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a;i[s]&&$.isObject(i[s])||(i[s]=[]);return e(t,n,i[s],r)&&$.isArray(i[s])&&(i[s]=function(t){const e={},n=Object.keys(t);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],e[s]=t[s];return e}(i[s])),!a}if($.isFormData(t)&&$.isFunction(t.entries)){const n={};return $.forEachEntry(t,(t,i)=>{e(function(t){return $.matchAll(/\w+|\[(\w*)]/g,t).map(t=>"[]"===t[0]?"":t[1]||t[0])}(t),i,n,0)}),n}return null}const pt={transitional:rt,adapter:["xhr","http","fetch"],transformRequest:[function(t,e){const n=e.getContentType()||"",i=n.indexOf("application/json")>-1,r=$.isObject(t);r&&$.isHTMLForm(t)&&(t=new FormData(t));if($.isFormData(t))return i?JSON.stringify(ht(t)):t;if($.isArrayBuffer(t)||$.isBuffer(t)||$.isStream(t)||$.isFile(t)||$.isBlob(t)||$.isReadableStream(t))return t;if($.isArrayBufferView(t))return t.buffer;if($.isURLSearchParams(t))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(t,e){return Y(t,new ut.classes.URLSearchParams,{visitor:function(t,e,n,i){return ut.isNode&&$.isBuffer(t)?(this.append(e,t.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...e})}(t,this.formSerializer).toString();if((s=$.isFileList(t))||n.indexOf("multipart/form-data")>-1){const e=this.env&&this.env.FormData;return Y(s?{"files[]":t}:t,e&&new e,this.formSerializer)}}return r||i?(e.setContentType("application/json",!1),function(t,e,n){if($.isString(t))try{return(e||JSON.parse)(t),$.trim(t)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){const e=this.transitional||pt.transitional,n=e&&e.forcedJSONParsing,i="json"===this.responseType;if($.isResponse(t)||$.isReadableStream(t))return t;if(t&&$.isString(t)&&(n&&!this.responseType||i)){const n=!(e&&e.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(r){if(n){if("SyntaxError"===r.name)throw W.from(r,W.ERR_BAD_RESPONSE,this,null,this.response);throw r}}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ut.classes.FormData,Blob:ut.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],t=>{pt.headers[t]={}});const mt=$.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gt=Symbol("internals");function ft(t){return t&&String(t).trim().toLowerCase()}function bt(t){return!1===t||null==t?t:$.isArray(t)?t.map(bt):String(t)}function yt(t,e,n,i,r){return $.isFunction(i)?i.call(this,e,n):(r&&(e=n),$.isString(e)?$.isString(i)?-1!==e.indexOf(i):$.isRegExp(i)?i.test(e):void 0:void 0)}let xt=class{constructor(t){t&&this.set(t)}set(t,e,n){const i=this;function r(t,e,n){const r=ft(e);if(!r)throw new Error("header name must be a non-empty string");const s=$.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||e]=bt(t))}const s=(t,e)=>$.forEach(t,(t,n)=>r(t,n,e));if($.isPlainObject(t)||t instanceof this.constructor)s(t,e);else if($.isString(t)&&(t=t.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim()))s((t=>{const e={};let n,i,r;return t&&t.split("\n").forEach(function(t){r=t.indexOf(":"),n=t.substring(0,r).trim().toLowerCase(),i=t.substring(r+1).trim(),!n||e[n]&&mt[n]||("set-cookie"===n?e[n]?e[n].push(i):e[n]=[i]:e[n]=e[n]?e[n]+", "+i:i)}),e})(t),e);else if($.isObject(t)&&$.isIterable(t)){let n,i,r={};for(const e of t){if(!$.isArray(e))throw TypeError("Object iterator must return a key-value pair");r[i=e[0]]=(n=r[i])?$.isArray(n)?[...n,e[1]]:[n,e[1]]:e[1]}s(r,e)}else null!=t&&r(e,t,n);return this}get(t,e){if(t=ft(t)){const n=$.findKey(this,t);if(n){const t=this[n];if(!e)return t;if(!0===e)return function(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(t);)e[i[1]]=i[2];return e}(t);if($.isFunction(e))return e.call(this,t,n);if($.isRegExp(e))return e.exec(t);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,e){if(t=ft(t)){const n=$.findKey(this,t);return!(!n||void 0===this[n]||e&&!yt(0,this[n],n,e))}return!1}delete(t,e){const n=this;let i=!1;function r(t){if(t=ft(t)){const r=$.findKey(n,t);!r||e&&!yt(0,n[r],r,e)||(delete n[r],i=!0)}}return $.isArray(t)?t.forEach(r):r(t),i}clear(t){const e=Object.keys(this);let n=e.length,i=!1;for(;n--;){const r=e[n];t&&!yt(0,this[r],r,t,!0)||(delete this[r],i=!0)}return i}normalize(t){const e=this,n={};return $.forEach(this,(i,r)=>{const s=$.findKey(n,r);if(s)return e[s]=bt(i),void delete e[r];const a=t?function(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,e,n)=>e.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete e[r],e[a]=bt(i),n[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const e=Object.create(null);return $.forEach(this,(n,i)=>{null!=n&&!1!==n&&(e[i]=t&&$.isArray(n)?n.join(", "):n)}),e}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,e])=>t+": "+e).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...e){const n=new this(t);return e.forEach(t=>n.set(t)),n}static accessor(t){const e=(this[gt]=this[gt]={accessors:{}}).accessors,n=this.prototype;function i(t){const i=ft(t);e[i]||(!function(t,e){const n=$.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(t,i+n,{value:function(t,n,r){return this[i].call(this,e,t,n,r)},configurable:!0})})}(n,t),e[i]=!0)}return $.isArray(t)?t.forEach(i):i(t),this}};function wt(t,e){const n=this||pt,i=e||n,r=xt.from(i.headers);let s=i.data;return $.forEach(t,function(t){s=t.call(n,s,r.normalize(),e?e.status:void 0)}),r.normalize(),s}function vt(t){return!(!t||!t.__CANCEL__)}function Et(t,e,n){W.call(this,null==t?"canceled":t,W.ERR_CANCELED,e,n),this.name="CanceledError"}function Ct(t,e,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?e(new W("Request failed with status code "+n.status,[W.ERR_BAD_REQUEST,W.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):t(n)}xt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$.reduceDescriptors(xt.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(t){this[n]=t}}}),$.freezeMethods(xt),$.inherits(Et,W,{__CANCEL__:!0});const At=(t,e,n=3)=>{let i=0;const r=function(t,e){t=t||10;const n=new Array(t),i=new Array(t);let r,s=0,a=0;return e=void 0!==e?e:1e3,function(o){const l=Date.now(),c=i[a];r||(r=l),n[s]=o,i[s]=l;let d=a,u=0;for(;d!==s;)u+=n[d++],d%=t;if(s=(s+1)%t,s===a&&(a=(a+1)%t),l-r<e)return;const h=c&&l-c;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(t,e){let n,i,r=0,s=1e3/e;const a=(e,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),t(...e)};return[(...t)=>{const e=Date.now(),o=e-r;o>=s?a(t,e):(n=t,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,l=r(o);i=s;t({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:l||void 0,estimated:l&&a&&s<=a?(a-s)/l:void 0,event:n,lengthComputable:null!=a,[e?"download":"upload"]:!0})},n)},St=(t,e)=>{const n=null!=t;return[i=>e[0]({lengthComputable:n,total:t,loaded:i}),e[1]]},kt=t=>(...e)=>$.asap(()=>t(...e)),Rt=ut.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,ut.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(ut.origin),ut.navigator&&/(msie|trident)/i.test(ut.navigator.userAgent)):()=>!0,Nt=ut.hasStandardBrowserEnv?{write(t,e,n,i,r,s,a){if("undefined"==typeof document)return;const o=[`${t}=${encodeURIComponent(e)}`];$.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),$.isString(i)&&o.push(`path=${i}`),$.isString(r)&&o.push(`domain=${r}`),!0===s&&o.push("secure"),$.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(t){if("undefined"==typeof document)return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function Tt(t,e,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e);return t&&(i||0==n)?function(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}(t,e):e}const Ot=t=>t instanceof xt?{...t}:t;function It(t,e){e=e||{};const n={};function i(t,e,n,i){return $.isPlainObject(t)&&$.isPlainObject(e)?$.merge.call({caseless:i},t,e):$.isPlainObject(e)?$.merge({},e):$.isArray(e)?e.slice():e}function r(t,e,n,r){return $.isUndefined(e)?$.isUndefined(t)?void 0:i(void 0,t,0,r):i(t,e,0,r)}function s(t,e){if(!$.isUndefined(e))return i(void 0,e)}function a(t,e){return $.isUndefined(e)?$.isUndefined(t)?void 0:i(void 0,t):i(void 0,e)}function o(n,r,s){return s in e?i(n,r):s in t?i(void 0,n):void 0}const l={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(t,e,n)=>r(Ot(t),Ot(e),0,!0)};return $.forEach(Object.keys({...t,...e}),function(i){const s=l[i]||r,a=s(t[i],e[i],i);$.isUndefined(a)&&s!==o||(n[i]=a)}),n}const Lt=t=>{const e=It({},t);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:s,headers:a,auth:o}=e;if(e.headers=a=xt.from(a),e.url=nt(Tt(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),o&&a.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),$.isFormData(n))if(ut.hasStandardBrowserEnv||ut.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if($.isFunction(n.getHeaders)){const t=n.getHeaders(),e=["content-type","content-length"];Object.entries(t).forEach(([t,n])=>{e.includes(t.toLowerCase())&&a.set(t,n)})}if(ut.hasStandardBrowserEnv&&(i&&$.isFunction(i)&&(i=i(e)),i||!1!==i&&Rt(e.url))){const t=r&&s&&Nt.read(s);t&&a.set(r,t)}return e},Dt="undefined"!=typeof XMLHttpRequest&&function(t){return new Promise(function(e,n){const i=Lt(t);let r=i.data;const s=xt.from(i.headers).normalize();let a,o,l,c,d,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=i;function m(){c&&c(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let g=new XMLHttpRequest;function f(){if(!g)return;const i=xt.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Ct(function(t){e(t),m()},function(t){n(t),m()},{data:u&&"text"!==u&&"json"!==u?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:i,config:t,request:g}),g=null}g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout,"onloadend"in g?g.onloadend=f:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(f)},g.onabort=function(){g&&(n(new W("Request aborted",W.ECONNABORTED,t,g)),g=null)},g.onerror=function(e){const i=new W(e&&e.message?e.message:"Network Error",W.ERR_NETWORK,t,g);i.event=e||null,n(i),g=null},g.ontimeout=function(){let e=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||rt;i.timeoutErrorMessage&&(e=i.timeoutErrorMessage),n(new W(e,r.clarifyTimeoutError?W.ETIMEDOUT:W.ECONNABORTED,t,g)),g=null},void 0===r&&s.setContentType(null),"setRequestHeader"in g&&$.forEach(s.toJSON(),function(t,e){g.setRequestHeader(e,t)}),$.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),u&&"json"!==u&&(g.responseType=i.responseType),p&&([l,d]=At(p,!0),g.addEventListener("progress",l)),h&&g.upload&&([o,c]=At(h),g.upload.addEventListener("progress",o),g.upload.addEventListener("loadend",c)),(i.cancelToken||i.signal)&&(a=e=>{g&&(n(!e||e.type?new Et(null,t,g):e),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const b=function(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}(i.url);b&&-1===ut.protocols.indexOf(b)?n(new W("Unsupported protocol "+b+":",W.ERR_BAD_REQUEST,t)):g.send(r||null)})},Ut=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let n,i=new AbortController;const r=function(t){if(!n){n=!0,a();const e=t instanceof Error?t:this.reason;i.abort(e instanceof W?e:new Et(e instanceof Error?e.message:e))}};let s=e&&setTimeout(()=>{s=null,r(new W(`timeout ${e} of ms exceeded`,W.ETIMEDOUT))},e);const a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(t=>{t.unsubscribe?t.unsubscribe(r):t.removeEventListener("abort",r)}),t=null)};t.forEach(t=>t.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>$.asap(a),o}},Pt=function*(t,e){let n=t.byteLength;if(n<e)return void(yield t);let i,r=0;for(;r<n;)i=r+e,yield t.slice(r,i),r=i},Ft=async function*(t){if(t[Symbol.asyncIterator])return void(yield*t);const e=t.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},Bt=(t,e,n,i)=>{const r=async function*(t,e){for await(const n of Ft(t))yield*Pt(n,e)}(t,e);let s,a=0,o=t=>{s||(s=!0,i&&i(t))};return new ReadableStream({async pull(t){try{const{done:e,value:i}=await r.next();if(e)return o(),void t.close();let s=i.byteLength;if(n){let t=a+=s;n(t)}t.enqueue(new Uint8Array(i))}catch(e){throw o(e),e}},cancel:t=>(o(t),r.return())},{highWaterMark:2})},{isFunction:jt}=$,_t=(({Request:t,Response:e})=>({Request:t,Response:e}))($.global),{ReadableStream:zt,TextEncoder:Mt}=$.global,qt=(t,...e)=>{try{return!!t(...e)}catch(n){return!1}},$t=t=>{t=$.merge.call({skipUndefined:!0},_t,t);const{fetch:e,Request:n,Response:i}=t,r=e?jt(e):"function"==typeof fetch,s=jt(n),a=jt(i);if(!r)return!1;const o=r&&jt(zt),l=r&&("function"==typeof Mt?(t=>e=>t.encode(e))(new Mt):async t=>new Uint8Array(await new n(t).arrayBuffer())),c=s&&o&&qt(()=>{let t=!1;const e=new n(ut.origin,{body:new zt,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),d=a&&o&&qt(()=>$.isReadableStream(new i("").body)),u={stream:d&&(t=>t.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!u[t]&&(u[t]=(e,n)=>{let i=e&&e[t];if(i)return i.call(e);throw new W(`Response type '${t}' is not supported`,W.ERR_NOT_SUPPORT,n)})});const h=async(t,e)=>{const i=$.toFiniteNumber(t.getContentLength());return null==i?(async t=>{if(null==t)return 0;if($.isBlob(t))return t.size;if($.isSpecCompliantForm(t)){const e=new n(ut.origin,{method:"POST",body:t});return(await e.arrayBuffer()).byteLength}return $.isArrayBufferView(t)||$.isArrayBuffer(t)?t.byteLength:($.isURLSearchParams(t)&&(t+=""),$.isString(t)?(await l(t)).byteLength:void 0)})(e):i};return async t=>{let{url:r,method:a,data:o,signal:l,cancelToken:p,timeout:m,onDownloadProgress:g,onUploadProgress:f,responseType:b,headers:y,withCredentials:x="same-origin",fetchOptions:w}=Lt(t),v=e||fetch;b=b?(b+"").toLowerCase():"text";let E=Ut([l,p&&p.toAbortSignal()],m),C=null;const A=E&&E.unsubscribe&&(()=>{E.unsubscribe()});let S;try{if(f&&c&&"get"!==a&&"head"!==a&&0!==(S=await h(y,o))){let t,e=new n(r,{method:"POST",body:o,duplex:"half"});if($.isFormData(o)&&(t=e.headers.get("content-type"))&&y.setContentType(t),e.body){const[t,n]=St(S,At(kt(f)));o=Bt(e.body,65536,t,n)}}$.isString(x)||(x=x?"include":"omit");const e=s&&"credentials"in n.prototype,l={...w,signal:E,method:a.toUpperCase(),headers:y.normalize().toJSON(),body:o,duplex:"half",credentials:e?x:void 0};C=s&&new n(r,l);let p=await(s?v(C,w):v(r,l));const m=d&&("stream"===b||"response"===b);if(d&&(g||m&&A)){const t={};["status","statusText","headers"].forEach(e=>{t[e]=p[e]});const e=$.toFiniteNumber(p.headers.get("content-length")),[n,r]=g&&St(e,At(kt(g),!0))||[];p=new i(Bt(p.body,65536,n,()=>{r&&r(),A&&A()}),t)}b=b||"text";let k=await u[$.findKey(u,b)||"text"](p,t);return!m&&A&&A(),await new Promise((e,n)=>{Ct(e,n,{data:k,headers:xt.from(p.headers),status:p.status,statusText:p.statusText,config:t,request:C})})}catch(k){if(A&&A(),k&&"TypeError"===k.name&&/Load failed|fetch/i.test(k.message))throw Object.assign(new W("Network Error",W.ERR_NETWORK,t,C),{cause:k.cause||k});throw W.from(k,k&&k.code,t,C)}}},Wt=new Map,Ht=t=>{let e=t&&t.env||{};const{fetch:n,Request:i,Response:r}=e,s=[i,r,n];let a,o,l=s.length,c=Wt;for(;l--;)a=s[l],o=c.get(a),void 0===o&&c.set(a,o=l?new Map:$t(e)),c=o;return o};Ht();const Kt={http:null,xhr:Dt,fetch:{get:Ht}};$.forEach(Kt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(n){}Object.defineProperty(t,"adapterName",{value:e})}});const Vt=t=>`- ${t}`,Jt=t=>$.isFunction(t)||null===t||!1===t;const Gt={getAdapter:function(t,e){t=$.isArray(t)?t:[t];const{length:n}=t;let i,r;const s={};for(let a=0;a<n;a++){let n;if(i=t[a],r=i,!Jt(i)&&(r=Kt[(n=String(i)).toLowerCase()],void 0===r))throw new W(`Unknown adapter '${n}'`);if(r&&($.isFunction(r)||(r=r.get(e))))break;s[n||"#"+a]=r}if(!r){const t=Object.entries(s).map(([t,e])=>`adapter ${t} `+(!1===e?"is not supported by the environment":"is not available in the build"));throw new W("There is no suitable adapter to dispatch the request "+(n?t.length>1?"since :\n"+t.map(Vt).join("\n"):" "+Vt(t[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r},adapters:Kt};function Xt(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Et(null,t)}function Yt(t){Xt(t),t.headers=xt.from(t.headers),t.data=wt.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1);return Gt.getAdapter(t.adapter||pt.adapter,t)(t).then(function(e){return Xt(t),e.data=wt.call(t,t.transformResponse,e),e.headers=xt.from(e.headers),e},function(e){return vt(e)||(Xt(t),e&&e.response&&(e.response.data=wt.call(t,t.transformResponse,e.response),e.response.headers=xt.from(e.response.headers))),Promise.reject(e)})}const Zt="1.13.2",Qt={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Qt[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const te={};Qt.transitional=function(t,e,n){function i(t,e){return"[Axios v"+Zt+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return(n,r,s)=>{if(!1===t)throw new W(i(r," has been removed"+(e?" in "+e:"")),W.ERR_DEPRECATED);return e&&!te[r]&&(te[r]=!0,console.warn(i(r," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,r,s)}},Qt.spelling=function(t){return(e,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};const ee={assertOptions:function(t,e,n){if("object"!=typeof t)throw new W("options must be an object",W.ERR_BAD_OPTION_VALUE);const i=Object.keys(t);let r=i.length;for(;r-- >0;){const s=i[r],a=e[s];if(a){const e=t[s],n=void 0===e||a(e,s,t);if(!0!==n)throw new W("option "+s+" must be "+n,W.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new W("Unknown option "+s,W.ERR_BAD_OPTION)}},validators:Qt},ne=ee.validators;let ie=class{constructor(t){this.defaults=t||{},this.interceptors={request:new it,response:new it}}async request(t,e){try{return await this._request(t,e)}catch(n){if(n instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const e=t.stack?t.stack.replace(/^.+\n/,""):"";try{n.stack?e&&!String(n.stack).endsWith(e.replace(/^.+\n.+\n/,""))&&(n.stack+="\n"+e):n.stack=e}catch(i){}}throw n}}_request(t,e){"string"==typeof t?(e=e||{}).url=t:e=t||{},e=It(this.defaults,e);const{transitional:n,paramsSerializer:i,headers:r}=e;void 0!==n&&ee.assertOptions(n,{silentJSONParsing:ne.transitional(ne.boolean),forcedJSONParsing:ne.transitional(ne.boolean),clarifyTimeoutError:ne.transitional(ne.boolean)},!1),null!=i&&($.isFunction(i)?e.paramsSerializer={serialize:i}:ee.assertOptions(i,{encode:ne.function,serialize:ne.function},!0)),void 0!==e.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),ee.assertOptions(e,{baseUrl:ne.spelling("baseURL"),withXsrfToken:ne.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let s=r&&$.merge(r.common,r[e.method]);r&&$.forEach(["delete","get","head","post","put","patch","common"],t=>{delete r[t]}),e.headers=xt.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(o=o&&t.synchronous,a.unshift(t.fulfilled,t.rejected))});const l=[];let c;this.interceptors.response.forEach(function(t){l.push(t.fulfilled,t.rejected)});let d,u=0;if(!o){const t=[Yt.bind(this),void 0];for(t.unshift(...a),t.push(...l),d=t.length,c=Promise.resolve(e);u<d;)c=c.then(t[u++],t[u++]);return c}d=a.length;let h=e;for(;u<d;){const t=a[u++],e=a[u++];try{h=t(h)}catch(p){e.call(this,p);break}}try{c=Yt.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,d=l.length;u<d;)c=c.then(l[u++],l[u++]);return c}getUri(t){return nt(Tt((t=It(this.defaults,t)).baseURL,t.url,t.allowAbsoluteUrls),t.params,t.paramsSerializer)}};$.forEach(["delete","get","head","options"],function(t){ie.prototype[t]=function(e,n){return this.request(It(n||{},{method:t,url:e,data:(n||{}).data}))}}),$.forEach(["post","put","patch"],function(t){function e(e){return function(n,i,r){return this.request(It(r||{},{method:t,headers:e?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}ie.prototype[t]=e(),ie.prototype[t+"Form"]=e(!0)});const re={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(re).forEach(([t,e])=>{re[e]=t});const se=function t(n){const i=new ie(n),r=e(ie.prototype.request,i);return $.extend(r,ie.prototype,i,{allOwnKeys:!0}),$.extend(r,i,null,{allOwnKeys:!0}),r.create=function(e){return t(It(n,e))},r}(pt);se.Axios=ie,se.CanceledError=Et,se.CancelToken=class t{constructor(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");let e;this.promise=new Promise(function(t){e=t});const n=this;this.promise.then(t=>{if(!n._listeners)return;let e=n._listeners.length;for(;e-- >0;)n._listeners[e](t);n._listeners=null}),this.promise.then=t=>{let e;const i=new Promise(t=>{n.subscribe(t),e=t}).then(t);return i.cancel=function(){n.unsubscribe(e)},i},t(function(t,i,r){n.reason||(n.reason=new Et(t,i,r),e(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){this.reason?t(this.reason):this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1)}toAbortSignal(){const t=new AbortController,e=e=>{t.abort(e)};return this.subscribe(e),t.signal.unsubscribe=()=>this.unsubscribe(e),t.signal}static source(){let e;return{token:new t(function(t){e=t}),cancel:e}}},se.isCancel=vt,se.VERSION=Zt,se.toFormData=Y,se.AxiosError=W,se.Cancel=se.CanceledError,se.all=function(t){return Promise.all(t)},se.spread=function(t){return function(e){return t.apply(null,e)}},se.isAxiosError=function(t){return $.isObject(t)&&!0===t.isAxiosError},se.mergeConfig=It,se.AxiosHeaders=xt,se.formToJSON=t=>ht($.isHTMLForm(t)?new FormData(t):t),se.getAdapter=Gt.getAdapter,se.HttpStatusCode=re,se.default=se;const{Axios:ae,AxiosError:oe,CanceledError:le,isCancel:ce,CancelToken:de,VERSION:ue,all:he,Cancel:pe,isAxiosError:me,spread:ge,toFormData:fe,AxiosHeaders:be,HttpStatusCode:ye,formToJSON:xe,getAdapter:we,mergeConfig:ve}=se;var Ee=class t extends Error{constructor(e,n){super(n),this.name="UtiliaSDKError",this.code=e,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,t)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString()}}isRateLimited(){return"RATE_LIMITED"===this.code}isUnauthorized(){return"UNAUTHORIZED"===this.code}isRetryable(){return"RATE_LIMITED"===this.code||"NETWORK_ERROR"===this.code}},Ce=class{constructor(t){this.config={timeout:3e4,retryAttempts:3,debug:!1,...t},this.axios=se.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json","X-Api-Key":this.config.apiKey}}),this.setupInterceptors()}setupInterceptors(){this.config.debug&&this.axios.interceptors.request.use(t=>{var e;return console.log("[UtiliaSDK] Request:",null==(e=t.method)?void 0:e.toUpperCase(),t.url),t}),this.config.debug&&this.axios.interceptors.response.use(t=>(console.log("[UtiliaSDK] Response:",t.status,t.config.url),t))}toSDKError(t){if(!t.response)return"ECONNABORTED"===t.code?new Ee("NETWORK_ERROR","Timeout: la solicitud excedio el tiempo limite"):new Ee("NETWORK_ERROR","Error de conexion: no se pudo conectar con el servidor");const e=t.response.status,n=t.response.data,i=(null==n?void 0:n.message)||(null==n?void 0:n.error)||t.message;switch(e){case 401:return new Ee("UNAUTHORIZED",i||"API Key invalida o faltante");case 403:return(null==i?void 0:i.toLowerCase().includes("rate limit"))?new Ee("RATE_LIMITED","Rate limit excedido. Intenta de nuevo mas tarde."):(null==i?void 0:i.toLowerCase().includes("origen"))?new Ee("FORBIDDEN","Origen no permitido por CORS"):new Ee("FORBIDDEN",i||"Acceso denegado");case 404:return new Ee("NOT_FOUND",i||"Recurso no encontrado");case 400:case 422:return new Ee("VALIDATION_ERROR",i||"Error de validacion en los datos enviados");case 429:return new Ee("RATE_LIMITED",i||"Rate limit excedido. Intenta de nuevo mas tarde.");case 500:case 502:case 503:case 504:return new Ee("UNKNOWN",i||"Error interno del servidor");default:return new Ee("UNKNOWN",i||`Error desconocido (HTTP ${e})`)}}isRetryableError(t){if(t instanceof oe){if(!t.response){return["ECONNABORTED","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETUNREACH","ERR_NETWORK"].includes(t.code||"")}const e=t.response.status;return 429===e||e>=500}return!1}async executeWithRetry(t){let e;for(let i=0;i<this.config.retryAttempts;i++)try{return await t()}catch(n){if(e=n,!this.isRetryableError(n)){if(n instanceof oe)throw this.toSDKError(n);throw n}if(i<this.config.retryAttempts-1){const t=500*Math.pow(2,i);this.config.debug&&console.log(`[UtiliaSDK] Retry attempt ${i+1}/${this.config.retryAttempts-1}, waiting ${t}ms`),await this.sleep(t)}}if(e instanceof oe)throw this.toSDKError(e);throw e}sleep(t){return new Promise(e=>setTimeout(e,t))}async get(t,e){return this.executeWithRetry(async()=>(await this.axios.get(t,e)).data)}async post(t,e,n){return this.executeWithRetry(async()=>(await this.axios.post(t,e,n)).data)}async patch(t,e,n){return this.executeWithRetry(async()=>(await this.axios.patch(t,e,n)).data)}async put(t,e,n){return this.executeWithRetry(async()=>(await this.axios.put(t,e,n)).data)}async delete(t,e){return this.executeWithRetry(async()=>(await this.axios.delete(t,e)).data)}async postForm(t,e,n){return this.executeWithRetry(async()=>(await this.axios.post(t,e,{headers:{"Content-Type":"multipart/form-data"},onUploadProgress:n?t=>{const e=Math.round(100*t.loaded/(t.total||1));n(e)}:void 0})).data)}},Ae=5,Se=500,ke=10,Re=1,Ne=5e3,Te=255,Oe=255,Ie=2048;function Le(t,e,n,i){if(void 0!==n&&t.length<n)throw new Ee("VALIDATION_ERROR",`${e} must be at least ${n} characters long (got ${t.length})`);if(void 0!==i&&t.length>i)throw new Ee("VALIDATION_ERROR",`${e} must be at most ${i} characters long (got ${t.length})`)}function De(t,e){if(null==t)throw new Ee("VALIDATION_ERROR",`${e} is required`);if("string"==typeof t&&0===t.trim().length)throw new Ee("VALIDATION_ERROR",`${e} must not be empty`)}var Ue=class{constructor(t){this.basePath="/external/v1/files",this.client=t}async upload(t,e){(null==e?void 0:e.name)&&Le(e.name,"file name",void 0,Te);const n=new FormData;return t instanceof Blob&&!(t instanceof File)?n.append("file",t,(null==e?void 0:e.name)||"file"):n.append("file",t),(null==e?void 0:e.name)&&n.append("name",e.name),(null==e?void 0:e.metadata)&&n.append("metadata",JSON.stringify(e.metadata)),this.client.postForm(`${this.basePath}/upload`,n,null==e?void 0:e.onProgress)}async getUrl(t){return(await this.client.get(`${this.basePath}/${t}/url`)).url}async getQuota(){return this.client.get(`${this.basePath}/quota`)}},Pe=class{constructor(t){this.basePath="/external/v1/tickets",this.client=t}async create(t){return De(t.title,"title"),Le(t.title,"title",Ae,Se),De(t.description,"description"),Le(t.description,"description",ke),this.client.post(this.basePath,t)}async list(t,e){const n=await this.client.get(this.basePath,{params:{userId:t,...e}});return{data:n.tickets,pagination:n.pagination}}async get(t,e){return this.client.get(`${this.basePath}/${t}`,{params:{userId:e}})}async getUnreadCount(t){return this.client.get(`${this.basePath}/unread-count`,{params:{userId:t}})}async addMessage(t,e,n){return De(n.content,"content"),Le(n.content,"content",Re,Ne),this.client.post(`${this.basePath}/${t}/messages`,n,{params:{userId:e}})}async close(t,e){await this.client.patch(`${this.basePath}/${t}/close`,null,{params:{userId:e}})}async reopen(t,e){await this.client.patch(`${this.basePath}/${t}/reopen`,null,{params:{userId:e}})}},Fe=class{constructor(t){this.basePath="/external/v1/users",this.client=t}async identify(t){if(De(t.externalId,"externalId"),Le(t.externalId,"externalId",void 0,Oe),void 0!==t.email&&null!==t.email&&(e=t.email,!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)))throw new Ee("VALIDATION_ERROR",`Invalid email format: "${t.email}"`);var e;if(void 0!==t.avatarUrl&&null!==t.avatarUrl){if(!function(t){try{return new URL(t),!0}catch{return!1}}(t.avatarUrl))throw new Ee("VALIDATION_ERROR",`Invalid avatar URL: "${t.avatarUrl}"`);Le(t.avatarUrl,"avatarUrl",void 0,Ie)}return this.client.post(`${this.basePath}/identify`,t)}async list(t=1,e=20){const n=await this.client.get(this.basePath,{params:{page:t,limit:e}});return{data:n.users,pagination:n.pagination}}},Be=class{constructor(t){this.basePath="/external/v1/tickets",this.client=t}async requestSuggestions(t){return this.client.post(`${this.basePath}/ai-suggest`,t)}async getSuggestionsStatus(t){return this.client.get(`${this.basePath}/ai-suggest/${t}`)}async transcribe(t,e){return this.client.post(`${this.basePath}/ai-transcribe`,{audioBase64:t,audioFilename:e})}async getSuggestions(t,e={}){const{pollInterval:n=1e3,maxWait:i=6e4,onProgress:r}=e,{jobId:s}=await this.requestSuggestions(t),a=Date.now();for(;Date.now()-a<i;){const t=await this.getSuggestionsStatus(s);if(r&&void 0!==t.progress&&r(t.progress),"completed"===t.status)return t.result;if("failed"===t.status)throw new Error(t.error||"Error al generar sugerencias");if("not_found"===t.status)throw new Error("Job no encontrado");await this.sleep(n)}throw new Error("Timeout: el job excedio el tiempo maximo de espera")}async trackAiAction(t){return this.client.post(`${this.basePath}/ai-track-action`,t)}sleep(t){return new Promise(e=>setTimeout(e,t))}},je=class{constructor(t){const e=new Ce(t);this.files=new Ue(e),this.tickets=new Pe(e),this.users=new Fe(e),this.ai=new Be(e)}};function _e(t){return{OPEN:"Abierto",IN_REVIEW:"En revision",RESOLVED:"Resuelto",CLOSED:"Cerrado"}[t]||t}function ze(t){return t.toLowerCase().replace("_","-")}class Me{constructor(t,e,n,i){this.tickets=[],this.isLoading=!0,this.error=null,this.container=t,this.sdk=e,this.userId=n,this.onSelect=i,this.loadTickets()}async loadTickets(){try{const t=await this.sdk.tickets.list(this.userId,{limit:20});this.tickets=t.data,this.error=null}catch(t){console.error("[UtiliaWidget] Error loading tickets:",t),this.error="Error al cargar los tickets"}finally{this.isLoading=!1,this.render()}}render(){this.container.replaceChildren(),this.isLoading?this.renderLoading():this.error?this.renderError():0!==this.tickets.length?this.renderTicketList():this.renderEmpty()}renderLoading(){const t=document.createElement("div");t.className="utilia-loading";const e=document.createElement("span");e.className="utilia-spinner",t.appendChild(e),this.container.appendChild(t)}renderError(){const t=document.createElement("div");t.className="utilia-error",t.textContent=this.error||"Error desconocido",this.container.appendChild(t)}renderEmpty(){const t=document.createElement("div");t.className="utilia-empty";const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("class","utilia-empty-icon"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"),e.appendChild(n),t.appendChild(e);const i=document.createElement("p");i.textContent="No tienes tickets aun",t.appendChild(i);const r=document.createElement("p");r.className="utilia-empty-text",r.textContent="Crea uno nuevo usando el boton +",t.appendChild(r),this.container.appendChild(t)}renderTicketList(){for(const t of this.tickets){const e=this.createTicketItem(t);this.container.appendChild(e)}}createTicketItem(t){const e=document.createElement("div");e.className="utilia-ticket-item",e.dataset.ticketId=t.id;const n=document.createElement("div");n.className="utilia-ticket-title",n.textContent=t.title,e.appendChild(n);const i=document.createElement("div");i.className="utilia-ticket-meta";const r=document.createElement("span");r.className=`utilia-ticket-badge ${ze(t.status)}`,r.textContent=_e(t.status),i.appendChild(r);const s=document.createElement("span");if(s.textContent=t.ticketKey,i.appendChild(s),t.unreadByExternal>0){const e=document.createElement("span");e.className="utilia-unread",e.textContent=`${t.unreadByExternal} nuevo${t.unreadByExternal>1?"s":""}`,i.appendChild(e)}return e.appendChild(i),e.addEventListener("click",()=>{this.onSelect(t.id)}),e}}class qe{constructor(t={}){this.mediaRecorder=null,this.audioChunks=[],this.stream=null,this.state="idle",this.callbacks=t}static isSupported(){return"undefined"!=typeof navigator&&void 0!==navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.getUserMedia&&void 0!==window.MediaRecorder}getState(){return this.state}async start(){if("idle"!==this.state)throw new Error("Ya hay una grabacion en curso");if(!qe.isSupported())throw new Error("Tu navegador no soporta grabacion de audio");try{this.setState("recording"),this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}});const t=this.getSupportedMimeType();this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:t}),this.audioChunks=[],this.mediaRecorder.ondataavailable=t=>{t.data.size>0&&this.audioChunks.push(t.data)},this.mediaRecorder.onerror=t=>{this.handleError(new Error("Error durante la grabacion"))},this.mediaRecorder.start(100)}catch(t){if(this.cleanup(),this.setState("idle"),t instanceof DOMException&&"NotAllowedError"===t.name)throw new Error("Permiso de microfono denegado");throw new Error("No se pudo acceder al microfono")}}async stop(){if("recording"!==this.state||!this.mediaRecorder)throw new Error("No hay grabacion activa");return this.setState("processing"),new Promise((t,e)=>{this.mediaRecorder?(this.mediaRecorder.onstop=async()=>{var n;try{const e=(null==(n=this.mediaRecorder)?void 0:n.mimeType)||"audio/webm",i=new Blob(this.audioChunks,{type:e}),r=await this.blobToBase64(i),s=this.getExtensionFromMimeType(e),a=`recording-${Date.now()}.${s}`;this.cleanup(),this.setState("idle"),t({base64:r,filename:a,mimeType:e})}catch(i){this.cleanup(),this.setState("idle"),e(i)}},this.mediaRecorder.stop()):e(new Error("MediaRecorder no disponible"))})}cancel(){this.mediaRecorder&&"recording"===this.state&&this.mediaRecorder.stop(),this.cleanup(),this.setState("idle")}blobToBase64(t){return new Promise((e,n)=>{const i=new FileReader;i.onloadend=()=>{const t=i.result.split(",")[1];e(t)},i.onerror=()=>n(new Error("Error al leer el audio")),i.readAsDataURL(t)})}getSupportedMimeType(){const t=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus"];for(const e of t)if(MediaRecorder.isTypeSupported(e))return e;return"audio/webm"}getExtensionFromMimeType(t){return t.includes("webm")?"webm":t.includes("mp4")?"mp4":t.includes("ogg")?"ogg":"webm"}setState(t){var e,n;this.state=t,null==(n=(e=this.callbacks).onStateChange)||n.call(e,t)}handleError(t){var e,n;this.cleanup(),this.setState("idle"),null==(n=(e=this.callbacks).onError)||n.call(e,t)}cleanup(){this.stream&&(this.stream.getTracks().forEach(t=>t.stop()),this.stream=null),this.mediaRecorder=null,this.audioChunks=[]}}class $e{constructor(t,e,n,i){this.ALLOWED_TYPES=["image/jpeg","image/png","image/gif","image/webp","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/csv"],this.container=t,this.sdk=e,this.onChange=n,this.maxFiles=(null==i?void 0:i.maxFiles)||5,this.maxSizeBytes=(null==i?void 0:i.maxSizeBytes)||10485760,this.state={files:[],pendingFiles:[],error:null},this.render()}getFileIds(){return this.state.files.map(t=>t.id)}reset(){this.state={files:[],pendingFiles:[],error:null},this.render()}render(){this.container.replaceChildren();const t=document.createElement("div");t.className="utilia-drop-zone",t.addEventListener("dragover",t=>this.handleDragOver(t)),t.addEventListener("dragleave",()=>this.handleDragLeave(t)),t.addEventListener("drop",e=>this.handleDrop(e,t)),t.addEventListener("click",()=>this.triggerFileSelect());const e=this.createUploadIcon();t.appendChild(e);const n=document.createElement("span");n.className="utilia-drop-text",n.textContent="Arrastra archivos aqui o haz clic para seleccionar",t.appendChild(n);const i=document.createElement("span");i.className="utilia-drop-hint",i.textContent=`Max ${this.maxFiles} archivos, ${this.formatBytes(this.maxSizeBytes)} cada uno`,t.appendChild(i),this.container.appendChild(t);const r=document.createElement("input");if(r.type="file",r.multiple=!0,r.accept=this.ALLOWED_TYPES.join(","),r.style.display="none",r.id="utilia-file-input",r.addEventListener("change",t=>this.handleFileSelect(t)),this.container.appendChild(r),this.state.files.length>0||this.state.pendingFiles.length>0){const t=document.createElement("div");t.className="utilia-file-list";for(const e of this.state.files)t.appendChild(this.createFileItem(e));for(const e of this.state.pendingFiles)t.appendChild(this.createPendingItem(e));this.container.appendChild(t)}if(this.state.error){const t=document.createElement("div");t.className="utilia-file-error",t.textContent=this.state.error,this.container.appendChild(t)}}createFileItem(t){const e=document.createElement("div");e.className="utilia-file-item";const n=document.createElement("div");n.className="utilia-file-info";const i=document.createElement("span");i.className="utilia-file-name",i.textContent=t.originalName,n.appendChild(i);const r=document.createElement("span");r.className="utilia-file-size",r.textContent=this.formatBytes(t.size),n.appendChild(r),e.appendChild(n);const s=document.createElement("button");return s.type="button",s.className="utilia-file-remove",s.textContent="×",s.addEventListener("click",()=>this.removeFile(t.id)),e.appendChild(s),e}createPendingItem(t){const e=document.createElement("div");e.className="utilia-file-item pending";const n=document.createElement("div");n.className="utilia-file-info";const i=document.createElement("span");if(i.className="utilia-file-name",i.textContent=t.file.name,n.appendChild(i),t.error){const e=document.createElement("span");e.className="utilia-file-error-inline",e.textContent=t.error,n.appendChild(e)}else{const e=document.createElement("div");e.className="utilia-file-progress";const i=document.createElement("div");i.className="utilia-file-progress-bar",i.style.width=`${t.progress}%`,e.appendChild(i),n.appendChild(e)}return e.appendChild(n),e}createUploadIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("class","utilia-upload-icon");const e=document.createElementNS("http://www.w3.org/2000/svg","path");e.setAttribute("d","M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"),t.appendChild(e);const n=document.createElementNS("http://www.w3.org/2000/svg","polyline");n.setAttribute("points","17 8 12 3 7 8"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","line");return i.setAttribute("x1","12"),i.setAttribute("y1","3"),i.setAttribute("x2","12"),i.setAttribute("y2","15"),t.appendChild(i),t}handleDragOver(t){t.preventDefault(),t.stopPropagation();t.currentTarget.classList.add("drag-over")}handleDragLeave(t){t.classList.remove("drag-over")}handleDrop(t,e){var n;t.preventDefault(),t.stopPropagation(),e.classList.remove("drag-over");const i=null==(n=t.dataTransfer)?void 0:n.files;i&&this.processFiles(Array.from(i))}triggerFileSelect(){const t=this.container.querySelector("#utilia-file-input");null==t||t.click()}handleFileSelect(t){const e=t.target;e.files&&(this.processFiles(Array.from(e.files)),e.value="")}async processFiles(t){this.state.error=null;if(this.state.files.length+t.length>this.maxFiles)return this.state.error=`Maximo ${this.maxFiles} archivos permitidos`,void this.render();const e=[];for(const i of t){if(!this.ALLOWED_TYPES.includes(i.type))return this.state.error=`Tipo de archivo no permitido: ${i.name}`,void this.render();if(i.size>this.maxSizeBytes)return this.state.error=`Archivo muy grande: ${i.name} (max ${this.formatBytes(this.maxSizeBytes)})`,void this.render();e.push(i)}for(const i of e){const t=Math.random().toString(36).substring(7);this.state.pendingFiles.push({id:t,file:i,progress:0})}this.render();for(const i of[...this.state.pendingFiles])try{const t=await this.sdk.files.upload(i.file,{onProgress:t=>{const e=this.state.pendingFiles.findIndex(t=>t.id===i.id);e>=0&&(this.state.pendingFiles[e].progress=t,this.render())}});this.state.files.push(t),this.state.pendingFiles=this.state.pendingFiles.filter(t=>t.id!==i.id),this.render(),this.notifyChange()}catch(n){const t=this.state.pendingFiles.findIndex(t=>t.id===i.id);t>=0&&(this.state.pendingFiles[t].error=n instanceof Error?n.message:"Error al subir",this.render())}}removeFile(t){this.state.files=this.state.files.filter(e=>e.id!==t),this.render(),this.notifyChange()}notifyChange(){this.onChange(this.getFileIds())}formatBytes(t){if(0===t)return"0 B";const e=Math.floor(Math.log(t)/Math.log(1024));return parseFloat((t/Math.pow(1024,e)).toFixed(1))+" "+["B","KB","MB","GB"][e]}}class We{constructor(t,e,n,i){this.isSubmitting=!1,this.error=null,this.audioRecorder=null,this.recorderState="idle",this.isLoadingAi=!1,this.aiProgress=0,this.aiError=null,this.pendingSuggestions=null,this.analyticsEventId=null,this.suggestionDecisions={},this.suggestionsReceivedAt=0,this.aiTextInput="",this.fileUpload=null,this.attachmentIds=[],this.titleInput=null,this.descriptionTextarea=null,this.categorySelect=null,this.prioritySelect=null,this.container=t,this.sdk=e,this.config=n,this.onSuccess=i,qe.isSupported()&&(this.audioRecorder=new qe({onStateChange:t=>{this.recorderState=t,this.updateRecordButton()},onError:t=>{this.aiError=t.message,this.render()}})),this.render()}render(){this.container.replaceChildren();const t=document.createElement("form");t.className="utilia-form",t.id="utilia-ticket-form",t.appendChild(this.createAiSection());const e=this.createFormGroup("Titulo *",this.createInput("text","title","Describe brevemente tu problema",!0,5,500));this.titleInput=e.querySelector("input"),t.appendChild(e);const n=this.createFormGroup("Descripcion *",this.createTextarea("description","Proporciona mas detalles sobre tu problema...",!0,10));this.descriptionTextarea=n.querySelector("textarea"),t.appendChild(n);const i=this.createFormGroup("Categoria",this.createSelect("category",[{value:"CONSULTA",label:"Consulta"},{value:"BUG",label:"Bug / Problema"},{value:"SUGERENCIA",label:"Sugerencia"}],this.config.defaultCategory||"CONSULTA"));this.categorySelect=i.querySelector("select"),t.appendChild(i);const r=this.createFormGroup("Prioridad",this.createSelect("priority",[{value:"BAJA",label:"Baja"},{value:"MEDIA",label:"Media"},{value:"ALTA",label:"Alta"},{value:"CRITICA",label:"Critica"}],this.config.defaultPriority||"MEDIA"));this.prioritySelect=r.querySelector("select"),t.appendChild(r);const s=document.createElement("div");s.className="utilia-form-group";const a=document.createElement("label");a.className="utilia-label",a.textContent="Archivos adjuntos (opcional)",s.appendChild(a);const o=document.createElement("div");if(o.id="utilia-file-upload",s.appendChild(o),t.appendChild(s),setTimeout(()=>{const e=t.querySelector("#utilia-file-upload");e&&!this.fileUpload&&(this.fileUpload=new $e(e,this.sdk,t=>{this.attachmentIds=t}))},0),this.error){const e=document.createElement("div");e.className="utilia-error",e.textContent=this.error,t.appendChild(e)}const l=document.createElement("button");l.type="submit",l.className="utilia-btn utilia-btn-primary",l.style.width="100%",l.disabled=this.isSubmitting||this.isLoadingAi,l.textContent=this.isSubmitting?"Enviando...":"Enviar ticket",t.appendChild(l),t.addEventListener("submit",t=>this.handleSubmit(t)),this.container.appendChild(t)}createAiSection(){const t=document.createElement("div");t.className="utilia-ai-section";const e=document.createElement("div");e.className="utilia-ai-header";const n=document.createElement("span");n.className="utilia-ai-label",n.textContent="Asistente IA",e.appendChild(n),t.appendChild(e);const i=document.createElement("p");i.className="utilia-ai-desc",i.textContent=qe.isSupported()?"Describe tu problema con texto o graba un audio y la IA completara el formulario.":"Describe tu problema y la IA completara el formulario por ti.",t.appendChild(i);const r=document.createElement("div");r.className="utilia-ai-input-group";const s=document.createElement("textarea");s.className="utilia-ai-textarea",s.placeholder="Describe tu problema aqui...",s.disabled=this.isLoadingAi||"recording"===this.recorderState,s.value=this.aiTextInput,s.addEventListener("input",()=>{this.aiTextInput=s.value}),r.appendChild(s);const a=document.createElement("button");if(a.type="button",a.className="utilia-btn utilia-btn-primary utilia-ai-generate-btn",a.textContent="Generar",a.disabled=this.isLoadingAi||"recording"===this.recorderState,a.addEventListener("click",()=>this.processTextWithAi()),r.appendChild(a),t.appendChild(r),qe.isSupported()){const e=document.createElement("div");e.className="utilia-ai-controls",e.style.marginTop="8px";const n=document.createElement("button");n.type="button",n.className="utilia-record-btn",n.id="utilia-record-btn",n.disabled=this.isLoadingAi,this.updateRecordButtonContent(n),n.addEventListener("click",()=>this.handleRecordClick()),e.appendChild(n),t.appendChild(e)}if(this.isLoadingAi){const e=document.createElement("div");e.className="utilia-ai-loading";const n=document.createElement("span");n.className="utilia-spinner utilia-spinner-small",e.appendChild(n);const i=document.createElement("span");i.textContent=this.aiProgress>0?`Procesando... ${this.aiProgress}%`:"Procesando...",e.appendChild(i),t.appendChild(e)}if(this.aiError){const e=document.createElement("div");e.className="utilia-ai-error",e.textContent=this.aiError,t.appendChild(e)}return this.pendingSuggestions&&t.appendChild(this.createSuggestionsReview()),t}updateRecordButtonContent(t){t.replaceChildren();const e=this.createMicrophoneIcon();t.appendChild(e);const n=document.createElement("span");switch(this.recorderState){case"recording":t.classList.add("recording"),n.textContent="Detener grabacion";break;case"processing":t.classList.remove("recording"),n.textContent="Procesando...";break;default:t.classList.remove("recording"),n.textContent="Grabar audio"}t.appendChild(n)}updateRecordButton(){const t=this.container.querySelector("#utilia-record-btn");t&&this.updateRecordButtonContent(t)}createMicrophoneIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("class","utilia-mic-icon");const e=document.createElementNS("http://www.w3.org/2000/svg","path");e.setAttribute("d","M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"),t.appendChild(e);const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M19 10v2a7 7 0 0 1-14 0v-2"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","line");i.setAttribute("x1","12"),i.setAttribute("y1","19"),i.setAttribute("x2","12"),i.setAttribute("y2","23"),t.appendChild(i);const r=document.createElementNS("http://www.w3.org/2000/svg","line");return r.setAttribute("x1","8"),r.setAttribute("y1","23"),r.setAttribute("x2","16"),r.setAttribute("y2","23"),t.appendChild(r),t}async handleRecordClick(){if(this.audioRecorder)if(this.aiError=null,"idle"===this.recorderState)try{await this.audioRecorder.start()}catch(t){this.aiError=t instanceof Error?t.message:"Error al grabar",this.render()}else if("recording"===this.recorderState)try{const t=await this.audioRecorder.stop();await this.processAudioWithAi(t)}catch(t){this.aiError=t instanceof Error?t.message:"Error al procesar audio",this.render()}}async processAudioWithAi(t){var e,n,i,r;this.isLoadingAi=!0,this.aiProgress=0,this.render();try{const s={};(null==(e=this.titleInput)?void 0:e.value)&&(s.title=this.titleInput.value),(null==(n=this.descriptionTextarea)?void 0:n.value)&&(s.description=this.descriptionTextarea.value),(null==(i=this.categorySelect)?void 0:i.value)&&(s.category=this.categorySelect.value),(null==(r=this.prioritySelect)?void 0:r.value)&&(s.priority=this.prioritySelect.value);const a=await this.sdk.ai.getSuggestions({userId:this.config.userId,audioBase64:t.base64,audioFilename:t.filename,existingFields:Object.keys(s).length>0?s:void 0},{pollInterval:800,maxWait:6e4,onProgress:t=>{this.aiProgress=t,this.updateLoadingText()}});if(null==a?void 0:a.suggestions){this.pendingSuggestions=a.suggestions,this.analyticsEventId=a.analyticsEventId||null,this.suggestionsReceivedAt=Date.now(),this.suggestionDecisions={};for(const t of Object.keys(a.suggestions))a.suggestions[t]&&(this.suggestionDecisions[t]="accepted")}this.isLoadingAi=!1,this.render()}catch(s){this.isLoadingAi=!1,this.aiError=s instanceof Error?s.message:"Error al obtener sugerencias",this.render()}}updateLoadingText(){const t=this.container.querySelector(".utilia-ai-loading span:last-child");t&&(t.textContent=`Procesando... ${this.aiProgress}%`)}async processTextWithAi(){var t,e,n,i;if(this.aiTextInput.trim()){this.isLoadingAi=!0,this.aiProgress=0,this.aiError=null,this.render();try{const r={};(null==(t=this.titleInput)?void 0:t.value)&&(r.title=this.titleInput.value),(null==(e=this.descriptionTextarea)?void 0:e.value)&&(r.description=this.descriptionTextarea.value),(null==(n=this.categorySelect)?void 0:n.value)&&(r.category=this.categorySelect.value),(null==(i=this.prioritySelect)?void 0:i.value)&&(r.priority=this.prioritySelect.value);const s=await this.sdk.ai.getSuggestions({userId:this.config.userId,text:this.aiTextInput.trim(),existingFields:Object.keys(r).length>0?r:void 0},{pollInterval:800,maxWait:6e4,onProgress:t=>{this.aiProgress=t,this.updateLoadingText()}});if(null==s?void 0:s.suggestions){this.pendingSuggestions=s.suggestions,this.analyticsEventId=s.analyticsEventId||null,this.suggestionsReceivedAt=Date.now(),this.suggestionDecisions={};for(const t of Object.keys(s.suggestions))s.suggestions[t]&&(this.suggestionDecisions[t]="accepted")}this.isLoadingAi=!1,this.render()}catch(r){this.isLoadingAi=!1,this.aiError=r instanceof Error?r.message:"Error al obtener sugerencias",this.render()}}}createCheckIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2");const e=document.createElementNS("http://www.w3.org/2000/svg","polyline");return e.setAttribute("points","20 6 9 17 4 12"),t.appendChild(e),t}createXIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2");const e=document.createElementNS("http://www.w3.org/2000/svg","line");e.setAttribute("x1","18"),e.setAttribute("y1","6"),e.setAttribute("x2","6"),e.setAttribute("y2","18"),t.appendChild(e);const n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","6"),n.setAttribute("y1","6"),n.setAttribute("x2","18"),n.setAttribute("y2","18"),t.appendChild(n),t}createSuggestionsReview(){const t=document.createElement("div");t.className="utilia-ai-suggestions";const e=document.createElement("div");e.className="utilia-ai-suggestions-header",e.textContent="Sugerencias de IA",t.appendChild(e);const n={title:"Titulo",description:"Descripcion",category:"Categoria",priority:"Prioridad"};if(this.pendingSuggestions)for(const[a,o]of Object.entries(n)){const e=this.pendingSuggestions[a];if(!e)continue;const n=document.createElement("div");n.className="utilia-suggestion-item";const i=document.createElement("div");i.className="utilia-suggestion-field";const r=document.createElement("div");r.className="utilia-suggestion-field-name",r.textContent=o,i.appendChild(r);const s=document.createElement("div");s.className="utilia-suggestion-value",s.textContent="description"===a&&e.length>80?e.substring(0,80)+"...":e,i.appendChild(s),n.appendChild(i);const l=document.createElement("div");l.className="utilia-suggestion-actions";const c=document.createElement("button");c.type="button",c.className="utilia-suggestion-btn accept","accepted"===this.suggestionDecisions[a]&&c.classList.add("active"),c.appendChild(this.createCheckIcon()),c.addEventListener("click",()=>{this.suggestionDecisions[a]="accepted",c.classList.add("active"),d.classList.remove("active")}),l.appendChild(c);const d=document.createElement("button");d.type="button",d.className="utilia-suggestion-btn reject","rejected"===this.suggestionDecisions[a]&&d.classList.add("active"),d.appendChild(this.createXIcon()),d.addEventListener("click",()=>{this.suggestionDecisions[a]="rejected",d.classList.add("active"),c.classList.remove("active")}),l.appendChild(d),n.appendChild(l),t.appendChild(n)}const i=document.createElement("div");i.className="utilia-suggestions-footer";const r=document.createElement("button");r.type="button",r.className="utilia-btn utilia-btn-primary",r.textContent="Aplicar seleccion",r.addEventListener("click",()=>this.handleAcceptSuggestions()),i.appendChild(r);const s=document.createElement("button");return s.type="button",s.className="utilia-btn utilia-btn-secondary",s.textContent="Rechazar todo",s.addEventListener("click",()=>this.handleRejectAllSuggestions()),i.appendChild(s),t.appendChild(i),t}async handleAcceptSuggestions(){if(!this.pendingSuggestions)return;const t=Object.keys(this.pendingSuggestions).filter(t=>this.pendingSuggestions[t]),e=t.filter(t=>"accepted"===this.suggestionDecisions[t]),n=t.filter(t=>"rejected"===this.suggestionDecisions[t]);if(e.length>0){const t={};for(const n of e)t[n]=this.pendingSuggestions[n];this.applySuggestions(t)}let i;i=n.length===t.length?"REJECTED":e.length===t.length?"ACCEPTED_ALL":"ACCEPTED_PARTIAL",this.analyticsEventId&&this.sdk.ai.trackAiAction({eventId:this.analyticsEventId,userAction:i,fieldsAccepted:e,fieldsRejected:n,timeToDecisionMs:Date.now()-this.suggestionsReceivedAt,source:"WIDGET"}).catch(()=>{}),this.pendingSuggestions=null,this.analyticsEventId=null,this.render()}async handleRejectAllSuggestions(){if(this.analyticsEventId){const t=this.pendingSuggestions?Object.keys(this.pendingSuggestions).filter(t=>this.pendingSuggestions[t]):[];this.sdk.ai.trackAiAction({eventId:this.analyticsEventId,userAction:"REJECTED",fieldsAccepted:[],fieldsRejected:t,timeToDecisionMs:Date.now()-this.suggestionsReceivedAt,source:"WIDGET"}).catch(()=>{})}this.pendingSuggestions=null,this.analyticsEventId=null,this.render()}applySuggestions(t){if(t.title&&this.titleInput&&(this.titleInput.value=t.title),t.description&&this.descriptionTextarea&&(this.descriptionTextarea.value=t.description),t.category&&this.categorySelect){const e={BUG:"BUG",CONSULTA:"CONSULTA",SUGERENCIA:"SUGERENCIA"}[t.category];e&&(this.categorySelect.value=e)}if(t.priority&&this.prioritySelect){const e={BAJA:"BAJA",MEDIA:"MEDIA",ALTA:"ALTA",CRITICA:"CRITICA"}[t.priority];e&&(this.prioritySelect.value=e)}}createFormGroup(t,e){const n=document.createElement("div");n.className="utilia-form-group";const i=document.createElement("label");return i.className="utilia-label",i.textContent=t,n.appendChild(i),n.appendChild(e),n}createInput(t,e,n,i,r,s){const a=document.createElement("input");return a.type=t,a.className="utilia-input",a.name=e,a.placeholder=n,a.required=i,r&&(a.minLength=r),s&&(a.maxLength=s),a}createTextarea(t,e,n,i){const r=document.createElement("textarea");return r.className="utilia-textarea",r.name=t,r.placeholder=e,r.required=n,i&&(r.minLength=i),r}createSelect(t,e,n){const i=document.createElement("select");i.className="utilia-select",i.name=t;for(const r of e){const t=document.createElement("option");t.value=r.value,t.textContent=r.label,t.selected=r.value===n,i.appendChild(t)}return i}async handleSubmit(t){var e,n,i;if(t.preventDefault(),this.isSubmitting)return;const r=t.target,s=new FormData(r),a=s.get("title").trim(),o=s.get("description").trim(),l=s.get("category"),c=s.get("priority");if(a.length<5)return this.error="El titulo debe tener al menos 5 caracteres",void this.render();if(o.length<10)return this.error="La descripcion debe tener al menos 10 caracteres",void this.render();this.isSubmitting=!0,this.error=null,this.render();try{const t=await this.sdk.tickets.create({user:{externalId:this.config.userId,email:this.config.userEmail,name:this.config.userName,metadata:this.config.userMetadata},title:a,description:o,category:l,priority:c,context:this.config.autoContext?{url:window.location.href,browserInfo:navigator.userAgent}:void 0,attachmentIds:this.attachmentIds.length>0?this.attachmentIds:void 0});null==(e=this.fileUpload)||e.reset(),this.attachmentIds=[],this.onSuccess({id:t.id,ticketKey:t.ticketKey})}catch(d){const t=d instanceof Error?d.message:"Error al crear el ticket";this.error=t,this.isSubmitting=!1,this.render(),null==(i=(n=this.config).onError)||i.call(n,d instanceof Error?d:new Error(t))}}}class He{constructor(t,e,n,i){this.ticket=null,this.isLoading=!0,this.isSending=!1,this.error=null,this.fileUpload=null,this.attachmentIds=[],this.container=t,this.sdk=e,this.userId=n,this.ticketId=i,this.loadTicket()}async loadTicket(){try{this.ticket=await this.sdk.tickets.get(this.ticketId,this.userId),this.error=null}catch(t){console.error("[UtiliaWidget] Error loading ticket:",t),this.error="Error al cargar el ticket"}finally{this.isLoading=!1,this.render()}}render(){this.container.replaceChildren(),this.isLoading?this.renderLoading():!this.error&&this.ticket?this.renderTicketDetail():this.renderError()}renderLoading(){const t=document.createElement("div");t.className="utilia-loading";const e=document.createElement("span");e.className="utilia-spinner",t.appendChild(e),this.container.appendChild(t)}renderError(){const t=document.createElement("div");t.className="utilia-error",t.textContent=this.error||"No se pudo cargar el ticket",this.container.appendChild(t)}renderTicketDetail(){if(this.ticket){if(this.container.appendChild(this.createHeader()),this.container.appendChild(this.createMessages()),"CLOSED"!==this.ticket.status)this.container.appendChild(this.createReplyForm());else{const t=document.createElement("div");t.className="utilia-closed-notice",t.textContent="Este ticket esta cerrado",this.container.appendChild(t)}this.scrollToBottom()}}createHeader(){const t=document.createElement("div");t.className="utilia-ticket-header";const e=document.createElement("div");e.className="utilia-ticket-title",e.textContent=this.ticket.title,t.appendChild(e);const n=document.createElement("div");n.className="utilia-ticket-meta",n.style.marginTop="8px";const i=document.createElement("span");i.className=`utilia-ticket-badge ${ze(this.ticket.status)}`,i.textContent=_e(this.ticket.status),n.appendChild(i);const r=document.createElement("span");return r.textContent=this.ticket.ticketKey,n.appendChild(r),t.appendChild(n),t}createMessages(){const t=document.createElement("div");t.className="utilia-messages",t.appendChild(this.createMessage({content:this.ticket.description,isExternal:!0,createdAt:this.ticket.createdAt,attachments:this.ticket.attachments}));for(const e of this.ticket.messages)t.appendChild(this.createMessage({content:e.content,isExternal:"EXTERNAL"===e.author.type,authorName:"INTERNAL"===e.author.type?e.author.name:void 0,createdAt:e.createdAt,attachments:e.attachments}));return t}createMessage(t){const e=document.createElement("div");if(e.className="utilia-message "+(t.isExternal?"external":"internal"),t.authorName){const n=document.createElement("div");n.className="utilia-message-author",n.textContent=t.authorName,e.appendChild(n)}const n=document.createElement("div");if(n.textContent=t.content,e.appendChild(n),t.attachments&&t.attachments.length>0){const n=document.createElement("div");n.className="utilia-message-attachments";for(const e of t.attachments){const t=document.createElement("a");t.className="utilia-attachment-item",t.href="#",t.addEventListener("click",async t=>{t.preventDefault();const n=await this.sdk.files.getUrl(e.id);window.open(n,"_blank")});const i=this.createFileIcon(e.mimeType);t.appendChild(i);const r=document.createElement("span");r.textContent=e.filename,t.appendChild(r),n.appendChild(t)}e.appendChild(n)}const i=document.createElement("div");var r;return i.className="utilia-message-time",i.textContent=(r=t.createdAt,new Date(r).toLocaleDateString("es-ES",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})),e.appendChild(i),e}createFileIcon(t){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("class","utilia-file-icon");const n=document.createElementNS("http://www.w3.org/2000/svg","path");return t.startsWith("image/")?n.setAttribute("d","M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zm4 8a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm7 6l-3-3-2 2-3-3-5 5"):n.setAttribute("d","M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6"),e.appendChild(n),e}createReplyForm(){const t=document.createElement("form");t.className="utilia-reply-form",t.id="utilia-reply-form";const e=document.createElement("textarea");e.className="utilia-textarea",e.name="content",e.placeholder="Escribe tu respuesta...",e.required=!0,t.appendChild(e);const n=document.createElement("div");n.className="utilia-reply-files",this.fileUpload=new $e(n,this.sdk,t=>{this.attachmentIds=t},{maxFiles:3}),t.appendChild(n);const i=document.createElement("button");return i.type="submit",i.className="utilia-btn utilia-btn-primary",i.disabled=this.isSending,i.textContent=this.isSending?"Enviando...":"Enviar respuesta",t.appendChild(i),t.addEventListener("submit",t=>this.handleSubmit(t)),t}async handleSubmit(t){if(t.preventDefault(),this.isSending)return;const e=t.target,n=new FormData(e).get("content").trim();if(n){this.isSending=!0,this.render();try{await this.sdk.tickets.addMessage(this.ticketId,this.userId,{content:n,attachmentIds:this.attachmentIds.length>0?this.attachmentIds:void 0}),this.attachmentIds=[],this.fileUpload&&this.fileUpload.reset(),this.isLoading=!0,this.isSending=!1,await this.loadTicket()}catch(i){console.error("[UtiliaWidget] Error sending message:",i),this.isSending=!1,this.render()}}}scrollToBottom(){const t=this.container.querySelector(".utilia-messages");t&&(t.scrollTop=t.scrollHeight)}}class Ke extends HTMLElement{constructor(){super(),this.sdk=null,this.config=null,this.state={view:"closed",selectedTicketId:null,isLoading:!1,error:null,unreadCount:0},this.ticketList=null,this.ticketForm=null,this.ticketDetail=null,this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","api-key","user-id","user-email","user-name","position","theme"]}connectedCallback(){this.render(),this.initializeFromAttributes()}disconnectedCallback(){}attributeChangedCallback(t,e,n){e!==n&&this.isConnected&&this.initializeFromAttributes()}init(t){this.config=t,this.sdk=new je({baseURL:t.baseURL,apiKey:t.apiKey}),t.theme&&this.setAttribute("data-theme",t.theme),this.identifyUser(),this.loadUnreadCount(),this.render()}initializeFromAttributes(){const t=this.getAttribute("base-url"),e=this.getAttribute("api-key"),n=this.getAttribute("user-id");t&&e&&n&&this.init({baseURL:t,apiKey:e,userId:n,userEmail:this.getAttribute("user-email")||void 0,userName:this.getAttribute("user-name")||void 0,position:this.getAttribute("position")||"bottom-right",theme:this.getAttribute("theme")||"light"})}async identifyUser(){if(this.sdk&&this.config)try{await this.sdk.users.identify({externalId:this.config.userId,email:this.config.userEmail,name:this.config.userName,metadata:this.config.userMetadata})}catch(t){console.error("[UtiliaWidget] Error identifying user:",t)}}async loadUnreadCount(){if(this.sdk&&this.config)try{const{count:t}=await this.sdk.tickets.getUnreadCount(this.config.userId);this.state.unreadCount=t,this.updateBadge()}catch(t){}}open(){this.state.view="list",this.render(),this.dispatchEvent(new CustomEvent("widget:open"))}close(){this.state.view="closed",this.state.selectedTicketId=null,this.render(),this.dispatchEvent(new CustomEvent("widget:close"))}showNewTicketForm(){this.state.view="form",this.render()}showTicketDetail(t){this.state.selectedTicketId=t,this.state.view="detail",this.render()}goBack(){this.state.view="list",this.state.selectedTicketId=null,this.render()}updateBadge(){const t=this.shadow.querySelector(".utilia-badge");t&&(t.textContent=this.state.unreadCount>99?"99+":String(this.state.unreadCount),t.classList.toggle("hidden",0===this.state.unreadCount))}render(){var t,e;this.shadow.replaceChildren();const n=document.createElement("style");n.textContent='\n :host {\n --utilia-primary: #2563eb;\n --utilia-primary-hover: #1d4ed8;\n --utilia-bg: #ffffff;\n --utilia-bg-secondary: #f8fafc;\n --utilia-text: #1e293b;\n --utilia-text-secondary: #64748b;\n --utilia-border: #e2e8f0;\n --utilia-radius: 12px;\n --utilia-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);\n --utilia-shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);\n\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n font-size: 14px;\n line-height: 1.5;\n }\n\n :host([data-theme="dark"]) {\n --utilia-bg: #1e293b;\n --utilia-bg-secondary: #334155;\n --utilia-text: #f8fafc;\n --utilia-text-secondary: #94a3b8;\n --utilia-border: #475569;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n\n .utilia-widget {\n position: fixed;\n z-index: 999999;\n }\n\n .utilia-widget[data-position="bottom-right"] {\n bottom: 20px;\n right: 20px;\n }\n\n .utilia-widget[data-position="bottom-left"] {\n bottom: 20px;\n left: 20px;\n }\n\n /* Launcher Button */\n .utilia-launcher {\n width: 56px;\n height: 56px;\n border-radius: 50%;\n background: var(--utilia-primary);\n color: white;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: var(--utilia-shadow-lg);\n transition: transform 0.2s, background 0.2s;\n position: relative;\n }\n\n .utilia-launcher:hover {\n background: var(--utilia-primary-hover);\n transform: scale(1.05);\n }\n\n .utilia-icon {\n width: 24px;\n height: 24px;\n }\n\n .utilia-badge {\n position: absolute;\n top: -4px;\n right: -4px;\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n background: #ef4444;\n color: white;\n font-size: 11px;\n font-weight: 600;\n border-radius: 10px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .utilia-badge.hidden {\n display: none;\n }\n\n /* Panel */\n .utilia-panel {\n width: 380px;\n max-width: calc(100vw - 40px);\n height: 560px;\n max-height: calc(100vh - 100px);\n background: var(--utilia-bg);\n border-radius: var(--utilia-radius);\n box-shadow: var(--utilia-shadow-lg);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n /* Header */\n .utilia-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--utilia-border);\n background: var(--utilia-bg);\n }\n\n .utilia-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--utilia-text);\n }\n\n .utilia-header-actions {\n display: flex;\n gap: 8px;\n }\n\n .utilia-header-actions button {\n width: 32px;\n height: 32px;\n border: none;\n background: transparent;\n border-radius: 8px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--utilia-text-secondary);\n transition: background 0.2s, color 0.2s;\n }\n\n .utilia-header-actions button:hover {\n background: var(--utilia-bg-secondary);\n color: var(--utilia-text);\n }\n\n .utilia-header-actions button svg {\n width: 18px;\n height: 18px;\n }\n\n /* Content */\n .utilia-content {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n /* Loading */\n .utilia-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 200px;\n }\n\n .utilia-spinner {\n width: 32px;\n height: 32px;\n border: 3px solid var(--utilia-border);\n border-top-color: var(--utilia-primary);\n border-radius: 50%;\n animation: utilia-spin 0.8s linear infinite;\n }\n\n @keyframes utilia-spin {\n to { transform: rotate(360deg); }\n }\n\n /* Buttons */\n .utilia-btn {\n padding: 10px 16px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n }\n\n .utilia-btn-primary {\n background: var(--utilia-primary);\n color: white;\n }\n\n .utilia-btn-primary:hover {\n background: var(--utilia-primary-hover);\n }\n\n .utilia-btn-primary:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n\n .utilia-btn-secondary {\n background: var(--utilia-bg-secondary);\n color: var(--utilia-text);\n border: 1px solid var(--utilia-border);\n }\n\n /* Form elements */\n .utilia-input,\n .utilia-textarea,\n .utilia-select {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--utilia-border);\n border-radius: 8px;\n font-size: 14px;\n background: var(--utilia-bg);\n color: var(--utilia-text);\n transition: border-color 0.2s;\n font-family: inherit;\n }\n\n .utilia-input:focus,\n .utilia-textarea:focus,\n .utilia-select:focus {\n outline: none;\n border-color: var(--utilia-primary);\n }\n\n .utilia-textarea {\n min-height: 100px;\n resize: vertical;\n }\n\n .utilia-label {\n display: block;\n margin-bottom: 6px;\n font-size: 13px;\n font-weight: 500;\n color: var(--utilia-text);\n }\n\n .utilia-form-group {\n margin-bottom: 16px;\n }\n\n /* Ticket List */\n .utilia-ticket-item {\n padding: 12px;\n border: 1px solid var(--utilia-border);\n border-radius: 8px;\n margin-bottom: 8px;\n cursor: pointer;\n transition: background 0.2s;\n }\n\n .utilia-ticket-item:hover {\n background: var(--utilia-bg-secondary);\n }\n\n .utilia-ticket-title {\n font-weight: 500;\n color: var(--utilia-text);\n margin-bottom: 4px;\n }\n\n .utilia-ticket-meta {\n font-size: 12px;\n color: var(--utilia-text-secondary);\n display: flex;\n gap: 8px;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .utilia-ticket-badge {\n padding: 2px 8px;\n border-radius: 4px;\n font-size: 11px;\n font-weight: 500;\n }\n\n .utilia-ticket-badge.open { background: #dbeafe; color: #1d4ed8; }\n .utilia-ticket-badge.in-review { background: #fef3c7; color: #d97706; }\n .utilia-ticket-badge.resolved { background: #dcfce7; color: #16a34a; }\n .utilia-ticket-badge.closed { background: #f1f5f9; color: #64748b; }\n\n .utilia-unread {\n color: var(--utilia-primary);\n font-weight: 500;\n }\n\n /* Messages */\n .utilia-messages {\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding-bottom: 16px;\n }\n\n .utilia-message {\n max-width: 85%;\n padding: 10px 14px;\n border-radius: 12px;\n word-wrap: break-word;\n }\n\n .utilia-message.external {\n align-self: flex-end;\n background: var(--utilia-primary);\n color: white;\n border-bottom-right-radius: 4px;\n }\n\n .utilia-message.internal {\n align-self: flex-start;\n background: var(--utilia-bg-secondary);\n color: var(--utilia-text);\n border-bottom-left-radius: 4px;\n }\n\n .utilia-message-author {\n font-size: 11px;\n font-weight: 500;\n margin-bottom: 4px;\n opacity: 0.9;\n }\n\n .utilia-message-time {\n font-size: 11px;\n opacity: 0.7;\n margin-top: 4px;\n }\n\n /* Ticket Detail Header */\n .utilia-ticket-header {\n margin-bottom: 16px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--utilia-border);\n }\n\n /* Empty state */\n .utilia-empty {\n text-align: center;\n padding: 40px 20px;\n color: var(--utilia-text-secondary);\n }\n\n .utilia-empty-icon {\n width: 48px;\n height: 48px;\n margin: 0 auto 16px;\n opacity: 0.5;\n }\n\n .utilia-empty-text {\n margin-top: 8px;\n font-size: 12px;\n }\n\n /* Error */\n .utilia-error {\n padding: 12px;\n background: #fef2f2;\n border: 1px solid #fecaca;\n border-radius: 8px;\n color: #dc2626;\n font-size: 13px;\n margin-bottom: 16px;\n }\n\n /* Reply form */\n .utilia-reply-form {\n margin-top: auto;\n padding-top: 16px;\n border-top: 1px solid var(--utilia-border);\n }\n\n .utilia-reply-form .utilia-textarea {\n min-height: 60px;\n }\n\n .utilia-reply-form .utilia-btn {\n width: 100%;\n margin-top: 8px;\n }\n\n .utilia-reply-files {\n margin-top: 12px;\n }\n\n .utilia-reply-files .utilia-drop-zone {\n padding: 12px;\n min-height: auto;\n }\n\n .utilia-reply-files .utilia-drop-text {\n font-size: 12px;\n }\n\n .utilia-reply-files .utilia-drop-hint {\n font-size: 11px;\n }\n\n /* Closed ticket notice */\n .utilia-closed-notice {\n text-align: center;\n padding: 16px;\n color: var(--utilia-text-secondary);\n font-size: 13px;\n }\n\n /* AI Section */\n .utilia-ai-section {\n background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);\n border: 1px solid #bae6fd;\n border-radius: 10px;\n padding: 14px;\n margin-bottom: 20px;\n }\n\n :host([data-theme="dark"]) .utilia-ai-section {\n background: linear-gradient(135deg, #1e3a5f 0%, #172554 100%);\n border-color: #1e40af;\n }\n\n .utilia-ai-header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n }\n\n .utilia-ai-label {\n font-size: 13px;\n font-weight: 600;\n color: #0369a1;\n }\n\n :host([data-theme="dark"]) .utilia-ai-label {\n color: #7dd3fc;\n }\n\n .utilia-ai-desc {\n font-size: 12px;\n color: #0c4a6e;\n margin-bottom: 12px;\n line-height: 1.4;\n }\n\n :host([data-theme="dark"]) .utilia-ai-desc {\n color: #bae6fd;\n }\n\n .utilia-ai-controls {\n display: flex;\n gap: 8px;\n }\n\n /* Record Button */\n .utilia-record-btn {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 10px 16px;\n background: var(--utilia-primary);\n color: white;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n font-size: 13px;\n font-weight: 500;\n transition: all 0.2s;\n width: 100%;\n justify-content: center;\n }\n\n .utilia-record-btn:hover:not(:disabled) {\n background: var(--utilia-primary-hover);\n transform: translateY(-1px);\n }\n\n .utilia-record-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n\n .utilia-record-btn.recording {\n background: #dc2626;\n animation: utilia-pulse 1.5s ease-in-out infinite;\n }\n\n .utilia-record-btn.recording:hover:not(:disabled) {\n background: #b91c1c;\n }\n\n @keyframes utilia-pulse {\n 0%, 100% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0.4); }\n 50% { box-shadow: 0 0 0 8px rgba(220, 38, 38, 0); }\n }\n\n .utilia-mic-icon {\n width: 18px;\n height: 18px;\n flex-shrink: 0;\n }\n\n /* AI Loading */\n .utilia-ai-loading {\n display: flex;\n align-items: center;\n gap: 10px;\n margin-top: 12px;\n padding: 10px;\n background: rgba(255, 255, 255, 0.7);\n border-radius: 6px;\n font-size: 12px;\n color: #0369a1;\n }\n\n :host([data-theme="dark"]) .utilia-ai-loading {\n background: rgba(0, 0, 0, 0.2);\n color: #7dd3fc;\n }\n\n .utilia-spinner-small {\n width: 16px;\n height: 16px;\n border-width: 2px;\n flex-shrink: 0;\n }\n\n /* AI Error */\n .utilia-ai-error {\n margin-top: 10px;\n padding: 8px 12px;\n background: #fef2f2;\n border: 1px solid #fecaca;\n border-radius: 6px;\n font-size: 12px;\n color: #dc2626;\n }\n\n :host([data-theme="dark"]) .utilia-ai-error {\n background: rgba(220, 38, 38, 0.15);\n border-color: rgba(220, 38, 38, 0.3);\n color: #fca5a5;\n }\n\n /* ======================================\n FILE UPLOAD STYLES\n ====================================== */\n\n /* Drop Zone */\n .utilia-drop-zone {\n border: 2px dashed var(--utilia-border);\n border-radius: 8px;\n padding: 20px;\n text-align: center;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 8px;\n }\n\n .utilia-drop-zone:hover,\n .utilia-drop-zone.drag-over {\n border-color: var(--utilia-primary);\n background: rgba(37, 99, 235, 0.05);\n }\n\n .utilia-upload-icon {\n width: 32px;\n height: 32px;\n color: var(--utilia-text-secondary);\n }\n\n .utilia-drop-text {\n font-size: 13px;\n color: var(--utilia-text);\n }\n\n .utilia-drop-hint {\n font-size: 11px;\n color: var(--utilia-text-secondary);\n }\n\n /* File List */\n .utilia-file-list {\n margin-top: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n }\n\n .utilia-file-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 12px;\n background: var(--utilia-bg-secondary);\n border-radius: 6px;\n font-size: 13px;\n }\n\n .utilia-file-item.pending {\n opacity: 0.7;\n }\n\n .utilia-file-info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .utilia-file-name {\n color: var(--utilia-text);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .utilia-file-size {\n font-size: 11px;\n color: var(--utilia-text-secondary);\n }\n\n .utilia-file-remove {\n width: 24px;\n height: 24px;\n border: none;\n background: transparent;\n color: var(--utilia-text-secondary);\n cursor: pointer;\n border-radius: 4px;\n font-size: 18px;\n line-height: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .utilia-file-remove:hover {\n background: rgba(239, 68, 68, 0.1);\n color: #ef4444;\n }\n\n /* Progress Bar */\n .utilia-file-progress {\n height: 4px;\n background: var(--utilia-border);\n border-radius: 2px;\n overflow: hidden;\n }\n\n .utilia-file-progress-bar {\n height: 100%;\n background: var(--utilia-primary);\n transition: width 0.2s;\n }\n\n /* File Error */\n .utilia-file-error {\n margin-top: 8px;\n padding: 8px 12px;\n background: #fef2f2;\n border: 1px solid #fecaca;\n border-radius: 6px;\n font-size: 12px;\n color: #dc2626;\n }\n\n .utilia-file-error-inline {\n font-size: 11px;\n color: #dc2626;\n }\n\n :host([data-theme="dark"]) .utilia-file-error,\n :host([data-theme="dark"]) .utilia-file-error-inline {\n background: rgba(220, 38, 38, 0.15);\n border-color: rgba(220, 38, 38, 0.3);\n color: #fca5a5;\n }\n\n /* Message Attachments */\n .utilia-message-attachments {\n margin-top: 8px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .utilia-attachment-item {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 4px 8px;\n background: rgba(255, 255, 255, 0.1);\n border-radius: 4px;\n font-size: 12px;\n color: inherit;\n text-decoration: none;\n transition: background 0.2s;\n }\n\n .utilia-attachment-item:hover {\n background: rgba(255, 255, 255, 0.2);\n }\n\n .utilia-file-icon {\n width: 14px;\n height: 14px;\n flex-shrink: 0;\n }\n\n /* ======================================\n AI SUGGESTIONS REVIEW\n ====================================== */\n\n .utilia-ai-suggestions {\n margin-top: 12px;\n border: 1px solid var(--utilia-border);\n border-radius: 8px;\n overflow: hidden;\n }\n\n .utilia-ai-suggestions-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 14px;\n background: var(--utilia-bg-secondary);\n border-bottom: 1px solid var(--utilia-border);\n font-size: 13px;\n font-weight: 500;\n }\n\n .utilia-suggestion-item {\n padding: 10px 14px;\n border-bottom: 1px solid var(--utilia-border);\n display: flex;\n align-items: flex-start;\n gap: 10px;\n }\n\n .utilia-suggestion-item:last-child {\n border-bottom: none;\n }\n\n .utilia-suggestion-field {\n flex: 1;\n min-width: 0;\n }\n\n .utilia-suggestion-field-name {\n font-size: 11px;\n font-weight: 600;\n color: var(--utilia-text-secondary);\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 4px;\n }\n\n .utilia-suggestion-value {\n font-size: 13px;\n color: var(--utilia-text);\n line-height: 1.4;\n max-height: 60px;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .utilia-suggestion-actions {\n display: flex;\n gap: 4px;\n flex-shrink: 0;\n }\n\n .utilia-suggestion-btn {\n width: 28px;\n height: 28px;\n border: 1px solid var(--utilia-border);\n border-radius: 6px;\n background: var(--utilia-bg);\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.15s;\n padding: 0;\n }\n\n .utilia-suggestion-btn.accept {\n color: #16a34a;\n }\n\n .utilia-suggestion-btn.accept:hover,\n .utilia-suggestion-btn.accept.active {\n background: #dcfce7;\n border-color: #16a34a;\n }\n\n .utilia-suggestion-btn.reject {\n color: #dc2626;\n }\n\n .utilia-suggestion-btn.reject:hover,\n .utilia-suggestion-btn.reject.active {\n background: #fef2f2;\n border-color: #dc2626;\n }\n\n .utilia-suggestion-btn svg {\n width: 14px;\n height: 14px;\n }\n\n .utilia-suggestions-footer {\n display: flex;\n gap: 8px;\n padding: 10px 14px;\n background: var(--utilia-bg-secondary);\n border-top: 1px solid var(--utilia-border);\n }\n\n .utilia-suggestions-footer .utilia-btn {\n flex: 1;\n padding: 8px 12px;\n font-size: 13px;\n }\n\n /* AI Text Input */\n .utilia-ai-input-group {\n display: flex;\n gap: 8px;\n margin-top: 8px;\n }\n\n .utilia-ai-textarea {\n flex: 1;\n min-height: 60px;\n max-height: 120px;\n resize: vertical;\n padding: 8px 12px;\n border: 1px solid var(--utilia-border);\n border-radius: 6px;\n font-size: 13px;\n font-family: inherit;\n background: var(--utilia-bg);\n color: var(--utilia-text);\n }\n\n .utilia-ai-textarea:focus {\n outline: none;\n border-color: var(--utilia-primary);\n }\n\n .utilia-ai-textarea:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .utilia-ai-generate-btn {\n padding: 8px 14px;\n font-size: 13px;\n white-space: nowrap;\n }\n',this.shadow.appendChild(n);const i=document.createElement("div");i.className="utilia-widget",i.dataset.position=(null==(t=this.config)?void 0:t.position)||"bottom-right",i.dataset.theme=(null==(e=this.config)?void 0:e.theme)||"light","closed"===this.state.view?i.appendChild(this.renderLauncher()):i.appendChild(this.renderPanel()),this.shadow.appendChild(i)}renderLauncher(){const t=document.createElement("button");t.className="utilia-launcher",t.setAttribute("aria-label","Abrir soporte");const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("class","utilia-icon"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"),e.appendChild(n),t.appendChild(e);const i=document.createElement("span");return i.className="utilia-badge "+(0===this.state.unreadCount?"hidden":""),i.textContent=this.state.unreadCount>99?"99+":String(this.state.unreadCount),t.appendChild(i),t.addEventListener("click",()=>this.open()),t}renderPanel(){const t=document.createElement("div");t.className="utilia-panel",t.appendChild(this.renderHeader());const e=document.createElement("main");return e.className="utilia-content",t.appendChild(e),setTimeout(()=>this.initSubComponent(e),0),t}renderHeader(){const t=document.createElement("header");t.className="utilia-header";const e=document.createElement("h2");switch(e.className="utilia-title",this.state.view){case"list":e.textContent="Soporte";break;case"form":e.textContent="Nuevo ticket";break;case"detail":e.textContent="Ticket"}t.appendChild(e);const n=document.createElement("div");if(n.className="utilia-header-actions","list"===this.state.view){const t=this.createHeaderButton("Nuevo ticket",this.createPlusIcon());t.addEventListener("click",()=>this.showNewTicketForm()),n.appendChild(t)}else{const t=this.createHeaderButton("Volver",this.createBackIcon());t.addEventListener("click",()=>this.goBack()),n.appendChild(t)}const i=this.createHeaderButton("Cerrar",this.createCloseIcon());return i.addEventListener("click",()=>this.close()),n.appendChild(i),t.appendChild(n),t}createHeaderButton(t,e){const n=document.createElement("button");return n.setAttribute("aria-label",t),n.appendChild(e),n}createPlusIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2");const e=document.createElementNS("http://www.w3.org/2000/svg","line");e.setAttribute("x1","12"),e.setAttribute("y1","5"),e.setAttribute("x2","12"),e.setAttribute("y2","19");const n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","5"),n.setAttribute("y1","12"),n.setAttribute("x2","19"),n.setAttribute("y2","12"),t.appendChild(e),t.appendChild(n),t}createBackIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2");const e=document.createElementNS("http://www.w3.org/2000/svg","polyline");return e.setAttribute("points","15 18 9 12 15 6"),t.appendChild(e),t}createCloseIcon(){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2");const e=document.createElementNS("http://www.w3.org/2000/svg","line");e.setAttribute("x1","18"),e.setAttribute("y1","6"),e.setAttribute("x2","6"),e.setAttribute("y2","18");const n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","6"),n.setAttribute("y1","6"),n.setAttribute("x2","18"),n.setAttribute("y2","18"),t.appendChild(e),t.appendChild(n),t}initSubComponent(t){if(this.sdk&&this.config)switch(this.state.view){case"list":this.ticketList=new Me(t,this.sdk,this.config.userId,t=>this.showTicketDetail(t));break;case"form":this.ticketForm=new We(t,this.sdk,this.config,t=>{var e,n;null==(n=null==(e=this.config)?void 0:e.onTicketCreated)||n.call(e,t),this.dispatchEvent(new CustomEvent("ticket:created",{detail:t})),this.state.view="list",this.render()});break;case"detail":this.state.selectedTicketId&&(this.ticketDetail=new He(t,this.sdk,this.config.userId,this.state.selectedTicketId))}}}function Ve(t){let e=document.querySelector("utilia-support");return e||(e=document.createElement("utilia-support"),document.body.appendChild(e)),e.init(t),e}if("undefined"==typeof window||customElements.get("utilia-support")||customElements.define("utilia-support",Ke),"undefined"!=typeof document){const t=()=>{const t=document.querySelector("script[data-utilia-widget]");if(!t)return;const e=t.getAttribute("data-base-url"),n=t.getAttribute("data-api-key"),i=t.getAttribute("data-user-id");if(!e||!n||!i)return void console.warn("[UtiliaWidget] Missing required data attributes: data-base-url, data-api-key, data-user-id");Ve({baseURL:e,apiKey:n,userId:i,userEmail:t.getAttribute("data-user-email")||void 0,userName:t.getAttribute("data-user-name")||void 0,position:t.getAttribute("data-position")||"bottom-right",theme:t.getAttribute("data-theme")||"light",autoContext:"false"!==t.getAttribute("data-auto-context")})};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}return t.UtiliaSupportWidget=Ke,t.initUtiliaWidget=Ve,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),t}({});
2
+ //# sourceMappingURL=utilia-widget.js.map