@transai/connector-runner-microsoft-office365-email 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 0.16.0 (2026-03-19)
2
+
3
+ This was a version bump only for connector-runner-microsoft-office365-email to align it with other projects, there were no code changes.
4
+
1
5
  ## 0.15.0 (2026-03-19)
2
6
 
3
7
  This was a version bump only for connector-runner-microsoft-office365-email to align it with other projects, there were no code changes.
package/index.cjs CHANGED
@@ -195,7 +195,7 @@ ${"".padEnd(e)}${"^".repeat(i)}`}function KX(t){return Z3e(vv,t)}function Br(t){
195
195
  `):n).split(`
196
196
  `).map(r=>"> "+r).join(`
197
197
  `)})}function jv(t,e){if(!e)return t;let i=typeof e[0]=="string"?e[0]:"[",a=typeof e[1]=="string"?e[1]:"]";return i+t+a}function v$(t,e,i,a,n){let r=typeof e=="function"?e(t,a,n):t;return r[0]==="/"&&i?Y6e(i,"/")+r:r}function mme(t,e,i,a){let n=t.attribs||{},r=n.alt?n.alt:"",s=n.src?v$(n.src,a.pathRewrite,a.baseUrl,i.metadata,t):"",o=s?r?r+" "+jv(s,a.linkBrackets):jv(s,a.linkBrackets):r;i.addInline(o,{noWordTransform:!0})}function Qme(t,e,i,a){function n(){if(a.ignoreHref||!t.attribs||!t.attribs.href)return"";let s=t.attribs.href.replace(/^mailto:/,"");return a.noAnchorUrl&&s[0]==="#"?"":(s=v$(s,a.pathRewrite,a.baseUrl,i.metadata,t),s)}let r=n();if(!r)e(t.children,i);else{let s="";i.pushWordTransform(c=>(c&&(s+=c),c)),e(t.children,i),i.popWordTransform(),a.hideLinkHrefIfSameAsText&&r===s||i.addInline(s?" "+jv(r,a.linkBrackets):r,{noWordTransform:!0})}}function F$(t,e,i,a,n){let r=Xu(t,["parent","name"])==="li",s=0,o=(t.children||[]).filter(c=>c.type!=="text"||!/^\s*$/.test(c.data)).map(function(c){if(c.name!=="li")return{node:c,prefix:""};let u=r?n().trimStart():n();return u.length>s&&(s=u.length),{node:c,prefix:u}});if(o.length){i.openList({interRowLineBreaks:1,leadingLineBreaks:r?1:a.leadingLineBreaks||2,maxPrefixLength:s,prefixAlign:"left"});for(let{node:c,prefix:u}of o)i.openListItem({prefix:u}),e([c],i),i.closeListItem();i.closeList({trailingLineBreaks:r?1:a.trailingLineBreaks||2})}}function bme(t,e,i,a){let n=a.itemPrefix||" * ";return F$(t,e,i,a,()=>n)}function yme(t,e,i,a){let n=Number(t.attribs.start||"1"),r=wme(t.attribs.type);return F$(t,e,i,a,()=>" "+r(n++)+". ")}function wme(t="1"){switch(t){case"a":return e=>B$(e,"a");case"A":return e=>B$(e,"A");case"i":return e=>I$(e).toLowerCase();case"I":return e=>I$(e);case"1":default:return e=>e.toString()}}function Dme(t){let e=[],i=[];for(let a of t)a.startsWith(".")?e.push(a.substring(1)):a.startsWith("#")&&i.push(a.substring(1));return{classes:e,ids:i}}function vme(t,e){if(e===!0)return!0;if(!t)return!1;let{classes:i,ids:a}=Dme(e),n=(t.class||"").split(" "),r=(t.id||"").split(" ");return n.some(s=>i.includes(s))||r.some(s=>a.includes(s))}function Fme(t,e,i,a){return vme(t.attribs,i.options.tables)?S$(t,e,i,a):Sme(t,e,i,a)}function Sme(t,e,i,a){i.openBlock({leadingLineBreaks:a.leadingLineBreaks}),e(t.children,i),i.closeBlock({trailingLineBreaks:a.trailingLineBreaks})}function S$(t,e,i,a){i.openTable(),t.children.forEach(r),i.closeTable({tableToString:s=>xme(s,a.rowSpacing??0,a.colSpacing??3),leadingLineBreaks:a.leadingLineBreaks,trailingLineBreaks:a.trailingLineBreaks});function n(s){let o=+Xu(s,["attribs","colspan"])||1,c=+Xu(s,["attribs","rowspan"])||1;i.openTableCell({maxColumnWidth:a.maxColumnWidth}),e(s.children,i),i.closeTableCell({colspan:o,rowspan:c})}function r(s){if(s.type!=="tag")return;let o=a.uppercaseHeaderCells!==!1?c=>{i.pushWordTransform(u=>u.toUpperCase()),n(c),i.popWordTransform()}:n;switch(s.name){case"thead":case"tbody":case"tfoot":case"center":s.children.forEach(r);return;case"tr":{i.openTableRow();for(let c of s.children)if(c.type==="tag")switch(c.name){case"th":{o(c);break}case"td":{n(c);break}}i.closeTableRow();break}}}}var kme=Object.freeze({__proto__:null,anchor:Qme,blockquote:Ime,dataTable:S$,heading:Cme,horizontalLine:fme,image:mme,lineBreak:dme,orderedList:yme,paragraph:pme,pre:Bme,table:Fme,unorderedList:bme,wbr:Eme}),Rme={baseElements:{selectors:["body"],orderBy:"selectors",returnDomByDefault:!0},decodeEntities:!0,encodeCharacters:{},formatters:{},limits:{ellipsis:"...",maxBaseElements:void 0,maxChildNodes:void 0,maxDepth:void 0,maxInputLength:1<<24},longWordSplit:{forceWrapOnLimit:!1,wrapCharacters:[]},preserveNewlines:!1,selectors:[{selector:"*",format:"inline"},{selector:"a",format:"anchor",options:{baseUrl:null,hideLinkHrefIfSameAsText:!1,ignoreHref:!1,linkBrackets:["[","]"],noAnchorUrl:!0}},{selector:"article",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"aside",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"blockquote",format:"blockquote",options:{leadingLineBreaks:2,trailingLineBreaks:2,trimEmptyLines:!0}},{selector:"br",format:"lineBreak"},{selector:"div",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"footer",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"form",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"h1",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h2",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h3",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h4",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h5",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h6",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"header",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"hr",format:"horizontalLine",options:{leadingLineBreaks:2,length:void 0,trailingLineBreaks:2}},{selector:"img",format:"image",options:{baseUrl:null,linkBrackets:["[","]"]}},{selector:"main",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"nav",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"ol",format:"orderedList",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"p",format:"paragraph",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"pre",format:"pre",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"section",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"table",format:"table",options:{colSpacing:3,leadingLineBreaks:2,maxColumnWidth:60,rowSpacing:0,trailingLineBreaks:2,uppercaseHeaderCells:!0}},{selector:"ul",format:"unorderedList",options:{itemPrefix:" * ",leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"wbr",format:"wbr"}],tables:[],whitespaceCharacters:` \r
198
- \f\u200B`,wordwrap:80},Nme=(t,e,i)=>[...t,...e],k$=(t,e,i)=>[...e],Lme=(t,e,i)=>t.some(a=>typeof a=="object")?Nme(t,e):k$(t,e);function Mme(t={}){return t=(0,Wv.default)(Rme,t,{arrayMerge:k$,customMerge:e=>e==="selectors"?Lme:void 0}),t.formatters=Object.assign({},ume,kme,t.formatters),t.selectors=b$(t.selectors,(e=>e.selector)),Tme(t),V6e(t)}function R$(t,e={},i=void 0){return Mme(e)(t,i)}function Tme(t){if(t.tags){let i=Object.entries(t.tags).map(([a,n])=>({...n,selector:a||"*"}));t.selectors.push(...i),t.selectors=b$(t.selectors,(a=>a.selector))}function e(i,a,n){let r=a.pop();for(let s of a){let o=i[s];o||(o={},i[s]=o),i=o}i[r]=n}if(t.baseElement){let i=t.baseElement;e(t,["baseElements","selectors"],Array.isArray(i)?i:[i])}t.returnDomByDefault!==void 0&&e(t,["baseElements","returnDomByDefault"],t.returnDomByDefault);for(let i of t.selectors)i.format==="anchor"&&Xu(i,["options","noLinkBrackets"])&&e(i,["options","linkBrackets"],!1)}var iB=class{async parsedToMailMessage(e,i,a,n){let r=[],s=[];i.headers.forEach((B,m)=>{r.push({key:String(m),header:Array.isArray(B)?B.join(", "):String(B)})}),i.headerLines.forEach(({key:B,line:m})=>{s.push({key:B,line:m})});let o=this.#e(i.to),c=this.#e(i.cc),u=this.#e(i.bcc),h=this.#e(i.from),g=this.#e(i.replyTo),d=typeof i.html=="string"?i.html:void 0,E=i.text||(d?R$(d):""),f=await this.#i(i.attachments??[]);return ai.verbose(`Parsed mail "${i.subject}" with ${f.length} attachments, to: ${o}, from: ${h}, cc: ${c}, bcc: ${u}`),{deltaLink:a,extraData:n,id:i.messageId??e.id,originalMessageId:e.internetMessageId,attachmentsCount:(i.attachments??[]).length,attachments:f,headers:r,headerLines:s,subject:i.subject,conversationId:i.references?.[0],references:i.references,date:new Date(i.date??e.sentDateTime??new Date),to:o,from:h,fromDomain:h?.[0]?.split("@")[1],cc:c,bcc:u,replyTo:g,text:(E||"").trim(),html:d,messageId:i.messageId,inReplyTo:i.inReplyTo,categories:e.categories}}formatMailReplyBody(e,i){let a=e.from?.emailAddress?.address||"",n=e.toRecipients?.map(u=>u.emailAddress?.address).filter(Boolean).join("; ")||"",r=e.subject||"",s=e.sentDateTime?new Date(e.sentDateTime).toLocaleString():"",o=`<br><hr style="border:none;border-top:solid #b1b1b1 1px;height:1px;margin:16px 0 8px 0;" /><br>From: ${a}<br>Sent: ${s}<br>To: ${n}<br>Subject: ${r}<br><br>`,c=e.body?.content||"";return`${i}${o}${c}`}#e(e){if(!e)return;let i=a=>!a||typeof a!="object"?[]:"address"in a&&typeof a.address=="string"&&a.address?[a.address].filter(Boolean):"group"in a&&Array.isArray(a.group)?a.group.flatMap(i).filter(Boolean):[];if("value"in e&&Array.isArray(e.value)){let a=e.value.flatMap(i);return a.length?a:void 0}if(Array.isArray(e)){let a=e.flatMap(i);return a.length?a:void 0}return i(e)}async#i(e){let i=[];for(let a of e){let n=a.contentType?.toLowerCase().includes("application/json")||a.filename?.toLowerCase().endsWith(".json"),r=await this.#t(a);if(!r&&!n)continue;a=r??a;let s=Buffer.isBuffer(a.content)?a.content:await new Promise((o,c)=>{let u=[];a.content?.on?.("data",h=>u.push(h)),a.content?.once?.("end",()=>o(Buffer.concat(u))),a.content?.once?.("error",h=>{ai.warn(`Failed to read content of attachment ${a.filename}: ${h.message}`,{error:h}),c(h)})}).catch(o=>(ai.warn(`Failed to bufferize content of attachment ${a.filename}`,{error:o}),Buffer.from("")));i.push({id:a.cid??a.contentId??a.checksum??a.filename??"attachment.json",filename:a.filename||"attachment.json",contentType:"application/json",content:s.toString("utf-8")})}return ai.verbose(`Parsed ${i.length} JSON attachments from ${e.length} total attachments.`),[...e,...i]}async#t(e){if(!(e.contentType?.toLowerCase().includes("application/pdf")||e.filename?.toLowerCase().endsWith(".pdf")))return null;ai.verbose(`Parsing PDF attachment ${e.filename} to JSON...`);let a=await this.#a(e.content).catch(s=>(ai.warn("Failed to bufferize PDF attachment",s),null));if(!a)return null;let n=await(0,N$.default)(a).catch(s=>(ai.warn("Failed to perform pdf2md on buffer",s),null));if(!n)return null;ai.verbose(`Parsed PDF attachment ${e.filename} to JSON with length: ${n.length}`);let r=`${e.filename?.replace(/\.pdf$/i,"")||"attachment"}.json`;return{...e,filename:r,contentType:"application/json",content:Buffer.from(n)}}async#a(e){return Buffer.isBuffer(e)?e:new Promise((i,a)=>{let n=[];e.on("data",r=>n.push(r)),e.once("end",()=>i(Buffer.concat(n))),e.once("error",a)})}};var aB=class{#e;#i;#t;#a;constructor(e,i,a){if(this.#t=e,this.#a=ai.getInstance(),this.#e=i??new jE(this.#t.username,this.#t.emlTestMode??!1),this.#i=a??new iB,!this.#t.tenantId||!this.#t.clientId||!this.#t.clientSecret)throw new Error("Graph requires tenantId, clientId, and clientSecret")}async readMailbox(e,i,a,n=1){let r,s,o;try{if(await this.#r(),r=await this.#e.getFolder(e).catch(h=>(this.#a.warn(`Failed to fetch mailbox folder for ${e}: ${h?.message}`,{error:h}),null)),!r)throw new Error(`Mailbox folder not found: ${e}`);let{mails:c,deltaLink:u}=await this.#e.getMails(r,i,a,n).catch(h=>{throw this.#a.warn(`Failed to fetch mailbox mails for ${e}/${r}: ${h?.message}`,{error:h}),h});s=c,o=u}catch(c){let u=`Failed to read email from mailbox ${e}: ${c?.message}`;throw this.#a.warn(u,{err:c}),new Error(u)}this.#a.verbose(`Fetched ${s.length} mails from mailbox ${e} (deltaLink: ${o})`);try{let c=[];for(let u of s.filter(Boolean)){let h=await this.#n(u,r,o).catch(g=>(this.#a.warn(`Failed to parse mail [${r.id}] ${r.displayName} // [${u.id}] ${u.subject}: ${g?.message}`,{error:g}),null));h&&c.push(h)}return this.#a.verbose(`Parsed ${c.length} of ${s.length} mails from mailbox ${e}`),{mails:c.sort((u,h)=>u.date.getTime()-h.date.getTime()),deltaLink:o}}catch(c){let u=`Failed to parse emails from mailbox ${e}: ${c?.message}`;throw this.#a.warn(u,{err:c}),new Error(u)}}async getAttachments(e){let i=await this.#e.getMail(e);if(!i)throw new Error(`Message with ID ${e} not found`);return(await this.#e.listAttachments(i)).filter(n=>n.isInline!==!0).map(n=>({id:n.cid??n.id,contentType:n.contentType,filename:n.fileName??n.name,content:n.contentBytes?Buffer.from(n.contentBytes,"base64").toString("utf-8"):void 0,contentBytes:n.contentBytes?Buffer.from(n.contentBytes,"base64"):void 0}))}async reply(e,i,a,n=!0){await this.#r();let r=await this.#e.getMail(e);if(!r)throw new Error(`Message with ID ${e} not found`);let s=await this.#e.createReply(r,this.#i.formatMailReplyBody(r,a),i);if(!n)return this.#e.sendMail(s);let o=await this.#e.getFolder("Drafts");if(!o)throw new Error("Folder not found: Drafts");return this.#e.moveMailToFolder(s,o)}async addCategory(e,...i){await this.#r();let a=await this.#e.getMail(e);if(!a)throw new Error(`Message with ID ${e} not found`);let r=(await this.#e.getMailCategories(a))?.categories||[];await this.#e.updateMailCategories(a,{categories:Array.from(new Set([...r,...i]).values())})}async removeCategory(e,...i){await this.#r();let a=await this.#e.getMail(e);if(!a)throw new Error(`Message with ID ${e} not found`);let r=(await this.#e.getMailCategories(a))?.categories||[];await this.#e.updateMailCategories(a,{categories:r.filter(s=>!i.includes(s))})}async#r(){this.#a.verbose(`Initializing Microsoft Office 365 mail client for ${this.#t.username}`),await this.#e.init(this.#t.tenantId,this.#t.clientId,this.#t.clientSecret).catch(e=>{let i=`Failed to initialize Microsoft Office 365 mail client for ${this.#t.username}: ${e?.message}`;throw this.#a.warn(i,{err:e}),new Error(i)}),this.#a.debug(`Microsoft Office 365 mail client initialized for ${this.#t.username}`)}async#n(e,i,a){try{let n=await this.#e.getFullMail(i,e).catch(s=>{throw this.#a.warn(`Failed to fetch full mail for [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${s?.message}`,{error:s}),s}),r=null;return this.#t.emlTestMode&&(r=(await this.#e.getExtraData(i,e).catch(()=>null))?.toString()??null),this.#a.verbose(`Fetched email [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}`),await this.#i.parsedToMailMessage(e,n,a,r).catch(s=>{throw this.#a.warn(`Failed to parse full mail for [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${s?.message}`,{error:s}),s})}catch(n){this.#a.warn(`Failed to read full mail and parse: [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${n?.message}`,{err:n});return}}};var nB=class{#e;#i;constructor(e,i){this.#e=e,this.#i=i}get callbackFunctionChain(){return this.#t(this.#e.receiver.emitEventType(this.#e.receiver.responses.created()))}#t(e){return async(i,a)=>{try{this.#e.logger.debug(`Apply templates on payload: ${JSON.stringify(i.payload)}, action: ${JSON.stringify(a)}`);let n=a.config.parsedTemplates,r=n.action({inputs:i.payload}).trim(),s=n.params({inputs:i.payload}).trim();if(i.testRun)return this.#e.logger.info(`Test run for ${i.eventId} with payload ${s} to action ${r}`),e(i);this.#e.logger.debug(`Parsed action: ${r}, parameters: ${s}`);let o=JSON.parse(s);this.#e.logger.debug(`Parsed params json: ${JSON.stringify(o)}`);let c=this.#a(o.mailboxIdentifier);switch(r){case"REPLY":await c.reply(o.messageId,o.from,o.mailBody,!0);break;case"FORWARD":break;case"SEND":break;case"CATEGORY_ADD":await c.addCategory(o.messageId,o.category);break;case"CATEGORY_REMOVE":await c.removeCategory(o.messageId,o.category);break;default:this.#e.logger.error(`Unknown action type: ${r} in message ${i.eventId}`)}return e(i)}catch(n){return this.#e.receiver.responses.internalServerError(n instanceof Error?n.message:"Unknown error occurred")(i)}}}#a(e){let i=this.#i.get(e);if(!i)throw new Error(`Mail client not found for mailbox identifier: ${e}`);return i}};var rB=class{constructor(e,i,a){this.DEFAULT_EVENT_TTL=36e5;this.DEFAULT_INTERVAL_SECONDS=60;this.MAX_PROCESSING_TRIES=10;this.#n=!1;this.#o=0;this.#e=e,this.#i=a,this.#t=i,this.#a=this.#e.logger;let n=this.#t.attachmentDestination??this.#e.config.attachmentDestination;this.#r=n?this.#e.files(n):void 0}#e;#i;#t;#a;#r;#n;#o;get name(){return`mail-processor-${this.#t.mailboxIdentifier}-${this.#t.mailbox}`}async onRun(){if(this.#n){this.#o>this.MAX_PROCESSING_TRIES&&(this.#e.telemetry.increment("microsoft_office365_email.mailbox.exceeded_tries"),this.#a.error(`Exceeded processingTries for mailbox processor: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),process.exit(1)),this.#e.telemetry.increment("microsoft_office365_email.mailbox.already_processing"),this.#a.debug(`Mailsource processor service is already processing: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),this.#o+=1;return}this.#n=!0;try{let e=await this.#c(this.#t);this.#e.telemetry.increment("microsoft_office365_email.mailbox.processed",e)}catch(e){throw this.#e.telemetry.increment("microsoft_office365_email.mailbox.error"),this.#a.warn(`Error processing mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`,JSON.stringify(e)),this.#n=!1,this.#o+=1,e}this.#n=!1,this.#o=0}async#c(e){this.#a.debug(`Processing mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`);let i=new Date,a=await this.#e.offsetStore.getOffset(`${this.#t.offsetFilePrefix??"offset"}_${this.#t.mailboxIdentifier}`),n=a?.deltaLink,r=a?.dateTime;this.#a.verbose(`Last message ID of mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${n}`);let s=await this.#i.readMailbox(e.mailbox,n?String(n):void 0,r?String(r):void 0,e.limit??1).catch(c=>{throw this.#a.error(`Error reading mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${c?.message}`,{error:c}),c});this.#a.debug(`Read ${s.mails.length} mails from mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`);let o=await this.#l(e.mailboxIdentifier,e.mailbox,...s.mails).catch(c=>{throw this.#a.error(`Error storing mails for mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${c?.message}`,{error:c}),c});return this.#e.offsetStore.setOffset({timestamp:i.getTime(),dateTime:i.toISOString(),id:s.mails?.reverse()[0]?.originalMessageId??a?.originalMessageId,...s.deltaLink?{deltaLink:s.deltaLink}:{}},`${this.#t.offsetFilePrefix??"offset"}_${this.#t.mailboxIdentifier}`),await this.#e.offsetStore.flush(),o}async#l(e,i,...a){if(a.length===0)return this.#a.debug(`No new messages found for mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),0;await this.#A(e,i,...a);let n=a.map(r=>({...r,attachments:(r.attachments??[]).map(s=>({...s,content:s.contentType==="application/json"?s.content:void 0,contentBytes:void 0}))}));return this.#a.debug(`Fetched ${n.length} new messages for mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}, sending as ${this.#t.type}`),this.#t.type==="metric"?await this.#e.sender.metricsLegacy(n,{keyField:"messageId",collection:this.#e.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}):await this.#e.sender.documents(n,{keyField:"messageId",collection:this.#e.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}),this.#a.info(`Fetched ${n.length} new messages for mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}, sent as ${this.#t.type}`),n.length}async#A(e,i,...a){if(!this.#r)return;let n=a.filter(r=>r.attachments.length>0);if(n.length!==0){this.#a.verbose(`Storing attachments for ${n.length} messages in mailbox ${this.#t.mailboxIdentifier}/${i}...`);for(let r of n)await this.#u(r,e,i).catch(s=>{this.#a.error(`Failed to store attachments of mail ${this.#t.mailboxIdentifier}/${i}/${r.id}`,s)})}}async#u(e,i,a){let{attachments:n}=e;if(n.length===0){this.#a.verbose(`No attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}`);return}this.#a.verbose(`Found ${n.length} attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}, storing to ${typeof this.#r}`);let r=[];for(let s of n){if(!s.contentBytes&&!s.content)continue;let o=`${i}/${a}/${encodeURIComponent(e.id)}/${s.filename}`;if(this.#a.verbose(`Storing mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}"...`),!await this.#r.write(o,s.contentBytes??s.content).catch(u=>(this.#a.error(`Failed to store mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}" due to: ${u.message}`,u),!1))){this.#a.verbose(`Storing mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}" was not succesful`);continue}this.#a.verbose(`Stored mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}"`),r.push({id:s.id,dsn:this.#r.pathAsDsn(o),filename:s.filename,contentType:s.contentType})}this.#a.debug(`Stored ${r.length} of ${e.attachments.length} attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}`),e.storedAttachments=[...e.storedAttachments??[],...r]}};var zv=class extends Jx{constructor(i,a){super(i,a);this.#e=new Map;this.init=async()=>{let{config:i}=this.connectorSDK;await Promise.all(i.mailboxes.map(async a=>{let n=this.#e.get(a.mailboxIdentifier??i.mailConfig.username);if(!n){this.connectorSDK.logger.error(`Mail client not found for mailboxIdentifier: ${a.mailboxIdentifier}, could not setup processor for mailbox: ${a.mailbox}`);return}let r=new rB(this.connectorSDK,a,n);await this.connectorSDK.processing.registerInterval(a.interval??r.DEFAULT_INTERVAL_SECONDS,r,{immediate:!0})}))};let{config:n}=this.connectorSDK;n.mailboxes.forEach(r=>{let s=r.mailboxIdentifier??n.mailConfig.username;this.#e.set(s,new aB({...n.mailConfig,username:s}))}),this.#i=new nB(this.connectorSDK,this.#e),this.callbackFunction=this.#i.callbackFunctionChain}#e;#i};0&&(module.exports={ConnectorRunnerMicrosoftOffice365Email});
198
+ \f\u200B`,wordwrap:80},Nme=(t,e,i)=>[...t,...e],k$=(t,e,i)=>[...e],Lme=(t,e,i)=>t.some(a=>typeof a=="object")?Nme(t,e):k$(t,e);function Mme(t={}){return t=(0,Wv.default)(Rme,t,{arrayMerge:k$,customMerge:e=>e==="selectors"?Lme:void 0}),t.formatters=Object.assign({},ume,kme,t.formatters),t.selectors=b$(t.selectors,(e=>e.selector)),Tme(t),V6e(t)}function R$(t,e={},i=void 0){return Mme(e)(t,i)}function Tme(t){if(t.tags){let i=Object.entries(t.tags).map(([a,n])=>({...n,selector:a||"*"}));t.selectors.push(...i),t.selectors=b$(t.selectors,(a=>a.selector))}function e(i,a,n){let r=a.pop();for(let s of a){let o=i[s];o||(o={},i[s]=o),i=o}i[r]=n}if(t.baseElement){let i=t.baseElement;e(t,["baseElements","selectors"],Array.isArray(i)?i:[i])}t.returnDomByDefault!==void 0&&e(t,["baseElements","returnDomByDefault"],t.returnDomByDefault);for(let i of t.selectors)i.format==="anchor"&&Xu(i,["options","noLinkBrackets"])&&e(i,["options","linkBrackets"],!1)}var iB=class{async parsedToMailMessage(e,i,a,n){let r=[],s=[];i.headers.forEach((B,m)=>{r.push({key:String(m),header:Array.isArray(B)?B.join(", "):String(B)})}),i.headerLines.forEach(({key:B,line:m})=>{s.push({key:B,line:m})});let o=this.#e(i.to),c=this.#e(i.cc),u=this.#e(i.bcc),h=this.#e(i.from),g=this.#e(i.replyTo),d=typeof i.html=="string"?i.html:void 0,E=i.text||(d?R$(d):""),f=await this.#i(i.attachments??[]);return ai.verbose(`Parsed mail "${i.subject}" with ${f.length} attachments, to: ${o}, from: ${h}, cc: ${c}, bcc: ${u}`),{deltaLink:a,extraData:n,id:i.messageId??e.id,originalMessageId:e.internetMessageId,attachmentsCount:(i.attachments??[]).length,attachments:f,headers:r,headerLines:s,subject:i.subject,conversationId:i.references?.[0],references:i.references,date:new Date(i.date??e.sentDateTime??new Date),to:o,from:h,fromDomain:h?.[0]?.split("@")[1],cc:c,bcc:u,replyTo:g,text:(E||"").trim(),html:d,messageId:i.messageId,inReplyTo:i.inReplyTo,categories:e.categories}}formatMailReplyBody(e,i){let a=e.from?.emailAddress?.address||"",n=e.toRecipients?.map(u=>u.emailAddress?.address).filter(Boolean).join("; ")||"",r=e.subject||"",s=e.sentDateTime?new Date(e.sentDateTime).toLocaleString():"",o=`<br><hr style="border:none;border-top:solid #b1b1b1 1px;height:1px;margin:16px 0 8px 0;" /><br>From: ${a}<br>Sent: ${s}<br>To: ${n}<br>Subject: ${r}<br><br>`,c=e.body?.content||"";return`${i}${o}${c}`}#e(e){if(!e)return;let i=a=>!a||typeof a!="object"?[]:"address"in a&&typeof a.address=="string"&&a.address?[a.address].filter(Boolean):"group"in a&&Array.isArray(a.group)?a.group.flatMap(i).filter(Boolean):[];if("value"in e&&Array.isArray(e.value)){let a=e.value.flatMap(i);return a.length?a:void 0}if(Array.isArray(e)){let a=e.flatMap(i);return a.length?a:void 0}return i(e)}async#i(e){let i=[];for(let a of e){let n=a.contentType?.toLowerCase().includes("application/json")||a.filename?.toLowerCase().endsWith(".json"),r=await this.#t(a);if(!r&&!n)continue;a=r??a;let s=Buffer.isBuffer(a.content)?a.content:await new Promise((o,c)=>{let u=[];a.content?.on?.("data",h=>u.push(h)),a.content?.once?.("end",()=>o(Buffer.concat(u))),a.content?.once?.("error",h=>{ai.warn(`Failed to read content of attachment ${a.filename}: ${h.message}`,{error:h}),c(h)})}).catch(o=>(ai.warn(`Failed to bufferize content of attachment ${a.filename}`,{error:o}),Buffer.from("")));i.push({id:a.cid??a.contentId??a.checksum??a.filename??"attachment.json",filename:a.filename||"attachment.json",contentType:"application/json",content:s.toString()})}return ai.verbose(`Parsed ${i.length} JSON attachments from ${e.length} total attachments.`),[...e,...i]}async#t(e){if(!(e.contentType?.toLowerCase().includes("application/pdf")||e.filename?.toLowerCase().endsWith(".pdf")))return null;ai.verbose(`Parsing PDF attachment ${e.filename} to JSON...`);let a=await this.#a(e.content).catch(s=>(ai.warn("Failed to bufferize PDF attachment",s),null));if(!a)return null;let n=await(0,N$.default)(a).catch(s=>(ai.warn("Failed to perform pdf2md on buffer",s),null));if(!n)return null;ai.verbose(`Parsed PDF attachment ${e.filename} to JSON with length: ${n.length}`);let r=`${e.filename?.replace(/\.pdf$/i,"")||"attachment"}.json`;return{...e,filename:r,contentType:"application/json",content:Buffer.from(n)}}async#a(e){return Buffer.isBuffer(e)?e:new Promise((i,a)=>{let n=[];e.on("data",r=>n.push(r)),e.once("end",()=>i(Buffer.concat(n))),e.once("error",a)})}};var aB=class{#e;#i;#t;#a;constructor(e,i,a){if(this.#t=e,this.#a=ai.getInstance(),this.#e=i??new jE(this.#t.username,this.#t.emlTestMode??!1),this.#i=a??new iB,!this.#t.tenantId||!this.#t.clientId||!this.#t.clientSecret)throw new Error("Graph requires tenantId, clientId, and clientSecret")}async readMailbox(e,i,a,n=1){let r,s,o;try{if(await this.#r(),r=await this.#e.getFolder(e).catch(h=>(this.#a.warn(`Failed to fetch mailbox folder for ${e}: ${h?.message}`,{error:h}),null)),!r)throw new Error(`Mailbox folder not found: ${e}`);let{mails:c,deltaLink:u}=await this.#e.getMails(r,i,a,n).catch(h=>{throw this.#a.warn(`Failed to fetch mailbox mails for ${e}/${r}: ${h?.message}`,{error:h}),h});s=c,o=u}catch(c){let u=`Failed to read email from mailbox ${e}: ${c?.message}`;throw this.#a.warn(u,{err:c}),new Error(u)}this.#a.verbose(`Fetched ${s.length} mails from mailbox ${e} (deltaLink: ${o})`);try{let c=[];for(let u of s.filter(Boolean)){let h=await this.#n(u,r,o).catch(g=>(this.#a.warn(`Failed to parse mail [${r.id}] ${r.displayName} // [${u.id}] ${u.subject}: ${g?.message}`,{error:g}),null));h&&c.push(h)}return this.#a.verbose(`Parsed ${c.length} of ${s.length} mails from mailbox ${e}`),{mails:c.sort((u,h)=>u.date.getTime()-h.date.getTime()),deltaLink:o}}catch(c){let u=`Failed to parse emails from mailbox ${e}: ${c?.message}`;throw this.#a.warn(u,{err:c}),new Error(u)}}async getAttachments(e){let i=await this.#e.getMail(e);if(!i)throw new Error(`Message with ID ${e} not found`);let a=await this.#e.listAttachments(i),n=new TextDecoder("utf-8",{fatal:!0});return a.filter(r=>r.isInline!==!0).map(r=>{let s=r.contentBytes?.length>0?Buffer.from(r.contentBytes,"base64"):void 0,o;try{s&&(o=n.decode(s??new Uint8Array,{}))}catch(c){this.#a.warn(`Failed to decode content: ${c?.message??c}`)}return{id:r.cid??r.id,contentType:r.contentType,filename:r.fileName??r.name,content:o,contentBytes:s}})}async reply(e,i,a,n=!0){await this.#r();let r=await this.#e.getMail(e);if(!r)throw new Error(`Message with ID ${e} not found`);let s=await this.#e.createReply(r,this.#i.formatMailReplyBody(r,a),i);if(!n)return this.#e.sendMail(s);let o=await this.#e.getFolder("Drafts");if(!o)throw new Error("Folder not found: Drafts");return this.#e.moveMailToFolder(s,o)}async addCategory(e,...i){await this.#r();let a=await this.#e.getMail(e);if(!a)throw new Error(`Message with ID ${e} not found`);let r=(await this.#e.getMailCategories(a))?.categories||[];await this.#e.updateMailCategories(a,{categories:Array.from(new Set([...r,...i]).values())})}async removeCategory(e,...i){await this.#r();let a=await this.#e.getMail(e);if(!a)throw new Error(`Message with ID ${e} not found`);let r=(await this.#e.getMailCategories(a))?.categories||[];await this.#e.updateMailCategories(a,{categories:r.filter(s=>!i.includes(s))})}async#r(){this.#a.verbose(`Initializing Microsoft Office 365 mail client for ${this.#t.username}`),await this.#e.init(this.#t.tenantId,this.#t.clientId,this.#t.clientSecret).catch(e=>{let i=`Failed to initialize Microsoft Office 365 mail client for ${this.#t.username}: ${e?.message}`;throw this.#a.warn(i,{err:e}),new Error(i)}),this.#a.debug(`Microsoft Office 365 mail client initialized for ${this.#t.username}`)}async#n(e,i,a){try{let n=await this.#e.getFullMail(i,e).catch(s=>{throw this.#a.warn(`Failed to fetch full mail for [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${s?.message}`,{error:s}),s}),r=null;return this.#t.emlTestMode&&(r=(await this.#e.getExtraData(i,e).catch(()=>null))?.toString()??null),this.#a.verbose(`Fetched email [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}`),await this.#i.parsedToMailMessage(e,n,a,r).catch(s=>{throw this.#a.warn(`Failed to parse full mail for [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${s?.message}`,{error:s}),s})}catch(n){this.#a.warn(`Failed to read full mail and parse: [${i.id}] ${i.displayName} // [${e.id}] ${e.subject}: ${n?.message}`,{err:n});return}}};var nB=class{#e;#i;constructor(e,i){this.#e=e,this.#i=i}get callbackFunctionChain(){return this.#t(this.#e.receiver.emitEventType(this.#e.receiver.responses.created()))}#t(e){return async(i,a)=>{try{this.#e.logger.debug(`Apply templates on payload: ${JSON.stringify(i.payload)}, action: ${JSON.stringify(a)}`);let n=a.config.parsedTemplates,r=n.action({inputs:i.payload}).trim(),s=n.params({inputs:i.payload}).trim();if(i.testRun)return this.#e.logger.info(`Test run for ${i.eventId} with payload ${s} to action ${r}`),e(i);this.#e.logger.debug(`Parsed action: ${r}, parameters: ${s}`);let o=JSON.parse(s);this.#e.logger.debug(`Parsed params json: ${JSON.stringify(o)}`);let c=this.#a(o.mailboxIdentifier);switch(r){case"REPLY":await c.reply(o.messageId,o.from,o.mailBody,!0);break;case"FORWARD":break;case"SEND":break;case"CATEGORY_ADD":await c.addCategory(o.messageId,o.category);break;case"CATEGORY_REMOVE":await c.removeCategory(o.messageId,o.category);break;default:this.#e.logger.error(`Unknown action type: ${r} in message ${i.eventId}`)}return e(i)}catch(n){return this.#e.receiver.responses.internalServerError(n instanceof Error?n.message:"Unknown error occurred")(i)}}}#a(e){let i=this.#i.get(e);if(!i)throw new Error(`Mail client not found for mailbox identifier: ${e}`);return i}};var rB=class{constructor(e,i,a){this.DEFAULT_EVENT_TTL=36e5;this.DEFAULT_INTERVAL_SECONDS=60;this.MAX_PROCESSING_TRIES=10;this.#n=!1;this.#o=0;this.#e=e,this.#i=a,this.#t=i,this.#a=this.#e.logger;let n=this.#t.attachmentDestination??this.#e.config.attachmentDestination;this.#r=n?this.#e.files(n):void 0}#e;#i;#t;#a;#r;#n;#o;get name(){return`mail-processor-${this.#t.mailboxIdentifier}-${this.#t.mailbox}`}async onRun(){if(this.#n){this.#o>this.MAX_PROCESSING_TRIES&&(this.#e.telemetry.increment("microsoft_office365_email.mailbox.exceeded_tries"),this.#a.error(`Exceeded processingTries for mailbox processor: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),process.exit(1)),this.#e.telemetry.increment("microsoft_office365_email.mailbox.already_processing"),this.#a.debug(`Mailsource processor service is already processing: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),this.#o+=1;return}this.#n=!0;try{let e=await this.#c(this.#t);this.#e.telemetry.increment("microsoft_office365_email.mailbox.processed",e)}catch(e){throw this.#e.telemetry.increment("microsoft_office365_email.mailbox.error"),this.#a.warn(`Error processing mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`,JSON.stringify(e)),this.#n=!1,this.#o+=1,e}this.#n=!1,this.#o=0}async#c(e){this.#a.debug(`Processing mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`);let i=new Date,a=await this.#e.offsetStore.getOffset(`${this.#t.offsetFilePrefix??"offset"}_${this.#t.mailboxIdentifier}`),n=a?.deltaLink,r=a?.dateTime;this.#a.verbose(`Last message ID of mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${n}`);let s=await this.#i.readMailbox(e.mailbox,n?String(n):void 0,r?String(r):void 0,e.limit??1).catch(c=>{throw this.#a.error(`Error reading mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${c?.message}`,{error:c}),c});this.#a.debug(`Read ${s.mails.length} mails from mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`);let o=await this.#l(e.mailboxIdentifier,e.mailbox,...s.mails).catch(c=>{throw this.#a.error(`Error storing mails for mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}: ${c?.message}`,{error:c}),c});return this.#e.offsetStore.setOffset({timestamp:i.getTime(),dateTime:i.toISOString(),id:s.mails?.reverse()[0]?.originalMessageId??a?.originalMessageId,...s.deltaLink?{deltaLink:s.deltaLink}:{}},`${this.#t.offsetFilePrefix??"offset"}_${this.#t.mailboxIdentifier}`),await this.#e.offsetStore.flush(),o}async#l(e,i,...a){if(a.length===0)return this.#a.debug(`No new messages found for mailbox: ${this.#t.mailboxIdentifier}/${this.#t.mailbox}`),0;await this.#A(e,i,...a);let n=a.map(r=>({...r,attachments:(r.attachments??[]).map(s=>({...s,content:s.contentType==="application/json"?s.content:void 0,contentBytes:void 0}))}));return this.#a.debug(`Fetched ${n.length} new messages for mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}, sending as ${this.#t.type}`),this.#t.type==="metric"?await this.#e.sender.metricsLegacy(n,{keyField:"messageId",collection:this.#e.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}):await this.#e.sender.documents(n,{keyField:"messageId",collection:this.#e.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}),this.#a.info(`Fetched ${n.length} new messages for mailbox ${this.#t.mailboxIdentifier}/${this.#t.mailbox}, sent as ${this.#t.type}`),n.length}async#A(e,i,...a){if(!this.#r)return;let n=a.filter(r=>r.attachments.length>0);if(n.length!==0){this.#a.verbose(`Storing attachments for ${n.length} messages in mailbox ${this.#t.mailboxIdentifier}/${i}...`);for(let r of n)await this.#u(r,e,i).catch(s=>{this.#a.error(`Failed to store attachments of mail ${this.#t.mailboxIdentifier}/${i}/${r.id}`,s)})}}async#u(e,i,a){let{attachments:n}=e;if(n.length===0){this.#a.verbose(`No attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}`);return}this.#a.verbose(`Found ${n.length} attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}, storing to ${typeof this.#r}`);let r=[];for(let s of n){if(!s.contentBytes&&!s.content)continue;let o=`${i}/${a}/${encodeURIComponent(e.id)}/${s.filename}`;if(this.#a.verbose(`Storing mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}"...`),!await this.#r.write(o,s.contentBytes??s.content).catch(u=>(this.#a.error(`Failed to store mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}" due to: ${u.message}`,u),!1))){this.#a.verbose(`Storing mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}" was not succesful`);continue}this.#a.verbose(`Stored mail ${this.#t.mailboxIdentifier}/${a}/${e.id} attachment "${o}"`),r.push({id:s.id,dsn:this.#r.pathAsDsn(o),filename:s.filename,contentType:s.contentType})}this.#a.debug(`Stored ${r.length} of ${e.attachments.length} attachments for mail ${this.#t.mailboxIdentifier}/${a}/${e.id}`),e.storedAttachments=[...e.storedAttachments??[],...r]}};var zv=class extends Jx{constructor(i,a){super(i,a);this.#e=new Map;this.init=async()=>{let{config:i}=this.connectorSDK;await Promise.all(i.mailboxes.map(async a=>{let n=this.#e.get(a.mailboxIdentifier??i.mailConfig.username);if(!n){this.connectorSDK.logger.error(`Mail client not found for mailboxIdentifier: ${a.mailboxIdentifier}, could not setup processor for mailbox: ${a.mailbox}`);return}let r=new rB(this.connectorSDK,a,n);await this.connectorSDK.processing.registerInterval(a.interval??r.DEFAULT_INTERVAL_SECONDS,r,{immediate:!0})}))};let{config:n}=this.connectorSDK;n.mailboxes.forEach(r=>{let s=r.mailboxIdentifier??n.mailConfig.username;this.#e.set(s,new aB({...n.mailConfig,username:s}))}),this.#i=new nB(this.connectorSDK,this.#e),this.callbackFunction=this.#i.callbackFunctionChain}#e;#i};0&&(module.exports={ConnectorRunnerMicrosoftOffice365Email});
199
199
  /*! Bundled license information:
200
200
 
201
201
  safe-buffer/index.js: