publishport-opencli 1.0.55 → 1.0.58

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.
Files changed (38) hide show
  1. package/cli-manifest.json +8 -1
  2. package/clis/_shared/article/images.js +5 -5
  3. package/clis/_shared/article/page-runtime.js +13 -4
  4. package/clis/_shared/article/publish.js +11 -11
  5. package/clis/baijiahao/article.js +2 -2
  6. package/clis/bilibili/article.js +1 -1
  7. package/clis/bilibili/comment.js +1 -1
  8. package/clis/cnblogs/article.js +1 -1
  9. package/clis/csdn/article.js +5 -5
  10. package/clis/cto51/article.js +1 -1
  11. package/clis/douyin/publish.js +8 -8
  12. package/clis/eastmoney/article.js +1 -1
  13. package/clis/imooc/article.js +3 -3
  14. package/clis/infoq/article.js +2 -2
  15. package/clis/jianshu/article.js +1 -1
  16. package/clis/juejin/article.js +4 -4
  17. package/clis/medium/article.js +4 -4
  18. package/clis/oschina/article.js +1 -1
  19. package/clis/segmentfault/article.js +3 -3
  20. package/clis/sohu/article.js +1 -1
  21. package/clis/toutiao/article.js +1 -1
  22. package/clis/wechat-channels/publish.js +111 -22
  23. package/clis/weibo/article.js +1 -1
  24. package/clis/weixin/article.js +1 -1
  25. package/clis/woshipm/article.js +1 -1
  26. package/clis/xianyu/im.js +1 -1
  27. package/clis/xiaohongshu/_shared/publish-settings.js +8 -1
  28. package/clis/xiaohongshu/human.js +2 -2
  29. package/clis/xiaohongshu/publish-video.js +1 -1
  30. package/clis/xiaohongshu/publish.js +21 -19
  31. package/clis/xueqiu/article.js +2 -2
  32. package/clis/yuque/article.js +1 -1
  33. package/clis/zhihu/answer.js +1 -1
  34. package/clis/zhihu/article.js +1 -1
  35. package/clis/zhihu/write-shared.js +3 -3
  36. package/dist/src/execution.d.ts +9 -0
  37. package/dist/src/execution.js +2 -2
  38. package/package.json +2 -1
@@ -1 +1 @@
1
- import{CliError as i,CommandExecutionError as v}from"@jackwener/opencli/errors";import{cli as U,Strategy as D}from"@jackwener/opencli/registry";import{publishArticle as O,gotoWritePage as R}from"../_shared/article/publish.js";import{SOHU_MPBP_HEADERS_JS as x,readSohuMpbpHeaders as L,sohuMpbpMessage as C}from"./mpbp.js";function M(){const s="0123456789abcdef";let n="";for(let t=0;t<32;t++)n+=s[Math.floor(Math.random()*s.length)];return n}export const sohuProfile={home:"https://mp.sohu.com/mpfe/v3/main/first/page?newsType=1",outputFormat:"html",preprocessConfig:{},checkAuth:async(s)=>{try{const t=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(t.code!==2000000||!t.data?.data?.length)return{isAuthenticated:!1};const o=[];for(const a of t.data.data)if(a.accounts)o.push(...a.accounts);if(!o.length)return{isAuthenticated:!1};const e=o[0],r=o.length>1?e.nickName+"(共"+o.length+"个子账号)":e.nickName;return{isAuthenticated:!0,userId:String(e.id),username:r,avatar:e.avatar||""}}catch(n){return{isAuthenticated:!1,error:String(n&&n.message||n)}}},image:{skip:["sohu.com"],uploadFn:async(s,n)=>{const o=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(o.code!==2000000||!o.data?.data?.length)throw Error("获取搜狐账号信息失败,请确认已登录搜狐号");const e=[];for(const m of o.data.data)if(m.accounts)e.push(...m.accounts);if(!e.length)throw Error("搜狐号子账号列表为空");const r=String(e[0].id),a=await fetch(s,{credentials:"omit"});if(!a.ok)throw Error("图片下载失败("+a.status+"):"+s);const c=await a.blob(),u=new FormData;u.append("file",c,"image.jpg");u.append("accountId",r);const h=await(await fetch("https://mp.sohu.com/commons/front/outerUpload/image/file?accountId="+r,{method:"POST",credentials:"include",body:u})).json();if(!h.url)throw Error("搜狐图片上传失败:"+(h.msg||JSON.stringify(h).slice(0,100)));return{url:h.url}}},publish:async(s,n)=>{const t=s.params||{},o=await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"}),e=await o.json();if(e.code!==2000000||!e.data?.data?.length)return{ok:!1,stage:"auth",status:o.status,message:"获取搜狐账号信息失败,请确认已登录搜狐号"};const r=[];for(const d of e.data.data)if(d.accounts)r.push(...d.accounts);if(!r.length)return{ok:!1,stage:"auth",status:0,message:"搜狐号子账号列表为空"};const a=Number(r[0].id),c=t.headers;if(!c||!c["sp-cm"])return{ok:!1,stage:"params",status:0,message:"缺少搜狐客户端请求头(P.headers),请由 Node 侧 readSohuMpbpHeaders 取值后传入"};const u=Number(t.channelId);if(!Number.isFinite(u)||u<=0)return{ok:!1,stage:"params",status:0,message:"缺少合法 channelId(频道 id),请先用 `sohu channels` 取值"};const I=t.categoryId==null||t.categoryId===""?-1:Number(t.categoryId),h={title:s.title,brief:typeof t.brief==="string"?t.brief:"",content:s.content,channelId:u,categoryId:I,id:0,userColumnId:t.userColumnId==null||t.userColumnId==-1?0:Number(t.userColumnId),columnNewsIds:Array.isArray(t.columnNewsIds)?t.columnNewsIds:[],businessCode:0,declareOriginal:Boolean(t.declareOriginal),cover:typeof t.cover==="string"?t.cover:"",topicIds:Array.isArray(t.topicIds)?t.topicIds:[],isAd:0,userLabels:"[]",reprint:!1,customTags:typeof t.customTags==="string"?t.customTags:"",infoResource:0,sourceUrl:"",visibleToLoginedUsers:0,attrIds:Array.isArray(t.attrIds)?t.attrIds:[],accountId:a};if(s.draftOnly){const d=Object.assign({},h,{auto:!0}),p=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/draft/v2?accountId="+a,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(d)}),A=await p.text();let g=null;try{g=JSON.parse(A)}catch(F){}if(!p.ok||!g||!g.success)return{ok:!1,stage:"draft",status:p.status,message:g&&g.msg||A.slice(0,300)};const T=String(g.data),j="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=2&id="+T;return{ok:!0,id:T,url:j,draft:!0}}const m=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/publish/v2?accountId="+a,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(h)}),b=await m.text();let l=null;try{l=JSON.parse(b)}catch(d){}if(!m.ok||!l||l.code!==2000000){let d=l&&(l.msg||l.message)||"";if(!d){const p=[];if(I!==-1)p.push("--category");if(Array.isArray(t.topicIds)&&t.topicIds.length>0)p.push("--topics");if(h.cover)p.push("--cover");d="搜狐发布接口返回非 JSON 错误页(HTTP "+m.status+")。"+(p.length?"实测该 500 多由可选参数触发——去掉 "+p.join(" / ")+"、只保留必填 --channel 重试即可。":"稍后重试;若持续失败,用 `sohu stats` 确认是否已产生重复内容。")}return{ok:!1,stage:"publish",status:m.status,message:d}}if(l.data!=null&&Object.prototype.toString.call(l.data)==="[object Object]")return{ok:!1,stage:"origin_check",status:m.status,message:"声明原创触发了原创校验(需在搜狐后台完成原创确认):"+JSON.stringify(l.data).slice(0,200)};const w=String(l.data),f="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=1&id="+w,N="https://www.sohu.com/a/"+w+"_"+a;return{ok:!0,id:w,url:f,publicUrl:N,draft:!1}}},sohuAuthProfile={home:sohuProfile.home,checkAuth:sohuProfile.checkAuth};function S(s){if(!s.execute)throw new i("INVALID_INPUT","此命令需要 --execute 才会真正写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function _(s){const n=typeof s.text==="string"?s.text:void 0,t=typeof s.file==="string"?s.file:void 0;if(n&&t)throw new i("INVALID_INPUT","text 和 --file 只能二选一");let o=n??"";if(t){const{readFile:e,stat:r}=await import("node:fs/promises");let a;try{a=await r(t)}catch{throw new i("INVALID_INPUT","文件不存在:"+t)}if(!a.isFile())throw new i("INVALID_INPUT","路径不是可读文本文件:"+t);let c;try{c=await e(t)}catch{throw new i("INVALID_INPUT","文件读取失败:"+t)}try{o=new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch{throw new i("INVALID_INPUT","文件不是合法 UTF-8 编码:"+t)}}if(!o.trim())throw new i("INVALID_INPUT","正文不能为空");return o}function P(s,n,t,o,e={}){return[{status:"success",outcome:o,message:s,target_type:n,target:t,...e}]}async function y(s,n,t){const o="(async () => {try {"+x+"const r = await fetch("+JSON.stringify(n)+', { method: "GET", credentials: "include", headers: HDRS });const t = await r.text();let j = null; try { j = JSON.parse(t); } catch (e) {}return { ok: r.ok, status: r.status, json: j, text: t.slice(0, 300) };} catch (e) { return { ok: false, status: 0, json: null, text: String((e && e.message) || e) }; }})()',e=await s.evaluate(o);if(!e||!e.ok||!e.json)throw new i("INVALID_INPUT","搜狐"+t+"接口请求失败(HTTP "+(e?e.status:"?")+"):"+(e?e.text:""));if(e.json.success===!1||e.json.code!=null&&e.json.code!==2000000&&e.json.code!==2000)throw new i("INVALID_INPUT","搜狐"+t+"接口返回错误:"+C(e.json));return e.json}async function V(s){const n=await y(s,"https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),"账号列表"),t=n.data&&n.data.data||[],o=[];for(const e of t)if(e.accounts)o.push(...e.accounts);if(!o.length)throw new i("INVALID_INPUT","搜狐号子账号列表为空,请确认已登录搜狐号");return String(o[0].id)}async function E(s,n,t){const o=await y(s,"https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId="+encodeURIComponent(n),"频道列举"),e=Array.isArray(o)?o:o.data||[],r=e.find((a)=>String(a.name)===String(t));if(!r)throw new i("INVALID_INPUT","未找到频道「"+t+"」,可选:"+(e.map((a)=>a.name).join(" / ")||"(空)")+"。用 `sohu channels` 查看完整列表。");return Number(r.id!=null?r.id:r.channelId)}async function H(s,n,t,o){const e=await y(s,"https://mp.sohu.com/mpbp/bp/account/common/channels/"+t+"/categories?accountId="+encodeURIComponent(n),"分类列举"),r=Array.isArray(e)?e:e.data||[],a=r.find((c)=>String(c.name)===String(o));if(!a)throw new i("INVALID_INPUT","频道(id="+t+")下未找到分类「"+o+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(该频道无分类)")+"。用 `sohu categories --channel <频道名>` 查看。");return Number(a.id)}async function J(s,n,t){const o=await y(s,"https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId="+encodeURIComponent(n)+"&page=1&size=100","专栏列举"),e=Array.isArray(o)?o:o.data&&(o.data.data||o.data)||o.data||[],r=Array.isArray(e)?e:[],a=r.find((c)=>String(c.name)===String(t));if(!a)throw new i("INVALID_INPUT","未找到专栏「"+t+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(你还没有任何专栏)")+"。用 `sohu columns` 查看。");return Number(a.id)}async function k(s,n,t){const o=t.split(",").map((r)=>r.trim()).filter(Boolean);if(!o.length)return[];const e=[];for(const r of o){const a=await y(s,"https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId="+n+"&keyword="+encodeURIComponent(r),"话题搜索"),u=(Array.isArray(a)?a:a.data||[]).find((I)=>String(I.name)===String(r));if(!u)throw new i("INVALID_INPUT","未找到话题「"+r+"」,请用 `sohu topics --keyword "+r+"` 搜索确认确切名称。");e.push(u.id)}return e}U({site:"sohu",name:"article",access:"write",description:"发布文章到搜狐号(HTML 格式,外链图片自动转存到搜狐图床)。默认正式发布,加 --draft 仅存草稿。频道必填,合法值用 `sohu channels` 取。",domain:"mp.sohu.com",strategy:D.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown,传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 或 HTML)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"channel",help:"频道名(精确匹配,必填),合法值用 `sohu channels` 列举"},{name:"category",help:"分类名(精确匹配,依赖所选频道),合法值用 `sohu categories --channel <频道名>` 列举;不传=不限"},{name:"column",help:"专栏名(精确匹配),合法值用 `sohu columns` 列举;不传=不归属专栏"},{name:"topics",help:"话题名,逗号分隔(每个精确匹配),用 `sohu topics` 搜索取确切名"},{name:"cover",help:"封面图 URL(须为搜狐图床地址);可空"},{name:"brief",help:"文章摘要;可空"},{name:"declare-original",type:"boolean",help:"声明原创(会触发搜狐原创校验,发布将被拦到原创确认流程)"},{name:"draft",type:"boolean",help:"仅保存草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入操作;不加此参数则拒绝写入(干跑保护)"}],columns:["status","outcome","message","target_type","target","created_target","created_url","public_url"],func:async(s,n)=>{if(!s)throw new v("搜狐号文章发布需要浏览器会话");S(n);const t=String(n.title??"").trim();if(!t)throw new i("INVALID_INPUT","文章标题不能为空");const o=await _(n),e=Boolean(n.draft),r=typeof n.channel==="string"?n.channel.trim():"";if(!r)throw new i("INVALID_INPUT","缺少 --channel(频道名)。请先运行 `sohu channels` 取合法频道名再传入,不提供默认值。");await R(s,sohuProfile.home);const a=await V(s),c=await E(s,a,r);let u=-1;const I=typeof n.category==="string"?n.category.trim():"";if(I)u=await H(s,a,c,I);let h=0;const m=typeof n.column==="string"?n.column.trim():"";if(m)h=await J(s,a,m);let b=[];const l=typeof n.topics==="string"?n.topics.trim():"";if(l)b=await k(s,a,l);const w={channelId:c,categoryId:u,userColumnId:h,topicIds:b,cover:typeof n.cover==="string"?n.cover.trim():"",brief:typeof n.brief==="string"?n.brief:"",declareOriginal:Boolean(n["declare-original"]),headers:await L(s)},f=await O(s,{title:t,body:o,format:n.html?"html":"markdown",draftOnly:e,profile:sohuProfile,publishParams:w}),N=f.images.uploaded.length|0,d=f.images.failed.length|0;let p=f.draft?"已保存搜狐号草稿":"已正式发布到搜狐号";if(N||d)p+=`;图片:${N} 张已转存${d?`,${d} 张失败`:""}`;return P(p,"article","",f.draft?"draft":"created",{created_target:(f.draft?"draft:":"article:")+f.id,created_url:f.url,public_url:f.publicUrl||""})}});export const __test__={sohuProfile,requireExecute:S,buildResultRow:P,resolvePayload:_,generateDeviceId:M};
1
+ import{CliError as i,CommandExecutionError as v}from"@jackwener/opencli/errors";import{cli as U,Strategy as D}from"@jackwener/opencli/registry";import{formatImageReport as R,publishArticle as O,gotoWritePage as x}from"../_shared/article/publish.js";import{SOHU_MPBP_HEADERS_JS as L,readSohuMpbpHeaders as C,sohuMpbpMessage as M}from"./mpbp.js";import{rememberArticleFile as V}from"../_shared/article/images.js";function E(){const a="0123456789abcdef";let o="";for(let t=0;t<32;t++)o+=a[Math.floor(Math.random()*a.length)];return o}export const sohuProfile={home:"https://mp.sohu.com/mpfe/v3/main/first/page?newsType=1",outputFormat:"html",preprocessConfig:{},checkAuth:async(a)=>{try{const t=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(t.code!==2000000||!t.data?.data?.length)return{isAuthenticated:!1};const n=[];for(const s of t.data.data)if(s.accounts)n.push(...s.accounts);if(!n.length)return{isAuthenticated:!1};const e=n[0],r=n.length>1?e.nickName+"(共"+n.length+"个子账号)":e.nickName;return{isAuthenticated:!0,userId:String(e.id),username:r,avatar:e.avatar||""}}catch(o){return{isAuthenticated:!1,error:String(o&&o.message||o)}}},image:{skip:["sohu.com"],uploadFn:async(a,o)=>{const n=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(n.code!==2000000||!n.data?.data?.length)throw Error("获取搜狐账号信息失败,请确认已登录搜狐号");const e=[];for(const h of n.data.data)if(h.accounts)e.push(...h.accounts);if(!e.length)throw Error("搜狐号子账号列表为空");const r=String(e[0].id),s=await fetch(a,{credentials:"omit"});if(!s.ok)throw Error("图片下载失败("+s.status+"):"+a);const c=await s.blob(),u=new FormData;u.append("file",c,"image.jpg");u.append("accountId",r);const m=await(await fetch("https://mp.sohu.com/commons/front/outerUpload/image/file?accountId="+r,{method:"POST",credentials:"include",body:u})).json();if(!m.url)throw Error("搜狐图片上传失败:"+(m.msg||JSON.stringify(m).slice(0,100)));return{url:m.url}}},publish:async(a,o)=>{const t=a.params||{},n=await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"}),e=await n.json();if(e.code!==2000000||!e.data?.data?.length)return{ok:!1,stage:"auth",status:n.status,message:"获取搜狐账号信息失败,请确认已登录搜狐号"};const r=[];for(const d of e.data.data)if(d.accounts)r.push(...d.accounts);if(!r.length)return{ok:!1,stage:"auth",status:0,message:"搜狐号子账号列表为空"};const s=Number(r[0].id),c=t.headers;if(!c||!c["sp-cm"])return{ok:!1,stage:"params",status:0,message:"缺少搜狐客户端请求头(P.headers),请由 Node 侧 readSohuMpbpHeaders 取值后传入"};const u=Number(t.channelId);if(!Number.isFinite(u)||u<=0)return{ok:!1,stage:"params",status:0,message:"缺少合法 channelId(频道 id),请先用 `sohu channels` 取值"};const I=t.categoryId==null||t.categoryId===""?-1:Number(t.categoryId),m={title:a.title,brief:typeof t.brief==="string"?t.brief:"",content:a.content,channelId:u,categoryId:I,id:0,userColumnId:t.userColumnId==null||t.userColumnId==-1?0:Number(t.userColumnId),columnNewsIds:Array.isArray(t.columnNewsIds)?t.columnNewsIds:[],businessCode:0,declareOriginal:Boolean(t.declareOriginal),cover:typeof t.cover==="string"?t.cover:"",topicIds:Array.isArray(t.topicIds)?t.topicIds:[],isAd:0,userLabels:"[]",reprint:!1,customTags:typeof t.customTags==="string"?t.customTags:"",infoResource:0,sourceUrl:"",visibleToLoginedUsers:0,attrIds:Array.isArray(t.attrIds)?t.attrIds:[],accountId:s};if(a.draftOnly){const d=Object.assign({},m,{auto:!0}),p=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/draft/v2?accountId="+s,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(d)}),A=await p.text();let g=null;try{g=JSON.parse(A)}catch(G){}if(!p.ok||!g||!g.success)return{ok:!1,stage:"draft",status:p.status,message:g&&g.msg||A.slice(0,300)};const T=String(g.data),j="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=2&id="+T;return{ok:!0,id:T,url:j,draft:!0}}const h=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/publish/v2?accountId="+s,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(m)}),b=await h.text();let l=null;try{l=JSON.parse(b)}catch(d){}if(!h.ok||!l||l.code!==2000000){let d=l&&(l.msg||l.message)||"";if(!d){const p=[];if(I!==-1)p.push("--category");if(Array.isArray(t.topicIds)&&t.topicIds.length>0)p.push("--topics");if(m.cover)p.push("--cover");d="搜狐发布接口返回非 JSON 错误页(HTTP "+h.status+")。"+(p.length?"实测该 500 多由可选参数触发——去掉 "+p.join(" / ")+"、只保留必填 --channel 重试即可。":"稍后重试;若持续失败,用 `sohu stats` 确认是否已产生重复内容。")}return{ok:!1,stage:"publish",status:h.status,message:d}}if(l.data!=null&&Object.prototype.toString.call(l.data)==="[object Object]")return{ok:!1,stage:"origin_check",status:h.status,message:"声明原创触发了原创校验(需在搜狐后台完成原创确认):"+JSON.stringify(l.data).slice(0,200)};const w=String(l.data),f="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=1&id="+w,N="https://www.sohu.com/a/"+w+"_"+s;return{ok:!0,id:w,url:f,publicUrl:N,draft:!1}}},sohuAuthProfile={home:sohuProfile.home,checkAuth:sohuProfile.checkAuth};function S(a){if(!a.execute)throw new i("INVALID_INPUT","此命令需要 --execute 才会真正写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function _(a){const o=typeof a.text==="string"?a.text:void 0,t=typeof a.file==="string"?a.file:void 0;if(o&&t)throw new i("INVALID_INPUT","text 和 --file 只能二选一");let n=o??"";if(t){V(t);const{readFile:e,stat:r}=await import("node:fs/promises");let s;try{s=await r(t)}catch{throw new i("INVALID_INPUT","文件不存在:"+t)}if(!s.isFile())throw new i("INVALID_INPUT","路径不是可读文本文件:"+t);let c;try{c=await e(t)}catch{throw new i("INVALID_INPUT","文件读取失败:"+t)}try{n=new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch{throw new i("INVALID_INPUT","文件不是合法 UTF-8 编码:"+t)}}if(!n.trim())throw new i("INVALID_INPUT","正文不能为空");return n}function P(a,o,t,n,e={}){return[{status:"success",outcome:n,message:a,target_type:o,target:t,...e}]}async function y(a,o,t){const n="(async () => {try {"+L+"const r = await fetch("+JSON.stringify(o)+', { method: "GET", credentials: "include", headers: HDRS });const t = await r.text();let j = null; try { j = JSON.parse(t); } catch (e) {}return { ok: r.ok, status: r.status, json: j, text: t.slice(0, 300) };} catch (e) { return { ok: false, status: 0, json: null, text: String((e && e.message) || e) }; }})()',e=await a.evaluate(n);if(!e||!e.ok||!e.json)throw new i("INVALID_INPUT","搜狐"+t+"接口请求失败(HTTP "+(e?e.status:"?")+"):"+(e?e.text:""));if(e.json.success===!1||e.json.code!=null&&e.json.code!==2000000&&e.json.code!==2000)throw new i("INVALID_INPUT","搜狐"+t+"接口返回错误:"+M(e.json));return e.json}async function H(a){const o=await y(a,"https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),"账号列表"),t=o.data&&o.data.data||[],n=[];for(const e of t)if(e.accounts)n.push(...e.accounts);if(!n.length)throw new i("INVALID_INPUT","搜狐号子账号列表为空,请确认已登录搜狐号");return String(n[0].id)}async function J(a,o,t){const n=await y(a,"https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId="+encodeURIComponent(o),"频道列举"),e=Array.isArray(n)?n:n.data||[],r=e.find((s)=>String(s.name)===String(t));if(!r)throw new i("INVALID_INPUT","未找到频道「"+t+"」,可选:"+(e.map((s)=>s.name).join(" / ")||"(空)")+"。用 `sohu channels` 查看完整列表。");return Number(r.id!=null?r.id:r.channelId)}async function k(a,o,t,n){const e=await y(a,"https://mp.sohu.com/mpbp/bp/account/common/channels/"+t+"/categories?accountId="+encodeURIComponent(o),"分类列举"),r=Array.isArray(e)?e:e.data||[],s=r.find((c)=>String(c.name)===String(n));if(!s)throw new i("INVALID_INPUT","频道(id="+t+")下未找到分类「"+n+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(该频道无分类)")+"。用 `sohu categories --channel <频道名>` 查看。");return Number(s.id)}async function F(a,o,t){const n=await y(a,"https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId="+encodeURIComponent(o)+"&page=1&size=100","专栏列举"),e=Array.isArray(n)?n:n.data&&(n.data.data||n.data)||n.data||[],r=Array.isArray(e)?e:[],s=r.find((c)=>String(c.name)===String(t));if(!s)throw new i("INVALID_INPUT","未找到专栏「"+t+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(你还没有任何专栏)")+"。用 `sohu columns` 查看。");return Number(s.id)}async function B(a,o,t){const n=t.split(",").map((r)=>r.trim()).filter(Boolean);if(!n.length)return[];const e=[];for(const r of n){const s=await y(a,"https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId="+o+"&keyword="+encodeURIComponent(r),"话题搜索"),u=(Array.isArray(s)?s:s.data||[]).find((I)=>String(I.name)===String(r));if(!u)throw new i("INVALID_INPUT","未找到话题「"+r+"」,请用 `sohu topics --keyword "+r+"` 搜索确认确切名称。");e.push(u.id)}return e}U({site:"sohu",name:"article",access:"write",description:"发布文章到搜狐号(HTML 格式,外链图片自动转存到搜狐图床)。默认正式发布,加 --draft 仅存草稿。频道必填,合法值用 `sohu channels` 取。",domain:"mp.sohu.com",strategy:D.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown,传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 或 HTML)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"channel",help:"频道名(精确匹配,必填),合法值用 `sohu channels` 列举"},{name:"category",help:"分类名(精确匹配,依赖所选频道),合法值用 `sohu categories --channel <频道名>` 列举;不传=不限"},{name:"column",help:"专栏名(精确匹配),合法值用 `sohu columns` 列举;不传=不归属专栏"},{name:"topics",help:"话题名,逗号分隔(每个精确匹配),用 `sohu topics` 搜索取确切名"},{name:"cover",help:"封面图 URL(须为搜狐图床地址);可空"},{name:"brief",help:"文章摘要;可空"},{name:"declare-original",type:"boolean",help:"声明原创(会触发搜狐原创校验,发布将被拦到原创确认流程)"},{name:"draft",type:"boolean",help:"仅保存草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入操作;不加此参数则拒绝写入(干跑保护)"}],columns:["status","outcome","message","target_type","target","created_target","created_url","public_url"],func:async(a,o)=>{if(!a)throw new v("搜狐号文章发布需要浏览器会话");S(o);const t=String(o.title??"").trim();if(!t)throw new i("INVALID_INPUT","文章标题不能为空");const n=await _(o),e=Boolean(o.draft),r=typeof o.channel==="string"?o.channel.trim():"";if(!r)throw new i("INVALID_INPUT","缺少 --channel(频道名)。请先运行 `sohu channels` 取合法频道名再传入,不提供默认值。");await x(a,sohuProfile.home);const s=await H(a),c=await J(a,s,r);let u=-1;const I=typeof o.category==="string"?o.category.trim():"";if(I)u=await k(a,s,c,I);let m=0;const h=typeof o.column==="string"?o.column.trim():"";if(h)m=await F(a,s,h);let b=[];const l=typeof o.topics==="string"?o.topics.trim():"";if(l)b=await B(a,s,l);const w={channelId:c,categoryId:u,userColumnId:m,topicIds:b,cover:typeof o.cover==="string"?o.cover.trim():"",brief:typeof o.brief==="string"?o.brief:"",declareOriginal:Boolean(o["declare-original"]),headers:await C(a)},f=await O(a,{title:t,body:n,format:o.html?"html":"markdown",draftOnly:e,profile:sohuProfile,publishParams:w}),N=f.images.uploaded.length|0,d=f.images.failed.length|0;let p=f.draft?"已保存搜狐号草稿":"已正式发布到搜狐号";if(N||d)p+=`;图片:${N} 张已转存${d?`,${d} 张失败`:""}`;p+=R(f.images);return P(p,"article","",f.draft?"draft":"created",{created_target:(f.draft?"draft:":"article:")+f.id,created_url:f.url,public_url:f.publicUrl||""})}});export const __test__={sohuProfile,requireExecute:S,buildResultRow:P,resolvePayload:_,generateDeviceId:E};
@@ -1 +1 @@
1
- import{CliError as m,CommandExecutionError as D}from"@jackwener/opencli/errors";import{cli as j,Strategy as V}from"@jackwener/opencli/registry";import{publishArticle as F}from"../_shared/article/publish.js";import{readFile as M,stat as O}from"node:fs/promises";function R(c){if(!c.execute)throw new m("INVALID_INPUT","此头条号写操作需要 --execute 参数才能真正发布。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function H(c){const a=typeof c.text==="string"?c.text:void 0,t=typeof c.file==="string"?c.file:void 0;if(a&&t)throw new m("INVALID_INPUT","正文和 --file 只能选一个");let i=a??"";if(t){let d;try{d=await O(t)}catch{throw new m("INVALID_INPUT",`找不到文件: ${t}`)}if(!d.isFile())throw new m("INVALID_INPUT",`--file 必须是可读文本文件: ${t}`);let p;try{p=await M(t)}catch{throw new m("INVALID_INPUT",`文件无法读取: ${t}`)}try{i=new TextDecoder("utf-8",{fatal:!0}).decode(p)}catch{throw new m("INVALID_INPUT",`文件必须是 UTF-8 编码: ${t}`)}}if(!i.trim())throw new m("INVALID_INPUT","正文不能为空");return i}function q(c,a,t,i,d={}){return[{status:"success",outcome:i,message:c,target_type:a,target:t,...d}]}export const toutiaoProfile={home:"https://mp.toutiao.com/profile_v3/graphic/publish",outputFormat:"html",preprocessConfig:{},publish:async(c,a)=>{const t=c.params||{},i=[],d=[];async function p(e,l){const s="/spice/image?upload_source="+l+"&need_enhance=true&aid=1231&device_platform=web",r=new FormData;let o;if(/^https?:/i.test(e)){r.append("imageUrl",e);o=await fetch(s+"&scene=paste",{method:"POST",credentials:"include",body:r})}else{const w=await fetch(e,{credentials:"omit"});if(!w.ok)throw Error("图片下载失败 HTTP "+w.status+":"+e.slice(0,80));const P=await w.blob(),k=((P.type||"").split("/")[1]||"jpg").split("+")[0].split(";")[0]||"jpg";r.append("image",P,"image."+k);o=await fetch(s,{method:"POST",credentials:"include",body:r})}const u=await o.json(),_=u&&u.data;if(!u||u.code!==0||!_||!_.image_uri)throw Error((u&&u.message||"图片上传失败")+(u&&u.code!=null?"(接口 code "+u.code+")":""));return{uri:_.image_uri,url:_.image_url,width:_.image_width,height:_.image_height}}async function y(e){const l=new FormData;l.append("imageUrl",e);const r=await(await fetch("/spice/image?upload_source=20020003&aid=1231&device_platform=web&need_cover_url=1",{method:"POST",credentials:"include",body:l})).json(),o=r&&r.data;if(!r||r.code!==0||!o||!o.image_uri)throw Error((r&&r.message||"封面图生成失败")+(r&&r.code!=null?"(接口 code "+r.code+")":""));return{uri:o.image_uri,url:o.image_url,width:o.image_width,height:o.image_height}}const g=document.createElement("div");g.innerHTML=c.content;const b=Array.prototype.slice.call(g.querySelectorAll("img"));let h=null;for(const e of b){const l=e.getAttribute("src")||"";if(!l){e.remove();continue}let s;try{s=await p(l,20020002)}catch(w){d.push({src:l.slice(0,120),error:String(w&&w.message||w)});e.remove();continue}i.push({src:l.slice(0,120),url:s.url});if(!h)h=s;const r=document.createElement("div");r.className="pgc-img";const o=document.createElement("img");o.setAttribute("src",s.url);o.setAttribute("class","");o.setAttribute("image_type","");o.setAttribute("mime_type","");o.setAttribute("web_uri",s.uri);o.setAttribute("img_width",String(s.width));o.setAttribute("img_height",String(s.height));const u=document.createElement("p");u.className="pgc-img-caption";r.appendChild(o);r.appendChild(u);(e.parentElement||g).replaceChild(r,e)}const U=g.innerHTML,T=[];let f=null,I="";if(t.cover&&String(t.cover).trim())try{f=await p(String(t.cover),20020002)}catch(e){return{ok:!1,stage:"cover",message:"封面图转存失败:"+String(e&&e.message||e),uploaded:i,failed:d}}else if(h){f=h;I=h.uri}if(f){let e;try{e=await y(f.url)}catch(s){return{ok:!1,stage:"cover",message:"封面图生成失败:"+String(s&&s.message||s),uploaded:i,failed:d}}const l={url:e.url,uri:e.uri,width:e.width,height:e.height,thumb_width:e.width,thumb_height:e.height,natural_width:f.width,natural_height:f.height,back_up_url:f.url,need_check:!1,paste:!1,auto_upload:!1,show_optimize_icon:!1,ic:!1,id:0,pos:0};if(I)l.extra={from_content:"1",from_content_uri:I};T.push(l)}await fetch("https://mp.toutiao.com/profile_v4/graphic/publish",{credentials:"include"});function x(){const e=document.cookie.match(/passport_csrf_token=([^;]+)/);return e?e[1]:""}const S=x(),L=new URLSearchParams({title:c.title,article_ad_type:"2",article_type:"0",from_diagnosis:"0",origin_debut_check_pgc_normal:"0",tree_plan_article:"0",save:"1",pgc_id:"0",content:U,pgc_feed_covers:JSON.stringify(T)}),A={"Content-Type":"application/x-www-form-urlencoded"};if(S)A["X-CSRFToken"]=S;const N=await fetch("https://mp.toutiao.com/mp/agw/article/publish?source=mp&type=article&aid=1231",{method:"POST",credentials:"include",headers:A,body:L});let n=null;try{n=await N.json()}catch(e){}const C=n&&(n.code===0||n.err_no===0),v=n&&n.data&&n.data.pgc_id;if(!C||!v||String(v)==="0"){let e=n&&(n.message||n.reason)||"头条号发布失败";if(n&&(n.code===7112||n.err_no===7112))e+="(code 7112「图片URI异常」:正文图或封面图不是头条编辑器图床里的资源。"+"若本次有图片转存失败(见 failed 列表),先解决那张图再发)";if(n&&(n.code===7050||n.err_no===7050))e+="(code 7050「保存失败」:内容可能被风控拦截或账号被平台限制发文,"+"请登录 mp.toutiao.com 查看站内通知)";return{ok:!1,stage:"publish",status:N.status,message:e,detail:n,uploaded:i,failed:d}}const E="https://www.toutiao.com/article/"+String(v)+"/";return{ok:!0,id:String(v),url:E,editUrl:"https://mp.toutiao.com/profile_v4/graphic/publish?pgc_id="+String(v),draft:!1,uploaded:i,failed:d}},checkAuth:async(c)=>{try{const t=await(await fetch("https://mp.toutiao.com/mp/agw/media/get_media_info",{credentials:"include"})).json(),i=t&&t.data&&t.data.user;if(t&&t.code===0&&i&&i.id)return{isAuthenticated:!0,userId:String(i.id),username:i.screen_name||i.name||"",avatar:i.https_avatar_url||i.avatar_url||""};return{isAuthenticated:!1}}catch(a){return{isAuthenticated:!1,error:String(a&&a.message||a)}}}};j({site:"toutiao",name:"article",access:"write",description:"正式发布头条号图文文章(会立即公开,头条无可靠的存草稿接口,故不支持草稿)。正文默认 Markdown,图片自动转存到头条图床。标题需 2~30 字;封面可选(--cover,不传则头条自动从正文图选封面)。",domain:"mp.toutiao.com",strategy:V.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(2~30 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为原始 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"cover",help:"封面图 URL 或本机路径(可选;会先转存到头条图床)"},{name:"execute",type:"boolean",help:"真正执行写操作。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(c,a)=>{if(!c)throw new D("头条号文章发布需要浏览器会话");R(a);const t=String(a.title??"").trim();if(!t)throw new m("INVALID_INPUT","文章标题不能为空");if(t.length<2||t.length>30)throw new m("INVALID_INPUT",`头条号标题需 2~30 字,当前 ${t.length} 字`);const i=await H(a),p={cover:typeof a.cover==="string"?a.cover.trim():""},y=await F(c,{title:t,body:i,format:a.html?"html":"markdown",profile:toutiaoProfile,publishParams:p}),g=y.images.uploaded.length|0,b=y.images.failed.length|0;let h="已正式发布头条号文章";if(g||b)h+=`(图片:${g} 张已转存${b?`,${b} 张失败`:""})`;return q(h,"article","","created",{created_target:"article:"+y.id,created_url:y.url})}});
1
+ import{CliError as p,CommandExecutionError as D}from"@jackwener/opencli/errors";import{cli as j,Strategy as F}from"@jackwener/opencli/registry";import{formatImageReport as V,publishArticle as M}from"../_shared/article/publish.js";import{readFile as O,stat as R}from"node:fs/promises";import{rememberArticleFile as H}from"../_shared/article/images.js";function q(n){if(!n.execute)throw new p("INVALID_INPUT","此头条号写操作需要 --execute 参数才能真正发布。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function K(n){const i=typeof n.text==="string"?n.text:void 0,t=typeof n.file==="string"?n.file:void 0;if(i&&t)throw new p("INVALID_INPUT","正文和 --file 只能选一个");let r=i??"";if(t){H(t);let d;try{d=await R(t)}catch{throw new p("INVALID_INPUT",`找不到文件: ${t}`)}if(!d.isFile())throw new p("INVALID_INPUT",`--file 必须是可读文本文件: ${t}`);let g;try{g=await O(t)}catch{throw new p("INVALID_INPUT",`文件无法读取: ${t}`)}try{r=new TextDecoder("utf-8",{fatal:!0}).decode(g)}catch{throw new p("INVALID_INPUT",`文件必须是 UTF-8 编码: ${t}`)}}if(!r.trim())throw new p("INVALID_INPUT","正文不能为空");return r}function z(n,i,t,r,d={}){return[{status:"success",outcome:r,message:n,target_type:i,target:t,...d}]}export const toutiaoProfile={home:"https://mp.toutiao.com/profile_v3/graphic/publish",outputFormat:"html",preprocessConfig:{},publish:async(n,i)=>{const t=n.params||{},r=[],d=[];async function g(e,l){const s="/spice/image?upload_source="+l+"&need_enhance=true&aid=1231&device_platform=web",o=new FormData;let a;if(/^https?:/i.test(e)){o.append("imageUrl",e);a=await fetch(s+"&scene=paste",{method:"POST",credentials:"include",body:o})}else{const y=await fetch(e,{credentials:"omit"});if(!y.ok)throw Error("图片下载失败 HTTP "+y.status+":"+e.slice(0,80));const U=await y.blob(),E=((U.type||"").split("/")[1]||"jpg").split("+")[0].split(";")[0]||"jpg";o.append("image",U,"image."+E);a=await fetch(s,{method:"POST",credentials:"include",body:o})}const u=await a.json(),w=u&&u.data;if(!u||u.code!==0||!w||!w.image_uri)throw Error((u&&u.message||"图片上传失败")+(u&&u.code!=null?"(接口 code "+u.code+")":""));return{uri:w.image_uri,url:w.image_url,width:w.image_width,height:w.image_height}}async function f(e){const l=new FormData;l.append("imageUrl",e);const o=await(await fetch("/spice/image?upload_source=20020003&aid=1231&device_platform=web&need_cover_url=1",{method:"POST",credentials:"include",body:l})).json(),a=o&&o.data;if(!o||o.code!==0||!a||!a.image_uri)throw Error((o&&o.message||"封面图生成失败")+(o&&o.code!=null?"(接口 code "+o.code+")":""));return{uri:a.image_uri,url:a.image_url,width:a.image_width,height:a.image_height}}const _=document.createElement("div");_.innerHTML=n.content;const b=Array.prototype.slice.call(_.querySelectorAll("img"));let m=null;for(const e of b){const l=e.getAttribute("src")||"";if(!l){e.remove();continue}let s;try{s=await g(l,20020002)}catch(y){d.push({src:l.slice(0,120),key:i.refKey(l),error:String(y&&y.message||y)});e.remove();continue}r.push({src:l.slice(0,120),key:i.refKey(l),url:s.url});if(!m)m=s;const o=document.createElement("div");o.className="pgc-img";const a=document.createElement("img");a.setAttribute("src",s.url);a.setAttribute("class","");a.setAttribute("image_type","");a.setAttribute("mime_type","");a.setAttribute("web_uri",s.uri);a.setAttribute("img_width",String(s.width));a.setAttribute("img_height",String(s.height));const u=document.createElement("p");u.className="pgc-img-caption";o.appendChild(a);o.appendChild(u);(e.parentElement||_).replaceChild(o,e)}const P=_.innerHTML,S=[];let h=null,I="";if(t.cover&&String(t.cover).trim())try{h=await g(String(t.cover),20020002);r.push({src:String(t.cover).slice(0,120),key:i.refKey(String(t.cover)),url:h.url})}catch(e){return{ok:!1,stage:"cover",message:"封面图转存失败:"+String(e&&e.message||e),uploaded:r,failed:d}}else if(m){h=m;I=m.uri}if(h){let e;try{e=await f(h.url)}catch(s){return{ok:!1,stage:"cover",message:"封面图生成失败:"+String(s&&s.message||s),uploaded:r,failed:d}}const l={url:e.url,uri:e.uri,width:e.width,height:e.height,thumb_width:e.width,thumb_height:e.height,natural_width:h.width,natural_height:h.height,back_up_url:h.url,need_check:!1,paste:!1,auto_upload:!1,show_optimize_icon:!1,ic:!1,id:0,pos:0};if(I)l.extra={from_content:"1",from_content_uri:I};S.push(l)}await fetch("https://mp.toutiao.com/profile_v4/graphic/publish",{credentials:"include"});function k(){const e=document.cookie.match(/passport_csrf_token=([^;]+)/);return e?e[1]:""}const T=k(),x=new URLSearchParams({title:n.title,article_ad_type:"2",article_type:"0",from_diagnosis:"0",origin_debut_check_pgc_normal:"0",tree_plan_article:"0",save:"1",pgc_id:"0",content:P,pgc_feed_covers:JSON.stringify(S)}),A={"Content-Type":"application/x-www-form-urlencoded"};if(T)A["X-CSRFToken"]=T;const N=await fetch("https://mp.toutiao.com/mp/agw/article/publish?source=mp&type=article&aid=1231",{method:"POST",credentials:"include",headers:A,body:x});let c=null;try{c=await N.json()}catch(e){}const L=c&&(c.code===0||c.err_no===0),v=c&&c.data&&c.data.pgc_id;if(!L||!v||String(v)==="0"){let e=c&&(c.message||c.reason)||"头条号发布失败";if(c&&(c.code===7112||c.err_no===7112))e+="(code 7112「图片URI异常」:正文图或封面图不是头条编辑器图床里的资源。"+"若本次有图片转存失败(见 failed 列表),先解决那张图再发)";if(c&&(c.code===7050||c.err_no===7050))e+="(code 7050「保存失败」:内容可能被风控拦截或账号被平台限制发文,"+"请登录 mp.toutiao.com 查看站内通知)";return{ok:!1,stage:"publish",status:N.status,message:e,detail:c,uploaded:r,failed:d}}const C="https://www.toutiao.com/article/"+String(v)+"/";return{ok:!0,id:String(v),url:C,editUrl:"https://mp.toutiao.com/profile_v4/graphic/publish?pgc_id="+String(v),draft:!1,uploaded:r,failed:d}},checkAuth:async(n)=>{try{const t=await(await fetch("https://mp.toutiao.com/mp/agw/media/get_media_info",{credentials:"include"})).json(),r=t&&t.data&&t.data.user;if(t&&t.code===0&&r&&r.id)return{isAuthenticated:!0,userId:String(r.id),username:r.screen_name||r.name||"",avatar:r.https_avatar_url||r.avatar_url||""};return{isAuthenticated:!1}}catch(i){return{isAuthenticated:!1,error:String(i&&i.message||i)}}}};j({site:"toutiao",name:"article",access:"write",description:"正式发布头条号图文文章(会立即公开,头条无可靠的存草稿接口,故不支持草稿)。正文默认 Markdown,图片自动转存到头条图床。标题需 2~30 字;封面可选(--cover,不传则头条自动从正文图选封面)。",domain:"mp.toutiao.com",strategy:F.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(2~30 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为原始 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"cover",help:"封面图 URL 或本机路径(可选;会先转存到头条图床)"},{name:"execute",type:"boolean",help:"真正执行写操作。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(n,i)=>{if(!n)throw new D("头条号文章发布需要浏览器会话");q(i);const t=String(i.title??"").trim();if(!t)throw new p("INVALID_INPUT","文章标题不能为空");if(t.length<2||t.length>30)throw new p("INVALID_INPUT",`头条号标题需 2~30 字,当前 ${t.length} 字`);const r=await K(i),g={cover:typeof i.cover==="string"?i.cover.trim():""},f=await M(n,{title:t,body:r,format:i.html?"html":"markdown",profile:toutiaoProfile,publishParams:g}),_=f.images.uploaded.length|0,b=f.images.failed.length|0;let m="已正式发布头条号文章";if(_||b)m+=`(图片:${_} 张已转存${b?`,${b} 张失败`:""})`;m+=V(f.images);return z(m,"article","","created",{created_target:"article:"+f.id,created_url:f.url})}});
@@ -1,4 +1,4 @@
1
- import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy as ne}from"@jackwener/opencli/registry";import{ArgumentError as f,AuthRequiredError as ie,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as ae}from"../_shared/file-inject.js";const M="https://channels.weixin.qq.com/platform/post/create",le=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],oe=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],se=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],ue=new Set([".mp4",".mov",".avi",".webm"]),ce=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],A="https://channels.weixin.qq.com/platform/post/list",j=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,q=16,F=6;function R(e){if(!e)return;if(e.length>q)throw new f(`短标题超过 ${q} 字限制(当前 ${e.length} 字)`);if(e.length<F)throw new f(`短标题至少 ${F} 个字(当前 ${e.length} 字)`);if(!j.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!j.test(i)))).join(" ");throw new f(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function de(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return de(await e.evaluate(t))}function P(e,t,i){const n=D.resolve(String(e));let r;try{r=te.statSync(n)}catch{throw new f(`${t}文件不存在: ${n}`)}if(!r.isFile())throw new f(`${t}路径不是文件: ${n}`);const a=D.extname(n).toLowerCase();if(!i.has(a))throw new f(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return n}function Q(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new f("--timeout must be an integer >= 30 seconds");return t}function L(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new f(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new f("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function O(e){return e===!0||e==="true"||e==="1"||e===1}function fe(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function U({isDraft:e,finalUrl:t,successMsg:i}){const n=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(n);if(/已发表|发布成功|发表成功|审核中/.test(n))return!0;const r=String(t||"");return/\/platform\/post\/list\b/.test(r)}const p=`
1
+ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy as le}from"@jackwener/opencli/registry";import{ArgumentError as f,AuthRequiredError as se,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as ue}from"../_shared/file-inject.js";const I="https://channels.weixin.qq.com/platform/post/create",ce=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],de=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],fe=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],pe=new Set([".mp4",".mov",".avi",".webm"]),me=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],T="https://channels.weixin.qq.com/platform/post/list",j=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,F=16,L=6;function Q(e){if(!e)return;if(e.length>F)throw new f(`短标题超过 ${F} 字限制(当前 ${e.length} 字)`);if(e.length<L)throw new f(`短标题至少 ${L} 个字(当前 ${e.length} 字)`);if(!j.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!j.test(i)))).join(" ");throw new f(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function he(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return he(await e.evaluate(t))}function B(e,t,i){const n=C.resolve(String(e));let r;try{r=ae.statSync(n)}catch{throw new f(`${t}文件不存在: ${n}`)}if(!r.isFile())throw new f(`${t}路径不是文件: ${n}`);const a=C.extname(n).toLowerCase();if(!i.has(a))throw new f(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return n}function H(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new f("--timeout must be an integer >= 30 seconds");return t}function U(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new f(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new f("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function O(e){return e===!0||e==="true"||e==="1"||e===1}function we(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function J({isDraft:e,finalUrl:t,successMsg:i}){const n=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(n);if(/已发表|发布成功|发表成功|审核中/.test(n))return!0;const r=String(t||"");return/\/platform\/post\/list\b/.test(r)}const p=`
2
2
  function wujieRoot() {
3
3
  var w = document.querySelector('wujie-app');
4
4
  return (w && w.shadowRoot) || null;
@@ -25,7 +25,27 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
25
25
  var rect = el.getBoundingClientRect();
26
26
  return rect.width > 0 && rect.height > 0;
27
27
  }
28
- `,E=`
28
+ `,V=`
29
+ function oTextOf(el) { return (el && (el.innerText || el.textContent) || '').replace(/\\s+/g, ''); }
30
+ function oButtons(scope, label) {
31
+ var list = scope ? Array.prototype.slice.call(scope.querySelectorAll('button')) : deepQueryAll('button');
32
+ return list.filter(function (b) { return isVisible(b) && oTextOf(b) === label; });
33
+ }
34
+ function findOriginalDialog() {
35
+ var direct = oButtons(null, '直接发表');
36
+ for (var i = 0; i < direct.length; i++) {
37
+ var node = direct[i].parentNode;
38
+ while (node && node.nodeType === 1 && !oButtons(node, '声明原创').length) node = node.parentNode;
39
+ if (!node || node.nodeType !== 1) continue;
40
+ // 两个按钮的共同祖先可能只是弹窗底栏;往上找到带说明文案(分成 / 须知)的弹窗本体,不越过发布表单。
41
+ for (var up = node; up && up.nodeType === 1 && !up.querySelector('.form-btns'); up = up.parentNode) {
42
+ if (/分成|须知|权益/.test(oTextOf(up))) return up;
43
+ }
44
+ return node;
45
+ }
46
+ return null;
47
+ }
48
+ `,A=`
29
49
  function vmOf(el) {
30
50
  while (el) {
31
51
  if (el.__vue__) return el.__vue__;
@@ -77,6 +97,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
77
97
  isPosting: pv ? safe(function () { return !!pv.isPosting; }) : null,
78
98
  isCaching: pv ? safe(function () { return !!pv.isCaching; }) : null,
79
99
  originalIntercept: pv ? safe(function () { return !!pv.visibleOriginalIntercept; }) : null,
100
+ originalDialog: typeof findOriginalDialog === 'function' ? !!findOriginalDialog() : null,
80
101
  draftObjectId: pv ? safe(function () { return String(pv.draftStore.objectId || ''); }) : null,
81
102
  files: files,
82
103
  schedule: sv ? {
@@ -89,10 +110,10 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
89
110
  titleError: titleErrEl ? (titleErrEl.innerText || titleErrEl.textContent || '').trim() : '',
90
111
  };
91
112
  }
92
- `;async function x(e){return d(e,`(() => { ${p} ${E} return readFormState(); })()`)}function H(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",n=i&&t?t:null,r=e.schedule,a=!!r&&Number.isFinite(r.time);let l=null;if(a&&r.checked&&r.time){const o=Number.isFinite(r.minTime)?Math.max(r.time,r.minTime):r.time;l=Math.floor(o/1000)}if(i&&a&&n!==l)return{known:!0,conflict:!0,seconds:n??l,formSeconds:n,pickerSeconds:l};if(i)return{known:!0,seconds:n};if(a)return{known:!0,seconds:l};return{known:!1,seconds:null}}function g(e){const t=new Date(e*1000),i=(n)=>String(n).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function N(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const r=e.files.filter((a)=>a.status!=="done");if(r.length)return`视频还没上传完成(状态 ${r.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const n=H(e);if(n.conflict){const r=(a)=>a?g(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${r(n.formSeconds)} / 时间选择器 ${r(n.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!n.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(n.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${g(t)},表单实际 ${n.seconds?g(n.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(n.known&&n.seconds)return`表单处于定时发表状态(${g(n.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function pe(e){return await d(e,`
113
+ `;async function M(e){return d(e,`(() => { ${p} ${V} ${A} return readFormState(); })()`)}function G(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",n=i&&t?t:null,r=e.schedule,a=!!r&&Number.isFinite(r.time);let o=null;if(a&&r.checked&&r.time){const l=Number.isFinite(r.minTime)?Math.max(r.time,r.minTime):r.time;o=Math.floor(l/1000)}if(i&&a&&n!==o)return{known:!0,conflict:!0,seconds:n??o,formSeconds:n,pickerSeconds:o};if(i)return{known:!0,seconds:n};if(a)return{known:!0,seconds:o};return{known:!1,seconds:null}}function _(e){const t=new Date(e*1000),i=(n)=>String(n).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function q(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const r=e.files.filter((a)=>a.status!=="done");if(r.length)return`视频还没上传完成(状态 ${r.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const n=G(e);if(n.conflict){const r=(a)=>a?_(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${r(n.formSeconds)} / 时间选择器 ${r(n.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!n.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(n.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${_(t)},表单实际 ${n.seconds?_(n.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(n.known&&n.seconds)return`表单处于定时发表状态(${_(n.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function ve(e){return await d(e,`
93
114
  (() => {
94
115
  ${p}
95
- var sels = ${JSON.stringify(se)};
116
+ var sels = ${JSON.stringify(fe)};
96
117
  for (var i = 0; i < sels.length; i++) {
97
118
  var el = deepQuery(sels[i]);
98
119
  if (el && isVisible(el)) {
@@ -102,7 +123,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
102
123
  }
103
124
  return { ok: false };
104
125
  })()
105
- `)}async function me(e,t=15000){const i=500,n=Math.max(1,Math.ceil(t/i));for(let r=0;r<n;r++){if(await d(e,`
126
+ `)}async function be(e,t=15000){const i=500,n=Math.max(1,Math.ceil(t/i));for(let r=0;r<n;r++){if(await d(e,`
106
127
  (() => {
107
128
  ${p}
108
129
  var inputSels = ['input[type="file"][accept*="video"]', 'input[type="file"]'];
@@ -111,7 +132,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
111
132
  }
112
133
  return false;
113
134
  })()
114
- `))return!0;if(r<n-1)await e.wait({time:i/1000})}return!1}const B=`((sel) => {
135
+ `))return!0;if(r<n-1)await e.wait({time:i/1000})}return!1}const Y=`((sel) => {
115
136
  ${p}
116
137
  var real = deepQuery(sel);
117
138
  if (!real) return null;
@@ -141,11 +162,11 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
141
162
  return real.dispatchEvent(new win.Event(ev.type, { bubbles: true }));
142
163
  },
143
164
  };
144
- })`;async function he(e,t){await pe(e);await e.wait({time:1});await me(e);let i;for(const n of ce)try{await ae(e,n,[t],{findInputJs:B});const r=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!r||r.error||r.count!==1||!r.realm)throw new c(`文件没能交给页面的上传控件: ${r?.error||`count=${r?.count??"未知"} realm=${r?.realm??"未知"}`}`);return}catch(r){i=r;if(!(r instanceof Error?r.message:String(r)).includes("未找到文件上传输入框"))break}await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
145
- 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function J(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function we(e,t,i=180000){const n=3000,r=Math.ceil(i/n),a=Math.ceil(20000/n);let l=0;for(let o=0;o<r;o++){let s;try{s=await d(e,`
165
+ })`;async function ge(e,t){await ve(e);await e.wait({time:1});await be(e);let i;for(const n of me)try{await ue(e,n,[t],{findInputJs:Y});const r=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!r||r.error||r.count!==1||!r.realm)throw new c(`文件没能交给页面的上传控件: ${r?.error||`count=${r?.count??"未知"} realm=${r?.realm??"未知"}`}`);return}catch(r){i=r;if(!(r instanceof Error?r.message:String(r)).includes("未找到文件上传输入框"))break}await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
166
+ 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function W(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function _e(e,t,i=180000){const n=3000,r=Math.ceil(i/n),a=Math.ceil(20000/n);let o=0;for(let l=0;l<r;l++){let s;try{s=await d(e,`
146
167
  ((fileName) => {
147
168
  ${p}
148
- ${E}
169
+ ${A}
149
170
  var files = readFormState().files;
150
171
  if (Array.isArray(files)) return { files: files };
151
172
 
@@ -164,8 +185,8 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
164
185
  var hasFileEvidence = fileName && bodyText.indexOf(fileName) >= 0;
165
186
  return { done: !uploading && (preview || hasFileEvidence), failed: false };
166
187
  })(${JSON.stringify(t)})
167
- `)}catch(u){const h=u instanceof Error?u.message:String(u);if(h.includes("ECONNRESET")||h.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${o+1}/${r})...
168
- `);await e.wait({time:n/1000});continue}throw u}const m=J(s?.files);if(m==="error"||s?.failed){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(m==="done"||m==="unknown"&&s?.done)return;if(m==="empty"){l+=1;if(l>=a){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else l=0;await e.wait({time:n/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function Y(e,t,i,n){const r=30;let a;for(let l=0;l<r;l++){a=await d(e,`
188
+ `)}catch(u){const h=u instanceof Error?u.message:String(u);if(h.includes("ECONNRESET")||h.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${l+1}/${r})...
189
+ `);await e.wait({time:n/1000});continue}throw u}const m=W(s?.files);if(m==="error"||s?.failed){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(m==="done"||m==="unknown"&&s?.done)return;if(m==="empty"){o+=1;if(o>=a){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else o=0;await e.wait({time:n/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function K(e,t,i,n){const r=30;let a;for(let o=0;o<r;o++){a=await d(e,`
169
190
  (function(selectors, text) {
170
191
  ${p}
171
192
 
@@ -212,10 +233,10 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
212
233
  el.blur();
213
234
  return { ok: actual.indexOf(text) >= 0, sel: foundSel, actual: actual };
214
235
  })(${JSON.stringify(t)}, ${JSON.stringify(i)})
215
- `);if(a?.ok)break;if(l<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:`/tmp/wechat-channels_publish_${n}_debug.png`});throw new c(`找不到 ${n} 输入框,截图已保存到 /tmp/wechat-channels_publish_${n}_debug.png`)}}const G=`
236
+ `);if(a?.ok)break;if(o<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:`/tmp/wechat-channels_publish_${n}_debug.png`});throw new c(`找不到 ${n} 输入框,截图已保存到 /tmp/wechat-channels_publish_${n}_debug.png`)}}const X=`
216
237
  (async function(TY, TM, TD, TH, TMin, TARGET_MS) {
217
238
  ${p}
218
- ${E}
239
+ ${A}
219
240
  function sleep(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
220
241
  function click(el) {
221
242
  el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
@@ -364,8 +385,8 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
364
385
  var inp = dateDl.querySelector('dt input') || deepQuery('input[placeholder*="发表时间"]');
365
386
  return { ok: true, value: inp ? inp.value : null, pick: pickOf(), commit: commit.join('+'), state: readFormState() };
366
387
  })
367
- `;async function ve(e,t){const i=t.getFullYear(),n=t.getMonth()+1,r=t.getDate(),a=t.getHours(),l=t.getMinutes(),o=(v)=>String(v).padStart(2,"0"),s=t.getTime(),m=Math.floor(s/1000),u=await d(e,`${G}(${i}, ${n}, ${r}, ${a}, ${l}, ${s})`);if(!u?.ok){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});const v=u?.reason?String(u.reason):"empty picker result";if(v==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${v}),截图: /tmp/wechat-channels_schedule_debug.png`)}const h=`${i}-${o(n)}-${o(r)} ${o(a)}:${o(l)}`,w=[];if(!String(u.value||"").includes(h))w.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==m)w.push(`时间选择器选中=${g(Math.floor(u.pick/1000))}`);const y=N({...u.state,files:null,titleError:""},{targetSeconds:m,isDraft:!1});if(y)w.push(y);if(w.length){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});throw new c(`定时设置未验证成功: 目标=${h};${w.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||h}(表单回读一致)
368
- `)}const W=`
388
+ `;async function ye(e,t){const i=t.getFullYear(),n=t.getMonth()+1,r=t.getDate(),a=t.getHours(),o=t.getMinutes(),l=(y)=>String(y).padStart(2,"0"),s=t.getTime(),m=Math.floor(s/1000),u=await d(e,`${X}(${i}, ${n}, ${r}, ${a}, ${o}, ${s})`);if(!u?.ok){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});const y=u?.reason?String(u.reason):"empty picker result";if(y==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${y}),截图: /tmp/wechat-channels_schedule_debug.png`)}const h=`${i}-${l(n)}-${l(r)} ${l(a)}:${l(o)}`,w=[];if(!String(u.value||"").includes(h))w.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==m)w.push(`时间选择器选中=${_(Math.floor(u.pick/1000))}`);const k=q({...u.state,files:null,titleError:""},{targetSeconds:m,isDraft:!1});if(k)w.push(k);if(w.length){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});throw new c(`定时设置未验证成功: 目标=${h};${w.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||h}(表单回读一致)
389
+ `)}const z=`
369
390
  (function(isDraft, labels) {
370
391
  ${p}
371
392
  function isDisabled(btn) {
@@ -405,19 +426,87 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
405
426
  target.click();
406
427
  return { ok: true, how: how, text: (target.innerText || target.textContent || '').trim() };
407
428
  })
408
- `;async function be(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],n=t?"保存草稿":"发表",r=30;let a;for(let l=0;l<r;l++){a=await d(e,`${W}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(l<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});const l=await x(e).catch(()=>null),o=a?.found?`「${n}」按钮一直是禁用状态${l?.disabledTip?`,页面给出的原因: ${l.disabledTip}`:""}`:`页面上没有「${n}」按钮`;throw new c(`${o}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}re({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:ne.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=Q(t.timeout),n=Date.now()+i*1000,r=P(t.video,"视频",ue),a=String(t.title??"").trim(),l=String(t.caption??"").trim(),o=L(t.schedule||null),s=O(t.draft),m=O(t.manual);R(a);if(s&&o)throw new f("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const u=o?Math.floor(o.getTime()/1000):0;await e.goto(M);await e.wait({time:4});{const b=(T)=>typeof T==="string"&&T.includes("/platform/post/create"),I=await d(e,"() => location.href");if(!b(I)){process.stderr.write(`
429
+ `,Z=`
430
+ (async function(choice) {
431
+ ${p}
432
+ ${V}
433
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
434
+ function fire(el) {
435
+ var r = el.getBoundingClientRect();
436
+ var opts = { bubbles: true, cancelable: true, composed: true, view: window, button: 0,
437
+ clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 };
438
+ var P = typeof PointerEvent === 'function' ? PointerEvent : MouseEvent;
439
+ el.dispatchEvent(new P('pointerdown', opts));
440
+ el.dispatchEvent(new MouseEvent('mousedown', opts));
441
+ el.dispatchEvent(new P('pointerup', opts));
442
+ el.dispatchEvent(new MouseEvent('mouseup', opts));
443
+ el.dispatchEvent(new MouseEvent('click', opts));
444
+ }
445
+ function btnDisabled(b) {
446
+ return b.disabled || b.getAttribute('disabled') !== null || /disabled/.test(b.className || '');
447
+ }
448
+ // 须知勾选框:优先 .original-proto-wrapper;没有这层时取框内文案像「须知 / 条款 / 同意」的勾选框,
449
+ // 绝不碰「不再提醒」那个(勾了会改账号设置)。
450
+ function termsBoxes(dialog) {
451
+ var scope = dialog.querySelector('.original-proto-wrapper');
452
+ var inputs = Array.prototype.slice.call((scope || dialog).querySelectorAll('input[type="checkbox"]'));
453
+ return inputs.map(function (input) {
454
+ var wrap = input.closest('.ant-checkbox-wrapper, label') || input.parentNode;
455
+ return { input: input, wrap: wrap, text: oTextOf(wrap.parentNode || wrap) };
456
+ }).filter(function (b) {
457
+ if (b.text.indexOf('不再提醒') >= 0 && !scope) return false;
458
+ return scope ? true : /须知|条款|同意|阅读|权益/.test(b.text);
459
+ });
460
+ }
461
+ function boxChecked(b) {
462
+ return !!(b.input.checked
463
+ || (b.wrap.classList && b.wrap.classList.contains('ant-checkbox-wrapper-checked'))
464
+ || b.wrap.querySelector('.ant-checkbox-checked'));
465
+ }
466
+ var dialog = findOriginalDialog();
467
+ if (!dialog) return { ok: false, reason: 'dialog-not-found' };
468
+ var dialogText = oTextOf(dialog).slice(0, 200);
469
+ var label = choice === 'original' ? '声明原创' : '直接发表';
470
+ var terms = [];
471
+ if (choice === 'original') {
472
+ terms = termsBoxes(dialog);
473
+ for (var t = 0; t < terms.length; t++) {
474
+ if (!boxChecked(terms[t])) fire(terms[t].input.getBoundingClientRect().width ? terms[t].input : terms[t].wrap);
475
+ }
476
+ for (var w = 0; w < 15 && terms.some(function (b) { return !boxChecked(b); }); w++) await sleep(200);
477
+ if (terms.some(function (b) { return !boxChecked(b); })) {
478
+ return { ok: false, reason: 'terms-unchecked', dialogText: dialogText };
479
+ }
480
+ }
481
+ var btn = null;
482
+ for (var a = 0; a < 15; a++) {
483
+ btn = oButtons(dialog, label)[0] || null;
484
+ if (btn && !btnDisabled(btn)) break;
485
+ await sleep(200);
486
+ }
487
+ if (!btn) return { ok: false, reason: 'button-not-found', label: label, dialogText: dialogText };
488
+ if (btnDisabled(btn)) return { ok: false, reason: 'button-disabled', label: label, termsCount: terms.length, dialogText: dialogText };
489
+ fire(btn);
490
+ for (var c = 0; c < 25; c++) {
491
+ await sleep(200);
492
+ if (!findOriginalDialog()) return { ok: true, label: label, termsCount: terms.length };
493
+ }
494
+ return { ok: false, reason: 'dialog-still-open', label: label, termsCount: terms.length, dialogText: dialogText };
495
+ })
496
+ `,ke={"dialog-not-found":"页面状态显示被原创确认框拦下,但没找到含「直接发表 / 声明原创」按钮的弹窗(平台可能改版)","terms-unchecked":"勾选原创权益须知后回读仍未勾上","button-not-found":"确认框里没有找到对应按钮","button-disabled":"确认框里的按钮一直是禁用状态(--original 时多半是须知没勾上,或账号当前不能声明原创)","dialog-still-open":"点了按钮后确认框没有关闭"};async function Te(e,t){const n=await d(e,`${Z}(${JSON.stringify(t?"original":"direct")})`);if(!n?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});const r=ke[n?.reason]||`确认框响应异常: ${JSON.stringify(n)}`;throw new c(`发表被平台的原创声明确认框拦下,自动选择「${t?"声明原创":"直接发表"}」失败:${r},作品尚未发出`,`先到 ${T} 确认作品列表里没有这条再重试;也可以换 ${t?"不带 --original(直接发表)":"--original(声明原创)"} 重试,`+"或加 --manual --site-session persistent 后在浏览器里手动选择。截图: /tmp/wechat-channels_publish_result_debug.png"+(n?.dialogText?`;弹窗文字: ${n.dialogText}`:""))}process.stderr.write(` 原创确认框: 已选择「${n.label}」${t?`(须知勾选框 ${n.termsCount} 个,已回读勾上)`:""}
497
+ `);return n}async function Se(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],n=t?"保存草稿":"发表",r=30;let a;for(let o=0;o<r;o++){a=await d(e,`${z}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(o<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});const o=await M(e).catch(()=>null),l=a?.found?`「${n}」按钮一直是禁用状态${o?.disabledTip?`,页面给出的原因: ${o.disabledTip}`:""}`:`页面上没有「${n}」按钮`;throw new c(`${l}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}oe({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:le.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"},{name:"original",type:"bool",default:!1,help:"创作分成计划账号发表时会弹「声明原创的视频有机会获得广告分成」确认框:默认自动点「直接发表」;传 --original 则勾选原创权益须知并点「声明原创」。不弹框的账号此参数无效果"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=H(t.timeout),n=Date.now()+i*1000,r=B(t.video,"视频",pe),a=String(t.title??"").trim(),o=String(t.caption??"").trim(),l=U(t.schedule||null),s=O(t.draft),m=O(t.manual),u=O(t.original);Q(a);if(u&&(s||m))throw new f("--original 只在自动发表时生效:原创确认框在点「发表」后才出现,不能与 --draft / --manual 同用");if(s&&l)throw new f("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const h=l?Math.floor(l.getTime()/1000):0;await e.goto(I);await e.wait({time:4});{const v=(D)=>typeof D==="string"&&D.includes("/platform/post/create"),E=await d(e,"() => location.href");if(!v(E)){process.stderr.write(`
409
498
  ⚠️ 未登录视频号(已被重定向离开发布页)。请在 Chrome 中扫码登录...
410
- `+" 当前地址: "+I+`
499
+ `+" 当前地址: "+E+`
411
500
  `+` 登录完成后将自动继续发布。
412
501
 
413
- `);const T=Math.min(n,Date.now()+120000);let V=!1;while(Date.now()<T){await e.wait({time:3});await e.goto(M);await e.wait({time:2});const ee=await d(e,"() => location.href");if(b(ee)){V=!0;break}process.stderr.write(` 等待扫码中...
414
- `)}if(!V)throw new ie("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
502
+ `);const D=Math.min(n,Date.now()+120000);let P=!1;while(Date.now()<D){await e.wait({time:3});await e.goto(I);await e.wait({time:2});const ie=await d(e,"() => location.href");if(v(ie)){P=!0;break}process.stderr.write(` 等待扫码中...
503
+ `)}if(!P)throw new se("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
415
504
 
416
- `);await e.wait({time:3});await e.goto(M);await e.wait({time:5})}}await he(e,r);await e.wait({time:2});await we(e,D.basename(r),Math.min(180000,fe(n,"视频上传/转码")));await e.wait({time:1});if(a){await Y(e,le,a,"title");await e.wait({time:0.5});const b=await x(e);if(b?.titleError)throw new c(`平台拒绝了短标题: ${b.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(l){await Y(e,oe,l,"caption");await e.wait({time:0.5})}if(o){await ve(e,o);await e.wait({time:0.5})}if(m){process.stderr.write(`
505
+ `);await e.wait({time:3});await e.goto(I);await e.wait({time:5})}}await ge(e,r);await e.wait({time:2});await _e(e,C.basename(r),Math.min(180000,we(n,"视频上传/转码")));await e.wait({time:1});if(a){await K(e,ce,a,"title");await e.wait({time:0.5});const v=await M(e);if(v?.titleError)throw new c(`平台拒绝了短标题: ${v.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(o){await K(e,de,o,"caption");await e.wait({time:0.5})}if(l){await ye(e,l);await e.wait({time:0.5})}if(m){process.stderr.write(`
417
506
  ℹ️ 手动模式:表单已填好,请在浏览器中检查并点击「发表」。
418
507
  `+` 若未加 --site-session persistent,此标签页约 30 秒后会被重置为空白页。
419
508
 
420
- `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[o?`定时: ${g(u)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:A}]}const h=await x(e),w=N(h,{targetSeconds:u,isDraft:s});if(w){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});throw new c(`${w}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await be(e,s);await e.wait({time:s?1:4});const y=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let v="",k="",S=!1,C="",_=null;const K=h?.draftObjectId||"";for(let b=0;b<30;b++){_=await x(e).catch(()=>null);if(s&&!K&&_?.draftObjectId&&_.isCaching===!1){C=_.draftObjectId;S=!0;break}if(!s&&_?.originalIntercept){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c("发表被平台的原创声明确认框拦下,作品尚未发出","需要在浏览器里人工确认是否声明原创后再发表。截图: /tmp/wechat-channels_publish_result_debug.png")}v=await d(e,"() => location.href");k=await d(e,`
509
+ `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[l?`定时: ${_(h)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:T}]}const w=await M(e),k=q(w,{targetSeconds:h,isDraft:s});if(k){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});throw new c(`${k}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await Se(e,s);await e.wait({time:s?1:4});const y=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let N="",S="",x=!1,R="",b=null;const ee=w?.draftObjectId||"";let g=null;for(let v=0;v<30;v++){b=await M(e).catch(()=>null);if(s&&!ee&&b?.draftObjectId&&b.isCaching===!1){R=b.draftObjectId;x=!0;break}const E=g?b?.originalDialog:b?.originalIntercept||b?.originalDialog;if(!s&&E){if(g){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已在原创确认框里选择「${g.label}」,但确认框再次出现,作品尚未发出`,`先到 ${T} 确认作品列表里没有这条,再加 --manual --site-session persistent 后在浏览器里手动处理。截图: /tmp/wechat-channels_publish_result_debug.png`)}g=await Te(e,u);await e.wait({time:1});continue}N=await d(e,"() => location.href");S=await d(e,`
421
510
  (function(markers) {
422
511
  ${p}
423
512
  var all = deepQueryAll('*');
@@ -432,4 +521,4 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
432
521
  }
433
522
  return '';
434
523
  })(${JSON.stringify(y)})
435
- `);S=U({isDraft:s,finalUrl:v,successMsg:k});if(S)break;await e.wait({time:0.5})}if(!S){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${A} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${v||""} message=${k||""}`)}const z=s?"草稿已保存":o?"定时发表已提交":"发布成功",X=[o?`定时: ${g(u)}(已回读表单确认)`:null,k||null,s?"草稿不公开,到管理页的草稿箱继续编辑":o?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),Z=[{status:`✅ ${z}`,title:a||"",detail:X.join(" · "),id:C,manage_url:A}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return Z}});export const __test__={parseTimeoutSeconds:Q,parseScheduleDate:L,parseBooleanFlag:O,requireFilePath:P,submitSucceeded:U,validateShortTitle:R,submittedScheduleSeconds:H,preSubmitBlocker:N,uploadProgress:J,DEEP_QUERY_FN:p,FORM_STATE_FN:E,REALM_FILE_INPUT_JS:B,SCHEDULE_PICK_JS:G,SUBMIT_CLICK_JS:W};
524
+ `);x=J({isDraft:s,finalUrl:N,successMsg:S});if(x)break;await e.wait({time:0.5})}if(!x){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${T} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${N||""} message=${S||""}`)}const te=s?"草稿已保存":l?"定时发表已提交":"发布成功",ne=[l?`定时: ${_(h)}(已回读表单确认)`:null,g?`原创确认框: 已选「${g.label}」`:null,u&&!g?"平台未弹原创确认框,未声明原创(账号可能不在创作分成计划内)":null,S||null,s?"草稿不公开,到管理页的草稿箱继续编辑":l?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),re=[{status:`✅ ${te}`,title:a||"",detail:ne.join(" · "),id:R,manage_url:T}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return re}});export const __test__={parseTimeoutSeconds:H,parseScheduleDate:U,parseBooleanFlag:O,requireFilePath:B,submitSucceeded:J,validateShortTitle:Q,submittedScheduleSeconds:G,preSubmitBlocker:q,uploadProgress:W,DEEP_QUERY_FN:p,FORM_STATE_FN:A,REALM_FILE_INPUT_JS:Y,SCHEDULE_PICK_JS:X,SUBMIT_CLICK_JS:z,ORIGINAL_DIALOG_FN:V,ORIGINAL_ANSWER_JS:Z};
@@ -1 +1 @@
1
- import{CliError as f,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as S,Strategy as v}from"@jackwener/opencli/registry";import{publishArticle as T}from"../_shared/article/publish.js";import{readFile as P,stat as O}from"node:fs/promises";function U(t){if(!t.execute)throw new f("INVALID_INPUT","微博头条文章写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function A(t){const c=typeof t.text==="string"?t.text:void 0,r=typeof t.file==="string"?t.file:void 0;if(c&&r)throw new f("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let i=c??"";if(r){let e;try{e=await O(r)}catch{throw new f("INVALID_INPUT",`文件不存在:${r}`)}if(!e.isFile())throw new f("INVALID_INPUT",`路径不是可读文本文件:${r}`);let u;try{u=await P(r)}catch{throw new f("INVALID_INPUT",`文件无法读取:${r}`)}try{i=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{throw new f("INVALID_INPUT",`文件无法解码为 UTF-8:${r}`)}}if(!i.trim())throw new f("INVALID_INPUT","正文不能为空。");return i}function L(t,c,r,i,e={}){return[{status:"success",outcome:i,message:t,target_type:c,target:r,...e}]}export const weiboProfile={home:"https://card.weibo.com/article/v5/editor",outputFormat:"html",preprocessConfig:{compactHtml:!0},image:{skip:["sinaimg.cn","weibo.com"],uploadFn:async(t,c)=>{async function r(){let a=document.documentElement.innerHTML||"",n=a.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!n){a=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();n=a.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!n)return"";try{const o=JSON.parse(n[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return o.uid?String(o.uid):""}catch(o){return""}}function i(a){const n=btoa(a+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let s=n;while(s.length<43)s+=o.charAt(Math.floor(Math.random()*o.length));return s.slice(0,43)}const e=await r();if(!e)throw Error("未取到微博 uid,请先登录微博");if(t.indexOf("data:")===0){const a=c.dataUriToBlob(t),o="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="+i(e),l=await(await fetch(o,{method:"POST",credentials:"include",body:a})).json(),d=l&&l.data&&l.data.pics&&l.data.pics.pic_1&&l.data.pics.pic_1.pid;if(!d)throw Error("图片直传失败:"+JSON.stringify(l).slice(0,200));return{url:"https://wx3.sinaimg.cn/large/"+d+".jpg"}}const u=i(e);try{await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncuploadimg?uid="+e+"&_rid="+u,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":u},body:new URLSearchParams({"urls[0]":t})})}catch(a){}for(let a=0;a<30;a++){const n=i(e),s=await(await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncimginfo?uid="+e+"&_rid="+n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":n},body:new URLSearchParams({"urls[0]":t})})).json(),l=s&&s.data&&s.data[0],d=l&&l.task_status_code;if(d===1&&l.pid)return{url:"https://wx3.sinaimg.cn/large/"+l.pid+".jpg"};if(d===2)throw Error("微博图片转存失败:"+t);await new Promise((g)=>setTimeout(g,1000))}throw Error("微博图片转存超时:"+t)}},checkAuth:async(t)=>{const i=(await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text()).match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!i)return{isAuthenticated:!1};let e=null;try{e=JSON.parse(i[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"))}catch(u){return{isAuthenticated:!1,error:"编辑器 config 解析失败"}}if(!e||!e.uid)return{isAuthenticated:!1};return{isAuthenticated:!0,userId:String(e.uid),username:e.nick||"",avatar:e.avatar_large||""}},publish:async(t,c)=>{async function r(){let m=document.documentElement.innerHTML||"",p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!p){m=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!p)return"";try{const h=JSON.parse(p[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return h.uid?String(h.uid):""}catch(h){return""}}function i(m){const p=btoa(m+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let w=p;while(w.length<43)w+=h.charAt(Math.floor(Math.random()*h.length));return w.slice(0,43)}const e=await r();if(!e)return{ok:!1,stage:"auth",message:"未取到微博 uid,请先登录微博"};let u=(t.content||"").replace(/>\s+</g,"><");const a=document.createElement("div");a.innerHTML=u;const n=a.querySelectorAll("img");for(let m=0;m<n.length;m++){const p=n[m],h=(p.getAttribute("src")||"").match(/sinaimg\.cn\/large\/([^/."]+)\.jpg/);if(!h)continue;p.setAttribute("data-pid",h[1]);if(!p.closest("figure")){const w=document.createElement("figure");w.className="image";p.parentNode.insertBefore(w,p);w.appendChild(p)}}u=a.innerHTML;const o=i(e),s=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/create?uid="+e+"&_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({})}),l=await s.text();let d=null;try{d=JSON.parse(l)}catch(m){}if(!s.ok||!d||d.code!==1e5||!d.data||!d.data.id)return{ok:!1,stage:"create",status:s.status,message:d&&d.msg||"创建草稿失败:"+l.slice(0,200)};const g=String(d.data.id),N=t.params&&typeof t.params.cover==="string"?t.params.cover:"",_=i(e),b=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/save?uid="+e+"&id="+g+"&_rid="+_,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":_},body:new URLSearchParams({id:g,title:t.title,subtitle:"",type:"",status:"0",publish_at:"",error_msg:"",error_code:"0",collection:"[]",free_content:"",content:u,cover:N,summary:"",writer:"",extra:"null",is_word:"0",article_recommend:"[]",follow_to_read:"1",isreward:"1",pay_setting:'{"ispay":0,"isvclub":0}',source:"0",action:"1",content_type:"0",save:"1"})}),I=await b.text();let y=null;try{y=JSON.parse(I)}catch(m){}if(!b.ok||!y||String(y.code)!=="100000")return{ok:!1,stage:"save",status:b.status,message:y&&y.msg||"保存草稿失败:"+I.slice(0,200)};return{ok:!0,id:g,url:"https://card.weibo.com/article/v5/editor#/draft/"+g,draft:!0}}};S({site:"weibo",name:"article",access:"write",description:"把长文以微博头条文章形式保存到草稿箱(card.weibo.com)。正文默认 Markdown,外链/本机图片自动转存到微博图床,支持 --cover 题图。注意:平台接口只到草稿态,正式发布需在微博头条文章编辑器里手动操作。",domain:"weibo.com",strategy:v.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"cover",help:"题图(本机图片路径或图片 URL,自动转存到微博图床)"},{name:"draft",type:"boolean",help:"仅保存草稿(微博头条文章目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行写入。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,c)=>{if(!t)throw new x("微博头条文章命令需要浏览器会话。");U(c);const r=String(c.title??"").trim();if(!r)throw new f("INVALID_INPUT","文章标题不能为空。");const i=await A(c),e=typeof c.cover==="string"&&c.cover.trim()?c.cover.trim():"",u=!0,a=await T(t,{title:r,body:i,format:c.html?"html":"markdown",draftOnly:u,profile:weiboProfile,publishParams:e?{cover:e}:null}),n=a.images.uploaded.length|0,o=a.images.failed.length|0;let s="已保存微博头条文章草稿(正式发布请在编辑器里手动操作)";if(n||o)s+="·图片:"+n+" 张已转存"+(o?","+o+" 张失败":"");return L(s,"article","","draft",{created_target:"draft:"+a.id,created_url:a.url})}});
1
+ import{CliError as h,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as S,Strategy as v}from"@jackwener/opencli/registry";import{formatImageReport as T,publishArticle as P}from"../_shared/article/publish.js";import{readFile as A,stat as O}from"node:fs/promises";import{rememberArticleFile as R}from"../_shared/article/images.js";function U(t){if(!t.execute)throw new h("INVALID_INPUT","微博头条文章写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function L(t){const c=typeof t.text==="string"?t.text:void 0,a=typeof t.file==="string"?t.file:void 0;if(c&&a)throw new h("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let i=c??"";if(a){R(a);let e;try{e=await O(a)}catch{throw new h("INVALID_INPUT",`文件不存在:${a}`)}if(!e.isFile())throw new h("INVALID_INPUT",`路径不是可读文本文件:${a}`);let u;try{u=await A(a)}catch{throw new h("INVALID_INPUT",`文件无法读取:${a}`)}try{i=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{throw new h("INVALID_INPUT",`文件无法解码为 UTF-8:${a}`)}}if(!i.trim())throw new h("INVALID_INPUT","正文不能为空。");return i}function E(t,c,a,i,e={}){return[{status:"success",outcome:i,message:t,target_type:c,target:a,...e}]}export const weiboProfile={home:"https://card.weibo.com/article/v5/editor",outputFormat:"html",preprocessConfig:{compactHtml:!0},image:{skip:["sinaimg.cn","weibo.com"],uploadFn:async(t,c)=>{async function a(){let r=document.documentElement.innerHTML||"",n=r.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!n){r=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();n=r.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!n)return"";try{const o=JSON.parse(n[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return o.uid?String(o.uid):""}catch(o){return""}}function i(r){const n=btoa(r+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let s=n;while(s.length<43)s+=o.charAt(Math.floor(Math.random()*o.length));return s.slice(0,43)}const e=await a();if(!e)throw Error("未取到微博 uid,请先登录微博");if(t.indexOf("data:")===0){const r=c.dataUriToBlob(t),o="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="+i(e),l=await(await fetch(o,{method:"POST",credentials:"include",body:r})).json(),d=l&&l.data&&l.data.pics&&l.data.pics.pic_1&&l.data.pics.pic_1.pid;if(!d)throw Error("图片直传失败:"+JSON.stringify(l).slice(0,200));return{url:"https://wx3.sinaimg.cn/large/"+d+".jpg"}}const u=i(e);try{await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncuploadimg?uid="+e+"&_rid="+u,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":u},body:new URLSearchParams({"urls[0]":t})})}catch(r){}for(let r=0;r<30;r++){const n=i(e),s=await(await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncimginfo?uid="+e+"&_rid="+n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":n},body:new URLSearchParams({"urls[0]":t})})).json(),l=s&&s.data&&s.data[0],d=l&&l.task_status_code;if(d===1&&l.pid)return{url:"https://wx3.sinaimg.cn/large/"+l.pid+".jpg"};if(d===2)throw Error("微博图片转存失败:"+t);await new Promise((g)=>setTimeout(g,1000))}throw Error("微博图片转存超时:"+t)}},checkAuth:async(t)=>{const i=(await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text()).match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!i)return{isAuthenticated:!1};let e=null;try{e=JSON.parse(i[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"))}catch(u){return{isAuthenticated:!1,error:"编辑器 config 解析失败"}}if(!e||!e.uid)return{isAuthenticated:!1};return{isAuthenticated:!0,userId:String(e.uid),username:e.nick||"",avatar:e.avatar_large||""}},publish:async(t,c)=>{async function a(){let m=document.documentElement.innerHTML||"",p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!p){m=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!p)return"";try{const f=JSON.parse(p[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return f.uid?String(f.uid):""}catch(f){return""}}function i(m){const p=btoa(m+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let w=p;while(w.length<43)w+=f.charAt(Math.floor(Math.random()*f.length));return w.slice(0,43)}const e=await a();if(!e)return{ok:!1,stage:"auth",message:"未取到微博 uid,请先登录微博"};let u=(t.content||"").replace(/>\s+</g,"><");const r=document.createElement("div");r.innerHTML=u;const n=r.querySelectorAll("img");for(let m=0;m<n.length;m++){const p=n[m],f=(p.getAttribute("src")||"").match(/sinaimg\.cn\/large\/([^/."]+)\.jpg/);if(!f)continue;p.setAttribute("data-pid",f[1]);if(!p.closest("figure")){const w=document.createElement("figure");w.className="image";p.parentNode.insertBefore(w,p);w.appendChild(p)}}u=r.innerHTML;const o=i(e),s=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/create?uid="+e+"&_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({})}),l=await s.text();let d=null;try{d=JSON.parse(l)}catch(m){}if(!s.ok||!d||d.code!==1e5||!d.data||!d.data.id)return{ok:!1,stage:"create",status:s.status,message:d&&d.msg||"创建草稿失败:"+l.slice(0,200)};const g=String(d.data.id),N=t.params&&typeof t.params.cover==="string"?t.params.cover:"",_=i(e),b=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/save?uid="+e+"&id="+g+"&_rid="+_,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":_},body:new URLSearchParams({id:g,title:t.title,subtitle:"",type:"",status:"0",publish_at:"",error_msg:"",error_code:"0",collection:"[]",free_content:"",content:u,cover:N,summary:"",writer:"",extra:"null",is_word:"0",article_recommend:"[]",follow_to_read:"1",isreward:"1",pay_setting:'{"ispay":0,"isvclub":0}',source:"0",action:"1",content_type:"0",save:"1"})}),I=await b.text();let y=null;try{y=JSON.parse(I)}catch(m){}if(!b.ok||!y||String(y.code)!=="100000")return{ok:!1,stage:"save",status:b.status,message:y&&y.msg||"保存草稿失败:"+I.slice(0,200)};return{ok:!0,id:g,url:"https://card.weibo.com/article/v5/editor#/draft/"+g,draft:!0}}};S({site:"weibo",name:"article",access:"write",description:"把长文以微博头条文章形式保存到草稿箱(card.weibo.com)。正文默认 Markdown,外链/本机图片自动转存到微博图床,支持 --cover 题图。注意:平台接口只到草稿态,正式发布需在微博头条文章编辑器里手动操作。",domain:"weibo.com",strategy:v.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"cover",help:"题图(本机图片路径或图片 URL,自动转存到微博图床)"},{name:"draft",type:"boolean",help:"仅保存草稿(微博头条文章目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行写入。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,c)=>{if(!t)throw new x("微博头条文章命令需要浏览器会话。");U(c);const a=String(c.title??"").trim();if(!a)throw new h("INVALID_INPUT","文章标题不能为空。");const i=await L(c),e=typeof c.cover==="string"&&c.cover.trim()?c.cover.trim():"",u=!0,r=await P(t,{title:a,body:i,format:c.html?"html":"markdown",draftOnly:u,profile:weiboProfile,publishParams:e?{cover:e}:null}),n=r.images.uploaded.length|0,o=r.images.failed.length|0;let s="已保存微博头条文章草稿(正式发布请在编辑器里手动操作)";if(n||o)s+="·图片:"+n+" 张已转存"+(o?","+o+" 张失败":"");s+=T(r.images);return E(s,"article","","draft",{created_target:"draft:"+r.id,created_url:r.url})}});
@@ -1 +1 @@
1
- import{CliError as m,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as k,Strategy as N}from"@jackwener/opencli/registry";import{publishArticle as b}from"../_shared/article/publish.js";import{readFile as q,stat as M}from"node:fs/promises";function T(t){if(!t.execute)throw new m("INVALID_INPUT","微信公众号写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function v(t){const i=typeof t.text==="string"?t.text:void 0,e=typeof t.file==="string"?t.file:void 0;if(i&&e)throw new m("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let n=i??"";if(e){let a;try{a=await M(e)}catch{throw new m("INVALID_INPUT",`文件不存在:${e}`)}if(!a.isFile())throw new m("INVALID_INPUT",`路径不是可读文本文件:${e}`);let o;try{o=await q(e)}catch{throw new m("INVALID_INPUT",`文件无法读取:${e}`)}try{n=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new m("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!n.trim())throw new m("INVALID_INPUT","正文不能为空。");return n}function P(t,i,e,n,a={}){return[{status:"success",outcome:n,message:t,target_type:i,target:e,...a}]}export const weixinProfile={home:"https://mp.weixin.qq.com",outputFormat:"html",preprocessConfig:{removeLinks:!0,keepLinkDomains:["mp.weixin.qq.com","weixin.qq.com"],compactHtml:!0},image:{skip:["mmbiz.qpic.cn","mmbiz.qlogo.cn"],uploadFn:async(t,i)=>{const e=document.documentElement.innerHTML,n=e.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/),a=e.match(/ticket:\s*["']([^"']+)["']/),o=e.match(/user_name:\s*["']([^"']+)["']/),c=e.match(/time:\s*["'](\d+)["']/);if(!n)throw Error("微信图片上传:页面中未找到 token,请确认已登录 mp.weixin.qq.com。");const r=n[1],l=a?a[1]:"",s=o?o[1]:"",p=c?Number(c[1]):Math.floor(Date.now()/1000),u=await fetch(t,{credentials:"omit"});if(!u.ok)throw Error("图片下载失败:"+t+"(HTTP "+u.status+")");const h=await u.blob(),_=Date.now(),w=_+".jpg",d=new FormData;d.append("type",h.type||"image/jpeg");d.append("id",String(_));d.append("name",w);d.append("lastModifiedDate",new Date().toString());d.append("size",String(h.size));d.append("file",h,w);const y=Date.now(),I="https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&scene=8&writetype=doublewrite&groupid=1&ticket_id="+encodeURIComponent(s)+"&ticket="+encodeURIComponent(l)+"&svr_time="+p+"&token="+encodeURIComponent(r)+"&lang=zh_CN&seq="+y+"&t="+Math.random(),g=await fetch(I,{method:"POST",credentials:"include",body:d}),f=await g.json().catch(()=>({}));if(!g.ok||f.base_resp?.err_msg!=="ok"||!f.cdn_url)throw Error("微信图片上传失败:"+t+"("+(f.base_resp?.err_msg||"HTTP "+g.status)+")");return{url:f.cdn_url}}},checkAuth:async(t)=>{const e=await(await fetch("https://mp.weixin.qq.com/",{method:"GET",credentials:"include"})).text(),n=e.match(/user_name:\s*["']([^"']+)["']/),a=e.match(/nick_name:\s*["']([^"']+)["']/);if(!n&&!a)return{isAuthenticated:!1};const o=e.match(/class="weui-desktop-account__thumb"[^>]*src="([^"]+)"/),c=e.match(/head_img:\s*['"]([^'"]+)['"]/);let r=o?o[1]:c?c[1]:"";if(r.startsWith("http://"))r=r.replace("http://","https://");return{isAuthenticated:!0,userId:n?n[1]:"",username:a?a[1]:"",avatar:r}},publish:async(t,i)=>{const n=document.documentElement.innerHTML.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/);if(!n)return{ok:!1,stage:"auth",message:"页面中未找到 token,请确认已登录 mp.weixin.qq.com。"};const a=n[1],o=t.content,c=new URLSearchParams({token:a,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:t.title,author0:"",writerid0:"0",fileid0:"",digest0:"",auto_gen_digest0:"1",content0:o,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:"[]"}),r=await fetch("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=77&token="+encodeURIComponent(a)+"&lang=zh_CN",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});var l=await r.text(),s=null;try{s=JSON.parse(l)}catch(w){}if(!r.ok||!s||!s.appMsgId){var p=s&&(s.ret!=null?s.ret:s.base_resp&&s.base_resp.ret),u={"-6":"请输入验证码","-8":"请输入验证码","-1":"系统错误,请注意备份内容后重试","-2":"参数错误,请注意备份内容后重试","-99":"内容超出字数,请调整","200003":"登录态超时,请重新登录","64507":"内容不能包含外部链接","64702":"标题超出 64 字长度限制","64705":"内容超出字数,请调整"},h=p!=null&&u[String(p)]||"发布失败(错误码:"+p+"):"+l.slice(0,200);return{ok:!1,stage:"publish",status:r.status,message:h}}const _="https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=77&appmsgid="+s.appMsgId+"&token="+encodeURIComponent(a)+"&lang=zh_CN";return{ok:!0,id:String(s.appMsgId),url:_,draft:!0}}},weixinAuthProfile={home:weixinProfile.home,checkAuth:weixinProfile.checkAuth};k({site:"weixin",name:"article",access:"write",description:"通过 API 把文章发布到微信公众号草稿箱。正文默认 Markdown,外链图片自动转存到微信 CDN。",domain:"mp.weixin.qq.com",strategy:N.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(最长 64 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"draft",type:"boolean",help:"仅保存草稿(微信公众号目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行发布。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,i)=>{if(!t)throw new x("微信公众号 article 命令需要浏览器会话。");T(i);const e=String(i.title??"").trim();if(!e)throw new m("INVALID_INPUT","文章标题不能为空。");const n=await v(i),a=!0,o=await b(t,{title:e,body:n,format:i.html?"html":"markdown",draftOnly:a,profile:weixinProfile}),c=o.images.uploaded.length|0,r=o.images.failed.length|0;let l="已保存微信公众号草稿";if(c||r)l+="·图片:"+c+" 张已转存"+(r?","+r+" 张失败":"");return P(l,"article","","draft",{created_target:"article:"+o.id,created_url:o.url})}});
1
+ import{CliError as l,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as k,Strategy as b}from"@jackwener/opencli/registry";import{formatImageReport as N,publishArticle as q}from"../_shared/article/publish.js";import{readFile as M,stat as T}from"node:fs/promises";import{rememberArticleFile as v}from"../_shared/article/images.js";function P(t){if(!t.execute)throw new l("INVALID_INPUT","微信公众号写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function A(t){const i=typeof t.text==="string"?t.text:void 0,e=typeof t.file==="string"?t.file:void 0;if(i&&e)throw new l("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let n=i??"";if(e){v(e);let r;try{r=await T(e)}catch{throw new l("INVALID_INPUT",`文件不存在:${e}`)}if(!r.isFile())throw new l("INVALID_INPUT",`路径不是可读文本文件:${e}`);let o;try{o=await M(e)}catch{throw new l("INVALID_INPUT",`文件无法读取:${e}`)}try{n=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new l("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!n.trim())throw new l("INVALID_INPUT","正文不能为空。");return n}function U(t,i,e,n,r={}){return[{status:"success",outcome:n,message:t,target_type:i,target:e,...r}]}export const weixinProfile={home:"https://mp.weixin.qq.com",outputFormat:"html",preprocessConfig:{removeLinks:!0,keepLinkDomains:["mp.weixin.qq.com","weixin.qq.com"],compactHtml:!0},image:{skip:["mmbiz.qpic.cn","mmbiz.qlogo.cn"],uploadFn:async(t,i)=>{const e=document.documentElement.innerHTML,n=e.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/),r=e.match(/ticket:\s*["']([^"']+)["']/),o=e.match(/user_name:\s*["']([^"']+)["']/),c=e.match(/time:\s*["'](\d+)["']/);if(!n)throw Error("微信图片上传:页面中未找到 token,请确认已登录 mp.weixin.qq.com。");const a=n[1],m=r?r[1]:"",s=o?o[1]:"",p=c?Number(c[1]):Math.floor(Date.now()/1000),u=await fetch(t,{credentials:"omit"});if(!u.ok)throw Error("图片下载失败:"+t+"(HTTP "+u.status+")");const h=await u.blob(),_=Date.now(),w=_+".jpg",d=new FormData;d.append("type",h.type||"image/jpeg");d.append("id",String(_));d.append("name",w);d.append("lastModifiedDate",new Date().toString());d.append("size",String(h.size));d.append("file",h,w);const y=Date.now(),I="https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&scene=8&writetype=doublewrite&groupid=1&ticket_id="+encodeURIComponent(s)+"&ticket="+encodeURIComponent(m)+"&svr_time="+p+"&token="+encodeURIComponent(a)+"&lang=zh_CN&seq="+y+"&t="+Math.random(),g=await fetch(I,{method:"POST",credentials:"include",body:d}),f=await g.json().catch(()=>({}));if(!g.ok||f.base_resp?.err_msg!=="ok"||!f.cdn_url)throw Error("微信图片上传失败:"+t+"("+(f.base_resp?.err_msg||"HTTP "+g.status)+")");return{url:f.cdn_url}}},checkAuth:async(t)=>{const e=await(await fetch("https://mp.weixin.qq.com/",{method:"GET",credentials:"include"})).text(),n=e.match(/user_name:\s*["']([^"']+)["']/),r=e.match(/nick_name:\s*["']([^"']+)["']/);if(!n&&!r)return{isAuthenticated:!1};const o=e.match(/class="weui-desktop-account__thumb"[^>]*src="([^"]+)"/),c=e.match(/head_img:\s*['"]([^'"]+)['"]/);let a=o?o[1]:c?c[1]:"";if(a.startsWith("http://"))a=a.replace("http://","https://");return{isAuthenticated:!0,userId:n?n[1]:"",username:r?r[1]:"",avatar:a}},publish:async(t,i)=>{const n=document.documentElement.innerHTML.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/);if(!n)return{ok:!1,stage:"auth",message:"页面中未找到 token,请确认已登录 mp.weixin.qq.com。"};const r=n[1],o=t.content,c=new URLSearchParams({token:r,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:t.title,author0:"",writerid0:"0",fileid0:"",digest0:"",auto_gen_digest0:"1",content0:o,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:"[]"}),a=await fetch("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=77&token="+encodeURIComponent(r)+"&lang=zh_CN",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});var m=await a.text(),s=null;try{s=JSON.parse(m)}catch(w){}if(!a.ok||!s||!s.appMsgId){var p=s&&(s.ret!=null?s.ret:s.base_resp&&s.base_resp.ret),u={"-6":"请输入验证码","-8":"请输入验证码","-1":"系统错误,请注意备份内容后重试","-2":"参数错误,请注意备份内容后重试","-99":"内容超出字数,请调整","200003":"登录态超时,请重新登录","64507":"内容不能包含外部链接","64702":"标题超出 64 字长度限制","64705":"内容超出字数,请调整"},h=p!=null&&u[String(p)]||"发布失败(错误码:"+p+"):"+m.slice(0,200);return{ok:!1,stage:"publish",status:a.status,message:h}}const _="https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=77&appmsgid="+s.appMsgId+"&token="+encodeURIComponent(r)+"&lang=zh_CN";return{ok:!0,id:String(s.appMsgId),url:_,draft:!0}}},weixinAuthProfile={home:weixinProfile.home,checkAuth:weixinProfile.checkAuth};k({site:"weixin",name:"article",access:"write",description:"通过 API 把文章发布到微信公众号草稿箱。正文默认 Markdown,外链图片自动转存到微信 CDN。",domain:"mp.weixin.qq.com",strategy:b.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(最长 64 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"draft",type:"boolean",help:"仅保存草稿(微信公众号目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行发布。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,i)=>{if(!t)throw new x("微信公众号 article 命令需要浏览器会话。");P(i);const e=String(i.title??"").trim();if(!e)throw new l("INVALID_INPUT","文章标题不能为空。");const n=await A(i),r=!0,o=await q(t,{title:e,body:n,format:i.html?"html":"markdown",draftOnly:r,profile:weixinProfile}),c=o.images.uploaded.length|0,a=o.images.failed.length|0;let m="已保存微信公众号草稿";if(c||a)m+="·图片:"+c+" 张已转存"+(a?","+a+" 张失败":"");m+=N(o.images);return U(m,"article","","draft",{created_target:"article:"+o.id,created_url:o.url})}});
@@ -1 +1 @@
1
- import{CliError as d,CommandExecutionError as f}from"@jackwener/opencli/errors";import{cli as g,Strategy as y}from"@jackwener/opencli/registry";import{publishArticle as _}from"../_shared/article/publish.js";import{checkLogin as E}from"../_shared/article/auth.js";import{readFile as I,stat as T}from"node:fs/promises";function L(a){if(!a.execute)throw new d("INVALID_INPUT","此写操作需要 --execute 参数确认,未传则拒绝写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function N(a){const n=typeof a.text==="string"?a.text:void 0,e=typeof a.file==="string"?a.file:void 0;if(n&&e)throw new d("INVALID_INPUT","正文来源只能二选一:<text> 或 --file,不能同时指定");let r=n??"";if(e){let i;try{i=await T(e)}catch{throw new d("INVALID_INPUT",`文件不存在:${e}`)}if(!i.isFile())throw new d("INVALID_INPUT",`必须是普通文本文件:${e}`);let o;try{o=await I(e)}catch{throw new d("INVALID_INPUT",`文件无法读取:${e}`)}try{r=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new d("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!r.trim())throw new d("INVALID_INPUT","正文不能为空或仅有空白字符");return r}function R(a,n,e,r,i={}){return[{status:"success",outcome:r,message:a,target_type:n,target:e,...i}]}export const woshipmProfile={home:"https://www.woshipm.com/writing",outputFormat:"html",preprocessConfig:{removeEmptyLines:!0},image:{skip:["woshipm.com","image.woshipm.com"],uploadFn:async(a,n)=>{const r=(document.documentElement.innerHTML||"").match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"";let o="image.png";try{const m=new URL(a).pathname.split("/"),w=m[m.length-1];if(w)o=w}catch(p){}const s=await fetch(a,{credentials:"omit"});if(!s.ok)throw Error("下载图片失败:"+s.status+" "+a);const c=await s.blob(),t=new FormData;t.append("action","wpuf_insert_image");t.append("name",o);t.append("files",c,o);const u={};if(i)u.jlstar="Bearer "+i;const l=await(await fetch("https://www.woshipm.com/tensorflow/upyun/upload",{method:"POST",credentials:"include",headers:u,body:t})).json();if(l&&l.data&&l.data.length>0&&l.data[0].url)return{url:l.data[0].url};throw Error(l.error||"图片上传失败:接口返回无 URL")}},checkAuth:async(a)=>{const e=await(await fetch("https://www.woshipm.com/writing",{method:"GET",credentials:"include"})).text(),r=e.match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"",o=e.match(/var\s+userSettings\s*=\s*\{[^}]*"uid"\s*:\s*"(\d+)"/);if(!o)return{isAuthenticated:!1};const s=o[1],c=await fetch("https://www.woshipm.com/api2/user/profile?uid="+s,{method:"GET",credentials:"include",headers:{"X-Requested-With":"XMLHttpRequest"}});let t=null;try{t=await c.json()}catch(u){}if(t&&t.CODE===200&&t.RESULT&&t.RESULT.userInfoVo&&t.RESULT.userInfoVo.uid){const u=t.RESULT.userInfoVo;return{isAuthenticated:!0,userId:String(u.uid),username:u.nickName||"",avatar:u.avartar||""}}return{isAuthenticated:!1,error:"接口返回未登录(CODE: "+(t&&t.CODE)+")"}},publish:async(a,n)=>{const e=a.content,r="https://www.woshipm.com/wp-admin/admin-ajax.php",i={"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"};if(a.draftOnly){const h=await fetch(r,{method:"POST",credentials:"include",headers:i,body:new URLSearchParams({action:"add_draft",post_title:a.title,post_content:e})}),l=await h.text();let p=null;try{p=JSON.parse(l)}catch(P){}if(!h.ok||!p||!p.post_id)return{ok:!1,stage:"create",status:h.status,message:p&&p.error||l.slice(0,300)};const m=String(p.post_id),w=p.url||"https://www.woshipm.com/writing?pid="+m;return{ok:!0,draft:!0,id:m,url:w}}const o=new URLSearchParams({action:"add_pending",post_title:a.title,post_content:e,copyright:"1",copyright_pm:"1",copyright_other:"1"}),s=await fetch(r,{method:"POST",credentials:"include",headers:i,body:o}),c=await s.text();let t=null;try{t=JSON.parse(c)}catch(h){}if(!s.ok||!t||String(t.success)!=="1")return{ok:!1,stage:"publish",status:s.status,message:t&&t.message||c.slice(0,300)};return{ok:!0,draft:!1,pending:!0,id:t&&(t.post_id||t.id)?String(t.post_id||t.id):"",url:"https://www.woshipm.com/me/posts/"}}};g({site:"woshipm",name:"article",access:"write",description:"发布文章到人人都是产品经理(woshipm.com)。默认提交审核(正式发布),加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到站内图床。注意:平台为审核制,提交后稿件进入待审核(pending),运营 24h 内人工审核通过才公开。",domain:"www.woshipm.com",strategy:y.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(非空,长度<=200)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 而非 Markdown 处理"},{name:"draft",type:"boolean",help:"仅保存草稿,不提交审核"},{name:"execute",type:"boolean",help:"确认执行写操作。未传则拒绝写入。提交审核不可轻易撤回,请确认后再加此参数。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(a,n)=>{if(!a)throw new f("woshipm article 需要浏览器会话");L(n);const e=String(n.title??"").trim();if(!e)throw new d("INVALID_INPUT","文章标题不能为空");if(e.length>200)throw new d("INVALID_INPUT","文章标题过长(最多 200 字),当前 "+e.length+" 字");const r=await N(n),i=Boolean(n.draft),o=await _(a,{title:e,body:r,format:n.html?"html":"markdown",draftOnly:i,profile:woshipmProfile}),s=o.images.uploaded.length|0,c=o.images.failed.length|0;let t=o.draft?"已保存到草稿箱":"已提交审核(稿件进入待审核 pending,运营 24h 内人工审核通过后才公开)";if(s||c)t+=`(图片:${s} 张已转存${c?`,${c} 张失败`:""})`;return R(t,"article","",o.draft?"draft":"pending",{created_target:(o.draft?"draft:":"article:")+(o.id||""),created_url:o.url})}});
1
+ import{CliError as d,CommandExecutionError as f}from"@jackwener/opencli/errors";import{cli as g,Strategy as y}from"@jackwener/opencli/registry";import{formatImageReport as _,publishArticle as I}from"../_shared/article/publish.js";import{checkLogin as A}from"../_shared/article/auth.js";import{readFile as T,stat as L}from"node:fs/promises";import{rememberArticleFile as R}from"../_shared/article/images.js";function N(a){if(!a.execute)throw new d("INVALID_INPUT","此写操作需要 --execute 参数确认,未传则拒绝写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function P(a){const n=typeof a.text==="string"?a.text:void 0,e=typeof a.file==="string"?a.file:void 0;if(n&&e)throw new d("INVALID_INPUT","正文来源只能二选一:<text> 或 --file,不能同时指定");let r=n??"";if(e){R(e);let i;try{i=await L(e)}catch{throw new d("INVALID_INPUT",`文件不存在:${e}`)}if(!i.isFile())throw new d("INVALID_INPUT",`必须是普通文本文件:${e}`);let o;try{o=await T(e)}catch{throw new d("INVALID_INPUT",`文件无法读取:${e}`)}try{r=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new d("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!r.trim())throw new d("INVALID_INPUT","正文不能为空或仅有空白字符");return r}function b(a,n,e,r,i={}){return[{status:"success",outcome:r,message:a,target_type:n,target:e,...i}]}export const woshipmProfile={home:"https://www.woshipm.com/writing",outputFormat:"html",preprocessConfig:{removeEmptyLines:!0},image:{skip:["woshipm.com","image.woshipm.com"],uploadFn:async(a,n)=>{const r=(document.documentElement.innerHTML||"").match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"";let o="image.png";try{const h=new URL(a).pathname.split("/"),w=h[h.length-1];if(w)o=w}catch(p){}const s=await fetch(a,{credentials:"omit"});if(!s.ok)throw Error("下载图片失败:"+s.status+" "+a);const c=await s.blob(),t=new FormData;t.append("action","wpuf_insert_image");t.append("name",o);t.append("files",c,o);const u={};if(i)u.jlstar="Bearer "+i;const l=await(await fetch("https://www.woshipm.com/tensorflow/upyun/upload",{method:"POST",credentials:"include",headers:u,body:t})).json();if(l&&l.data&&l.data.length>0&&l.data[0].url)return{url:l.data[0].url};throw Error(l.error||"图片上传失败:接口返回无 URL")}},checkAuth:async(a)=>{const e=await(await fetch("https://www.woshipm.com/writing",{method:"GET",credentials:"include"})).text(),r=e.match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"",o=e.match(/var\s+userSettings\s*=\s*\{[^}]*"uid"\s*:\s*"(\d+)"/);if(!o)return{isAuthenticated:!1};const s=o[1],c=await fetch("https://www.woshipm.com/api2/user/profile?uid="+s,{method:"GET",credentials:"include",headers:{"X-Requested-With":"XMLHttpRequest"}});let t=null;try{t=await c.json()}catch(u){}if(t&&t.CODE===200&&t.RESULT&&t.RESULT.userInfoVo&&t.RESULT.userInfoVo.uid){const u=t.RESULT.userInfoVo;return{isAuthenticated:!0,userId:String(u.uid),username:u.nickName||"",avatar:u.avartar||""}}return{isAuthenticated:!1,error:"接口返回未登录(CODE: "+(t&&t.CODE)+")"}},publish:async(a,n)=>{const e=a.content,r="https://www.woshipm.com/wp-admin/admin-ajax.php",i={"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"};if(a.draftOnly){const m=await fetch(r,{method:"POST",credentials:"include",headers:i,body:new URLSearchParams({action:"add_draft",post_title:a.title,post_content:e})}),l=await m.text();let p=null;try{p=JSON.parse(l)}catch(x){}if(!m.ok||!p||!p.post_id)return{ok:!1,stage:"create",status:m.status,message:p&&p.error||l.slice(0,300)};const h=String(p.post_id),w=p.url||"https://www.woshipm.com/writing?pid="+h;return{ok:!0,draft:!0,id:h,url:w}}const o=new URLSearchParams({action:"add_pending",post_title:a.title,post_content:e,copyright:"1",copyright_pm:"1",copyright_other:"1"}),s=await fetch(r,{method:"POST",credentials:"include",headers:i,body:o}),c=await s.text();let t=null;try{t=JSON.parse(c)}catch(m){}if(!s.ok||!t||String(t.success)!=="1")return{ok:!1,stage:"publish",status:s.status,message:t&&t.message||c.slice(0,300)};return{ok:!0,draft:!1,pending:!0,id:t&&(t.post_id||t.id)?String(t.post_id||t.id):"",url:"https://www.woshipm.com/me/posts/"}}};g({site:"woshipm",name:"article",access:"write",description:"发布文章到人人都是产品经理(woshipm.com)。默认提交审核(正式发布),加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到站内图床。注意:平台为审核制,提交后稿件进入待审核(pending),运营 24h 内人工审核通过才公开。",domain:"www.woshipm.com",strategy:y.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(非空,长度<=200)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 而非 Markdown 处理"},{name:"draft",type:"boolean",help:"仅保存草稿,不提交审核"},{name:"execute",type:"boolean",help:"确认执行写操作。未传则拒绝写入。提交审核不可轻易撤回,请确认后再加此参数。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(a,n)=>{if(!a)throw new f("woshipm article 需要浏览器会话");N(n);const e=String(n.title??"").trim();if(!e)throw new d("INVALID_INPUT","文章标题不能为空");if(e.length>200)throw new d("INVALID_INPUT","文章标题过长(最多 200 字),当前 "+e.length+" 字");const r=await P(n),i=Boolean(n.draft),o=await I(a,{title:e,body:r,format:n.html?"html":"markdown",draftOnly:i,profile:woshipmProfile}),s=o.images.uploaded.length|0,c=o.images.failed.length|0;let t=o.draft?"已保存到草稿箱":"已提交审核(稿件进入待审核 pending,运营 24h 内人工审核通过后才公开)";if(s||c)t+=`(图片:${s} 张已转存${c?`,${c} 张失败`:""})`;t+=_(o.images);return b(t,"article","",o.draft?"draft":"pending",{created_target:(o.draft?"draft:":"article:")+(o.id||""),created_url:o.url})}});
package/clis/xianyu/im.js CHANGED
@@ -1,4 +1,4 @@
1
- import{ArgumentError as s,CommandExecutionError as l}from"@jackwener/opencli/errors";export const DEFAULT_INBOX_LIMIT=20,MAX_INBOX_LIMIT=100,DEFAULT_MESSAGE_LIMIT=50,MAX_MESSAGE_LIMIT=200;export function normalizeLimit(e,t=DEFAULT_INBOX_LIMIT,r=MAX_INBOX_LIMIT,a="limit"){const o=String(e??"").trim();if(!o)return t;if(!/^\d+$/.test(o))throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);const n=Number(o);if(!Number.isSafeInteger(n)||n<1||n>r)throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);return n}export function normalizeRank(e){const t=String(e??"").trim();if(!t)return 0;if(!/^\d+$/.test(t))throw new s("xianyu rank must be a positive integer from xianyu inbox");const r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new s("xianyu rank must be a positive integer from xianyu inbox");return r}export function requireText(e,t){const r=String(e??"").replace(/\s+/g," ").trim();if(!r)throw new s(`${t} cannot be empty`);return r}export function requireEvaluateObject(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new l(`Xianyu ${t} returned malformed browser payload`);return e}export function requireClickResult(e,t){const r=requireEvaluateObject(e,t);if(r.ok!==!0)throw new l(`Xianyu ${t} failed: ${r.reason||"unknown-reason"}`);return r}export function buildChatUrl(e,t){return`https://www.goofish.com/im?itemId=${encodeURIComponent(e)}&peerUserId=${encodeURIComponent(t)}`}export function buildInboxUrl(){return"https://www.goofish.com/im"}export function buildClickInboxConversationEvaluate(e){return`
1
+ import{ArgumentError as s,CommandExecutionError as l}from"@jackwener/opencli/errors";export const DEFAULT_INBOX_LIMIT=20,MAX_INBOX_LIMIT=100,DEFAULT_MESSAGE_LIMIT=50,MAX_MESSAGE_LIMIT=200;export function normalizeLimit(e,t=DEFAULT_INBOX_LIMIT,r=MAX_INBOX_LIMIT,a="limit"){const o=String(e??"").trim();if(!o)return t;if(!/^\d+$/.test(o))throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);const n=Number(o);if(!Number.isSafeInteger(n)||n<1||n>r)throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);return n}export function normalizeRank(e){const t=String(e??"").trim();if(!t||t==="0")return 0;if(!/^\d+$/.test(t))throw new s("xianyu rank must be a positive integer from xianyu inbox");const r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new s("xianyu rank must be a positive integer from xianyu inbox");return r}export function requireText(e,t){const r=String(e??"").replace(/\s+/g," ").trim();if(!r)throw new s(`${t} cannot be empty`);return r}export function requireEvaluateObject(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new l(`Xianyu ${t} returned malformed browser payload`);return e}export function requireClickResult(e,t){const r=requireEvaluateObject(e,t);if(r.ok!==!0)throw new l(`Xianyu ${t} failed: ${r.reason||"unknown-reason"}`);return r}export function buildChatUrl(e,t){return`https://www.goofish.com/im?itemId=${encodeURIComponent(e)}&peerUserId=${encodeURIComponent(t)}`}export function buildInboxUrl(){return"https://www.goofish.com/im"}export function buildClickInboxConversationEvaluate(e){return`
2
2
  (() => {
3
3
  const rows = Array.from(document.querySelectorAll('#conv-list-scrollable [class*="conversation-item"], a[href*="/im"], a[href*="itemId="][href*="peerUserId="]'));
4
4
  const row = rows[${e}];