-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
16 lines (13 loc) · 26.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(function(){"use strict";function I(){return window.panel}function K(){return I().api}function fe(){const o=K();return{load:({parent:n,name:e})=>o.get(`${n}/sections/${e}`)}}function he(){return I().app.$store}const s=window.Vue,Y=s.computed;s.customRef,s.defineAsyncComponent,s.defineComponent,s.effectScope,s.getCurrentInstance,s.getCurrentScope,s.h,s.inject,s.isProxy,s.isReactive,s.isReadonly,s.isRef,s.isShallow,s.markRaw;const X=s.nextTick;s.onActivated,s.onBeforeMount;const me=s.onBeforeUnmount;s.onBeforeUpdate,s.onDeactivated,s.onErrorCaptured,s.onMounted,s.onRenderTracked,s.onRenderTriggered,s.onScopeDispose,s.onServerPrefetch,s.onUnmounted,s.onUpdated,s.provide,s.proxyRefs,s.reactive,s.readonly;const m=s.ref;s.shallowReactive,s.shallowReadonly,s.shallowRef,s.toRaw,s.toRef,s.toRefs,s.triggerRef;const Q=s.unref;s.useAttrs,s.useCssModule,s.useCssVars,s.useListeners,s.useSlots;const Z=s.watch;s.watchEffect,s.watchPostEffect,s.watchSyncEffect;const ge={blueprint:String,lock:[Boolean,Object],help:String,name:String,parent:String,timestamp:Number},N={en:{"modal.info":"Thanks for purchasing {label}! Please enter your email address and order ID to activate your license.","modal.fields.orderId.help":'<a href="https://app.lemonsqueezy.com/my-orders" target="_blank">Find your order number</a> on Lemon Squeezy or <a href="mailto:[email protected]">contact us</a> if you cannot find it.',"modal.error.required.fields":"Email address and order ID are required","modal.error.invalid.unauthorized":"Email address or order ID is incorrect","modal.error.invalid.licenseKey":"License key invalid for this plugin","modal.error.incompatible.licenseKey":"License key invalid for this plugin version","modal.error.registered":"License key already registered",activate:"Activate",activated:"Plugin activated"},de:{"modal.info":"Dankeschön für den Kauf von {label}! Bitte gib deine E-Mail-Adresse und Bestellnummer ein, um deine Lizenz zu aktivieren.","modal.fields.orderId.help":'<a href="https://app.lemonsqueezy.com/my-orders" target="_blank">Finde deine Bestellnummer</a> bei Lemon Squeezy oder <a href="mailto:[email protected]">kontaktiere uns</a>, wenn du sie nicht finden kannst.',"modal.error.required.fields":"E-Mail-Adresse und Bestellnummer sind notwendig","modal.error.invalid.unauthorized":"E-Mail-Adresse oder Bestellnummer ist falsch","modal.error.invalid.licenseKey":"Lizenzschlüssel ungültig für dieses Plugin","modal.error.incompatible.licenseKey":"Lizenzschlüssel ungültig für diese Plugin-Version","modal.error.registered":"Lizenzschlüssel bereits registriert",activate:"Aktivieren",activated:"Plugin aktiviert"},fr:{"modal.info":"Merci d'avoir acheté {label} ! Veuillez saisir votre adresse e-mail et votre numéro de commande pour activer votre licence.","modal.fields.orderId.help":'<a href="https://app.lemonsqueezy.com/my-orders" target="_blank">Trouvez votre numéro de commande</a> sur Lemon Squeezy ou <a href="mailto:[email protected]">contactez-nous</a> si vous ne le trouvez pas.',"modal.error.required.fields":"Adresse e-mail et numéro de commande requis","modal.error.invalid.unauthorized":"Adresse e-mail ou numéro de commande incorrect","modal.error.invalid.licenseKey":"Clé de licence invalide pour ce plugin","modal.error.incompatible.licenseKey":"Clé de licence invalide pour cette version du plugin","modal.error.registered":"Clé de licence déjà enregistrée",activate:"Activer",activated:"Plugin activé"}};function P(o,t,n){var l;const r=I().translation.code,a=((l=N==null?void 0:N[r])==null?void 0:l[o])??n;if(a)return t?ye(a,t):a}function ye(o,t,n){return o.replace(/\{(\w+)\}/g,(e,r)=>t[r]||r)}const ve=["localhost","127.0.0.1","[::1]"],we=["local","test","ddev.site"];function _e({label:o,apiNamespace:t}){const n=I(),e=K(),r=be(),a=async(i,u)=>{if(!i||!u)throw new Error("Email and order ID are required");const d=await e.post(`${t}/register`,{email:i,orderId:u});if((d==null?void 0:d.status)!=="ok")throw new Error("Registration failed");return!0};return{isLocalhost:r,assertActivationIntegrity:async({component:i,licenseStatus:u})=>{if(Q(u)==="active")return;await X();const d=Q(i);if(!(d!=null&&d.$el)||window.getComputedStyle(d.$el).display==="none"||window.getComputedStyle(d.$el).visibility==="hidden"||window.getComputedStyle(d.$el).opacity==="0")throw new Error("Are you trying to hide the activation buttons? Please buy a license.")},openLicenseModal:()=>{let i=!1;return new Promise(u=>{n.dialog.open({component:"k-form-dialog",props:{submitButton:{icon:"check",theme:"love",text:P("activate",{label:o})},fields:{info:{type:"info",text:P("modal.info",{label:o})},email:{label:n.t("email"),type:"email"},orderId:{label:"Order ID",type:"text",help:P("modal.fields.orderId.help",{label:o})}}},on:{close:()=>{u({isRegistered:i})},submit:async d=>{const{email:g,orderId:c}=d;if(!g||!c){n.notification.error(P("modal.error.required.fields"));return}try{await a(g,Number(c))}catch(x){let y=x.message;y==="Unauthorized"?y=P("modal.error.invalid.unauthorized"):y==="License key not valid for this plugin"?y=P("modal.error.invalid.licenseKey"):y==="License key not valid for this plugin version"?y=P("modal.error.incompatible.licenseKey"):y==="License key already registered"&&(y=P("modal.error.registered")),n.notification.error(y);return}i=!0,n.dialog.close(),n.notification.success(P("activated"))}}})})}}}function be(){const{hostname:o}=window.location,t=ve.includes(o),n=we.some(e=>o.endsWith(`.${e}`));return t||n}const xe=["anthropic","mistral","openai"],q=["image/png","image/jpeg","image/webp","image/gif"],ke=["error","warn","info","debug"],Se="kirby$copilot$";let U=[];const V=new Map;async function Pe(o){if(!Array.isArray(o))throw new TypeError("Expected an array of assets");U.length>0||(U=o)}function ee(o){if(U.length===0)throw new Error("Plugin assets are not registered");const t=U.find(n=>n.filename===o);if(!t)throw new Error(`Plugin asset "${o}" not found`);return t}async function te(o){if(o.endsWith(".js")||(o+=".js"),V.has(o))return V.get(o);const n=await import(ee(o).url);return V.set(o,n),n}function Be(o,t,n){return o.replace(/\{(\w+)\}/g,(e,r)=>t[r.toLowerCase()]||r)}let T;async function Ee(o){const t=await Le(),n=await o.arrayBuffer(),e=await t.getDocument({data:n,useSystemFonts:!0}).promise;return(await Promise.all(Array.from({length:e.numPages},(a,l)=>Ce(e,l+1)))).join(`
`).replace(/\s+/g," ")}async function Ce(o,t){return(await(await o.getPage(t)).getTextContent()).items.filter(r=>r.str!=null).map(r=>r.str).join(" ")}async function Le(){if(T)return T;T=await te("pdfjs");const o=ee("pdfjs.worker.js");return T.GlobalWorkerOptions.workerSrc=o.url,T}class ze{constructor(){this.defaultColor="#7f8c8d",this.levelColorMap={0:"#c0392b",1:"#f39c12",2:"#00BCD4"},this.typeColorMap={success:"#2ecc71"}}_getLogFn(t){return t<1?console.error:console.log}log(t){const n=this._getLogFn(t.level),e=t.type==="log"?"":t.type,r=t.tag||"",l=`
background: ${this.typeColorMap[t.type]||this.levelColorMap[t.level]||this.defaultColor};
border-radius: 0.5em;
color: white;
font-weight: bold;
padding: 2px 0.5em;
`.trimStart(),h=`%c${[r,e].filter(Boolean).join(":")}`;typeof t.args[0]=="string"?n(`${h}%c ${t.args[0]}`,l,"",...t.args.slice(1)):n(h,l,...t.args)}}const Ae={error:0,warn:1,info:2};function Re(o){const t=new ze;return new Proxy({},{get(n,e){return(...r)=>{t.log({level:Ae[e],type:e,tag:o,args:r})}}})}let Fe;function $e(){return Fe??(Fe=Re("copilot"))}async function je({userPrompt:o,systemPrompt:t,context:n,files:e,config:r,logLevel:a,abortSignal:l}){const h=$e(),{createAnthropic:i,createMistral:u,createOpenAI:d,experimental_streamText:g}=await te("ai"),c=r.provider,x=r.providers[c],y={mistral:u,openai:d,anthropic:i}[c],$=y({baseUrl:x.baseUrl||void 0,apiKey:x.apiKey}),E=e.filter(v=>v.type.startsWith("image/")),z=e.filter(v=>v.type==="application/pdf");let k=Be(o,n);if(z.length>0){const w=`Additional context from the following PDF documents has been processed and made available to you. Include the information from these documents as applicable.
${(await Promise.all(z.map(Ee))).map((_,j)=>`PDF document ${j+1}: ${_}`).join(`
`)}`;k+=`
${w}`}if(a>1&&(h.info("System prompt:",t),h.info("User prompt with context:",k)),c==="openai"&&E.length>0){const v=await Promise.all(E.map(async w=>{const _=await w.arrayBuffer();return{data:new Uint8Array(_),mimeType:w.type}}));return g({model:$.chat(x.model),temperature:r.temperature,maxTokens:r.maxGenerationTokens,system:t,messages:[{role:"user",content:[{type:"text",text:k},...v.map(w=>({type:"image",image:w.data}))]}],abortSignal:l})}return g({model:$.chat(x.model),temperature:r.temperature,maxTokens:r.maxGenerationTokens,system:t,prompt:k,abortSignal:l})}const ne=Object.freeze({ignoreUnknown:!1,respectType:!1,respectFunctionNames:!1,respectFunctionProperties:!1,unorderedObjects:!0,unorderedArrays:!1,unorderedSets:!1,excludeKeys:void 0,excludeValues:void 0,replacer:void 0});function Ie(o,t){t?t={...ne,...t}:t=ne;const n=re(t);return n.dispatch(o),n.toString()}const Te=Object.freeze(["prototype","__proto__","constructor"]);function re(o){let t="",n=new Map;const e=r=>{t+=r};return{toString(){return t},getContext(){return n},dispatch(r){return o.replacer&&(r=o.replacer(r)),this[r===null?"null":typeof r](r)},object(r){if(r&&typeof r.toJSON=="function")return this.object(r.toJSON());const a=Object.prototype.toString.call(r);let l="";const h=a.length;h<10?l="unknown:["+a+"]":l=a.slice(8,h-1),l=l.toLowerCase();let i=null;if((i=n.get(r))===void 0)n.set(r,n.size);else return this.dispatch("[CIRCULAR:"+i+"]");if(typeof Buffer<"u"&&Buffer.isBuffer&&Buffer.isBuffer(r))return e("buffer:"),e(r.toString("utf8"));if(l!=="object"&&l!=="function"&&l!=="asyncfunction")this[l]?this[l](r):o.ignoreUnknown||this.unkown(r,l);else{let u=Object.keys(r);o.unorderedObjects&&(u=u.sort());let d=[];o.respectType!==!1&&!ie(r)&&(d=Te),o.excludeKeys&&(u=u.filter(c=>!o.excludeKeys(c)),d=d.filter(c=>!o.excludeKeys(c))),e("object:"+(u.length+d.length)+":");const g=c=>{this.dispatch(c),e(":"),o.excludeValues||this.dispatch(r[c]),e(",")};for(const c of u)g(c);for(const c of d)g(c)}},array(r,a){if(a=a===void 0?o.unorderedArrays!==!1:a,e("array:"+r.length+":"),!a||r.length<=1){for(const i of r)this.dispatch(i);return}const l=new Map,h=r.map(i=>{const u=re(o);u.dispatch(i);for(const[d,g]of u.getContext())l.set(d,g);return u.toString()});return n=l,h.sort(),this.array(h,!1)},date(r){return e("date:"+r.toJSON())},symbol(r){return e("symbol:"+r.toString())},unkown(r,a){if(e(a),!!r&&(e(":"),r&&typeof r.entries=="function"))return this.array(Array.from(r.entries()),!0)},error(r){return e("error:"+r.toString())},boolean(r){return e("bool:"+r)},string(r){e("string:"+r.length+":"),e(r)},function(r){e("fn:"),ie(r)?this.dispatch("[native]"):this.dispatch(r.toString()),o.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(r.name)),o.respectFunctionProperties&&this.object(r)},number(r){return e("number:"+r)},xml(r){return e("xml:"+r.toString())},null(){return e("Null")},undefined(){return e("Undefined")},regexp(r){return e("regex:"+r.toString())},uint8array(r){return e("uint8array:"),this.dispatch(Array.prototype.slice.call(r))},uint8clampedarray(r){return e("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(r))},int8array(r){return e("int8array:"),this.dispatch(Array.prototype.slice.call(r))},uint16array(r){return e("uint16array:"),this.dispatch(Array.prototype.slice.call(r))},int16array(r){return e("int16array:"),this.dispatch(Array.prototype.slice.call(r))},uint32array(r){return e("uint32array:"),this.dispatch(Array.prototype.slice.call(r))},int32array(r){return e("int32array:"),this.dispatch(Array.prototype.slice.call(r))},float32array(r){return e("float32array:"),this.dispatch(Array.prototype.slice.call(r))},float64array(r){return e("float64array:"),this.dispatch(Array.prototype.slice.call(r))},arraybuffer(r){return e("arraybuffer:"),this.dispatch(new Uint8Array(r))},url(r){return e("url:"+r.toString())},map(r){e("map:");const a=[...r];return this.array(a,o.unorderedSets!==!1)},set(r){e("set:");const a=[...r];return this.array(a,o.unorderedSets!==!1)},file(r){return e("file:"),this.dispatch([r.name,r.size,r.type,r.lastModfied])},blob(){if(o.ignoreUnknown)return e("[blob]");throw new Error(`Hashing Blob objects is currently not supported
Use "options.replacer" or "options.ignoreUnknown"
`)},domwindow(){return e("domwindow")},bigint(r){return e("bigint:"+r.toString())},process(){return e("process")},timer(){return e("timer")},pipe(){return e("pipe")},tcp(){return e("tcp")},udp(){return e("udp")},tty(){return e("tty")},statwatcher(){return e("statwatcher")},securecontext(){return e("securecontext")},connection(){return e("connection")},zlib(){return e("zlib")},context(){return e("context")},nodescript(){return e("nodescript")},httpparser(){return e("httpparser")},dataview(){return e("dataview")},signal(){return e("signal")},fsevent(){return e("fsevent")},tlswrap(){return e("tlswrap")}}}const oe="[native code] }",Me=oe.length;function ie(o){return typeof o!="function"?!1:Function.prototype.toString.call(o).slice(-Me)===oe}class L{constructor(t,n){t=this.words=t||[],this.sigBytes=n===void 0?t.length*4:n}toString(t){return(t||De).stringify(this)}concat(t){if(this.clamp(),this.sigBytes%4)for(let n=0;n<t.sigBytes;n++){const e=t.words[n>>>2]>>>24-n%4*8&255;this.words[this.sigBytes+n>>>2]|=e<<24-(this.sigBytes+n)%4*8}else for(let n=0;n<t.sigBytes;n+=4)this.words[this.sigBytes+n>>>2]=t.words[n>>>2];return this.sigBytes+=t.sigBytes,this}clamp(){this.words[this.sigBytes>>>2]&=4294967295<<32-this.sigBytes%4*8,this.words.length=Math.ceil(this.sigBytes/4)}clone(){return new L([...this.words])}}const De={stringify(o){const t=[];for(let n=0;n<o.sigBytes;n++){const e=o.words[n>>>2]>>>24-n%4*8&255;t.push((e>>>4).toString(16),(e&15).toString(16))}return t.join("")}},Ue={stringify(o){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=[];for(let e=0;e<o.sigBytes;e+=3){const r=o.words[e>>>2]>>>24-e%4*8&255,a=o.words[e+1>>>2]>>>24-(e+1)%4*8&255,l=o.words[e+2>>>2]>>>24-(e+2)%4*8&255,h=r<<16|a<<8|l;for(let i=0;i<4&&e*8+i*6<o.sigBytes*8;i++)n.push(t.charAt(h>>>6*(3-i)&63))}return n.join("")}},Oe={parse(o){const t=o.length,n=[];for(let e=0;e<t;e++)n[e>>>2]|=(o.charCodeAt(e)&255)<<24-e%4*8;return new L(n,t)}},Ke={parse(o){return Oe.parse(unescape(encodeURIComponent(o)))}};class Ne{constructor(){this._data=new L,this._nDataBytes=0,this._minBufferSize=0,this.blockSize=512/32}reset(){this._data=new L,this._nDataBytes=0}_append(t){typeof t=="string"&&(t=Ke.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes}_doProcessBlock(t,n){}_process(t){let n,e=this._data.sigBytes/(this.blockSize*4);t?e=Math.ceil(e):e=Math.max((e|0)-this._minBufferSize,0);const r=e*this.blockSize,a=Math.min(r*4,this._data.sigBytes);if(r){for(let l=0;l<r;l+=this.blockSize)this._doProcessBlock(this._data.words,l);n=this._data.words.splice(0,r),this._data.sigBytes-=a}return new L(n,a)}}class qe extends Ne{update(t){return this._append(t),this._process(),this}finalize(t){t&&this._append(t)}}const se=[1779033703,-1150833019,1013904242,-1521486534,1359893119,-1694144372,528734635,1541459225],Ve=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998],F=[];class Ge extends qe{constructor(){super(...arguments),this._hash=new L([...se])}reset(){super.reset(),this._hash=new L([...se])}_doProcessBlock(t,n){const e=this._hash.words;let r=e[0],a=e[1],l=e[2],h=e[3],i=e[4],u=e[5],d=e[6],g=e[7];for(let c=0;c<64;c++){if(c<16)F[c]=t[n+c]|0;else{const v=F[c-15],w=(v<<25|v>>>7)^(v<<14|v>>>18)^v>>>3,_=F[c-2],j=(_<<15|_>>>17)^(_<<13|_>>>19)^_>>>10;F[c]=w+F[c-7]+j+F[c-16]}const x=i&u^~i&d,y=r&a^r&l^a&l,$=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),E=(i<<26|i>>>6)^(i<<21|i>>>11)^(i<<7|i>>>25),z=g+E+x+Ve[c]+F[c],k=$+y;g=d,d=u,u=i,i=h+z|0,h=l,l=a,a=r,r=z+k|0}e[0]=e[0]+r|0,e[1]=e[1]+a|0,e[2]=e[2]+l|0,e[3]=e[3]+h|0,e[4]=e[4]+i|0,e[5]=e[5]+u|0,e[6]=e[6]+d|0,e[7]=e[7]+g|0}finalize(t){super.finalize(t);const n=this._nDataBytes*8,e=this._data.sigBytes*8;return this._data.words[e>>>5]|=128<<24-e%32,this._data.words[(e+64>>>9<<4)+14]=Math.floor(n/4294967296),this._data.words[(e+64>>>9<<4)+15]=n,this._data.sigBytes=this._data.words.length*4,this._process(),this._hash}}function He(o){return new Ge().finalize(o).toString(Ue)}function We(o,t={}){const n=typeof o=="string"?o:Ie(o,t);return He(n).slice(0,10)}function Je(...o){return`${Se}${We([...o])}`}let B;async function Ye({accept:o="*",multiple:t=!0}={}){return B=document.createElement("input"),B.type="file",B.classList.add("sr-only"),B.value=null,B.accept=o,B.multiple=t,B.click(),new Promise(n=>{B.addEventListener("change",e=>{n([...e.target.files]),B.remove()})})}async function Xe(o,{maxSize:t}={}){if(!t)return o;const n=await Qe(o);return await Ze(n,o.type,t)}async function Qe(o){const t=new Image,n=URL.createObjectURL(o);return t.src=n,await new Promise((e,r)=>{t.onload=()=>{e(t)},t.onerror=()=>{URL.revokeObjectURL(n),r(new Error("Failed to load the image"))}}),URL.revokeObjectURL(n),t}async function Ze(o,t,n){const e=document.createElement("canvas"),r=e.getContext("2d");let a=1;n&&(o.width>n||o.height>n)&&(a=n/Math.max(o.width,o.height)),e.width=o.width*a,e.height=o.height*a,r.drawImage(o,0,0,e.width,e.height);const l=await new Promise(h=>{e.toBlob(h,t)});if(!l)throw new Error("Failed to convert canvas to Blob");return l}function et(o,t,n,e,r,a,l,h){var i=typeof o=="function"?o.options:o;return t&&(i.render=t,i.staticRenderFns=n,i._compiled=!0),{exports:o,options:i}}const ae={...ge},tt=Object.assign({inheritAttrs:!1},{__name:"Copilot",props:ae,setup(o){const t=o,n=I(),e=K(),r=he(),{openLicenseModal:a,assertActivationIntegrity:l}=_e({label:"Kirby Copilot",apiNamespace:"__copilot__"}),h=/^<(\w+)>\s*<\/\1>$/,i=m(),u=m(),d=m(),g=m(),c=m(),x=m(),y=m(),$=m(),E=m(),z=m(),k=m(),v=m(!1),w=m(!1),_=m(!1),j=m(),M=m(),b=m(),G=m([]),O=m([]),le=m();let A,R;const H=Y(()=>r.getters["content/values"]()),ce=Y(()=>!w.value&&b.value!==void 0);Z(M,f=>{v.value&&c.value&&(f&&f!==d.value?localStorage.setItem(`${A}$prompt`,f):(!f||f===d.value)&&localStorage.removeItem(`${A}$prompt`))}),Z(_,f=>{v.value&&c.value&&(f?localStorage.setItem(`${A}$open`,"true"):localStorage.removeItem(`${A}$open`))}),(async()=>{const{load:f}=fe(),p=await f({parent:t.parent,name:t.name});if(i.value=ue(p.label)||n.t("johannschopplich.copilot.label"),u.value=p.field??void 0,d.value=p.userPrompt??void 0,g.value=p.systemPrompt||p.config.systemPrompt||void 0,c.value=p.storage,p.editable===!0&&G.value.push("edit"),p.files===!0&&G.value.push("files"),x.value=p.size,y.value=ke.indexOf(p.config.logLevel??p.logLevel),$.value=p.supported,E.value=p.config,k.value=p.license,Pe(p.assets),p.files==="auto"&&p.modelFile){z.value=p.modelFile;const{mime:C,url:S}=p.modelFile;q.includes(C)&&fetch(S).then(D=>D.blob()).then(D=>{O.value=[D]})}c.value&&(A=Je(n.view.path,u.value),M.value=localStorage.getItem(`${A}$prompt`)||d.value||"",_.value=localStorage.getItem(`${A}$open`)==="true",X(()=>{j.value&&_.value&&(j.value.open=!0)})),n.events.on("view.save",J),v.value=!0,l({component:le,licenseStatus:k.value})})(),me(()=>{n.events.off("view.save",J)});function ue(f){return!f||typeof f=="string"?f:f[n.translation.code]??Object.values(f)[0]}async function st(){if(!M.value){n.notification.error(n.t("johannschopplich.copilot.prompt.empty"));return}n.isLoading=!0,w.value=!0,b.value=H.value[u.value],R=new AbortController;let f="",p=Date.now(),C=E.value;try{const{textStream:S}=await je({userPrompt:M.value,systemPrompt:g.value,context:de(),files:O.value,config:C,logLevel:y.value,abortSignal:R.signal});for await(const D of S)if(f+=D,Array.isArray(b.value)){if(Date.now()-p<E.value.blocksUpdateThrottle)continue;p=Date.now();const pe=await W(f);pe.length>0&&r.dispatch("content/update",[u.value,[...b.value,...pe]])}else r.dispatch("content/update",[u.value,b.value+f])}catch(S){if(R=void 0,n.isLoading=!1,w.value=!1,S instanceof Error&&S.name==="AbortError")return;if(S instanceof Error&&S.name==="ApiCallError"){console.error(S),n.notification.error(S.message);return}console.error(S),n.notification.error(n.t("johannschopplich.copilot.generator.error"));return}r.dispatch("content/update",[u.value,Array.isArray(b.value)?[...b.value,...await W(f)]:b.value+f]),R=void 0,n.isLoading=!1,w.value=!1,n.notification.success({icon:"sparkling",message:n.t("johannschopplich.copilot.generator.success")})}function at(){R==null||R.abort()}function lt(){r.dispatch("content/update",[u.value,b.value]),b.value=void 0}async function ct(){const f=await Ye({accept:[...q,"application/pdf"].join(",")});O.value=await Promise.all(f.map(async p=>p.type.startsWith("image/")?Xe(p,{maxSize:2048}):p))}async function W(f){if(!f)return[];const{blocks:p}=await e.post("__copilot__/html2blocks",{html:f});return p.length===1&&"text"in p[0].content&&h.test(p[0].content.text)?[]:p}function de(){const f={...H.value,title:n.view.title};return Object.fromEntries(Object.entries(f).map(([p,C])=>[p,Array.isArray(C)||typeof C=="object"&&C!==null?JSON.stringify(C):C]))}function J(){ce.value&&(b.value=void 0)}async function ut(){const{isRegistered:f}=await a();f&&(k.value="active")}return{__sfc:!0,propsDefinition:ae,props:t,panel:n,api:e,store:r,openLicenseModal:a,assertActivationIntegrity:l,EMPTY_HTML_TAG_RE:h,label:i,field:u,userPrompt:d,systemPrompt:g,storage:c,size:x,logLevel:y,supported:$,config:E,modelFile:z,license:k,isInitialized:v,isGenerating:w,isDetailsOpen:_,detailsElement:j,currentPrompt:M,currentFieldContent:b,allow:G,files:O,licenseButtonGroup:le,storageKey:A,abortController:R,currentContent:H,canUndo:ce,t:ue,generate:st,abort:at,undo:lt,pickFiles:ct,htmlToBlocks:W,createContext:de,onModelSave:J,handleRegistration:ut,SUPPORTED_PROVIDERS:xe,SUPPORTED_VISION_MIME_TYPES:q}}});var nt=function(){var r,a,l,h;var t=this,n=t._self._c,e=t._self._setupProxy;return e.isInitialized?n("k-section",{attrs:{label:e.label}},[e.license!=="active"?n("k-button-group",{ref:"licenseButtonGroup",attrs:{slot:"options",layout:"collapsed"},slot:"options"},[n("k-button",{attrs:{theme:"love",variant:"filled",size:"xs",link:"https://kirbycopilot.com/buy",target:"_blank",text:e.panel.t("johannschopplich.copilot.license.buy")}}),n("k-button",{attrs:{theme:"love",variant:"filled",size:"xs",icon:"key",text:e.panel.t("johannschopplich.copilot.license.activate")},on:{click:function(i){return e.handleRegistration()}}})],1):t._e(),!e.config.provider||!e.SUPPORTED_PROVIDERS.includes(e.config.provider)?n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" Unsupported provider "),n("code",[t._v(t._s(e.config.provider))]),t._v(" in the "),n("code",[t._v("johannschopplich.copilot.provider")]),t._v(" global configuration. ")])],1):(a=(r=e.config.providers)==null?void 0:r[e.config.provider])!=null&&a.apiKey?(h=(l=e.config.providers)==null?void 0:l[e.config.provider])!=null&&h.model?e.field?e.field in e.currentContent?e.supported?!e.allow.includes("edit")&&!e.userPrompt?n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" If the user prompt cannot be edited by the user, a default "),n("code",[t._v("userPrompt")]),t._v(" has to be set in the section configuration. ")])],1):n("div",{staticClass:"kai-space-y-4"},[n("k-button-group",{attrs:{layout:"collapsed"}},[n("k-button",{attrs:{icon:e.isGenerating?"loader":"sparkling",text:e.panel.t("johannschopplich.copilot.generate"),variant:"filled",size:e.size,theme:"positive",disabled:e.isGenerating},on:{click:function(i){return e.generate()}}}),e.isGenerating?n("k-button",{attrs:{icon:"cancel",text:e.panel.t("johannschopplich.copilot.stop"),variant:"filled",size:e.size,theme:"notice"},on:{click:function(i){return e.abort()}}}):t._e(),e.canUndo?n("k-button",{attrs:{icon:"undo",text:e.panel.t("johannschopplich.copilot.undo"),variant:"filled",size:e.size},on:{click:function(i){return e.undo()}}}):t._e()],1),e.allow.length>0?n("details",{ref:"detailsElement",on:{toggle:function(i){e.isDetailsOpen=i.target.open}}},[n("summary",[t._v(" "+t._s([...e.allow.includes("edit")?[e.panel.t("johannschopplich.copilot.prompt.label")]:[],...e.allow.includes("files")?[e.panel.t("johannschopplich.copilot.context")]:[]].join(", "))+" ")]),n("div",{staticClass:"kai-mt-3"},[e.allow.includes("edit")?n("div",{staticClass:"kai-mb-2 kai-text-right"},[n("k-input",{key:e.isDetailsOpen?1:0,staticClass:"kai-mb-1",attrs:{placeholder:e.panel.t("johannschopplich.copilot.prompt.placeholder"),type:"textarea",buttons:!1,counter:!1},model:{value:e.currentPrompt,callback:function(i){e.currentPrompt=i},expression:"currentPrompt"}}),n("k-button",{directives:[{name:"show",rawName:"v-show",value:e.userPrompt&&e.currentPrompt!==e.userPrompt,expression:"userPrompt && currentPrompt !== userPrompt"}],attrs:{icon:"undo",text:"Reset",size:"xs",variant:"dimmed"},on:{click:function(i){e.currentPrompt=e.userPrompt}}})],1):t._e(),e.allow.includes("files")?n("k-button-group",{attrs:{layout:"collapsed"}},[n("k-button",{attrs:{icon:"upload",text:e.panel.t("johannschopplich.copilot.files.select"),variant:"filled",size:"sm"},on:{click:function(i){return e.pickFiles()}}}),e.files.length>0?n("k-button",{attrs:{icon:"cancel",text:e.panel.t("johannschopplich.copilot.remove"),variant:"filled",size:"sm"},on:{click:function(i){e.files=[]}}}):t._e()],1):e.modelFile?n("k-box",{attrs:{theme:"none"}},[n("k-text",[t._v(" "+t._s(e.panel.t(`johannschopplich.copilot.context.file.${e.SUPPORTED_VISION_MIME_TYPES.includes(e.modelFile.mime)?"model":"unsupported"}`))+" ")])],1):t._e()],1)]):t._e()],1):n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" The "),n("code",[t._v(t._s(e.field))]),t._v(" field is not supported. Use a "),n("code",[t._v("blocks")]),t._v(", "),n("code",[t._v("text")]),t._v(", "),n("code",[t._v("textarea")]),t._v(" or "),n("code",[t._v("textarea")]),t._v(" type. ")])],1):n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" The "),n("code",[t._v(t._s(e.field))]),t._v(" field does not exist in the current model. ")])],1):n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" Missing "),n("code",[t._v("field")]),t._v(" property in the section configuration. It is required for the generated text. ")])],1):n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" Missing "),n("code",[t._v("model")]),t._v(" property in the "),n("code",[t._v(t._s(`johannschopplich.copilot.providers.${e.config.provider}`))]),t._v(" global configuration. ")])],1):n("k-box",{attrs:{theme:"empty"}},[n("k-text",[t._v(" Missing "),n("code",[t._v("apiKey")]),t._v(" property in the "),n("code",[t._v(t._s(`johannschopplich.copilot.providers.${e.config.provider}`))]),t._v(" global configuration. ")])],1)],1):t._e()},rt=[],ot=et(tt,nt,rt);const it=ot.exports;window.panel.plugin("johannschopplich/copilot",{sections:{copilot:it}})})();