@qwanyx/stack 0.2.109 → 0.2.110
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/LLMClient.d.ts +10 -0
- package/dist/index.cjs.js +3 -3
- package/dist/index.esm.js +22 -6
- package/package.json +1 -1
|
@@ -77,6 +77,16 @@ export declare class LLMClient {
|
|
|
77
77
|
tts(text: string, options?: {
|
|
78
78
|
voice?: TTSVoice;
|
|
79
79
|
}): Promise<string>;
|
|
80
|
+
/**
|
|
81
|
+
* Generate an image from a text prompt
|
|
82
|
+
* @param prompt - Text description of the image to generate
|
|
83
|
+
* @param options - Generation options
|
|
84
|
+
* @returns Base64 encoded PNG image data
|
|
85
|
+
*/
|
|
86
|
+
generateImage(prompt: string, options?: {
|
|
87
|
+
size?: '1024x1024' | '1536x1024' | '1024x1536' | 'auto';
|
|
88
|
+
quality?: 'low' | 'medium' | 'high' | 'auto';
|
|
89
|
+
}): Promise<string>;
|
|
80
90
|
/**
|
|
81
91
|
* Transcribe audio to text
|
|
82
92
|
*/
|
package/dist/index.cjs.js
CHANGED
|
@@ -25,7 +25,7 @@ ${s}
|
|
|
25
25
|
`&&(e=" "),(e.charCodeAt(0)>=33||[" "," "].includes(e))&&(this.node.value+=e),this.escaped=!1}}const Zd=50;function Dn(r,e){e=e||{};let t=e._depth||0;if(t>Zd)return[];let s=new Xd(r).tokenize(),i=[],o=[],l=[];if(s.forEach(a=>{a.type==="operator"&&(a.value===","||a.value===";")?(o.length&&i.push(o),o=[]):o.push(a)}),o.length&&i.push(o),i.forEach(a=>{a=Jd(a,t),a.length&&(l=l.concat(a))}),e.flatten){let a=[],u=c=>{c.forEach(d=>{if(d.group)return u(d.group);a.push(d)})};return u(l),a}return l}function ef(r){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(r),s=n.byteLength,i=s%3,o=s-i,l,a,u,c,d,f=0;f<o;f=f+3)d=n[f]<<16|n[f+1]<<8|n[f+2],l=(d&16515072)>>18,a=(d&258048)>>12,u=(d&4032)>>6,c=d&63,e+=t[l]+t[a]+t[u]+t[c];return i==1?(d=n[o],l=(d&252)>>2,a=(d&3)<<4,e+=t[l]+t[a]+"=="):i==2&&(d=n[o]<<8|n[o+1],l=(d&64512)>>10,a=(d&1008)>>4,u=(d&15)<<2,e+=t[l]+t[a]+t[u]+"="),e}const tf=256,rf=2*1024*1024;class Ds{static parse(e,t){return new Ds(t).parse(e)}constructor(e){this.options=e||{},this.mimeOptions={maxNestingDepth:this.options.maxNestingDepth||tf,maxHeadersSize:this.options.maxHeadersSize||rf},this.root=this.currentNode=new va({postalMime:this,...this.mimeOptions}),this.boundaries=[],this.textContent={},this.attachments=[],this.attachmentEncoding=(this.options.attachmentEncoding||"").toString().replace(/[-_\s]/g,"").trim().toLowerCase()||"arraybuffer",this.started=!1}async finalize(){await this.root.finalize()}async processLine(e,t){let n=this.boundaries;if(n.length&&e.length>2&&e[0]===45&&e[1]===45)for(let s=n.length-1;s>=0;s--){let i=n[s];if(e.length!==i.value.length+2&&e.length!==i.value.length+4)continue;let o=e.length===i.value.length+4;if(o&&(e[e.length-2]!==45||e[e.length-1]!==45))continue;let l=!0;for(let a=0;a<i.value.length;a++)if(e[a+2]!==i.value[a]){l=!1;break}if(l)return o?(await i.node.finalize(),this.currentNode=i.node.parentNode||this.root):(await i.node.finalizeChildNodes(),this.currentNode=new va({postalMime:this,parentNode:i.node,...this.mimeOptions})),t?this.finalize():void 0}if(this.currentNode.feed(e),t)return this.finalize()}readLine(){let e=this.readPos,t=this.readPos,n=()=>({bytes:new Uint8Array(this.buf,e,t-e),done:this.readPos>=this.av.length});for(;this.readPos<this.av.length;){const s=this.av[this.readPos++];if(s!==13&&s!==10&&(t=this.readPos),s===10)return n()}return n()}async processNodeTree(){let e={},t=new Set,n=this.textMap=new Map,s=this.forceRfc822Attachments(),i=async(o,l,a)=>{if(l=l||!1,a=a||!1,o.contentType.multipart)o.contentType.multipart==="alternative"?l=o:o.contentType.multipart==="related"&&(a=o);else if(this.isInlineMessageRfc822(o)&&!s){const u=new Ds;o.subMessage=await u.parse(o.content),n.has(o)||n.set(o,{});let c=n.get(o);(o.subMessage.text||!o.subMessage.html)&&(c.plain=c.plain||[],c.plain.push({type:"subMessage",value:o.subMessage}),t.add("plain")),o.subMessage.html&&(c.html=c.html||[],c.html.push({type:"subMessage",value:o.subMessage}),t.add("html")),u.textMap&&u.textMap.forEach((d,f)=>{n.set(f,d)});for(let d of o.subMessage.attachments||[])this.attachments.push(d)}else if(this.isInlineTextNode(o)){let u=o.contentType.parsed.value.substr(o.contentType.parsed.value.indexOf("/")+1),c=l||o;n.has(c)||n.set(c,{});let d=n.get(c);d[u]=d[u]||[],d[u].push({type:"text",value:o.getTextContent()}),t.add(u)}else if(o.content){const u=o.contentDisposition.parsed.params.filename||o.contentType.parsed.params.name||null,c={filename:u?En(u):null,mimeType:o.contentType.parsed.value,disposition:o.contentDisposition.parsed.value||null};switch(a&&o.contentId&&(c.related=!0),o.contentDescription&&(c.description=o.contentDescription),o.contentId&&(c.contentId=o.contentId),o.contentType.parsed.value){case"text/calendar":case"application/ics":{o.contentType.parsed.params.method&&(c.method=o.contentType.parsed.params.method.toString().toUpperCase().trim());const d=o.getTextContent().replace(/\r?\n/g,`
|
|
26
26
|
`).replace(/\n*$/,`
|
|
27
27
|
`);c.content=Xr.encode(d);break}default:c.content=o.content}this.attachments.push(c)}for(let u of o.childNodes)await i(u,l,a)};await i(this.root,!1,[]),n.forEach(o=>{t.forEach(l=>{if(e[l]||(e[l]=[]),o[l])o[l].forEach(a=>{switch(a.type){case"text":e[l].push(a.value);break;case"subMessage":switch(l){case"html":e[l].push(Ca(a.value));break;case"plain":e[l].push(wa(a.value));break}break}});else{let a;switch(l){case"html":a="plain";break;case"plain":a="html";break}(o[a]||[]).forEach(u=>{switch(u.type){case"text":switch(l){case"html":e[l].push(Kd(u.value));break;case"plain":e[l].push(Yd(u.value));break}break;case"subMessage":switch(l){case"html":e[l].push(Ca(u.value));break;case"plain":e[l].push(wa(u.value));break}break}})}})}),Object.keys(e).forEach(o=>{e[o]=e[o].join(`
|
|
28
|
-
`)}),this.textContent=e}isInlineTextNode(e){if(e.contentDisposition.parsed.value==="attachment")return!1;switch(e.contentType.parsed.value){case"text/html":case"text/plain":return!0;case"text/calendar":case"text/csv":default:return!1}}isInlineMessageRfc822(e){return e.contentType.parsed.value!=="message/rfc822"?!1:(e.contentDisposition.parsed.value||(this.options.rfc822Attachments?"attachment":"inline"))==="inline"}forceRfc822Attachments(){if(this.options.forceRfc822Attachments)return!0;let e=!1,t=n=>{n.contentType.multipart||["message/delivery-status","message/feedback-report"].includes(n.contentType.parsed.value)&&(e=!0);for(let s of n.childNodes)t(s)};return t(this.root),e}async resolveStream(e){let t=0,n=[];const s=e.getReader();for(;;){const{done:l,value:a}=await s.read();if(l)break;n.push(a),t+=a.length}const i=new Uint8Array(t);let o=0;for(let l of n)i.set(l,o),o+=l.length;return i}async parse(e){var s,i;if(this.started)throw new Error("Can not reuse parser, create a new PostalMime object");for(this.started=!0,e&&typeof e.getReader=="function"&&(e=await this.resolveStream(e)),e=e||new ArrayBuffer(0),typeof e=="string"&&(e=Xr.encode(e)),(e instanceof Blob||Object.prototype.toString.call(e)==="[object Blob]")&&(e=await ni(e)),e.buffer instanceof ArrayBuffer&&(e=new Uint8Array(e).buffer),this.buf=e,this.av=new Uint8Array(e),this.readPos=0;this.readPos<this.av.length;){const o=this.readLine();await this.processLine(o.bytes,o.done)}await this.processNodeTree();const t={headers:this.root.headers.map(o=>({key:o.key,value:o.value})).reverse()};for(const o of["from","sender"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=Dn(l.value);a&&a.length&&(t[o]=a[0])}}for(const o of["delivered-to","return-path"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=Dn(l.value);if(a&&a.length&&a[0].address){const u=o.replace(/\-(.)/g,(c,d)=>d.toUpperCase());t[u]=a[0].address}}}for(const o of["to","cc","bcc","reply-to"]){const l=this.root.headers.filter(u=>u.key===o);let a=[];if(l.filter(u=>u&&u.value).map(u=>Dn(u.value)).forEach(u=>a=a.concat(u||[])),a&&a.length){const u=o.replace(/\-(.)/g,(c,d)=>d.toUpperCase());t[u]=a}}for(const o of["subject","message-id","in-reply-to","references"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=o.replace(/\-(.)/g,(u,c)=>c.toUpperCase());t[a]=En(l.value)}}let n=this.root.headers.find(o=>o.key==="date");if(n){let o=new Date(n.value);!o||o.toString()==="Invalid Date"?o=n.value:o=o.toISOString(),t.date=o}switch((s=this.textContent)!=null&&s.html&&(t.html=this.textContent.html),(i=this.textContent)!=null&&i.plain&&(t.text=this.textContent.plain),t.attachments=this.attachments,this.attachmentEncoding){case"arraybuffer":break;case"base64":for(let l of t.attachments||[])l!=null&&l.content&&(l.content=ef(l.content),l.encoding="base64");break;case"utf8":let o=new TextDecoder("utf8");for(let l of t.attachments||[])l!=null&&l.content&&(l.content=o.decode(l.content),l.encoding="utf8");break;default:throw new Error("Unknwon attachment encoding")}return t}}class iu{constructor(e){_t(this,"config");if(!e.system_id)throw new Error("MailClient: system_id is REQUIRED");this.config=e}async callCoprocessor(e,t,n={}){const s={coprocessor:e,method:t,system_id:this.config.system_id,params:{user_id:this.config.system_id,...n}};try{const i=await fetch(`${this.config.baseUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.getToken()}`},body:JSON.stringify(s)});if(!i.ok){const l=await i.text();throw new Error(`API error (${i.status}): ${l}`)}const o=await i.json();if(!o.success&&o.error)throw new Error(o.error);return o.result}catch(i){throw console.error("API call failed:",i),i}}async callMail(e,t={}){return this.callCoprocessor("mail",e,t)}async callEmail(e,t={}){return this.callCoprocessor("email",e,t)}getToken(){return typeof window<"u"&&window.localStorage&&localStorage.getItem("qwanyx_token")||""}async getSettings(){try{return await this.callMail("get_email_settings")||{accounts:[]}}catch{return{accounts:[]}}}async saveSettings(e){await this.callMail("save_email_settings",{accounts:e})}async listEmails(e,t=150,n){return this.callMail("list_emails",{account_id:e,limit:t,folder:n})}async deleteEmails(e,t,n=!0){return this.callMail("delete_emails",{account_id:e,uids:t,expunge:n})}async imapExec(e,t){return this.callMail("imap_exec",{account_id:e,commands:t})}async trashEmails(e,t,n="INBOX"){const s=["[Gmail]/Trash","[Gmail]/Corbeille","[Gmail]/Bin","Trash"];for(const i of s){const o=[`SELECT "${n}"`,...t.map(u=>`UID MOVE ${u} "${i}"`)],a=(await this.imapExec(e,o)).responses.filter(u=>u.ok&&u.command==="UID MOVE").length;if(a>0)return{success:!0,moved:a}}return{success:!1,moved:0}}async archiveEmails(e,t,n="INBOX"){const s=[`SELECT "${n}"`,...t.map(l=>`UID STORE ${l} +FLAGS (\\Deleted)`),"EXPUNGE"],o=(await this.imapExec(e,s)).responses.filter(l=>l.ok&&l.command==="UID STORE").length;return{success:o>0,archived:o}}async listFolders(e){const n=(await this.imapExec(e,['LIST "" *'])).responses.find(s=>s.command==="LIST");return n!=null&&n.ok&&n.folders?{success:!0,folders:n.folders}:{success:!1,folders:[]}}async listEmailsSorted(e,t="INBOX",n=150){const s=await this.imapExec(e,[`SELECT ${t}`,"FETCH 1:* (UID INTERNALDATE)"]),i=s.responses.find(p=>p.command==="SELECT");if(!(i!=null&&i.ok))throw new Error(`Failed to select folder: ${(i==null?void 0:i.error)||"Unknown error"}`);const o=s.responses.find(p=>p.command==="FETCH");if(!(o!=null&&o.ok)||!o.messages)return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:[]};const a=[...o.messages].sort((p,g)=>{const m=p.internalDate?new Date(p.internalDate).getTime():0;return(g.internalDate?new Date(g.internalDate).getTime():0)-m}).slice(0,n).map(p=>p.uid).filter(Boolean);if(a.length===0)return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:[]};const c=(await this.imapExec(e,[`SELECT ${t}`,`UID FETCH ${a.join(",")} (UID FLAGS ENVELOPE)`])).responses.find(p=>p.command==="UID FETCH");if(!(c!=null&&c.ok)||!c.messages)throw new Error(`Failed to fetch details: ${(c==null?void 0:c.error)||"Unknown error"}`);const d=new Map;for(const p of c.messages)p.uid&&d.set(p.uid,p);const f=a.map(p=>{var w,S,D,k,C;const g=d.get(p);if(!g)return null;const m=((w=g.flags)==null?void 0:w.some(E=>E.includes("Seen")))||!1,x=((D=(S=g.envelope)==null?void 0:S.from)==null?void 0:D.email)||"Unknown",_=((k=g.envelope)==null?void 0:k.subject)||"(No subject)",b=((C=g.envelope)==null?void 0:C.date)||"";return{uid:p,from:x,subject:_,date:b,seen:m}}).filter(Boolean);return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:f}}async getEmail(e,t,n="INBOX"){return this.callMail("get_email",{account_id:e,uid:t,folder:n})}async getAttachment(e,t,n,s="INBOX"){return this.callMail("get_attachment",{account_id:e,uid:t,attachment_index:typeof n=="number"?n:void 0,attachment_id:typeof n=="string"?n:void 0,folder:s})}async searchContactEmails(e,t,n=50){return this.callMail("search_contact_emails",{account_id:e,contact_email:t,limit:n})}async getEmailParsed(e,t,n="INBOX"){var g,m,x,_,b,w;const i=(await this.imapExec(e,[`SELECT "${n}"`,`UID FETCH ${t} (FLAGS BODY[])`])).responses.find(S=>S.command==="UID FETCH");if(!(i!=null&&i.ok)||!((g=i.messages)!=null&&g[0]))return console.error("Failed to fetch raw email:",i==null?void 0:i.error),null;const o=i.messages[0],l=o.body||o.raw;if(!l)return console.error("No raw email content in response"),null;const u=await new Ds().parse(l);console.log("[MailClient] Parsed email - attachments count:",((m=u.attachments)==null?void 0:m.length)||0),console.log("[MailClient] Parsed attachments:",(x=u.attachments)==null?void 0:x.map(S=>({filename:S.filename,mimeType:S.mimeType,contentId:S.contentId})));const c=new Map;for(const S of u.attachments||[])if(S.contentId){const D=this.contentToBase64(S.content),k=`data:${S.mimeType};base64,${D}`,C=S.contentId.replace(/^<|>$/g,"");c.set(C,k),c.set(`<${C}>`,k)}let d=u.html||"";d&&c.size>0&&(d=d.replace(/src=["']cid:([^"']+)["']/gi,(S,D)=>{const k=c.get(D)||c.get(`<${D}>`);return k?`src="${k}"`:S}));const f=((_=o.flags)==null?void 0:_.some(S=>S.toLowerCase().includes("seen")))||!1,p=((b=u.from)==null?void 0:b.address)||((w=u.from)==null?void 0:w.name)||"Unknown";return{uid:t,from:p,subject:u.subject||"(No subject)",date:u.date||"",body:d||u.text||"",html:d,text:u.text||"",seen:f,attachments:(u.attachments||[]).map(S=>({filename:S.filename||"attachment",mimeType:S.mimeType||"application/octet-stream",size:this.getContentSize(S.content)}))}}async findEmailInAllMail(e,t){var i,o;const n=await this.getSettings(),s=((i=n.accounts)==null?void 0:i.find(l=>l.id===e))||((o=n.accounts)==null?void 0:o[0]);if(!(s!=null&&s.imap))return console.error("[MailClient] No IMAP configuration found for account"),{found:!1};try{return await this.callEmail("findEmailInAllMail",{message_id:t.message_id,from:t.from,subject:t.subject,folder:t.folder,imap_config:{host:s.imap.host,port:parseInt(s.imap.port,10)||993,username:s.imap.user,password:s.imap.password}})}catch(l){return console.error("[MailClient] findEmailInAllMail failed:",l),{found:!1}}}contentToBase64(e){if(typeof e=="string")try{return btoa(e)}catch{return e}const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++)n+=String.fromCharCode(t[s]);return btoa(n)}getContentSize(e){return e?typeof e=="string"?e.length:(e instanceof Uint8Array,e.byteLength):0}async sendMail(e){const t={to:e.to,subject:e.subject,body:e.body};return e.html&&(t.html=e.html),e.from&&(t.from=e.from),e.smtpConfig&&(t.smtp_config=e.smtpConfig),this.callEmail("send",t)}async sendEmail(e,t){var n,s;try{const i=await this.getSettings(),o=((n=i.accounts)==null?void 0:n.find(u=>u.id===e))||((s=i.accounts)==null?void 0:s[0]);if(!(o!=null&&o.smtp))return{success:!1,error:"No SMTP configuration found for account"};const l={to:Array.isArray(t.to)?t.to:[t.to],subject:t.subject,body:t.text||"",html:t.html,from:o.email,smtp_config:{host:o.smtp.host,port:parseInt(o.smtp.port,10)||587,username:o.smtp.user,password:o.smtp.password}};t.cc&&(l.cc=Array.isArray(t.cc)?t.cc:[t.cc]),t.bcc&&(l.bcc=Array.isArray(t.bcc)?t.bcc:[t.bcc]),t.in_reply_to&&(l.in_reply_to=t.in_reply_to),t.attachments&&t.attachments.length>0&&(l.attachments=t.attachments);const a=await this.callEmail("send",l);return{success:(a==null?void 0:a.sent)??!1,message_id:a==null?void 0:a.message_id,error:a==null?void 0:a.error}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async getGmailAuthUrl(e,t){return this.callMail("gmail_get_auth_url",{account_id:e||"gmail",redirect_uri:t||"https://api.qwanyx.com/oauth/gmail/callback"})}async isGmailConnected(e){var t;try{const s=(t=(await this.getSettings()).accounts)==null?void 0:t.find(i=>i.id===e);return(s==null?void 0:s.auth_type)==="gmail_api"&&!!(s!=null&&s.gmail_tokens)}catch{return!1}}async disconnectGmail(e){try{return await this.callMail("gmail_disconnect",{account_id:e}),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async gmailSearchMessage(e,t,n){try{const s=await this.callMail("gmail_search_message",{account_id:e,subject:t,from:n});return(s==null?void 0:s.found)===!1?null:s}catch(s){return console.error("[MailClient] gmailSearchMessage failed:",s),null}}async connectGmail(e){return new Promise(async t=>{try{const{auth_url:n}=await this.getGmailAuthUrl(e),s=600,i=700,o=window.screenX+(window.outerWidth-s)/2,l=window.screenY+(window.outerHeight-i)/2,a=window.open(n,"gmail_oauth",`width=${s},height=${i},left=${o},top=${l},scrollbars=yes`);if(!a){t({success:!1,error:"Popup blocked. Please allow popups for this site."});return}const u=d=>{var f,p;((f=d.data)==null?void 0:f.type)==="gmail_oauth_success"?(window.removeEventListener("message",u),t({success:!0,email:d.data.email})):((p=d.data)==null?void 0:p.type)==="gmail_oauth_error"&&(window.removeEventListener("message",u),t({success:!1,error:d.data.description||d.data.error}))};window.addEventListener("message",u);const c=setInterval(()=>{a.closed&&(clearInterval(c),window.removeEventListener("message",u),setTimeout(()=>{},500))},500)}catch(n){t({success:!1,error:n instanceof Error?n.message:String(n)})}})}}const ou=[{id:"marin",name:"Marin",description:"⭐ Féminin, naturel et fluide"},{id:"cedar",name:"Cedar",description:"⭐ Masculin, expressif et vivant"},{id:"coral",name:"Coral",description:"Féminin, chaleureux et doux"},{id:"alloy",name:"Alloy",description:"Neutre, polyvalent"},{id:"ash",name:"Ash",description:"Masculin, calme et posé"},{id:"ballad",name:"Ballad",description:"Neutre, expressif et narratif"},{id:"echo",name:"Echo",description:"Masculin, profond et résonant"},{id:"fable",name:"Fable",description:"Masculin, accent britannique"},{id:"onyx",name:"Onyx",description:"Masculin, grave et autoritaire"},{id:"nova",name:"Nova",description:"Féminin, dynamique et énergique"},{id:"sage",name:"Sage",description:"Neutre, calme et apaisant"},{id:"shimmer",name:"Shimmer",description:"Féminin, léger et aérien"},{id:"verse",name:"Verse",description:"Neutre, poétique et mélodieux"}];class nf{constructor(e){_t(this,"config");_t(this,"promptCache",{});if(!e.system_id)throw new Error("LLMClient: system_id is REQUIRED");this.config=e}async callLLM(e,t={}){const n={coprocessor:"llm",method:e,system_id:this.config.system_id,params:t};try{const s=await fetch(`${this.config.baseUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.getToken()}`},body:JSON.stringify(n)});if(!s.ok){const o=await s.text();throw new Error(`LLM API error (${s.status}): ${o}`)}const i=await s.json();if(!i.success&&i.error)throw new Error(i.error);return i}catch(s){throw console.error("LLM API call failed:",s),s}}getToken(){return typeof window<"u"&&window.localStorage&&localStorage.getItem("qwanyx_token")||""}async complete(e,t){var i;const n={model:(t==null?void 0:t.model)??"mlm",prompt:e,max_completion_tokens:(t==null?void 0:t.maxTokens)??2e3};t!=null&&t.systemPrompt&&(n.system=t.systemPrompt),(t==null?void 0:t.temperature)!==void 0&&(n.temperature=t.temperature);const s=await this.callLLM("complete",n);return((i=s.result)==null?void 0:i.text)||s.result||""}async chat(e,t){const n={model:(t==null?void 0:t.model)??"mlm",messages:e};(t==null?void 0:t.temperature)!==void 0&&(n.temperature=t.temperature),(t==null?void 0:t.maxTokens)!==void 0&&(n.max_completion_tokens=t.maxTokens);const i=(await this.callLLM("chat",n)).result;return typeof i=="string"?i:typeof(i==null?void 0:i.response)=="string"?i.response:typeof(i==null?void 0:i.text)=="string"?i.text:typeof(i==null?void 0:i.content)=="string"?i.content:typeof(i==null?void 0:i.message)=="string"?i.message:(console.warn("LLMClient.chat: unexpected result format",JSON.stringify(i,null,2)),"")}async chatJson(e,t,n){const s=[{role:"system",content:e},{role:"user",content:t}];let o=await this.chat(s,n);return typeof o=="string"&&(o=o.trim(),o.startsWith("```json")?o=o.slice(7):o.startsWith("```")&&(o=o.slice(3)),o.endsWith("```")&&(o=o.slice(0,-3)),o=o.trim()),JSON.parse(o)}async analyzeDocuments(e,t,n){var o;const s={prompt:e,files:t,model:(n==null?void 0:n.model)??"xlm"};return(n==null?void 0:n.temperature)!==void 0&&(s.temperature=n.temperature),(n==null?void 0:n.maxTokens)!==void 0&&(s.max_tokens=n.maxTokens),((o=(await this.callLLM("analyze",s)).result)==null?void 0:o.text)||""}async tts(e,t){var i;const n={model:"gpt-4o-mini-tts",voice:(t==null?void 0:t.voice)??"coral",input:e,response_format:"mp3"},s=await this.callLLM("tts",n);return((i=s.result)==null?void 0:i.audio)||s.result||""}async transcribe(e,t){var i;const n={audio_data:e};return t!=null&&t.filename&&(n.filename=t.filename),t!=null&&t.language&&(n.language=t.language),((i=(await this.callLLM("transcribe",n)).result)==null?void 0:i.text)||""}async getPrompt(e){var s;if(this.promptCache[e])return this.promptCache[e];const n=((s=(await this.callLLM("get_prompt",{name:e})).result)==null?void 0:s.content)||"";return this.promptCache[e]=n,n}clearPromptCache(){this.promptCache={}}buildPrompt(e,t){let n=e;for(const[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),i);return n}}const Ai="qwanyx_auth_token",Ti="qwanyx_refresh_token",Ni="qwanyx_auth_user";class Je{static setToken(e){typeof window<"u"&&localStorage.setItem(Ai,e)}static getToken(){return typeof window<"u"?localStorage.getItem(Ai):null}static clearToken(){typeof window<"u"&&(localStorage.removeItem(Ai),localStorage.removeItem(Ti))}static setRefreshToken(e){typeof window<"u"&&localStorage.setItem(Ti,e)}static getRefreshToken(){return typeof window<"u"?localStorage.getItem(Ti):null}static isAuthenticated(){return!!this.getToken()}static getAuthHeader(){const e=this.getToken();return e?{Authorization:`Bearer ${e}`}:{}}static setUser(e){typeof window<"u"&&localStorage.setItem(Ni,JSON.stringify(e))}static getUser(){if(typeof window<"u"){const e=localStorage.getItem(Ni);if(e)try{return JSON.parse(e)}catch{return null}}return null}static clearUser(){typeof window<"u"&&localStorage.removeItem(Ni)}static clearAll(){this.clearToken(),this.clearUser()}}class Ao{constructor(e){_t(this,"config");this.config=e}async register(e,t,n){var s,i;try{const o=n!=null&&n.tenantDomain?[n.tenantDomain]:[],l=(n==null?void 0:n.tenantDomain)||null,u=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"register",params:{email:e,password:t,...n,domains:o,primaryDomain:l,system_id:this.config.systemId}})})).json();return u.success&&((s=u.result)!=null&&s.success)?{success:!0,userId:u.result.user_id,email:u.result.email,requiresVerification:u.result.requiresVerification}:{success:!1,error:((i=u.result)==null?void 0:i.message)||u.error||"Registration failed"}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Network error"}}}async verifyEmail(e,t){var n,s,i,o;try{const a=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"verify_email",params:{email:e,code:t}})})).json();if(a.success&&((n=a.result)!=null&&n.token)){const{token:u,user:c}=a.result;return Je.setToken(u),Je.setUser(c),(i=(s=this.config).onLogin)==null||i.call(s,c),{success:!0,user:c,token:u}}else return{success:!1,error:((o=a.result)==null?void 0:o.error)||a.error||"Verification failed"}}catch(l){return{success:!1,error:l instanceof Error?l.message:"Network error"}}}async requestPasswordReset(e){var t,n;try{const i=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"request_password_reset",params:{email:e}})})).json();return i.success&&((t=i.result)!=null&&t.success)?{success:!0,message:i.result.message}:{success:!1,error:((n=i.result)==null?void 0:n.message)||i.error||"Request failed"}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Network error"}}}async setPasswordWithCode(e,t,n){var s,i,o,l;try{const u=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"set_password_with_code",params:{email:e,code:t,password:n}})})).json();if(u.success&&((s=u.result)!=null&&s.token)){const{token:c,user:d}=u.result;return Je.setToken(c),Je.setUser(d),(o=(i=this.config).onLogin)==null||o.call(i,d),{success:!0,user:d,token:c}}else return{success:!1,error:((l=u.result)==null?void 0:l.message)||u.error||"Password reset failed"}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Network error"}}}async login(e,t,n){var s,i,o,l,a,u,c;try{const f=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"login",params:{email:e,password:t,system_id:this.config.systemId,...n}})})).json();if((s=f.result)!=null&&s.requiresVerification||f.requiresVerification)return{success:!1,error:((i=f.result)==null?void 0:i.error)||f.error||"Please verify your email first",requiresVerification:!0};if(f.success&&((o=f.result)!=null&&o.token)){const{token:p,user:g}=f.result;return Je.setToken(p),Je.setUser(g),n!=null&&n.tenantDomain&&!((l=g.domains)!=null&&l.includes(n.tenantDomain))&&this.addDomainToUser(g._id||g.id,n.tenantDomain).catch(()=>{}),(u=(a=this.config).onLogin)==null||u.call(a,g),{success:!0,user:g,token:p}}else return{success:!1,error:((c=f.result)==null?void 0:c.error)||f.error||"Login failed"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Network error"}}}async resendVerificationCode(e){return this.requestPasswordReset(e)}logout(){var e,t;Je.clearAll(),(t=(e=this.config).onLogout)==null||t.call(e)}async checkRole(e,t){var n;try{const i=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:this.config.systemId||"system",coprocessor:"graph",method:"get_user_role",params:{group_id:e,target_user_id:t}})})).json();return i.success&&((n=i.result)!=null&&n.role)?i.result.role:null}catch{return null}}async isAdmin(e){return this.config.systemId?await this.checkRole(`${this.config.systemId}__admins`,e)==="admin":!1}getCurrentUser(){return Je.getUser()}isAuthenticated(){return Je.isAuthenticated()}async addDomainToUser(e,t){try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_domain_to_user",params:{user_id:e,domain:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async listAllUsers(e){try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_users",params:{...(e==null?void 0:e.limit)&&{limit:e.limit},...(e==null?void 0:e.offset)&&{offset:e.offset}}})})).json();return n.success&&n.result?{success:!0,users:n.result.users||[],total:n.result.total||0}:{success:!1,error:n.error||"Failed to list users"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async listSystemUsers(e){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_system_users",params:{system_id:this.config.systemId,...(e==null?void 0:e.limit)&&{limit:e.limit},...(e==null?void 0:e.offset)&&{offset:e.offset}}})})).json();return n.success&&n.result?{success:!0,users:n.result.users||[],total:n.result.total||0}:{success:!1,error:n.error||"Failed to list users"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async addUserToSystem(e,t="member"){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_system_to_user",params:{user_id:e,system_id:this.config.systemId,role:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async updateMembershipRole(e,t){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_system_to_user",params:{user_id:e,system_id:this.config.systemId,role:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async listUserSystems(e){try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_systems",params:{user_id:e}})})).json();return n.success&&n.result?{success:!0,systems:n.result.systems||[]}:{success:!1,error:n.error||"Failed to list user systems"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async updateUser(e,t){try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"update_user",params:{user_id:e,updates:t}})})).json();if(s.success&&s.result){const i=Je.getUser();if(i&&(i._id===e||i.id===e)){const o={...i,...t};Je.setUser(o)}return{success:!0}}return{success:!1,error:s.error||"Update failed"}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async removeUserFromSystem(e){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"remove_system_from_user",params:{user_id:e,system_id:this.config.systemId}})})).json();return{success:n.success||!1,error:n.error}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}}let As=null;function sf(r){return As=new Ao(r),As}function of(){if(!As)throw new Error("Auth service not initialized. Call initializeAuthService() first.");return As}class au{constructor(e){_t(this,"config");this.config={timeout:3e4,headers:{"Content-Type":"application/json"},...e}}buildQueryString(e){if(!e||Object.keys(e).length===0)return"";const t=new URLSearchParams;Object.entries(e).forEach(([s,i])=>{i!=null&&t.append(s,String(i))});const n=t.toString();return n?`?${n}`:""}async request(e,t={}){const{method:n="GET",headers:s={},body:i,params:o}=t,l=`${this.config.baseUrl}/${e}${this.buildQueryString(o)}`,a={...this.config.headers,...Je.getAuthHeader(),...s},u={method:n,headers:a};i&&n!=="GET"&&(u.body=JSON.stringify(i));try{const c=new AbortController,d=setTimeout(()=>c.abort(),this.config.timeout),f=await fetch(l,{...u,signal:c.signal});if(clearTimeout(d),!f.ok){const p=await f.json().catch(()=>({message:f.statusText}));throw new Error(p.message||`HTTP ${f.status}`)}return await f.json()}catch(c){throw c instanceof Error?c:new Error("An unexpected error occurred")}}async get(e,t){return this.request(e,{method:"GET",params:t})}async post(e,t,n){return this.request(e,{method:"POST",body:t,params:n})}async put(e,t,n){return this.request(e,{method:"PUT",body:t,params:n})}async patch(e,t,n){return this.request(e,{method:"PATCH",body:t,params:n})}async delete(e,t){return this.request(e,{method:"DELETE",params:t})}setBaseUrl(e){this.config.baseUrl=e}getBaseUrl(){return this.config.baseUrl}}let Ts=null;function af(r){return Ts=new au(r),Ts}function To(){if(!Ts)throw new Error("API client not initialized. Call initializeApiClient() first.");return Ts}var Vi={exports:{}},cn={};/**
|
|
28
|
+
`)}),this.textContent=e}isInlineTextNode(e){if(e.contentDisposition.parsed.value==="attachment")return!1;switch(e.contentType.parsed.value){case"text/html":case"text/plain":return!0;case"text/calendar":case"text/csv":default:return!1}}isInlineMessageRfc822(e){return e.contentType.parsed.value!=="message/rfc822"?!1:(e.contentDisposition.parsed.value||(this.options.rfc822Attachments?"attachment":"inline"))==="inline"}forceRfc822Attachments(){if(this.options.forceRfc822Attachments)return!0;let e=!1,t=n=>{n.contentType.multipart||["message/delivery-status","message/feedback-report"].includes(n.contentType.parsed.value)&&(e=!0);for(let s of n.childNodes)t(s)};return t(this.root),e}async resolveStream(e){let t=0,n=[];const s=e.getReader();for(;;){const{done:l,value:a}=await s.read();if(l)break;n.push(a),t+=a.length}const i=new Uint8Array(t);let o=0;for(let l of n)i.set(l,o),o+=l.length;return i}async parse(e){var s,i;if(this.started)throw new Error("Can not reuse parser, create a new PostalMime object");for(this.started=!0,e&&typeof e.getReader=="function"&&(e=await this.resolveStream(e)),e=e||new ArrayBuffer(0),typeof e=="string"&&(e=Xr.encode(e)),(e instanceof Blob||Object.prototype.toString.call(e)==="[object Blob]")&&(e=await ni(e)),e.buffer instanceof ArrayBuffer&&(e=new Uint8Array(e).buffer),this.buf=e,this.av=new Uint8Array(e),this.readPos=0;this.readPos<this.av.length;){const o=this.readLine();await this.processLine(o.bytes,o.done)}await this.processNodeTree();const t={headers:this.root.headers.map(o=>({key:o.key,value:o.value})).reverse()};for(const o of["from","sender"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=Dn(l.value);a&&a.length&&(t[o]=a[0])}}for(const o of["delivered-to","return-path"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=Dn(l.value);if(a&&a.length&&a[0].address){const u=o.replace(/\-(.)/g,(c,d)=>d.toUpperCase());t[u]=a[0].address}}}for(const o of["to","cc","bcc","reply-to"]){const l=this.root.headers.filter(u=>u.key===o);let a=[];if(l.filter(u=>u&&u.value).map(u=>Dn(u.value)).forEach(u=>a=a.concat(u||[])),a&&a.length){const u=o.replace(/\-(.)/g,(c,d)=>d.toUpperCase());t[u]=a}}for(const o of["subject","message-id","in-reply-to","references"]){const l=this.root.headers.find(a=>a.key===o);if(l&&l.value){const a=o.replace(/\-(.)/g,(u,c)=>c.toUpperCase());t[a]=En(l.value)}}let n=this.root.headers.find(o=>o.key==="date");if(n){let o=new Date(n.value);!o||o.toString()==="Invalid Date"?o=n.value:o=o.toISOString(),t.date=o}switch((s=this.textContent)!=null&&s.html&&(t.html=this.textContent.html),(i=this.textContent)!=null&&i.plain&&(t.text=this.textContent.plain),t.attachments=this.attachments,this.attachmentEncoding){case"arraybuffer":break;case"base64":for(let l of t.attachments||[])l!=null&&l.content&&(l.content=ef(l.content),l.encoding="base64");break;case"utf8":let o=new TextDecoder("utf8");for(let l of t.attachments||[])l!=null&&l.content&&(l.content=o.decode(l.content),l.encoding="utf8");break;default:throw new Error("Unknwon attachment encoding")}return t}}class iu{constructor(e){_t(this,"config");if(!e.system_id)throw new Error("MailClient: system_id is REQUIRED");this.config=e}async callCoprocessor(e,t,n={}){const s={coprocessor:e,method:t,system_id:this.config.system_id,params:{user_id:this.config.system_id,...n}};try{const i=await fetch(`${this.config.baseUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.getToken()}`},body:JSON.stringify(s)});if(!i.ok){const l=await i.text();throw new Error(`API error (${i.status}): ${l}`)}const o=await i.json();if(!o.success&&o.error)throw new Error(o.error);return o.result}catch(i){throw console.error("API call failed:",i),i}}async callMail(e,t={}){return this.callCoprocessor("mail",e,t)}async callEmail(e,t={}){return this.callCoprocessor("email",e,t)}getToken(){return typeof window<"u"&&window.localStorage&&localStorage.getItem("qwanyx_token")||""}async getSettings(){try{return await this.callMail("get_email_settings")||{accounts:[]}}catch{return{accounts:[]}}}async saveSettings(e){await this.callMail("save_email_settings",{accounts:e})}async listEmails(e,t=150,n){return this.callMail("list_emails",{account_id:e,limit:t,folder:n})}async deleteEmails(e,t,n=!0){return this.callMail("delete_emails",{account_id:e,uids:t,expunge:n})}async imapExec(e,t){return this.callMail("imap_exec",{account_id:e,commands:t})}async trashEmails(e,t,n="INBOX"){const s=["[Gmail]/Trash","[Gmail]/Corbeille","[Gmail]/Bin","Trash"];for(const i of s){const o=[`SELECT "${n}"`,...t.map(u=>`UID MOVE ${u} "${i}"`)],a=(await this.imapExec(e,o)).responses.filter(u=>u.ok&&u.command==="UID MOVE").length;if(a>0)return{success:!0,moved:a}}return{success:!1,moved:0}}async archiveEmails(e,t,n="INBOX"){const s=[`SELECT "${n}"`,...t.map(l=>`UID STORE ${l} +FLAGS (\\Deleted)`),"EXPUNGE"],o=(await this.imapExec(e,s)).responses.filter(l=>l.ok&&l.command==="UID STORE").length;return{success:o>0,archived:o}}async listFolders(e){const n=(await this.imapExec(e,['LIST "" *'])).responses.find(s=>s.command==="LIST");return n!=null&&n.ok&&n.folders?{success:!0,folders:n.folders}:{success:!1,folders:[]}}async listEmailsSorted(e,t="INBOX",n=150){const s=await this.imapExec(e,[`SELECT ${t}`,"FETCH 1:* (UID INTERNALDATE)"]),i=s.responses.find(p=>p.command==="SELECT");if(!(i!=null&&i.ok))throw new Error(`Failed to select folder: ${(i==null?void 0:i.error)||"Unknown error"}`);const o=s.responses.find(p=>p.command==="FETCH");if(!(o!=null&&o.ok)||!o.messages)return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:[]};const a=[...o.messages].sort((p,g)=>{const m=p.internalDate?new Date(p.internalDate).getTime():0;return(g.internalDate?new Date(g.internalDate).getTime():0)-m}).slice(0,n).map(p=>p.uid).filter(Boolean);if(a.length===0)return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:[]};const c=(await this.imapExec(e,[`SELECT ${t}`,`UID FETCH ${a.join(",")} (UID FLAGS ENVELOPE)`])).responses.find(p=>p.command==="UID FETCH");if(!(c!=null&&c.ok)||!c.messages)throw new Error(`Failed to fetch details: ${(c==null?void 0:c.error)||"Unknown error"}`);const d=new Map;for(const p of c.messages)p.uid&&d.set(p.uid,p);const f=a.map(p=>{var w,S,D,k,C;const g=d.get(p);if(!g)return null;const m=((w=g.flags)==null?void 0:w.some(E=>E.includes("Seen")))||!1,x=((D=(S=g.envelope)==null?void 0:S.from)==null?void 0:D.email)||"Unknown",_=((k=g.envelope)==null?void 0:k.subject)||"(No subject)",b=((C=g.envelope)==null?void 0:C.date)||"";return{uid:p,from:x,subject:_,date:b,seen:m}}).filter(Boolean);return{account:{id:e,label:"",email:""},mailbox:{name:t,total:i.exists||0},messages:f}}async getEmail(e,t,n="INBOX"){return this.callMail("get_email",{account_id:e,uid:t,folder:n})}async getAttachment(e,t,n,s="INBOX"){return this.callMail("get_attachment",{account_id:e,uid:t,attachment_index:typeof n=="number"?n:void 0,attachment_id:typeof n=="string"?n:void 0,folder:s})}async searchContactEmails(e,t,n=50){return this.callMail("search_contact_emails",{account_id:e,contact_email:t,limit:n})}async getEmailParsed(e,t,n="INBOX"){var g,m,x,_,b,w;const i=(await this.imapExec(e,[`SELECT "${n}"`,`UID FETCH ${t} (FLAGS BODY[])`])).responses.find(S=>S.command==="UID FETCH");if(!(i!=null&&i.ok)||!((g=i.messages)!=null&&g[0]))return console.error("Failed to fetch raw email:",i==null?void 0:i.error),null;const o=i.messages[0],l=o.body||o.raw;if(!l)return console.error("No raw email content in response"),null;const u=await new Ds().parse(l);console.log("[MailClient] Parsed email - attachments count:",((m=u.attachments)==null?void 0:m.length)||0),console.log("[MailClient] Parsed attachments:",(x=u.attachments)==null?void 0:x.map(S=>({filename:S.filename,mimeType:S.mimeType,contentId:S.contentId})));const c=new Map;for(const S of u.attachments||[])if(S.contentId){const D=this.contentToBase64(S.content),k=`data:${S.mimeType};base64,${D}`,C=S.contentId.replace(/^<|>$/g,"");c.set(C,k),c.set(`<${C}>`,k)}let d=u.html||"";d&&c.size>0&&(d=d.replace(/src=["']cid:([^"']+)["']/gi,(S,D)=>{const k=c.get(D)||c.get(`<${D}>`);return k?`src="${k}"`:S}));const f=((_=o.flags)==null?void 0:_.some(S=>S.toLowerCase().includes("seen")))||!1,p=((b=u.from)==null?void 0:b.address)||((w=u.from)==null?void 0:w.name)||"Unknown";return{uid:t,from:p,subject:u.subject||"(No subject)",date:u.date||"",body:d||u.text||"",html:d,text:u.text||"",seen:f,attachments:(u.attachments||[]).map(S=>({filename:S.filename||"attachment",mimeType:S.mimeType||"application/octet-stream",size:this.getContentSize(S.content)}))}}async findEmailInAllMail(e,t){var i,o;const n=await this.getSettings(),s=((i=n.accounts)==null?void 0:i.find(l=>l.id===e))||((o=n.accounts)==null?void 0:o[0]);if(!(s!=null&&s.imap))return console.error("[MailClient] No IMAP configuration found for account"),{found:!1};try{return await this.callEmail("findEmailInAllMail",{message_id:t.message_id,from:t.from,subject:t.subject,folder:t.folder,imap_config:{host:s.imap.host,port:parseInt(s.imap.port,10)||993,username:s.imap.user,password:s.imap.password}})}catch(l){return console.error("[MailClient] findEmailInAllMail failed:",l),{found:!1}}}contentToBase64(e){if(typeof e=="string")try{return btoa(e)}catch{return e}const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let s=0;s<t.byteLength;s++)n+=String.fromCharCode(t[s]);return btoa(n)}getContentSize(e){return e?typeof e=="string"?e.length:(e instanceof Uint8Array,e.byteLength):0}async sendMail(e){const t={to:e.to,subject:e.subject,body:e.body};return e.html&&(t.html=e.html),e.from&&(t.from=e.from),e.smtpConfig&&(t.smtp_config=e.smtpConfig),this.callEmail("send",t)}async sendEmail(e,t){var n,s;try{const i=await this.getSettings(),o=((n=i.accounts)==null?void 0:n.find(u=>u.id===e))||((s=i.accounts)==null?void 0:s[0]);if(!(o!=null&&o.smtp))return{success:!1,error:"No SMTP configuration found for account"};const l={to:Array.isArray(t.to)?t.to:[t.to],subject:t.subject,body:t.text||"",html:t.html,from:o.email,smtp_config:{host:o.smtp.host,port:parseInt(o.smtp.port,10)||587,username:o.smtp.user,password:o.smtp.password}};t.cc&&(l.cc=Array.isArray(t.cc)?t.cc:[t.cc]),t.bcc&&(l.bcc=Array.isArray(t.bcc)?t.bcc:[t.bcc]),t.in_reply_to&&(l.in_reply_to=t.in_reply_to),t.attachments&&t.attachments.length>0&&(l.attachments=t.attachments);const a=await this.callEmail("send",l);return{success:(a==null?void 0:a.sent)??!1,message_id:a==null?void 0:a.message_id,error:a==null?void 0:a.error}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async getGmailAuthUrl(e,t){return this.callMail("gmail_get_auth_url",{account_id:e||"gmail",redirect_uri:t||"https://api.qwanyx.com/oauth/gmail/callback"})}async isGmailConnected(e){var t;try{const s=(t=(await this.getSettings()).accounts)==null?void 0:t.find(i=>i.id===e);return(s==null?void 0:s.auth_type)==="gmail_api"&&!!(s!=null&&s.gmail_tokens)}catch{return!1}}async disconnectGmail(e){try{return await this.callMail("gmail_disconnect",{account_id:e}),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async gmailSearchMessage(e,t,n){try{const s=await this.callMail("gmail_search_message",{account_id:e,subject:t,from:n});return(s==null?void 0:s.found)===!1?null:s}catch(s){return console.error("[MailClient] gmailSearchMessage failed:",s),null}}async connectGmail(e){return new Promise(async t=>{try{const{auth_url:n}=await this.getGmailAuthUrl(e),s=600,i=700,o=window.screenX+(window.outerWidth-s)/2,l=window.screenY+(window.outerHeight-i)/2,a=window.open(n,"gmail_oauth",`width=${s},height=${i},left=${o},top=${l},scrollbars=yes`);if(!a){t({success:!1,error:"Popup blocked. Please allow popups for this site."});return}const u=d=>{var f,p;((f=d.data)==null?void 0:f.type)==="gmail_oauth_success"?(window.removeEventListener("message",u),t({success:!0,email:d.data.email})):((p=d.data)==null?void 0:p.type)==="gmail_oauth_error"&&(window.removeEventListener("message",u),t({success:!1,error:d.data.description||d.data.error}))};window.addEventListener("message",u);const c=setInterval(()=>{a.closed&&(clearInterval(c),window.removeEventListener("message",u),setTimeout(()=>{},500))},500)}catch(n){t({success:!1,error:n instanceof Error?n.message:String(n)})}})}}const ou=[{id:"marin",name:"Marin",description:"⭐ Féminin, naturel et fluide"},{id:"cedar",name:"Cedar",description:"⭐ Masculin, expressif et vivant"},{id:"coral",name:"Coral",description:"Féminin, chaleureux et doux"},{id:"alloy",name:"Alloy",description:"Neutre, polyvalent"},{id:"ash",name:"Ash",description:"Masculin, calme et posé"},{id:"ballad",name:"Ballad",description:"Neutre, expressif et narratif"},{id:"echo",name:"Echo",description:"Masculin, profond et résonant"},{id:"fable",name:"Fable",description:"Masculin, accent britannique"},{id:"onyx",name:"Onyx",description:"Masculin, grave et autoritaire"},{id:"nova",name:"Nova",description:"Féminin, dynamique et énergique"},{id:"sage",name:"Sage",description:"Neutre, calme et apaisant"},{id:"shimmer",name:"Shimmer",description:"Féminin, léger et aérien"},{id:"verse",name:"Verse",description:"Neutre, poétique et mélodieux"}];class nf{constructor(e){_t(this,"config");_t(this,"promptCache",{});if(!e.system_id)throw new Error("LLMClient: system_id is REQUIRED");this.config=e}async callLLM(e,t={}){const n={coprocessor:"llm",method:e,system_id:this.config.system_id,params:t};try{const s=await fetch(`${this.config.baseUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.getToken()}`},body:JSON.stringify(n)});if(!s.ok){const o=await s.text();throw new Error(`LLM API error (${s.status}): ${o}`)}const i=await s.json();if(!i.success&&i.error)throw new Error(i.error);return i}catch(s){throw console.error("LLM API call failed:",s),s}}getToken(){return typeof window<"u"&&window.localStorage&&localStorage.getItem("qwanyx_token")||""}async complete(e,t){var i;const n={model:(t==null?void 0:t.model)??"mlm",prompt:e,max_completion_tokens:(t==null?void 0:t.maxTokens)??2e3};t!=null&&t.systemPrompt&&(n.system=t.systemPrompt),(t==null?void 0:t.temperature)!==void 0&&(n.temperature=t.temperature);const s=await this.callLLM("complete",n);return((i=s.result)==null?void 0:i.text)||s.result||""}async chat(e,t){const n={model:(t==null?void 0:t.model)??"mlm",messages:e};(t==null?void 0:t.temperature)!==void 0&&(n.temperature=t.temperature),(t==null?void 0:t.maxTokens)!==void 0&&(n.max_completion_tokens=t.maxTokens);const i=(await this.callLLM("chat",n)).result;return typeof i=="string"?i:typeof(i==null?void 0:i.response)=="string"?i.response:typeof(i==null?void 0:i.text)=="string"?i.text:typeof(i==null?void 0:i.content)=="string"?i.content:typeof(i==null?void 0:i.message)=="string"?i.message:(console.warn("LLMClient.chat: unexpected result format",JSON.stringify(i,null,2)),"")}async chatJson(e,t,n){const s=[{role:"system",content:e},{role:"user",content:t}];let o=await this.chat(s,n);return typeof o=="string"&&(o=o.trim(),o.startsWith("```json")?o=o.slice(7):o.startsWith("```")&&(o=o.slice(3)),o.endsWith("```")&&(o=o.slice(0,-3)),o=o.trim()),JSON.parse(o)}async analyzeDocuments(e,t,n){var o;const s={prompt:e,files:t,model:(n==null?void 0:n.model)??"xlm"};return(n==null?void 0:n.temperature)!==void 0&&(s.temperature=n.temperature),(n==null?void 0:n.maxTokens)!==void 0&&(s.max_tokens=n.maxTokens),((o=(await this.callLLM("analyze",s)).result)==null?void 0:o.text)||""}async tts(e,t){var i;const n={model:"gpt-4o-mini-tts",voice:(t==null?void 0:t.voice)??"coral",input:e,response_format:"mp3"},s=await this.callLLM("tts",n);return((i=s.result)==null?void 0:i.audio)||s.result||""}async generateImage(e,t){var i;const n={prompt:e,size:(t==null?void 0:t.size)??"1536x1024",quality:(t==null?void 0:t.quality)??"medium"};return((i=(await this.callLLM("generate_image",n)).result)==null?void 0:i.image)||""}async transcribe(e,t){var i;const n={audio_data:e};return t!=null&&t.filename&&(n.filename=t.filename),t!=null&&t.language&&(n.language=t.language),((i=(await this.callLLM("transcribe",n)).result)==null?void 0:i.text)||""}async getPrompt(e){var s;if(this.promptCache[e])return this.promptCache[e];const n=((s=(await this.callLLM("get_prompt",{name:e})).result)==null?void 0:s.content)||"";return this.promptCache[e]=n,n}clearPromptCache(){this.promptCache={}}buildPrompt(e,t){let n=e;for(const[s,i]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),i);return n}}const Ai="qwanyx_auth_token",Ti="qwanyx_refresh_token",Ni="qwanyx_auth_user";class Je{static setToken(e){typeof window<"u"&&localStorage.setItem(Ai,e)}static getToken(){return typeof window<"u"?localStorage.getItem(Ai):null}static clearToken(){typeof window<"u"&&(localStorage.removeItem(Ai),localStorage.removeItem(Ti))}static setRefreshToken(e){typeof window<"u"&&localStorage.setItem(Ti,e)}static getRefreshToken(){return typeof window<"u"?localStorage.getItem(Ti):null}static isAuthenticated(){return!!this.getToken()}static getAuthHeader(){const e=this.getToken();return e?{Authorization:`Bearer ${e}`}:{}}static setUser(e){typeof window<"u"&&localStorage.setItem(Ni,JSON.stringify(e))}static getUser(){if(typeof window<"u"){const e=localStorage.getItem(Ni);if(e)try{return JSON.parse(e)}catch{return null}}return null}static clearUser(){typeof window<"u"&&localStorage.removeItem(Ni)}static clearAll(){this.clearToken(),this.clearUser()}}class Ao{constructor(e){_t(this,"config");this.config=e}async register(e,t,n){var s,i;try{const o=n!=null&&n.tenantDomain?[n.tenantDomain]:[],l=(n==null?void 0:n.tenantDomain)||null,u=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"register",params:{email:e,password:t,...n,domains:o,primaryDomain:l,system_id:this.config.systemId}})})).json();return u.success&&((s=u.result)!=null&&s.success)?{success:!0,userId:u.result.user_id,email:u.result.email,requiresVerification:u.result.requiresVerification}:{success:!1,error:((i=u.result)==null?void 0:i.message)||u.error||"Registration failed"}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Network error"}}}async verifyEmail(e,t){var n,s,i,o;try{const a=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"verify_email",params:{email:e,code:t}})})).json();if(a.success&&((n=a.result)!=null&&n.token)){const{token:u,user:c}=a.result;return Je.setToken(u),Je.setUser(c),(i=(s=this.config).onLogin)==null||i.call(s,c),{success:!0,user:c,token:u}}else return{success:!1,error:((o=a.result)==null?void 0:o.error)||a.error||"Verification failed"}}catch(l){return{success:!1,error:l instanceof Error?l.message:"Network error"}}}async requestPasswordReset(e){var t,n;try{const i=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"request_password_reset",params:{email:e}})})).json();return i.success&&((t=i.result)!=null&&t.success)?{success:!0,message:i.result.message}:{success:!1,error:((n=i.result)==null?void 0:n.message)||i.error||"Request failed"}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Network error"}}}async setPasswordWithCode(e,t,n){var s,i,o,l;try{const u=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"set_password_with_code",params:{email:e,code:t,password:n}})})).json();if(u.success&&((s=u.result)!=null&&s.token)){const{token:c,user:d}=u.result;return Je.setToken(c),Je.setUser(d),(o=(i=this.config).onLogin)==null||o.call(i,d),{success:!0,user:d,token:c}}else return{success:!1,error:((l=u.result)==null?void 0:l.message)||u.error||"Password reset failed"}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Network error"}}}async login(e,t,n){var s,i,o,l,a,u,c;try{const f=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"login",params:{email:e,password:t,system_id:this.config.systemId,...n}})})).json();if((s=f.result)!=null&&s.requiresVerification||f.requiresVerification)return{success:!1,error:((i=f.result)==null?void 0:i.error)||f.error||"Please verify your email first",requiresVerification:!0};if(f.success&&((o=f.result)!=null&&o.token)){const{token:p,user:g}=f.result;return Je.setToken(p),Je.setUser(g),n!=null&&n.tenantDomain&&!((l=g.domains)!=null&&l.includes(n.tenantDomain))&&this.addDomainToUser(g._id||g.id,n.tenantDomain).catch(()=>{}),(u=(a=this.config).onLogin)==null||u.call(a,g),{success:!0,user:g,token:p}}else return{success:!1,error:((c=f.result)==null?void 0:c.error)||f.error||"Login failed"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Network error"}}}async resendVerificationCode(e){return this.requestPasswordReset(e)}logout(){var e,t;Je.clearAll(),(t=(e=this.config).onLogout)==null||t.call(e)}async checkRole(e,t){var n;try{const i=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:this.config.systemId||"system",coprocessor:"graph",method:"get_user_role",params:{group_id:e,target_user_id:t}})})).json();return i.success&&((n=i.result)!=null&&n.role)?i.result.role:null}catch{return null}}async isAdmin(e){return this.config.systemId?await this.checkRole(`${this.config.systemId}__admins`,e)==="admin":!1}getCurrentUser(){return Je.getUser()}isAuthenticated(){return Je.isAuthenticated()}async addDomainToUser(e,t){try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_domain_to_user",params:{user_id:e,domain:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async listAllUsers(e){try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_users",params:{...(e==null?void 0:e.limit)&&{limit:e.limit},...(e==null?void 0:e.offset)&&{offset:e.offset}}})})).json();return n.success&&n.result?{success:!0,users:n.result.users||[],total:n.result.total||0}:{success:!1,error:n.error||"Failed to list users"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async listSystemUsers(e){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_system_users",params:{system_id:this.config.systemId,...(e==null?void 0:e.limit)&&{limit:e.limit},...(e==null?void 0:e.offset)&&{offset:e.offset}}})})).json();return n.success&&n.result?{success:!0,users:n.result.users||[],total:n.result.total||0}:{success:!1,error:n.error||"Failed to list users"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async addUserToSystem(e,t="member"){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_system_to_user",params:{user_id:e,system_id:this.config.systemId,role:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async updateMembershipRole(e,t){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"add_system_to_user",params:{user_id:e,system_id:this.config.systemId,role:t}})})).json();return{success:s.success||!1,error:s.error}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async listUserSystems(e){try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"list_systems",params:{user_id:e}})})).json();return n.success&&n.result?{success:!0,systems:n.result.systems||[]}:{success:!1,error:n.error||"Failed to list user systems"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}async updateUser(e,t){try{const s=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"update_user",params:{user_id:e,updates:t}})})).json();if(s.success&&s.result){const i=Je.getUser();if(i&&(i._id===e||i.id===e)){const o={...i,...t};Je.setUser(o)}return{success:!0}}return{success:!1,error:s.error||"Update failed"}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}async removeUserFromSystem(e){if(!this.config.systemId)return{success:!1,error:"System ID not configured"};try{const n=await(await fetch(`${this.config.apiUrl}/spu/invoke`,{method:"POST",headers:{"Content-Type":"application/json",...Je.getAuthHeader()},body:JSON.stringify({system_id:"system",coprocessor:"auth",method:"remove_system_from_user",params:{user_id:e,system_id:this.config.systemId}})})).json();return{success:n.success||!1,error:n.error}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Network error"}}}}let As=null;function sf(r){return As=new Ao(r),As}function of(){if(!As)throw new Error("Auth service not initialized. Call initializeAuthService() first.");return As}class au{constructor(e){_t(this,"config");this.config={timeout:3e4,headers:{"Content-Type":"application/json"},...e}}buildQueryString(e){if(!e||Object.keys(e).length===0)return"";const t=new URLSearchParams;Object.entries(e).forEach(([s,i])=>{i!=null&&t.append(s,String(i))});const n=t.toString();return n?`?${n}`:""}async request(e,t={}){const{method:n="GET",headers:s={},body:i,params:o}=t,l=`${this.config.baseUrl}/${e}${this.buildQueryString(o)}`,a={...this.config.headers,...Je.getAuthHeader(),...s},u={method:n,headers:a};i&&n!=="GET"&&(u.body=JSON.stringify(i));try{const c=new AbortController,d=setTimeout(()=>c.abort(),this.config.timeout),f=await fetch(l,{...u,signal:c.signal});if(clearTimeout(d),!f.ok){const p=await f.json().catch(()=>({message:f.statusText}));throw new Error(p.message||`HTTP ${f.status}`)}return await f.json()}catch(c){throw c instanceof Error?c:new Error("An unexpected error occurred")}}async get(e,t){return this.request(e,{method:"GET",params:t})}async post(e,t,n){return this.request(e,{method:"POST",body:t,params:n})}async put(e,t,n){return this.request(e,{method:"PUT",body:t,params:n})}async patch(e,t,n){return this.request(e,{method:"PATCH",body:t,params:n})}async delete(e,t){return this.request(e,{method:"DELETE",params:t})}setBaseUrl(e){this.config.baseUrl=e}getBaseUrl(){return this.config.baseUrl}}let Ts=null;function af(r){return Ts=new au(r),Ts}function To(){if(!Ts)throw new Error("API client not initialized. Call initializeApiClient() first.");return Ts}var Vi={exports:{}},cn={};/**
|
|
29
29
|
* @license React
|
|
30
30
|
* react-jsx-runtime.production.min.js
|
|
31
31
|
*
|
|
@@ -54,7 +54,7 @@ Check the top-level render call using <`+se+">.")}return q}}function L(A,q){{if(
|
|
|
54
54
|
<%s {...props} />
|
|
55
55
|
React keys must be passed directly to JSX without using spread:
|
|
56
56
|
let props = %s;
|
|
57
|
-
<%s key={someKey} {...props} />`,Si,vr,jd,vr),Ne[vr+Si]=!0}}return A===n?be(st):ve(st),st}}function lt(A,q,se){return rt(A,q,se,!0)}function bt(A,q,se){return rt(A,q,se,!1)}var Zt=bt,jt=lt;dn.Fragment=n,dn.jsx=Zt,dn.jsxs=jt}()),dn}process.env.NODE_ENV==="production"?Vi.exports=lf():Vi.exports=uf();var h=Vi.exports;const lu=y.createContext(void 0);function cf({apiUrl:r,systemId:e,children:t}){const[n,s]=y.useState(null),[i,o]=y.useState(null),[l,a]=y.useState(!1),[u,c]=y.useState(!0),[d]=y.useState(()=>new Ao({apiUrl:r,systemId:e})),f=y.useCallback(async D=>{const k=await d.isAdmin(D);a(k)},[d]),p=y.useCallback(()=>{const D=Je.getToken(),k=Je.getUser();D&&k?(o(D),s(k),f(k._id).finally(()=>c(!1))):c(!1)},[f]);y.useEffect(()=>{p()},[p]);const g=y.useCallback(async(D,k)=>{const C=await d.login(D,k);return C.success&&C.user&&C.token&&(o(C.token),s(C.user),await f(C.user._id)),C},[d,f]),m=y.useCallback(async(D,k,C)=>d.register(D,k,C),[d]),x=y.useCallback(async(D,k)=>{const C=await d.verifyEmail(D,k);return C.success&&C.user&&C.token&&(o(C.token),s(C.user),await f(C.user._id)),C},[d,f]),_=y.useCallback(async D=>d.requestPasswordReset(D),[d]),b=y.useCallback(async(D,k,C)=>{const E=await d.setPasswordWithCode(D,k,C);return E.success&&E.user&&E.token&&(o(E.token),s(E.user),await f(E.user._id)),E},[d,f]),w=y.useCallback(async D=>d.resendVerificationCode(D),[d]),S=y.useCallback(()=>{d.logout(),s(null),o(null),a(!1)},[d]);return h.jsx(lu.Provider,{value:{user:n,token:i,isAdmin:l,loading:u,login:g,register:m,verifyEmail:x,requestPasswordReset:_,setPasswordWithCode:b,resendVerificationCode:w,logout:S,refreshUser:p},children:t})}function df(){const r=y.useContext(lu);if(r===void 0)throw new Error("useAuth must be used within an AuthProvider");return r}const ff={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",inputBackground:"#ffffff",borderRadius:"0.5rem"};function No({onLogin:r,onSuccess:e,logo:t,title:n="Connexion",submitText:s="Se connecter",loadingText:i="Connexion...",emailLabel:o="Email",passwordLabel:l="Mot de passe",theme:a,className:u="",isModal:c=!1}){const[d,f]=y.useState(""),[p,g]=y.useState(""),[m,x]=y.useState(""),[_,b]=y.useState(!1),w={...ff,...a};async function S(N){N.preventDefault(),b(!0),x("");const T=await r(d,p);T.success?e==null||e():x(T.error||"Connexion impossible"),b(!1)}const D={backgroundColor:w.backgroundColor,borderRadius:w.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"
|
|
57
|
+
<%s key={someKey} {...props} />`,Si,vr,jd,vr),Ne[vr+Si]=!0}}return A===n?be(st):ve(st),st}}function lt(A,q,se){return rt(A,q,se,!0)}function bt(A,q,se){return rt(A,q,se,!1)}var Zt=bt,jt=lt;dn.Fragment=n,dn.jsx=Zt,dn.jsxs=jt}()),dn}process.env.NODE_ENV==="production"?Vi.exports=lf():Vi.exports=uf();var h=Vi.exports;const lu=y.createContext(void 0);function cf({apiUrl:r,systemId:e,children:t}){const[n,s]=y.useState(null),[i,o]=y.useState(null),[l,a]=y.useState(!1),[u,c]=y.useState(!0),[d]=y.useState(()=>new Ao({apiUrl:r,systemId:e})),f=y.useCallback(async D=>{const k=await d.isAdmin(D);a(k)},[d]),p=y.useCallback(()=>{const D=Je.getToken(),k=Je.getUser();D&&k?(o(D),s(k),f(k._id).finally(()=>c(!1))):c(!1)},[f]);y.useEffect(()=>{p()},[p]);const g=y.useCallback(async(D,k)=>{const C=await d.login(D,k);return C.success&&C.user&&C.token&&(o(C.token),s(C.user),await f(C.user._id)),C},[d,f]),m=y.useCallback(async(D,k,C)=>d.register(D,k,C),[d]),x=y.useCallback(async(D,k)=>{const C=await d.verifyEmail(D,k);return C.success&&C.user&&C.token&&(o(C.token),s(C.user),await f(C.user._id)),C},[d,f]),_=y.useCallback(async D=>d.requestPasswordReset(D),[d]),b=y.useCallback(async(D,k,C)=>{const E=await d.setPasswordWithCode(D,k,C);return E.success&&E.user&&E.token&&(o(E.token),s(E.user),await f(E.user._id)),E},[d,f]),w=y.useCallback(async D=>d.resendVerificationCode(D),[d]),S=y.useCallback(()=>{d.logout(),s(null),o(null),a(!1)},[d]);return h.jsx(lu.Provider,{value:{user:n,token:i,isAdmin:l,loading:u,login:g,register:m,verifyEmail:x,requestPasswordReset:_,setPasswordWithCode:b,resendVerificationCode:w,logout:S,refreshUser:p},children:t})}function df(){const r=y.useContext(lu);if(r===void 0)throw new Error("useAuth must be used within an AuthProvider");return r}const ff={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",inputBackground:"#ffffff",borderRadius:"0.5rem"};function No({onLogin:r,onSuccess:e,logo:t,title:n="Connexion",submitText:s="Se connecter",loadingText:i="Connexion...",emailLabel:o="Email",passwordLabel:l="Mot de passe",theme:a,className:u="",isModal:c=!1}){const[d,f]=y.useState(""),[p,g]=y.useState(""),[m,x]=y.useState(""),[_,b]=y.useState(!1),w={...ff,...a};async function S(N){N.preventDefault(),b(!0),x("");const T=await r(d,p);T.success?e==null||e():x(T.error||"Connexion impossible"),b(!1)}const D={backgroundColor:w.backgroundColor,borderRadius:w.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"28rem",...c&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},k={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${w.borderColor}`,borderRadius:w.borderRadius,backgroundColor:w.inputBackground,color:w.textColor,fontSize:"1rem",outline:"none"},C={display:"block",fontSize:"0.875rem",fontWeight:500,color:w.textMutedColor,marginBottom:"0.25rem"},E={width:"100%",padding:"0.75rem",backgroundColor:_?w.textMutedColor:w.primaryColor,color:"#ffffff",border:"none",borderRadius:w.borderRadius,fontSize:"1rem",fontWeight:500,cursor:_?"not-allowed":"pointer",transition:"background-color 0.2s"},M={padding:"0.75rem",backgroundColor:w.errorBackgroundColor,border:`1px solid ${w.errorColor}20`,borderRadius:w.borderRadius,marginBottom:"1rem"};return h.jsxs("div",{style:D,className:u,children:[t&&h.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:"1.5rem"},children:t}),h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:w.textColor,marginBottom:"1rem",textAlign:t?"center":"left"},children:n}),h.jsxs("form",{onSubmit:S,children:[m&&h.jsx("div",{style:M,children:h.jsx("p",{style:{fontSize:"0.875rem",color:w.errorColor,margin:0},children:m})}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:C,children:o}),h.jsx("input",{type:"email",value:d,onChange:N=>f(N.target.value),required:!0,style:k,onFocus:N=>{N.target.style.borderColor=w.primaryColor,N.target.style.boxShadow=`0 0 0 2px ${w.primaryColor}20`},onBlur:N=>{N.target.style.borderColor=w.borderColor,N.target.style.boxShadow="none"}})]}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:C,children:l}),h.jsx("input",{type:"password",value:p,onChange:N=>g(N.target.value),required:!0,style:k,onFocus:N=>{N.target.style.borderColor=w.primaryColor,N.target.style.boxShadow=`0 0 0 2px ${w.primaryColor}20`},onBlur:N=>{N.target.style.borderColor=w.borderColor,N.target.style.boxShadow="none"}})]}),h.jsx("button",{type:"submit",disabled:_,style:E,onMouseEnter:N=>{_||(N.target.style.backgroundColor=w.primaryHoverColor)},onMouseLeave:N=>{_||(N.target.style.backgroundColor=w.primaryColor)},children:_?i:s})]})]})}function hf({isOpen:r,onClose:e,backdropBlur:t=!0,...n}){if(!r)return null;const s={position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem"},i={position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",...t&&{backdropFilter:"blur(4px)"}},o={position:"relative",animation:"slideUp 0.2s ease-out"};return h.jsxs("div",{style:s,children:[h.jsx("div",{style:i,onClick:e}),h.jsxs("div",{style:o,children:[h.jsx("button",{onClick:e,style:{position:"absolute",top:"0.75rem",right:"0.75rem",zIndex:10,background:"none",border:"none",padding:"0.25rem",cursor:"pointer",color:"#9CA3AF"},onMouseEnter:l=>{l.target.style.color="#4B5563"},onMouseLeave:l=>{l.target.style.color="#9CA3AF"},children:h.jsx("svg",{width:"24",height:"24",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),h.jsx(No,{...n,isModal:!0})]}),h.jsx("style",{children:`
|
|
58
58
|
@keyframes slideUp {
|
|
59
59
|
from {
|
|
60
60
|
opacity: 0;
|
|
@@ -65,7 +65,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
65
65
|
transform: translateY(0);
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`})]})}const pf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",successBackgroundColor:"#ECFDF5",inputBackground:"#ffffff",borderRadius:"0.5rem"};function uu({onRegister:r,onSuccess:e,onLoginClick:t,logo:n,title:s="Créer un compte",submitText:i="S'inscrire",loadingText:o="Inscription...",emailLabel:l="Email",passwordLabel:a="Mot de passe",confirmPasswordLabel:u="Confirmer le mot de passe",firstNameLabel:c="Prénom",lastNameLabel:d="Nom",loginLinkText:f="Déjà un compte ? Se connecter",showNameFields:p=!1,theme:g,className:m="",isModal:x=!1}){const[_,b]=y.useState(""),[w,S]=y.useState(""),[D,k]=y.useState(""),[C,E]=y.useState(""),[M,N]=y.useState(""),[T,B]=y.useState(""),[R,v]=y.useState(!1),j={...pf,...g};async function F(H){if(H.preventDefault(),B(""),w!==D){B("Les mots de passe ne correspondent pas");return}if(w.length<8){B("Le mot de passe doit contenir au moins 8 caractères");return}v(!0);const ce=await r(_,w,p?{firstName:C,lastName:M}:void 0);ce.success?e==null||e(_):B(ce.error||"Erreur lors de l'inscription"),v(!1)}const z={backgroundColor:j.backgroundColor,borderRadius:j.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"24rem",...x&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},W={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${j.borderColor}`,borderRadius:j.borderRadius,backgroundColor:j.inputBackground,color:j.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},te={display:"block",fontSize:"0.875rem",fontWeight:500,color:j.textMutedColor,marginBottom:"0.25rem"},re={width:"100%",padding:"0.75rem",backgroundColor:R?j.textMutedColor:j.primaryColor,color:"#ffffff",border:"none",borderRadius:j.borderRadius,fontSize:"1rem",fontWeight:500,cursor:R?"not-allowed":"pointer",transition:"background-color 0.2s"},$={padding:"0.75rem",backgroundColor:j.errorBackgroundColor,border:`1px solid ${j.errorColor}20`,borderRadius:j.borderRadius,marginBottom:"1rem"},Q={color:j.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"};return h.jsxs("div",{style:z,className:m,children:[n&&h.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:"1.5rem"},children:n}),h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:j.textColor,marginBottom:"1rem",textAlign:n?"center":"left"},children:s}),h.jsxs("form",{onSubmit:F,children:[T&&h.jsx("div",{style:$,children:h.jsx("p",{style:{fontSize:"0.875rem",color:j.errorColor,margin:0},children:T})}),p&&h.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginBottom:"1rem"},children:[h.jsxs("div",{style:{flex:1},children:[h.jsx("label",{style:te,children:c}),h.jsx("input",{type:"text",value:C,onChange:H=>E(H.target.value),style:W})]}),h.jsxs("div",{style:{flex:1},children:[h.jsx("label",{style:te,children:d}),h.jsx("input",{type:"text",value:M,onChange:H=>N(H.target.value),style:W})]})]}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:te,children:l}),h.jsx("input",{type:"email",value:_,onChange:H=>b(H.target.value),required:!0,style:W})]}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:te,children:a}),h.jsx("input",{type:"password",value:w,onChange:H=>S(H.target.value),required:!0,minLength:8,style:W})]}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:te,children:u}),h.jsx("input",{type:"password",value:D,onChange:H=>k(H.target.value),required:!0,style:W})]}),h.jsx("button",{type:"submit",disabled:R,style:re,onMouseEnter:H=>{R||(H.target.style.backgroundColor=j.primaryHoverColor)},onMouseLeave:H=>{R||(H.target.style.backgroundColor=j.primaryColor)},children:R?o:i}),t&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("span",{style:Q,onClick:t,children:f})})]})]})}const gf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",inputBackground:"#ffffff",borderRadius:"0.5rem"};function Gi({email:r,onVerify:e,onSuccess:t,onResendCode:n,onBackClick:s,title:i="Vérification",subtitle:o,submitText:l="Vérifier",loadingText:a="Vérification...",resendText:u="Renvoyer le code",resendingText:c="Envoi...",backText:d="← Retour",codeLength:f=6,theme:p,className:g="",isModal:m=!1}){const[x,_]=y.useState(Array(f).fill("")),[b,w]=y.useState(""),[S,D]=y.useState(!1),[k,C]=y.useState(!1),[E,M]=y.useState(!1),N=y.useRef([]),T={...gf,...p};y.useEffect(()=>{var $;($=N.current[0])==null||$.focus()},[]);const B=($,Q)=>{var ce;const H=Q.replace(/\D/g,"").slice(-1),oe=[...x];if(oe[$]=H,_(oe),w(""),H&&$<f-1&&((ce=N.current[$+1])==null||ce.focus()),H&&$===f-1){const he=oe.join("");he.length===f&&j(he)}},R=($,Q)=>{var H;Q.key==="Backspace"&&!x[$]&&$>0&&((H=N.current[$-1])==null||H.focus())},v=$=>{var ce;$.preventDefault();const Q=$.clipboardData.getData("text").replace(/\D/g,"").slice(0,f),H=[...x];Q.split("").forEach((he,pe)=>{pe<f&&(H[pe]=he)}),_(H);const oe=Math.min(Q.length,f)-1;oe>=0&&((ce=N.current[oe])==null||ce.focus()),Q.length===f&&j(Q)};async function j($){var oe;const Q=$||x.join("");if(Q.length!==f){w("Veuillez entrer le code complet");return}D(!0),w("");const H=await e(r,Q);H.success?t==null||t():(w(H.error||"Code invalide"),_(Array(f).fill("")),(oe=N.current[0])==null||oe.focus()),D(!1)}async function F(){if(!n)return;C(!0),M(!1),w("");const $=await n(r);$.success?(M(!0),setTimeout(()=>M(!1),3e3)):w($.error||"Erreur lors de l'envoi"),C(!1)}const z={backgroundColor:T.backgroundColor,borderRadius:T.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"24rem",...m&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},W={width:"3rem",height:"3.5rem",textAlign:"center",fontSize:"1.5rem",fontWeight:600,border:`2px solid ${T.borderColor}`,borderRadius:T.borderRadius,backgroundColor:T.inputBackground,color:T.textColor,outline:"none",transition:"border-color 0.2s, box-shadow 0.2s"},te={width:"100%",padding:"0.75rem",backgroundColor:S?T.textMutedColor:T.primaryColor,color:"#ffffff",border:"none",borderRadius:T.borderRadius,fontSize:"1rem",fontWeight:500,cursor:S?"not-allowed":"pointer",transition:"background-color 0.2s"},re={color:T.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:z,className:g,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:T.textColor,marginBottom:"0.5rem",textAlign:"center"},children:i}),h.jsx("p",{style:{fontSize:"0.875rem",color:T.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:o||`Un code a été envoyé à ${r}`}),b&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:T.errorBackgroundColor,border:`1px solid ${T.errorColor}20`,borderRadius:T.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:T.errorColor,margin:0,textAlign:"center"},children:b})}),E&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:"#ECFDF5",border:`1px solid ${T.successColor}20`,borderRadius:T.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:T.successColor,margin:0,textAlign:"center"},children:"Code renvoyé !"})}),h.jsx("div",{style:{display:"flex",justifyContent:"center",gap:"0.5rem",marginBottom:"1.5rem"},children:x.map(($,Q)=>h.jsx("input",{ref:H=>{N.current[Q]=H},type:"text",inputMode:"numeric",maxLength:1,value:$,onChange:H=>B(Q,H.target.value),onKeyDown:H=>R(Q,H),onPaste:v,disabled:S,style:{...W,borderColor:$?T.primaryColor:T.borderColor},onFocus:H=>{H.target.style.borderColor=T.primaryColor,H.target.style.boxShadow=`0 0 0 3px ${T.primaryColor}20`},onBlur:H=>{H.target.style.borderColor=$?T.primaryColor:T.borderColor,H.target.style.boxShadow="none"}},Q))}),h.jsx("button",{type:"button",onClick:()=>j(),disabled:S||x.join("").length!==f,style:{...te,opacity:x.join("").length!==f?.5:1},children:S?a:l}),n&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:F,disabled:k,style:{...re,opacity:k?.5:1},children:k?c:u})}),s&&h.jsx("p",{style:{textAlign:"center",marginTop:"0.75rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:s,style:re,children:d})})]})}const mf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",successBackgroundColor:"#ECFDF5",inputBackground:"#ffffff",borderRadius:"0.5rem"};function cu({onRequestReset:r,onSuccess:e,onBackClick:t,title:n="Mot de passe oublié",subtitle:s="Entrez votre email pour recevoir un code de réinitialisation",submitText:i="Envoyer le code",loadingText:o="Envoi...",emailLabel:l="Email",backText:a="← Retour à la connexion",theme:u,className:c="",isModal:d=!1}){const[f,p]=y.useState(""),[g,m]=y.useState(""),[x,_]=y.useState(!1),b={...mf,...u};async function w(M){M.preventDefault(),_(!0),m("");const N=await r(f);N.success?e==null||e(f):m(N.error||"Erreur lors de l'envoi"),_(!1)}const S={backgroundColor:b.backgroundColor,borderRadius:b.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"24rem",...d&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},D={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${b.borderColor}`,borderRadius:b.borderRadius,backgroundColor:b.inputBackground,color:b.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},k={display:"block",fontSize:"0.875rem",fontWeight:500,color:b.textMutedColor,marginBottom:"0.25rem"},C={width:"100%",padding:"0.75rem",backgroundColor:x?b.textMutedColor:b.primaryColor,color:"#ffffff",border:"none",borderRadius:b.borderRadius,fontSize:"1rem",fontWeight:500,cursor:x?"not-allowed":"pointer",transition:"background-color 0.2s"},E={color:b.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:S,className:c,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:b.textColor,marginBottom:"0.5rem",textAlign:"center"},children:n}),h.jsx("p",{style:{fontSize:"0.875rem",color:b.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:s}),h.jsxs("form",{onSubmit:w,children:[g&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:b.errorBackgroundColor,border:`1px solid ${b.errorColor}20`,borderRadius:b.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:b.errorColor,margin:0},children:g})}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:k,children:l}),h.jsx("input",{type:"email",value:f,onChange:M=>p(M.target.value),required:!0,style:D})]}),h.jsx("button",{type:"submit",disabled:x,style:C,onMouseEnter:M=>{x||(M.target.style.backgroundColor=b.primaryHoverColor)},onMouseLeave:M=>{x||(M.target.style.backgroundColor=b.primaryColor)},children:x?o:i}),t&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:t,style:E,children:a})})]})]})}const yf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",inputBackground:"#ffffff",borderRadius:"0.5rem"};function du({email:r,code:e,onResetPassword:t,onSuccess:n,onBackClick:s,title:i="Nouveau mot de passe",subtitle:o,submitText:l="Réinitialiser",loadingText:a="Réinitialisation...",passwordLabel:u="Nouveau mot de passe",confirmPasswordLabel:c="Confirmer le mot de passe",backText:d="← Retour",theme:f,className:p="",isModal:g=!1}){const[m,x]=y.useState(""),[_,b]=y.useState(""),[w,S]=y.useState(""),[D,k]=y.useState(!1),C={...yf,...f};async function E(v){if(v.preventDefault(),S(""),m!==_){S("Les mots de passe ne correspondent pas");return}if(m.length<8){S("Le mot de passe doit contenir au moins 8 caractères");return}k(!0);const j=await t(r,e,m);j.success?n==null||n():S(j.error||"Erreur lors de la réinitialisation"),k(!1)}const M={backgroundColor:C.backgroundColor,borderRadius:C.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"24rem",...g&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},N={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${C.borderColor}`,borderRadius:C.borderRadius,backgroundColor:C.inputBackground,color:C.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},T={display:"block",fontSize:"0.875rem",fontWeight:500,color:C.textMutedColor,marginBottom:"0.25rem"},B={width:"100%",padding:"0.75rem",backgroundColor:D?C.textMutedColor:C.primaryColor,color:"#ffffff",border:"none",borderRadius:C.borderRadius,fontSize:"1rem",fontWeight:500,cursor:D?"not-allowed":"pointer",transition:"background-color 0.2s"},R={color:C.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:M,className:p,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:C.textColor,marginBottom:"0.5rem",textAlign:"center"},children:i}),o&&h.jsx("p",{style:{fontSize:"0.875rem",color:C.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:o}),h.jsxs("form",{onSubmit:E,children:[w&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:C.errorBackgroundColor,border:`1px solid ${C.errorColor}20`,borderRadius:C.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:C.errorColor,margin:0},children:w})}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:T,children:u}),h.jsx("input",{type:"password",value:m,onChange:v=>x(v.target.value),required:!0,minLength:8,style:N})]}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:T,children:c}),h.jsx("input",{type:"password",value:_,onChange:v=>b(v.target.value),required:!0,style:N})]}),h.jsx("button",{type:"submit",disabled:D,style:B,onMouseEnter:v=>{D||(v.target.style.backgroundColor=C.primaryHoverColor)},onMouseLeave:v=>{D||(v.target.style.backgroundColor=C.primaryColor)},children:D?a:l}),s&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:s,style:R,children:d})})]})]})}function fu({onLogin:r,onRegister:e,onVerifyEmail:t,onRequestPasswordReset:n,onResetPassword:s,onResendCode:i,onSuccess:o,initialState:l="login",logo:a,theme:u,showNameFields:c=!1,className:d="",isModal:f=!1,labels:p={}}){const[g,m]=y.useState(l),[x,_]=y.useState(""),[b,w]=y.useState("");async function S(N,T){const B=await r(N,T);return B.requiresVerification?(_(N),m("verify-email"),{success:!1,error:"Veuillez vérifier votre email"}):B}async function D(N,T,B){const R=await e(N,T,B);return R.success&&(R.requiresVerification?(_(N),m("verify-email")):o==null||o()),R}async function k(N){const T=await n(N);return T.success&&(_(N),m("verify-reset-code")),T}async function C(N,T){return w(T),m("reset-password"),{success:!0}}const E=()=>{switch(g){case"login":return h.jsx(No,{onLogin:S,onSuccess:o,logo:a,theme:u,title:p.loginTitle,className:d,isModal:f});case"register":return h.jsx(uu,{onRegister:D,onSuccess:()=>{},onLoginClick:()=>m("login"),logo:a,theme:u,title:p.registerTitle,showNameFields:c,className:d,isModal:f});case"verify-email":return h.jsx(Gi,{email:x,onVerify:t,onSuccess:o,onResendCode:i,onBackClick:()=>m("login"),title:p.verifyTitle||"Vérification email",theme:u,className:d,isModal:f});case"forgot-password":return h.jsx(cu,{onRequestReset:k,onBackClick:()=>m("login"),title:p.forgotPasswordTitle,theme:u,className:d,isModal:f});case"verify-reset-code":return h.jsx(Gi,{email:x,onVerify:C,onResendCode:i,onBackClick:()=>m("forgot-password"),title:"Code de réinitialisation",theme:u,className:d,isModal:f});case"reset-password":return h.jsx(du,{email:x,code:b,onResetPassword:s,onSuccess:o,onBackClick:()=>m("login"),title:p.resetPasswordTitle,theme:u,className:d,isModal:f})}},M=()=>{const N={color:(u==null?void 0:u.primaryColor)||"#1877F2",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return g==="login"?h.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"1rem",padding:"0 1.5rem",maxWidth:"24rem",width:"100%"},children:[h.jsx("button",{type:"button",onClick:()=>m("forgot-password"),style:N,children:"Mot de passe oublié ?"}),h.jsx("button",{type:"button",onClick:()=>m("register"),style:N,children:"Créer un compte"})]}):null};return h.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:"100%"},children:[E(),M()]})}function xf({isOpen:r,onClose:e,backdropBlur:t=!0,...n}){return r?h.jsxs("div",{style:{position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem"},children:[h.jsx("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",...t&&{backdropFilter:"blur(4px)"}},onClick:e}),h.jsxs("div",{style:{position:"relative",animation:"authFlowSlideUp 0.2s ease-out"},children:[h.jsx("button",{onClick:e,style:{position:"absolute",top:"0.75rem",right:"0.75rem",zIndex:10,background:"none",border:"none",padding:"0.25rem",cursor:"pointer",color:"#9CA3AF"},children:h.jsx("svg",{width:"24",height:"24",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),h.jsx(fu,{...n,isModal:!0})]}),h.jsx("style",{children:`
|
|
68
|
+
`})]})}const pf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",successBackgroundColor:"#ECFDF5",inputBackground:"#ffffff",borderRadius:"0.5rem"};function uu({onRegister:r,onSuccess:e,onLoginClick:t,logo:n,title:s="Créer un compte",submitText:i="S'inscrire",loadingText:o="Inscription...",emailLabel:l="Email",passwordLabel:a="Mot de passe",confirmPasswordLabel:u="Confirmer le mot de passe",firstNameLabel:c="Prénom",lastNameLabel:d="Nom",loginLinkText:f="Déjà un compte ? Se connecter",showNameFields:p=!1,theme:g,className:m="",isModal:x=!1}){const[_,b]=y.useState(""),[w,S]=y.useState(""),[D,k]=y.useState(""),[C,E]=y.useState(""),[M,N]=y.useState(""),[T,B]=y.useState(""),[R,v]=y.useState(!1),j={...pf,...g};async function F(H){if(H.preventDefault(),B(""),w!==D){B("Les mots de passe ne correspondent pas");return}if(w.length<8){B("Le mot de passe doit contenir au moins 8 caractères");return}v(!0);const ce=await r(_,w,p?{firstName:C,lastName:M}:void 0);ce.success?e==null||e(_):B(ce.error||"Erreur lors de l'inscription"),v(!1)}const z={backgroundColor:j.backgroundColor,borderRadius:j.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"28rem",...x&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},W={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${j.borderColor}`,borderRadius:j.borderRadius,backgroundColor:j.inputBackground,color:j.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},te={display:"block",fontSize:"0.875rem",fontWeight:500,color:j.textMutedColor,marginBottom:"0.25rem"},re={width:"100%",padding:"0.75rem",backgroundColor:R?j.textMutedColor:j.primaryColor,color:"#ffffff",border:"none",borderRadius:j.borderRadius,fontSize:"1rem",fontWeight:500,cursor:R?"not-allowed":"pointer",transition:"background-color 0.2s"},$={padding:"0.75rem",backgroundColor:j.errorBackgroundColor,border:`1px solid ${j.errorColor}20`,borderRadius:j.borderRadius,marginBottom:"1rem"},Q={color:j.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"};return h.jsxs("div",{style:z,className:m,children:[n&&h.jsx("div",{style:{display:"flex",justifyContent:"center",marginBottom:"1.5rem"},children:n}),h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:j.textColor,marginBottom:"1rem",textAlign:n?"center":"left"},children:s}),h.jsxs("form",{onSubmit:F,children:[T&&h.jsx("div",{style:$,children:h.jsx("p",{style:{fontSize:"0.875rem",color:j.errorColor,margin:0},children:T})}),p&&h.jsxs("div",{style:{display:"flex",gap:"0.75rem",marginBottom:"1rem"},children:[h.jsxs("div",{style:{flex:1},children:[h.jsx("label",{style:te,children:c}),h.jsx("input",{type:"text",value:C,onChange:H=>E(H.target.value),style:W})]}),h.jsxs("div",{style:{flex:1},children:[h.jsx("label",{style:te,children:d}),h.jsx("input",{type:"text",value:M,onChange:H=>N(H.target.value),style:W})]})]}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:te,children:l}),h.jsx("input",{type:"email",value:_,onChange:H=>b(H.target.value),required:!0,style:W})]}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:te,children:a}),h.jsx("input",{type:"password",value:w,onChange:H=>S(H.target.value),required:!0,minLength:8,style:W})]}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:te,children:u}),h.jsx("input",{type:"password",value:D,onChange:H=>k(H.target.value),required:!0,style:W})]}),h.jsx("button",{type:"submit",disabled:R,style:re,onMouseEnter:H=>{R||(H.target.style.backgroundColor=j.primaryHoverColor)},onMouseLeave:H=>{R||(H.target.style.backgroundColor=j.primaryColor)},children:R?o:i}),t&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("span",{style:Q,onClick:t,children:f})})]})]})}const gf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",inputBackground:"#ffffff",borderRadius:"0.5rem"};function Gi({email:r,onVerify:e,onSuccess:t,onResendCode:n,onBackClick:s,title:i="Vérification",subtitle:o,submitText:l="Vérifier",loadingText:a="Vérification...",resendText:u="Renvoyer le code",resendingText:c="Envoi...",backText:d="← Retour",codeLength:f=6,theme:p,className:g="",isModal:m=!1}){const[x,_]=y.useState(Array(f).fill("")),[b,w]=y.useState(""),[S,D]=y.useState(!1),[k,C]=y.useState(!1),[E,M]=y.useState(!1),N=y.useRef([]),T={...gf,...p};y.useEffect(()=>{var $;($=N.current[0])==null||$.focus()},[]);const B=($,Q)=>{var ce;const H=Q.replace(/\D/g,"").slice(-1),oe=[...x];if(oe[$]=H,_(oe),w(""),H&&$<f-1&&((ce=N.current[$+1])==null||ce.focus()),H&&$===f-1){const he=oe.join("");he.length===f&&j(he)}},R=($,Q)=>{var H;Q.key==="Backspace"&&!x[$]&&$>0&&((H=N.current[$-1])==null||H.focus())},v=$=>{var ce;$.preventDefault();const Q=$.clipboardData.getData("text").replace(/\D/g,"").slice(0,f),H=[...x];Q.split("").forEach((he,pe)=>{pe<f&&(H[pe]=he)}),_(H);const oe=Math.min(Q.length,f)-1;oe>=0&&((ce=N.current[oe])==null||ce.focus()),Q.length===f&&j(Q)};async function j($){var oe;const Q=$||x.join("");if(Q.length!==f){w("Veuillez entrer le code complet");return}D(!0),w("");const H=await e(r,Q);H.success?t==null||t():(w(H.error||"Code invalide"),_(Array(f).fill("")),(oe=N.current[0])==null||oe.focus()),D(!1)}async function F(){if(!n)return;C(!0),M(!1),w("");const $=await n(r);$.success?(M(!0),setTimeout(()=>M(!1),3e3)):w($.error||"Erreur lors de l'envoi"),C(!1)}const z={backgroundColor:T.backgroundColor,borderRadius:T.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"28rem",...m&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},W={width:"3rem",height:"3.5rem",textAlign:"center",fontSize:"1.5rem",fontWeight:600,border:`2px solid ${T.borderColor}`,borderRadius:T.borderRadius,backgroundColor:T.inputBackground,color:T.textColor,outline:"none",transition:"border-color 0.2s, box-shadow 0.2s"},te={width:"100%",padding:"0.75rem",backgroundColor:S?T.textMutedColor:T.primaryColor,color:"#ffffff",border:"none",borderRadius:T.borderRadius,fontSize:"1rem",fontWeight:500,cursor:S?"not-allowed":"pointer",transition:"background-color 0.2s"},re={color:T.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:z,className:g,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:T.textColor,marginBottom:"0.5rem",textAlign:"center"},children:i}),h.jsx("p",{style:{fontSize:"0.875rem",color:T.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:o||`Un code a été envoyé à ${r}`}),b&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:T.errorBackgroundColor,border:`1px solid ${T.errorColor}20`,borderRadius:T.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:T.errorColor,margin:0,textAlign:"center"},children:b})}),E&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:"#ECFDF5",border:`1px solid ${T.successColor}20`,borderRadius:T.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:T.successColor,margin:0,textAlign:"center"},children:"Code renvoyé !"})}),h.jsx("div",{style:{display:"flex",justifyContent:"center",gap:"0.5rem",marginBottom:"1.5rem"},children:x.map(($,Q)=>h.jsx("input",{ref:H=>{N.current[Q]=H},type:"text",inputMode:"numeric",maxLength:1,value:$,onChange:H=>B(Q,H.target.value),onKeyDown:H=>R(Q,H),onPaste:v,disabled:S,style:{...W,borderColor:$?T.primaryColor:T.borderColor},onFocus:H=>{H.target.style.borderColor=T.primaryColor,H.target.style.boxShadow=`0 0 0 3px ${T.primaryColor}20`},onBlur:H=>{H.target.style.borderColor=$?T.primaryColor:T.borderColor,H.target.style.boxShadow="none"}},Q))}),h.jsx("button",{type:"button",onClick:()=>j(),disabled:S||x.join("").length!==f,style:{...te,opacity:x.join("").length!==f?.5:1},children:S?a:l}),n&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:F,disabled:k,style:{...re,opacity:k?.5:1},children:k?c:u})}),s&&h.jsx("p",{style:{textAlign:"center",marginTop:"0.75rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:s,style:re,children:d})})]})}const mf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",successColor:"#059669",successBackgroundColor:"#ECFDF5",inputBackground:"#ffffff",borderRadius:"0.5rem"};function cu({onRequestReset:r,onSuccess:e,onBackClick:t,title:n="Mot de passe oublié",subtitle:s="Entrez votre email pour recevoir un code de réinitialisation",submitText:i="Envoyer le code",loadingText:o="Envoi...",emailLabel:l="Email",backText:a="← Retour à la connexion",theme:u,className:c="",isModal:d=!1}){const[f,p]=y.useState(""),[g,m]=y.useState(""),[x,_]=y.useState(!1),b={...mf,...u};async function w(M){M.preventDefault(),_(!0),m("");const N=await r(f);N.success?e==null||e(f):m(N.error||"Erreur lors de l'envoi"),_(!1)}const S={backgroundColor:b.backgroundColor,borderRadius:b.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"28rem",...d&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},D={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${b.borderColor}`,borderRadius:b.borderRadius,backgroundColor:b.inputBackground,color:b.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},k={display:"block",fontSize:"0.875rem",fontWeight:500,color:b.textMutedColor,marginBottom:"0.25rem"},C={width:"100%",padding:"0.75rem",backgroundColor:x?b.textMutedColor:b.primaryColor,color:"#ffffff",border:"none",borderRadius:b.borderRadius,fontSize:"1rem",fontWeight:500,cursor:x?"not-allowed":"pointer",transition:"background-color 0.2s"},E={color:b.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:S,className:c,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:b.textColor,marginBottom:"0.5rem",textAlign:"center"},children:n}),h.jsx("p",{style:{fontSize:"0.875rem",color:b.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:s}),h.jsxs("form",{onSubmit:w,children:[g&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:b.errorBackgroundColor,border:`1px solid ${b.errorColor}20`,borderRadius:b.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:b.errorColor,margin:0},children:g})}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:k,children:l}),h.jsx("input",{type:"email",value:f,onChange:M=>p(M.target.value),required:!0,style:D})]}),h.jsx("button",{type:"submit",disabled:x,style:C,onMouseEnter:M=>{x||(M.target.style.backgroundColor=b.primaryHoverColor)},onMouseLeave:M=>{x||(M.target.style.backgroundColor=b.primaryColor)},children:x?o:i}),t&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:t,style:E,children:a})})]})]})}const yf={primaryColor:"#1877F2",primaryHoverColor:"#166FE5",backgroundColor:"#ffffff",textColor:"#111827",textMutedColor:"#6B7280",borderColor:"#D1D5DB",errorColor:"#DC2626",errorBackgroundColor:"#FEF2F2",inputBackground:"#ffffff",borderRadius:"0.5rem"};function du({email:r,code:e,onResetPassword:t,onSuccess:n,onBackClick:s,title:i="Nouveau mot de passe",subtitle:o,submitText:l="Réinitialiser",loadingText:a="Réinitialisation...",passwordLabel:u="Nouveau mot de passe",confirmPasswordLabel:c="Confirmer le mot de passe",backText:d="← Retour",theme:f,className:p="",isModal:g=!1}){const[m,x]=y.useState(""),[_,b]=y.useState(""),[w,S]=y.useState(""),[D,k]=y.useState(!1),C={...yf,...f};async function E(v){if(v.preventDefault(),S(""),m!==_){S("Les mots de passe ne correspondent pas");return}if(m.length<8){S("Le mot de passe doit contenir au moins 8 caractères");return}k(!0);const j=await t(r,e,m);j.success?n==null||n():S(j.error||"Erreur lors de la réinitialisation"),k(!1)}const M={backgroundColor:C.backgroundColor,borderRadius:C.borderRadius,padding:"1.5rem",width:"100%",maxWidth:"28rem",...g&&{boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"}},N={width:"100%",padding:"0.5rem 1rem",border:`1px solid ${C.borderColor}`,borderRadius:C.borderRadius,backgroundColor:C.inputBackground,color:C.textColor,fontSize:"1rem",outline:"none",boxSizing:"border-box"},T={display:"block",fontSize:"0.875rem",fontWeight:500,color:C.textMutedColor,marginBottom:"0.25rem"},B={width:"100%",padding:"0.75rem",backgroundColor:D?C.textMutedColor:C.primaryColor,color:"#ffffff",border:"none",borderRadius:C.borderRadius,fontSize:"1rem",fontWeight:500,cursor:D?"not-allowed":"pointer",transition:"background-color 0.2s"},R={color:C.primaryColor,textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return h.jsxs("div",{style:M,className:p,children:[h.jsx("h2",{style:{fontSize:"1.25rem",fontWeight:700,color:C.textColor,marginBottom:"0.5rem",textAlign:"center"},children:i}),o&&h.jsx("p",{style:{fontSize:"0.875rem",color:C.textMutedColor,textAlign:"center",marginBottom:"1.5rem"},children:o}),h.jsxs("form",{onSubmit:E,children:[w&&h.jsx("div",{style:{padding:"0.75rem",backgroundColor:C.errorBackgroundColor,border:`1px solid ${C.errorColor}20`,borderRadius:C.borderRadius,marginBottom:"1rem"},children:h.jsx("p",{style:{fontSize:"0.875rem",color:C.errorColor,margin:0},children:w})}),h.jsxs("div",{style:{marginBottom:"1rem"},children:[h.jsx("label",{style:T,children:u}),h.jsx("input",{type:"password",value:m,onChange:v=>x(v.target.value),required:!0,minLength:8,style:N})]}),h.jsxs("div",{style:{marginBottom:"1.5rem"},children:[h.jsx("label",{style:T,children:c}),h.jsx("input",{type:"password",value:_,onChange:v=>b(v.target.value),required:!0,style:N})]}),h.jsx("button",{type:"submit",disabled:D,style:B,onMouseEnter:v=>{D||(v.target.style.backgroundColor=C.primaryHoverColor)},onMouseLeave:v=>{D||(v.target.style.backgroundColor=C.primaryColor)},children:D?a:l}),s&&h.jsx("p",{style:{textAlign:"center",marginTop:"1rem",marginBottom:0},children:h.jsx("button",{type:"button",onClick:s,style:R,children:d})})]})]})}function fu({onLogin:r,onRegister:e,onVerifyEmail:t,onRequestPasswordReset:n,onResetPassword:s,onResendCode:i,onSuccess:o,initialState:l="login",logo:a,theme:u,showNameFields:c=!1,className:d="",isModal:f=!1,labels:p={}}){const[g,m]=y.useState(l),[x,_]=y.useState(""),[b,w]=y.useState("");async function S(N,T){const B=await r(N,T);return B.requiresVerification?(_(N),m("verify-email"),{success:!1,error:"Veuillez vérifier votre email"}):B}async function D(N,T,B){const R=await e(N,T,B);return R.success&&(R.requiresVerification?(_(N),m("verify-email")):o==null||o()),R}async function k(N){const T=await n(N);return T.success&&(_(N),m("verify-reset-code")),T}async function C(N,T){return w(T),m("reset-password"),{success:!0}}const E=()=>{switch(g){case"login":return h.jsx(No,{onLogin:S,onSuccess:o,logo:a,theme:u,title:p.loginTitle,className:d,isModal:f});case"register":return h.jsx(uu,{onRegister:D,onSuccess:()=>{},onLoginClick:()=>m("login"),logo:a,theme:u,title:p.registerTitle,showNameFields:c,className:d,isModal:f});case"verify-email":return h.jsx(Gi,{email:x,onVerify:t,onSuccess:o,onResendCode:i,onBackClick:()=>m("login"),title:p.verifyTitle||"Vérification email",theme:u,className:d,isModal:f});case"forgot-password":return h.jsx(cu,{onRequestReset:k,onBackClick:()=>m("login"),title:p.forgotPasswordTitle,theme:u,className:d,isModal:f});case"verify-reset-code":return h.jsx(Gi,{email:x,onVerify:C,onResendCode:i,onBackClick:()=>m("forgot-password"),title:"Code de réinitialisation",theme:u,className:d,isModal:f});case"reset-password":return h.jsx(du,{email:x,code:b,onResetPassword:s,onSuccess:o,onBackClick:()=>m("login"),title:p.resetPasswordTitle,theme:u,className:d,isModal:f})}},M=()=>{const N={color:(u==null?void 0:u.primaryColor)||"#1877F2",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer",background:"none",border:"none",padding:0};return g==="login"?h.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"1rem",padding:"0 1.5rem",maxWidth:"28rem",width:"100%"},children:[h.jsx("button",{type:"button",onClick:()=>m("forgot-password"),style:N,children:"Mot de passe oublié ?"}),h.jsx("button",{type:"button",onClick:()=>m("register"),style:N,children:"Créer un compte"})]}):null};return h.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:"100%"},children:[E(),M()]})}function xf({isOpen:r,onClose:e,backdropBlur:t=!0,...n}){return r?h.jsxs("div",{style:{position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem"},children:[h.jsx("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",...t&&{backdropFilter:"blur(4px)"}},onClick:e}),h.jsxs("div",{style:{position:"relative",animation:"authFlowSlideUp 0.2s ease-out"},children:[h.jsx("button",{onClick:e,style:{position:"absolute",top:"0.75rem",right:"0.75rem",zIndex:10,background:"none",border:"none",padding:"0.25rem",cursor:"pointer",color:"#9CA3AF"},children:h.jsx("svg",{width:"24",height:"24",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:h.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),h.jsx(fu,{...n,isModal:!0})]}),h.jsx("style",{children:`
|
|
69
69
|
@keyframes authFlowSlideUp {
|
|
70
70
|
from {
|
|
71
71
|
opacity: 0;
|
package/dist/index.esm.js
CHANGED
|
@@ -4079,6 +4079,22 @@ class S2 {
|
|
|
4079
4079
|
}, s = await this.callLLM("tts", n);
|
|
4080
4080
|
return ((i = s.result) == null ? void 0 : i.audio) || s.result || "";
|
|
4081
4081
|
}
|
|
4082
|
+
// ===== IMAGE GENERATION =====
|
|
4083
|
+
/**
|
|
4084
|
+
* Generate an image from a text prompt
|
|
4085
|
+
* @param prompt - Text description of the image to generate
|
|
4086
|
+
* @param options - Generation options
|
|
4087
|
+
* @returns Base64 encoded PNG image data
|
|
4088
|
+
*/
|
|
4089
|
+
async generateImage(e, t) {
|
|
4090
|
+
var i;
|
|
4091
|
+
const n = {
|
|
4092
|
+
prompt: e,
|
|
4093
|
+
size: (t == null ? void 0 : t.size) ?? "1536x1024",
|
|
4094
|
+
quality: (t == null ? void 0 : t.quality) ?? "medium"
|
|
4095
|
+
};
|
|
4096
|
+
return ((i = (await this.callLLM("generate_image", n)).result) == null ? void 0 : i.image) || "";
|
|
4097
|
+
}
|
|
4082
4098
|
// ===== TRANSCRIPTION =====
|
|
4083
4099
|
/**
|
|
4084
4100
|
* Transcribe audio to text
|
|
@@ -5515,7 +5531,7 @@ function fu({
|
|
|
5515
5531
|
borderRadius: _.borderRadius,
|
|
5516
5532
|
padding: "1.5rem",
|
|
5517
5533
|
width: "100%",
|
|
5518
|
-
maxWidth: "
|
|
5534
|
+
maxWidth: "28rem",
|
|
5519
5535
|
...c && {
|
|
5520
5536
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
|
|
5521
5537
|
}
|
|
@@ -5738,7 +5754,7 @@ function Zd({
|
|
|
5738
5754
|
borderRadius: B.borderRadius,
|
|
5739
5755
|
padding: "1.5rem",
|
|
5740
5756
|
width: "100%",
|
|
5741
|
-
maxWidth: "
|
|
5757
|
+
maxWidth: "28rem",
|
|
5742
5758
|
...y && {
|
|
5743
5759
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
|
|
5744
5760
|
}
|
|
@@ -5955,7 +5971,7 @@ function Ea({
|
|
|
5955
5971
|
borderRadius: A.borderRadius,
|
|
5956
5972
|
padding: "1.5rem",
|
|
5957
5973
|
width: "100%",
|
|
5958
|
-
maxWidth: "
|
|
5974
|
+
maxWidth: "28rem",
|
|
5959
5975
|
...m && {
|
|
5960
5976
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
|
|
5961
5977
|
}
|
|
@@ -6119,7 +6135,7 @@ function rf({
|
|
|
6119
6135
|
borderRadius: x.borderRadius,
|
|
6120
6136
|
padding: "1.5rem",
|
|
6121
6137
|
width: "100%",
|
|
6122
|
-
maxWidth: "
|
|
6138
|
+
maxWidth: "28rem",
|
|
6123
6139
|
...d && {
|
|
6124
6140
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
|
|
6125
6141
|
}
|
|
@@ -6261,7 +6277,7 @@ function sf({
|
|
|
6261
6277
|
borderRadius: w.borderRadius,
|
|
6262
6278
|
padding: "1.5rem",
|
|
6263
6279
|
width: "100%",
|
|
6264
|
-
maxWidth: "
|
|
6280
|
+
maxWidth: "28rem",
|
|
6265
6281
|
...g && {
|
|
6266
6282
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)"
|
|
6267
6283
|
}
|
|
@@ -6504,7 +6520,7 @@ function of({
|
|
|
6504
6520
|
justifyContent: "space-between",
|
|
6505
6521
|
marginTop: "1rem",
|
|
6506
6522
|
padding: "0 1.5rem",
|
|
6507
|
-
maxWidth: "
|
|
6523
|
+
maxWidth: "28rem",
|
|
6508
6524
|
width: "100%"
|
|
6509
6525
|
}, children: [
|
|
6510
6526
|
/* @__PURE__ */ h.jsx("button", { type: "button", onClick: () => m("forgot-password"), style: T, children: "Mot de passe oublié ?" }),
|
package/package.json
CHANGED