writedock-mcp 0.4.9 → 0.4.10

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.
@@ -39,4 +39,4 @@ b, strong { font-weight: bolder; }
39
39
  `).trim())return S("微博页面正文与本次 Agent 稿件不一致,已停止发布,请检查原投稿页。");const H=O=>O===null||O===""||O==="0"||O==="{}"||O==="[]",ee=X.get("visible");if(ee===null&&m("微博发布请求中未读到可见范围字段"),ee!==null&&ee!=="0"||["share_id","vote","schedule_timestamp","schedule_id","mid","mblog_id","auth_state","is_vip_paid","sync_mblog","topic_id","mblog_statement"].some(O=>!H(X.get(O))))return S("微博的可见范围、定时、转发、内容声明或其他发布设置需要核对,请在原页面手动处理。");let Z,ie;try{Z=X.get("media")?A(X.get("media")):null,ie=X.get("pic_id")?A(X.get("pic_id")):[]}catch{m("微博素材字段无法解析,已依据提交前的页面核对放行"),M();return}if(e.kind==="image"){if(Array.isArray(ie)&&ie.length&&ie.length!==e.imageCount)return S("微博图片数量与本次投稿不一致,已停止发布,请检查原投稿页。");!Array.isArray(ie)||!ie.length?m("微博发布请求中未读到图片字段"):(new Set(ie.map(O=>O.pid)).size!==e.imageCount||ie.some(O=>!String(O.type).startsWith("image/")||!r.has(O.pid)||O.media_id))&&m("微博图片未匹配本次观察到的上传记录"),Z&&Object.keys(Z).length&&m("微博图文请求带有 media 字段")}else if(!Z)m("微博发布请求中未读到视频字段");else{const O=Z.homemade||Z.contribution,G={original:0,secondary:2,repost:1}[e.creation],T=Array.isArray(Z.titles)?(se=Z.titles[0])==null?void 0:se.title:void 0;if(typeof T=="string"&&T!==e.title)return S("微博视频标题与本任务不一致,已停止发布,请核对原页面。");if((O==null?void 0:O.type)!==void 0&&O.type!==G)return S("微博视频创作类型与本任务不一致,已停止发布,请核对原页面。");if(e.explicitCover&&Array.isArray(Z.covers)&&((Y=Z.covers[0])!=null&&Y.pid)&&!n.has(Z.covers[0].pid))return S("本次指定的视频封面未确认应用,未使用默认封面替代,请在原页面完成设置。");if((ge=Z.resource)!=null&&ge.statement||(C=Z.resource)!=null&&C.manual_split||(z=Z.cooperate_video)!=null&&z.length||Z.is_vip_paid||Z.um_video_switch||(q=Z.follower_watch_entire)!=null&&q.enable)return S("微博视频需要内容声明、来源、共创、付费或阅读设置确认,请在原页面核对并手动发布。");typeof T!="string"&&m("微博发布请求中未读到视频标题字段"),(O==null?void 0:O.type)===void 0&&m("微博发布请求中未读到创作类型字段"),(Z.type!=="video"||!a.has(Z.media_id))&&m("微博视频未匹配本次观察到的上传记录"),(!Array.isArray(Z.covers)||!Z.covers.length||Z.covers.some(F=>!D(F.pid)))&&m("微博发布请求中未读到有效的视频封面字段"),Array.isArray(ie)&&ie.length&&m("微博视频请求带有图片字段")}M()},f=($,S,M,X)=>{var j,H,ee,Z,ie,se,Y,ge,C,z,q,O,G;if(!c)try{const T=A(M);if($!=="publish"){if(S<200||S>=300)return;if($==="picture"){const K=(T==null?void 0:T.ret)===!0?(j=T.pic)==null?void 0:j.pid:(Z=(ee=(H=T==null?void 0:T.data)==null?void 0:H.pics)==null?void 0:ee.pic_1)==null?void 0:Z.pid;D(K)&&(r.add(K),X&&n.add(K))}$==="init"&&D(T==null?void 0:T.media_id)&&i.add(T.media_id),$==="check"&&(T==null?void 0:T.result)===!0&&i.has(T.media_id)&&a.add(T.media_id),g();return}const F=String((T==null?void 0:T.msg)||(T==null?void 0:T.message)||"").slice(0,300);if((ie=T==null?void 0:T.data)!=null&&ie.verify||(se=T==null?void 0:T.data)!=null&&se.geetest||(Y=T==null?void 0:T.data)!=null&&Y.verify_url||/验证码|安全验证|完成验证|验证后/.test(F)){u("captcha","微博要求人工验证。请切换到已打开的投稿页完成验证并手动发布,Agent 不要重新提交。");return}if((T==null?void 0:T.ok)===1&&!T.error&&S>=200&&S<300){const K=(ge=T.data)==null?void 0:ge.mblogid,J=String(((z=(C=T.data)==null?void 0:C.user)==null?void 0:z.idstr)??((O=(q=T.data)==null?void 0:q.user)==null?void 0:O.id)??""),ne=typeof K=="string"&&/^[a-zA-Z0-9]+$/.test(K)&&/^\d+$/.test(J)?`https://weibo.com/${J}/${K}`:"https://weibo.com";p({success:!0,publicationState:"submitted",responseConfirmed:!0,postUrl:ne,...typeof((G=T.data)==null?void 0:G.idstr)=="string"&&/^\d+$/.test(T.data.idstr)?{postId:T.data.idstr}:{}});return}if(/声明|来源|原创|版权|协议|选择.*类型/.test(F)){u("publication_settings",F||"请在原微博投稿页核对内容声明并手动发布。");return}p({success:!1,publicationState:(T==null?void 0:T.ok)===0?"failed":"unknown",error:F||`微博发布结果未确认(HTTP ${S}),请检查平台,不要自动重发。`})}catch{$==="publish"&&p({success:!1,publicationState:"unknown",error:"微博发布响应无法解析,请检查平台,不要自动重发。"})}},l=()=>{throw u("publication_settings","微博页面试图定时、转发或修改已有帖子,未按本次即时发布提交,请在原页面核对。"),new Error("WriteDock 已停止本次未授权的微博发布方式")},_=window.fetch,k=async function($,S){const M=(S==null?void 0:S.method)||($ instanceof Request?$.method:"GET"),X=b(M,$ instanceof Request?$.url:String($)),j=y;X==="other_publish"&&l(),X==="publish"&&d((S==null?void 0:S.body)??($ instanceof Request?await $.clone().text():void 0));try{const H=await _.call(window,$,S);return X&&f(X,H.status,await H.clone().text(),j),H}catch(H){throw X==="publish"&&p({success:!1,publicationState:"unknown",error:"微博发布连接中断,请检查原帖,不要自动重发。"}),H}},I=XMLHttpRequest.prototype,E=I.open,v=I.send,R=new WeakMap,U=function($,S,...M){return R.set(this,{method:$,url:String(S)}),Reflect.apply(E,this,[$,S,...M])},B=function($){const S=R.get(this),M=S?b(S.method,S.url):null,X=y;return M==="other_publish"&&l(),M==="publish"&&d($),M&&this.addEventListener("loadend",()=>{try{f(M,this.status,this.responseType==="json"?this.response:this.responseText,X)}catch{M==="publish"&&f(M,this.status,void 0,X)}},{once:!0}),v.call(this,$)},W=()=>{!c&&!o&&Date.now()<e.deadline&&(s=!0)},P=()=>{y=!0},N=()=>{var H,ee;const $=document.querySelector(`input[data-writedock-video="${e.channel}"]`),S=Array.from(document.querySelectorAll('[id^="area_video"]')).find(Z=>Z.getClientRects().length>0);if(!$)return;if(!((H=$.files)!=null&&H.length)||!S){$.setAttribute("data-writedock-drop-status",`files=${((ee=$.files)==null?void 0:ee.length)??0} area=${S?1:0}`);return}const M=new DataTransfer;for(const Z of Array.from($.files))M.items.add(Z);const X=S.firstElementChild||S,j=["dragenter","dragover","drop"].map(Z=>X.dispatchEvent(new DragEvent(Z,{bubbles:!0,cancelable:!0,composed:!0,dataTransfer:M}))?0:1).join("");$.setAttribute("data-writedock-drop-status",`files=${M.files.length} handled=${j}`)},x=()=>{window.fetch===k&&(window.fetch=_),I.open===U&&(I.open=E),I.send===B&&(I.send=v),clearTimeout(L),window.removeEventListener(`${t}:arm`,W),window.removeEventListener(`${t}:cover`,P),window.removeEventListener(`${t}:drop-video`,N),window.removeEventListener(`${t}:stop`,x)};window.fetch=k,I.open=U,I.send=B,window.addEventListener(`${t}:arm`,W),window.addEventListener(`${t}:cover`,P),window.addEventListener(`${t}:drop-video`,N),window.addEventListener(`${t}:stop`,x,{once:!0});const L=setTimeout(x,Math.max(1,e.deadline-Date.now()));return{observing:!0}}function Mr(e){const t=`writedock-weibo-post-${e.channel}`;let r=!1,i=!1,a=!1,n={pictures:[],videos:[],covers:[]};const s=v=>new Promise(R=>setTimeout(R,v)),o=v=>v.getClientRects().length>0&&getComputedStyle(v).visibility!=="hidden",c=v=>o(v)&&!v.hasAttribute("disabled")&&v.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(v.className),y=async(v,R={})=>{const U=await chrome.runtime.sendMessage({type:v,jobId:e.id,jobSecret:e.secret,...R});if(!U||U.error)throw new Error((U==null?void 0:U.error)||"扩展后台已断开,请检查微博,不要自动重发");return U.data},h=(v,R,U)=>y("PAGE_PUBLISH_PROGRESS",{stage:v,current:R,total:U}),w=()=>{window.removeEventListener(t,u),window.removeEventListener(`${t}:cancel`,m),window.dispatchEvent(new Event(`${t}:stop`))},m=()=>{r=!0,w()},p=async v=>{i||r||(i=!0,w(),await y("PAGE_PUBLISH_DONE",{result:{...v,postUrl:v.postUrl||location.href}}))},u=v=>{if(!(r||i))try{const R=JSON.parse(v.detail);R.phase==="uploads"&&(n=R),R.phase==="request"&&(a=!0,h("verifying").catch(m)),R.phase==="result"&&p(R).catch(m)}catch{}};window.addEventListener(t,u),window.addEventListener(`${t}:cancel`,m,{once:!0});try{const v=sessionStorage.getItem(t);v&&u(new CustomEvent(t,{detail:v}))}catch{}function g(v,R){throw Object.assign(new Error(R),{manualReason:v})}const D=()=>{if(r||i)throw new Error("本次微博自动投稿已结束");if(Date.now()>=e.deadline)throw new Error("微博投稿超时,请检查平台,不要自动重发");if(location.origin!=="https://weibo.com"||/\/(?:login|newlogin|passport)(?:\/|$)/.test(location.pathname))throw new Error("请先在当前浏览器登录微博");Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="geetest"],iframe[src*="verify"],iframe[src*="yidun"],.geetest_panel,.yidun_popup')).some(o)&&g("captcha","微博要求人工验证,请在已打开的投稿页完成验证并手动发布,Agent 不要重新提交。");const v=Array.from(document.querySelectorAll('[role="alert"],.woo-toast-main,.woo-dialog-main,.woo-modal-main')).filter(o).map(U=>{var B;return((B=U.textContent)==null?void 0:B.trim())||""}).filter(U=>U.length<1e3);v.some(U=>/验证码|安全验证|完成验证/.test(U))&&g("captcha","请在已打开的微博投稿页完成验证并手动发布,Agent 不要重发。"),v.some(U=>/请.*(?:声明|来源|原视频|分类|类型)|我同意|原创.*协议|版权.*协议/.test(U))&&g("publication_settings","微博需要补充来源、分类、内容声明或协议确认,请在原投稿页核对并手动发布。");const R=v.find(U=>/上传失败|发布失败|发送失败|格式不支持|超出.*限制|超过.*限制/.test(U));if(R)throw new Error(R.slice(0,300))},A=async(v,R,U,B)=>{const W=Math.min(Date.now()+R,e.deadline);for(;Date.now()<W;){D();const P=v();if(P)return P;await s(300)}throw B&&g(B,U),new Error(U)},b=(v=document)=>Array.from(v.querySelectorAll('button,[role="button"]')).filter(c),d=()=>Array.from(document.querySelectorAll("textarea")).find(v=>o(v)&&/新鲜事|分享/.test(v.placeholder)),f=v=>{let R=v.parentElement;for(;R&&R!==document.body;){if(Array.from(R.querySelectorAll('button,[role="button"]')).some(U=>{var B;return o(U)&&/^(?:发送|发布|发布微博|立即发布)$/.test(((B=U.textContent)==null?void 0:B.trim())||"")}))return R;R=R.parentElement}throw new Error("未能定位本次微博的完整投稿表单,已停止发布")},l=(v,R)=>{var U,B;if(v.maxLength>0&&R.length>v.maxLength)throw new Error(`微博输入内容超过页面 ${v.maxLength} 字限制,未截断发布`);(B=(U=Object.getOwnPropertyDescriptor(v instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:U.set)==null||B.call(v,R),v.dispatchEvent(new Event("input",{bubbles:!0})),v.dispatchEvent(new Event("change",{bubbles:!0}))},_=async(v,R)=>{const U=new DataTransfer,B=R.reduce((P,N)=>P+N.size,0);let W=0;await h("transferring_media",0,B);for(const P of R){const N=v.toLowerCase().split(",").map(L=>L.trim());if(v&&!N.some(L=>L==="*/*"||L===P.type||L===`${P.type.split("/")[0]}/*`||L==="image/jpg"&&P.type==="image/jpeg"||L.startsWith(".")&&P.name.toLowerCase().endsWith(L)))throw new Error(`微博当前控件不接受 ${P.name} 的格式`);const x=[];for(let L=0;L<P.size;L+=1024*1024){D();const $=Math.min(1024*1024,P.size-L),S=await y("PAGE_PUBLISH_READ_ASSET",{assetId:P.id,offset:L,length:$});D();const M=Uint8Array.from(atob(S.base64),X=>X.charCodeAt(0));if(M.length!==$)throw new Error("微博素材读取不完整,已停止上传");x.push(M.buffer),W+=M.length,(L%(8*1024*1024)===0||W===B)&&await h("transferring_media",W,B)}U.items.add(new File(x,P.name,{type:P.type}))}return U},k=async(v,R)=>{if(!v.multiple&&R.length>1)throw new Error("微博当前上传控件不接受多张图片,未丢弃素材发布");const U=await _(v.accept,R);D(),v.files=U.files,v.dispatchEvent(new Event("change",{bubbles:!0})),await h("uploading_media")},I=async(v,R)=>{const U=await _("",[R]);D();const B=document.createElement("input");B.type="file",B.hidden=!0,B.setAttribute("data-writedock-video",e.channel),B.files=U.files,document.body.append(B),await h("uploading_media");const W=()=>!o(v)||n.videos.length>0;try{for(let P=0;P<5&&!W();P++){await s(P?6e3:2e3),D(),W()||window.dispatchEvent(new Event(`${t}:drop-video`));for(let N=0;N<20&&!W();N++)await s(300),D()}if(!W())throw new Error(`微博视频页没有响应拖放上传(${B.getAttribute("data-writedock-drop-status")||"页面脚本未执行"}),未提交发布`)}finally{B.remove()}};return(async()=>{var P;await h("checking_auth");const v=e.post;if(v.kind==="image"){const N=await A(d,6e4,"未找到微博普通发博输入框,请确认已登录;页面改版时需更新适配");N.value.trim()&&g("publication_settings","当前微博输入框已有未发内容,未覆盖原内容,请在这个页面自行核对。");const x=f(N);l(N,e.text);const L=await A(()=>Array.from(x.querySelectorAll('input[type="file"]')).find($=>/image|\.(?:jpe?g|png|gif|webp)/i.test($.accept)),2e4,"未找到本次普通微博的图片上传控件");await k(L,v.images),await A(()=>n.pictures.length>=v.images.length,5*6e4,"微博图片上传未全部确认,未提交发布,请检查原页面")}else{const N=await A(()=>Array.from(document.querySelectorAll('[id^="area_video"]')).find(o),6e4,"未找到微博视频上传区域,请确认已登录视频发布页"),x=d();x!=null&&x.value.trim()&&g("publication_settings","微博视频页面已有未发正文,未覆盖原内容,请在当前页面自行核对。"),await I(N,v.video),await A(()=>n.videos.length===1,15*6e4,"微博视频上传尚未完成,未提交发布,请检查原投稿页");const L=await A(()=>Array.from(document.querySelectorAll('input[type="text"]')).find(j=>o(j)&&/填写标题|视频标题/.test(j.placeholder)),6e4,"未找到微博视频标题输入框");l(L,v.title);const $={original:"原创",secondary:"二创",repost:"转载"}[v.weiboVideoCreation],S=Array.from(document.querySelectorAll("label.woo-radio-main")).find(j=>{var H;return o(j)&&((H=j.textContent)==null?void 0:H.trim())===$}),M=S==null?void 0:S.querySelector('input[type="radio"]');(!S||!M||M.disabled)&&g("publication_settings",`当前微博页面无法选择“${$}”,请检查账号可用类型并手动处理。`),D(),M.checked||S.click(),await s(300),D(),M.checked||g("publication_settings","微博视频创作类型未确认选中,请在当前页面核对。");const X=await A(d,6e4,"未找到微博视频正文输入框");if(l(X,e.text),v.cover){const j=Array.from(document.querySelectorAll('a,button,[role="button"]')).find(se=>{var Y;return c(se)&&((Y=se.textContent)==null?void 0:Y.trim())==="上传封面"});j||g("cover_required","当前页面未找到视频封面上传入口,未使用默认封面替代,请在原页面设置指定封面后手动发布。");const H=new Set(document.querySelectorAll('input[type="file"]'));D(),j.click();const ee=await A(()=>Array.from(document.querySelectorAll('input[type="file"]')).find(se=>!H.has(se)&&/image|\.(?:jpg|jpeg|png)/i.test(se.accept)),2e4,"未找到新打开的视频封面控件,请在原页面手动设置封面并发布","cover_required"),Z=ee.closest('.wbpro-layer,.woo-modal-main,[role="dialog"]');(!Z||!o(Z))&&g("cover_required","视频封面编辑窗口未就绪,请在原页面设置封面并手动发布。"),await k(ee,[v.cover]),await A(()=>Array.from(Z.querySelectorAll(".cropper-canvas img")).find(se=>se.src.startsWith("blob:")&&se.complete&&se.naturalWidth>0),2e4,"本次封面尚未载入裁切区,请在原页面完成封面并手动发布","cover_required");const ie=await A(()=>b(Z).find(se=>{var Y;return((Y=se.textContent)==null?void 0:Y.trim())==="完成"}),2e4,"视频封面需要手动调整,请在原页面完成封面并手动发布","cover_required");D(),window.dispatchEvent(new Event(`${t}:cover`)),ie.click(),await A(()=>n.covers.length>0&&!o(Z),6e4,"视频封面上传或应用未确认,请在原页面核对后手动发布","cover_required")}if(L.value!==v.title)throw new Error("微博页面视频标题被修改或截断,已停止发布")}const R=await A(d,3e4,"未找到微博正文,未提交发布"),U=f(R),B=await A(()=>b(U).find(N=>{var x;return/^(?:发送|发布|发布微博|立即发布)$/.test(((x=N.textContent)==null?void 0:x.trim())||"")}),5*6e4,"微博发布按钮尚不可用,可能需要补充来源、内容声明或分类,请在原页面核对并手动发布","publication_settings");if(D(),R.value.replace(/\r\n?/g,`
40
40
  `).trim()!==e.text.replace(/\r\n?/g,`
41
41
  `).trim())throw new Error("微博页面正文与本次稿件不一致,已停止发布");if(e.rehearsal){((P=localStorage.getItem("from_content"))==null?void 0:P.replace(/\s/g,""))===e.text.replace(/\s/g,"")&&localStorage.removeItem("from_content"),await p({success:!1,publicationState:"rehearsed"});return}if(await h("publishing"),D(),!B.isConnected||!c(B))throw new Error("微博发布控件状态变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,B.click();const W=Math.min(Date.now()+12e4,e.deadline);for(;!i&&!r&&Date.now()<W;)D(),await s(300);!i&&!r&&await p({success:!1,publicationState:"unknown",error:"已触发微博发送,但未收到本次发布成功回执,请检查原页面,不要自动重发。"})})().catch(v=>{r||i||p(v!=null&&v.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:v.manualReason,message:v.message}:{success:!1,publicationState:a?"unknown":"failed",error:v instanceof Error?v.message:"微博投稿失败"}).catch(m)}),{started:!0}}const St=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),Nt=async(e,t)=>{const r=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return St(new Uint8Array(await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t))))};async function Ct(e,t,r){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(r)||t<0||r<1||r>1024*1024||t+r>e.size)throw new Error("素材读取范围不正确");const i=St(crypto.getRandomValues(new Uint8Array(32))),a=String(Date.now()),n=t+r-1,s=await Nt(e.accessKey,`asset-request:${e.id}:${t}:${n}:${a}:${i}`),o=await fetch(`http://127.0.0.1:${e.port}/assets/${e.id}`,{headers:{"X-Writedock-Asset-Nonce":i,"X-Writedock-Asset-Time":a,"X-Writedock-Asset-Proof":s,Range:`bytes=${t}-${n}`},cache:"no-store",signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error("本机素材授权已失效或文件已变化,请重新准备素材");const c=new Uint8Array(await o.arrayBuffer());if(c.length!==r)throw new Error("素材读取不完整");const y=St(new Uint8Array(await crypto.subtle.digest("SHA-256",c)));if(o.headers.get("x-writedock-asset-proof")!==await Nt(e.accessKey,`asset-response:${i}:${y}`))throw new Error("本机素材服务未通过身份校验");return c}function Br(e,t){const r=new DOMParser().parseFromString(e,"text/html");if(r.querySelector("video,audio,iframe,object,embed"))throw new Error("小红书写长文只接文字和正文图片;独立视频请使用 publish_post");r.querySelectorAll("script,style").forEach(n=>n.remove());const i=r.body.textContent||"";if(i.length>1e4)throw new Error("小红书长文正文不能超过 10000 字,请让 Agent 缩短正文,未截断发布");const a=Array.from(r.querySelectorAll("img")).map((n,s)=>{const o=(n.getAttribute("src")||"").trim();let c=/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(o);try{const w=new URL(o);c||(c=["https:","http:"].includes(w.protocol)&&!w.username&&!w.password)}catch{}if(!c)throw new Error("小红书长文存在无法读取的图片,请让 Agent 提供本地图片或 HTTP(S) 图片地址");const y=`image-${s+1}`,h=`WRITEDOCK_XHS_${t.replace(/-/g,"")}_${s+1}`;return n.replaceWith(r.createTextNode(h)),{id:y,source:o,marker:h}});if(!i.trim()&&!a.length)throw new Error("小红书长文正文不能为空");return{markup:r.body.innerHTML,text:i,images:a}}function Nr(e){const t=`writedock-xhs-${e.channel}`,r=O=>O.replace(/[\s\u200b-\u200d\ufeff]/g,""),i=O=>typeof O=="string"?JSON.parse(O):O,a=[],n=O=>{a.includes(O)||a.push(O)},s=O=>Array.isArray(O)?O.length>0:O&&typeof O=="object"?Object.keys(O).length>0:!!O,o=(O,G)=>{try{return i(O)}catch{n(`无法解析小红书${G},已依据提交前的页面核对放行`);return}},c=new Set,y=new Set,h=new Set,w=new Map;let m=!1,p=!1,u=!1,g=!1,D=!1,A=0,b,d=!1,f=0,l;const _=O=>{if(typeof O!="string")return"";if(/^spectrum\/[A-Za-z0-9_/-]{1,480}$/.test(O))return O;try{const G=new URL(O);return G.protocol==="https:"&&/(?:^|\.)(?:xhscdn|xiaohongshu)\.com$/.test(G.hostname)&&/^\/spectrum\/[A-Za-z0-9_/-]{1,480}$/.test(G.pathname)?G.pathname.slice(1):""}catch{return""}},k=O=>{const G=JSON.stringify({...O,jobId:e.id});try{sessionStorage.setItem(t,G)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:G}))},I=()=>{u||k({phase:"state",uploads:y.size,layoutReady:D,renderedCount:A,firstFrameReady:d,renderUploads:[...h].filter(O=>y.has(O)).length})},E=O=>{u||(u=!0,k({phase:"result",...a.length?{warnings:a}:{},...O}))},v=(O,G)=>E({success:!1,publicationState:"needs_user_action",manualReason:O,message:G}),R=(O,G="publication_settings")=>{throw v(G,`${O}请在已打开的原投稿页核对并手动发布,Agent 不要重新提交。`),new Error("WriteDock 已停止小红书自动提交")},U=(O,G)=>{try{const T=new URL(G,location.href),F=O.toUpperCase();if(["https://creator.xiaohongshu.com","https://edith.xiaohongshu.com"].includes(T.origin)){if(F==="GET"&&T.pathname==="/api/media/v1/upload/creator/permit")return{operation:"permit",url:T};if(F==="GET"&&T.pathname==="/web_api/sns/capa/postgw/query_transcode")return{operation:"transcode",url:T};if(F==="POST"&&T.pathname==="/web_api/sns/v2/note")return{operation:"publish",url:T};if(F==="POST"&&/\/web_api\/sns\/v\d+\/note(?:\/|$)/.test(T.pathname))return{operation:"other_publish",url:T};if(F==="POST"&&T.pathname==="/web_api/sns/v6/creator/long_text/template/rec")return{operation:"layout",url:T};if(F==="POST"&&T.pathname==="/web_api/sns/v6/creator/long_text/template/preview")return{operation:"preview",url:T};if(F==="POST"&&T.pathname==="/web_api/sns/v6/creator/long_text/article/images")return{operation:"render",url:T}}if(T.protocol==="https:"&&/^ros-upload(?:-[a-z0-9]+)*\.(?:xhscdn|xiaohongshu)\.com$/.test(T.hostname)&&_(T.href)){if(F==="PUT")return{operation:T.searchParams.has("uploadId")?"part":"upload",url:T};if(F==="POST"&&T.searchParams.has("uploads"))return{operation:"multipart",url:T};if(F==="POST"&&T.searchParams.has("uploadId"))return{operation:"complete",url:T}}}catch{}return null},B=O=>{const G=[],T=[];let F=!1;const K=J=>{var ne;if(!(!J||typeof J!="object")){if(Array.isArray(J)){J.forEach(K);return}if(J.type!=="articleTitle"){if(J.type==="text"&&typeof J.text=="string"&&G.push(J.text),J.type==="image"){const ce=(ne=J.attrs)==null?void 0:ne.imgs;if(!Array.isArray(ce)||!ce.length)n("小红书长文的图片节点结构与抓包时不同");else for(const fe of ce){const ue=_(fe.src);(!ue||!y.has(ue)||!(fe.width>0&&fe.height>0))&&n("小红书长文有图片未匹配本次观察到的上传记录"),T.push(ue)}}/video|audio|iframe|embed/i.test(String(J.type||""))&&(F=!0),Array.isArray(J.content)&&J.content.forEach(K)}}};return K(O),F?R("长文包含未接入的视频或嵌入内容,已停止排版和发布。"):G.length&&r(G.join(""))!==r(e.content)?R("长文正文与本次稿件不一致,已停止排版和发布。"):(!G.length&&r(e.content)&&n("小红书长文请求中未读到正文字段,已依据提交前的编辑器核对放行"),T.length&&T.length!==e.imageCount?R("长文插图数量与本次稿件不一致,已停止排版和发布。"):(!T.length&&e.imageCount&&n("小红书长文请求中未读到图片字段,已依据提交前的编辑器核对放行"),l!=null&&l.length&&T.length&&T.join("|")!==l.join("|")?R("长文排版前后的插图或顺序发生变化,已停止发布。"):T))},W=O=>r(O.replace(/\[话题\]#/g,"")),P=(O,G)=>{var ue,be,re,we,V,Q,he,pe,me,Ce,lt,Ze;if(!O)return;const T=O.operation;if(T==="other_publish")return R("页面尝试修改已有笔记或使用未接入的发布接口。");if(["layout","preview","render"].includes(T)){if(e.mode!=="article"||!g||u||Date.now()>=e.deadline)return R("小红书长文尚未完成核对,已停止排版提交。");const le=o(G,"长文排版参数");if(T==="layout"){typeof(le==null?void 0:le.title)=="string"&&r(le.title)!==r(e.title)&&n(`小红书长文排版请求的标题为「${le.title.slice(0,40)}」,与稿件不同`),typeof(le==null?void 0:le.title)!="string"&&n("小红书长文排版请求中未读到标题字段");const oe=o(le==null?void 0:le.content,"长文正文");oe!==void 0&&(l=B(oe))}else{const oe=o(le==null?void 0:le.article_content,"长文排版内容"),de=(be=(ue=oe==null?void 0:oe.config)==null?void 0:ue.cover)==null?void 0:be.titleText;if(typeof de=="string"&&r(de)!==r(e.title)&&n(`小红书长文封面标题为「${de.slice(0,40)}」,与稿件不同`),Array.isArray(oe==null?void 0:oe.cards)?l=B(oe.cards):n("小红书长文排版请求中未读到分页数据"),T==="render"){if(!D||A)return R("长文排版尚未完成或页面尝试重复生成,已停止发布。");Number.isSafeInteger(le==null?void 0:le.album_id)&&le.album_id>0?b=le.album_id:n("小红书长文生成请求中未读到有效的 album_id")}}return}if(T!=="publish")return;if(e.rehearsal)return R("演练不提交发布,已拦截小红书发布请求。");if(u||!m||p||Date.now()>=e.deadline)return R("稿件尚未核对完成或页面尝试重复发送,已停止提交。");const F=o(G,"发布请求"),K=F==null?void 0:F.common;if(!K||typeof K!="object"){n("小红书发布请求结构与抓包时不同,已依据提交前的页面核对放行"),p=!0,m=!1,k({phase:"request"});return}const J=o(K.business_binds,"发布设置"),ne=o((re=K.capa_trace_info)==null?void 0:re.contextJson,"排版记录"),ce=K.privacy_info;if(K.note_id)return R("发布请求指向已有笔记。");if(typeof K.title=="string"&&r(K.title)!==r(e.title))return R(`发布请求的标题「${K.title.slice(0,40)}」与本次稿件不一致。`);if((ce==null?void 0:ce.type)!==void 0&&ce.type!==0||s(ce==null?void 0:ce.user_ids)||s(K.ats)||s(K.biz_relations)||s(K.goods_info))return R("公开范围、提及用户或商业关联需要人工核对。");if(s(J==null?void 0:J.notePostTiming)||s(J==null?void 0:J.noteOrderBind)||s((we=J==null?void 0:J.noteCollectionBind)==null?void 0:we.id)||s((V=J==null?void 0:J.noteSketchCollectionBind)==null?void 0:V.id)||s(J==null?void 0:J.optionRelationList))return R("定时、合集或内容声明需要人工核对。");const fe=K.hash_tag;if(Array.isArray(fe)&&fe.length&&(fe.length!==e.tags.length||fe.some(le=>!e.tags.includes((le==null?void 0:le.name)||(le==null?void 0:le.topic_name)))))return R("发布话题与 Agent 提供的话题不一致。");if(K.type!==(e.mode==="video"?"video":"normal")&&n(`小红书笔记 type=${String(K.type)},与抓包时不同`),((ce==null?void 0:ce.op_type)!==1||(ce==null?void 0:ce.type)===void 0)&&n("小红书公开范围字段与抓包时不同"),((J==null?void 0:J.version)!==1||(J==null?void 0:J.noteId)!==0||(J==null?void 0:J.bizType)!==0)&&n("小红书 business_binds 的版本或类型与抓包时不同"),((Q=J==null?void 0:J.interactionPermissionBind)==null?void 0:Q.commentPermission)!==0&&n("小红书评论权限字段与抓包时不同"),typeof K.title!="string"&&n("小红书发布请求中未读到标题字段"),e.mode==="article"){const le=(he=F.image_info)==null?void 0:he.images,oe=ne==null?void 0:ne.longTextToImage,de=Array.isArray(le)?le.map(Ke=>Ke.file_id):[];if(!A)return R("长文分页图片尚未生成。");if(de.length&&de.length!==A)return R("最终笔记的图片数量与本次排版结果不一致。");de.length||n("小红书发布请求中未读到长文图片字段"),de.some(Ke=>typeof Ke!="string"||!h.has(Ke)||!y.has(Ke))&&n("小红书长文图片未匹配本次观察到的上传记录"),((oe==null?void 0:oe.albumId)!==b||!Array.isArray(oe==null?void 0:oe.imageFileIds)||oe.imageFileIds.join("|")!==de.join("|"))&&n("小红书长文排版记录与抓包时不同"),(K.desc!==""||F.video_info!=null)&&n("小红书长文的 desc 或 video_info 与抓包时不同")}else{const le=[e.content,...e.tags.map(oe=>`#${oe}`)].filter(Boolean).join(" ");if(typeof K.desc=="string"&&W(K.desc)!==r(le))return R("正文或话题与本次任务不一致。");if(typeof K.desc!="string"&&n("小红书发布请求中未读到正文字段"),ne!=null&&ne.longTextToImage&&n("小红书普通笔记请求带有长文排版记录"),e.mode==="image"){const oe=(pe=F.image_info)==null?void 0:pe.images;if(Array.isArray(oe)&&oe.length!==e.imageCount)return R("图文图片数量与本次投稿不一致。");Array.isArray(oe)?oe.some(de=>!c.has(de.file_id)||!y.has(de.file_id)||!(de.width>0&&de.height>0))&&n("小红书图片未匹配本次观察到的上传记录"):n("小红书发布请求中未读到图片字段"),F.video_info!=null&&n("小红书图文请求带有 video_info")}else{const oe=F.video_info,de=oe==null?void 0:oe.cover;if(!oe)n("小红书发布请求中未读到视频字段");else{if((!c.has(oe.file_id)||!y.has(oe.file_id))&&n("小红书视频未匹配本次观察到的上传记录"),(oe.file_id!==oe.fileid||!(oe.format_width>0&&oe.format_height>0)||((me=oe.segments)==null?void 0:me.count)!==1||((Ce=oe.segments)==null?void 0:Ce.need_slice)!==!1)&&n("小红书视频分段字段与抓包时不同"),s(oe.timelines)&&n("小红书视频带有时间线设置"),e.explicitCover&&((lt=de==null?void 0:de.frame)==null?void 0:lt.is_upload)===!1)return R("显式提供的视频封面尚未应用。","cover_required");if(!e.explicitCover&&((Ze=de==null?void 0:de.frame)==null?void 0:Ze.is_upload)===!0)return R("页面使用了非第一帧的上传封面,与本次任务不一致。","cover_required");de!=null&&de.frame||n("小红书发布请求中未读到封面来源字段"),de&&(de.file_id!==de.fileid||!c.has(de.file_id)||!y.has(de.file_id)||!(de.width>0&&de.height>0))&&n("小红书视频封面未匹配本次观察到的上传记录")}}}p=!0,m=!1,k({phase:"request"})},N=(O,G,T)=>{var ne,ce,fe,ue,be;if(u)return;const{operation:F,url:K}=O,J=G>=200&&G<300;if(["upload","part","multipart","complete"].includes(F)){const re=_(K.href);if(!J||!c.has(re))return;if(F==="upload"&&y.add(re),F==="multipart"){const V=new DOMParser().parseFromString(String(T||""),"application/xml"),Q=(ne=V.querySelector("UploadId"))==null?void 0:ne.textContent;Q&&w.set(re,{uploadId:Q,parts:new Set})}const we=w.get(re);if(we&&we.uploadId===K.searchParams.get("uploadId")){if(F==="part"){const V=Number(K.searchParams.get("partNumber"));Number.isInteger(V)&&V>0&&we.parts.add(V)}F==="complete"&&we.parts.size&&!/<Error(?:\s|>)/i.test(String(T||""))&&y.add(re)}I();return}try{const re=i(T),we=String((re==null?void 0:re.msg)||(re==null?void 0:re.message)||"");if(/验证码|安全验证|验证后|完成验证|旋转.*(?:图片|验证)|转动.*图片|captcha/i.test(we)){v("captcha","小红书要求人工验证,请在已打开的原投稿页完成验证并手动发布,Agent 不要重发。");return}if(/原创声明|我已阅读|同意.*协议/.test(we)){v("agreement","小红书要求确认声明或协议,请在原投稿页阅读、自行决定并手动发布。");return}if(F==="publish"){const Q=(ce=re==null?void 0:re.data)==null?void 0:ce.id,he=p&&J&&(re==null?void 0:re.success)===!0&&(re==null?void 0:re.result)===0&&(re.code===void 0||re.code===0)&&typeof Q=="string"&&/^[a-f0-9]{24}$/.test(Q);E({success:he,publicationState:he?"submitted":"unknown",...he?{responseConfirmed:!0,postId:Q,postUrl:`https://www.xiaohongshu.com/explore/${Q}`}:{error:"小红书发布回执未能确认成功,请检查原稿件,不要自动重发。"}});return}if(!(J&&(re==null?void 0:re.success)===!0&&(re.code===void 0||re.code===0)))return;if(F==="permit"&&Array.isArray((fe=re.data)==null?void 0:fe.uploadTempPermits))for(const Q of re.data.uploadTempPermits)for(const he of Array.isArray(Q.fileIds)?Q.fileIds:[]){const pe=_(he);pe&&(c.add(pe),A&&h.add(pe))}if(F==="preview"&&(D=!0),F==="render"){const Q=(ue=re.data)==null?void 0:ue.article_images;if(!Array.isArray(Q)||!Q.length){n("小红书长文生成接口未返回分页图片字段"),I();return}Q.some(he=>{try{const pe=new URL(String(he));return pe.protocol!=="https:"||!/(?:^|\.)xhscdn\.com$/.test(pe.hostname)||!pe.pathname.startsWith("/mediaai/")||!!pe.username||!!pe.password}catch{return!0}})&&n("小红书长文分页图片地址与抓包时不同"),A=Q.length}F==="transcode"&&((be=re.data)==null?void 0:be.has_first_frame)===!0&&typeof re.data.first_frame_file_id=="string"&&(d=!0),I()}catch{F==="publish"&&E({success:!1,publicationState:"unknown",error:"小红书发布回执无法解析,请检查平台,不要自动重发。"})}},x=window.fetch,L=async function(O,G){const T=U((G==null?void 0:G.method)||(O instanceof Request?O.method:"GET"),O instanceof Request?O.url:String(O)),F=T&&["publish","other_publish","layout","preview","render"].includes(T.operation)?(G==null?void 0:G.body)??(O instanceof Request?await O.clone().text():void 0):void 0;P(T,F);try{const K=await x.call(window,O,G);return T&&!["upload","part","complete"].includes(T.operation)?N(T,K.status,await K.clone().text()):T&&N(T,K.status,T.operation==="complete"?await K.clone().text():""),K}catch(K){throw(T==null?void 0:T.operation)==="publish"&&E({success:!1,publicationState:"unknown",error:"小红书发布连接中断,请检查平台,不要自动重发。"}),K}},$=XMLHttpRequest.prototype,S=$.open,M=$.send,X=new WeakMap,j=function(O,G,...T){return X.set(this,U(O,String(G))),Reflect.apply(S,this,[O,G,...T])},H=function(O){const G=X.get(this)||null;return P(G,O),G&&this.addEventListener("loadend",()=>{try{const T=["upload","part"].includes(G.operation)?"":this.responseType==="json"?this.response:this.responseType==="document"?new XMLSerializer().serializeToString(this.responseXML):this.responseText;N(G,this.status,T)}catch{G.operation==="publish"&&N(G,this.status,void 0)}},{once:!0}),M.call(this,O)},ee=HTMLInputElement.prototype.click,Z=function(){if(!u&&f>Date.now()&&this.type==="file"&&/image|\.(?:png|jpe?g|webp)/i.test(this.accept)){f=0,this.setAttribute("data-writedock-xhs-input",e.channel),this.isConnected||(this.hidden=!0,this.setAttribute("data-writedock-xhs-transient",e.channel),document.body.append(this));return}return ee.call(this)},ie=()=>{!u&&!p&&(m=!0)},se=()=>{!u&&e.mode==="article"&&(g=!0)},Y=()=>{u||(f=Date.now()+1e4)},ge=()=>{f=0},C=()=>{e.rehearsal&&E({success:!1,publicationState:"rehearsed"})},z=()=>{window.fetch===L&&(window.fetch=x),$.open===j&&($.open=S),$.send===H&&($.send=M),HTMLInputElement.prototype.click===Z&&(HTMLInputElement.prototype.click=ee),clearTimeout(q),window.removeEventListener(`${t}:arm`,ie),window.removeEventListener(`${t}:layout`,se),window.removeEventListener(`${t}:rehearsed`,C),window.removeEventListener(`${t}:capture-image`,Y),window.removeEventListener(`${t}:release-image`,ge),window.removeEventListener(`${t}:read`,I),window.removeEventListener(`${t}:stop`,z),document.querySelectorAll(`[data-writedock-xhs-transient="${e.channel}"]`).forEach(O=>O.remove())};window.fetch=L,$.open=j,$.send=H,HTMLInputElement.prototype.click=Z,window.addEventListener(`${t}:arm`,ie),window.addEventListener(`${t}:layout`,se),window.addEventListener(`${t}:rehearsed`,C),window.addEventListener(`${t}:capture-image`,Y),window.addEventListener(`${t}:release-image`,ge),window.addEventListener(`${t}:read`,I),window.addEventListener(`${t}:stop`,z,{once:!0});const q=setTimeout(z,Math.max(1,e.deadline-Date.now()));return{observing:!0}}function zr(e){const t=`writedock-xhs-${e.channel}`;let r=!1,i=!1,a=!1,n=!1,s=0,o=!1,c=0,y=0,h=!1;const w=C=>C.replace(/[\s\u200b-\u200d\ufeff]/g,""),m=C=>new Promise(z=>setTimeout(z,C)),p=async(C,z={})=>{const q=await chrome.runtime.sendMessage({type:C,jobId:e.id,jobSecret:e.secret,...z});if(!q||q.error)throw new Error((q==null?void 0:q.error)||"扩展后台已断开,请检查小红书,不要自动重发");return q.data},u=(C,z,q)=>p("XHS_PUBLISH_PROGRESS",{stage:C,current:z,total:q}),g=C=>C.getClientRects().length>0&&getComputedStyle(C).visibility!=="hidden",D=C=>g(C)&&!C.hasAttribute("disabled")&&C.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(C.className),A=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(D),b=()=>{window.removeEventListener(t,l),window.removeEventListener(`${t}:cancel`,d),window.dispatchEvent(new Event(`${t}:stop`))},d=()=>{r=!0,b()},f=async C=>{r||i||(i=!0,b(),await p("XHS_PUBLISH_DONE",{result:C}))},l=C=>{try{const z=JSON.parse(C.detail);if(r||i||z.jobId!==e.id)return;z.phase==="state"&&(s=z.uploads,o=z.layoutReady,c=z.renderedCount,y=z.renderUploads,h=z.firstFrameReady),z.phase==="request"&&(n=!0,u("verifying").catch(d)),z.phase==="result"&&f(z).catch(d)}catch{}};window.addEventListener(t,l),window.addEventListener(`${t}:cancel`,d,{once:!0});function _(C,z){throw Object.assign(new Error(z),{manualReason:C})}const k=()=>{if(r||i)throw new Error("本次小红书自动投稿已结束");if(Date.now()>=e.deadline)throw new Error("小红书投稿等待超时,请检查原稿件,不要自动重发");if(location.origin!=="https://creator.xiaohongshu.com"||/\/(?:login|passport)(?:\/|$)/.test(location.pathname))throw new Error("请先在当前浏览器完成小红书创作者后台登录");Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="verify"],.geetest_panel,.yidun_panel,.captcha-container,.red-captcha-container')).some(g)&&_("captcha","小红书要求人工验证,请切换到已打开的原投稿页完成验证并手动发布,Agent 不要重发。");const C=Array.from(document.querySelectorAll('[role="alert"],[role="dialog"],.el-message,.el-dialog,.d-message,.d-modal,.toast,.message-box')).filter(g).map(q=>{var O;return((O=q.textContent)==null?void 0:O.trim())||""}).filter(q=>q.length<1500);C.some(q=>/验证码|安全验证|拖动.*(?:图片|滑块)|旋转.*图片|转动.*图片/.test(q))&&_("captcha","请在已打开的小红书原投稿页完成人工验证并手动发布,Agent 不要重发。"),C.some(q=>/我已阅读|我同意|原创声明|同意.*协议|确认.*声明/.test(q))&&_("agreement","小红书要求确认内容声明或协议,请在原投稿页阅读、自行决定并手动发布。"),C.some(q=>/请选择封面|请设置封面|封面不能为空/.test(q))&&_("cover_required","小红书要求补充封面,请在原投稿页设置并手动发布。"),C.some(q=>/请选择|请设置|实名认证|绑定手机|补充.*(?:声明|来源|信息)/.test(q))&&_("publication_settings","小红书要求补充发布设置或账号信息,请在原投稿页核对并手动发布。");const z=C.find(q=>/上传失败|发布失败|格式不支持|超出|超过|不能为空|图片过大/.test(q));if(z)throw new Error(z.slice(0,300))},I=async(C,z,q)=>{const O=Math.min(Date.now()+z,e.deadline);for(;Date.now()<O;){k();const G=C();if(G)return G;await m(300)}throw new Error(q)},E=()=>window.dispatchEvent(new Event(`${t}:read`)),v=()=>Array.from(document.querySelectorAll('input[placeholder*="标题"],textarea[placeholder*="标题"],[contenteditable="true"][data-placeholder*="标题"]')).find(g),R=()=>Array.from(document.querySelectorAll('.ProseMirror[contenteditable="true"],div[contenteditable="true"]')).find(C=>g(C)&&C!==v()&&!C.closest('[class*="title-input"],[class*="titleInput"]')),U=C=>C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement?C.value:C.textContent||"",B=C=>{C.focus();const z=document.createRange();z.selectNodeContents(C);const q=getSelection();q==null||q.removeAllRanges(),q==null||q.addRange(z)},W=(C,z,q)=>{const O=new DataTransfer;O.setData("text/plain",z),q!==void 0&&O.setData("text/html",q),C.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:O}))},P=C=>{var z,q;if(C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement){if(C.maxLength>0&&e.title.length>C.maxLength)throw new Error(`小红书当前标题最多 ${C.maxLength} 字,未截断发布`);(q=(z=Object.getOwnPropertyDescriptor(C instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype,"value"))==null?void 0:z.set)==null||q.call(C,e.title),C.dispatchEvent(new Event("input",{bubbles:!0})),C.dispatchEvent(new Event("change",{bubbles:!0}))}else B(C),W(C,e.title);if(U(C)!==e.title)throw new Error("标题未能完整写入小红书编辑器,未提交发布")},N=(C,z)=>!C.accept||C.accept.toLowerCase().split(",").map(q=>q.trim()).some(q=>q==="*/*"||q===z.type||q===`${z.type.split("/")[0]}/*`||q==="image/jpg"&&z.type==="image/jpeg"||q.startsWith(".")&&z.name.toLowerCase().endsWith(q)),x=async C=>{const z=[];await u("transferring_media",0,C.size);for(let q=0;q<C.size;q+=1024*1024){k();const O=Math.min(1024*1024,C.size-q),G=await p("XHS_READ_ASSET",{assetId:C.id,offset:q,length:O}),T=Uint8Array.from(atob(G.base64),F=>F.charCodeAt(0));if(T.length!==O)throw new Error("小红书素材传输不完整,已停止投稿");z.push(T.buffer),(q%(8*1024*1024)===0||q+O===C.size)&&await u("transferring_media",q+O,C.size)}return new File(z,C.name,{type:C.type})},L=(C,z)=>{if(k(),!C.multiple&&z.length>1)throw new Error("当前小红书上传控件不接受多张图片,未丢弃图片后继续发布");if(z.some(O=>!N(C,O)))throw new Error("小红书当前上传控件不接受此素材格式");const q=new DataTransfer;z.forEach(O=>q.items.add(O)),C.files=q.files,C.dispatchEvent(new Event("change",{bubbles:!0}))},$=["图片","插入图片","添加图片"],S=()=>Array.from(document.querySelectorAll('button,[role="button"],[title],[aria-label],[data-tooltip],.toolbar-item')).find(C=>{var z;return D(C)&&$.includes(C.getAttribute("title")||C.getAttribute("aria-label")||C.getAttribute("data-tooltip")||((z=C.textContent)==null?void 0:z.trim())||"")});let M;const X=async C=>{const z=()=>Array.from(document.querySelectorAll('.menu-tooltip,[role="tooltip"],.d-popover-tooltip')).filter(g),q=new Set(z());for(const F of[C,C.parentElement].filter(Boolean))F.dispatchEvent(new MouseEvent("mouseenter")),F.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0}));await m(250);const O=z(),G=O.filter(F=>!q.has(F)),T=(G.length?G:O.slice(-1)).map(F=>{var K;return((K=F.textContent)==null?void 0:K.trim())||""}).join("");for(const F of[C,C.parentElement].filter(Boolean))F.dispatchEvent(new MouseEvent("mouseleave")),F.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0}));return await m(150),T},j=async()=>{const C=Math.min(Date.now()+1e4,e.deadline);for(;Date.now()<C;){k();const z=S();if(z)return z;if(M!=null&&M.isConnected&&D(M))return M;for(const q of Array.from(document.querySelectorAll(".menu-items-container .menu-item,.menu-items-container button")).filter(D))if($.includes(await X(q)))return M=q,q;await m(500)}throw new Error("未找到小红书长文的原生插图按钮,未提交发布")},H=async C=>{const z=new Set(document.querySelectorAll('input[type="file"]'));document.querySelectorAll(`[data-writedock-xhs-input="${e.channel}"]`).forEach(q=>q.removeAttribute("data-writedock-xhs-input")),window.dispatchEvent(new Event(`${t}:capture-image`)),k(),C.click();try{return await I(()=>document.querySelector(`input[data-writedock-xhs-input="${e.channel}"]`)||Array.from(document.querySelectorAll('input[type="file"]')).find(q=>/image|\.(?:png|jpe?g|webp)/i.test(q.accept)&&(!z.has(q)||!!q.closest('[role="dialog"],.el-dialog,.d-modal'))),1e4,"未找到小红书原生图片上传控件,请在原稿件页处理,未提交发布")}finally{window.dispatchEvent(new Event(`${t}:release-image`))}},ee=C=>Array.from(document.querySelectorAll('button,[role="button"],[role="tab"],a,div,span')).filter(z=>{var q;return D(z)&&C.includes(((q=z.textContent)==null?void 0:q.trim())||"")}).find(z=>!Array.from(z.children).some(q=>{var O;return C.includes(((O=q.textContent)==null?void 0:O.trim())||"")})),Z=C=>{const z=ee(C);return z?z.closest('button,[role="button"]')||z:void 0},ie=async()=>{const C=Math.min(Date.now()+45e3,e.deadline);let z=!1,q=!1;for(;Date.now()<C;){if(k(),v()&&R())return;const O=Z(["新的创作","新建长文","开始创作"]);if(O&&!q){q=!0,O.click(),await m(1500);continue}if(!O&&!z){const G=Z(["写长文"]);if(G){z=!0,G.click(),await m(1e3);continue}}await m(500)}throw new Error(q?"已点击「新的创作」,但小红书长文编辑器未出现,请确认账号已开通长文":"未找到小红书「写长文 → 新的创作」入口,请确认已登录创作者后台且账号可发长文")},se=async()=>{var K;const C=e.article;await u("preparing_article"),await ie();const z=await I(v,45e3,"未找到小红书长文标题输入框,请确认已登录创作者后台"),q=await I(R,3e4,"未找到小红书长文正文编辑器");(w(U(z))||w(q.textContent||"")||q.querySelector("img"))&&_("publication_settings","小红书长文编辑器已有内容,未覆盖原稿,请在当前页面自行核对。");const O=new DOMParser().parseFromString(C.markup,"text/html").body.textContent||"";P(z),B(q),W(q,O,C.markup),await I(()=>C.images.every(J=>{var ne;return((ne=q.textContent)==null?void 0:ne.split(J.marker).length)===2})&&w(q.textContent||"")===w(O),1e4,"小红书长文未能完整写入,已停止发布");for(let J=0;J<C.images.length;J++){const ne=C.images[J],ce=await p("XHS_READ_ARTICLE_IMAGE",{imageId:ne.id}),fe=Uint8Array.from(atob(ce.base64),he=>he.charCodeAt(0)),ue={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[ce.type];if(!ue||!fe.length)throw new Error("小红书长文图片读取失败");k(),q.focus();const be=document.createTreeWalker(q,NodeFilter.SHOW_TEXT);let re,we=!1;for(;re=be.nextNode();){const he=(re.textContent||"").indexOf(ne.marker);if(he<0)continue;const pe=document.createRange();pe.setStart(re,he),pe.setEnd(re,he+ne.marker.length);const me=getSelection();me==null||me.removeAllRanges(),me==null||me.addRange(pe),we=!0;break}if(!we)throw new Error("无法定位长文插图位置,未提交发布");const V=await j();if(!document.execCommand("delete")||(K=q.textContent)!=null&&K.includes(ne.marker))throw new Error("无法替换长文插图位置,未提交发布");const Q=await H(V);L(Q,[new File([fe],`${ne.id}.${ue}`,{type:ce.type})]),await u("uploading_images",J,C.images.length),await I(()=>(E(),s>=J+1&&q.querySelectorAll("img").length===J+1),3*6e4,"小红书长文插图未完整上传或插入,已停止排版"),Q.getAttribute("data-writedock-xhs-transient")===e.channel&&Q.remove(),await u("uploading_images",J+1,C.images.length)}if(w(q.textContent||"")!==w(e.content)||C.images.some(J=>{var ne;return(ne=q.textContent)==null?void 0:ne.includes(J.marker)})||q.querySelectorAll("img").length!==e.imageCount||U(z)!==e.title)throw new Error("小红书长文正文或插图不完整,已停止排版");const G=await I(()=>A().find(J=>{var ne;return["一键排版","自动排版"].includes(((ne=J.textContent)==null?void 0:ne.trim())||"")}),3e4,"未找到小红书「一键排版」按钮");window.dispatchEvent(new Event(`${t}:layout`)),k(),G.click(),await I(()=>(E(),o),2*6e4,"小红书长文自动排版未完成,未提交发布");const T=await I(()=>A().find(J=>{var ne;return((ne=J.textContent)==null?void 0:ne.trim())==="下一步"}),3e4,"未找到小红书排版后的「下一步」按钮");k(),T.click(),await I(()=>(E(),c>0&&y>=c),5*6e4,"小红书长文分页图片未完整生成或上传,未提交发布");const F=await I(v,3e4,"小红书长文未进入最终发布页");if(U(F)||P(F),U(F)!==e.title)throw new Error("小红书长文排版后的标题发生变化,已停止发布")},Y=async()=>{var fe;const C=e.post,z=await I(()=>Array.from(document.querySelectorAll('input[type="file"]')).find(ue=>e.mode==="image"?/image|\.(?:png|jpe?g|webp)/i.test(ue.accept):/video|\.(?:mp4|mov|m4v|webm)/i.test(ue.accept)),6e4,"未找到对应的小红书图文或视频上传入口,请确认创作者后台已登录"),q=v(),O=R();(q&&w(U(q))||w((O==null?void 0:O.textContent)||"")||O!=null&&O.querySelector("img"))&&_("publication_settings","小红书发布页已有未发内容,未追加素材或覆盖原稿,请在当前页面自行核对。");const G=[];for(const ue of e.mode==="image"?C.images:[C.video])G.push(await x(ue));L(z,G),await u("uploading_media");const T=await I(v,3*6e4,"上传后未找到小红书标题输入框,请检查素材处理状态"),F=await I(R,3e4,"未找到小红书正文输入区"),K=U(T).trim(),J=(fe=C.video)==null?void 0:fe.name,ne=e.mode==="video"&&J&&[J,J.replace(/\.[^.]+$/,"")].includes(K);(w(K)&&!ne||w(F.textContent||""))&&_("publication_settings","小红书发布页已有文案,未覆盖原稿,请在当前页面自行核对。"),P(T);const ce=[e.content,...e.tags.map(ue=>`#${ue}`)].filter(Boolean).join(`
42
- `);if(ce&&(B(F),W(F,ce),await m(300),w(F.textContent||"")||(B(F),document.execCommand("insertText",!1,ce)),await I(()=>w(F.textContent||"")===w(ce),1e4,"小红书正文或话题未能完整写入,已停止发布"),F.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0}))),C.cover){const ue=await I(()=>document.querySelector("div.noCover.uploadCover")||A().find(V=>{var Q;return/^(?:设置封面|编辑封面|修改封面)$/.test(((Q=V.textContent)==null?void 0:Q.trim())||"")}),12e4,"未找到小红书视频封面入口"),be=await x(C.cover),re=await H(ue);L(re,[be]),await u("uploading_media");const we=await I(()=>A().find(V=>{var Q;return/^(?:确定|完成)$/.test(((Q=V.textContent)==null?void 0:Q.trim())||"")&&!!V.closest('[role="dialog"],.el-dialog,.d-modal')}),3e4,"请在原投稿页完成视频封面设置,未提交发布");k(),we.click()}if(await I(()=>(E(),e.mode==="image"?s>=e.imageCount:h&&s>=2),15*6e4,"小红书素材上传、转码或第一帧封面尚未就绪,未提交发布"),U(T)!==e.title||w(F.textContent||"")!==w(ce))throw new Error("小红书标题或正文发生变化,已停止发布")},ge=async()=>{await u("checking_auth"),e.mode==="article"?await se():await Y(),await I(()=>!/笔记图片生成中/.test(document.body.innerText),3*6e4,"小红书笔记图片仍在生成,未提交发布");const C=()=>{var T,F,K;for(const J of Array.from(document.querySelectorAll("xhs-publish-btn"))){if(J.getAttribute("submit-disabled")==="true"||J.getAttribute("submit-loading")==="true")continue;const ne=(F=(T=chrome.dom)==null?void 0:T.openOrClosedShadowRoot)==null?void 0:F.call(T,J),ce=((K=J.getAttribute("submit-text"))==null?void 0:K.trim())||"发布",fe=Array.from((ne==null?void 0:ne.querySelectorAll("*"))||[]).find(be=>{var re;return((re=be.textContent)==null?void 0:re.trim())===ce&&!Array.from(be.children).some(we=>{var V;return((V=we.textContent)==null?void 0:V.trim())===ce})}),ue=(fe==null?void 0:fe.closest('button,[role="button"]'))||fe;if(ue&&D(ue))return ue}},z=await I(()=>C()||A().find(T=>{var F;return/^(?:发布|立即发布)$/.test(((F=T.textContent)==null?void 0:F.trim())||"")}),6e4,"小红书发布按钮尚不可用,请检查素材或账号要求");if(e.rehearsal){k(),window.dispatchEvent(new Event(`${t}:rehearsed`)),await m(1e3),!i&&!r&&await f({success:!1,publicationState:"rehearsed"});return}const q=new Set(A());if(await u("publishing"),k(),!z.isConnected||!D(z))throw new Error("小红书发布控件发生变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,z.click();const O=Math.min(Date.now()+12e4,e.deadline);let G=!1;for(;!r&&!i&&Date.now()<O;){if(k(),!n&&!G){const T=A().find(F=>{var K;return!q.has(F)&&/^(?:确认发布|确定发布)$/.test(((K=F.textContent)==null?void 0:K.trim())||"")&&!!F.closest('[role="dialog"],.el-dialog,.d-modal')});T&&(G=!0,T.click())}await m(300)}!r&&!i&&await f({success:!1,publicationState:"unknown",error:"已触发小红书发布,但没有取得匹配的成功回执,请检查平台,不要自动重发。"})};try{const C=sessionStorage.getItem(t);C&&l(new CustomEvent(t,{detail:C}))}catch{}return!r&&!i&&ge().catch(C=>{r||i||f(C!=null&&C.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:C.manualReason,message:C.message}:{success:!1,publicationState:a?"unknown":"failed",error:C instanceof Error?C.message:"小红书投稿失败"}).catch(d)}),{started:!0}}function Hr(){const e=window;if(e.__writedockNetworkTrail)return{installed:!1};const t=[];e.__writedockNetworkTrail=t;const r=h=>{try{const w=new URL(h,location.href);return/^(?:mon\.zijieapi|mcs\.snssdk|imapi\.douyin|t2\.xiaohongshu|apm-fe\.xiaohongshu)\.com$/.test(w.hostname)?"":/^https?:$/.test(w.protocol)?w.origin+w.pathname:""}catch{return""}},i=(h,w)=>{const m=r(w);if(!m)return null;const p={method:h.toUpperCase(),url:m};return t.push(p),t.length>40&&t.shift(),p},a=(h,w)=>{if(!w||w.length>2e5)return;const m=JSON.parse(w);if(!m||typeof m!="object")return;for(const u of["code","errno","result","ok","success"])if(u in m){h.code=`${u}=${String(m[u])}`.slice(0,40);break}const p=m.message??m.msg??m.errmsg;typeof p=="string"&&p&&(h.message=p.slice(0,120))},n=window.fetch;window.fetch=function(h,w){const m=i((w==null?void 0:w.method)||(h instanceof Request?h.method:"GET"),h instanceof Request?h.url:String(h)),p=n.call(window,h,w);return p.then(u=>{m&&(m.status=u.status,/json/i.test(u.headers.get("content-type")||"")&&u.clone().text().then(g=>a(m,g)).catch(()=>{}))}).catch(()=>{m&&(m.message="连接中断")}),p};const s=XMLHttpRequest.prototype,o=s.open,c=s.send,y=new WeakMap;return s.open=function(h,w,...m){return y.set(this,{method:h,url:String(w)}),Reflect.apply(o,this,[h,w,...m])},s.send=function(h){const w=y.get(this),m=w?i(w.method,w.url):null;return m&&this.addEventListener("loadend",()=>{m.status=this.status;try{a(m,this.responseType==="json"?JSON.stringify(this.response):this.responseType===""||this.responseType==="text"?this.responseText:"")}catch{}},{once:!0}),c.call(this,h)},{installed:!0}}function Fr(){var m;const e=(p,u)=>(p||"").replace(/\s+/g," ").trim().slice(0,u),t=p=>p.getClientRects().length>0&&getComputedStyle(p).visibility!=="hidden",r=(p,u)=>[...new Set(p.filter(Boolean))].slice(0,u),i=p=>Array.from(document.querySelectorAll(p)).filter(t),a=(m=chrome.dom)==null?void 0:m.openOrClosedShadowRoot,n=Array.from(document.querySelectorAll("*")).filter(p=>p.tagName.includes("-")).slice(0,20).flatMap(p=>{const u=a==null?void 0:a(p);return u?Array.from(u.querySelectorAll('button,[role="button"]')).filter(t).map(g=>`${p.tagName.toLowerCase()}: ${e(g.textContent,20)}`):[]}),s=r([...n,...i('button,[role="button"],[role="tab"]').map(p=>e(p.textContent,30))],30),o=r(i('[role="alert"],[role="dialog"],[role="status"],[aria-modal="true"],[class*="toast"],[class*="message"],[class*="modal"],[class*="dialog"]').map(p=>e(p.textContent,200)),5),c=i('input:not([type="hidden"]):not([type="file"]):not([type="checkbox"]):not([type="radio"]),textarea,[contenteditable="true"]').slice(0,10).map(p=>{const u=p,g=u.value??p.textContent??"";return{tag:p.tagName.toLowerCase(),...u.placeholder?{placeholder:e(u.placeholder,40)}:{},...typeof p.className=="string"&&p.className?{className:e(p.className,60)}:{},textLength:g.replace(/[\s​-‍]/g,"").length}}),y=r(Array.from(document.querySelectorAll('input[type="file"]')).map(p=>e(p.accept,60)||"*"),6),h=p=>/^https?:$/.test(p.protocol)?p.origin+p.pathname:p.protocol,w=r(Array.from(document.querySelectorAll("iframe")).map(p=>{try{return h(new URL(p.src,location.href))}catch{return""}}),6);return window!==window.top&&!s.length&&!c.length&&!o.length?null:{url:h(location),title:e(document.title,80),buttons:s,notices:o,editors:c,fileInputs:y,iframes:w}}function Wr(){return window.__writedockNetworkTrail||[]}async function Je(e){await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:Hr}).catch(()=>{})}async function jr(e){const t=await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"ISOLATED",func:Fr}),r=await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:Wr}).catch(()=>[]);return{capturedAt:Date.now(),frames:t.map(i=>i.result).filter(i=>!!i).slice(0,6),network:r.flatMap(i=>i.result||[]).slice(-40)}}async function Jr(e){const t=new Promise(r=>setTimeout(()=>r({capturedAt:Date.now()}),3e3));return Promise.race([jr(e).catch(()=>({capturedAt:Date.now(),tabClosed:!0})),t])}async function Ae(e,t,r){const i=Array.isArray(r)?r.filter(a=>typeof a=="string").map(a=>a.slice(0,200)).slice(0,20):[];return{...t,...i.length?{warnings:i}:{},...t.success?{}:{diagnostics:await Jr(e)}}}function Ge(e,t){return{platform:e,success:!1,draftOnly:!1,publicationState:"rehearsed",postUrl:t,timestamp:Date.now(),message:"演练已走到点击发布之前并停下,未提交发布。稿件留在已打开的标签页,确认后关闭即可;图片可能已上传到平台,部分平台会留下中间草稿。最终发布请求和平台回执只有真实发布时才能核对。"}}function Gr(e){var t,r,i;return((t=e.latest)==null?void 0:t.kind)==="success"?"success":((r=e.latest)==null?void 0:r.kind)==="failure"||((i=e.latest)==null?void 0:i.kind)==="unclear"?"unknown":e.now>=e.deadline?e.requestPending?"unknown":"hand_off":"wait"}const Ve=e=>e.publicationState==="needs_user_action"&&e.manualReason==="captcha";function Vr(e){const t=window;if(t[e.key])return{watching:!0};const r={requests:0,pending:0,rejected:!1};t[e.key]=r;const i={bilibili:[/^https:\/\/api\.bilibili\.com$/,"/x/dynamic/feed/create/opus"],baijiahao:[/^https:\/\/baijiahao\.baidu\.com$/,"/pcui/article/publish"],xiaohongshu:[/^https:\/\/(?:edith|creator)\.xiaohongshu\.com$/,"/web_api/sns/v2/note"],weibo:[/^https:\/\/weibo\.com$/,"/ajax/statuses/update"],"weibo-article":[/^https:\/\/card\.weibo\.com$/,"/article/v5/aj/editor/draft/publish"],zhihu:[/^https:\/\/www\.zhihu\.com$/,"/api/v4/content/publish"]},a=(p,u)=>{try{const g=new URL(u,location.href),[D,A]=i[e.platform];return p.toUpperCase()==="POST"&&D.test(g.origin)&&g.pathname===A}catch{return!1}},n=p=>{if(typeof p!="string")return p;const u=p.trim(),g=/^[\w.$]+\s*\(([\s\S]*)\)\s*;?\s*$/.exec(u);return JSON.parse(g?g[1]:u)},s=(p,u)=>{var d,f,l,_,k,I,E,v,R,U,B,W;let g;try{g=n(u)}catch{return{kind:"unclear",message:"发布响应无法解析"}}const D=String((g==null?void 0:g.message)??(g==null?void 0:g.msg)??(g==null?void 0:g.errmsg)??"").slice(0,200);if(/验证码|安全验证|完成验证|验证后|captcha/i.test(D)||(g==null?void 0:g.code)===-352||(g==null?void 0:g.errno)===10000015||!!((d=g==null?void 0:g.data)!=null&&d.verify)||!!((f=g==null?void 0:g.data)!=null&&f.geetest))return{kind:"captcha",message:D};const b=p>=200&&p<300;switch(e.platform){case"bilibili":{const P=(l=g==null?void 0:g.data)==null?void 0:l.dyn_id_str;if(b&&(g==null?void 0:g.code)===0&&typeof P=="string"&&/^\d{1,24}$/.test(P))return{kind:"success",postId:P,postUrl:`https://www.bilibili.com/opus/${P}`};break}case"baijiahao":if(b&&(g==null?void 0:g.errno)===0&&(!e.articleId||((_=g==null?void 0:g.ret)==null?void 0:_.article_id)===e.articleId))return{kind:"success",postId:e.articleId,postUrl:`https://baijiahao.baidu.com/s?id=${e.articleId}`};break;case"xiaohongshu":{const P=(k=g==null?void 0:g.data)==null?void 0:k.id;if(b&&(g==null?void 0:g.success)===!0&&(g==null?void 0:g.result)===0&&typeof P=="string"&&/^[a-f0-9]{24}$/.test(P))return{kind:"success",postId:P,postUrl:`https://www.xiaohongshu.com/explore/${P}`};break}case"weibo":{if(b&&(g==null?void 0:g.ok)===1&&!g.error){const P=(I=g.data)==null?void 0:I.mblogid,N=String(((v=(E=g.data)==null?void 0:E.user)==null?void 0:v.idstr)??((U=(R=g.data)==null?void 0:R.user)==null?void 0:U.id)??"");return{kind:"success",...typeof((B=g.data)==null?void 0:B.idstr)=="string"?{postId:g.data.idstr}:{},postUrl:typeof P=="string"&&/^\d+$/.test(N)?`https://weibo.com/${N}/${P}`:"https://weibo.com"}}break}case"weibo-article":if(b&&(g==null?void 0:g.code)===1e5&&typeof((W=g.data)==null?void 0:W.url)=="string")return{kind:"success",postUrl:g.data.url};break;case"zhihu":if(b&&(g==null?void 0:g.code)===0)return{kind:"success"};break}return{kind:"failure",message:D||`发布结果未确认(HTTP ${p})`}},o=p=>{r.pending=Math.max(0,r.pending-1),r.latest=p,r.rejected=p.kind==="captcha"},c=window.fetch;window.fetch=function(p,u){const g=a((u==null?void 0:u.method)||(p instanceof Request?p.method:"GET"),p instanceof Request?p.url:String(p));g&&(r.requests++,r.pending++,r.latest=void 0,r.rejected=!1);const D=c.call(window,p,u);return g&&D.then(A=>A.clone().text().then(b=>o(s(A.status,b)))).catch(()=>o({kind:"unclear",message:"发布连接中断"})),D};const y=XMLHttpRequest.prototype,h=y.open,w=y.send,m=new WeakMap;return y.open=function(p,u,...g){return m.set(this,a(p,String(u))),Reflect.apply(h,this,[p,u,...g])},y.send=function(p){return m.get(this)&&(r.requests++,r.pending++,r.latest=void 0,r.rejected=!1,this.addEventListener("loadend",()=>{try{o(s(this.status,this.responseType==="json"?this.response:this.responseText))}catch{o({kind:"unclear",message:"发布响应无法读取"})}},{once:!0})),w.call(this,p)},{watching:!0}}function Xr(e){return window[e]||null}function Xe(e){const t=`__writedockVerification_${e.channel.replace(/-/g,"")}`,r=Date.now()+(e.timeoutMs??10*6e4),i={tabId:e.tabId,allFrames:!0};let a=!1;e.progress({stage:"waiting_verification",url:e.url,message:e.message});const n=c=>{clearInterval(o),c()},s=async()=>{var c;if(!a){a=!0;try{if(!e.isActive()){clearInterval(o);return}await chrome.tabs.get(e.tabId),await chrome.scripting.executeScript({target:i,world:"MAIN",func:Vr,args:[{key:t,platform:e.platform,articleId:e.articleId}]}).catch(()=>[]);const h=(await chrome.scripting.executeScript({target:i,world:"MAIN",func:Xr,args:[t]}).catch(()=>[])).map(p=>p.result).filter(p=>!!p),w=(c=h.find(p=>p.latest))==null?void 0:c.latest,m=Gr({now:Date.now(),deadline:r,requestPending:h.some(p=>p.pending>0),latest:w});m==="success"?n(()=>e.onReceipt({success:!0,publicationState:"submitted",responseConfirmed:!0,postId:w==null?void 0:w.postId,postUrl:w==null?void 0:w.postUrl})):m==="unknown"?n(()=>e.onReceipt({success:!1,publicationState:"unknown",error:`${(w==null?void 0:w.message)||"发布结果未确认"}。请检查平台,不要自动重发。`})):m==="hand_off"&&n(e.onHandOff)}catch{n(e.onHandOff)}finally{a=!1}}},o=setInterval(()=>{s()},2e3);s()}const Ie=new Map,vt=({id:e,name:t,type:r,size:i})=>({id:e,name:t,type:r,size:i}),ir=e=>{let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)},Zr=(e,t,r={})=>nr({mode:e.kind,post:Le(e)},t,r),Kr=(e,t,r,i={})=>nr({mode:"article",title:e,html:t},r,i);async function nr(e,t,r){const i=r.rehearsal===!0,a=crypto.randomUUID(),n=crypto.randomUUID(),s=crypto.randomUUID(),o=Date.now()+30*6e4,c=e.mode==="article"?e.title:e.post.title,y=`https://creator.xiaohongshu.com/publish/publish?target=${e.mode}&writedock_job=${a}`,h=await chrome.tabs.create({url:y,active:!0});if(!h.id)throw new Error("无法打开小红书发布页");const w=h.id;return new Promise(m=>{let p=!1;const u=(l,_=!1)=>{if(!Ie.has(a)||p&&!_&&!l.success)return;if(!_&&!i&&!p&&Ve(l)){p=!0,clearTimeout(A),Xe({tabId:w,platform:"xiaohongshu",channel:s,url:f.editUrl,message:"小红书要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>Ie.has(a),progress:t,onReceipt:R=>{f.attempted=!0,u(R,!0)},onHandOff:()=>u(l,!0)});return}Ie.delete(a),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),window.dispatchEvent(new Event(`${R}:stop`)),sessionStorage.removeItem(R)},args:[`writedock-xhs-${s}`]}).catch(()=>{});let k="";try{const R=new URL(l.postUrl||"");R.origin==="https://www.xiaohongshu.com"&&/^\/explore\/[a-f0-9]{24}$/.test(R.pathname)&&l.postId===R.pathname.split("/").pop()&&(k=R.href)}catch{}if(i&&l.publicationState==="rehearsed"){Ae(w,Ge("xiaohongshu",f.editUrl),l.warnings).then(m);return}const I=!i&&f.attempted&&l.success===!0&&l.publicationState==="submitted"&&l.responseConfirmed===!0&&!!k,E=l.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(l.manualReason||""),v=String(l.message||"请在已打开的小红书原投稿页核对内容、完成平台要求并手动发布,Agent 不要重新提交。").slice(0,1e3);Ae(w,{platform:"xiaohongshu",success:I,draftOnly:!1,publicationState:I?"submitted":E?"needs_user_action":f.attempted?"unknown":"failed",postUrl:I?k:f.editUrl,timestamp:Date.now(),...I?{postId:l.postId,message:"小红书发布接口已确认提交,展示状态以平台为准"}:E?{requiresUserAction:!0,userAction:{type:l.manualReason,url:f.editUrl,message:v},message:v}:{error:l.error||"小红书发布结果未确认,请检查平台,不要自动重发"}},l.warnings).then(m)},g=l=>{l===w&&u({error:"小红书投稿页已关闭,请先检查平台,不要自动重发"})},D=(l,_,k)=>{var I,E;l!==w||!Ie.has(a)||((I=k.url)!=null&&I.startsWith("https://creator.xiaohongshu.com/publish/publish")&&(f.editUrl=k.url),!(_.status!=="complete"||!f.attempted||!((E=k.url)!=null&&E.startsWith("https://creator.xiaohongshu.com/")))&&chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:v=>sessionStorage.getItem(v),args:[`writedock-xhs-${s}`]}).then(v=>{var B;const R=(B=v[0])==null?void 0:B.result;if(typeof R!="string"||!Ie.has(a))return;const U=JSON.parse(R);U.jobId===a&&U.phase==="result"&&u(U)}).catch(()=>{}))},A=setTimeout(()=>u({error:"等待小红书投稿超时,请检查原稿件,不要自动重发"}),30*6e4),b=e.mode==="article"?void 0:e.post,d=b?[...b.images,...b.video?[b.video]:[],...b.cover?[b.cover]:[]]:[],f={tabId:w,secret:n,channel:s,editUrl:y,attempted:!1,assets:new Map(d.map(l=>[l.id,l])),articleImages:new Map,progress:t,finish:u};Ie.set(a,f),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var U,B,W,P,N,x;const l=Date.now()+6e4;for(;Ie.has(a)&&Date.now()<l&&(await chrome.tabs.get(w)).status!=="complete";)await new Promise($=>setTimeout($,250));if(!Ie.has(a))return;const _=await chrome.tabs.get(w);if(_.status!=="complete"||!((U=_.url)!=null&&U.startsWith("https://creator.xiaohongshu.com/publish/publish")))throw new Error("小红书发布页未就绪,请先在当前浏览器完成创作者后台登录");let k;if(e.mode==="article"){if(k=(B=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:Br,args:[e.html,s]}))[0])==null?void 0:B.result,!k)throw new Error("小红书长文解析失败,未提交发布");f.articleImages=new Map(k.images.map($=>[$.id,$.source]))}const I={id:a,channel:s,deadline:o,mode:e.mode,title:c,content:(k==null?void 0:k.text)??(b==null?void 0:b.content)??"",tags:(b==null?void 0:b.tags)||[],imageCount:(k==null?void 0:k.images.length)??(b==null?void 0:b.images.length)??0,explicitCover:!!(b!=null&&b.cover),rehearsal:i};await Je(w);const E=await chrome.scripting.executeScript({target:{tabId:w},world:"MAIN",func:Nr,args:[I]});if(!Ie.has(a))return;if(!((P=(W=E[0])==null?void 0:W.result)!=null&&P.observing))throw new Error("无法观察小红书发布回执,已停止投稿");const v={...I,secret:n,...k?{article:{markup:k.markup,images:k.images.map(({id:L,marker:$})=>({id:L,marker:$}))}}:{},...b?{post:{images:b.images.map(vt),...b.video?{video:vt(b.video)}:{},...b.cover?{cover:vt(b.cover)}:{}}}:{}};if(!((x=(N=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:zr,args:[v]}))[0])==null?void 0:N.result)!=null&&x.started))throw new Error("无法启动小红书投稿脚本")})().catch(l=>u({error:l instanceof Error?l.message:"启动小红书投稿失败"}))})}async function Yr(e){if(!/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(e)&&!/^https?:\/\//i.test(e))throw new Error("长文图片地址不正确,请让 Agent 重新准备稿件");const t=await fetch(e,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(3e4)});if(!t.ok||!t.body)throw new Error("无法读取小红书长文图片,已停止投稿");const r=t.body.getReader(),i=[];let a=0;for(;;){const{done:y,value:h}=await r.read();if(y)break;if(a+=h.length,a>8*1024*1024)throw await r.cancel(),new Error("小红书长文单张图片不能超过 8 MB");i.push(h)}const n=new Uint8Array(a);let s=0;for(const y of i)n.set(y,s),s+=y.length;const o=String.fromCharCode(...n.subarray(0,12)),c=n[0]===137&&o.slice(1,4)==="PNG"?"image/png":n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":/^GIF8[79]a/.test(o)?"image/gif":o.startsWith("RIFF")&&o.slice(8,12)==="WEBP"?"image/webp":"";if(!c)throw new Error("小红书长文插图只接受 PNG、JPEG、GIF、WebP 图片");return{base64:ir(n),type:c}}async function Qr(e,t){var i,a;const r=Ie.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://creator.xiaohongshu.com/"))||e.jobSecret!==r.secret)throw new Error("小红书任务已结束或来源不匹配");if(e.type==="XHS_PUBLISH_PROGRESS"){if(!["checking_auth","preparing_article","uploading_images","transferring_media","uploading_media","publishing","verifying"].includes(String(e.stage)))throw new Error("小红书投稿阶段不正确");return["publishing","verifying"].includes(String(e.stage))&&(r.attempted=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="XHS_READ_ASSET"){const n=r.assets.get(String(e.assetId||""));if(!n)throw new Error("素材不属于本次小红书任务");return{base64:ir(await Ct(n,Number(e.offset),Number(e.length)))}}if(e.type==="XHS_READ_ARTICLE_IMAGE"){const n=r.articleImages.get(String(e.imageId||""));if(!n)throw new Error("插图不属于本次小红书长文");return Yr(n)}if(e.type==="XHS_PUBLISH_DONE")return r.finish(e.result||{error:"小红书没有返回投稿结果"}),!0;throw new Error("不支持的小红书页面操作")}const ke=new Map,He=e=>e==="weibo"?"https://weibo.com":"https://creator.douyin.com",ei=e=>He(e)+(e==="weibo"?"/":"/creator-micro/content/manage"),_t=({id:e,name:t,type:r,size:i})=>({id:e,name:t,type:r,size:i});function Fe(e,t,r=!1){if(e.watching&&!r&&!(t!=null&&t.success))return;if(!r&&!e.rehearsal&&!e.watching&&e.platform==="weibo"&&t&&Ve(t)){e.watching=!0,Xe({tabId:e.tabId,platform:"weibo",channel:e.channel,url:e.editUrl,message:"微博要求完成验证。请在已打开的页面完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>{var c;return((c=ke.get(e.id))==null?void 0:c.watching)===!0},progress:e.progress,onReceipt:c=>{e.attempted=!0,Fe(e,c,!0)},onHandOff:()=>Fe(e,t,!0)});return}const i=t!=null&&t.warnings?{warnings:t.warnings}:{};if(e.rehearsal&&(t==null?void 0:t.publicationState)==="rehearsed"){e.finish({...Ge(e.platform,e.editUrl),...i});return}const a=!e.rehearsal&&(t==null?void 0:t.success)===!0&&["submitted","published"].includes(t.publicationState||"")&&e.attempted&&(e.platform==="weibo"?t.responseConfirmed===!0:e.platform==="douyin"&&e.clicked&&t.pageConfirmed===!0),n=(t==null?void 0:t.publicationState)==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings","old_draft"].includes(t.manualReason||""),s=String((t==null?void 0:t.message)||"请在已打开的原投稿页完成设置或验证并手动发布,Agent 不要重发。").slice(0,1e3);let o=a?ei(e.platform):e.editUrl;try{const c=new URL((t==null?void 0:t.postUrl)||"");c.origin===He(e.platform)&&(o=c.href)}catch{}n&&(o=e.editUrl),e.finish({...i,platform:e.platform,success:a,draftOnly:!1,publicationState:a?t.publicationState:n?"needs_user_action":e.attempted?"unknown":"failed",postUrl:o,...a?{...typeof(t==null?void 0:t.postId)=="string"&&/^\d+$/.test(t.postId)?{postId:t.postId}:{},message:e.platform==="weibo"?"微博发布接口已确认提交,展示状态以平台为准":(t==null?void 0:t.message)||"平台已确认提交"}:n?{requiresUserAction:!0,userAction:{type:t.manualReason,url:o,message:s},message:s}:{error:(t==null?void 0:t.error)||"发布结果未确认,请检查作品管理,不要自动重复发布"},timestamp:Date.now()})}async function ti(e){await new Promise((t,r)=>{const i=s=>{clearTimeout(n),chrome.tabs.onUpdated.removeListener(a),s?r(s):t()},a=(s,o)=>{s===e&&o.status==="complete"&&i()},n=setTimeout(()=>i(new Error("创作者页面加载超时")),6e4);chrome.tabs.onUpdated.addListener(a),chrome.tabs.get(e).then(s=>{s.status==="complete"&&i()}).catch(s=>i(s))})}async function ri(e,t,r,i={}){const a=i.rehearsal===!0;if(!Rt(e))throw new Error("当前平台尚未接入图文或视频直发");const n=Le(t);mt(n,[e]);const s=e==="douyin"?n.kind==="video"?5:4:10;if(n.tags.length>s)throw new Error(`当前 ${e==="douyin"?"抖音":"小红书"} 适配最多接收 ${s} 个话题,请先减少话题`);if(e==="xiaohongshu")return Zr(n,r,i);const o=crypto.randomUUID(),c=crypto.randomUUID(),y=crypto.randomUUID(),h=`writedockDouyinRehearsalDraft:${n.kind}`,w=e==="douyin"?(await chrome.storage.local.get(h))[h]:void 0,m=i.discardOldDraft===!0||typeof w=="number"&&Date.now()-w<24*60*6e4;w!==void 0&&await chrome.storage.local.remove(h);const p=He(e)+(e==="weibo"?`${n.kind==="video"?"/upload/channel":"/"}?writedock_post=${o}`:`/creator-micro/content/upload?${n.kind==="image"?"default-tab=3&":""}writedock_post=${o}`),u=await chrome.tabs.create({url:p,active:!0});if(!u.id)throw new Error("无法打开创作者页面");const g=u.id,D=[...n.images,...n.video?[n.video]:[],...n.cover?[n.cover]:[]];return new Promise(A=>{const b=v=>{ke.has(o)&&(ke.delete(o),clearTimeout(k),e==="douyin"&&v.publicationState==="rehearsed"&&chrome.storage.local.set({[h]:Date.now()}).catch(()=>{}),chrome.tabs.onRemoved.removeListener(f),chrome.tabs.onUpdated.removeListener(l),e==="weibo"&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),window.dispatchEvent(new Event(`${R}:stop`)),sessionStorage.removeItem(R)},args:[`writedock-weibo-post-${y}`]}).catch(()=>{}),e==="douyin"&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),sessionStorage.removeItem(R)},args:[`writedock-douyin-${y}`]}).catch(()=>{}),Ae(g,v,v.warnings).then(A))},d=v=>{I.watching||b({platform:e,success:!1,draftOnly:!1,publicationState:I.attempted?"unknown":"failed",error:v,postUrl:I.editUrl,timestamp:Date.now()})},f=v=>{v===g&&d("投稿标签页已关闭,请检查平台结果后再决定是否重试")},l=(v,R,U)=>{if(v!==g||!ke.has(o)||!U.url)return;if(e==="weibo"){const P=new URL(U.url);if(P.origin==="https://security.weibo.com"&&/^\/(?:verify|captcha)(?:\/|$)/.test(P.pathname)){I.editUrl=P.href,Fe(I,{publicationState:"needs_user_action",manualReason:"captcha",message:"微博已进入人工验证页。请在当前标签页完成验证、核对内容并手动发布,Agent 不要重新提交。"});return}P.origin==="https://weibo.com"&&(I.editUrl=P.href,R.status==="complete"&&I.attempted&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:N=>sessionStorage.getItem(N),args:[`writedock-weibo-post-${y}`]}).then(N=>{var $;const x=($=N[0])==null?void 0:$.result;if(typeof x!="string"||!ke.has(o))return;const L=JSON.parse(x);L.phase==="result"&&Fe(I,L)}).catch(()=>{}));return}const B=new URL(U.url);if(B.origin!==He(e)||(/^\/creator-micro\/content\/(?:upload|publish)(?:\/|$)/.test(B.pathname)&&!B.pathname.endsWith("/success")&&(I.editUrl=B.href),!I.clicked||R.status!=="complete"))return;const W=/^\/creator-micro\/content\/manage(?:\/|$)|\/publish\/success(?:\/|$)/.test(B.pathname);chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:P=>sessionStorage.getItem(P),args:[`writedock-douyin-${y}`]}).then(P=>{var x;if(!ke.has(o))return;const N=(x=P[0])==null?void 0:x.result;if(typeof N=="string")try{const L=JSON.parse(N);if(L.jobId===o&&L.phase==="result"){Fe(I,L);return}}catch{}W&&d("抖音已进入作品管理,但未取得明确成功提示,请检查平台,不要自动重发")}).catch(()=>{W&&ke.has(o)&&d("抖音页面已跳转,发布结果未能确认,请检查平台,不要自动重发")})},_=Date.now()+18e5,k=setTimeout(()=>d("等待投稿结果超时,请检查作品管理,不要自动重复发布"),30*6e4),I={id:o,tabId:g,secret:c,platform:e,editUrl:p,rehearsal:a,channel:y,assets:new Map(D.map(v=>[v.id,v])),progress:r,attempted:!1,clicked:!1,finish:b};ke.set(o,I),chrome.tabs.onRemoved.addListener(f),chrome.tabs.onUpdated.addListener(l);const E={id:o,secret:c,platform:e,deadline:_,channel:y,rehearsal:a,discardDraft:m,post:{...n,images:n.images.map(_t),...n.video?{video:_t(n.video)}:{},...n.cover?{cover:_t(n.cover)}:{}}};ti(g).then(async()=>{var U,B,W,P,N,x,L;if(!ke.has(o))return;if(!((U=(await chrome.tabs.get(g)).url)!=null&&U.startsWith(`${He(e)}/`)))throw new Error("请在创作者后台完成登录后再投稿");if(await Je(g),e==="weibo"){const $=Or(n);if(!((W=(B=(await chrome.scripting.executeScript({target:{tabId:g},world:"MAIN",func:qr,args:[{channel:y,deadline:_,kind:n.kind,text:$,title:n.title,imageCount:n.images.length,creation:n.weiboVideoCreation,explicitCover:!!n.cover,rehearsal:a}]}))[0])==null?void 0:B.result)!=null&&W.observing))throw new Error("无法观察微博发布回执,已停止自动投稿");if(!((N=(P=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Mr,args:[{...E,channel:y,text:$}]}))[0])==null?void 0:P.result)!=null&&N.started))throw new Error("无法启动微博图文/视频投稿脚本");return}if(!((L=(x=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Pr,args:[E]}))[0])==null?void 0:x.result)!=null&&L.started))throw new Error("无法启动页面投稿脚本")}).catch(v=>d(v instanceof Error?v.message:"启动投稿失败"))})}async function ii(e,t){var i,a;const r=ke.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||e.jobSecret!==r.secret||!((a=t.url)!=null&&a.startsWith(`${He(r.platform)}/`)))throw new Error("页面投稿任务已结束或来源不匹配");if(e.type==="PAGE_PUBLISH_PROGRESS"){if(e.stage==="waiting_verification"&&r.platform==="douyin"&&r.clicked)return r.progress({stage:"waiting_verification",url:r.editUrl,message:"抖音要求短信验证。请在已打开的页面点“获取验证码”,填写手机收到的验证码后点“验证”,不要把验证码发给 Agent。如果验证后页面回到编辑状态,再点“发布”。结果会自动更新,不要重新提交。"}),!0;if(!["checking_auth","transferring_media","uploading_media","publishing","verifying"].includes(String(e.stage)))throw new Error("投稿阶段不正确");return e.stage==="publishing"&&(r.attempted=!0),e.stage==="verifying"&&(r.clicked=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="PAGE_PUBLISH_READ_ASSET"){const n=r.assets.get(String(e.assetId||"")),s=Number(e.offset),o=Number(e.length);if(!n||!Number.isSafeInteger(s)||!Number.isSafeInteger(o)||s<0||o<1||o>1024*1024||s+o>n.size)throw new Error("素材读取范围不正确");const c=await Ct(n,s,o);let y="";for(let h=0;h<c.length;h+=32768)y+=String.fromCharCode(...c.subarray(h,h+32768));return{base64:btoa(y)}}if(e.type==="PAGE_PUBLISH_DONE")return Fe(r,e.result),!0;throw new Error("不支持的页面投稿操作")}const ni={zhihu:100,baijiahao:64,weibo:32,xiaohongshu:64},zt=new Set(["zhihu","baijiahao","weibo","bilibili","xiaohongshu"]),Ht=new Set(["weibo","xiaohongshu","douyin"]),ai=new Set(["weixin","sohu"]),oi=new Set(["baijiahao","weibo"]),si={zhihu:"知乎",baijiahao:"百家号",weibo:"微博",bilibili:"B站",xiaohongshu:"小红书",douyin:"抖音",weixin:"公众号",sohu:"搜狐号"},ci=e=>{var t;return(t=/<img\b[^>]*\bsrc=["']([^"']+)["']/i.exec(e))==null?void 0:t[1]};function li(e){const{article:t,post:r}=e,i=e.modes&&typeof e.modes=="object"?e.modes:{};return e.platforms.map(a=>{var m,p;const n=si[a]||a,s=i[a],o=(u,g)=>({platform:a,mode:u,error:g});if(s!==void 0&&s!=="article"&&s!=="post")return o("article",`${n} 的 modes 只能是 article 或 post`);if(ai.has(a))return e.rehearsal?o("draft",`${n}只保存草稿,无需演练`):s==="post"?o("draft",`${n}目前只接文章草稿,不接图文或视频`):t?(m=t.videos)!=null&&m.length?o("draft",`${n}不接文章内嵌视频`):{platform:a,mode:"draft",...t.cover?{cover:t.cover}:{}}:o("draft",`${n}需要文章内容,本次只提供了图文或视频`);const c=s==="article"||s==="post"?s:Ht.has(a)&&(r||!zt.has(a))?"post":"article";if(c==="post"){if(!Ht.has(a))return o("post",`${n}不接图文或视频,请提供文章内容`);if(!r)return o("post",`${n}需要图文或视频素材,本次只提供了文章`);try{mt(r,[a])}catch(u){return o("post",u instanceof Error?u.message:`${n}不接受这份素材`)}return{platform:a,mode:c}}if(!zt.has(a))return o("article",`${n}不接文章,请提供图文或视频素材`);if(!t)return o("article",`${n}需要文章内容,本次只提供了图文或视频`);const y=ni[a];if(y&&t.title.length>y)return o("article",`${n}文章标题最多 ${y} 字,未截断发布,请缩短后单独提交`);if((p=t.videos)!=null&&p.length&&a!=="zhihu")return o("article",`${n}不接文章内嵌视频,请去掉视频后单独提交`);const h=[];let w=t.cover;if(w&&!oi.has(a)&&(h.push(`${n}不接独立封面,已忽略 cover`),w=void 0),a==="baijiahao"&&!w){if(w=ci(t.html||""),!w)return o("article","百家号必须有封面,请提供 cover 或在正文中放一张图片");h.push("百家号未提供 cover,已使用正文第一张图片作为封面")}return{platform:a,mode:c,...w?{cover:w}:{},...h.length?{notes:h}:{}}})}const di=(e,t,r=!1)=>!r&&Array.isArray(e)&&e.includes(t);function ui(e){var h,w;const t=`writedock-zhihu-${e.channel}`;if(location.origin!=="https://zhuanlan.zhihu.com")return null;let r=null;for(const m of[`writedock-zhihu-early-${e.draftId}`,t])try{const p=JSON.parse(sessionStorage.getItem(m)||"null");if((p==null?void 0:p.draftId)===e.draftId&&p.phase==="result"){if(p.publicationState!=="unknown")return p;r=p}}catch{}if(sessionStorage.getItem(`${t}:attempted`)!==e.draftId)return null;const i=location.pathname.replace(/\/$/,"");if(i!==`/p/${e.draftId}`&&i!==`/p/${e.draftId}/edit`)return null;const a=m=>m.getClientRects().length>0&&getComputedStyle(m).visibility!=="hidden",n=m=>!m.closest('.Post-RichText,[contenteditable="true"],.DraftEditor-root'),s=Array.from(document.querySelectorAll('[role="dialog"],[aria-modal="true"],.Modal-wrapper,.Modal')).filter(m=>a(m)&&n(m)),o=(w=(h=document.querySelector("h1.Post-Title"))==null?void 0:h.textContent)==null?void 0:w.trim();return i===`/p/${e.draftId}`&&o===e.title&&s.some(m=>Array.from(m.querySelectorAll('h1,h2,h3,h4,[role="heading"],div,p,span')).some(p=>{var u;return a(p)&&n(p)&&/^(?:文章)?发布成功[!!]?$/.test(((u=p.textContent)==null?void 0:u.trim())||"")}))?{phase:"result",draftId:e.draftId,success:!0,publicationState:"submitted",pageConfirmed:!0}:Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="verify"],[class*="Captcha"],[class*="captcha"],.geetest_panel,.yidun_panel')).some(m=>a(m)&&n(m))||s.some(m=>/验证码|安全验证|人机验证|拖动滑块|旋转图片|转动图片/.test(m.textContent||""))?{phase:"result",draftId:e.draftId,success:!1,publicationState:"needs_user_action",manualReason:"captcha",message:"知乎要求验证码或图形验证,请用户点击原稿件链接,在同一投稿页完成验证并手动发布;Agent 不要打开网页或重发。"}:r}function hi(e){const t=`writedock-zhihu-${e.channel}`,r=`writedock-zhihu-early-${e.draftId}`;let i=!1,a=!1,n=!1,s=!1;const o=d=>new Promise(f=>setTimeout(f,d)),c=async(d,f={})=>{const l=await chrome.runtime.sendMessage({type:d,jobId:e.id,jobSecret:e.secret,...f});if(l!=null&&l.error)throw new Error(l.error)},y=d=>d.getClientRects().length>0&&getComputedStyle(d).visibility!=="hidden",h=d=>y(d)&&!d.hasAttribute("disabled")&&d.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(d.className),w=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(h),m=()=>{window.removeEventListener(t,g),window.removeEventListener(r,g),window.removeEventListener(`${t}:cancel`,u),window.dispatchEvent(new Event(`${t}:stop`)),window.dispatchEvent(new Event(`${r}:stop`))},p=async d=>{if(!(n||s)){try{sessionStorage.setItem(t,JSON.stringify({...d,phase:"result",draftId:e.draftId}))}catch{}n=!0,m(),await c("ZHIHU_ARTICLE_DONE",{result:{...d,phase:"result",draftId:e.draftId}})}},u=()=>{s=!0,m()},g=d=>{try{const f=JSON.parse(d.detail);if(f.draftId!==e.draftId||s||n)return;f.phase==="request"&&(a=!0,c("ZHIHU_ARTICLE_PROGRESS",{stage:"verifying"}).catch(()=>u())),f.phase==="result"&&p(f).catch(()=>u())}catch{}};window.addEventListener(t,g),window.addEventListener(r,g),window.addEventListener(`${t}:cancel`,u,{once:!0});const D=()=>Array.from(document.querySelectorAll('[role="alert"],.Message,.Toast,.Form-error,[class*="errorMessage"]')).filter(y).map(d=>{var f;return((f=d.textContent)==null?void 0:f.trim())||""}).find(d=>d.length<250&&/失败|错误|验证码|扫码|登录|必填|请填写|不能为空|请选择|未完成|频繁|限制/.test(d)),A=d=>{const f=/验证码|扫码|安全验证|人机验证|滑块|旋转|转动/.test(d)?"captcha":/声明|协议/.test(d)?"agreement":/必填|请填写|不能为空|请选择|未完成/.test(d)?"publication_settings":void 0;throw Object.assign(new Error(d),{manualReason:f})};return(async()=>{var W;const d=Math.min(Date.now()+6e4,e.deadline);let f,l=!1;for(;!s&&Date.now()<d;){f=Array.from(document.querySelectorAll("textarea,input")).find(N=>y(N)&&/标题/.test(N.placeholder||""));const P=document.querySelector('[data-contents="true"],[contenteditable="true"]');if((f==null?void 0:f.value.trim())===e.title&&P&&y(P)&&((W=P.textContent)!=null&&W.trim()||P.querySelector("img,.video-link"))){l=!0;break}await o(500)}if(s)return;if(!l||!f||f.value.trim()!==e.title||location.pathname.replace(/\/$/,"")!==`/p/${e.draftId}/edit`)throw new Error("知乎编辑页未加载目标稿件,或标题已变化,已停止发布");const _=Math.min(Date.now()+2e4,e.deadline),k=()=>document.querySelectorAll('[contenteditable="true"] img').length;for(;!s&&k()<(e.imageCount||0)&&Date.now()<_;)await o(500);if(s)return;if(k()<(e.imageCount||0))throw new Error(`知乎编辑器只有 ${k()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);const I=D();I&&A(I);const E=Math.min(Date.now()+3e4,e.deadline);let v=w().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});for(;!v&&!s&&!n&&Date.now()<E;)await o(500),v=w().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});if(s||n)return;if(!v)throw new Error(D()||"知乎发布按钮不可用,请检查登录、必填项或平台提示");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const R=new Set(w());if(await c("ZHIHU_ARTICLE_PROGRESS",{stage:"publishing"}),s||Date.now()>=e.deadline||f.value.trim()!==e.title||!v.isConnected||!h(v))throw new Error("知乎页面状态已变化,已停止操作");i=!0;try{sessionStorage.setItem(`${t}:attempted`,e.draftId)}catch{}v.click();let U=!1;const B=Math.min(Date.now()+12e4,e.deadline);for(;!s&&!n&&Date.now()<B;){const P=D();if(P&&A(P),!a&&!U){const N=w().find(x=>{var L;return x!==v&&/^(发布|发布文章|确认发布|立即发布)$/.test(((L=x.textContent)==null?void 0:L.trim())||"")&&(!R.has(x)||x.closest('[role="dialog"],.Modal,.PublishPanel,.Popover-content'))});N&&(U=!0,N.click())}await o(300)}!s&&!n&&await p({success:!1,publicationState:"unknown",error:"知乎已尝试发布,但没有取得匹配的成功回执,请用户点击原稿件链接核对;Agent 不要打开网页或自动重发"})})().catch(d=>p(d!=null&&d.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:d.manualReason,message:`${d.message}。请用户点击原稿件链接自行处理并手动发布,Agent 不要打开网页或重发。`}:{success:!1,publicationState:i?"unknown":"failed",error:d instanceof Error?d.message:"知乎页面投稿失败",.../频率|频繁|后重试|稍后再试|超过.*限制/.test(d instanceof Error?d.message:"")?{platformRejected:!0}:{}}).catch(()=>{})),{started:!0}}const xe=new Map;async function pi(){const e="writedock-zhihu-publication-observer";(await chrome.scripting.getRegisteredContentScripts({ids:[e]})).length||await chrome.scripting.registerContentScripts([{id:e,js:["zhihu-publication-observer.js"],matches:["https://zhuanlan.zhihu.com/p/*/edit*"],runAt:"document_start",world:"MAIN",allFrames:!1,persistAcrossSessions:!0}])}async function fi(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("知乎草稿 ID 无效,未提交发布");await pi();const n=`https://zhuanlan.zhihu.com/p/${e}/edit`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开知乎发布页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1,u=n,g,D,A=!1;const b=(E,v=!1)=>{if(!xe.has(c)||A&&!v&&!E.success)return;if(!v&&!a&&!A&&Ve(E)){A=!0,clearTimeout(_),Xe({tabId:o,platform:"zhihu",channel:h,url:u,message:"知乎要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。",isActive:()=>xe.has(c),progress:r,onReceipt:W=>{I.attempted=!0,b({...W,draftId:e},!0)},onHandOff:()=>b(E,!0)});return}if(!v&&E.publicationState==="unknown"&&I.resultDeadline&&Date.now()<I.resultDeadline){g=E;return}if(xe.delete(c),clearTimeout(_),clearInterval(k),clearTimeout(D),chrome.tabs.onRemoved.removeListener(f),chrome.tabs.onUpdated.removeListener(l),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:(W,P)=>{window.dispatchEvent(new Event(`${W}:cancel`)),window.dispatchEvent(new Event(`${W}:stop`)),window.dispatchEvent(new Event(`${P}:stop`));for(const N of[W,`${W}:attempted`,P,`${P}:ready`])sessionStorage.removeItem(N)},args:[`writedock-zhihu-${h}`,`writedock-zhihu-early-${e}`]}).catch(()=>{}),a&&E.publicationState==="rehearsed"){Ae(o,{...Ge("zhihu",n),postId:e}).then(m);return}const R=!a&&I.attempted&&E.success===!0&&E.publicationState==="submitted"&&E.draftId===e&&(E.responseConfirmed===!0||E.pageConfirmed===!0),U=E.publicationState==="needs_user_action"&&["captcha","agreement","publication_settings"].includes(E.manualReason||""),B=E.message||"请用户点击原稿件链接,在同一投稿页完成平台要求并手动发布;Agent 不要打开网页或重发。";Ae(o,{platform:"zhihu",success:R,draftOnly:!1,publicationState:R?"submitted":U?"needs_user_action":I.attempted&&!E.platformRejected?"unknown":"failed",postId:e,postUrl:R?`https://zhuanlan.zhihu.com/p/${e}`:n,...R?{confirmation:E.responseConfirmed?"http_response":"native_page_message",message:E.responseConfirmed?"知乎发布接口已确认提交成功":"知乎原生页面已明确提示本篇文章发布成功"}:U?{requiresUserAction:!0,userAction:{type:E.manualReason,url:u,message:B},message:B}:{error:E.error||"知乎发布结果未确认,请用户点击原稿件链接核对;Agent 不要打开网页或重发"},timestamp:Date.now()},E.warnings).then(m)},d=async()=>{var E;if(!(!xe.has(c)||!I.attempted||p)){p=!0;try{const R=(E=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:ui,args:[{channel:h,draftId:e,title:t}]}))[0])==null?void 0:E.result;(R==null?void 0:R.phase)==="result"&&R.draftId===e&&b(R)}catch{}finally{p=!1}xe.has(c)&&I.resultDeadline&&Date.now()>=I.resultDeadline&&b(g||{error:"知乎已尝试发布,但等待成功回执超时。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"})}},f=E=>{E===o&&(D=setTimeout(()=>b({error:"知乎投稿标签页已关闭,结果未确认。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),500))},l=(E,v,R)=>{if(!(E!==o||!xe.has(c)||!I.attempted)){if(/^https:\/\/www\.zhihu\.com\/account\/unhuman(?:[/?#]|$)/.test(R.url||"")){u=R.url,b({publicationState:"needs_user_action",manualReason:"captcha",message:"知乎进入了人工验证页,请用户切换到同一投稿标签页完成验证并手动发布,Agent 不要打开网页或重发。"});return}v.status==="complete"&&d()}},_=setTimeout(()=>b({error:"等待知乎发布结果超时,请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),10*6e4),k=setInterval(()=>{d()},1e3),I={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:b};xe.set(c,I),chrome.tabs.onRemoved.addListener(f),chrome.tabs.onUpdated.addListener(l),(async()=>{var B,W,P,N;const E=Date.now()+6e4;for(;Date.now()<E&&xe.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(L=>setTimeout(L,250));if(!xe.has(c))return;const v=await chrome.tabs.get(o);if(v.status!=="complete"||!((B=v.url)!=null&&B.startsWith(n)))throw new Error("知乎发布页未就绪,请确认登录状态");if(!((W=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:x=>sessionStorage.getItem(`writedock-zhihu-early-${x}:ready`)==="1",args:[e]}))[0])!=null&&W.result))throw new Error("知乎发布监听未在页面启动前就绪,已停止发布;请重新加载新版扩展后再试");if(await Je(o),!((N=(P=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:hi,args:[{id:c,secret:y,channel:h,draftId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:P.result)!=null&&N.started))throw new Error("无法启动知乎发布流程")})().catch(E=>b({error:E instanceof Error?E.message:"启动知乎发布失败"}))})}async function mi(e,t){var i,a;const r=xe.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||((a=t.url)==null?void 0:a.split("/")[2])!=="zhuanlan.zhihu.com"||e.jobSecret!==r.secret)throw new Error("知乎投稿任务已结束或来源不匹配");if(e.type==="ZHIHU_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("知乎投稿阶段不正确");return r.attempted=!0,r.resultDeadline??(r.resultDeadline=Date.now()+12e4),r.progress({stage:e.stage}),!0}if(e.type==="ZHIHU_ARTICLE_DONE"){const n=e.result;return r.finish(n||{error:"知乎没有返回投稿结果"}),!0}throw new Error("不支持的知乎页面操作")}function wi(e){const t=`writedock-baijiahao-${e.channel}`,r=[],i=b=>{const d=JSON.stringify({...b,articleId:e.articleId,...b.phase==="result"&&r.length?{warnings:r}:{}});try{sessionStorage.setItem(t,d)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:d}))},a=(b,d,f)=>{try{const l=new URL(d,location.href);if(b.toUpperCase()!=="POST"||l.origin!=="https://baijiahao.baidu.com"||l.pathname!=="/pcui/article/publish")return"unrelated";const _=f instanceof URLSearchParams||f instanceof FormData?f:typeof f=="string"?new URLSearchParams(f):null;if(!_||_.get("article_id")!==e.articleId)return"unrelated";const k=_.get("cover_images");let I;try{I=typeof k=="string"?JSON.parse(k):void 0}catch{return r.push("百家号 cover_images 格式无法解析"),"publish"}return I===void 0?(r.push("百家号发布请求中未读到 cover_images 字段"),"publish"):Array.isArray(I)?I.length?(I.every(E=>typeof(E==null?void 0:E.src)=="string"&&E.src)||r.push("百家号封面字段结构与抓包时不同"),"publish"):"cover_required":(r.push("百家号 cover_images 结构与抓包时不同"),"publish")}catch{return"unrelated"}},n=(b,d)=>i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:b,message:d}),s=(b,d)=>{var f;try{let l=d;if(typeof l=="string"){const I=l.trim(),E=/^[\w.$]+\s*\(([\s\S]*)\)\s*;?\s*$/.exec(I);l=JSON.parse(E?E[1]:I)}const _=l;if((_==null?void 0:_.errno)===10000015||/完成验证|安全验证|验证码/.test((_==null?void 0:_.errmsg)||"")){i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:"captcha",captchaRejected:!0,message:"百家号要求人工完成旋转图片等验证码。请切换到已打开的百家号稿件页完成验证;Agent 不要重新提交。"});return}if((_==null?void 0:_.errno)!==0&&/封面/.test((_==null?void 0:_.errmsg)||"")){n("cover_required","百家号要求选择或调整封面,请打开同一稿件页完成封面设置并手动发布。");return}const k=b>=200&&b<300&&(_==null?void 0:_.errno)===0&&((f=_.ret)==null?void 0:f.article_id)===e.articleId;i({phase:"result",success:k,publicationState:k?"submitted":"unknown",...k?{}:{error:(_==null?void 0:_.errno)===0?"百家号返回的文章 ID 与本任务不匹配,请在平台核实":String((_==null?void 0:_.errmsg)||`百家号发布结果未确认(HTTP ${b})`).slice(0,300)}})}catch{i({phase:"result",success:!1,publicationState:"unknown",error:"百家号发布响应无法解析,请检查平台,不要自动重发"})}},o=b=>{if(b==="cover_required")throw n("cover_required","百家号尚未选好封面,已停止自动发布。请打开同一稿件页选择封面并手动发布。"),new Error("百家号需要选择封面,自动发布已停止");if(b==="publish"&&e.rehearsal)throw new Error("演练不提交发布,已拦截百家号发布请求");b==="publish"&&i({phase:"request"})},c=window.fetch,y=async function(b,d){let f="unrelated";try{const l=(d==null?void 0:d.method)||(b instanceof Request?b.method:"GET"),_=b instanceof Request?b.url:String(b),k=(d==null?void 0:d.body)??(b instanceof Request&&l.toUpperCase()==="POST"&&new URL(_,location.href).pathname==="/pcui/article/publish"?await b.clone().text():void 0);f=a(l,_,k)}catch{}o(f);try{const l=await c.call(window,b,d);return f==="publish"&&s(l.status,await l.clone().text()),l}catch(l){throw f==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"百家号发布连接中断,请检查平台,不要自动重发"}),l}},h=XMLHttpRequest.prototype,w=h.open,m=h.send,p=new WeakMap,u=function(b,d,...f){return p.set(this,{method:b,url:String(d)}),Reflect.apply(w,this,[b,d,...f])},g=function(b){const d=p.get(this),f=d?a(d.method,d.url,b):"unrelated";return o(f),f==="publish"&&this.addEventListener("loadend",()=>{try{s(this.status,this.responseType==="json"?this.response:this.responseText)}catch{s(this.status,void 0)}},{once:!0}),m.call(this,b)};window.fetch=y,h.open=u,h.send=g;const D=()=>{window.fetch===y&&(window.fetch=c),h.open===u&&(h.open=w),h.send===g&&(h.send=m),clearTimeout(A),window.removeEventListener(`${t}:stop`,D)},A=setTimeout(D,Math.max(1,e.deadline-Date.now()));return window.addEventListener(`${t}:stop`,D,{once:!0}),{observing:!0}}function gi(e){const t=`writedock-baijiahao-${e.channel}`;let r=!1,i=!1,a=!1,n=!1;const s=d=>new Promise(f=>setTimeout(f,d)),o=async(d,f={})=>{const l=await chrome.runtime.sendMessage({type:d,jobId:e.id,jobSecret:e.secret,...f});if(l!=null&&l.error)throw new Error(l.error)},c=d=>d.getClientRects().length>0&&getComputedStyle(d).visibility!=="hidden",y=d=>c(d)&&!d.hasAttribute("disabled")&&d.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(d.className),h=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(y),w=()=>{window.removeEventListener(t,u),window.removeEventListener(`${t}:cancel`,m),window.dispatchEvent(new Event(`${t}:stop`))},m=()=>{r=!0,w()},p=async d=>{i||r||(i=!0,w(),await o("BAIJIAHAO_ARTICLE_DONE",{result:d}))},u=d=>{try{const f=JSON.parse(d.detail);if(f.articleId!==e.articleId||r||i)return;f.phase==="request"&&(n=!0,o("BAIJIAHAO_ARTICLE_PROGRESS",{stage:"verifying"}).catch(m)),f.phase==="result"&&p(f).catch(m)}catch{}};window.addEventListener(t,u),window.addEventListener(`${t}:cancel`,m,{once:!0});const g=()=>Array.from(document.querySelectorAll('iframe[src*="passport.baidu.com/cap"],#vcode-spin,.vcode-spin,.vcode-spin-wrapper,.vcode-spin-container')).some(c)||Array.from(document.querySelectorAll('[role="dialog"],.ant-modal,.passMod_dialog-wrapper')).some(d=>c(d)&&/旋转图片|完成验证|安全验证|验证码|拖动滑块/.test(d.textContent||"")),D=()=>p({success:!1,publicationState:"needs_user_action",manualReason:"captcha",message:"百家号要求人工验证码,请切换到当前稿件页完成验证并手动发布。Agent 不要重新提交。"}),A=()=>Array.from(document.querySelectorAll('[role="alert"],.ant-message-notice,.ant-notification-notice,.form-error')).filter(c).map(d=>{var f;return((f=d.textContent)==null?void 0:f.trim())||""}).find(d=>d.length<250&&/封面|失败|错误|验证码|完成验证|不能为空|必填|请选择|请填写|频繁|限制/.test(d));return(async()=>{var x;const d=Math.min(Date.now()+6e4,e.deadline);let f,l=!1;const _=L=>(L instanceof HTMLInputElement||L instanceof HTMLTextAreaElement?L.value:L.textContent||"").trim(),k=()=>Array.from(document.querySelectorAll('[class*="titleInput"] [contenteditable="true"],[class*="titleInput"] textarea,[class*="titleInput"] input,textarea[placeholder*="标题"],input[placeholder*="标题"]')).find(c),I=()=>{var $;const L=document.querySelector('iframe#ueditor_0,iframe[id^="ueditor_"]');try{const S=L&&c(L)?($=L.contentDocument)==null?void 0:$.body:null;if(S)return S}catch{}return Array.from(document.querySelectorAll('[contenteditable="true"],.ProseMirror,.ql-editor')).find(S=>c(S)&&!S.closest('[class*="titleInput"]'))};for(;!r&&!i&&Date.now()<d;){if(g()){await D();return}f=k();const L=I();if(f&&_(f)===e.title&&L&&((x=L.textContent)!=null&&x.replace(/[\s\u200b-\u200d\ufeff]/g,"")||L.querySelector("img"))){l=!0;break}await s(500)}if(r||i)return;if(!l||!f||_(f)!==e.title||new URL(location.href).searchParams.get("article_id")!==e.articleId)throw new Error("百家号编辑页未加载目标稿件,已停止发布");const E=Math.min(Date.now()+2e4,e.deadline),v=()=>{var L;return((L=I())==null?void 0:L.querySelectorAll("img").length)||0};for(;!r&&!i&&v()<(e.imageCount||0)&&Date.now()<E;)await s(500);if(r||i)return;if(v()<(e.imageCount||0))throw new Error(`百家号编辑器只有 ${v()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);const R=A();if(R&&/完成验证|安全验证|验证码/.test(R)){await D();return}if(R&&/封面/.test(R)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页处理并手动发布。"});return}const U=Math.min(Date.now()+3e4,e.deadline);let B=h().find(L=>{var $;return/^(发布|发布文章|立即发布)$/.test((($=L.textContent)==null?void 0:$.trim())||"")});for(;!B&&!r&&!i&&Date.now()<U;)await s(500),B=h().find(L=>{var $;return/^(发布|发布文章|立即发布)$/.test((($=L.textContent)==null?void 0:$.trim())||"")});if(r||i)return;if(!B)throw new Error(A()||"百家号发布按钮不可用,请检查页面要求");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const W=new Set(h());if(await o("BAIJIAHAO_ARTICLE_PROGRESS",{stage:"publishing"}),r||i||_(f)!==e.title||!B.isConnected||!y(B)||Date.now()>=e.deadline)throw new Error("百家号页面状态变化,已停止自动发布");a=!0,B.click();const P=Math.min(Date.now()+12e4,e.deadline);let N=!1;for(;!r&&!i&&Date.now()<P;){if(g()){await D();return}const L=A();if(L&&/完成验证|安全验证|验证码/.test(L)){await D();return}if(L&&/封面/.test(L)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页完成封面设置并手动发布。"});return}if(L)throw new Error(L);if(!n&&!N){const $=h().find(S=>{var M;return S!==B&&/^(发布|确认发布|立即发布|确认并发布|发布并提交审核)$/.test(((M=S.textContent)==null?void 0:M.trim())||"")&&(!W.has(S)||S.closest('[role="dialog"],.ant-modal'))});$&&(N=!0,$.click())}await s(300)}!r&&!i&&await p({success:!1,publicationState:"unknown",error:"已尝试发布,但未取得匹配的百家号成功响应,请检查平台,不要自动重发"})})().catch(d=>p({success:!1,publicationState:a?"unknown":"failed",error:d instanceof Error?d.message:"百家号页面投稿失败"}).catch(()=>{})),{started:!0}}const qe=new Map;async function yi(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("百家号稿件 ID 无效,未提交发布");const n=`https://baijiahao.baidu.com/builder/rc/edit?type=news&article_id=${e}`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开百家号发布页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!qe.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:o,platform:"baijiahao",channel:h,url:n,articleId:e,message:"百家号要求完成验证码。请在已打开的稿件页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>qe.has(c),progress:r,onReceipt:I=>{b.attempted=!0,u(I,!0)},onHandOff:()=>u(d,!0)});return}if(qe.delete(c),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:I=>{window.dispatchEvent(new Event(`${I}:cancel`)),window.dispatchEvent(new Event(`${I}:stop`)),sessionStorage.removeItem(I)},args:[`writedock-baijiahao-${h}`]}).catch(()=>{}),a&&d.publicationState==="rehearsed"){Ae(o,{...Ge("baijiahao",n),postId:e},d.warnings).then(m);return}const l=!a&&d.success===!0&&d.publicationState==="submitted",_=d.publicationState==="needs_user_action"&&["captcha","cover_required"].includes(d.manualReason||""),k=d.message||"请打开同一百家号稿件页,完成平台要求并手动发布。Agent 不要自动重试。";Ae(o,{platform:"baijiahao",success:l,draftOnly:!1,publicationState:l?"submitted":_?"needs_user_action":b.attempted?"unknown":"failed",postId:e,postUrl:l?`https://baijiahao.baidu.com/s?id=${e}`:n,timestamp:Date.now(),...l?{message:"百家号发布接口已确认提交成功"}:_?{requiresUserAction:!0,userAction:{type:d.manualReason,url:n,message:k},message:k}:{error:d.error||"百家号发布结果未确认,请检查平台"}},d.warnings).then(m)},g=d=>{d===o&&u({error:"百家号投稿页已关闭,请先检查平台,不要自动重发"})},D=(d,f,l)=>{var _;d!==o||f.status!=="complete"||!b.attempted||!((_=l.url)!=null&&_.startsWith("https://baijiahao.baidu.com/"))||chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:k=>sessionStorage.getItem(k),args:[`writedock-baijiahao-${h}`]}).then(k=>{var v;const I=(v=k[0])==null?void 0:v.result;if(typeof I!="string")return;const E=JSON.parse(I);E.articleId===e&&E.phase==="result"&&u(E)}).catch(()=>{})},A=setTimeout(()=>u({error:"等待百家号发布结果超时,请检查稿件,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,articleId:e,attempted:!1,progress:r,finish:u};qe.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var I,E,v,R;const d=Date.now()+6e4;for(;Date.now()<d&&qe.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(U=>setTimeout(U,250));if(!qe.has(c))return;const f=await chrome.tabs.get(o),l=new URL(f.url||"");if(f.status!=="complete"||l.origin!=="https://baijiahao.baidu.com"||l.searchParams.get("article_id")!==e)throw new Error("百家号稿件页未就绪,请确认登录");if(await Je(o),!((E=(I=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:wi,args:[{channel:h,articleId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:I.result)!=null&&E.observing))throw new Error("无法监测百家号发布响应,已停止发布");if(!((R=(v=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:gi,args:[{id:c,secret:y,channel:h,articleId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:v.result)!=null&&R.started))throw new Error("无法启动百家号发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动百家号发布失败"}))})}async function bi(e,t){var i,a;const r=qe.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://baijiahao.baidu.com/"))||e.jobSecret!==r.secret)throw new Error("百家号投稿任务已结束或来源不匹配");if(e.type==="BAIJIAHAO_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("百家号投稿阶段不正确");return r.attempted=!0,r.progress({stage:e.stage}),!0}if(e.type==="BAIJIAHAO_ARTICLE_DONE")return r.finish(e.result||{error:"百家号没有返回结果"}),!0;throw new Error("不支持的百家号页面操作")}function vi(e){const t=`writedock-weibo-article-${e.channel}`,r=[],i=b=>{const d=JSON.stringify({...b,draftId:e.draftId,...b.phase==="result"&&r.length?{warnings:r}:{}});try{sessionStorage.setItem(t,d)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:d}))},a=(b,d,f)=>{try{const l=new URL(d,location.href);if(b.toUpperCase()!=="POST"||l.origin!=="https://card.weibo.com")return null;const _=l.pathname==="/article/v5/aj/editor/draft/save"?"save":l.pathname==="/article/v5/aj/editor/draft/publish"?"publish":null;if(!_)return null;const k=f instanceof URLSearchParams||f instanceof FormData?f:typeof f=="string"?new URLSearchParams(f):null;return k&&k.get("id")===e.draftId?{operation:_,data:k}:null}catch{return null}},n=(b,d)=>i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:b,message:d}),s=b=>{if((b==null?void 0:b.operation)!=="publish")return;if(e.rehearsal)throw new Error("演练不提交发布,已拦截微博长文章发布请求");const d=["follow_official","is_original","follow_to_read","mpkey"],f=l=>l!==null&&l!==""&&l!=="0";if(d.some(l=>f(b.data.get(l)))||b.data.get("time"))throw n("publication_settings","微博发布窗口的关注、原创声明、阅读限制、同步或定时设置需要核对,已停止自动提交,请检查原稿件并手动发布。"),new Error("微博发布设置需要人工检查,未自动提交");for(const l of d)b.data.get(l)===null&&r.push(`微博发布请求中未读到 ${l} 字段`);i({phase:"request"})},o=(b,d,f)=>{var l,_,k,I;try{const E=typeof f=="string"?JSON.parse(f):f;if((_=(l=E==null?void 0:E.data)==null?void 0:l.geetest)!=null&&_.verifyUrl||/验证码|安全验证|完成验证/.test((E==null?void 0:E.msg)||"")){n("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(b!=="publish")return;let v="";try{const U=new URL(((k=E==null?void 0:E.data)==null?void 0:k.url)||""),B=U.searchParams.get("id");U.protocol==="https:"&&U.hostname==="weibo.com"&&U.pathname==="/ttarticle/p/show"&&B&&/^\d+$/.test(B)&&((I=E==null?void 0:E.data)==null?void 0:I.object_id)===`1022:${B}`&&(v=U.href)}catch{}const R=d>=200&&d<300&&(E==null?void 0:E.code)===1e5&&!!v;i({phase:"result",success:R,publicationState:R?"submitted":"unknown",...R?{postUrl:v}:{error:(E==null?void 0:E.code)===1e5?"微博返回的文章链接未能核实,请检查平台,不要重发":String((E==null?void 0:E.msg)||`微博发布结果未确认(HTTP ${d})`).slice(0,300)}})}catch{b==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"微博发布响应无法解析,请检查平台,不要自动重发"})}},c=window.fetch,y=async function(b,d){let f=null;try{const l=(d==null?void 0:d.method)||(b instanceof Request?b.method:"GET"),_=b instanceof Request?b.url:String(b),k=(d==null?void 0:d.body)??(b instanceof Request&&l.toUpperCase()==="POST"&&/\/draft\/(save|publish)$/.test(new URL(_,location.href).pathname)?await b.clone().text():void 0);f=a(l,_,k)}catch{}s(f);try{const l=await c.call(window,b,d);return f&&o(f.operation,l.status,await l.clone().text()),l}catch(l){throw(f==null?void 0:f.operation)==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"微博发布连接中断,请检查平台,不要自动重发"}),l}},h=XMLHttpRequest.prototype,w=h.open,m=h.send,p=new WeakMap,u=function(b,d,...f){return p.set(this,{method:b,url:String(d)}),Reflect.apply(w,this,[b,d,...f])},g=function(b){const d=p.get(this),f=d?a(d.method,d.url,b):null;return s(f),f&&this.addEventListener("loadend",()=>{try{o(f.operation,this.status,this.responseType==="json"?this.response:this.responseText)}catch{o(f.operation,this.status,void 0)}},{once:!0}),m.call(this,b)};window.fetch=y,h.open=u,h.send=g;const D=()=>{window.fetch===y&&(window.fetch=c),h.open===u&&(h.open=w),h.send===g&&(h.send=m),clearTimeout(A),window.removeEventListener(`${t}:stop`,D)},A=setTimeout(D,Math.max(1,e.deadline-Date.now()));return window.addEventListener(`${t}:stop`,D,{once:!0}),{observing:!0}}function _i(e){const t=`writedock-weibo-article-${e.channel}`;let r=!1,i=!1,a=!1,n=!1;const s=f=>new Promise(l=>setTimeout(l,f)),o=async(f,l={})=>{const _=await chrome.runtime.sendMessage({type:f,jobId:e.id,jobSecret:e.secret,...l});if(_!=null&&_.error)throw new Error(_.error)},c=f=>f.getClientRects().length>0&&getComputedStyle(f).visibility!=="hidden",y=f=>c(f)&&!f.hasAttribute("disabled")&&f.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(f.className),h=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(y),w=()=>{window.removeEventListener(t,u),window.removeEventListener(`${t}:cancel`,m),window.dispatchEvent(new Event(`${t}:stop`))},m=()=>{r=!0,w()},p=async f=>{i||r||(i=!0,w(),await o("WEIBO_ARTICLE_DONE",{result:f}))},u=f=>{try{const l=JSON.parse(f.detail);if(l.draftId!==e.draftId||r||i)return;l.phase==="request"&&(n=!0,o("WEIBO_ARTICLE_PROGRESS",{stage:"verifying"}).catch(m)),l.phase==="result"&&p(l).catch(m)}catch{}};window.addEventListener(t,u),window.addEventListener(`${t}:cancel`,m,{once:!0});const g=()=>Array.from(document.querySelectorAll('iframe[src*="security.weibo.com/verify"],iframe[src*="security.weibo.com/captcha"],iframe[src*="dun.163.com"],.yidun_popup,.yidun_modal,.geetest_panel')).some(c),D=()=>Array.from(document.querySelectorAll('[role="alert"],.n-message,.n-notification,.error_message')).filter(c).map(f=>{var l;return((l=f.textContent)==null?void 0:l.trim())||""}).find(f=>f.length<250&&/失败|错误|验证码|安全验证|封面|请输入|不能为空|频繁|限制/.test(f)),A=(f,l)=>p({success:!1,publicationState:"needs_user_action",manualReason:f,message:l}),b=(f,l=!0)=>{var k;const _=Array.from(document.querySelectorAll('span,label,[role="checkbox"]')).filter(I=>{var E;return c(I)&&(((E=I.textContent)==null?void 0:E.trim().length)||0)<100&&f.test(I.textContent||"")});for(const I of _){const E=I.closest('label,[role="checkbox"]')||((k=I.parentElement)==null?void 0:k.querySelector('input[type="checkbox"],[role="checkbox"]'));if(!E)return!1;const v=E instanceof HTMLInputElement?E:E.querySelector('input[type="checkbox"]'),R=v?v.checked:E.getAttribute("aria-checked")==="true"?!0:E.getAttribute("aria-checked")==="false"?!1:void 0;if(R===void 0||R&&(!l||!y(E)))return!1;R&&E.click();break}return!0};return(async()=>{var B,W;const f=Math.min(Date.now()+6e4,e.deadline);let l,_=!1;for(;!r&&!i&&Date.now()<f;){if(g()){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}l=Array.from(document.querySelectorAll("input,textarea")).find(N=>c(N)&&/标题/.test(N.placeholder||""));const P=document.querySelector('[contenteditable="true"],.ProseMirror');if((l==null?void 0:l.value.trim())===e.title&&P&&c(P)&&((B=P.textContent)!=null&&B.trim()||P.querySelector("img"))){_=!0;break}await s(500)}if(r||i)return;if(!_||!l||l.value.trim()!==e.title||!new RegExp(`^#/draft/${e.draftId}(?:[/?]|$)`).test(location.hash))throw new Error("微博长文章编辑页未加载目标稿件,已停止发布");const k=Math.min(Date.now()+2e4,e.deadline),I=()=>{var P;return((P=document.querySelector('[contenteditable="true"].ProseMirror,.ProseMirror'))==null?void 0:P.querySelectorAll("img").length)||0};for(;!r&&!i&&I()<(e.imageCount||0)&&Date.now()<k;)await s(500);if(r||i)return;if(I()<(e.imageCount||0))throw new Error(`微博长文章编辑器只有 ${I()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);if(!b(/同步至新浪新闻/)){await A("publication_settings","请检查微博文章的同步设置并手动发布,未自动提交到其他平台。");return}await s(100);const E=Math.min(Date.now()+3e4,e.deadline);let v=h().find(P=>{var N;return((N=P.textContent)==null?void 0:N.trim())==="下一步"})||h().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});for(;!v&&!r&&!i&&Date.now()<E;)await s(500),v=h().find(P=>{var N;return((N=P.textContent)==null?void 0:N.trim())==="下一步"})||h().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});if(r||i)return;if(!v)throw new Error(D()||"未找到微博长文章的下一步按钮");if(e.rehearsal&&((W=v.textContent)==null?void 0:W.trim())!=="下一步"){await p({success:!1,publicationState:"rehearsed"});return}if(e.rehearsal||await o("WEIBO_ARTICLE_PROGRESS",{stage:"publishing"}),r||i||Date.now()>=e.deadline||l.value.trim()!==e.title||!v.isConnected||!y(v))throw new Error("微博页面状态变化,已停止操作");e.rehearsal||(a=!0),v.click();const R=Math.min(Date.now()+12e4,e.deadline);let U=!1;for(;!r&&!i&&Date.now()<R;){if(g()){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(h().find(x=>{var L,$;return((L=x.textContent)==null?void 0:L.trim())==="我同意"&&/头条文章原创声明|微博签约媒体原创认证协议/.test((($=x.closest('[role="dialog"],.n-dialog,.n-modal'))==null?void 0:$.textContent)||"")})){await A("agreement","微博显示原创相关协议确认,未自动同意或声明原创。请打开原稿件页阅读并自行决定,再手动发布。");return}const N=D();if(N&&/验证码|安全验证/.test(N)){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(N&&/封面/.test(N)){await A("cover_required","微博长文章需要设置封面,请在原稿件页完成设置并手动发布。");return}if(N)throw new Error(N);if(!n&&!U){const x=h().find(L=>{var $;return L!==v&&(($=L.textContent)==null?void 0:$.trim())==="发布"&&L.closest('[role="dialog"],.n-modal,.n-dialog,.wb-common-dialog')});if(x){if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}if(!b(/关注\s*@头条文章/)||!b(/并声明本文是原创作品/,!1)){await A("publication_settings","微博发布窗口的勾选项无法安全核对,请自行检查关注及原创声明后手动发布。");return}if(await s(100),r||i||n)return;if(!x.isConnected||!y(x))throw new Error("微博发布确认按钮状态变化,未继续操作");U=!0,x.click()}}await s(300)}!r&&!i&&await p(e.rehearsal?{success:!1,publicationState:"failed",error:"点击下一步后未出现微博发布窗口,演练未通过"}:{success:!1,publicationState:"unknown",error:"微博长文章发布结果未确认,请检查平台,不要自动重发"})})().catch(f=>p({success:!1,publicationState:a?"unknown":"failed",error:f instanceof Error?f.message:"微博长文章投稿失败"}).catch(()=>{})),{started:!0}}const De=new Map;async function Ei(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("微博长文章草稿 ID 无效,未提交发布");const n=`https://card.weibo.com/article/v5/editor#/draft/${e}`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开微博长文章编辑页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!De.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:o,platform:"weibo-article",channel:h,url:n,message:"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。",isActive:()=>De.has(c),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}De.delete(c),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:E=>{window.dispatchEvent(new Event(`${E}:cancel`)),window.dispatchEvent(new Event(`${E}:stop`)),sessionStorage.removeItem(E)},args:[`writedock-weibo-article-${h}`]}).catch(()=>{});let l="";try{const E=new URL(d.postUrl||"");E.origin==="https://weibo.com"&&E.pathname==="/ttarticle/p/show"&&/^\d+$/.test(E.searchParams.get("id")||"")&&(l=E.href)}catch{}if(a&&d.publicationState==="rehearsed"){Ae(o,{...Ge("weibo",n),postId:e},d.warnings).then(m);return}const _=!a&&d.success===!0&&d.publicationState==="submitted"&&!!l,k=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),I=d.message||"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。";Ae(o,{platform:"weibo",success:_,draftOnly:!1,publicationState:_?"submitted":k?"needs_user_action":b.attempted?"unknown":"failed",postId:e,postUrl:_?l:n,timestamp:Date.now(),..._?{message:"微博长文章发布接口已确认成功"}:k?{requiresUserAction:!0,userAction:{type:d.manualReason,url:n,message:I},message:I}:{error:d.error||"微博长文章结果未确认,请检查平台"}},d.warnings).then(m)},g=d=>{d===o&&u({error:"微博投稿标签页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;if(!(d!==o||!De.has(c))){if(/^https:\/\/security\.weibo\.com\/(?:verify|captcha)(?:\/|\?|$)/.test(l.url||"")){u({publicationState:"needs_user_action",manualReason:"captcha",message:"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。"});return}f.status!=="complete"||!b.attempted||!((_=l.url)!=null&&_.startsWith("https://card.weibo.com/"))||chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:k=>sessionStorage.getItem(k),args:[`writedock-weibo-article-${h}`]}).then(k=>{var v;const I=(v=k[0])==null?void 0:v.result;if(typeof I!="string")return;const E=JSON.parse(I);E.draftId===e&&E.phase==="result"&&u(E)}).catch(()=>{})}},A=setTimeout(()=>u({error:"等待微博长文章发布结果超时,请检查平台,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:u};De.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var k,I,E,v,R;const d=Date.now()+6e4;for(;Date.now()<d&&De.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(U=>setTimeout(U,250));if(!De.has(c))return;const f=await chrome.tabs.get(o);if(f.status!=="complete"||!((k=f.url)!=null&&k.startsWith("https://card.weibo.com/article/v5/editor")))throw new Error("微博长文章编辑页未就绪,请确认登录");if(await Je(o),!((E=(I=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:vi,args:[{channel:h,draftId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:I.result)!=null&&E.observing))throw new Error("无法监测微博长文章的发布响应,已停止发布");if(!((R=(v=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:_i,args:[{id:c,secret:y,channel:h,draftId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:v.result)!=null&&R.started))throw new Error("无法启动微博长文章发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动微博长文章投稿失败"}))})}async function Si(e,t){var i,a;const r=De.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://card.weibo.com/"))||e.jobSecret!==r.secret)throw new Error("微博长文章任务已结束或来源不匹配");if(e.type==="WEIBO_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("微博投稿阶段不正确");return r.attempted=!0,r.progress({stage:e.stage}),!0}if(e.type==="WEIBO_ARTICLE_DONE")return r.finish(e.result||{error:"微博没有返回结果"}),!0;throw new Error("不支持的微博长文章页面操作")}function Ai(e){const t=`writedock-bilibili-${e.channel}`,r=new DOMParser().parseFromString(e.html,"text/html"),i=S=>S.replace(/[\s\u200b-\u200d\ufeff]/g,""),a=i(r.body.textContent||""),n=r.querySelectorAll("img[src]").length,s=new Set,o=new Set,c=S=>{try{const M=new URL(String(S),location.href);return/^https?:$/.test(M.protocol)&&/(?:^|\.)(?:hdslb\.com|biliimg\.com)$/.test(M.hostname)&&M.pathname.startsWith("/bfs/")?M.pathname:""}catch{return""}};for(const S of r.querySelectorAll("img[src]")){const M=c(S.getAttribute("src"));M&&o.add(M)}let y=!1,h=!1,w=!1,m="";const p=[],u=S=>{p.includes(S)||p.push(S)},g=S=>Array.isArray(S)?S.length>0:S&&typeof S=="object"?Object.keys(S).length>0:!!S,D=S=>{const M=JSON.stringify({...S,jobId:e.id});try{sessionStorage.setItem(t,M)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:M}))},A=S=>{w||(w=!0,D({phase:"result",...p.length?{warnings:p}:{},...S}))},b=(S,M)=>A({success:!1,publicationState:"needs_user_action",manualReason:S,message:M}),d=S=>typeof S=="string"?JSON.parse(S):S,f=(S,M)=>{try{const X=new URL(M,location.href);if(X.origin!=="https://api.bilibili.com")return null;if(/^\/x\/gaia-vgate\/(?:v2\/register|v1\/img)$/.test(X.pathname))return"captcha";if(S.toUpperCase()!=="POST")return null;if(X.pathname==="/x/dynamic/feed/create/opus")return"publish";if(X.pathname==="/x/dynamic/feed/edit/opus"||/^\/x\/article\/creative\/article\/(?:addupdate|update)$/.test(X.pathname))return"other_publish";if(X.pathname==="/x/dynamic/feed/article/draft/add")return"draft";if(["/x/dynamic/feed/draw/upload_bfs","/x/dynamic/feed/draw/transfer_image"].includes(X.pathname))return"image"}catch{}return null},l=(S,M)=>{throw b(S,M),new Error("WriteDock 已停止B站专栏自动发布,请检查原稿件")},_=(S,M)=>{var ge,C,z,q,O,G;if(S==="captcha"){b("captcha","B站要求人工验证码。请切换到已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");return}if(S==="other_publish")return l("publication_settings","B站页面试图修改已有内容或使用旧发布接口,已停止操作,请核对原投稿页。");if(S!=="publish")return;if(e.rehearsal)return l("publication_settings","演练不提交发布,已拦截B站发布请求。");if(w||h||!y||Date.now()>=e.deadline)return h&&!w&&A({success:!1,publicationState:"unknown",error:"B站页面尝试重复提交,请检查原帖,不要自动重发。"}),l("publication_settings","本次B站稿件尚未核对完成或页面尝试重复发送,已停止自动提交。");let X;try{X=d(M)}catch{}if(!X||typeof X!="object"){u("B站发布请求格式无法解析,已依据提交前的编辑器核对放行"),h=!0,y=!1,D({phase:"request"});return}const j=X.opus_req,H=j==null?void 0:j.opus,ee=j==null?void 0:j.option;if(X.dyn_id_str||X.cvid_str)return l("publication_settings","B站发布请求指向已有内容,已停止发布。");if(typeof(H==null?void 0:H.title)=="string"&&H.title!==e.title)return l("publication_settings","B站发布请求的标题与本次稿件不一致,已停止发布。");if((ee==null?void 0:ee.private_pub)!==void 0&&ee.private_pub!==2||ee!=null&&ee.timer_pub_time||(ge=H==null?void 0:H.pub_info)!=null&&ge.timer_pub_time||ee!=null&&ee.only_fans||ee!=null&&ee.only_fans_level||g(j==null?void 0:j.topic)||g(H==null?void 0:H.attachments)||g((C=H==null?void 0:H.article)==null?void 0:C.list_id))return l("publication_settings","B站的公开范围、定时、充电专享、文集、话题或附加内容需要人工核对,请在原稿件页手动发布。");if((z=H==null?void 0:H.article)!=null&&z.originality)return l("agreement","B站稿件已选择原创声明,Agent 不自动声明原创或同意原创协议,请在原稿件页自行核对并手动发布。");if(X.draft_id_str&&m&&X.draft_id_str!==m)return l("publication_settings","B站发布请求未匹配本次原生编辑器保存的中间稿件,已停止发布。");X.raw_content!==void 0&&X.raw_content!==""&&u("B站 raw_content 不为空"),(j==null?void 0:j.scene)!==12&&u(`B站 scene=${String(j==null?void 0:j.scene)},与抓包时的 12 不同`),(H==null?void 0:H.opus_source)!==2&&u(`B站 opus_source=${String(H==null?void 0:H.opus_source)},与抓包时的 2 不同`),((q=H==null?void 0:H.article)==null?void 0:q.category_id)!==15&&u(`B站 category_id=${String((O=H==null?void 0:H.article)==null?void 0:O.category_id)},与抓包时的 15 不同`),typeof(H==null?void 0:H.title)!="string"&&u("B站发布请求中未读到标题字段"),(ee==null?void 0:ee.private_pub)===void 0&&u("B站发布请求中未读到公开范围字段"),((G=H==null?void 0:H.article)==null?void 0:G.originality)===void 0&&u("B站发布请求中未读到原创声明字段"),X.draft_id_str&&!m&&u("未观察到B站中间稿件保存回执");const Z=[],ie=[];let se=!1;const Y=T=>{if(!(!T||typeof T!="object")){if(Array.isArray(T)){T.forEach(Y);return}for(const[F,K]of Object.entries(T))F==="words"&&typeof K=="string"?Z.push(K):F==="pics"&&Array.isArray(K)?ie.push(...K):["video","video_card","archive","audio","live","bangumi","vote","goods","lottery"].includes(F)?se=!0:Y(K)}};if(Y(H==null?void 0:H.content),se)return l("publication_settings","B站发布内容包含未接入的内容卡片,已停止发布。");if(Z.length&&i(Z.join(""))!==a)return l("publication_settings","B站发布请求的正文与本次稿件不一致,已停止发布。");if(!Z.length&&a&&u("B站发布请求中未读到正文字段,已依据提交前的编辑器核对放行"),ie.length&&ie.length!==n)return l("publication_settings","B站发布请求的图片数量与本次稿件不一致,已停止发布。");if(!ie.length&&n&&u("B站发布请求中未读到图片字段,已依据提交前的编辑器核对放行"),ie.some(T=>String(T.url).startsWith("data:")))return l("publication_settings","B站发布请求中有图片尚未上传完成,已停止发布。");ie.some(T=>{const F=c(T.url);return!F||!s.has(F)&&!o.has(F)||!(T.width>0&&T.height>0)})&&u("B站发布请求中有图片未匹配本次观察到的上传记录"),h=!0,y=!1,D({phase:"request"})},k=(S,M,X,j)=>{var H,ee,Z,ie,se;if(!(w||S==="captcha"))try{const Y=d(X);if((Y==null?void 0:Y.code)===-352||/验证码|安全验证|验证后|完成验证/.test(String((Y==null?void 0:Y.message)||""))){A({success:!1,publicationState:"needs_user_action",manualReason:"captcha",captchaRejected:!0,message:"B站专栏要求人工验证。请在已打开的原投稿页完成验证码,Agent 不要重新提交。"});return}if(S==="image"){const z=(Y==null?void 0:Y.code)===0&&M>=200&&M<300?c((H=Y.data)==null?void 0:H.image_url):"";z&&(s.add(z),D({phase:"images",current:s.size,total:n}));return}if(S==="draft"){let z="";try{z=((Z=(ee=d(j))==null?void 0:ee.arg)==null?void 0:Z.title)||""}catch{}const q=(ie=Y==null?void 0:Y.data)==null?void 0:ie.article_id;(Y==null?void 0:Y.code)===0&&z===e.title&&(typeof q=="number"&&Number.isSafeInteger(q)||typeof q=="string")&&/^\d{1,16}$/.test(String(q))&&(m=String(q));return}if(S!=="publish")return;const ge=(se=Y==null?void 0:Y.data)==null?void 0:se.dyn_id_str,C=M>=200&&M<300&&(Y==null?void 0:Y.code)===0&&typeof ge=="string"&&/^\d{1,24}$/.test(ge);A({success:C,publicationState:C?"submitted":"unknown",...C?{responseConfirmed:!0,postId:ge,postUrl:`https://www.bilibili.com/opus/${ge}`}:{error:(Y==null?void 0:Y.code)===0?"B站返回成功但没有可核实的内容 ID,请检查平台,不要自动重发。":String((Y==null?void 0:Y.message)||`B站发布结果未确认(HTTP ${M})`).slice(0,300)}})}catch{S==="publish"&&A({success:!1,publicationState:"unknown",error:"B站发布回执无法解析,请检查原帖,不要自动重发。"})}},I=window.fetch,E=async function(S,M){const X=(M==null?void 0:M.method)||(S instanceof Request?S.method:"GET"),j=f(X,S instanceof Request?S.url:String(S)),H=["publish","draft"].includes(j||"")?(M==null?void 0:M.body)??(S instanceof Request?await S.clone().text():void 0):void 0;_(j,H);try{const ee=await I.call(window,S,M);return j&&k(j,ee.status,await ee.clone().text(),H),ee}catch(ee){throw j==="publish"&&A({success:!1,publicationState:"unknown",error:"B站发布连接中断,请检查原帖,不要自动重发。"}),ee}},v=XMLHttpRequest.prototype,R=v.open,U=v.send,B=new WeakMap,W=function(S,M,...X){return B.set(this,{method:S,url:String(M)}),Reflect.apply(R,this,[S,M,...X])},P=function(S){const M=B.get(this),X=M?f(M.method,M.url):null;return _(X,S),X&&this.addEventListener("loadend",()=>{try{k(X,this.status,this.responseType==="json"?this.response:this.responseText,S)}catch{X==="publish"&&k(X,this.status,void 0)}},{once:!0}),U.call(this,S)},N=()=>{!w&&!h&&Date.now()<e.deadline&&(y=!0)},x=()=>{var ee,Z;if(w||h)return;const S=window.editor,M=(Z=(ee=S==null?void 0:S.storage)==null?void 0:ee.biliImage)==null?void 0:Z.allImages,X=[],j=ie=>{!ie||typeof ie!="object"||(ie.type==="text"&&typeof ie.text=="string"&&X.push(ie.text),Array.isArray(ie.content)&&ie.content.forEach(j))};typeof(S==null?void 0:S.getJSON)=="function"&&j(S.getJSON());const H=typeof(S==null?void 0:S.getJSON)=="function"&&i(X.join(""))===a&&Array.isArray(M)&&M.length===n&&M.every(ie=>ie.attrs.status===1)&&(s.size>=n||M.every(ie=>!!c(ie.attrs.src)));D({phase:"content",ready:H})},L=()=>{window.fetch===E&&(window.fetch=I),v.open===W&&(v.open=R),v.send===P&&(v.send=U),clearTimeout($),window.removeEventListener(`${t}:arm`,N),window.removeEventListener(`${t}:read`,x),window.removeEventListener(`${t}:stop`,L)};window.fetch=E,v.open=W,v.send=P,window.addEventListener(`${t}:arm`,N),window.addEventListener(`${t}:read`,x),window.addEventListener(`${t}:stop`,L,{once:!0});const $=setTimeout(L,Math.max(1,e.deadline-Date.now()));return{observing:!0}}function Ii(e){const t=`writedock-bilibili-${e.channel}`;let r=!1,i=!1,a=!1,n=!1,s=!1;const o=l=>new Promise(_=>setTimeout(_,l)),c=async(l,_={})=>{const k=await chrome.runtime.sendMessage({type:l,jobId:e.id,jobSecret:e.secret,..._});if(!k||k.error)throw new Error((k==null?void 0:k.error)||"扩展后台已断开,请检查B站,不要自动重发")},y=l=>l.getClientRects().length>0&&getComputedStyle(l).visibility!=="hidden",h=l=>y(l)&&!l.hasAttribute("disabled")&&l.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(l.className),w=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(h),m=()=>{window.removeEventListener(t,g),window.removeEventListener(`${t}:cancel`,p),window.dispatchEvent(new Event(`${t}:stop`))},p=()=>{r=!0,m()},u=async l=>{r||i||(i=!0,m(),await c("BILIBILI_ARTICLE_DONE",{result:l}))},g=l=>{try{const _=JSON.parse(l.detail);if(r||i||_.jobId!==e.id)return;_.phase==="content"&&(s=_.ready===!0),_.phase==="images"&&c("BILIBILI_ARTICLE_PROGRESS",{stage:"uploading_images",current:_.current,total:_.total}).catch(p),_.phase==="request"&&(n=!0,c("BILIBILI_ARTICLE_PROGRESS",{stage:"verifying"}).catch(p)),_.phase==="result"&&u(_).catch(p)}catch{}};window.addEventListener(t,g),window.addEventListener(`${t}:cancel`,p,{once:!0});function D(l,_){throw Object.assign(new Error(_),{manualReason:l})}const A=()=>{if(r||i)throw new Error("本次B站自动投稿已结束");if(Date.now()>=e.deadline)throw new Error("B站专栏投稿超时,请检查平台,不要自动重发");Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="geetest"],.geetest_panel,.bili-captcha,.bili-captcha-container,.geetest_holder')).some(y)&&D("captcha","B站要求人工验证码,请在已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");const l=Array.from(document.querySelectorAll('[role="alert"],.vui_toast,.vui_toast--item,.b-message,.el-message,.vui_dialog,.vui-dialog')).filter(y).map(k=>{var I;return((I=k.textContent)==null?void 0:I.trim())||""}).filter(k=>k.length<1e3);l.some(k=>/验证码|完成验证|安全验证|拖动.*(?:滑块|图片)|点选.*文字/.test(k))&&D("captcha","请在已打开的B站专栏投稿页完成验证码并手动发布,Agent 不要重发。"),l.some(k=>/我已阅读|我同意|原创声明|确认.*声明/.test(k))&&D("agreement","B站要求确认原创声明或协议,请在原投稿页阅读、自行决定并手动发布。"),l.some(k=>/请选择|请设置|封面|未实名|绑定手机|转正答题|声明/.test(k))&&D("publication_settings","B站要求补充封面、账号权限或发布设置,请在原投稿页核对并手动处理。");const _=l.find(k=>/失败|错误|限制|超出|超过|不能为空|图片过大/.test(k));if(_)throw new Error(_.slice(0,300))},b=async(l,_,k)=>{const I=Math.min(Date.now()+_,e.deadline);for(;Date.now()<I;){A();const E=l();if(E)return E;await o(300)}throw new Error(k)},d=()=>(s=!1,window.dispatchEvent(new Event(`${t}:read`)),s),f=async()=>{var N,x;await c("BILIBILI_ARTICLE_PROGRESS",{stage:"preparing_article"});const l=await b(()=>document.querySelector("textarea.title-input__inner:not([disabled])"),3e4,"B站专栏标题输入框未就绪"),_=await b(()=>document.querySelector('.editor-container .ProseMirror[contenteditable="true"]'),3e4,"B站新版专栏正文编辑器未就绪"),k=L=>(L||"").replace(/[\s​-‍]/g,"").length>0;if((k(l.value)||k(_.textContent)||_.querySelector("img"))&&D("publication_settings","B站编辑器已有未发内容,未覆盖原稿,请在已打开的页面自行核对。"),l.maxLength>0&&e.title.length>l.maxLength)throw new Error(`B站当前标题最多 ${l.maxLength} 字,请让 Agent 缩短标题后重新提交,未截断发布`);const I=new DOMParser().parseFromString(e.html,"text/html");if(I.querySelector("video,audio,iframe"))throw new Error("当前B站专栏只接文字和图片,不接视频、音频或嵌入卡片");(x=(N=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"))==null?void 0:N.set)==null||x.call(l,e.title),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0}));const E=new DataTransfer;E.setData("text/html",I.body.innerHTML),E.setData("text/plain",I.body.textContent||""),A(),_.focus();const v=document.createRange();v.selectNodeContents(_);const R=getSelection();if(R==null||R.removeAllRanges(),R==null||R.addRange(v),_.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:E})),await b(()=>{if(_.querySelector(".upload-failed,.image-error"))throw new Error("B站正文图片上传失败,未删除图片后继续发布,请检查原稿件");return d()},5*6e4,"B站正文或图片未完整载入,请在原投稿页检查,未提交发布"),l.value!==e.title)throw new Error("B站标题被修改或截断,已停止发布");const U=await b(()=>w().find(L=>{var $;return(($=L.textContent)==null?void 0:$.trim())==="发布"}),3e4,"B站发布按钮不可用,请检查账号权限和正文要求");if(e.rehearsal){if(!d())throw new Error("B站稿件状态变化,演练未通过");await u({success:!1,publicationState:"rehearsed"});return}const B=new Set(w());if(await c("BILIBILI_ARTICLE_PROGRESS",{stage:"publishing"}),A(),!U.isConnected||!h(U)||l.value!==e.title||!d())throw new Error("B站稿件或发布控件状态变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,U.click();const W=Math.min(Date.now()+12e4,e.deadline);let P=!1;for(;!r&&!i&&Date.now()<W;){if(A(),!n&&!P){const L=w().find($=>{var S;return!B.has($)&&/^(?:确认发布|确认并发布|发布)$/.test(((S=$.textContent)==null?void 0:S.trim())||"")&&!!$.closest('[role="dialog"],.vui_dialog,.vui-dialog')});L&&(P=!0,L.click())}await o(300)}!r&&!i&&await u({success:!1,publicationState:"unknown",error:"已触发B站专栏发布,但未取得匹配的成功回执,请检查平台,不要自动重发。"})};try{const l=sessionStorage.getItem(t);l&&g(new CustomEvent(t,{detail:l}))}catch{}return!r&&!i&&f().catch(l=>{r||i||u(l!=null&&l.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:l.manualReason,message:l.message}:{success:!1,publicationState:a?"unknown":"failed",error:l instanceof Error?l.message:"B站专栏投稿失败"}).catch(p)}),{started:!0}}const Re=new Map,ar=e=>{try{const t=new URL(e);return t.protocol==="https:"&&["member.bilibili.com","www.bilibili.com"].includes(t.hostname)}catch{return!1}};async function xi(e,t,r,i={}){const a=i.rehearsal===!0,n=crypto.randomUUID(),s=crypto.randomUUID(),o=crypto.randomUUID(),c=Date.now()+10*6e4,y=`https://member.bilibili.com/platform/upload/text?writedock_article=${n}`,h=await chrome.tabs.create({url:y,active:!0});if(!h.id)throw new Error("无法打开B站专栏编辑页");const w=h.id;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!Re.has(n)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:w,platform:"bilibili",channel:o,url:b.editUrl,message:"B站要求输入验证码。请在已打开的投稿页输入验证码并点“确定”,确定后 B站会自动发布,不需要再点“发布”;结果会自动更新。",isActive:()=>Re.has(n),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}Re.delete(n),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),b.frameId!==void 0&&chrome.scripting.executeScript({target:{tabId:w,frameIds:[b.frameId]},world:"ISOLATED",func:E=>{window.dispatchEvent(new Event(`${E}:cancel`)),window.dispatchEvent(new Event(`${E}:stop`)),sessionStorage.removeItem(E)},args:[`writedock-bilibili-${o}`]}).catch(()=>{});let l="";try{const E=new URL(d.postUrl||"");E.origin==="https://www.bilibili.com"&&/^\/opus\/\d{1,24}$/.test(E.pathname)&&d.postId===E.pathname.split("/").pop()&&(l=E.href)}catch{}if(a&&d.publicationState==="rehearsed"){Ae(w,Ge("bilibili",b.editUrl),d.warnings).then(m);return}const _=!a&&b.attempted&&d.success===!0&&d.publicationState==="submitted"&&d.responseConfirmed===!0&&!!l,k=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),I=String(d.message||"请在已打开的B站原投稿页完成验证或设置并手动发布,Agent 不要重新提交。").slice(0,1e3);Ae(w,{platform:"bilibili",success:_,draftOnly:!1,publicationState:_?"submitted":k?"needs_user_action":b.attempted?"unknown":"failed",postUrl:_?l:b.editUrl,timestamp:Date.now(),..._?{postId:d.postId,message:"B站专栏发布接口已确认提交,展示状态以平台为准"}:k?{requiresUserAction:!0,userAction:{type:d.manualReason,url:b.editUrl,message:I},message:I}:{error:d.error||"B站专栏发布结果未确认,请检查原稿件,不要自动重发"}},d.warnings).then(m)},g=d=>{d===w&&u({error:"B站专栏投稿页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;d!==w||!Re.has(n)||((_=l.url)!=null&&_.startsWith("https://member.bilibili.com/")&&(b.editUrl=l.url),!(f.status!=="complete"||!b.attempted)&&chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",func:k=>["member.bilibili.com","www.bilibili.com"].includes(location.hostname)?sessionStorage.getItem(k):null,args:[`writedock-bilibili-${o}`]}).then(k=>{for(const I of k){if(typeof I.result!="string"||!Re.has(n))continue;const E=JSON.parse(I.result);if(E.jobId===n&&E.phase==="result"){u(E);break}}}).catch(()=>{}))},A=setTimeout(()=>u({error:"等待B站专栏发布超时,请检查原稿件,不要自动重发"}),10*6e4),b={tabId:w,secret:s,channel:o,editUrl:y,attempted:!1,progress:r,finish:u};Re.set(n,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var l,_,k,I;const d=Date.now()+6e4;let f=!1;for(;Re.has(n)&&Date.now()<d;){const E=await chrome.tabs.get(w);if(ar(E.url||"")){const R=(await chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",func:()=>{if(location.protocol!=="https:"||!["member.bilibili.com","www.bilibili.com"].includes(location.hostname))return!1;const U=document.querySelector('.editor-container .ProseMirror[contenteditable="true"]'),B=document.querySelector("textarea.title-input__inner");return!!U&&!!B&&U.getClientRects().length>0&&B.getClientRects().length>0}})).filter(U=>U.result===!0);if(!R.length){const U=await chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",args:[f],func:B=>{if(location.protocol!=="https:"||location.hostname!=="member.bilibili.com")return null;const W=x=>x.getClientRects().length>0&&getComputedStyle(x).visibility!=="hidden";if(Array.from(document.querySelectorAll('.vui_dialog--body,.vui_dialog,[role="dialog"]')).filter(W).map(x=>x.textContent||"").some(x=>/当日投稿上限|今日投稿.*上限|已达.*上限/.test(x)))return"limit";if(B)return null;const N=Array.from(document.querySelectorAll('button.new-creation_button,button,[role="button"]')).find(x=>{var L;return W(x)&&((L=x.textContent)==null?void 0:L.trim())==="新的创作"});return N?(N.click(),"clicked"):null}}).catch(()=>[]);if(U.some(B=>B.result==="limit")){u({error:"B站账号已达到当日专栏投稿上限(LV1–3 每天 1 篇),今天无法再自动发布,未提交。请明天再试,或在B站手动保存为草稿。"});return}U.some(B=>B.result==="clicked")&&(f=!0,b.progress({stage:"preparing_article"}))}if(R.length>1)throw new Error("发现多个B站专栏编辑器,未选择不明确的稿件发布");if(R.length===1){const U=R[0];b.frameId=U.frameId,b.documentId=typeof U.documentId=="string"?U.documentId:void 0;const B={tabId:w,frameIds:[U.frameId]};await Je(w);const W=await chrome.scripting.executeScript({target:B,world:"MAIN",func:Ai,args:[{id:n,channel:o,title:e,html:t,deadline:c,rehearsal:a}]});if(!Re.has(n))return;if(!((_=(l=W[0])==null?void 0:l.result)!=null&&_.observing))throw new Error("无法监测B站专栏发布回执,已停止投稿");if(!((I=(k=(await chrome.scripting.executeScript({target:B,world:"ISOLATED",func:Ii,args:[{id:n,secret:s,channel:o,title:e,html:t,deadline:c,rehearsal:a}]}))[0])==null?void 0:k.result)!=null&&I.started))throw new Error("无法启动B站专栏投稿脚本");return}}else if(E.status==="complete")throw new Error("B站专栏未进入编辑页,请先完成登录");await new Promise(v=>setTimeout(v,500))}if(Re.has(n))throw new Error(f?"已点击B站「新的创作」,但专栏编辑器未出现,请确认账号权限与登录状态":"B站专栏页未找到「新的创作」入口或编辑器,请确认账号权限与登录状态")})().catch(d=>u({error:d instanceof Error?d.message:"启动B站专栏投稿失败"}))})}async function Ri(e,t){var i;const r=Re.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==r.frameId||r.documentId&&t.documentId!==r.documentId||!ar(t.url||"")||e.jobSecret!==r.secret)throw new Error("B站专栏任务已结束或来源不匹配");if(e.type==="BILIBILI_ARTICLE_PROGRESS"){if(!["preparing_article","uploading_images","publishing","verifying"].includes(String(e.stage)))throw new Error("B站专栏投稿阶段不正确");return["publishing","verifying"].includes(String(e.stage))&&(r.attempted=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="BILIBILI_ARTICLE_DONE")return r.finish(e.result||{error:"B站专栏没有返回结果"}),!0;throw new Error("不支持的B站专栏页面操作")}let Be=!1,ve=null,Ft=Promise.resolve();const At=new Set;function Se(e){const t=Ft.catch(()=>{}).then(e);return Ft=t.then(()=>{},()=>{}),t}function Dt(){return Be}async function ki(e){await Se(async()=>{const r=(await chrome.storage.local.get(te.draftIndex))[te.draftIndex]||[],{id:i,title:a,updatedAt:n,source:s}=e;await chrome.storage.local.set({[`writedockDraft:${i}`]:e,[te.draftIndex]:[{id:i,title:a,updatedAt:n,source:s},...r.filter(o=>o.id!==i)]}),chrome.runtime.sendMessage({type:"DRAFT_SAVED",draftId:i}).catch(()=>{})})}async function Lt(e){const t=await or();return(t==null?void 0:t.id)===e?t:(await Ut()).find(r=>r.id===e)||null}async function wt(){const e=await chrome.storage.local.get([te.activeTask,te.history,te.lastInput]),t=e[te.activeTask]||null,r=e[te.history]||[],i=e[te.lastInput],a=[...new Set([t==null?void 0:t.draftId,...r.map(m=>m.draftId),i==null?void 0:i.input.draftId].filter(m=>!!m))],n=await Promise.all(a.map(async m=>[m,await chrome.storage.local.getBytesInUse(`writedockDraft:${m}`)>0])),s=new Set(n.filter(([,m])=>m).map(([m])=>m)),o=m=>s.has(m),c=t&&o(t.draftId)?t:null,y=r.filter(m=>o(m.draftId)),h=i&&o(i.input.draftId)?i:null,w=[];return t&&!c&&w.push(te.activeTask),i&&!h&&w.push(te.lastInput),y.length!==r.length&&await chrome.storage.local.set({[te.history]:y}),w.length&&await chrome.storage.local.remove(w),{active:c,history:y,last:h}}async function et(){if(!ve)return;const e=structuredClone(ve);await Se(async()=>{await chrome.storage.local.set({[te.activeTask]:e}),chrome.runtime.sendMessage({type:"TASK_UPDATED",task:e}).catch(()=>{})})}async function or(){return Be&&ve?structuredClone(ve):Se(async()=>{const{active:e}=await wt();return Be&&ve?structuredClone(ve):((e==null?void 0:e.status)==="syncing"&&(e.status="interrupted",e.finishedAt=Date.now(),e.error="上次任务被中断。请把原稿件或平台后台链接交给用户自行核对,Agent 不要调用浏览器或重新投稿。",await chrome.storage.local.set({[te.activeTask]:e})),e)})}async function Ut(){return Se(async()=>(await wt()).history)}async function $i(e){return Se(async()=>{const{last:t}=await wt();if(!t||t.taskId!==e)throw new Error("该任务的原始内容已被替换,请打开原稿后重新同步");return t.input})}async function Ti(e){if(typeof e!="string"||!e)throw new Error("草稿信息不完整");if(Be&&(ve==null?void 0:ve.draftId)===e)throw new Error("这篇文章正在同步,请等待同步结束后再删除");At.add(e);try{return await Se(async()=>{var c,y;const t=await chrome.storage.local.get([te.draftIndex,te.activeDraft,te.activeTask,te.history,te.lastInput,te.agentRequests]),r=(t[te.draftIndex]||[]).filter(h=>h.id!==e),i=(t[te.history]||[]).filter(h=>h.draftId!==e),a=[`writedockDraft:${e}`],n=((c=t[te.activeTask])==null?void 0:c.draftId)===e;n&&a.push(te.activeTask),((y=t[te.lastInput])==null?void 0:y.input.draftId)===e&&a.push(te.lastInput),t[te.activeDraft]===e&&a.push(te.activeDraft);const s=t[te.agentRequests]||{},o=Object.fromEntries(Object.entries(s).map(([h,w])=>[h,w.draftId===e?{...w,deleted:!0}:w]));return await chrome.storage.local.set({[te.draftIndex]:r,[te.history]:i,[te.agentRequests]:o}),await chrome.storage.local.remove(a),(ve==null?void 0:ve.draftId)===e&&(ve=null),n&&await chrome.action.setBadgeText({text:""}).catch(()=>{}),chrome.runtime.sendMessage({type:"DRAFT_DELETED",draftId:e}).catch(()=>{}),r})}finally{At.delete(e)}}async function Ci(e){var i;let t=await at(e);if(!t.isAuthenticated&&t.error&&(t=await at(e)),t.isAuthenticated)return;const r=((i=Ue().find(a=>a.id===e))==null?void 0:i.name)||e;throw Object.assign(new Error(t.error?`无法确认${r}的登录状态,未执行发布:${t.error}`:`${r}未登录,未执行发布。请在装有扩展的浏览器中登录后再提交`),{errorCode:t.error?"login_unconfirmed":"not_logged_in"})}async function Ot(e,t={}){var p;if(Be)throw new Error("已有一项同步正在进行,请等待完成");if(At.has(e==null?void 0:e.draftId))throw new Error("草稿正在删除,无法同步");const r=xt(e==null?void 0:e.platforms,Ue().map(u=>u.id)),i=e.post?Le(e.post):void 0,a=e.publication==="article",n=e.rehearsal===!0,s=e.routes;if(n&&!i&&!a&&!s)throw new Error("演练只支持发布类平台;公众号、搜狐号只保存草稿,无需演练");const o={rehearsal:n},c=di(e.discardOldDrafts,"douyin",n);if(!s){if(i?a||r.some(u=>!Rt(u)):r.some(u=>ft(u)&&!(a&&u==="xiaohongshu")))throw new Error("普通图文/视频用 publish_post,小红书长文及平台文章用 publish_article,需分别提交;旧草稿调用不会自动公开发布");if(i&&mt(i,r),a&&r.some(u=>!["zhihu","baijiahao","weibo","bilibili","xiaohongshu"].includes(u)))throw new Error("文章直发目前接入知乎、百家号、微博长文章、B站专栏和小红书长文");if(!i&&!a&&r.some(u=>["zhihu","baijiahao","weibo","bilibili"].includes(u)))throw new Error("知乎、百家号、微博长文章、B站专栏请使用 publish_article,旧草稿调用不会自动公开发布")}if(!(e!=null&&e.article)||typeof e.article.title!="string"||!e.article.title.trim())throw new Error("请先填写文章标题");if(typeof e.article.html!="string"||!Vt(e.article.html))throw new Error("请先编写文章正文或插入图片");if(new TextEncoder().encode(JSON.stringify(e.article)).length>24*1024*1024)throw new Error("文章图片过大,请压缩图片或减少图片后再同步");if(typeof e.draftId!="string")throw new Error("稿件信息不完整,请重新打开写作台");const y=$t(e.article.videos,e.article.html);if(!s){if(y.length&&(!a||r.some(u=>u!=="zhihu")))throw new Error("文章内嵌视频目前只支持知乎直发");if(a&&r.includes("zhihu")&&e.article.title.trim().length>100)throw new Error("知乎标题最多 100 字");if(a&&r.includes("baijiahao")&&(e.article.title.trim().length>64||!e.article.cover))throw new Error("百家号请提供 64 字以内的标题和必选封面 cover");if(a&&r.includes("weibo")&&e.article.title.trim().length>32)throw new Error("当前微博长文章接入接收 32 字以内的标题");if(a&&r.includes("xiaohongshu")&&e.article.title.trim().length>64)throw new Error("小红书长文标题最多 64 字");if(a&&r.includes("xiaohongshu")&&e.article.cover)throw new Error("小红书长文由原生自动排版生成封面,不接独立 cover,请分别提交");if(a&&r.includes("bilibili")&&e.article.cover)throw new Error("当前B站专栏未接入独立封面 cover,请与需要封面的平台分别提交");if(a&&!r.some(u=>["baijiahao","weibo"].includes(u))&&e.article.cover)throw new Error("独立封面 cover 目前用于百家号和微博长文章")}Be=!0,ve={id:t.taskId||`sync_${crypto.randomUUID()}`,draftId:e.draftId,title:e.article.title.trim(),platforms:r,status:"syncing",progress:Object.fromEntries(r.map(u=>[u,{stage:"pending"}])),results:[],startedAt:Date.now(),action:n?"rehearsal":s||i||a?"publish":"draft"};const h=ve,w=new Map,m=(u,g)=>{var D;h.progress[u]=g,g.stage==="waiting_verification"&&((D=w.get(u))==null||D()),et().catch(A=>console.warn("[WriteDock] Progress could not be saved:",A))};try{await Se(async()=>{if(await chrome.storage.local.getBytesInUse(`writedockDraft:${e.draftId}`)===0)throw new Error("这篇草稿已被删除,请重新打开写作台");const{discardOldDrafts:A,...b}=e;await chrome.storage.local.set({[te.lastInput]:{taskId:h.id,input:b}})}),await et(),(p=t.onStarted)==null||p.call(t,structuredClone(h));const u=s||i||a?1:3,g=[];for(let A=0;A<r.length;A+=u){const b=r.slice(A,A+u),d=Promise.all(b.map(async f=>{var v,R;let l;const _=s==null?void 0:s.find(U=>U.platform===f),k=_?_.mode==="post":!!i,I=_?_.mode==="article":a,E=_?{...e.article,cover:_.cover}:e.article;try{if(_!=null&&_.error)throw new Error(_.error);if(m(f,{stage:"checking_auth"}),await Ci(f),k&&i)l=await ri(f,i,U=>m(f,U),f==="douyin"&&c?{...o,discardOldDraft:c}:o);else if(I&&f==="xiaohongshu")l=await Kr(e.article.title.trim(),e.article.html||"",U=>m(f,U),o);else{const U=await Yt(f),B=await Lr(e.article.html||"",Dr(f));for(const{marker:W,asset:P}of y){if(!(U instanceof Zt)||B.html.split(W).length!==2)throw new Error("文章视频占位符在排版后不完整,已停止发布");m(f,{stage:"uploading_media",current:0,total:P.size});const N=await U.uploadArticleVideo(P,($,S)=>Ct(P,$,S),($,S)=>m(f,{stage:"uploading_media",current:$,total:S})),x=Me(N.cover),L=`<a class="video-link" href="https://www.zhihu.com/video/${N.videoId}" data-src="" data-name="${Me(P.name)}" data-poster="${x}" data-video-id="" data-lens-id="${N.videoId}" data-video-playable="true"><img src="${x}" alt="${Me(P.name)}"><span>${Me(P.name)}</span></a>`;B.html=B.html.replace(W,L)}if(m(f,{stage:I?"preparing_article":"saving"}),I&&f==="bilibili")l=await xi(e.article.title.trim(),B.html,W=>m(f,W),o);else{const W=await Et(U.publish({...E,...B,...I&&f==="zhihu"?{cover:void 0}:{}},{draftOnly:!0,onImageProgress:(P,N)=>{m(f,{stage:P>=N?I?"preparing_article":"saving":"uploading_images",current:P,total:N})}}),6e5,"准备平台稿件超时,请先检查平台后台,再决定是否重试");if(I){if(!W.success||!W.postId)throw new Error(W.error||"平台稿件准备失败,未提交发布");const P=f==="zhihu"?fi:f==="weibo"?Ei:yi,N=(B.html.replace(/<a class="video-link"[\s\S]*?<\/a>/g,"").match(/<img\b/gi)||[]).length;l=await P(String(W.postId),e.article.title.trim(),x=>m(f,x),{...o,imageCount:N})}else l=W}}}catch(U){l={platform:f,success:!1,error:U instanceof Error?U.message:"同步失败,请稍后重试",timestamp:Date.now(),...k||I?{draftOnly:!1,publicationState:"failed"}:{},...U.errorCode?{errorCode:U.errorCode}:{}}}(v=_==null?void 0:_.notes)!=null&&v.length&&(l={...l,warnings:[..._.notes,...l.warnings||[]]}),l.success||(l={...l,diagnostics:{...l.diagnostics,stage:(R=h.progress[f])==null?void 0:R.stage}}),h.results.push(l),h.progress[f]={stage:l.publicationState==="needs_user_action"?"needs_user_action":l.publicationState==="unknown"?"unknown":l.success||l.publicationState==="rehearsed"?"completed":"failed",error:l.error},await et()}));g.push(d),await Promise.race([d,new Promise(f=>{for(const l of b)w.set(l,f)})])}await Promise.all(g),h.status=wr(h.results,r.length),h.finishedAt=Date.now(),await et(),await Se(async()=>{const{history:A}=await wt();await chrome.storage.local.set({[te.history]:[structuredClone(h),...A].slice(0,25)})});const D=h.results.filter(A=>A.success||A.publicationState==="rehearsed").length;return await chrome.action.setBadgeText({text:D===r.length?"✓":`${D}`}),await chrome.action.setBadgeBackgroundColor({color:D===r.length?"#2563eb":"#9a6700"}),structuredClone(h)}catch(u){throw h.status="failed",h.error=u instanceof Error?u.message:"同步任务失败",h.finishedAt=Date.now(),await et().catch(()=>{}),u}finally{Be=!1}}let Wt=Promise.resolve();function gt(e){const t=Wt.catch(()=>{}).then(e);return Wt=t,t}async function Pt(e){if(!e||typeof e!="object")throw new Error("请提供稿件内容");const t=e;if(typeof t.title!="string"||!t.title.trim()||t.title.trim().length>200)throw new Error("文章标题需要 1–200 字");if(typeof t.html!="string"||new TextEncoder().encode(JSON.stringify(t)).length>24*1024*1024)throw new Error("稿件格式不正确,或超过 24 MB");if(t.cover&&!rt(t.cover)&&!/^data:image\/(png|jpeg|gif|webp);base64,/i.test(t.cover))throw new Error("封面图片地址无效");const r=await Ur(t.html);if(!Vt(r))throw new Error("稿件正文为空");const i=$t(t.videos,r);return{title:t.title.trim(),html:r,markdown:"",...t.cover?{cover:t.cover}:{},...i.length?{videos:i}:{}}}async function yt(e,t=[],r){var n;const i=Date.now(),a={id:crypto.randomUUID(),title:e.title,html:e.html||"",cover:e.cover||"",platforms:t,createdAt:i,updatedAt:i,source:"mcp",...r?{post:r}:{},...(n=e.videos)!=null&&n.length?{videos:e.videos}:{}};return await ki(a),a}async function Di(e){return gt(async()=>{var i;const t=await Pt(e),r=await yt(t);return{draft_id:r.id,title:r.title,image_count:(r.html.match(/<img\b/gi)||[]).length,video_count:((i=r.videos)==null?void 0:i.length)||0,saved_locally:!0}})}async function Li(e){return gt(async()=>{const t=Le(e);return{draft_id:(await yt(Tt(t),[],t)).id,title:t.title,kind:t.kind,image_count:t.images.length,...t.video?{video_file:t.video.name}:{},saved_locally:!0}})}async function qt(e){const r=(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{};return Object.hasOwn(r,e)?r[e]:void 0}const Ui=e=>{const t=r=>e.results.filter(r).map(i=>i.platform);return{submitted:t(r=>r.success&&!r.draftOnly),draft_saved:t(r=>r.success&&r.draftOnly===!0),rehearsed:t(r=>r.publicationState==="rehearsed"),not_logged_in:t(r=>r.errorCode==="not_logged_in"),login_unconfirmed:t(r=>r.errorCode==="login_unconfirmed"),needs_user_action:t(r=>r.publicationState==="needs_user_action"),waiting_verification:e.platforms.filter(r=>{var i;return((i=e.progress[r])==null?void 0:i.stage)==="waiting_verification"}),unknown:t(r=>r.publicationState==="unknown"),failed:t(r=>!r.success&&!r.errorCode&&!["rehearsed","needs_user_action","unknown"].includes(r.publicationState||"")),pending:e.platforms.filter(r=>{var i;return!e.results.some(a=>a.platform===r)&&((i=e.progress[r])==null?void 0:i.stage)!=="waiting_verification"})}},ot=(e,t=!1)=>{var n;const r=Ue(),i=e.results.flatMap(s=>{var y,h,w,m;const o=s.requiresUserAction||s.publicationState==="needs_user_action";if(!o&&s.publicationState!=="unknown")return[];const c=rt(((y=s.userAction)==null?void 0:y.url)||s.postUrl)||rt((h=r.find(p=>p.id===s.platform))==null?void 0:h.homepage);return[{platform:s.platform,type:((w=s.userAction)==null?void 0:w.type)||(o?"publication_settings":"result_unconfirmed"),...c?{url:c}:{},message:((m=s.userAction)==null?void 0:m.message)||s.message||s.error||"请用户在原稿件页核对并手动处理。"}]});if(e.status==="interrupted")for(const s of e.platforms.filter(o=>!e.results.some(c=>c.platform===o))){const o=rt((n=r.find(c=>c.id===s))==null?void 0:n.homepage);i.push({platform:s,type:"result_unconfirmed",...o?{url:o}:{},message:"任务已中断,结果未确认。请用户点击平台链接自行核对,不要重新投稿。"})}for(const[s,o]of Object.entries(e.progress)){if(o.stage!=="waiting_verification")continue;const c=rt(o.url);i.push({platform:s,type:"captcha",...c?{url:c}:{},message:o.message||"请在已打开的页面完成验证。"})}if(e.action==="rehearsal")for(const s of i)s.message=s.type==="old_draft"?"演练未走完:抖音有一份上次没发完的内容,演练不会动它。真实发布时再问用户是否放弃。":`演练未走完:${s.message.replace(/并手动发布|并手动处理|手动发布/g,"")}这只是演练,不需要点击发布。`;const a=e.status!=="syncing";return{task_id:e.id,draft_id:e.draftId,status:e.status,reused:t,finished:a,next_action:a?"report_result":"poll_task",...a?{}:{poll_after_ms:3e3},...e.action==="rehearsal"?{rehearsal:!0}:{},agent_instructions:(e.action==="rehearsal"?"这是演练任务,没有向平台提交发布,rehearsed 不代表已发布,不得告诉用户内容已发出;未经用户明确要求,不要接着调用发布工具。":"")+"仅通过 WriteDock MCP 获取发布结果,不需要也不得调用浏览器、Playwright 或其他网页工具验证或处理投稿。任务进行中按原 task_id/request_id 调用 get_sync_task,不重复提交;submitted/published 直接向用户汇报确认结果和链接,不再打开网页验证。needs_user_action、unknown 或 interrupted 时,将原因和 user_actions 链接交给用户自行点击、验证或手动发布;不要代做验证码、自动重发或更换 request_id。人工接管后不声称已发布。失败时把 error 和 diagnostics(阶段、页面结构、请求记录)原样提供给用户或开发者排查;warnings 是平台字段变化的提醒,不代表失败,一并转告。waiting_verification 表示该平台在等用户完成验证码:立即把 user_actions 的 message 和链接原样告诉用户,由用户在已打开的页面手动完成验证,Agent 不代做、不重发,并继续查询;用户验证后任务会自动更新结果。任务结束后按 summary 逐平台告诉用户结果:哪些成功,哪些未登录(not_logged_in,未执行发布,让用户登录后用新的 request_id 只重发这些平台)。",requires_user_action:i.length>0,...i.length?{user_actions:i}:{},summary:Ui(e),results:e.results,task:e}};async function tt(e){return gt(async()=>{var g,D;const t=e.rehearsal===!0,r=e.requestId;if(!t&&(typeof r!="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(r)))throw new Error("请提供 8–120 位稳定的 request_id(字母、数字、下划线或横线)");const i=t?void 0:await qt(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=xt(e.platforms,Ue().map(A=>A.id)),n=e.publication===!0,s=e.publication==="article";if(t&&!n&&!s)throw new Error("演练只支持发布类平台;公众号、搜狐号只保存草稿,无需演练");if(n&&a.some(A=>!Rt(A)))throw new Error("publish_post 支持小红书、抖音和微博普通图文/视频;知乎、百家号、微博长文章、B站专栏请用 publish_article");if(!n&&a.some(A=>ft(A)&&!(s&&A==="xiaohongshu")))throw new Error("小红书长文请用 publish_article;小红书、抖音图文/视频请用 publish_post;旧草稿调用不会自动公开发布");if(s&&a.some(A=>!["zhihu","baijiahao","weibo","bilibili","xiaohongshu"].includes(A)))throw new Error("publish_article 目前接入知乎、百家号、微博长文章、B站专栏和小红书长文");if(!i&&!n&&!s&&a.some(A=>["zhihu","baijiahao","weibo","bilibili"].includes(A)))throw new Error("知乎、百家号、微博长文章、B站专栏已改用 publish_article;旧草稿调用不会自动公开发布");let o,c,y;if(typeof e.draftId=="string"){if(e.article||e.post)throw new Error("draft_id 与稿件内容不能同时提供");if(o=(await chrome.storage.local.get(`writedockDraft:${e.draftId}`))[`writedockDraft:${e.draftId}`],!o)throw new Error("稿件不存在或已被删除");if(n){if(!o.post)throw new Error("请先用 prepare_post 准备图文或视频素材");y=Le(o.post)}else if(o.post)throw new Error("该稿件是图文或视频投稿,请使用 publish_post");c={title:o.title,html:o.html,markdown:"",cover:o.cover||void 0,...(g=o.videos)!=null&&g.length?{videos:$t(o.videos,o.html)}:{}}}else n?(y=Le(e.post),c=Tt(y)):c=await Pt(e.article);if(y&&mt(y,a),(D=c.videos)!=null&&D.length&&(!s||a.some(A=>A!=="zhihu")))throw new Error("文章内嵌视频目前只支持单独向知乎 publish_article");if(s&&a.includes("zhihu")&&c.title.length>100)throw new Error("知乎文章标题最多 100 字,请先缩短标题");if(s&&a.includes("baijiahao")&&(c.title.length>64||!c.cover))throw new Error("百家号直发请提供 64 字以内的标题和必选封面 cover(本地图片路径或图片地址)");if(s&&a.includes("weibo")&&c.title.length>32)throw new Error("当前微博长文章接入接收 32 字以内的标题");if(s&&a.includes("xiaohongshu")&&c.title.length>64)throw new Error("小红书长文标题最多 64 字,请先缩短标题");if(s&&a.includes("xiaohongshu")&&c.cover)throw new Error("小红书长文由原生自动排版生成封面,不接独立 cover,请与需要封面的平台分别提交");if(s&&a.includes("bilibili")&&c.cover)throw new Error("当前B站专栏未接入独立封面 cover,请与需要封面的平台分别提交");if(s&&!a.some(A=>["baijiahao","weibo"].includes(A))&&c.cover)throw new Error("独立封面 cover 目前用于百家号和微博长文章");const{videos:h,...w}=c,m=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({article:w,platforms:[...a].sort(),draftId:e.draftId||null,...y?{post:rr(y)}:{},...s?{publication:"article",...h!=null&&h.length?{videos:tr(h)}:{}}:{}}))),p=Array.from(new Uint8Array(m),A=>A.toString(16).padStart(2,"0")).join("");if(i){if(i.fingerprint!==p)throw new Error("同一个 request_id 对应的稿件或平台已改变;请使用新的 request_id");const A=await Lt(i.taskId);if(!A)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return ot(A,!0)}if(Dt())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");o??(o=await yt(c,a,y));const u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Se(async()=>{const A=await chrome.storage.local.get(te.agentRequests);await chrome.storage.local.set({[te.agentRequests]:{...A[te.agentRequests]||{},[r]:{fingerprint:p,draftId:o.id,taskId:u}}})});try{const A=await new Promise((b,d)=>{Ot({draftId:o.id,platforms:a,article:c,...y?{post:y}:{},...s?{publication:"article"}:{},...t?{rehearsal:!0}:{}},{taskId:u,onStarted:b}).catch(d)});return ot(A)}catch(A){throw t||await Se(async()=>{const d={...(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{}};delete d[r],await chrome.storage.local.set({[te.agentRequests]:d})}),A}})}async function jt(e){return gt(async()=>{const t=e.rehearsal===!0,r=e.requestId;if(!t&&(typeof r!="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(r)))throw new Error("请提供 8–120 位稳定的 request_id(字母、数字、下划线或横线)");const i=t?void 0:await qt(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=xt(e.platforms,Ue().map(g=>g.id));if(!e.article&&!e.post)throw new Error("请提供 article(文章)或 post(图文/视频)内容");const n=e.article?await Pt(e.article):void 0,s=e.post?Le(e.post):void 0,o=li({platforms:a,article:n,post:s,modes:e.modes,rehearsal:t});if(o.every(g=>g.error))throw new Error(`所有平台都无法接收这份内容:${o.map(g=>g.error).join(";")}`);const c=n||Tt(s),{videos:y,...h}=c,w=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({unified:!0,article:h,routes:o.map(({platform:g,mode:D})=>({platform:g,mode:D})).sort((g,D)=>g.platform.localeCompare(D.platform)),...s?{post:rr(s)}:{},...y!=null&&y.length?{videos:tr(y)}:{}}))),m=Array.from(new Uint8Array(w),g=>g.toString(16).padStart(2,"0")).join("");if(i){if(i.fingerprint!==m)throw new Error("同一个 request_id 对应的稿件或平台已改变;请使用新的 request_id");const g=await Lt(i.taskId);if(!g)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return ot(g,!0)}if(Dt())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");const p=await yt(c,a,s),u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Se(async()=>{const g=await chrome.storage.local.get(te.agentRequests);await chrome.storage.local.set({[te.agentRequests]:{...g[te.agentRequests]||{},[r]:{fingerprint:m,draftId:p.id,taskId:u}}})});try{const g=await new Promise((D,A)=>{Ot({draftId:p.id,platforms:a,article:c,...s?{post:s}:{},routes:o,...t?{rehearsal:!0}:{},...e.discardOldDrafts?{discardOldDrafts:e.discardOldDrafts}:{}},{taskId:u,onStarted:D}).catch(A)});return ot(g)}catch(g){throw t||await Se(async()=>{const A={...(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{}};delete A[r],await chrome.storage.local.set({[te.agentRequests]:A})}),g}})}async function Oi(e){let t=e.taskId;if(typeof e.requestId=="string"){const i=await qt(e.requestId);if(!i||i.deleted)throw new Error("该请求没有可查询的本地任务,或其稿件已被删除");if(t&&t!==i.taskId)throw new Error("task_id 与 request_id 不匹配");t=i.taskId}if(typeof t!="string"||!t)throw new Error("请提供 task_id 或 request_id");const r=await Lt(t);if(!r)throw new Error("任务不存在,或已超出最近 25 条记录的保留范围");return ot(r)}const Mt="writedock-mcp-reconnect";let It,Ee=null,it,Bt=0,ht=!1,st,dt=!1,pt={};const sr=()=>Array.from(crypto.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join("");async function ct(){return It??(It=(async()=>{const t=(await chrome.storage.local.get(te.bridge))[te.bridge],r={enabled:(t==null?void 0:t.enabled)===!0,port:Number.isInteger(t==null?void 0:t.port)&&t.port>=1024&&t.port<=65535?t.port:9647,token:typeof(t==null?void 0:t.token)=="string"&&/^[A-Za-z0-9_-]{24,128}$/.test(t.token)?t.token:sr()};return await chrome.storage.local.set({[te.bridge]:r}),r})()),It}async function ut(e,t){ht=e,st=t,e||(pt={}),chrome.runtime.sendMessage({type:"BRIDGE_STATUS_UPDATED"}).catch(()=>{})}const Pi=(e,t)=>{const r=n=>n.split(/[-+]/)[0].split(".").map(Number),i=r(e),a=r(t);for(let n=0;n<3;n++)if(i[n]!==a[n])return i[n]>a[n];return!1};function Jt(e){const t=i=>typeof i=="string"&&i.length<=120&&/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(i);if(!t(e.mcp_version))return;const r={mcpVersion:e.mcp_version,...t(e.latest_version)?{mcpLatestVersion:e.latest_version}:{},mcpUpdateAvailable:t(e.latest_version)&&e.update_available===!0,...typeof e.update_checked_at=="number"&&Number.isSafeInteger(e.update_checked_at)?{mcpUpdateCheckedAt:e.update_checked_at}:{},...typeof e.update_check_error=="string"?{mcpUpdateCheckError:e.update_check_error.slice(0,200)}:{},mcpUpdateChecking:e.update_checking===!0,...t(e.extension_bundle_version)&&Pi(e.extension_bundle_version,chrome.runtime.getManifest().version)?{extensionUpdateVersion:e.extension_bundle_version}:{}};JSON.stringify(r)!==JSON.stringify(pt)&&(pt=r,chrome.runtime.sendMessage({type:"BRIDGE_STATUS_UPDATED"}).catch(()=>{}))}async function Gt(e,t,r){const i=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",i,new TextEncoder().encode(`${t}:${r}`));return Array.from(new Uint8Array(a),n=>n.toString(16).padStart(2,"0")).join("")}async function qi(e){try{const r=await(await fetch(`http://127.0.0.1:${e}/hello`,{signal:AbortSignal.timeout(1500),cache:"no-store"})).json();return(r==null?void 0:r.service)==="writedock-mcp"?{mcpFound:!0,...typeof r.version=="string"?{mcpFoundVersion:r.version.slice(0,40)}:{}}:{}}catch{return{}}}async function cr(){const e=await ct();return{...e,connected:ht,...pt,...st?{error:st}:{},...ht?{}:await qi(e.port)}}let We;async function Mi(){if(Dt())throw new Error("正在发布,请等任务结束后再更新");if(!Ee||Ee.readyState!==WebSocket.OPEN||!ht)throw new Error("还没有连接,无法更新");const e=await new Promise((t,r)=>{const i=setTimeout(()=>{We=void 0,r(new Error("更新超时,请稍后再试"))},6e4);We={resolve:a=>{clearTimeout(i),We=void 0,t(a)}},Ee.send(JSON.stringify({type:"update_extension"}))});if(e.ok!==!0)throw new Error(typeof e.error=="string"?e.error:"更新失败");return setTimeout(()=>chrome.runtime.reload(),300),!0}async function Bi(){if(dt)throw new Error("正在连接,请稍候");dt=!0;try{const e=await ct(),t=await new Promise((r,i)=>{const a=new WebSocket(`ws://127.0.0.1:${e.port}/connect`),n=setTimeout(()=>{a.close(),i(new Error("连接超时,请确认 agent 已启动 WriteDock"))},8e3);a.onmessage=s=>{clearTimeout(n);try{const o=JSON.parse(s.data);if(o.type!=="connect_result"||typeof o.token!="string"||!/^[A-Za-z0-9_-]{24,128}$/.test(o.token)||o.port!==e.port)throw new Error("invalid");r({token:o.token,port:o.port})}catch{i(new Error("服务返回的连接信息不正确"))}a.close()},a.onerror=()=>{clearTimeout(n),i(new Error("无法连接服务,请确认 agent 已启动 WriteDock"))}});return st=void 0,await lr(e,{...e,...t,enabled:!0})}finally{dt=!1}}async function lr(e,t){const r=t.enabled!==e.enabled||t.port!==e.port||t.token!==e.token;if(await chrome.storage.local.set({[te.bridge]:t}),It=Promise.resolve(t),r){clearTimeout(it),it=void 0,Bt=0;const i=Ee;Ee=null,i==null||i.close(),await ut(!1),t.enabled?await nt():await chrome.alarms.clear(Mt)}return cr()}async function Ni(e){if(dt)throw new Error("正在连接,请完成后再修改设置");const t=await ct(),r={...t};if("enabled"in e){if(typeof e.enabled!="boolean")throw new Error("连接开关格式不正确");r.enabled=e.enabled}if("port"in e){if(!Number.isInteger(e.port)||e.port<1024||e.port>65535)throw new Error("端口需要是 1024–65535 的整数");r.port=e.port}return e.rotateToken===!0&&(r.token=sr()),lr(t,r)}async function zi(e,t){switch(e){case"listPlatforms":return Qt(t.forceRefresh===!0);case"checkAuth":{if(typeof t.platform!="string")throw new Error("请提供平台 ID");const r=Ue().find(i=>i.id===t.platform);if(!r)throw new Error("扩展没有此平台的适配器");return{...r,...await at(t.platform)}}case"prepareArticle":return Di(t.article);case"preparePost":return Li(t.post);case"publishPost":return tt({...t,publication:!0,rehearsal:!1});case"publishArticle":return tt({...t,publication:"article",rehearsal:!1});case"syncArticle":return tt({...t,publication:void 0,rehearsal:!1});case"publish":return jt({...t,rehearsal:!1});case"rehearsePublish":return jt({...t,rehearsal:!0});case"rehearsePost":return tt({...t,publication:!0,rehearsal:!0});case"rehearseArticle":return tt({...t,publication:"article",rehearsal:!0});case"getSyncTask":return Oi(t);case"getSyncHistory":return Ut();default:throw new Error("不支持的 MCP 操作")}}async function Hi(){it||!(await ct()).enabled||(it=setTimeout(()=>{it=void 0,nt()},Math.min(500*2**Math.min(Bt++,5),1e4)))}async function nt(){const e=await ct();if(!e.enabled||(await chrome.alarms.create(Mt,{periodInMinutes:1}),Ee&&(Ee.readyState===WebSocket.OPEN||Ee.readyState===WebSocket.CONNECTING)))return;const t=new WebSocket(`ws://127.0.0.1:${e.port}/extension`);Ee=t;let r=!1,i=!1;const a=setTimeout(()=>{r||t.close(1008,"Handshake timed out")},8e3);t.onmessage=n=>{(async()=>{if(Ee!==t)return;const s=JSON.parse(n.data);if(s.type==="challenge"&&!r){if(typeof s.nonce!="string"||!/^[a-f0-9]{64}$/.test(s.nonce)||s.proof!==await Gt(e.token,"server",s.nonce)){await ut(!1,"连接已失效,请点“连接”重新连上"),t.close(1008,"Handshake failed");return}if(Ee!==t||t.readyState!==WebSocket.OPEN)return;i=!0,t.send(JSON.stringify({type:"hello",extensionId:chrome.runtime.id,proof:await Gt(e.token,"extension",s.nonce)}));return}if(s.type==="ready"){if(!i)throw new Error("WriteDock 服务没有通过验证");r=!0,Bt=0,clearTimeout(a),Jt(s),await ut(!0);return}if(!r)throw new Error("WriteDock 服务尚未连接");if(s.type==="update_extension_result"){We==null||We.resolve(s);return}if(s.type==="ping"){Jt(s),t.send(JSON.stringify({type:"pong"}));return}if(typeof s.id!="string"||typeof s.method!="string"||!s.params||typeof s.params!="object"||Array.isArray(s.params))throw new Error("MCP 请求格式不正确");let o;try{o={id:s.id,result:await zi(s.method,s.params)}}catch(c){o={id:s.id,error:{code:-32e3,message:c instanceof Error?c.message:"MCP 操作失败"}}}t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(o))})().catch(()=>{t.close(1008,"Invalid MCP message")})},t.onclose=n=>{clearTimeout(a),Ee===t&&(Ee=null,ut(!1,st||(n.code===1008?"连接没有成功,请点“连接”重试;如果另一个浏览器也装了 WriteDock,请先关掉它":"等待 agent 启动 MCP 服务")),Hi())},t.onerror=()=>{}}function Fi(){chrome.alarms.onAlarm.addListener(e=>{e.name===Mt&&nt()}),chrome.runtime.onStartup.addListener(()=>{nt()}),nt().catch(console.error)}async function dr(){const e=chrome.runtime.getURL("src/editor/index.html"),r=(await chrome.tabs.query({})).find(i=>{var a;return((a=i.url)==null?void 0:a.split("#")[0])===e});r!=null&&r.id?(await chrome.tabs.update(r.id,{active:!0}),await chrome.windows.update(r.windowId,{focused:!0})):await chrome.tabs.create({url:e}),await chrome.action.setBadgeText({text:""})}chrome.action.onClicked.addListener(()=>{dr().catch(console.error)});chrome.runtime.onInstalled.addListener(e=>{e.reason==="install"&&chrome.storage.local.remove(te.authCache).catch(console.error)});chrome.runtime.onMessage.addListener((e,t,r)=>t.id!==chrome.runtime.id||(e==null?void 0:e.target)==="offscreen"||["TASK_UPDATED","DRAFT_DELETED","DRAFT_SAVED","BRIDGE_STATUS_UPDATED"].includes(e==null?void 0:e.type)?!1:((async()=>{switch(e==null?void 0:e.type){case"XHS_PUBLISH_PROGRESS":case"XHS_READ_ASSET":case"XHS_READ_ARTICLE_IMAGE":case"XHS_PUBLISH_DONE":return Qr(e,t);case"BILIBILI_ARTICLE_PROGRESS":case"BILIBILI_ARTICLE_DONE":return Ri(e,t);case"WEIBO_ARTICLE_PROGRESS":case"WEIBO_ARTICLE_DONE":return Si(e,t);case"BAIJIAHAO_ARTICLE_PROGRESS":case"BAIJIAHAO_ARTICLE_DONE":return bi(e,t);case"ZHIHU_ARTICLE_PROGRESS":case"ZHIHU_ARTICLE_DONE":return mi(e,t);case"PAGE_PUBLISH_PROGRESS":case"PAGE_PUBLISH_READ_ASSET":case"PAGE_PUBLISH_DONE":return ii(e,t);case"GET_PLATFORMS":return Ue();case"CHECK_ALL_AUTH":return Qt(e.forceRefresh===!0);case"CHECK_AUTH":return at(e.platform);case"SYNC_ARTICLE":return Ot(e.payload);case"GET_SYNC_STATE":return or();case"GET_SYNC_HISTORY":return Ut();case"GET_LAST_INPUT":return $i(e.taskId);case"DELETE_DRAFT":return Ti(e.draftId);case"GET_BRIDGE_STATE":return cr();case"SET_BRIDGE_CONFIG":return Ni(e.payload||{});case"CONNECT_BRIDGE":return Bi();case"UPDATE_EXTENSION":return Mi();case"OPEN_EDITOR":return await dr(),!0;default:throw new Error("不支持的请求")}})().then(a=>r({data:a})).catch(a=>{r({error:a instanceof Error?a.message:"操作失败,请重试"})}),!0));Fi();
42
+ `);if(ce&&(B(F),W(F,ce),await m(300),w(F.textContent||"")||(B(F),document.execCommand("insertText",!1,ce)),await I(()=>w(F.textContent||"")===w(ce),1e4,"小红书正文或话题未能完整写入,已停止发布"),F.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0}))),C.cover){const ue=await I(()=>document.querySelector("div.noCover.uploadCover")||A().find(V=>{var Q;return/^(?:设置封面|编辑封面|修改封面)$/.test(((Q=V.textContent)==null?void 0:Q.trim())||"")}),12e4,"未找到小红书视频封面入口"),be=await x(C.cover),re=await H(ue);L(re,[be]),await u("uploading_media");const we=await I(()=>A().find(V=>{var Q;return/^(?:确定|完成)$/.test(((Q=V.textContent)==null?void 0:Q.trim())||"")&&!!V.closest('[role="dialog"],.el-dialog,.d-modal')}),3e4,"请在原投稿页完成视频封面设置,未提交发布");k(),we.click()}if(await I(()=>(E(),e.mode==="image"?s>=e.imageCount:h&&s>=2),15*6e4,"小红书素材上传、转码或第一帧封面尚未就绪,未提交发布"),U(T)!==e.title||w(F.textContent||"")!==w(ce))throw new Error("小红书标题或正文发生变化,已停止发布")},ge=async()=>{await u("checking_auth"),e.mode==="article"?await se():await Y(),await I(()=>!/笔记图片生成中/.test(document.body.innerText),3*6e4,"小红书笔记图片仍在生成,未提交发布");const C=()=>{var T,F,K;for(const J of Array.from(document.querySelectorAll("xhs-publish-btn"))){if(J.getAttribute("submit-disabled")==="true"||J.getAttribute("submit-loading")==="true")continue;const ne=(F=(T=chrome.dom)==null?void 0:T.openOrClosedShadowRoot)==null?void 0:F.call(T,J),ce=((K=J.getAttribute("submit-text"))==null?void 0:K.trim())||"发布",fe=Array.from((ne==null?void 0:ne.querySelectorAll("*"))||[]).find(be=>{var re;return((re=be.textContent)==null?void 0:re.trim())===ce&&!Array.from(be.children).some(we=>{var V;return((V=we.textContent)==null?void 0:V.trim())===ce})}),ue=(fe==null?void 0:fe.closest('button,[role="button"]'))||fe;if(ue&&D(ue))return ue}},z=await I(()=>C()||A().find(T=>{var F;return/^(?:发布|立即发布)$/.test(((F=T.textContent)==null?void 0:F.trim())||"")}),6e4,"小红书发布按钮尚不可用,请检查素材或账号要求");if(e.rehearsal){k(),window.dispatchEvent(new Event(`${t}:rehearsed`)),await m(1e3),!i&&!r&&await f({success:!1,publicationState:"rehearsed"});return}const q=new Set(A());if(await u("publishing"),k(),!z.isConnected||!D(z))throw new Error("小红书发布控件发生变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,z.click();const O=Math.min(Date.now()+12e4,e.deadline);let G=!1;for(;!r&&!i&&Date.now()<O;){if(k(),!n&&!G){const T=A().find(F=>{var K;return!q.has(F)&&/^(?:确认发布|确定发布)$/.test(((K=F.textContent)==null?void 0:K.trim())||"")&&!!F.closest('[role="dialog"],.el-dialog,.d-modal')});T&&(G=!0,T.click())}await m(300)}!r&&!i&&await f({success:!1,publicationState:"unknown",error:"已触发小红书发布,但没有取得匹配的成功回执,请检查平台,不要自动重发。"})};try{const C=sessionStorage.getItem(t);C&&l(new CustomEvent(t,{detail:C}))}catch{}return!r&&!i&&ge().catch(C=>{r||i||f(C!=null&&C.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:C.manualReason,message:C.message}:{success:!1,publicationState:a?"unknown":"failed",error:C instanceof Error?C.message:"小红书投稿失败"}).catch(d)}),{started:!0}}function Hr(){const e=window;if(e.__writedockNetworkTrail)return{installed:!1};const t=[];e.__writedockNetworkTrail=t;const r=h=>{try{const w=new URL(h,location.href);return/^(?:mon\.zijieapi|mcs\.snssdk|imapi\.douyin|t2\.xiaohongshu|apm-fe\.xiaohongshu)\.com$/.test(w.hostname)?"":/^https?:$/.test(w.protocol)?w.origin+w.pathname:""}catch{return""}},i=(h,w)=>{const m=r(w);if(!m)return null;const p={method:h.toUpperCase(),url:m};return t.push(p),t.length>40&&t.shift(),p},a=(h,w)=>{if(!w||w.length>2e5)return;const m=JSON.parse(w);if(!m||typeof m!="object")return;for(const u of["code","errno","result","ok","success"])if(u in m){h.code=`${u}=${String(m[u])}`.slice(0,40);break}const p=m.message??m.msg??m.errmsg;typeof p=="string"&&p&&(h.message=p.slice(0,120))},n=window.fetch;window.fetch=function(h,w){const m=i((w==null?void 0:w.method)||(h instanceof Request?h.method:"GET"),h instanceof Request?h.url:String(h)),p=n.call(window,h,w);return p.then(u=>{m&&(m.status=u.status,/json/i.test(u.headers.get("content-type")||"")&&u.clone().text().then(g=>a(m,g)).catch(()=>{}))}).catch(()=>{m&&(m.message="连接中断")}),p};const s=XMLHttpRequest.prototype,o=s.open,c=s.send,y=new WeakMap;return s.open=function(h,w,...m){return y.set(this,{method:h,url:String(w)}),Reflect.apply(o,this,[h,w,...m])},s.send=function(h){const w=y.get(this),m=w?i(w.method,w.url):null;return m&&this.addEventListener("loadend",()=>{m.status=this.status;try{a(m,this.responseType==="json"?JSON.stringify(this.response):this.responseType===""||this.responseType==="text"?this.responseText:"")}catch{}},{once:!0}),c.call(this,h)},{installed:!0}}function Fr(){var m;const e=(p,u)=>(p||"").replace(/\s+/g," ").trim().slice(0,u),t=p=>p.getClientRects().length>0&&getComputedStyle(p).visibility!=="hidden",r=(p,u)=>[...new Set(p.filter(Boolean))].slice(0,u),i=p=>Array.from(document.querySelectorAll(p)).filter(t),a=(m=chrome.dom)==null?void 0:m.openOrClosedShadowRoot,n=Array.from(document.querySelectorAll("*")).filter(p=>p.tagName.includes("-")).slice(0,20).flatMap(p=>{const u=a==null?void 0:a(p);return u?Array.from(u.querySelectorAll('button,[role="button"]')).filter(t).map(g=>`${p.tagName.toLowerCase()}: ${e(g.textContent,20)}`):[]}),s=r([...n,...i('button,[role="button"],[role="tab"]').map(p=>e(p.textContent,30))],30),o=r(i('[role="alert"],[role="dialog"],[role="status"],[aria-modal="true"],[class*="toast"],[class*="message"],[class*="modal"],[class*="dialog"]').map(p=>e(p.textContent,200)),5),c=i('input:not([type="hidden"]):not([type="file"]):not([type="checkbox"]):not([type="radio"]),textarea,[contenteditable="true"]').slice(0,10).map(p=>{const u=p,g=u.value??p.textContent??"";return{tag:p.tagName.toLowerCase(),...u.placeholder?{placeholder:e(u.placeholder,40)}:{},...typeof p.className=="string"&&p.className?{className:e(p.className,60)}:{},textLength:g.replace(/[\s​-‍]/g,"").length}}),y=r(Array.from(document.querySelectorAll('input[type="file"]')).map(p=>e(p.accept,60)||"*"),6),h=p=>/^https?:$/.test(p.protocol)?p.origin+p.pathname:p.protocol,w=r(Array.from(document.querySelectorAll("iframe")).map(p=>{try{return h(new URL(p.src,location.href))}catch{return""}}),6);return window!==window.top&&!s.length&&!c.length&&!o.length?null:{url:h(location),title:e(document.title,80),buttons:s,notices:o,editors:c,fileInputs:y,iframes:w}}function Wr(){return window.__writedockNetworkTrail||[]}async function Je(e){await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:Hr}).catch(()=>{})}async function jr(e){const t=await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"ISOLATED",func:Fr}),r=await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:Wr}).catch(()=>[]);return{capturedAt:Date.now(),frames:t.map(i=>i.result).filter(i=>!!i).slice(0,6),network:r.flatMap(i=>i.result||[]).slice(-40)}}async function Jr(e){const t=new Promise(r=>setTimeout(()=>r({capturedAt:Date.now()}),3e3));return Promise.race([jr(e).catch(()=>({capturedAt:Date.now(),tabClosed:!0})),t])}async function Ae(e,t,r){const i=Array.isArray(r)?r.filter(a=>typeof a=="string").map(a=>a.slice(0,200)).slice(0,20):[];return{...t,...i.length?{warnings:i}:{},...t.success?{}:{diagnostics:await Jr(e)}}}function Ge(e,t){return{platform:e,success:!1,draftOnly:!1,publicationState:"rehearsed",postUrl:t,timestamp:Date.now(),message:"演练已走到点击发布之前并停下,未提交发布。稿件留在已打开的标签页,确认后关闭即可;图片可能已上传到平台,部分平台会留下中间草稿。最终发布请求和平台回执只有真实发布时才能核对。"}}function Gr(e){var t,r,i;return((t=e.latest)==null?void 0:t.kind)==="success"?"success":((r=e.latest)==null?void 0:r.kind)==="failure"||((i=e.latest)==null?void 0:i.kind)==="unclear"?"unknown":e.now>=e.deadline?e.requestPending?"unknown":"hand_off":"wait"}const Ve=e=>e.publicationState==="needs_user_action"&&e.manualReason==="captcha";function Vr(e){const t=window;if(t[e.key])return{watching:!0};const r={requests:0,pending:0,rejected:!1};t[e.key]=r;const i={bilibili:[/^https:\/\/api\.bilibili\.com$/,"/x/dynamic/feed/create/opus"],baijiahao:[/^https:\/\/baijiahao\.baidu\.com$/,"/pcui/article/publish"],xiaohongshu:[/^https:\/\/(?:edith|creator)\.xiaohongshu\.com$/,"/web_api/sns/v2/note"],weibo:[/^https:\/\/weibo\.com$/,"/ajax/statuses/update"],"weibo-article":[/^https:\/\/card\.weibo\.com$/,"/article/v5/aj/editor/draft/publish"],zhihu:[/^https:\/\/www\.zhihu\.com$/,"/api/v4/content/publish"]},a=(p,u)=>{try{const g=new URL(u,location.href),[D,A]=i[e.platform];return p.toUpperCase()==="POST"&&D.test(g.origin)&&g.pathname===A}catch{return!1}},n=p=>{if(typeof p!="string")return p;const u=p.trim(),g=/^[\w.$]+\s*\(([\s\S]*)\)\s*;?\s*$/.exec(u);return JSON.parse(g?g[1]:u)},s=(p,u)=>{var d,f,l,_,k,I,E,v,R,U,B,W;let g;try{g=n(u)}catch{return{kind:"unclear",message:"发布响应无法解析"}}const D=String((g==null?void 0:g.message)??(g==null?void 0:g.msg)??(g==null?void 0:g.errmsg)??"").slice(0,200);if(/验证码|安全验证|完成验证|验证后|captcha/i.test(D)||(g==null?void 0:g.code)===-352||(g==null?void 0:g.errno)===10000015||!!((d=g==null?void 0:g.data)!=null&&d.verify)||!!((f=g==null?void 0:g.data)!=null&&f.geetest))return{kind:"captcha",message:D};const b=p>=200&&p<300;switch(e.platform){case"bilibili":{const P=(l=g==null?void 0:g.data)==null?void 0:l.dyn_id_str;if(b&&(g==null?void 0:g.code)===0&&typeof P=="string"&&/^\d{1,24}$/.test(P))return{kind:"success",postId:P,postUrl:`https://www.bilibili.com/opus/${P}`};break}case"baijiahao":if(b&&(g==null?void 0:g.errno)===0&&(!e.articleId||((_=g==null?void 0:g.ret)==null?void 0:_.article_id)===e.articleId))return{kind:"success",postId:e.articleId,postUrl:`https://baijiahao.baidu.com/s?id=${e.articleId}`};break;case"xiaohongshu":{const P=(k=g==null?void 0:g.data)==null?void 0:k.id;if(b&&(g==null?void 0:g.success)===!0&&(g==null?void 0:g.result)===0&&typeof P=="string"&&/^[a-f0-9]{24}$/.test(P))return{kind:"success",postId:P,postUrl:`https://www.xiaohongshu.com/explore/${P}`};break}case"weibo":{if(b&&(g==null?void 0:g.ok)===1&&!g.error){const P=(I=g.data)==null?void 0:I.mblogid,N=String(((v=(E=g.data)==null?void 0:E.user)==null?void 0:v.idstr)??((U=(R=g.data)==null?void 0:R.user)==null?void 0:U.id)??"");return{kind:"success",...typeof((B=g.data)==null?void 0:B.idstr)=="string"?{postId:g.data.idstr}:{},postUrl:typeof P=="string"&&/^\d+$/.test(N)?`https://weibo.com/${N}/${P}`:"https://weibo.com"}}break}case"weibo-article":if(b&&(g==null?void 0:g.code)===1e5&&typeof((W=g.data)==null?void 0:W.url)=="string")return{kind:"success",postUrl:g.data.url};break;case"zhihu":if(b&&(g==null?void 0:g.code)===0)return{kind:"success"};break}return{kind:"failure",message:D||`发布结果未确认(HTTP ${p})`}},o=p=>{r.pending=Math.max(0,r.pending-1),r.latest=p,r.rejected=p.kind==="captcha"},c=window.fetch;window.fetch=function(p,u){const g=a((u==null?void 0:u.method)||(p instanceof Request?p.method:"GET"),p instanceof Request?p.url:String(p));g&&(r.requests++,r.pending++,r.latest=void 0,r.rejected=!1);const D=c.call(window,p,u);return g&&D.then(A=>A.clone().text().then(b=>o(s(A.status,b)))).catch(()=>o({kind:"unclear",message:"发布连接中断"})),D};const y=XMLHttpRequest.prototype,h=y.open,w=y.send,m=new WeakMap;return y.open=function(p,u,...g){return m.set(this,a(p,String(u))),Reflect.apply(h,this,[p,u,...g])},y.send=function(p){return m.get(this)&&(r.requests++,r.pending++,r.latest=void 0,r.rejected=!1,this.addEventListener("loadend",()=>{try{o(s(this.status,this.responseType==="json"?this.response:this.responseText))}catch{o({kind:"unclear",message:"发布响应无法读取"})}},{once:!0})),w.call(this,p)},{watching:!0}}function Xr(e){return window[e]||null}function Xe(e){const t=`__writedockVerification_${e.channel.replace(/-/g,"")}`,r=Date.now()+(e.timeoutMs??10*6e4),i={tabId:e.tabId,allFrames:!0};let a=!1;e.progress({stage:"waiting_verification",url:e.url,message:e.message});const n=c=>{clearInterval(o),c()},s=async()=>{var c;if(!a){a=!0;try{if(!e.isActive()){clearInterval(o);return}await chrome.tabs.get(e.tabId),await chrome.scripting.executeScript({target:i,world:"MAIN",func:Vr,args:[{key:t,platform:e.platform,articleId:e.articleId}]}).catch(()=>[]);const h=(await chrome.scripting.executeScript({target:i,world:"MAIN",func:Xr,args:[t]}).catch(()=>[])).map(p=>p.result).filter(p=>!!p),w=(c=h.find(p=>p.latest))==null?void 0:c.latest,m=Gr({now:Date.now(),deadline:r,requestPending:h.some(p=>p.pending>0),latest:w});m==="success"?n(()=>e.onReceipt({success:!0,publicationState:"submitted",responseConfirmed:!0,postId:w==null?void 0:w.postId,postUrl:w==null?void 0:w.postUrl})):m==="unknown"?n(()=>e.onReceipt({success:!1,publicationState:"unknown",error:`${(w==null?void 0:w.message)||"发布结果未确认"}。请检查平台,不要自动重发。`})):m==="hand_off"&&n(e.onHandOff)}catch{n(e.onHandOff)}finally{a=!1}}},o=setInterval(()=>{s()},2e3);s()}const Ie=new Map,vt=({id:e,name:t,type:r,size:i})=>({id:e,name:t,type:r,size:i}),ir=e=>{let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)},Zr=(e,t,r={})=>nr({mode:e.kind,post:Le(e)},t,r),Kr=(e,t,r,i={})=>nr({mode:"article",title:e,html:t},r,i);async function nr(e,t,r){const i=r.rehearsal===!0,a=crypto.randomUUID(),n=crypto.randomUUID(),s=crypto.randomUUID(),o=Date.now()+30*6e4,c=e.mode==="article"?e.title:e.post.title,y=`https://creator.xiaohongshu.com/publish/publish?target=${e.mode}&writedock_job=${a}`,h=await chrome.tabs.create({url:y,active:!0});if(!h.id)throw new Error("无法打开小红书发布页");const w=h.id;return new Promise(m=>{let p=!1;const u=(l,_=!1)=>{if(!Ie.has(a)||p&&!_&&!l.success)return;if(!_&&!i&&!p&&Ve(l)){p=!0,clearTimeout(A),Xe({tabId:w,platform:"xiaohongshu",channel:s,url:f.editUrl,message:"小红书要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>Ie.has(a),progress:t,onReceipt:R=>{f.attempted=!0,u(R,!0)},onHandOff:()=>u(l,!0)});return}Ie.delete(a),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),window.dispatchEvent(new Event(`${R}:stop`)),sessionStorage.removeItem(R)},args:[`writedock-xhs-${s}`]}).catch(()=>{});let k="";try{const R=new URL(l.postUrl||"");R.origin==="https://www.xiaohongshu.com"&&/^\/explore\/[a-f0-9]{24}$/.test(R.pathname)&&l.postId===R.pathname.split("/").pop()&&(k=R.href)}catch{}if(i&&l.publicationState==="rehearsed"){Ae(w,Ge("xiaohongshu",f.editUrl),l.warnings).then(m);return}const I=!i&&f.attempted&&l.success===!0&&l.publicationState==="submitted"&&l.responseConfirmed===!0&&!!k,E=l.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(l.manualReason||""),v=String(l.message||"请在已打开的小红书原投稿页核对内容、完成平台要求并手动发布,Agent 不要重新提交。").slice(0,1e3);Ae(w,{platform:"xiaohongshu",success:I,draftOnly:!1,publicationState:I?"submitted":E?"needs_user_action":f.attempted?"unknown":"failed",postUrl:I?k:f.editUrl,timestamp:Date.now(),...I?{postId:l.postId,message:"小红书发布接口已确认提交,展示状态以平台为准"}:E?{requiresUserAction:!0,userAction:{type:l.manualReason,url:f.editUrl,message:v},message:v}:{error:l.error||"小红书发布结果未确认,请检查平台,不要自动重发"}},l.warnings).then(m)},g=l=>{l===w&&u({error:"小红书投稿页已关闭,请先检查平台,不要自动重发"})},D=(l,_,k)=>{var I,E;l!==w||!Ie.has(a)||((I=k.url)!=null&&I.startsWith("https://creator.xiaohongshu.com/publish/publish")&&(f.editUrl=k.url),!(_.status!=="complete"||!f.attempted||!((E=k.url)!=null&&E.startsWith("https://creator.xiaohongshu.com/")))&&chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:v=>sessionStorage.getItem(v),args:[`writedock-xhs-${s}`]}).then(v=>{var B;const R=(B=v[0])==null?void 0:B.result;if(typeof R!="string"||!Ie.has(a))return;const U=JSON.parse(R);U.jobId===a&&U.phase==="result"&&u(U)}).catch(()=>{}))},A=setTimeout(()=>u({error:"等待小红书投稿超时,请检查原稿件,不要自动重发"}),30*6e4),b=e.mode==="article"?void 0:e.post,d=b?[...b.images,...b.video?[b.video]:[],...b.cover?[b.cover]:[]]:[],f={tabId:w,secret:n,channel:s,editUrl:y,attempted:!1,assets:new Map(d.map(l=>[l.id,l])),articleImages:new Map,progress:t,finish:u};Ie.set(a,f),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var U,B,W,P,N,x;const l=Date.now()+6e4;for(;Ie.has(a)&&Date.now()<l&&(await chrome.tabs.get(w)).status!=="complete";)await new Promise($=>setTimeout($,250));if(!Ie.has(a))return;const _=await chrome.tabs.get(w);if(_.status!=="complete"||!((U=_.url)!=null&&U.startsWith("https://creator.xiaohongshu.com/publish/publish")))throw new Error("小红书发布页未就绪,请先在当前浏览器完成创作者后台登录");let k;if(e.mode==="article"){if(k=(B=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:Br,args:[e.html,s]}))[0])==null?void 0:B.result,!k)throw new Error("小红书长文解析失败,未提交发布");f.articleImages=new Map(k.images.map($=>[$.id,$.source]))}const I={id:a,channel:s,deadline:o,mode:e.mode,title:c,content:(k==null?void 0:k.text)??(b==null?void 0:b.content)??"",tags:(b==null?void 0:b.tags)||[],imageCount:(k==null?void 0:k.images.length)??(b==null?void 0:b.images.length)??0,explicitCover:!!(b!=null&&b.cover),rehearsal:i};await Je(w);const E=await chrome.scripting.executeScript({target:{tabId:w},world:"MAIN",func:Nr,args:[I]});if(!Ie.has(a))return;if(!((P=(W=E[0])==null?void 0:W.result)!=null&&P.observing))throw new Error("无法观察小红书发布回执,已停止投稿");const v={...I,secret:n,...k?{article:{markup:k.markup,images:k.images.map(({id:L,marker:$})=>({id:L,marker:$}))}}:{},...b?{post:{images:b.images.map(vt),...b.video?{video:vt(b.video)}:{},...b.cover?{cover:vt(b.cover)}:{}}}:{}};if(!((x=(N=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:zr,args:[v]}))[0])==null?void 0:N.result)!=null&&x.started))throw new Error("无法启动小红书投稿脚本")})().catch(l=>u({error:l instanceof Error?l.message:"启动小红书投稿失败"}))})}async function Yr(e){if(!/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(e)&&!/^https?:\/\//i.test(e))throw new Error("长文图片地址不正确,请让 Agent 重新准备稿件");const t=await fetch(e,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(3e4)});if(!t.ok||!t.body)throw new Error("无法读取小红书长文图片,已停止投稿");const r=t.body.getReader(),i=[];let a=0;for(;;){const{done:y,value:h}=await r.read();if(y)break;if(a+=h.length,a>8*1024*1024)throw await r.cancel(),new Error("小红书长文单张图片不能超过 8 MB");i.push(h)}const n=new Uint8Array(a);let s=0;for(const y of i)n.set(y,s),s+=y.length;const o=String.fromCharCode(...n.subarray(0,12)),c=n[0]===137&&o.slice(1,4)==="PNG"?"image/png":n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":/^GIF8[79]a/.test(o)?"image/gif":o.startsWith("RIFF")&&o.slice(8,12)==="WEBP"?"image/webp":"";if(!c)throw new Error("小红书长文插图只接受 PNG、JPEG、GIF、WebP 图片");return{base64:ir(n),type:c}}async function Qr(e,t){var i,a;const r=Ie.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://creator.xiaohongshu.com/"))||e.jobSecret!==r.secret)throw new Error("小红书任务已结束或来源不匹配");if(e.type==="XHS_PUBLISH_PROGRESS"){if(!["checking_auth","preparing_article","uploading_images","transferring_media","uploading_media","publishing","verifying"].includes(String(e.stage)))throw new Error("小红书投稿阶段不正确");return["publishing","verifying"].includes(String(e.stage))&&(r.attempted=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="XHS_READ_ASSET"){const n=r.assets.get(String(e.assetId||""));if(!n)throw new Error("素材不属于本次小红书任务");return{base64:ir(await Ct(n,Number(e.offset),Number(e.length)))}}if(e.type==="XHS_READ_ARTICLE_IMAGE"){const n=r.articleImages.get(String(e.imageId||""));if(!n)throw new Error("插图不属于本次小红书长文");return Yr(n)}if(e.type==="XHS_PUBLISH_DONE")return r.finish(e.result||{error:"小红书没有返回投稿结果"}),!0;throw new Error("不支持的小红书页面操作")}const ke=new Map,He=e=>e==="weibo"?"https://weibo.com":"https://creator.douyin.com",ei=e=>He(e)+(e==="weibo"?"/":"/creator-micro/content/manage"),_t=({id:e,name:t,type:r,size:i})=>({id:e,name:t,type:r,size:i});function Fe(e,t,r=!1){if(e.watching&&!r&&!(t!=null&&t.success))return;if(!r&&!e.rehearsal&&!e.watching&&e.platform==="weibo"&&t&&Ve(t)){e.watching=!0,Xe({tabId:e.tabId,platform:"weibo",channel:e.channel,url:e.editUrl,message:"微博要求完成验证。请在已打开的页面完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>{var c;return((c=ke.get(e.id))==null?void 0:c.watching)===!0},progress:e.progress,onReceipt:c=>{e.attempted=!0,Fe(e,c,!0)},onHandOff:()=>Fe(e,t,!0)});return}const i=t!=null&&t.warnings?{warnings:t.warnings}:{};if(e.rehearsal&&(t==null?void 0:t.publicationState)==="rehearsed"){e.finish({...Ge(e.platform,e.editUrl),...i});return}const a=!e.rehearsal&&(t==null?void 0:t.success)===!0&&["submitted","published"].includes(t.publicationState||"")&&e.attempted&&(e.platform==="weibo"?t.responseConfirmed===!0:e.platform==="douyin"&&e.clicked&&t.pageConfirmed===!0),n=(t==null?void 0:t.publicationState)==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings","old_draft"].includes(t.manualReason||""),s=String((t==null?void 0:t.message)||"请在已打开的原投稿页完成设置或验证并手动发布,Agent 不要重发。").slice(0,1e3);let o=a?ei(e.platform):e.editUrl;try{const c=new URL((t==null?void 0:t.postUrl)||"");c.origin===He(e.platform)&&(o=c.href)}catch{}n&&(o=e.editUrl),e.finish({...i,platform:e.platform,success:a,draftOnly:!1,publicationState:a?t.publicationState:n?"needs_user_action":e.attempted?"unknown":"failed",postUrl:o,...a?{...typeof(t==null?void 0:t.postId)=="string"&&/^\d+$/.test(t.postId)?{postId:t.postId}:{},message:e.platform==="weibo"?"微博发布接口已确认提交,展示状态以平台为准":(t==null?void 0:t.message)||"平台已确认提交"}:n?{requiresUserAction:!0,userAction:{type:t.manualReason,url:o,message:s},message:s}:{error:(t==null?void 0:t.error)||"发布结果未确认,请检查作品管理,不要自动重复发布"},timestamp:Date.now()})}async function ti(e){await new Promise((t,r)=>{const i=s=>{clearTimeout(n),chrome.tabs.onUpdated.removeListener(a),s?r(s):t()},a=(s,o)=>{s===e&&o.status==="complete"&&i()},n=setTimeout(()=>i(new Error("创作者页面加载超时")),6e4);chrome.tabs.onUpdated.addListener(a),chrome.tabs.get(e).then(s=>{s.status==="complete"&&i()}).catch(s=>i(s))})}async function ri(e,t,r,i={}){const a=i.rehearsal===!0;if(!Rt(e))throw new Error("当前平台尚未接入图文或视频直发");const n=Le(t);mt(n,[e]);const s=e==="douyin"?n.kind==="video"?5:4:10;if(n.tags.length>s)throw new Error(`当前 ${e==="douyin"?"抖音":"小红书"} 适配最多接收 ${s} 个话题,请先减少话题`);if(e==="xiaohongshu")return Zr(n,r,i);const o=crypto.randomUUID(),c=crypto.randomUUID(),y=crypto.randomUUID(),h=`writedockDouyinRehearsalDraft:${n.kind}`,w=e==="douyin"?(await chrome.storage.local.get(h))[h]:void 0,m=i.discardOldDraft===!0||typeof w=="number"&&Date.now()-w<24*60*6e4;w!==void 0&&await chrome.storage.local.remove(h);const p=He(e)+(e==="weibo"?`${n.kind==="video"?"/upload/channel":"/"}?writedock_post=${o}`:`/creator-micro/content/upload?${n.kind==="image"?"default-tab=3&":""}writedock_post=${o}`),u=await chrome.tabs.create({url:p,active:!0});if(!u.id)throw new Error("无法打开创作者页面");const g=u.id,D=[...n.images,...n.video?[n.video]:[],...n.cover?[n.cover]:[]];return new Promise(A=>{const b=v=>{ke.has(o)&&(ke.delete(o),clearTimeout(k),e==="douyin"&&v.publicationState==="rehearsed"&&chrome.storage.local.set({[h]:Date.now()}).catch(()=>{}),chrome.tabs.onRemoved.removeListener(f),chrome.tabs.onUpdated.removeListener(l),e==="weibo"&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),window.dispatchEvent(new Event(`${R}:stop`)),sessionStorage.removeItem(R)},args:[`writedock-weibo-post-${y}`]}).catch(()=>{}),e==="douyin"&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:R=>{window.dispatchEvent(new Event(`${R}:cancel`)),sessionStorage.removeItem(R)},args:[`writedock-douyin-${y}`]}).catch(()=>{}),Ae(g,v,v.warnings).then(A))},d=v=>{I.watching||b({platform:e,success:!1,draftOnly:!1,publicationState:I.attempted?"unknown":"failed",error:v,postUrl:I.editUrl,timestamp:Date.now()})},f=v=>{v===g&&d("投稿标签页已关闭,请检查平台结果后再决定是否重试")},l=(v,R,U)=>{if(v!==g||!ke.has(o)||!U.url)return;if(e==="weibo"){const P=new URL(U.url);if(P.origin==="https://security.weibo.com"&&/^\/(?:verify|captcha)(?:\/|$)/.test(P.pathname)){I.editUrl=P.href,Fe(I,{publicationState:"needs_user_action",manualReason:"captcha",message:"微博已进入人工验证页。请在当前标签页完成验证、核对内容并手动发布,Agent 不要重新提交。"});return}P.origin==="https://weibo.com"&&(I.editUrl=P.href,R.status==="complete"&&I.attempted&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:N=>sessionStorage.getItem(N),args:[`writedock-weibo-post-${y}`]}).then(N=>{var $;const x=($=N[0])==null?void 0:$.result;if(typeof x!="string"||!ke.has(o))return;const L=JSON.parse(x);L.phase==="result"&&Fe(I,L)}).catch(()=>{}));return}const B=new URL(U.url);if(B.origin!==He(e)||(/^\/creator-micro\/content\/(?:upload|publish)(?:\/|$)/.test(B.pathname)&&!B.pathname.endsWith("/success")&&(I.editUrl=B.href),!I.clicked||R.status!=="complete"))return;const W=/^\/creator-micro\/content\/manage(?:\/|$)|\/publish\/success(?:\/|$)/.test(B.pathname);chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:P=>sessionStorage.getItem(P),args:[`writedock-douyin-${y}`]}).then(P=>{var x;if(!ke.has(o))return;const N=(x=P[0])==null?void 0:x.result;if(typeof N=="string")try{const L=JSON.parse(N);if(L.jobId===o&&L.phase==="result"){Fe(I,L);return}}catch{}W&&d("抖音已进入作品管理,但未取得明确成功提示,请检查平台,不要自动重发")}).catch(()=>{W&&ke.has(o)&&d("抖音页面已跳转,发布结果未能确认,请检查平台,不要自动重发")})},_=Date.now()+18e5,k=setTimeout(()=>d("等待投稿结果超时,请检查作品管理,不要自动重复发布"),30*6e4),I={id:o,tabId:g,secret:c,platform:e,editUrl:p,rehearsal:a,channel:y,assets:new Map(D.map(v=>[v.id,v])),progress:r,attempted:!1,clicked:!1,finish:b};ke.set(o,I),chrome.tabs.onRemoved.addListener(f),chrome.tabs.onUpdated.addListener(l);const E={id:o,secret:c,platform:e,deadline:_,channel:y,rehearsal:a,discardDraft:m,post:{...n,images:n.images.map(_t),...n.video?{video:_t(n.video)}:{},...n.cover?{cover:_t(n.cover)}:{}}};ti(g).then(async()=>{var U,B,W,P,N,x,L;if(!ke.has(o))return;if(!((U=(await chrome.tabs.get(g)).url)!=null&&U.startsWith(`${He(e)}/`)))throw new Error("请在创作者后台完成登录后再投稿");if(await Je(g),e==="weibo"){const $=Or(n);if(!((W=(B=(await chrome.scripting.executeScript({target:{tabId:g},world:"MAIN",func:qr,args:[{channel:y,deadline:_,kind:n.kind,text:$,title:n.title,imageCount:n.images.length,creation:n.weiboVideoCreation,explicitCover:!!n.cover,rehearsal:a}]}))[0])==null?void 0:B.result)!=null&&W.observing))throw new Error("无法观察微博发布回执,已停止自动投稿");if(!((N=(P=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Mr,args:[{...E,channel:y,text:$}]}))[0])==null?void 0:P.result)!=null&&N.started))throw new Error("无法启动微博图文/视频投稿脚本");return}if(!((L=(x=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Pr,args:[E]}))[0])==null?void 0:x.result)!=null&&L.started))throw new Error("无法启动页面投稿脚本")}).catch(v=>d(v instanceof Error?v.message:"启动投稿失败"))})}async function ii(e,t){var i,a;const r=ke.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||e.jobSecret!==r.secret||!((a=t.url)!=null&&a.startsWith(`${He(r.platform)}/`)))throw new Error("页面投稿任务已结束或来源不匹配");if(e.type==="PAGE_PUBLISH_PROGRESS"){if(e.stage==="waiting_verification"&&r.platform==="douyin"&&r.clicked)return r.progress({stage:"waiting_verification",url:r.editUrl,message:"抖音要求短信验证。请在已打开的页面点“获取验证码”,填写手机收到的验证码后点“验证”,不要把验证码发给 Agent。验证后抖音会自动发布,不用再点“发布”。结果会自动更新,不要重新提交。"}),!0;if(!["checking_auth","transferring_media","uploading_media","publishing","verifying"].includes(String(e.stage)))throw new Error("投稿阶段不正确");return e.stage==="publishing"&&(r.attempted=!0),e.stage==="verifying"&&(r.clicked=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="PAGE_PUBLISH_READ_ASSET"){const n=r.assets.get(String(e.assetId||"")),s=Number(e.offset),o=Number(e.length);if(!n||!Number.isSafeInteger(s)||!Number.isSafeInteger(o)||s<0||o<1||o>1024*1024||s+o>n.size)throw new Error("素材读取范围不正确");const c=await Ct(n,s,o);let y="";for(let h=0;h<c.length;h+=32768)y+=String.fromCharCode(...c.subarray(h,h+32768));return{base64:btoa(y)}}if(e.type==="PAGE_PUBLISH_DONE")return Fe(r,e.result),!0;throw new Error("不支持的页面投稿操作")}const ni={zhihu:100,baijiahao:64,weibo:32,xiaohongshu:64},zt=new Set(["zhihu","baijiahao","weibo","bilibili","xiaohongshu"]),Ht=new Set(["weibo","xiaohongshu","douyin"]),ai=new Set(["weixin","sohu"]),oi=new Set(["baijiahao","weibo"]),si={zhihu:"知乎",baijiahao:"百家号",weibo:"微博",bilibili:"B站",xiaohongshu:"小红书",douyin:"抖音",weixin:"公众号",sohu:"搜狐号"},ci=e=>{var t;return(t=/<img\b[^>]*\bsrc=["']([^"']+)["']/i.exec(e))==null?void 0:t[1]};function li(e){const{article:t,post:r}=e,i=e.modes&&typeof e.modes=="object"?e.modes:{};return e.platforms.map(a=>{var m,p;const n=si[a]||a,s=i[a],o=(u,g)=>({platform:a,mode:u,error:g});if(s!==void 0&&s!=="article"&&s!=="post")return o("article",`${n} 的 modes 只能是 article 或 post`);if(ai.has(a))return e.rehearsal?o("draft",`${n}只保存草稿,无需演练`):s==="post"?o("draft",`${n}目前只接文章草稿,不接图文或视频`):t?(m=t.videos)!=null&&m.length?o("draft",`${n}不接文章内嵌视频`):{platform:a,mode:"draft",...t.cover?{cover:t.cover}:{}}:o("draft",`${n}需要文章内容,本次只提供了图文或视频`);const c=s==="article"||s==="post"?s:Ht.has(a)&&(r||!zt.has(a))?"post":"article";if(c==="post"){if(!Ht.has(a))return o("post",`${n}不接图文或视频,请提供文章内容`);if(!r)return o("post",`${n}需要图文或视频素材,本次只提供了文章`);try{mt(r,[a])}catch(u){return o("post",u instanceof Error?u.message:`${n}不接受这份素材`)}return{platform:a,mode:c}}if(!zt.has(a))return o("article",`${n}不接文章,请提供图文或视频素材`);if(!t)return o("article",`${n}需要文章内容,本次只提供了图文或视频`);const y=ni[a];if(y&&t.title.length>y)return o("article",`${n}文章标题最多 ${y} 字,未截断发布,请缩短后单独提交`);if((p=t.videos)!=null&&p.length&&a!=="zhihu")return o("article",`${n}不接文章内嵌视频,请去掉视频后单独提交`);const h=[];let w=t.cover;if(w&&!oi.has(a)&&(h.push(`${n}不接独立封面,已忽略 cover`),w=void 0),a==="baijiahao"&&!w){if(w=ci(t.html||""),!w)return o("article","百家号必须有封面,请提供 cover 或在正文中放一张图片");h.push("百家号未提供 cover,已使用正文第一张图片作为封面")}return{platform:a,mode:c,...w?{cover:w}:{},...h.length?{notes:h}:{}}})}const di=(e,t,r=!1)=>!r&&Array.isArray(e)&&e.includes(t);function ui(e){var h,w;const t=`writedock-zhihu-${e.channel}`;if(location.origin!=="https://zhuanlan.zhihu.com")return null;let r=null;for(const m of[`writedock-zhihu-early-${e.draftId}`,t])try{const p=JSON.parse(sessionStorage.getItem(m)||"null");if((p==null?void 0:p.draftId)===e.draftId&&p.phase==="result"){if(p.publicationState!=="unknown")return p;r=p}}catch{}if(sessionStorage.getItem(`${t}:attempted`)!==e.draftId)return null;const i=location.pathname.replace(/\/$/,"");if(i!==`/p/${e.draftId}`&&i!==`/p/${e.draftId}/edit`)return null;const a=m=>m.getClientRects().length>0&&getComputedStyle(m).visibility!=="hidden",n=m=>!m.closest('.Post-RichText,[contenteditable="true"],.DraftEditor-root'),s=Array.from(document.querySelectorAll('[role="dialog"],[aria-modal="true"],.Modal-wrapper,.Modal')).filter(m=>a(m)&&n(m)),o=(w=(h=document.querySelector("h1.Post-Title"))==null?void 0:h.textContent)==null?void 0:w.trim();return i===`/p/${e.draftId}`&&o===e.title&&s.some(m=>Array.from(m.querySelectorAll('h1,h2,h3,h4,[role="heading"],div,p,span')).some(p=>{var u;return a(p)&&n(p)&&/^(?:文章)?发布成功[!!]?$/.test(((u=p.textContent)==null?void 0:u.trim())||"")}))?{phase:"result",draftId:e.draftId,success:!0,publicationState:"submitted",pageConfirmed:!0}:Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="verify"],[class*="Captcha"],[class*="captcha"],.geetest_panel,.yidun_panel')).some(m=>a(m)&&n(m))||s.some(m=>/验证码|安全验证|人机验证|拖动滑块|旋转图片|转动图片/.test(m.textContent||""))?{phase:"result",draftId:e.draftId,success:!1,publicationState:"needs_user_action",manualReason:"captcha",message:"知乎要求验证码或图形验证,请用户点击原稿件链接,在同一投稿页完成验证并手动发布;Agent 不要打开网页或重发。"}:r}function hi(e){const t=`writedock-zhihu-${e.channel}`,r=`writedock-zhihu-early-${e.draftId}`;let i=!1,a=!1,n=!1,s=!1;const o=d=>new Promise(f=>setTimeout(f,d)),c=async(d,f={})=>{const l=await chrome.runtime.sendMessage({type:d,jobId:e.id,jobSecret:e.secret,...f});if(l!=null&&l.error)throw new Error(l.error)},y=d=>d.getClientRects().length>0&&getComputedStyle(d).visibility!=="hidden",h=d=>y(d)&&!d.hasAttribute("disabled")&&d.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(d.className),w=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(h),m=()=>{window.removeEventListener(t,g),window.removeEventListener(r,g),window.removeEventListener(`${t}:cancel`,u),window.dispatchEvent(new Event(`${t}:stop`)),window.dispatchEvent(new Event(`${r}:stop`))},p=async d=>{if(!(n||s)){try{sessionStorage.setItem(t,JSON.stringify({...d,phase:"result",draftId:e.draftId}))}catch{}n=!0,m(),await c("ZHIHU_ARTICLE_DONE",{result:{...d,phase:"result",draftId:e.draftId}})}},u=()=>{s=!0,m()},g=d=>{try{const f=JSON.parse(d.detail);if(f.draftId!==e.draftId||s||n)return;f.phase==="request"&&(a=!0,c("ZHIHU_ARTICLE_PROGRESS",{stage:"verifying"}).catch(()=>u())),f.phase==="result"&&p(f).catch(()=>u())}catch{}};window.addEventListener(t,g),window.addEventListener(r,g),window.addEventListener(`${t}:cancel`,u,{once:!0});const D=()=>Array.from(document.querySelectorAll('[role="alert"],.Message,.Toast,.Form-error,[class*="errorMessage"]')).filter(y).map(d=>{var f;return((f=d.textContent)==null?void 0:f.trim())||""}).find(d=>d.length<250&&/失败|错误|验证码|扫码|登录|必填|请填写|不能为空|请选择|未完成|频繁|限制/.test(d)),A=d=>{const f=/验证码|扫码|安全验证|人机验证|滑块|旋转|转动/.test(d)?"captcha":/声明|协议/.test(d)?"agreement":/必填|请填写|不能为空|请选择|未完成/.test(d)?"publication_settings":void 0;throw Object.assign(new Error(d),{manualReason:f})};return(async()=>{var W;const d=Math.min(Date.now()+6e4,e.deadline);let f,l=!1;for(;!s&&Date.now()<d;){f=Array.from(document.querySelectorAll("textarea,input")).find(N=>y(N)&&/标题/.test(N.placeholder||""));const P=document.querySelector('[data-contents="true"],[contenteditable="true"]');if((f==null?void 0:f.value.trim())===e.title&&P&&y(P)&&((W=P.textContent)!=null&&W.trim()||P.querySelector("img,.video-link"))){l=!0;break}await o(500)}if(s)return;if(!l||!f||f.value.trim()!==e.title||location.pathname.replace(/\/$/,"")!==`/p/${e.draftId}/edit`)throw new Error("知乎编辑页未加载目标稿件,或标题已变化,已停止发布");const _=Math.min(Date.now()+2e4,e.deadline),k=()=>document.querySelectorAll('[contenteditable="true"] img').length;for(;!s&&k()<(e.imageCount||0)&&Date.now()<_;)await o(500);if(s)return;if(k()<(e.imageCount||0))throw new Error(`知乎编辑器只有 ${k()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);const I=D();I&&A(I);const E=Math.min(Date.now()+3e4,e.deadline);let v=w().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});for(;!v&&!s&&!n&&Date.now()<E;)await o(500),v=w().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});if(s||n)return;if(!v)throw new Error(D()||"知乎发布按钮不可用,请检查登录、必填项或平台提示");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const R=new Set(w());if(await c("ZHIHU_ARTICLE_PROGRESS",{stage:"publishing"}),s||Date.now()>=e.deadline||f.value.trim()!==e.title||!v.isConnected||!h(v))throw new Error("知乎页面状态已变化,已停止操作");i=!0;try{sessionStorage.setItem(`${t}:attempted`,e.draftId)}catch{}v.click();let U=!1;const B=Math.min(Date.now()+12e4,e.deadline);for(;!s&&!n&&Date.now()<B;){const P=D();if(P&&A(P),!a&&!U){const N=w().find(x=>{var L;return x!==v&&/^(发布|发布文章|确认发布|立即发布)$/.test(((L=x.textContent)==null?void 0:L.trim())||"")&&(!R.has(x)||x.closest('[role="dialog"],.Modal,.PublishPanel,.Popover-content'))});N&&(U=!0,N.click())}await o(300)}!s&&!n&&await p({success:!1,publicationState:"unknown",error:"知乎已尝试发布,但没有取得匹配的成功回执,请用户点击原稿件链接核对;Agent 不要打开网页或自动重发"})})().catch(d=>p(d!=null&&d.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:d.manualReason,message:`${d.message}。请用户点击原稿件链接自行处理并手动发布,Agent 不要打开网页或重发。`}:{success:!1,publicationState:i?"unknown":"failed",error:d instanceof Error?d.message:"知乎页面投稿失败",.../频率|频繁|后重试|稍后再试|超过.*限制/.test(d instanceof Error?d.message:"")?{platformRejected:!0}:{}}).catch(()=>{})),{started:!0}}const xe=new Map;async function pi(){const e="writedock-zhihu-publication-observer";(await chrome.scripting.getRegisteredContentScripts({ids:[e]})).length||await chrome.scripting.registerContentScripts([{id:e,js:["zhihu-publication-observer.js"],matches:["https://zhuanlan.zhihu.com/p/*/edit*"],runAt:"document_start",world:"MAIN",allFrames:!1,persistAcrossSessions:!0}])}async function fi(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("知乎草稿 ID 无效,未提交发布");await pi();const n=`https://zhuanlan.zhihu.com/p/${e}/edit`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开知乎发布页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1,u=n,g,D,A=!1;const b=(E,v=!1)=>{if(!xe.has(c)||A&&!v&&!E.success)return;if(!v&&!a&&!A&&Ve(E)){A=!0,clearTimeout(_),Xe({tabId:o,platform:"zhihu",channel:h,url:u,message:"知乎要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。",isActive:()=>xe.has(c),progress:r,onReceipt:W=>{I.attempted=!0,b({...W,draftId:e},!0)},onHandOff:()=>b(E,!0)});return}if(!v&&E.publicationState==="unknown"&&I.resultDeadline&&Date.now()<I.resultDeadline){g=E;return}if(xe.delete(c),clearTimeout(_),clearInterval(k),clearTimeout(D),chrome.tabs.onRemoved.removeListener(f),chrome.tabs.onUpdated.removeListener(l),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:(W,P)=>{window.dispatchEvent(new Event(`${W}:cancel`)),window.dispatchEvent(new Event(`${W}:stop`)),window.dispatchEvent(new Event(`${P}:stop`));for(const N of[W,`${W}:attempted`,P,`${P}:ready`])sessionStorage.removeItem(N)},args:[`writedock-zhihu-${h}`,`writedock-zhihu-early-${e}`]}).catch(()=>{}),a&&E.publicationState==="rehearsed"){Ae(o,{...Ge("zhihu",n),postId:e}).then(m);return}const R=!a&&I.attempted&&E.success===!0&&E.publicationState==="submitted"&&E.draftId===e&&(E.responseConfirmed===!0||E.pageConfirmed===!0),U=E.publicationState==="needs_user_action"&&["captcha","agreement","publication_settings"].includes(E.manualReason||""),B=E.message||"请用户点击原稿件链接,在同一投稿页完成平台要求并手动发布;Agent 不要打开网页或重发。";Ae(o,{platform:"zhihu",success:R,draftOnly:!1,publicationState:R?"submitted":U?"needs_user_action":I.attempted&&!E.platformRejected?"unknown":"failed",postId:e,postUrl:R?`https://zhuanlan.zhihu.com/p/${e}`:n,...R?{confirmation:E.responseConfirmed?"http_response":"native_page_message",message:E.responseConfirmed?"知乎发布接口已确认提交成功":"知乎原生页面已明确提示本篇文章发布成功"}:U?{requiresUserAction:!0,userAction:{type:E.manualReason,url:u,message:B},message:B}:{error:E.error||"知乎发布结果未确认,请用户点击原稿件链接核对;Agent 不要打开网页或重发"},timestamp:Date.now()},E.warnings).then(m)},d=async()=>{var E;if(!(!xe.has(c)||!I.attempted||p)){p=!0;try{const R=(E=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:ui,args:[{channel:h,draftId:e,title:t}]}))[0])==null?void 0:E.result;(R==null?void 0:R.phase)==="result"&&R.draftId===e&&b(R)}catch{}finally{p=!1}xe.has(c)&&I.resultDeadline&&Date.now()>=I.resultDeadline&&b(g||{error:"知乎已尝试发布,但等待成功回执超时。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"})}},f=E=>{E===o&&(D=setTimeout(()=>b({error:"知乎投稿标签页已关闭,结果未确认。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),500))},l=(E,v,R)=>{if(!(E!==o||!xe.has(c)||!I.attempted)){if(/^https:\/\/www\.zhihu\.com\/account\/unhuman(?:[/?#]|$)/.test(R.url||"")){u=R.url,b({publicationState:"needs_user_action",manualReason:"captcha",message:"知乎进入了人工验证页,请用户切换到同一投稿标签页完成验证并手动发布,Agent 不要打开网页或重发。"});return}v.status==="complete"&&d()}},_=setTimeout(()=>b({error:"等待知乎发布结果超时,请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),10*6e4),k=setInterval(()=>{d()},1e3),I={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:b};xe.set(c,I),chrome.tabs.onRemoved.addListener(f),chrome.tabs.onUpdated.addListener(l),(async()=>{var B,W,P,N;const E=Date.now()+6e4;for(;Date.now()<E&&xe.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(L=>setTimeout(L,250));if(!xe.has(c))return;const v=await chrome.tabs.get(o);if(v.status!=="complete"||!((B=v.url)!=null&&B.startsWith(n)))throw new Error("知乎发布页未就绪,请确认登录状态");if(!((W=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:x=>sessionStorage.getItem(`writedock-zhihu-early-${x}:ready`)==="1",args:[e]}))[0])!=null&&W.result))throw new Error("知乎发布监听未在页面启动前就绪,已停止发布;请重新加载新版扩展后再试");if(await Je(o),!((N=(P=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:hi,args:[{id:c,secret:y,channel:h,draftId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:P.result)!=null&&N.started))throw new Error("无法启动知乎发布流程")})().catch(E=>b({error:E instanceof Error?E.message:"启动知乎发布失败"}))})}async function mi(e,t){var i,a;const r=xe.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||((a=t.url)==null?void 0:a.split("/")[2])!=="zhuanlan.zhihu.com"||e.jobSecret!==r.secret)throw new Error("知乎投稿任务已结束或来源不匹配");if(e.type==="ZHIHU_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("知乎投稿阶段不正确");return r.attempted=!0,r.resultDeadline??(r.resultDeadline=Date.now()+12e4),r.progress({stage:e.stage}),!0}if(e.type==="ZHIHU_ARTICLE_DONE"){const n=e.result;return r.finish(n||{error:"知乎没有返回投稿结果"}),!0}throw new Error("不支持的知乎页面操作")}function wi(e){const t=`writedock-baijiahao-${e.channel}`,r=[],i=b=>{const d=JSON.stringify({...b,articleId:e.articleId,...b.phase==="result"&&r.length?{warnings:r}:{}});try{sessionStorage.setItem(t,d)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:d}))},a=(b,d,f)=>{try{const l=new URL(d,location.href);if(b.toUpperCase()!=="POST"||l.origin!=="https://baijiahao.baidu.com"||l.pathname!=="/pcui/article/publish")return"unrelated";const _=f instanceof URLSearchParams||f instanceof FormData?f:typeof f=="string"?new URLSearchParams(f):null;if(!_||_.get("article_id")!==e.articleId)return"unrelated";const k=_.get("cover_images");let I;try{I=typeof k=="string"?JSON.parse(k):void 0}catch{return r.push("百家号 cover_images 格式无法解析"),"publish"}return I===void 0?(r.push("百家号发布请求中未读到 cover_images 字段"),"publish"):Array.isArray(I)?I.length?(I.every(E=>typeof(E==null?void 0:E.src)=="string"&&E.src)||r.push("百家号封面字段结构与抓包时不同"),"publish"):"cover_required":(r.push("百家号 cover_images 结构与抓包时不同"),"publish")}catch{return"unrelated"}},n=(b,d)=>i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:b,message:d}),s=(b,d)=>{var f;try{let l=d;if(typeof l=="string"){const I=l.trim(),E=/^[\w.$]+\s*\(([\s\S]*)\)\s*;?\s*$/.exec(I);l=JSON.parse(E?E[1]:I)}const _=l;if((_==null?void 0:_.errno)===10000015||/完成验证|安全验证|验证码/.test((_==null?void 0:_.errmsg)||"")){i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:"captcha",captchaRejected:!0,message:"百家号要求人工完成旋转图片等验证码。请切换到已打开的百家号稿件页完成验证;Agent 不要重新提交。"});return}if((_==null?void 0:_.errno)!==0&&/封面/.test((_==null?void 0:_.errmsg)||"")){n("cover_required","百家号要求选择或调整封面,请打开同一稿件页完成封面设置并手动发布。");return}const k=b>=200&&b<300&&(_==null?void 0:_.errno)===0&&((f=_.ret)==null?void 0:f.article_id)===e.articleId;i({phase:"result",success:k,publicationState:k?"submitted":"unknown",...k?{}:{error:(_==null?void 0:_.errno)===0?"百家号返回的文章 ID 与本任务不匹配,请在平台核实":String((_==null?void 0:_.errmsg)||`百家号发布结果未确认(HTTP ${b})`).slice(0,300)}})}catch{i({phase:"result",success:!1,publicationState:"unknown",error:"百家号发布响应无法解析,请检查平台,不要自动重发"})}},o=b=>{if(b==="cover_required")throw n("cover_required","百家号尚未选好封面,已停止自动发布。请打开同一稿件页选择封面并手动发布。"),new Error("百家号需要选择封面,自动发布已停止");if(b==="publish"&&e.rehearsal)throw new Error("演练不提交发布,已拦截百家号发布请求");b==="publish"&&i({phase:"request"})},c=window.fetch,y=async function(b,d){let f="unrelated";try{const l=(d==null?void 0:d.method)||(b instanceof Request?b.method:"GET"),_=b instanceof Request?b.url:String(b),k=(d==null?void 0:d.body)??(b instanceof Request&&l.toUpperCase()==="POST"&&new URL(_,location.href).pathname==="/pcui/article/publish"?await b.clone().text():void 0);f=a(l,_,k)}catch{}o(f);try{const l=await c.call(window,b,d);return f==="publish"&&s(l.status,await l.clone().text()),l}catch(l){throw f==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"百家号发布连接中断,请检查平台,不要自动重发"}),l}},h=XMLHttpRequest.prototype,w=h.open,m=h.send,p=new WeakMap,u=function(b,d,...f){return p.set(this,{method:b,url:String(d)}),Reflect.apply(w,this,[b,d,...f])},g=function(b){const d=p.get(this),f=d?a(d.method,d.url,b):"unrelated";return o(f),f==="publish"&&this.addEventListener("loadend",()=>{try{s(this.status,this.responseType==="json"?this.response:this.responseText)}catch{s(this.status,void 0)}},{once:!0}),m.call(this,b)};window.fetch=y,h.open=u,h.send=g;const D=()=>{window.fetch===y&&(window.fetch=c),h.open===u&&(h.open=w),h.send===g&&(h.send=m),clearTimeout(A),window.removeEventListener(`${t}:stop`,D)},A=setTimeout(D,Math.max(1,e.deadline-Date.now()));return window.addEventListener(`${t}:stop`,D,{once:!0}),{observing:!0}}function gi(e){const t=`writedock-baijiahao-${e.channel}`;let r=!1,i=!1,a=!1,n=!1;const s=d=>new Promise(f=>setTimeout(f,d)),o=async(d,f={})=>{const l=await chrome.runtime.sendMessage({type:d,jobId:e.id,jobSecret:e.secret,...f});if(l!=null&&l.error)throw new Error(l.error)},c=d=>d.getClientRects().length>0&&getComputedStyle(d).visibility!=="hidden",y=d=>c(d)&&!d.hasAttribute("disabled")&&d.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(d.className),h=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(y),w=()=>{window.removeEventListener(t,u),window.removeEventListener(`${t}:cancel`,m),window.dispatchEvent(new Event(`${t}:stop`))},m=()=>{r=!0,w()},p=async d=>{i||r||(i=!0,w(),await o("BAIJIAHAO_ARTICLE_DONE",{result:d}))},u=d=>{try{const f=JSON.parse(d.detail);if(f.articleId!==e.articleId||r||i)return;f.phase==="request"&&(n=!0,o("BAIJIAHAO_ARTICLE_PROGRESS",{stage:"verifying"}).catch(m)),f.phase==="result"&&p(f).catch(m)}catch{}};window.addEventListener(t,u),window.addEventListener(`${t}:cancel`,m,{once:!0});const g=()=>Array.from(document.querySelectorAll('iframe[src*="passport.baidu.com/cap"],#vcode-spin,.vcode-spin,.vcode-spin-wrapper,.vcode-spin-container')).some(c)||Array.from(document.querySelectorAll('[role="dialog"],.ant-modal,.passMod_dialog-wrapper')).some(d=>c(d)&&/旋转图片|完成验证|安全验证|验证码|拖动滑块/.test(d.textContent||"")),D=()=>p({success:!1,publicationState:"needs_user_action",manualReason:"captcha",message:"百家号要求人工验证码,请切换到当前稿件页完成验证并手动发布。Agent 不要重新提交。"}),A=()=>Array.from(document.querySelectorAll('[role="alert"],.ant-message-notice,.ant-notification-notice,.form-error')).filter(c).map(d=>{var f;return((f=d.textContent)==null?void 0:f.trim())||""}).find(d=>d.length<250&&/封面|失败|错误|验证码|完成验证|不能为空|必填|请选择|请填写|频繁|限制/.test(d));return(async()=>{var x;const d=Math.min(Date.now()+6e4,e.deadline);let f,l=!1;const _=L=>(L instanceof HTMLInputElement||L instanceof HTMLTextAreaElement?L.value:L.textContent||"").trim(),k=()=>Array.from(document.querySelectorAll('[class*="titleInput"] [contenteditable="true"],[class*="titleInput"] textarea,[class*="titleInput"] input,textarea[placeholder*="标题"],input[placeholder*="标题"]')).find(c),I=()=>{var $;const L=document.querySelector('iframe#ueditor_0,iframe[id^="ueditor_"]');try{const S=L&&c(L)?($=L.contentDocument)==null?void 0:$.body:null;if(S)return S}catch{}return Array.from(document.querySelectorAll('[contenteditable="true"],.ProseMirror,.ql-editor')).find(S=>c(S)&&!S.closest('[class*="titleInput"]'))};for(;!r&&!i&&Date.now()<d;){if(g()){await D();return}f=k();const L=I();if(f&&_(f)===e.title&&L&&((x=L.textContent)!=null&&x.replace(/[\s\u200b-\u200d\ufeff]/g,"")||L.querySelector("img"))){l=!0;break}await s(500)}if(r||i)return;if(!l||!f||_(f)!==e.title||new URL(location.href).searchParams.get("article_id")!==e.articleId)throw new Error("百家号编辑页未加载目标稿件,已停止发布");const E=Math.min(Date.now()+2e4,e.deadline),v=()=>{var L;return((L=I())==null?void 0:L.querySelectorAll("img").length)||0};for(;!r&&!i&&v()<(e.imageCount||0)&&Date.now()<E;)await s(500);if(r||i)return;if(v()<(e.imageCount||0))throw new Error(`百家号编辑器只有 ${v()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);const R=A();if(R&&/完成验证|安全验证|验证码/.test(R)){await D();return}if(R&&/封面/.test(R)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页处理并手动发布。"});return}const U=Math.min(Date.now()+3e4,e.deadline);let B=h().find(L=>{var $;return/^(发布|发布文章|立即发布)$/.test((($=L.textContent)==null?void 0:$.trim())||"")});for(;!B&&!r&&!i&&Date.now()<U;)await s(500),B=h().find(L=>{var $;return/^(发布|发布文章|立即发布)$/.test((($=L.textContent)==null?void 0:$.trim())||"")});if(r||i)return;if(!B)throw new Error(A()||"百家号发布按钮不可用,请检查页面要求");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const W=new Set(h());if(await o("BAIJIAHAO_ARTICLE_PROGRESS",{stage:"publishing"}),r||i||_(f)!==e.title||!B.isConnected||!y(B)||Date.now()>=e.deadline)throw new Error("百家号页面状态变化,已停止自动发布");a=!0,B.click();const P=Math.min(Date.now()+12e4,e.deadline);let N=!1;for(;!r&&!i&&Date.now()<P;){if(g()){await D();return}const L=A();if(L&&/完成验证|安全验证|验证码/.test(L)){await D();return}if(L&&/封面/.test(L)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页完成封面设置并手动发布。"});return}if(L)throw new Error(L);if(!n&&!N){const $=h().find(S=>{var M;return S!==B&&/^(发布|确认发布|立即发布|确认并发布|发布并提交审核)$/.test(((M=S.textContent)==null?void 0:M.trim())||"")&&(!W.has(S)||S.closest('[role="dialog"],.ant-modal'))});$&&(N=!0,$.click())}await s(300)}!r&&!i&&await p({success:!1,publicationState:"unknown",error:"已尝试发布,但未取得匹配的百家号成功响应,请检查平台,不要自动重发"})})().catch(d=>p({success:!1,publicationState:a?"unknown":"failed",error:d instanceof Error?d.message:"百家号页面投稿失败"}).catch(()=>{})),{started:!0}}const qe=new Map;async function yi(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("百家号稿件 ID 无效,未提交发布");const n=`https://baijiahao.baidu.com/builder/rc/edit?type=news&article_id=${e}`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开百家号发布页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!qe.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:o,platform:"baijiahao",channel:h,url:n,articleId:e,message:"百家号要求完成验证码。请在已打开的稿件页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>qe.has(c),progress:r,onReceipt:I=>{b.attempted=!0,u(I,!0)},onHandOff:()=>u(d,!0)});return}if(qe.delete(c),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:I=>{window.dispatchEvent(new Event(`${I}:cancel`)),window.dispatchEvent(new Event(`${I}:stop`)),sessionStorage.removeItem(I)},args:[`writedock-baijiahao-${h}`]}).catch(()=>{}),a&&d.publicationState==="rehearsed"){Ae(o,{...Ge("baijiahao",n),postId:e},d.warnings).then(m);return}const l=!a&&d.success===!0&&d.publicationState==="submitted",_=d.publicationState==="needs_user_action"&&["captcha","cover_required"].includes(d.manualReason||""),k=d.message||"请打开同一百家号稿件页,完成平台要求并手动发布。Agent 不要自动重试。";Ae(o,{platform:"baijiahao",success:l,draftOnly:!1,publicationState:l?"submitted":_?"needs_user_action":b.attempted?"unknown":"failed",postId:e,postUrl:l?`https://baijiahao.baidu.com/s?id=${e}`:n,timestamp:Date.now(),...l?{message:"百家号发布接口已确认提交成功"}:_?{requiresUserAction:!0,userAction:{type:d.manualReason,url:n,message:k},message:k}:{error:d.error||"百家号发布结果未确认,请检查平台"}},d.warnings).then(m)},g=d=>{d===o&&u({error:"百家号投稿页已关闭,请先检查平台,不要自动重发"})},D=(d,f,l)=>{var _;d!==o||f.status!=="complete"||!b.attempted||!((_=l.url)!=null&&_.startsWith("https://baijiahao.baidu.com/"))||chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:k=>sessionStorage.getItem(k),args:[`writedock-baijiahao-${h}`]}).then(k=>{var v;const I=(v=k[0])==null?void 0:v.result;if(typeof I!="string")return;const E=JSON.parse(I);E.articleId===e&&E.phase==="result"&&u(E)}).catch(()=>{})},A=setTimeout(()=>u({error:"等待百家号发布结果超时,请检查稿件,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,articleId:e,attempted:!1,progress:r,finish:u};qe.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var I,E,v,R;const d=Date.now()+6e4;for(;Date.now()<d&&qe.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(U=>setTimeout(U,250));if(!qe.has(c))return;const f=await chrome.tabs.get(o),l=new URL(f.url||"");if(f.status!=="complete"||l.origin!=="https://baijiahao.baidu.com"||l.searchParams.get("article_id")!==e)throw new Error("百家号稿件页未就绪,请确认登录");if(await Je(o),!((E=(I=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:wi,args:[{channel:h,articleId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:I.result)!=null&&E.observing))throw new Error("无法监测百家号发布响应,已停止发布");if(!((R=(v=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:gi,args:[{id:c,secret:y,channel:h,articleId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:v.result)!=null&&R.started))throw new Error("无法启动百家号发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动百家号发布失败"}))})}async function bi(e,t){var i,a;const r=qe.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://baijiahao.baidu.com/"))||e.jobSecret!==r.secret)throw new Error("百家号投稿任务已结束或来源不匹配");if(e.type==="BAIJIAHAO_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("百家号投稿阶段不正确");return r.attempted=!0,r.progress({stage:e.stage}),!0}if(e.type==="BAIJIAHAO_ARTICLE_DONE")return r.finish(e.result||{error:"百家号没有返回结果"}),!0;throw new Error("不支持的百家号页面操作")}function vi(e){const t=`writedock-weibo-article-${e.channel}`,r=[],i=b=>{const d=JSON.stringify({...b,draftId:e.draftId,...b.phase==="result"&&r.length?{warnings:r}:{}});try{sessionStorage.setItem(t,d)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:d}))},a=(b,d,f)=>{try{const l=new URL(d,location.href);if(b.toUpperCase()!=="POST"||l.origin!=="https://card.weibo.com")return null;const _=l.pathname==="/article/v5/aj/editor/draft/save"?"save":l.pathname==="/article/v5/aj/editor/draft/publish"?"publish":null;if(!_)return null;const k=f instanceof URLSearchParams||f instanceof FormData?f:typeof f=="string"?new URLSearchParams(f):null;return k&&k.get("id")===e.draftId?{operation:_,data:k}:null}catch{return null}},n=(b,d)=>i({phase:"result",success:!1,publicationState:"needs_user_action",manualReason:b,message:d}),s=b=>{if((b==null?void 0:b.operation)!=="publish")return;if(e.rehearsal)throw new Error("演练不提交发布,已拦截微博长文章发布请求");const d=["follow_official","is_original","follow_to_read","mpkey"],f=l=>l!==null&&l!==""&&l!=="0";if(d.some(l=>f(b.data.get(l)))||b.data.get("time"))throw n("publication_settings","微博发布窗口的关注、原创声明、阅读限制、同步或定时设置需要核对,已停止自动提交,请检查原稿件并手动发布。"),new Error("微博发布设置需要人工检查,未自动提交");for(const l of d)b.data.get(l)===null&&r.push(`微博发布请求中未读到 ${l} 字段`);i({phase:"request"})},o=(b,d,f)=>{var l,_,k,I;try{const E=typeof f=="string"?JSON.parse(f):f;if((_=(l=E==null?void 0:E.data)==null?void 0:l.geetest)!=null&&_.verifyUrl||/验证码|安全验证|完成验证/.test((E==null?void 0:E.msg)||"")){n("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(b!=="publish")return;let v="";try{const U=new URL(((k=E==null?void 0:E.data)==null?void 0:k.url)||""),B=U.searchParams.get("id");U.protocol==="https:"&&U.hostname==="weibo.com"&&U.pathname==="/ttarticle/p/show"&&B&&/^\d+$/.test(B)&&((I=E==null?void 0:E.data)==null?void 0:I.object_id)===`1022:${B}`&&(v=U.href)}catch{}const R=d>=200&&d<300&&(E==null?void 0:E.code)===1e5&&!!v;i({phase:"result",success:R,publicationState:R?"submitted":"unknown",...R?{postUrl:v}:{error:(E==null?void 0:E.code)===1e5?"微博返回的文章链接未能核实,请检查平台,不要重发":String((E==null?void 0:E.msg)||`微博发布结果未确认(HTTP ${d})`).slice(0,300)}})}catch{b==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"微博发布响应无法解析,请检查平台,不要自动重发"})}},c=window.fetch,y=async function(b,d){let f=null;try{const l=(d==null?void 0:d.method)||(b instanceof Request?b.method:"GET"),_=b instanceof Request?b.url:String(b),k=(d==null?void 0:d.body)??(b instanceof Request&&l.toUpperCase()==="POST"&&/\/draft\/(save|publish)$/.test(new URL(_,location.href).pathname)?await b.clone().text():void 0);f=a(l,_,k)}catch{}s(f);try{const l=await c.call(window,b,d);return f&&o(f.operation,l.status,await l.clone().text()),l}catch(l){throw(f==null?void 0:f.operation)==="publish"&&i({phase:"result",success:!1,publicationState:"unknown",error:"微博发布连接中断,请检查平台,不要自动重发"}),l}},h=XMLHttpRequest.prototype,w=h.open,m=h.send,p=new WeakMap,u=function(b,d,...f){return p.set(this,{method:b,url:String(d)}),Reflect.apply(w,this,[b,d,...f])},g=function(b){const d=p.get(this),f=d?a(d.method,d.url,b):null;return s(f),f&&this.addEventListener("loadend",()=>{try{o(f.operation,this.status,this.responseType==="json"?this.response:this.responseText)}catch{o(f.operation,this.status,void 0)}},{once:!0}),m.call(this,b)};window.fetch=y,h.open=u,h.send=g;const D=()=>{window.fetch===y&&(window.fetch=c),h.open===u&&(h.open=w),h.send===g&&(h.send=m),clearTimeout(A),window.removeEventListener(`${t}:stop`,D)},A=setTimeout(D,Math.max(1,e.deadline-Date.now()));return window.addEventListener(`${t}:stop`,D,{once:!0}),{observing:!0}}function _i(e){const t=`writedock-weibo-article-${e.channel}`;let r=!1,i=!1,a=!1,n=!1;const s=f=>new Promise(l=>setTimeout(l,f)),o=async(f,l={})=>{const _=await chrome.runtime.sendMessage({type:f,jobId:e.id,jobSecret:e.secret,...l});if(_!=null&&_.error)throw new Error(_.error)},c=f=>f.getClientRects().length>0&&getComputedStyle(f).visibility!=="hidden",y=f=>c(f)&&!f.hasAttribute("disabled")&&f.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(f.className),h=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(y),w=()=>{window.removeEventListener(t,u),window.removeEventListener(`${t}:cancel`,m),window.dispatchEvent(new Event(`${t}:stop`))},m=()=>{r=!0,w()},p=async f=>{i||r||(i=!0,w(),await o("WEIBO_ARTICLE_DONE",{result:f}))},u=f=>{try{const l=JSON.parse(f.detail);if(l.draftId!==e.draftId||r||i)return;l.phase==="request"&&(n=!0,o("WEIBO_ARTICLE_PROGRESS",{stage:"verifying"}).catch(m)),l.phase==="result"&&p(l).catch(m)}catch{}};window.addEventListener(t,u),window.addEventListener(`${t}:cancel`,m,{once:!0});const g=()=>Array.from(document.querySelectorAll('iframe[src*="security.weibo.com/verify"],iframe[src*="security.weibo.com/captcha"],iframe[src*="dun.163.com"],.yidun_popup,.yidun_modal,.geetest_panel')).some(c),D=()=>Array.from(document.querySelectorAll('[role="alert"],.n-message,.n-notification,.error_message')).filter(c).map(f=>{var l;return((l=f.textContent)==null?void 0:l.trim())||""}).find(f=>f.length<250&&/失败|错误|验证码|安全验证|封面|请输入|不能为空|频繁|限制/.test(f)),A=(f,l)=>p({success:!1,publicationState:"needs_user_action",manualReason:f,message:l}),b=(f,l=!0)=>{var k;const _=Array.from(document.querySelectorAll('span,label,[role="checkbox"]')).filter(I=>{var E;return c(I)&&(((E=I.textContent)==null?void 0:E.trim().length)||0)<100&&f.test(I.textContent||"")});for(const I of _){const E=I.closest('label,[role="checkbox"]')||((k=I.parentElement)==null?void 0:k.querySelector('input[type="checkbox"],[role="checkbox"]'));if(!E)return!1;const v=E instanceof HTMLInputElement?E:E.querySelector('input[type="checkbox"]'),R=v?v.checked:E.getAttribute("aria-checked")==="true"?!0:E.getAttribute("aria-checked")==="false"?!1:void 0;if(R===void 0||R&&(!l||!y(E)))return!1;R&&E.click();break}return!0};return(async()=>{var B,W;const f=Math.min(Date.now()+6e4,e.deadline);let l,_=!1;for(;!r&&!i&&Date.now()<f;){if(g()){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}l=Array.from(document.querySelectorAll("input,textarea")).find(N=>c(N)&&/标题/.test(N.placeholder||""));const P=document.querySelector('[contenteditable="true"],.ProseMirror');if((l==null?void 0:l.value.trim())===e.title&&P&&c(P)&&((B=P.textContent)!=null&&B.trim()||P.querySelector("img"))){_=!0;break}await s(500)}if(r||i)return;if(!_||!l||l.value.trim()!==e.title||!new RegExp(`^#/draft/${e.draftId}(?:[/?]|$)`).test(location.hash))throw new Error("微博长文章编辑页未加载目标稿件,已停止发布");const k=Math.min(Date.now()+2e4,e.deadline),I=()=>{var P;return((P=document.querySelector('[contenteditable="true"].ProseMirror,.ProseMirror'))==null?void 0:P.querySelectorAll("img").length)||0};for(;!r&&!i&&I()<(e.imageCount||0)&&Date.now()<k;)await s(500);if(r||i)return;if(I()<(e.imageCount||0))throw new Error(`微博长文章编辑器只有 ${I()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);if(!b(/同步至新浪新闻/)){await A("publication_settings","请检查微博文章的同步设置并手动发布,未自动提交到其他平台。");return}await s(100);const E=Math.min(Date.now()+3e4,e.deadline);let v=h().find(P=>{var N;return((N=P.textContent)==null?void 0:N.trim())==="下一步"})||h().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});for(;!v&&!r&&!i&&Date.now()<E;)await s(500),v=h().find(P=>{var N;return((N=P.textContent)==null?void 0:N.trim())==="下一步"})||h().find(P=>{var N;return/^(发布|发布文章)$/.test(((N=P.textContent)==null?void 0:N.trim())||"")});if(r||i)return;if(!v)throw new Error(D()||"未找到微博长文章的下一步按钮");if(e.rehearsal&&((W=v.textContent)==null?void 0:W.trim())!=="下一步"){await p({success:!1,publicationState:"rehearsed"});return}if(e.rehearsal||await o("WEIBO_ARTICLE_PROGRESS",{stage:"publishing"}),r||i||Date.now()>=e.deadline||l.value.trim()!==e.title||!v.isConnected||!y(v))throw new Error("微博页面状态变化,已停止操作");e.rehearsal||(a=!0),v.click();const R=Math.min(Date.now()+12e4,e.deadline);let U=!1;for(;!r&&!i&&Date.now()<R;){if(g()){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(h().find(x=>{var L,$;return((L=x.textContent)==null?void 0:L.trim())==="我同意"&&/头条文章原创声明|微博签约媒体原创认证协议/.test((($=x.closest('[role="dialog"],.n-dialog,.n-modal'))==null?void 0:$.textContent)||"")})){await A("agreement","微博显示原创相关协议确认,未自动同意或声明原创。请打开原稿件页阅读并自行决定,再手动发布。");return}const N=D();if(N&&/验证码|安全验证/.test(N)){await A("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(N&&/封面/.test(N)){await A("cover_required","微博长文章需要设置封面,请在原稿件页完成设置并手动发布。");return}if(N)throw new Error(N);if(!n&&!U){const x=h().find(L=>{var $;return L!==v&&(($=L.textContent)==null?void 0:$.trim())==="发布"&&L.closest('[role="dialog"],.n-modal,.n-dialog,.wb-common-dialog')});if(x){if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}if(!b(/关注\s*@头条文章/)||!b(/并声明本文是原创作品/,!1)){await A("publication_settings","微博发布窗口的勾选项无法安全核对,请自行检查关注及原创声明后手动发布。");return}if(await s(100),r||i||n)return;if(!x.isConnected||!y(x))throw new Error("微博发布确认按钮状态变化,未继续操作");U=!0,x.click()}}await s(300)}!r&&!i&&await p(e.rehearsal?{success:!1,publicationState:"failed",error:"点击下一步后未出现微博发布窗口,演练未通过"}:{success:!1,publicationState:"unknown",error:"微博长文章发布结果未确认,请检查平台,不要自动重发"})})().catch(f=>p({success:!1,publicationState:a?"unknown":"failed",error:f instanceof Error?f.message:"微博长文章投稿失败"}).catch(()=>{})),{started:!0}}const De=new Map;async function Ei(e,t,r,i={}){const a=i.rehearsal===!0;if(!/^\d+$/.test(e))throw new Error("微博长文章草稿 ID 无效,未提交发布");const n=`https://card.weibo.com/article/v5/editor#/draft/${e}`,s=await chrome.tabs.create({url:n,active:!0});if(!s.id)throw new Error("无法打开微博长文章编辑页");const o=s.id,c=crypto.randomUUID(),y=crypto.randomUUID(),h=crypto.randomUUID(),w=Date.now()+10*6e4;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!De.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:o,platform:"weibo-article",channel:h,url:n,message:"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。",isActive:()=>De.has(c),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}De.delete(c),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:E=>{window.dispatchEvent(new Event(`${E}:cancel`)),window.dispatchEvent(new Event(`${E}:stop`)),sessionStorage.removeItem(E)},args:[`writedock-weibo-article-${h}`]}).catch(()=>{});let l="";try{const E=new URL(d.postUrl||"");E.origin==="https://weibo.com"&&E.pathname==="/ttarticle/p/show"&&/^\d+$/.test(E.searchParams.get("id")||"")&&(l=E.href)}catch{}if(a&&d.publicationState==="rehearsed"){Ae(o,{...Ge("weibo",n),postId:e},d.warnings).then(m);return}const _=!a&&d.success===!0&&d.publicationState==="submitted"&&!!l,k=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),I=d.message||"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。";Ae(o,{platform:"weibo",success:_,draftOnly:!1,publicationState:_?"submitted":k?"needs_user_action":b.attempted?"unknown":"failed",postId:e,postUrl:_?l:n,timestamp:Date.now(),..._?{message:"微博长文章发布接口已确认成功"}:k?{requiresUserAction:!0,userAction:{type:d.manualReason,url:n,message:I},message:I}:{error:d.error||"微博长文章结果未确认,请检查平台"}},d.warnings).then(m)},g=d=>{d===o&&u({error:"微博投稿标签页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;if(!(d!==o||!De.has(c))){if(/^https:\/\/security\.weibo\.com\/(?:verify|captcha)(?:\/|\?|$)/.test(l.url||"")){u({publicationState:"needs_user_action",manualReason:"captcha",message:"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。"});return}f.status!=="complete"||!b.attempted||!((_=l.url)!=null&&_.startsWith("https://card.weibo.com/"))||chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:k=>sessionStorage.getItem(k),args:[`writedock-weibo-article-${h}`]}).then(k=>{var v;const I=(v=k[0])==null?void 0:v.result;if(typeof I!="string")return;const E=JSON.parse(I);E.draftId===e&&E.phase==="result"&&u(E)}).catch(()=>{})}},A=setTimeout(()=>u({error:"等待微博长文章发布结果超时,请检查平台,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:u};De.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var k,I,E,v,R;const d=Date.now()+6e4;for(;Date.now()<d&&De.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(U=>setTimeout(U,250));if(!De.has(c))return;const f=await chrome.tabs.get(o);if(f.status!=="complete"||!((k=f.url)!=null&&k.startsWith("https://card.weibo.com/article/v5/editor")))throw new Error("微博长文章编辑页未就绪,请确认登录");if(await Je(o),!((E=(I=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:vi,args:[{channel:h,draftId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:I.result)!=null&&E.observing))throw new Error("无法监测微博长文章的发布响应,已停止发布");if(!((R=(v=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:_i,args:[{id:c,secret:y,channel:h,draftId:e,title:t,deadline:w,rehearsal:a,imageCount:i.imageCount}]}))[0])==null?void 0:v.result)!=null&&R.started))throw new Error("无法启动微博长文章发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动微博长文章投稿失败"}))})}async function Si(e,t){var i,a;const r=De.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==0||!((a=t.url)!=null&&a.startsWith("https://card.weibo.com/"))||e.jobSecret!==r.secret)throw new Error("微博长文章任务已结束或来源不匹配");if(e.type==="WEIBO_ARTICLE_PROGRESS"){if(!["publishing","verifying"].includes(String(e.stage)))throw new Error("微博投稿阶段不正确");return r.attempted=!0,r.progress({stage:e.stage}),!0}if(e.type==="WEIBO_ARTICLE_DONE")return r.finish(e.result||{error:"微博没有返回结果"}),!0;throw new Error("不支持的微博长文章页面操作")}function Ai(e){const t=`writedock-bilibili-${e.channel}`,r=new DOMParser().parseFromString(e.html,"text/html"),i=S=>S.replace(/[\s\u200b-\u200d\ufeff]/g,""),a=i(r.body.textContent||""),n=r.querySelectorAll("img[src]").length,s=new Set,o=new Set,c=S=>{try{const M=new URL(String(S),location.href);return/^https?:$/.test(M.protocol)&&/(?:^|\.)(?:hdslb\.com|biliimg\.com)$/.test(M.hostname)&&M.pathname.startsWith("/bfs/")?M.pathname:""}catch{return""}};for(const S of r.querySelectorAll("img[src]")){const M=c(S.getAttribute("src"));M&&o.add(M)}let y=!1,h=!1,w=!1,m="";const p=[],u=S=>{p.includes(S)||p.push(S)},g=S=>Array.isArray(S)?S.length>0:S&&typeof S=="object"?Object.keys(S).length>0:!!S,D=S=>{const M=JSON.stringify({...S,jobId:e.id});try{sessionStorage.setItem(t,M)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:M}))},A=S=>{w||(w=!0,D({phase:"result",...p.length?{warnings:p}:{},...S}))},b=(S,M)=>A({success:!1,publicationState:"needs_user_action",manualReason:S,message:M}),d=S=>typeof S=="string"?JSON.parse(S):S,f=(S,M)=>{try{const X=new URL(M,location.href);if(X.origin!=="https://api.bilibili.com")return null;if(/^\/x\/gaia-vgate\/(?:v2\/register|v1\/img)$/.test(X.pathname))return"captcha";if(S.toUpperCase()!=="POST")return null;if(X.pathname==="/x/dynamic/feed/create/opus")return"publish";if(X.pathname==="/x/dynamic/feed/edit/opus"||/^\/x\/article\/creative\/article\/(?:addupdate|update)$/.test(X.pathname))return"other_publish";if(X.pathname==="/x/dynamic/feed/article/draft/add")return"draft";if(["/x/dynamic/feed/draw/upload_bfs","/x/dynamic/feed/draw/transfer_image"].includes(X.pathname))return"image"}catch{}return null},l=(S,M)=>{throw b(S,M),new Error("WriteDock 已停止B站专栏自动发布,请检查原稿件")},_=(S,M)=>{var ge,C,z,q,O,G;if(S==="captcha"){b("captcha","B站要求人工验证码。请切换到已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");return}if(S==="other_publish")return l("publication_settings","B站页面试图修改已有内容或使用旧发布接口,已停止操作,请核对原投稿页。");if(S!=="publish")return;if(e.rehearsal)return l("publication_settings","演练不提交发布,已拦截B站发布请求。");if(w||h||!y||Date.now()>=e.deadline)return h&&!w&&A({success:!1,publicationState:"unknown",error:"B站页面尝试重复提交,请检查原帖,不要自动重发。"}),l("publication_settings","本次B站稿件尚未核对完成或页面尝试重复发送,已停止自动提交。");let X;try{X=d(M)}catch{}if(!X||typeof X!="object"){u("B站发布请求格式无法解析,已依据提交前的编辑器核对放行"),h=!0,y=!1,D({phase:"request"});return}const j=X.opus_req,H=j==null?void 0:j.opus,ee=j==null?void 0:j.option;if(X.dyn_id_str||X.cvid_str)return l("publication_settings","B站发布请求指向已有内容,已停止发布。");if(typeof(H==null?void 0:H.title)=="string"&&H.title!==e.title)return l("publication_settings","B站发布请求的标题与本次稿件不一致,已停止发布。");if((ee==null?void 0:ee.private_pub)!==void 0&&ee.private_pub!==2||ee!=null&&ee.timer_pub_time||(ge=H==null?void 0:H.pub_info)!=null&&ge.timer_pub_time||ee!=null&&ee.only_fans||ee!=null&&ee.only_fans_level||g(j==null?void 0:j.topic)||g(H==null?void 0:H.attachments)||g((C=H==null?void 0:H.article)==null?void 0:C.list_id))return l("publication_settings","B站的公开范围、定时、充电专享、文集、话题或附加内容需要人工核对,请在原稿件页手动发布。");if((z=H==null?void 0:H.article)!=null&&z.originality)return l("agreement","B站稿件已选择原创声明,Agent 不自动声明原创或同意原创协议,请在原稿件页自行核对并手动发布。");if(X.draft_id_str&&m&&X.draft_id_str!==m)return l("publication_settings","B站发布请求未匹配本次原生编辑器保存的中间稿件,已停止发布。");X.raw_content!==void 0&&X.raw_content!==""&&u("B站 raw_content 不为空"),(j==null?void 0:j.scene)!==12&&u(`B站 scene=${String(j==null?void 0:j.scene)},与抓包时的 12 不同`),(H==null?void 0:H.opus_source)!==2&&u(`B站 opus_source=${String(H==null?void 0:H.opus_source)},与抓包时的 2 不同`),((q=H==null?void 0:H.article)==null?void 0:q.category_id)!==15&&u(`B站 category_id=${String((O=H==null?void 0:H.article)==null?void 0:O.category_id)},与抓包时的 15 不同`),typeof(H==null?void 0:H.title)!="string"&&u("B站发布请求中未读到标题字段"),(ee==null?void 0:ee.private_pub)===void 0&&u("B站发布请求中未读到公开范围字段"),((G=H==null?void 0:H.article)==null?void 0:G.originality)===void 0&&u("B站发布请求中未读到原创声明字段"),X.draft_id_str&&!m&&u("未观察到B站中间稿件保存回执");const Z=[],ie=[];let se=!1;const Y=T=>{if(!(!T||typeof T!="object")){if(Array.isArray(T)){T.forEach(Y);return}for(const[F,K]of Object.entries(T))F==="words"&&typeof K=="string"?Z.push(K):F==="pics"&&Array.isArray(K)?ie.push(...K):["video","video_card","archive","audio","live","bangumi","vote","goods","lottery"].includes(F)?se=!0:Y(K)}};if(Y(H==null?void 0:H.content),se)return l("publication_settings","B站发布内容包含未接入的内容卡片,已停止发布。");if(Z.length&&i(Z.join(""))!==a)return l("publication_settings","B站发布请求的正文与本次稿件不一致,已停止发布。");if(!Z.length&&a&&u("B站发布请求中未读到正文字段,已依据提交前的编辑器核对放行"),ie.length&&ie.length!==n)return l("publication_settings","B站发布请求的图片数量与本次稿件不一致,已停止发布。");if(!ie.length&&n&&u("B站发布请求中未读到图片字段,已依据提交前的编辑器核对放行"),ie.some(T=>String(T.url).startsWith("data:")))return l("publication_settings","B站发布请求中有图片尚未上传完成,已停止发布。");ie.some(T=>{const F=c(T.url);return!F||!s.has(F)&&!o.has(F)||!(T.width>0&&T.height>0)})&&u("B站发布请求中有图片未匹配本次观察到的上传记录"),h=!0,y=!1,D({phase:"request"})},k=(S,M,X,j)=>{var H,ee,Z,ie,se;if(!(w||S==="captcha"))try{const Y=d(X);if((Y==null?void 0:Y.code)===-352||/验证码|安全验证|验证后|完成验证/.test(String((Y==null?void 0:Y.message)||""))){A({success:!1,publicationState:"needs_user_action",manualReason:"captcha",captchaRejected:!0,message:"B站专栏要求人工验证。请在已打开的原投稿页完成验证码,Agent 不要重新提交。"});return}if(S==="image"){const z=(Y==null?void 0:Y.code)===0&&M>=200&&M<300?c((H=Y.data)==null?void 0:H.image_url):"";z&&(s.add(z),D({phase:"images",current:s.size,total:n}));return}if(S==="draft"){let z="";try{z=((Z=(ee=d(j))==null?void 0:ee.arg)==null?void 0:Z.title)||""}catch{}const q=(ie=Y==null?void 0:Y.data)==null?void 0:ie.article_id;(Y==null?void 0:Y.code)===0&&z===e.title&&(typeof q=="number"&&Number.isSafeInteger(q)||typeof q=="string")&&/^\d{1,16}$/.test(String(q))&&(m=String(q));return}if(S!=="publish")return;const ge=(se=Y==null?void 0:Y.data)==null?void 0:se.dyn_id_str,C=M>=200&&M<300&&(Y==null?void 0:Y.code)===0&&typeof ge=="string"&&/^\d{1,24}$/.test(ge);A({success:C,publicationState:C?"submitted":"unknown",...C?{responseConfirmed:!0,postId:ge,postUrl:`https://www.bilibili.com/opus/${ge}`}:{error:(Y==null?void 0:Y.code)===0?"B站返回成功但没有可核实的内容 ID,请检查平台,不要自动重发。":String((Y==null?void 0:Y.message)||`B站发布结果未确认(HTTP ${M})`).slice(0,300)}})}catch{S==="publish"&&A({success:!1,publicationState:"unknown",error:"B站发布回执无法解析,请检查原帖,不要自动重发。"})}},I=window.fetch,E=async function(S,M){const X=(M==null?void 0:M.method)||(S instanceof Request?S.method:"GET"),j=f(X,S instanceof Request?S.url:String(S)),H=["publish","draft"].includes(j||"")?(M==null?void 0:M.body)??(S instanceof Request?await S.clone().text():void 0):void 0;_(j,H);try{const ee=await I.call(window,S,M);return j&&k(j,ee.status,await ee.clone().text(),H),ee}catch(ee){throw j==="publish"&&A({success:!1,publicationState:"unknown",error:"B站发布连接中断,请检查原帖,不要自动重发。"}),ee}},v=XMLHttpRequest.prototype,R=v.open,U=v.send,B=new WeakMap,W=function(S,M,...X){return B.set(this,{method:S,url:String(M)}),Reflect.apply(R,this,[S,M,...X])},P=function(S){const M=B.get(this),X=M?f(M.method,M.url):null;return _(X,S),X&&this.addEventListener("loadend",()=>{try{k(X,this.status,this.responseType==="json"?this.response:this.responseText,S)}catch{X==="publish"&&k(X,this.status,void 0)}},{once:!0}),U.call(this,S)},N=()=>{!w&&!h&&Date.now()<e.deadline&&(y=!0)},x=()=>{var ee,Z;if(w||h)return;const S=window.editor,M=(Z=(ee=S==null?void 0:S.storage)==null?void 0:ee.biliImage)==null?void 0:Z.allImages,X=[],j=ie=>{!ie||typeof ie!="object"||(ie.type==="text"&&typeof ie.text=="string"&&X.push(ie.text),Array.isArray(ie.content)&&ie.content.forEach(j))};typeof(S==null?void 0:S.getJSON)=="function"&&j(S.getJSON());const H=typeof(S==null?void 0:S.getJSON)=="function"&&i(X.join(""))===a&&Array.isArray(M)&&M.length===n&&M.every(ie=>ie.attrs.status===1)&&(s.size>=n||M.every(ie=>!!c(ie.attrs.src)));D({phase:"content",ready:H})},L=()=>{window.fetch===E&&(window.fetch=I),v.open===W&&(v.open=R),v.send===P&&(v.send=U),clearTimeout($),window.removeEventListener(`${t}:arm`,N),window.removeEventListener(`${t}:read`,x),window.removeEventListener(`${t}:stop`,L)};window.fetch=E,v.open=W,v.send=P,window.addEventListener(`${t}:arm`,N),window.addEventListener(`${t}:read`,x),window.addEventListener(`${t}:stop`,L,{once:!0});const $=setTimeout(L,Math.max(1,e.deadline-Date.now()));return{observing:!0}}function Ii(e){const t=`writedock-bilibili-${e.channel}`;let r=!1,i=!1,a=!1,n=!1,s=!1;const o=l=>new Promise(_=>setTimeout(_,l)),c=async(l,_={})=>{const k=await chrome.runtime.sendMessage({type:l,jobId:e.id,jobSecret:e.secret,..._});if(!k||k.error)throw new Error((k==null?void 0:k.error)||"扩展后台已断开,请检查B站,不要自动重发")},y=l=>l.getClientRects().length>0&&getComputedStyle(l).visibility!=="hidden",h=l=>y(l)&&!l.hasAttribute("disabled")&&l.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(l.className),w=()=>Array.from(document.querySelectorAll('button,[role="button"]')).filter(h),m=()=>{window.removeEventListener(t,g),window.removeEventListener(`${t}:cancel`,p),window.dispatchEvent(new Event(`${t}:stop`))},p=()=>{r=!0,m()},u=async l=>{r||i||(i=!0,m(),await c("BILIBILI_ARTICLE_DONE",{result:l}))},g=l=>{try{const _=JSON.parse(l.detail);if(r||i||_.jobId!==e.id)return;_.phase==="content"&&(s=_.ready===!0),_.phase==="images"&&c("BILIBILI_ARTICLE_PROGRESS",{stage:"uploading_images",current:_.current,total:_.total}).catch(p),_.phase==="request"&&(n=!0,c("BILIBILI_ARTICLE_PROGRESS",{stage:"verifying"}).catch(p)),_.phase==="result"&&u(_).catch(p)}catch{}};window.addEventListener(t,g),window.addEventListener(`${t}:cancel`,p,{once:!0});function D(l,_){throw Object.assign(new Error(_),{manualReason:l})}const A=()=>{if(r||i)throw new Error("本次B站自动投稿已结束");if(Date.now()>=e.deadline)throw new Error("B站专栏投稿超时,请检查平台,不要自动重发");Array.from(document.querySelectorAll('iframe[src*="captcha"],iframe[src*="geetest"],.geetest_panel,.bili-captcha,.bili-captcha-container,.geetest_holder')).some(y)&&D("captcha","B站要求人工验证码,请在已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");const l=Array.from(document.querySelectorAll('[role="alert"],.vui_toast,.vui_toast--item,.b-message,.el-message,.vui_dialog,.vui-dialog')).filter(y).map(k=>{var I;return((I=k.textContent)==null?void 0:I.trim())||""}).filter(k=>k.length<1e3);l.some(k=>/验证码|完成验证|安全验证|拖动.*(?:滑块|图片)|点选.*文字/.test(k))&&D("captcha","请在已打开的B站专栏投稿页完成验证码并手动发布,Agent 不要重发。"),l.some(k=>/我已阅读|我同意|原创声明|确认.*声明/.test(k))&&D("agreement","B站要求确认原创声明或协议,请在原投稿页阅读、自行决定并手动发布。"),l.some(k=>/请选择|请设置|封面|未实名|绑定手机|转正答题|声明/.test(k))&&D("publication_settings","B站要求补充封面、账号权限或发布设置,请在原投稿页核对并手动处理。");const _=l.find(k=>/失败|错误|限制|超出|超过|不能为空|图片过大/.test(k));if(_)throw new Error(_.slice(0,300))},b=async(l,_,k)=>{const I=Math.min(Date.now()+_,e.deadline);for(;Date.now()<I;){A();const E=l();if(E)return E;await o(300)}throw new Error(k)},d=()=>(s=!1,window.dispatchEvent(new Event(`${t}:read`)),s),f=async()=>{var N,x;await c("BILIBILI_ARTICLE_PROGRESS",{stage:"preparing_article"});const l=await b(()=>document.querySelector("textarea.title-input__inner:not([disabled])"),3e4,"B站专栏标题输入框未就绪"),_=await b(()=>document.querySelector('.editor-container .ProseMirror[contenteditable="true"]'),3e4,"B站新版专栏正文编辑器未就绪"),k=L=>(L||"").replace(/[\s​-‍]/g,"").length>0;if((k(l.value)||k(_.textContent)||_.querySelector("img"))&&D("publication_settings","B站编辑器已有未发内容,未覆盖原稿,请在已打开的页面自行核对。"),l.maxLength>0&&e.title.length>l.maxLength)throw new Error(`B站当前标题最多 ${l.maxLength} 字,请让 Agent 缩短标题后重新提交,未截断发布`);const I=new DOMParser().parseFromString(e.html,"text/html");if(I.querySelector("video,audio,iframe"))throw new Error("当前B站专栏只接文字和图片,不接视频、音频或嵌入卡片");(x=(N=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"))==null?void 0:N.set)==null||x.call(l,e.title),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0}));const E=new DataTransfer;E.setData("text/html",I.body.innerHTML),E.setData("text/plain",I.body.textContent||""),A(),_.focus();const v=document.createRange();v.selectNodeContents(_);const R=getSelection();if(R==null||R.removeAllRanges(),R==null||R.addRange(v),_.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:E})),await b(()=>{if(_.querySelector(".upload-failed,.image-error"))throw new Error("B站正文图片上传失败,未删除图片后继续发布,请检查原稿件");return d()},5*6e4,"B站正文或图片未完整载入,请在原投稿页检查,未提交发布"),l.value!==e.title)throw new Error("B站标题被修改或截断,已停止发布");const U=await b(()=>w().find(L=>{var $;return(($=L.textContent)==null?void 0:$.trim())==="发布"}),3e4,"B站发布按钮不可用,请检查账号权限和正文要求");if(e.rehearsal){if(!d())throw new Error("B站稿件状态变化,演练未通过");await u({success:!1,publicationState:"rehearsed"});return}const B=new Set(w());if(await c("BILIBILI_ARTICLE_PROGRESS",{stage:"publishing"}),A(),!U.isConnected||!h(U)||l.value!==e.title||!d())throw new Error("B站稿件或发布控件状态变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,U.click();const W=Math.min(Date.now()+12e4,e.deadline);let P=!1;for(;!r&&!i&&Date.now()<W;){if(A(),!n&&!P){const L=w().find($=>{var S;return!B.has($)&&/^(?:确认发布|确认并发布|发布)$/.test(((S=$.textContent)==null?void 0:S.trim())||"")&&!!$.closest('[role="dialog"],.vui_dialog,.vui-dialog')});L&&(P=!0,L.click())}await o(300)}!r&&!i&&await u({success:!1,publicationState:"unknown",error:"已触发B站专栏发布,但未取得匹配的成功回执,请检查平台,不要自动重发。"})};try{const l=sessionStorage.getItem(t);l&&g(new CustomEvent(t,{detail:l}))}catch{}return!r&&!i&&f().catch(l=>{r||i||u(l!=null&&l.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:l.manualReason,message:l.message}:{success:!1,publicationState:a?"unknown":"failed",error:l instanceof Error?l.message:"B站专栏投稿失败"}).catch(p)}),{started:!0}}const Re=new Map,ar=e=>{try{const t=new URL(e);return t.protocol==="https:"&&["member.bilibili.com","www.bilibili.com"].includes(t.hostname)}catch{return!1}};async function xi(e,t,r,i={}){const a=i.rehearsal===!0,n=crypto.randomUUID(),s=crypto.randomUUID(),o=crypto.randomUUID(),c=Date.now()+10*6e4,y=`https://member.bilibili.com/platform/upload/text?writedock_article=${n}`,h=await chrome.tabs.create({url:y,active:!0});if(!h.id)throw new Error("无法打开B站专栏编辑页");const w=h.id;return new Promise(m=>{let p=!1;const u=(d,f=!1)=>{if(!Re.has(n)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ve(d)){p=!0,clearTimeout(A),Xe({tabId:w,platform:"bilibili",channel:o,url:b.editUrl,message:"B站要求输入验证码。请在已打开的投稿页输入验证码并点“确定”,确定后 B站会自动发布,不需要再点“发布”;结果会自动更新。",isActive:()=>Re.has(n),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}Re.delete(n),clearTimeout(A),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),b.frameId!==void 0&&chrome.scripting.executeScript({target:{tabId:w,frameIds:[b.frameId]},world:"ISOLATED",func:E=>{window.dispatchEvent(new Event(`${E}:cancel`)),window.dispatchEvent(new Event(`${E}:stop`)),sessionStorage.removeItem(E)},args:[`writedock-bilibili-${o}`]}).catch(()=>{});let l="";try{const E=new URL(d.postUrl||"");E.origin==="https://www.bilibili.com"&&/^\/opus\/\d{1,24}$/.test(E.pathname)&&d.postId===E.pathname.split("/").pop()&&(l=E.href)}catch{}if(a&&d.publicationState==="rehearsed"){Ae(w,Ge("bilibili",b.editUrl),d.warnings).then(m);return}const _=!a&&b.attempted&&d.success===!0&&d.publicationState==="submitted"&&d.responseConfirmed===!0&&!!l,k=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),I=String(d.message||"请在已打开的B站原投稿页完成验证或设置并手动发布,Agent 不要重新提交。").slice(0,1e3);Ae(w,{platform:"bilibili",success:_,draftOnly:!1,publicationState:_?"submitted":k?"needs_user_action":b.attempted?"unknown":"failed",postUrl:_?l:b.editUrl,timestamp:Date.now(),..._?{postId:d.postId,message:"B站专栏发布接口已确认提交,展示状态以平台为准"}:k?{requiresUserAction:!0,userAction:{type:d.manualReason,url:b.editUrl,message:I},message:I}:{error:d.error||"B站专栏发布结果未确认,请检查原稿件,不要自动重发"}},d.warnings).then(m)},g=d=>{d===w&&u({error:"B站专栏投稿页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;d!==w||!Re.has(n)||((_=l.url)!=null&&_.startsWith("https://member.bilibili.com/")&&(b.editUrl=l.url),!(f.status!=="complete"||!b.attempted)&&chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",func:k=>["member.bilibili.com","www.bilibili.com"].includes(location.hostname)?sessionStorage.getItem(k):null,args:[`writedock-bilibili-${o}`]}).then(k=>{for(const I of k){if(typeof I.result!="string"||!Re.has(n))continue;const E=JSON.parse(I.result);if(E.jobId===n&&E.phase==="result"){u(E);break}}}).catch(()=>{}))},A=setTimeout(()=>u({error:"等待B站专栏发布超时,请检查原稿件,不要自动重发"}),10*6e4),b={tabId:w,secret:s,channel:o,editUrl:y,attempted:!1,progress:r,finish:u};Re.set(n,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var l,_,k,I;const d=Date.now()+6e4;let f=!1;for(;Re.has(n)&&Date.now()<d;){const E=await chrome.tabs.get(w);if(ar(E.url||"")){const R=(await chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",func:()=>{if(location.protocol!=="https:"||!["member.bilibili.com","www.bilibili.com"].includes(location.hostname))return!1;const U=document.querySelector('.editor-container .ProseMirror[contenteditable="true"]'),B=document.querySelector("textarea.title-input__inner");return!!U&&!!B&&U.getClientRects().length>0&&B.getClientRects().length>0}})).filter(U=>U.result===!0);if(!R.length){const U=await chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",args:[f],func:B=>{if(location.protocol!=="https:"||location.hostname!=="member.bilibili.com")return null;const W=x=>x.getClientRects().length>0&&getComputedStyle(x).visibility!=="hidden";if(Array.from(document.querySelectorAll('.vui_dialog--body,.vui_dialog,[role="dialog"]')).filter(W).map(x=>x.textContent||"").some(x=>/当日投稿上限|今日投稿.*上限|已达.*上限/.test(x)))return"limit";if(B)return null;const N=Array.from(document.querySelectorAll('button.new-creation_button,button,[role="button"]')).find(x=>{var L;return W(x)&&((L=x.textContent)==null?void 0:L.trim())==="新的创作"});return N?(N.click(),"clicked"):null}}).catch(()=>[]);if(U.some(B=>B.result==="limit")){u({error:"B站账号已达到当日专栏投稿上限(LV1–3 每天 1 篇),今天无法再自动发布,未提交。请明天再试,或在B站手动保存为草稿。"});return}U.some(B=>B.result==="clicked")&&(f=!0,b.progress({stage:"preparing_article"}))}if(R.length>1)throw new Error("发现多个B站专栏编辑器,未选择不明确的稿件发布");if(R.length===1){const U=R[0];b.frameId=U.frameId,b.documentId=typeof U.documentId=="string"?U.documentId:void 0;const B={tabId:w,frameIds:[U.frameId]};await Je(w);const W=await chrome.scripting.executeScript({target:B,world:"MAIN",func:Ai,args:[{id:n,channel:o,title:e,html:t,deadline:c,rehearsal:a}]});if(!Re.has(n))return;if(!((_=(l=W[0])==null?void 0:l.result)!=null&&_.observing))throw new Error("无法监测B站专栏发布回执,已停止投稿");if(!((I=(k=(await chrome.scripting.executeScript({target:B,world:"ISOLATED",func:Ii,args:[{id:n,secret:s,channel:o,title:e,html:t,deadline:c,rehearsal:a}]}))[0])==null?void 0:k.result)!=null&&I.started))throw new Error("无法启动B站专栏投稿脚本");return}}else if(E.status==="complete")throw new Error("B站专栏未进入编辑页,请先完成登录");await new Promise(v=>setTimeout(v,500))}if(Re.has(n))throw new Error(f?"已点击B站「新的创作」,但专栏编辑器未出现,请确认账号权限与登录状态":"B站专栏页未找到「新的创作」入口或编辑器,请确认账号权限与登录状态")})().catch(d=>u({error:d instanceof Error?d.message:"启动B站专栏投稿失败"}))})}async function Ri(e,t){var i;const r=Re.get(String(e.jobId||""));if(!r||((i=t.tab)==null?void 0:i.id)!==r.tabId||t.frameId!==r.frameId||r.documentId&&t.documentId!==r.documentId||!ar(t.url||"")||e.jobSecret!==r.secret)throw new Error("B站专栏任务已结束或来源不匹配");if(e.type==="BILIBILI_ARTICLE_PROGRESS"){if(!["preparing_article","uploading_images","publishing","verifying"].includes(String(e.stage)))throw new Error("B站专栏投稿阶段不正确");return["publishing","verifying"].includes(String(e.stage))&&(r.attempted=!0),r.progress({stage:e.stage,...typeof e.current=="number"?{current:e.current}:{},...typeof e.total=="number"?{total:e.total}:{}}),!0}if(e.type==="BILIBILI_ARTICLE_DONE")return r.finish(e.result||{error:"B站专栏没有返回结果"}),!0;throw new Error("不支持的B站专栏页面操作")}let Be=!1,ve=null,Ft=Promise.resolve();const At=new Set;function Se(e){const t=Ft.catch(()=>{}).then(e);return Ft=t.then(()=>{},()=>{}),t}function Dt(){return Be}async function ki(e){await Se(async()=>{const r=(await chrome.storage.local.get(te.draftIndex))[te.draftIndex]||[],{id:i,title:a,updatedAt:n,source:s}=e;await chrome.storage.local.set({[`writedockDraft:${i}`]:e,[te.draftIndex]:[{id:i,title:a,updatedAt:n,source:s},...r.filter(o=>o.id!==i)]}),chrome.runtime.sendMessage({type:"DRAFT_SAVED",draftId:i}).catch(()=>{})})}async function Lt(e){const t=await or();return(t==null?void 0:t.id)===e?t:(await Ut()).find(r=>r.id===e)||null}async function wt(){const e=await chrome.storage.local.get([te.activeTask,te.history,te.lastInput]),t=e[te.activeTask]||null,r=e[te.history]||[],i=e[te.lastInput],a=[...new Set([t==null?void 0:t.draftId,...r.map(m=>m.draftId),i==null?void 0:i.input.draftId].filter(m=>!!m))],n=await Promise.all(a.map(async m=>[m,await chrome.storage.local.getBytesInUse(`writedockDraft:${m}`)>0])),s=new Set(n.filter(([,m])=>m).map(([m])=>m)),o=m=>s.has(m),c=t&&o(t.draftId)?t:null,y=r.filter(m=>o(m.draftId)),h=i&&o(i.input.draftId)?i:null,w=[];return t&&!c&&w.push(te.activeTask),i&&!h&&w.push(te.lastInput),y.length!==r.length&&await chrome.storage.local.set({[te.history]:y}),w.length&&await chrome.storage.local.remove(w),{active:c,history:y,last:h}}async function et(){if(!ve)return;const e=structuredClone(ve);await Se(async()=>{await chrome.storage.local.set({[te.activeTask]:e}),chrome.runtime.sendMessage({type:"TASK_UPDATED",task:e}).catch(()=>{})})}async function or(){return Be&&ve?structuredClone(ve):Se(async()=>{const{active:e}=await wt();return Be&&ve?structuredClone(ve):((e==null?void 0:e.status)==="syncing"&&(e.status="interrupted",e.finishedAt=Date.now(),e.error="上次任务被中断。请把原稿件或平台后台链接交给用户自行核对,Agent 不要调用浏览器或重新投稿。",await chrome.storage.local.set({[te.activeTask]:e})),e)})}async function Ut(){return Se(async()=>(await wt()).history)}async function $i(e){return Se(async()=>{const{last:t}=await wt();if(!t||t.taskId!==e)throw new Error("该任务的原始内容已被替换,请打开原稿后重新同步");return t.input})}async function Ti(e){if(typeof e!="string"||!e)throw new Error("草稿信息不完整");if(Be&&(ve==null?void 0:ve.draftId)===e)throw new Error("这篇文章正在同步,请等待同步结束后再删除");At.add(e);try{return await Se(async()=>{var c,y;const t=await chrome.storage.local.get([te.draftIndex,te.activeDraft,te.activeTask,te.history,te.lastInput,te.agentRequests]),r=(t[te.draftIndex]||[]).filter(h=>h.id!==e),i=(t[te.history]||[]).filter(h=>h.draftId!==e),a=[`writedockDraft:${e}`],n=((c=t[te.activeTask])==null?void 0:c.draftId)===e;n&&a.push(te.activeTask),((y=t[te.lastInput])==null?void 0:y.input.draftId)===e&&a.push(te.lastInput),t[te.activeDraft]===e&&a.push(te.activeDraft);const s=t[te.agentRequests]||{},o=Object.fromEntries(Object.entries(s).map(([h,w])=>[h,w.draftId===e?{...w,deleted:!0}:w]));return await chrome.storage.local.set({[te.draftIndex]:r,[te.history]:i,[te.agentRequests]:o}),await chrome.storage.local.remove(a),(ve==null?void 0:ve.draftId)===e&&(ve=null),n&&await chrome.action.setBadgeText({text:""}).catch(()=>{}),chrome.runtime.sendMessage({type:"DRAFT_DELETED",draftId:e}).catch(()=>{}),r})}finally{At.delete(e)}}async function Ci(e){var i;let t=await at(e);if(!t.isAuthenticated&&t.error&&(t=await at(e)),t.isAuthenticated)return;const r=((i=Ue().find(a=>a.id===e))==null?void 0:i.name)||e;throw Object.assign(new Error(t.error?`无法确认${r}的登录状态,未执行发布:${t.error}`:`${r}未登录,未执行发布。请在装有扩展的浏览器中登录后再提交`),{errorCode:t.error?"login_unconfirmed":"not_logged_in"})}async function Ot(e,t={}){var p;if(Be)throw new Error("已有一项同步正在进行,请等待完成");if(At.has(e==null?void 0:e.draftId))throw new Error("草稿正在删除,无法同步");const r=xt(e==null?void 0:e.platforms,Ue().map(u=>u.id)),i=e.post?Le(e.post):void 0,a=e.publication==="article",n=e.rehearsal===!0,s=e.routes;if(n&&!i&&!a&&!s)throw new Error("演练只支持发布类平台;公众号、搜狐号只保存草稿,无需演练");const o={rehearsal:n},c=di(e.discardOldDrafts,"douyin",n);if(!s){if(i?a||r.some(u=>!Rt(u)):r.some(u=>ft(u)&&!(a&&u==="xiaohongshu")))throw new Error("普通图文/视频用 publish_post,小红书长文及平台文章用 publish_article,需分别提交;旧草稿调用不会自动公开发布");if(i&&mt(i,r),a&&r.some(u=>!["zhihu","baijiahao","weibo","bilibili","xiaohongshu"].includes(u)))throw new Error("文章直发目前接入知乎、百家号、微博长文章、B站专栏和小红书长文");if(!i&&!a&&r.some(u=>["zhihu","baijiahao","weibo","bilibili"].includes(u)))throw new Error("知乎、百家号、微博长文章、B站专栏请使用 publish_article,旧草稿调用不会自动公开发布")}if(!(e!=null&&e.article)||typeof e.article.title!="string"||!e.article.title.trim())throw new Error("请先填写文章标题");if(typeof e.article.html!="string"||!Vt(e.article.html))throw new Error("请先编写文章正文或插入图片");if(new TextEncoder().encode(JSON.stringify(e.article)).length>24*1024*1024)throw new Error("文章图片过大,请压缩图片或减少图片后再同步");if(typeof e.draftId!="string")throw new Error("稿件信息不完整,请重新打开写作台");const y=$t(e.article.videos,e.article.html);if(!s){if(y.length&&(!a||r.some(u=>u!=="zhihu")))throw new Error("文章内嵌视频目前只支持知乎直发");if(a&&r.includes("zhihu")&&e.article.title.trim().length>100)throw new Error("知乎标题最多 100 字");if(a&&r.includes("baijiahao")&&(e.article.title.trim().length>64||!e.article.cover))throw new Error("百家号请提供 64 字以内的标题和必选封面 cover");if(a&&r.includes("weibo")&&e.article.title.trim().length>32)throw new Error("当前微博长文章接入接收 32 字以内的标题");if(a&&r.includes("xiaohongshu")&&e.article.title.trim().length>64)throw new Error("小红书长文标题最多 64 字");if(a&&r.includes("xiaohongshu")&&e.article.cover)throw new Error("小红书长文由原生自动排版生成封面,不接独立 cover,请分别提交");if(a&&r.includes("bilibili")&&e.article.cover)throw new Error("当前B站专栏未接入独立封面 cover,请与需要封面的平台分别提交");if(a&&!r.some(u=>["baijiahao","weibo"].includes(u))&&e.article.cover)throw new Error("独立封面 cover 目前用于百家号和微博长文章")}Be=!0,ve={id:t.taskId||`sync_${crypto.randomUUID()}`,draftId:e.draftId,title:e.article.title.trim(),platforms:r,status:"syncing",progress:Object.fromEntries(r.map(u=>[u,{stage:"pending"}])),results:[],startedAt:Date.now(),action:n?"rehearsal":s||i||a?"publish":"draft"};const h=ve,w=new Map,m=(u,g)=>{var D;h.progress[u]=g,g.stage==="waiting_verification"&&((D=w.get(u))==null||D()),et().catch(A=>console.warn("[WriteDock] Progress could not be saved:",A))};try{await Se(async()=>{if(await chrome.storage.local.getBytesInUse(`writedockDraft:${e.draftId}`)===0)throw new Error("这篇草稿已被删除,请重新打开写作台");const{discardOldDrafts:A,...b}=e;await chrome.storage.local.set({[te.lastInput]:{taskId:h.id,input:b}})}),await et(),(p=t.onStarted)==null||p.call(t,structuredClone(h));const u=s||i||a?1:3,g=[];for(let A=0;A<r.length;A+=u){const b=r.slice(A,A+u),d=Promise.all(b.map(async f=>{var v,R;let l;const _=s==null?void 0:s.find(U=>U.platform===f),k=_?_.mode==="post":!!i,I=_?_.mode==="article":a,E=_?{...e.article,cover:_.cover}:e.article;try{if(_!=null&&_.error)throw new Error(_.error);if(m(f,{stage:"checking_auth"}),await Ci(f),k&&i)l=await ri(f,i,U=>m(f,U),f==="douyin"&&c?{...o,discardOldDraft:c}:o);else if(I&&f==="xiaohongshu")l=await Kr(e.article.title.trim(),e.article.html||"",U=>m(f,U),o);else{const U=await Yt(f),B=await Lr(e.article.html||"",Dr(f));for(const{marker:W,asset:P}of y){if(!(U instanceof Zt)||B.html.split(W).length!==2)throw new Error("文章视频占位符在排版后不完整,已停止发布");m(f,{stage:"uploading_media",current:0,total:P.size});const N=await U.uploadArticleVideo(P,($,S)=>Ct(P,$,S),($,S)=>m(f,{stage:"uploading_media",current:$,total:S})),x=Me(N.cover),L=`<a class="video-link" href="https://www.zhihu.com/video/${N.videoId}" data-src="" data-name="${Me(P.name)}" data-poster="${x}" data-video-id="" data-lens-id="${N.videoId}" data-video-playable="true"><img src="${x}" alt="${Me(P.name)}"><span>${Me(P.name)}</span></a>`;B.html=B.html.replace(W,L)}if(m(f,{stage:I?"preparing_article":"saving"}),I&&f==="bilibili")l=await xi(e.article.title.trim(),B.html,W=>m(f,W),o);else{const W=await Et(U.publish({...E,...B,...I&&f==="zhihu"?{cover:void 0}:{}},{draftOnly:!0,onImageProgress:(P,N)=>{m(f,{stage:P>=N?I?"preparing_article":"saving":"uploading_images",current:P,total:N})}}),6e5,"准备平台稿件超时,请先检查平台后台,再决定是否重试");if(I){if(!W.success||!W.postId)throw new Error(W.error||"平台稿件准备失败,未提交发布");const P=f==="zhihu"?fi:f==="weibo"?Ei:yi,N=(B.html.replace(/<a class="video-link"[\s\S]*?<\/a>/g,"").match(/<img\b/gi)||[]).length;l=await P(String(W.postId),e.article.title.trim(),x=>m(f,x),{...o,imageCount:N})}else l=W}}}catch(U){l={platform:f,success:!1,error:U instanceof Error?U.message:"同步失败,请稍后重试",timestamp:Date.now(),...k||I?{draftOnly:!1,publicationState:"failed"}:{},...U.errorCode?{errorCode:U.errorCode}:{}}}(v=_==null?void 0:_.notes)!=null&&v.length&&(l={...l,warnings:[..._.notes,...l.warnings||[]]}),l.success||(l={...l,diagnostics:{...l.diagnostics,stage:(R=h.progress[f])==null?void 0:R.stage}}),h.results.push(l),h.progress[f]={stage:l.publicationState==="needs_user_action"?"needs_user_action":l.publicationState==="unknown"?"unknown":l.success||l.publicationState==="rehearsed"?"completed":"failed",error:l.error},await et()}));g.push(d),await Promise.race([d,new Promise(f=>{for(const l of b)w.set(l,f)})])}await Promise.all(g),h.status=wr(h.results,r.length),h.finishedAt=Date.now(),await et(),await Se(async()=>{const{history:A}=await wt();await chrome.storage.local.set({[te.history]:[structuredClone(h),...A].slice(0,25)})});const D=h.results.filter(A=>A.success||A.publicationState==="rehearsed").length;return await chrome.action.setBadgeText({text:D===r.length?"✓":`${D}`}),await chrome.action.setBadgeBackgroundColor({color:D===r.length?"#2563eb":"#9a6700"}),structuredClone(h)}catch(u){throw h.status="failed",h.error=u instanceof Error?u.message:"同步任务失败",h.finishedAt=Date.now(),await et().catch(()=>{}),u}finally{Be=!1}}let Wt=Promise.resolve();function gt(e){const t=Wt.catch(()=>{}).then(e);return Wt=t,t}async function Pt(e){if(!e||typeof e!="object")throw new Error("请提供稿件内容");const t=e;if(typeof t.title!="string"||!t.title.trim()||t.title.trim().length>200)throw new Error("文章标题需要 1–200 字");if(typeof t.html!="string"||new TextEncoder().encode(JSON.stringify(t)).length>24*1024*1024)throw new Error("稿件格式不正确,或超过 24 MB");if(t.cover&&!rt(t.cover)&&!/^data:image\/(png|jpeg|gif|webp);base64,/i.test(t.cover))throw new Error("封面图片地址无效");const r=await Ur(t.html);if(!Vt(r))throw new Error("稿件正文为空");const i=$t(t.videos,r);return{title:t.title.trim(),html:r,markdown:"",...t.cover?{cover:t.cover}:{},...i.length?{videos:i}:{}}}async function yt(e,t=[],r){var n;const i=Date.now(),a={id:crypto.randomUUID(),title:e.title,html:e.html||"",cover:e.cover||"",platforms:t,createdAt:i,updatedAt:i,source:"mcp",...r?{post:r}:{},...(n=e.videos)!=null&&n.length?{videos:e.videos}:{}};return await ki(a),a}async function Di(e){return gt(async()=>{var i;const t=await Pt(e),r=await yt(t);return{draft_id:r.id,title:r.title,image_count:(r.html.match(/<img\b/gi)||[]).length,video_count:((i=r.videos)==null?void 0:i.length)||0,saved_locally:!0}})}async function Li(e){return gt(async()=>{const t=Le(e);return{draft_id:(await yt(Tt(t),[],t)).id,title:t.title,kind:t.kind,image_count:t.images.length,...t.video?{video_file:t.video.name}:{},saved_locally:!0}})}async function qt(e){const r=(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{};return Object.hasOwn(r,e)?r[e]:void 0}const Ui=e=>{const t=r=>e.results.filter(r).map(i=>i.platform);return{submitted:t(r=>r.success&&!r.draftOnly),draft_saved:t(r=>r.success&&r.draftOnly===!0),rehearsed:t(r=>r.publicationState==="rehearsed"),not_logged_in:t(r=>r.errorCode==="not_logged_in"),login_unconfirmed:t(r=>r.errorCode==="login_unconfirmed"),needs_user_action:t(r=>r.publicationState==="needs_user_action"),waiting_verification:e.platforms.filter(r=>{var i;return((i=e.progress[r])==null?void 0:i.stage)==="waiting_verification"}),unknown:t(r=>r.publicationState==="unknown"),failed:t(r=>!r.success&&!r.errorCode&&!["rehearsed","needs_user_action","unknown"].includes(r.publicationState||"")),pending:e.platforms.filter(r=>{var i;return!e.results.some(a=>a.platform===r)&&((i=e.progress[r])==null?void 0:i.stage)!=="waiting_verification"})}},ot=(e,t=!1)=>{var n;const r=Ue(),i=e.results.flatMap(s=>{var y,h,w,m;const o=s.requiresUserAction||s.publicationState==="needs_user_action";if(!o&&s.publicationState!=="unknown")return[];const c=rt(((y=s.userAction)==null?void 0:y.url)||s.postUrl)||rt((h=r.find(p=>p.id===s.platform))==null?void 0:h.homepage);return[{platform:s.platform,type:((w=s.userAction)==null?void 0:w.type)||(o?"publication_settings":"result_unconfirmed"),...c?{url:c}:{},message:((m=s.userAction)==null?void 0:m.message)||s.message||s.error||"请用户在原稿件页核对并手动处理。"}]});if(e.status==="interrupted")for(const s of e.platforms.filter(o=>!e.results.some(c=>c.platform===o))){const o=rt((n=r.find(c=>c.id===s))==null?void 0:n.homepage);i.push({platform:s,type:"result_unconfirmed",...o?{url:o}:{},message:"任务已中断,结果未确认。请用户点击平台链接自行核对,不要重新投稿。"})}for(const[s,o]of Object.entries(e.progress)){if(o.stage!=="waiting_verification")continue;const c=rt(o.url);i.push({platform:s,type:"captcha",...c?{url:c}:{},message:o.message||"请在已打开的页面完成验证。"})}if(e.action==="rehearsal")for(const s of i)s.message=s.type==="old_draft"?"演练未走完:抖音有一份上次没发完的内容,演练不会动它。真实发布时再问用户是否放弃。":`演练未走完:${s.message.replace(/并手动发布|并手动处理|手动发布/g,"")}这只是演练,不需要点击发布。`;const a=e.status!=="syncing";return{task_id:e.id,draft_id:e.draftId,status:e.status,reused:t,finished:a,next_action:a?"report_result":"poll_task",...a?{}:{poll_after_ms:3e3},...e.action==="rehearsal"?{rehearsal:!0}:{},agent_instructions:(e.action==="rehearsal"?"这是演练任务,没有向平台提交发布,rehearsed 不代表已发布,不得告诉用户内容已发出;未经用户明确要求,不要接着调用发布工具。":"")+"仅通过 WriteDock MCP 获取发布结果,不需要也不得调用浏览器、Playwright 或其他网页工具验证或处理投稿。任务进行中按原 task_id/request_id 调用 get_sync_task,不重复提交;submitted/published 直接向用户汇报确认结果和链接,不再打开网页验证。needs_user_action、unknown 或 interrupted 时,将原因和 user_actions 链接交给用户自行点击、验证或手动发布;不要代做验证码、自动重发或更换 request_id。人工接管后不声称已发布。失败时把 error 和 diagnostics(阶段、页面结构、请求记录)原样提供给用户或开发者排查;warnings 是平台字段变化的提醒,不代表失败,一并转告。waiting_verification 表示该平台在等用户完成验证码:立即把 user_actions 的 message 和链接原样告诉用户,由用户在已打开的页面手动完成验证,Agent 不代做、不重发,并继续查询;用户验证后任务会自动更新结果。任务结束后按 summary 逐平台告诉用户结果:哪些成功,哪些未登录(not_logged_in,未执行发布,让用户登录后用新的 request_id 只重发这些平台)。",requires_user_action:i.length>0,...i.length?{user_actions:i}:{},summary:Ui(e),results:e.results,task:e}};async function tt(e){return gt(async()=>{var g,D;const t=e.rehearsal===!0,r=e.requestId;if(!t&&(typeof r!="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(r)))throw new Error("请提供 8–120 位稳定的 request_id(字母、数字、下划线或横线)");const i=t?void 0:await qt(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=xt(e.platforms,Ue().map(A=>A.id)),n=e.publication===!0,s=e.publication==="article";if(t&&!n&&!s)throw new Error("演练只支持发布类平台;公众号、搜狐号只保存草稿,无需演练");if(n&&a.some(A=>!Rt(A)))throw new Error("publish_post 支持小红书、抖音和微博普通图文/视频;知乎、百家号、微博长文章、B站专栏请用 publish_article");if(!n&&a.some(A=>ft(A)&&!(s&&A==="xiaohongshu")))throw new Error("小红书长文请用 publish_article;小红书、抖音图文/视频请用 publish_post;旧草稿调用不会自动公开发布");if(s&&a.some(A=>!["zhihu","baijiahao","weibo","bilibili","xiaohongshu"].includes(A)))throw new Error("publish_article 目前接入知乎、百家号、微博长文章、B站专栏和小红书长文");if(!i&&!n&&!s&&a.some(A=>["zhihu","baijiahao","weibo","bilibili"].includes(A)))throw new Error("知乎、百家号、微博长文章、B站专栏已改用 publish_article;旧草稿调用不会自动公开发布");let o,c,y;if(typeof e.draftId=="string"){if(e.article||e.post)throw new Error("draft_id 与稿件内容不能同时提供");if(o=(await chrome.storage.local.get(`writedockDraft:${e.draftId}`))[`writedockDraft:${e.draftId}`],!o)throw new Error("稿件不存在或已被删除");if(n){if(!o.post)throw new Error("请先用 prepare_post 准备图文或视频素材");y=Le(o.post)}else if(o.post)throw new Error("该稿件是图文或视频投稿,请使用 publish_post");c={title:o.title,html:o.html,markdown:"",cover:o.cover||void 0,...(g=o.videos)!=null&&g.length?{videos:$t(o.videos,o.html)}:{}}}else n?(y=Le(e.post),c=Tt(y)):c=await Pt(e.article);if(y&&mt(y,a),(D=c.videos)!=null&&D.length&&(!s||a.some(A=>A!=="zhihu")))throw new Error("文章内嵌视频目前只支持单独向知乎 publish_article");if(s&&a.includes("zhihu")&&c.title.length>100)throw new Error("知乎文章标题最多 100 字,请先缩短标题");if(s&&a.includes("baijiahao")&&(c.title.length>64||!c.cover))throw new Error("百家号直发请提供 64 字以内的标题和必选封面 cover(本地图片路径或图片地址)");if(s&&a.includes("weibo")&&c.title.length>32)throw new Error("当前微博长文章接入接收 32 字以内的标题");if(s&&a.includes("xiaohongshu")&&c.title.length>64)throw new Error("小红书长文标题最多 64 字,请先缩短标题");if(s&&a.includes("xiaohongshu")&&c.cover)throw new Error("小红书长文由原生自动排版生成封面,不接独立 cover,请与需要封面的平台分别提交");if(s&&a.includes("bilibili")&&c.cover)throw new Error("当前B站专栏未接入独立封面 cover,请与需要封面的平台分别提交");if(s&&!a.some(A=>["baijiahao","weibo"].includes(A))&&c.cover)throw new Error("独立封面 cover 目前用于百家号和微博长文章");const{videos:h,...w}=c,m=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({article:w,platforms:[...a].sort(),draftId:e.draftId||null,...y?{post:rr(y)}:{},...s?{publication:"article",...h!=null&&h.length?{videos:tr(h)}:{}}:{}}))),p=Array.from(new Uint8Array(m),A=>A.toString(16).padStart(2,"0")).join("");if(i){if(i.fingerprint!==p)throw new Error("同一个 request_id 对应的稿件或平台已改变;请使用新的 request_id");const A=await Lt(i.taskId);if(!A)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return ot(A,!0)}if(Dt())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");o??(o=await yt(c,a,y));const u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Se(async()=>{const A=await chrome.storage.local.get(te.agentRequests);await chrome.storage.local.set({[te.agentRequests]:{...A[te.agentRequests]||{},[r]:{fingerprint:p,draftId:o.id,taskId:u}}})});try{const A=await new Promise((b,d)=>{Ot({draftId:o.id,platforms:a,article:c,...y?{post:y}:{},...s?{publication:"article"}:{},...t?{rehearsal:!0}:{}},{taskId:u,onStarted:b}).catch(d)});return ot(A)}catch(A){throw t||await Se(async()=>{const d={...(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{}};delete d[r],await chrome.storage.local.set({[te.agentRequests]:d})}),A}})}async function jt(e){return gt(async()=>{const t=e.rehearsal===!0,r=e.requestId;if(!t&&(typeof r!="string"||!/^[A-Za-z0-9_-]{8,120}$/.test(r)))throw new Error("请提供 8–120 位稳定的 request_id(字母、数字、下划线或横线)");const i=t?void 0:await qt(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=xt(e.platforms,Ue().map(g=>g.id));if(!e.article&&!e.post)throw new Error("请提供 article(文章)或 post(图文/视频)内容");const n=e.article?await Pt(e.article):void 0,s=e.post?Le(e.post):void 0,o=li({platforms:a,article:n,post:s,modes:e.modes,rehearsal:t});if(o.every(g=>g.error))throw new Error(`所有平台都无法接收这份内容:${o.map(g=>g.error).join(";")}`);const c=n||Tt(s),{videos:y,...h}=c,w=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify({unified:!0,article:h,routes:o.map(({platform:g,mode:D})=>({platform:g,mode:D})).sort((g,D)=>g.platform.localeCompare(D.platform)),...s?{post:rr(s)}:{},...y!=null&&y.length?{videos:tr(y)}:{}}))),m=Array.from(new Uint8Array(w),g=>g.toString(16).padStart(2,"0")).join("");if(i){if(i.fingerprint!==m)throw new Error("同一个 request_id 对应的稿件或平台已改变;请使用新的 request_id");const g=await Lt(i.taskId);if(!g)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return ot(g,!0)}if(Dt())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");const p=await yt(c,a,s),u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Se(async()=>{const g=await chrome.storage.local.get(te.agentRequests);await chrome.storage.local.set({[te.agentRequests]:{...g[te.agentRequests]||{},[r]:{fingerprint:m,draftId:p.id,taskId:u}}})});try{const g=await new Promise((D,A)=>{Ot({draftId:p.id,platforms:a,article:c,...s?{post:s}:{},routes:o,...t?{rehearsal:!0}:{},...e.discardOldDrafts?{discardOldDrafts:e.discardOldDrafts}:{}},{taskId:u,onStarted:D}).catch(A)});return ot(g)}catch(g){throw t||await Se(async()=>{const A={...(await chrome.storage.local.get(te.agentRequests))[te.agentRequests]||{}};delete A[r],await chrome.storage.local.set({[te.agentRequests]:A})}),g}})}async function Oi(e){let t=e.taskId;if(typeof e.requestId=="string"){const i=await qt(e.requestId);if(!i||i.deleted)throw new Error("该请求没有可查询的本地任务,或其稿件已被删除");if(t&&t!==i.taskId)throw new Error("task_id 与 request_id 不匹配");t=i.taskId}if(typeof t!="string"||!t)throw new Error("请提供 task_id 或 request_id");const r=await Lt(t);if(!r)throw new Error("任务不存在,或已超出最近 25 条记录的保留范围");return ot(r)}const Mt="writedock-mcp-reconnect";let It,Ee=null,it,Bt=0,ht=!1,st,dt=!1,pt={};const sr=()=>Array.from(crypto.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join("");async function ct(){return It??(It=(async()=>{const t=(await chrome.storage.local.get(te.bridge))[te.bridge],r={enabled:(t==null?void 0:t.enabled)===!0,port:Number.isInteger(t==null?void 0:t.port)&&t.port>=1024&&t.port<=65535?t.port:9647,token:typeof(t==null?void 0:t.token)=="string"&&/^[A-Za-z0-9_-]{24,128}$/.test(t.token)?t.token:sr()};return await chrome.storage.local.set({[te.bridge]:r}),r})()),It}async function ut(e,t){ht=e,st=t,e||(pt={}),chrome.runtime.sendMessage({type:"BRIDGE_STATUS_UPDATED"}).catch(()=>{})}const Pi=(e,t)=>{const r=n=>n.split(/[-+]/)[0].split(".").map(Number),i=r(e),a=r(t);for(let n=0;n<3;n++)if(i[n]!==a[n])return i[n]>a[n];return!1};function Jt(e){const t=i=>typeof i=="string"&&i.length<=120&&/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(i);if(!t(e.mcp_version))return;const r={mcpVersion:e.mcp_version,...t(e.latest_version)?{mcpLatestVersion:e.latest_version}:{},mcpUpdateAvailable:t(e.latest_version)&&e.update_available===!0,...typeof e.update_checked_at=="number"&&Number.isSafeInteger(e.update_checked_at)?{mcpUpdateCheckedAt:e.update_checked_at}:{},...typeof e.update_check_error=="string"?{mcpUpdateCheckError:e.update_check_error.slice(0,200)}:{},mcpUpdateChecking:e.update_checking===!0,...t(e.extension_bundle_version)&&Pi(e.extension_bundle_version,chrome.runtime.getManifest().version)?{extensionUpdateVersion:e.extension_bundle_version}:{}};JSON.stringify(r)!==JSON.stringify(pt)&&(pt=r,chrome.runtime.sendMessage({type:"BRIDGE_STATUS_UPDATED"}).catch(()=>{}))}async function Gt(e,t,r){const i=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",i,new TextEncoder().encode(`${t}:${r}`));return Array.from(new Uint8Array(a),n=>n.toString(16).padStart(2,"0")).join("")}async function qi(e){try{const r=await(await fetch(`http://127.0.0.1:${e}/hello`,{signal:AbortSignal.timeout(1500),cache:"no-store"})).json();return(r==null?void 0:r.service)==="writedock-mcp"?{mcpFound:!0,...typeof r.version=="string"?{mcpFoundVersion:r.version.slice(0,40)}:{}}:{}}catch{return{}}}async function cr(){const e=await ct();return{...e,connected:ht,...pt,...st?{error:st}:{},...ht?{}:await qi(e.port)}}let We;async function Mi(){if(Dt())throw new Error("正在发布,请等任务结束后再更新");if(!Ee||Ee.readyState!==WebSocket.OPEN||!ht)throw new Error("还没有连接,无法更新");const e=await new Promise((t,r)=>{const i=setTimeout(()=>{We=void 0,r(new Error("更新超时,请稍后再试"))},6e4);We={resolve:a=>{clearTimeout(i),We=void 0,t(a)}},Ee.send(JSON.stringify({type:"update_extension"}))});if(e.ok!==!0)throw new Error(typeof e.error=="string"?e.error:"更新失败");return setTimeout(()=>chrome.runtime.reload(),300),!0}async function Bi(){if(dt)throw new Error("正在连接,请稍候");dt=!0;try{const e=await ct(),t=await new Promise((r,i)=>{const a=new WebSocket(`ws://127.0.0.1:${e.port}/connect`),n=setTimeout(()=>{a.close(),i(new Error("连接超时,请确认 agent 已启动 WriteDock"))},8e3);a.onmessage=s=>{clearTimeout(n);try{const o=JSON.parse(s.data);if(o.type!=="connect_result"||typeof o.token!="string"||!/^[A-Za-z0-9_-]{24,128}$/.test(o.token)||o.port!==e.port)throw new Error("invalid");r({token:o.token,port:o.port})}catch{i(new Error("服务返回的连接信息不正确"))}a.close()},a.onerror=()=>{clearTimeout(n),i(new Error("无法连接服务,请确认 agent 已启动 WriteDock"))}});return st=void 0,await lr(e,{...e,...t,enabled:!0})}finally{dt=!1}}async function lr(e,t){const r=t.enabled!==e.enabled||t.port!==e.port||t.token!==e.token;if(await chrome.storage.local.set({[te.bridge]:t}),It=Promise.resolve(t),r){clearTimeout(it),it=void 0,Bt=0;const i=Ee;Ee=null,i==null||i.close(),await ut(!1),t.enabled?await nt():await chrome.alarms.clear(Mt)}return cr()}async function Ni(e){if(dt)throw new Error("正在连接,请完成后再修改设置");const t=await ct(),r={...t};if("enabled"in e){if(typeof e.enabled!="boolean")throw new Error("连接开关格式不正确");r.enabled=e.enabled}if("port"in e){if(!Number.isInteger(e.port)||e.port<1024||e.port>65535)throw new Error("端口需要是 1024–65535 的整数");r.port=e.port}return e.rotateToken===!0&&(r.token=sr()),lr(t,r)}async function zi(e,t){switch(e){case"listPlatforms":return Qt(t.forceRefresh===!0);case"checkAuth":{if(typeof t.platform!="string")throw new Error("请提供平台 ID");const r=Ue().find(i=>i.id===t.platform);if(!r)throw new Error("扩展没有此平台的适配器");return{...r,...await at(t.platform)}}case"prepareArticle":return Di(t.article);case"preparePost":return Li(t.post);case"publishPost":return tt({...t,publication:!0,rehearsal:!1});case"publishArticle":return tt({...t,publication:"article",rehearsal:!1});case"syncArticle":return tt({...t,publication:void 0,rehearsal:!1});case"publish":return jt({...t,rehearsal:!1});case"rehearsePublish":return jt({...t,rehearsal:!0});case"rehearsePost":return tt({...t,publication:!0,rehearsal:!0});case"rehearseArticle":return tt({...t,publication:"article",rehearsal:!0});case"getSyncTask":return Oi(t);case"getSyncHistory":return Ut();default:throw new Error("不支持的 MCP 操作")}}async function Hi(){it||!(await ct()).enabled||(it=setTimeout(()=>{it=void 0,nt()},Math.min(500*2**Math.min(Bt++,5),1e4)))}async function nt(){const e=await ct();if(!e.enabled||(await chrome.alarms.create(Mt,{periodInMinutes:1}),Ee&&(Ee.readyState===WebSocket.OPEN||Ee.readyState===WebSocket.CONNECTING)))return;const t=new WebSocket(`ws://127.0.0.1:${e.port}/extension`);Ee=t;let r=!1,i=!1;const a=setTimeout(()=>{r||t.close(1008,"Handshake timed out")},8e3);t.onmessage=n=>{(async()=>{if(Ee!==t)return;const s=JSON.parse(n.data);if(s.type==="challenge"&&!r){if(typeof s.nonce!="string"||!/^[a-f0-9]{64}$/.test(s.nonce)||s.proof!==await Gt(e.token,"server",s.nonce)){await ut(!1,"连接已失效,请点“连接”重新连上"),t.close(1008,"Handshake failed");return}if(Ee!==t||t.readyState!==WebSocket.OPEN)return;i=!0,t.send(JSON.stringify({type:"hello",extensionId:chrome.runtime.id,proof:await Gt(e.token,"extension",s.nonce)}));return}if(s.type==="ready"){if(!i)throw new Error("WriteDock 服务没有通过验证");r=!0,Bt=0,clearTimeout(a),Jt(s),await ut(!0);return}if(!r)throw new Error("WriteDock 服务尚未连接");if(s.type==="update_extension_result"){We==null||We.resolve(s);return}if(s.type==="ping"){Jt(s),t.send(JSON.stringify({type:"pong"}));return}if(typeof s.id!="string"||typeof s.method!="string"||!s.params||typeof s.params!="object"||Array.isArray(s.params))throw new Error("MCP 请求格式不正确");let o;try{o={id:s.id,result:await zi(s.method,s.params)}}catch(c){o={id:s.id,error:{code:-32e3,message:c instanceof Error?c.message:"MCP 操作失败"}}}t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(o))})().catch(()=>{t.close(1008,"Invalid MCP message")})},t.onclose=n=>{clearTimeout(a),Ee===t&&(Ee=null,ut(!1,st||(n.code===1008?"连接没有成功,请点“连接”重试;如果另一个浏览器也装了 WriteDock,请先关掉它":"等待 agent 启动 MCP 服务")),Hi())},t.onerror=()=>{}}function Fi(){chrome.alarms.onAlarm.addListener(e=>{e.name===Mt&&nt()}),chrome.runtime.onStartup.addListener(()=>{nt()}),nt().catch(console.error)}async function dr(){const e=chrome.runtime.getURL("src/editor/index.html"),r=(await chrome.tabs.query({})).find(i=>{var a;return((a=i.url)==null?void 0:a.split("#")[0])===e});r!=null&&r.id?(await chrome.tabs.update(r.id,{active:!0}),await chrome.windows.update(r.windowId,{focused:!0})):await chrome.tabs.create({url:e}),await chrome.action.setBadgeText({text:""})}chrome.action.onClicked.addListener(()=>{dr().catch(console.error)});chrome.runtime.onInstalled.addListener(e=>{e.reason==="install"&&chrome.storage.local.remove(te.authCache).catch(console.error)});chrome.runtime.onMessage.addListener((e,t,r)=>t.id!==chrome.runtime.id||(e==null?void 0:e.target)==="offscreen"||["TASK_UPDATED","DRAFT_DELETED","DRAFT_SAVED","BRIDGE_STATUS_UPDATED"].includes(e==null?void 0:e.type)?!1:((async()=>{switch(e==null?void 0:e.type){case"XHS_PUBLISH_PROGRESS":case"XHS_READ_ASSET":case"XHS_READ_ARTICLE_IMAGE":case"XHS_PUBLISH_DONE":return Qr(e,t);case"BILIBILI_ARTICLE_PROGRESS":case"BILIBILI_ARTICLE_DONE":return Ri(e,t);case"WEIBO_ARTICLE_PROGRESS":case"WEIBO_ARTICLE_DONE":return Si(e,t);case"BAIJIAHAO_ARTICLE_PROGRESS":case"BAIJIAHAO_ARTICLE_DONE":return bi(e,t);case"ZHIHU_ARTICLE_PROGRESS":case"ZHIHU_ARTICLE_DONE":return mi(e,t);case"PAGE_PUBLISH_PROGRESS":case"PAGE_PUBLISH_READ_ASSET":case"PAGE_PUBLISH_DONE":return ii(e,t);case"GET_PLATFORMS":return Ue();case"CHECK_ALL_AUTH":return Qt(e.forceRefresh===!0);case"CHECK_AUTH":return at(e.platform);case"SYNC_ARTICLE":return Ot(e.payload);case"GET_SYNC_STATE":return or();case"GET_SYNC_HISTORY":return Ut();case"GET_LAST_INPUT":return $i(e.taskId);case"DELETE_DRAFT":return Ti(e.draftId);case"GET_BRIDGE_STATE":return cr();case"SET_BRIDGE_CONFIG":return Ni(e.payload||{});case"CONNECT_BRIDGE":return Bi();case"UPDATE_EXTENSION":return Mi();case"OPEN_EDITOR":return await dr(),!0;default:throw new Error("不支持的请求")}})().then(a=>r({data:a})).catch(a=>{r({error:a instanceof Error?a.message:"操作失败,请重试"})}),!0));Fi();
@@ -4,7 +4,7 @@
4
4
  "name": "写作台 WriteDock",
5
5
  "short_name": "写作台",
6
6
  "description": "连接自己的 AI agent,通过 MCP 发布小红书长文、图文和视频,微博图文、视频及长文章,知乎、百家号、B站专栏文章与抖音图文视频。",
7
- "version": "0.4.9",
7
+ "version": "0.4.10",
8
8
  "minimum_chrome_version": "116",
9
9
  "icons": {
10
10
  "16": "assets/icon-16.png",
@@ -1 +1 @@
1
- import './assets/index.ts-C3FUEli7.js';
1
+ import './assets/index.ts-CSY6FJ6h.js';
@@ -1,4 +1,4 @@
1
- WriteDock 安装与更新 v0.4.9
1
+ WriteDock 安装与更新 v0.4.10
2
2
 
3
3
  首次使用
4
4
  1. 把这句话发给你的 agent:帮我安装 WriteDock:先检查电脑上有没有 Node.js 22 或更高版本,没有就帮我安装,需要我操作时告诉我;然后运行 npx -y writedock-mcp@latest setup,最后告诉我怎么重启你。
package/index.cjs CHANGED
@@ -29740,7 +29740,7 @@ var MediaStore = class {
29740
29740
  // package.json
29741
29741
  var package_default = {
29742
29742
  name: "@writedock/mcp-server",
29743
- version: "0.4.9",
29743
+ version: "0.4.10",
29744
29744
  private: true,
29745
29745
  type: "module",
29746
29746
  description: "WriteDock local MCP server for the browser extension",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "writedock-mcp",
3
- "version": "0.4.9",
3
+ "version": "0.4.10",
4
4
  "description": "WriteDock local MCP server for the browser extension",
5
5
  "type": "commonjs",
6
6
  "license": "GPL-3.0-only",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedock/mcp-server",
3
- "version": "0.4.9",
3
+ "version": "0.4.10",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "description": "WriteDock local MCP server for the browser extension",