openbird 3.2.6 → 3.2.7
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/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -31,7 +31,7 @@ ${l.text||""}
|
|
|
31
31
|
`);case"ordered_list":{let e=Number.isInteger(l.start)&&l.start>0?l.start:1;return(l.items||[]).map((t,V)=>`${e+V}. ${this.renderRichTextListItemAsMarkdown(t)}`).join(`
|
|
32
32
|
`)}case"list_item":return this.renderRichTextInlineNodesAsMarkdown(l.children||[]);case"code_block":return`${l.language?`\`\`\`${l.language}`:"```"}
|
|
33
33
|
${l.text||""}
|
|
34
|
-
\`\`\``;case"code":return`\`${l.text||""}\``;case"text":return this.applyMarkdownMarks(l.text||"",l.marks||[]);case"mention":return l.text||"";case"link":{let e=this.applyMarkdownMarks(l.text||l.url||"",l.marks||[]);return l.url?`[${e}](${l.url})`:e}case"image":return l.imageKey?``:l.alt||"";default:return""}}static renderRichTextInlineNodesAsMarkdown(l){let e=[],t=[],V=()=>{t.length!==0&&(e.push(this.renderRichTextTextRunAsMarkdown(t)),t=[])};for(let o of l||[]){if(o?.type==="text"){t.push(o);continue}V(),e.push(this.renderRichTextAstAsMarkdown(o))}return V(),e.join("")}static renderRichTextListItemAsMarkdown(l){return this.renderRichTextAstAsMarkdown(l).replace(/\n+/g," ").trim()}static renderRichTextTextRunAsMarkdown(l){let e=(l||[]).filter(R=>R?.type==="text");if(e.length===0)return"";if(e.some(R=>(R.marks||[]).includes("underline")))return this.renderRichTextTextRunAsHtml(e);let t=["bold","strikethrough","italic","underline"],V={bold:{open:"**",close:"**"},strikethrough:{open:"~~",close:"~~"},italic:{open:"_",close:"_"},underline:{open:"<u>",close:"</u>"}},o="",c=[],a=R=>{let A=0;for(;A<c.length&&A<R.length&&c[A]===R[A];)A+=1;for(let n=c.length-1;n>=A;n-=1)o+=V[c[n]].close;for(let n=A;n<R.length;n+=1)o+=V[R[n]].open;c=R};for(let R of l){let A=t.filter(n=>(R.marks||[]).includes(n));a(A),o+=R.text||""}return a([]),o}static renderRichTextTextRunAsHtml(l){let e=["bold","strikethrough","italic","underline"],t={bold:"strong",italic:"em",strikethrough:"del",underline:"u"},V="",o=[],c=a=>{let R=0;for(;R<o.length&&R<a.length&&o[R]===a[R];)R+=1;for(let A=o.length-1;A>=R;A-=1)V+=`</${t[o[A]]}>`;for(let A=R;A<a.length;A+=1)V+=`<${t[a[A]]}>`;o=a};for(let a of l){let R=e.filter(A=>(a.marks||[]).includes(A));c(R),V+=this.escapeHtmlText(a.text||"")}return c([]),V}static escapeHtmlText(l){return String(l).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}static applyMarkdownMarks(l,e=[]){let t=l,V=new Set(e);return V.has("strikethrough")&&(t=`~~${t}~~`),V.has("italic")&&(t=`*${t}*`),V.has("bold")&&(t=`**${t}**`),V.has("underline")&&(t=`<u>${t}</u>`),t}static parseCardContent(l){if(!l||l.length===0)return{summary:"[\u7A7A\u5361\u7247]"};let e=this.extractCardJson(l);if(e)try{let o=JSON.parse(e);return this.parseCardJson(o,e)}catch{}try{let o=Buffer.from(l).toString("utf8");if(o.startsWith("{")){let c=JSON.parse(o);return this.parseCardJson(c,o)}}catch{}let t=Buffer.from(l),V=t.indexOf("{");if(V>=0){let o=0,c=-1;for(let a=V;a<t.length;a++)if(t[a]===123&&o++,t[a]===125&&o--,o===0){c=a;break}if(c>V)try{let a=t.slice(V,c+1).toString("utf8"),R=JSON.parse(a);return this.parseCardJson(R,a)}catch{}}return{summary:"[\u5361\u7247\u6D88\u606F]",rawContentBase64:Buffer.from(l).toString("base64")}}static extractCardJson(l){let e=Buffer.from(l),t=0;for(;t<e.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(e,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(e,t);if(t+=A,t+R>e.length)break;let n=e.subarray(t,t+R);if(t+=R,R>2&&n[0]===123)try{let h=n.toString("utf8");return JSON.parse(h),h}catch{}if(R>10){let h=this.extractCardJson(n);if(h)return h}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(e,t);t+=R}else if(c===5)t+=4;else if(c===1)t+=8;else break}return null}static parseCardJson(l,e){let t={json:l,rawJson:e,title:null,summary:null};if(t.title=this.pickFirstText([l.header?.title?.content,l.header?.property?.title?.content,l.header?.property?.title?.property?.content,l.header?.property?.mainTitle?.content,l.header?.property?.mainTitle?.property?.content,l.header?.property?.subtitle?.content,l.header?.property?.subtitle?.property?.content]),t.summary=this.pickFirstText([l.config?.summary?.content,l.config?.summary,l.summary?.content,l.summary]),!t.summary)if(t.title)t.summary=`[\u5361\u7247] ${t.title}`;else{let V=this.extractCardBodyText(l);t.summary=V?`[\u5361\u7247] ${V.substring(0,50)}`:"[\u5361\u7247\u6D88\u606F]"}return t}static extractCardBodyText(l){let e=[],t=new Set,V=c=>{if(typeof c!="string")return;let a=c.replace(/\s+/g," ").trim();a&&(/^https?:\/\//.test(a)||/^#[0-9a-fA-F]{6,8}$/.test(a)||/^(default|normal|small|medium|large)$/i.test(a)||t.has(a)||(t.add(a),e.push(a)))},o=(c,a=0)=>{if(!(!c||a>10||e.length>=8)){if(typeof c=="string"){V(c);return}if(Array.isArray(c)){for(let R of c)if(o(R,a+1),e.length>=8)break;return}typeof c=="object"&&(V(c.content),V(c.text),V(c.title),V(c.subtitle),c.text&&typeof c.text=="object"&&(V(c.text.content),V(c.text.text)),c.property&&typeof c.property=="object"&&(V(c.property.content),V(c.property.text),V(c.property.title),V(c.property.subtitle)),o(c.newBody,a+1),o(c.body,a+1),o(c.elements,a+1),o(c.fields,a+1),o(c.columns,a+1),o(c.actions,a+1),o(c.header,a+1),o(c.property,a+1),o(c.text,a+1),o(c.title,a+1),o(c.subtitle,a+1))}};return o(l),e.slice(0,3).join(" ")}static pickFirstText(l){for(let e of l){if(typeof e!="string")continue;let t=e.trim();if(t)return t}return null}static parseTextProperty(l){if(!l||l.length===0)return"";try{return G(ne,l).content||""}catch{let t=Buffer.from(l),V=0;for(;V<t.length;){let o=t[V];if(o===void 0)break;let c=o&7,a=o>>3;if(V++,c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(t,V);if(V+=A,a===1)return t.subarray(V,V+R).toString("utf8");V+=R}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(t,V);V+=R}else break}return""}}static parseImageProperty(l){let e={imageKey:null,cryptoInfo:null};if(!l||l.length===0)return e;let t=Buffer.from(l),V=0;for(;V<t.length&&!(V>=t.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(t,V);if(c===0)break;V+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(t,V);V+=n;let h=t.subarray(V,V+A);if(V+=A,R===2){let d=h.toString("utf8").trim();this.isValidImageKey(d)&&(e.imageKey=d)}else if(R===17)try{let d=G(ye,h);this.isValidImageKey(d.imageKey)&&(e.imageKey=d.imageKey.trim()),d.crypto&&(e.cryptoInfo=this.extractCryptoInfo(d.crypto))}catch{let g=this.extractCryptoFromBytes(h);g&&(e.cryptoInfo=g)}if(A>10&&R!==17)try{let d=G(ye,h);!e.imageKey&&this.isValidImageKey(d.imageKey)&&(e.imageKey=d.imageKey.trim()),d.crypto&&(e.cryptoInfo=this.extractCryptoInfo(d.crypto))}catch{let g=this.extractCryptoFromBytes(h);g&&(e.cryptoInfo=g)}}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(t,V);V+=A}else break}if(!e.imageKey){let o=t.toString("utf8"),c=this.extractImageKeysFromString(o);c.length>0&&(e.imageKey=c[0])}return e.cryptoInfo||(e.cryptoInfo=this.extractCryptoFromBytes(t)),e}static parseTextMessageContent(l){let e=Buffer.from(l),t=0,V="",o=null;for(;t<e.length&&!(t>=e.length);){let{value:c,bytesRead:a}=this.readVarintWithLength(e,t);if(a===0)break;t+=a;let R=c&7,A=c>>3;if(R===2){let{value:n,bytesRead:h}=this.readVarintWithLength(e,t);if(t+=h,t+n>e.length)break;let d=e.subarray(t,t+n);t+=n,A===1&&n>0?V=d.toString("utf8"):A===3&&(o=d)}else if(R===0){let{bytesRead:n}=this.readVarintWithLength(e,t);t+=n}else break}return V||(o?this.parseRichTextFromBytes(o):"")}static parseRichTextFromBytes(l){let e=0,t="",V=null;for(;e<l.length&&!(e>=l.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);e+=A,R===2&&A>0?t=h.toString("utf8"):R===3&&(V=h)}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(l,e);e+=A}else break}return t||(V?this.extractTextFromElementsBytes(V):"")}static extractTextFromElementsBytes(l){let e=[],t=0;for(;t<l.length&&!(t>=l.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1){let h=this.extractTextFromMapEntry(n);h&&e.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e.join("")}static extractTextFromMapEntry(l){let e=0,t=null;for(;e<l.length&&!(e>=l.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(l,e);if(o===0)break;e+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,e);if(e+=A,e+R>l.length)break;let n=l.subarray(e,e+R);e+=R,a===2&&(t=n)}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,e);e+=R}else break}return t?this.extractTextFromRichTextElement(t):""}static extractTextFromRichTextElement(l){let e=0,t=0,V=null;for(;e<l.length&&!(e>=l.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===0){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);e+=n,R===1&&(t=A)}else if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);e+=A,R===3&&(V=h)}else break}return t===1&&V?this.parseTextPropertyBytes(V):""}static parseTextPropertyBytes(l){let e=0;for(;e<l.length&&!(e>=l.length);){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===1)return A.toString("utf8")}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return""}static tryDecodeTextFromBytes(l){if(!l||l.length===0)return"";let e=Buffer.from(l),t=0;for(;t<e.length&&!(t>=e.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(e,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(e,t);if(t+=A,t+R>e.length)break;let n=e.subarray(t,t+R);if(t+=R,a===1&&R>0)try{let h=n.toString("utf8");if(h&&!/[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(h))return h}catch{}if(a===14&&R>0){let h=this.tryExtractInnerText(n);if(h)return h}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(e,t);t+=R}else break}return""}static tryExtractInnerText(l){let e=0;for(;e<l.length&&!(e>=l.length);){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===2&&a>0)try{let n=A.toString("utf8");if(n&&!/[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(n))return n}catch{}}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return""}static readVarintWithLength(l,e){let t=0,V=0,o=0,c;do c=l[e+o],V<28?t|=(c&127)<<V:t+=(c&127)*2**V,o++,V+=7;while(c&128);return{value:t,bytesRead:o}}static extractCryptoFromBytes(l,e=0){if(!l||l.length===0||e>6)return null;let t=Buffer.from(l);try{let o=G(Il,t),c=this.extractCryptoInfo(o);if(c?.secret&&c?.nonce)return c}catch{}try{let o=G(ye,t);if(o?.crypto){let c=this.extractCryptoInfo(o.crypto);if(c?.secret&&c?.nonce)return c}}catch{}try{let o=G(dt,t);if(o?.crypto){let c=this.extractCryptoInfo(o.crypto);if(c?.secret&&c?.nonce)return c}}catch{}let V=0;for(;V<t.length;){let{value:o,bytesRead:c}=this.readVarintWithLength(t,V);if(!c)break;V+=c;let a=o&7;if(a===2){let{value:R,bytesRead:A}=this.readVarintWithLength(t,V);if(V+=A,R<0||V+R>t.length)break;let n=t.subarray(V,V+R);V+=R;let h=this.extractCryptoFromBytes(n,e+1);if(h?.secret&&h?.nonce)return h}else if(a===0){let{bytesRead:R}=this.readVarintWithLength(t,V);V+=R}else if(a===1)V+=8;else if(a===5)V+=4;else break}return null}static isValidImageCryptoInfo(l){if(!l?.secret||!l?.nonce)return!1;let e=Buffer.from(l.secret).length,t=Buffer.from(l.nonce).length;return e===32&&t===12}static getCryptoFingerprint(l){if(!this.isValidImageCryptoInfo(l))return"";let e=Buffer.from(l.secret).toString("hex"),t=Buffer.from(l.nonce).toString("hex");return e.slice(0,16)+":"+t.slice(0,8)}static extractDirectCryptoInfo(l){if(!l||l.length===0)return null;try{let e=G(Il,l),t=this.extractCryptoInfo(e);if(this.isValidImageCryptoInfo(t))return t}catch{}return null}static collectCryptoBlocksFromPayload(l,e=0,t=0,V=10,o=[]){if(!l||t>V)return o;let c=l instanceof Buffer?l:Buffer.from(l);if(c.length===0)return o;let a=0;for(;a<c.length;){let{value:R,bytesRead:A}=this.readVarintWithLength(c,a);if(!A)break;a+=A;let n=R&7;if(n===2){let{value:h,bytesRead:d}=this.readVarintWithLength(c,a);if(a+=d,h<0||a+h>c.length)break;let g=a,E=a+h,X=c.subarray(g,E),r=this.extractDirectCryptoInfo(X);r&&o.push({offset:e+g,end:e+E,cryptoInfo:r,fingerprint:this.getCryptoFingerprint(r)}),this.collectCryptoBlocksFromPayload(X,e+g,t+1,V,o),a=E}else if(n===0){let{bytesRead:h}=this.readVarintWithLength(c,a);if(!h)break;a+=h}else if(n===1)a+=8;else if(n===5)a+=4;else break}return o}static findImageKeyOccurrencesInBuffer(l,e){let t=[];for(let V of e){let o=0;for(;o<l.length;){let c=l.indexOf(V,o,"utf8");if(c===-1)break;t.push({imageKey:V,offset:c,end:c+Buffer.byteLength(V,"utf8")}),o=c+1}}return t.sort((V,o)=>V.offset-o.offset)}static cacheImageCryptoFromCmd77Payload(l){if(!l||l.length===0)return 0;let e=l instanceof Buffer?l:Buffer.from(l),t=this.extractImageKeysFromString(e.toString("utf8"));if(t.length===0)return 0;let V=this.findImageKeyOccurrencesInBuffer(e,t);if(V.length===0)return 0;let o=this.collectCryptoBlocksFromPayload(e);if(o.length===0)return 0;let c=new Map;for(let n of o){let h=n.offset+":"+n.fingerprint;c.has(h)||c.set(h,n)}let a=Array.from(c.values()),R=new Map;for(let n of V){let h=a.filter(m=>{let W=m.offset-n.end;return W>=0&&W<=2048}),d=h.length>0?h:a.filter(m=>Math.abs(m.offset-n.end)<=512);if(d.length===0)continue;let g=null;for(let m of d){let W=Math.abs(m.offset-n.end),u=m.offset>=n.end?0:256,I=W+u;(!g||I<g.score)&&(g={block:m,score:I})}if(!g)continue;let E=g.block.fingerprint;if(!E)continue;let X=R.get(n.imageKey);X||(X=new Map,R.set(n.imageKey,X));let r=X.get(E)||{count:0,bestScore:Number.MAX_SAFE_INTEGER,cryptoInfo:g.block.cryptoInfo};r.count+=1,r.bestScore=Math.min(r.bestScore,g.score),X.set(E,r)}let A=0;for(let[n,h]of R.entries()){let d=Array.from(h.entries());if(d.length===0)continue;d.sort((E,X)=>{let[,r]=E,[,m]=X;return m.count!==r.count?m.count-r.count:r.bestScore-m.bestScore});let[,g]=d[0];this.isValidImageCryptoInfo(g.cryptoInfo)&&(_l(n,g.cryptoInfo),A+=1)}return A}static cacheImageCryptoFromGatewayResponseBuffer(l){if(!l||l.length===0)return 0;try{let e=l instanceof Uint8Array?l:new Uint8Array(l),t=G(F,e);return!t.payload||t.payload.length===0?0:this.cacheImageCryptoFromCmd77Payload(t.payload)}catch{return 0}}static cacheImageCryptoFromCmd77ResponseBuffer(l){return this.cacheImageCryptoFromGatewayResponseBuffer(l)}static readVarint(l,e){let t=0,V=0,o;do o=l[e],t|=(o&127)<<V,e++,V+=7;while(o&128);return t}static varintLength(l,e){let t=0;for(;l[e+t]&128;)t++;return t+1}static buildReplyRequest(l,e,t,V={}){let{rootId:o,parentId:c}=V,a=te(),R=te(),A=i(ne,{content:l}),n=i(me,{text:l,richText:{elementIds:[R],innerText:l,elements:{dictionary:{[R]:{tag:1,property:b(ne,A)}}}}}),h=i(xe,{type:4,chatId:t,rootId:o||"",parentId:c||"",cid:a,isNotified:!0,sendToChat:!1,version:1,isThreadGroupTopic:!1,content:n}),d=i(F,{payloadType:1,cmd:5,cid:e,payload:b(xe,h)});return Buffer.from(b(F,d))}static decodePutMessageResponse(l){try{if(!l||l.length===0)return{success:!1,error:"Empty packet"};let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=G(_V,e.payload);if(!t.message)return{success:!1,error:"PutMessageResponse missing message"};let V={success:!0};return V.message=this.parseMessageContent(t.message,e.sid),t.positions&&Object.keys(t.positions).length>0&&(V.positions=this._normalizeProtoValue(t.positions)),t.thread&&(V.thread=this._normalizeProtoValue(t.thread)),t.feedCard&&(V.feedCard=this._normalizeProtoValue(t.feedCard)),t.feedCards&&Object.keys(t.feedCards).length>0&&(V.feedCards=this._normalizeProtoValue(t.feedCards)),t.syncToChatMessage&&(V.syncToChatMessage=this.parseMessageContent(t.syncToChatMessage,e.sid)),V}catch(e){return{success:!1,error:e.message}}}static buildAckPacket(l){let e=Date.now(),t=i(F,{payloadType:1,cmd:1,sid:l}),V=i(Rl,{seqid:aV.parse(e),logid:aV.parse(e),service:1,method:1,headers:[{key:"x-request-time",value:`${e}000`}],payloadType:"pb",payload:b(F,t)});return Buffer.from(b(Rl,V))}static buildGetUserProfileRequest(l,e){let t=[];t.push(8,1);let V=new TextEncoder().encode(e);t.push(18),S(t,V.length),t.push(...V),t.push(40,2),t.push(88,1),t.push(96,1),t.push(112,1);let o=new Uint8Array(t),c=i(F,{payloadType:1,cmd:5031,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserProfileResponse(l){let e=G(F,l);if(!e.payload)return null;let t=Buffer.from(e.payload);return this.parseUserProfilePayload(t)}static parseUserProfilePayload(l){let e={userId:null,name:null,enName:null,avatarUrl:null,avatarKey:null,tenantId:null,alias:null,memoText:null,memoPicture:null,memoPictureV2:[]},t=l.toString("utf8"),V=t.match(/\d{19}/g);if(V&&(e.userId=V[0]),e.userId){let n=Buffer.from(e.userId),h=0,d=0;for(;(h=l.indexOf(n,d))!==-1;){if(h>=2&&l[h-2]===10&&l[h-1]===19){let g=h+n.length;if(g<l.length&&l[g]===18){let E=l[g+1];if(E>0&&E<=30&&g+2+E<=l.length){let X=l.subarray(g+2,g+2+E);try{let r=X.toString("utf8");(/^[\u4e00-\u9fa5]{2,10}$/.test(r)||/^[a-zA-Z\s]+$/.test(r))&&(e.name=r)}catch{}}}break}d=h+1}}if(e.userId){let n=Buffer.from(e.userId),h=l.lastIndexOf(n);if(h>0){let d=Math.min(l.length,h+2e3),X=l.subarray(h,d).toString("utf8").match(/([a-z]+(?: [a-z]+)+)/);X&&X[0].length<30&&(e.enName=X[0])}}let o=t.match(/https:\/\/s\d-imfile\.feishucdn\.com\/static-resource\/v\d\/[^\s~?]+/);o&&(e.avatarUrl=o[0]);let c=t.match(/v3_[a-z0-9]{4}_[a-f0-9-]+/i);c&&(e.avatarKey=c[0]);let a=t.match(/赵天雄[\s\S]*?\n\x05zh_cn\x12\x06([^\x00-\x1f]{2,20})/);if(a&&a[1]&&a[1]!==e.name&&(e.alias=a[1].replace(/�+$/g,"")),e.alias===null){let n=t.match(/B-ALIAS[\s\S]*?\{"text":\{"default_val":"([^"]*)"\}\}/);n&&(e.alias=n[1])}let R=t.indexOf('{"memo_text":"'),A=']}"';if(R!==-1){let n=t.indexOf(A,R),h=n===-1?null:t.slice(R,n+A.length-1);if(h)try{let d=JSON.parse(h);e.memoText=d.memo_text??null,e.memoPicture=d.memo_picture??null,e.memoPictureV2=Array.isArray(d.memo_picture_v2)?d.memo_picture_v2:[]}catch{let d=t.match(/\{"memo_text":"((?:\\.|[^"])*)"/);if(d)try{e.memoText=JSON.parse(`"${d[1]}"`)}catch{e.memoText=d[1]}}}return e}static buildGetUserInfoByIdRequest(l,e){let t=[],V=Buffer.from(e,"utf-8");t.push(10,V.length,...V),t.push(16,1);let o=new Uint8Array(t),c=i(F,{payloadType:1,cmd:46,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserInfoByIdResponse(l){let e=G(F,l);if(!e.payload)return{success:!1,error:"No payload in response"};let t=Buffer.from(e.payload);return this.parseUserInfoPayload(t)}static buildGetUserProfileCardRequest(l,e){let t=BigInt(e),V=[8];this.pushVarintBigInt(V,t);let o=new Uint8Array(V),c=i(F,{payloadType:1,cmd:5017,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserProfileCardResponse(l){let e=G(F,l);if(!e.payload)return{success:!1,error:"No payload in response"};if(this._isPacketError(e))return{success:!1,error:`Packet status: ${e.status}`};let t=Buffer.from(e.payload);return this.parseUserProfileCardPayload(t)}static parseUserProfileCardPayload(l){let e={success:!0,orgName:null,description:null,email:null,displayName:null,displayNameLocalized:null,avatarKey:null,profileUserId:null,alias:null,profileFieldPolicies:[]},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===2)e.orgName=n.toString("utf8");else if(a===3)e.description=n.toString("utf8");else if(a===5)e.email=n.toString("utf8");else if(a===7)e.displayName=n.toString("utf8");else if(a===11)e.displayNameLocalized=n.toString("utf8");else if(a===19)e.avatarKey=n.toString("utf8");else if(a===22)e.profileUserId=n.toString("utf8");else if(a===24)e.alias=n.toString("utf8");else if(a===50){let h=this.parseUserProfileFieldPolicy(n);h&&e.profileFieldPolicies.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return e}static parseUserProfileFieldPolicy(l){let e={key:null,locale:null,visible:null,editable:null,mode:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===1?e.key=n.toString("utf8"):a===5&&(e.locale=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3?e.visible=R:a===4?e.editable=R:a===6&&(e.mode=R)}else if(c===1)t+=8;else if(c===5)t+=4;else break}return e.key?e:null}static parseUserInfoPayload(l){let e={userId:null,name:null,isBot:!1,userType:1,avatarKey:null};try{let t=l.toString("utf8"),V=t.match(/\d{19}/);V&&(e.userId=V[0]);let o=Buffer.from([10,3,98,111,116]);if(l.includes(o)&&(e.isBot=!0,e.userType=2),e.userId){let a=Buffer.from(e.userId),R=l.indexOf(a);for(;R!==-1;){let A=R+a.length;if(A<l.length&&l[A]===18){let n=l[A+1];if(n>0&&n<=50&&A+2+n<=l.length){let h=l.subarray(A+2,A+2+n);try{let d=h.toString("utf8");if(d.length>0&&d.length<=30){e.name=d;break}}catch{}}}R=l.indexOf(a,R+1)}}let c=t.match(/v3_[a-z0-9]{4}_[a-f0-9-]+/i);if(c)e.avatarKey=c[0];else{let a=t.match(/[a-f0-9]{20,}/);a&&(e.avatarKey=a[0])}}catch(t){return{success:!1,error:t.message}}return{success:!0,...e}}static RSVP_STATUS={ACCEPT:1,DECLINE:2,TENTATIVE:3};static REPLY_CALENDAR_EVENT_INVITATION_REPLY_TYPES={ACCEPT:Ke.ACCEPT,DECLINE:Ke.DECLINE,TENTATIVE:Ke.TENTATIVE,DELETE:Ke.DELETE,NEEDS_ACTION:Ke.NEEDS_ACTION};static buildReplyCalendarEventInvitationRequest(l,e,t,V={}){let o=i(Pt,{calendarEventKey:i(OV,{uniqueKey:e.uniqueKey,calendarId:e.calendarId,originalTime:BigInt(e.originalTime)}),replyType:t,quitMeeting:V.quitMeeting??!1,needsBriefEvents:V.needsBriefEvents??!1,useAttendeePageToken:V.useAttendeePageToken??!1,...V.rsvpCommentInfo?{rsvpCommentInfo:i(MV,{replyCommentId:V.rsvpCommentInfo.replyCommentId??"",comment:V.rsvpCommentInfo.comment??"",inviteOperatorId:V.rsvpCommentInfo.inviteOperatorId??""})}:{}}),c=i(F,{payloadType:1,cmd:1020002,cid:l,payload:b(Pt,o)});return Buffer.from(b(F,c))}static buildCalendarRsvpRequest(l,e,t,V){let o=[],c=[],a=new TextEncoder().encode(e);c.push(10),S(c,a.length),c.push(...a);let R=new TextEncoder().encode(t);c.push(18),S(c,R.length),c.push(...R),c.push(24,0);let A=new Uint8Array(c);o.push(10),S(o,A.length),o.push(...A),o.push(16),o.push(V),o.push(40,1),o.push(48,1);let n=new Uint8Array(o),h=i(F,{payloadType:1,cmd:1020002,cid:l,payload:n});return Buffer.from(b(F,h))}static buildCalendarEventDetailRequest(l,e,t=0){let V=[],o=[],c=new TextEncoder().encode(e);if(o.push(10),S(o,c.length),o.push(...c),t!==0){o.push(16);let n=t<<1^t>>31;this.pushVarint(o,n)}o.push(32,0),o.push(40,1),o.push(48,3);let a=new Uint8Array(o);V.push(10),S(V,a.length),V.push(...a);let R=new Uint8Array(V),A=i(F,{payloadType:1,cmd:1010048,cid:l,payload:R});return Buffer.from(b(F,A))}static buildGetBusyUserRequest(l,e,t,V,o={}){let c=[];for(let R of e||[]){let A=new TextEncoder().encode(String(R));c.push(10),S(c,A.length),c.push(...A)}if(c.push(16),this.pushVarintBigInt(c,BigInt(t)),c.push(24),this.pushVarintBigInt(c,BigInt(V)),o.uid){let R=new TextEncoder().encode(String(o.uid));c.push(34),S(c,R.length),c.push(...R)}o.originalTime!==void 0&&o.originalTime!==null&&(c.push(40),this.pushVarintBigInt(c,BigInt(o.originalTime))),o.bidirectionalSyncOccupyBusy!==void 0&&c.push(48,o.bidirectionalSyncOccupyBusy?1:0),o.bidirectionalSyncOptimizeFg!==void 0&&c.push(56,o.bidirectionalSyncOptimizeFg?1:0);let a=i(F,{payloadType:1,cmd:1010020,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static buildCreateCalendarEventRequest(l,e,t={},V={}){let o=Ge(e,"calendarId"),{start:c,end:a}=CR(t.startTime,t.endTime,"startTime","endTime"),R=Ie(t.timezone,t.startTimezone,t.endTimezone),A=t.uniqueKey||RV.randomUUID(),n=t.originalTime===void 0||t.originalTime===null||t.originalTime===""?c:ee(t.originalTime,"originalTime"),h=String(Ie(t.eventId,"0")),d=String(Ie(t.creatorCalendarId,o)),g=String(Ie(t.organizerCalendarId,o)),E=De(t.reminders).map((N,Y)=>({calendarEventId:String(Ie(N.calendarEventId,N.calendar_event_id,"0")),minutes:bR(N.minutes,Go(Y,"minutes")),method:de(N.method,El,El.default,Go(Y,"method"))})),X=[...De(t.locations),...De(t.location)].map((N,Y)=>({name:N.name??"",address:N.address??"",type:de(N.type,Fl,Fl.ordinary,sV(Y,"type")),...N.latitude!==void 0?{latitude:mo(N.latitude,sV(Y,"latitude"))}:{},...N.longitude!==void 0?{longitude:mo(N.longitude,sV(Y,"longitude"))}:{}})),r=BR(t.attendees),m=i(sl,{id:h,key:A,originalTime:n,calendarId:o,organizerCalendarId:g,creatorCalendarId:d,successorCalendarId:t.successorCalendarId??"0",summary:t.summary??"",rrule:t.rrule??"",startTime:c,endTime:a,status:de(t.status,gl,gl.confirmed,"status"),source:t.source??jV.PC_CLIENT,attendeeSource:ql(t.attendeeSource??1,"attendeeSource"),isDeleted:!1,isAllDay:t.isAllDay??!1,isCrossTenant:t.isCrossTenant??!1,guestCanInvite:t.guestCanInvite??!0,guestCanSeeOtherGuests:t.guestCanSeeOtherGuests??!0,guestCanModify:t.guestCanModify??!1,selfAttendeeStatus:de(t.selfAttendeeStatus,oV,oV.accept,"selfAttendeeStatus"),color:ql(t.color??-1,"color"),version:BigInt(ql(t.version??0,"version")),visibility:de(t.visibility,Zl,Zl.default,"visibility"),isFree:t.isFree??!1,locations:X,reminders:E,...r.length>0?{attendees:r}:{},...t.description!==void 0||t.docsDescription!==void 0||t.docs_description!==void 0?{description:t.description??"",...t.docsDescription!==void 0||t.docs_description!==void 0?{docsDescription:t.docsDescription??t.docs_description}:{}}:{},...t.attachments?{attachments:t.attachments}:{},...t.videoConfig?{videoConfig:t.videoConfig}:{},...t.encryptionInfo?{encryptionInfo:t.encryptionInfo}:{},...bo(R)?{startTimezone:Ie(t.startTimezone,R),endTimezone:Ie(t.endTimezone,R)}:{}}),W=b(sl,m),u=[];u.push(10),S(u,W.length),u.push(...W),V.notificationType!==void 0&&V.notificationType!==null&&V.notificationType!==""&&(u.push(16),this.pushVarint(u,de(V.notificationType,dl,dl.default,"notificationType")));let I=i(F,{payloadType:1,cmd:1002003,cid:l,payload:new Uint8Array(u)});return Buffer.from(b(F,I))}static buildDeleteCalendarEventRequest(l,e,t,V={}){let o=[],c=V.deleteType??0,a=V.needNotification??!0,R=new TextEncoder().encode(String(e));o.push(10),S(o,R.length),o.push(...R);let A=new TextEncoder().encode(String(t));o.push(18),S(o,A.length),o.push(...A),o.push(24),this.pushVarint(o,Number(c)),o.push(32),this.pushVarint(o,a?1:0);let n=i(F,{payloadType:1,cmd:1002005,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,n))}static buildUpdateCalendarEventRequest(l,e,t={}){let V=[],o=i(sl,e),c=b(sl,o);V.push(10),S(V,c.length),V.push(...c),t.span!==void 0&&(V.push(16),this.pushVarint(V,Number(t.span))),t.instanceStartTime!==void 0&&t.instanceStartTime!==null&&(V.push(24),this.pushVarintBigInt(V,BigInt(t.instanceStartTime))),t.notificationType!==void 0&&(V.push(32),this.pushVarint(V,Number(t.notificationType)));let a=i(F,{payloadType:1,cmd:1002004,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,a))}static buildWebListCalendarEventsRequest(l,e,t,V,o={}){let c=o.limit??100,a=[],R=new TextEncoder().encode(String(e));a.push(10),S(a,R.length),a.push(...R),a.push(16),this.pushVarintBigInt(a,BigInt(t)),a.push(24),this.pushVarintBigInt(a,BigInt(V)),a.push(40),this.pushVarintBigInt(a,BigInt(c));let A=[10];S(A,a.length),A.push(...a);let n=i(F,{payloadType:1,cmd:1002001,cid:l,payload:new Uint8Array(A)});return Buffer.from(b(F,n))}static buildCreateMeetingMinuteRequest(l,e,t,V={}){let o=[],c=V.originalTime??0,a=new TextEncoder().encode(String(e));o.push(10),S(o,a.length),o.push(...a);let R=new TextEncoder().encode(String(t));o.push(18),S(o,R.length),o.push(...R),o.push(24),this.pushVarintBigInt(o,BigInt(c));let A=i(F,{payloadType:1,cmd:1010028,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,A))}static buildTransferCalendarEventRequest(l,e,t,V,o={}){let c=[],a=[],R=o.originalTime??0,A=o.transferFlag??1,n=new TextEncoder().encode(String(e));a.push(10),S(a,n.length),a.push(...n);let h=new TextEncoder().encode(String(t));a.push(18),S(a,h.length),a.push(...h),a.push(24),this.pushVarintBigInt(a,BigInt(R)),c.push(10),S(c,a.length),c.push(...a),c.push(16),this.pushVarintBigInt(c,BigInt.asUintN(32,BigInt(V))),c.push(24),this.pushVarintBigInt(c,BigInt(A));let d=i(F,{payloadType:1,cmd:1010022,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,d))}static buildWebShareCalendarEventRequest(l,e,t,V,o={}){let c=[],a=o.originalTime??0;for(let h of e)c.push(8),this.pushVarintBigInt(c,BigInt(h));let R=new TextEncoder().encode(String(t));c.push(18),S(c,R.length),c.push(...R);let A=new TextEncoder().encode(String(V));c.push(26),S(c,A.length),c.push(...A),c.push(32),this.pushVarintBigInt(c,BigInt(a));let n=i(F,{payloadType:1,cmd:1002012,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,n))}static buildUpgradeToMeetingRequest(l,e,t={}){let V=t.originalTime??0,o=[],c=new TextEncoder().encode(String(e.eventId));o.push(10),S(o,c.length),o.push(...c);let a=new TextEncoder().encode(String(e.uid));o.push(18),S(o,a.length),o.push(...a);let R=new TextEncoder().encode(String(e.calendarId));if(o.push(26),S(o,R.length),o.push(...R),o.push(32),this.pushVarintBigInt(o,BigInt(V)),e.creatorId!==void 0&&e.creatorId!==null){let g=new TextEncoder().encode(String(e.creatorId));o.push(42),S(o,g.length),o.push(...g)}if(e.organizerId!==void 0&&e.organizerId!==null){let g=new TextEncoder().encode(String(e.organizerId));o.push(50),S(o,g.length),o.push(...g)}o.push(64),this.pushVarintBigInt(o,BigInt(e.startTime));let A=new TextEncoder().encode(String(e.startTimezone));if(o.push(74),S(o,A.length),o.push(...A),o.push(80),this.pushVarintBigInt(o,BigInt(e.endTime)),e.endTimezone!==void 0&&e.endTimezone!==null){let g=new TextEncoder().encode(String(e.endTimezone));o.push(90),S(o,g.length),o.push(...g)}if(t.rrule){let g=new TextEncoder().encode(String(t.rrule));o.push(114),S(o,g.length),o.push(...g)}o.push(200,1),this.pushVarint(o,0);let n=new TextEncoder().encode(String(e.summary));o.push(234,1),S(o,n.length),o.push(...n);let h=[];h.push(10),S(h,o.length),h.push(...o),h.push(16),this.pushVarint(h,1),h.push(24),this.pushVarint(h,1);let d=i(F,{payloadType:1,cmd:1010014,cid:l,payload:new Uint8Array(h)});return Buffer.from(b(F,d))}static decodeUpgradeToMeetingResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let g=this.extractErrorMessage(e.payload);if(g)return{success:!1,error:g}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty response payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=null,o=null,c=null,a=t.find(g=>g.fieldNo===1&&g.wireType===2);if(a){let g=this.parseProtobufFields(a.data);V=this.getStringField(g,1),o=this.getStringField(g,2);let E=this.getVarintField(g,3,null);c=E!==null?E!==0:null}let R={},A=t.filter(g=>g.fieldNo===2&&g.wireType===2);for(let g of A){let E=this.parseProtobufFields(g.data),X=this.getStringField(E,1),r=this.getStringField(E,2);X&&(R[X]=r)}let n=[],h=null,d=t.find(g=>g.fieldNo===3&&g.wireType===2);if(d){let g=this.parseProtobufFields(d.data);h=this.getStringField(g,29);let E=g.filter(X=>X.fieldNo===26&&X.wireType===2);for(let X of E){let r=this.parseProtobufFields(X.data),m=this.getStringField(r,1),W=this.getStringField(r,2),u=this.getVarintField(r,6,null),I=this.getVarintField(r,23,null);W&&n.push({attendeeCalendarId:W,displayName:m,status:u,individualAttendeeType:I})}}return V?o?{success:!0,meetingId:V,meetingChatId:o,isFirstEntrance:c,eventMeetingMap:R,attendees:n,summary:h}:{success:!1,error:"Missing meetingChatId in response"}:{success:!1,error:"Missing meetingId in response"}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static pushVarint(l,e){for(;e>127;)l.push(e&127|128),e>>>=7;l.push(e)}static pushVarintBigInt(l,e){let t=BigInt(e);for(;t>127n;)l.push(Number(t&0x7fn|0x80n)),t>>=7n;l.push(Number(t))}static decodeCalendarRsvpResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Status: ${e.status}`}}return{success:!0}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeReplyCalendarEventInvitationResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,data:{},rsvpCommentFailed:[]};let t=G(Eo,e.payload),V=this._normalizeProtoValue(t);return{success:!0,data:V,calendarEvent:V.calendarEvent,rsvpCommentFailed:V.rsvpCommentFailed||[]}}catch(e){return{success:!1,error:e.message}}}static extractErrorMessage(l){try{if(l[0]===10&&l.length>2){let e=l[1];if(e>0&&e<l.length-2){let t=Buffer.from(l.slice(2,2+e)).toString("utf8");if(/^[A-Za-z][A-Za-z0-9_]+$/.test(t))return t}}}catch{}return null}static decodeCalendarEventDetailResponse(l){try{let e=G(F,l);return!e.payload||e.payload.length<10?{success:!1,error:"Empty payload",events:[]}:{success:!0,events:this.parseCalendarEventPayload(Buffer.from(e.payload))}}catch(e){return{success:!1,error:e.message,events:[]}}}static decodeGetBusyUserResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,calendarBusyMap:{}};let t=this.parseProtobufFields(Buffer.from(e.payload)),V={};for(let o of t){if(o.fieldNo!==1||o.wireType!==2)continue;let c=this.parseProtobufFields(o.data),a=this.getStringField(c,1)||"",R=c.find(A=>A.fieldNo===2&&A.wireType===0);!a||!R||(V[a]=!!R.val)}return{success:!0,calendarBusyMap:V}}catch(e){return{success:!1,error:e.message}}}static decodeCreateCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return{success:!0,data:{}}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeDeleteCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let c=this.extractErrorMessage(e.payload);if(c)return{success:!1,error:c}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,data:{}};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,5);if(!V)return{success:!0,data:{}};let o=Buffer.from(V).toString("utf8");try{return{success:!0,data:JSON.parse(o)}}catch{return{success:!0,data:{raw:o}}}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeUpdateCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return{success:!0,data:{}}}catch(e){return{success:!1,error:e.message}}}static decodeWebListCalendarEventsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let R=this.extractErrorMessage(e.payload);if(R)return{success:!1,error:R}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,calendarId:"",events:[]};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,1);if(!V)return{success:!0,calendarId:"",events:[]};let o=this.parseProtobufFields(Buffer.from(V)),c=this.getStringField(o,1)||"",a=[];for(let R of o){if(R.fieldNo!==2||R.wireType!==2)continue;let A=this.parseProtobufFields(Buffer.from(R.data));a.push({eventKey:this.getStringField(A,1)||"",uid:this.getStringField(A,2)||"",startTime:this.getVarintField(A,25,0),startTimezone:this.getStringField(A,26)||"",endTime:this.getVarintField(A,27,0),endTimezone:this.getStringField(A,28)||"",summary:this.getStringField(A,29)||""})}return{success:!0,calendarId:c,events:a}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeCreateMeetingMinuteResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty response payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getStringField(t,1);return V?{success:!0,meetingMinuteUrl:V}:{success:!1,error:"Missing meeting minute URL in response"}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeTransferCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,events:[]}:{success:!0,events:this.parseProtobufFields(Buffer.from(e.payload)).filter(o=>o.fieldNo===1&&o.wireType===2).map(o=>this.parseTransferredCalendarEvent(o.data))}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeWebShareCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,sharedFailedChats:[]}:{success:!0,sharedFailedChats:this.parseProtobufFields(Buffer.from(e.payload)).filter(o=>o.fieldNo===1&&o.wireType===0).map(o=>Number(o.val))}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static parseCalendarEventPayload(l){let e=[],t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===2){let h=this.parseCalendarEvent(n);h&&e.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e}static parseCalendarEvent(l){let e={userId:null,eventId:null,title:null,startTime:null,endTime:null,timezone:null,organizer:null,attendees:[],meetingUrl:null,rsvpStatus:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1)e.userId=n.toString("utf8");else if(a===2)e.eventId=n.toString("utf8");else if(a===4)this.parseEventDetails(n,e);else if(a===5){let h=this.parseRsvpInfo(n);h&&(e.rsvpStatus=h.status)}else if(a===20){let h=this.parseAttendeeInfo(n);h&&e.attendees.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e.eventId||e.title?e:null}static parseTransferredCalendarEvent(l){let e=this.parseProtobufFields(l);return{eventKey:this.getStringField(e,1)||"",summary:this.getStringField(e,29)||"",description:this.getStringField(e,30)||"",startTime:this.getVarintField(e,8,null),timezone:this.getStringField(e,9)||"",endTime:this.getVarintField(e,10,null),meetingMinuteUrl:this.getStringField(e,51)||""}}static parseEventDetails(l,e){let t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===8?e.title=n.toString("utf8"):a===12&&(e.timezone=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===11?e.startTime=R:a===13&&(e.endTime=R)}else break}}static parseRsvpInfo(l){let e={userId:null,status:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===2&&(e.userId=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3&&(e.status=R)}else break}return e}static parseAttendeeInfo(l){let e={name:null,userId:null,rsvpStatus:null,type:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1)e.name=n.toString("utf8");else if(a===2)e.userId=n.toString("utf8");else if(a===11){let h=this.extractTypeFromNested(n);h&&(e.type=h)}}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3&&(e.rsvpStatus=R)}else break}return e.name||e.userId?e:null}static extractTypeFromNested(l){let e=0;for(;e<l.length;){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===2)return A.toString("utf8")}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return null}static buildPullSmartReplyResourceRequestPayload(l){let e=[...new Set((l||[]).map(V=>String(V||"").trim()).filter(V=>/^img_v[23]_/.test(V)))],t=[];for(let V of e){let o=Buffer.from(V,"utf8");t.push(10),S(t,o.length),t.push(...o)}return new Uint8Array(t)}static buildCmd77PullSmartReplyResourceRequest(l,e,t={}){let V=this.buildPullSmartReplyResourceRequestPayload(e),o=typeof t.subRequestId=="string"&&t.subRequestId.trim()?t.subRequestId.trim():(globalThis.crypto?.randomUUID?.()||te()).toUpperCase(),c=[];c.push(16,1),c.push(24),S(c,1105047),c.push(42),S(c,V.length),c.push(...V);let a=Buffer.from(o,"utf8");c.push(50),S(c,a.length),c.push(...a);let R=[10];S(R,c.length),R.push(...c);let A=i(F,{payloadType:1,cmd:77,cid:l,payload:new Uint8Array(R)});return Buffer.from(b(F,A))}static buildPullSmartReplyResourceRequest(l,e){let t=this.buildPullSmartReplyResourceRequestPayload(e),V=i(F,{payloadType:1,cmd:1105047,cid:l,payload:t});return Buffer.from(b(F,V))}static buildGetChatHistoryRequest(l,e,t){let V=i(Yl,{chatId:e,positions:t,flag1:1,flag2:1,flag3:2,flag4:1}),o=i(F,{payloadType:1,cmd:43,cid:l,payload:b(Yl,V)});return Buffer.from(b(F,o))}static buildEmojiReactionRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=Buffer.from(t,"utf-8"),c=[];c.push(10),S(c,V.length),c.push(...V),c.push(18),S(c,o.length),c.push(...o),c.push(24,1);let a=i(F,{payloadType:1,cmd:25,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodeEmojiReactionResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildRemoveEmojiReactionRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=Buffer.from(t,"utf-8"),c=[];c.push(10),S(c,V.length),c.push(...V),c.push(18),S(c,o.length),c.push(...o),c.push(24,1);let a=i(F,{payloadType:1,cmd:26,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodeRemoveEmojiReactionResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildGetChatMetaRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[10];S(V,t.length),V.push(...t);let o=i(F,{payloadType:1,cmd:64,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeGetChatMetaResponse(l){try{let e=G(F,l);if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=Buffer.from(e.payload),V=this.extractLengthDelimitedField(t,1);if(!V)return{success:!1,error:"No chat meta entry in payload"};let o=Buffer.from(V),c=this.extractLengthDelimitedField(o,1),a=this.extractLengthDelimitedField(o,2);if(!a)return{success:!1,error:"No chat bytes in chat meta entry"};let R=G(Et,a);return{success:!0,chat:{id:R.id||(c?Buffer.from(c).toString("utf8"):""),type:R.type,name:R.name||"",description:R.description||"",ownerId:R.ownerId||"",lastMessageId:R.lastMessageId||"",lastVisibleMessageId:R.lastVisibleMessageId||"",lastMessagePosition:R.lastMessagePosition||0,lastVisibleMessagePosition:R.lastVisibleMessagePosition||0,readPosition:R.readPosition||0,readPositionBadgeCount:R.readPositionBadgeCount||0,lastMessagePositionBadgeCount:R.lastMessagePositionBadgeCount||0,newMessageCount:R.newMessageCount||0,noBadgedNewMessageCount:R.noBadgedNewMessageCount||0,firstChatMessagePosition:R.firstChatMessagePosition||0,updateTime:Number(R.updateTime||0n),updateTimeMs:Number(R.updateTimeMs||0n),createTime:Number(R.createTime||0n),memberCount:R.memberCount||0,userCount:R.userCount||0,role:R.role,status:R.status,chatMode:R.chatMode,allowPost:R.allowPost}}}catch(e){return{success:!1,error:e.message}}}static extractLengthDelimitedField(l,e){let t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===e)return n}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return null}static tryDecodeAsUtf8(l){if(!l||l.length===0)return"";try{let e=Buffer.from(l).toString("utf8");return e.includes("\uFFFD")?"":e}catch{return""}}static isValidImageKey(l){return typeof l=="string"&&rR.test(l.trim())}static extractImageKeysFromString(l){let e=String(l||""),t=e.match(/img_v3_[a-z0-9]{4}_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/gi)||[],V=e.match(/img_v2_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/gi)||[],o=[...t,...V];if(o.length>0)return[...new Set(o)];let c=e.split(/(?=img_v[23]_)/g).filter(R=>/^img_v[23]_/.test(R)),a=[];for(let R of c){let A=R.match(/^(img_v3_[a-z0-9]{4}_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}|img_v2_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})/i);if(A){a.push(A[1]);continue}let n=R.match(/^img_v[23]_[a-zA-Z0-9_-]+/);if(!n)continue;let h=n[0];h.length<20||h.length>80||this.isValidImageKey(h)&&a.push(h)}return[...new Set(a)]}static tryDecodeChatHistoryImagePayload(l,e){if(!l||l.length===0)return;let t=l instanceof Uint8Array?l:new Uint8Array(l);try{let V=G(ye,t);if(V.imageKey){let o={imageKey:V.imageKey,cryptoInfo:V.crypto?this.extractCryptoInfo(V.crypto):null,fsUnit:V.fsUnit||null};e(o)}}catch{}try{let V=G(Nl,t),o=this.extractImageInfo(V);o?.imageKey&&e(o)}catch{}try{let V=G(me,t);if(V.imageKey&&e({imageKey:V.imageKey,cryptoInfo:null}),V.richText){let o=this.parsePostContent(V);for(let c of o.images||[])c?.imageKey&&e(c)}}catch{}try{let V=G(Ql,t),o=this.parsePostContent({richText:V,text:V.innerText||""});for(let c of o.images||[])c?.imageKey&&e(c)}catch{}try{let V=G(gt,t);if(V?.dictionary){for(let o of Object.values(V.dictionary))if(o?.tag===2&&o.property){let c=this.parseImageProperty(o.property);c?.imageKey&&e(c)}}}catch{}}static collectImageInfosFromChatHistoryContent(l={}){let e=[],t=new Set,V=a=>{let R=a?.imageKey?String(a.imageKey).trim():"";!this.isValidImageKey(R)||t.has(R)||(t.add(R),e.push({imageKey:R,cryptoInfo:a?.cryptoInfo||null}))};this.tryDecodeChatHistoryImagePayload(l?.richTextOrImageBytes,V),this.tryDecodeChatHistoryImagePayload(l?.richTextBytes,V),this.tryDecodeChatHistoryImagePayload(l?.richTextData,V);let o=l?.htmlText||this.tryDecodeAsUtf8(l?.richTextOrImageBytes)||"",c=this.extractImageKeysFromString(`${l?.text||""}
|
|
34
|
+
\`\`\``;case"code":return`\`${l.text||""}\``;case"text":return this.applyMarkdownMarks(l.text||"",l.marks||[]);case"mention":return l.text||"";case"link":{let e=this.applyMarkdownMarks(l.text||l.url||"",l.marks||[]);return l.url?`[${e}](${l.url})`:e}case"image":return l.imageKey?``:l.alt||"";default:return""}}static renderRichTextInlineNodesAsMarkdown(l){let e=[],t=[],V=()=>{t.length!==0&&(e.push(this.renderRichTextTextRunAsMarkdown(t)),t=[])};for(let o of l||[]){if(o?.type==="text"){t.push(o);continue}V(),e.push(this.renderRichTextAstAsMarkdown(o))}return V(),e.join("")}static renderRichTextListItemAsMarkdown(l){return this.renderRichTextAstAsMarkdown(l).replace(/\n+/g," ").trim()}static renderRichTextTextRunAsMarkdown(l){let e=(l||[]).filter(R=>R?.type==="text");if(e.length===0)return"";if(e.some(R=>(R.marks||[]).includes("underline")))return this.renderRichTextTextRunAsHtml(e);let t=["bold","strikethrough","italic","underline"],V={bold:{open:"**",close:"**"},strikethrough:{open:"~~",close:"~~"},italic:{open:"_",close:"_"},underline:{open:"<u>",close:"</u>"}},o="",c=[],a=R=>{let A=0;for(;A<c.length&&A<R.length&&c[A]===R[A];)A+=1;for(let n=c.length-1;n>=A;n-=1)o+=V[c[n]].close;for(let n=A;n<R.length;n+=1)o+=V[R[n]].open;c=R};for(let R of l){let A=t.filter(n=>(R.marks||[]).includes(n));a(A),o+=R.text||""}return a([]),o}static renderRichTextTextRunAsHtml(l){let e=["bold","strikethrough","italic","underline"],t={bold:"strong",italic:"em",strikethrough:"del",underline:"u"},V="",o=[],c=a=>{let R=0;for(;R<o.length&&R<a.length&&o[R]===a[R];)R+=1;for(let A=o.length-1;A>=R;A-=1)V+=`</${t[o[A]]}>`;for(let A=R;A<a.length;A+=1)V+=`<${t[a[A]]}>`;o=a};for(let a of l){let R=e.filter(A=>(a.marks||[]).includes(A));c(R),V+=this.escapeHtmlText(a.text||"")}return c([]),V}static escapeHtmlText(l){return String(l).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}static applyMarkdownMarks(l,e=[]){let t=l,V=new Set(e);return V.has("strikethrough")&&(t=`~~${t}~~`),V.has("italic")&&(t=`*${t}*`),V.has("bold")&&(t=`**${t}**`),V.has("underline")&&(t=`<u>${t}</u>`),t}static parseCardContent(l){if(!l||l.length===0)return{summary:"[\u7A7A\u5361\u7247]"};let e=this.extractCardJson(l);if(e)try{let o=JSON.parse(e);return this.parseCardJson(o,e)}catch{}try{let o=Buffer.from(l).toString("utf8");if(o.startsWith("{")){let c=JSON.parse(o);return this.parseCardJson(c,o)}}catch{}let t=Buffer.from(l),V=t.indexOf("{");if(V>=0){let o=0,c=-1;for(let a=V;a<t.length;a++)if(t[a]===123&&o++,t[a]===125&&o--,o===0){c=a;break}if(c>V)try{let a=t.slice(V,c+1).toString("utf8"),R=JSON.parse(a);return this.parseCardJson(R,a)}catch{}}return{summary:"[\u5361\u7247\u6D88\u606F]",rawContentBase64:Buffer.from(l).toString("base64")}}static extractCardJson(l){let e=Buffer.from(l),t=0;for(;t<e.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(e,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(e,t);if(t+=A,t+R>e.length)break;let n=e.subarray(t,t+R);if(t+=R,R>2&&n[0]===123)try{let h=n.toString("utf8");return JSON.parse(h),h}catch{}if(R>10){let h=this.extractCardJson(n);if(h)return h}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(e,t);t+=R}else if(c===5)t+=4;else if(c===1)t+=8;else break}return null}static parseCardJson(l,e){let t={json:l,rawJson:e,title:null,summary:null};if(t.title=this.pickFirstText([l.header?.title?.content,l.header?.property?.title?.content,l.header?.property?.title?.property?.content,l.header?.property?.mainTitle?.content,l.header?.property?.mainTitle?.property?.content,l.header?.property?.subtitle?.content,l.header?.property?.subtitle?.property?.content]),t.summary=this.pickFirstText([l.config?.summary?.content,l.config?.summary,l.summary?.content,l.summary]),!t.summary)if(t.title)t.summary=`[\u5361\u7247] ${t.title}`;else{let V=this.extractCardBodyText(l);t.summary=V?`[\u5361\u7247] ${V.substring(0,50)}`:"[\u5361\u7247\u6D88\u606F]"}return t}static extractCardBodyText(l){let e=[],t=new Set,V=c=>{if(typeof c!="string")return;let a=c.replace(/\s+/g," ").trim();a&&(/^https?:\/\//.test(a)||/^#[0-9a-fA-F]{6,8}$/.test(a)||/^(default|normal|small|medium|large)$/i.test(a)||t.has(a)||(t.add(a),e.push(a)))},o=(c,a=0)=>{if(!(!c||a>10||e.length>=8)){if(typeof c=="string"){V(c);return}if(Array.isArray(c)){for(let R of c)if(o(R,a+1),e.length>=8)break;return}typeof c=="object"&&(V(c.content),V(c.text),V(c.title),V(c.subtitle),c.text&&typeof c.text=="object"&&(V(c.text.content),V(c.text.text)),c.property&&typeof c.property=="object"&&(V(c.property.content),V(c.property.text),V(c.property.title),V(c.property.subtitle)),o(c.newBody,a+1),o(c.body,a+1),o(c.elements,a+1),o(c.fields,a+1),o(c.columns,a+1),o(c.actions,a+1),o(c.header,a+1),o(c.property,a+1),o(c.text,a+1),o(c.title,a+1),o(c.subtitle,a+1))}};return o(l),e.slice(0,3).join(" ")}static pickFirstText(l){for(let e of l){if(typeof e!="string")continue;let t=e.trim();if(t)return t}return null}static parseTextProperty(l){if(!l||l.length===0)return"";try{return G(ne,l).content||""}catch{let t=Buffer.from(l),V=0;for(;V<t.length;){let o=t[V];if(o===void 0)break;let c=o&7,a=o>>3;if(V++,c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(t,V);if(V+=A,a===1)return t.subarray(V,V+R).toString("utf8");V+=R}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(t,V);V+=R}else break}return""}}static parseImageProperty(l){let e={imageKey:null,cryptoInfo:null};if(!l||l.length===0)return e;let t=Buffer.from(l),V=0;for(;V<t.length&&!(V>=t.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(t,V);if(c===0)break;V+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(t,V);V+=n;let h=t.subarray(V,V+A);if(V+=A,R===2){let d=h.toString("utf8").trim();this.isValidImageKey(d)&&(e.imageKey=d)}else if(R===17)try{let d=G(ye,h);this.isValidImageKey(d.imageKey)&&(e.imageKey=d.imageKey.trim()),d.crypto&&(e.cryptoInfo=this.extractCryptoInfo(d.crypto))}catch{let g=this.extractCryptoFromBytes(h);g&&(e.cryptoInfo=g)}if(A>10&&R!==17)try{let d=G(ye,h);!e.imageKey&&this.isValidImageKey(d.imageKey)&&(e.imageKey=d.imageKey.trim()),d.crypto&&(e.cryptoInfo=this.extractCryptoInfo(d.crypto))}catch{let g=this.extractCryptoFromBytes(h);g&&(e.cryptoInfo=g)}}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(t,V);V+=A}else break}if(!e.imageKey){let o=t.toString("utf8"),c=this.extractImageKeysFromString(o);c.length>0&&(e.imageKey=c[0])}return e.cryptoInfo||(e.cryptoInfo=this.extractCryptoFromBytes(t)),e}static parseTextMessageContent(l){let e=Buffer.from(l),t=0,V="",o=null;for(;t<e.length&&!(t>=e.length);){let{value:c,bytesRead:a}=this.readVarintWithLength(e,t);if(a===0)break;t+=a;let R=c&7,A=c>>3;if(R===2){let{value:n,bytesRead:h}=this.readVarintWithLength(e,t);if(t+=h,t+n>e.length)break;let d=e.subarray(t,t+n);t+=n,A===1&&n>0?V=d.toString("utf8"):A===3&&(o=d)}else if(R===0){let{bytesRead:n}=this.readVarintWithLength(e,t);t+=n}else break}return V||(o?this.parseRichTextFromBytes(o):"")}static parseRichTextFromBytes(l){let e=0,t="",V=null;for(;e<l.length&&!(e>=l.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);e+=A,R===2&&A>0?t=h.toString("utf8"):R===3&&(V=h)}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(l,e);e+=A}else break}return t||(V?this.extractTextFromElementsBytes(V):"")}static extractTextFromElementsBytes(l){let e=[],t=0;for(;t<l.length&&!(t>=l.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1){let h=this.extractTextFromMapEntry(n);h&&e.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e.join("")}static extractTextFromMapEntry(l){let e=0,t=null;for(;e<l.length&&!(e>=l.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(l,e);if(o===0)break;e+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,e);if(e+=A,e+R>l.length)break;let n=l.subarray(e,e+R);e+=R,a===2&&(t=n)}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,e);e+=R}else break}return t?this.extractTextFromRichTextElement(t):""}static extractTextFromRichTextElement(l){let e=0,t=0,V=null;for(;e<l.length&&!(e>=l.length);){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===0){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);e+=n,R===1&&(t=A)}else if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);e+=A,R===3&&(V=h)}else break}return t===1&&V?this.parseTextPropertyBytes(V):""}static parseTextPropertyBytes(l){let e=0;for(;e<l.length&&!(e>=l.length);){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===1)return A.toString("utf8")}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return""}static tryDecodeTextFromBytes(l){if(!l||l.length===0)return"";let e=Buffer.from(l),t=0;for(;t<e.length&&!(t>=e.length);){let{value:V,bytesRead:o}=this.readVarintWithLength(e,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(e,t);if(t+=A,t+R>e.length)break;let n=e.subarray(t,t+R);if(t+=R,a===1&&R>0)try{let h=n.toString("utf8");if(h&&!/[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(h))return h}catch{}if(a===14&&R>0){let h=this.tryExtractInnerText(n);if(h)return h}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(e,t);t+=R}else break}return""}static tryExtractInnerText(l){let e=0;for(;e<l.length&&!(e>=l.length);){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===2&&a>0)try{let n=A.toString("utf8");if(n&&!/[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(n))return n}catch{}}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return""}static readVarintWithLength(l,e){let t=0,V=0,o=0,c;do c=l[e+o],V<28?t|=(c&127)<<V:t+=(c&127)*2**V,o++,V+=7;while(c&128);return{value:t,bytesRead:o}}static extractCryptoFromBytes(l,e=0){if(!l||l.length===0||e>6)return null;let t=Buffer.from(l);try{let o=G(Il,t),c=this.extractCryptoInfo(o);if(c?.secret&&c?.nonce)return c}catch{}try{let o=G(ye,t);if(o?.crypto){let c=this.extractCryptoInfo(o.crypto);if(c?.secret&&c?.nonce)return c}}catch{}try{let o=G(dt,t);if(o?.crypto){let c=this.extractCryptoInfo(o.crypto);if(c?.secret&&c?.nonce)return c}}catch{}let V=0;for(;V<t.length;){let{value:o,bytesRead:c}=this.readVarintWithLength(t,V);if(!c)break;V+=c;let a=o&7;if(a===2){let{value:R,bytesRead:A}=this.readVarintWithLength(t,V);if(V+=A,R<0||V+R>t.length)break;let n=t.subarray(V,V+R);V+=R;let h=this.extractCryptoFromBytes(n,e+1);if(h?.secret&&h?.nonce)return h}else if(a===0){let{bytesRead:R}=this.readVarintWithLength(t,V);V+=R}else if(a===1)V+=8;else if(a===5)V+=4;else break}return null}static isValidImageCryptoInfo(l){if(!l?.secret||!l?.nonce)return!1;let e=Buffer.from(l.secret).length,t=Buffer.from(l.nonce).length;return e===32&&t===12}static getCryptoFingerprint(l){if(!this.isValidImageCryptoInfo(l))return"";let e=Buffer.from(l.secret).toString("hex"),t=Buffer.from(l.nonce).toString("hex");return e.slice(0,16)+":"+t.slice(0,8)}static extractDirectCryptoInfo(l){if(!l||l.length===0)return null;try{let e=G(Il,l),t=this.extractCryptoInfo(e);if(this.isValidImageCryptoInfo(t))return t}catch{}return null}static collectCryptoBlocksFromPayload(l,e=0,t=0,V=10,o=[]){if(!l||t>V)return o;let c=l instanceof Buffer?l:Buffer.from(l);if(c.length===0)return o;let a=0;for(;a<c.length;){let{value:R,bytesRead:A}=this.readVarintWithLength(c,a);if(!A)break;a+=A;let n=R&7;if(n===2){let{value:h,bytesRead:d}=this.readVarintWithLength(c,a);if(a+=d,h<0||a+h>c.length)break;let g=a,E=a+h,X=c.subarray(g,E),r=this.extractDirectCryptoInfo(X);r&&o.push({offset:e+g,end:e+E,cryptoInfo:r,fingerprint:this.getCryptoFingerprint(r)}),this.collectCryptoBlocksFromPayload(X,e+g,t+1,V,o),a=E}else if(n===0){let{bytesRead:h}=this.readVarintWithLength(c,a);if(!h)break;a+=h}else if(n===1)a+=8;else if(n===5)a+=4;else break}return o}static findImageKeyOccurrencesInBuffer(l,e){let t=[];for(let V of e){let o=0;for(;o<l.length;){let c=l.indexOf(V,o,"utf8");if(c===-1)break;t.push({imageKey:V,offset:c,end:c+Buffer.byteLength(V,"utf8")}),o=c+1}}return t.sort((V,o)=>V.offset-o.offset)}static cacheImageCryptoFromCmd77Payload(l){if(!l||l.length===0)return 0;let e=l instanceof Buffer?l:Buffer.from(l),t=this.extractImageKeysFromString(e.toString("utf8"));if(t.length===0)return 0;let V=this.findImageKeyOccurrencesInBuffer(e,t);if(V.length===0)return 0;let o=this.collectCryptoBlocksFromPayload(e);if(o.length===0)return 0;let c=new Map;for(let n of o){let h=n.offset+":"+n.fingerprint;c.has(h)||c.set(h,n)}let a=Array.from(c.values()),R=new Map;for(let n of V){let h=a.filter(m=>{let W=m.offset-n.end;return W>=0&&W<=2048}),d=h.length>0?h:a.filter(m=>Math.abs(m.offset-n.end)<=512);if(d.length===0)continue;let g=null;for(let m of d){let W=Math.abs(m.offset-n.end),u=m.offset>=n.end?0:256,I=W+u;(!g||I<g.score)&&(g={block:m,score:I})}if(!g)continue;let E=g.block.fingerprint;if(!E)continue;let X=R.get(n.imageKey);X||(X=new Map,R.set(n.imageKey,X));let r=X.get(E)||{count:0,bestScore:Number.MAX_SAFE_INTEGER,cryptoInfo:g.block.cryptoInfo};r.count+=1,r.bestScore=Math.min(r.bestScore,g.score),X.set(E,r)}let A=0;for(let[n,h]of R.entries()){let d=Array.from(h.entries());if(d.length===0)continue;d.sort((E,X)=>{let[,r]=E,[,m]=X;return m.count!==r.count?m.count-r.count:r.bestScore-m.bestScore});let[,g]=d[0];this.isValidImageCryptoInfo(g.cryptoInfo)&&(_l(n,g.cryptoInfo),A+=1)}return A}static cacheImageCryptoFromGatewayResponseBuffer(l){if(!l||l.length===0)return 0;try{let e=l instanceof Uint8Array?l:new Uint8Array(l),t=G(F,e);return!t.payload||t.payload.length===0?0:this.cacheImageCryptoFromCmd77Payload(t.payload)}catch{return 0}}static cacheImageCryptoFromCmd77ResponseBuffer(l){return this.cacheImageCryptoFromGatewayResponseBuffer(l)}static readVarint(l,e){let t=0,V=0,o;do o=l[e],t|=(o&127)<<V,e++,V+=7;while(o&128);return t}static varintLength(l,e){let t=0;for(;l[e+t]&128;)t++;return t+1}static buildReplyRequest(l,e,t,V={}){let{rootId:o,parentId:c}=V,a=te(),R=te(),A=i(ne,{content:l}),n=i(me,{text:l,richText:{elementIds:[R],innerText:l,elements:{dictionary:{[R]:{tag:1,property:b(ne,A)}}}}}),h=i(xe,{type:4,chatId:t,rootId:o||"",parentId:c||"",cid:a,isNotified:!0,sendToChat:!1,version:1,isThreadGroupTopic:!1,content:n}),d=i(F,{payloadType:1,cmd:5,cid:e,payload:b(xe,h)});return Buffer.from(b(F,d))}static decodePutMessageResponse(l){try{if(!l||l.length===0)return{success:!1,error:"Empty packet"};let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=G(_V,e.payload);if(!t.message)return{success:!1,error:"PutMessageResponse missing message"};let V={success:!0};return V.message=this.parseMessageContent(t.message,e.sid),t.positions&&Object.keys(t.positions).length>0&&(V.positions=this._normalizeProtoValue(t.positions)),t.thread&&(V.thread=this._normalizeProtoValue(t.thread)),t.feedCard&&(V.feedCard=this._normalizeProtoValue(t.feedCard)),t.feedCards&&Object.keys(t.feedCards).length>0&&(V.feedCards=this._normalizeProtoValue(t.feedCards)),t.syncToChatMessage&&(V.syncToChatMessage=this.parseMessageContent(t.syncToChatMessage,e.sid)),V}catch(e){return{success:!1,error:e.message}}}static buildAckPacket(l){let e=Date.now(),t=i(F,{payloadType:1,cmd:1,sid:l}),V=i(Rl,{seqid:aV.parse(e),logid:aV.parse(e),service:1,method:1,headers:[{key:"x-request-time",value:`${e}000`}],payloadType:"pb",payload:b(F,t)});return Buffer.from(b(Rl,V))}static buildGetUserProfileRequest(l,e){let t=[];t.push(8,1);let V=new TextEncoder().encode(e);t.push(18),S(t,V.length),t.push(...V),t.push(40,2),t.push(88,1),t.push(96,1),t.push(112,1);let o=new Uint8Array(t),c=i(F,{payloadType:1,cmd:5031,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserProfileResponse(l){let e=G(F,l);if(!e.payload)return null;let t=Buffer.from(e.payload);return this.parseUserProfilePayload(t)}static parseUserProfilePayload(l){let e={userId:null,name:null,enName:null,avatarUrl:null,avatarKey:null,tenantId:null,alias:null,memoText:null,memoPicture:null,memoPictureV2:[]},t=l.toString("utf8"),V=t.match(/\d{19}/g);if(V&&(e.userId=V[0]),e.userId){let n=Buffer.from(e.userId),h=0,d=0;for(;(h=l.indexOf(n,d))!==-1;){if(h>=2&&l[h-2]===10&&l[h-1]===19){let g=h+n.length;if(g<l.length&&l[g]===18){let E=l[g+1];if(E>0&&E<=30&&g+2+E<=l.length){let X=l.subarray(g+2,g+2+E);try{let r=X.toString("utf8");(/^[\u4e00-\u9fa5]{2,10}$/.test(r)||/^[a-zA-Z\s]+$/.test(r))&&(e.name=r)}catch{}}}break}d=h+1}}if(e.userId){let n=Buffer.from(e.userId),h=l.lastIndexOf(n);if(h>0){let d=Math.min(l.length,h+2e3),X=l.subarray(h,d).toString("utf8").match(/([a-z]+(?: [a-z]+)+)/);X&&X[0].length<30&&(e.enName=X[0])}}let o=t.match(/https:\/\/s\d-imfile\.feishucdn\.com\/static-resource\/v\d\/[^\s~?]+/);o&&(e.avatarUrl=o[0]);let c=t.match(/v3_[a-z0-9]{4}_[a-f0-9-]+/i);c&&(e.avatarKey=c[0]);let a=t.match(/赵天雄[\s\S]*?\n\x05zh_cn\x12\x06([^\x00-\x1f]{2,20})/);if(a&&a[1]&&a[1]!==e.name&&(e.alias=a[1].replace(/�+$/g,"")),e.alias===null){let n=t.match(/B-ALIAS[\s\S]*?\{"text":\{"default_val":"([^"]*)"\}\}/);n&&(e.alias=n[1])}let R=t.indexOf('{"memo_text":"'),A=']}"';if(R!==-1){let n=t.indexOf(A,R),h=n===-1?null:t.slice(R,n+A.length-1);if(h)try{let d=JSON.parse(h);e.memoText=d.memo_text??null,e.memoPicture=d.memo_picture??null,e.memoPictureV2=Array.isArray(d.memo_picture_v2)?d.memo_picture_v2:[]}catch{let d=t.match(/\{"memo_text":"((?:\\.|[^"])*)"/);if(d)try{e.memoText=JSON.parse(`"${d[1]}"`)}catch{e.memoText=d[1]}}}return e}static buildGetUserInfoByIdRequest(l,e){let t=[],V=Buffer.from(e,"utf-8");t.push(10,V.length,...V),t.push(16,1);let o=new Uint8Array(t),c=i(F,{payloadType:1,cmd:46,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserInfoByIdResponse(l){let e=G(F,l);if(!e.payload)return{success:!1,error:"No payload in response"};let t=Buffer.from(e.payload);return this.parseUserInfoPayload(t)}static buildGetUserProfileCardRequest(l,e){let t=BigInt(e),V=[8];this.pushVarintBigInt(V,t);let o=new Uint8Array(V),c=i(F,{payloadType:1,cmd:5017,cid:l,payload:o});return Buffer.from(b(F,c))}static decodeGetUserProfileCardResponse(l){let e=G(F,l);if(!e.payload)return{success:!1,error:"No payload in response"};if(this._isPacketError(e))return{success:!1,error:`Packet status: ${e.status}`};let t=Buffer.from(e.payload);return this.parseUserProfileCardPayload(t)}static parseUserProfileCardPayload(l){let e={success:!0,orgName:null,description:null,email:null,displayName:null,displayNameLocalized:null,avatarKey:null,profileUserId:null,alias:null,profileFieldPolicies:[]},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===2)e.orgName=n.toString("utf8");else if(a===3)e.description=n.toString("utf8");else if(a===5)e.email=n.toString("utf8");else if(a===7)e.displayName=n.toString("utf8");else if(a===11)e.displayNameLocalized=n.toString("utf8");else if(a===19)e.avatarKey=n.toString("utf8");else if(a===22)e.profileUserId=n.toString("utf8");else if(a===24)e.alias=n.toString("utf8");else if(a===50){let h=this.parseUserProfileFieldPolicy(n);h&&e.profileFieldPolicies.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return e}static parseUserProfileFieldPolicy(l){let e={key:null,locale:null,visible:null,editable:null,mode:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===1?e.key=n.toString("utf8"):a===5&&(e.locale=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3?e.visible=R:a===4?e.editable=R:a===6&&(e.mode=R)}else if(c===1)t+=8;else if(c===5)t+=4;else break}return e.key?e:null}static parseUserInfoPayload(l){let e={userId:null,name:null,isBot:!1,userType:1,avatarKey:null};try{let t=l.toString("utf8"),V=t.match(/\d{19}/);V&&(e.userId=V[0]);let o=Buffer.from([10,3,98,111,116]);if(l.includes(o)&&(e.isBot=!0,e.userType=2),e.userId){let a=Buffer.from(e.userId),R=l.indexOf(a);for(;R!==-1;){let A=R+a.length;if(A<l.length&&l[A]===18){let n=l[A+1];if(n>0&&n<=50&&A+2+n<=l.length){let h=l.subarray(A+2,A+2+n);try{let d=h.toString("utf8");if(d.length>0&&d.length<=30){e.name=d;break}}catch{}}}R=l.indexOf(a,R+1)}}let c=t.match(/v3_[a-z0-9]{4}_[a-f0-9-]+/i);if(c)e.avatarKey=c[0];else{let a=t.match(/[a-f0-9]{20,}/);a&&(e.avatarKey=a[0])}}catch(t){return{success:!1,error:t.message}}return{success:!0,...e}}static RSVP_STATUS={ACCEPT:1,DECLINE:2,TENTATIVE:3};static REPLY_CALENDAR_EVENT_INVITATION_REPLY_TYPES={ACCEPT:Ke.ACCEPT,DECLINE:Ke.DECLINE,TENTATIVE:Ke.TENTATIVE,DELETE:Ke.DELETE,NEEDS_ACTION:Ke.NEEDS_ACTION};static buildReplyCalendarEventInvitationRequest(l,e,t,V={}){let o=i(Pt,{calendarEventKey:i(OV,{uniqueKey:e.uniqueKey,calendarId:e.calendarId,originalTime:BigInt(e.originalTime)}),replyType:t,quitMeeting:V.quitMeeting??!1,needsBriefEvents:V.needsBriefEvents??!1,useAttendeePageToken:V.useAttendeePageToken??!1,...V.rsvpCommentInfo?{rsvpCommentInfo:i(MV,{replyCommentId:V.rsvpCommentInfo.replyCommentId??"",comment:V.rsvpCommentInfo.comment??"",inviteOperatorId:V.rsvpCommentInfo.inviteOperatorId??""})}:{}}),c=i(F,{payloadType:1,cmd:1020002,cid:l,payload:b(Pt,o)});return Buffer.from(b(F,c))}static buildCalendarRsvpRequest(l,e,t,V){let o=[],c=[],a=new TextEncoder().encode(e);c.push(10),S(c,a.length),c.push(...a);let R=new TextEncoder().encode(t);c.push(18),S(c,R.length),c.push(...R),c.push(24,0);let A=new Uint8Array(c);o.push(10),S(o,A.length),o.push(...A),o.push(16),o.push(V),o.push(40,1),o.push(48,1);let n=new Uint8Array(o),h=i(F,{payloadType:1,cmd:1020002,cid:l,payload:n});return Buffer.from(b(F,h))}static buildCalendarEventDetailRequest(l,e,t=0){let V=[],o=[],c=new TextEncoder().encode(e);if(o.push(10),S(o,c.length),o.push(...c),t!==0){o.push(16);let n=t<<1^t>>31;this.pushVarint(o,n)}o.push(32,0),o.push(40,1),o.push(48,3);let a=new Uint8Array(o);V.push(10),S(V,a.length),V.push(...a);let R=new Uint8Array(V),A=i(F,{payloadType:1,cmd:1010048,cid:l,payload:R});return Buffer.from(b(F,A))}static buildGetBusyUserRequest(l,e,t,V,o={}){let c=[];for(let R of e||[]){let A=new TextEncoder().encode(String(R));c.push(10),S(c,A.length),c.push(...A)}if(c.push(16),this.pushVarintBigInt(c,BigInt(t)),c.push(24),this.pushVarintBigInt(c,BigInt(V)),o.uid){let R=new TextEncoder().encode(String(o.uid));c.push(34),S(c,R.length),c.push(...R)}o.originalTime!==void 0&&o.originalTime!==null&&(c.push(40),this.pushVarintBigInt(c,BigInt(o.originalTime))),o.bidirectionalSyncOccupyBusy!==void 0&&c.push(48,o.bidirectionalSyncOccupyBusy?1:0),o.bidirectionalSyncOptimizeFg!==void 0&&c.push(56,o.bidirectionalSyncOptimizeFg?1:0);let a=i(F,{payloadType:1,cmd:1010020,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static buildCreateCalendarEventRequest(l,e,t={},V={}){let o=Ge(e,"calendarId"),{start:c,end:a}=CR(t.startTime,t.endTime,"startTime","endTime"),R=Ie(t.timezone,t.startTimezone,t.endTimezone),A=t.uniqueKey||RV.randomUUID(),n=t.originalTime===void 0||t.originalTime===null||t.originalTime===""?c:ee(t.originalTime,"originalTime"),h=String(Ie(t.eventId,"0")),d=String(Ie(t.creatorCalendarId,o)),g=String(Ie(t.organizerCalendarId,o)),E=De(t.reminders).map((N,Y)=>({calendarEventId:String(Ie(N.calendarEventId,N.calendar_event_id,"0")),minutes:bR(N.minutes,Go(Y,"minutes")),method:de(N.method,El,El.default,Go(Y,"method"))})),X=[...De(t.locations),...De(t.location)].map((N,Y)=>({name:N.name??"",address:N.address??"",type:de(N.type,Fl,Fl.ordinary,sV(Y,"type")),...N.latitude!==void 0?{latitude:mo(N.latitude,sV(Y,"latitude"))}:{},...N.longitude!==void 0?{longitude:mo(N.longitude,sV(Y,"longitude"))}:{}})),r=BR(t.attendees),m=i(sl,{id:h,key:A,originalTime:n,calendarId:o,organizerCalendarId:g,creatorCalendarId:d,successorCalendarId:t.successorCalendarId??"0",summary:t.summary??"",rrule:t.rrule??"",startTime:c,endTime:a,status:de(t.status,gl,gl.confirmed,"status"),source:t.source??jV.PC_CLIENT,attendeeSource:ql(t.attendeeSource??1,"attendeeSource"),isDeleted:!1,isAllDay:t.isAllDay??!1,isCrossTenant:t.isCrossTenant??!1,guestCanInvite:t.guestCanInvite??!0,guestCanSeeOtherGuests:t.guestCanSeeOtherGuests??!0,guestCanModify:t.guestCanModify??!1,selfAttendeeStatus:de(t.selfAttendeeStatus,oV,oV.accept,"selfAttendeeStatus"),color:ql(t.color??-1,"color"),version:BigInt(ql(t.version??0,"version")),visibility:de(t.visibility,Zl,Zl.default,"visibility"),isFree:t.isFree??!1,locations:X,reminders:E,...r.length>0?{attendees:r}:{},...t.description!==void 0||t.docsDescription!==void 0||t.docs_description!==void 0?{description:t.description??"",...t.docsDescription!==void 0||t.docs_description!==void 0?{docsDescription:t.docsDescription??t.docs_description}:{}}:{},...t.attachments?{attachments:t.attachments}:{},...t.videoConfig?{videoConfig:t.videoConfig}:{},...t.encryptionInfo?{encryptionInfo:t.encryptionInfo}:{},...bo(R)?{startTimezone:Ie(t.startTimezone,R),endTimezone:Ie(t.endTimezone,R)}:{}}),W=b(sl,m),u=[];u.push(10),S(u,W.length),u.push(...W),V.notificationType!==void 0&&V.notificationType!==null&&V.notificationType!==""&&(u.push(16),this.pushVarint(u,de(V.notificationType,dl,dl.default,"notificationType")));let I=i(F,{payloadType:1,cmd:1002003,cid:l,payload:new Uint8Array(u)});return Buffer.from(b(F,I))}static buildDeleteCalendarEventRequest(l,e,t,V={}){let o=[],c=V.deleteType??0,a=V.needNotification??!0,R=new TextEncoder().encode(String(e));o.push(10),S(o,R.length),o.push(...R);let A=new TextEncoder().encode(String(t));o.push(18),S(o,A.length),o.push(...A),o.push(24),this.pushVarint(o,Number(c)),o.push(32),this.pushVarint(o,a?1:0);let n=i(F,{payloadType:1,cmd:1002005,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,n))}static buildUpdateCalendarEventRequest(l,e,t={}){let V=[],o=i(sl,e),c=b(sl,o);V.push(10),S(V,c.length),V.push(...c),t.span!==void 0&&(V.push(16),this.pushVarint(V,Number(t.span))),t.instanceStartTime!==void 0&&t.instanceStartTime!==null&&(V.push(24),this.pushVarintBigInt(V,BigInt(t.instanceStartTime))),t.notificationType!==void 0&&(V.push(32),this.pushVarint(V,Number(t.notificationType)));let a=i(F,{payloadType:1,cmd:1002004,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,a))}static buildWebListCalendarEventsRequest(l,e,t,V,o={}){let c=o.limit??100,a=[],R=new TextEncoder().encode(String(e));a.push(10),S(a,R.length),a.push(...R),a.push(16),this.pushVarintBigInt(a,BigInt(t)),a.push(24),this.pushVarintBigInt(a,BigInt(V)),a.push(40),this.pushVarintBigInt(a,BigInt(c));let A=[10];S(A,a.length),A.push(...a);let n=i(F,{payloadType:1,cmd:1002001,cid:l,payload:new Uint8Array(A)});return Buffer.from(b(F,n))}static buildCreateMeetingMinuteRequest(l,e,t,V={}){let o=[],c=V.originalTime??0,a=new TextEncoder().encode(String(e));o.push(10),S(o,a.length),o.push(...a);let R=new TextEncoder().encode(String(t));o.push(18),S(o,R.length),o.push(...R),o.push(24),this.pushVarintBigInt(o,BigInt(c));let A=i(F,{payloadType:1,cmd:1010028,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,A))}static buildTransferCalendarEventRequest(l,e,t,V,o={}){let c=[],a=[],R=o.originalTime??0,A=o.transferFlag??1,n=new TextEncoder().encode(String(e));a.push(10),S(a,n.length),a.push(...n);let h=new TextEncoder().encode(String(t));a.push(18),S(a,h.length),a.push(...h),a.push(24),this.pushVarintBigInt(a,BigInt(R)),c.push(10),S(c,a.length),c.push(...a),c.push(16),this.pushVarintBigInt(c,BigInt.asUintN(32,BigInt(V))),c.push(24),this.pushVarintBigInt(c,BigInt(A));let d=i(F,{payloadType:1,cmd:1010022,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,d))}static buildWebShareCalendarEventRequest(l,e,t,V,o={}){let c=[],a=o.originalTime??0;for(let h of e)c.push(8),this.pushVarintBigInt(c,BigInt(h));let R=new TextEncoder().encode(String(t));c.push(18),S(c,R.length),c.push(...R);let A=new TextEncoder().encode(String(V));c.push(26),S(c,A.length),c.push(...A),c.push(32),this.pushVarintBigInt(c,BigInt(a));let n=i(F,{payloadType:1,cmd:1002012,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,n))}static buildUpgradeToMeetingRequest(l,e,t={}){let V=t.originalTime??0,o=[],c=new TextEncoder().encode(String(e.eventId));o.push(10),S(o,c.length),o.push(...c);let a=new TextEncoder().encode(String(e.uid));o.push(18),S(o,a.length),o.push(...a);let R=new TextEncoder().encode(String(e.calendarId));if(o.push(26),S(o,R.length),o.push(...R),o.push(32),this.pushVarintBigInt(o,BigInt(V)),e.creatorId!==void 0&&e.creatorId!==null){let g=new TextEncoder().encode(String(e.creatorId));o.push(42),S(o,g.length),o.push(...g)}if(e.organizerId!==void 0&&e.organizerId!==null){let g=new TextEncoder().encode(String(e.organizerId));o.push(50),S(o,g.length),o.push(...g)}o.push(64),this.pushVarintBigInt(o,BigInt(e.startTime));let A=new TextEncoder().encode(String(e.startTimezone));if(o.push(74),S(o,A.length),o.push(...A),o.push(80),this.pushVarintBigInt(o,BigInt(e.endTime)),e.endTimezone!==void 0&&e.endTimezone!==null){let g=new TextEncoder().encode(String(e.endTimezone));o.push(90),S(o,g.length),o.push(...g)}if(t.rrule){let g=new TextEncoder().encode(String(t.rrule));o.push(114),S(o,g.length),o.push(...g)}o.push(200,1),this.pushVarint(o,0);let n=new TextEncoder().encode(String(e.summary));o.push(234,1),S(o,n.length),o.push(...n);let h=[];h.push(10),S(h,o.length),h.push(...o),h.push(16),this.pushVarint(h,1),h.push(24),this.pushVarint(h,1);let d=i(F,{payloadType:1,cmd:1010014,cid:l,payload:new Uint8Array(h)});return Buffer.from(b(F,d))}static decodeUpgradeToMeetingResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let g=this.extractErrorMessage(e.payload);if(g)return{success:!1,error:g}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty response payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=null,o=null,c=null,a=t.find(g=>g.fieldNo===1&&g.wireType===2);if(a){let g=this.parseProtobufFields(a.data);V=this.getStringField(g,1),o=this.getStringField(g,2);let E=this.getVarintField(g,3,null);c=E!==null?E!==0:null}let R={},A=t.filter(g=>g.fieldNo===2&&g.wireType===2);for(let g of A){let E=this.parseProtobufFields(g.data),X=this.getStringField(E,1),r=this.getStringField(E,2);X&&(R[X]=r)}let n=[],h=null,d=t.find(g=>g.fieldNo===3&&g.wireType===2);if(d){let g=this.parseProtobufFields(d.data);h=this.getStringField(g,29);let E=g.filter(X=>X.fieldNo===26&&X.wireType===2);for(let X of E){let r=this.parseProtobufFields(X.data),m=this.getStringField(r,1),W=this.getStringField(r,2),u=this.getVarintField(r,6,null),I=this.getVarintField(r,23,null);W&&n.push({attendeeCalendarId:W,displayName:m,status:u,individualAttendeeType:I})}}return V?o?{success:!0,meetingId:V,meetingChatId:o,isFirstEntrance:c,eventMeetingMap:R,attendees:n,summary:h}:{success:!1,error:"Missing meetingChatId in response"}:{success:!1,error:"Missing meetingId in response"}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static pushVarint(l,e){for(;e>127;)l.push(e&127|128),e>>>=7;l.push(e)}static pushVarintBigInt(l,e){let t=BigInt(e);for(;t>127n;)l.push(Number(t&0x7fn|0x80n)),t>>=7n;l.push(Number(t))}static decodeCalendarRsvpResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Status: ${e.status}`}}return{success:!0}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeReplyCalendarEventInvitationResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,data:{},rsvpCommentFailed:[]};let t=G(Eo,e.payload),V=this._normalizeProtoValue(t);return{success:!0,data:V,calendarEvent:V.calendarEvent,rsvpCommentFailed:V.rsvpCommentFailed||[]}}catch(e){return{success:!1,error:e.message}}}static extractErrorMessage(l){try{if(l[0]===10&&l.length>2){let e=l[1];if(e>0&&e<l.length-2){let t=Buffer.from(l.slice(2,2+e)).toString("utf8");if(/^[A-Za-z][A-Za-z0-9_]+$/.test(t))return t}}}catch{}return null}static decodeCalendarEventDetailResponse(l){try{let e=G(F,l);return!e.payload||e.payload.length<10?{success:!1,error:"Empty payload",events:[]}:{success:!0,events:this.parseCalendarEventPayload(Buffer.from(e.payload))}}catch(e){return{success:!1,error:e.message,events:[]}}}static decodeGetBusyUserResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,calendarBusyMap:{}};let t=this.parseProtobufFields(Buffer.from(e.payload)),V={};for(let o of t){if(o.fieldNo!==1||o.wireType!==2)continue;let c=this.parseProtobufFields(o.data),a=this.getStringField(c,1)||"",R=c.find(A=>A.fieldNo===2&&A.wireType===0);!a||!R||(V[a]=!!R.val)}return{success:!0,calendarBusyMap:V}}catch(e){return{success:!1,error:e.message}}}static decodeCreateCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return{success:!0,data:{}}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeDeleteCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let c=this.extractErrorMessage(e.payload);if(c)return{success:!1,error:c}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,data:{}};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,5);if(!V)return{success:!0,data:{}};let o=Buffer.from(V).toString("utf8");try{return{success:!0,data:JSON.parse(o)}}catch{return{success:!0,data:{raw:o}}}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeUpdateCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return{success:!0,data:{}}}catch(e){return{success:!1,error:e.message}}}static decodeWebListCalendarEventsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let R=this.extractErrorMessage(e.payload);if(R)return{success:!1,error:R}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,calendarId:"",events:[]};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,1);if(!V)return{success:!0,calendarId:"",events:[]};let o=this.parseProtobufFields(Buffer.from(V)),c=this.getStringField(o,1)||"",a=[];for(let R of o){if(R.fieldNo!==2||R.wireType!==2)continue;let A=this.parseProtobufFields(Buffer.from(R.data));a.push({eventKey:this.getStringField(A,1)||"",uid:this.getStringField(A,2)||"",startTime:this.getVarintField(A,25,0),startTimezone:this.getStringField(A,26)||"",endTime:this.getVarintField(A,27,0),endTimezone:this.getStringField(A,28)||"",summary:this.getStringField(A,29)||""})}return{success:!0,calendarId:c,events:a}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeCreateMeetingMinuteResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty response payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getStringField(t,1);return V?{success:!0,meetingMinuteUrl:V}:{success:!1,error:"Missing meeting minute URL in response"}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeTransferCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,events:[]}:{success:!0,events:this.parseProtobufFields(Buffer.from(e.payload)).filter(o=>o.fieldNo===1&&o.wireType===2).map(o=>this.parseTransferredCalendarEvent(o.data))}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static decodeWebShareCalendarEventResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,sharedFailedChats:[]}:{success:!0,sharedFailedChats:this.parseProtobufFields(Buffer.from(e.payload)).filter(o=>o.fieldNo===1&&o.wireType===0).map(o=>Number(o.val))}}catch(e){let t=this.extractErrorMessage(l);return t?{success:!1,error:t}:{success:!1,error:e.message}}}static parseCalendarEventPayload(l){let e=[],t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===2){let h=this.parseCalendarEvent(n);h&&e.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e}static parseCalendarEvent(l){let e={userId:null,eventId:null,title:null,startTime:null,endTime:null,timezone:null,organizer:null,attendees:[],meetingUrl:null,rsvpStatus:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1)e.userId=n.toString("utf8");else if(a===2)e.eventId=n.toString("utf8");else if(a===4)this.parseEventDetails(n,e);else if(a===5){let h=this.parseRsvpInfo(n);h&&(e.rsvpStatus=h.status)}else if(a===20){let h=this.parseAttendeeInfo(n);h&&e.attendees.push(h)}}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else break}return e.eventId||e.title?e:null}static parseTransferredCalendarEvent(l){let e=this.parseProtobufFields(l);return{eventKey:this.getStringField(e,1)||"",summary:this.getStringField(e,29)||"",description:this.getStringField(e,30)||"",startTime:this.getVarintField(e,8,null),timezone:this.getStringField(e,9)||"",endTime:this.getVarintField(e,10,null),meetingMinuteUrl:this.getStringField(e,51)||""}}static parseEventDetails(l,e){let t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===8?e.title=n.toString("utf8"):a===12&&(e.timezone=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===11?e.startTime=R:a===13&&(e.endTime=R)}else break}}static parseRsvpInfo(l){let e={userId:null,status:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);t+=R,a===2&&(e.userId=n.toString("utf8"))}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3&&(e.status=R)}else break}return e}static parseAttendeeInfo(l){let e={name:null,userId:null,rsvpStatus:null,type:null},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===1)e.name=n.toString("utf8");else if(a===2)e.userId=n.toString("utf8");else if(a===11){let h=this.extractTypeFromNested(n);h&&(e.type=h)}}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===3&&(e.rsvpStatus=R)}else break}return e.name||e.userId?e:null}static extractTypeFromNested(l){let e=0;for(;e<l.length;){let{value:t,bytesRead:V}=this.readVarintWithLength(l,e);if(V===0)break;e+=V;let o=t&7,c=t>>3;if(o===2){let{value:a,bytesRead:R}=this.readVarintWithLength(l,e);if(e+=R,e+a>l.length)break;let A=l.subarray(e,e+a);if(e+=a,c===2)return A.toString("utf8")}else if(o===0){let{bytesRead:a}=this.readVarintWithLength(l,e);e+=a}else break}return null}static buildPullSmartReplyResourceRequestPayload(l){let e=[...new Set((l||[]).map(V=>String(V||"").trim()).filter(V=>/^img_v[23]_/.test(V)))],t=[];for(let V of e){let o=Buffer.from(V,"utf8");t.push(10),S(t,o.length),t.push(...o)}return new Uint8Array(t)}static buildCmd77PullSmartReplyResourceRequest(l,e,t={}){let V=this.buildPullSmartReplyResourceRequestPayload(e),o=typeof t.subRequestId=="string"&&t.subRequestId.trim()?t.subRequestId.trim():(globalThis.crypto?.randomUUID?.()||te()).toUpperCase(),c=[];c.push(16,1),c.push(24),S(c,1105047),c.push(42),S(c,V.length),c.push(...V);let a=Buffer.from(o,"utf8");c.push(50),S(c,a.length),c.push(...a);let R=[10];S(R,c.length),R.push(...c);let A=i(F,{payloadType:1,cmd:77,cid:l,payload:new Uint8Array(R)});return Buffer.from(b(F,A))}static buildPullSmartReplyResourceRequest(l,e){let t=this.buildPullSmartReplyResourceRequestPayload(e),V=i(F,{payloadType:1,cmd:1105047,cid:l,payload:t});return Buffer.from(b(F,V))}static buildGetChatHistoryRequest(l,e,t){let V=i(Yl,{chatId:e,positions:t,flag1:1,flag2:1,flag3:2,flag4:1}),o=i(F,{payloadType:1,cmd:43,cid:l,payload:b(Yl,V)});return Buffer.from(b(F,o))}static buildEmojiReactionRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=Buffer.from(t,"utf-8"),c=[];c.push(10),S(c,V.length),c.push(...V),c.push(18),S(c,o.length),c.push(...o),c.push(24,1);let a=i(F,{payloadType:1,cmd:25,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodeEmojiReactionResponse(l){try{let e=G(F,l);return this._isPacketError(e)?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildRemoveEmojiReactionRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=Buffer.from(t,"utf-8"),c=[];c.push(10),S(c,V.length),c.push(...V),c.push(18),S(c,o.length),c.push(...o),c.push(24,1);let a=i(F,{payloadType:1,cmd:26,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodeRemoveEmojiReactionResponse(l){try{let e=G(F,l);return this._isPacketError(e)?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildGetChatMetaRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[10];S(V,t.length),V.push(...t);let o=i(F,{payloadType:1,cmd:64,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeGetChatMetaResponse(l){try{let e=G(F,l);if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=Buffer.from(e.payload),V=this.extractLengthDelimitedField(t,1);if(!V)return{success:!1,error:"No chat meta entry in payload"};let o=Buffer.from(V),c=this.extractLengthDelimitedField(o,1),a=this.extractLengthDelimitedField(o,2);if(!a)return{success:!1,error:"No chat bytes in chat meta entry"};let R=G(Et,a);return{success:!0,chat:{id:R.id||(c?Buffer.from(c).toString("utf8"):""),type:R.type,name:R.name||"",description:R.description||"",ownerId:R.ownerId||"",lastMessageId:R.lastMessageId||"",lastVisibleMessageId:R.lastVisibleMessageId||"",lastMessagePosition:R.lastMessagePosition||0,lastVisibleMessagePosition:R.lastVisibleMessagePosition||0,readPosition:R.readPosition||0,readPositionBadgeCount:R.readPositionBadgeCount||0,lastMessagePositionBadgeCount:R.lastMessagePositionBadgeCount||0,newMessageCount:R.newMessageCount||0,noBadgedNewMessageCount:R.noBadgedNewMessageCount||0,firstChatMessagePosition:R.firstChatMessagePosition||0,updateTime:Number(R.updateTime||0n),updateTimeMs:Number(R.updateTimeMs||0n),createTime:Number(R.createTime||0n),memberCount:R.memberCount||0,userCount:R.userCount||0,role:R.role,status:R.status,chatMode:R.chatMode,allowPost:R.allowPost}}}catch(e){return{success:!1,error:e.message}}}static extractLengthDelimitedField(l,e){let t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;let n=l.subarray(t,t+R);if(t+=R,a===e)return n}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return null}static tryDecodeAsUtf8(l){if(!l||l.length===0)return"";try{let e=Buffer.from(l).toString("utf8");return e.includes("\uFFFD")?"":e}catch{return""}}static isValidImageKey(l){return typeof l=="string"&&rR.test(l.trim())}static extractImageKeysFromString(l){let e=String(l||""),t=e.match(/img_v3_[a-z0-9]{4}_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/gi)||[],V=e.match(/img_v2_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/gi)||[],o=[...t,...V];if(o.length>0)return[...new Set(o)];let c=e.split(/(?=img_v[23]_)/g).filter(R=>/^img_v[23]_/.test(R)),a=[];for(let R of c){let A=R.match(/^(img_v3_[a-z0-9]{4}_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}|img_v2_[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})/i);if(A){a.push(A[1]);continue}let n=R.match(/^img_v[23]_[a-zA-Z0-9_-]+/);if(!n)continue;let h=n[0];h.length<20||h.length>80||this.isValidImageKey(h)&&a.push(h)}return[...new Set(a)]}static tryDecodeChatHistoryImagePayload(l,e){if(!l||l.length===0)return;let t=l instanceof Uint8Array?l:new Uint8Array(l);try{let V=G(ye,t);if(V.imageKey){let o={imageKey:V.imageKey,cryptoInfo:V.crypto?this.extractCryptoInfo(V.crypto):null,fsUnit:V.fsUnit||null};e(o)}}catch{}try{let V=G(Nl,t),o=this.extractImageInfo(V);o?.imageKey&&e(o)}catch{}try{let V=G(me,t);if(V.imageKey&&e({imageKey:V.imageKey,cryptoInfo:null}),V.richText){let o=this.parsePostContent(V);for(let c of o.images||[])c?.imageKey&&e(c)}}catch{}try{let V=G(Ql,t),o=this.parsePostContent({richText:V,text:V.innerText||""});for(let c of o.images||[])c?.imageKey&&e(c)}catch{}try{let V=G(gt,t);if(V?.dictionary){for(let o of Object.values(V.dictionary))if(o?.tag===2&&o.property){let c=this.parseImageProperty(o.property);c?.imageKey&&e(c)}}}catch{}}static collectImageInfosFromChatHistoryContent(l={}){let e=[],t=new Set,V=a=>{let R=a?.imageKey?String(a.imageKey).trim():"";!this.isValidImageKey(R)||t.has(R)||(t.add(R),e.push({imageKey:R,cryptoInfo:a?.cryptoInfo||null}))};this.tryDecodeChatHistoryImagePayload(l?.richTextOrImageBytes,V),this.tryDecodeChatHistoryImagePayload(l?.richTextBytes,V),this.tryDecodeChatHistoryImagePayload(l?.richTextData,V);let o=l?.htmlText||this.tryDecodeAsUtf8(l?.richTextOrImageBytes)||"",c=this.extractImageKeysFromString(`${l?.text||""}
|
|
35
35
|
${o}`);for(let a of c)V({imageKey:a,cryptoInfo:null});return e}static decodeGetChatHistoryResponse(l){try{let e=G(F,l);return!e.payload||e.payload.length===0?{success:!1,error:"Empty payload",messages:[]}:this.manualDecodeGetChatHistoryResponse(e.payload)}catch(e){return{success:!1,error:e.message,messages:[]}}}static manualDecodeGetChatHistoryResponse(l){let e=[],t=Buffer.from(l),V=0;for(;V<t.length;){let{value:o,bytesRead:c}=this.readVarintWithLength(t,V);if(c===0)break;V+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(t,V);if(V+=n,V+A>t.length)break;let h=t.subarray(V,V+A);if(V+=A,R===1){let d=this.parseMessageEntry(h);d&&e.push(d)}}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(t,V);V+=A}else if(a===5)V+=4;else if(a===1)V+=8;else break}return e.sort((o,c)=>{let a=Number.isInteger(o?.position)?o.position:0;return(Number.isInteger(c?.position)?c.position:0)-a}),{success:!0,messages:e}}static parseMessageEntry(l){let e=0,t=0,V=null;for(;e<l.length;){let{value:c,bytesRead:a}=this.readVarintWithLength(l,e);if(a===0)break;e+=a;let R=c&7,A=c>>3;if(R===0){let{value:n,bytesRead:h}=this.readVarintWithLength(l,e);e+=h,A===1&&(t=n)}else if(R===2){let{value:n,bytesRead:h}=this.readVarintWithLength(l,e);if(e+=h,e+n>l.length)break;let d=l.subarray(e,e+n);e+=n,A===2&&(V=d)}else if(R===5)e+=4;else if(R===1)e+=8;else break}if(!V)return null;let o=this.parseChatMessage(V);return{...o,position:t||o.position}}static parseChatMessage(l){let e=0,t=null,V={position:0,messageId:"",type:0,typeName:"UNKNOWN",fromId:"",fromType:0,fromTypeName:"UNKNOWN",chatId:"",cid:"",createTime:0,text:"",htmlText:"",richText:null,markdown:"",content:void 0,imageKey:"",imageKeys:[],fileKey:"",fileKeys:[],fileName:"",fileMime:"",fileSize:void 0,language:"",replyCount:"0",parentMsgId:"",baikeAnnotations:[]};for(;e<l.length;){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===0){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);switch(e+=n,R){case 2:V.type=A,V.typeName=gV(A);break;case 4:V.createTime=A;break;case 6:break;case 7:V.fromType=A,V.fromTypeName=ZV(A);break;case 13:V.position=A;break}}else if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);switch(e+=A,R){case 1:V.messageId=h.toString("utf8");break;case 3:V.fromId=h.toString("utf8");break;case 5:t=h;break;case 10:V.chatId=h.toString("utf8");break;case 12:V.cid=h.toString("utf8");break;case 16:V.replyCount=h.toString("utf8");break;case 18:V.parentMsgId=h.toString("utf8");break;case 24:V.chatId||(V.chatId=h.toString("utf8"));break;case 39:V.language=h.toString("utf8");break}}else if(a===5)e+=4;else if(a===1)e+=8;else break}if(t)if(V.type===3){let o=this.parseChatFileContent(t);V.text=o.text,V.fileKey=o.fileKey,V.fileKeys=o.fileKeys,V.fileName=o.fileName,V.fileMime=o.fileMime,V.fileSize=o.fileSize}else{let o=this.parseChatMessageContent(t);V.text=o.text,V.htmlText=o.htmlText,V.richText=o.richText,V.markdown=o.markdown,Array.isArray(o.content)&&o.content.length>0&&(V.content=o.content),V.baikeAnnotations=o.baikeAnnotations||[];let c=o.imageInfos||[],a=c.map(R=>R.imageKey).filter(Boolean);V.imageKey=a[0]||"",V.imageKeys=a;for(let R of c)R.imageKey&&R.cryptoInfo&&_l(R.imageKey,R.cryptoInfo)}return V}static normalizeChatFileSize(l){return typeof l=="bigint"?l<=BigInt(Number.MAX_SAFE_INTEGER)?Number(l):l.toString():Number.isSafeInteger(l)?l:void 0}static buildParsedChatFileContent({text:l="",fileKey:e="",fileName:t="",fileMime:V="",fileSize:o}={}){let c=typeof l=="string"?l:"",a=typeof e=="string"?e.trim():"",R=typeof t=="string"?t.trim():"",A=typeof V=="string"?V.trim():"",n=this.normalizeChatFileSize(o);return{text:c,fileKey:a,fileKeys:a?[a]:[],fileName:R,fileMime:A,...n!==void 0?{fileSize:n}:{}}}static parseChatFileContent(l){try{let V=G(me,l);if(V.fileKey||V.fileName||V.fileMime||V.fileSize)return this.buildParsedChatFileContent({text:V.text||"",fileKey:V.fileKey,fileName:V.fileName,fileMime:V.fileMime,fileSize:V.fileSize})}catch{}try{let V=G(KV,l);if(V.key||V.name||V.mime||V.size)return this.buildParsedChatFileContent({fileKey:V.key,fileName:V.name,fileMime:V.mime,fileSize:V.size})}catch{}let e=this.parseProtobufFields(l),t=this.getStringField(e,6)||"";return this.buildParsedChatFileContent({text:t&&this.getStringField(e,1)||"",fileKey:t||this.getStringField(e,1)||"",fileName:this.getStringField(e,2)||this.getStringField(e,11)||"",fileMime:this.getStringField(e,4)||this.getStringField(e,12)||"",fileSize:this.getVarintField(e,3,this.getVarintField(e,13,void 0))})}static buildMessageContentParts({text:l="",imageInfos:e=[]}={}){let t=[],V=typeof l=="string"?l:"";V&&t.push({type:"text",text:V});for(let o of e||[]){let c=typeof o?.imageKey=="string"?o.imageKey.trim():"";c&&t.push({type:"image_key",image_key:{key:c}})}return t}static parseChatMessageContent(l){let e=0,t={text:"",htmlText:"",richText:null,markdown:"",content:void 0,richTextOrImageBytes:new Uint8Array,richTextBytes:new Uint8Array,richTextData:new Uint8Array,imageInfos:[],baikeAnnotations:[]};for(;e<l.length;){let{value:o,bytesRead:c}=this.readVarintWithLength(l,e);if(c===0)break;e+=c;let a=o&7,R=o>>3;if(a===2){let{value:A,bytesRead:n}=this.readVarintWithLength(l,e);if(e+=n,e+A>l.length)break;let h=l.subarray(e,e+A);switch(e+=A,R){case 1:t.text=h.toString("utf8");break;case 2:t.richTextOrImageBytes=h,t.htmlText=this.tryDecodeAsUtf8(h)||"";break;case 3:t.richTextBytes=h;break;case 6:{t.richTextData=h;let d=this.parseBaikeAnnotation(h);d&&t.baikeAnnotations.push(d);break}}}else if(a===0){let{bytesRead:A}=this.readVarintWithLength(l,e);e+=A}else if(a===5)e+=4;else if(a===1)e+=8;else break}let V=this.extractStructuredRichTextFromChatHistoryContent(t);if(t.richText=V.richText,t.markdown=V.markdown,!t.text&&V.text&&(t.text=V.text),t.imageInfos=this.collectImageInfosFromChatHistoryContent(t),Array.isArray(V.content)&&V.content.length>0)t.content=V.content;else{let o=this.buildMessageContentParts({text:t.text,imageInfos:t.imageInfos});o.length>0&&(t.content=o)}return t}static parseBaikeAnnotation(l){let e=this.parseProtobufFields(l);if(this.getStringField(e,1)!=="baike")return null;let V=this.getBytesField(e,2);if(!V)return null;let o=this.parseProtobufFields(V),c=this.getBytesField(o,1);if(!c)return null;let a=this.parseProtobufFields(c),R=this.getBytesField(a,2);if(!R)return null;let A=this.parseProtobufFields(R),n=this.getBytesField(A,1);if(!n)return null;let h=this.parseProtobufFields(n),d=this.getBytesField(h,1),g=0,E=0;if(d){let u=this.parseProtobufFields(d);g=this.getVarintField(u,1,0),E=this.getVarintField(u,2,0)}let X=this.getStringField(h,2)||"",r=this.getBytesField(h,4),m="",W=0;if(r){let u=this.parseProtobufFields(r);m=this.getStringField(u,1)||"",W=this.getVarintField(u,2,0)}return m?{type:"baike",entityId:m,entityType:W,entityTypeName:W===1?"enterprise":"public",text:X,offset:g,length:E}:null}static parseProtobufFields(l){let e=[],t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(o===0)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,t+R>l.length)break;e.push({fieldNo:a,wireType:c,data:l.subarray(t,t+R)}),t+=R}else if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,e.push({fieldNo:a,wireType:c,val:R})}else if(c===5)t+=4;else if(c===1)t+=8;else break}return e}static getStringField(l,e){let t=l.find(V=>V.fieldNo===e&&V.wireType===2);return t?t.data.toString("utf8"):null}static getBytesField(l,e){let t=l.find(V=>V.fieldNo===e&&V.wireType===2);return t?t.data:null}static getVarintField(l,e,t){let V=l.find(o=>o.fieldNo===e&&o.wireType===0);return V?V.val:t}static getAllFields(l,e,t){return l.filter(V=>V.fieldNo===e&&(t===void 0||V.wireType===t))}static buildLengthDelimitedField(l,e){let t=Buffer.isBuffer(e)?e:Buffer.from(e),V=[Number(l<<3|2)];return S(V,t.length),V.push(...t),V}static buildVarintField(l,e){let t=[Number(l<<3|0)];return this.pushVarintBigInt(t,BigInt(e)),t}static parseProtoMapEntries(l,e){return this.getAllFields(l,e,2).map(V=>this.parseProtobufFields(Buffer.from(V.data)))}static normalizePin(l){if(!l)return l;let e=this._normalizeProtoValue(l);return{id:e.id,chatId:e.chatId,messageId:e.messageId,chatterId:e.chatterId,createTime:e.createTime,deletedTime:e.deletedTime}}static normalizePins(l){return Array.isArray(l)?l.map(e=>this.normalizePin(e)):[]}static resolvePinChatId(...l){for(let e of l){let t=Array.isArray(e)?e:e?[e]:[];for(let V of t){let o=V?.chatId;if(o!=null)return o}}return null}static normalizePinnedMessage(l){if(!l)return l;let e=this._normalizeProtoValue(l),t=this.parseMessageContent(l);return{...e,...t,id:e.id??t.messageId,fromId:e.fromId??t.fromId,chatId:e.chatId??t.chatId,threadId:e.threadId??t.threadId}}static buildMarkChatReadRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=[];o.push(10),S(o,V.length),o.push(...V),o.push(16),this.pushVarintBigInt(o,BigInt(t));let c=i(F,{payloadType:1,cmd:201,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,c))}static decodeMarkChatReadResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t="";if(e.payload&&e.payload.length>0){let V=this.extractLengthDelimitedField(Buffer.from(e.payload),3);V&&(t=Buffer.from(V).toString("utf-8"))}return{success:!0,chatId:t}}catch(e){return{success:!1,error:e.message}}}static buildPinSessionRequest(l,e,t=1){let V=Buffer.from(e,"utf-8"),o=[];o.push(10),S(o,V.length),o.push(...V),o.push(16),this.pushVarintBigInt(o,BigInt(t));let c=[];c.push(10),S(c,o.length),c.push(...o);let a=i(F,{payloadType:1,cmd:1100,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodePinSessionResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t={success:!0,status:0,version:0};if(e.payload&&e.payload.length>0){let V=Buffer.from(e.payload),o=0;for(;o<V.length;){let{value:c,bytesRead:a}=this.readVarintWithLength(V,o);if(!a)break;o+=a;let R=c&7,A=c>>3;if(R===0){let{value:n,bytesRead:h}=this.readVarintWithLength(V,o);o+=h,A===1?t.status=n:A===2&&(t.version=n)}else if(R===2){let{value:n,bytesRead:h}=this.readVarintWithLength(V,o);o+=h+n}else if(R===1)o+=8;else if(R===5)o+=4;else break}}return t}catch(e){return{success:!1,error:e.message}}}static buildUnpinSessionRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[];V.push(10),S(V,t.length),V.push(...t),V.push(16,1);let o=[];o.push(10),S(o,V.length),o.push(...V);let c=i(F,{payloadType:1,cmd:1101,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,c))}static decodeUnpinSessionResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildPutPinRequest(l,e,t){let V=i(zl,{chatId:ee(e,"chatId"),messageId:ee(t,"messageId")}),o=i(F,{payloadType:1,cmd:5100,cid:l,payload:b(zl,V)});return Buffer.from(b(F,o))}static decodePutPinResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(Ot,e.payload);return{success:!0,pin:t.pin?this.normalizePin(t.pin):void 0}}catch(e){return{success:!1,error:e.message}}}static buildPullPinReadStatusRequest(l,e){let t=i(vl,{chatId:ee(e,"chatId")}),V=i(F,{payloadType:1,cmd:5106,cid:l,payload:b(vl,t)});return Buffer.from(b(F,V))}static decodePullPinReadStatusResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,hasUnreadPin:!1}:{success:!0,hasUnreadPin:!!G(tV,e.payload).hasUnreadPin}}catch(e){return{success:!1,error:e.message}}}static buildPutPinReadRequest(l,e){let t=i(Pl,{chatId:ee(e,"chatId")}),V=i(F,{payloadType:1,cmd:5107,cid:l,payload:b(Pl,t)});return Buffer.from(b(F,V))}static decodePutPinReadResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return e.payload&&e.payload.length>0&&G(VV,e.payload),{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildPullChatPinsRequest(l,e,t={}){let V=hV(t.cursor,"cursor"),o=hV(t.count,"count"),c=t.isPullUserAllPin??t.is_pull_user_all_pin,a=t.withMessages??t.with_messages,R=i(wl,{chatId:ee(e,"chatId"),...V!==void 0?{cursor:BigInt(V)}:{},...o!==void 0?{count:o}:{},...c!==void 0?{isPullUserAllPin:!!c}:{},...a!==void 0?{withMessages:!!a}:{}}),A=i(F,{payloadType:1,cmd:5102,cid:l,payload:b(wl,R)});return Buffer.from(b(F,A))}static decodePullChatPinsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,pins:[],pinCount:0,hasMore:!1};let t=G(_t,e.payload);return{success:!0,pins:Array.isArray(t.pins)?t.pins.map(o=>{let c=this.normalizePin(o),a=t.pinedMessages?.[String(c.messageId)];return a?{...c,message:this.normalizePinnedMessage(a)}:c}):[],pinCount:t.pinCount??0,hasMore:!!t.hasMore,lastReadTime:t.lastReadTime!==void 0?this._normalizeProtoValue(t.lastReadTime):void 0,nextCursor:t.nextCursor!==void 0?this._normalizeProtoValue(t.nextCursor):void 0}}catch(e){return{success:!1,error:e.message}}}static buildDeletePinRequest(l,e,t){let V=i(Ll,{id:ee(e,"pinId"),chatId:ee(t,"chatId")}),o=i(F,{payloadType:1,cmd:5103,cid:l,payload:b(Ll,V)});return Buffer.from(b(F,o))}static decodeDeletePinResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let t=this.extractErrorMessage(e.payload);if(t)return{success:!1,error:t}}return{success:!1,error:`Packet status: ${e.status}`}}return e.payload&&e.payload.length>0&&G(qt,e.payload),{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildMarkSessionRequest(l,e,t=!0){let V=[];V.push(8),this.pushVarintBigInt(V,BigInt(e)),V.push(16,1),V.push(24,1);let o=t?10:18,c=[];c.push(o),S(c,V.length),c.push(...V);let a=i(F,{payloadType:1,cmd:1027,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,a))}static decodeMarkSessionResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildGetUserRelationRequest(l,e){let t=[];t.push(8),this.pushVarintBigInt(t,BigInt(e)),t.push(16,1);let V=i(F,{payloadType:1,cmd:406,cid:l,payload:new Uint8Array(t)});return Buffer.from(b(F,V))}static decodeGetUserRelationResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t={success:!0,relationType:0,status:0};if(e.payload&&e.payload.length>0){let V=Buffer.from(e.payload),o=this.extractLengthDelimitedField(V,1);if(o){let c=Buffer.from(o),a=0;for(;a<c.length;){let{value:R,bytesRead:A}=this.readVarintWithLength(c,a);if(!A)break;a+=A;let n=R&7,h=R>>3;if(n===0){let{value:d,bytesRead:g}=this.readVarintWithLength(c,a);a+=g,h===1&&(t.relationType=d)}else if(n===2){let{value:d,bytesRead:g}=this.readVarintWithLength(c,a);if(a+=g,h===2){let E=c.subarray(a,a+d),X=0;for(;X<E.length;){let{value:r,bytesRead:m}=this.readVarintWithLength(E,X);if(!m)break;X+=m;let W=r&7,u=r>>3;if(W===0){let{value:I,bytesRead:N}=this.readVarintWithLength(E,X);X+=N,u===1&&(t.status=I)}else break}}a+=d}else if(n===1)a+=8;else if(n===5)a+=4;else break}}}return t}catch(e){return{success:!1,error:e.message}}}static buildGetUserPresenceRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[];V.push(10),S(V,t.length),V.push(...t);let o=i(F,{payloadType:1,cmd:5093,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeGetUserPresenceResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t={success:!0,userId:"",presenceData:""};if(e.payload&&e.payload.length>0){let V=Buffer.from(e.payload),o=this.extractLengthDelimitedField(V,1);if(o){let c=Buffer.from(o),a=this.extractLengthDelimitedField(c,1),R=this.extractLengthDelimitedField(c,2);a&&(t.userId=Buffer.from(a).toString("utf-8")),R&&R.length>0&&(t.presenceData=Buffer.from(R).toString("hex"))}}return t}catch(e){return{success:!1,error:e.message}}}static buildGetConfigRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[];V.push(10),S(V,t.length),V.push(...t);let o=i(F,{payloadType:1,cmd:7026,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeGetConfigResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t={success:!0,configName:"",value:0,defaultValue:0};if(e.payload&&e.payload.length>0){let V=Buffer.from(e.payload),o=this.extractLengthDelimitedField(V,1);if(o){let c=Buffer.from(o),a=this.extractLengthDelimitedField(c,1);a&&(t.configName=Buffer.from(a).toString("utf-8"));let R=this.extractLengthDelimitedField(c,2);if(R){let A=Buffer.from(R),n=0;for(;n<A.length;){let{value:h,bytesRead:d}=this.readVarintWithLength(A,n);if(!d)break;n+=d;let g=h&7,E=h>>3;if(g===0){let{value:X,bytesRead:r}=this.readVarintWithLength(A,n);n+=r,E===2?t.value=X:E===3&&(t.defaultValue=X)}else if(g===2){let{value:X,bytesRead:r}=this.readVarintWithLength(A,n);n+=r+X}else if(g===1)n+=8;else if(g===5)n+=4;else break}}}}return t}catch(e){return{success:!1,error:e.message}}}static buildGetFeatureFlagsRequest(l,e={}){let{version:t=1,clientId:V="1-0",syncToken:o=""}=e,c=Buffer.from(V,"utf-8"),a=[];if(a.push(8),this.pushVarintBigInt(a,BigInt(t)),a.push(18),S(a,c.length),a.push(...c),o){let A=Buffer.from(o,"utf-8");a.push(26),S(a,A.length),a.push(...A)}let R=i(F,{payloadType:1,cmd:1011741,cid:l,payload:new Uint8Array(a)});return Buffer.from(b(F,R))}static decodeGetFeatureFlagsResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};let t={success:!0,syncToken:"",flags:{group1:[],group2:[]}};if(e.payload&&e.payload.length>0){let V=Buffer.from(e.payload),o=0;for(;o<V.length;){let{value:c,bytesRead:a}=this.readVarintWithLength(V,o);if(!a)break;o+=a;let R=c&7,A=c>>3;if(R===2){let{value:n,bytesRead:h}=this.readVarintWithLength(V,o);if(o+=h,A===3)t.syncToken=V.subarray(o,o+n).toString("utf-8");else if(A===4){let d=V.subarray(o,o+n);t.flags=this._parseFeatureFlags(d)}o+=n}else if(R===0){let{bytesRead:n}=this.readVarintWithLength(V,o);o+=n}else if(R===1)o+=8;else if(R===5)o+=4;else break}}return t}catch(e){return{success:!1,error:e.message}}}static _parseFeatureFlags(l){let e={group1:[],group2:[]},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,a===1||a===2){let n=l.subarray(t,t+R),h=this._parseFlagEntry(n);h&&(a===1?e.group1:e.group2).push(h)}t+=R}else if(c===0){let{bytesRead:R}=this.readVarintWithLength(l,t);t+=R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return e}static _parseFlagEntry(l){let e={id:0,value:0},t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A,a===1?e.id=R:a===2&&(e.value=R)}else if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A+R}else break}return e}static generateUploadKey(l="image"){let e=RV.randomUUID().slice(0,35);return`${l==="file"?"file_v3_00ve_":"img_v3_00ve_"}${e}g`}static generateImageKey(){return this.generateUploadKey("image")}static buildUploadCreateRequest(l,e={}){let t=Buffer.from(l,"utf-8"),V=[];if(V.push(10),S(V,t.length),V.push(...t),e.fileType===void 0&&(V.push(16),S(V,e.type??0)),e.fileType!==void 0&&(V.push(24),S(V,e.fileType)),e.secondaryId&&(V.push(34),S(V,e.secondaryId.length),V.push(...e.secondaryId)),e.filename){let o=Buffer.from(e.filename,"utf-8");V.push(42),S(V,o.length),V.push(...o)}if(e.fileSize!==void 0&&(V.push(48),S(V,e.fileSize)),e.blake3Hash){let o=Buffer.from("blake3:"),c=Buffer.concat([o,e.blake3Hash]);V.push(74),S(V,c.length),V.push(...c)}return Buffer.from(V)}static decodeUploadCreateResponse(l){try{let e=this._decodeSimpleProto(l);return e[1]!==1?{success:!1,error:e[3]||`Unexpected status: ${e[1]}`}:{success:!0,version:e[2]}}catch(e){return{success:!1,error:e.message}}}static decodeUploadPartResponse(l){try{let e=this._decodeSimpleProto(l),t=e[1],V=e[2];return t===void 0||V===void 0?{success:!1,error:e[3]||"Missing id or version in part response"}:{success:!0,id:t,version:V}}catch(e){return{success:!1,error:e.message}}}static buildUploadCompleteRequest(l,e,t={}){let V=Buffer.from(l,"utf-8"),o=[];o.push(10),S(o,V.length),o.push(...V),o.push(16),S(o,e.length);for(let R of e){let A=[];A.push(8),S(A,R.id??1),A.push(16),S(A,R.version??0),o.push(26),S(o,A.length),o.push(...A)}let c=Buffer.from(t.filename||"","utf-8");o.push(34),S(o,c.length),c.length&&o.push(...c);let a=Buffer.from(t.mimeType||"","utf-8");return o.push(42),S(o,a.length),a.length&&o.push(...a),Buffer.from(o)}static decodeUploadCompleteResponse(l){try{let e=this._decodeSimpleProto(l);return e[1]!==0?{success:!1,error:e[4]||`Upload failed with status: ${e[1]}`}:{success:!0,key:e[2]}}catch(e){return{success:!1,error:e.message}}}static _decodeSimpleProto(l){let e=0,t={};for(;e<l.length;){let V=l[e++],o=V>>3,c=V&7;if(c===0){let a=0,R=1;for(;e<l.length;){let A=l[e++];if(a+=(A&127)*R,R*=128,(A&128)===0)break}t[o]=a}else if(c===2){let a=0,R=1;for(;e<l.length;){let A=l[e++];if(a+=(A&127)*R,R*=128,(A&128)===0)break}t[o]=l.slice(e,e+a).toString("utf-8"),e+=a}else if(c===1)e+=8;else if(c===5)e+=4;else throw new Error(`Unknown wire type ${c} at offset ${e-1}`)}return t}static buildSaveContactAliasRequest(l,e,t={}){let{alias:V="",memo:o="",memoImageKey:c=""}=t,a=Buffer.from(e,"utf-8"),R=[];R.push(10),S(R,a.length),R.push(...a);let A=Buffer.from(V,"utf-8");R.push(18),S(R,A.length),R.push(...A);let n=Buffer.from(o,"utf-8");R.push(26),S(R,n.length),R.push(...n);let h=Buffer.from(c,"utf-8");R.push(34),S(R,h.length),R.push(...h);let d=i(F,{payloadType:1,cmd:5036,cid:l,payload:new Uint8Array(R)});return Buffer.from(b(F,d))}static decodeSaveContactAliasResponse(l){try{let e=G(F,l);return this._isPacketError(e)?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildContactInfoSyncRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[];V.push(10),S(V,t.length),V.push(...t);let o=i(F,{payloadType:1,cmd:1100319,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeContactInfoSyncResponse(l){try{let e=G(F,l);if(this._isPacketError(e))return{success:!1,error:`Packet status: ${e.status}`};if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload in sync response",syncStatus:{}};let t=Buffer.from(e.payload),V={},o=0;for(;o<t.length;){let{value:c,bytesRead:a}=this.readVarintWithLength(t,o);if(!a)break;o+=a;let R=c>>3,A=c&7;if(A===0){let{value:n,bytesRead:h}=this.readVarintWithLength(t,o);o+=h,R===1?V.statusCode=Number(n):R===2?V.syncFlag2=Number(n):R===3?V.syncFlag3=Number(n):R===4?V.syncFlag4=Number(n):R===7?V.syncFlag7=Number(n):R===8?V.syncFlag8=Number(n):R===9&&(V.syncFlag9=Number(n))}else if(A===2){let{value:n,bytesRead:h}=this.readVarintWithLength(t,o);o+=h;let d=t.subarray(o,o+Number(n));o+=Number(n),R===5?V.syncToken=Buffer.from(d).toString("utf-8"):R===6&&(V.extraData=Buffer.from(d).toString("hex")||null)}else if(A===1)o+=8;else if(A===5)o+=4;else break}return V.statusCode!==void 0&&V.statusCode!==1?{success:!1,error:`Sync failed with status code: ${V.statusCode}`,syncStatus:V}:V.statusCode===void 0?{success:!1,error:"Missing status code in sync response",syncStatus:V}:{success:!0,syncStatus:V}}catch(e){return{success:!1,error:e.message}}}static buildCreateThreadRequest(l,e){let t=Buffer.from(e,"utf-8"),V=[];V.push(10),S(V,t.length),V.push(...t),V.push(16,5);let o=i(F,{payloadType:1,cmd:8111,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,o))}static decodeCreateThreadResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildGetThreadMessagesRequest(l,e,t){let V=i(wt,{threadId:e,positions:t}),o=i(F,{payloadType:1,cmd:8109,cid:l,payload:b(wt,V)});return Buffer.from(b(F,o))}static decodeGetThreadMessagesResponse(l){try{let e=G(F,l);if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload",messages:[]};let t=this.manualDecodeGetChatHistoryResponse(e.payload);try{let V=G(Zo,e.payload);V.hasMore&&(t.hasMore=!0),V.nextPosition&&(t.nextPosition=V.nextPosition),V.threadId&&(t.threadId=V.threadId)}catch{}return t}catch(e){return{success:!1,error:e.message,messages:[]}}}static buildPutMessageLinkRequest(l,e,t={}){let V=De(t.copiedIds).map((a,R)=>ee(a,`copiedIds[${R}]`)),o=i(Bt,{fromId:ee(e,"fromId"),from:iR(t.from),copiedId:V}),c=i(F,{payloadType:1,cmd:1150,cid:l,payload:b(Bt,o)});return Buffer.from(b(F,c))}static decodePutMessageLinkResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(eo,e.payload);return{success:!0,token:t.token||"",tokenUrl:t.tokenUrl||""}}catch(e){return{success:!1,error:e.message}}}static buildGetMessageLinkPermissionRequest(l,e){let t=i(Ct,{token:Ge(e,"token")}),V=i(F,{payloadType:1,cmd:1151,cid:l,payload:b(Ct,t)});return Buffer.from(b(F,V))}static decodeGetMessageLinkPermissionResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(lo,e.payload),V={[pt.NONE]:"NONE",[pt.ALLOW_PREVIEW]:"ALLOW_PREVIEW"}[t.permission]||"UNKNOWN";return{success:!0,permission:t.permission,permissionName:V,applinkUrl:t.applinkUrl||""}}catch(e){return{success:!1,error:e.message}}}static buildPullMessageLinkMessagesRequest(l,e,t,V={}){let o=De(V.needMessageIds).map((A,n)=>ee(A,`needMessageIds[${n}]`)),c=V.chatId===void 0||V.chatId===null||V.chatId===""?void 0:ee(V.chatId,"chatId"),a=i(It,{messageLinkUrl:Ge(e,"messageLinkUrl"),previewToken:Ge(t,"previewToken"),needMessageIds:o,...c!==void 0?{chatId:c}:{}}),R=i(F,{payloadType:1,cmd:1152,cid:l,payload:b(It,a)});return Buffer.from(b(F,R))}static decodePullMessageLinkMessagesResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(to,e.payload);return{success:!0,link:t.link?this._normalizeProtoValue(t.link):void 0}}catch(e){return{success:!1,error:e.message}}}static buildPutTransmitMessageRequest(l,e={}){let{messageId:t,chatIds:V=[],cids:o={},targets:c={},version:a=1,originMergeForwardId:R=""}=e,A=[...new Set(V.map(E=>String(E??"").trim()).filter(Boolean))],n={},h={};for(let E of A){n[E]=String(o[E]??RV.randomUUID().toUpperCase());let X=c[E]??{},r=WR(X.targetType??X.target_type),m=X.threadIdsCidsMap??X.thread_ids_cids_map??{};h[E]=i(qV,{targetType:r,threadIdsCidsMap:m})}let d=i(rt,{chatIds:A,messageId:String(t??""),cids:n,version:a,targets:h,originMergeForwardId:String(R??"")}),g=i(F,{payloadType:1,cmd:51,cid:l,payload:b(rt,d)});return Buffer.from(b(F,g))}static decodePutTransmitMessageResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,data:{messages:{},feedCards:{},threadMessages:{},threads:{}},messages:{},feedCards:{},threadMessages:{},threads:{}};let t=G($V,e.payload),V=this._normalizeProtoValue(t);return{success:!0,data:V,messages:V.messages||{},feedCards:V.feedCards||{},threadMessages:V.threadMessages||{},filePermCheck:V.filePermCheck,threads:V.threads||{}}}catch(e){return{success:!1,error:e.message}}}static buildSearchInChatRequest(l,e,t,V={}){let{pageSize:o=5,locale:c="zh_CN"}=V,a=te(),R=Buffer.from(e,"utf-8"),A=Buffer.from(t,"utf-8"),n=Buffer.from(a,"utf-8"),h=Buffer.from(c,"utf-8"),d=Buffer.from("SEARCH_MESSAGES","utf-8"),g=[];g.push(8,1),g.push(18),S(g,A.length),g.push(...A);let E=[];E.push(8),this.pushVarintBigInt(E,BigInt(o)),E.push(18,4,26,2,10,0),E.push(26,4,42,2,40,1);let X=[];X.push(10),S(X,d.length),X.push(...d),X.push(18),S(X,E.length),X.push(...E),X.push(26),S(X,g.length),X.push(...g);let r=[];r.push(10),S(r,n.length),r.push(...n),r.push(16,1),r.push(26),S(r,R.length),r.push(...R),r.push(42),S(r,X.length),r.push(...X),r.push(50),S(r,h.length),r.push(...h);let m=[];m.push(10),S(m,r.length),m.push(...r);let W=i(F,{payloadType:1,cmd:11021,cid:l,payload:new Uint8Array(m)});return Buffer.from(b(F,W))}static decodeSearchInChatResponse(l){let e=G(F,l);return e.payload?(G(fl,e.payload).results||[]).map(V=>{let o=V.resultMeta?.typedMeta.case==="messageMeta"?this.normalizeMessageSearchMeta(V.resultMeta.typedMeta.value):void 0;return{type:o?"message":this.mapSearchEntityType(V.type),id:V.id,rawType:V.type,titleHighlighted:V.titleHighlighted,summaryHighlighted:V.summaryHighlighted,avatarKey:V.avatarKey,...o?{messageMeta:o}:{}}}):[]}static extractVarintField(l,e){let t=0;for(;t<l.length;){let{value:V,bytesRead:o}=this.readVarintWithLength(l,t);if(!o)break;t+=o;let c=V&7,a=V>>3;if(c===0){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);if(t+=A,a===e)return R}else if(c===2){let{value:R,bytesRead:A}=this.readVarintWithLength(l,t);t+=A+R}else if(c===1)t+=8;else if(c===5)t+=4;else break}return null}static buildPutUrgentRequest(l,e,t,V,o,c={}){let a=c.urgentType||1,R=Math.floor(Date.now()/1e3),A=Buffer.from(e,"utf-8"),n=Buffer.from(o,"utf-8"),h=Buffer.from(V,"utf-8"),d=Buffer.from(t,"utf-8"),g=[];g.push(10),S(g,A.length),g.push(...A),g.push(16),this.pushVarintBigInt(g,BigInt(a)),g.push(24),this.pushVarintBigInt(g,BigInt(R)),g.push(34),S(g,n.length),g.push(...n);let E=[];E.push(10),S(E,h.length),E.push(...h),E.push(18),S(E,d.length),E.push(...d);let X=[];X.push(10),S(X,g.length),X.push(...g),X.push(18),S(X,h.length),X.push(...h),X.push(26),S(X,E.length),X.push(...E);let r=i(F,{payloadType:1,cmd:1,cid:l,payload:new Uint8Array(X)});return Buffer.from(b(F,r))}static decodePutUrgentResponse(l){try{let e=G(F,l);return e.status&&e.status!==0?{success:!1,error:`Packet status: ${e.status}`}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildPullUrgentAckStatusRequest(l,e,t){let V=Buffer.from(e,"utf-8"),o=Buffer.from(t.messageId,"utf-8"),c=Buffer.from(t.targetUserId,"utf-8"),a=t.urgentAckId?Buffer.from(t.urgentAckId,"utf-8"):null,R=t.urgentType||1,A=Math.floor(Date.now()/1e3),n=[];n.push(10),S(n,o.length),n.push(...o),n.push(18),S(n,V.length),n.push(...V),n.push(26),S(n,c.length),n.push(...c),a&&(n.push(34),S(n,a.length),n.push(...a)),n.push(40),this.pushVarintBigInt(n,BigInt(A)),n.push(48),this.pushVarintBigInt(n,BigInt(R));let h=[];h.push(10),S(h,n.length),h.push(...n);let d=[];d.push(10),S(d,V.length),d.push(...V),d.push(18),S(d,h.length),d.push(...h);let g=[];g.push(26),S(g,d.length),g.push(...d);let E=i(F,{payloadType:1,cmd:1,cid:l,payload:new Uint8Array(g)});return Buffer.from(b(F,E))}static decodePullUrgentAckStatusResponse(l){try{let e=G(F,l);if(e.status&&e.status!==0)return{success:!1,error:`Packet status: ${e.status}`};if(!e.payload||e.payload.length===0)return{success:!0,ackEntries:[]};let t=Buffer.from(e.payload),V=[],o=this.extractLengthDelimitedField(t,3);if(o){let c=0;for(;c<o.length;){let a=o[c],R=a>>3,A=a&7;if(R===2&&A===2){c++;let{value:n,bytesRead:h}=this.readVarintWithLength(o,c);c+=h;let d=o.subarray(c,c+Number(n));c+=Number(n);let g={},E=this.extractLengthDelimitedField(d,1);E&&(g.messageId=Buffer.from(E).toString("utf-8"));let X=this.extractLengthDelimitedField(d,2);X&&(g.chatId=Buffer.from(X).toString("utf-8"));let r=this.extractLengthDelimitedField(d,3);r&&(g.targetUserId=Buffer.from(r).toString("utf-8"));let m=this.extractLengthDelimitedField(d,4);m&&(g.urgentAckId=Buffer.from(m).toString("utf-8"));let W=0;for(;W<d.length;){let u=d[W],I=u>>3,N=u&7;if(N===0){W++;let{value:Y,bytesRead:T}=this.readVarintWithLength(d,W);W+=T,I===5?g.timestamp=Number(Y):I===6?g.urgentType=Number(Y):I===7&&(g.ackStatus=Number(Y))}else if(N===2){W++;let{value:Y,bytesRead:T}=this.readVarintWithLength(d,W);W+=T+Number(Y)}else W++}V.push(g)}else if(A===2){c++;let{value:n,bytesRead:h}=this.readVarintWithLength(o,c);c+=h+Number(n)}else if(A===0){c++;let{bytesRead:n}=this.readVarintWithLength(o,c);c+=n}else c++}}return{success:!0,ackEntries:V}}catch(e){return{success:!1,error:e.message}}}static buildPutScheduleMessageRequest(l,e,t,V,o={}){let{entityId:c,parseMarkdown:a=!0}=o,R=te(),A=Ul(e),n=A.innerText,h=a&&Ol(e)&&A.isBlockLevel||!1,d=this.buildContentBytes(h?"":n,A.elementIds,n,A.dictionaryBytes),g=this.buildPutMessageRequestBytes(h?2:4,t,R,d),E=[],X=Buffer.from(t,"utf-8"),r=Buffer.from(c||t,"utf-8");E.push(10),S(E,g.length),E.push(...g);let m=Number(V)>=1e12?Math.floor(Number(V)/1e3):Number(V);E.push(16),this.pushVarintBigInt(E,BigInt(m)),E.push(26),S(E,X.length),E.push(...X),E.push(34),S(E,r.length),E.push(...r);let W=i(F,{payloadType:1,cmd:900030,cid:l,payload:new Uint8Array(E)});return Buffer.from(b(F,W))}static decodePutScheduleMessageResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(Wt,e.payload);return t.message?{success:!0,scheduleMessage:this._normalizeScheduleMessage(t.message)}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildPatchScheduleMessageRequest(l,e,t,V,o={}){let{scheduleTime:c,content:a,sendImmediately:R,parseMarkdown:A=!0}=o,n=Buffer.from(e,"utf-8"),h=Buffer.from(t,"utf-8"),d=[];if(d.push(8),this.pushVarint(d,V),d.push(18),S(d,h.length),d.push(...h),d.push(26),S(d,n.length),d.push(...n),c!==void 0){let E=Number(c)>=1e12?Math.floor(Number(c)/1e3):Number(c);this.pushVarint(d,160),this.pushVarintBigInt(d,BigInt(E))}if(a!==void 0){let E=Ul(a),X=A&&Ol(a)&&E.isBlockLevel||!1,r=this.buildContentBytes(X?"":E.innerText,E.elementIds,E.innerText,E.dictionaryBytes);this.pushVarint(d,168),this.pushVarint(d,X?2:4),this.pushVarint(d,178),S(d,r.length),d.push(...r)}R&&(this.pushVarint(d,184),d.push(1));let g=i(F,{payloadType:1,cmd:900034,cid:l,payload:new Uint8Array(d)});return Buffer.from(b(F,g))}static decodePatchScheduleMessageResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let V=this.extractErrorMessage(e.payload);if(V)return{success:!1,error:V}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0};let t=G(bt,e.payload);return t.message?{success:!0,scheduleMessage:this._normalizeScheduleMessage(t.message)}:{success:!0}}catch(e){return{success:!1,error:e.message}}}static buildPullScheduleMessageByIdsRequest(l,e,t){let V=[],o=Buffer.from(e,"utf-8");V.push(10),S(V,o.length),V.push(...o);for(let a of t){let R=Buffer.from(a,"utf-8");V.push(18),S(V,R.length),V.push(...R)}let c=i(F,{payloadType:1,cmd:900032,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,c))}static decodePullScheduleMessageByIdsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,scheduleMessages:{}};let t=G(ut,e.payload),V={};for(let[o,c]of Object.entries(t.messages||{}))V[o]=this._normalizeScheduleMessage(c);return{success:!0,scheduleMessages:V}}catch(e){return{success:!1,error:e.message}}}static buildPullChatScheduleMessagesRequest(l,e,t={}){let{entityType:V=1,entityId:o=e,status:c=[1,2]}=t,a=[],R=Buffer.from(e,"utf-8"),A=Buffer.from(o,"utf-8");a.push(10),S(a,R.length),a.push(...R),a.push(16),this.pushVarintBigInt(a,BigInt(V)),a.push(26),S(a,A.length),a.push(...A);for(let h of c)a.push(32),this.pushVarintBigInt(a,BigInt(h));let n=i(F,{payloadType:1,cmd:900031,cid:l,payload:new Uint8Array(a)});return Buffer.from(b(F,n))}static decodePullChatScheduleMessagesResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,scheduleMessages:[]}:{success:!0,scheduleMessages:(G(it,e.payload).messages||[]).map(o=>this._normalizeScheduleMessage(o))}}catch(e){return{success:!1,error:e.message}}}static _isPacketError(l){return l.status!==0&&l.status!==200}static _normalizeProtoValue(l){if(typeof l=="bigint")return l>BigInt(Number.MAX_SAFE_INTEGER)||l<BigInt(Number.MIN_SAFE_INTEGER)?l.toString():Number(l);if(Array.isArray(l))return l.map(e=>this._normalizeProtoValue(e));if(l&&typeof l=="object"){let e={};for(let[t,V]of Object.entries(l))t.startsWith("$")||(e[t]=this._normalizeProtoValue(V));return e}return l}static _normalizeScheduleMessage(l){let e={0:"UNKNOWN",1:"PENDING",2:"SUSPEND",3:"SUCCESS",4:"FAIL",5:"DELETE"};return{messageId:l.messageId||"",scheduleTime:String(l.scheduleTime||0n),status:l.status,statusName:e[l.status]||"UNKNOWN"}}static buildGetBaikeCardRequest(l,e,t,V={}){let o=V.entityType??1,c=V.chatId||"",a=V.messageId||"",R=[],A=Buffer.from(e,"utf-8");R.push(10),S(R,A.length),R.push(...A);let n=Buffer.from(t,"utf-8");if(R.push(18),S(R,n.length),R.push(...n),R.push(24),S(R,o),R.push(32,0),R.push(40,2),c){let X=Buffer.from(c,"utf-8");R.push(50),S(R,X.length),R.push(...X)}if(a){let X=Buffer.from(a,"utf-8");R.push(58),S(R,X.length),R.push(...X)}R.push(64,0,72,0,80,0);let h=Buffer.from("im","utf-8");R.push(162,1),S(R,h.length),R.push(...h);let d=Buffer.from("click","utf-8");R.push(170,1),S(R,d.length),R.push(...d);let g=Buffer.from("{}","utf-8");R.push(178,1),S(R,g.length),R.push(...g);let E=i(F,{payloadType:1,cmd:4303,cid:l,payload:new Uint8Array(R)});return Buffer.from(b(F,E))}static decodeGetBaikeCardResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let R=this.extractErrorMessage(e.payload);if(R)return{success:!1,error:R}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,1);if(!V)return{success:!1,error:"No content in response"};let o=this.parseProtobufFields(V),c=this.getBytesField(o,1);return!c||c.length===0?{success:!1,error:"No HTML content"}:{success:!0,html:c.toString("utf-8")}}catch(e){return{success:!1,error:e.message}}}static extractBaikeCardInfo(l){let e={term:"",fullName:"",definition:"",detailUrl:"",contributors:[]},t=l.match(/font-size:\s*18px[^"]*"[^>]*text="([^"]+)"/);t&&(e.term=t[1]);let V=l.match(/aslCard-baikeCard-alias"[^>]*text="([^"]+)"/);V&&(e.fullName=V[1]);let o=l.match(/white-space:\s*pre-wrap;word-break:\s*break-word;[^"]*"\s*\n?\s*text="([^"]+)"/);o&&(e.definition=o[1]);let c=l.match(/https:\/\/ai\.feishu\.cn\/lingo\/detail\/\d+/);c&&(e.detailUrl=c[0]);let a=/title="([^"]+)">\s*<\/tooltip>\s*<text[^>]*>([^<]*)<\/text>/g,R;for(;(R=a.exec(l))!==null;)R[1]&&!e.contributors.includes(R[1])&&e.contributors.push(R[1]);return e}static buildGetBaikeRecommendDocsRequest(l,e,t=1){let V=[],o=Buffer.from(e,"utf-8");V.push(10),S(V,o.length),V.push(...o),V.push(16),S(V,t);let c=Buffer.from("recommend_docs","utf-8");V.push(26),S(V,c.length),V.push(...c),V.push(32,0),V.push(162,1,0);let a=i(F,{payloadType:1,cmd:4306,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,a))}static decodeGetBaikeRecommendDocsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let A=this.extractErrorMessage(e.payload);if(A)return{success:!1,error:A}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!1,error:"Empty payload"};let t=this.parseProtobufFields(Buffer.from(e.payload)),V=this.getBytesField(t,1);if(!V)return{success:!1,error:"No entry data in response",entityId:"",docs:[]};let o=this.parseProtobufFields(V),c=this.getStringField(o,1)||"",a=this.getBytesField(o,2),R=[];if(a&&a.length>0){let A=this.parseProtobufFields(a);for(let n of A)n.wireType===2&&R.push(n.data.toString("utf-8"))}return{success:!0,entityId:c,docs:R}}catch(e){return{success:!1,error:e.message}}}static buildSearchMeetingRoomsRequest(l,e,t,V={}){let o=[];if(o.push(8),this.pushVarintBigInt(o,BigInt(e)),o.push(16),this.pushVarintBigInt(o,BigInt(t)),V.keyword!=null&&V.keyword!==""){let A=Buffer.from(V.keyword,"utf-8");o.push(26),S(o,A.length),o.push(...A)}if(V.count!=null&&(o.push(32),S(o,V.count)),V.timezone!=null&&V.timezone!==""){let A=Buffer.from(V.timezone,"utf-8");o.push(58),S(o,A.length),o.push(...A)}let c=[];if(V.minCapacity!=null&&V.minCapacity>0&&(c.push(8),S(c,V.minCapacity)),V.needEquipments&&V.needEquipments.length>0)for(let A of V.needEquipments){let n=Buffer.from(A,"utf-8");c.push(18),S(c,n.length),c.push(...n)}c.length>0&&(o.push(66),S(o,c.length),o.push(...c)),V.cursor!=null&&(o.push(72),S(o,V.cursor));let a=V.type??(V.cursor!=null?2:1);o.push(80),S(o,a);let R=i(F,{payloadType:1,cmd:1000016,cid:l,payload:new Uint8Array(o)});return Buffer.from(b(F,R))}static buildSearchGuestsRequest(l,e,t={}){let V=t.offset??0,o=t.limit??50,c=t.locale??"zh_CN",a=t.guestType??2,R=[],A=Buffer.from(e,"utf-8");R.push(10),S(R,A.length),R.push(...A),R.push(16),S(R,V),R.push(24),S(R,o),R.push(32,1);let n=Buffer.from(c,"utf-8");R.push(42),S(R,n.length),R.push(...n),R.push(48,0),R.push(56,0),R.push(64,0),R.push(72,1),R.push(88,0),R.push(104,1);let h=[8];S(h,a);let d=[10];S(d,h.length),d.push(...h),R.push(114),S(R,d.length),R.push(...d);let g=i(F,{payloadType:1,cmd:1000014,cid:l,payload:new Uint8Array(R)});return Buffer.from(b(F,g))}static decodeSearchGuestsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}return!e.payload||e.payload.length===0?{success:!0,guests:[]}:{success:!0,guests:this.parseProtobufFields(Buffer.from(e.payload)).filter(o=>o.fieldNo===1&&o.wireType===2).map(o=>this._parseSearchGuest(o.data))}}catch(e){return{success:!1,error:e.message}}}static _parseSearchGuest(l){let e=this.parseProtobufFields(l),t=this.getStringField(e,3)||"",V=null;if(t)try{V=JSON.parse(t)}catch{V=null}let o=this.getVarintField(e,5,0);return{guestId:this.getStringField(e,1)||"",displayName:this.getStringField(e,2)||"",description:t,descriptionData:V,avatarUrl:this.getStringField(e,4)||"",type:o,typeName:o===1?"USER":o===2?"GROUP":`UNKNOWN(${o})`,tenantId:this.getStringField(e,6)||""}}static decodeSearchMeetingRoomsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let R=this.extractErrorMessage(e.payload);if(R)return{success:!1,error:R}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,buildings:[],hasMore:!1,cursor:0};let t=Buffer.from(e.payload),V=this.parseProtobufFields(t),o=V.filter(R=>R.fieldNo===1&&R.wireType===2).map(R=>this._parseCalendarBuilding(R.data)),c=this.getVarintField(V,2,0)!==0,a=this.getVarintField(V,3,0);return{success:!0,buildings:o,hasMore:c,cursor:a}}catch(e){return{success:!1,error:e.message}}}static buildPullBuildingsRequest(l,e={}){let t={...e.meetingRoomFilter||{}};e.minCapacity!=null&&t.minCapacity==null&&(t.minCapacity=e.minCapacity),e.needEquipments!=null&&t.needEquipments==null&&(t.needEquipments=e.needEquipments);let V=i(jt,{...e.eventField?{eventField:e.eventField}:{},...Object.keys(t).length>0?{meetingRoomFilter:t}:{},...e.enableRecommendations!=null?{enableRecommendations:e.enableRecommendations}:{},...e.operateInstanceField?{operateInstanceField:e.operateInstanceField}:{}}),o=i(F,{payloadType:1,cmd:1010009,cid:l,payload:b(jt,V)});return Buffer.from(b(F,o))}static decodePullBuildingsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let o=this.extractErrorMessage(e.payload);if(o)return{success:!1,error:o}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,buildings:{}};let t=this.parseProtobufFields(Buffer.from(e.payload)),V={};for(let o of t.filter(c=>c.fieldNo===1&&c.wireType===2)){let c=this.parseProtobufFields(o.data),a=this.getStringField(c,1),R=this.getBytesField(c,2);!a||!R||(V[a]=this._parseCalendarBuilding(R))}return{success:!0,buildings:V}}catch(e){return{success:!1,error:e.message}}}static _parseCalendarBuilding(l){let e=this.parseProtobufFields(l),t=e.filter(a=>a.fieldNo===6&&a.wireType===2),V={};for(let a of e.filter(R=>R.fieldNo===11&&R.wireType===2)){let R=this.parseProtobufFields(a.data),A=this.getStringField(R,1),n=this.getStringField(R,2);A!=null&&n!=null&&(V[A]=n)}let o={id:this.getStringField(e,1)||"",name:this.getStringField(e,2)||"",description:this.getStringField(e,3)||"",floors:t.map(a=>a.data.toString("utf8")),meetingRooms:[],isDeleted:this.getVarintField(e,8,0)!==0,weight:this.getVarintField(e,9,0),seizeTime:this.getVarintField(e,10,0),floorLevelIds:V},c=e.filter(a=>a.fieldNo===7&&a.wireType===2);return o.meetingRooms=c.map(a=>this._parseCalendarResource(a.data)),o}static _parseCalendarResource(l){let e=this.parseProtobufFields(l),t=this.getVarintField(e,5,0),V=this.getVarintField(e,4,0);return{id:this.getStringField(e,1)||"",calendarId:this.getStringField(e,2)||"",name:this.getStringField(e,3)||"",type:V===1?"MEETING_ROOM":V===2?"OTHER":V,status:t===1?"FREE":t===2?"BUSY":t,buildingId:this.getStringField(e,6)||"",description:this.getStringField(e,7)||"",capacity:this.getVarintField(e,8,0),floorName:this.getStringField(e,9)||""}}static buildMgetEventsWithIdsRequest(l,e){let t=[];for(let o of e||[]){let c=Buffer.from(o,"utf-8");t.push(10),S(t,c.length),t.push(...c)}let V=i(F,{payloadType:1,cmd:1002006,cid:l,payload:new Uint8Array(t)});return Buffer.from(b(F,V))}static decodeMgetEventsWithIdsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let c=this.extractErrorMessage(e.payload);if(c)return{success:!1,error:c}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,events:{}};let t=Buffer.from(e.payload),V=this.parseProtobufFields(t),o={};for(let c of V){if(c.fieldNo!==1||c.wireType!==2)continue;let a=this.parseProtobufFields(c.data),R=this.getStringField(a,1);if(!R)continue;let A=this.getBytesField(a,2);if(!A){o[R]={eventKey:R};continue}o[R]=this._parseMgetEventDetail(A)}return{success:!0,events:o}}catch(e){return{success:!1,error:e.message}}}static _parseMgetEventDetail(l){let e=this.parseProtobufFields(l),t={eventKey:this.getStringField(e,1)||"",uid:this.getStringField(e,2)||"",rrule:this.getStringField(e,20)||"",startTime:this.getVarintField(e,25,0),startTimezone:this.getStringField(e,26)||"",endTime:this.getVarintField(e,27,0),endTimezone:this.getStringField(e,28)||"",summary:this.getStringField(e,29)||"",description:this.getStringField(e,30)||"",location:null,attendees:[]},V=this.getBytesField(e,32);if(V){let o=this.parseProtobufFields(V);t.location={name:this.getStringField(o,1)||"",address:this.getStringField(o,2)||""}}for(let o of e){if(o.fieldNo!==33||o.wireType!==2)continue;let c=this.parseProtobufFields(o.data);t.attendees.push({displayName:this.getStringField(c,4)||"",isOrganizer:this.getVarintField(c,6,0)!==0})}return t}static buildGetPlaceTipsRequest(l,e,t={}){let V=[],o=Buffer.from(e,"utf-8"),c=Buffer.from(t.locale||"zh_CN","utf-8");V.push(10),S(V,o.length),V.push(...o),V.push(18),S(V,c.length),V.push(...c);let a=i(F,{payloadType:1,cmd:1000037,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,a))}static decodeGetPlaceTipsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let c=this.extractErrorMessage(e.payload);if(c)return{success:!1,error:c}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,places:[]};let t=Buffer.from(e.payload);return{success:!0,places:this.parseProtobufFields(t).filter(c=>c.fieldNo===1&&c.wireType===2).map(c=>this._parsePlaceTip(c.data))}}catch(e){return{success:!1,error:e.message}}}static _parsePlaceTip(l){let e=this.parseProtobufFields(l),t=this.getStringField(e,3)||"",V=null,o=null;if(t){let[c,a]=t.split(","),R=Number.parseFloat(c),A=Number.parseFloat(a);V=Number.isFinite(R)?R:null,o=Number.isFinite(A)?A:null}return{placeId:this.getStringField(e,1)||"",name:this.getStringField(e,2)||"",coordinates:t,longitude:V,latitude:o,address:this.getStringField(e,4)||"",description:this.getStringField(e,5)||""}}static buildPullMeetingRoomsInBuildingRequest(l,e,t,V,o={}){let c=[];c.push(8),this.pushVarintBigInt(c,BigInt(t)),c.push(16),this.pushVarintBigInt(c,BigInt(V));for(let A of e){if(!A)continue;let n=Buffer.from(A,"utf-8");c.push(26),S(c,n.length),c.push(...n)}if(o.rrule!=null&&o.rrule!==""){let A=Buffer.from(o.rrule,"utf-8");c.push(34),S(c,A.length),c.push(...A)}if(o.needDisabledResource!=null&&(c.push(40),c.push(o.needDisabledResource?1:0)),o.timezone!=null&&o.timezone!==""){let A=Buffer.from(o.timezone,"utf-8");c.push(50),S(c,A.length),c.push(...A)}let a=[];if(o.minCapacity!=null&&o.minCapacity>0&&(a.push(8),S(a,o.minCapacity)),o.needEquipments&&o.needEquipments.length>0)for(let A of o.needEquipments){let n=Buffer.from(A,"utf-8");a.push(18),S(a,n.length),a.push(...n)}a.length>0&&(c.push(58),S(c,a.length),c.push(...a));let R=i(F,{payloadType:1,cmd:1010010,cid:l,payload:new Uint8Array(c)});return Buffer.from(b(F,R))}static decodePullMeetingRoomsInBuildingResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let a=this.extractErrorMessage(e.payload);if(a)return{success:!1,error:a}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,resources:{},resourceWeights:{}};let t=Buffer.from(e.payload),V=this.parseProtobufFields(t),o={};for(let a of V){if(a.fieldNo!==1||a.wireType!==2)continue;let R=this.parseProtobufFields(a.data),A=this.getStringField(R,1)||"",n=this.getBytesField(R,2);!A||!n||(o[A]=this._parseCalendarResource(n))}let c={};for(let a of V){if(a.fieldNo!==4||a.wireType!==2)continue;let R=this.parseProtobufFields(a.data),A=this.getStringField(R,1)||"",n=this.getVarintField(R,2,0);A&&(c[A]=n)}return{success:!0,resources:o,resourceWeights:c}}catch(e){return{success:!1,error:e.message}}}static buildMultiCalendarSearchRequest(l,e,t={}){let V=[],o=Buffer.from(e,"utf-8");V.push(10),S(V,o.length),V.push(...o),t.offset!=null&&(V.push(16),S(V,t.offset));let c=t.count??50;V.push(24),S(V,c),t.needSearchMeetingRoom!=null&&(V.push(32),V.push(t.needSearchMeetingRoom?1:0)),t.needSearchSharedCalendar!=null&&(V.push(40),V.push(t.needSearchSharedCalendar?1:0)),t.needSearchPrimaryCalendar!=null&&(V.push(48),V.push(t.needSearchPrimaryCalendar?1:0)),t.needSearchExternalPrimaryCalendar!=null&&(V.push(56),V.push(t.needSearchExternalPrimaryCalendar?1:0));let a=i(F,{payloadType:1,cmd:1000017,cid:l,payload:new Uint8Array(V)});return Buffer.from(b(F,a))}static buildPullTenantsByIdsBody(l=[]){let e=[];for(let t of l){if(!t)continue;let V=Buffer.from(t,"utf-8");e.push(18),S(e,V.length),e.push(...V)}return Buffer.from(e)}static buildPullTenantsByIdsRequest(l,e=[]){let t=this.buildPullTenantsByIdsBody(e),V=i(F,{payloadType:1,cmd:300,cid:l,payload:new Uint8Array(t)});return Buffer.from(b(F,V))}static decodeMultiCalendarSearchResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let A=this.extractErrorMessage(e.payload);if(A)return{success:!1,error:A}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,contents:[],calendarChatterMap:{},chatterMap:{},calendarBriefMap:{}};let t=Buffer.from(e.payload),V=this.parseProtobufFields(t),o=V.filter(A=>A.fieldNo===1&&A.wireType===2).map(A=>this._parseMultiCalendarSearchContent(A.data)),c={},a={},R={};for(let A of V)if(A.wireType===2&&(A.fieldNo===2||A.fieldNo===3||A.fieldNo===4)){let n=this.parseProtobufFields(A.data),h=this.getStringField(n,1)||"";if(!h)continue;let d=this.getBytesField(n,2);if(!d)continue;let g=A.fieldNo===2?c:A.fieldNo===3?a:R;g[h]=d}return{success:!0,contents:o,calendarChatterMap:c,chatterMap:a,calendarBriefMap:R}}catch(e){return{success:!1,error:e.message}}}static decodePullTenantsByIdsResponse(l){try{let e=G(F,l);if(this._isPacketError(e)){if(e.payload&&e.payload.length>0){let c=this.extractErrorMessage(e.payload);if(c)return{success:!1,error:c}}return{success:!1,error:`Packet status: ${e.status}`}}if(!e.payload||e.payload.length===0)return{success:!0,tenants:{}};let t=Buffer.from(e.payload),V=this.parseProtobufFields(t),o={};for(let c of V){if(c.fieldNo!==1||c.wireType!==2)continue;let a=this.parseProtobufFields(c.data),R=this.getStringField(a,1)||"",A=this.getBytesField(a,2);!R||!A||(o[R]=this._parseTenant(A))}return{success:!0,tenants:o}}catch(e){return{success:!1,error:e.message}}}static _parseTenant(l){let e=this.parseProtobufFields(l);return{id:this.getStringField(e,1)||"",name:this.getStringField(e,2)||"",contactName:this.getStringField(e,3)||"",contactMobile:this.getStringField(e,4)||"",contactEmail:this.getStringField(e,5)||"",address:this.getStringField(e,6)||"",domain:this.getStringField(e,7)||"",postCode:this.getStringField(e,8)||"",remark:this.getStringField(e,9)||"",telephone:this.getStringField(e,10)||"",iconUrl:this.getStringField(e,11)||"",avatar:this._parseImage(this.getBytesField(e,12)),unitLeague:this.getStringField(e,13)||"",i18nName:this._parseStringMap(e,14)}}static _parseImage(l){if(!l)return null;let e=this.parseProtobufFields(l);return{key:this.getStringField(e,1)||"",width:this.getVarintField(e,3,0),height:this.getVarintField(e,4,0),secureKey:this.getStringField(e,5)||"",secureWidth:this.getVarintField(e,7,0),secureHeight:this.getVarintField(e,8,0),size:this.getVarintField(e,10,0),fsUnit:this.getStringField(e,11)||"",params:this._parseStringMap(e,12),etag:this.getStringField(e,13)||""}}static _parseStringMap(l,e){let t=l.filter(o=>o.fieldNo===e&&o.wireType===2),V={};for(let o of t){let c=this.parseProtobufFields(o.data),a=this.getStringField(c,1)||"";a&&(V[a]=this.getStringField(c,2)||"")}return V}static _parseMultiCalendarSearchContent(l){let e=this.parseProtobufFields(l),t=this.getVarintField(e,2,0),V={1:"CHATTER",2:"MEETING_ROOM",3:"SHARED_CALENDAR"};return{calendarId:this.getStringField(e,1)||"",type:V[t]||t,title:this.getStringField(e,3)||"",subtitle:this.getStringField(e,4)||"",avatarUrl:this.getStringField(e,5)||"",isPrivate:this.getVarintField(e,6,0)!==0,isMember:this.getVarintField(e,7,0)!==0,isDisabled:this.getVarintField(e,8,0)!==0,isDismiss:this.getVarintField(e,9,0)!==0,isCrossTenant:this.getVarintField(e,10,0)!==0,calendarTenantId:this.getStringField(e,11)||"",subscriberNum:this.getVarintField(e,15,0)}}};k.CMD_DECODERS={27:k.decodeReactions,41:k.decodeMessageReadCount,74:k.decodeGroupReadState,92:k.decodeThreadReplyCount,130:k.decodeUserReactions,146:k.decodeUserMRUReactions,1002:k.decodeFeedCards,1311:k.decodeMessagePreviews,5104:k.decodePushPin,5105:k.decodePushPinRead,5916:k.decodeChatTabs,7001:k.decodeDeviceOnlineStatus,8106:k.decodeThreadReadState,8110:k.decodeThreadUpdated,30002:k.decodeUrgent,30003:k.decodeUrgentAck,1020003:k.decodeCalendarSync,1103704:k.decodeChatTopNotice};var U=k;import rl from"crypto";var B=new IR({connect:{rejectUnauthorized:!1}}),NR=new Set(["originalTime","lastDate","version","startTime","endTime","createTime","updateTime"]);function ml(s,l){return s==null||s===""?l:typeof s=="bigint"?s:BigInt(s)}function QR(s){return!s||typeof s!="object"?s:{...s,...s.originalTime!==void 0?{originalTime:ml(s.originalTime)}:{}}}function YR(s,l={}){let e=BigInt(Date.now()),t=e*1000n,V={id:String(s),version:ml(l.version,t),createTime:ml(l.createTime,e),updateTime:ml(l.updateTime,e)};for(let[o,c]of Object.entries(l))if(c!==void 0){if(NR.has(o)){V[o]=ml(c);continue}if(o==="attendees"&&Array.isArray(c)){V.attendees=c.map(QR);continue}V[o]=c}return V}function Bo(s,l){if(typeof s=="bigint")return s;if(typeof s=="number"){if(!Number.isInteger(s))throw new TypeError(`${l} must be an integer`);return BigInt(s)}if(typeof s=="string"){let e=s.trim();if(/^-?\d+$/.test(e))return BigInt(e);throw new TypeError(`${l} must be an integer or numeric string`)}throw new TypeError(`${l} must be an integer or numeric string`)}function JR(s,l){let e=Bo(s,"startTime");if(Bo(l,"endTime")<=e)throw new TypeError("endTime must be greater than startTime")}function Ne(s){if(typeof s=="number")return Number.isSafeInteger(s)?s:void 0;if(typeof s=="string"){let l=s.trim();if(/^-?\d+$/.test(l)){let e=Number(l);return Number.isSafeInteger(e)?e:void 0}}}function TR(s){if(typeof s!="string"||s.length===0)return;let l=s.match(/filename\*\s*=\s*(?:([^']*)'[^']*')?([^;]+)/i);if(l?.[2])try{return decodeURIComponent(l[2].replace(/^"|"$/g,""))}catch{return l[2].replace(/^"|"$/g,"")}let e=s.match(/filename\s*=\s*"((?:\\.|[^"])*)"/i);if(e?.[1])return e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\");let t=s.match(/filename\s*=\s*([^;]+)/i);if(t?.[1])return t[1].trim()}var yR="/tmp/openbird-downloads";function xR(s){if(typeof s!="string"||s.trim()==="")return;let l=We.basename(s).replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").trim();return l===""||l==="."||l===".."?void 0:l}async function kR(s,l){let e=We.resolve(s),t=We.extname(l),V=t?l.slice(0,-t.length):l;for(let o=0;o<1e4;o++){let c=o===0?We.join(e,l):We.join(e,`${V} (${o})${t}`),a=We.resolve(c);if(!(a!==c||We.relative(e,a).startsWith("..")))try{return{handle:await FV.open(a,"wx"),path:a}}catch(R){if(R?.code==="EEXIST")continue;throw R}}throw new Error("Could not allocate unique download path")}async function fR(s,l){if(s?.body&&typeof s.body.getReader=="function"){let t=s.body.getReader(),V=0;try{for(;;){let{done:o,value:c}=await t.read();if(o)break;if(c&&c.length>0){let a=Buffer.isBuffer(c)?c:Buffer.from(c),R=0;for(;R<a.length;){let{bytesWritten:A}=await l.write(a,R,a.length-R);R+=A}V+=a.length}}}finally{t.releaseLock?.()}return V}let e=Buffer.from(await s.arrayBuffer());return await l.writeFile(e),e.length}async function Co(s){if(!(!s||!s.body||typeof s.body.cancel!="function"))try{await s.body.cancel()}catch{}}var SV=class s{constructor(){this.baseUrl="https://internal-api-lark-api.feishu.cn/im/gateway/",this.fileBaseUrl="https://internal-api-lark-file.feishu.cn",this.getCsrfTokenUrl="https://internal-api-lark-api.feishu.cn/accounts/csrf",this.getUserInfoUrl="https://internal-api-lark-api.feishu.cn/accounts/web/user",this.setUserSignatureUrl="https://internal-api-lark-api.feishu.cn/passport/users/details/",this.imageBaseUrl="https://s1-imfile.feishucdn.com/static-resource/image/",this.chatbotBaseUrl="https://open.feishu.cn/open-apis/chatbot/api/",this.botSearchBaseUrl="https://internal-api.feishu.cn/lark/bot/api/"}async getCsrfToken(l){let e=p.buildGetCsrfTokenHeader();e.Cookie=C(l.cookies);let t=cl.buildGetCsrfTokenParam(),V=new URL(this.getCsrfTokenUrl);V.search=new URLSearchParams(t).toString();let o=await fetch(V,{method:"POST",headers:e,dispatcher:B}),c=o.headers.getSetCookie(),a="";if(c){for(let A of c)if(A.includes("swp_csrf_token=")){let n=A.match(/swp_csrf_token=([^;]+)/);n&&(a=n[1],l.cookies.swp_csrf_token=n[1])}}return{data:await o.json(),xCsrfToken:a}}async getUserInfo(l,e){let t=p.buildGetUserInfoHeader(e);t.Cookie=C(l.cookies);let V=cl.buildGetUserInfoParam(),o=new URL(this.getUserInfoUrl);o.search=new URLSearchParams(V).toString();let a=await(await fetch(o,{headers:t,dispatcher:B})).json(),R=a?.data?.user?.id;return{data:a,userId:R}}async setUserSignature(l,e,t={}){if(!l||!l.cookies||typeof l.cookies!="object")return{success:!1,status:0,error:"auth with cookies is required"};if(typeof e!="string")return{success:!1,status:0,error:"description must be a string"};let{descriptionFlag:V=0}=t;if(!Number.isInteger(V)||V<0)return{success:!1,status:0,error:"descriptionFlag must be a non-negative integer"};let o=p.buildSetUserSignatureHeader();o.Cookie=C(l.cookies);let c={description:e,description_flag:V};try{let a=await fetch(this.setUserSignatureUrl,{method:"PUT",headers:o,body:JSON.stringify(c),signal:AbortSignal.timeout(1e4),dispatcher:B}),R=await a.text(),A;try{A=JSON.parse(R)}catch{A={raw:R}}if(a.status!==200){let n=A?.msg||A?.message||`HTTP ${a.status}`;return{success:!1,status:a.status,error:n,data:A}}return typeof A?.code=="number"&&A.code!==0?{success:!1,status:a.status,error:A.msg||A.message||`API code ${A.code}`,data:A}:{success:!0,status:a.status,data:A}}catch(a){return{success:!1,status:0,error:a.message}}}async getUserProfileCard(l,e){if(!l||!l.cookies||typeof l.cookies!="object")return{success:!1,error:"auth with cookies is required"};if(typeof e!="string"||!/^\d{15,20}$/.test(e))return{success:!1,error:"userId must be a 15-20 digit string"};let t=p.buildGetUserProfileCardHeader();t.Cookie=C(l.cookies);let V=U.buildGetUserProfileCardRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetUserProfileCardResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async searchSome(l,e){let t=p.buildSearchHeader();t.Cookie=C(l.cookies);let V=U.buildSearchRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B}),c=U.decodeSearchResponse(Buffer.from(await o.arrayBuffer()));return{data:c,userAndGroupIds:c}}async createChat(l,e){let t=p.buildCreateChatHeader();t.Cookie=C(l.cookies);let V=U.buildCreateChatRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,dispatcher:B}),c=U.decodeCreateChatResponse(Buffer.from(await o.arrayBuffer()));return{data:{chatId:c},chatId:c}}async createGroup(l,{name:e,description:t,memberIds:V,chatMode:o,iconKey:c}){let a=p.buildCreateGroupHeader();a.Cookie=C(l.cookies);let R=U.buildCreateGroupRequest(a["x-request-id"],{name:e,description:t,memberIds:V,chatMode:o,iconKey:c}),A=await fetch(this.baseUrl,{method:"POST",headers:a,body:R,dispatcher:B}),n=U.decodeCreateChatResponse(Buffer.from(await A.arrayBuffer()));return{success:!!n,data:{chatId:n},chatId:n}}async patchGroupChat(l,e,t={}){let V=p.buildPatchGroupChatHeader();V.Cookie=C(l.cookies);try{let o=U.buildPatchGroupChatRequest(V["x-request-id"],e,t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePatchGroupChatResponse(Buffer.from(await c.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async sendMessage(l,e,t){let V=p.buildSendMsgHeader();V.Cookie=C(l.cookies);let o=U.buildRichMessageRequest(e,V["x-request-id"],t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,dispatcher:B});return{...U.decodePutMessageResponse(Buffer.from(await c.arrayBuffer())),status:c.status}}async sendFileMessage(l,e,t){let V=p.buildSendMsgHeader();V.Cookie=C(l.cookies);let o=U.buildSendFileMessageRequest(e,V["x-request-id"],t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,dispatcher:B});return{data:Buffer.from(await c.arrayBuffer()),status:c.status}}async sendImageMessage(l,e,t){let V=p.buildSendMsgHeader();V.Cookie=C(l.cookies);let o=U.buildSendImageMessageRequest(e,V["x-request-id"],t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,dispatcher:B});return{data:Buffer.from(await c.arrayBuffer()),status:c.status}}async sendMentionMessage(l,e,t,V){let o=p.buildSendMsgHeader();o.Cookie=C(l.cookies);let c=U.buildMentionMessageRequest(e,o["x-request-id"],t,V),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,dispatcher:B});return{data:Buffer.from(await a.arrayBuffer()),status:a.status}}async sendReply(l,e,t,V={}){let{rootId:o,parentId:c}=V;if(!o||!c)throw new Error("rootId and parentId are required for thread comments");let a=p.buildSendMsgHeader();a.Cookie=C(l.cookies);let R=U.buildReplyRequest(e,a["x-request-id"],t,{rootId:o,parentId:c}),A=await fetch(this.baseUrl,{method:"POST",headers:a,body:R,dispatcher:B});return{data:Buffer.from(await A.arrayBuffer()),status:A.status}}async getUserById(l,e){let t=p.buildGetUserProfileHeader();t.Cookie=C(l.cookies);let V=U.buildGetUserProfileRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`,data:null}:{success:!0,data:U.decodeGetUserProfileResponse(Buffer.from(await o.arrayBuffer()))}}async getUserInfoById(l,e){let t=p.buildGetUserInfoByIdHeader();t.Cookie=C(l.cookies);let V=U.buildGetUserInfoByIdRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetUserInfoByIdResponse(Buffer.from(await o.arrayBuffer()))}async downloadFile(l,e,t,V={}){if(!l||!l.cookies||typeof l.cookies!="object")return{success:!1,status:0,error:"auth with cookies is required"};if(typeof e!="string"||e.trim()==="")return{success:!1,status:0,error:"messageId is required"};if(typeof t!="string"||t.trim()==="")return{success:!1,status:0,error:"fileKey is required"};if(!V||typeof V!="object"||typeof V.chatId!="string"||V.chatId.trim()==="")return{success:!1,status:0,error:"options.chatId is required"};let o=typeof V.scene=="string"&&V.scene.trim()?V.scene:"chat",c=typeof V.downloadDir=="string"&&V.downloadDir.trim()?We.resolve(V.downloadDir):yR,a=new URL(`${this.fileBaseUrl}/download/messages/${encodeURIComponent(e)}/keys/${encodeURIComponent(t)}`);a.search=new URLSearchParams({chat_id:V.chatId,scene:o}).toString();let R;try{let A=p.buildDownloadFileHeader("bytes=0-0");if(A.Cookie=C(l.cookies),R=await fetch(a.toString(),{method:"GET",headers:A,signal:AbortSignal.timeout(1e4),dispatcher:B}),R.status!==206)return{success:!1,status:R.status,error:`HTTP ${R.status}`};let n=p.buildDownloadFileHeader();n.Cookie=C(l.cookies);let h;try{if(h=await fetch(a.toString(),{method:"GET",headers:n,signal:AbortSignal.timeout(1e4),dispatcher:B}),h.status!==200)return{success:!1,status:h.status,error:`HTTP ${h.status}`};let d=h.headers?.get?.("content-disposition")??void 0,g=h.headers?.get?.("content-type")??void 0,E=h.headers?.get?.("content-range")??void 0,X=Ne(h.headers?.get?.("content-length")),r=xR(TR(d))??`${t}.bin`;await FV.mkdir(c,{recursive:!0});let{handle:m,path:W}=await kR(c,r),u=0,I=!1;try{u=await fR(h,m)}catch(N){throw I=!0,N}finally{await m.close().catch(()=>{}),I&&await FV.rm(W,{force:!0}).catch(()=>{})}return{success:!0,status:h.status,fileName:r,...g?{mimeType:g}:{},size:u,...X!==void 0?{contentLength:X}:{},...E?{contentRange:E}:{},path:W}}finally{await Co(h)}}catch(A){return{success:!1,status:0,error:A.message}}finally{await Co(R)}}async downloadImage(l,e={}){let{size:t="ORIGIN"}=e,V=EV(l),o=t==="ORIGIN",c=t==="ORIGIN"?"_ORIGIN":`_${t}`,a=`${this.imageBaseUrl}${l}${c}`;try{let R=await fetch(a,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",Referer:""},signal:AbortSignal.timeout(3e4),dispatcher:B});if(R.status!==200)return o?this.downloadImage(l,{size:"MIDDLE_WEBP"}):{success:!1,error:`HTTP ${R.status}`};let A=Buffer.from(await R.arrayBuffer());if(V&&V.secret&&V.nonce)try{A=this.decryptImage(A,V)}catch(d){return o?this.downloadImage(l,{size:"MIDDLE_WEBP"}):{success:!1,error:`Decryption failed: ${d.message}`}}let n=null,h=A.subarray(0,12).toString("hex");if(h.startsWith("89504e47"))n="image/png";else if(h.startsWith("ffd8ff"))n="image/jpeg";else if(h.startsWith("47494638"))n="image/gif";else{let d=A.subarray(0,4).toString("ascii"),g=A.subarray(8,12).toString("ascii");d==="RIFF"&&g==="WEBP"&&(n="image/webp")}return n?{success:!0,data:A,base64:A.toString("base64"),mimeType:n}:o?this.downloadImage(l,{size:"MIDDLE_WEBP"}):{success:!1,error:"Invalid image bytes (unknown magic header)"}}catch(R){return o?this.downloadImage(l,{size:"MIDDLE_WEBP"}):{success:!1,error:R.message}}}decryptImage(l,e){let{secret:t,nonce:V,additionalData:o}=e,c=Buffer.isBuffer(t)?t:Buffer.from(t),a=Buffer.isBuffer(V)?V:Buffer.from(V),R=o?Buffer.isBuffer(o)?o:Buffer.from(o):Buffer.alloc(0),A=16,n=l.subarray(0,l.length-A),h=l.subarray(l.length-A),d=rl.createDecipheriv("aes-256-gcm",c,a);return d.setAuthTag(h),R.length>0&&d.setAAD(R),Buffer.concat([d.update(n),d.final()])}async addEmojiReaction(l,e,t){let V=p.buildEmojiReactionHeader();V.Cookie=C(l.cookies);let o=U.buildEmojiReactionRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeEmojiReactionResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async removeEmojiReaction(l,e,t){let V=p.buildRemoveEmojiReactionHeader();V.Cookie=C(l.cookies);let o=U.buildRemoveEmojiReactionRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeRemoveEmojiReactionResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async calendarRsvp(l,e,t,V){let c=typeof V=="string"?{accept:1,decline:2,tentative:3}[V.toLowerCase()]||1:V,a=p.buildCalendarRsvpHeader();a.Cookie=C(l.cookies);let R=U.buildCalendarRsvpRequest(a["x-request-id"],e,t,c),A=await fetch(this.baseUrl,{method:"POST",headers:a,body:R,signal:AbortSignal.timeout(1e4),dispatcher:B}),n=Buffer.from(await A.arrayBuffer());return A.status!==200&&n.length>0?{success:!1,error:U.extractErrorMessage(n)||`HTTP ${A.status}`}:A.status!==200?{success:!1,error:`HTTP ${A.status}`}:U.decodeCalendarRsvpResponse(n)}async replyCalendarEventInvitation(l,e,t,V={}){try{let c=typeof t=="string"?{accept:1,decline:2,tentative:3,delete:4,needs_action:5,"needs-action":5}[t.toLowerCase()]??1:t,a=p.buildCalendarRsvpHeader();a.Cookie=C(l.cookies);let R=U.buildReplyCalendarEventInvitationRequest(a["x-request-id"],e,c,V),A=await fetch(this.baseUrl,{method:"POST",headers:a,body:R,signal:AbortSignal.timeout(1e4),dispatcher:B}),n=Buffer.from(await A.arrayBuffer());if(A.status!==200&&n.length>0){let h=U.decodeReplyCalendarEventInvitationResponse(n);return h.success?{success:!1,error:`HTTP ${A.status}`}:h}return A.status!==200?{success:!1,error:`HTTP ${A.status}`}:U.decodeReplyCalendarEventInvitationResponse(n)}catch(o){return{success:!1,error:o.message}}}async getCalendarEvents(l,e){let t=p.buildCalendarEventDetailHeader();t.Cookie=C(l.cookies);let V=U.buildCalendarEventDetailRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`,events:[]}:U.decodeCalendarEventDetailResponse(Buffer.from(await o.arrayBuffer()))}async createCalendarEvent(l,e,t={},V={}){try{if(typeof e!="string"||e.trim()==="")return{success:!1,error:"calendarId is required"};let o=e.trim();if(!t||typeof t!="object")return{success:!1,error:"params object is required"};if(typeof t.summary!="string"||t.summary.trim()==="")return{success:!1,error:"summary is required"};if(t.startTime===void 0||t.endTime===void 0)return{success:!1,error:"startTime and endTime are required"};JR(t.startTime,t.endTime);let c=p.buildCreateCalendarEventHeader();c.Cookie=C(l.cookies);let a=U.buildCreateCalendarEventRequest(c["x-request-id"],o,t,V),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeCreateCalendarEventResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeCreateCalendarEventResponse(A)}catch(o){return{success:!1,error:o.message}}}async deleteCalendarEvent(l,e,t,V={}){try{let o=p.buildDeleteCalendarEventHeader();o.Cookie=C(l.cookies);let c=U.buildDeleteCalendarEventRequest(o["x-request-id"],e,t,V),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(1e4),dispatcher:B}),R=Buffer.from(await a.arrayBuffer());if(a.status!==200&&R.length>0){let A=U.decodeDeleteCalendarEventResponse(R);return A.success?{success:!1,error:`HTTP ${a.status}`}:A}return a.status!==200?{success:!1,error:`HTTP ${a.status}`}:U.decodeDeleteCalendarEventResponse(R)}catch(o){return{success:!1,error:o.message}}}async updateCalendarEvent(l,e,t={},V={}){try{let o=p.buildUpdateCalendarEventHeader();o.Cookie=C(l.cookies);let c=YR(e,t),a=U.buildUpdateCalendarEventRequest(o["x-request-id"],c,V),R=await fetch(this.baseUrl,{method:"POST",headers:o,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeUpdateCalendarEventResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeUpdateCalendarEventResponse(A)}catch(o){return{success:!1,error:o.message}}}async webListCalendarEvents(l,e,t,V,o={}){try{let c=p.buildWebListCalendarEventsHeader();c.Cookie=C(l.cookies);let a=U.buildWebListCalendarEventsRequest(c["x-request-id"],e,t,V,o),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeWebListCalendarEventsResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeWebListCalendarEventsResponse(A)}catch(c){return{success:!1,error:c.message}}}async createMeetingMinute(l,e,t,V={}){try{let o=p.buildCreateMeetingMinuteHeader();o.Cookie=C(l.cookies);let c=U.buildCreateMeetingMinuteRequest(o["x-request-id"],e,t,V),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(1e4),dispatcher:B}),R=Buffer.from(await a.arrayBuffer());if(a.status!==200&&R.length>0){let A=U.decodeCreateMeetingMinuteResponse(R);return A.success?{success:!1,error:`HTTP ${a.status}`}:A}return a.status!==200?{success:!1,error:`HTTP ${a.status}`}:U.decodeCreateMeetingMinuteResponse(R)}catch(o){return{success:!1,error:o.message}}}async transferCalendarEvent(l,e,t,V,o={}){try{let c=p.buildTransferCalendarEventHeader();c.Cookie=C(l.cookies);let a=U.buildTransferCalendarEventRequest(c["x-request-id"],e,t,V,o),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeTransferCalendarEventResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeTransferCalendarEventResponse(A)}catch(c){return{success:!1,error:c.message}}}async webMgetEventsWithIds(l,e){try{let t=p.buildMgetEventsWithIdsHeader();t.Cookie=C(l.cookies);let V=U.buildMgetEventsWithIdsRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B}),c=Buffer.from(await o.arrayBuffer());if(o.status!==200&&c.length>0){let a=U.decodeMgetEventsWithIdsResponse(c);return a.success?{success:!1,error:`HTTP ${o.status}`}:a}return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeMgetEventsWithIdsResponse(c)}catch(t){return{success:!1,error:t.message}}}async webShareCalendarEvent(l,e,t,V,o={}){try{let c=p.buildWebShareCalendarEventHeader();c.Cookie=C(l.cookies);let a=U.buildWebShareCalendarEventRequest(c["x-request-id"],e,t,V,o),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeWebShareCalendarEventResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeWebShareCalendarEventResponse(A)}catch(c){return{success:!1,error:c.message}}}async upgradeToMeeting(l,e,t={}){try{let V=p.buildUpgradeToMeetingHeader();V.Cookie=C(l.cookies);let o=U.buildUpgradeToMeetingRequest(V["x-request-id"],e,t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B}),a=Buffer.from(await c.arrayBuffer());if(c.status!==200&&a.length>0){let R=U.decodeUpgradeToMeetingResponse(a);return R.success?{success:!1,error:`HTTP ${c.status}`}:R}return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeUpgradeToMeetingResponse(a)}catch(V){return{success:!1,error:V.message}}}async getBusyUser(l,e,t,V,o={}){try{let c=p.buildGetBusyUserHeader();c.Cookie=C(l.cookies);let a=U.buildGetBusyUserRequest(c["x-request-id"],e,t,V,o),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodeGetBusyUserResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodeGetBusyUserResponse(A)}catch(c){return{success:!1,error:c.message}}}async pullSmartReplyResourcesViaCmd77(l,e=[]){let t=[...new Set((e||[]).map(c=>String(c||"").trim()).filter(c=>/^img_v[23]_/.test(c)))];if(t.length===0)return{success:!0,requested:0,cachedCount:0,mode:"skip"};let V=t.filter(c=>!EV(c));if(V.length===0)return{success:!0,requested:0,cachedCount:0,mode:"skip"};let o="";try{let c=p.buildCmd77Header();c.Cookie=C(l.cookies);let a=U.buildCmd77PullSmartReplyResourceRequest(c["x-request-id"],V),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(15e3),dispatcher:B});if(R.status===200){let A=U.cacheImageCryptoFromGatewayResponseBuffer(Buffer.from(await R.arrayBuffer()));if(A>0)return{success:!0,requested:V.length,cachedCount:A,mode:"cmd77"};o="cmd=77 returned no crypto info"}else o="cmd=77 HTTP "+R.status}catch(c){o="cmd=77 error: "+c.message}try{let c=p.buildPullSmartReplyResourceHeader();c.Cookie=C(l.cookies);let a=U.buildPullSmartReplyResourceRequest(c["x-request-id"],V),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(15e3),dispatcher:B});if(R.status===200){let A=U.cacheImageCryptoFromGatewayResponseBuffer(Buffer.from(await R.arrayBuffer()));return A>0?{success:!0,requested:V.length,cachedCount:A,mode:"cmd1105047"}:{success:!1,requested:V.length,cachedCount:0,mode:"cmd1105047",error:(o?o+"; ":"")+"cmd=1105047 returned no crypto info"}}return{success:!1,requested:V.length,cachedCount:0,mode:"cmd1105047",error:(o?o+"; ":"")+"cmd=1105047 HTTP "+R.status}}catch(c){return{success:!1,requested:V.length,cachedCount:0,mode:"cmd1105047",error:(o?o+"; ":"")+"cmd=1105047 error: "+c.message}}}async getChatMeta(l,e){let t=p.buildGetChatMetaHeader();t.Cookie=C(l.cookies);let V=U.buildGetChatMetaRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(15e3),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`,chat:null}:U.decodeGetChatMetaResponse(Buffer.from(await o.arrayBuffer()))}async getChatHistory(l,e,t={}){let V=Array.isArray(t.positions)?t.positions.map(Ne):t.positions;if(!V||V.length===0){let A=Ne(t.startPosition),n=Ne(t.count)||20;if(Number.isInteger(A)&&A>0){V=[];for(let h=n;h>0;h--)V.push(A+h)}else{let h=A;if(!Number.isInteger(h)||h<=0){let d=await this.getChatMeta(l,e);d.success&&d.chat?.lastMessagePosition>0&&(h=d.chat.lastMessagePosition)}(!Number.isInteger(h)||h<=0)&&(h=100),V=[];for(let d=0;d<n;d++)V.push(h-d)}}if(V=V.filter(A=>Number.isInteger(A)&&A>0),V.length===0)return{success:!1,error:"No valid positions provided",messages:[]};let o=p.buildGetChatHistoryHeader();o.Cookie=C(l.cookies);let c=U.buildGetChatHistoryRequest(o["x-request-id"],e,V),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(15e3),dispatcher:B});if(a.status!==200)return{success:!1,error:`HTTP ${a.status}`,messages:[]};let R=U.decodeGetChatHistoryResponse(Buffer.from(await a.arrayBuffer()));if(R.success){let A=[...new Set((R.messages||[]).flatMap(n=>Array.isArray(n?.imageKeys)&&n.imageKeys.length>0?n.imageKeys:n?.imageKey?[n.imageKey]:[]).map(n=>String(n||"").trim()).filter(n=>/^img_v[23]_/.test(n)))];if(A.length>0)try{let n=await this.pullSmartReplyResourcesViaCmd77(l,A);n.success?n.cachedCount>0?Q.log("[FeishuApi] \u2705 \u5DF2\u7F13\u5B58\u56FE\u7247\u52A0\u5BC6\u4FE1\u606F: "+n.cachedCount+"/"+n.requested+" ("+n.mode+")"):n.requested>0&&Q.warn("[FeishuApi] \u26A0\uFE0F \u56FE\u7247\u52A0\u5BC6\u4FE1\u606F\u672A\u547D\u4E2D: requested="+n.requested+" mode="+n.mode):Q.warn("[FeishuApi] \u26A0\uFE0F \u56FE\u7247\u52A0\u5BC6\u4FE1\u606F\u62C9\u53D6\u5931\u8D25:",n.error||"unknown error")}catch(n){Q.warn("[FeishuApi] \u26A0\uFE0F cmd=77 \u62C9\u53D6\u56FE\u7247\u52A0\u5BC6\u4FE1\u606F\u5F02\u5E38:",n.message)}}return R}async markChatRead(l,e,t){let V=p.buildMarkChatReadHeader();V.Cookie=C(l.cookies);let o=U.buildMarkChatReadRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeMarkChatReadResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async pinSession(l,e){let t=p.buildPinSessionHeader();t.Cookie=C(l.cookies);let V=U.buildPinSessionRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodePinSessionResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async unpinSession(l,e){let t=p.buildUnpinSessionHeader();t.Cookie=C(l.cookies);let V=U.buildUnpinSessionRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeUnpinSessionResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async pullPinReadStatus(l,e){let t=p.buildPullPinReadStatusHeader();t.Cookie=C(l.cookies);let V=U.buildPullPinReadStatusRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodePullPinReadStatusResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async putPinRead(l,e){let t=p.buildPutPinReadHeader();t.Cookie=C(l.cookies);let V=U.buildPutPinReadRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodePutPinReadResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async putPin(l,e,t){let V=p.buildPutPinHeader();V.Cookie=C(l.cookies);let o=U.buildPutPinRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePutPinResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async pullChatPins(l,e,t={}){let V=p.buildPullChatPinsHeader();V.Cookie=C(l.cookies);let o=U.buildPullChatPinsRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePullChatPinsResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async deletePin(l,e,t){let V=p.buildDeletePinHeader();V.Cookie=C(l.cookies);let o=U.buildDeletePinRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeDeletePinResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async pinMessage(l,e,t){return this.putPin(l,e,t)}async unpinMessage(l,e,t){return this.deletePin(l,t,e)}async markSession(l,e){let t=p.buildMarkSessionHeader();t.Cookie=C(l.cookies);let V=U.buildMarkSessionRequest(t["x-request-id"],e,!0);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeMarkSessionResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async unmarkSession(l,e){let t=p.buildMarkSessionHeader();t.Cookie=C(l.cookies);let V=U.buildMarkSessionRequest(t["x-request-id"],e,!1);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeMarkSessionResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async getUserRelation(l,e){let t=p.buildGetUserRelationHeader();t.Cookie=C(l.cookies);let V=U.buildGetUserRelationRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetUserRelationResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async getUserPresence(l,e){let t=p.buildGetUserPresenceHeader();t.Cookie=C(l.cookies);let V=U.buildGetUserPresenceRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetUserPresenceResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async getConfig(l,e){let t=p.buildGetConfigHeader();t.Cookie=C(l.cookies);let V=U.buildGetConfigRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetConfigResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async getFeatureFlags(l,e={}){let t=p.buildGetFeatureFlagsHeader();t.Cookie=C(l.cookies);let V=U.buildGetFeatureFlagsRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetFeatureFlagsResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async saveContactAlias(l,e,t={}){let V=p.buildSaveContactAliasHeader();V.Cookie=C(l.cookies);let o=U.buildSaveContactAliasRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeSaveContactAliasResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async syncContactInfo(l,e){let t=p.buildContactInfoSyncHeader();t.Cookie=C(l.cookies);let V=U.buildContactInfoSyncRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeContactInfoSyncResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async createThread(l,e){let t=p.buildCreateThreadHeader();t.Cookie=C(l.cookies);let V=U.buildCreateThreadRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeCreateThreadResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async getThreadMessages(l,e,t={}){let V=Array.isArray(t.positions)?t.positions.map(Ne):t.positions;if(!V||V.length===0){let a=Ne(t.startPosition)||50,R=Ne(t.count)||50;V=[];for(let A=0;A<=R;A++){let n=a-A;n>=0&&V.push(n)}}if(V=V.filter(a=>Number.isInteger(a)&&a>=0),V.length===0)return{success:!1,error:"No valid positions provided",messages:[]};let o=p.buildGetThreadMessagesHeader();o.Cookie=C(l.cookies);let c=U.buildGetThreadMessagesRequest(o["x-request-id"],e,V);try{let a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(15e3),dispatcher:B});return a.status!==200?{success:!1,error:`HTTP ${a.status}`,messages:[]}:U.decodeGetThreadMessagesResponse(Buffer.from(await a.arrayBuffer()))}catch(a){return{success:!1,error:a.message,messages:[]}}}async putMessageLink(l,e,t={}){let V=p.buildPutMessageLinkHeader();V.Cookie=C(l.cookies);let o=U.buildPutMessageLinkRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePutMessageLinkResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async getMessageLinkPermission(l,e){let t=p.buildGetMessageLinkPermissionHeader();t.Cookie=C(l.cookies);let V=U.buildGetMessageLinkPermissionRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodeGetMessageLinkPermissionResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async pullMessageLinkMessages(l,e,t,V={}){let o=p.buildPullMessageLinkMessagesHeader();o.Cookie=C(l.cookies);let c=U.buildPullMessageLinkMessagesRequest(o["x-request-id"],e,t,V);try{let a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(1e4),dispatcher:B});return a.status!==200?{success:!1,error:`HTTP ${a.status}`}:U.decodePullMessageLinkMessagesResponse(Buffer.from(await a.arrayBuffer()))}catch(a){return{success:!1,error:a.message}}}async forwardMessage(l,e){let t=p.buildPutTransmitMessageHeader();t.Cookie=C(l.cookies);let V=U.buildPutTransmitMessageRequest(t["x-request-id"],e);try{let o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B});return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodePutTransmitMessageResponse(Buffer.from(await o.arrayBuffer()))}catch(o){return{success:!1,error:o.message}}}async searchInChat(l,e,t,V={}){let o=p.buildSearchHeader();o.Cookie=C(l.cookies);let c=U.buildSearchInChatRequest(o["x-request-id"],e,t,V);try{let a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(1e4),dispatcher:B});return a.status!==200?{success:!1,error:`HTTP ${a.status}`}:{success:!0,data:U.decodeSearchInChatResponse(Buffer.from(await a.arrayBuffer()))}}catch(a){return{success:!1,error:a.message}}}async putUrgent(l,e,t,V,o,c={}){let a=p.buildPutUrgentHeader();a.Cookie=C(l.cookies);let R=U.buildPutUrgentRequest(a["x-request-id"],e,t,V,o,c);try{let A=await fetch(this.baseUrl,{method:"POST",headers:a,body:R,signal:AbortSignal.timeout(1e4),dispatcher:B});return A.status!==200?{success:!1,error:`HTTP ${A.status}`}:U.decodePutUrgentResponse(Buffer.from(await A.arrayBuffer()))}catch(A){return{success:!1,error:A.message}}}async pullUrgentAckStatus(l,e,t){let V=p.buildPullUrgentAckStatusHeader();V.Cookie=C(l.cookies);let o=U.buildPullUrgentAckStatusRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePullUrgentAckStatusResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async putScheduleMessage(l,e,t,V,o={}){let c=p.buildPutScheduleMessageHeader();c.Cookie=C(l.cookies);let a=U.buildPutScheduleMessageRequest(c["x-request-id"],e,t,V,o);try{let R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B});return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodePutScheduleMessageResponse(Buffer.from(await R.arrayBuffer()))}catch(R){return{success:!1,error:R.message}}}async patchScheduleMessage(l,e,t,V,o={}){let c=p.buildPatchScheduleMessageHeader();c.Cookie=C(l.cookies);let a=U.buildPatchScheduleMessageRequest(c["x-request-id"],e,t,V,o);try{let R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B});return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodePatchScheduleMessageResponse(Buffer.from(await R.arrayBuffer()))}catch(R){return{success:!1,error:R.message}}}async pullScheduleMessageByIds(l,e,t){let V=p.buildPullScheduleMessageByIdsHeader();V.Cookie=C(l.cookies);let o=U.buildPullScheduleMessageByIdsRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePullScheduleMessageByIdsResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async pullChatScheduleMessages(l,e,t={}){let V=p.buildPullChatScheduleMessagesHeader();V.Cookie=C(l.cookies);let o=U.buildPullChatScheduleMessagesRequest(V["x-request-id"],e,t);try{let c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B});return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodePullChatScheduleMessagesResponse(Buffer.from(await c.arrayBuffer()))}catch(c){return{success:!1,error:c.message}}}async _upload(l,e,t){let{uploadKey:V,createOptions:o={},completeOptions:c={},chunkSize:a=4194304}=t;if(!Number.isInteger(a)||a<=0)return{success:!1,error:`Invalid chunkSize: ${a}`};let R="https://internal-api-lark-file.feishu.cn",A=C(l.cookies),n=U.buildUploadCreateRequest(V,o),h=p.buildUploadCreateHeader();h.Cookie=A;let d=[];try{let m=await fetch(`${R}/upload/create`,{method:"POST",headers:h,body:n,signal:AbortSignal.timeout(1e4),dispatcher:B});if(m.status!==200)return{success:!1,error:`Upload create failed: HTTP ${m.status}`};let W=U.decodeUploadCreateResponse(Buffer.from(await m.arrayBuffer()));if(!W.success)return W}catch(m){return{success:!1,error:`Upload create error: ${m.message}`}}let g=Math.ceil(e.length/a),E=p.buildUploadPartHeader();E.Cookie=A;for(let m=0;m<g;m++){let W=m*a,u=e.slice(W,W+a),I=m+1,N=`${R}/upload/part?upload_id=${encodeURIComponent(V)}&part_id=${I}&offset=${W}`;try{let Y=await fetch(N,{method:"POST",headers:E,body:u,signal:AbortSignal.timeout(3e4),dispatcher:B});if(Y.status!==200)return{success:!1,error:`Upload part ${I} failed: HTTP ${Y.status}`};let T=U.decodeUploadPartResponse(Buffer.from(await Y.arrayBuffer()));if(!T.success)return{success:!1,error:`Upload part ${I} decode failed: ${T.error}`};if(T.id===void 0||T.version===void 0)return{success:!1,error:`Upload part ${I} missing id or version`};d.push({id:T.id,version:T.version})}catch(Y){return{success:!1,error:`Upload part ${I} error: ${Y.message}`}}}let X=U.buildUploadCompleteRequest(V,d,c),r=p.buildUploadCreateHeader();r.Cookie=A;try{let m=await fetch(`${R}/upload/complete`,{method:"POST",headers:r,body:X,signal:AbortSignal.timeout(1e4),dispatcher:B});return m.status!==200?{success:!1,error:`Upload complete failed: HTTP ${m.status}`}:U.decodeUploadCompleteResponse(Buffer.from(await m.arrayBuffer()))}catch(m){return{success:!1,error:`Upload complete error: ${m.message}`}}}async uploadImage(l,e,t={}){return this._upload(l,e,{uploadKey:U.generateUploadKey("image"),createOptions:{type:0},completeOptions:{},chunkSize:t.chunkSize})}async uploadFile(l,e,t,V={}){let{mimeType:o="application/octet-stream"}=V,c=Buffer.from(JV(e)),a=rl.randomBytes(16);return this._upload(l,e,{uploadKey:U.generateUploadKey("file"),createOptions:{fileType:1,filename:t,fileSize:e.length,blake3Hash:c,secondaryId:a},completeOptions:{filename:t,mimeType:o},chunkSize:V.chunkSize})}async _jsonPost(l,e,t){let V={"content-type":"application/json",Cookie:C(e.cookies)};try{let o=await fetch(l,{method:"POST",headers:V,body:JSON.stringify(t),signal:AbortSignal.timeout(1e4),dispatcher:B});if(o.status!==200)return{success:!1,error:`HTTP ${o.status}`};let c=await o.json();return c.code!==0?{success:!1,error:c.msg||`code ${c.code}`,code:c.code}:{success:!0,data:c.data}}catch(o){return{success:!1,error:o.message}}}buildWebhookBotSignature(l,e=Math.floor(Date.now()/1e3)){let t=String(e),V=`${t}
|
|
36
36
|
${l}`,o=rl.createHmac("sha256",V).update("").digest("base64");return{timestamp:t,sign:o}}async sendWebhookBotMessage(l,e,t={}){let{secret:V,timestamp:o,sign:c,timeoutMs:a=1e4}=t,R=o!==void 0,A=c!==void 0;if(V!==void 0&&(R||A))return{success:!1,error:"secret cannot be combined with timestamp/sign options"};if(R!==A)return{success:!1,error:"timestamp and sign must be provided together"};if(e&&typeof e=="object"&&(e.timestamp!==void 0||e.sign!==void 0)&&(V!==void 0||R||A))return{success:!1,error:"payload timestamp/sign cannot be combined with signature options"};let n={...e};if(V!==void 0){let h=this.buildWebhookBotSignature(V);n.timestamp=h.timestamp,n.sign=h.sign}else R&&A&&(n.timestamp=String(o),n.sign=c);try{let h=await fetch(l,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(a),dispatcher:B});if(h.status!==200)return{success:!1,error:`HTTP ${h.status}`};let d=await h.json(),g=d?.StatusCode??d?.code,E=d?.StatusMessage??d?.msg;return typeof g=="number"&&g!==0?{success:!1,error:E||`code ${g}`,code:g}:{success:!0,data:d}}catch(h){return{success:!1,error:h.message}}}async sendWebhookBotText(l,e,t={}){return this.sendWebhookBotMessage(l,{msg_type:"text",content:{text:e}},t)}async sendWebhookBotPost(l,e,t={}){return this.sendWebhookBotMessage(l,{msg_type:"post",content:{post:e}},t)}async sendWebhookBotImage(l,e,t={}){return this.sendWebhookBotMessage(l,{msg_type:"image",content:{image_key:e}},t)}async sendWebhookBotShareChat(l,e,t={}){return this.sendWebhookBotMessage(l,{msg_type:"share_chat",content:{share_chat_id:e}},t)}async sendWebhookBotCard(l,e,t={}){return this.sendWebhookBotMessage(l,{msg_type:"interactive",card:e},t)}async _docsJsonPost(l,e,t){let V=rl.randomBytes(6).toString("base64url"),o=new URL(l),c={"content-type":"application/json;charset=UTF-8",Cookie:C(e.cookies),"x-csrftoken":e.cookies._csrf_token||e.cookies.swp_csrf_token||"","ccm-scene":"web","x-lgw-app-id":"1161","x-lgw-os-type":"3","x-lgw-terminal-type":"2","x-lsc-bizid":"2","x-lsc-terminal":"web","x-lsc-version":"1","request-id":V,"x-request-id":V,Referer:`${o.origin}/`,Origin:o.origin};try{let a=await fetch(l,{method:"POST",headers:c,body:JSON.stringify(t),signal:AbortSignal.timeout(1e4),dispatcher:B});if(a.status!==200)return{success:!1,error:`HTTP ${a.status}`};let R=await a.json();return R.code!==0?{success:!1,error:R.msg||`code ${R.code}`,code:R.code}:{success:!0,data:R.data}}catch(a){return{success:!1,error:a.message}}}async createWebhookBot(l,e,t,V,o={}){let c={name:t,description:V,bot_type_id:"444",chat_id:e,i18n:o.i18n||"zh_CN"};return o.userId&&(c.user_id=o.userId),o.avatarKey&&(c.avatar_key=o.avatarKey),o.avatarType!==void 0&&(c.avatar_type=o.avatarType),this._jsonPost(this.chatbotBaseUrl+"CreateWebhookBot",l,c)}async getWebhookBotInfo(l,e,t={}){return this._jsonPost(this.chatbotBaseUrl+"GetWebhookBotInfo",l,{bot_id:e,i18n:t.i18n||"zh_CN"})}async updateWebhookBot(l,e,t={}){let V={bot_id:e,i18n:t.i18n||"zh_CN"};return t.name&&(V.name=t.name),t.description&&(V.description=t.description),t.avatarKey&&(V.avatar_key=t.avatarKey),t.avatarType!==void 0&&(V.avatar_type=t.avatarType),this._jsonPost(this.chatbotBaseUrl+"UpdateWebhookBotInfo",l,V)}async getSignature(l,e){return this._jsonPost(this.chatbotBaseUrl+"GetSignature",l,{bot_id:e})}async deleteBot(l,e,t,V={}){return this._jsonPost(this.chatbotBaseUrl+"DeleteBotResource",l,{chat_id:e,bot_id:t,i18n:V.i18n||"zh_CN"})}async addBotToChat(l,e,t,V={}){return this._jsonPost(this.chatbotBaseUrl+"SetBotAddConf",l,{chat_id:e,bot_id:t,check_mender:V.checkMender||!1,i18n:V.i18n||"zh_CN"})}async updateAppBotInfo(l,e,t,V={}){return this._jsonPost(this.chatbotBaseUrl+"UpdateAppBotInfo",l,{chat_id:e,bot_id:t,check_mender:V.checkMender!==void 0?V.checkMender:!0,i18n:V.i18n||"zh_CN"})}async fetchBotAddConf(l,e,t={}){return this._jsonPost(this.chatbotBaseUrl+"fetch_bot_add_conf",l,{bot_id:e,i18n:t.i18n||"zh_CN"})}async fetchBotConfResource(l,e,t,V={}){return this._jsonPost(this.chatbotBaseUrl+"fetch_bot_conf_resource",l,{bot_id:e,chat_id:t,i18n:V.i18n||"zh_CN"})}async listCandidateBots(l,e,t={}){return this._jsonPost(this.botSearchBaseUrl+"pull_chat_candidate_bots",l,{chat_id:e,locale:t.locale||"zh_CN"})}async searchBots(l,e,t,V={}){return this._jsonPost(this.botSearchBaseUrl+"search_v2",l,{query:t,chat_id:e,locale:V.locale||"zh_CN"})}async getBaikeCard(l,e,t,V={}){let o=p.buildGetBaikeCardHeader();o.Cookie=C(l.cookies);let c=U.buildGetBaikeCardRequest(o["x-request-id"],e,t,{entityType:V.entityType,chatId:V.chatId,messageId:V.messageId}),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(15e3),dispatcher:B});if(a.status!==200)return{success:!1,error:`HTTP ${a.status}`};let R=Buffer.from(await a.arrayBuffer()),A=U.decodeGetBaikeCardResponse(R);return A.success&&A.html&&(A.info=U.extractBaikeCardInfo(A.html)),A}async getBaikeRecommendDocs(l,e,t={}){let V=p.buildGetBaikeRecommendDocsHeader();V.Cookie=C(l.cookies);let o=U.buildGetBaikeRecommendDocsRequest(V["x-request-id"],e,t.entityType??1),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(15e3),dispatcher:B});if(c.status!==200)return{success:!1,error:`HTTP ${c.status}`};let a=Buffer.from(await c.arrayBuffer());return U.decodeGetBaikeRecommendDocsResponse(a)}async searchGuests(l,e,t={}){try{let V=p.buildSearchGuestsHeader();V.Cookie=C(l.cookies);let o=U.buildSearchGuestsRequest(V["x-request-id"],e,t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B}),a=Buffer.from(await c.arrayBuffer());if(c.status!==200&&a.length>0){let R=U.decodeSearchGuestsResponse(a);return R.success?{success:!1,error:`HTTP ${c.status}`}:R}return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeSearchGuestsResponse(a)}catch(V){return{success:!1,error:V.message}}}async searchMeetingRooms(l,e,t,V={}){try{let o=p.buildSearchMeetingRoomsHeader();o.Cookie=C(l.cookies);let c=U.buildSearchMeetingRoomsRequest(o["x-request-id"],e,t,V),a=await fetch(this.baseUrl,{method:"POST",headers:o,body:c,signal:AbortSignal.timeout(1e4),dispatcher:B}),R=Buffer.from(await a.arrayBuffer());if(a.status!==200&&R.length>0){let A=U.decodeSearchMeetingRoomsResponse(R);return A.success?{success:!1,error:`HTTP ${a.status}`}:A}return a.status!==200?{success:!1,error:`HTTP ${a.status}`}:U.decodeSearchMeetingRoomsResponse(R)}catch(o){return{success:!1,error:o.message}}}async pullBuildings(l,e={}){try{let t=p.buildPullBuildingsHeader();t.Cookie=C(l.cookies);let V=U.buildPullBuildingsRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B}),c=Buffer.from(await o.arrayBuffer());if(o.status!==200&&c.length>0){let a=U.decodePullBuildingsResponse(c);return a.success?{success:!1,error:`HTTP ${o.status}`}:a}return o.status!==200?{success:!1,error:`HTTP ${o.status}`}:U.decodePullBuildingsResponse(c)}catch(t){return{success:!1,error:t.message}}}async pullMeetingRoomsInBuilding(l,e,t,V,o={}){try{let c=p.buildPullMeetingRoomsInBuildingHeader();c.Cookie=C(l.cookies);let a=U.buildPullMeetingRoomsInBuildingRequest(c["x-request-id"],e,t,V,o),R=await fetch(this.baseUrl,{method:"POST",headers:c,body:a,signal:AbortSignal.timeout(1e4),dispatcher:B}),A=Buffer.from(await R.arrayBuffer());if(R.status!==200&&A.length>0){let n=U.decodePullMeetingRoomsInBuildingResponse(A);return n.success?{success:!1,error:`HTTP ${R.status}`}:n}return R.status!==200?{success:!1,error:`HTTP ${R.status}`}:U.decodePullMeetingRoomsInBuildingResponse(A)}catch(c){return{success:!1,error:c.message}}}async getPlaceTips(l,e,t={}){try{let V=p.buildGetPlaceTipsHeader();V.Cookie=C(l.cookies);let o=U.buildGetPlaceTipsRequest(V["x-request-id"],e,t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B}),a=Buffer.from(await c.arrayBuffer());if(c.status!==200&&a.length>0){let R=U.decodeGetPlaceTipsResponse(a);return R.success?{success:!1,error:`HTTP ${c.status}`}:R}return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeGetPlaceTipsResponse(a)}catch(V){return{success:!1,error:V.message}}}async multiCalendarSearch(l,e,t={}){try{let V=p.buildMultiCalendarSearchHeader();V.Cookie=C(l.cookies);let o=U.buildMultiCalendarSearchRequest(V["x-request-id"],e,t),c=await fetch(this.baseUrl,{method:"POST",headers:V,body:o,signal:AbortSignal.timeout(1e4),dispatcher:B}),a=Buffer.from(await c.arrayBuffer());if(c.status!==200&&a.length>0){let R=U.decodeMultiCalendarSearchResponse(a);return R.success?{success:!1,error:`HTTP ${c.status}`}:R}return c.status!==200?{success:!1,error:`HTTP ${c.status}`}:U.decodeMultiCalendarSearchResponse(a)}catch(V){return{success:!1,error:V.message}}}async pullTenantsByIds(l,e){try{let t=p.buildPullTenantsByIdsHeader();t.Cookie=C(l.cookies);let V=U.buildPullTenantsByIdsRequest(t["x-request-id"],e),o=await fetch(this.baseUrl,{method:"POST",headers:t,body:V,signal:AbortSignal.timeout(1e4),dispatcher:B}),c=Buffer.from(await o.arrayBuffer());if(o.status!==200&&c.length>0){let R=U.decodePullTenantsByIdsResponse(c);return R.success?{success:!1,error:`HTTP ${o.status}`}:R}if(o.status!==200)return{success:!1,error:`HTTP ${o.status}`};let a=U.decodePullTenantsByIdsResponse(c);return a.success?{success:!0,data:{tenants:a.tenants}}:a}catch(t){return{success:!1,error:t.message}}}static _validateFeishuOrigin(l){try{let{hostname:e,protocol:t}=new URL(l);return t!=="https:"?{valid:!1,error:`Origin must use HTTPS, got: ${t}`}:/\.(feishu\.cn|larksuite\.com)$/.test(e)?{valid:!0}:{valid:!1,error:`Origin must be a *.feishu.cn or *.larksuite.com domain, got: ${e}`}}catch{return{valid:!1,error:`Invalid origin URL: ${l}`}}}async _jsonGet(l,e,t={}){let V=new URL(l);for(let[c,a]of Object.entries(t))a!=null&&V.searchParams.set(c,String(a));let o={accept:"application/json, text/plain, */*",Cookie:C(e.cookies),"x-csrf-token":e.cookies.swp_csrf_token||e.cookies._csrf_token||""};try{let c=await fetch(V.href,{method:"GET",headers:o,signal:AbortSignal.timeout(15e3),dispatcher:B});if(c.status!==200)return{success:!1,error:`HTTP ${c.status}`};let a=await c.json();return a.code!==0?{success:!1,error:a.msg||`code ${a.code}`,code:a.code}:{success:!0,data:a.data}}catch(c){return{success:!1,error:c.message}}}async resolveWikiToken(l,e,t){let o=`${new URL(e).origin}/wiki/${encodeURIComponent(t)}`,c={accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",Cookie:C(l.cookies)};try{let a=o,R=5;for(let A=0;A<=R;A++){let n=await fetch(a,{method:"GET",headers:c,signal:AbortSignal.timeout(15e3),redirect:"manual",dispatcher:B});if(n.status>=300&&n.status<400){let d=n.headers.get("location");if(!d)return{success:!1,error:`Redirect with no Location header (HTTP ${n.status})`};if(A===R)return{success:!1,error:`Too many redirects (>${R})`};a=new URL(d,a).href;continue}if(n.status!==200)return{success:!1,error:`HTTP ${n.status}`};let h=await n.text();return s._parseWikiHtml(h)}return{success:!1,error:`Too many redirects (>${R})`}}catch(a){return{success:!1,error:a.message}}}static _parseWikiHtml(l){let e=/window\.current_space_wiki\s*=\s*Object\s*\(\s*\{/,t=l.match(e);if(!t)return{success:!1,error:"Cannot find window.current_space_wiki in SSR HTML"};let V=l.indexOf("{",t.index+t[0].length-1),o=s._findBalancedObject(l,V);if(!o)return{success:!1,error:"Cannot parse window.current_space_wiki object"};let c;try{c=JSON.parse(o)}catch{if(c=s._parseJsObjectLiteral(o),!c)return{success:!1,error:"Cannot parse current_space_wiki object literal"}}return!c.obj_token||c.obj_type===void 0?{success:!1,error:"current_space_wiki missing required fields (obj_token, obj_type)"}:{success:!0,data:{objToken:c.obj_token,objType:c.obj_type,spaceId:c.space_id,wikiToken:c.wiki_token,wikiVersion:c.wiki_version}}}static _findBalancedObject(l,e){let t=0,V=null,o=!1;for(let c=e;c<l.length;c++){let a=l[c];if(V){o?o=!1:a==="\\"?o=!0:a===V&&(V=null);continue}if(a==='"'||a==="'"){V=a;continue}if(a==="{"){t++;continue}if(a==="}"&&(t--,t===0))return l.slice(e,c+1)}return null}static _parseJsObjectLiteral(l){let e={},t=1,V=l.length-1;for(;t<V;){for(;t<V&&/[\s,]/.test(l[t]);)t++;if(t>=V)break;let o;if(l[t]==='"'||l[t]==="'"){let c=l[t++],a=t;for(;t<V;){if(l[t]==="\\"){t+=2;continue}if(l[t]===c)break;t++}o=l.slice(a,t),t++}else{let c=t;for(;t<V&&/\w/.test(l[t]);)t++;o=l.slice(c,t)}if(!o)return null;for(;t<V&&l[t]===" ";)t++;if(l[t]!==":")return null;for(t++;t<V&&l[t]===" ";)t++;if(l[t]==='"'||l[t]==="'"){let c=l[t++],a=t;for(;t<V;){if(l[t]==="\\"){t+=2;continue}if(l[t]===c)break;t++}e[o]=l.slice(a,t),t++}else if(l[t]==="{"){let c=1;for(t++;t<V&&c>0;){if(l[t]==='"'||l[t]==="'"){let a=l[t++];for(;t<V&&l[t]!==a;)l[t]==="\\"&&t++,t++}else l[t]==="{"?c++:l[t]==="}"&&c--;t++}}else if(l[t]==="["){let c=1;for(t++;t<V&&c>0;){if(l[t]==='"'||l[t]==="'"){let a=l[t++];for(;t<V&&l[t]!==a;)l[t]==="\\"&&t++,t++}else l[t]==="["?c++:l[t]==="]"&&c--;t++}}else{let c=t;for(;t<V&&/[^\s,}]/.test(l[t]);)t++;let a=l.slice(c,t);e[o]=/^-?\d+(\.\d+)?$/.test(a)?Number(a):a}}return Object.keys(e).length>0?e:null}async getDocxBlockTree(l,e,t,V={}){let o=V.mode??0,c=V.limit??200,a=V.maxPages??100,A=`${new URL(e).origin}/space/api/docx/pages/client_vars`,n={},h=[],d=null,g=[],E=null,X=new Set,r=!1;try{for(let W=0;W<a;W++){let u={id:t,mode:o,limit:c};E&&(u.cursor=E);let I=await this._jsonGet(A,l,u);if(!I.success)return I;let N=I.data||{},Y=N.block_map||{};if(Object.assign(n,Y),N.block_sequence&&(h=h.concat(N.block_sequence)),N.structure_version!==void 0&&(d=N.structure_version),N.skip_blocks&&(g=g.concat(N.skip_blocks)),!N.has_more){r=!1;break}if(!N.cursor)return{success:!1,error:"API returned has_more=true but no cursor"};if(r=!0,X.has(N.cursor))return{success:!1,error:`Pagination loop detected: cursor ${N.cursor} repeated`};X.add(N.cursor),E=N.cursor}if(r)return{success:!1,error:`Exceeded maxPages (${a}) while paginating docx blocks`};let m=s._buildBlockTree(t,n);return m.missing?{success:!1,error:`Root block ${t} not found in API response`}:{success:!0,data:{token:t,structureVersion:d,totalBlocks:Object.keys(n).length,skipBlocks:g,blockSequence:h,tree:m,rawBlockMap:n}}}catch(m){return{success:!1,error:m.message}}}async submitDocxChange(l,e,t,V,o){let a=`${new URL(e).origin}/space/api/docx/blocks/user_change`,R={member_id:V,uuid:rl.randomUUID(),page_id:t,change_map:o};return this._docsJsonPost(a,l,R)}static _extractPlainText(l){let e=l?.data?.text?.initialAttributedTexts?.text;return e?typeof e=="string"?e:Object.entries(e).sort(([t],[V])=>Number(t)-Number(V)).map(([,t])=>t).join(""):""}static _buildBlockTree(l,e){function t(V,o=new Set){let c=e[V];if(!c)return{id:V,missing:!0};if(o.has(V))return{id:V,cycle:!0,children:[]};let a=c.data||{},R=Array.isArray(a.children)?a.children:[],A=new Set(o);return A.add(V),{id:c.id,type:a.type||null,version:c.version,parentId:a.parent_id||null,text:s._extractPlainText(c),children:R.map(n=>t(n,A))}}return t(l)}},Fe=SV;import KR from"ws";import{ungzip as MR}from"pako";var XV=class{constructor(l,e={}){this.baseUrl="wss://msg-frontier.feishu.cn/ws/v2",this.auth=l,this.meId=null,this.ws=null,this.messageHandlers=[],this.eventHandlers=[],this.processedMessages=new Map,this.MESSAGE_CACHE_EXPIRY_MS=300*1e3,this.MAX_CACHE_SIZE=1e4,this.autoReconnect=e.autoReconnect!==!1,this.reconnectBaseDelay=e.reconnectBaseDelay||1e3,this.reconnectMaxDelay=e.reconnectMaxDelay||3e4,this.reconnectAttempts=0,this.reconnectTimer=null,this.shouldReconnect=!1}setMeId(l){this.meId=String(l)}sendAck(l,e){let t=U.buildAckPacket(e);l.send(t)}onMessage(l){this.messageHandlers.push(l)}onEvent(l){this.eventHandlers.push(l)}isDuplicateMessage(l){let{messageId:e,sid:t}=l,V=e||t;if(!V)return!1;let o=Date.now();return this.processedMessages.has(V)?!0:(this.processedMessages.set(V,o),this.processedMessages.size>this.MAX_CACHE_SIZE&&this.cleanupMessageCache(),!1)}cleanupMessageCache(){let l=Date.now(),e=0;for(let[t,V]of this.processedMessages)l-V>this.MESSAGE_CACHE_EXPIRY_MS&&(this.processedMessages.delete(t),e++);if(this.processedMessages.size>this.MAX_CACHE_SIZE){let t=Array.from(this.processedMessages.entries());t.sort((o,c)=>o[1]-c[1]);let V=Math.floor(t.length/2);for(let o=0;o<V;o++)this.processedMessages.delete(t[o][0]),e++}e>0&&Q.log(`[WS] Cleaned ${e} expired message cache entries, current cache size: ${this.processedMessages.size}`)}scheduleReconnect(){if(!this.autoReconnect||!this.shouldReconnect)return;let l=Math.min(this.reconnectBaseDelay*Math.pow(2,this.reconnectAttempts),this.reconnectMaxDelay);this.reconnectAttempts++,Q.log(`[WS] Reconnecting in ${l/1e3}s (attempt ${this.reconnectAttempts})...`),this.reconnectTimer=setTimeout(async()=>{if(this.shouldReconnect)try{await this.connect()}catch(e){Q.error("[WS] Reconnect failed:",e.message),this.scheduleReconnect()}},l)}async connect(){let l=await cl.buildReceiveMsgParam(this.auth),e=Object.entries(l).map(([V,o])=>`${encodeURIComponent(V)}=${encodeURIComponent(o)}`).join("&"),t=`${this.baseUrl}?${e}`;return Q.log("[WS] Connecting..."),new Promise((V,o)=>{this.ws=new KR(t,{headers:{Origin:"https://open-dev.feishu.cn","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.ws.on("open",()=>{Q.log("[WS] Connected"),this.reconnectAttempts=0,V()}),this.ws.on("message",async c=>{try{let a;c[0]===31&&c[1]===139?a=MR(c):a=c;let R=U.decodeReceiveMessage(a);R.sid&&this.sendAck(this.ws,R.sid),await this.handleMessage(R)}catch(a){Q.error("[WS] Error processing message:",a)}}),this.ws.on("close",(c,a)=>{Q.log(`[WS] Disconnected: code=${c}`),this.ws=null,this.shouldReconnect&&this.scheduleReconnect()}),this.ws.on("error",c=>{Q.error("[WS] Error:",c.message),o(c)})})}async handleMessage(l){let{command:e}=l;if(e&&e!==6){let r=dV[e]||"UNKNOWN",m=l.event||r;e!==200&&e!==6e3&&Q.log(`[WS] Event | cmd=${e} | ${r} | ${m}`);for(let W of this.eventHandlers)try{await W(l,this)}catch(u){Q.error("[WS] Event handler error:",u)}return}let{fromId:t,chatId:V,type:o,fromType:c,chatType:a,threadId:R,messageId:A}=l;if(this.isDuplicateMessage(l)){Q.log(`[WS] Skipping duplicate message messageId=${A||"N/A"}`);return}let n=Wo(a),h=ZV(c),d=gV(o),g=R?` thread=${R}`:"",{content:E}=l,X=E&&E.length>50?E.substring(0,50)+"...":E||"";if(V&&Q.log(`[WS] Message | ${n} | ${h} | ${d} | chat=${V} | from=${t}${g}: ${X}`),V)for(let r of this.messageHandlers)try{await r(l,this)}catch(m){Q.error("[WS] Error in message handler:",m)}}async start(){this.shouldReconnect=!0,await this.connect()}stop(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null),this.processedMessages.clear()}},po=XV;import DR from"crypto";function He(s){return s.toString(36)}function rV(s,l){if(!s)return{changeset:"Z:0>0$",apool:UV(l)};let e=He(s.length);return{changeset:`Z:0>${e}*0+${e}$${s}`,apool:UV(l)}}function Io(s,l,e){if(s===0)return rV(l,e);let t=l.length,V=t-s,o=He(s),c=V>=0?`>${He(V)}`:`<${He(-V)}`,a=`-${o}`,R=t>0?`*0+${He(t)}`:"",A=t>0?`$${l}`:"$";return{changeset:`Z:${o}${c}${a}${R}${A}`,apool:UV(e)}}function No(s,l){if(!s)return{initialAttributedTexts:{text:{0:""},attribs:{0:""}},apool:{numToAttrib:{},nextNum:0}};let e=He(s.length);return{initialAttributedTexts:{text:{0:s},attribs:{0:`*0+${e}`}},apool:{numToAttrib:{0:["author",l]},nextNum:1}}}function UV(s){return{numToAttrib:{0:["author",s]},nextNum:1,attribToNum:{[`author,${s}`]:0}}}var mV=class s{constructor(l,e,t,V){this.api=l,this.auth=e,this.origin=t,this.pageId=V,this.blockMap=null,this.structureVersion=null,this.memberId=null,this.authorId=null,this._opened=!1}async open(){let l=await this.api.getDocxBlockTree(this.auth,this.origin,this.pageId);if(!l.success)return{success:!1,error:l.error};this.blockMap=l.data.rawBlockMap,this.structureVersion=l.data.structureVersion,this.memberId=s._generateMemberId(),this.authorId="";for(let e of Object.values(this.blockMap))if(e.data?.author){this.authorId=e.data.author;break}return this._opened=!0,{success:!0,data:{blockCount:Object.keys(this.blockMap).length,structureVersion:this.structureVersion}}}getBlockTree(){return this._assertOpen(),Fe._buildBlockTree(this.pageId,this.blockMap)}getBlock(l){return this._assertOpen(),this.blockMap[l]||null}async insertBlock(l,e,t,V={}){this._assertOpen();let o=this.blockMap[l];if(!o)return{success:!1,error:`Parent block ${l} not found`};let c=o.data?.children||[];if(e<0||e>c.length)return{success:!1,error:`Position ${e} out of bounds (0-${c.length})`};let a=s._generateBlockId(),{text:R,...A}=V,n={parent_id:l,type:t,children:[],comments:[],revisions:[],author:this.authorId,text:No(R||"",this.authorId),folded:!1};for(let[E,X]of Object.entries(A))X!==void 0&&(n[E]=X);let h={[a]:{id:a,version:0,payload:{ops:[{p:[],action:{oi:n}}]}},[l]:{id:l,version:o.version,payload:{ops:[{p:["children",e],action:{li:a}}]}}},d=await this._submitChange(h);if(!d.success)return d;let g=d.data?.block_map?.[a]?.version??0;return this.blockMap[a]={id:a,version:g,data:n},o.data.children||(o.data.children=[]),o.data.children.splice(e,0,a),{success:!0,data:{blockId:a}}}async editText(l,e){this._assertOpen();let t=this.blockMap[l];if(!t)return{success:!1,error:`Block ${l} not found`};let V=t.data?.text?.initialAttributedTexts?.text||{},c=Object.entries(V).sort(([g],[E])=>Number(g)-Number(E)).map(([,g])=>g).join("").length,a,R;c===0?{changeset:a,apool:R}=rV(e,this.authorId):{changeset:a,apool:R}=Io(c,e,this.authorId);let A={[l]:{id:l,version:t.version,payload:{ops:[{p:["text"],subType:{t:"easysync",o:{zone_changesets:{0:a},apool:R}}}]}}},n=await this._submitChange(A);if(!n.success)return n;t.data.text||(t.data.text={initialAttributedTexts:{text:{},attribs:{}},apool:{}});let h=t.data.text.initialAttributedTexts;h.text={0:e};let d=e.length.toString(36);return h.attribs={0:e?`*0+${d}`:""},t.data.text.apool=e?{numToAttrib:{0:["author",this.authorId]},nextNum:1}:{numToAttrib:{},nextNum:0},{success:!0}}async deleteBlocks(l){this._assertOpen();let e=new Map;for(let o of l){let c=this.blockMap[o];if(!c)return{success:!1,error:`Block ${o} not found`};let a=c.data?.parent_id;if(!a||!this.blockMap[a])return{success:!1,error:`Parent of block ${o} not found`};e.has(a)||e.set(a,[]),e.get(a).push(o)}let t={};for(let[o,c]of e){let a=this.blockMap[o],R=[...a.data?.children||[]],n=c.map(h=>({id:h,idx:R.indexOf(h)})).filter(h=>h.idx>=0).sort((h,d)=>d.idx-h.idx).map(({id:h,idx:d})=>({p:["children",d],action:{ld:h}}));t[o]={id:o,version:a.version,payload:{ops:n}}}let V=await this._submitChange(t);if(!V.success)return V;for(let[o,c]of e){let a=this.blockMap[o];a.data?.children&&(a.data.children=a.data.children.filter(R=>!c.includes(R)))}for(let o of l)this._removeSubtree(o);return{success:!0}}async changeBlockType(l,e){this._assertOpen();let t=this.blockMap[l];if(!t)return{success:!1,error:`Block ${l} not found`};let V=t.data?.type;if(!V)return{success:!1,error:`Block ${l} has no type`};let o={[l]:{id:l,version:t.version,payload:{ops:[{p:["type"],action:{od:V,oi:e}}]}}},c=await this._submitChange(o);return c.success?(t.data.type=e,{success:!0}):c}async setBlockProperties(l,e){this._assertOpen();let t=this.blockMap[l];if(!t)return{success:!1,error:`Block ${l} not found`};let V=[];for(let[a,R]of Object.entries(e)){let A=t.data?.[a];A!==void 0?V.push({p:[a],action:{od:A,oi:R}}):V.push({p:[a],action:{oi:R}})}if(V.length===0)return{success:!0};let o={[l]:{id:l,version:t.version,payload:{ops:V}}},c=await this._submitChange(o);return c.success?(Object.assign(t.data,e),{success:!0}):c}async moveBlock(l,e,t){this._assertOpen();let V=this.blockMap[l];if(!V)return{success:!1,error:`Block ${l} not found`};let o=this.blockMap[e];if(!o)return{success:!1,error:`New parent ${e} not found`};let c=V.data?.parent_id;if(!c||!this.blockMap[c])return{success:!1,error:`Current parent of block ${l} not found`};let a=this.blockMap[c],A=(a.data?.children||[]).indexOf(l);if(A<0)return{success:!1,error:`Block ${l} not in parent's children`};let n={};if(c===e){let d=[{p:["children",A],action:{ld:l}},{p:["children",t],action:{li:l}}];n[c]={id:c,version:a.version,payload:{ops:d}}}else n[c]={id:c,version:a.version,payload:{ops:[{p:["children",A],action:{ld:l}}]}},n[e]={id:e,version:o.version,payload:{ops:[{p:["children",t],action:{li:l}}]}},n[l]={id:l,version:V.version,payload:{ops:[{p:["parent_id"],action:{od:c,oi:e}}]}};let h=await this._submitChange(n);return h.success?(a.data.children.splice(A,1),c===e?a.data.children.splice(t,0,l):(o.data.children||(o.data.children=[]),o.data.children.splice(t,0,l),V.data.parent_id=e),{success:!0}):h}_removeSubtree(l){let e=this.blockMap[l];if(!e)return;let t=e.data?.children||[];for(let V of t)this._removeSubtree(V);delete this.blockMap[l]}async _submitChange(l){let e=await this.api.submitDocxChange(this.auth,this.origin,this.pageId,this.memberId,l);return e.success&&this._updateState(e.data),e}_updateState(l){if(!l)return;let e=l.block_map||{};for(let[t,V]of Object.entries(e))this.blockMap[t]&&(this.blockMap[t].version=V.version);l.structure_version!==void 0&&(this.structureVersion=l.structure_version)}_assertOpen(){if(!this._opened)throw new Error("DocxEditor not opened. Call open() first.")}static _generateBlockId(){let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=DR.randomBytes(27),t="";for(let V=0;V<27;V++)t+=l[e[V]%l.length];return t}static _generateMemberId(){let l=Date.now(),e=Math.floor(Math.random()*1e3);return String(l)+String(e).padStart(3,"0")}},GV=mV;import et from"node:fs/promises";import ie from"node:path";import{McpServer as HR}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as zR}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as Z}from"zod";var Qo=["OK","THUMBSUP","THANKS","MUSCLE","FINGERHEART","APPLAUSE","FISTBUMP","JIAYI","DONE","SMILE","BLUSH","LAUGH","SMIRK","LOL","FACEPALM","LOVE","WINK","PROUD","WITTY","SMART","SCOWL","THINKING","SOB","CRY","ERROR","NOSEPICK","HAUGHTY","SLAP","SPITBLOOD","TOASTED","GLANCE","DULL","INNOCENTSMILE","JOYFUL","WOW","TRICK","YEAH","ENOUGH","TEARS","EMBARRASSED","KISS","SMOOCH","DROOL","OBSESSED","MONEY","TEASE","SHOWOFF","COMFORT","CLAP","PRAISE","STRIVE","XBLUSH","SILENT","WAVE","WHAT","FROWN","SHY","DIZZY","LOOKDOWN","CHUCKLE","WAIL","CRAZY","WHIMPER","HUG","BLUBBER","WRONGED","HUSKY","SHHH","SMUG","ANGRY","HAMMER","SHOCKED","TERROR","PETRIFIED","SKULL","SWEAT","SPEECHLESS","SLEEP","DROWSY","YAWN","SICK","PUKE","BETRAYED","HEADSET","EatingFood","MeMeMe","Sigh","Typing","Lemon","Get","LGTM","OnIt","OneSecond","VRHeadset","YouAreTheBest","SALUTE","SHAKE","HIGHFIVE","UPPERLEFT","ThumbsDown","SLIGHT","TONGUE","EYESCLOSED","RoarForYou","CALF","BEAR","BULL","RAINBOWPUKE","ROSE","HEART","PARTY","LIPS","BEER","CAKE","GIFT","CUCUMBER","Drumstick","Pepper","CANDIEDHAWS","BubbleTea","Coffee","Yes","No","OKR","CheckMark","CrossMark","MinusOne","Hundred","AWESOMEN","Pin","Alarm","Loudspeaker","Trophy","Fire","BOMB","Music","XmasTree","Snowman","XmasHat","FIREWORKS","2022","REDPACKET","FORTUNE","LUCK","FIRECRACKER","StickyRiceBalls","HEARTBROKEN","POOP","StatusFlashOfInspiration","18X","CLEAVER","Soccer","Basketball","GeneralDoNotDisturb","Status_PrivateMessage","GeneralInMeetingBusy","StatusReading","StatusInFlight","GeneralBusinessTrip","GeneralWorkFromHome","StatusEnjoyLife","GeneralTravellingCar","StatusBus","GeneralSun","GeneralMoonRest","MoonRabbit","Mooncake","JubilantRabbit","TV","Movie","Pumpkin","BeamingFace","Delighted","ColdSweat","FullMoonFace","Partying","GoGoGo","ThanksFace","SaluteFace","Shrug","ClownFace","HappyDragon"];var wR=/^img_v(?:2|3)_[a-z0-9_-]+$/i;function ze(s,l,e,t){return typeof s.registerTool=="function"?s.registerTool(l,e,t):s.tool(l,e.description,e.inputSchema,t)}function je(...s){return s.some(oe)}function we(s){let l;try{l=new URL(s)}catch{return{valid:!1,error:"Invalid URL"}}if(l.username||l.password)return{valid:!1,error:"Webhook URL must not include username or password"};let e=Fe._validateFeishuOrigin(l.origin);return e.valid?/^\/open-apis\/bot\/v2\/hook\/[^/?#]+\/?$/.test(l.pathname)?{valid:!0,url:l.href}:{valid:!1,error:"URL must match /open-apis/bot/v2/hook/<token> path"}:e}function Le({secret:s,timestamp:l,sign:e}){let t={};return s!==void 0&&(t.secret=s),l!==void 0&&(t.timestamp=l),e!==void 0&&(t.sign=e),t}var H=s=>({content:[{type:"text",text:JSON.stringify(s)}]}),Yo=new WeakMap;function LR(s){let l=Yo.get(s);return l||(l=new Map,Yo.set(s,l)),l}async function vR(s,l){let e=LR(s),t=e.get(l);if(t)return t;let V=(async()=>{try{let o=await s.downloadImage(l),c=await ta(l,o);return c?.path?e.set(l,c):e.delete(l),c}catch(o){throw e.delete(l),o}})();return e.set(l,V),V}function PR(s,l){if(!Array.isArray(s)||s.length===0)return s;let e=new Map((l||[]).filter(o=>typeof o?.imageKey=="string"&&typeof o?.path=="string").map(o=>[o.imageKey,o.path])),t=!1,V=s.map(o=>{if(o?.type!=="image_key")return o;let c=typeof o.image_key=="string"?o.image_key:o.image_key?.key,a=e.get(c);return a?(t=!0,{type:"image_path",image_path:{path:a}}):o});return t?V:s}function jR(s){if(!s||typeof s!="object")return s;let{htmlText:l,richText:e,...t}=s;return t}function Jo(s){return!s||typeof s!="object"||!Array.isArray(s.messages)?s:{...s,messages:s.messages.map(jR)}}var WV="/tmp/openbird-downloads",OR={"image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp"};function To(s){return Z.enum(Qo).describe(s)}function _R(s){let l=[];return Array.isArray(s?.imageKeys)&&l.push(...s.imageKeys),s?.imageKey!==void 0&&l.push(s.imageKey),[...new Set(l.map(e=>Ae(String(e??""))).filter(e=>typeof e=="string"&&wR.test(e)))]}function qR(s){let l=[];return Array.isArray(s?.fileKeys)&&l.push(...s.fileKeys),s?.fileKey!==void 0&&l.push(s.fileKey),[...new Set(l.map(e=>Ae(String(e??""))).filter(Boolean))]}function $R(s){if(typeof s!="string"||s.trim()==="")return;let l=ie.basename(s).replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").trim();return l===""||l==="."||l===".."?void 0:l}async function ea(s,l){let e=ie.resolve(s),t=ie.extname(l),V=t?l.slice(0,-t.length):l;for(let o=0;o<1e4;o+=1){let c=o===0?ie.join(e,l):ie.join(e,`${V} (${o})${t}`),a=ie.resolve(c);if(!(a!==c||ie.relative(e,a).startsWith("..")))try{return{handle:await et.open(a,"wx"),path:a}}catch(R){if(R?.code==="EEXIST")continue;throw R}}throw new Error("Could not allocate unique download path")}function ko(s,l){let e=OR[l]||".bin";return $R(`${s}${e}`)||`${s}${e}`}async function la(s,l){let e=ie.join(WV,ko(s,l));try{let t=await et.stat(e);return t.isFile()?{imageKey:s,path:e,...l?{mimeType:l}:{},size:t.size}:null}catch(t){if(t?.code==="ENOENT")return null;throw t}}async function ta(s,l){if(!l?.success||!l.data)return{imageKey:s,error:l?.error||"image download failed"};let e=Buffer.isBuffer(l.data)?l.data:Buffer.from(l.data),t=await la(s,l.mimeType);if(t)return t;let V=ko(s,l.mimeType);await et.mkdir(WV,{recursive:!0});let{handle:o,path:c}=await ea(WV,V),a=!1;try{await o.writeFile(e)}catch(R){throw a=!0,R}finally{await o.close().catch(()=>{}),a&&await et.rm(c,{force:!0}).catch(()=>{})}return{imageKey:s,path:c,...l.mimeType?{mimeType:l.mimeType}:{},size:e.length}}async function Va({api:s,auth:l,message:e,fallbackChatId:t,scene:V}){let o=[],c=[];for(let a of _R(e))try{let R=await vR(s,a);o.push(R)}catch(R){o.push({imageKey:a,error:R?.message||"image download failed"})}for(let a of qR(e)){let R=Ae(String(e?.messageId??"")),A=Ae(String(e?.chatId??""))||t,n=Ae(String(e?.fileName??""));if(!R){c.push({fileKey:a,...n?{fileName:n}:{},error:"messageId is required for file download"});continue}if(!A){c.push({fileKey:a,...n?{fileName:n}:{},error:"chatId is required for file download"});continue}try{let h=await s.downloadFile(l,R,a,{chatId:A,scene:V});if(!h?.success){c.push({fileKey:a,...n?{fileName:n}:{},error:h?.error||"file download failed"});continue}c.push({fileKey:a,...h.fileName||n?{fileName:h.fileName||n}:{},...h.path?{path:h.path}:{},...h.mimeType?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}})}catch(h){c.push({fileKey:a,...n?{fileName:n}:{},error:h?.message||"file download failed"})}}if(o.length>0){let a=PR(e.content,o);if(a!==e.content)return{...e,content:a,localImages:o}}return o.length===0&&c.length===0?e:{...e,...o.length>0?{localImages:o}:{},...c.length>0?{localFiles:c}:{}}}async function yo({api:s,auth:l,result:e,fallbackChatId:t,scene:V}){return!e?.success||!Array.isArray(e.messages)||e.messages.length===0?e:{...e,messages:await Promise.all(e.messages.map(o=>Va({api:s,auth:l,message:o,fallbackChatId:t,scene:V})))}}function Ae(s){if(typeof s!="string")return s;let l=s.trim();return l===""?void 0:l}var Pe=Z.number().int(),K=Z.string().trim().min(1),$l=Z.union([Z.number().safe().int(),K.regex(/^-?\d+$/).transform(s=>Number(s)).refine(Number.isSafeInteger,{message:"Expected a safe integer"})]),lt=Z.union([Pe,K.regex(/^-?\d+$/)]),ve=K.regex(/^-?\d+$/),xo=K.optional(),oa=lt.optional(),ca=Z.string().trim().length(0),Ra={secret:xo.describe("Webhook signature secret; auto-generates timestamp/sign when provided"),timestamp:oa.describe("Explicit signature timestamp"),sign:xo.describe("Explicit webhook signature")};function aa(s,l){let e=s.secret!==void 0,t=s.timestamp!==void 0,V=s.sign!==void 0;if(e&&(t||V)){let o="secret cannot be combined with timestamp/sign options";l.addIssue({code:Z.ZodIssueCode.custom,message:o,path:["secret"]}),t&&l.addIssue({code:Z.ZodIssueCode.custom,message:o,path:["timestamp"]}),V&&l.addIssue({code:Z.ZodIssueCode.custom,message:o,path:["sign"]});return}if(t!==V){let o="timestamp and sign must be provided together";t&&l.addIssue({code:Z.ZodIssueCode.custom,message:o,path:["sign"]}),V&&l.addIssue({code:Z.ZodIssueCode.custom,message:o,path:["timestamp"]})}}function Oe(s,l={}){return Z.object({...s,...Ra}).superRefine((e,t)=>{if(aa(e,t),!l.rejectPayloadSignatureMix)return;let V=e.payload;if(!V||typeof V!="object")return;let o=V.timestamp!==void 0,c=V.sign!==void 0,a=e.secret!==void 0||e.timestamp!==void 0||e.sign!==void 0;(o||c)&&a&&t.addIssue({code:Z.ZodIssueCode.custom,message:"payload timestamp/sign cannot be combined with signature options",path:["payload"]})})}var Aa=Oe({webhook_url:K.describe("Webhook bot URL"),text:K.describe("Text message content")}),sa=Oe({webhook_url:K.describe("Webhook bot URL"),post:Z.object({}).passthrough().describe("Raw Feishu post object")}),na=Oe({webhook_url:K.describe("Webhook bot URL"),image_key:K.describe("Existing image key to send")}),ha=Oe({webhook_url:K.describe("Webhook bot URL"),share_chat_id:K.describe("Chat ID to share")}),da=Oe({webhook_url:K.describe("Webhook bot URL"),card:Z.object({}).passthrough().describe("Raw Feishu interactive card JSON")}),Za=Oe({webhook_url:K.describe("Webhook bot URL"),payload:Z.object({}).passthrough().describe("Raw webhook bot payload")},{rejectPayloadSignatureMix:!0});function Se(s){return Z.union([s,ca]).optional()}function ga(s,l){return`aliases: ${[...s].sort().join(", ")}; numeric values: ${[...l].sort((e,t)=>e-t).join(", ")}`}function ue(s,l){let e=So(s),t=Xo(s),V=new Set(e),o=new Set(t),c=`${l} must be one of ${ga(V,o)}`;return Z.union([Pe.refine(a=>o.has(a),{message:c}),K.transform(a=>a.toLowerCase()).refine(a=>V.has(a)?!0:/^-?\d+$/.test(a)?o.has(Number(a)):!1,{message:c})])}var Ea=Se(ue(Zl,"visibility")),Fa=Se(ue(gl,"status")),Sa=Se(ue(dl,"notification_type")),Xa=Se(ue(Fl,"locations[].type")),Ua=ue(El,"reminders[].method"),ra={chat:1,thread:2,message_thread:3},ma=Se(ue(ra,"from")),Ga=Se(ue(q,"attendees[].category")),Wa=Se(ue(Sl,"attendees[].status")),ia=Se(lt);function fo(s){if(typeof s=="number")return{1:"user",2:"group",3:"resource",4:"third_party_user"}[s];if(!oe(s))return;let l=s.trim().toLowerCase();return/^-?\d+$/.test(l)?fo(Number(l)):l}function ua(s){if(!s||typeof s!="object")return"user";let l=fo(s.category);return l||(je(s.group_id,s.groupId)?"group":oe(s.email)?"email":je(s.user_id,s.userId)?"user":je(s.attendee_calendar_id,s.attendeeCalendarId)?"resource":"user")}var ba=Z.object({category:Ga,attendee_calendar_id:Z.string().optional(),attendeeCalendarId:Z.string().optional(),status:Wa,is_optional:Z.boolean().optional(),isOptional:Z.boolean().optional(),user_id:Z.string().optional(),userId:Z.string().optional(),group_id:Z.string().optional(),groupId:Z.string().optional(),email:Z.string().optional()}).passthrough().superRefine((s,l)=>{let e=ua(s);(e==="user"||e==="")&&!je(s.user_id,s.userId)&&l.addIssue({code:Z.ZodIssueCode.custom,message:"attendees[].user_id or attendees[].userId is required for user attendees",path:["user_id"]}),e==="group"&&!je(s.group_id,s.groupId)&&l.addIssue({code:Z.ZodIssueCode.custom,message:"attendees[].group_id or attendees[].groupId is required for group attendees",path:["group_id"]}),(e==="email"||e==="third_party_user"||e==="thirdpartyuser")&&!oe(s.email)&&l.addIssue({code:Z.ZodIssueCode.custom,message:"attendees[].email is required for email attendees",path:["email"]}),e==="resource"&&!je(s.attendee_calendar_id,s.attendeeCalendarId)&&l.addIssue({code:Z.ZodIssueCode.custom,message:"attendees[].attendee_calendar_id or attendees[].attendeeCalendarId is required for resource attendees",path:["attendee_calendar_id"]})});async function Ko(s,l,e){let t=new HR({name:"openbird",version:"1.0.0"});t.tool("send_message","Send a message to a Feishu chat (supports Markdown)",{chat_id:Z.string().describe("Chat ID to send the message to"),text:Z.string().describe("Message text (plain or Markdown)")},async({chat_id:R,text:A})=>{let n=await s.sendMessage(l,A,R);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("send_mention_message","Send a message with @mentions to a Feishu chat",{chat_id:Z.string().describe("Chat ID to send the message to"),text:Z.string().describe('Message text with @displayName patterns (e.g., "Hello @\u8D75\u5929\u96C4")'),mentions:Z.array(Z.object({user_id:Z.string().describe("User ID to mention"),display_name:Z.string().describe("Display name matching @pattern in text")})).describe("List of mention targets")},async({chat_id:R,text:A,mentions:n})=>{let h=n.map(g=>({userId:g.user_id,displayName:g.display_name})),d=await s.sendMentionMessage(l,A,R,h);return{content:[{type:"text",text:JSON.stringify(d)}]}}),t.tool("send_reply","Reply to a specific message in a Feishu chat",{chat_id:Z.string().describe("Chat ID"),text:Z.string().describe("Reply text (plain or Markdown)"),root_id:Z.string().describe("Root message ID of the thread"),parent_id:Z.string().describe("Message ID being replied to")},async({chat_id:R,text:A,root_id:n,parent_id:h})=>{let d=await s.sendReply(l,A,R,{rootId:n,parentId:h});return{content:[{type:"text",text:JSON.stringify(d)}]}}),t.tool("add_reaction","Add an emoji reaction to a message",{message_id:Z.string().describe("Message ID to react to"),emoji_type:To("Emoji type (e.g., THUMBSUP, SMILE, HEART)")},async({message_id:R,emoji_type:A})=>{let n=await s.addEmojiReaction(l,R,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("remove_reaction","Remove an emoji reaction from a message",{message_id:Z.string().describe("Message ID to remove reaction from"),emoji_type:To("Emoji type to remove")},async({message_id:R,emoji_type:A})=>{let n=await s.removeEmojiReaction(l,R,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("get_chat_history","Get chat message history",{chat_id:Z.string().describe("Chat ID"),start_position:$l.optional().describe("Cursor position; fetches messages after this position"),count:$l.optional().describe("Number of messages to fetch (default: 20)"),download_media:Z.boolean().optional().default(!1).describe("Automatically download image/file attachments and include local temp paths")},async({chat_id:R,start_position:A,count:n,download_media:h=!1})=>{let d={};A!==void 0&&(d.startPosition=A),n!==void 0&&(d.count=n);let g=await s.getChatHistory(l,R,d),E=Jo(g);if(h&&(E=await yo({api:s,auth:l,result:E,fallbackChatId:R,scene:"chat"})),E.success&&E.messages?.length>0){let X=new Map;for(let r of E.messages)for(let m of r.baikeAnnotations||[])m.entityId&&!X.has(m.entityId)&&X.set(m.entityId,m);X.size>0&&(E.glossaryTerms=[...X.values()])}return H(E)}),t.tool("get_chat_meta","Get chat metadata (last message position, read position, etc.)",{chat_id:Z.string().describe("Chat ID")},async({chat_id:R})=>{let A=await s.getChatMeta(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("create_chat","Create a P2P chat with a user",{user_id:Z.string().describe("User ID to create chat with")},async({user_id:R})=>{let A=await s.createChat(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("create_group","Create a group chat",{name:Z.string().describe("Group name"),description:Z.string().optional().describe("Group description"),member_ids:Z.array(Z.string()).optional().describe("Member user IDs to add"),chat_mode:Z.number().optional().describe("Chat mode: 1=DEFAULT, 2=THREAD, 3=THREAD_V2"),icon_key:Z.string().optional().describe("Group icon key")},async({name:R,description:A,member_ids:n,chat_mode:h,icon_key:d})=>{let g=await s.createGroup(l,{name:R,description:A,memberIds:n,chatMode:h,iconKey:d});return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("patch_group_chat","Update group chat info (name, description, or icon)",{chat_id:Z.string().describe("Chat ID of the group to update"),name:Z.string().optional().describe("New group name"),description:Z.string().optional().describe("New group description"),icon_key:Z.string().optional().describe("New group icon key")},async({chat_id:R,name:A,description:n,icon_key:h})=>{let d={};A!==void 0&&(d.name=A),n!==void 0&&(d.description=n),h!==void 0&&(d.iconKey=h);let g=await s.patchGroupChat(l,R,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("search","Search for users and groups in Feishu",{query:Z.string().describe("Search query")},async({query:R})=>{let A=await s.searchSome(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_user_info","Get user info by user ID (works for both users and bots)",{user_id:Z.string().describe("User ID to look up")},async({user_id:R})=>{let A=await s.getUserInfoById(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_user_by_id","Get user profile by user ID (cmd=5031, includes alias and memoText when available)",{user_id:Z.string().describe("User ID to look up")},async({user_id:R})=>{let A=await s.getUserById(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("create_webhook_bot","Create a webhook bot in a Feishu chat",{chat_id:K.describe("Chat ID to create the webhook bot in"),name:K.describe("Webhook bot name"),description:K.describe("Webhook bot description"),i18n:Z.string().default("zh_CN").describe("Locale string (default: zh_CN)"),avatar_key:Z.string().optional().describe("Optional avatar key"),avatar_type:Z.number().int().optional().describe("Optional avatar type"),user_id:Z.string().optional().describe("Creator user ID (defaults to current MCP session user)")},async({chat_id:R,name:A,description:n,i18n:h,avatar_key:d,avatar_type:g,user_id:E})=>{let X={userId:E||e,i18n:h};d!==void 0&&(X.avatarKey=d),g!==void 0&&(X.avatarType=g);let r=await s.createWebhookBot(l,R,A,n,X);return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("get_webhook_bot_info","Get webhook bot details including its webhook URL and signature settings",{bot_id:K.describe("Webhook bot ID"),i18n:Z.string().default("zh_CN").describe("Locale string (default: zh_CN)")},async({bot_id:R,i18n:A})=>{let n=await s.getWebhookBotInfo(l,R,{i18n:A});return{content:[{type:"text",text:JSON.stringify(n)}]}}),ze(t,"send_webhook_bot_text",{description:"Send a text message to a webhook bot URL",inputSchema:Aa},async({webhook_url:R,text:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotText(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),ze(t,"send_webhook_bot_post",{description:"Send a post message to a webhook bot URL",inputSchema:sa},async({webhook_url:R,post:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotPost(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),ze(t,"send_webhook_bot_image",{description:"Send an image message to a webhook bot URL using an existing image_key",inputSchema:na},async({webhook_url:R,image_key:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotImage(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),ze(t,"send_webhook_bot_share_chat",{description:"Send a share_chat message to a webhook bot URL",inputSchema:ha},async({webhook_url:R,share_chat_id:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotShareChat(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),ze(t,"send_webhook_bot_card",{description:"Send an interactive card message to a webhook bot URL",inputSchema:da},async({webhook_url:R,card:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotCard(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),ze(t,"send_webhook_bot_message",{description:"Send a raw webhook bot payload to a webhook bot URL",inputSchema:Za},async({webhook_url:R,payload:A,secret:n,timestamp:h,sign:d})=>{let g=we(R);if(!g.valid)return H({success:!1,error:g.error});let E=await s.sendWebhookBotMessage(g.url,A,Le({secret:n,timestamp:h,sign:d}));return H(E)}),t.tool("get_user_profile_card","Get user profile card (description, display name, avatar)",{user_id:Z.string().describe("User ID to get profile card for")},async({user_id:R})=>{let A=await s.getUserProfileCard(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("set_user_signature","Set the current user profile signature",{description:Z.string().describe("Signature text"),description_flag:Z.number().optional().describe("Signature flag (default: 0)")},async({description:R,description_flag:A})=>{let n={};A!==void 0&&(n.descriptionFlag=A);let h=await s.setUserSignature(l,R,n);return{content:[{type:"text",text:JSON.stringify(h)}]}}),t.tool("get_calendar_events","Get calendar events for a user",{user_id:Z.string().optional().describe("User ID (defaults to current user)")},async({user_id:R})=>{let A=R||e,n=await s.getCalendarEvents(l,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("mget_events_with_ids","Batch-fetch calendar events by their event keys. Returns full event details including title, time, location, attendees, recurrence rules.",{event_keys:Z.array(Z.string()).min(1).describe("Event keys to fetch")},async({event_keys:R})=>{let A=await s.webMgetEventsWithIds(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_place_tips","Search place and location autocomplete tips for calendar event locations",{keyword:Z.string().describe("Place search keyword"),locale:Z.string().optional().describe("Locale code (default: zh_CN)")},async({keyword:R,locale:A})=>{let n={};A!==void 0&&(n.locale=A);let h=await s.getPlaceTips(l,R,n);return{content:[{type:"text",text:JSON.stringify(h)}]}}),t.tool("create_calendar_event","Create a calendar event with title, time, location, reminders, and optional attendees",{calendar_id:K.describe("Target calendar ID"),summary:K.describe("Event title"),start_time:Pe.describe("Start time as Unix timestamp"),end_time:Pe.describe("End time as Unix timestamp"),timezone:Z.string().optional().describe("Shared timezone for start/end, e.g. Asia/Shanghai"),start_timezone:Z.string().optional().describe("Start timezone override"),end_timezone:Z.string().optional().describe("End timezone override"),description:Z.string().optional().describe("Plain-text description"),docs_description:Z.string().optional().describe("Docs description"),rrule:Z.string().optional().describe("Recurrence rule"),is_all_day:Z.boolean().optional().describe("Whether the event lasts all day"),is_free:Z.boolean().optional().describe("Whether the event should not block busy status"),visibility:Ea.describe("Visibility enum or alias (default/public/private)"),status:Fa.describe("Status enum or alias (confirmed/tentative/cancelled)"),notification_type:Sa.describe("Notification type enum or alias"),unique_key:Z.string().optional().describe("Optional unique event key"),original_time:ia.describe("Original event timestamp"),locations:Z.array(Z.object({name:Z.string().optional(),address:Z.string().optional(),type:Xa,latitude:Z.number().optional(),longitude:Z.number().optional()})).optional().describe("Event locations"),reminders:Z.array(Z.object({minutes:Pe,method:Ua,calendar_event_id:Z.string().optional(),calendarEventId:Z.string().optional()})).optional().describe("Event reminders"),attendees:Z.array(ba).optional().describe("Attendees to add on create")},async({calendar_id:R,summary:A,start_time:n,end_time:h,timezone:d,start_timezone:g,end_timezone:E,description:X,docs_description:r,rrule:m,is_all_day:W,is_free:u,visibility:I,status:N,notification_type:Y,unique_key:T,original_time:z,locations:le,reminders:_e,attendees:qe})=>{let M={summary:A,startTime:n,endTime:h},$e={},el=Ae(d);el!==void 0&&(M.timezone=el);let ll=Ae(g);ll!==void 0&&(M.startTimezone=ll);let be=Ae(E);be!==void 0&&(M.endTimezone=be),X!==void 0&&(M.description=X),r!==void 0&&(M.docsDescription=r),m!==void 0&&(M.rrule=m),W!==void 0&&(M.isAllDay=W),u!==void 0&&(M.isFree=u),I!==void 0&&(M.visibility=I),N!==void 0&&(M.status=N);let il=Ae(T);il!==void 0&&(M.uniqueKey=il),z!==void 0&&(M.originalTime=z),le!==void 0&&(M.locations=le),_e!==void 0&&(M.reminders=_e.map(Xe=>{let iV=Ae(Xe.calendar_event_id??Xe.calendarEventId);return{minutes:Xe.minutes,method:Xe.method,...iV!==void 0?{calendarEventId:iV}:{}}})),qe!==void 0&&(M.attendees=qe),Y!==void 0&&($e.notificationType=Y);let Vt=await s.createCalendarEvent(l,R,M,$e);return{content:[{type:"text",text:JSON.stringify(Vt)}]}}),t.tool("calendar_rsvp","RSVP to a calendar event (accept/decline/tentative)",{event_id:Z.string().describe("Calendar event ID"),rsvp_status:Z.string().describe("RSVP status: accept, decline, or tentative")},async({event_id:R,rsvp_status:A})=>{let n=await s.calendarRsvp(l,R,e,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("reply_calendar_event_invitation","Reply to a calendar event invitation with protobuf fields and optional RSVP comment",{unique_key:Z.string().describe("Calendar event unique key"),calendar_id:Z.string().describe("Calendar ID"),original_time:Z.number().describe("Original event timestamp"),reply_type:Z.string().describe("Reply type: accept, decline, tentative, delete, or needs_action"),quit_meeting:Z.boolean().optional().describe("Leave linked meeting after replying"),needs_brief_events:Z.boolean().optional().describe("Request brief event data in the response"),use_attendee_page_token:Z.boolean().optional().describe("Use attendee page token"),reply_comment_id:Z.string().optional().describe("Reply comment ID"),comment:Z.string().optional().describe("RSVP comment text"),invite_operator_id:Z.string().optional().describe("Invite operator ID")},async({unique_key:R,calendar_id:A,original_time:n,reply_type:h,quit_meeting:d,needs_brief_events:g,use_attendee_page_token:E,reply_comment_id:X,comment:r,invite_operator_id:m})=>{let W={};d!==void 0&&(W.quitMeeting=d),g!==void 0&&(W.needsBriefEvents=g),E!==void 0&&(W.useAttendeePageToken=E),(X!==void 0||r!==void 0||m!==void 0)&&(W.rsvpCommentInfo={...X!==void 0?{replyCommentId:X}:{},...r!==void 0?{comment:r}:{},...m!==void 0?{inviteOperatorId:m}:{}});let u=await s.replyCalendarEventInvitation(l,{uniqueKey:R,calendarId:A,originalTime:n},h,W);return{content:[{type:"text",text:JSON.stringify(u)}]}}),t.tool("delete_calendar_event","Delete a calendar event",{calendar_id:Z.string().describe("Calendar ID"),event_id:Z.string().describe("Calendar event ID"),delete_type:Z.number().optional().describe("Delete mode (default: 0 = this event only)"),need_notification:Z.boolean().optional().describe("Notify attendees (default: true)")},async({calendar_id:R,event_id:A,delete_type:n,need_notification:h})=>{let d={};n!==void 0&&(d.deleteType=n),h!==void 0&&(d.needNotification=h);let g=await s.deleteCalendarEvent(l,R,A,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("update_calendar_event","Update an existing calendar event",{event_id:Z.string().describe("Calendar event ID"),calendar_id:Z.string().optional().describe("Calendar ID"),key:Z.string().optional().describe("Event key, if known"),summary:Z.string().optional().describe("Updated event title"),description:Z.string().optional().describe("Updated plain-text description"),docs_description:Z.string().optional().describe("Updated docs description"),start_time:Z.number().optional().describe("Updated start time as Unix timestamp"),end_time:Z.number().optional().describe("Updated end time as Unix timestamp"),start_timezone:Z.string().optional().describe("Start timezone, e.g. Asia/Shanghai"),end_timezone:Z.string().optional().describe("End timezone, e.g. Asia/Shanghai"),is_all_day:Z.boolean().optional().describe("Whether the event is all-day"),is_free:Z.boolean().optional().describe("Whether the event blocks busy time"),visibility:Z.number().optional().describe("Visibility enum value"),status:Z.number().optional().describe("Status enum value"),rrule:Z.string().optional().describe("Recurrence rule"),version:Z.union([Z.number(),Z.string()]).optional().describe("Event version; defaults to current microsecond timestamp"),create_time:Z.union([Z.number(),Z.string()]).optional().describe("Original create timestamp"),update_time:Z.union([Z.number(),Z.string()]).optional().describe("Updated modify timestamp"),locations:Z.array(Z.object({name:Z.string().optional(),address:Z.string().optional(),type:Z.number().optional(),latitude:Z.number().optional(),longitude:Z.number().optional()})).optional().describe("Updated event locations"),reminders:Z.array(Z.object({calendar_event_id:Z.string().optional(),minutes:Z.number(),method:Z.number()})).optional().describe("Updated reminders"),attendees:Z.array(Z.object({}).passthrough()).optional().describe("Updated attendee objects in raw WebCalendarEventAttendee shape"),span:Z.number().min(0).max(1).optional().describe("Recurring update scope: 0=NONE_SPAN, 1=THIS_EVENT"),instance_start_time:Z.union([Z.number(),Z.string()]).optional().describe("Specific recurring instance timestamp"),notification_type:Z.number().optional().describe("Notification type enum value")},async({event_id:R,calendar_id:A,key:n,summary:h,description:d,docs_description:g,start_time:E,end_time:X,start_timezone:r,end_timezone:m,is_all_day:W,is_free:u,visibility:I,status:N,rrule:Y,version:T,create_time:z,update_time:le,locations:_e,reminders:qe,attendees:M,span:$e,instance_start_time:el,notification_type:ll})=>{let be={};$e!==void 0&&(be.span=$e),el!==void 0&&(be.instanceStartTime=el),ll!==void 0&&(be.notificationType=ll);let il={...A!==void 0?{calendarId:A}:{},...n!==void 0?{key:n}:{},...h!==void 0?{summary:h}:{},...d!==void 0?{description:d}:{},...g!==void 0?{docsDescription:g}:{},...E!==void 0?{startTime:E}:{},...X!==void 0?{endTime:X}:{},...r!==void 0?{startTimezone:r}:{},...m!==void 0?{endTimezone:m}:{},...W!==void 0?{isAllDay:W}:{},...u!==void 0?{isFree:u}:{},...I!==void 0?{visibility:I}:{},...N!==void 0?{status:N}:{},...Y!==void 0?{rrule:Y}:{},...T!==void 0?{version:T}:{},...z!==void 0?{createTime:z}:{},...le!==void 0?{updateTime:le}:{},..._e!==void 0?{locations:_e}:{},...qe!==void 0?{reminders:qe.map(Xe=>({...Xe,...Xe.calendar_event_id!==void 0?{calendarEventId:Xe.calendar_event_id}:{}}))}:{},...M!==void 0?{attendees:M}:{}},Vt=await s.updateCalendarEvent(l,R,il,be);return{content:[{type:"text",text:JSON.stringify(Vt)}]}}),t.tool("web_list_calendar_events","List calendar events within a time range for a calendar",{calendar_id:Z.string().describe("Calendar ID"),start_time:Z.number().describe("Start time as Unix timestamp in seconds"),end_time:Z.number().describe("End time as Unix timestamp in seconds"),limit:Z.number().optional().describe("Maximum number of events to return (default: 100)")},async({calendar_id:R,start_time:A,end_time:n,limit:h})=>{let d={};h!==void 0&&(d.limit=h);let g=await s.webListCalendarEvents(l,R,A,n,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("create_meeting_minute","Create a meeting minute (notes document) for a calendar event, returns a Feishu doc URL",{calendar_id:Z.string().describe("Calendar ID"),event_key:Z.string().describe("Calendar event key (from CalendarEvent.key, distinct from event ID)"),original_time:Z.number().optional().describe("Original event timestamp (default: 0)")},async({calendar_id:R,event_key:A,original_time:n})=>{let h={};n!==void 0&&(h.originalTime=n);let d=await s.createMeetingMinute(l,R,A,h);return{content:[{type:"text",text:JSON.stringify(d)}]}}),t.tool("transfer_calendar_event","Transfer ownership of a calendar event to another user",{calendar_id:Z.string().describe("Calendar ID / owner UID"),event_key:Z.string().describe("Calendar event key (from CalendarEvent.key, distinct from event ID)"),target_user_hash:Z.number().int().describe("Target user hash captured from the transfer flow"),original_time:Z.number().optional().describe("Original event timestamp (default: 0)"),transfer_flag:Z.number().int().optional().describe("Captured transfer flag (default: 1)")},async({calendar_id:R,event_key:A,target_user_hash:n,original_time:h,transfer_flag:d})=>{let g={};h!==void 0&&(g.originalTime=h),d!==void 0&&(g.transferFlag=d);let E=await s.transferCalendarEvent(l,R,A,n,g);return{content:[{type:"text",text:JSON.stringify(E)}]}}),t.tool("web_share_calendar_event","Share a calendar event to one or more chats",{chat_ids:Z.array(Z.number().safe().int().nonnegative()).nonempty().describe("Chat IDs to share the event with"),calendar_id:Z.string().describe("Calendar ID"),event_key:Z.string().describe("Calendar event key"),original_time:Z.number().safe().int().nonnegative().optional().describe("Original event timestamp (default: 0, non-recurring)")},async({chat_ids:R,calendar_id:A,event_key:n,original_time:h})=>{let d={};h!==void 0&&(d.originalTime=h);let g=await s.webShareCalendarEvent(l,R,A,n,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("upgrade_to_meeting","Upgrade a calendar event into a video meeting (creates a meeting chat group)",{event_id:Z.string().describe("Calendar event ID (CalendarEvent.id)"),uid:Z.string().describe("Event UID"),calendar_id:Z.string().describe("Calendar ID"),creator_id:Z.string().optional().describe("Creator calendar ID"),organizer_id:Z.string().optional().describe("Organizer calendar ID"),start_time:Z.number().describe("Start time (Unix timestamp in seconds)"),start_timezone:Z.string().describe('Start timezone (e.g. "Asia/Shanghai")'),end_time:Z.number().describe("End time (Unix timestamp in seconds)"),end_timezone:Z.string().optional().describe('End timezone (e.g. "Asia/Shanghai")'),summary:Z.string().describe("Event summary/title"),original_time:Z.number().optional().describe("Original event timestamp (default: 0)"),rrule:Z.string().optional().describe('Recurrence rule (e.g. "FREQ=DAILY;UNTIL=20280305T155959Z;INTERVAL=3")')},async({event_id:R,uid:A,calendar_id:n,creator_id:h,organizer_id:d,start_time:g,start_timezone:E,end_time:X,end_timezone:r,summary:m,original_time:W,rrule:u})=>{let I={eventId:R,uid:A,calendarId:n,startTime:g,startTimezone:E,endTime:X,summary:m};h!==void 0&&(I.creatorId=h),d!==void 0&&(I.organizerId=d),r!==void 0&&(I.endTimezone=r);let N={};W!==void 0&&(N.originalTime=W),u!==void 0&&(N.rrule=u);let Y=await s.upgradeToMeeting(l,I,N);return{content:[{type:"text",text:JSON.stringify(Y)}]}}),t.tool("download_image","Download an image by its image key, returns base64-encoded data",{image_key:Z.string().describe("Image key (e.g., img_v3_02uc_...)"),size:Z.string().optional().describe("Image size: ORIGIN, MIDDLE_WEBP, or SMALL_WEBP (default: ORIGIN)")},async({image_key:R,size:A})=>{let n={};A&&(n.size=A);let h=await s.downloadImage(R,n);return h.success?{content:[{type:"text",text:JSON.stringify({success:!0,mimeType:h.mimeType,size:h.data.length})},{type:"image",data:h.base64,mimeType:h.mimeType}]}:{content:[{type:"text",text:JSON.stringify(h)}]}}),t.tool("download_file","Download a message attachment to a local temp file and return metadata including path",{message_id:Z.string().describe("Message ID containing the file"),file_key:Z.string().describe("File key from the message content"),chat_id:Z.string().describe("Chat ID where the file message belongs"),scene:Z.string().default("chat").describe("Download scene (default: chat)")},async({message_id:R,file_key:A,chat_id:n,scene:h})=>{let d=await s.downloadFile(l,R,A,{chatId:n,scene:h});return{content:[{type:"text",text:JSON.stringify(d)}]}}),t.tool("mark_chat_read","Mark a chat as read up to a specific position",{encrypted_chat_id:Z.string().describe("Encrypted chat ID string"),read_position:Z.number().describe("Read position timestamp")},async({encrypted_chat_id:R,read_position:A})=>{let n=await s.markChatRead(l,R,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("pin_session","Pin a chat session (stick to top of feed)",{chat_id:Z.string().describe("Chat ID to pin")},async({chat_id:R})=>{let A=await s.pinSession(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("unpin_session","Unpin a chat session",{chat_id:Z.string().describe("Chat ID to unpin")},async({chat_id:R})=>{let A=await s.unpinSession(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("pin_message","Pin a message inside a chat",{chat_id:ve.describe("Chat ID containing the message"),message_id:ve.describe("Message ID to pin")},async({chat_id:R,message_id:A})=>{let n=await s.pinMessage(l,R,A);return H(n)}),t.tool("list_chat_pins","List pinned messages in a chat",{chat_id:ve.describe("Chat ID to list pins for"),cursor:Se(ve).describe("Optional pagination cursor"),count:Pe.optional().describe("Optional page size"),with_messages:Z.boolean().optional().describe("Whether to include pinned message payloads")},async({chat_id:R,cursor:A,count:n,with_messages:h})=>{let d={};A!==void 0&&(d.cursor=A),n!==void 0&&(d.count=n),h!==void 0&&(d.withMessages=h);let g=await s.pullChatPins(l,R,d);return H(g)}),t.tool("unpin_message","Unpin a pinned message from a chat",{chat_id:ve.describe("Chat ID containing the pin"),pin_id:ve.describe("Pin ID to delete")},async({chat_id:R,pin_id:A})=>{let n=await s.unpinMessage(l,R,A);return H(n)}),t.tool("mark_session","Mark a session as important (flag)",{user_hash_id:Z.number().describe("User hash ID (numeric)")},async({user_hash_id:R})=>{let A=await s.markSession(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("unmark_session","Remove mark/flag from a session",{user_hash_id:Z.number().describe("User hash ID (numeric)")},async({user_hash_id:R})=>{let A=await s.unmarkSession(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_user_relation","Query relationship between current user and target user",{user_hash_id:Z.number().describe("Target user hash ID")},async({user_hash_id:R})=>{let A=await s.getUserRelation(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_user_presence","Get user online/presence status",{user_id:Z.string().describe("User ID to check presence for")},async({user_id:R})=>{let A=await s.getUserPresence(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_config","Get a Feishu configuration item value",{config_name:Z.string().describe("Config item name (e.g., PROFILE_NAME_DISPLAY_TYPE)")},async({config_name:R})=>{let A=await s.getConfig(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_feature_flags","Get feature flags / capabilities list",{sync_token:Z.string().optional().describe("Sync token from previous response for incremental updates")},async({sync_token:R})=>{let A={};R&&(A.syncToken=R);let n=await s.getFeatureFlags(l,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("save_contact_alias","Save contact alias name and/or memo for a user",{user_id:Z.string().describe("Target user ID"),alias:Z.string().optional().describe("Alias name for the contact"),memo:Z.string().optional().describe("Memo/note text"),memo_image_key:Z.string().optional().describe("Image key for memo image")},async({user_id:R,alias:A,memo:n,memo_image_key:h})=>{let d={};A!==void 0&&(d.alias=A),n!==void 0&&(d.memo=n),h!==void 0&&(d.memoImageKey=h);let g=await s.saveContactAlias(l,R,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("sync_contact_info","Sync contact info after updating contact aliases (cmd=1100319)",{user_id:Z.string().describe("Target user ID to sync contact info for")},async({user_id:R})=>{let A=await s.syncContactInfo(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("create_thread","Create a thread from a message",{message_id:Z.string().describe("Message ID to create thread from")},async({message_id:R})=>{let A=await s.createThread(l,R);return{content:[{type:"text",text:JSON.stringify(A)}]}}),t.tool("get_thread_messages","Get messages from a thread (topic reply chain)",{thread_id:Z.string().describe("Thread ID"),start_position:$l.optional().describe("Start position (fetches backwards, default: 50)"),count:$l.optional().describe("Number of messages to fetch (default: 50)"),download_media:Z.boolean().optional().default(!1).describe("Automatically download image/file attachments and include local temp paths")},async({thread_id:R,start_position:A,count:n,download_media:h=!1})=>{let d={};A!==void 0&&(d.startPosition=A),n!==void 0&&(d.count=n);let g=await s.getThreadMessages(l,R,d),E=Jo(g);if(h&&(E=await yo({api:s,auth:l,result:E,scene:"chat"})),E.success&&E.messages?.length>0){let X=new Map;for(let r of E.messages)for(let m of r.baikeAnnotations||[])m.entityId&&!X.has(m.entityId)&&X.set(m.entityId,m);X.size>0&&(E.glossaryTerms=[...X.values()])}return H(E)}),t.tool("put_message_link","Create a Feishu message link for a chat, thread, or message thread",{from_id:lt.describe("Source entity ID: chat ID, thread ID, or message-thread ID"),from:ma.describe("Source type: chat, thread, or message_thread (default: chat)"),copied_ids:Z.array(lt).optional().describe("Message IDs to include in the link")},async({from_id:R,from:A,copied_ids:n})=>{let h={};A!==void 0&&Ae(String(A))!==void 0&&(h.from=A),n!==void 0&&(h.copiedIds=n);let d=await s.putMessageLink(l,R,h);return H(d)}),t.tool("get_message_link_permission","Query preview permission for a Feishu message link token",{token:K.describe("Message link token")},async({token:R})=>{let A=await s.getMessageLinkPermission(l,R);return H(A)}),t.tool("search_in_chat","Search for messages within a specific chat",{query:Z.string().describe("Search query"),chat_id:Z.string().describe("Chat ID to search within"),page_size:Z.number().optional().describe("Results per page (default: 5)")},async({query:R,chat_id:A,page_size:n})=>{let h={};n!==void 0&&(h.pageSize=n);let d=await s.searchInChat(l,R,A,h);return{content:[{type:"text",text:JSON.stringify(d)}]}}),t.tool("send_urgent","Send an urgent notification (\u52A0\u6025) for a message to a user",{chat_id:Z.string().describe("Chat ID containing the message"),message_id:Z.string().describe("Message ID to mark urgent"),target_user_id:Z.string().describe("User ID to send urgent to"),urgent_type:Z.number().min(1).max(3).optional().describe("Urgent type: 1=APP (default), 2=SMS, 3=PHONE")},async({chat_id:R,message_id:A,target_user_id:n,urgent_type:h})=>{let d={};h!==void 0&&(d.urgentType=h);let g=await s.putUrgent(l,R,A,n,e,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("get_urgent_ack_status","Query urgent notification acknowledgment status",{chat_id:Z.string().describe("Chat ID"),message_id:Z.string().describe("Message ID that was marked urgent"),target_user_id:Z.string().describe("User ID the urgent was sent to"),urgent_ack_id:Z.string().optional().describe("Urgent ack ID (if known)"),urgent_type:Z.number().min(1).max(3).optional().describe("Urgent type: 1=APP (default), 2=SMS, 3=PHONE")},async({chat_id:R,message_id:A,target_user_id:n,urgent_ack_id:h,urgent_type:d})=>{let g={messageId:A,targetUserId:n};h&&(g.urgentAckId=h),d!==void 0&&(g.urgentType=d);let E=await s.pullUrgentAckStatus(l,R,g);return{content:[{type:"text",text:JSON.stringify(E)}]}}),t.tool("put_schedule_message","Create a scheduled message to be sent at a future time",{text:Z.string().describe("Message content (supports Markdown)"),chat_id:Z.string().describe("Chat ID to send the message to"),schedule_time:Z.number().describe("Scheduled send time as Unix timestamp in milliseconds"),entity_id:Z.string().optional().describe("Thread ID or chat ID (defaults to chat_id)")},async({text:R,chat_id:A,schedule_time:n,entity_id:h})=>{let d={};h!==void 0&&(d.entityId=h);let g=await s.putScheduleMessage(l,R,A,n,d);return{content:[{type:"text",text:JSON.stringify(g)}]}}),t.tool("patch_schedule_message","Update, suspend, delete, or immediately send a scheduled message",{chat_id:Z.string().describe("Chat ID"),message_id:Z.string().describe("Schedule message ID"),patch_type:Z.number().min(1).max(3).describe("Operation type: 1=UPDATE, 2=SUSPEND, 3=DELETE"),schedule_time:Z.number().optional().describe("New scheduled time in milliseconds (for UPDATE)"),content:Z.string().optional().describe("New message content text (for UPDATE)"),send_immediately:Z.boolean().optional().describe("Send the message immediately (for UPDATE)")},async({chat_id:R,message_id:A,patch_type:n,schedule_time:h,content:d,send_immediately:g})=>{let E={};h!==void 0&&(E.scheduleTime=h),d!==void 0&&(E.content=d),g!==void 0&&(E.sendImmediately=g);let X=await s.patchScheduleMessage(l,R,A,n,E);return{content:[{type:"text",text:JSON.stringify(X)}]}}),t.tool("pull_schedule_message_by_ids","Pull specific scheduled messages by their IDs",{chat_id:Z.string().describe("Chat ID"),message_ids:Z.array(Z.string()).describe("Schedule message IDs to retrieve")},async({chat_id:R,message_ids:A})=>{let n=await s.pullScheduleMessageByIds(l,R,A);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("get_baike_card","Get a Feishu Lingo (\u98DE\u4E66\u8BCD\u5178) glossary card for a term, including its definition, full name, contributors, and detail URL",{entity_id:Z.string().describe('Baike entity ID (e.g. "enterprise_7613780366768819403")'),text:Z.string().describe('Term text (e.g. "\u8868\u60C5\u56DE\u590D")'),entity_type:Z.number().optional().describe("Entity type: 1=enterprise (default), 0=public"),chat_id:Z.string().optional().describe("Chat ID where term was found (for context)"),message_id:Z.string().optional().describe("Message ID where term was found (for context)")},async({entity_id:R,text:A,entity_type:n,chat_id:h,message_id:d})=>{let g={};n!==void 0&&(g.entityType=n),h!==void 0&&(g.chatId=h),d!==void 0&&(g.messageId=d);let E=await s.getBaikeCard(l,R,A,g);if(E.success&&E.info){let X={success:!0,info:E.info};return{content:[{type:"text",text:JSON.stringify(X)}]}}return{content:[{type:"text",text:JSON.stringify(E)}]}}),t.tool("get_baike_recommend_docs","Get recommended documents for a Feishu Lingo (\u98DE\u4E66\u8BCD\u5178) glossary term",{entity_id:Z.string().describe('Baike entity ID (e.g. "enterprise_7613780366768819403")'),entity_type:Z.number().optional().describe("Entity type: 1=enterprise (default), 0=public")},async({entity_id:R,entity_type:A})=>{let n={};A!==void 0&&(n.entityType=A);let h=await s.getBaikeRecommendDocs(l,R,n);return{content:[{type:"text",text:JSON.stringify(h)}]}}),t.tool("search_guests","Search users and groups that can be added as calendar event attendees",{query:Z.string().min(1).describe("Search keyword for users or groups"),offset:Z.number().int().nonnegative().optional().describe("Pagination offset (default 0)"),limit:Z.number().int().min(1).max(100).optional().describe("Page size (default 50)"),locale:Z.string().optional().describe("Locale string such as zh_CN"),guest_type:Z.number().int().nonnegative().optional().describe("Guest type filter (default 2 = all)")},async({query:R,offset:A,limit:n,locale:h,guest_type:d})=>{let g={};A!==void 0&&(g.offset=A),n!==void 0&&(g.limit=n),h!==void 0&&(g.locale=h),d!==void 0&&(g.guestType=d);let E=await s.searchGuests(l,R,g);return{content:[{type:"text",text:JSON.stringify(E)}]}}),t.tool("search_meeting_rooms","Search for available meeting rooms within a time window",{start_time:Z.number().int().nonnegative().describe("Search window start time (Unix timestamp in seconds)"),end_time:Z.number().int().nonnegative().describe("Search window end time (Unix timestamp in seconds)"),keyword:Z.string().optional().describe("Search keyword (room name, building name, etc.)"),timezone:Z.string().optional().describe("IANA timezone for the search window (server defaults to UTC if omitted)"),min_capacity:Z.number().int().nonnegative().optional().describe("Minimum room capacity (number of people)"),cursor:Z.number().int().nonnegative().optional().describe("Pagination cursor from previous response")},async({start_time:R,end_time:A,keyword:n,timezone:h,min_capacity:d,cursor:g})=>{let E={};n!==void 0&&(E.keyword=n),h!==void 0&&(E.timezone=h),d!==void 0&&(E.minCapacity=d),g!==void 0&&(E.cursor=g);let X=await s.searchMeetingRooms(l,R,A,E);return{content:[{type:"text",text:JSON.stringify(X)}]}}),t.tool("pull_buildings","List buildings that contain meeting rooms",{min_capacity:Z.number().int().nonnegative().optional().describe("Minimum room capacity filter"),need_equipments:Z.array(Z.string()).optional().describe("Required equipment types"),enable_recommendations:Z.boolean().optional().describe("Whether to enable recommendation-based sorting"),event_start_timestamp:Z.string().optional().describe("Event start timestamp string for event context"),event_end_timestamp:Z.string().optional().describe("Event end timestamp string for event context"),start_timezone:Z.string().optional().describe("IANA start timezone for event context"),end_timezone:Z.string().optional().describe("IANA end timezone for event context"),instance_start_time:Z.string().optional().describe("Operate-instance start time string"),instance_end_time:Z.string().optional().describe("Operate-instance end time string")},async({min_capacity:R,need_equipments:A,enable_recommendations:n,event_start_timestamp:h,event_end_timestamp:d,start_timezone:g,end_timezone:E,instance_start_time:X,instance_end_time:r})=>{let m={};R!==void 0&&(m.minCapacity=R),A!==void 0&&(m.needEquipments=A),n!==void 0&&(m.enableRecommendations=n),(h!==void 0||d!==void 0||g!==void 0||E!==void 0)&&(m.eventField={},h!==void 0&&(m.eventField.eventStartTimestamp=h),d!==void 0&&(m.eventField.eventEndTimestamp=d),g!==void 0&&(m.eventField.startTimezone=g),E!==void 0&&(m.eventField.endTimezone=E)),(X!==void 0||r!==void 0)&&(m.operateInstanceField={},X!==void 0&&(m.operateInstanceField.instanceStartTime=X),r!==void 0&&(m.operateInstanceField.instanceEndTime=r));let W=await s.pullBuildings(l,m);return{content:[{type:"text",text:JSON.stringify(W)}]}}),t.tool("pull_meeting_rooms_in_building","List meeting rooms within specific buildings, filtered by time range and recurrence",{building_ids:Z.array(Z.string()).min(1).describe("Building IDs to query"),start_time:Z.number().int().nonnegative().describe("Window start time (Unix timestamp in seconds)"),end_time:Z.number().int().nonnegative().describe("Window end time (Unix timestamp in seconds)"),rrule:Z.string().optional().describe('Recurrence rule (e.g. "FREQ=DAILY;UNTIL=20280305T155959Z;INTERVAL=3")'),need_disabled_resource:Z.boolean().optional().describe("Include disabled rooms"),timezone:Z.string().optional().describe("IANA timezone (server defaults to UTC if omitted)"),min_capacity:Z.number().int().nonnegative().optional().describe("Minimum room capacity (number of people)")},async({building_ids:R,start_time:A,end_time:n,rrule:h,need_disabled_resource:d,timezone:g,min_capacity:E})=>{let X={};h!==void 0&&(X.rrule=h),d!==void 0&&(X.needDisabledResource=d),g!==void 0&&(X.timezone=g),E!==void 0&&(X.minCapacity=E);let r=await s.pullMeetingRoomsInBuilding(l,R,A,n,X);return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("pull_tenants_by_ids","Fetch tenant or organization information by tenant IDs",{tenantIds:Z.array(Z.string()).min(1).describe("Tenant IDs to fetch")},async({tenantIds:R})=>{let A=s.baseUrl||"https://internal-api-lark-api.feishu.cn";try{A=new URL(A).origin}catch{}let n=Fe._validateFeishuOrigin(A);if(!n.valid)return{content:[{type:"text",text:JSON.stringify({success:!1,error:n.error})}]};let h=await s.pullTenantsByIds(l,R);return{content:[{type:"text",text:JSON.stringify(h)}]}}),t.tool("get_docx_block_tree","Get the block tree of a Feishu document (wiki or docx). Returns structured blocks with text, type, version, and children.",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),mode:Z.union([Z.literal(0),Z.literal(1),Z.literal(7)]).optional().describe("Fetch mode: 0=ALL (default), 1=TOP_BOTTOM, 7=AroundV2"),limit:Z.number().int().min(1).max(500).optional().describe("Blocks per page (1-500, default 200)")},async({url:R,mode:A,limit:n})=>{let h;try{h=new URL(R)}catch{return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid URL"})}]}}let d=h.origin,g=Fe._validateFeishuOrigin(d);if(!g.valid)return{content:[{type:"text",text:JSON.stringify({success:!1,error:g.error})}]};let E=h.pathname.match(/\/wiki\/([^/?#]+)/),X=h.pathname.match(/\/docx\/([^/?#]+)/);if(!E&&!X)return{content:[{type:"text",text:JSON.stringify({success:!1,error:"URL must contain /wiki/ or /docx/ path"})}]};let r;if(E){let u=await s.resolveWikiToken(l,d,E[1]);if(!u.success)return{content:[{type:"text",text:JSON.stringify(u)}]};if(u.data.objType!==22)return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Unsupported wiki object type: ${u.data.objType} (only docx type 22 is supported)`})}]};r=u.data.objToken}else r=X[1];let m={};A!==void 0&&(m.mode=A),n!==void 0&&(m.limit=n);let W=await s.getDocxBlockTree(l,d,r,m);return{content:[{type:"text",text:JSON.stringify(W)}]}});let V=new Map;async function o(R,{refresh:A=!1}={}){let n;try{n=new URL(R)}catch{return{success:!1,error:"Invalid URL"}}let h=n.origin,d=Fe._validateFeishuOrigin(h);if(!d.valid)return{success:!1,error:d.error};let g=n.pathname.match(/\/wiki\/([^/?#]+)/),E=n.pathname.match(/\/docx\/([^/?#]+)/);if(!g&&!E)return{success:!1,error:"URL must contain /wiki/ or /docx/ path"};let X;if(g){let W=await s.resolveWikiToken(l,h,g[1]);if(!W.success)return{success:!1,error:W.error};if(W.data.objType!==22)return{success:!1,error:`Unsupported wiki object type: ${W.data.objType} (only docx type 22 is supported)`};X=W.data.objToken}else X=E[1];let r=`${h}|${X}`,m=V.get(r);if(A||!m){m=new GV(s,l,h,X);let W=await m.open();if(!W.success)return{success:!1,error:W.error};V.set(r,m)}return{success:!0,editor:m,origin:h,pageId:X,cacheKey:r}}async function c(R,A){let n=await o(R);if(!n.success)return{content:[{type:"text",text:JSON.stringify({success:!1,error:n.error})}]};let h=await A(n.editor,n);return h.success||V.delete(n.cacheKey),{content:[{type:"text",text:JSON.stringify(h)}]}}t.tool("docx_open_document","Open a Feishu document for editing. Returns the block tree. The document stays cached for subsequent edit operations. Use refresh=true to re-fetch the latest state.",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),refresh:Z.boolean().optional().describe("Force re-fetch the document from server (default: false)")},async({url:R,refresh:A})=>{let n=await o(R,{refresh:!!A});if(!n.success)return{content:[{type:"text",text:JSON.stringify({success:!1,error:n.error})}]};let h=n.editor.getBlockTree();return{content:[{type:"text",text:JSON.stringify({success:!0,data:{pageId:n.pageId,structureVersion:n.editor.structureVersion,blockCount:Object.keys(n.editor.blockMap).length,tree:h}})}]}}),t.tool("docx_insert_block","Insert a new block into a Feishu document",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),parent_id:Z.string().optional().describe("Parent block ID (defaults to page root)"),position:Z.number().int().min(0).optional().describe("Index in parent children (defaults to end)"),type:Z.string().optional().describe("Block type: text (default), heading1-9, todo, bullet, ordered, code, quote, divider, equation"),text:Z.string().optional().describe("Initial text content")},async({url:R,parent_id:A,position:n,type:h,text:d})=>c(R,(g,E)=>{let X=A||E.pageId,r=g.getBlock(X);if(!r)return{success:!1,error:`Parent block ${X} not found`};let m=n??(r.data?.children?.length||0),W=h||"text",u={};return d!==void 0&&(u.text=d),g.insertBlock(X,m,W,u)})),t.tool("docx_edit_text","Edit the text content of a block in a Feishu document",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),block_id:Z.string().describe("Block ID to edit"),text:Z.string().describe("New text content")},async({url:R,block_id:A,text:n})=>c(R,h=>h.editText(A,n))),t.tool("docx_delete_blocks","Delete one or more blocks from a Feishu document",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),block_ids:Z.array(Z.string()).min(1).describe("Block IDs to delete")},async({url:R,block_ids:A})=>c(R,n=>n.deleteBlocks(A))),t.tool("docx_change_block_type","Change the type of a block in a Feishu document (e.g. text to heading1, bullet to todo)",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),block_id:Z.string().describe("Block ID to change"),new_type:Z.string().describe("New block type: text, heading1-9, todo, bullet, ordered, code, quote, divider, equation")},async({url:R,block_id:A,new_type:n})=>c(R,h=>h.changeBlockType(A,n))),t.tool("docx_set_block_properties","Set properties on a block. Common properties: done (bool, todo), folded (bool), align (left/center/right), language (string, code), emoji_id (string, callout), text_indent (number)",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),block_id:Z.string().describe("Block ID to modify"),properties:Z.record(Z.string(),Z.any()).describe('Key-value pairs to set (e.g. {"done": true, "align": "center"})')},async({url:R,block_id:A,properties:n})=>c(R,h=>h.setBlockProperties(A,n))),t.tool("docx_move_block","Move a block to a new parent and/or position within a Feishu document",{url:Z.string().describe("Document URL: https://xxx.feishu.cn/wiki/xxx or /docx/xxx"),block_id:Z.string().describe("Block ID to move"),new_parent_id:Z.string().describe("Target parent block ID"),new_position:Z.number().int().min(0).describe("Target index in new parent children")},async({url:R,block_id:A,new_parent_id:n,new_position:h})=>c(R,d=>d.moveBlock(A,n,h)));let a=new zR;await t.connect(a),Q.log("[MCP] Server started on stdio")}var Ba={1:"p2p",2:"group",3:"topic_group"},Ca={1:"user",2:"bot"},pa={2:"rich",3:"file",4:"text",5:"image",6:"system",7:"audio",9:"share_group_chat",10:"sticker",11:"merge_forward",12:"calendar",14:"card",15:"media",23:"share_user_card",24:"todo"},Ia={0:"unknown",1:"pc",2:"web",3:"android",4:"ios"},Na={0:"unknown",1:"online",2:"offline"},Mo={0:"unknown",1:"inbox",2:"done"},Qa={0:"unknown",1:"chat",2:"mail",3:"doc",4:"thread",5:"box",6:"openapp",7:"topic",8:"app_chat",10:"subscription",11:"msg_thread",12:"my_ai",13:"app_feed",14:"knowledge_ai"},Ya={0:"unknown",1:"app",2:"sms",3:"phone"},Ja={0:"unknown",1:"message",2:"doc_list",3:"doc",4:"pin",5:"meeting_minute",6:"chat_announcement",7:"url",8:"file",9:"task",10:"doc_file_url_merge",11:"image_video_merge"},Ta={0:"unknown",1:"message",2:"announcement"},ya={1:"chat",2:"email"};function Gl(s){return typeof s=="bigint"?s.toString():Array.isArray(s)?s.map(Gl):s&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([l,e])=>[l,Gl(e)])):s}var xa={27:"im.message.reaction_v1",41:"im.message.read_count_v1",74:"im.chat.read_state_v1",92:"im.thread.reply_count_v1",130:"im.reaction.user_v1",146:"im.reaction.user_mru_v1",1002:"feed.cards_v1",1311:"im.message.preview_v1",5916:"im.chat.tabs_v1",7001:"system.device.status_v1",8106:"im.thread.read_state_v1",8110:"im.thread.updated_v1",30002:"im.message.urgent_v1",30003:"im.message.urgent_ack_v1",1020003:"calendar.event.sync_v1",1103704:"im.chat.top_notice_v1"},ka=new Set([200,6e3]);function Do(s){let{command:l}=s;if(ka.has(l))return null;if(l===6)return fa(s);let e=xa[l];return e?Ka(e,s):Gl({type:"system.event.unknown",event_id:null,timestamp:Date.now(),data:{command:l,raw:s}})}function fa(s){let{messageId:l,chatId:e,chatType:t,fromId:V,fromType:o,type:c,content:a,threadId:R}=s;return Gl({type:"im.message.receive_v1",event_id:l?`evt_${l}`:null,timestamp:Date.now(),data:{id:l||null,chat:{id:e||null,type:Ba[t]||"unknown"},sender:{id:V||null,type:Ca[o]||"unknown"},content:{type:pa[c]||"unknown",text:a||""},thread_id:R||null}})}function Ka(s,l){let{command:e,event:t,sid:V,fromId:o,content:c,type:a,chatId:R,...A}=l;return R&&(A.chatId=R),Ma(e,A),Gl({type:s,event_id:V?`evt_${V}`:null,timestamp:Date.now(),data:A})}function Ma(s,l){switch(s){case 7001:l.terminalType=Ia[l.terminalType]??l.terminalType,l.onlineStatus=Na[l.onlineStatus]??l.onlineStatus;break;case 1002:l.feedType=Mo[l.feedType]??l.feedType,l.cards&&(l.cards=l.cards.map(e=>({...e,type:Qa[e.type]??e.type,feedType:Mo[e.feedType]??e.feedType})));break;case 30002:case 30003:l.urgentType=Ya[l.urgentType]??l.urgentType;break;case 5916:l.tabs&&(l.tabs=l.tabs.map(e=>({...e,tabType:Ja[e.tabType]??e.tabType})));break;case 1103704:l.topNotice?.content&&(l.topNotice={...l.topNotice,content:{...l.topNotice.content,type:Ta[l.topNotice.content.type]??l.topNotice.content.type}});break;case 41:l.pairs&&(l.pairs=l.pairs.map(e=>({...e,type:ya[e.type]??e.type})));break}}function Da(s){let l=s?.data?.threadId??null,e=s?.data?.replyCount??null;return{entity:"thread",action:"activity_detected",kind:"state_signal",consumable:!1,requires_hydration:"fetch_thread_messages",dedupe_key:l!==null&&e!==null?`thread:${l}:reply_count:${e}`:null,dedupe_strategy:"drop_exact_match",routing_hints:["thread","activity"]}}var Ha=new Map([["im.thread.reply_count_v1",Da]]);function Ho(s){let l=Ha.get(s?.type);return l?{...s,semantic:l(s)}:s}var Wl=5,za=500;function wa(s,l){return typeof l=="bigint"?l.toString():l}async function zo(s,l){for(let e=1;e<=Wl;e++){try{let t=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l,wa),signal:AbortSignal.timeout(1e4)});if(t.status>=200&&t.status<300){Q.debug(`[Webhook] Delivered event ${l.event_id||"N/A"} (${t.status})`);return}Q.warn(`[Webhook] Non-2xx response ${t.status} for event ${l.event_id||"N/A"} (attempt ${e}/${Wl})`)}catch(t){Q.warn(`[Webhook] Request failed for event ${l.event_id||"N/A"} (attempt ${e}/${Wl}): ${t.message}`)}if(e<Wl){let t=za*Math.pow(2,e-1);await new Promise(V=>setTimeout(V,t))}}Q.error(`[Webhook] Failed to deliver event ${l.event_id||"N/A"} after ${Wl} attempts`)}var La=300*1e3;function wo(s){return typeof s=="bigint"?s.toString():s}var tt=class s{constructor(l,e){this.api=l,this.auth=e,this.chatCache=new Map,this.userCache=new Map,this.chatInflight=new Map,this.userInflight=new Map}static extractIds(l){let e=new Set,t=new Set,V=l?.data;if(!V)return{chatIds:e,userIds:t};let o=l.type;if(o==="im.message.receive_v1")V.chat?.id&&e.add(V.chat.id),V.sender?.id&&t.add(V.sender.id);else if(o==="im.message.urgent_v1")V.chatId&&e.add(V.chatId),V.sendChatterId&&t.add(V.sendChatterId);else if(o==="im.message.urgent_ack_v1")V.chatId&&e.add(V.chatId),V.ackChatterId&&t.add(V.ackChatterId);else if(o==="im.chat.top_notice_v1")V.chatId&&e.add(V.chatId),V.topNotice?.operatorId&&t.add(V.topNotice.operatorId),V.topNotice?.content?.senderId&&t.add(V.topNotice.content.senderId);else if(o==="im.message.read_count_v1"){if(Array.isArray(V.pairs))for(let c of V.pairs)c.chatId&&e.add(c.chatId)}else V.chatId&&e.add(V.chatId);return{chatIds:e,userIds:t}}_getCached(l,e){let t=l.get(e);if(t){if(Date.now()>t.expiresAt){l.delete(e);return}return t.data}}_setCache(l,e,t){l.set(e,{data:t,expiresAt:Date.now()+La})}async _resolveChat(l){l=wo(l);let e=this._getCached(this.chatCache,l);if(e)return e;let t=this.chatInflight.get(l);if(t)return t;let V=this._fetchChat(l);this.chatInflight.set(l,V);try{return await V}finally{this.chatInflight.delete(l)}}async _fetchChat(l){try{let e=await this.api.getChatMeta(this.auth,l);if(!e.success||!e.chat)return null;let t={name:e.chat.name,type:e.chat.type,memberCount:e.chat.memberCount};return this._setCache(this.chatCache,l,t),t}catch(e){return Q.error(`Enricher: failed to resolve chat ${l}:`,e.message),null}}async _resolveUser(l){l=wo(l);let e=this._getCached(this.userCache,l);if(e)return e;let t=this.userInflight.get(l);if(t)return t;let V=this._fetchUser(l);this.userInflight.set(l,V);try{return await V}finally{this.userInflight.delete(l)}}async _fetchUser(l){try{let e=await this.api.getUserInfoById(this.auth,l);if(!e.success)return null;let t={name:e.name,isBot:e.isBot};return this._setCache(this.userCache,l,t),t}catch(e){return Q.error(`Enricher: failed to resolve user ${l}:`,e.message),null}}async enrich(l){let{chatIds:e,userIds:t}=s.extractIds(l);if(e.size===0&&t.size===0)return l;let[V,o]=await Promise.all([Promise.all([...e].map(async R=>[R,await this._resolveChat(R)])),Promise.all([...t].map(async R=>[R,await this._resolveUser(R)]))]),c={};for(let[R,A]of V)A&&(c[R]=A);let a={};for(let[R,A]of o)A&&(a[R]=A);return Object.keys(c).length===0&&Object.keys(a).length===0?l:this._applyEnrichment(l,c,a)}_applyEnrichment(l,e,t){let V=l.type,o={...l.data};return V==="im.message.receive_v1"?(o.chat?.id&&e[o.chat.id]&&(o.chat={...e[o.chat.id],...o.chat}),o.sender?.id&&t[o.sender.id]&&(o.sender={...t[o.sender.id],...o.sender})):V==="im.message.urgent_v1"?(o.chatId&&e[o.chatId]&&(o.chat={id:o.chatId,...e[o.chatId]}),o.sendChatterId&&t[o.sendChatterId]&&(o.sender={id:o.sendChatterId,...t[o.sendChatterId]})):V==="im.message.urgent_ack_v1"?(o.chatId&&e[o.chatId]&&(o.chat={id:o.chatId,...e[o.chatId]}),o.ackChatterId&&t[o.ackChatterId]&&(o.acker={id:o.ackChatterId,...t[o.ackChatterId]})):V==="im.chat.top_notice_v1"?(o.chatId&&e[o.chatId]&&(o.chat={id:o.chatId,...e[o.chatId]}),o.topNotice&&(o.topNotice={...o.topNotice},o.topNotice.operatorId&&t[o.topNotice.operatorId]&&(o.topNotice.operator={id:o.topNotice.operatorId,...t[o.topNotice.operatorId]}),o.topNotice.content?.senderId&&t[o.topNotice.content.senderId]&&(o.topNotice.content={...o.topNotice.content},o.topNotice.content.sender={id:o.topNotice.content.senderId,...t[o.topNotice.content.senderId]}))):V==="im.message.read_count_v1"?Array.isArray(o.pairs)&&(o.pairs=o.pairs.map(c=>c.chatId&&e[c.chatId]?{...c,chat:{id:c.chatId,...e[c.chatId]}}:c)):o.chatId&&e[o.chatId]&&(o.chat={id:o.chatId,...e[o.chatId]}),{...l,data:o}}};var va=["Usage:"," openbird mcp"," openbird relay <webhook-url>","","Examples:"," npx openbird mcp"," npx openbird relay http://localhost:3000/webhook"].join(`
|
|
37
37
|
`);function Lo(s){s&&process.stderr.write(`${s}
|