writedock-mcp 0.4.8 → 0.4.9

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.
@@ -1,42 +0,0 @@
1
- var ur=Object.defineProperty;var hr=(e,t,r)=>t in e?ur(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ae=(e,t,r)=>hr(e,typeof t!="symbol"?t+"":t,r);import{c as Be,m as pr,a as fr,j as mr}from"./index.browser-Hs3ZYqOv.js";import{S as Q,e as qe,n as St,h as Vt,d as wr,s as et}from"./task-utils-DwzGcJkm.js";import"./react-vendor-BrXlnJmF.js";const gr={outputFormat:"html",removeIframes:!0,removeComments:!0,removeSpecialTags:!0,removeSvgImages:!0,processCodeBlocks:!0,processLazyImages:!0,removeEmptyElements:!0,removeDataAttributes:!0,removeEmptyImages:!0,removeSrcset:!0,removeSizes:!0,normalizeViaMarkdown:!1};function Xt(e){const t=[],r=e.length;let i=0;const a=n=>{for(let s=n;s<r;s++){const o=e[s];if(o==="\\"){s++;continue}if(o==="]")return s}return-1};for(;i<r;){const n=e.indexOf("![",i);if(n===-1)break;const s=n+2,o=a(s);if(o===-1||e[o+1]!=="("){i=s;continue}let c=o+2;for(;c<r&&/\s/.test(e[c]);)c++;let y="";if(e[c]==="<"){const m=e.indexOf(">",c+1);if(m===-1){i=o+1;continue}y=e.slice(c+1,m),c=m+1}else{const m=c;let p=0;for(;c<r;){const u=e[c];if(u==="\\"){c+=2;continue}if(u==="(")p++;else if(u===")"){if(p===0)break;p--}else if(/\s/.test(u)&&p===0)break;c++}y=e.slice(m,c)}if(!y){i=o+1;continue}for(;c<r&&/\s/.test(e[c]);)c++;if(c<r&&(e[c]==='"'||e[c]==="'")){const m=e[c];for(c++;c<r;){const p=e[c];if(p==="\\"){c+=2;continue}if(p===m){c++;break}c++}for(;c<r&&/\s/.test(e[c]);)c++}else if(c<r&&e[c]==="("){for(c++;c<r;){const m=e[c];if(m==="\\"){c+=2;continue}if(m===")"){c++;break}c++}for(;c<r&&/\s/.test(e[c]);)c++}if(e[c]!==")"){i=o+1;continue}const h=e.slice(n,c+1),w=e.slice(s,o);t.push({full:h,alt:w,src:y}),i=c+1}return t}const Ue=Be("CodeAdapter");class We{constructor(){ae(this,"runtime");ae(this,"headerRuleIds",[])}async init(t){this.runtime=t}async addHeaderRule(t){if(!this.runtime.headerRules)return null;const r=await this.runtime.headerRules.add(t);return this.headerRuleIds.push(r),r}async addHeaderRules(t){for(const r of t)await this.addHeaderRule(r);this.headerRuleIds.length>0&&Ue.debug(`[${this.meta.id}] Header rules added:`,this.headerRuleIds)}async clearHeaderRules(){if(!(!this.runtime.headerRules||this.headerRuleIds.length===0)){for(const t of this.headerRuleIds)await this.runtime.headerRules.remove(t);Ue.debug(`[${this.meta.id}] Header rules cleared:`,this.headerRuleIds),this.headerRuleIds=[]}}async withHeaderRules(t,r){await this.addHeaderRules(t);try{return await r()}finally{await this.clearHeaderRules()}}async get(t,r){const i=await this.runtime.fetch(t,{method:"GET",credentials:"include",headers:r});return this.parseResponse(i)}async postJson(t,r,i){const a=await this.runtime.fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...i},body:JSON.stringify(r)});return this.parseResponse(a)}async postForm(t,r,i){const a=await this.runtime.fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...i},body:new URLSearchParams(r)});return this.parseResponse(a)}async postMultipart(t,r,i){const a=await this.runtime.fetch(t,{method:"POST",credentials:"include",headers:i,body:r});return this.parseResponse(a)}async parseResponse(t){if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.text();try{return JSON.parse(r)}catch{return r}}async processImages(t,r,i){const{skipPatterns:a=[],onProgress:n,failOnUploadError:s=!1}=i||{},o=[],c=/<img[^>]+src=(?:"([^"]*)"|'([^']*)'|((?:https?:)?\/\/[^\s>"']+|data:[^\s>"']+))[^>]*>/gi;let y;for(;(y=c.exec(t))!==null;){const p=y[1]||y[2]||y[3];p&&o.push({full:y[0],src:p,type:"html"})}for(const p of Xt(t))o.push({full:p.full,src:p.src,alt:p.alt,type:"markdown"});if(o.length===0)return t;Ue.debug(`Found ${o.length} images to process (HTML + Markdown)`);let h=t;const w=new Map;let m=0;for(const{full:p,src:u,alt:g,type:D}of o)if(u){if(!u.startsWith("data:")&&a.some(b=>u.includes(b))){Ue.debug(`Skipping matched pattern: ${u}`);continue}m++,n==null||n(m,o.length);try{let S=w.get(u);S||(Ue.debug(`Uploading image ${m}/${o.length}: ${u.startsWith("data:")?"data URI":u}`),S=await r(u),w.set(u,S));let b;if(D==="html"){if(b=`<img src="${S.url}"`,S.attrs)for(const[d,f]of Object.entries(S.attrs))b+=` ${d}="${f}"`;b+=" />"}else b=`![${g||""}](${S.url})`;h=h.replace(p,b),Ue.debug(`Image uploaded: ${S.url}`)}catch(S){if(Ue.error(`Failed to upload image: ${u}`,S),s)throw new Error(`正文图片上传失败,未提交发布:${S.message}`)}await this.delay(300)}return h}async uploadImageByUrl(t){throw new Error("uploadImageByUrl not implemented")}async uploadImage(t,r){const i=await this.blobToDataUri(t);return(await this.uploadImageByUrl(i)).url}async blobToDataUri(t){return new Promise((r,i)=>{const a=new FileReader;a.onload=()=>{const n=a.result;typeof n=="string"?r(n):i(new Error("Failed to read blob as data URI"))},a.onerror=()=>i(new Error("FileReader error")),a.readAsDataURL(t)})}async dataUriToBlob(t){return(await fetch(t)).blob()}delay(t){return new Promise(r=>setTimeout(r,t))}createResult(t,r){return{platform:this.meta.id,success:t,timestamp:Date.now(),...r}}}const $e=Be("Sohu");function wt(){const e="0123456789abcdef";let t="";for(let r=0;r<32;r++)t+=e[Math.floor(Math.random()*e.length)];return t}class yr extends We{constructor(){super(...arguments);ae(this,"meta",{id:"sohu",name:"搜狐号",icon:"https://mp.sohu.com/favicon.ico",homepage:"https://mp.sohu.com/mpfe/v3/main/first/page?newsType=1",capabilities:["article","draft","image_upload"]});ae(this,"preprocessConfig",{outputFormat:"html"});ae(this,"accountInfo",null);ae(this,"deviceId",wt());ae(this,"spCm","");ae(this,"HEADER_RULES",[{urlFilter:"*://mp.sohu.com/*",headers:{Origin:"https://mp.sohu.com",Referer:"https://mp.sohu.com/"},resourceTypes:["xmlhttprequest"]}])}async checkAuth(){var r,i,a,n;try{const o=await(await this.runtime.fetch(`https://mp.sohu.com/mpbp/bp/account/list?_=${Date.now()}`,{method:"GET",credentials:"include"})).json();if($e.debug("checkAuth response:",o),o.code!==2e6||!((n=(a=(i=(r=o.data)==null?void 0:r.data)==null?void 0:i[0])==null?void 0:a.accounts)!=null&&n.length))return{isAuthenticated:!1};const c=[];for(const h of o.data.data)h.accounts&&c.push(...h.accounts);if(c.length===0)return{isAuthenticated:!1};this.accountInfo=c[0],$e.info(`Using account: ${this.accountInfo.nickName} (id: ${this.accountInfo.id})`+(c.length>1?`, ${c.length} sub-accounts available`:"")),await this.fetchSpCm();const y=c.length>1?`${this.accountInfo.nickName} (共${c.length}个子账号)`:this.accountInfo.nickName;return{isAuthenticated:!0,userId:String(this.accountInfo.id),username:y,avatar:this.accountInfo.avatar}}catch(s){return $e.debug("checkAuth: not logged in -",s),{isAuthenticated:!1,error:s.message}}}async fetchSpCm(){try{if(this.runtime.getCookie){const r=await this.runtime.getCookie(".sohu.com","mp-cv");if(r){this.spCm=r,$e.debug("Got sp-cm from cookie:",this.spCm);return}}this.spCm=`100-${Date.now()}-${wt()}`,$e.debug("Generated sp-cm:",this.spCm)}catch{this.spCm=`100-${Date.now()}-${wt()}`,$e.debug("Fallback sp-cm:",this.spCm)}}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{if($e.info("Starting publish..."),!this.accountInfo&&!(await this.checkAuth()).isAuthenticated)throw new Error("请先登录搜狐号");let a=r.html||"";a=await this.processImages(a,h=>this.uploadImageByUrl(h),{skipPatterns:["sohu.com"],onProgress:i==null?void 0:i.onImageProgress});const n={title:r.title,brief:"",content:a,channelId:24,categoryId:-1,id:0,userColumnId:0,columnNewsIds:[],businessCode:0,declareOriginal:!1,cover:"",topicIds:[],isAd:0,userLabels:"[]",reprint:!1,customTags:"",infoResource:0,sourceUrl:"",visibleToLoginedUsers:0,attrIds:[],auto:!0,accountId:Number(this.accountInfo.id)},o=await(await this.runtime.fetch(`https://mp.sohu.com/mpbp/bp/news/v4/news/draft/v2?accountId=${this.accountInfo.id}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","dv-id":this.deviceId,"sp-cm":this.spCm},body:JSON.stringify(n)})).json();if($e.debug(" Save response:",o),!o.success)throw new Error(o.msg||"保存失败");const c=o.data,y=`https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=2&id=${c}`;return this.createResult(!0,{postId:String(c),postUrl:y,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}async uploadImageByUrl(r){if(!this.accountInfo)throw new Error("未登录");const i=await fetch(r);if(!i.ok)throw new Error("图片下载失败: "+r);const a=await i.blob(),n=new FormData;n.append("file",a,"image.jpg"),n.append("accountId",this.accountInfo.id);const o=await(await this.runtime.fetch("https://mp.sohu.com/commons/front/outerUpload/image/file?accountId="+this.accountInfo.id,{method:"POST",credentials:"include",body:n})).json();if($e.debug(" Image upload response:",o),!o.url)throw new Error("图片上传失败:"+o.msg);return{url:o.url}}}async function br(e,t,r,i){var y,h,w;if(t.type!=="video/mp4"||!Number.isSafeInteger(t.size)||t.size<1||t.size>512*1024*1024)throw new Error("知乎内嵌视频需要 512 MB 以内的 MP4 文件");const a=async(m,p)=>{const u=await e.fetch(m,{...p,redirect:"error"});if(!u.ok)throw new Error(`知乎视频请求失败(HTTP ${u.status})`);return u},n=pr.md5.create();for(let m=0;m<t.size;m+=1024*1024){const p=Math.min(1048576,t.size-m),u=await r(m,p);if(u.byteLength!==p)throw new Error("视频文件读取不完整");n.update(u),i(m+p,t.size)}const s=await(await a("https://lens.zhihu.com/api/v5/videos",{method:"POST",headers:{"Content-Type":"application/json","x-upload-content-length":String(t.size),"x-upload-content-type":t.type},body:JSON.stringify({file_md5:n.hex(),source:"article"})})).json(),o=(y=s.upload_file)==null?void 0:y.video_id;if(typeof o!="string"||!/^\d+$/.test(o))throw new Error("知乎没有返回有效的视频 ID");if(((h=s.upload_file)==null?void 0:h.state)===3){const m=s.upload_vendor,p=m==null?void 0:m.upload_token,u=s.upload_file.object_key;if((m==null?void 0:m.vendor_code)!=="ali"||m.endpoint!=="upload-oss.vzuu.com"||!u||!/^[A-Za-z0-9_./-]+$/.test(u)||!(p!=null&&p.access_id)||!p.access_key||!p.access_token)throw new Error("知乎视频上传凭证格式已变化,请检查最新上传流程");const g=`https://upload-oss.vzuu.com/${u.split("/").map(encodeURIComponent).join("/")}`,D=async(f,l,_,$="")=>{const x=new Date().toUTCString(),E={"x-oss-date":x,"x-oss-security-token":p.access_token,"x-oss-user-agent":"aliyun-sdk-js/6.8.0"},v=Object.keys(E).sort().map(I=>`${I}:${E[I]}`).join(`
2
- `),k=`/zhihu-video-input/${u}${l}`,O=await crypto.subtle.importKey("raw",new TextEncoder().encode(p.access_key),{name:"HMAC",hash:"SHA-1"},!1,["sign"]),z=new Uint8Array(await crypto.subtle.sign("HMAC",O,new TextEncoder().encode(`${f}
3
-
4
- ${$}
5
- ${x}
6
- ${v}
7
- ${k}`)));return E.Authorization=`OSS ${p.access_id}:${btoa(String.fromCharCode(...z))}`,$&&(E["Content-Type"]=$),a(g+l,{method:f,headers:E,..._===void 0?{}:{body:_}})},S=await(await D("POST","?uploads")).text(),b=(w=/<UploadId>([^<]+)<\/UploadId>/.exec(S))==null?void 0:w[1];if(!b||!/^[A-Za-z0-9_-]+$/.test(b))throw new Error("知乎没有返回有效的视频分片上传 ID");const d=f=>a(`https://lens.zhihu.com/api/v4/videos/${o}/uploading_status`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({object_key:u,upload_id:b,video_source:"origin",upload_event:f})});try{await d("UPLOADING_START");const f=[];for(let _=0,$=1;_<t.size;_+=1024*1024,$++){const x=await r(_,Math.min(1048576,t.size-_)),v=(await D("PUT",`?partNumber=${$}&uploadId=${b}`,new Blob([x]),"application/octet-stream")).headers.get("ETag");if(!v||!/^"?[A-Fa-f0-9-]+"?$/.test(v))throw new Error("知乎视频分片没有返回有效的 ETag");f.push(`<Part><PartNumber>${$}</PartNumber><ETag>${v}</ETag></Part>`),i(_+x.length,t.size)}await d("UPLOADING");const l=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${f.join("")}</CompleteMultipartUpload>`;await D("POST",`?uploadId=${b}`,l,"application/xml"),await d("UPLOADING_SUCCESS")}catch(f){throw await D("DELETE",`?uploadId=${b}`).catch(()=>{}),f}}const c=Date.now()+5*6e4;for(;Date.now()<c;){const p=await(await a(`https://lens.zhihu.com/api/v4/videos/${o}/default_cover`)).json();if(p.default_cover_url){const u=new URL(p.default_cover_url);if(u.protocol!=="https:"||!/(^|\.)zhimg\.com$/.test(u.hostname))throw new Error("知乎返回的视频封面地址无效");return await a(`https://lens.zhihu.com/api/v4/videos/${o}/default_cover`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cover_url:u.href})}),{videoId:o,cover:u.href}}await new Promise(u=>setTimeout(u,2e3))}throw new Error("知乎视频处理超时,文章尚未提交发布")}const ve=Be("Zhihu"),vr=fr;class Zt extends We{constructor(){super(...arguments);ae(this,"meta",{id:"zhihu",name:"知乎",icon:"https://static.zhihu.com/static/favicon.ico",homepage:"https://www.zhihu.com",capabilities:["article","draft","image_upload","tags","cover"]});ae(this,"preprocessConfig",{outputFormat:"html",removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,removeDataAttributes:!1,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0});ae(this,"HEADER_RULES",[{urlFilter:"*://www.zhihu.com/api/*",headers:{"x-requested-with":"fetch"},resourceTypes:["xmlhttprequest"]},{urlFilter:"*://zhuanlan.zhihu.com/api/*",headers:{"x-requested-with":"fetch"},resourceTypes:["xmlhttprequest"]},{urlFilter:"*://api.zhihu.com/*",headers:{"x-requested-with":"fetch"},resourceTypes:["xmlhttprequest"]}])}async uploadArticleVideo(r,i,a){return this.withHeaderRules([{urlFilter:"*://lens.zhihu.com/api/*",headers:{Origin:"https://zhuanlan.zhihu.com",Referer:"https://zhuanlan.zhihu.com/"},resourceTypes:["xmlhttprequest"]},{urlFilter:"*://upload-oss.vzuu.com/*",headers:{Origin:"https://zhuanlan.zhihu.com",Referer:"https://zhuanlan.zhihu.com/"},resourceTypes:["xmlhttprequest"]}],()=>br(this.runtime,r,i,a))}async checkAuth(){try{const i=await(await this.runtime.fetch("https://www.zhihu.com/api/v4/me",{method:"GET",credentials:"include",headers:{"x-requested-with":"fetch"}})).json();return i.id?{isAuthenticated:!0,userId:i.id,username:i.name,avatar:i.avatar_url}:{isAuthenticated:!1}}catch(r){return ve.debug("checkAuth: not logged in -",r),{isAuthenticated:!1,error:r.message}}}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{var p;ve.info("Starting publish...");const a=(p=(await this.runtime.cookies.get(".zhihu.com")).find(u=>u.name==="_xsrf"))==null?void 0:p.value,n={"Content-Type":"application/json","x-requested-with":"fetch",...a?{"x-xsrftoken":a}:{}},s=await this.runtime.fetch("https://zhuanlan.zhihu.com/api/articles/drafts",{method:"POST",credentials:"include",headers:n,body:JSON.stringify({title:r.title,content:"",delta_time:0})}),o=await s.text();if(ve.debug("Create draft response:",s.status,o.substring(0,200)),!s.ok)throw new Error(`创建草稿失败: ${s.status} - ${o}`);let c;try{c=JSON.parse(o)}catch{throw new Error(`创建草稿失败: 响应不是有效 JSON - ${o.substring(0,100)}`)}const y=typeof c.id=="string"?c.id:typeof c.id=="number"&&Number.isSafeInteger(c.id)?String(c.id):"";if(!/^\d+$/.test(y))throw new Error("创建草稿失败: 无效响应");ve.debug("Draft created:",y);let h=r.html||"";h=await this.processImages(h,u=>this.uploadImageByUrl(u),{skipPatterns:["zhimg.com","pic1.zhimg.com","pic2.zhimg.com","pic3.zhimg.com","pic4.zhimg.com"],onProgress:i==null?void 0:i.onImageProgress,failOnUploadError:!0}),h=this.transformContent(h);const w=await this.runtime.fetch(`https://zhuanlan.zhihu.com/api/articles/${y}/draft`,{method:"PATCH",credentials:"include",headers:n,body:JSON.stringify({title:r.title,content:h})});if(!w.ok){const u=await w.text();throw ve.error("Update draft failed:",w.status,u),new Error(`更新草稿失败: ${w.status}`)}ve.debug("Draft updated, status:",w.status);const m=`https://zhuanlan.zhihu.com/p/${y}/edit`;return this.createResult(!0,{postId:y,postUrl:m,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}transformContent(r){let i=r;return i=this.transformTables(i),i=i.replace(/<img([^>]+)src="([^"]+)"([^>]*)>/gi,'<figure><img$1src="$2"$3></figure>'),i=i.replace(/<pre><code class="language-(\w+)">/gi,'<pre lang="$1"><code>'),i=i.replace(/\s+(data-[a-z0-9-]+)="[^"]*"/gi,(a,n)=>/^data-(?:draft(?:-.*)?|lens-id|video-id|video-playable|poster|name|src)$/i.test(n)?a:""),i=i.replace(/\s*style="[^"]*"/gi,""),i}transformTables(r){let i=r.replace(/<figure[^>]*>\s*(<table[\s\S]*?<\/table>)\s*<\/figure>/gi,"$1");return i=i.replace(/<table[^>]*>([\s\S]*?)<\/table>/gi,(a,n)=>{const s=n.match(/<thead[^>]*>([\s\S]*?)<\/thead>/i),o=n.match(/<tbody[^>]*>([\s\S]*?)<\/tbody>/i);let c="",y="";if(s&&(c=s[1].replace(/<td([^>]*)>/gi,"<th$1>").replace(/<\/td>/gi,"</th>")),o?y=o[1]:y=n.replace(/<thead[^>]*>[\s\S]*?<\/thead>/gi,"").replace(/<\/?tbody[^>]*>/gi,""),!s){const h=y.match(/<tr[^>]*>([\s\S]*?)<\/tr>/i);if(h){const w=h[1];/<th[^>]*>/i.test(w)&&!/<td[^>]*>/i.test(w)&&(c=h[0],y=y.replace(h[0],""))}}return`<table data-draft-node="block" data-draft-type="table" data-size="normal" data-row-style="normal"><tbody>${c}${y}</tbody></table>`}),i}async uploadImage(r,i){return this.uploadImageBinaryInternal(r)}async uploadImageByUrl(r){if(r.startsWith("data:")){ve.debug("Detected data URI, using binary upload");const n=await fetch(r).then(o=>o.blob());return{url:await this.uploadImageBinaryInternal(n)}}const a=await(await this.runtime.fetch("https://zhuanlan.zhihu.com/api/uploaded_images",{method:"POST",credentials:"include",headers:{"x-requested-with":"fetch","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({url:r,source:"article"})})).json();if(a.src)return{url:a.src};throw new Error("图片上传失败")}async uploadImageBinaryInternal(r){const i=await r.arrayBuffer(),a=vr(i),s=await(await this.runtime.fetch("https://api.zhihu.com/images",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({image_hash:a,source:"article"})})).json(),o=s.upload_file;if(o.state===1)return`https://pic4.zhimg.com/${(await this.waitForImageReady(o.image_id)).original_hash}`;const c=s.upload_token;await this.ossUpload("https://zhihu-pics-upload.zhimg.com",o.object_key,r,c);let y=o.object_key;return r.type==="image/gif"&&(y=y+".gif"),`https://pic4.zhimg.com/${y}`}async waitForImageReady(r){for(let a=0;a<10;a++){const s=await(await this.runtime.fetch(`https://api.zhihu.com/images/${r}`,{credentials:"include"})).json();if(s.status==="completed"||s.original_hash)return s;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Image processing timeout")}async ossUpload(r,i,a,n){const s=a.type||"application/octet-stream",o=`${r}/${i}`,c=new Date().toUTCString(),h={"x-oss-date":c,"x-oss-security-token":n.access_token,"x-oss-user-agent":"aliyun-sdk-js/6.8.0"},w=Object.keys(h).sort().map(b=>`${b}:${h[b]}`).join(`
8
- `),p=`/zhihu-pics/${i}`,u=`PUT
9
-
10
- `+s+`
11
- `+c+`
12
- `+w+`
13
- `+p,g=await this.hmacSha1Base64(n.access_key,u),D=`OSS ${n.access_id}:${g}`;ve.debug("OSS stringToSign:",JSON.stringify(u)),ve.debug("OSS authorization:",D);let S;try{this.runtime.headerRules&&(S=await this.runtime.headerRules.add({urlFilter:"*://zhihu-pics-upload.zhimg.com/*",headers:{Origin:"https://zhuanlan.zhihu.com",Referer:"https://zhuanlan.zhihu.com/"},resourceTypes:["xmlhttprequest"]}),ve.debug("Added header rule for OSS upload:",S));const b=await this.runtime.fetch(o,{method:"PUT",headers:{"Content-Type":s,Authorization:D,"x-oss-date":c,"x-oss-security-token":n.access_token,"x-oss-user-agent":"aliyun-sdk-js/6.8.0"},body:a});if(!b.ok){const d=await b.text();throw ve.error("OSS upload failed:",b.status,d),new Error(`OSS upload failed: ${b.status}`)}ve.debug("OSS upload success")}finally{S&&this.runtime.headerRules&&(await this.runtime.headerRules.remove(S),ve.debug("Removed header rule:",S))}}async hmacSha1Base64(r,i){const a=new TextEncoder,n=a.encode(r),s=a.encode(i),o=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),c=await crypto.subtle.sign("HMAC",o,s);return btoa(String.fromCharCode(...new Uint8Array(c)))}}const ye=Be("Weibo");class _r extends We{constructor(){super(...arguments);ae(this,"meta",{id:"weibo",name:"微博长文章",icon:"https://weibo.com/favicon.ico",homepage:"https://card.weibo.com/article/v5/editor",capabilities:["article","draft","image_upload","cover"]});ae(this,"preprocessConfig",{outputFormat:"html"});ae(this,"userConfig",null);ae(this,"HEADER_RULES",[{urlFilter:"*://card.weibo.com/*",headers:{Origin:"https://card.weibo.com",Referer:"https://card.weibo.com/article/v5/editor"},resourceTypes:["xmlhttprequest"]},{urlFilter:"*://picupload.weibo.com/*",headers:{Origin:"https://weibo.com",Referer:"https://weibo.com/"},resourceTypes:["xmlhttprequest"]}])}async checkAuth(){try{const r=await this.getUserConfig();return r!=null&&r.uid?{isAuthenticated:!0,userId:r.uid,username:r.nick,avatar:r.avatar_large}:{isAuthenticated:!1}}catch(r){return ye.debug("checkAuth: not logged in -",r),{isAuthenticated:!1,error:r.message}}}async getUserConfig(){if(this.userConfig)return this.userConfig;const a=(await(await this.runtime.fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text()).match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!a)return ye.error("Failed to find config in HTML"),null;try{const n=a[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"),s=JSON.parse(n);return s.uid?(this.userConfig={uid:String(s.uid),nick:s.nick||"",avatar_large:s.avatar_large||""},ye.debug("User config:",this.userConfig),this.userConfig):null}catch(n){return ye.error("Failed to parse config:",n),null}}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{var D,S;ye.info("Starting publish...");const a=await this.getUserConfig();if(!(a!=null&&a.uid))throw new Error("请先登录微博");let n=r.html||"";n=n.replace(/>\s+</g,"><"),n=await this.processWeiboImages(n,i==null?void 0:i.onImageProgress);let s="";if(r.cover?s=(await this.uploadImageByUrl(r.cover)).url:s=((D=/<img[^>]+src="([^"]+)"/i.exec(n))==null?void 0:D[1])||"",!s)throw new Error("微博长文章请提供封面 cover 或至少一张正文图片,避免平台自动使用上一篇文章的封面");const o=this.generateReqId(),y=await(await this.runtime.fetch(`https://card.weibo.com/article/v5/aj/editor/draft/create?uid=${a.uid}&_rid=${o}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":o},body:new URLSearchParams({})})).json();if(y.code!==1e5||!((S=y.data)!=null&&S.id))throw new Error(y.msg||"创建草稿失败");const h=y.data.id;ye.debug("Created draft:",h);const w=this.generateReqId(),p=await(await this.runtime.fetch(`https://card.weibo.com/article/v5/aj/editor/draft/save?uid=${a.uid}&id=${h}&_rid=${w}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":w},body:new URLSearchParams({id:h,title:r.title,subtitle:"",type:"",status:"0",publish_at:"",error_msg:"",error_code:"0",collection:"[]",free_content:"",content:n,cover:s,summary:"",writer:"",extra:"null",is_word:"0",article_recommend:"[]",follow_to_read:"0",isreward:"1",pay_setting:'{"ispay":0,"isvclub":0}',source:"0",action:"0",is_markdown:"0",is_v4:"1",ver:"4.0",content_type:"0",save:"1"})})).json();ye.debug("Save response:",p);const u=String(p.code);if(u!=="100000")throw new Error(p.msg||`保存失败 (错误码: ${u})`);const g=`https://card.weibo.com/article/v5/editor#/draft/${h}`;return this.createResult(!0,{postId:h,postUrl:g,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}generateReqId(){var s;const r=`${(s=this.userConfig)==null?void 0:s.uid}&${Date.now()}`,i=btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let n=i;for(;n.length<43;)n+=a.charAt(Math.floor(Math.random()*a.length));return n.slice(0,43)}async uploadImageByUrl(r){if(r.startsWith("data:"))return ye.debug("Uploading data URI image via direct upload"),this.uploadDataUri(r);const i=await this.getUserConfig();if(!(i!=null&&i.uid))throw new Error("请先登录微博");const a=this.generateReqId();try{const c=await(await this.runtime.fetch(`https://card.weibo.com/article/v5/aj/editor/plugins/asyncuploadimg?uid=${i.uid}&_rid=${a}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":a},body:new URLSearchParams({"urls[0]":r})})).json();ye.debug("Async upload response:",c)}catch(o){ye.warn("Async upload request failed, will try polling anyway:",o)}const n=await this.waitForImageDone(r);return{url:`https://wx3.sinaimg.cn/large/${n.pid}.jpg`,attrs:{"data-pid":n.pid}}}async uploadImageBase64(r,i){const a=`data:${i};base64,${r}`;return this.uploadDataUri(a)}async uploadDataUri(r){var d,f,l;const i=r.match(/^data:([^;]+);base64,(.+)$/);if(!i)throw new Error("Invalid data URI format");const a=i[1],n=i[2],s=atob(n),o=new Uint8Array(s.length);for(let _=0;_<s.length;_++)o[_]=s.charCodeAt(_);const c=new Blob([o],{type:a});ye.debug(`Uploading blob: ${a}, size: ${c.size}`);const h=`https://picupload.weibo.com/interface/pic_upload.php?app=miniblog&s=json&p=1&data=1&url=&markpos=1&logo=0&nick=&file_source=4&_rid=${this.generateReqId()}`,m=await(await this.runtime.fetch(h,{method:"POST",credentials:"include",body:c})).json();if(ye.debug("Direct upload response:",m),!((l=(f=(d=m.data)==null?void 0:d.pics)==null?void 0:f.pic_1)!=null&&l.pid))throw new Error("图片上传失败: "+JSON.stringify(m));const p=m.data.pics.pic_1.pid,u=await this.getUserConfig();if(!(u!=null&&u.uid))throw new Error("请先登录微博");const g=this.generateReqId(),D=await this.runtime.fetch(`https://card.weibo.com/article/v5/aj/editor/plugins/uploadpic?_rid=${g}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded","SN-REQID":g},body:new URLSearchParams({pid:p,uid:u.uid})}),S=await D.json();if(!D.ok||S.code!==1e5)throw new Error(S.msg||"图片未能登记到微博长文章素材库,已停止投稿");return{url:`https://wx3.sinaimg.cn/large/${p}.jpg`,attrs:{"data-pid":p}}}async processWeiboImages(r,i){var p;const a=r,n=/<figure[^>]*>[\s\S]*?<img[^>]+src="([^"]+)"[^>]*>[\s\S]*?<\/figure>/gi,s=/<img[^>]+src="([^"]+)"[^>]*>/gi,o=[];let c;const y=new Set;for(;(c=n.exec(a))!==null;)o.push({full:c[0],src:c[1],hasFigure:!0}),y.add(c[1]);for(;(c=s.exec(a))!==null;)y.has(c[1])||o.push({full:c[0],src:c[1],hasFigure:!1});for(const u of Xt(a))o.push({full:u.full,src:u.src,hasFigure:!1});if(o.length===0)return a;ye.info(`Found ${o.length} images to process`);let h=a;const w=new Map;let m=0;for(const{full:u,src:g,hasFigure:D}of o)if(g){if(g.includes("sinaimg.cn")||g.includes("weibo.com")){ye.debug(`Skipping weibo image: ${g}`);continue}m++,i==null||i(m,o.length);try{let S=w.get(g);if(!S){ye.debug(`Uploading image ${m}/${o.length}: ${g}`);const d=await this.uploadImageByUrl(g);S={pid:((p=d.attrs)==null?void 0:p["data-pid"])||"",url:d.url},w.set(g,S)}let b;D?b=u.replace(/<img[^>]+src="[^"]+"[^>]*>/i,`<img src="${S.url}" data-pid="${S.pid}" />`):b=`<figure class="image"><img src="${S.url}" data-pid="${S.pid}" /></figure>`,h=h.replace(u,b),ye.debug(`Image uploaded: ${S.url}`)}catch(S){throw new Error(`微博文章图片上传失败,已停止投稿:${S instanceof Error?S.message:"图片接口异常"}`)}await this.delay(300)}return h}async waitForImageDone(r){var n;const i=await this.getUserConfig(),a=30;for(let s=0;s<a;s++){const o=this.generateReqId(),h=(n=(await(await this.runtime.fetch(`https://card.weibo.com/article/v5/aj/editor/plugins/asyncimginfo?uid=${i.uid}&_rid=${o}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":o},body:new URLSearchParams({"urls[0]":r})})).json()).data)==null?void 0:n[0],w=h==null?void 0:h.task_status_code;if(w===1&&h)return ye.debug("Image upload complete:",h),h;if(w===2)throw new Error("图片上传失败");await this.delay(1e3)}throw new Error("图片上传超时")}}const Te=Be("Bilibili");class Er extends We{constructor(){super(...arguments);ae(this,"meta",{id:"bilibili",name:"B站专栏",icon:"https://www.bilibili.com/favicon.ico",homepage:"https://member.bilibili.com/platform/upload/text",capabilities:["article","draft","image_upload"]});ae(this,"preprocessConfig",{outputFormat:"html",removeLinks:!0});ae(this,"userInfo",null);ae(this,"csrf","");ae(this,"HEADER_RULES",[{urlFilter:"*://api.bilibili.com/*",headers:{Origin:"https://member.bilibili.com",Referer:"https://member.bilibili.com/"},resourceTypes:["xmlhttprequest"]}])}async checkAuth(){var r;try{const i=await this.get("https://api.bilibili.com/x/web-interface/nav?build=0&mobi_app=web");return Te.debug("checkAuth response:",i),i.code===0&&((r=i.data)!=null&&r.isLogin)?(this.userInfo=i.data,await this.fetchCsrf(),{isAuthenticated:!0,userId:String(i.data.mid),username:i.data.uname,avatar:i.data.face}):{isAuthenticated:!1}}catch(i){return Te.debug("checkAuth: not logged in -",i),{isAuthenticated:!1,error:i.message}}}async fetchCsrf(){try{if(this.runtime.getCookie){const r=await this.runtime.getCookie(".bilibili.com","bili_jct");this.csrf=r||""}Te.debug("CSRF token:",this.csrf?"obtained":"not found")}catch(r){Te.error("Failed to get CSRF:",r)}}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{var o;if(Te.info("Starting publish..."),!this.userInfo&&!(await this.checkAuth()).isAuthenticated)throw new Error("请先登录B站");if(!this.csrf)throw new Error("获取 CSRF token 失败,请刷新页面后重试");let a=r.html||"";a=await this.processImages(a,c=>this.uploadImageByUrl(c),{skipPatterns:["hdslb.com","bilibili.com","biliimg.com"],onProgress:i==null?void 0:i.onImageProgress}),a=a.replace(/<img[^>]+src=(?:"([^"]*)"|'([^']*)'|((?:https?:)?\/\/[^\s>"']+|data:[^\s>"']+))[^>]*>/gi,(c,y,h,w)=>{const m=y||h||w||"";return m.includes("hdslb.com")||m.includes("bilibili.com")||m.includes("biliimg.com")?c:""});const n=await this.postForm("https://api.bilibili.com/x/article/creative/draft/addupdate",{tid:"4",title:r.title,content:a,csrf:this.csrf,save:"0",pgc_id:"0"});if(Te.debug("Draft response:",n),n.code!==0||!((o=n.data)!=null&&o.aid)){Te.error("draft save failed",{code:n.code,message:n.message,contentLength:a.length});const c=n.message||JSON.stringify(n).slice(0,200);throw new Error(`保存草稿失败 (code=${n.code}, 内容长度=${a.length}): ${c}`)}const s=`https://member.bilibili.com/platform/upload/text/edit?aid=${n.data.aid}`;return this.createResult(!0,{postId:String(n.data.aid),postUrl:s,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}async uploadImageByUrl(r){var y;if(!this.csrf)throw new Error("CSRF token 未获取");const i=await fetch(r);if(!i.ok)throw new Error("图片下载失败: "+r);const a=await i.blob(),n=new FormData;n.append("binary",a,"image.jpg"),n.append("csrf",this.csrf);const c=await(await this.runtime.fetch("https://api.bilibili.com/x/article/creative/article/upcover",{method:"POST",credentials:"include",body:n})).json();if(Te.debug("Image upload response:",c),c.code!==0||!((y=c.data)!=null&&y.url))throw Te.error("image upload failed",{code:c.code,message:c.message,src:r.slice(0,100)}),new Error(`图片上传失败 (code=${c.code}): ${c.message||JSON.stringify(c).slice(0,200)}`);return{url:c.data.url,attrs:{size:String(c.data.size)}}}}const Ne=Be("Baijiahao");class Sr extends We{constructor(){super(...arguments);ae(this,"meta",{id:"baijiahao",name:"百家号",icon:"https://www.baidu.com/favicon.ico",homepage:"https://baijiahao.baidu.com/",capabilities:["article","draft","image_upload","cover"]});ae(this,"preprocessConfig",{outputFormat:"html"});ae(this,"userInfo",null);ae(this,"authToken","");ae(this,"HEADER_RULES",[{urlFilter:"*://baijiahao.baidu.com/*",headers:{Origin:"https://baijiahao.baidu.com",Referer:"https://baijiahao.baidu.com/"},resourceTypes:["xmlhttprequest"]}])}async checkAuth(){var r;try{const i=await this.get(`https://baijiahao.baidu.com/builder/app/appinfo?_=${Date.now()}`);return Ne.debug("checkAuth response:",i),i.errmsg==="success"&&((r=i.data)!=null&&r.user)?(this.userInfo=i.data.user,{isAuthenticated:!0,userId:i.data.user.userid,username:i.data.user.name,avatar:i.data.user.avatar}):{isAuthenticated:!1}}catch(i){return Ne.debug("checkAuth: not logged in -",i),{isAuthenticated:!1,error:i.message}}}async fetchAuthToken(){const a=(await(await this.runtime.fetch("https://baijiahao.baidu.com/builder/rc/edit",{credentials:"include"})).text()).match(/window\.__BJH__INIT__AUTH__\s*=\s*['"]([^'"]+)['"]/);if(!a)throw new Error("登录失效,请重新登录百家号");const n=a[1];return Ne.debug("Auth token obtained"),n}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{var p;if(Ne.info("Starting publish..."),!this.userInfo&&!(await this.checkAuth()).isAuthenticated)throw new Error("请先登录百家号");this.authToken=await this.fetchAuthToken();let a=r.html||"";a=await this.processImages(a,u=>this.uploadImageByUrl(u),{skipPatterns:["baijiahao.baidu.com","bdstatic.com","bcebos.com"],onProgress:i==null?void 0:i.onImageProgress});const n=r.cover?await this.uploadImageByUrl(r.cover):void 0,s=n?{cover_layout:"one",cover_images:JSON.stringify([{src:n.url,cropData:{},machine_chooseimg:0,isLegal:0,cover_source_tag:"local"}]),_cover_images_map:JSON.stringify([{src:n.url,origin_src:n.url}]),source:"upload",cover_source:"upload"}:{},y=(await(await this.runtime.fetch("https://baijiahao.baidu.com/pcui/article/save?callback=bjhdraft",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",token:this.authToken},body:new URLSearchParams({title:r.title,content:a,feed_cat:"1",len:String(a.length),activity_list:JSON.stringify([{id:408,is_checked:0}]),source_reprinted_allow:"0",original_status:"0",original_handler_status:"1",isBeautify:"false",subtitle:"",bjhtopic_id:"",bjhtopic_info:"",type:"news",...s})})).text()).replace(/^bjhdraft\(/,"").replace(/\)$/,""),h=JSON.parse(y);if(Ne.debug("Save response:",h),h.errmsg!=="success"||!((p=h.ret)!=null&&p.article_id))throw new Error(h.errmsg||"保存草稿失败");const w=h.ret.article_id,m=`https://baijiahao.baidu.com/builder/rc/edit?type=news&article_id=${w}`;return this.createResult(!0,{postId:w,postUrl:m,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}async uploadImageByUrl(r){var y;const i=await fetch(r);if(!i.ok)throw new Error("图片下载失败: "+r);const a=await i.blob(),n=new FormData;n.append("media",a,"image.jpg"),n.append("org_file_name","image.jpg"),n.append("type","image"),n.append("app_id","1589639493090963"),n.append("is_waterlog","1"),n.append("save_material","1"),n.append("no_compress","0"),n.append("is_events",""),n.append("article_type","news");const c=await(await this.runtime.fetch("https://baijiahao.baidu.com/materialui/picture/uploadProxy",{method:"POST",credentials:"include",headers:{token:this.authToken,"X-Requested-With":"XMLHttpRequest"},body:n})).json();if(Ne.debug("Image upload response:",c),c.errmsg!=="success"||!((y=c.ret)!=null&&y.https_url))throw new Error(c.errmsg||"图片上传失败");return{url:c.ret.https_url}}}const Oe=Be("Weixin"),Ar=`
14
- p {
15
- color: rgb(51, 51, 51);
16
- font-size: 15px;
17
- line-height: 1.75em;
18
- margin: 0 0 1em 0;
19
- }
20
- h1, h2, h3, h4, h5, h6 {
21
- font-weight: bold;
22
- }
23
- h1 { font-size: 1.25em; line-height: 1.4em; margin: 1em 0 0.5em 0; }
24
- h2 { font-size: 1.125em; margin: 1em 0 0.5em 0; }
25
- h3 { font-size: 1.05em; margin: 0.8em 0 0.4em 0; }
26
- h4, h5, h6 { font-size: 1em; margin: 0.8em 0 0.4em 0; }
27
- li p { margin: 0; }
28
- ul, ol { margin: 1em 0; padding-left: 2em; }
29
- li { margin-bottom: 0.4em; }
30
- pre, tt, code, kbd, samp { font-family: monospace; }
31
- pre { white-space: pre; margin: 1em 0; }
32
- blockquote { border-left: 4px solid #ddd; padding-left: 1em; margin: 1em 0; color: #666; }
33
- hr { border: none; border-top: 1px solid #ddd; margin: 1.5em 0; }
34
- i, cite, em, var, address { font-style: italic; }
35
- b, strong { font-weight: bolder; }
36
- `;class Ir extends We{constructor(){super(...arguments);ae(this,"meta",{id:"weixin",name:"微信公众号",icon:"https://mp.weixin.qq.com/favicon.ico",homepage:"https://mp.weixin.qq.com",capabilities:["article","draft","image_upload"]});ae(this,"preprocessConfig",{outputFormat:"html",removeLinks:!0,keepLinkDomains:["mp.weixin.qq.com","weixin.qq.com"],compactHtml:!0});ae(this,"weixinMeta",null);ae(this,"HEADER_RULES",[{urlFilter:"*://mp.weixin.qq.com/cgi-bin/*",headers:{Origin:"https://mp.weixin.qq.com",Referer:"https://mp.weixin.qq.com/"},resourceTypes:["xmlhttprequest"]}])}async checkAuth(){try{const i=await(await this.runtime.fetch("https://mp.weixin.qq.com/",{method:"GET",credentials:"include"})).text(),a=i.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/);if(!a)return Oe.debug(" No token found"),{isAuthenticated:!1};const n=i.match(/ticket:\s*["']([^"']+)["']/),s=i.match(/user_name:\s*["']([^"']+)["']/),o=i.match(/nick_name:\s*["']([^"']+)["']/),c=i.match(/time:\s*["'](\d+)["']/),y=i.match(/head_img:\s*['"]([^'"]+)['"]/),h=i.match(/class="weui-desktop-account__thumb"[^>]*src="([^"]+)"/);let w=h?h[1]:y?y[1]:"";return w.startsWith("http://")&&(w=w.replace("http://","https://")),this.weixinMeta={token:a[1],userName:s?s[1]:"",nickName:o?o[1]:"",ticket:n?n[1]:"",svrTime:c?Number(c[1]):Date.now()/1e3,avatar:w},Oe.debug(" Auth info:",{userName:this.weixinMeta.userName,nickName:this.weixinMeta.nickName,hasToken:!!this.weixinMeta.token}),{isAuthenticated:!0,userId:this.weixinMeta.userName,username:this.weixinMeta.nickName,avatar:this.weixinMeta.avatar}}catch(r){return Oe.debug("checkAuth: not logged in -",r),{isAuthenticated:!1,error:r.message}}}async publish(r,i){return this.withHeaderRules(this.HEADER_RULES,async()=>{var y,h;if(Oe.info("Starting publish..."),!this.weixinMeta&&!(await this.checkAuth()).isAuthenticated)throw new Error("请先登录微信公众号");let a=((y=r.source)==null?void 0:y.platform)==="weixin"&&r.rawHtml?r.rawHtml:r.html||"";((h=r.source)==null?void 0:h.platform)==="weixin"?Oe.info("Source is WeChat, using raw HTML, skipping content processing"):(a=this.processLatex(a),a=this.stripExternalLinks(a),a=await this.processImages(a,w=>this.uploadImageByUrl(w),{skipPatterns:["mmbiz.qpic.cn","mmbiz.qlogo.cn"],onProgress:i==null?void 0:i.onImageProgress}),a=this.processContent(a));const n=new URLSearchParams({token:this.weixinMeta.token,lang:"zh_CN",f:"json",ajax:"1",random:String(Math.random()),AppMsgId:"",count:"1",data_seq:"0",operate_from:"Chrome",isnew:"0",ad_video_transition0:"",can_reward0:"0",related_video0:"",is_video_recommend0:"-1",title0:r.title,author0:"",writerid0:"0",fileid0:"",digest0:"",auto_gen_digest0:"1",content0:a,sourceurl0:"",need_open_comment0:"1",only_fans_can_comment0:"0",cdn_url0:"",cdn_235_1_url0:"",cdn_1_1_url0:"",cdn_url_back0:"",crop_list0:"",music_id0:"",video_id0:"",voteid0:"",voteismlt0:"",supervoteid0:"",cardid0:"",cardquantity0:"",cardlimit0:"",vid_type0:"",show_cover_pic0:"0",shortvideofileid0:"",copyright_type0:"0",releasefirst0:"",platform0:"",reprint_permit_type0:"",allow_reprint0:"",allow_reprint_modify0:"",original_article_type0:"",ori_white_list0:"",free_content0:"",fee0:"0",ad_id0:"",guide_words0:"",is_share_copyright0:"0",share_copyright_url0:"",source_article_type0:"",reprint_recommend_title0:"",reprint_recommend_content0:"",share_page_type0:"0",share_imageinfo0:'{"list":[]}',share_video_id0:"",dot0:"{}",share_voice_id0:"",insert_ad_mode0:"",categories_list0:"[]"}),o=await(await this.runtime.fetch(`https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=77&token=${this.weixinMeta.token}&lang=zh_CN`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})).json();if(Oe.debug(" Save response:",o),!o.appMsgId){const w=this.formatError(o);throw new Error(w)}const c=`https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=77&appmsgid=${o.appMsgId}&token=${this.weixinMeta.token}&lang=zh_CN`;return this.createResult(!0,{postId:o.appMsgId,postUrl:c,draftOnly:(i==null?void 0:i.draftOnly)??!0})}).catch(a=>this.createResult(!1,{error:a.message}))}async uploadImageByUrl(r){var g;if(!this.weixinMeta)throw new Error("未登录");const i=await fetch(r);if(!i.ok)throw new Error("图片下载失败: "+r);const a=await i.blob(),n=new FormData,s=Date.now(),o=`${s}.jpg`;n.append("type",a.type||"image/jpeg"),n.append("id",String(s)),n.append("name",o),n.append("lastModifiedDate",new Date().toString()),n.append("size",String(a.size)),n.append("file",a,o);const{token:c,userName:y,ticket:h,svrTime:w}=this.weixinMeta,m=Date.now(),u=await(await this.runtime.fetch(`https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&scene=8&writetype=doublewrite&groupid=1&ticket_id=${y}&ticket=${h}&svr_time=${w}&token=${c}&lang=zh_CN&seq=${m}&t=${Math.random()}`,{method:"POST",credentials:"include",body:n})).json();if(Oe.debug(" Image upload response:",u),((g=u.base_resp)==null?void 0:g.err_msg)!=="ok"||!u.cdn_url)throw new Error("图片上传失败: "+r);return{url:u.cdn_url}}isLatexFormula(r){return!!(/[\\^_{}]/.test(r)||/[α-ωΑ-Ω]/.test(r)||/[∑∏∫∂∇∞≠≤≥±×÷√]/.test(r))}processLatex(r){const i="https://latex.codecogs.com/png.latex";return r=r.replace(/\$\$([^$]+)\$\$/g,(a,n)=>{if(!this.isLatexFormula(n))return a;const s=encodeURIComponent(n.trim());return`<p style="text-align: center;"><img src="${i}?\\dpi{150}${s}" alt="formula" style="vertical-align: middle; max-width: 100%;"></p>`}),r=r.replace(/\$([^$]+)\$/g,(a,n)=>{if(!this.isLatexFormula(n))return a;const s=encodeURIComponent(n.trim());return`<img src="${i}?\\dpi{120}${s}" alt="formula" style="vertical-align: middle;">`}),r}processContent(r){const i=`<section style="margin-left: 6px; margin-right: 6px; line-height: 1.75em;">${r}</section>`;return mr.inlineContent(i,Ar)}stripExternalLinks(r){return r.replace(/<a\s+[^>]*href=["']([^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi,(i,a,n)=>a&&(a.includes("mp.weixin.qq.com")||a.includes("weixin.qq.com")||a.startsWith("#")||a.startsWith("javascript:"))?i:n)}formatError(r){var n;const i=r.ret??((n=r.base_resp)==null?void 0:n.ret);return{[-6]:"请输入验证码",[-8]:"请输入验证码",[-1]:"系统错误,请注意备份内容后重试",[-2]:"参数错误,请注意备份内容后重试",[-5]:"服务错误,请注意备份内容后重试",[-99]:"内容超出字数,请调整",[-206]:"服务负荷过大,请稍后重试",200002:"参数错误,请注意备份内容后重试",200003:"登录态超时,请重新登录",412:"图文中含非法外链",62752:"可能含有具备安全风险的链接,请检查",64502:"你输入的微信号不存在",64505:"发送预览失败,请稍后再试",64506:"保存失败,链接不合法",64507:"内容不能包含外部链接",64562:"请勿插入非微信域名的链接",64509:"正文中不能包含超过3个视频",64515:"当前素材非最新内容,请重新打开并编辑",64702:"标题超出64字长度限制",64703:"摘要超出120字长度限制",64705:"内容超出字数,请调整",10806:"正文不能有违规内容,请重新编辑",10807:"内容不能违反公众平台协议",220001:"素材管理中的存储数量已达上限",220002:"图片库已达到存储上限"}[i]||`同步失败 (错误码: ${i})`}}const xr=30*1e3;class Rr{constructor(t){ae(this,"type","extension");ae(this,"ruleIdBase",Date.now()%1e5);ae(this,"ruleIdCounter",0);ae(this,"cookies",{async get(t){return(await chrome.cookies.getAll({domain:t})).map(i=>({name:i.name,value:i.value,domain:i.domain,path:i.path,secure:i.secure,httpOnly:i.httpOnly,expirationDate:i.expirationDate}))},async set(t){await chrome.cookies.set({url:`https://${t.domain}${t.path||"/"}`,name:t.name,value:t.value,domain:t.domain,path:t.path,secure:t.secure,httpOnly:t.httpOnly,expirationDate:t.expirationDate})},async remove(t,r){await chrome.cookies.remove({url:`https://${r}`,name:t})}});ae(this,"storage",{async get(t){return(await chrome.storage.local.get(t))[t]??null},async set(t,r){await chrome.storage.local.set({[t]:r})},async remove(t){await chrome.storage.local.remove(t)}});ae(this,"session",{async get(t){return(await chrome.storage.session.get(t))[t]??null},async set(t,r){await chrome.storage.session.set({[t]:r})}});ae(this,"headerRules",{add:async t=>{const r=this.ruleIdBase+this.ruleIdCounter++,i=`rule_${r}`;return await chrome.declarativeNetRequest.updateDynamicRules({addRules:[{id:r,priority:1,action:{type:chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,requestHeaders:Object.entries(t.headers).map(([a,n])=>({header:a,operation:chrome.declarativeNetRequest.HeaderOperation.SET,value:n}))},condition:{urlFilter:t.urlFilter,initiatorDomains:[chrome.runtime.id],resourceTypes:t.resourceTypes||["xmlhttprequest"]}}]}),i},remove:async t=>{const r=parseInt(t.replace("rule_",""),10);await chrome.declarativeNetRequest.updateDynamicRules({removeRuleIds:[r]})},clear:async()=>{const t=await chrome.declarativeNetRequest.getDynamicRules();await chrome.declarativeNetRequest.updateDynamicRules({removeRuleIds:t.map(r=>r.id)})}});ae(this,"downloads",{async download(t,r,i=!0){const a=await t.arrayBuffer(),n=btoa(new Uint8Array(a).reduce((y,h)=>y+String.fromCharCode(h),"")),o=`data:${t.type||"application/octet-stream"};base64,${n}`;return await chrome.downloads.download({url:o,filename:r,saveAs:i})}});ae(this,"tabs",{async query(t){return(await chrome.tabs.query({url:t})).filter(i=>i.id!==void 0).map(i=>({id:i.id,url:i.url}))},async create(t,r=!1){return{id:(await chrome.tabs.create({url:t,active:r})).id}},async waitForLoad(t,r=3e4){return new Promise((i,a)=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(s),a(new Error("Tab load timeout"))},r),s=(o,c)=>{o===t&&c.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(s),setTimeout(i,1e3))};chrome.tabs.onUpdated.addListener(s)})},async executeScript(t,r,i){var s;return(s=(await chrome.scripting.executeScript({target:{tabId:t},world:"MAIN",func:r,args:i}))[0])==null?void 0:s.result}});ae(this,"dom",{parseHTML:async t=>new DOMParser().parseFromString(t,"text/html"),querySelector:(t,r)=>t.querySelector(r),querySelectorAll:(t,r)=>Array.from(t.querySelectorAll(r)),getTextContent:t=>t.textContent||"",getInnerHTML:t=>t.innerHTML});this.config=t}async fetch(t,r){var s;const i=((s=this.config)==null?void 0:s.timeout)??xr,a=new AbortController,n=setTimeout(()=>a.abort(),i);try{return await fetch(t,{...r,credentials:"include",signal:a.signal})}catch(o){throw o.name==="AbortError"?new Error(`请求超时(${i/1e3}秒): ${t}`):o}finally{clearTimeout(n)}}async getCookie(t,r){const i=await chrome.cookies.getAll({domain:t,name:r});return i.length>0?i[0].value:null}}function kr(e){return new Rr(e)}const Kt=[{id:"xiaohongshu",name:"小红书",icon:"https://www.xiaohongshu.com/favicon.ico",homepage:"https://creator.xiaohongshu.com",capabilities:["article","video","image_upload","cover","tags","publish"],publishModes:["article","image","video"],tools:{article:"publish_article",image:"publish_post",video:"publish_post"},modeOptions:{article:{titleMaxLength:64,contentMaxLength:1e4,inlineImages:!0,embeddedVideo:!1,cover:!1,tags:!1,automaticLayout:!0},image:{cover:"first_image",tags:!0,limits:"native_page"},video:{cover:"optional",defaultCover:"first_frame",tags:!0,limits:"native_page"}},delivery:"page",action:"publish"},{id:"douyin",name:"抖音",icon:"https://creator.douyin.com/favicon.ico",homepage:"https://creator.douyin.com",capabilities:["article","video","image_upload","cover","tags","publish"],publishModes:["image","video"],tools:{image:"publish_post",video:"publish_post"},modeOptions:{image:{maxTags:4,cover:"first_image",limits:"native_page",scheduledPublish:!1},video:{maxTags:5,cover:"optional",defaultCover:"native_page",limits:"native_page",scheduledPublish:!1}},confirmation:"native_page_message",delivery:"page",action:"publish"}],ut=e=>Kt.some(t=>t.id===e),At=e=>e==="weibo"||ut(e);async function $r(e){var t,r,i;try{if(e==="douyin"){const c=await fetch("https://creator.douyin.com/web/api/media/user/info/",{credentials:"include",headers:{Accept:"application/json"}});if(!c.ok)throw new Error(`抖音账号检测失败 (${c.status})`);const y=await c.json();return(t=y.user)!=null&&t.sec_uid?{isAuthenticated:!0,userId:y.user.sec_uid,username:y.user.nickname,avatar:(i=(r=y.user.avatar_larger)==null?void 0:r.url_list)==null?void 0:i[0]}:{isAuthenticated:!1}}if(e!=="xiaohongshu")throw new Error("不支持的平台账号检测");const a=await fetch("https://creator.xiaohongshu.com/api/galaxy/user/info",{credentials:"include",cache:"no-store",headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(a.status===401)return{isAuthenticated:!1};if(!a.ok)throw new Error(`小红书创作者账号检测失败(HTTP ${a.status}),不代表未登录;请打开创作者后台确认后重新检测`);const n=await a.json().catch(()=>{throw new Error("小红书账号接口未返回有效 JSON,检测失败不代表未登录;请打开创作者后台确认后重新检测")}),s=String((n==null?void 0:n.msg)||(n==null?void 0:n.message)||"");if((n==null?void 0:n.code)===401||(n==null?void 0:n.code)===-100||/未登录|尚未登录|登录(?:已)?(?:失效|过期)|not[ _-]?login|login[ _-]?required/i.test(s))return{isAuthenticated:!1};if((n==null?void 0:n.success)===!1||!((n==null?void 0:n.success)===!0||(n==null?void 0:n.code)===0||(n==null?void 0:n.code)==="0"))throw new Error("小红书创作者账号接口暂时无法确认登录状态,请在创作者后台确认后重新检测");const o=n.data;if(typeof(o==null?void 0:o.userId)!="string"||!o.userId.trim()||o.userId.length>128)throw new Error("小红书创作者账号信息未能读取,检测失败不代表未登录;请打开创作者后台确认");return{isAuthenticated:!0,userId:o.userId,...typeof o.userName=="string"?{username:o.userName}:{},...typeof o.userAvatar=="string"?{avatar:o.userAvatar}:{}}}catch(a){return{isAuthenticated:!1,error:a instanceof Error?a.message:"账号检测失败"}}}const Tr=[Zt,_r,Er,Sr,yr,Ir],It=Tr.map(e=>({Factory:e,sample:new e})),Cr=kr();function Le(){return[...It.map(({sample:e})=>{const{meta:t}=e;if(!["zhihu","baijiahao","weibo","bilibili"].includes(t.id))return{...t,action:"draft",publishModes:["article"],delivery:"http"};const r=t.id==="weibo";return{...t,...r?{name:"微博",homepage:"https://weibo.com",videoCreationRequired:!0,videoCreationOptions:["original","secondary","repost"]}:{},tools:r?{article:"publish_article",image:"publish_post",video:"publish_post"}:{article:"publish_article"},capabilities:[...t.capabilities.filter(i=>!(t.id==="zhihu"?["draft","cover","tags"]:["draft"]).includes(i)),"publish",...r?["video","tags"]:[]],action:"publish",publishModes:r?["article","image","video"]:["article"],embeddedVideo:t.id==="zhihu",coverRequired:t.id==="baijiahao",delivery:t.id==="bilibili"?"page":"http+page",...t.id==="zhihu"?{confirmation:"http_response_or_native_page_message"}:{}}}),...Kt]}function Dr(e){const t=It.find(({sample:r})=>r.meta.id===e);if(!t)throw new Error("不支持的平台");return{...gr,...t.sample.preprocessConfig}}async function Yt(e){const t=It.find(({sample:i})=>i.meta.id===e);if(!t)throw new Error("不支持的平台");const r=new t.Factory;return await r.init(Cr),r}async function bt(e,t,r){let i;try{return await Promise.race([e,new Promise((a,n)=>{i=setTimeout(()=>n(new Error(r)),t)})])}finally{i&&clearTimeout(i)}}async function it(e){try{if(ut(e))return await bt($r(e),1e4,"登录检测超时,请在创作者后台确认登录");const t=await Yt(e);return await bt(t.checkAuth(),1e4,"登录检测超时,请稍后重试")}catch(t){return{isAuthenticated:!1,error:t instanceof Error?t.message:"登录检测失败"}}}let Ze=null;async function Qt(e=!1){if(Ze)return Ze;Ze=(async()=>{const t=await chrome.storage.local.get(Q.authCache),r=Le(),i=new Set(r.map(s=>s.id)),a=Object.fromEntries(Object.entries(t[Q.authCache]||{}).filter(([s])=>i.has(s))),n=[];for(let s=0;s<r.length;s+=5)n.push(...await Promise.all(r.slice(s,s+5).map(async o=>{const c=a[o.id],y=c!=null&&c.isAuthenticated?3e5:3e4,h=o.id!=="xiaohongshu"||(c==null?void 0:c.authRevision)===1;let w;return!e&&c&&h&&Date.now()-c.timestamp<y?w=c:(w=await it(o.id),a[o.id]={...w,timestamp:Date.now(),...o.id==="xiaohongshu"?{authRevision:1}:{}}),{...o,...w,checked:!0}})));return await chrome.storage.local.set({[Q.authCache]:a}),n})();try{return await Ze}finally{Ze=null}}let Ke=null;async function er(){Ke||(Ke=(async()=>{var t;await chrome.offscreen.hasDocument()||await chrome.offscreen.createDocument({url:"src/offscreen/index.html",reasons:[chrome.offscreen.Reason.DOM_PARSER],justification:"在本地为文章转换各平台需要的 HTML 和 Markdown 排版"});for(let r=0;r<50;r+=1){try{const i=await chrome.runtime.sendMessage({target:"offscreen",type:"OFFSCREEN_READY"});if((t=i==null?void 0:i.data)!=null&&t.ready)return}catch{}await new Promise(i=>setTimeout(i,100))}throw new Error("文章排版处理页面未就绪,请重新打开写作台")})());const e=Ke;try{await e}finally{Ke===e&&(Ke=null)}}async function Lr(e,t){await er();const r=await chrome.runtime.sendMessage({target:"offscreen",type:"PREPROCESS_ARTICLE",payload:{rawHtml:e,config:t}});if(!(r!=null&&r.data))throw new Error((r==null?void 0:r.error)||"文章排版处理失败,请重新打开写作台");return r.data}async function Ur(e){await er();const t=await chrome.runtime.sendMessage({target:"offscreen",type:"NORMALIZE_AGENT_HTML",payload:{rawHtml:e}});if(typeof(t==null?void 0:t.data)!="string")throw new Error((t==null?void 0:t.error)||"稿件处理失败");return t.data}function xt(e,t){if(e===void 0)return[];if(!Array.isArray(e)||!e.length||e.length>5)throw new Error("文章内嵌视频列表不正确,最多 5 个");const r=new Set,i=e.map(a=>{if(!a||typeof a.marker!="string"||!/^WRITEDOCK_VIDEO_[1-5]$/.test(a.marker)||r.has(a.marker)||t.split(a.marker).length!==2)throw new Error("文章视频占位符缺失或重复,请重新准备稿件");r.add(a.marker);const n=De({kind:"video",title:"文章内嵌视频",content:"",images:[],tags:[],video:a.asset});if(n.video.type!=="video/mp4")throw new Error("当前知乎文章内嵌视频仅接入 MP4 格式");return{marker:a.marker,asset:n.video}});if(i.reduce((a,n)=>a+n.asset.size,0)>512*1024*1024)throw new Error("文章内嵌视频总量不能超过 512 MB");return i}function tr(e){return e.map(({marker:t,asset:{fingerprint:r,name:i,size:a,type:n}})=>({marker:t,fingerprint:r,name:i,size:a,type:n}))}function De(e){if(!e||typeof e!="object")throw new Error("请提供图文或视频内容");const t=e;if(!["image","video"].includes(t.kind)||typeof t.title!="string"||!t.title.trim()||t.title.trim().length>200)throw new Error("投稿类型或标题不正确");if(typeof t.content!="string"||t.content.length>5e4)throw new Error("正文必须是 50000 字以内的文本");const r=(o,c)=>{if(!o||!/^[a-f0-9-]{36}$/.test(o.id)||!/^[a-f0-9]{64}$/.test(o.accessKey)||!/^[a-f0-9]{64}$/.test(o.fingerprint)||!Number.isInteger(o.port)||o.port<1024||o.port>65535||typeof o.name!="string"||!o.name||o.name.length>255||typeof o.type!="string"||!o.type.startsWith(`${c}/`)||!Number.isSafeInteger(o.size)||o.size<1||o.size>(c==="video"?512:20)*1024*1024)throw new Error("素材授权格式不正确或大小超限,请让 agent 重新准备素材");return{id:o.id,accessKey:o.accessKey,port:o.port,name:o.name,type:o.type,size:o.size,fingerprint:o.fingerprint}};if(!Array.isArray(t.images)||t.images.length>35)throw new Error("图片列表格式不正确,最多 35 张");const i=t.images.map(o=>r(o,"image"));if(i.reduce((o,c)=>o+c.size,0)>100*1024*1024)throw new Error("图文图片总量不能超过 100 MB");const a=t.video?r(t.video,"video"):void 0,n=t.cover?r(t.cover,"image"):void 0;if(t.kind==="image"&&(!i.length||a||n))throw new Error("图文需要图片列表;封面使用第一张图片,不能同时提供视频或独立视频封面");if(t.kind==="video"&&(!a||i.length))throw new Error("视频投稿需要视频文件,不能同时提供图文图片列表");if(t.weiboVideoCreation!==void 0&&(t.kind!=="video"||!["original","secondary","repost"].includes(t.weiboVideoCreation)))throw new Error("微博视频创作类型仅用于视频,请明确提供 original(原创)、secondary(二创)或 repost(转载)");if(!Array.isArray(t.tags)||t.tags.length>10||t.tags.some(o=>typeof o!="string"||o.length>50))throw new Error("话题最多 10 个,每个不超过 50 字");const s=[...new Set(t.tags.map(o=>o.trim().replace(/^#+/,"")).filter(Boolean))];return{kind:t.kind,title:t.title.trim(),content:t.content,images:i,...a?{video:a}:{},...n?{cover:n}:{},tags:s,...t.weiboVideoCreation?{weiboVideoCreation:t.weiboVideoCreation}:{}}}function ht(e,t){if(t.includes("douyin")){const r=e.kind==="video"?5:4;if(e.tags.length>r)throw new Error(`当前抖音适配${e.kind==="video"?"视频":"图文"}最多接收 ${r} 个话题,请先减少话题`);if(e.tags.some(i=>/[#\r\n]/.test(i)))throw new Error("抖音话题中不能包含 # 或换行,请提供话题名称")}if(t.includes("weibo")){if(e.kind==="image"&&e.images.length>18)throw new Error("当前微博普通图文接入最多 18 张图片");if(e.kind==="video"&&!e.weiboVideoCreation)throw new Error("微博视频必须由 Agent 根据用户实际选择明确传入 weibo_video_creation:original(原创)、secondary(二创)或 repost(转载),不得默认声明原创");if(e.cover&&e.cover.size>5*1024*1024)throw new Error("当前微博视频封面不能超过 5 MB");if(e.kind==="video"&&e.title.split("").reduce((r,i)=>r+(i.charCodeAt(0)<=255?1:2),0)>60)throw new Error("微博视频标题超过当前页面的 30 个汉字(60 个半角字符)限制");if(e.tags.some(r=>/[#\r\n]/.test(r)))throw new Error("微博话题中不能包含 # 或换行,请提供话题名称")}}function Or(e){return[...e.kind==="image"?[e.title]:[],e.content,...e.tags.length?[e.tags.map(t=>`#${t}#`).join(" ")]:[]].filter(Boolean).join(`
37
- `)||e.title}function Rt(e){const t=[...e.images,...e.video?[e.video]:[],...e.cover?[e.cover]:[]];return{title:e.title,markdown:"",html:`<p>${qe(e.content).replace(/\n/g,"<br>")}</p>${e.tags.length?`<p>${e.tags.map(r=>qe(`#${r}`)).join(" ")}</p>`:""}<p>${e.kind==="video"?"视频投稿":"图文投稿"}${e.weiboVideoCreation?` · 微博:${{original:"原创",secondary:"二创",repost:"转载"}[e.weiboVideoCreation]}`:""}</p><ul>${t.map(r=>`<li>${qe(r.name)} · ${(r.size/1024/1024).toFixed(1)} MB</li>`).join("")}</ul>`}}function rr(e){const t=({fingerprint:r,name:i,size:a,type:n})=>({fingerprint:r,name:i,size:a,type:n});return{kind:e.kind,title:e.title,content:e.content,tags:e.tags,images:e.images.map(t),...e.video?{video:t(e.video)}:{},...e.cover?{cover:t(e.cover)}:{},...e.weiboVideoCreation?{weiboVideoCreation:e.weiboVideoCreation}:{}}}function Pr(e){const t=`writedock-douyin-${e.channel||e.id}`;let r=!1,i=!1,a=!1,n=!1,s;const o=I=>I.getClientRects().length>0&&getComputedStyle(I).visibility!=="hidden",c=I=>o(I)&&!I.hasAttribute("disabled")&&I.getAttribute("aria-disabled")!=="true"&&!/disabled/i.test(I.className),y=I=>I.replace(/[\s\u200b-\u200d\ufeff]/g,""),h=I=>y(I||"").length>0,w=I=>{var R;for(let L=I.parentElement,N=0;L&&N<4;L=L.parentElement,N++){const B=(R=L.textContent)==null?void 0:R.match(/(?:^|\D)\d+\s*\/\s*(\d{1,4})(?:\D|$)/);if(B)return Number(B[1])}return 0},m=I=>new Promise(R=>setTimeout(R,I)),p=()=>{s==null||s.disconnect(),window.removeEventListener(`${t}:cancel`,u)},u=()=>{i=!0,p()};window.addEventListener(`${t}:cancel`,u,{once:!0});const g=async I=>{if(i||a)return;a=!0,p();const R={...I,phase:"result",jobId:e.id};try{sessionStorage.setItem(t,JSON.stringify(R))}catch{}await chrome.runtime.sendMessage({type:"PAGE_PUBLISH_DONE",jobId:e.id,jobSecret:e.secret,result:R})};function D(I,R){throw Object.assign(new Error(R),{manualReason:I})}const S=()=>Array.from(document.querySelectorAll('[role="alert"],[role="dialog"],.semi-toast,.semi-modal-content,.semi-modal-body')).filter(o).map(I=>{var R;return((R=I.textContent)==null?void 0:R.trim())||""}).filter(I=>I.length>0&&I.length<1500),b=()=>{if(i||a)throw new Error("本次抖音自动投稿已结束");if(e.platform!=="douyin")throw new Error("当前页面脚本仅用于抖音");if(Date.now()>=e.deadline)throw new Error("投稿等待超时,请检查平台后台,不要自动重复发布");if(location.origin!=="https://creator.douyin.com"||/\/(?:login|passport)(?:\/|$)/.test(location.pathname))throw new Error("请先在当前浏览器完成抖音创作者后台登录");Array.from(document.querySelectorAll('#captcha_container,.captcha_verify_container,.captcha-verify-container,iframe[src*="captcha"],iframe[src*="verify"],.geetest_panel')).some(o)&&D("captcha","抖音要求人工验证,请在扩展已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");const I=S();I.some(N=>/验证码|安全验证|拖动.*(?:滑块|图片)|旋转.*图片|转动.*图片|请.*(?:验证|扫码)/.test(N))&&D("captcha","抖音要求人工验证,请在已打开的原投稿页完成验证并手动发布,Agent 不要重发。"),I.some(N=>/我已阅读|我同意|原创声明|创作声明|同意.*协议|确认.*声明|请选择.*(?:原创|转载|来源)/.test(N))&&D("agreement","抖音要求确认来源、声明或协议,请在原投稿页阅读、自行选择并手动发布。"),!n&&I.some(N=>/请选择封面|请设置封面|封面不能为空/.test(N))&&D("cover_required","抖音要求设置封面,请在原投稿页补充封面并手动发布。");const R=Array.from(document.querySelectorAll('[role="alert"],.semi-toast')).filter(o).map(N=>N.textContent||"");(I.some(N=>/实名认证|绑定手机|补充.*(?:声明|来源|信息)/.test(N))||!n&&R.some(N=>/请选择|请设置/.test(N)))&&D("publication_settings","抖音要求补充账号信息或发布设置,请在原投稿页处理并手动发布。");const L=I.find(N=>/发布失败|提交失败|上传失败|格式不支持|账号.*异常|超过.*(?:限制|字)|标题不能为空|正文不能为空/.test(N));if(L)throw new Error(L.slice(0,300))},d=async(I,R={})=>{b();const L=await chrome.runtime.sendMessage({type:I,jobId:e.id,jobSecret:e.secret,...R});if(!L||L.error)throw new Error((L==null?void 0:L.error)||"扩展后台已断开,请检查抖音结果,不要自动重发");return b(),L.data},f=(I,R,L)=>d("PAGE_PUBLISH_PROGRESS",{stage:I,current:R,total:L}),l=async(I,R,L)=>{const N=Math.min(Date.now()+R,e.deadline);for(;Date.now()<N;){b();const B=I();if(B)return B;await m(300)}throw new Error(L)},_=()=>Array.from(document.querySelectorAll("button")).filter(c),$=()=>Array.from(document.querySelectorAll('input[placeholder*="作品标题"],input[placeholder*="标题"]')).find(o),x=()=>{const I=document.querySelector('div.zone-container.editor-kit-container.editor.editor-comp-publish[contenteditable="true"]');if(I&&o(I))return I;const R=Array.from(document.querySelectorAll('div[contenteditable="true"]')).filter(o);return R.length===1?R[0]:void 0},E=(I,R=!1)=>{I.focus();const L=document.createRange();L.selectNodeContents(I),R&&L.collapse(!1);const N=getSelection();N==null||N.removeAllRanges(),N==null||N.addRange(L)},v=(I,R)=>{const L=new DataTransfer;L.setData("text/plain",R),I.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:L}))},k=async(I,R)=>{var P;if(!I.multiple&&R.length>1)throw new Error("抖音当前控件不接受多张图片,未丢弃素材后继续发布");const L=new DataTransfer,N=R.reduce((A,q)=>A+q.size,0);let B=0;await f("transferring_media",0,N);for(const A of R){if(I.accept&&!I.accept.toLowerCase().split(",").map(K=>K.trim()).some(K=>K==="*/*"||K===A.type||K===`${A.type.split("/")[0]}/*`||K==="image/jpg"&&A.type==="image/jpeg"||K.startsWith(".")&&A.name.toLowerCase().endsWith(K)))throw new Error(`抖音当前上传控件不接受 ${A.name} 的格式`);const q=[];for(let j=0;j<A.size;j+=1024*1024){const K=Math.min(1048576,A.size-j),J=await d("PAGE_PUBLISH_READ_ASSET",{assetId:A.id,offset:j,length:K}),ee=Uint8Array.from(atob(J.base64),X=>X.charCodeAt(0));if(ee.length!==K)throw new Error("素材传输不完整,已停止投稿");q.push(ee.buffer),B+=ee.length,(j%(8*1024*1024)===0||B===N)&&await f("transferring_media",B,N)}L.items.add(new File(q,A.name,{type:A.type}))}if(b(),!I.isConnected)throw new Error("抖音上传控件已变化,未向旧控件提交素材");if(I.files=L.files,((P=I.files)==null?void 0:P.length)!==R.length)throw new Error("抖音上传控件未接收全部素材,已停止投稿");I.dispatchEvent(new Event("change",{bubbles:!0})),I.dispatchEvent(new Event("input",{bubbles:!0})),await f("uploading_media")},O=()=>Array.from(document.querySelectorAll('[role="alert"],[role="status"],.semi-toast,.semi-toast-content,.semi-modal-content h1,.semi-modal-content h2')).filter(o).filter(I=>{var L;const R=((L=I.textContent)==null?void 0:L.trim())||"";return R.length<100&&/^(?:(?:图文|作品|视频)\s*)?(?:发布成功|提交成功|已提交审核)(?:[!!。,,\s]|$)/.test(R)});return(async()=>{var F,Z,G,ne,se,fe;const I=e.post;if(await f("checking_auth"),await l(()=>document.querySelector('input[type="file"]'),6e4,"未找到抖音上传入口,请确认已登录创作者后台"),I.kind==="image"){const W=document.querySelector(".semi-tabs.semi-tabs-top"),ie=(F=W==null?void 0:W.previousElementSibling)==null?void 0:F.querySelectorAll("div"),pe=[...Array.from(ie||[]),...Array.from(document.querySelectorAll('[role="tab"],span.title,div'))].find(le=>{var ce;return o(le)&&((ce=le.textContent)==null?void 0:ce.trim())==="发布图文"&&!Array.from(le.children).some(ge=>{var we;return((we=ge.textContent)==null?void 0:we.trim())==="发布图文"})});pe&&(pe.click(),await m(700))}const R=()=>Array.from(document.querySelectorAll("div,span,p")).some(W=>o(W)&&W.children.length<3&&/你还有上次未发布的(?:图文|视频)/.test(W.textContent||"")&&(W.textContent||"").length<60),L="抖音还有一份上次没发完的内容,这篇还没有上传。请问用户:放弃那份旧内容,继续发布这篇吗?放弃后无法恢复。";if(R()){const W=e.discardDraft?Array.from(document.querySelectorAll("*")).find(Y=>{var pe;return o(Y)&&!Y.children.length&&((pe=Y.textContent)==null?void 0:pe.trim())==="放弃"}):void 0;W||D("old_draft",L),W.click();const ie=Date.now()+8e3;for(;R()&&Date.now()<ie;)await m(300);R()&&D("old_draft",L)}const N=$(),B=x();(h(N==null?void 0:N.value)||h(B==null?void 0:B.textContent))&&D("publication_settings","抖音发布页已有未发内容,未追加素材或覆盖原稿,请在当前页面自行核对。");const P=await l(()=>{if(I.kind==="image"){const ie=document.querySelector('input[accept="image/png,image/jpeg,image/jpg,image/bmp,image/webp,image/tif"]');if(ie)return ie}const W=Array.from(document.querySelectorAll('input[type="file"]'));return W.find(ie=>I.kind==="image"?/image|\.(?:png|jpe?g|webp|gif)/i.test(ie.accept):/video|\.(?:mp4|mov|m4v|webm|avi)/i.test(ie.accept))||(I.kind==="video"&&W.length===1&&!W[0].accept?W[0]:void 0)},3e4,"未找到抖音对应的图片或视频上传控件");await k(P,I.kind==="image"?I.images:[I.video]);const A=await l($,3*6e4,"上传后未找到抖音作品标题输入框,请检查素材处理状态"),q=await l(x,3e4,"未找到抖音正文编辑器"),j=(Z=I.video)==null?void 0:Z.name,K=I.kind==="video"&&j&&[j,j.replace(/\.[^.]+$/,"")].includes(A.value.trim());(h(A.value)&&!K||h(q.textContent))&&D("publication_settings","抖音发布页已有文案,未覆盖原稿,请在当前页面自行核对。");const J=A.maxLength>0?A.maxLength:w(A);if(J>0&&I.title.length>J)throw new Error(`抖音当前标题最多 ${J} 字,请缩短标题,未截断发布`);(ne=(G=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value"))==null?void 0:G.set)==null||ne.call(A,I.title),A.dispatchEvent(new Event("input",{bubbles:!0})),A.dispatchEvent(new Event("change",{bubbles:!0})),I.content&&(E(q),v(q,I.content),await m(300),h(q.textContent)||(E(q),document.execCommand("insertText",!1,I.content)),await l(()=>y(q.innerText)===y(I.content),1e4,"抖音正文未完整写入,已停止发布"));for(let W=0;W<I.tags.length;W++){const ie=` #${I.tags[W]}`;E(q,!0);const Y=q.innerText;v(q,ie),await m(600),q.innerText===Y&&(E(q,!0),document.execCommand("insertText",!1,ie));const pe=[I.content,...I.tags.slice(0,W+1).map(le=>`#${le}`)].join(" ");await l(()=>y(q.innerText)===y(pe),1e4,"抖音话题未完整写入,已停止发布")}const ee=[I.content,...I.tags.map(W=>`#${W}`)].join(" ");if(I.cover){n=!0;try{const ie=(fe=(se=(await l(()=>document.querySelector("div.content-upload-new"),6e4,"未找到抖音视频封面入口")).firstElementChild)==null?void 0:se.firstElementChild)==null?void 0:fe.firstElementChild;ie||D("cover_required","未找到抖音原生封面上传按钮,请在已打开的原投稿页设置封面并手动发布。"),b(),ie.click();const Y=await l(()=>Array.from(document.querySelectorAll('input[type="file"].semi-upload-hidden-input')).find(le=>/image|\.(?:png|jpe?g|webp)/i.test(le.accept)),2e4,"未找到抖音封面上传控件");await k(Y,[I.cover]),await m(3e3);const pe=await l(()=>_().find(le=>{var ce;return((ce=le.textContent)==null?void 0:ce.trim())==="完成"&&(le.matches(".semi-button.semi-button-primary.semi-button-light")||!!le.closest('[role="dialog"],.semi-modal-content'))}),3e4,"抖音封面处理未完成");b(),pe.click()}catch(W){if(i||a||W!=null&&W.manualReason)throw W;D("cover_required","抖音视频封面未能设置完成,请在已打开的原投稿页核对封面并手动发布。")}finally{n=!1}}const X=await l(()=>_().find(W=>{var ie;return((ie=W.textContent)==null?void 0:ie.trim())==="发布"}),15*6e4,"抖音上传或处理尚未完成,发布按钮不可用,未点击发布");if(A.value!==I.title||y(q.innerText)!==y(ee))throw new Error("抖音标题、完整正文或话题发生变化,已停止发布");Array.from(document.querySelectorAll('.semi-radio-checked,[role="radio"][aria-checked="true"],input[type="radio"]:checked')).filter(o).some(W=>{var ie;return/定时发布|仅自己可见|私密|部分可见|好友可见/.test(((ie=W.closest("label"))==null?void 0:ie.textContent)||W.textContent||"")})&&D("publication_settings","抖音当前选择了定时或非公开发布,请在原投稿页核对设置并手动发布。");const he=()=>Math.max(0,...performance.getEntriesByType("resource").filter(W=>W.name.includes("/post_assistant/fast_detect/")).map(W=>W.startTime));if(await l(()=>performance.now()-he()>15e3,5*6e4,"抖音内容检测长时间未结束,未点击发布"),e.rehearsal){await g({success:!1,publicationState:"rehearsed"});return}const te=new Map(O().map(W=>[W,W.textContent])),me=()=>{if(!(i||a||!r))try{b(),O().find(ie=>!te.has(ie)||te.get(ie)!==ie.textContent)&&g({success:!0,pageConfirmed:!0,publicationState:"submitted",postUrl:"https://creator.douyin.com/creator-micro/content/manage",message:"抖音原生页面已提示发布成功或提交审核,展示状态以平台为准"}).catch(u)}catch(W){g(W!=null&&W.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:W.manualReason,message:W.message}:{success:!1,publicationState:"unknown",error:W instanceof Error?W.message:"抖音发布结果未确认"}).catch(u)}};s=new MutationObserver(me),s.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0});const C=new Set(_());if(await f("publishing"),b(),!X.isConnected||!c(X)||!A.isConnected||!q.isConnected||A.value!==I.title||y(q.innerText)!==y(ee))throw new Error("抖音稿件或发布控件发生变化,已停止操作");if(await f("verifying"),b(),!X.isConnected||!c(X)||!A.isConnected||!q.isConnected||A.value!==I.title||y(q.innerText)!==y(ee))throw new Error("抖音稿件或发布控件发生变化,未点击发布");if(X.scrollIntoView({block:"center"}),await m(500),b(),!X.isConnected||!c(X))throw new Error("抖音发布控件发生变化,未点击发布");r=!0;const H=X.getBoundingClientRect(),M={bubbles:!0,cancelable:!0,composed:!0,view:window,clientX:H.left+H.width/2,clientY:H.top+H.height/2,button:0};X.dispatchEvent(new PointerEvent("pointerdown",{...M,pointerType:"mouse",isPrimary:!0})),X.dispatchEvent(new MouseEvent("mousedown",M)),X.dispatchEvent(new PointerEvent("pointerup",{...M,pointerType:"mouse",isPrimary:!0})),X.dispatchEvent(new MouseEvent("mouseup",M)),X.click();const U=Math.min(Date.now()+12e4,e.deadline);let V=!1,T=0;for(;!i&&!a&&Date.now()<U;){if(b(),me(),i||a)return;if(!V){const W=_().find(ie=>{var Y;return!C.has(ie)&&/^(?:确认发布|确定发布)$/.test(((Y=ie.textContent)==null?void 0:Y.trim())||"")&&!!ie.closest('[role="dialog"],.semi-modal-content')});W&&(V=!0,W.click())}if(/^\/creator-micro\/content\/manage(?:\/|$)/.test(location.pathname)&&(T||(T=Date.now()),Date.now()-T>3e3))break;await m(300)}!i&&!a&&await g({success:!1,publicationState:"unknown",error:"已触发抖音发布,但未取得明确成功提示,请检查原投稿页或作品管理,不要自动重发。"})})().catch(I=>{i||a||g(I!=null&&I.manualReason?{success:!1,publicationState:"needs_user_action",manualReason:I.manualReason,message:I.message}:{success:!1,publicationState:r?"unknown":"failed",error:I instanceof Error?I.message:"抖音页面投稿失败"}).catch(u)}),{started:!0}}function qr(e){const t=`writedock-weibo-post-${e.channel}`,r=new Set,i=new Set,a=new Set,n=new Set;let s=!1,o=!1,c=!1,y=!1;const h=P=>{const A=JSON.stringify(P);try{sessionStorage.setItem(t,A)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:A}))},w=[],m=P=>{w.includes(P)||w.push(P)},p=P=>{c||(c=!0,h({phase:"result",...w.length?{warnings:w}:{},...P}))},u=(P,A)=>p({success:!1,publicationState:"needs_user_action",manualReason:P,message:A}),g=()=>h({phase:"uploads",pictures:[...r],videos:[...a],covers:[...n]}),D=P=>typeof P=="string"&&/^[\w:-]{1,128}$/.test(P),S=P=>{if(typeof P!="string")return P;try{return JSON.parse(P)}catch{return JSON.parse(decodeURIComponent(P))}},b=(P,A)=>{try{const q=new URL(A,location.href);if(P.toUpperCase()!=="POST")return null;if(q.origin==="https://weibo.com"&&q.pathname==="/ajax/statuses/update")return"publish";if(q.origin==="https://weibo.com"&&/^\/ajax\/statuses\/(?:schedule\/(?:upload|update)|modify|repost|normal_repost)$/.test(q.pathname))return"other_publish";if(q.hostname==="picupload.weibo.com"&&/^\/interface\/(?:pic_)?upload\.php$/.test(q.pathname))return"picture";if(/^fileplatform(?:-[a-z0-9-]+)?\.api\.weibo\.com$/.test(q.hostname)){if(q.pathname==="/2/fileplatform/init.json")return"init";if(q.pathname==="/2/fileplatform/check.json")return"check"}}catch{}return null},d=P=>{var he,te,me,C,H,M;const A=U=>{throw u("publication_settings",U),new Error("WriteDock 已停止微博自动提交,请检查投稿页")};if(e.rehearsal)return A("演练不提交发布,已拦截微博发布请求。");if(c||o||!s||Date.now()>=e.deadline)return o&&!c&&p({success:!1,publicationState:"unknown",error:"微博页面尝试重复发送,请检查原帖,Agent 不要重发。"}),A("微博页面尚未完成本次稿件核对或尝试重复发送,已停止自动提交,请检查原投稿页。");const q=()=>{o=!0,s=!1,h({phase:"request"})},j=P instanceof URLSearchParams||P instanceof FormData?P:typeof P=="string"?new URLSearchParams(P):null;if(!j){m("微博发布请求格式无法解析,已依据提交前的页面核对放行"),q();return}const K=j.get("content");if(K===null)m("微博发布请求中未读到正文字段");else if(String(K).replace(/\r\n?/g,`
38
- `).trim()!==e.text.replace(/\r\n?/g,`
39
- `).trim())return A("微博页面正文与本次 Agent 稿件不一致,已停止发布,请检查原投稿页。");const J=U=>U===null||U===""||U==="0"||U==="{}"||U==="[]",ee=j.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(U=>!J(j.get(U))))return A("微博的可见范围、定时、转发、内容声明或其他发布设置需要核对,请在原页面手动处理。");let X,re;try{X=j.get("media")?S(j.get("media")):null,re=j.get("pic_id")?S(j.get("pic_id")):[]}catch{m("微博素材字段无法解析,已依据提交前的页面核对放行"),q();return}if(e.kind==="image"){if(Array.isArray(re)&&re.length&&re.length!==e.imageCount)return A("微博图片数量与本次投稿不一致,已停止发布,请检查原投稿页。");!Array.isArray(re)||!re.length?m("微博发布请求中未读到图片字段"):(new Set(re.map(U=>U.pid)).size!==e.imageCount||re.some(U=>!String(U.type).startsWith("image/")||!r.has(U.pid)||U.media_id))&&m("微博图片未匹配本次观察到的上传记录"),X&&Object.keys(X).length&&m("微博图文请求带有 media 字段")}else if(!X)m("微博发布请求中未读到视频字段");else{const U=X.homemade||X.contribution,V={original:0,secondary:2,repost:1}[e.creation],T=Array.isArray(X.titles)?(he=X.titles[0])==null?void 0:he.title:void 0;if(typeof T=="string"&&T!==e.title)return A("微博视频标题与本任务不一致,已停止发布,请核对原页面。");if((U==null?void 0:U.type)!==void 0&&U.type!==V)return A("微博视频创作类型与本任务不一致,已停止发布,请核对原页面。");if(e.explicitCover&&Array.isArray(X.covers)&&((te=X.covers[0])!=null&&te.pid)&&!n.has(X.covers[0].pid))return A("本次指定的视频封面未确认应用,未使用默认封面替代,请在原页面完成设置。");if((me=X.resource)!=null&&me.statement||(C=X.resource)!=null&&C.manual_split||(H=X.cooperate_video)!=null&&H.length||X.is_vip_paid||X.um_video_switch||(M=X.follower_watch_entire)!=null&&M.enable)return A("微博视频需要内容声明、来源、共创、付费或阅读设置确认,请在原页面核对并手动发布。");typeof T!="string"&&m("微博发布请求中未读到视频标题字段"),(U==null?void 0:U.type)===void 0&&m("微博发布请求中未读到创作类型字段"),(X.type!=="video"||!a.has(X.media_id))&&m("微博视频未匹配本次观察到的上传记录"),(!Array.isArray(X.covers)||!X.covers.length||X.covers.some(F=>!D(F.pid)))&&m("微博发布请求中未读到有效的视频封面字段"),Array.isArray(re)&&re.length&&m("微博视频请求带有图片字段")}q()},f=(P,A,q,j)=>{var K,J,ee,X,re,he,te,me,C,H,M,U,V;if(!c)try{const T=S(q);if(P!=="publish"){if(A<200||A>=300)return;if(P==="picture"){const Z=(T==null?void 0:T.ret)===!0?(K=T.pic)==null?void 0:K.pid:(X=(ee=(J=T==null?void 0:T.data)==null?void 0:J.pics)==null?void 0:ee.pic_1)==null?void 0:X.pid;D(Z)&&(r.add(Z),j&&n.add(Z))}P==="init"&&D(T==null?void 0:T.media_id)&&i.add(T.media_id),P==="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((re=T==null?void 0:T.data)!=null&&re.verify||(he=T==null?void 0:T.data)!=null&&he.geetest||(te=T==null?void 0:T.data)!=null&&te.verify_url||/验证码|安全验证|完成验证|验证后/.test(F)){u("captcha","微博要求人工验证。请切换到已打开的投稿页完成验证并手动发布,Agent 不要重新提交。");return}if((T==null?void 0:T.ok)===1&&!T.error&&A>=200&&A<300){const Z=(me=T.data)==null?void 0:me.mblogid,G=String(((H=(C=T.data)==null?void 0:C.user)==null?void 0:H.idstr)??((U=(M=T.data)==null?void 0:M.user)==null?void 0:U.id)??""),ne=typeof Z=="string"&&/^[a-zA-Z0-9]+$/.test(Z)&&/^\d+$/.test(G)?`https://weibo.com/${G}/${Z}`:"https://weibo.com";p({success:!0,publicationState:"submitted",responseConfirmed:!0,postUrl:ne,...typeof((V=T.data)==null?void 0:V.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 ${A}),请检查平台,不要自动重发。`})}catch{P==="publish"&&p({success:!1,publicationState:"unknown",error:"微博发布响应无法解析,请检查平台,不要自动重发。"})}},l=()=>{throw u("publication_settings","微博页面试图定时、转发或修改已有帖子,未按本次即时发布提交,请在原页面核对。"),new Error("WriteDock 已停止本次未授权的微博发布方式")},_=window.fetch,$=async function(P,A){const q=(A==null?void 0:A.method)||(P instanceof Request?P.method:"GET"),j=b(q,P instanceof Request?P.url:String(P)),K=y;j==="other_publish"&&l(),j==="publish"&&d((A==null?void 0:A.body)??(P instanceof Request?await P.clone().text():void 0));try{const J=await _.call(window,P,A);return j&&f(j,J.status,await J.clone().text(),K),J}catch(J){throw j==="publish"&&p({success:!1,publicationState:"unknown",error:"微博发布连接中断,请检查原帖,不要自动重发。"}),J}},x=XMLHttpRequest.prototype,E=x.open,v=x.send,k=new WeakMap,O=function(P,A,...q){return k.set(this,{method:P,url:String(A)}),Reflect.apply(E,this,[P,A,...q])},z=function(P){const A=k.get(this),q=A?b(A.method,A.url):null,j=y;return q==="other_publish"&&l(),q==="publish"&&d(P),q&&this.addEventListener("loadend",()=>{try{f(q,this.status,this.responseType==="json"?this.response:this.responseText,j)}catch{q==="publish"&&f(q,this.status,void 0,j)}},{once:!0}),v.call(this,P)},I=()=>{!c&&!o&&Date.now()<e.deadline&&(s=!0)},R=()=>{y=!0},L=()=>{var J,ee;const P=document.querySelector(`input[data-writedock-video="${e.channel}"]`),A=Array.from(document.querySelectorAll('[id^="area_video"]')).find(X=>X.getClientRects().length>0);if(!P)return;if(!((J=P.files)!=null&&J.length)||!A){P.setAttribute("data-writedock-drop-status",`files=${((ee=P.files)==null?void 0:ee.length)??0} area=${A?1:0}`);return}const q=new DataTransfer;for(const X of Array.from(P.files))q.items.add(X);const j=A.firstElementChild||A,K=["dragenter","dragover","drop"].map(X=>j.dispatchEvent(new DragEvent(X,{bubbles:!0,cancelable:!0,composed:!0,dataTransfer:q}))?0:1).join("");P.setAttribute("data-writedock-drop-status",`files=${q.files.length} handled=${K}`)},N=()=>{window.fetch===$&&(window.fetch=_),x.open===O&&(x.open=E),x.send===z&&(x.send=v),clearTimeout(B),window.removeEventListener(`${t}:arm`,I),window.removeEventListener(`${t}:cover`,R),window.removeEventListener(`${t}:drop-video`,L),window.removeEventListener(`${t}:stop`,N)};window.fetch=$,x.open=O,x.send=z,window.addEventListener(`${t}:arm`,I),window.addEventListener(`${t}:cover`,R),window.addEventListener(`${t}:drop-video`,L),window.addEventListener(`${t}:stop`,N,{once:!0});const B=setTimeout(N,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(k=>setTimeout(k,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,k={})=>{const O=await chrome.runtime.sendMessage({type:v,jobId:e.id,jobSecret:e.secret,...k});if(!O||O.error)throw new Error((O==null?void 0:O.error)||"扩展后台已断开,请检查微博,不要自动重发");return O.data},h=(v,k,O)=>y("PAGE_PUBLISH_PROGRESS",{stage:v,current:k,total:O}),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 k=JSON.parse(v.detail);k.phase==="uploads"&&(n=k),k.phase==="request"&&(a=!0,h("verifying").catch(m)),k.phase==="result"&&p(k).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,k){throw Object.assign(new Error(k),{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(O=>{var z;return((z=O.textContent)==null?void 0:z.trim())||""}).filter(O=>O.length<1e3);v.some(O=>/验证码|安全验证|完成验证/.test(O))&&g("captcha","请在已打开的微博投稿页完成验证并手动发布,Agent 不要重发。"),v.some(O=>/请.*(?:声明|来源|原视频|分类|类型)|我同意|原创.*协议|版权.*协议/.test(O))&&g("publication_settings","微博需要补充来源、分类、内容声明或协议确认,请在原投稿页核对并手动发布。");const k=v.find(O=>/上传失败|发布失败|发送失败|格式不支持|超出.*限制|超过.*限制/.test(O));if(k)throw new Error(k.slice(0,300))},S=async(v,k,O,z)=>{const I=Math.min(Date.now()+k,e.deadline);for(;Date.now()<I;){D();const R=v();if(R)return R;await s(300)}throw z&&g(z,O),new Error(O)},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 k=v.parentElement;for(;k&&k!==document.body;){if(Array.from(k.querySelectorAll('button,[role="button"]')).some(O=>{var z;return o(O)&&/^(?:发送|发布|发布微博|立即发布)$/.test(((z=O.textContent)==null?void 0:z.trim())||"")}))return k;k=k.parentElement}throw new Error("未能定位本次微博的完整投稿表单,已停止发布")},l=(v,k)=>{var O,z;if(v.maxLength>0&&k.length>v.maxLength)throw new Error(`微博输入内容超过页面 ${v.maxLength} 字限制,未截断发布`);(z=(O=Object.getOwnPropertyDescriptor(v instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:O.set)==null||z.call(v,k),v.dispatchEvent(new Event("input",{bubbles:!0})),v.dispatchEvent(new Event("change",{bubbles:!0}))},_=async(v,k)=>{const O=new DataTransfer,z=k.reduce((R,L)=>R+L.size,0);let I=0;await h("transferring_media",0,z);for(const R of k){const L=v.toLowerCase().split(",").map(B=>B.trim());if(v&&!L.some(B=>B==="*/*"||B===R.type||B===`${R.type.split("/")[0]}/*`||B==="image/jpg"&&R.type==="image/jpeg"||B.startsWith(".")&&R.name.toLowerCase().endsWith(B)))throw new Error(`微博当前控件不接受 ${R.name} 的格式`);const N=[];for(let B=0;B<R.size;B+=1024*1024){D();const P=Math.min(1024*1024,R.size-B),A=await y("PAGE_PUBLISH_READ_ASSET",{assetId:R.id,offset:B,length:P});D();const q=Uint8Array.from(atob(A.base64),j=>j.charCodeAt(0));if(q.length!==P)throw new Error("微博素材读取不完整,已停止上传");N.push(q.buffer),I+=q.length,(B%(8*1024*1024)===0||I===z)&&await h("transferring_media",I,z)}O.items.add(new File(N,R.name,{type:R.type}))}return O},$=async(v,k)=>{if(!v.multiple&&k.length>1)throw new Error("微博当前上传控件不接受多张图片,未丢弃素材发布");const O=await _(v.accept,k);D(),v.files=O.files,v.dispatchEvent(new Event("change",{bubbles:!0})),await h("uploading_media")},x=async(v,k)=>{const O=await _("",[k]);D();const z=document.createElement("input");z.type="file",z.hidden=!0,z.setAttribute("data-writedock-video",e.channel),z.files=O.files,document.body.append(z),await h("uploading_media");const I=()=>!o(v)||n.videos.length>0;try{for(let R=0;R<5&&!I();R++){await s(R?6e3:2e3),D(),I()||window.dispatchEvent(new Event(`${t}:drop-video`));for(let L=0;L<20&&!I();L++)await s(300),D()}if(!I())throw new Error(`微博视频页没有响应拖放上传(${z.getAttribute("data-writedock-drop-status")||"页面脚本未执行"}),未提交发布`)}finally{z.remove()}};return(async()=>{var R;await h("checking_auth");const v=e.post;if(v.kind==="image"){const L=await S(d,6e4,"未找到微博普通发博输入框,请确认已登录;页面改版时需更新适配");L.value.trim()&&g("publication_settings","当前微博输入框已有未发内容,未覆盖原内容,请在这个页面自行核对。");const N=f(L);l(L,e.text);const B=await S(()=>Array.from(N.querySelectorAll('input[type="file"]')).find(P=>/image|\.(?:jpe?g|png|gif|webp)/i.test(P.accept)),2e4,"未找到本次普通微博的图片上传控件");await $(B,v.images),await S(()=>n.pictures.length>=v.images.length,5*6e4,"微博图片上传未全部确认,未提交发布,请检查原页面")}else{const L=await S(()=>Array.from(document.querySelectorAll('[id^="area_video"]')).find(o),6e4,"未找到微博视频上传区域,请确认已登录视频发布页"),N=d();N!=null&&N.value.trim()&&g("publication_settings","微博视频页面已有未发正文,未覆盖原内容,请在当前页面自行核对。"),await x(L,v.video),await S(()=>n.videos.length===1,15*6e4,"微博视频上传尚未完成,未提交发布,请检查原投稿页");const B=await S(()=>Array.from(document.querySelectorAll('input[type="text"]')).find(K=>o(K)&&/填写标题|视频标题/.test(K.placeholder)),6e4,"未找到微博视频标题输入框");l(B,v.title);const P={original:"原创",secondary:"二创",repost:"转载"}[v.weiboVideoCreation],A=Array.from(document.querySelectorAll("label.woo-radio-main")).find(K=>{var J;return o(K)&&((J=K.textContent)==null?void 0:J.trim())===P}),q=A==null?void 0:A.querySelector('input[type="radio"]');(!A||!q||q.disabled)&&g("publication_settings",`当前微博页面无法选择“${P}”,请检查账号可用类型并手动处理。`),D(),q.checked||A.click(),await s(300),D(),q.checked||g("publication_settings","微博视频创作类型未确认选中,请在当前页面核对。");const j=await S(d,6e4,"未找到微博视频正文输入框");if(l(j,e.text),v.cover){const K=Array.from(document.querySelectorAll('a,button,[role="button"]')).find(he=>{var te;return c(he)&&((te=he.textContent)==null?void 0:te.trim())==="上传封面"});K||g("cover_required","当前页面未找到视频封面上传入口,未使用默认封面替代,请在原页面设置指定封面后手动发布。");const J=new Set(document.querySelectorAll('input[type="file"]'));D(),K.click();const ee=await S(()=>Array.from(document.querySelectorAll('input[type="file"]')).find(he=>!J.has(he)&&/image|\.(?:jpg|jpeg|png)/i.test(he.accept)),2e4,"未找到新打开的视频封面控件,请在原页面手动设置封面并发布","cover_required"),X=ee.closest('.wbpro-layer,.woo-modal-main,[role="dialog"]');(!X||!o(X))&&g("cover_required","视频封面编辑窗口未就绪,请在原页面设置封面并手动发布。"),await $(ee,[v.cover]),await S(()=>Array.from(X.querySelectorAll(".cropper-canvas img")).find(he=>he.src.startsWith("blob:")&&he.complete&&he.naturalWidth>0),2e4,"本次封面尚未载入裁切区,请在原页面完成封面并手动发布","cover_required");const re=await S(()=>b(X).find(he=>{var te;return((te=he.textContent)==null?void 0:te.trim())==="完成"}),2e4,"视频封面需要手动调整,请在原页面完成封面并手动发布","cover_required");D(),window.dispatchEvent(new Event(`${t}:cover`)),re.click(),await S(()=>n.covers.length>0&&!o(X),6e4,"视频封面上传或应用未确认,请在原页面核对后手动发布","cover_required")}if(B.value!==v.title)throw new Error("微博页面视频标题被修改或截断,已停止发布")}const k=await S(d,3e4,"未找到微博正文,未提交发布"),O=f(k),z=await S(()=>b(O).find(L=>{var N;return/^(?:发送|发布|发布微博|立即发布)$/.test(((N=L.textContent)==null?void 0:N.trim())||"")}),5*6e4,"微博发布按钮尚不可用,可能需要补充来源、内容声明或分类,请在原页面核对并手动发布","publication_settings");if(D(),k.value.replace(/\r\n?/g,`
40
- `).trim()!==e.text.replace(/\r\n?/g,`
41
- `).trim())throw new Error("微博页面正文与本次稿件不一致,已停止发布");if(e.rehearsal){((R=localStorage.getItem("from_content"))==null?void 0:R.replace(/\s/g,""))===e.text.replace(/\s/g,"")&&localStorage.removeItem("from_content"),await p({success:!1,publicationState:"rehearsed"});return}if(await h("publishing"),D(),!z.isConnected||!c(z))throw new Error("微博发布控件状态变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,z.click();const I=Math.min(Date.now()+12e4,e.deadline);for(;!i&&!r&&Date.now()<I;)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 vt=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 vt(new Uint8Array(await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t))))};async function kt(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=vt(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=vt(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=U=>U.replace(/[\s\u200b-\u200d\ufeff]/g,""),i=U=>typeof U=="string"?JSON.parse(U):U,a=[],n=U=>{a.includes(U)||a.push(U)},s=U=>Array.isArray(U)?U.length>0:U&&typeof U=="object"?Object.keys(U).length>0:!!U,o=(U,V)=>{try{return i(U)}catch{n(`无法解析小红书${V},已依据提交前的页面核对放行`);return}},c=new Set,y=new Set,h=new Set,w=new Map;let m=!1,p=!1,u=!1,g=!1,D=!1,S=0,b,d=!1,f=0,l;const _=U=>{if(typeof U!="string")return"";if(/^spectrum\/[A-Za-z0-9_/-]{1,480}$/.test(U))return U;try{const V=new URL(U);return V.protocol==="https:"&&/(?:^|\.)(?:xhscdn|xiaohongshu)\.com$/.test(V.hostname)&&/^\/spectrum\/[A-Za-z0-9_/-]{1,480}$/.test(V.pathname)?V.pathname.slice(1):""}catch{return""}},$=U=>{const V=JSON.stringify({...U,jobId:e.id});try{sessionStorage.setItem(t,V)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:V}))},x=()=>{u||$({phase:"state",uploads:y.size,layoutReady:D,renderedCount:S,firstFrameReady:d,renderUploads:[...h].filter(U=>y.has(U)).length})},E=U=>{u||(u=!0,$({phase:"result",...a.length?{warnings:a}:{},...U}))},v=(U,V)=>E({success:!1,publicationState:"needs_user_action",manualReason:U,message:V}),k=(U,V="publication_settings")=>{throw v(V,`${U}请在已打开的原投稿页核对并手动发布,Agent 不要重新提交。`),new Error("WriteDock 已停止小红书自动提交")},O=(U,V)=>{try{const T=new URL(V,location.href),F=U.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},z=U=>{const V=[],T=[];let F=!1;const Z=G=>{var ne;if(!(!G||typeof G!="object")){if(Array.isArray(G)){G.forEach(Z);return}if(G.type!=="articleTitle"){if(G.type==="text"&&typeof G.text=="string"&&V.push(G.text),G.type==="image"){const se=(ne=G.attrs)==null?void 0:ne.imgs;if(!Array.isArray(se)||!se.length)n("小红书长文的图片节点结构与抓包时不同");else for(const fe of se){const W=_(fe.src);(!W||!y.has(W)||!(fe.width>0&&fe.height>0))&&n("小红书长文有图片未匹配本次观察到的上传记录"),T.push(W)}}/video|audio|iframe|embed/i.test(String(G.type||""))&&(F=!0),Array.isArray(G.content)&&G.content.forEach(Z)}}};return Z(U),F?k("长文包含未接入的视频或嵌入内容,已停止排版和发布。"):V.length&&r(V.join(""))!==r(e.content)?k("长文正文与本次稿件不一致,已停止排版和发布。"):(!V.length&&r(e.content)&&n("小红书长文请求中未读到正文字段,已依据提交前的编辑器核对放行"),T.length&&T.length!==e.imageCount?k("长文插图数量与本次稿件不一致,已停止排版和发布。"):(!T.length&&e.imageCount&&n("小红书长文请求中未读到图片字段,已依据提交前的编辑器核对放行"),l!=null&&l.length&&T.length&&T.join("|")!==l.join("|")?k("长文排版前后的插图或顺序发生变化,已停止发布。"):T))},I=U=>r(U.replace(/\[话题\]#/g,"")),R=(U,V)=>{var W,ie,Y,pe,le,ce,ge,we,ke,qt,Mt,Bt;if(!U)return;const T=U.operation;if(T==="other_publish")return k("页面尝试修改已有笔记或使用未接入的发布接口。");if(["layout","preview","render"].includes(T)){if(e.mode!=="article"||!g||u||Date.now()>=e.deadline)return k("小红书长文尚未完成核对,已停止排版提交。");const de=o(V,"长文排版参数");if(T==="layout"){typeof(de==null?void 0:de.title)=="string"&&r(de.title)!==r(e.title)&&n(`小红书长文排版请求的标题为「${de.title.slice(0,40)}」,与稿件不同`),typeof(de==null?void 0:de.title)!="string"&&n("小红书长文排版请求中未读到标题字段");const oe=o(de==null?void 0:de.content,"长文正文");oe!==void 0&&(l=z(oe))}else{const oe=o(de==null?void 0:de.article_content,"长文排版内容"),ue=(ie=(W=oe==null?void 0:oe.config)==null?void 0:W.cover)==null?void 0:ie.titleText;if(typeof ue=="string"&&r(ue)!==r(e.title)&&n(`小红书长文封面标题为「${ue.slice(0,40)}」,与稿件不同`),Array.isArray(oe==null?void 0:oe.cards)?l=z(oe.cards):n("小红书长文排版请求中未读到分页数据"),T==="render"){if(!D||S)return k("长文排版尚未完成或页面尝试重复生成,已停止发布。");Number.isSafeInteger(de==null?void 0:de.album_id)&&de.album_id>0?b=de.album_id:n("小红书长文生成请求中未读到有效的 album_id")}}return}if(T!=="publish")return;if(e.rehearsal)return k("演练不提交发布,已拦截小红书发布请求。");if(u||!m||p||Date.now()>=e.deadline)return k("稿件尚未核对完成或页面尝试重复发送,已停止提交。");const F=o(V,"发布请求"),Z=F==null?void 0:F.common;if(!Z||typeof Z!="object"){n("小红书发布请求结构与抓包时不同,已依据提交前的页面核对放行"),p=!0,m=!1,$({phase:"request"});return}const G=o(Z.business_binds,"发布设置"),ne=o((Y=Z.capa_trace_info)==null?void 0:Y.contextJson,"排版记录"),se=Z.privacy_info;if(Z.note_id)return k("发布请求指向已有笔记。");if(typeof Z.title=="string"&&r(Z.title)!==r(e.title))return k(`发布请求的标题「${Z.title.slice(0,40)}」与本次稿件不一致。`);if((se==null?void 0:se.type)!==void 0&&se.type!==0||s(se==null?void 0:se.user_ids)||s(Z.ats)||s(Z.biz_relations)||s(Z.goods_info))return k("公开范围、提及用户或商业关联需要人工核对。");if(s(G==null?void 0:G.notePostTiming)||s(G==null?void 0:G.noteOrderBind)||s((pe=G==null?void 0:G.noteCollectionBind)==null?void 0:pe.id)||s((le=G==null?void 0:G.noteSketchCollectionBind)==null?void 0:le.id)||s(G==null?void 0:G.optionRelationList))return k("定时、合集或内容声明需要人工核对。");const fe=Z.hash_tag;if(Array.isArray(fe)&&fe.length&&(fe.length!==e.tags.length||fe.some(de=>!e.tags.includes((de==null?void 0:de.name)||(de==null?void 0:de.topic_name)))))return k("发布话题与 Agent 提供的话题不一致。");if(Z.type!==(e.mode==="video"?"video":"normal")&&n(`小红书笔记 type=${String(Z.type)},与抓包时不同`),((se==null?void 0:se.op_type)!==1||(se==null?void 0:se.type)===void 0)&&n("小红书公开范围字段与抓包时不同"),((G==null?void 0:G.version)!==1||(G==null?void 0:G.noteId)!==0||(G==null?void 0:G.bizType)!==0)&&n("小红书 business_binds 的版本或类型与抓包时不同"),((ce=G==null?void 0:G.interactionPermissionBind)==null?void 0:ce.commentPermission)!==0&&n("小红书评论权限字段与抓包时不同"),typeof Z.title!="string"&&n("小红书发布请求中未读到标题字段"),e.mode==="article"){const de=(ge=F.image_info)==null?void 0:ge.images,oe=ne==null?void 0:ne.longTextToImage,ue=Array.isArray(de)?de.map(Xe=>Xe.file_id):[];if(!S)return k("长文分页图片尚未生成。");if(ue.length&&ue.length!==S)return k("最终笔记的图片数量与本次排版结果不一致。");ue.length||n("小红书发布请求中未读到长文图片字段"),ue.some(Xe=>typeof Xe!="string"||!h.has(Xe)||!y.has(Xe))&&n("小红书长文图片未匹配本次观察到的上传记录"),((oe==null?void 0:oe.albumId)!==b||!Array.isArray(oe==null?void 0:oe.imageFileIds)||oe.imageFileIds.join("|")!==ue.join("|"))&&n("小红书长文排版记录与抓包时不同"),(Z.desc!==""||F.video_info!=null)&&n("小红书长文的 desc 或 video_info 与抓包时不同")}else{const de=[e.content,...e.tags.map(oe=>`#${oe}`)].filter(Boolean).join(" ");if(typeof Z.desc=="string"&&I(Z.desc)!==r(de))return k("正文或话题与本次任务不一致。");if(typeof Z.desc!="string"&&n("小红书发布请求中未读到正文字段"),ne!=null&&ne.longTextToImage&&n("小红书普通笔记请求带有长文排版记录"),e.mode==="image"){const oe=(we=F.image_info)==null?void 0:we.images;if(Array.isArray(oe)&&oe.length!==e.imageCount)return k("图文图片数量与本次投稿不一致。");Array.isArray(oe)?oe.some(ue=>!c.has(ue.file_id)||!y.has(ue.file_id)||!(ue.width>0&&ue.height>0))&&n("小红书图片未匹配本次观察到的上传记录"):n("小红书发布请求中未读到图片字段"),F.video_info!=null&&n("小红书图文请求带有 video_info")}else{const oe=F.video_info,ue=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)||((ke=oe.segments)==null?void 0:ke.count)!==1||((qt=oe.segments)==null?void 0:qt.need_slice)!==!1)&&n("小红书视频分段字段与抓包时不同"),s(oe.timelines)&&n("小红书视频带有时间线设置"),e.explicitCover&&((Mt=ue==null?void 0:ue.frame)==null?void 0:Mt.is_upload)===!1)return k("显式提供的视频封面尚未应用。","cover_required");if(!e.explicitCover&&((Bt=ue==null?void 0:ue.frame)==null?void 0:Bt.is_upload)===!0)return k("页面使用了非第一帧的上传封面,与本次任务不一致。","cover_required");ue!=null&&ue.frame||n("小红书发布请求中未读到封面来源字段"),ue&&(ue.file_id!==ue.fileid||!c.has(ue.file_id)||!y.has(ue.file_id)||!(ue.width>0&&ue.height>0))&&n("小红书视频封面未匹配本次观察到的上传记录")}}}p=!0,m=!1,$({phase:"request"})},L=(U,V,T)=>{var ne,se,fe,W,ie;if(u)return;const{operation:F,url:Z}=U,G=V>=200&&V<300;if(["upload","part","multipart","complete"].includes(F)){const Y=_(Z.href);if(!G||!c.has(Y))return;if(F==="upload"&&y.add(Y),F==="multipart"){const le=new DOMParser().parseFromString(String(T||""),"application/xml"),ce=(ne=le.querySelector("UploadId"))==null?void 0:ne.textContent;ce&&w.set(Y,{uploadId:ce,parts:new Set})}const pe=w.get(Y);if(pe&&pe.uploadId===Z.searchParams.get("uploadId")){if(F==="part"){const le=Number(Z.searchParams.get("partNumber"));Number.isInteger(le)&&le>0&&pe.parts.add(le)}F==="complete"&&pe.parts.size&&!/<Error(?:\s|>)/i.test(String(T||""))&&y.add(Y)}x();return}try{const Y=i(T),pe=String((Y==null?void 0:Y.msg)||(Y==null?void 0:Y.message)||"");if(/验证码|安全验证|验证后|完成验证|旋转.*(?:图片|验证)|转动.*图片|captcha/i.test(pe)){v("captcha","小红书要求人工验证,请在已打开的原投稿页完成验证并手动发布,Agent 不要重发。");return}if(/原创声明|我已阅读|同意.*协议/.test(pe)){v("agreement","小红书要求确认声明或协议,请在原投稿页阅读、自行决定并手动发布。");return}if(F==="publish"){const ce=(se=Y==null?void 0:Y.data)==null?void 0:se.id,ge=p&&G&&(Y==null?void 0:Y.success)===!0&&(Y==null?void 0:Y.result)===0&&(Y.code===void 0||Y.code===0)&&typeof ce=="string"&&/^[a-f0-9]{24}$/.test(ce);E({success:ge,publicationState:ge?"submitted":"unknown",...ge?{responseConfirmed:!0,postId:ce,postUrl:`https://www.xiaohongshu.com/explore/${ce}`}:{error:"小红书发布回执未能确认成功,请检查原稿件,不要自动重发。"}});return}if(!(G&&(Y==null?void 0:Y.success)===!0&&(Y.code===void 0||Y.code===0)))return;if(F==="permit"&&Array.isArray((fe=Y.data)==null?void 0:fe.uploadTempPermits))for(const ce of Y.data.uploadTempPermits)for(const ge of Array.isArray(ce.fileIds)?ce.fileIds:[]){const we=_(ge);we&&(c.add(we),S&&h.add(we))}if(F==="preview"&&(D=!0),F==="render"){const ce=(W=Y.data)==null?void 0:W.article_images;if(!Array.isArray(ce)||!ce.length){n("小红书长文生成接口未返回分页图片字段"),x();return}ce.some(ge=>{try{const we=new URL(String(ge));return we.protocol!=="https:"||!/(?:^|\.)xhscdn\.com$/.test(we.hostname)||!we.pathname.startsWith("/mediaai/")||!!we.username||!!we.password}catch{return!0}})&&n("小红书长文分页图片地址与抓包时不同"),S=ce.length}F==="transcode"&&((ie=Y.data)==null?void 0:ie.has_first_frame)===!0&&typeof Y.data.first_frame_file_id=="string"&&(d=!0),x()}catch{F==="publish"&&E({success:!1,publicationState:"unknown",error:"小红书发布回执无法解析,请检查平台,不要自动重发。"})}},N=window.fetch,B=async function(U,V){const T=O((V==null?void 0:V.method)||(U instanceof Request?U.method:"GET"),U instanceof Request?U.url:String(U)),F=T&&["publish","other_publish","layout","preview","render"].includes(T.operation)?(V==null?void 0:V.body)??(U instanceof Request?await U.clone().text():void 0):void 0;R(T,F);try{const Z=await N.call(window,U,V);return T&&!["upload","part","complete"].includes(T.operation)?L(T,Z.status,await Z.clone().text()):T&&L(T,Z.status,T.operation==="complete"?await Z.clone().text():""),Z}catch(Z){throw(T==null?void 0:T.operation)==="publish"&&E({success:!1,publicationState:"unknown",error:"小红书发布连接中断,请检查平台,不要自动重发。"}),Z}},P=XMLHttpRequest.prototype,A=P.open,q=P.send,j=new WeakMap,K=function(U,V,...T){return j.set(this,O(U,String(V))),Reflect.apply(A,this,[U,V,...T])},J=function(U){const V=j.get(this)||null;return R(V,U),V&&this.addEventListener("loadend",()=>{try{const T=["upload","part"].includes(V.operation)?"":this.responseType==="json"?this.response:this.responseType==="document"?new XMLSerializer().serializeToString(this.responseXML):this.responseText;L(V,this.status,T)}catch{V.operation==="publish"&&L(V,this.status,void 0)}},{once:!0}),q.call(this,U)},ee=HTMLInputElement.prototype.click,X=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)},re=()=>{!u&&!p&&(m=!0)},he=()=>{!u&&e.mode==="article"&&(g=!0)},te=()=>{u||(f=Date.now()+1e4)},me=()=>{f=0},C=()=>{e.rehearsal&&E({success:!1,publicationState:"rehearsed"})},H=()=>{window.fetch===B&&(window.fetch=N),P.open===K&&(P.open=A),P.send===J&&(P.send=q),HTMLInputElement.prototype.click===X&&(HTMLInputElement.prototype.click=ee),clearTimeout(M),window.removeEventListener(`${t}:arm`,re),window.removeEventListener(`${t}:layout`,he),window.removeEventListener(`${t}:rehearsed`,C),window.removeEventListener(`${t}:capture-image`,te),window.removeEventListener(`${t}:release-image`,me),window.removeEventListener(`${t}:read`,x),window.removeEventListener(`${t}:stop`,H),document.querySelectorAll(`[data-writedock-xhs-transient="${e.channel}"]`).forEach(U=>U.remove())};window.fetch=B,P.open=K,P.send=J,HTMLInputElement.prototype.click=X,window.addEventListener(`${t}:arm`,re),window.addEventListener(`${t}:layout`,he),window.addEventListener(`${t}:rehearsed`,C),window.addEventListener(`${t}:capture-image`,te),window.addEventListener(`${t}:release-image`,me),window.addEventListener(`${t}:read`,x),window.addEventListener(`${t}:stop`,H,{once:!0});const M=setTimeout(H,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(H=>setTimeout(H,C)),p=async(C,H={})=>{const M=await chrome.runtime.sendMessage({type:C,jobId:e.id,jobSecret:e.secret,...H});if(!M||M.error)throw new Error((M==null?void 0:M.error)||"扩展后台已断开,请检查小红书,不要自动重发");return M.data},u=(C,H,M)=>p("XHS_PUBLISH_PROGRESS",{stage:C,current:H,total:M}),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),S=()=>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 H=JSON.parse(C.detail);if(r||i||H.jobId!==e.id)return;H.phase==="state"&&(s=H.uploads,o=H.layoutReady,c=H.renderedCount,y=H.renderUploads,h=H.firstFrameReady),H.phase==="request"&&(n=!0,u("verifying").catch(d)),H.phase==="result"&&f(H).catch(d)}catch{}};window.addEventListener(t,l),window.addEventListener(`${t}:cancel`,d,{once:!0});function _(C,H){throw Object.assign(new Error(H),{manualReason:C})}const $=()=>{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(M=>{var U;return((U=M.textContent)==null?void 0:U.trim())||""}).filter(M=>M.length<1500);C.some(M=>/验证码|安全验证|拖动.*(?:图片|滑块)|旋转.*图片|转动.*图片/.test(M))&&_("captcha","请在已打开的小红书原投稿页完成人工验证并手动发布,Agent 不要重发。"),C.some(M=>/我已阅读|我同意|原创声明|同意.*协议|确认.*声明/.test(M))&&_("agreement","小红书要求确认内容声明或协议,请在原投稿页阅读、自行决定并手动发布。"),C.some(M=>/请选择封面|请设置封面|封面不能为空/.test(M))&&_("cover_required","小红书要求补充封面,请在原投稿页设置并手动发布。"),C.some(M=>/请选择|请设置|实名认证|绑定手机|补充.*(?:声明|来源|信息)/.test(M))&&_("publication_settings","小红书要求补充发布设置或账号信息,请在原投稿页核对并手动发布。");const H=C.find(M=>/上传失败|发布失败|格式不支持|超出|超过|不能为空|图片过大/.test(M));if(H)throw new Error(H.slice(0,300))},x=async(C,H,M)=>{const U=Math.min(Date.now()+H,e.deadline);for(;Date.now()<U;){$();const V=C();if(V)return V;await m(300)}throw new Error(M)},E=()=>window.dispatchEvent(new Event(`${t}:read`)),v=()=>Array.from(document.querySelectorAll('input[placeholder*="标题"],textarea[placeholder*="标题"],[contenteditable="true"][data-placeholder*="标题"]')).find(g),k=()=>Array.from(document.querySelectorAll('.ProseMirror[contenteditable="true"],div[contenteditable="true"]')).find(C=>g(C)&&C!==v()&&!C.closest('[class*="title-input"],[class*="titleInput"]')),O=C=>C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement?C.value:C.textContent||"",z=C=>{C.focus();const H=document.createRange();H.selectNodeContents(C);const M=getSelection();M==null||M.removeAllRanges(),M==null||M.addRange(H)},I=(C,H,M)=>{const U=new DataTransfer;U.setData("text/plain",H),M!==void 0&&U.setData("text/html",M),C.dispatchEvent(new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:U}))},R=C=>{var H,M;if(C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement){if(C.maxLength>0&&e.title.length>C.maxLength)throw new Error(`小红书当前标题最多 ${C.maxLength} 字,未截断发布`);(M=(H=Object.getOwnPropertyDescriptor(C instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype,"value"))==null?void 0:H.set)==null||M.call(C,e.title),C.dispatchEvent(new Event("input",{bubbles:!0})),C.dispatchEvent(new Event("change",{bubbles:!0}))}else z(C),I(C,e.title);if(O(C)!==e.title)throw new Error("标题未能完整写入小红书编辑器,未提交发布")},L=(C,H)=>!C.accept||C.accept.toLowerCase().split(",").map(M=>M.trim()).some(M=>M==="*/*"||M===H.type||M===`${H.type.split("/")[0]}/*`||M==="image/jpg"&&H.type==="image/jpeg"||M.startsWith(".")&&H.name.toLowerCase().endsWith(M)),N=async C=>{const H=[];await u("transferring_media",0,C.size);for(let M=0;M<C.size;M+=1024*1024){$();const U=Math.min(1024*1024,C.size-M),V=await p("XHS_READ_ASSET",{assetId:C.id,offset:M,length:U}),T=Uint8Array.from(atob(V.base64),F=>F.charCodeAt(0));if(T.length!==U)throw new Error("小红书素材传输不完整,已停止投稿");H.push(T.buffer),(M%(8*1024*1024)===0||M+U===C.size)&&await u("transferring_media",M+U,C.size)}return new File(H,C.name,{type:C.type})},B=(C,H)=>{if($(),!C.multiple&&H.length>1)throw new Error("当前小红书上传控件不接受多张图片,未丢弃图片后继续发布");if(H.some(U=>!L(C,U)))throw new Error("小红书当前上传控件不接受此素材格式");const M=new DataTransfer;H.forEach(U=>M.items.add(U)),C.files=M.files,C.dispatchEvent(new Event("change",{bubbles:!0}))},P=["图片","插入图片","添加图片"],A=()=>Array.from(document.querySelectorAll('button,[role="button"],[title],[aria-label],[data-tooltip],.toolbar-item')).find(C=>{var H;return D(C)&&P.includes(C.getAttribute("title")||C.getAttribute("aria-label")||C.getAttribute("data-tooltip")||((H=C.textContent)==null?void 0:H.trim())||"")});let q;const j=async C=>{const H=()=>Array.from(document.querySelectorAll('.menu-tooltip,[role="tooltip"],.d-popover-tooltip')).filter(g),M=new Set(H());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 U=H(),V=U.filter(F=>!M.has(F)),T=(V.length?V:U.slice(-1)).map(F=>{var Z;return((Z=F.textContent)==null?void 0:Z.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},K=async()=>{const C=Math.min(Date.now()+1e4,e.deadline);for(;Date.now()<C;){$();const H=A();if(H)return H;if(q!=null&&q.isConnected&&D(q))return q;for(const M of Array.from(document.querySelectorAll(".menu-items-container .menu-item,.menu-items-container button")).filter(D))if(P.includes(await j(M)))return q=M,M;await m(500)}throw new Error("未找到小红书长文的原生插图按钮,未提交发布")},J=async C=>{const H=new Set(document.querySelectorAll('input[type="file"]'));document.querySelectorAll(`[data-writedock-xhs-input="${e.channel}"]`).forEach(M=>M.removeAttribute("data-writedock-xhs-input")),window.dispatchEvent(new Event(`${t}:capture-image`)),$(),C.click();try{return await x(()=>document.querySelector(`input[data-writedock-xhs-input="${e.channel}"]`)||Array.from(document.querySelectorAll('input[type="file"]')).find(M=>/image|\.(?:png|jpe?g|webp)/i.test(M.accept)&&(!H.has(M)||!!M.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(H=>{var M;return D(H)&&C.includes(((M=H.textContent)==null?void 0:M.trim())||"")}).find(H=>!Array.from(H.children).some(M=>{var U;return C.includes(((U=M.textContent)==null?void 0:U.trim())||"")})),X=C=>{const H=ee(C);return H?H.closest('button,[role="button"]')||H:void 0},re=async()=>{const C=Math.min(Date.now()+45e3,e.deadline);let H=!1,M=!1;for(;Date.now()<C;){if($(),v()&&k())return;const U=X(["新的创作","新建长文","开始创作"]);if(U&&!M){M=!0,U.click(),await m(1500);continue}if(!U&&!H){const V=X(["写长文"]);if(V){H=!0,V.click(),await m(1e3);continue}}await m(500)}throw new Error(M?"已点击「新的创作」,但小红书长文编辑器未出现,请确认账号已开通长文":"未找到小红书「写长文 → 新的创作」入口,请确认已登录创作者后台且账号可发长文")},he=async()=>{var Z;const C=e.article;await u("preparing_article"),await re();const H=await x(v,45e3,"未找到小红书长文标题输入框,请确认已登录创作者后台"),M=await x(k,3e4,"未找到小红书长文正文编辑器");(w(O(H))||w(M.textContent||"")||M.querySelector("img"))&&_("publication_settings","小红书长文编辑器已有内容,未覆盖原稿,请在当前页面自行核对。");const U=new DOMParser().parseFromString(C.markup,"text/html").body.textContent||"";R(H),z(M),I(M,U,C.markup),await x(()=>C.images.every(G=>{var ne;return((ne=M.textContent)==null?void 0:ne.split(G.marker).length)===2})&&w(M.textContent||"")===w(U),1e4,"小红书长文未能完整写入,已停止发布");for(let G=0;G<C.images.length;G++){const ne=C.images[G],se=await p("XHS_READ_ARTICLE_IMAGE",{imageId:ne.id}),fe=Uint8Array.from(atob(se.base64),ge=>ge.charCodeAt(0)),W={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[se.type];if(!W||!fe.length)throw new Error("小红书长文图片读取失败");$(),M.focus();const ie=document.createTreeWalker(M,NodeFilter.SHOW_TEXT);let Y,pe=!1;for(;Y=ie.nextNode();){const ge=(Y.textContent||"").indexOf(ne.marker);if(ge<0)continue;const we=document.createRange();we.setStart(Y,ge),we.setEnd(Y,ge+ne.marker.length);const ke=getSelection();ke==null||ke.removeAllRanges(),ke==null||ke.addRange(we),pe=!0;break}if(!pe)throw new Error("无法定位长文插图位置,未提交发布");const le=await K();if(!document.execCommand("delete")||(Z=M.textContent)!=null&&Z.includes(ne.marker))throw new Error("无法替换长文插图位置,未提交发布");const ce=await J(le);B(ce,[new File([fe],`${ne.id}.${W}`,{type:se.type})]),await u("uploading_images",G,C.images.length),await x(()=>(E(),s>=G+1&&M.querySelectorAll("img").length===G+1),3*6e4,"小红书长文插图未完整上传或插入,已停止排版"),ce.getAttribute("data-writedock-xhs-transient")===e.channel&&ce.remove(),await u("uploading_images",G+1,C.images.length)}if(w(M.textContent||"")!==w(e.content)||C.images.some(G=>{var ne;return(ne=M.textContent)==null?void 0:ne.includes(G.marker)})||M.querySelectorAll("img").length!==e.imageCount||O(H)!==e.title)throw new Error("小红书长文正文或插图不完整,已停止排版");const V=await x(()=>S().find(G=>{var ne;return["一键排版","自动排版"].includes(((ne=G.textContent)==null?void 0:ne.trim())||"")}),3e4,"未找到小红书「一键排版」按钮");window.dispatchEvent(new Event(`${t}:layout`)),$(),V.click(),await x(()=>(E(),o),2*6e4,"小红书长文自动排版未完成,未提交发布");const T=await x(()=>S().find(G=>{var ne;return((ne=G.textContent)==null?void 0:ne.trim())==="下一步"}),3e4,"未找到小红书排版后的「下一步」按钮");$(),T.click(),await x(()=>(E(),c>0&&y>=c),5*6e4,"小红书长文分页图片未完整生成或上传,未提交发布");const F=await x(v,3e4,"小红书长文未进入最终发布页");if(O(F)||R(F),O(F)!==e.title)throw new Error("小红书长文排版后的标题发生变化,已停止发布")},te=async()=>{var fe;const C=e.post,H=await x(()=>Array.from(document.querySelectorAll('input[type="file"]')).find(W=>e.mode==="image"?/image|\.(?:png|jpe?g|webp)/i.test(W.accept):/video|\.(?:mp4|mov|m4v|webm)/i.test(W.accept)),6e4,"未找到对应的小红书图文或视频上传入口,请确认创作者后台已登录"),M=v(),U=k();(M&&w(O(M))||w((U==null?void 0:U.textContent)||"")||U!=null&&U.querySelector("img"))&&_("publication_settings","小红书发布页已有未发内容,未追加素材或覆盖原稿,请在当前页面自行核对。");const V=[];for(const W of e.mode==="image"?C.images:[C.video])V.push(await N(W));B(H,V),await u("uploading_media");const T=await x(v,3*6e4,"上传后未找到小红书标题输入框,请检查素材处理状态"),F=await x(k,3e4,"未找到小红书正文输入区"),Z=O(T).trim(),G=(fe=C.video)==null?void 0:fe.name,ne=e.mode==="video"&&G&&[G,G.replace(/\.[^.]+$/,"")].includes(Z);(w(Z)&&!ne||w(F.textContent||""))&&_("publication_settings","小红书发布页已有文案,未覆盖原稿,请在当前页面自行核对。"),R(T);const se=[e.content,...e.tags.map(W=>`#${W}`)].filter(Boolean).join(`
42
- `);if(se&&(z(F),I(F,se),await m(300),w(F.textContent||"")||(z(F),document.execCommand("insertText",!1,se)),await x(()=>w(F.textContent||"")===w(se),1e4,"小红书正文或话题未能完整写入,已停止发布"),F.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",code:"Escape",bubbles:!0}))),C.cover){const W=await x(()=>document.querySelector("div.noCover.uploadCover")||S().find(le=>{var ce;return/^(?:设置封面|编辑封面|修改封面)$/.test(((ce=le.textContent)==null?void 0:ce.trim())||"")}),12e4,"未找到小红书视频封面入口"),ie=await N(C.cover),Y=await J(W);B(Y,[ie]),await u("uploading_media");const pe=await x(()=>S().find(le=>{var ce;return/^(?:确定|完成)$/.test(((ce=le.textContent)==null?void 0:ce.trim())||"")&&!!le.closest('[role="dialog"],.el-dialog,.d-modal')}),3e4,"请在原投稿页完成视频封面设置,未提交发布");$(),pe.click()}if(await x(()=>(E(),e.mode==="image"?s>=e.imageCount:h&&s>=2),15*6e4,"小红书素材上传、转码或第一帧封面尚未就绪,未提交发布"),O(T)!==e.title||w(F.textContent||"")!==w(se))throw new Error("小红书标题或正文发生变化,已停止发布")},me=async()=>{await u("checking_auth"),e.mode==="article"?await he():await te(),await x(()=>!/笔记图片生成中/.test(document.body.innerText),3*6e4,"小红书笔记图片仍在生成,未提交发布");const C=()=>{var T,F,Z;for(const G of Array.from(document.querySelectorAll("xhs-publish-btn"))){if(G.getAttribute("submit-disabled")==="true"||G.getAttribute("submit-loading")==="true")continue;const ne=(F=(T=chrome.dom)==null?void 0:T.openOrClosedShadowRoot)==null?void 0:F.call(T,G),se=((Z=G.getAttribute("submit-text"))==null?void 0:Z.trim())||"发布",fe=Array.from((ne==null?void 0:ne.querySelectorAll("*"))||[]).find(ie=>{var Y;return((Y=ie.textContent)==null?void 0:Y.trim())===se&&!Array.from(ie.children).some(pe=>{var le;return((le=pe.textContent)==null?void 0:le.trim())===se})}),W=(fe==null?void 0:fe.closest('button,[role="button"]'))||fe;if(W&&D(W))return W}},H=await x(()=>C()||S().find(T=>{var F;return/^(?:发布|立即发布)$/.test(((F=T.textContent)==null?void 0:F.trim())||"")}),6e4,"小红书发布按钮尚不可用,请检查素材或账号要求");if(e.rehearsal){$(),window.dispatchEvent(new Event(`${t}:rehearsed`)),await m(1e3),!i&&!r&&await f({success:!1,publicationState:"rehearsed"});return}const M=new Set(S());if(await u("publishing"),$(),!H.isConnected||!D(H))throw new Error("小红书发布控件发生变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,H.click();const U=Math.min(Date.now()+12e4,e.deadline);let V=!1;for(;!r&&!i&&Date.now()<U;){if($(),!n&&!V){const T=S().find(F=>{var Z;return!M.has(F)&&/^(?:确认发布|确定发布)$/.test(((Z=F.textContent)==null?void 0:Z.trim())||"")&&!!F.closest('[role="dialog"],.el-dialog,.d-modal')});T&&(V=!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&&me().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 Se(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 Je(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 Ge=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,S]=i[e.platform];return p.toUpperCase()==="POST"&&D.test(g.origin)&&g.pathname===S}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,_,$,x,E,v,k,O,z,I;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 R=(l=g==null?void 0:g.data)==null?void 0:l.dyn_id_str;if(b&&(g==null?void 0:g.code)===0&&typeof R=="string"&&/^\d{1,24}$/.test(R))return{kind:"success",postId:R,postUrl:`https://www.bilibili.com/opus/${R}`};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 R=($=g==null?void 0:g.data)==null?void 0:$.id;if(b&&(g==null?void 0:g.success)===!0&&(g==null?void 0:g.result)===0&&typeof R=="string"&&/^[a-f0-9]{24}$/.test(R))return{kind:"success",postId:R,postUrl:`https://www.xiaohongshu.com/explore/${R}`};break}case"weibo":{if(b&&(g==null?void 0:g.ok)===1&&!g.error){const R=(x=g.data)==null?void 0:x.mblogid,L=String(((v=(E=g.data)==null?void 0:E.user)==null?void 0:v.idstr)??((O=(k=g.data)==null?void 0:k.user)==null?void 0:O.id)??"");return{kind:"success",...typeof((z=g.data)==null?void 0:z.idstr)=="string"?{postId:g.data.idstr}:{},postUrl:typeof R=="string"&&/^\d+$/.test(L)?`https://weibo.com/${L}/${R}`:"https://weibo.com"}}break}case"weibo-article":if(b&&(g==null?void 0:g.code)===1e5&&typeof((I=g.data)==null?void 0:I.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(S=>S.clone().text().then(b=>o(s(S.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 Ve(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 Ae=new Map,gt=({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:De(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(!Ae.has(a)||p&&!_&&!l.success)return;if(!_&&!i&&!p&&Ge(l)){p=!0,clearTimeout(S),Ve({tabId:w,platform:"xiaohongshu",channel:s,url:f.editUrl,message:"小红书要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>Ae.has(a),progress:t,onReceipt:k=>{f.attempted=!0,u(k,!0)},onHandOff:()=>u(l,!0)});return}Ae.delete(a),clearTimeout(S),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:k=>{window.dispatchEvent(new Event(`${k}:cancel`)),window.dispatchEvent(new Event(`${k}:stop`)),sessionStorage.removeItem(k)},args:[`writedock-xhs-${s}`]}).catch(()=>{});let $="";try{const k=new URL(l.postUrl||"");k.origin==="https://www.xiaohongshu.com"&&/^\/explore\/[a-f0-9]{24}$/.test(k.pathname)&&l.postId===k.pathname.split("/").pop()&&($=k.href)}catch{}if(i&&l.publicationState==="rehearsed"){Se(w,Je("xiaohongshu",f.editUrl),l.warnings).then(m);return}const x=!i&&f.attempted&&l.success===!0&&l.publicationState==="submitted"&&l.responseConfirmed===!0&&!!$,E=l.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(l.manualReason||""),v=String(l.message||"请在已打开的小红书原投稿页核对内容、完成平台要求并手动发布,Agent 不要重新提交。").slice(0,1e3);Se(w,{platform:"xiaohongshu",success:x,draftOnly:!1,publicationState:x?"submitted":E?"needs_user_action":f.attempted?"unknown":"failed",postUrl:x?$:f.editUrl,timestamp:Date.now(),...x?{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,_,$)=>{var x,E;l!==w||!Ae.has(a)||((x=$.url)!=null&&x.startsWith("https://creator.xiaohongshu.com/publish/publish")&&(f.editUrl=$.url),!(_.status!=="complete"||!f.attempted||!((E=$.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 z;const k=(z=v[0])==null?void 0:z.result;if(typeof k!="string"||!Ae.has(a))return;const O=JSON.parse(k);O.jobId===a&&O.phase==="result"&&u(O)}).catch(()=>{}))},S=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};Ae.set(a,f),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var O,z,I,R,L,N;const l=Date.now()+6e4;for(;Ae.has(a)&&Date.now()<l&&(await chrome.tabs.get(w)).status!=="complete";)await new Promise(P=>setTimeout(P,250));if(!Ae.has(a))return;const _=await chrome.tabs.get(w);if(_.status!=="complete"||!((O=_.url)!=null&&O.startsWith("https://creator.xiaohongshu.com/publish/publish")))throw new Error("小红书发布页未就绪,请先在当前浏览器完成创作者后台登录");let $;if(e.mode==="article"){if($=(z=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:Br,args:[e.html,s]}))[0])==null?void 0:z.result,!$)throw new Error("小红书长文解析失败,未提交发布");f.articleImages=new Map($.images.map(P=>[P.id,P.source]))}const x={id:a,channel:s,deadline:o,mode:e.mode,title:c,content:($==null?void 0:$.text)??(b==null?void 0:b.content)??"",tags:(b==null?void 0:b.tags)||[],imageCount:($==null?void 0:$.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:[x]});if(!Ae.has(a))return;if(!((R=(I=E[0])==null?void 0:I.result)!=null&&R.observing))throw new Error("无法观察小红书发布回执,已停止投稿");const v={...x,secret:n,...$?{article:{markup:$.markup,images:$.images.map(({id:B,marker:P})=>({id:B,marker:P}))}}:{},...b?{post:{images:b.images.map(gt),...b.video?{video:gt(b.video)}:{},...b.cover?{cover:gt(b.cover)}:{}}}:{}};if(!((N=(L=(await chrome.scripting.executeScript({target:{tabId:w},world:"ISOLATED",func:zr,args:[v]}))[0])==null?void 0:L.result)!=null&&N.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=Ae.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 kt(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 Re=new Map,ze=e=>e==="weibo"?"https://weibo.com":"https://creator.douyin.com",ei=e=>ze(e)+(e==="weibo"?"/":"/creator-micro/content/manage"),yt=({id:e,name:t,type:r,size:i})=>({id:e,name:t,type:r,size:i});function He(e,t,r=!1){if(e.watching&&!r&&!(t!=null&&t.success))return;if(!r&&!e.rehearsal&&!e.watching&&e.platform==="weibo"&&t&&Ge(t)){e.watching=!0,Ve({tabId:e.tabId,platform:"weibo",channel:e.channel,url:e.editUrl,message:"微博要求完成验证。请在已打开的页面完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>{var c;return((c=Re.get(e.id))==null?void 0:c.watching)===!0},progress:e.progress,onReceipt:c=>{e.attempted=!0,He(e,c,!0)},onHandOff:()=>He(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({...Je(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===ze(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(!At(e))throw new Error("当前平台尚未接入图文或视频直发");const n=De(t);ht(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=ze(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(S=>{const b=v=>{Re.has(o)&&(Re.delete(o),clearTimeout($),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:k=>{window.dispatchEvent(new Event(`${k}:cancel`)),window.dispatchEvent(new Event(`${k}:stop`)),sessionStorage.removeItem(k)},args:[`writedock-weibo-post-${y}`]}).catch(()=>{}),e==="douyin"&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:k=>{window.dispatchEvent(new Event(`${k}:cancel`)),sessionStorage.removeItem(k)},args:[`writedock-douyin-${y}`]}).catch(()=>{}),Se(g,v,v.warnings).then(S))},d=v=>{x.watching||b({platform:e,success:!1,draftOnly:!1,publicationState:x.attempted?"unknown":"failed",error:v,postUrl:x.editUrl,timestamp:Date.now()})},f=v=>{v===g&&d("投稿标签页已关闭,请检查平台结果后再决定是否重试")},l=(v,k,O)=>{if(v!==g||!Re.has(o)||!O.url)return;if(e==="weibo"){const R=new URL(O.url);if(R.origin==="https://security.weibo.com"&&/^\/(?:verify|captcha)(?:\/|$)/.test(R.pathname)){x.editUrl=R.href,He(x,{publicationState:"needs_user_action",manualReason:"captcha",message:"微博已进入人工验证页。请在当前标签页完成验证、核对内容并手动发布,Agent 不要重新提交。"});return}R.origin==="https://weibo.com"&&(x.editUrl=R.href,k.status==="complete"&&x.attempted&&chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:L=>sessionStorage.getItem(L),args:[`writedock-weibo-post-${y}`]}).then(L=>{var P;const N=(P=L[0])==null?void 0:P.result;if(typeof N!="string"||!Re.has(o))return;const B=JSON.parse(N);B.phase==="result"&&He(x,B)}).catch(()=>{}));return}const z=new URL(O.url);if(z.origin!==ze(e)||(/^\/creator-micro\/content\/(?:upload|publish)(?:\/|$)/.test(z.pathname)&&!z.pathname.endsWith("/success")&&(x.editUrl=z.href),!x.clicked||k.status!=="complete"))return;const I=/^\/creator-micro\/content\/manage(?:\/|$)|\/publish\/success(?:\/|$)/.test(z.pathname);chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:R=>sessionStorage.getItem(R),args:[`writedock-douyin-${y}`]}).then(R=>{var N;if(!Re.has(o))return;const L=(N=R[0])==null?void 0:N.result;if(typeof L=="string")try{const B=JSON.parse(L);if(B.jobId===o&&B.phase==="result"){He(x,B);return}}catch{}I&&d("抖音已进入作品管理,但未取得明确成功提示,请检查平台,不要自动重发")}).catch(()=>{I&&Re.has(o)&&d("抖音页面已跳转,发布结果未能确认,请检查平台,不要自动重发")})},_=Date.now()+18e5,$=setTimeout(()=>d("等待投稿结果超时,请检查作品管理,不要自动重复发布"),30*6e4),x={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};Re.set(o,x),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(yt),...n.video?{video:yt(n.video)}:{},...n.cover?{cover:yt(n.cover)}:{}}};ti(g).then(async()=>{var O,z,I,R,L,N,B;if(!Re.has(o))return;if(!((O=(await chrome.tabs.get(g)).url)!=null&&O.startsWith(`${ze(e)}/`)))throw new Error("请在创作者后台完成登录后再投稿");if(await je(g),e==="weibo"){const P=Or(n);if(!((I=(z=(await chrome.scripting.executeScript({target:{tabId:g},world:"MAIN",func:qr,args:[{channel:y,deadline:_,kind:n.kind,text:P,title:n.title,imageCount:n.images.length,creation:n.weiboVideoCreation,explicitCover:!!n.cover,rehearsal:a}]}))[0])==null?void 0:z.result)!=null&&I.observing))throw new Error("无法观察微博发布回执,已停止自动投稿");if(!((L=(R=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Mr,args:[{...E,channel:y,text:P}]}))[0])==null?void 0:R.result)!=null&&L.started))throw new Error("无法启动微博图文/视频投稿脚本");return}if(!((B=(N=(await chrome.scripting.executeScript({target:{tabId:g},world:"ISOLATED",func:Pr,args:[E]}))[0])==null?void 0:N.result)!=null&&B.started))throw new Error("无法启动页面投稿脚本")}).catch(v=>d(v instanceof Error?v.message:"启动投稿失败"))})}async function ii(e,t){var i,a;const r=Re.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(`${ze(r.platform)}/`)))throw new Error("页面投稿任务已结束或来源不匹配");if(e.type==="PAGE_PUBLISH_PROGRESS"){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 kt(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 He(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{ht(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)),S=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 I;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(L=>y(L)&&/标题/.test(L.placeholder||""));const R=document.querySelector('[data-contents="true"],[contenteditable="true"]');if((f==null?void 0:f.value.trim())===e.title&&R&&y(R)&&((I=R.textContent)!=null&&I.trim()||R.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),$=()=>document.querySelectorAll('[contenteditable="true"] img').length;for(;!s&&$()<(e.imageCount||0)&&Date.now()<_;)await o(500);if(s)return;if($()<(e.imageCount||0))throw new Error(`知乎编辑器只有 ${$()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);const x=D();x&&S(x);const E=Math.min(Date.now()+3e4,e.deadline);let v=w().find(R=>{var L;return/^(发布|发布文章)$/.test(((L=R.textContent)==null?void 0:L.trim())||"")});for(;!v&&!s&&!n&&Date.now()<E;)await o(500),v=w().find(R=>{var L;return/^(发布|发布文章)$/.test(((L=R.textContent)==null?void 0:L.trim())||"")});if(s||n)return;if(!v)throw new Error(D()||"知乎发布按钮不可用,请检查登录、必填项或平台提示");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const k=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 O=!1;const z=Math.min(Date.now()+12e4,e.deadline);for(;!s&&!n&&Date.now()<z;){const R=D();if(R&&S(R),!a&&!O){const L=w().find(N=>{var B;return N!==v&&/^(发布|发布文章|确认发布|立即发布)$/.test(((B=N.textContent)==null?void 0:B.trim())||"")&&(!k.has(N)||N.closest('[role="dialog"],.Modal,.PublishPanel,.Popover-content'))});L&&(O=!0,L.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 Ie=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,S=!1;const b=(E,v=!1)=>{if(!Ie.has(c)||S&&!v&&!E.success)return;if(!v&&!a&&!S&&Ge(E)){S=!0,clearTimeout(_),Ve({tabId:o,platform:"zhihu",channel:h,url:u,message:"知乎要求完成验证。请在已打开的投稿页完成验证;如果几秒后没有自动发布,再在该页点“发布”。",isActive:()=>Ie.has(c),progress:r,onReceipt:I=>{x.attempted=!0,b({...I,draftId:e},!0)},onHandOff:()=>b(E,!0)});return}if(!v&&E.publicationState==="unknown"&&x.resultDeadline&&Date.now()<x.resultDeadline){g=E;return}if(Ie.delete(c),clearTimeout(_),clearInterval($),clearTimeout(D),chrome.tabs.onRemoved.removeListener(f),chrome.tabs.onUpdated.removeListener(l),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:(I,R)=>{window.dispatchEvent(new Event(`${I}:cancel`)),window.dispatchEvent(new Event(`${I}:stop`)),window.dispatchEvent(new Event(`${R}:stop`));for(const L of[I,`${I}:attempted`,R,`${R}:ready`])sessionStorage.removeItem(L)},args:[`writedock-zhihu-${h}`,`writedock-zhihu-early-${e}`]}).catch(()=>{}),a&&E.publicationState==="rehearsed"){Se(o,{...Je("zhihu",n),postId:e}).then(m);return}const k=!a&&x.attempted&&E.success===!0&&E.publicationState==="submitted"&&E.draftId===e&&(E.responseConfirmed===!0||E.pageConfirmed===!0),O=E.publicationState==="needs_user_action"&&["captcha","agreement","publication_settings"].includes(E.manualReason||""),z=E.message||"请用户点击原稿件链接,在同一投稿页完成平台要求并手动发布;Agent 不要打开网页或重发。";Se(o,{platform:"zhihu",success:k,draftOnly:!1,publicationState:k?"submitted":O?"needs_user_action":x.attempted&&!E.platformRejected?"unknown":"failed",postId:e,postUrl:k?`https://zhuanlan.zhihu.com/p/${e}`:n,...k?{confirmation:E.responseConfirmed?"http_response":"native_page_message",message:E.responseConfirmed?"知乎发布接口已确认提交成功":"知乎原生页面已明确提示本篇文章发布成功"}:O?{requiresUserAction:!0,userAction:{type:E.manualReason,url:u,message:z},message:z}:{error:E.error||"知乎发布结果未确认,请用户点击原稿件链接核对;Agent 不要打开网页或重发"},timestamp:Date.now()},E.warnings).then(m)},d=async()=>{var E;if(!(!Ie.has(c)||!x.attempted||p)){p=!0;try{const k=(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;(k==null?void 0:k.phase)==="result"&&k.draftId===e&&b(k)}catch{}finally{p=!1}Ie.has(c)&&x.resultDeadline&&Date.now()>=x.resultDeadline&&b(g||{error:"知乎已尝试发布,但等待成功回执超时。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"})}},f=E=>{E===o&&(D=setTimeout(()=>b({error:"知乎投稿标签页已关闭,结果未确认。请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),500))},l=(E,v,k)=>{if(!(E!==o||!Ie.has(c)||!x.attempted)){if(/^https:\/\/www\.zhihu\.com\/account\/unhuman(?:[/?#]|$)/.test(k.url||"")){u=k.url,b({publicationState:"needs_user_action",manualReason:"captcha",message:"知乎进入了人工验证页,请用户切换到同一投稿标签页完成验证并手动发布,Agent 不要打开网页或重发。"});return}v.status==="complete"&&d()}},_=setTimeout(()=>b({error:"等待知乎发布结果超时,请用户点击原稿件链接核对,Agent 不要打开网页或重发。"}),10*6e4),$=setInterval(()=>{d()},1e3),x={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:b};Ie.set(c,x),chrome.tabs.onRemoved.addListener(f),chrome.tabs.onUpdated.addListener(l),(async()=>{var z,I,R,L;const E=Date.now()+6e4;for(;Date.now()<E&&Ie.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(B=>setTimeout(B,250));if(!Ie.has(c))return;const v=await chrome.tabs.get(o);if(v.status!=="complete"||!((z=v.url)!=null&&z.startsWith(n)))throw new Error("知乎发布页未就绪,请确认登录状态");if(!((I=(await chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:N=>sessionStorage.getItem(`writedock-zhihu-early-${N}:ready`)==="1",args:[e]}))[0])!=null&&I.result))throw new Error("知乎发布监听未在页面启动前就绪,已停止发布;请重新加载新版扩展后再试");if(await je(o),!((L=(R=(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:R.result)!=null&&L.started))throw new Error("无法启动知乎发布流程")})().catch(E=>b({error:E instanceof Error?E.message:"启动知乎发布失败"}))})}async function mi(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?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 $=_.get("cover_images");let x;try{x=typeof $=="string"?JSON.parse($):void 0}catch{return r.push("百家号 cover_images 格式无法解析"),"publish"}return x===void 0?(r.push("百家号发布请求中未读到 cover_images 字段"),"publish"):Array.isArray(x)?x.length?(x.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 x=l.trim(),E=/^[\w.$]+\s*\(([\s\S]*)\)\s*;?\s*$/.exec(x);l=JSON.parse(E?E[1]:x)}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 $=b>=200&&b<300&&(_==null?void 0:_.errno)===0&&((f=_.ret)==null?void 0:f.article_id)===e.articleId;i({phase:"result",success:$,publicationState:$?"submitted":"unknown",...$?{}:{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),$=(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,_,$)}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(S),window.removeEventListener(`${t}:stop`,D)},S=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 不要重新提交。"}),S=()=>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 N;const d=Math.min(Date.now()+6e4,e.deadline);let f,l=!1;const _=B=>(B instanceof HTMLInputElement||B instanceof HTMLTextAreaElement?B.value:B.textContent||"").trim(),$=()=>Array.from(document.querySelectorAll('[class*="titleInput"] [contenteditable="true"],[class*="titleInput"] textarea,[class*="titleInput"] input,textarea[placeholder*="标题"],input[placeholder*="标题"]')).find(c),x=()=>{var P;const B=document.querySelector('iframe#ueditor_0,iframe[id^="ueditor_"]');try{const A=B&&c(B)?(P=B.contentDocument)==null?void 0:P.body:null;if(A)return A}catch{}return Array.from(document.querySelectorAll('[contenteditable="true"],.ProseMirror,.ql-editor')).find(A=>c(A)&&!A.closest('[class*="titleInput"]'))};for(;!r&&!i&&Date.now()<d;){if(g()){await D();return}f=$();const B=x();if(f&&_(f)===e.title&&B&&((N=B.textContent)!=null&&N.replace(/[\s\u200b-\u200d\ufeff]/g,"")||B.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 B;return((B=x())==null?void 0:B.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 k=S();if(k&&/完成验证|安全验证|验证码/.test(k)){await D();return}if(k&&/封面/.test(k)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页处理并手动发布。"});return}const O=Math.min(Date.now()+3e4,e.deadline);let z=h().find(B=>{var P;return/^(发布|发布文章|立即发布)$/.test(((P=B.textContent)==null?void 0:P.trim())||"")});for(;!z&&!r&&!i&&Date.now()<O;)await s(500),z=h().find(B=>{var P;return/^(发布|发布文章|立即发布)$/.test(((P=B.textContent)==null?void 0:P.trim())||"")});if(r||i)return;if(!z)throw new Error(S()||"百家号发布按钮不可用,请检查页面要求");if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}const I=new Set(h());if(await o("BAIJIAHAO_ARTICLE_PROGRESS",{stage:"publishing"}),r||i||_(f)!==e.title||!z.isConnected||!y(z)||Date.now()>=e.deadline)throw new Error("百家号页面状态变化,已停止自动发布");a=!0,z.click();const R=Math.min(Date.now()+12e4,e.deadline);let L=!1;for(;!r&&!i&&Date.now()<R;){if(g()){await D();return}const B=S();if(B&&/完成验证|安全验证|验证码/.test(B)){await D();return}if(B&&/封面/.test(B)){await p({success:!1,publicationState:"needs_user_action",manualReason:"cover_required",message:"百家号要求选择或调整封面,请打开同一稿件页完成封面设置并手动发布。"});return}if(B)throw new Error(B);if(!n&&!L){const P=h().find(A=>{var q;return A!==z&&/^(发布|确认发布|立即发布|确认并发布|发布并提交审核)$/.test(((q=A.textContent)==null?void 0:q.trim())||"")&&(!I.has(A)||A.closest('[role="dialog"],.ant-modal'))});P&&(L=!0,P.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 Pe=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(!Pe.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ge(d)){p=!0,clearTimeout(S),Ve({tabId:o,platform:"baijiahao",channel:h,url:n,articleId:e,message:"百家号要求完成验证码。请在已打开的稿件页完成验证;如果几秒后没有自动发布,再在该页点“发布”。结果会自动更新。",isActive:()=>Pe.has(c),progress:r,onReceipt:x=>{b.attempted=!0,u(x,!0)},onHandOff:()=>u(d,!0)});return}if(Pe.delete(c),clearTimeout(S),chrome.tabs.onRemoved.removeListener(g),chrome.tabs.onUpdated.removeListener(D),chrome.scripting.executeScript({target:{tabId:o},world:"ISOLATED",func:x=>{window.dispatchEvent(new Event(`${x}:cancel`)),window.dispatchEvent(new Event(`${x}:stop`)),sessionStorage.removeItem(x)},args:[`writedock-baijiahao-${h}`]}).catch(()=>{}),a&&d.publicationState==="rehearsed"){Se(o,{...Je("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||""),$=d.message||"请打开同一百家号稿件页,完成平台要求并手动发布。Agent 不要自动重试。";Se(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:$},message:$}:{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:$=>sessionStorage.getItem($),args:[`writedock-baijiahao-${h}`]}).then($=>{var v;const x=(v=$[0])==null?void 0:v.result;if(typeof x!="string")return;const E=JSON.parse(x);E.articleId===e&&E.phase==="result"&&u(E)}).catch(()=>{})},S=setTimeout(()=>u({error:"等待百家号发布结果超时,请检查稿件,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,articleId:e,attempted:!1,progress:r,finish:u};Pe.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var x,E,v,k;const d=Date.now()+6e4;for(;Date.now()<d&&Pe.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(O=>setTimeout(O,250));if(!Pe.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=(x=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:wi,args:[{channel:h,articleId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:x.result)!=null&&E.observing))throw new Error("无法监测百家号发布响应,已停止发布");if(!((k=(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&&k.started))throw new Error("无法启动百家号发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动百家号发布失败"}))})}async function bi(e,t){var i,a;const r=Pe.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 $=f instanceof URLSearchParams||f instanceof FormData?f:typeof f=="string"?new URLSearchParams(f):null;return $&&$.get("id")===e.draftId?{operation:_,data:$}: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,_,$,x;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 O=new URL((($=E==null?void 0:E.data)==null?void 0:$.url)||""),z=O.searchParams.get("id");O.protocol==="https:"&&O.hostname==="weibo.com"&&O.pathname==="/ttarticle/p/show"&&z&&/^\d+$/.test(z)&&((x=E==null?void 0:E.data)==null?void 0:x.object_id)===`1022:${z}`&&(v=O.href)}catch{}const k=d>=200&&d<300&&(E==null?void 0:E.code)===1e5&&!!v;i({phase:"result",success:k,publicationState:k?"submitted":"unknown",...k?{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),$=(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,_,$)}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(S),window.removeEventListener(`${t}:stop`,D)},S=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)),S=(f,l)=>p({success:!1,publicationState:"needs_user_action",manualReason:f,message:l}),b=(f,l=!0)=>{var $;const _=Array.from(document.querySelectorAll('span,label,[role="checkbox"]')).filter(x=>{var E;return c(x)&&(((E=x.textContent)==null?void 0:E.trim().length)||0)<100&&f.test(x.textContent||"")});for(const x of _){const E=x.closest('label,[role="checkbox"]')||(($=x.parentElement)==null?void 0:$.querySelector('input[type="checkbox"],[role="checkbox"]'));if(!E)return!1;const v=E instanceof HTMLInputElement?E:E.querySelector('input[type="checkbox"]'),k=v?v.checked:E.getAttribute("aria-checked")==="true"?!0:E.getAttribute("aria-checked")==="false"?!1:void 0;if(k===void 0||k&&(!l||!y(E)))return!1;k&&E.click();break}return!0};return(async()=>{var z,I;const f=Math.min(Date.now()+6e4,e.deadline);let l,_=!1;for(;!r&&!i&&Date.now()<f;){if(g()){await S("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}l=Array.from(document.querySelectorAll("input,textarea")).find(L=>c(L)&&/标题/.test(L.placeholder||""));const R=document.querySelector('[contenteditable="true"],.ProseMirror');if((l==null?void 0:l.value.trim())===e.title&&R&&c(R)&&((z=R.textContent)!=null&&z.trim()||R.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 $=Math.min(Date.now()+2e4,e.deadline),x=()=>{var R;return((R=document.querySelector('[contenteditable="true"].ProseMirror,.ProseMirror'))==null?void 0:R.querySelectorAll("img").length)||0};for(;!r&&!i&&x()<(e.imageCount||0)&&Date.now()<$;)await s(500);if(r||i)return;if(x()<(e.imageCount||0))throw new Error(`微博长文章编辑器只有 ${x()} 张图片,稿件有 ${e.imageCount} 张,已停止发布`);if(!b(/同步至新浪新闻/)){await S("publication_settings","请检查微博文章的同步设置并手动发布,未自动提交到其他平台。");return}await s(100);const E=Math.min(Date.now()+3e4,e.deadline);let v=h().find(R=>{var L;return((L=R.textContent)==null?void 0:L.trim())==="下一步"})||h().find(R=>{var L;return/^(发布|发布文章)$/.test(((L=R.textContent)==null?void 0:L.trim())||"")});for(;!v&&!r&&!i&&Date.now()<E;)await s(500),v=h().find(R=>{var L;return((L=R.textContent)==null?void 0:L.trim())==="下一步"})||h().find(R=>{var L;return/^(发布|发布文章)$/.test(((L=R.textContent)==null?void 0:L.trim())||"")});if(r||i)return;if(!v)throw new Error(D()||"未找到微博长文章的下一步按钮");if(e.rehearsal&&((I=v.textContent)==null?void 0:I.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 k=Math.min(Date.now()+12e4,e.deadline);let O=!1;for(;!r&&!i&&Date.now()<k;){if(g()){await S("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(h().find(N=>{var B,P;return((B=N.textContent)==null?void 0:B.trim())==="我同意"&&/头条文章原创声明|微博签约媒体原创认证协议/.test(((P=N.closest('[role="dialog"],.n-dialog,.n-modal'))==null?void 0:P.textContent)||"")})){await S("agreement","微博显示原创相关协议确认,未自动同意或声明原创。请打开原稿件页阅读并自行决定,再手动发布。");return}const L=D();if(L&&/验证码|安全验证/.test(L)){await S("captcha","微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。");return}if(L&&/封面/.test(L)){await S("cover_required","微博长文章需要设置封面,请在原稿件页完成设置并手动发布。");return}if(L)throw new Error(L);if(!n&&!O){const N=h().find(B=>{var P;return B!==v&&((P=B.textContent)==null?void 0:P.trim())==="发布"&&B.closest('[role="dialog"],.n-modal,.n-dialog,.wb-common-dialog')});if(N){if(e.rehearsal){await p({success:!1,publicationState:"rehearsed"});return}if(!b(/关注\s*@头条文章/)||!b(/并声明本文是原创作品/,!1)){await S("publication_settings","微博发布窗口的勾选项无法安全核对,请自行检查关注及原创声明后手动发布。");return}if(await s(100),r||i||n)return;if(!N.isConnected||!y(N))throw new Error("微博发布确认按钮状态变化,未继续操作");O=!0,N.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 Ce=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(!Ce.has(c)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ge(d)){p=!0,clearTimeout(S),Ve({tabId:o,platform:"weibo-article",channel:h,url:n,message:"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。",isActive:()=>Ce.has(c),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}Ce.delete(c),clearTimeout(S),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"){Se(o,{...Je("weibo",n),postId:e},d.warnings).then(m);return}const _=!a&&d.success===!0&&d.publicationState==="submitted"&&!!l,$=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),x=d.message||"微博要求验证。请在已打开的页面完成验证;验证后会弹出发布窗口,请点里面的“发布”,文章才会发出。结果会自动更新,不要重新提交。";Se(o,{platform:"weibo",success:_,draftOnly:!1,publicationState:_?"submitted":$?"needs_user_action":b.attempted?"unknown":"failed",postId:e,postUrl:_?l:n,timestamp:Date.now(),..._?{message:"微博长文章发布接口已确认成功"}:$?{requiresUserAction:!0,userAction:{type:d.manualReason,url:n,message:x},message:x}:{error:d.error||"微博长文章结果未确认,请检查平台"}},d.warnings).then(m)},g=d=>{d===o&&u({error:"微博投稿标签页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;if(!(d!==o||!Ce.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:$=>sessionStorage.getItem($),args:[`writedock-weibo-article-${h}`]}).then($=>{var v;const x=(v=$[0])==null?void 0:v.result;if(typeof x!="string")return;const E=JSON.parse(x);E.draftId===e&&E.phase==="result"&&u(E)}).catch(()=>{})}},S=setTimeout(()=>u({error:"等待微博长文章发布结果超时,请检查平台,不要自动重发"}),10*6e4),b={tabId:o,secret:y,channel:h,draftId:e,attempted:!1,progress:r,finish:u};Ce.set(c,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var $,x,E,v,k;const d=Date.now()+6e4;for(;Date.now()<d&&Ce.has(c)&&(await chrome.tabs.get(o)).status!=="complete";)await new Promise(O=>setTimeout(O,250));if(!Ce.has(c))return;const f=await chrome.tabs.get(o);if(f.status!=="complete"||!(($=f.url)!=null&&$.startsWith("https://card.weibo.com/article/v5/editor")))throw new Error("微博长文章编辑页未就绪,请确认登录");if(await je(o),!((E=(x=(await chrome.scripting.executeScript({target:{tabId:o},world:"MAIN",func:vi,args:[{channel:h,draftId:e,deadline:w,rehearsal:a}]}))[0])==null?void 0:x.result)!=null&&E.observing))throw new Error("无法监测微博长文章的发布响应,已停止发布");if(!((k=(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&&k.started))throw new Error("无法启动微博长文章发布流程")})().catch(d=>u({error:d instanceof Error?d.message:"启动微博长文章投稿失败"}))})}async function Si(e,t){var i,a;const r=Ce.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=A=>A.replace(/[\s\u200b-\u200d\ufeff]/g,""),a=i(r.body.textContent||""),n=r.querySelectorAll("img[src]").length,s=new Set,o=new Set,c=A=>{try{const q=new URL(String(A),location.href);return/^https?:$/.test(q.protocol)&&/(?:^|\.)(?:hdslb\.com|biliimg\.com)$/.test(q.hostname)&&q.pathname.startsWith("/bfs/")?q.pathname:""}catch{return""}};for(const A of r.querySelectorAll("img[src]")){const q=c(A.getAttribute("src"));q&&o.add(q)}let y=!1,h=!1,w=!1,m="";const p=[],u=A=>{p.includes(A)||p.push(A)},g=A=>Array.isArray(A)?A.length>0:A&&typeof A=="object"?Object.keys(A).length>0:!!A,D=A=>{const q=JSON.stringify({...A,jobId:e.id});try{sessionStorage.setItem(t,q)}catch{}window.dispatchEvent(new CustomEvent(t,{detail:q}))},S=A=>{w||(w=!0,D({phase:"result",...p.length?{warnings:p}:{},...A}))},b=(A,q)=>S({success:!1,publicationState:"needs_user_action",manualReason:A,message:q}),d=A=>typeof A=="string"?JSON.parse(A):A,f=(A,q)=>{try{const j=new URL(q,location.href);if(j.origin!=="https://api.bilibili.com")return null;if(/^\/x\/gaia-vgate\/(?:v2\/register|v1\/img)$/.test(j.pathname))return"captcha";if(A.toUpperCase()!=="POST")return null;if(j.pathname==="/x/dynamic/feed/create/opus")return"publish";if(j.pathname==="/x/dynamic/feed/edit/opus"||/^\/x\/article\/creative\/article\/(?:addupdate|update)$/.test(j.pathname))return"other_publish";if(j.pathname==="/x/dynamic/feed/article/draft/add")return"draft";if(["/x/dynamic/feed/draw/upload_bfs","/x/dynamic/feed/draw/transfer_image"].includes(j.pathname))return"image"}catch{}return null},l=(A,q)=>{throw b(A,q),new Error("WriteDock 已停止B站专栏自动发布,请检查原稿件")},_=(A,q)=>{var me,C,H,M,U,V;if(A==="captcha"){b("captcha","B站要求人工验证码。请切换到已打开的原投稿页完成验证并手动发布,Agent 不要重新提交。");return}if(A==="other_publish")return l("publication_settings","B站页面试图修改已有内容或使用旧发布接口,已停止操作,请核对原投稿页。");if(A!=="publish")return;if(e.rehearsal)return l("publication_settings","演练不提交发布,已拦截B站发布请求。");if(w||h||!y||Date.now()>=e.deadline)return h&&!w&&S({success:!1,publicationState:"unknown",error:"B站页面尝试重复提交,请检查原帖,不要自动重发。"}),l("publication_settings","本次B站稿件尚未核对完成或页面尝试重复发送,已停止自动提交。");let j;try{j=d(q)}catch{}if(!j||typeof j!="object"){u("B站发布请求格式无法解析,已依据提交前的编辑器核对放行"),h=!0,y=!1,D({phase:"request"});return}const K=j.opus_req,J=K==null?void 0:K.opus,ee=K==null?void 0:K.option;if(j.dyn_id_str||j.cvid_str)return l("publication_settings","B站发布请求指向已有内容,已停止发布。");if(typeof(J==null?void 0:J.title)=="string"&&J.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||(me=J==null?void 0:J.pub_info)!=null&&me.timer_pub_time||ee!=null&&ee.only_fans||ee!=null&&ee.only_fans_level||g(K==null?void 0:K.topic)||g(J==null?void 0:J.attachments)||g((C=J==null?void 0:J.article)==null?void 0:C.list_id))return l("publication_settings","B站的公开范围、定时、充电专享、文集、话题或附加内容需要人工核对,请在原稿件页手动发布。");if((H=J==null?void 0:J.article)!=null&&H.originality)return l("agreement","B站稿件已选择原创声明,Agent 不自动声明原创或同意原创协议,请在原稿件页自行核对并手动发布。");if(j.draft_id_str&&m&&j.draft_id_str!==m)return l("publication_settings","B站发布请求未匹配本次原生编辑器保存的中间稿件,已停止发布。");j.raw_content!==void 0&&j.raw_content!==""&&u("B站 raw_content 不为空"),(K==null?void 0:K.scene)!==12&&u(`B站 scene=${String(K==null?void 0:K.scene)},与抓包时的 12 不同`),(J==null?void 0:J.opus_source)!==2&&u(`B站 opus_source=${String(J==null?void 0:J.opus_source)},与抓包时的 2 不同`),((M=J==null?void 0:J.article)==null?void 0:M.category_id)!==15&&u(`B站 category_id=${String((U=J==null?void 0:J.article)==null?void 0:U.category_id)},与抓包时的 15 不同`),typeof(J==null?void 0:J.title)!="string"&&u("B站发布请求中未读到标题字段"),(ee==null?void 0:ee.private_pub)===void 0&&u("B站发布请求中未读到公开范围字段"),((V=J==null?void 0:J.article)==null?void 0:V.originality)===void 0&&u("B站发布请求中未读到原创声明字段"),j.draft_id_str&&!m&&u("未观察到B站中间稿件保存回执");const X=[],re=[];let he=!1;const te=T=>{if(!(!T||typeof T!="object")){if(Array.isArray(T)){T.forEach(te);return}for(const[F,Z]of Object.entries(T))F==="words"&&typeof Z=="string"?X.push(Z):F==="pics"&&Array.isArray(Z)?re.push(...Z):["video","video_card","archive","audio","live","bangumi","vote","goods","lottery"].includes(F)?he=!0:te(Z)}};if(te(J==null?void 0:J.content),he)return l("publication_settings","B站发布内容包含未接入的内容卡片,已停止发布。");if(X.length&&i(X.join(""))!==a)return l("publication_settings","B站发布请求的正文与本次稿件不一致,已停止发布。");if(!X.length&&a&&u("B站发布请求中未读到正文字段,已依据提交前的编辑器核对放行"),re.length&&re.length!==n)return l("publication_settings","B站发布请求的图片数量与本次稿件不一致,已停止发布。");if(!re.length&&n&&u("B站发布请求中未读到图片字段,已依据提交前的编辑器核对放行"),re.some(T=>String(T.url).startsWith("data:")))return l("publication_settings","B站发布请求中有图片尚未上传完成,已停止发布。");re.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"})},$=(A,q,j,K)=>{var J,ee,X,re,he;if(!(w||A==="captcha"))try{const te=d(j);if((te==null?void 0:te.code)===-352||/验证码|安全验证|验证后|完成验证/.test(String((te==null?void 0:te.message)||""))){S({success:!1,publicationState:"needs_user_action",manualReason:"captcha",captchaRejected:!0,message:"B站专栏要求人工验证。请在已打开的原投稿页完成验证码,Agent 不要重新提交。"});return}if(A==="image"){const H=(te==null?void 0:te.code)===0&&q>=200&&q<300?c((J=te.data)==null?void 0:J.image_url):"";H&&(s.add(H),D({phase:"images",current:s.size,total:n}));return}if(A==="draft"){let H="";try{H=((X=(ee=d(K))==null?void 0:ee.arg)==null?void 0:X.title)||""}catch{}const M=(re=te==null?void 0:te.data)==null?void 0:re.article_id;(te==null?void 0:te.code)===0&&H===e.title&&(typeof M=="number"&&Number.isSafeInteger(M)||typeof M=="string")&&/^\d{1,16}$/.test(String(M))&&(m=String(M));return}if(A!=="publish")return;const me=(he=te==null?void 0:te.data)==null?void 0:he.dyn_id_str,C=q>=200&&q<300&&(te==null?void 0:te.code)===0&&typeof me=="string"&&/^\d{1,24}$/.test(me);S({success:C,publicationState:C?"submitted":"unknown",...C?{responseConfirmed:!0,postId:me,postUrl:`https://www.bilibili.com/opus/${me}`}:{error:(te==null?void 0:te.code)===0?"B站返回成功但没有可核实的内容 ID,请检查平台,不要自动重发。":String((te==null?void 0:te.message)||`B站发布结果未确认(HTTP ${q})`).slice(0,300)}})}catch{A==="publish"&&S({success:!1,publicationState:"unknown",error:"B站发布回执无法解析,请检查原帖,不要自动重发。"})}},x=window.fetch,E=async function(A,q){const j=(q==null?void 0:q.method)||(A instanceof Request?A.method:"GET"),K=f(j,A instanceof Request?A.url:String(A)),J=["publish","draft"].includes(K||"")?(q==null?void 0:q.body)??(A instanceof Request?await A.clone().text():void 0):void 0;_(K,J);try{const ee=await x.call(window,A,q);return K&&$(K,ee.status,await ee.clone().text(),J),ee}catch(ee){throw K==="publish"&&S({success:!1,publicationState:"unknown",error:"B站发布连接中断,请检查原帖,不要自动重发。"}),ee}},v=XMLHttpRequest.prototype,k=v.open,O=v.send,z=new WeakMap,I=function(A,q,...j){return z.set(this,{method:A,url:String(q)}),Reflect.apply(k,this,[A,q,...j])},R=function(A){const q=z.get(this),j=q?f(q.method,q.url):null;return _(j,A),j&&this.addEventListener("loadend",()=>{try{$(j,this.status,this.responseType==="json"?this.response:this.responseText,A)}catch{j==="publish"&&$(j,this.status,void 0)}},{once:!0}),O.call(this,A)},L=()=>{!w&&!h&&Date.now()<e.deadline&&(y=!0)},N=()=>{var ee,X;if(w||h)return;const A=window.editor,q=(X=(ee=A==null?void 0:A.storage)==null?void 0:ee.biliImage)==null?void 0:X.allImages,j=[],K=re=>{!re||typeof re!="object"||(re.type==="text"&&typeof re.text=="string"&&j.push(re.text),Array.isArray(re.content)&&re.content.forEach(K))};typeof(A==null?void 0:A.getJSON)=="function"&&K(A.getJSON());const J=typeof(A==null?void 0:A.getJSON)=="function"&&i(j.join(""))===a&&Array.isArray(q)&&q.length===n&&q.every(re=>re.attrs.status===1)&&(s.size>=n||q.every(re=>!!c(re.attrs.src)));D({phase:"content",ready:J})},B=()=>{window.fetch===E&&(window.fetch=x),v.open===I&&(v.open=k),v.send===R&&(v.send=O),clearTimeout(P),window.removeEventListener(`${t}:arm`,L),window.removeEventListener(`${t}:read`,N),window.removeEventListener(`${t}:stop`,B)};window.fetch=E,v.open=I,v.send=R,window.addEventListener(`${t}:arm`,L),window.addEventListener(`${t}:read`,N),window.addEventListener(`${t}:stop`,B,{once:!0});const P=setTimeout(B,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 $=await chrome.runtime.sendMessage({type:l,jobId:e.id,jobSecret:e.secret,..._});if(!$||$.error)throw new Error(($==null?void 0:$.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 S=()=>{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($=>{var x;return((x=$.textContent)==null?void 0:x.trim())||""}).filter($=>$.length<1e3);l.some($=>/验证码|完成验证|安全验证|拖动.*(?:滑块|图片)|点选.*文字/.test($))&&D("captcha","请在已打开的B站专栏投稿页完成验证码并手动发布,Agent 不要重发。"),l.some($=>/我已阅读|我同意|原创声明|确认.*声明/.test($))&&D("agreement","B站要求确认原创声明或协议,请在原投稿页阅读、自行决定并手动发布。"),l.some($=>/请选择|请设置|封面|未实名|绑定手机|转正答题|声明/.test($))&&D("publication_settings","B站要求补充封面、账号权限或发布设置,请在原投稿页核对并手动处理。");const _=l.find($=>/失败|错误|限制|超出|超过|不能为空|图片过大/.test($));if(_)throw new Error(_.slice(0,300))},b=async(l,_,$)=>{const x=Math.min(Date.now()+_,e.deadline);for(;Date.now()<x;){S();const E=l();if(E)return E;await o(300)}throw new Error($)},d=()=>(s=!1,window.dispatchEvent(new Event(`${t}:read`)),s),f=async()=>{var L,N;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站新版专栏正文编辑器未就绪"),$=B=>(B||"").replace(/[\s​-‍]/g,"").length>0;if(($(l.value)||$(_.textContent)||_.querySelector("img"))&&D("publication_settings","B站编辑器已有未发内容,未覆盖原稿,请在已打开的页面自行核对。"),l.maxLength>0&&e.title.length>l.maxLength)throw new Error(`B站当前标题最多 ${l.maxLength} 字,请让 Agent 缩短标题后重新提交,未截断发布`);const x=new DOMParser().parseFromString(e.html,"text/html");if(x.querySelector("video,audio,iframe"))throw new Error("当前B站专栏只接文字和图片,不接视频、音频或嵌入卡片");(N=(L=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"))==null?void 0:L.set)==null||N.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",x.body.innerHTML),E.setData("text/plain",x.body.textContent||""),S(),_.focus();const v=document.createRange();v.selectNodeContents(_);const k=getSelection();if(k==null||k.removeAllRanges(),k==null||k.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 O=await b(()=>w().find(B=>{var P;return((P=B.textContent)==null?void 0:P.trim())==="发布"}),3e4,"B站发布按钮不可用,请检查账号权限和正文要求");if(e.rehearsal){if(!d())throw new Error("B站稿件状态变化,演练未通过");await u({success:!1,publicationState:"rehearsed"});return}const z=new Set(w());if(await c("BILIBILI_ARTICLE_PROGRESS",{stage:"publishing"}),S(),!O.isConnected||!h(O)||l.value!==e.title||!d())throw new Error("B站稿件或发布控件状态变化,已停止操作");window.dispatchEvent(new Event(`${t}:arm`)),a=!0,O.click();const I=Math.min(Date.now()+12e4,e.deadline);let R=!1;for(;!r&&!i&&Date.now()<I;){if(S(),!n&&!R){const B=w().find(P=>{var A;return!z.has(P)&&/^(?:确认发布|确认并发布|发布)$/.test(((A=P.textContent)==null?void 0:A.trim())||"")&&!!P.closest('[role="dialog"],.vui_dialog,.vui-dialog')});B&&(R=!0,B.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 xe=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(!xe.has(n)||p&&!f&&!d.success)return;if(!f&&!a&&!p&&Ge(d)){p=!0,clearTimeout(S),Ve({tabId:w,platform:"bilibili",channel:o,url:b.editUrl,message:"B站要求输入验证码。请在已打开的投稿页输入验证码并点“确定”,确定后 B站会自动发布,不需要再点“发布”;结果会自动更新。",isActive:()=>xe.has(n),progress:r,onReceipt:E=>{b.attempted=!0,u(E,!0)},onHandOff:()=>u(d,!0)});return}xe.delete(n),clearTimeout(S),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"){Se(w,Je("bilibili",b.editUrl),d.warnings).then(m);return}const _=!a&&b.attempted&&d.success===!0&&d.publicationState==="submitted"&&d.responseConfirmed===!0&&!!l,$=d.publicationState==="needs_user_action"&&["captcha","cover_required","agreement","publication_settings"].includes(d.manualReason||""),x=String(d.message||"请在已打开的B站原投稿页完成验证或设置并手动发布,Agent 不要重新提交。").slice(0,1e3);Se(w,{platform:"bilibili",success:_,draftOnly:!1,publicationState:_?"submitted":$?"needs_user_action":b.attempted?"unknown":"failed",postUrl:_?l:b.editUrl,timestamp:Date.now(),..._?{postId:d.postId,message:"B站专栏发布接口已确认提交,展示状态以平台为准"}:$?{requiresUserAction:!0,userAction:{type:d.manualReason,url:b.editUrl,message:x},message:x}:{error:d.error||"B站专栏发布结果未确认,请检查原稿件,不要自动重发"}},d.warnings).then(m)},g=d=>{d===w&&u({error:"B站专栏投稿页已关闭,请检查平台,不要自动重发"})},D=(d,f,l)=>{var _;d!==w||!xe.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:$=>["member.bilibili.com","www.bilibili.com"].includes(location.hostname)?sessionStorage.getItem($):null,args:[`writedock-bilibili-${o}`]}).then($=>{for(const x of $){if(typeof x.result!="string"||!xe.has(n))continue;const E=JSON.parse(x.result);if(E.jobId===n&&E.phase==="result"){u(E);break}}}).catch(()=>{}))},S=setTimeout(()=>u({error:"等待B站专栏发布超时,请检查原稿件,不要自动重发"}),10*6e4),b={tabId:w,secret:s,channel:o,editUrl:y,attempted:!1,progress:r,finish:u};xe.set(n,b),chrome.tabs.onRemoved.addListener(g),chrome.tabs.onUpdated.addListener(D),(async()=>{var l,_,$,x;const d=Date.now()+6e4;let f=!1;for(;xe.has(n)&&Date.now()<d;){const E=await chrome.tabs.get(w);if(ar(E.url||"")){const k=(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 O=document.querySelector('.editor-container .ProseMirror[contenteditable="true"]'),z=document.querySelector("textarea.title-input__inner");return!!O&&!!z&&O.getClientRects().length>0&&z.getClientRects().length>0}})).filter(O=>O.result===!0);if(!k.length){const O=await chrome.scripting.executeScript({target:{tabId:w,allFrames:!0},world:"ISOLATED",args:[f],func:z=>{if(location.protocol!=="https:"||location.hostname!=="member.bilibili.com")return null;const I=N=>N.getClientRects().length>0&&getComputedStyle(N).visibility!=="hidden";if(Array.from(document.querySelectorAll('.vui_dialog--body,.vui_dialog,[role="dialog"]')).filter(I).map(N=>N.textContent||"").some(N=>/当日投稿上限|今日投稿.*上限|已达.*上限/.test(N)))return"limit";if(z)return null;const L=Array.from(document.querySelectorAll('button.new-creation_button,button,[role="button"]')).find(N=>{var B;return I(N)&&((B=N.textContent)==null?void 0:B.trim())==="新的创作"});return L?(L.click(),"clicked"):null}}).catch(()=>[]);if(O.some(z=>z.result==="limit")){u({error:"B站账号已达到当日专栏投稿上限(LV1–3 每天 1 篇),今天无法再自动发布,未提交。请明天再试,或在B站手动保存为草稿。"});return}O.some(z=>z.result==="clicked")&&(f=!0,b.progress({stage:"preparing_article"}))}if(k.length>1)throw new Error("发现多个B站专栏编辑器,未选择不明确的稿件发布");if(k.length===1){const O=k[0];b.frameId=O.frameId,b.documentId=typeof O.documentId=="string"?O.documentId:void 0;const z={tabId:w,frameIds:[O.frameId]};await je(w);const I=await chrome.scripting.executeScript({target:z,world:"MAIN",func:Ai,args:[{id:n,channel:o,title:e,html:t,deadline:c,rehearsal:a}]});if(!xe.has(n))return;if(!((_=(l=I[0])==null?void 0:l.result)!=null&&_.observing))throw new Error("无法监测B站专栏发布回执,已停止投稿");if(!((x=($=(await chrome.scripting.executeScript({target:z,world:"ISOLATED",func:Ii,args:[{id:n,secret:s,channel:o,title:e,html:t,deadline:c,rehearsal:a}]}))[0])==null?void 0:$.result)!=null&&x.started))throw new Error("无法启动B站专栏投稿脚本");return}}else if(E.status==="complete")throw new Error("B站专栏未进入编辑页,请先完成登录");await new Promise(v=>setTimeout(v,500))}if(xe.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=xe.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 Me=!1,be=null,Ft=Promise.resolve();const _t=new Set;function Ee(e){const t=Ft.catch(()=>{}).then(e);return Ft=t.then(()=>{},()=>{}),t}function $t(){return Me}async function ki(e){await Ee(async()=>{const r=(await chrome.storage.local.get(Q.draftIndex))[Q.draftIndex]||[],{id:i,title:a,updatedAt:n,source:s}=e;await chrome.storage.local.set({[`writedockDraft:${i}`]:e,[Q.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 Tt(e){const t=await or();return(t==null?void 0:t.id)===e?t:(await Ct()).find(r=>r.id===e)||null}async function pt(){const e=await chrome.storage.local.get([Q.activeTask,Q.history,Q.lastInput]),t=e[Q.activeTask]||null,r=e[Q.history]||[],i=e[Q.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(Q.activeTask),i&&!h&&w.push(Q.lastInput),y.length!==r.length&&await chrome.storage.local.set({[Q.history]:y}),w.length&&await chrome.storage.local.remove(w),{active:c,history:y,last:h}}async function Ye(){if(!be)return;const e=structuredClone(be);await Ee(async()=>{await chrome.storage.local.set({[Q.activeTask]:e}),chrome.runtime.sendMessage({type:"TASK_UPDATED",task:e}).catch(()=>{})})}async function or(){return Me&&be?structuredClone(be):Ee(async()=>{const{active:e}=await pt();return Me&&be?structuredClone(be):((e==null?void 0:e.status)==="syncing"&&(e.status="interrupted",e.finishedAt=Date.now(),e.error="上次任务被中断。请把原稿件或平台后台链接交给用户自行核对,Agent 不要调用浏览器或重新投稿。",await chrome.storage.local.set({[Q.activeTask]:e})),e)})}async function Ct(){return Ee(async()=>(await pt()).history)}async function $i(e){return Ee(async()=>{const{last:t}=await pt();if(!t||t.taskId!==e)throw new Error("该任务的原始内容已被替换,请打开原稿后重新同步");return t.input})}async function Ti(e){if(typeof e!="string"||!e)throw new Error("草稿信息不完整");if(Me&&(be==null?void 0:be.draftId)===e)throw new Error("这篇文章正在同步,请等待同步结束后再删除");_t.add(e);try{return await Ee(async()=>{var c,y;const t=await chrome.storage.local.get([Q.draftIndex,Q.activeDraft,Q.activeTask,Q.history,Q.lastInput,Q.agentRequests]),r=(t[Q.draftIndex]||[]).filter(h=>h.id!==e),i=(t[Q.history]||[]).filter(h=>h.draftId!==e),a=[`writedockDraft:${e}`],n=((c=t[Q.activeTask])==null?void 0:c.draftId)===e;n&&a.push(Q.activeTask),((y=t[Q.lastInput])==null?void 0:y.input.draftId)===e&&a.push(Q.lastInput),t[Q.activeDraft]===e&&a.push(Q.activeDraft);const s=t[Q.agentRequests]||{},o=Object.fromEntries(Object.entries(s).map(([h,w])=>[h,w.draftId===e?{...w,deleted:!0}:w]));return await chrome.storage.local.set({[Q.draftIndex]:r,[Q.history]:i,[Q.agentRequests]:o}),await chrome.storage.local.remove(a),(be==null?void 0:be.draftId)===e&&(be=null),n&&await chrome.action.setBadgeText({text:""}).catch(()=>{}),chrome.runtime.sendMessage({type:"DRAFT_DELETED",draftId:e}).catch(()=>{}),r})}finally{_t.delete(e)}}async function Ci(e){var i;let t=await it(e);if(!t.isAuthenticated&&t.error&&(t=await it(e)),t.isAuthenticated)return;const r=((i=Le().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 Dt(e,t={}){var p;if(Me)throw new Error("已有一项同步正在进行,请等待完成");if(_t.has(e==null?void 0:e.draftId))throw new Error("草稿正在删除,无法同步");const r=St(e==null?void 0:e.platforms,Le().map(u=>u.id)),i=e.post?De(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=>!At(u)):r.some(u=>ut(u)&&!(a&&u==="xiaohongshu")))throw new Error("普通图文/视频用 publish_post,小红书长文及平台文章用 publish_article,需分别提交;旧草稿调用不会自动公开发布");if(i&&ht(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=xt(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 目前用于百家号和微博长文章")}Me=!0,be={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=be,w=new Map,m=(u,g)=>{var D;h.progress[u]=g,g.stage==="waiting_verification"&&((D=w.get(u))==null||D()),Ye().catch(S=>console.warn("[WriteDock] Progress could not be saved:",S))};try{await Ee(async()=>{if(await chrome.storage.local.getBytesInUse(`writedockDraft:${e.draftId}`)===0)throw new Error("这篇草稿已被删除,请重新打开写作台");const{discardOldDrafts:S,...b}=e;await chrome.storage.local.set({[Q.lastInput]:{taskId:h.id,input:b}})}),await Ye(),(p=t.onStarted)==null||p.call(t,structuredClone(h));const u=s||i||a?1:3,g=[];for(let S=0;S<r.length;S+=u){const b=r.slice(S,S+u),d=Promise.all(b.map(async f=>{var v,k;let l;const _=s==null?void 0:s.find(O=>O.platform===f),$=_?_.mode==="post":!!i,x=_?_.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),$&&i)l=await ri(f,i,O=>m(f,O),f==="douyin"&&c?{...o,discardOldDraft:c}:o);else if(x&&f==="xiaohongshu")l=await Kr(e.article.title.trim(),e.article.html||"",O=>m(f,O),o);else{const O=await Yt(f),z=await Lr(e.article.html||"",Dr(f));for(const{marker:I,asset:R}of y){if(!(O instanceof Zt)||z.html.split(I).length!==2)throw new Error("文章视频占位符在排版后不完整,已停止发布");m(f,{stage:"uploading_media",current:0,total:R.size});const L=await O.uploadArticleVideo(R,(P,A)=>kt(R,P,A),(P,A)=>m(f,{stage:"uploading_media",current:P,total:A})),N=qe(L.cover),B=`<a class="video-link" href="https://www.zhihu.com/video/${L.videoId}" data-src="" data-name="${qe(R.name)}" data-poster="${N}" data-video-id="" data-lens-id="${L.videoId}" data-video-playable="true"><img src="${N}" alt="${qe(R.name)}"><span>${qe(R.name)}</span></a>`;z.html=z.html.replace(I,B)}if(m(f,{stage:x?"preparing_article":"saving"}),x&&f==="bilibili")l=await xi(e.article.title.trim(),z.html,I=>m(f,I),o);else{const I=await bt(O.publish({...E,...z,...x&&f==="zhihu"?{cover:void 0}:{}},{draftOnly:!0,onImageProgress:(R,L)=>{m(f,{stage:R>=L?x?"preparing_article":"saving":"uploading_images",current:R,total:L})}}),6e5,"准备平台稿件超时,请先检查平台后台,再决定是否重试");if(x){if(!I.success||!I.postId)throw new Error(I.error||"平台稿件准备失败,未提交发布");const R=f==="zhihu"?fi:f==="weibo"?Ei:yi,L=(z.html.replace(/<a class="video-link"[\s\S]*?<\/a>/g,"").match(/<img\b/gi)||[]).length;l=await R(String(I.postId),e.article.title.trim(),N=>m(f,N),{...o,imageCount:L})}else l=I}}}catch(O){l={platform:f,success:!1,error:O instanceof Error?O.message:"同步失败,请稍后重试",timestamp:Date.now(),...$||x?{draftOnly:!1,publicationState:"failed"}:{},...O.errorCode?{errorCode:O.errorCode}:{}}}(v=_==null?void 0:_.notes)!=null&&v.length&&(l={...l,warnings:[..._.notes,...l.warnings||[]]}),l.success||(l={...l,diagnostics:{...l.diagnostics,stage:(k=h.progress[f])==null?void 0:k.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 Ye()}));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 Ye(),await Ee(async()=>{const{history:S}=await pt();await chrome.storage.local.set({[Q.history]:[structuredClone(h),...S].slice(0,25)})});const D=h.results.filter(S=>S.success||S.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 Ye().catch(()=>{}),u}finally{Me=!1}}let Wt=Promise.resolve();function ft(e){const t=Wt.catch(()=>{}).then(e);return Wt=t,t}async function Lt(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&&!et(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=xt(t.videos,r);return{title:t.title.trim(),html:r,markdown:"",...t.cover?{cover:t.cover}:{},...i.length?{videos:i}:{}}}async function mt(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 ft(async()=>{var i;const t=await Lt(e),r=await mt(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 ft(async()=>{const t=De(e);return{draft_id:(await mt(Rt(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 Ut(e){const r=(await chrome.storage.local.get(Q.agentRequests))[Q.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"})}},nt=(e,t=!1)=>{var n;const r=Le(),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=et(((y=s.userAction)==null?void 0:y.url)||s.postUrl)||et((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=et((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=et(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 Qe(e){return ft(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 Ut(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=St(e.platforms,Le().map(S=>S.id)),n=e.publication===!0,s=e.publication==="article";if(t&&!n&&!s)throw new Error("演练只支持发布类平台;公众号、搜狐号只保存草稿,无需演练");if(n&&a.some(S=>!At(S)))throw new Error("publish_post 支持小红书、抖音和微博普通图文/视频;知乎、百家号、微博长文章、B站专栏请用 publish_article");if(!n&&a.some(S=>ut(S)&&!(s&&S==="xiaohongshu")))throw new Error("小红书长文请用 publish_article;小红书、抖音图文/视频请用 publish_post;旧草稿调用不会自动公开发布");if(s&&a.some(S=>!["zhihu","baijiahao","weibo","bilibili","xiaohongshu"].includes(S)))throw new Error("publish_article 目前接入知乎、百家号、微博长文章、B站专栏和小红书长文");if(!i&&!n&&!s&&a.some(S=>["zhihu","baijiahao","weibo","bilibili"].includes(S)))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=De(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:xt(o.videos,o.html)}:{}}}else n?(y=De(e.post),c=Rt(y)):c=await Lt(e.article);if(y&&ht(y,a),(D=c.videos)!=null&&D.length&&(!s||a.some(S=>S!=="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(S=>["baijiahao","weibo"].includes(S))&&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),S=>S.toString(16).padStart(2,"0")).join("");if(i){if(i.fingerprint!==p)throw new Error("同一个 request_id 对应的稿件或平台已改变;请使用新的 request_id");const S=await Tt(i.taskId);if(!S)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return nt(S,!0)}if($t())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");o??(o=await mt(c,a,y));const u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Ee(async()=>{const S=await chrome.storage.local.get(Q.agentRequests);await chrome.storage.local.set({[Q.agentRequests]:{...S[Q.agentRequests]||{},[r]:{fingerprint:p,draftId:o.id,taskId:u}}})});try{const S=await new Promise((b,d)=>{Dt({draftId:o.id,platforms:a,article:c,...y?{post:y}:{},...s?{publication:"article"}:{},...t?{rehearsal:!0}:{}},{taskId:u,onStarted:b}).catch(d)});return nt(S)}catch(S){throw t||await Ee(async()=>{const d={...(await chrome.storage.local.get(Q.agentRequests))[Q.agentRequests]||{}};delete d[r],await chrome.storage.local.set({[Q.agentRequests]:d})}),S}})}async function jt(e){return ft(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 Ut(r);if(i!=null&&i.deleted)throw new Error("原任务的稿件已被删除,旧 request_id 不会重新提交;如需新同步,请明确使用新的 request_id");const a=St(e.platforms,Le().map(g=>g.id));if(!e.article&&!e.post)throw new Error("请提供 article(文章)或 post(图文/视频)内容");const n=e.article?await Lt(e.article):void 0,s=e.post?De(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||Rt(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 Tt(i.taskId);if(!g)throw new Error("原任务结果已不在最近记录中。不会重新提交,请先检查平台后台");return nt(g,!0)}if($t())throw new Error("已有同步正在进行,请查询当前任务完成后再提交");const p=await mt(c,a,s),u=`${t?"rehearsal":"sync"}_${crypto.randomUUID()}`;t||await Ee(async()=>{const g=await chrome.storage.local.get(Q.agentRequests);await chrome.storage.local.set({[Q.agentRequests]:{...g[Q.agentRequests]||{},[r]:{fingerprint:m,draftId:p.id,taskId:u}}})});try{const g=await new Promise((D,S)=>{Dt({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(S)});return nt(g)}catch(g){throw t||await Ee(async()=>{const S={...(await chrome.storage.local.get(Q.agentRequests))[Q.agentRequests]||{}};delete S[r],await chrome.storage.local.set({[Q.agentRequests]:S})}),g}})}async function Oi(e){let t=e.taskId;if(typeof e.requestId=="string"){const i=await Ut(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 Tt(t);if(!r)throw new Error("任务不存在,或已超出最近 25 条记录的保留范围");return nt(r)}const Ot="writedock-mcp-reconnect";let Et,_e=null,tt,Pt=0,lt=!1,at,st=!1,dt={};const sr=()=>Array.from(crypto.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join("");async function ot(){return Et??(Et=(async()=>{const t=(await chrome.storage.local.get(Q.bridge))[Q.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({[Q.bridge]:r}),r})()),Et}async function ct(e,t){lt=e,at=t,e||(dt={}),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(dt)&&(dt=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 ot();return{...e,connected:lt,...dt,...at?{error:at}:{},...lt?{}:await qi(e.port)}}let Fe;async function Mi(){if($t())throw new Error("正在发布,请等任务结束后再更新");if(!_e||_e.readyState!==WebSocket.OPEN||!lt)throw new Error("还没有连接,无法更新");const e=await new Promise((t,r)=>{const i=setTimeout(()=>{Fe=void 0,r(new Error("更新超时,请稍后再试"))},6e4);Fe={resolve:a=>{clearTimeout(i),Fe=void 0,t(a)}},_e.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(st)throw new Error("正在连接,请稍候");st=!0;try{const e=await ot(),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 at=void 0,await lr(e,{...e,...t,enabled:!0})}finally{st=!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({[Q.bridge]:t}),Et=Promise.resolve(t),r){clearTimeout(tt),tt=void 0,Pt=0;const i=_e;_e=null,i==null||i.close(),await ct(!1),t.enabled?await rt():await chrome.alarms.clear(Ot)}return cr()}async function Ni(e){if(st)throw new Error("正在连接,请完成后再修改设置");const t=await ot(),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=Le().find(i=>i.id===t.platform);if(!r)throw new Error("扩展没有此平台的适配器");return{...r,...await it(t.platform)}}case"prepareArticle":return Di(t.article);case"preparePost":return Li(t.post);case"publishPost":return Qe({...t,publication:!0,rehearsal:!1});case"publishArticle":return Qe({...t,publication:"article",rehearsal:!1});case"syncArticle":return Qe({...t,publication:void 0,rehearsal:!1});case"publish":return jt({...t,rehearsal:!1});case"rehearsePublish":return jt({...t,rehearsal:!0});case"rehearsePost":return Qe({...t,publication:!0,rehearsal:!0});case"rehearseArticle":return Qe({...t,publication:"article",rehearsal:!0});case"getSyncTask":return Oi(t);case"getSyncHistory":return Ct();default:throw new Error("不支持的 MCP 操作")}}async function Hi(){tt||!(await ot()).enabled||(tt=setTimeout(()=>{tt=void 0,rt()},Math.min(500*2**Math.min(Pt++,5),1e4)))}async function rt(){const e=await ot();if(!e.enabled||(await chrome.alarms.create(Ot,{periodInMinutes:1}),_e&&(_e.readyState===WebSocket.OPEN||_e.readyState===WebSocket.CONNECTING)))return;const t=new WebSocket(`ws://127.0.0.1:${e.port}/extension`);_e=t;let r=!1,i=!1;const a=setTimeout(()=>{r||t.close(1008,"Handshake timed out")},8e3);t.onmessage=n=>{(async()=>{if(_e!==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 ct(!1,"连接已失效,请点“连接”重新连上"),t.close(1008,"Handshake failed");return}if(_e!==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,Pt=0,clearTimeout(a),Jt(s),await ct(!0);return}if(!r)throw new Error("WriteDock 服务尚未连接");if(s.type==="update_extension_result"){Fe==null||Fe.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),_e===t&&(_e=null,ct(!1,at||(n.code===1008?"连接没有成功,请点“连接”重试;如果另一个浏览器也装了 WriteDock,请先关掉它":"等待 agent 启动 MCP 服务")),Hi())},t.onerror=()=>{}}function Fi(){chrome.alarms.onAlarm.addListener(e=>{e.name===Ot&&rt()}),chrome.runtime.onStartup.addListener(()=>{rt()}),rt().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(Q.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 Le();case"CHECK_ALL_AUTH":return Qt(e.forceRefresh===!0);case"CHECK_AUTH":return it(e.platform);case"SYNC_ARTICLE":return Dt(e.payload);case"GET_SYNC_STATE":return or();case"GET_SYNC_HISTORY":return Ct();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();