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,8 @@
1
- import{readChapters as v,setXhsChapters as x}from"./publish-editors.js";import*as s from"node:fs";import*as a from"node:path";import{setInputFiles as f}from"../../_shared/file-inject.js";import{ArgumentError as l,CommandExecutionError as m}from"@jackwener/opencli/errors";import{clickControl as c,control as w,fillControl as u,verifyControl as r,publicationTime as q,resolveDeclaration as b}from"../../_shared/publish-controls.js";async function y(t,e){const o=await w(t,".d-select",e);await t.evaluate(`(() => {const el=document.querySelectorAll('.d-select')[${o.nth}].closest('.d-select-wrapper'); el.focus();return true;})()`);await t.wait({time:0.2})}async function h(t,e,o){const n=await w(t,e,o);await t.evaluate(`(() => {document.querySelectorAll(${JSON.stringify(e)})[${n.nth}].click();return true;})()`);await t.wait({time:0.2})}export const XHS_DECLARATIONS={ai:"笔记含AI合成内容",fiction:"虚构演绎,仅供娱乐",marketing:"内容包含营销广告",reprint:"来源转载","self-shot":"自主拍摄"};const d={public:"公开可见",private:"仅自己可见",friends:"仅互关好友可见",include:"只给谁看",exclude:"不给谁看"};export const XHS_PUBLISH_ARGS=[{name:"declaration",choices:Object.keys(XHS_DECLARATIONS),help:"内容声明:ai / fiction / marketing / reprint / self-shot"},{name:"source",help:"转载来源媒体名称(declaration=reprint 必填)"},{name:"shot-location",help:"自主拍摄地点(使用平台候选地点的完整名称)"},{name:"shot-date",help:"自主拍摄日期 YYYY-MM-DD"},{name:"original",type:"boolean",help:"声明原创;true 同意平台原创声明须知,false 取消"},{name:"visibility",choices:Object.keys(d),help:"可见范围;include/exclude 需同时指定 --audience"},{name:"audience",help:"定向可见用户昵称,逗号分隔(最多200人,须在平台可选列表中)"},{name:"schedule",help:"北京时间 YYYY-MM-DD HH:mm / 带时区 ISO8601 / Unix秒;1小时至14天后"},{name:"allow-duet",type:"boolean",help:"允许合拍(true/false,不传保留平台默认)"},{name:"allow-copy",type:"boolean",help:"允许正文复制(true/false,不传保留平台默认)"},{name:"location",help:"地点完整名称,按平台搜索结果精确选择"},{name:"location-address",help:"地点完整地址,使用 xiaohongshu location 返回的地址区分重名"},{name:"activity",help:"关联活动完整名称(平台会自动添加活动话题)"},{name:"quote-note",help:"引用笔记链接(小红书完整链接,包含访问所需参数)"},{name:"quote-title",help:"引用自己已发布笔记的完整标题,与 --quote-note 二选一"},{name:"attachment",help:"文件附件路径:pdf/doc/docx/ppt/pptx,最多100MB"}],XHS_VIDEO_ARGS=[...XHS_PUBLISH_ARGS.filter((t)=>!["allow-duet","allow-copy","attachment"].includes(t.name)),{name:"chapters",help:"章节 JSON 文件路径:[{time:整数秒,title:章节名,description:描述}],视频须至少15秒"},{name:"summary",help:"视频内容总结(最多100字)"},{name:"cover",help:"自定义视频封面图片路径(jpg/png/webp)"},{name:"cover-ratio",choices:["original","1:1","3:4","4:3"],help:"封面裁剪比例,需同时提供 --cover"}];export function validateXhsSettings(t){if(t["location-address"]&&!t.location)throw new l("--location-address 需要 --location");const e=v(t.chapters);if(t.summary!==void 0&&[...String(t.summary)].length>100)throw new l("--summary 最多100字");if(t["cover-ratio"]&&!t.cover)throw new l("--cover-ratio 需要 --cover");if(t.cover){const i=a.resolve(t.cover);if(!s.existsSync(i)||!s.statSync(i).isFile()||![".jpg",".jpeg",".png",".webp"].includes(a.extname(i).toLowerCase()))throw new l("封面需为存在的 jpg/png/webp 文件")}if(t["quote-note"]&&t["quote-title"])throw new l("--quote-note 与 --quote-title 二选一");if(t["quote-note"]){let i;try{i=new URL(t["quote-note"])}catch{throw new l("--quote-note 需要完整的小红书笔记链接")}if(i.protocol!=="https:"||!["xiaohongshu.com","www.xiaohongshu.com","xhslink.com"].includes(i.hostname))throw new l("--quote-note 需要 HTTPS 小红书笔记链接")}if(t.attachment){const i=a.resolve(t.attachment);if(!s.existsSync(i)||!s.statSync(i).isFile())throw new l("附件文件不存在: "+i);if(![".pdf",".doc",".docx",".ppt",".pptx"].includes(a.extname(i).toLowerCase())||s.statSync(i).size>104857600)throw new l("附件需为100MB以内的 pdf/doc/docx/ppt/pptx")}const o=b(t,XHS_DECLARATIONS);if(o==="reprint"&&!String(t.source||"").trim())throw new l("--declaration reprint 需要 --source 媒体名称");if(t.source&&o!=="reprint")throw new l("--source 仅用于 --declaration reprint");if(o==="reprint"&&t.original)throw new l("转载来源声明不能与 --original true 同时使用");if(o==="self-shot"&&(!t["shot-location"]||!/^\d{4}-\d{2}-\d{2}$/.test(t["shot-date"]||"")))throw new l("自主拍摄需 --shot-location 和 --shot-date YYYY-MM-DD");if((t["shot-date"]||t["shot-location"])&&o!=="self-shot")throw new l("拍摄地点和日期仅用于 --declaration self-shot");if(t.visibility!==void 0&&!Object.hasOwn(d,t.visibility))throw new l("不支持的 --visibility");const n=String(t.audience||"").split(",").map((i)=>i.trim()).filter(Boolean);if(["include","exclude"].includes(t.visibility)&&(!n.length||n.length>200||new Set(n).size!==n.length))throw new l("定向可见需要1至200个不重复的 --audience 用户");if(n.length&&!["include","exclude"].includes(t.visibility))throw new l("--audience 仅用于 include/exclude 可见范围");return{declaration:o,schedule:q(t.schedule,1),audience:n,chapters:e}}async function p(t,e,o){return t.evaluate(`([...document.querySelectorAll(${JSON.stringify(e)})].filter(e=>e.getClientRects().length && e.textContent.trim()===${JSON.stringify(o)}).length === 1)`)}export async function xhsSwitch(t,e,o){const i=await(()=>t.evaluate(`((label)=>{const rows=[...document.querySelectorAll('.custom-switch-card')].filter(e=>e.querySelector('.custom-switch-text-content > span')?.textContent.trim()===label);if(rows.length!==1)return null; const input=rows[0].querySelector('input[type="checkbox"]');return input ? {checked:input.checked,nth:[...document.querySelectorAll('.custom-switch-card .d-switch')].indexOf(rows[0].querySelector('.d-switch'))}:null;})(${JSON.stringify(e)})`))();if(!i||i.nth<0)throw new m("未找到发布设置开关:"+e+";已停止提交");if(i?.checked===o)return;await t.click(".custom-switch-card .d-switch",{nth:i.nth});await t.wait({time:0.2});if(e==="原创声明"&&o&&await t.evaluate("!!document.querySelector('.originalContainer')")){await c(t,".originalContainer .d-checkbox");await c(t,".originalContainer button","声明原创")}await r(t,`((label,value)=>{const rows=[...document.querySelectorAll('.custom-switch-card')].filter(e=>e.querySelector('.custom-switch-text-content > span')?.textContent.trim()===label);return rows.length===1 && rows[0].querySelector('input[type="checkbox"]')?.checked===value;})(${JSON.stringify(e)},${o})`,e)}async function C(t,e,o){const n=XHS_DECLARATIONS[o],i=await p(t,".d-select-description",n);if(i&&!["reprint","self-shot"].includes(o))return;await c(t,".d-select",i?n:"添加内容类型声明");if(o==="reprint"||o==="self-shot")await c(t,".declaration-drop-down .d-option-name","内容来源声明");await c(t,".d-popover .d-option-content",n);if(o==="reprint"){await u(t,'input[placeholder="请输入媒体名称"]',e.source);await c(t,".self-shooting-contain button","确认")}if(o==="self-shot"){await u(t,'input[placeholder="下拉选择地点"]',e["shot-location"],!1);await r(t,`!![...document.querySelectorAll('.el-autocomplete-suggestion .name')].find(e=>e.textContent.trim()===${JSON.stringify(e["shot-location"])})`,"拍摄地点候选");await c(t,".el-autocomplete-suggestion .name",e["shot-location"],!1);await u(t,".self-shooting-contain .d-datepicker-input-filter input",e["shot-date"]);await c(t,".self-shooting-contain button","确认")}await r(t,`([...document.querySelectorAll('.d-select-description')].filter(e=>e.textContent.trim()===${JSON.stringify(n)}).length===1) && !document.querySelector('.self-shooting-contain')`,n)}export async function setXhsPublishSettings(t,e){const o=validateXhsSettings(e);if(e.original!==void 0)await xhsSwitch(t,"原创声明",e.original);if(o.declaration)await C(t,e,o.declaration);if(e["allow-duet"]!==void 0)await xhsSwitch(t,"允许合拍",e["allow-duet"]);if(e["allow-copy"]!==void 0)await xhsSwitch(t,"允许正文复制",e["allow-copy"]);if(e.visibility){const n=d[e.visibility];if(!await p(t,".d-select-description",n)){const i=await t.evaluate(`([...document.querySelectorAll('.d-select-description')].filter(e=>${JSON.stringify(Object.values(d))}.includes(e.textContent.trim())).map(e=>e.textContent.trim()))`);if(i.length!==1)throw new m("无法确定当前可见范围;已停止提交");await y(t,i[0]);await h(t,".custom-option .name",n)}if(o.audience.length){for(const i of o.audience){await u(t,'.d-modal input[placeholder="搜索用户"]',i,!1);await r(t,`!![...document.querySelectorAll('.d-modal .left .user-list *')].find(e=>!e.children.length&&e.textContent.trim()===${JSON.stringify(i)})`,"可选用户 "+i);await c(t,".d-modal .left .user-list .user-name",i)}await c(t,".d-modal .confirm-btn","确认")}await r(t,`([...document.querySelectorAll('.d-select-description')].filter(e=>e.textContent.trim()===${JSON.stringify(n)}).length===1)`,"可见范围")}if(o.schedule){await xhsSwitch(t,"定时发布",!0);await u(t,".d-datepicker-input-filter input",o.schedule)}if(e.location){await y(t,"添加地点");await u(t,".d-select.focus input",e.location,!1);const n=`(({name,address})=>{const all=[...document.querySelectorAll('.d-popover .option-name')];const hits=all.filter(e=>e.getClientRects().length && e.textContent.trim()===name && (!address || e.parentElement.querySelector('.option-subname')?.textContent.trim()===address));return hits.length===1 ? all.indexOf(hits[0]) : -1;})(${JSON.stringify({name:e.location,address:e["location-address"]})})`;await r(t,`(${n})>=0`,"唯一地点(重名时指定 --location-address)");const i=await t.evaluate(n);if(i<0)throw new m("地点候选已变化,停止提交");await t.evaluate(`document.querySelectorAll('.d-popover .option-name')[${i}].click()`);await r(t,`!![...document.querySelectorAll('.d-select-description')].find(e=>e.textContent.trim()===${JSON.stringify(e.location)})`,"地点")}if(e["quote-note"]||e["quote-title"]){await c(t,".setting-card-text","引用笔记");if(e["quote-note"]){await c(t,".select-note-modal__tab","他人笔记");await u(t,'input[placeholder="请粘贴笔记链接 http://..."]',e["quote-note"],!1)}const n=e["quote-title"];await r(t,`([...document.querySelectorAll('.select-note-modal .note-card__title')].filter(e=>e.getClientRects().length ${n?"&& e.textContent.trim()==="+JSON.stringify(n):""}).length===1)`,"待引用笔记");const i=await w(t,".select-note-modal .note-card__title",n),S=await t.evaluate(`document.querySelectorAll('.select-note-modal .note-card__title')[${i.nth}].textContent.trim()`);await t.click(i.selector,{nth:i.nth});await c(t,".select-note-modal button","确认引用");await r(t,`!document.querySelector('.select-note-modal') && document.body.innerText.includes(${JSON.stringify("《")} + ${JSON.stringify(S)} + '》')`,"引用笔记")}if(e.activity){await h(t,".more","更多");const n=`((name)=>{const cards=[...document.querySelectorAll('.activity-card-drawer')].filter(e=>e.querySelector('.activity-name')?.textContent.trim()===name);return cards.length===1 ? {nth:[...document.querySelectorAll('.activity-card-drawer .activity-action')].indexOf(cards[0].querySelector('.activity-action')),selected:cards[0].querySelector('.activity-action')?.textContent.trim()==='取消关联'} : null;})(${JSON.stringify(e.activity)})`;await r(t,`!!(${n})`,"活动 "+e.activity);const i=await t.evaluate(n);if(!i.selected)await t.evaluate(`document.querySelectorAll('.activity-card-drawer .activity-action')[${i.nth}].click()`);await r(t,`(${n})?.selected === true`,"关联活动");await h(t,".d-drawer-close")}if(e.attachment){await f(t,'.file-relation-container input[type="file"]',[a.resolve(e.attachment)]);await r(t,`document.querySelector('.file-relation-container .setting-card-text')?.textContent.trim() === ${JSON.stringify(a.basename(e.attachment))} && !document.querySelector('.file-relation-container')?.textContent.includes('上传中')`,"附件上传",60000)}if(o.chapters||e.summary!==void 0)await x(t,o.chapters,e.summary);if(e.cover){const n=await t.evaluate("document.querySelector('.cover-plugin-preview > .cover > .default')?.style.backgroundImage");await c(t,".cover-plugin-preview > .cover > .default");await c(t,".cover-plugin-preview .cover-edit-entry");await c(t,".d-modal .d-tabs-header-label","上传封面");await f(t,'.d-modal input[type="file"]',[a.resolve(e.cover)]);await r(t,"!!document.querySelector('#upload-cover-containner .cropper-canvas img')?.getAttribute('src')","封面图片载入",30000);if(e["cover-ratio"]){const i=e["cover-ratio"]==="original"?"原始":e["cover-ratio"];await c(t,".d-modal .crop-ratio-item",i);await r(t,`document.querySelector('.d-modal .crop-ratio-item-active')?.textContent.trim()===${JSON.stringify(i)}`,"封面裁剪比例")}await c(t,".d-modal button","确定");await r(t,`!document.querySelector('#upload-cover-containner') && document.querySelector('.cover-plugin-preview')?.getAttribute('aria-busy')==='false' && document.querySelector('.cover-plugin-preview > .cover > .default')?.style.backgroundImage !== ${JSON.stringify(n)}`,"视频封面上传",60000)}}
1
+ import{readChapters as v,setXhsChapters as x}from"./publish-editors.js";import*as s from"node:fs";import*as a from"node:path";import{setInputFiles as f}from"../../_shared/file-inject.js";import{ArgumentError as c,CommandExecutionError as d}from"@jackwener/opencli/errors";import{clickControl as l,control as w,fillControl as u,verifyControl as r,publicationTime as q,resolveDeclaration as b}from"../../_shared/publish-controls.js";async function y(t,e){const o=await w(t,".d-select",e);await t.evaluate(`(() => {const el=document.querySelectorAll('.d-select')[${o.nth}].closest('.d-select-wrapper'); el.focus();return true;})()`);await t.wait({time:0.2})}async function h(t,e,o){const n=await w(t,e,o);await t.evaluate(`(() => {document.querySelectorAll(${JSON.stringify(e)})[${n.nth}].click();return true;})()`);await t.wait({time:0.2})}export const XHS_DECLARATIONS={ai:"笔记含AI合成内容",fiction:"虚构演绎,仅供娱乐",marketing:"内容包含营销广告",reprint:"来源转载","self-shot":"自主拍摄"};const m={public:"公开可见",private:"仅自己可见",friends:"仅互关好友可见",include:"只给谁看",exclude:"不给谁看"};export const XHS_PUBLISH_ARGS=[{name:"declaration",choices:Object.keys(XHS_DECLARATIONS),help:"内容声明:ai / fiction / marketing / reprint / self-shot"},{name:"source",help:"转载来源媒体名称(declaration=reprint 必填)"},{name:"shot-location",help:"自主拍摄地点(使用平台候选地点的完整名称)"},{name:"shot-date",help:"自主拍摄日期 YYYY-MM-DD"},{name:"original",type:"boolean",help:"声明原创;true 同意平台原创声明须知,false 取消"},{name:"visibility",choices:Object.keys(m),help:"可见范围;include/exclude 需同时指定 --audience"},{name:"audience",help:"定向可见用户昵称,逗号分隔(最多200人,须在平台可选列表中)"},{name:"schedule",help:"北京时间 YYYY-MM-DD HH:mm / 带时区 ISO8601 / Unix秒;1小时至14天后"},{name:"allow-duet",type:"boolean",help:"允许合拍(true/false,不传保留平台默认)"},{name:"allow-copy",type:"boolean",help:"允许正文复制(true/false,不传保留平台默认)"},{name:"location",help:"地点完整名称,按平台搜索结果精确选择"},{name:"location-address",help:"地点完整地址,使用 xiaohongshu location 返回的地址区分重名"},{name:"activity",help:"关联活动完整名称(平台会自动添加活动话题)"},{name:"quote-note",help:"引用笔记链接(小红书完整链接,包含访问所需参数)"},{name:"quote-title",help:"引用自己已发布笔记的完整标题,与 --quote-note 二选一"},{name:"attachment",help:"文件附件路径:pdf/doc/docx/ppt/pptx,最多100MB"}],XHS_VIDEO_ARGS=[...XHS_PUBLISH_ARGS.filter((t)=>!["allow-duet","allow-copy","attachment"].includes(t.name)),{name:"chapters",help:"章节 JSON 文件路径:[{time:整数秒,title:章节名,description:描述}],视频须至少15秒"},{name:"summary",help:"视频内容总结(最多100字)"},{name:"cover",help:"自定义视频封面图片路径(jpg/png/webp)"},{name:"cover-ratio",choices:["original","1:1","3:4","4:3"],help:"封面裁剪比例,需同时提供 --cover"}];export function validateXhsSettings(t){if(t["location-address"]&&!t.location)throw new c("--location-address 需要 --location");const e=v(t.chapters);if(t.summary!==void 0&&[...String(t.summary)].length>100)throw new c("--summary 最多100字");if(t["cover-ratio"]&&!t.cover)throw new c("--cover-ratio 需要 --cover");if(t.cover){const i=a.resolve(t.cover);if(!s.existsSync(i)||!s.statSync(i).isFile()||![".jpg",".jpeg",".png",".webp"].includes(a.extname(i).toLowerCase()))throw new c("封面需为存在的 jpg/png/webp 文件")}if(t["quote-note"]&&t["quote-title"])throw new c("--quote-note 与 --quote-title 二选一");if(t["quote-note"]){let i;try{i=new URL(t["quote-note"])}catch{throw new c("--quote-note 需要完整的小红书笔记链接")}if(i.protocol!=="https:"||!["xiaohongshu.com","www.xiaohongshu.com","xhslink.com"].includes(i.hostname))throw new c("--quote-note 需要 HTTPS 小红书笔记链接")}if(t.attachment){const i=a.resolve(t.attachment);if(!s.existsSync(i)||!s.statSync(i).isFile())throw new c("附件文件不存在: "+i);if(![".pdf",".doc",".docx",".ppt",".pptx"].includes(a.extname(i).toLowerCase())||s.statSync(i).size>104857600)throw new c("附件需为100MB以内的 pdf/doc/docx/ppt/pptx")}const o=b(t,XHS_DECLARATIONS);if(o==="reprint"&&!String(t.source||"").trim())throw new c("--declaration reprint 需要 --source 媒体名称");if(t.source&&o!=="reprint")throw new c("--source 仅用于 --declaration reprint");if(o==="reprint"&&t.original)throw new c("转载来源声明不能与 --original true 同时使用");if(o==="self-shot"&&(!t["shot-location"]||!/^\d{4}-\d{2}-\d{2}$/.test(t["shot-date"]||"")))throw new c("自主拍摄需 --shot-location 和 --shot-date YYYY-MM-DD");if((t["shot-date"]||t["shot-location"])&&o!=="self-shot")throw new c("拍摄地点和日期仅用于 --declaration self-shot");if(t.visibility!==void 0&&!Object.hasOwn(m,t.visibility))throw new c("不支持的 --visibility");const n=String(t.audience||"").split(",").map((i)=>i.trim()).filter(Boolean);if(["include","exclude"].includes(t.visibility)&&(!n.length||n.length>200||new Set(n).size!==n.length))throw new c("定向可见需要1至200个不重复的 --audience 用户");if(n.length&&!["include","exclude"].includes(t.visibility))throw new c("--audience 仅用于 include/exclude 可见范围");return{declaration:o,schedule:q(t.schedule,1),audience:n,chapters:e}}async function p(t,e,o){return t.evaluate(`([...document.querySelectorAll(${JSON.stringify(e)})].filter(e=>e.getClientRects().length && e.textContent.trim()===${JSON.stringify(o)}).length === 1)`)}export async function xhsSwitch(t,e,o){const i=await(()=>t.evaluate(`((label)=>{const rows=[...document.querySelectorAll('.custom-switch-card')].filter(e=>e.querySelector('.custom-switch-text-content > span')?.textContent.trim()===label);if(rows.length!==1)return null; const input=rows[0].querySelector('input[type="checkbox"]');return input ? {checked:input.checked,nth:[...document.querySelectorAll('.custom-switch-card .d-switch')].indexOf(rows[0].querySelector('.d-switch'))}:null;})(${JSON.stringify(e)})`))();if(!i||i.nth<0)throw new d("未找到发布设置开关:"+e+";已停止提交");if(i?.checked===o)return;await t.click(".custom-switch-card .d-switch",{nth:i.nth});await t.wait({time:0.2});if(e==="原创声明"&&o&&await t.evaluate("!!document.querySelector('.originalContainer')")){await l(t,".originalContainer .d-checkbox");await l(t,".originalContainer button","声明原创")}await r(t,`((label,value)=>{const rows=[...document.querySelectorAll('.custom-switch-card')].filter(e=>e.querySelector('.custom-switch-text-content > span')?.textContent.trim()===label);return rows.length===1 && rows[0].querySelector('input[type="checkbox"]')?.checked===value;})(${JSON.stringify(e)},${o})`,e)}async function C(t,e,o){const n=XHS_DECLARATIONS[o],i=await p(t,".d-select-description",n);if(i&&!["reprint","self-shot"].includes(o))return;await l(t,".d-select",i?n:"添加内容类型声明");if(o==="reprint"||o==="self-shot")await l(t,".declaration-drop-down .d-option-name","内容来源声明");await l(t,".d-popover .d-option-content",n);if(o==="reprint"){await u(t,'input[placeholder="请输入媒体名称"]',e.source);await l(t,".self-shooting-contain button","确认")}if(o==="self-shot"){await u(t,'input[placeholder="下拉选择地点"]',e["shot-location"],!1);await r(t,`!![...document.querySelectorAll('.el-autocomplete-suggestion .name')].find(e=>e.textContent.trim()===${JSON.stringify(e["shot-location"])})`,"拍摄地点候选");await l(t,".el-autocomplete-suggestion .name",e["shot-location"],!1);await u(t,".self-shooting-contain .d-datepicker-input-filter input",e["shot-date"]);await l(t,".self-shooting-contain button","确认")}await r(t,`([...document.querySelectorAll('.d-select-description')].filter(e=>e.textContent.trim()===${JSON.stringify(n)}).length===1) && !document.querySelector('.self-shooting-contain')`,n)}async function O(t){const e=await t.evaluate(`(() => {
2
+ const preview = document.querySelector('.cover-plugin-preview');
3
+ if (!preview) return {error: '未找到视频封面区(.cover-plugin-preview)'};
4
+ const entries = [...preview.querySelectorAll('.cover-edit-entry')].filter(e => e.textContent.trim() === '编辑封面');
5
+ if (entries.length !== 1) return {error: '封面区「编辑封面」入口应唯一,找到 ' + entries.length + ';封面区现有文字:' + preview.innerText.replace(/\\s+/g, ' ').trim().slice(0, 80)};
6
+ entries[0].click();
7
+ return {ok: true};
8
+ })()`);if(!e?.ok)throw new d(`发布设置 视频封面:${e?.error||"页面响应异常"};已停止提交`);await r(t,"[...document.querySelectorAll('.d-modal .d-tabs-header-label')].some(e => e.getClientRects().length && e.textContent.trim() === '上传封面')","打开设置封面弹窗",1e4)}export async function setXhsPublishSettings(t,e){const o=validateXhsSettings(e);if(e.original!==void 0)await xhsSwitch(t,"原创声明",e.original);if(o.declaration)await C(t,e,o.declaration);if(e["allow-duet"]!==void 0)await xhsSwitch(t,"允许合拍",e["allow-duet"]);if(e["allow-copy"]!==void 0)await xhsSwitch(t,"允许正文复制",e["allow-copy"]);if(e.visibility){const n=m[e.visibility];if(!await p(t,".d-select-description",n)){const i=await t.evaluate(`([...document.querySelectorAll('.d-select-description')].filter(e=>${JSON.stringify(Object.values(m))}.includes(e.textContent.trim())).map(e=>e.textContent.trim()))`);if(i.length!==1)throw new d("无法确定当前可见范围;已停止提交");await y(t,i[0]);await h(t,".custom-option .name",n)}if(o.audience.length){for(const i of o.audience){await u(t,'.d-modal input[placeholder="搜索用户"]',i,!1);await r(t,`!![...document.querySelectorAll('.d-modal .left .user-list *')].find(e=>!e.children.length&&e.textContent.trim()===${JSON.stringify(i)})`,"可选用户 "+i);await l(t,".d-modal .left .user-list .user-name",i)}await l(t,".d-modal .confirm-btn","确认")}await r(t,`([...document.querySelectorAll('.d-select-description')].filter(e=>e.textContent.trim()===${JSON.stringify(n)}).length===1)`,"可见范围")}if(o.schedule){await xhsSwitch(t,"定时发布",!0);await u(t,".d-datepicker-input-filter input",o.schedule)}if(e.location){await y(t,"添加地点");await u(t,".d-select.focus input",e.location,!1);const n=`(({name,address})=>{const all=[...document.querySelectorAll('.d-popover .option-name')];const hits=all.filter(e=>e.getClientRects().length && e.textContent.trim()===name && (!address || e.parentElement.querySelector('.option-subname')?.textContent.trim()===address));return hits.length===1 ? all.indexOf(hits[0]) : -1;})(${JSON.stringify({name:e.location,address:e["location-address"]})})`;await r(t,`(${n})>=0`,"唯一地点(重名时指定 --location-address)");const i=await t.evaluate(n);if(i<0)throw new d("地点候选已变化,停止提交");await t.evaluate(`document.querySelectorAll('.d-popover .option-name')[${i}].click()`);await r(t,`!![...document.querySelectorAll('.d-select-description')].find(e=>e.textContent.trim()===${JSON.stringify(e.location)})`,"地点")}if(e["quote-note"]||e["quote-title"]){await l(t,".setting-card-text","引用笔记");if(e["quote-note"]){await l(t,".select-note-modal__tab","他人笔记");await u(t,'input[placeholder="请粘贴笔记链接 http://..."]',e["quote-note"],!1)}const n=e["quote-title"];await r(t,`([...document.querySelectorAll('.select-note-modal .note-card__title')].filter(e=>e.getClientRects().length ${n?"&& e.textContent.trim()==="+JSON.stringify(n):""}).length===1)`,"待引用笔记");const i=await w(t,".select-note-modal .note-card__title",n),S=await t.evaluate(`document.querySelectorAll('.select-note-modal .note-card__title')[${i.nth}].textContent.trim()`);await t.click(i.selector,{nth:i.nth});await l(t,".select-note-modal button","确认引用");await r(t,`!document.querySelector('.select-note-modal') && document.body.innerText.includes(${JSON.stringify("《")} + ${JSON.stringify(S)} + '》')`,"引用笔记")}if(e.activity){await h(t,".more","更多");const n=`((name)=>{const cards=[...document.querySelectorAll('.activity-card-drawer')].filter(e=>e.querySelector('.activity-name')?.textContent.trim()===name);return cards.length===1 ? {nth:[...document.querySelectorAll('.activity-card-drawer .activity-action')].indexOf(cards[0].querySelector('.activity-action')),selected:cards[0].querySelector('.activity-action')?.textContent.trim()==='取消关联'} : null;})(${JSON.stringify(e.activity)})`;await r(t,`!!(${n})`,"活动 "+e.activity);const i=await t.evaluate(n);if(!i.selected)await t.evaluate(`document.querySelectorAll('.activity-card-drawer .activity-action')[${i.nth}].click()`);await r(t,`(${n})?.selected === true`,"关联活动");await h(t,".d-drawer-close")}if(e.attachment){await f(t,'.file-relation-container input[type="file"]',[a.resolve(e.attachment)]);await r(t,`document.querySelector('.file-relation-container .setting-card-text')?.textContent.trim() === ${JSON.stringify(a.basename(e.attachment))} && !document.querySelector('.file-relation-container')?.textContent.includes('上传中')`,"附件上传",60000)}if(o.chapters||e.summary!==void 0)await x(t,o.chapters,e.summary);if(e.cover){const n=await t.evaluate("document.querySelector('.cover-plugin-preview > .cover > .default')?.style.backgroundImage");await O(t);await l(t,".d-modal .d-tabs-header-label","上传封面");await f(t,'.d-modal input[type="file"]',[a.resolve(e.cover)]);await r(t,"!!document.querySelector('#upload-cover-containner .cropper-canvas img')?.getAttribute('src')","封面图片载入",30000);if(e["cover-ratio"]){const i=e["cover-ratio"]==="original"?"原始":e["cover-ratio"];await l(t,".d-modal .crop-ratio-item",i);await r(t,`document.querySelector('.d-modal .crop-ratio-item-active')?.textContent.trim()===${JSON.stringify(i)}`,"封面裁剪比例")}await l(t,".d-modal button","确定");await r(t,`!document.querySelector('#upload-cover-containner') && document.querySelector('.cover-plugin-preview')?.getAttribute('aria-busy')==='false' && document.querySelector('.cover-plugin-preview > .cover > .default')?.style.backgroundImage !== ${JSON.stringify(n)}`,"视频封面上传",60000)}}
@@ -1,4 +1,4 @@
1
- function e(t,o){return t+Math.random()*(o-t)}function M(t,o=0.4,r=0.02){const n=t*o;return Math.max(r,t-n+Math.random()*n*2)}export async function humanWait(t,o,r=0.4){try{await t.wait({time:M(o,r)})}catch{}}export async function humanType(t,o){const r=String(o);if(!r)return;if(typeof t.insertText!=="function"){try{await t.insertText?.(r)}catch{}return}let n=0;while(n<r.length){const a=Math.max(1,Math.round(e(1,4))),i=r.slice(n,n+a);n+=i.length;try{await t.insertText(i)}catch{try{await t.insertText(r.slice(n-i.length))}catch{}return}const h=Math.random()<0.12?e(0.35,0.8):e(0.04,0.18);try{await t.wait({time:h})}catch{}}}function m(t){if(!t.__xhsCursor)t.__xhsCursor={x:Math.round(e(80,520)),y:Math.round(e(120,420))};return t.__xhsCursor}function _(t,o,r){const n=o.x-t.x,a=o.y-t.y,i=Math.hypot(n,a)||1,h=-a/i,y=n/i,u=e(0.05,0.22)*i*(Math.random()<0.5?1:-1),l={x:t.x+n*e(0.2,0.4)+h*u,y:t.y+a*e(0.2,0.4)+y*u},d={x:t.x+n*e(0.6,0.8)+h*u*e(0.3,0.7),y:t.y+a*e(0.6,0.8)+y*u*e(0.3,0.7)},f=[];for(let x=1;x<=r;x++){const c=x/r,s=1-c,w=s*s*s*t.x+3*s*s*c*l.x+3*s*c*c*d.x+c*c*c*o.x,p=s*s*s*t.y+3*s*s*c*l.y+3*s*c*c*d.y+c*c*c*o.y;f.push({x:Math.round(w),y:Math.round(p)})}return f}export async function humanMoveTo(t,o,r){if(typeof t.cdp!=="function")return;const n={x:Math.round(o+e(-3,3)),y:Math.round(r+e(-3,3))},a=m(t),i=Math.hypot(n.x-a.x,n.y-a.y),h=Math.max(6,Math.min(18,Math.round(i/30))),y=_(a,n,h);for(const u of y){try{await t.cdp("Input.dispatchMouseEvent",{type:"mouseMoved",x:u.x,y:u.y})}catch{return}try{await t.wait({time:M(0.02,0.6,0.008)})}catch{}}t.__xhsCursor=n}export async function elementViewportCenter(t,o){try{const r=await t.evaluate(`
1
+ function c(t,e){return t+Math.random()*(e-t)}function M(t,e=0.4,r=0.02){const n=t*e;return Math.max(r,t-n+Math.random()*n*2)}export async function humanWait(t,e,r=0.4){try{await t.wait({time:M(e,r)})}catch{}}export async function humanType(t,e){const r=String(e);if(!r)return;if(typeof t.insertText!=="function"){try{await t.insertText?.(r)}catch{}return}const n=splitGraphemes(r);let o=0;while(o<n.length){const u=Math.max(1,Math.round(c(1,4))),h=n.slice(o,o+u).join(""),y=n.slice(o).join("");o+=u;try{await t.insertText(h)}catch{try{await t.insertText(y)}catch{}return}const i=Math.random()<0.12?c(0.35,0.8):c(0.04,0.18);try{await t.wait({time:i})}catch{}}}export function splitGraphemes(t){const e=String(t);if(typeof Intl<"u"&&typeof Intl.Segmenter==="function")return Array.from(new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e),(r)=>r.segment);return Array.from(e)}function w(t){if(!t.__xhsCursor)t.__xhsCursor={x:Math.round(c(80,520)),y:Math.round(c(120,420))};return t.__xhsCursor}function _(t,e,r){const n=e.x-t.x,o=e.y-t.y,u=Math.hypot(n,o)||1,h=-o/u,y=n/u,i=c(0.05,0.22)*u*(Math.random()<0.5?1:-1),l={x:t.x+n*c(0.2,0.4)+h*i,y:t.y+o*c(0.2,0.4)+y*i},f={x:t.x+n*c(0.6,0.8)+h*i*c(0.3,0.7),y:t.y+o*c(0.6,0.8)+y*i*c(0.3,0.7)},d=[];for(let x=1;x<=r;x++){const s=x/r,a=1-s,m=a*a*a*t.x+3*a*a*s*l.x+3*a*s*s*f.x+s*s*s*e.x,p=a*a*a*t.y+3*a*a*s*l.y+3*a*s*s*f.y+s*s*s*e.y;d.push({x:Math.round(m),y:Math.round(p)})}return d}export async function humanMoveTo(t,e,r){if(typeof t.cdp!=="function")return;const n={x:Math.round(e+c(-3,3)),y:Math.round(r+c(-3,3))},o=w(t),u=Math.hypot(n.x-o.x,n.y-o.y),h=Math.max(6,Math.min(18,Math.round(u/30))),y=_(o,n,h);for(const i of y){try{await t.cdp("Input.dispatchMouseEvent",{type:"mouseMoved",x:i.x,y:i.y})}catch{return}try{await t.wait({time:M(0.02,0.6,0.008)})}catch{}}t.__xhsCursor=n}export async function elementViewportCenter(t,e){try{const r=await t.evaluate(`
2
2
  (sels => {
3
3
  const __opencli_xhs_el_center = true;
4
4
  for (const sel of sels) {
@@ -10,5 +10,5 @@ function e(t,o){return t+Math.random()*(o-t)}function M(t,o=0.4,r=0.02){const n=
10
10
  }
11
11
  }
12
12
  return null;
13
- })(${JSON.stringify(o)})
13
+ })(${JSON.stringify(e)})
14
14
  `),n=r&&typeof r==="object"&&"data"in r?r.data:r;if(n&&typeof n.x==="number"&&typeof n.y==="number")return n}catch{}return null}
@@ -37,7 +37,7 @@ import{TOPIC_ID_ARG as C,parseTopics as I,attachTopics as q}from"./_shared/topic
37
37
  `)}B({site:"xiaohongshu",name:"publish-video",access:"write",description:"小红书发布视频笔记(creator center UI 自动化)",domain:"creator.xiaohongshu.com",strategy:U.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不展开 @文件 引用;长正文用 --file)"},{name:"file",required:!1,help:"从本机文件读取正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题(≤20字)"},{name:"video",required:!0,help:"视频文件路径 (mp4/mov/mkv/...)"},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},C,{name:"draft",type:"bool",default:!1,help:"暂存为草稿,不直接发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...D],columns:["status","detail"],func:async(t,e)=>{R(e);if(!t)throw Error("Browser page required");const i=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new s("正文位置参数和 --file 只能二选一");const r=p.resolve(n);if(!_.existsSync(r))throw new s(`--file 指向的文件不存在: ${r}`);o=_.readFileSync(r,"utf-8").trim();if(!o)throw new s(`--file 指向的文件内容为空: ${r}`)}const c=I(e),h=c.map((r)=>r.name),l=Boolean(e.draft);if(!i)throw new s("--title 必填");if(i.length>y)throw new s(`标题 ${i.length} 字,需 ≤ ${y} 字`);if(!o)throw new s("缺少正文:给位置参数 <content>,或用 --file <本机文件路径>");k(o,{fileFlag:"--file"});if(o.length>x)throw new s(`正文 ${o.length} 字,需 ≤ ${x} 字`);if(!e.video)throw new s("--video 必填");if(h.length>S)throw new s(`话题过多: ${h.length}(最多 ${S} 个)`);const v=G(String(e.video));await t.goto(J);await t.evaluate(`(() => {
38
38
  document.documentElement.setAttribute('data-ppcli-composer-reload', 'pending');
39
39
  setTimeout(() => location.reload(), 100);
40
- })()`);await L(t,`!document.documentElement.hasAttribute('data-ppcli-composer-reload') && !!document.querySelector('input[type="file"]')`,"新的视频发布表单",30000);let d="";for(let r=0;r<30;r++){await t.wait({time:0.5});d=await t.evaluate("() => location.href");if(d.includes("creator.xiaohongshu.com"))break}if(!d.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_video_redirect_debug.png"});throw new a(`被重定向离开创作者中心(当前 ${d})——登录态可能已过期。`+"用 ppcli xiaohongshu creator-profile 重新登录。截图: /tmp/xhs_video_redirect_debug.png")}const g=await K(t,v);if(!g.ok){await t.screenshot({path:"/tmp/xhs_video_upload_debug.png"});throw new a(`视频上传失败: ${g.error??"unknown"}。截图: /tmp/xhs_video_upload_debug.png`)}if(!await Q(t)){await t.screenshot({path:"/tmp/xhs_video_form_debug.png"});throw new a("上传后编辑表单未就绪(标题/正文未出现)。截图: /tmp/xhs_video_form_debug.png")}process.stderr.write(` 等待视频转码(可发布状态)...
40
+ })()`);await L(t,`!!document.documentElement && !document.documentElement.hasAttribute('data-ppcli-composer-reload') && !!document.querySelector('input[type="file"]')`,"新的视频发布表单",30000);let d="";for(let r=0;r<30;r++){await t.wait({time:0.5});d=await t.evaluate("() => location.href");if(d.includes("creator.xiaohongshu.com"))break}if(!d.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_video_redirect_debug.png"});throw new a(`被重定向离开创作者中心(当前 ${d})——登录态可能已过期。`+"用 ppcli xiaohongshu creator-profile 重新登录。截图: /tmp/xhs_video_redirect_debug.png")}const g=await K(t,v);if(!g.ok){await t.screenshot({path:"/tmp/xhs_video_upload_debug.png"});throw new a(`视频上传失败: ${g.error??"unknown"}。截图: /tmp/xhs_video_upload_debug.png`)}if(!await Q(t)){await t.screenshot({path:"/tmp/xhs_video_form_debug.png"});throw new a("上传后编辑表单未就绪(标题/正文未出现)。截图: /tmp/xhs_video_form_debug.png")}process.stderr.write(` 等待视频转码(可发布状态)...
41
41
  `);if(!await z(t)){await t.screenshot({path:"/tmp/xhs_video_transcode_debug.png"});throw new a("视频转码超时(10min),发布按钮未解禁。截图: /tmp/xhs_video_transcode_debug.png")}await W(t,i);await t.wait({time:0.4});await Z(t,o);await t.wait({time:0.5});let m=[];if(h.length){m=await q(t,[b],c);const r=h.filter((P)=>!m.includes(P));if(r.length){await t.screenshot({path:"/tmp/xhs_video_topic_debug.png"});throw new a(`话题未能生成实体: ${r.join(", ")}(联想下拉未出现或无匹配项)。截图: /tmp/xhs_video_topic_debug.png`)}}await F(t,e);const M=await t.evaluate("(() => { const b = document.querySelector('xhs-publish-btn'); return !!b && b.getAttribute('submit-disabled') === 'false'; })()");if(!l&&!M){await t.screenshot({path:"/tmp/xhs_video_prepublish_debug.png"});throw new a("发布前复查:发布按钮不可用(submit-disabled≠false)。截图: /tmp/xhs_video_prepublish_debug.png")}const f=await tt(t,l);if(!f?.ok){await t.screenshot({path:"/tmp/xhs_video_submit_debug.png"});throw new a(`找不到「${l?"暂存离开":"发布"}」触发方式(hosts=${f?.hosts??0}${f?.lastMethodError?`, lastMethodError=${f.lastMethodError}`:""})。截图: /tmp/xhs_video_submit_debug.png`)}await t.wait({time:4});let u=await t.evaluate("() => location.href");const N=l?["草稿已保存","暂存成功","保存成功","保存于"]:["发布成功","上传成功"],w=await t.evaluate(`
42
42
  ((markers) => {
43
43
  for (const el of document.querySelectorAll('*')) {
@@ -1,4 +1,4 @@
1
- import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as L from"node:fs";import*as N from"node:path";import{CommandExecutionError as u,ArgumentError as b}from"@jackwener/opencli/errors";import{cli as xt,Strategy as yt}from"@jackwener/opencli/registry";import{assertLiteralContent as vt}from"../_shared/content-guard.js";import{setInputFiles as St}from"../_shared/file-inject.js";import{humanType as X,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as $t}from"./_shared/note-manager.js";const Et="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",B=18,H=20,G=3000,Y="|||",S="基础",K=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=K.map(([t])=>t),U="文字配图",W="再写一张",Q="生成图片",Z="下一步",F=".tiptap.ProseMirror",At=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],J=['[contenteditable="true"][placeholder*="标题"]','[contenteditable="true"][placeholder*="赞"]','input[placeholder*="标题"]','input[placeholder*="title" i]','[contenteditable="true"][class*="title"]','input[maxlength="20"]','input[class*="title"]',".title-input input",".note-title input","input[maxlength]"],tt=['[contenteditable="true"][class*="content"]','[contenteditable="true"][class*="editor"]','[contenteditable="true"][placeholder*="描述"]','[contenteditable="true"][placeholder*="正文"]','[contenteditable="true"][placeholder*="内容"]','.note-content [contenteditable="true"]','.editor-content [contenteditable="true"]','[contenteditable="true"]:not([placeholder*="标题"]):not([placeholder*="赞"]):not([placeholder*="title" i])'],Mt={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function _(t){if(t&&typeof t==="object"&&typeof t.session==="string"&&Object.prototype.hasOwnProperty.call(t,"data"))return t.data;return t}function Nt(t){return t.map((e)=>{const r=N.resolve(e);if(!L.existsSync(r))throw new b(`Image file not found: ${r}`);const n=N.extname(r).toLowerCase();if(!Mt[n])throw new b(`Unsupported image format "${n}". Supported: jpg, png, gif, webp`);return r})}const et='input[type="file"][accept*="image"],input[type="file"][accept*=".jpg"],input[type="file"][accept*=".jpeg"],input[type="file"][accept*=".png"],input[type="file"][accept*=".gif"],input[type="file"][accept*=".webp"]';async function It(t,e=15000){const r=500,n=Math.max(1,Math.ceil(e/r));for(let o=0;o<n;o++){if(await t.evaluate(`
1
+ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as L from"node:fs";import*as N from"node:path";import{CommandExecutionError as u,ArgumentError as b}from"@jackwener/opencli/errors";import{cli as xt,Strategy as yt}from"@jackwener/opencli/registry";import{assertLiteralContent as vt}from"../_shared/content-guard.js";import{setInputFiles as St}from"../_shared/file-inject.js";import{humanType as H,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as Et}from"./_shared/note-manager.js";const $t="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",B=18,X=20,G=3000,Y="|||",k="基础",K=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=K.map(([t])=>t),F="文字配图",W="再写一张",Q="生成图片",Z="下一步",U=".tiptap.ProseMirror",At=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],J=['[contenteditable="true"][placeholder*="标题"]','[contenteditable="true"][placeholder*="赞"]','input[placeholder*="标题"]','input[placeholder*="title" i]','[contenteditable="true"][class*="title"]','input[maxlength="20"]','input[class*="title"]',".title-input input",".note-title input","input[maxlength]"],tt=['[contenteditable="true"][class*="content"]','[contenteditable="true"][class*="editor"]','[contenteditable="true"][placeholder*="描述"]','[contenteditable="true"][placeholder*="正文"]','[contenteditable="true"][placeholder*="内容"]','.note-content [contenteditable="true"]','.editor-content [contenteditable="true"]','[contenteditable="true"]:not([placeholder*="标题"]):not([placeholder*="赞"]):not([placeholder*="title" i])'],Mt={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function _(t){if(t&&typeof t==="object"&&typeof t.session==="string"&&Object.prototype.hasOwnProperty.call(t,"data"))return t.data;return t}function Nt(t){return t.map((e)=>{const r=N.resolve(e);if(!L.existsSync(r))throw new b(`Image file not found: ${r}`);const n=N.extname(r).toLowerCase();if(!Mt[n])throw new b(`Unsupported image format "${n}". Supported: jpg, png, gif, webp`);return r})}const et='input[type="file"][accept*="image"],input[type="file"][accept*=".jpg"],input[type="file"][accept*=".jpeg"],input[type="file"][accept*=".png"],input[type="file"][accept*=".gif"],input[type="file"][accept*=".webp"]';async function It(t,e=15000){const r=500,n=Math.max(1,Math.ceil(e/r));for(let o=0;o<n;o++){if(await t.evaluate(`
2
2
  (() => {
3
3
  const sels = ${JSON.stringify(et)};
4
4
  return !!document.querySelector(sels);
@@ -7,7 +7,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
7
7
  () => !!document.querySelector(
8
8
  '[class*="upload"][class*="progress"], [class*="uploading"], [class*="loading"][class*="image"]'
9
9
  )
10
- `))return;await t.wait({time:r/1000})}}export function describeTextMismatch(t,e){const r=String(t??""),n=String(e??""),o=(m)=>m.split(/\n\s*\n/).filter((y)=>y.trim()).length;let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;const a=(m)=>JSON.stringify(m.slice(Math.max(0,i-15),i+25)),c=`内容校验不一致:期望 ${r.length} 字符 / ${o(r)} 段,实际 ${n.length} 字符 / ${o(n)} 段。`,s=i>=r.length&&i>=n.length?"":` 首个差异在第 ${i+1} 个字符:期望 ${a(r)},实际 ${a(n)}。`,d=o(r)>1&&o(n)<=1?" 段落数塌成 1 段,通常是编辑器把换行吃掉了。":"";return c+s+d}async function Pt(t,e,r){const n=()=>t.evaluate(`
10
+ `))return;await t.wait({time:r/1000})}}export function describeTextMismatch(t,e,r){const n=String(t??""),o=String(e??""),i=(x)=>x.split(/\n\s*\n/).filter((S)=>S.trim()).length,a=r?r.expected:i(n),l=r?r.actual:i(o);let s=0;while(s<n.length&&s<o.length&&n[s]===o[s])s++;const d=(x)=>JSON.stringify(x.slice(Math.max(0,s-15),s+25)),w=`内容校验不一致:期望 ${n.length} 字符 / ${a} 段,实际 ${o.length} 字符 / ${l} 段。`,v=s>=n.length&&s>=o.length?"":` 首个差异在第 ${s+1} 个字符:期望 ${d(n)},实际 ${d(o)}。`,m=a>1&&l<=1?" 段落数塌成 1 段,通常是编辑器把换行吃掉了。":"",f=/\uFFFD/.test(o)&&!/\uFFFD/.test(n)?" 实际文本出现替换字符 �,说明 emoji 等多码元字符在写入时被拆开了。":"";return w+v+m+f}async function Pt(t,e,r){const n=()=>t.evaluate(`
11
11
  ((sel) => {
12
12
  const el = Array.from(document.querySelectorAll(sel)).find(n => n && n.offsetParent !== null);
13
13
  if (!el) return -1;
@@ -117,7 +117,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
117
117
  return { ok: true };
118
118
  })(${JSON.stringify(o.sel)})
119
119
  `))?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});throw Error(`Could not prepare ${n} input. Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}await t.wait({time:0.35});try{const s=String(r).split(`
120
- `);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await X(t,s[d])}a=await t.evaluate(`
120
+ `);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await H(t,s[d])}a=await t.evaluate(`
121
121
  ((selector, expectedText) => {
122
122
  const __opencli_xhs_fill_phase = "verify";
123
123
  const normalize = (value) => (value || '').replace(/\\s+/g, ' ').trim();
@@ -138,10 +138,12 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
138
138
  el.dispatchEvent(new Event('change', { bubbles: true }));
139
139
  el.blur();
140
140
  const actual = normalize(el.innerText || el.textContent || '');
141
- return { ok: actual === normalize(expectedText), actual };
141
+ const blocks = el.querySelectorAll('p, div[data-node-type], li').length || el.childElementCount;
142
+ return { ok: actual === normalize(expectedText), actual, blocks };
142
143
  })(${JSON.stringify(o.sel)}, ${JSON.stringify(r)})
143
144
  `)}catch(s){if(s instanceof u)throw s;if(String(r).includes(`
144
- `))throw new u(`写入${n}失败:${String(s?.message||s)}。`+"正文含换行,不能回退到单段写入方式(那会把多段正文塞进一段),因此中止。"+"⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看。");a=await i()}}else a=await i();if(!a?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});const c=typeof a?.actual==="string"?a.actual:"";throw Error(`Failed to set ${n}. ${describeTextMismatch(r,c)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function Rt(t){const e=await t.evaluate(`
145
+ `))throw new u(`写入${n}失败:${String(s?.message||s)}。`+"正文含换行,不能回退到单段写入方式(那会把多段正文塞进一段),因此中止。"+"⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看。");a=await i()}}else a=await i();if(!a?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});const l=typeof a?.actual==="string"?a.actual:"";throw Error(`Failed to set ${n}. ${describeTextMismatch(String(r).replace(/\s+/g," ").trim(),l,typeof a?.blocks==="number"?{expected:String(r).split(`
146
+ `).length,actual:a.blocks}:void 0)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function Rt(t){const e=await t.evaluate(`
145
147
  () => {
146
148
  const isVisible = (el) => {
147
149
  if (!el || el.offsetParent === null) return false;
@@ -190,7 +192,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
190
192
  }
191
193
  return { ok: false, visibleTexts };
192
194
  }
193
- `);if(e?.ok)await t.wait({time:1});return e}async function T(t,e,r=7000){const n=500,o=Math.max(1,Math.ceil(r/n));let i={ok:!1};for(let a=0;a<o;a++){i=_(await t.evaluate(`
195
+ `);if(e?.ok)await t.wait({time:1});return e}async function E(t,e,r=7000){const n=500,o=Math.max(1,Math.ceil(r/n));let i={ok:!1};for(let a=0;a<o;a++){i=_(await t.evaluate(`
194
196
  ((cfg) => {
195
197
  const __opencli_xhs_click_label = { wantLabel: ${JSON.stringify(e)} };
196
198
  const wantLabel = ${JSON.stringify(e)};
@@ -228,7 +230,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
228
230
  `));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function Dt(t){const e=await t.evaluate(`
229
231
  (() => {
230
232
  const __opencli_xhs_focus_card = true;
231
- const sel = ${JSON.stringify(F)};
233
+ const sel = ${JSON.stringify(U)};
232
234
  const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
233
235
  // Prefer the editor inside the active swiper slide if present.
234
236
  const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
@@ -245,7 +247,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
245
247
  `);return _(e)}async function qt(t){const e=await t.evaluate(`
246
248
  (() => {
247
249
  const __opencli_xhs_card_text = true;
248
- const sel = ${JSON.stringify(F)};
250
+ const sel = ${JSON.stringify(U)};
249
251
  const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
250
252
  const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
251
253
  const text = active ? (active.innerText || active.textContent || '').trim() : '';
@@ -254,22 +256,22 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
254
256
  `);return _(e)}async function it(t){const e=await t.evaluate(`
255
257
  (() => {
256
258
  const __opencli_xhs_card_count = true;
257
- const sel = ${JSON.stringify(F)};
259
+ const sel = ${JSON.stringify(U)};
258
260
  const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
259
261
  const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
260
262
  const activeText = active ? (active.innerText || active.textContent || '').trim() : '';
261
263
  return { ok: true, count: editors.length, activeEmpty: !activeText };
262
264
  })()
263
- `);return _(e)}async function Ot(t,e=8000){const r=300,n=Math.ceil(e/r);for(let o=0;o<n;o++){if((await it(t))?.count>=1)return!0;await t.wait({time:r/1000})}return!1}async function Lt(t,e,r=6000){const n=300,o=Math.ceil(r/n);for(let i=0;i<o;i++){const a=await it(t);if(a?.count>=e&&a?.activeEmpty)return!0;await t.wait({time:n/1000})}return!1}async function Bt(t,e,r=4){for(let n=0;n<r;n++){if(!(await T(t,W))?.ok)return!1;if(await Lt(t,e,2500))return!0}return!1}async function Ut(t){const e=await t.evaluate(`
265
+ `);return _(e)}async function Ot(t,e=8000){const r=300,n=Math.ceil(e/r);for(let o=0;o<n;o++){if((await it(t))?.count>=1)return!0;await t.wait({time:r/1000})}return!1}async function Lt(t,e,r=6000){const n=300,o=Math.ceil(r/n);for(let i=0;i<o;i++){const a=await it(t);if(a?.count>=e&&a?.activeEmpty)return!0;await t.wait({time:n/1000})}return!1}async function Bt(t,e,r=4){for(let n=0;n<r;n++){if(!(await E(t,W))?.ok)return!1;if(await Lt(t,e,2500))return!0}return!1}async function Ft(t){const e=await t.evaluate(`
264
266
  (() => {
265
267
  const __opencli_xhs_preview_ready = true;
266
268
  const ready = Array.from(document.querySelectorAll('button'))
267
269
  .some((b) => b.offsetParent !== null && (b.innerText || '').replace(/\\s+/g, '') === '下一步');
268
270
  return { ok: ready };
269
271
  })()
270
- `);return _(e)}async function Ft(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await T(t,Q))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Ut(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function Jt(t,e,r){e=String(e).replace(/\\n/g,`
272
+ `);return _(e)}async function Ut(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await E(t,Q))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Ft(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function Jt(t,e,r){e=String(e).replace(/\\n/g,`
271
273
  `);if(!(await Dt(t))?.ok)throw new u(`文字配图: could not focus card editor #${r+1}`);if(typeof t.insertText==="function"){const i=e.split(`
272
- `);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await X(t,i[a])}}else await t.evaluate(`(t => document.execCommand('insertText', false, t))(${JSON.stringify(e)})`);await t.wait({time:0.4});if(!(await qt(t))?.ok)throw new u(`文字配图: card editor #${r+1} is empty after typing`)}async function jt(t,e){if(!e||e===S)return S;const r=_(await t.evaluate(`
274
+ `);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await H(t,i[a])}}else await t.evaluate(`(t => document.execCommand('insertText', false, t))(${JSON.stringify(e)})`);await t.wait({time:0.4});if(!(await qt(t))?.ok)throw new u(`文字配图: card editor #${r+1} is empty after typing`)}async function jt(t,e){if(!e||e===k)return k;const r=_(await t.evaluate(`
273
275
  (async () => {
274
276
  const __opencli_xhs_card_styles = true;
275
277
  const want = ${JSON.stringify(e)};
@@ -298,7 +300,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
298
300
  }
299
301
  return { ok: seen.length > 0, styles: seen, found: false };
300
302
  })()
301
- `));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${S}.`);if(!(await T(t,e))?.ok)throw new u(`文字配图: could not click requested style "${e}".`);await t.wait({time:0.6});return e}async function at(t){const e=await t.evaluate(`
303
+ `));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${k}.`);if(!(await E(t,e))?.ok)throw new u(`文字配图: could not click requested style "${e}".`);await t.wait({time:0.6});return e}async function at(t){const e=await t.evaluate(`
302
304
  (() => {
303
305
  const __opencli_xhs_composer_media_count = true;
304
306
  const visibleBox = (el) => {
@@ -330,7 +332,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
330
332
  }
331
333
  return { ok: true, count };
332
334
  })()
333
- `);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await T(t,U))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${U}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Ot(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${U}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let c=0;c<e.length;c++){if(c>0){if(!await Bt(t,c+1)){await t.screenshot({path:"/tmp/xhs_publish_addcard_debug.png"});throw new u(`文字配图: new card editor #${c+1} did not render after "${W}". Debug: /tmp/xhs_publish_addcard_debug.png`)}}await Jt(t,e[c],c)}if(!await Ft(t)){await t.screenshot({path:"/tmp/xhs_publish_generate_debug.png"});throw new u(`文字配图: "${Q}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await jt(t,r);if(!(await T(t,Z))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Z}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
335
+ `);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await E(t,F))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${F}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Ot(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${F}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let l=0;l<e.length;l++){if(l>0){if(!await Bt(t,l+1)){await t.screenshot({path:"/tmp/xhs_publish_addcard_debug.png"});throw new u(`文字配图: new card editor #${l+1} did not render after "${W}". Debug: /tmp/xhs_publish_addcard_debug.png`)}}await Jt(t,e[l],l)}if(!await Ut(t)){await t.screenshot({path:"/tmp/xhs_publish_generate_debug.png"});throw new u(`文字配图: "${Q}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await jt(t,r);if(!(await E(t,Z))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Z}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
334
336
  () => {
335
337
  const text = (document.body?.innerText || '').replace(/s+/g, ' ').trim();
336
338
  const hasTitleInput = !!Array.from(document.querySelectorAll('input, textarea')).find((el) => {
@@ -360,7 +362,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
360
362
  const state = hasTitleInput ? 'editor_ready' : hasImageInput || !hasVideoSurface ? 'image_surface' : 'video_surface';
361
363
  return { state, hasTitleInput, hasImageInput, hasVideoSurface };
362
364
  }
363
- `)}async function zt(t,e=5000){const r=500,n=Math.max(1,Math.ceil(e/r));let o=await lt(t);for(let i=0;i<n;i++){if(o.state!=="video_surface")return o;if(i<n-1){await t.wait({time:r/1000});o=await lt(t)}}return o}async function Xt(t,e=1e4){const r=1000,n=Math.ceil(e/r);for(let o=0;o<n;o++){if(await t.evaluate(`
365
+ `)}async function zt(t,e=5000){const r=500,n=Math.max(1,Math.ceil(e/r));let o=await lt(t);for(let i=0;i<n;i++){if(o.state!=="video_surface")return o;if(i<n-1){await t.wait({time:r/1000});o=await lt(t)}}return o}async function Ht(t,e=1e4){const r=1000,n=Math.ceil(e/r);for(let o=0;o<n;o++){if(await t.evaluate(`
364
366
  (() => {
365
367
  const sels = ${JSON.stringify(J)};
366
368
  for (const sel of sels) {
@@ -368,7 +370,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
368
370
  if (el && el.offsetParent !== null) return true;
369
371
  }
370
372
  return false;
371
- })()`))return!0;if(o<n-1)await t.wait({time:r/1000})}return!1}async function Ht(t){const e=_(await t.evaluate(`
373
+ })()`))return!0;if(o<n-1)await t.wait({time:r/1000})}return!1}async function Xt(t){const e=_(await t.evaluate(`
372
374
  (() => {
373
375
  const __opencli_xhs_restore_srcs = true;
374
376
  return Array.from(document.querySelectorAll('.img-container img'))
@@ -406,7 +408,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
406
408
  }
407
409
  return removed;
408
410
  })(${JSON.stringify(e)})
409
- `));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),c=Math.ceil(n/o),s=new Set;for(let d=0;d<c;d++){const m=await t.readNetworkCapture().catch(()=>[]);for(const y of Array.isArray(m)?m:[]){const w=Gt(y);if(w)s.add(w)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const c=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!c)return!0;const s=Date.UTC(Number(c[1]),Number(c[2])-1,Number(c[3]),Number(c[4]),Number(c[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await $t(t,{tab:"all",limit:j+5})}catch(c){return{note:null,reason:`创作者后台笔记列表读取出错:${c?.message??String(c)}`}}const a=pickPublishedNote(i.notes,e);if(a)return{note:a,reason:""};n=i.notes.length===0?"创作者后台笔记列表为空":`创作者后台最新 ${Math.min(i.notes.length,j)} 条笔记里没有同标题笔记`}return{note:null,reason:n}}xt({site:"xiaohongshu",name:"publish",access:"write",description:"小红书发布图文笔记 (creator center UI automation)",domain:"creator.xiaohongshu.com",strategy:yt.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不会展开 @文件 引用;长正文建议用 --file)"},{name:"file",required:!1,help:"从本机文件读取笔记正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题 (最多20字)"},{name:"images",required:!1,help:`图片路径,逗号分隔,最多${B}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${Y} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${S}。可选: ${K.map(([t,e])=>`${t}(${e})`).join(" ")}`},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},mt,{name:"draft",type:"bool",default:!1,help:"保存为草稿,不直接发布"},{name:"timeout",type:"int",default:300,help:"整段发布流程的等待预算(秒);超时后先用 creator-notes 回查,勿直接重复发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...wt],columns:["status","detail","url"],func:async(t,e)=>{gt(e);if(!t)throw Error("Browser page required");const r=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new b("正文位置参数和 --file 只能二选一,不能同时给");const l=N.resolve(n);if(!L.existsSync(l))throw new b(`--file 指向的文件不存在: ${l}`);o=L.readFileSync(l,"utf-8").trim();if(!o)throw new b(`--file 指向的文件内容为空: ${l}`)}const i=e.images?String(e.images).split(",").map((l)=>l.trim()).filter(Boolean):[],a=pt(e),c=a.map((l)=>l.name),s=Boolean(e.draft),d=e["card-text"]?String(e["card-text"]):"",m=d?d.split(Y).map((l)=>l.trim()).filter(Boolean):[],y=e["card-style"]?String(e["card-style"]).trim():"",w=m.length>0;if(!r)throw new b("--title is required");if(r.length>H)throw new b(`Title is ${r.length} chars — must be ≤ ${H}`);if(!o)throw new b("缺少笔记正文:给位置参数 <content>(字面文本),或用 --file <本机文件路径>");vt(o,{fileFlag:"--file"});if(!w&&i.length===0)throw new b("Provide --card-text (text-image mode) or --images (upload mode); neither was given.");if(i.length>B)throw new b(`Too many images: ${i.length} (max ${B})`);if(w&&i.some((l)=>N.extname(l).toLowerCase()===".gif"))throw new b("文字配图模式追加的图片不支持 .gif(编辑器图片入口只接受 jpg/jpeg/png/webp)");const f=Nt(i);await t.goto(Et);await t.wait({time:1});await t.evaluate("() => { try { window.onbeforeunload = null; } catch (e) {} location.reload(); }").catch(()=>{return});let k="";for(let l=0;l<30;l++){await t.wait({time:0.5});k=await t.evaluate("() => location.href");if(k.includes("creator.xiaohongshu.com"))break}if(!k.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_publish_redirect_debug.png"});throw Error(`Redirected away from creator center (landed on ${k}) — session may have expired. `+"Re-capture browser login via: ppcli xiaohongshu creator-profile. Debug screenshot: /tmp/xhs_publish_redirect_debug.png")}const E=await Rt(t);if((await zt(t,E?.ok?5000:2000)).state==="video_surface"){await t.screenshot({path:"/tmp/xhs_publish_tab_debug.png"});const l=E?.ok?`clicked "${E.text}"`:`visible candidates: ${(E?.visibleTexts||[]).join(" | ")||"none"}`;throw Error("Still on the video publish page after trying to select 图文. "+`Details: ${l}. Debug screenshot: /tmp/xhs_publish_tab_debug.png`)}const A=await Ht(t);let C=y;if(w)C=await Vt(t,m,y);else{const l=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片注入失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_upload_debug.png")}await t.wait({time:G/1000});const x=await dt(t,f.length,l);if(!x.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片上传未全部完成:只确认 ${x.completed}/${f.length} 张传到小红书 CDN,`+"继续发布会丢图(通常只剩封面)。直接重新运行本 publish 命令即可(会自动重置发布页重传);"+"请勿手动修改当前页面。Debug: /tmp/xhs_publish_upload_debug.png")}await rt(t);if(A.length){await ct(t,A);await t.wait({time:0.5})}const M=await at(t);if(M&&typeof M.count==="number"&&M.count>f.length){await t.screenshot({path:"/tmp/xhs_publish_dup_debug.png"});throw new u(`清掉恢复态旧图后编辑器内仍有 ${M.count} 张图,超过本次注入的 ${f.length} 张。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。Debug: /tmp/xhs_publish_dup_debug.png")}}if(!await Xt(t)){await t.screenshot({path:"/tmp/xhs_publish_form_debug.png"});throw new u("Editing form did not appear after image acquisition. The page layout may have changed. Debug screenshot: /tmp/xhs_publish_form_debug.png")}if(w)await st(t,m.length,"文字配图 generated images");if(w&&f.length>0){const l=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await t.wait({time:G/1000});const x=await dt(t,f.length,l);if(!x.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片上传未全部完成:只确认 ${x.completed}/${f.length} 张传到小红书 CDN。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await rt(t);await st(t,m.length+f.length,"文字配图 appended images")}if(w&&A.length){await ct(t,A);await t.wait({time:0.5})}await ot(t,J,r,"title");await I(t,0.6);await ot(t,tt,o,"content");await I(t,0.6);let P=[];if(c.length)P=await bt(t,tt,a);await _t(t,e);await I(t,1,0.6);const R=await kt(t,["xhs-publish-btn"]);if(R){await Tt(t,R.x,R.y);await I(t,0.4)}const V=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
411
+ `));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),l=Math.ceil(n/o),s=new Set;for(let d=0;d<l;d++){const w=await t.readNetworkCapture().catch(()=>[]);for(const v of Array.isArray(w)?w:[]){const m=Gt(v);if(m)s.add(m)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const l=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!l)return!0;const s=Date.UTC(Number(l[1]),Number(l[2])-1,Number(l[3]),Number(l[4]),Number(l[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await Et(t,{tab:"all",limit:j+5})}catch(l){return{note:null,reason:`创作者后台笔记列表读取出错:${l?.message??String(l)}`}}const a=pickPublishedNote(i.notes,e);if(a)return{note:a,reason:""};n=i.notes.length===0?"创作者后台笔记列表为空":`创作者后台最新 ${Math.min(i.notes.length,j)} 条笔记里没有同标题笔记`}return{note:null,reason:n}}xt({site:"xiaohongshu",name:"publish",access:"write",description:"小红书发布图文笔记 (creator center UI automation)",domain:"creator.xiaohongshu.com",strategy:yt.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不会展开 @文件 引用;长正文建议用 --file)"},{name:"file",required:!1,help:"从本机文件读取笔记正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题 (最多20字)"},{name:"images",required:!1,help:`图片路径,逗号分隔,最多${B}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${Y} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${k}。可选: ${K.map(([t,e])=>`${t}(${e})`).join(" ")}`},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},mt,{name:"draft",type:"bool",default:!1,help:"保存为草稿,不直接发布"},{name:"timeout",type:"int",default:300,help:"整段发布流程的等待预算(秒);超时后先用 creator-notes 回查,勿直接重复发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...wt],columns:["status","detail","url"],func:async(t,e)=>{gt(e);if(!t)throw Error("Browser page required");const r=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new b("正文位置参数和 --file 只能二选一,不能同时给");const c=N.resolve(n);if(!L.existsSync(c))throw new b(`--file 指向的文件不存在: ${c}`);o=L.readFileSync(c,"utf-8").trim();if(!o)throw new b(`--file 指向的文件内容为空: ${c}`)}const i=e.images?String(e.images).split(",").map((c)=>c.trim()).filter(Boolean):[],a=pt(e),l=a.map((c)=>c.name),s=Boolean(e.draft),d=e["card-text"]?String(e["card-text"]):"",w=d?d.split(Y).map((c)=>c.trim()).filter(Boolean):[],v=e["card-style"]?String(e["card-style"]).trim():"",m=w.length>0;if(!r)throw new b("--title is required");if(r.length>X)throw new b(`Title is ${r.length} chars — must be ≤ ${X}`);if(!o)throw new b("缺少笔记正文:给位置参数 <content>(字面文本),或用 --file <本机文件路径>");vt(o,{fileFlag:"--file"});if(!m&&i.length===0)throw new b("Provide --card-text (text-image mode) or --images (upload mode); neither was given.");if(i.length>B)throw new b(`Too many images: ${i.length} (max ${B})`);if(m&&i.some((c)=>N.extname(c).toLowerCase()===".gif"))throw new b("文字配图模式追加的图片不支持 .gif(编辑器图片入口只接受 jpg/jpeg/png/webp)");const f=Nt(i);await t.goto($t);await t.wait({time:1});await t.evaluate("() => { try { window.onbeforeunload = null; } catch (e) {} location.reload(); }").catch(()=>{return});let x="";for(let c=0;c<30;c++){await t.wait({time:0.5});x=await t.evaluate("() => location.href");if(x.includes("creator.xiaohongshu.com"))break}if(!x.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_publish_redirect_debug.png"});throw Error(`Redirected away from creator center (landed on ${x}) — session may have expired. `+"Re-capture browser login via: ppcli xiaohongshu creator-profile. Debug screenshot: /tmp/xhs_publish_redirect_debug.png")}const S=await Rt(t);if((await zt(t,S?.ok?5000:2000)).state==="video_surface"){await t.screenshot({path:"/tmp/xhs_publish_tab_debug.png"});const c=S?.ok?`clicked "${S.text}"`:`visible candidates: ${(S?.visibleTexts||[]).join(" | ")||"none"}`;throw Error("Still on the video publish page after trying to select 图文. "+`Details: ${c}. Debug screenshot: /tmp/xhs_publish_tab_debug.png`)}const A=await Xt(t);let C=v;if(m)C=await Vt(t,w,v);else{const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片注入失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_upload_debug.png")}await t.wait({time:G/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN,`+"继续发布会丢图(通常只剩封面)。直接重新运行本 publish 命令即可(会自动重置发布页重传);"+"请勿手动修改当前页面。Debug: /tmp/xhs_publish_upload_debug.png")}await rt(t);if(A.length){await ct(t,A);await t.wait({time:0.5})}const M=await at(t);if(M&&typeof M.count==="number"&&M.count>f.length){await t.screenshot({path:"/tmp/xhs_publish_dup_debug.png"});throw new u(`清掉恢复态旧图后编辑器内仍有 ${M.count} 张图,超过本次注入的 ${f.length} 张。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。Debug: /tmp/xhs_publish_dup_debug.png")}}if(!await Ht(t)){await t.screenshot({path:"/tmp/xhs_publish_form_debug.png"});throw new u("Editing form did not appear after image acquisition. The page layout may have changed. Debug screenshot: /tmp/xhs_publish_form_debug.png")}if(m)await st(t,w.length,"文字配图 generated images");if(m&&f.length>0){const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await t.wait({time:G/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await rt(t);await st(t,w.length+f.length,"文字配图 appended images")}if(m&&A.length){await ct(t,A);await t.wait({time:0.5})}await ot(t,J,r,"title");await I(t,0.6);await ot(t,tt,o,"content");await I(t,0.6);let P=[];if(l.length)P=await bt(t,tt,a);await _t(t,e);await I(t,1,0.6);const R=await kt(t,["xhs-publish-btn"]);if(R){await Tt(t,R.x,R.y);await I(t,0.4)}const V=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
410
412
  (cfg => {
411
413
  const { isDraftMode, publishNames, draftNames, labels } = cfg;
412
414
  const isVisible = (el) => {
@@ -484,7 +486,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
484
486
  }
485
487
  return false;
486
488
  }
487
- `)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const l=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",x=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${V[0]}」按钮${l}${g}${x}。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_submit_debug.png")}await t.wait({time:4});const v=await t.evaluate("() => location.href"),ft=s?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],z=await t.evaluate(`
489
+ `)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const c=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",y=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${V[0]}」按钮${c}${g}${y}。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_submit_debug.png")}await t.wait({time:4});const T=await t.evaluate("() => location.href"),ft=s?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],z=await t.evaluate(`
488
490
  (markers => {
489
491
  for (const el of document.querySelectorAll('*')) {
490
492
  if (el.tagName === 'STYLE' || el.tagName === 'SCRIPT') continue;
@@ -494,4 +496,4 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
494
496
  }
495
497
  return '';
496
498
  })(${JSON.stringify(ft)})
497
- `),ht=!v.includes("/publish/publish");let D=z.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,O="";if(!s){const l=await Yt(t,r,D?2:4);p=l.note;O=l.reason;if(p)D=!0}if(!D){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(v?`当前 URL: ${v}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${O||"未回查到"})。`+(v?`当前 URL: ${v}。`:"")+"注意:发布按钮已被触发,笔记仍可能延迟入库。禁止立即重发——请等 1-2 分钟后用 `xiaohongshu creator-notes` 回查本篇标题是否已出现;确认不存在后才重新运行本 publish 命令,否则会重复发布。")}return[{status:`✅ ${q}`,detail:[`"${r}"`,w?`${m.length}张文字配图${f.length?` + ${f.length}张图片`:""}${C&&C!==S?` (${C})`:""}`:`${f.length}张图片`,P.length?`话题: ${P.join(" ")}`:"",p?.id?`笔记ID: ${p.id}`:"",z||(p?"已在创作者后台确认":"")||v||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${O||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
499
+ `),ht=!T.includes("/publish/publish");let D=z.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,O="";if(!s){const c=await Yt(t,r,D?2:4);p=c.note;O=c.reason;if(p)D=!0}if(!D){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(T?`当前 URL: ${T}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${O||"未回查到"})。`+(T?`当前 URL: ${T}。`:"")+"注意:发布按钮已被触发,笔记仍可能延迟入库。禁止立即重发——请等 1-2 分钟后用 `xiaohongshu creator-notes` 回查本篇标题是否已出现;确认不存在后才重新运行本 publish 命令,否则会重复发布。")}return[{status:`✅ ${q}`,detail:[`"${r}"`,m?`${w.length}张文字配图${f.length?` + ${f.length}张图片`:""}${C&&C!==k?` (${C})`:""}`:`${f.length}张图片`,P.length?`话题: ${P.join(" ")}`:"",p?.id?`笔记ID: ${p.id}`:"",z||(p?"已在创作者后台确认":"")||T||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${O||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
@@ -1,4 +1,4 @@
1
- import{CliError as m,CommandExecutionError as A}from"@jackwener/opencli/errors";import{cli as O,Strategy as j}from"@jackwener/opencli/registry";import{readFile as C,stat as L}from"node:fs/promises";import{publishArticle as D}from"../_shared/article/publish.js";export const xueqiuProfile={home:"https://mp.xueqiu.com/writeV2",outputFormat:"markdown",image:{spec:{url:"https://mp.xueqiu.com/xq/photo/upload.json",method:"POST",bodyType:"binary-multipart",fileField:"file",fileName:"image.jpg",responsePath:"url"},skip:["xueqiu.com","imedao.com"],uploadFn:async(o,i)=>{const e=await fetch(o,{credentials:"omit"});if(!e.ok)throw Error("图片下载失败: "+o);const l=await e.blob(),s=new FormData;s.append("file",l,"image.jpg");const a=await fetch("https://mp.xueqiu.com/xq/photo/upload.json",{method:"POST",credentials:"include",body:s}),t=await a.text();let n=null;try{n=JSON.parse(t)}catch(p){}if(!a.ok||!n||!n.url||!n.filename)throw Error("图片上传失败: "+t.slice(0,200));return{url:(n.url.startsWith("//")?"https:"+n.url:n.url)+"/"+n.filename}}},checkAuth:async(o)=>{try{const l=(await(await fetch("https://mp.xueqiu.com/writeV2",{method:"GET",credentials:"include"})).text()).match(/window\.UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(!l)return{isAuthenticated:!1};let s=null;try{s=JSON.parse(l[1])}catch(n){}const a=s&&s.currentUser;if(!a||!a.id)return{isAuthenticated:!1};const t=a.photo_domain&&a.profile_image_url?"https:"+a.photo_domain+(a.profile_image_url.split(",")[0]||""):"";return{isAuthenticated:!0,userId:String(a.id),username:a.screen_name||"",avatar:t}}catch(i){return{isAuthenticated:!1,error:String(i&&i.message||i)}}},publish:async(o,i)=>{const e=o.params||{};let l=o.content;const s=l.split(`
1
+ import{CliError as p,CommandExecutionError as A}from"@jackwener/opencli/errors";import{cli as O,Strategy as j}from"@jackwener/opencli/registry";import{readFile as C,stat as L}from"node:fs/promises";import{formatImageReport as F,publishArticle as D}from"../_shared/article/publish.js";import{rememberArticleFile as M}from"../_shared/article/images.js";export const xueqiuProfile={home:"https://mp.xueqiu.com/writeV2",outputFormat:"markdown",image:{spec:{url:"https://mp.xueqiu.com/xq/photo/upload.json",method:"POST",bodyType:"binary-multipart",fileField:"file",fileName:"image.jpg",responsePath:"url"},skip:["xueqiu.com","imedao.com"],uploadFn:async(o,i)=>{const e=await fetch(o,{credentials:"omit"});if(!e.ok)throw Error("图片下载失败: "+o);const l=await e.blob(),s=new FormData;s.append("file",l,"image.jpg");const a=await fetch("https://mp.xueqiu.com/xq/photo/upload.json",{method:"POST",credentials:"include",body:s}),t=await a.text();let n=null;try{n=JSON.parse(t)}catch(m){}if(!a.ok||!n||!n.url||!n.filename)throw Error("图片上传失败: "+t.slice(0,200));return{url:(n.url.startsWith("//")?"https:"+n.url:n.url)+"/"+n.filename}}},checkAuth:async(o)=>{try{const l=(await(await fetch("https://mp.xueqiu.com/writeV2",{method:"GET",credentials:"include"})).text()).match(/window\.UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(!l)return{isAuthenticated:!1};let s=null;try{s=JSON.parse(l[1])}catch(n){}const a=s&&s.currentUser;if(!a||!a.id)return{isAuthenticated:!1};const t=a.photo_domain&&a.profile_image_url?"https:"+a.photo_domain+(a.profile_image_url.split(",")[0]||""):"";return{isAuthenticated:!0,userId:String(a.id),username:a.screen_name||"",avatar:t}}catch(i){return{isAuthenticated:!1,error:String(i&&i.message||i)}}},publish:async(o,i)=>{const e=o.params||{};let l=o.content;const s=l.split(`
2
2
  `),a=[];let t=0;while(t<s.length){const r=s[t];if(r.startsWith("```")){let P="";t++;while(t<s.length&&!s[t].startsWith("```")){P+=(P?`
3
3
  `:"")+s[t];t++}a.push("<pre><code>"+P.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</code></pre>");t++;continue}const c=r.match(/^#{1,6}\s+(.*)/);if(c){a.push("<h4>"+c[1]+"</h4>");t++;continue}const d=r.match(/^!\[([^\]]*)\]\(([^)]+)\)/);if(d){a.push('<img src="'+d[2]+'" alt="'+d[1]+'" class="ke_img">');t++;continue}if(/^[-*_]{3,}\s*$/.test(r)){t++;continue}if(!r.trim()){a.push("");t++;continue}let k=r.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>").replace(/\*([^*]+)\*/g,"<i>$1</i>").replace(/`([^`]+)`/g,"<code>$1</code>");a.push("<p>"+k+"</p>");t++}l=a.filter((r,c,d)=>{return!(r===""&&c>0&&d[c-1]==="")}).join(`
4
- `).trim();const n=typeof e.coverPic==="string"?e.coverPic.trim():"";if(n&&!/(imedao\.com|xueqiu\.com)/.test(n))return{ok:!1,stage:"cover",message:"封面图必须是雪球图床地址(含 imedao.com / xueqiu.com);外链需先上传。当前:"+n.slice(0,120)};const f=new URLSearchParams({text:l,title:o.title,cover_pic:n,flags:"false",original_event:"",status_id:"",legal_user_visible:"false",is_private:"false"}),p=await fetch("https://mp.xueqiu.com/xq/statuses/draft/save.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f}),S=await p.text();let h=null;try{h=JSON.parse(S)}catch(r){}if(!p.ok||!h||!h.id)return{ok:!1,stage:"save",status:p.status,message:h&&h.error_description||S.slice(0,300)};const v=String(h.id);if(o.draftOnly)return{ok:!0,id:v,url:"https://mp.xueqiu.com/write/draft/"+v,draft:!0};let w=typeof e.originalEventId==="string"?e.originalEventId.trim():"",I="",_=!0;if(w)try{const c=await(await fetch("/xq/statuses/original/original_event.json?id="+encodeURIComponent(w),{credentials:"include"})).json(),d=c&&c.originalEvent;if(!d||d.id==null)return{ok:!1,stage:"original_event",message:"原创活动事件不存在:"+w+"(用 `xueqiu events` 列举热门事件)"};if(d.disabled)return{ok:!1,stage:"original_event",message:"原创活动事件已停用,不可参与:"+w};I=String(d.tag||"")}catch(r){return{ok:!1,stage:"original_event",message:"校验原创活动事件失败:"+String(r&&r.message||r)}}else _=!1;let y="";try{const c=await(await fetch("/xq/provider/session/token.json?api_path="+encodeURIComponent("/statuses/update.json"),{credentials:"include"})).json();y=c&&c.session_token?String(c.session_token):""}catch(r){return{ok:!1,stage:"csrf",message:"获取发布 CSRF token 失败:"+String(r&&r.message||r)}}if(!y)return{ok:!1,stage:"csrf",message:"未取得发布 CSRF token(session_token 为空)"};const q=e.showCoverPic===!1?"false":"true",N=e.original===!0?"true":"false",R=e.allowReward===!0?"true":"false",U=new URLSearchParams({title:o.title,status:l,draft_id:v,session_token:y,cover_pic:n,show_cover_pic:q,original:N,industry_category_name:"",original_event_id:_?w:"",original_event_tag:_?I:"",original_event_active:_?"true":"false",legal_user_visible:"false",is_private:"false",legal_user_state:"open",allow_reward:R}),x=await fetch("https://mp.xueqiu.com/xq/statuses/update.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:U}),T=await x.text();let u=null;try{u=JSON.parse(T)}catch(r){}if(!x.ok||!u||!u.id)return{ok:!1,stage:"publish",status:x.status,message:u&&(u.error_description||u.error_code)||T.slice(0,300)};const b=String(u.id);let g="";if(u.user_id!=null)g=String(u.user_id);else if(u.user&&u.user.id!=null)g=String(u.user.id);if(!g)try{const r=(document.documentElement.outerHTML||"").match(/UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(r){const c=JSON.parse(r[1]).currentUser;if(c&&c.id!=null)g=String(c.id)}}catch(r){}const E=g?"https://xueqiu.com/"+g+"/"+b:"https://xueqiu.com/"+b;return{ok:!0,id:b,url:E,draft:!1}}};function F(o){if(!o.execute)throw new m("INVALID_INPUT","此命令需要 --execute 参数才能实际写入,防止误操作。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function M(o){const i=typeof o.text==="string"?o.text:void 0,e=typeof o.file==="string"?o.file:void 0;if(i&&e)throw new m("INVALID_INPUT","不能同时使用 <text> 和 --file,请选一种");let l=i??"";if(e){let s;try{s=await L(e)}catch{throw new m("INVALID_INPUT","文件不存在: "+e)}if(!s.isFile())throw new m("INVALID_INPUT","路径必须是可读文本文件: "+e);let a;try{a=await C(e)}catch{throw new m("INVALID_INPUT","文件读取失败: "+e)}try{l=new TextDecoder("utf-8",{fatal:!0}).decode(a)}catch{throw new m("INVALID_INPUT","文件不是合法 UTF-8 文本: "+e)}}if(!l.trim())throw new m("INVALID_INPUT","正文不能为空");return l}function V(o,i,e,l,s={}){return[{status:"success",outcome:l,message:o,target_type:i,target:e,...s}]}O({site:"xueqiu",name:"article",access:"write",description:"发布雪球文章(长文)。默认正式发布,加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到雪球图床。",domain:"mp.xueqiu.com",strategy:j.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-image",help:"封面图地址(必须是雪球图床 imedao.com/xueqiu.com 的 url;外链请先上传)。可空=无封面"},{name:"no-cover",type:"boolean",help:"有封面图时不在文章头部展示封面(show_cover_pic=false)"},{name:"original",type:"boolean",help:"声明原创(需账号有原创权限,否则发布会被拒)。默认非原创"},{name:"original-event-id",help:"参与的原创活动/事件 id(精确校验,找不到/已停用报错);合法值用 `xueqiu events` 列举。可空=不参与"},{name:"allow-reward",type:"boolean",help:"允许打赏。默认不允许"},{name:"draft",type:"boolean",help:"仅保存为草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入;不加此参数命令拒绝写操作"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(o,i)=>{if(!o)throw new A("雪球文章发布需要浏览器会话(browser session)");F(i);const e=String(i.title??"").trim();if(!e)throw new m("INVALID_INPUT","文章标题不能为空");const l=await M(i),s=Boolean(i.draft),a={coverPic:typeof i["cover-image"]==="string"?i["cover-image"].trim():"",showCoverPic:!i["no-cover"],original:Boolean(i.original),originalEventId:typeof i["original-event-id"]==="string"?i["original-event-id"].trim():"",allowReward:Boolean(i["allow-reward"])},t=await D(o,{title:e,body:l,format:i.html?"html":"markdown",draftOnly:s,profile:xueqiuProfile,publishParams:a}),n=t.images.uploaded.length|0,f=t.images.failed.length|0;let p=t.draft?"已保存雪球文章草稿(需在写作页手动发布)":"已正式发布雪球文章";if(n||f)p+=`;图片: ${n} 张已转存${f?`,${f} 张失败`:""}`;return V(p,"article","",t.draft?"draft":"created",{created_target:"article:"+t.id,created_url:t.url})}});
4
+ `).trim();const n=typeof e.coverPic==="string"?e.coverPic.trim():"";if(n&&!/(imedao\.com|xueqiu\.com)/.test(n))return{ok:!1,stage:"cover",message:"封面图必须是雪球图床地址(含 imedao.com / xueqiu.com);外链需先上传。当前:"+n.slice(0,120)};const f=new URLSearchParams({text:l,title:o.title,cover_pic:n,flags:"false",original_event:"",status_id:"",legal_user_visible:"false",is_private:"false"}),m=await fetch("https://mp.xueqiu.com/xq/statuses/draft/save.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f}),I=await m.text();let h=null;try{h=JSON.parse(I)}catch(r){}if(!m.ok||!h||!h.id)return{ok:!1,stage:"save",status:m.status,message:h&&h.error_description||I.slice(0,300)};const v=String(h.id);if(o.draftOnly)return{ok:!0,id:v,url:"https://mp.xueqiu.com/write/draft/"+v,draft:!0};let w=typeof e.originalEventId==="string"?e.originalEventId.trim():"",S="",_=!0;if(w)try{const c=await(await fetch("/xq/statuses/original/original_event.json?id="+encodeURIComponent(w),{credentials:"include"})).json(),d=c&&c.originalEvent;if(!d||d.id==null)return{ok:!1,stage:"original_event",message:"原创活动事件不存在:"+w+"(用 `xueqiu events` 列举热门事件)"};if(d.disabled)return{ok:!1,stage:"original_event",message:"原创活动事件已停用,不可参与:"+w};S=String(d.tag||"")}catch(r){return{ok:!1,stage:"original_event",message:"校验原创活动事件失败:"+String(r&&r.message||r)}}else _=!1;let y="";try{const c=await(await fetch("/xq/provider/session/token.json?api_path="+encodeURIComponent("/statuses/update.json"),{credentials:"include"})).json();y=c&&c.session_token?String(c.session_token):""}catch(r){return{ok:!1,stage:"csrf",message:"获取发布 CSRF token 失败:"+String(r&&r.message||r)}}if(!y)return{ok:!1,stage:"csrf",message:"未取得发布 CSRF token(session_token 为空)"};const q=e.showCoverPic===!1?"false":"true",N=e.original===!0?"true":"false",R=e.allowReward===!0?"true":"false",U=new URLSearchParams({title:o.title,status:l,draft_id:v,session_token:y,cover_pic:n,show_cover_pic:q,original:N,industry_category_name:"",original_event_id:_?w:"",original_event_tag:_?S:"",original_event_active:_?"true":"false",legal_user_visible:"false",is_private:"false",legal_user_state:"open",allow_reward:R}),x=await fetch("https://mp.xueqiu.com/xq/statuses/update.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:U}),T=await x.text();let u=null;try{u=JSON.parse(T)}catch(r){}if(!x.ok||!u||!u.id)return{ok:!1,stage:"publish",status:x.status,message:u&&(u.error_description||u.error_code)||T.slice(0,300)};const b=String(u.id);let g="";if(u.user_id!=null)g=String(u.user_id);else if(u.user&&u.user.id!=null)g=String(u.user.id);if(!g)try{const r=(document.documentElement.outerHTML||"").match(/UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(r){const c=JSON.parse(r[1]).currentUser;if(c&&c.id!=null)g=String(c.id)}}catch(r){}const E=g?"https://xueqiu.com/"+g+"/"+b:"https://xueqiu.com/"+b;return{ok:!0,id:b,url:E,draft:!1}}};function V(o){if(!o.execute)throw new p("INVALID_INPUT","此命令需要 --execute 参数才能实际写入,防止误操作。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function J(o){const i=typeof o.text==="string"?o.text:void 0,e=typeof o.file==="string"?o.file:void 0;if(i&&e)throw new p("INVALID_INPUT","不能同时使用 <text> 和 --file,请选一种");let l=i??"";if(e){M(e);let s;try{s=await L(e)}catch{throw new p("INVALID_INPUT","文件不存在: "+e)}if(!s.isFile())throw new p("INVALID_INPUT","路径必须是可读文本文件: "+e);let a;try{a=await C(e)}catch{throw new p("INVALID_INPUT","文件读取失败: "+e)}try{l=new TextDecoder("utf-8",{fatal:!0}).decode(a)}catch{throw new p("INVALID_INPUT","文件不是合法 UTF-8 文本: "+e)}}if(!l.trim())throw new p("INVALID_INPUT","正文不能为空");return l}function B(o,i,e,l,s={}){return[{status:"success",outcome:l,message:o,target_type:i,target:e,...s}]}O({site:"xueqiu",name:"article",access:"write",description:"发布雪球文章(长文)。默认正式发布,加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到雪球图床。",domain:"mp.xueqiu.com",strategy:j.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-image",help:"封面图地址(必须是雪球图床 imedao.com/xueqiu.com 的 url;外链请先上传)。可空=无封面"},{name:"no-cover",type:"boolean",help:"有封面图时不在文章头部展示封面(show_cover_pic=false)"},{name:"original",type:"boolean",help:"声明原创(需账号有原创权限,否则发布会被拒)。默认非原创"},{name:"original-event-id",help:"参与的原创活动/事件 id(精确校验,找不到/已停用报错);合法值用 `xueqiu events` 列举。可空=不参与"},{name:"allow-reward",type:"boolean",help:"允许打赏。默认不允许"},{name:"draft",type:"boolean",help:"仅保存为草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入;不加此参数命令拒绝写操作"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(o,i)=>{if(!o)throw new A("雪球文章发布需要浏览器会话(browser session)");V(i);const e=String(i.title??"").trim();if(!e)throw new p("INVALID_INPUT","文章标题不能为空");const l=await J(i),s=Boolean(i.draft),a={coverPic:typeof i["cover-image"]==="string"?i["cover-image"].trim():"",showCoverPic:!i["no-cover"],original:Boolean(i.original),originalEventId:typeof i["original-event-id"]==="string"?i["original-event-id"].trim():"",allowReward:Boolean(i["allow-reward"])},t=await D(o,{title:e,body:l,format:i.html?"html":"markdown",draftOnly:s,profile:xueqiuProfile,publishParams:a}),n=t.images.uploaded.length|0,f=t.images.failed.length|0;let m=t.draft?"已保存雪球文章草稿(需在写作页手动发布)":"已正式发布雪球文章";if(n||f)m+=`;图片: ${n} 张已转存${f?`,${f} 张失败`:""}`;m+=F(t.images);return B(m,"article","",t.draft?"draft":"created",{created_target:"article:"+t.id,created_url:t.url})}});
@@ -1 +1 @@
1
- import{CliError as c,CommandExecutionError as R}from"@jackwener/opencli/errors";import{cli as V,Strategy as j}from"@jackwener/opencli/registry";import{publishArticle as C}from"../_shared/article/publish.js";export const yuqueProfile={home:"https://www.yuque.com/dashboard",outputFormat:"markdown",preprocessConfig:null,image:null,publish:async(l,o)=>{const f=o.cookie("yuque_ctoken");if(!f)return{ok:!1,stage:"auth",message:"未检测到语雀登录态,请先在 Chrome 中登录语雀(缺少 yuque_ctoken cookie)"};const s={"Content-Type":"application/json","x-csrf-token":f},m=await fetch("https://www.yuque.com/api/mine/common_used",{method:"GET",credentials:"include",headers:s});let e=null;try{e=await m.json()}catch(t){}if(!m.ok||!e?.data?.books?.length)return{ok:!1,stage:"auth",status:m.status,message:"无法获取语雀知识库列表,请确认已登录语雀"};const r=e.data.books[0].target_id,p=await fetch("https://www.yuque.com/api/docs",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({title:l.title,type:"Doc",format:"lake",book_id:r,status:0})});let i=null;try{i=await p.json()}catch(t){}if(!p.ok||!i?.data?.id)return{ok:!1,stage:"create",status:p.status,message:i?.message||"创建语雀草稿文档失败"};const a=i.data.id,T="https://www.yuque.com/go/doc/"+a+"/edit";let h=l.content;const I=["yuque.com","cdn.nlark.com"],b=/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?\s*\)/g,w=[];let _;while((_=b.exec(h))!==null)w.push({full:_[0],alt:_[1],src:_[2]});const y=[],g=[],L="https://www.yuque.com/api/upload/attach?attachable_type=Doc&attachable_id="+a+"&type=image";for(let t=0;t<w.length;t++){const d=w[t],u=d.src;if(!u)continue;if(u.indexOf("data:")===0)continue;if(I.some(function(n){return u.indexOf(n)!==-1}))continue;try{const n=await fetch(u,{credentials:"omit"});if(!n.ok)throw Error("图片下载失败 HTTP "+n.status);const A=await n.blob(),O=new FormData;O.append("file",A,"image.jpg");const P=await fetch(L,{method:"POST",credentials:"include",headers:{"x-csrf-token":f},body:O});let k=null;try{k=await P.json()}catch(E){}if(!P.ok||!k?.data?.url)throw Error(k&&k.message||"图片上传失败 HTTP "+P.status);const v=k.data.url;h=h.split(d.full).join("!["+d.alt+"]("+v+")");y.push({src:u.slice(0,120),url:v})}catch(n){g.push({src:u.slice(0,120),error:String(n&&n.message||n)})}}const N=await fetch("https://www.yuque.com/api/docs/convert",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({from:"markdown",to:"lake",content:h})});let x=null;try{x=await N.json()}catch(t){}if(!N.ok||!x?.data?.content)return{ok:!1,stage:"convert",status:N.status,message:"内容格式转换失败(markdown→lake)",id:String(a),uploaded:y,failed:g};const S=x.data.content,U='<div class="lake-content" typography="traditional">'+S+"</div>",D=await fetch("https://www.yuque.com/api/docs/"+a+"/content",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({format:"lake",body_asl:S,body:U,body_html:U,draft_version:0,sync_dynamic_data:!1,save_type:"auto",edit_type:"Lake"})});if(!D.ok){let t="";try{t=await D.text()}catch(d){}return{ok:!1,stage:"save",status:D.status,message:"保存正文失败:"+t.slice(0,300),id:String(a),uploaded:y,failed:g}}if(!l.draftOnly){const t=await fetch("https://www.yuque.com/api/docs/"+a+"/publish",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({status:1})});if(!t.ok){let d="";try{d=await t.text()}catch(u){}return{ok:!1,stage:"publish",status:t.status,message:"发布失败:"+d.slice(0,300),id:String(a),url:T,uploaded:y,failed:g}}}return{ok:!0,id:String(a),url:T,draft:Boolean(l.draftOnly),uploaded:y,failed:g}}};V({site:"yuque",name:"article",access:"write",description:"发布语雀文章(知识库文档)。正文默认为 Markdown,外链图片自动转存到语雀图床。",domain:"www.yuque.com",strategy:j.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(Markdown 格式;或用 --file 读文件)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 格式)"},{name:"html",type:"boolean",help:"把正文当 HTML 输入(语雀仍转 lake 发布)"},{name:"draft",type:"boolean",help:"仅保存草稿,不发布"},{name:"execute",type:"boolean",help:"实际执行写操作。不加此参数命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(l,o)=>{if(!l)throw new R("语雀文章发布需要浏览器会话");if(!o.execute)throw new c("INVALID_INPUT","此命令需要加 --execute 才会实际写入(防误操作)");const f=String(o.title??"").trim();if(!f)throw new c("INVALID_INPUT","文章标题不能为空");let s="";const m=typeof o.text==="string"?o.text:void 0,e=typeof o.file==="string"?o.file:void 0;if(m&&e)throw new c("INVALID_INPUT","正文和 --file 不能同时使用");if(e){const{readFile:h,stat:I}=await import("node:fs/promises");let b;try{b=await I(e)}catch{throw new c("INVALID_INPUT",`文件不存在:${e}`)}if(!b.isFile())throw new c("INVALID_INPUT",`路径不是文件:${e}`);let w;try{w=await h(e)}catch{throw new c("INVALID_INPUT",`文件无法读取:${e}`)}try{s=new TextDecoder("utf-8",{fatal:!0}).decode(w)}catch{throw new c("INVALID_INPUT",`文件无法以 UTF-8 解码:${e}`)}}else s=m??"";if(!s.trim())throw new c("INVALID_INPUT","正文不能为空");const q=Boolean(o.draft),r=await C(l,{title:f,body:s,format:o.html?"html":"markdown",draftOnly:q,profile:yuqueProfile}),p=r.images.uploaded.length|0,i=r.images.failed.length|0;let a=r.draft?"已保存语雀草稿":"语雀文章发布成功";if(p||i)a+=`(图片:${p} 张已转存${i?`,${i} 张失败`:""})`;return[{status:"success",outcome:r.draft?"draft":"created",message:a,target_type:"article",target:"",created_target:"article:"+r.id,created_url:r.url}]}});
1
+ import{CliError as c,CommandExecutionError as R}from"@jackwener/opencli/errors";import{cli as V,Strategy as j}from"@jackwener/opencli/registry";import{formatImageReport as C,publishArticle as E}from"../_shared/article/publish.js";import{rememberArticleFile as F}from"../_shared/article/images.js";export const yuqueProfile={home:"https://www.yuque.com/dashboard",outputFormat:"markdown",preprocessConfig:null,image:null,publish:async(l,o)=>{const f=o.cookie("yuque_ctoken");if(!f)return{ok:!1,stage:"auth",message:"未检测到语雀登录态,请先在 Chrome 中登录语雀(缺少 yuque_ctoken cookie)"};const s={"Content-Type":"application/json","x-csrf-token":f},m=await fetch("https://www.yuque.com/api/mine/common_used",{method:"GET",credentials:"include",headers:s});let t=null;try{t=await m.json()}catch(e){}if(!m.ok||!t?.data?.books?.length)return{ok:!1,stage:"auth",status:m.status,message:"无法获取语雀知识库列表,请确认已登录语雀"};const r=t.data.books[0].target_id,p=await fetch("https://www.yuque.com/api/docs",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({title:l.title,type:"Doc",format:"lake",book_id:r,status:0})});let i=null;try{i=await p.json()}catch(e){}if(!p.ok||!i?.data?.id)return{ok:!1,stage:"create",status:p.status,message:i?.message||"创建语雀草稿文档失败"};const a=i.data.id,T="https://www.yuque.com/go/doc/"+a+"/edit";let h=l.content;const I=["yuque.com","cdn.nlark.com"],b=/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?\s*\)/g,w=[];let _;while((_=b.exec(h))!==null)w.push({full:_[0],alt:_[1],src:_[2]});const y=[],g=[],A="https://www.yuque.com/api/upload/attach?attachable_type=Doc&attachable_id="+a+"&type=image";for(let e=0;e<w.length;e++){const d=w[e],u=d.src;if(!u)continue;if(u.indexOf("data:")===0)continue;if(I.some(function(n){return u.indexOf(n)!==-1}))continue;try{const n=await fetch(u,{credentials:"omit"});if(!n.ok)throw Error("图片下载失败 HTTP "+n.status);const L=await n.blob(),O=new FormData;O.append("file",L,"image.jpg");const P=await fetch(A,{method:"POST",credentials:"include",headers:{"x-csrf-token":f},body:O});let k=null;try{k=await P.json()}catch(B){}if(!P.ok||!k?.data?.url)throw Error(k&&k.message||"图片上传失败 HTTP "+P.status);const v=k.data.url;h=h.split(d.full).join("!["+d.alt+"]("+v+")");y.push({src:u.slice(0,120),url:v})}catch(n){g.push({src:u.slice(0,120),error:String(n&&n.message||n)})}}const N=await fetch("https://www.yuque.com/api/docs/convert",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({from:"markdown",to:"lake",content:h})});let x=null;try{x=await N.json()}catch(e){}if(!N.ok||!x?.data?.content)return{ok:!1,stage:"convert",status:N.status,message:"内容格式转换失败(markdown→lake)",id:String(a),uploaded:y,failed:g};const S=x.data.content,U='<div class="lake-content" typography="traditional">'+S+"</div>",D=await fetch("https://www.yuque.com/api/docs/"+a+"/content",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({format:"lake",body_asl:S,body:U,body_html:U,draft_version:0,sync_dynamic_data:!1,save_type:"auto",edit_type:"Lake"})});if(!D.ok){let e="";try{e=await D.text()}catch(d){}return{ok:!1,stage:"save",status:D.status,message:"保存正文失败:"+e.slice(0,300),id:String(a),uploaded:y,failed:g}}if(!l.draftOnly){const e=await fetch("https://www.yuque.com/api/docs/"+a+"/publish",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({status:1})});if(!e.ok){let d="";try{d=await e.text()}catch(u){}return{ok:!1,stage:"publish",status:e.status,message:"发布失败:"+d.slice(0,300),id:String(a),url:T,uploaded:y,failed:g}}}return{ok:!0,id:String(a),url:T,draft:Boolean(l.draftOnly),uploaded:y,failed:g}}};V({site:"yuque",name:"article",access:"write",description:"发布语雀文章(知识库文档)。正文默认为 Markdown,外链图片自动转存到语雀图床。",domain:"www.yuque.com",strategy:j.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(Markdown 格式;或用 --file 读文件)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 格式)"},{name:"html",type:"boolean",help:"把正文当 HTML 输入(语雀仍转 lake 发布)"},{name:"draft",type:"boolean",help:"仅保存草稿,不发布"},{name:"execute",type:"boolean",help:"实际执行写操作。不加此参数命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(l,o)=>{if(!l)throw new R("语雀文章发布需要浏览器会话");if(!o.execute)throw new c("INVALID_INPUT","此命令需要加 --execute 才会实际写入(防误操作)");const f=String(o.title??"").trim();if(!f)throw new c("INVALID_INPUT","文章标题不能为空");let s="";const m=typeof o.text==="string"?o.text:void 0,t=typeof o.file==="string"?o.file:void 0;if(m&&t)throw new c("INVALID_INPUT","正文和 --file 不能同时使用");if(t){F(t);const{readFile:h,stat:I}=await import("node:fs/promises");let b;try{b=await I(t)}catch{throw new c("INVALID_INPUT",`文件不存在:${t}`)}if(!b.isFile())throw new c("INVALID_INPUT",`路径不是文件:${t}`);let w;try{w=await h(t)}catch{throw new c("INVALID_INPUT",`文件无法读取:${t}`)}try{s=new TextDecoder("utf-8",{fatal:!0}).decode(w)}catch{throw new c("INVALID_INPUT",`文件无法以 UTF-8 解码:${t}`)}}else s=m??"";if(!s.trim())throw new c("INVALID_INPUT","正文不能为空");const q=Boolean(o.draft),r=await E(l,{title:f,body:s,format:o.html?"html":"markdown",draftOnly:q,profile:yuqueProfile}),p=r.images.uploaded.length|0,i=r.images.failed.length|0;let a=r.draft?"已保存语雀草稿":"语雀文章发布成功";if(p||i)a+=`(图片:${p} 张已转存${i?`,${i} 张失败`:""})`;a+=C(r.images);return[{status:"success",outcome:r.draft?"draft":"created",message:a,target_type:"article",target:"",created_target:"article:"+r.id,created_url:r.url}]}});
@@ -1 +1 @@
1
- import{CommandExecutionError as m}from"@jackwener/opencli/errors";import{cli as d,Strategy as h}from"@jackwener/opencli/registry";import{publishArticle as c}from"../_shared/article/publish.js";import{zhihuImageProfile as p}from"./image-profile.js";import{assertAllowedKinds as w,parseTarget as g}from"./target.js";import{buildResultRow as f,requireExecute as y,resolveCurrentUserIdentity as b,resolvePayload as q}from"./write-shared.js";function T(i){return{home:i,originRe:"https?://(www\\.)?zhihu\\.com",outputFormat:"html",preprocessConfig:{removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0},image:p,publish:async(r,u)=>{const s=r.content.replace(/<img([^>]+?)\/?>/gi,"<figure><img$1></figure>"),o=r.params&&r.params.questionId;if(!o)return{ok:!1,stage:"publish",message:"缺少 questionId"};const t=await fetch("https://www.zhihu.com/api/v4/questions/"+o+"/answers",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,reshipment_settings:"disallowed"})}),n=await t.text();let e=null;try{e=JSON.parse(n)}catch(l){}if(!t.ok)return{ok:!1,stage:"publish",status:t.status,message:e&&e.error&&e.error.message||n.slice(0,300),detail:e};if(!e||!e.id)return{ok:!1,stage:"publish",status:t.status,message:"回答接口没有返回回答 id:"+n.slice(0,300)};const a=String(e.id);return{ok:!0,draft:!1,id:a,url:e.url||"https://www.zhihu.com/question/"+o+"/answer/"+a}}}}d({site:"zhihu",name:"answer",access:"write",description:"Answer a Zhihu question. Body is Markdown by default (paragraphs become <p>); pass --html for raw HTML. Images (including local file paths) are auto-rehosted to Zhihu.",domain:"www.zhihu.com",strategy:h.COOKIE,browser:!0,args:[{name:"target",positional:!0,required:!0,help:"Zhihu question URL (e.g. https://www.zhihu.com/question/461491497) or typed target question:461491497; bare numeric id is rejected"},{name:"text",positional:!0,help:"Answer body (Markdown by default; pass --html for raw HTML)"},{name:"file",help:"Answer body file path (UTF-8, Markdown by default)"},{name:"html",type:"boolean",help:"Treat body as raw HTML instead of Markdown"},{name:"execute",type:"boolean",help:"Actually perform the write action"}],columns:["status","outcome","message","target_type","target","created_target","created_url","author_identity"],func:async(i,r)=>{if(!i)throw new m("Browser session required for zhihu answer");y(r);const u=String(r.target),s=w("answer",g(u)),o=await q(r),t=await c(i,{title:"",body:o,format:r.html?"html":"markdown",profile:T(s.url),publishParams:{questionId:s.id}}),n=await b(i),e=t.images.uploaded.length|0,a=t.images.failed.length|0;let l=`Answered question ${s.id}`;if(e||a)l+=` · images: ${e} rehosted${a?`, ${a} failed`:""}`;return f(l,s.kind,u,"created",{created_target:"answer:"+s.id+":"+t.id,created_url:t.url,author_identity:n})}});
1
+ import{CommandExecutionError as m}from"@jackwener/opencli/errors";import{cli as d,Strategy as h}from"@jackwener/opencli/registry";import{formatImageReport as c,publishArticle as p}from"../_shared/article/publish.js";import{zhihuImageProfile as w}from"./image-profile.js";import{assertAllowedKinds as g,parseTarget as f}from"./target.js";import{buildResultRow as y,requireExecute as b,resolveCurrentUserIdentity as q,resolvePayload as T}from"./write-shared.js";function v(i){return{home:i,originRe:"https?://(www\\.)?zhihu\\.com",outputFormat:"html",preprocessConfig:{removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0},image:w,publish:async(r,l)=>{const a=r.content.replace(/<img([^>]+?)\/?>/gi,"<figure><img$1></figure>"),o=r.params&&r.params.questionId;if(!o)return{ok:!1,stage:"publish",message:"缺少 questionId"};const t=await fetch("https://www.zhihu.com/api/v4/questions/"+o+"/answers",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:a,reshipment_settings:"disallowed"})}),n=await t.text();let e=null;try{e=JSON.parse(n)}catch(u){}if(!t.ok)return{ok:!1,stage:"publish",status:t.status,message:e&&e.error&&e.error.message||n.slice(0,300),detail:e};if(!e||!e.id)return{ok:!1,stage:"publish",status:t.status,message:"回答接口没有返回回答 id:"+n.slice(0,300)};const s=String(e.id);return{ok:!0,draft:!1,id:s,url:e.url||"https://www.zhihu.com/question/"+o+"/answer/"+s}}}}d({site:"zhihu",name:"answer",access:"write",description:"Answer a Zhihu question. Body is Markdown by default (paragraphs become <p>); pass --html for raw HTML. Images (including local file paths) are auto-rehosted to Zhihu.",domain:"www.zhihu.com",strategy:h.COOKIE,browser:!0,args:[{name:"target",positional:!0,required:!0,help:"Zhihu question URL (e.g. https://www.zhihu.com/question/461491497) or typed target question:461491497; bare numeric id is rejected"},{name:"text",positional:!0,help:"Answer body (Markdown by default; pass --html for raw HTML)"},{name:"file",help:"Answer body file path (UTF-8, Markdown by default)"},{name:"html",type:"boolean",help:"Treat body as raw HTML instead of Markdown"},{name:"execute",type:"boolean",help:"Actually perform the write action"}],columns:["status","outcome","message","target_type","target","created_target","created_url","author_identity"],func:async(i,r)=>{if(!i)throw new m("Browser session required for zhihu answer");b(r);const l=String(r.target),a=g("answer",f(l)),o=await T(r),t=await p(i,{title:"",body:o,format:r.html?"html":"markdown",profile:v(a.url),publishParams:{questionId:a.id}}),n=await q(i),e=t.images.uploaded.length|0,s=t.images.failed.length|0;let u=`Answered question ${a.id}`;if(e||s)u+=` · images: ${e} rehosted${s?`, ${s} failed`:""}`;u+=c(t.images);return y(u,a.kind,l,"created",{created_target:"answer:"+a.id+":"+t.id,created_url:t.url,author_identity:n})}});
@@ -1 +1 @@
1
- import{CliError as y,CommandExecutionError as b}from"@jackwener/opencli/errors";import{cli as v,Strategy as w}from"@jackwener/opencli/registry";import{buildResultRow as x,requireExecute as z,resolvePayload as T}from"./write-shared.js";import{publishArticle as S}from"../_shared/article/publish.js";import{zhihuImageProfile as C}from"./image-profile.js";export const zhihuProfile={home:"https://zhuanlan.zhihu.com",outputFormat:"html",preprocessConfig:{removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0},image:C,publish:async(e,r)=>{let s=e.content;s=s.replace(/<img([^>]+?)\/?>/gi,"<figure><img$1></figure>");const i=e.params&&typeof e.params.cover==="string"?e.params.cover.trim():"";if(i&&i.indexOf("zhimg.com")===-1)return{ok:!1,stage:"cover",message:"题图必须是知乎图床(zhimg.com)地址,转存未生效:"+i.slice(0,120)};const l={"Content-Type":"application/json","x-requested-with":"fetch","x-xsrftoken":r.xsrf()},t="https://zhuanlan.zhihu.com/api/articles",n=await fetch(t+"/drafts",{method:"POST",credentials:"include",headers:l,body:JSON.stringify({title:e.title})}),c=await n.text();let o=null;try{o=JSON.parse(c)}catch(f){}if(!n.ok||!o||!o.id)return{ok:!1,stage:"create",status:n.status,message:c.slice(0,300)};const a=String(o.id),u={title:e.title,content:s,table_of_contents:!1,delta_time:30};if(i){u.titleImage=i;u.isTitleImageFullScreen=!1}const m=await fetch(t+"/"+a+"/draft",{method:"PATCH",credentials:"include",headers:l,body:JSON.stringify(u)});if(!m.ok){const f=await m.text();return{ok:!1,stage:"update",status:m.status,message:f.slice(0,300),id:a}}if(e.draftOnly)return{ok:!0,draft:!0,id:a,url:"https://zhuanlan.zhihu.com/p/"+a+"/edit"};const h=await fetch(t+"/"+a+"/publish",{method:"PUT",credentials:"include",headers:l,body:JSON.stringify({})}),g=await h.text();let d=null;try{d=JSON.parse(g)}catch(f){}if(!h.ok)return{ok:!1,stage:"publish",status:h.status,message:g.slice(0,300),id:a};return{ok:!0,draft:!1,id:a,url:d&&d.url||"https://zhuanlan.zhihu.com/p/"+a}}};v({site:"zhihu",name:"article",access:"write",description:"Publish a Zhihu article (文章/专栏). Body is Markdown by default; images (incl. local paths) and --cover are auto-rehosted to Zhihu.",domain:"zhuanlan.zhihu.com",strategy:w.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"Article title"},{name:"text",positional:!0,help:"Article body (Markdown by default; pass --html for raw HTML)"},{name:"file",help:"Article body file path (UTF-8, Markdown by default)"},{name:"html",type:"boolean",help:"Treat body as raw HTML instead of Markdown"},{name:"cover",help:"Cover image (题图): local file path or image URL; auto-rehosted to Zhihu (zhimg.com)"},{name:"draft",type:"boolean",help:"Save as draft only; do not publish"},{name:"execute",type:"boolean",help:"Actually create/publish. Without it the command refuses to write."}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(e,r)=>{if(!e)throw new b("Browser session required for zhihu article");z(r);const s=String(r.title??"").trim();if(!s)throw new y("INVALID_INPUT","Article title cannot be empty");const i=await T(r),p=Boolean(r.draft),l=typeof r.cover==="string"?r.cover.trim():"",t=await S(e,{title:s,body:i,format:r.html?"html":"markdown",draftOnly:p,profile:zhihuProfile,publishParams:l?{cover:l}:null}),n=t.images.uploaded.length|0,c=t.images.failed.length|0;let o=t.draft?"Saved article draft":"Published article";if(n||c)o+=` · images: ${n} rehosted${c?`, ${c} failed`:""}`;return x(o,"article","",t.draft?"draft":"created",{created_target:"article:"+t.id,created_url:t.url})}});
1
+ import{CliError as y,CommandExecutionError as b}from"@jackwener/opencli/errors";import{cli as v,Strategy as w}from"@jackwener/opencli/registry";import{buildResultRow as x,requireExecute as z,resolvePayload as T}from"./write-shared.js";import{formatImageReport as S,publishArticle as C}from"../_shared/article/publish.js";import{zhihuImageProfile as N}from"./image-profile.js";export const zhihuProfile={home:"https://zhuanlan.zhihu.com",outputFormat:"html",preprocessConfig:{removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0},image:N,publish:async(t,r)=>{let s=t.content;s=s.replace(/<img([^>]+?)\/?>/gi,"<figure><img$1></figure>");const o=t.params&&typeof t.params.cover==="string"?t.params.cover.trim():"";if(o&&o.indexOf("zhimg.com")===-1)return{ok:!1,stage:"cover",message:"题图必须是知乎图床(zhimg.com)地址,转存未生效:"+o.slice(0,120)};const l={"Content-Type":"application/json","x-requested-with":"fetch","x-xsrftoken":r.xsrf()},e="https://zhuanlan.zhihu.com/api/articles",n=await fetch(e+"/drafts",{method:"POST",credentials:"include",headers:l,body:JSON.stringify({title:t.title})}),c=await n.text();let a=null;try{a=JSON.parse(c)}catch(f){}if(!n.ok||!a||!a.id)return{ok:!1,stage:"create",status:n.status,message:c.slice(0,300)};const i=String(a.id),u={title:t.title,content:s,table_of_contents:!1,delta_time:30};if(o){u.titleImage=o;u.isTitleImageFullScreen=!1}const m=await fetch(e+"/"+i+"/draft",{method:"PATCH",credentials:"include",headers:l,body:JSON.stringify(u)});if(!m.ok){const f=await m.text();return{ok:!1,stage:"update",status:m.status,message:f.slice(0,300),id:i}}if(t.draftOnly)return{ok:!0,draft:!0,id:i,url:"https://zhuanlan.zhihu.com/p/"+i+"/edit"};const h=await fetch(e+"/"+i+"/publish",{method:"PUT",credentials:"include",headers:l,body:JSON.stringify({})}),g=await h.text();let d=null;try{d=JSON.parse(g)}catch(f){}if(!h.ok)return{ok:!1,stage:"publish",status:h.status,message:g.slice(0,300),id:i};return{ok:!0,draft:!1,id:i,url:d&&d.url||"https://zhuanlan.zhihu.com/p/"+i}}};v({site:"zhihu",name:"article",access:"write",description:"Publish a Zhihu article (文章/专栏). Body is Markdown by default; images (incl. local paths) and --cover are auto-rehosted to Zhihu.",domain:"zhuanlan.zhihu.com",strategy:w.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"Article title"},{name:"text",positional:!0,help:"Article body (Markdown by default; pass --html for raw HTML)"},{name:"file",help:"Article body file path (UTF-8, Markdown by default)"},{name:"html",type:"boolean",help:"Treat body as raw HTML instead of Markdown"},{name:"cover",help:"Cover image (题图): local file path or image URL; auto-rehosted to Zhihu (zhimg.com)"},{name:"draft",type:"boolean",help:"Save as draft only; do not publish"},{name:"execute",type:"boolean",help:"Actually create/publish. Without it the command refuses to write."}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,r)=>{if(!t)throw new b("Browser session required for zhihu article");z(r);const s=String(r.title??"").trim();if(!s)throw new y("INVALID_INPUT","Article title cannot be empty");const o=await T(r),p=Boolean(r.draft),l=typeof r.cover==="string"?r.cover.trim():"",e=await C(t,{title:s,body:o,format:r.html?"html":"markdown",draftOnly:p,profile:zhihuProfile,publishParams:l?{cover:l}:null}),n=e.images.uploaded.length|0,c=e.images.failed.length|0;let a=e.draft?"Saved article draft":"Published article";if(n||c)a+=` · images: ${n} rehosted${c?`, ${c} failed`:""}`;a+=S(e.images);return x(a,"article","",e.draft?"draft":"created",{created_target:"article:"+e.id,created_url:e.url})}});
@@ -1,6 +1,6 @@
1
- import{readFile as b,stat as _}from"node:fs/promises";import{CliError as i}from"@jackwener/opencli/errors";const L=new Set(["status","outcome","message","target_type","target"]),s='header, nav, [role="banner"], [role="navigation"]',c='a[href^="/people/"]',u='img, [class*="Avatar"], [data-testid*="avatar" i], [aria-label*="头像"]',f=["我","我的","个人主页"],d=[["self"],["current","user"],["account","profile"],["my","profile"],["my","account"]],w=JSON.stringify(d);function T(){return{readFile:b,stat:(t)=>_(t),decodeUtf8:(t)=>new TextDecoder("utf-8",{fatal:!0}).decode(t)}}function E(t){const e=t.toLowerCase();return f.some((r)=>t.includes(r))||e.includes("my profile")||e.includes("my account")}function N(t){return t.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function x(t){const e=new Set(N(t));return d.some((r)=>r.every((o)=>e.has(o)))}function v(t){return typeof t==="object"&&t!==null&&"querySelectorAll"in t&&typeof t.querySelectorAll==="function"}function F(t){return typeof t==="object"&&t!==null&&"getAttribute"in t&&"querySelector"in t&&typeof t.getAttribute==="function"&&typeof t.querySelector==="function"}function O(t){const e=t?.topstory?.me?.slug||t?.me?.slug||t?.initialState?.me?.slug;return typeof e==="string"&&e?e:null}function k(t,e){const o=(t.getAttribute("href")||"").match(/^\/people\/([A-Za-z0-9_-]+)/);if(!o)return null;const n=t.getAttribute("aria-label")||"",l=t.getAttribute("title")||"",a=t.getAttribute("data-testid")||"",g=t.getAttribute("class")||"",m=t.getAttribute("rel")||"",S=`${n} ${l} ${t.textContent||""}`,I=`${a} ${g} ${m}`,p=Boolean(t.querySelector(u)),A=E(S),h=x(I);if(A||h)return o[1];if(e&&p)return o[1];return null}function y(t,e){for(const r of t)for(const o of Array.from(r.querySelectorAll(c)).filter(F)){const n=k(o,e);if(n)return n}return null}export function resolveCurrentUserSlugFromDom(t,e){const r=O(t);if(r)return r;const o=Array.from(e.querySelectorAll(s)).filter(v);return y(o,!0)||y([e],!1)}export function requireExecute(t){if(!t.execute)throw new i("INVALID_INPUT","此知乎写命令需要 --execute 才会真正执行。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}export async function resolvePayload(t,e=T()){const r=typeof t.text==="string"?t.text:void 0,o=typeof t.file==="string"?t.file:void 0;if(r&&o)throw new i("INVALID_INPUT","Use either <text> or --file, not both");let n=r??"";if(o){let l;try{l=await e.stat(o)}catch{throw new i("INVALID_INPUT",`File not found: ${o}`)}if(!l.isFile())throw new i("INVALID_INPUT",`File must be a readable text file: ${o}`);let a;try{a=await e.readFile(o)}catch{throw new i("INVALID_INPUT",`File could not be read: ${o}`)}try{n=e.decodeUtf8(a)}catch{throw new i("INVALID_INPUT",`File could not be decoded as UTF-8 text: ${o}`)}}if(!n.trim())throw new i("INVALID_INPUT","Payload cannot be empty or whitespace only");return n}function C(){return`(() => {
1
+ import{readFile as b,stat as _}from"node:fs/promises";import{CliError as i}from"@jackwener/opencli/errors";import{rememberArticleFile as L}from"../_shared/article/images.js";const w=new Set(["status","outcome","message","target_type","target"]),s='header, nav, [role="banner"], [role="navigation"]',c='a[href^="/people/"]',u='img, [class*="Avatar"], [data-testid*="avatar" i], [aria-label*="头像"]',f=["我","我的","个人主页"],d=[["self"],["current","user"],["account","profile"],["my","profile"],["my","account"]],T=JSON.stringify(d);function E(){return{readFile:b,stat:(t)=>_(t),decodeUtf8:(t)=>new TextDecoder("utf-8",{fatal:!0}).decode(t)}}function N(t){const e=t.toLowerCase();return f.some((r)=>t.includes(r))||e.includes("my profile")||e.includes("my account")}function x(t){return t.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function v(t){const e=new Set(x(t));return d.some((r)=>r.every((o)=>e.has(o)))}function F(t){return typeof t==="object"&&t!==null&&"querySelectorAll"in t&&typeof t.querySelectorAll==="function"}function O(t){return typeof t==="object"&&t!==null&&"getAttribute"in t&&"querySelector"in t&&typeof t.getAttribute==="function"&&typeof t.querySelector==="function"}function k(t){const e=t?.topstory?.me?.slug||t?.me?.slug||t?.initialState?.me?.slug;return typeof e==="string"&&e?e:null}function C(t,e){const o=(t.getAttribute("href")||"").match(/^\/people\/([A-Za-z0-9_-]+)/);if(!o)return null;const n=t.getAttribute("aria-label")||"",l=t.getAttribute("title")||"",a=t.getAttribute("data-testid")||"",m=t.getAttribute("class")||"",g=t.getAttribute("rel")||"",S=`${n} ${l} ${t.textContent||""}`,I=`${a} ${m} ${g}`,p=Boolean(t.querySelector(u)),A=N(S),h=v(I);if(A||h)return o[1];if(e&&p)return o[1];return null}function y(t,e){for(const r of t)for(const o of Array.from(r.querySelectorAll(c)).filter(O)){const n=C(o,e);if(n)return n}return null}export function resolveCurrentUserSlugFromDom(t,e){const r=k(t);if(r)return r;const o=Array.from(e.querySelectorAll(s)).filter(F);return y(o,!0)||y([e],!1)}export function requireExecute(t){if(!t.execute)throw new i("INVALID_INPUT","此知乎写命令需要 --execute 才会真正执行。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}export async function resolvePayload(t,e=E()){const r=typeof t.text==="string"?t.text:void 0,o=typeof t.file==="string"?t.file:void 0;if(r&&o)throw new i("INVALID_INPUT","Use either <text> or --file, not both");let n=r??"";if(o){L(o);let l;try{l=await e.stat(o)}catch{throw new i("INVALID_INPUT",`File not found: ${o}`)}if(!l.isFile())throw new i("INVALID_INPUT",`File must be a readable text file: ${o}`);let a;try{a=await e.readFile(o)}catch{throw new i("INVALID_INPUT",`File could not be read: ${o}`)}try{n=e.decodeUtf8(a)}catch{throw new i("INVALID_INPUT",`File could not be decoded as UTF-8 text: ${o}`)}}if(!n.trim())throw new i("INVALID_INPUT","Payload cannot be empty or whitespace only");return n}function U(){return`(() => {
2
2
  const selfLabelTokens = ${JSON.stringify(f)};
3
- const explicitIdentityMetaTokenGroups = ${w};
3
+ const explicitIdentityMetaTokenGroups = ${T};
4
4
  const navScopeSelector = ${JSON.stringify(s)};
5
5
  const profileLinkSelector = ${JSON.stringify(c)};
6
6
  const avatarSelector = ${JSON.stringify(u)};
@@ -68,4 +68,4 @@ import{readFile as b,stat as _}from"node:fs/promises";import{CliError as i}from"
68
68
  if (altMatch) return { slug: altMatch[1] };
69
69
  }
70
70
  return null;
71
- })()`}export async function resolveCurrentUserIdentity(t){let e=null;for(let r=0;r<30;r++){e=await t.evaluate(C());if(e?.slug)break;await t.wait({time:0.5})}if(!e?.slug)throw new i("ACTION_NOT_AVAILABLE","Could not resolve the logged-in Zhihu user identity before write");return e.slug}export function buildResultRow(t,e,r,o,n={}){for(const l of Object.keys(n))if(L.has(l))throw new i("INVALID_INPUT",`Result extra field cannot overwrite reserved key: ${l}`);return[{status:"success",outcome:o,message:t,target_type:e,target:r,...n}]}export const __test__={requireExecute,resolvePayload,resolveCurrentUserIdentity,resolveCurrentUserSlugFromDom,buildResultRow};
71
+ })()`}export async function resolveCurrentUserIdentity(t){let e=null;for(let r=0;r<30;r++){e=await t.evaluate(U());if(e?.slug)break;await t.wait({time:0.5})}if(!e?.slug)throw new i("ACTION_NOT_AVAILABLE","Could not resolve the logged-in Zhihu user identity before write");return e.slug}export function buildResultRow(t,e,r,o,n={}){for(const l of Object.keys(n))if(w.has(l))throw new i("INVALID_INPUT",`Result extra field cannot overwrite reserved key: ${l}`);return[{status:"success",outcome:o,message:t,target_type:e,target:r,...n}]}export const __test__={requireExecute,resolvePayload,resolveCurrentUserIdentity,resolveCurrentUserSlugFromDom,buildResultRow};
@@ -31,3 +31,12 @@ export declare function isAdapterStillRunning(err: unknown): boolean;
31
31
  */
32
32
  export declare function resolveFileBackedArg(cmd: CliCommand, kwargs: CommandArgs): void;
33
33
  export declare function prepareCommandArgs(cmd: CliCommand, rawKwargs: CommandArgs): CommandArgs;
34
+ /**
35
+ * [pp-only] 未声明 --timeout 的写命令的整体等待上限(秒)。
36
+ * 全局 60 秒默认值面向读命令;写命令(发视频、传图、长文)常在 60 秒后仍在设备上
37
+ * 继续上传并最终发出,CLI 却已报 TIMEOUT,调用方据此重发就会重复投稿(复盘:抖音
38
+ * 380MB / 545MB 视频、推特长文均如此)。取 540 秒:低于中转 local_bash 600 秒上限,
39
+ * 让 CLI 自己的「写操作超时不代表没写成功」提示先于设备侧强杀出现。
40
+ */
41
+ export declare const WRITE_COMMAND_DEFAULT_TIMEOUT_SECONDS = 540;
42
+ export declare function resolveBrowserCommandTimeout(cmd: CliCommand, userTimeoutSec: number | null): number;