publishport-opencli 1.0.55 → 1.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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}
@@ -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;
@@ -1,2 +1,2 @@
1
- import{getRegistry as ie,fullName as w}from"./registry.js";import{pathToFileURL as se}from"node:url";import*as ae from"node:crypto";import*as M from"node:fs";import*as j from"node:os";import*as N from"node:path";import{executePipeline as K}from"./pipeline/index.js";import{adapterLoadError as ue,ArgumentError as d,CommandExecutionError as A,SessionBusyError as ce,attachTraceReceipt as le,getErrorMessage as k}from"./errors.js";import{shouldUseBrowserSession as fe}from"./capabilityRouting.js";import{getBrowserFactory as me,browserSession as de,runWithTimeout as V,isRemoteExecution as pe,DEFAULT_BROWSER_COMMAND_TIMEOUT as he}from"./runtime.js";import{withBrowserSessionLockIf as ge}from"./browser-session-lock.js";import{resolveProfile as we}from"./browser/profile.js";import{ensureManagedChrome as ye}from"./browser/managed-chrome.js";import{generateFingerprintJs as Se}from"./browser/fingerprint.js";import{CDPBridge as ve}from"./browser/index.js";import{clearDaemonRunContext as be,generateRunId as $e,isUnknownOutcomeError as G,releaseSiteSessionLease as J,setDaemonCommandTimeoutSeconds as Ee,setDaemonRunContext as Q}from"./browser/daemon-client.js";import{emitHook as D}from"./hooks.js";import{setContentBaseDir as Pe}from"./utils.js";import{log as X}from"./logger.js";import{isElectronApp as Ae}from"./electron-apps.js";import{probeCDP as xe,resolveElectronEndpoint as Re}from"./launcher.js";import{ObservationSession as Ce,exportObservationSession as Ie}from"./observation/index.js";import{resolveAdapterSourcePath as Te}from"./adapter-source.js";const v=new Map,_=new Map,Me=`${j.homedir()}/.ppcli/clis/`;function Ne(e){if(e===void 0||e===null||e===""||e==="off")return"off";if(e==="on"||e==="retain-on-failure")return e;throw new d(`--trace must be one of: off, on, retain-on-failure. Received: "${String(e)}"`)}export function coerceAndValidateArgs(e,r){const t={...r};for(const n of e){const o=t[n.name];if(n.required&&(o===void 0||o===null||o===""))throw new d(`Argument "${n.name}" is required.`,n.help??`Provide a value for --${n.name}`);if(o!==void 0&&o!==null){if(n.type==="int"||n.type==="number"){const l=Number(o);if(!Number.isFinite(l))throw new d(`Argument "${n.name}" must be a valid number. Received: "${o}"`);if(n.type==="int"&&!Number.isInteger(l))throw new d(`Argument "${n.name}" must be a valid integer. Received: "${o}"`);t[n.name]=l}else if(n.type==="boolean"||n.type==="bool")if(typeof o==="string"){const l=o.toLowerCase();if(l==="true"||l==="1")t[n.name]=!0;else if(l==="false"||l==="0")t[n.name]=!1;else throw new d(`Argument "${n.name}" must be a boolean (true/false). Received: "${o}"`)}else t[n.name]=Boolean(o);const s=t[n.name];if(n.choices&&n.choices.length>0){if(!n.choices.map(String).includes(String(s)))throw new d(`Argument "${n.name}" must be one of: ${n.choices.join(", ")}. Received: "${s}"`)}}else if(n.default!==void 0)t[n.name]=n.default}return t}async function B(e,r,t,n){const o=e;if(o._lazy&&o._modulePath){const s=o._modulePath;if(s.startsWith(Me)&&v.has(s))try{const m=M.statSync(s),i=_.get(s);if(i!==void 0&&m.mtimeMs!==i)v.delete(s)}catch{}if(!v.has(s)){const m=se(s).href,g=import(_.has(s)?`${m}?t=${Date.now()}`:m).then(()=>{try{_.set(s,M.statSync(s).mtimeMs)}catch{}},(p)=>{v.delete(s);throw ue(`Failed to load adapter module ${s}: ${k(p)}`,"Check that the adapter file exists and has no syntax errors.")});v.set(s,g)}await v.get(s);const f=ie().get(w(e));if(f?.func)return Y(f,r,t,n);if(f?.pipeline)return K(r,f.pipeline,{args:t,debug:n})}if(e.func)return Y(e,r,t,n);if(e.pipeline)return K(r,e.pipeline,{args:t,debug:n});throw new A(`Command ${w(e)} has no func or pipeline`,"This is likely a bug in the adapter definition. Please report this issue.")}function Y(e,r,t,n){if(e.browser===!1)return e.func(t,n);if(!r)throw new A(`Command ${w(e)} requires a browser session but none was provided`);return e.func(r,t,n)}function ke(e){if(e.navigateBefore===!1)return null;if(typeof e.navigateBefore==="string")return e.navigateBefore;return null}function De(e,r){if(!e||!r)return!1;try{const t=new URL(e).hostname;return t===r||t.endsWith(`.${r}`)}catch{return!1}}function _e(e,r){if(!r)return!1;try{const t=new URL(e),n=t.hostname===r||t.hostname.endsWith(`.${r}`),o=t.pathname===""||t.pathname==="/";return n&&o&&t.search===""&&t.hash===""}catch{return!1}}async function Be(e,r,t,n){if(t!=="persistent"||!e.domain)return!0;if(!_e(n,e.domain))return!0;const o=await r.getCurrentUrl?.().catch(()=>null);return!De(o,e.domain)}export async function executeCommand(e,r,t=!1,n={}){let o;try{o=n.prepared?r:prepareCommandArgs(e,r)}catch(i){if(i instanceof d)throw i;throw new d(k(i))}const s=je(e,o);Ee(s);const l=Ne(n.trace),f={command:w(e),args:o,startedAt:Date.now()};await D("onBeforeExecute",f);let m;try{if(fe(e)){const i=Ae(e.site),g=we(n.profile),p=!i&&g.kind==="managed"?g:null;process.env.PPCLI_ACTIVE_PROFILE=p?p.name:"";let P;const x=He(e.defaultWindowMode??"background",n.windowMode);let F,W;if(p){P=await ye(p.name,p.entry,{windowMode:x});const u=p.entry.fingerprint;if(u?.enabled)F=Se(u);const a=p.entry.proxy;if(a?.username)W={username:a.username,password:a.password??""}}else if(i){const u=process.env.OPENCLI_CDP_ENDPOINT;if(u){const a=Number(new URL(u).port);if(!await xe(a))throw new A(`CDP not reachable at ${u}`,"Check that the app is running with --remote-debugging-port and the endpoint is correct.");P=u}else P=await Re(e.site)}const ne=p?ve:me(e.site),L=!p&&g.kind==="extension"?g.contextId:void 0,oe=e,b=We(e,n.siteSession),R=Le(e,b),q=ze(e,b,n.keepTab),y=b==="persistent"&&e.access==="write"?{runId:$e(),session:R}:null;if(y)Q({runId:y.runId,command:w(e),access:"write"});let z,H=!1,C=null;try{m=await ge(x!=="foreground",()=>de(ne,async(u)=>{const a=l==="off"?null:new Ce({scope:{contextId:L??p?.name,session:R,target:u.getActivePage?.(),site:e.site,command:w(e),adapterSourcePath:Te(oe)}});if(a){a.record({stream:"action",name:"command",phase:"start",data:{args:o}});await u.startNetworkCapture?.().catch(()=>!1)}const h=ke(e);if(h&&await Be(e,u,b,h)){a?.record({stream:"action",name:"pre_navigate",phase:"start",data:{url:h}});try{await u.goto(h);a?.record({stream:"action",name:"pre_navigate",phase:"end",data:{url:h}})}catch(c){if(c instanceof ce)throw c;a?.record({stream:"action",name:"pre_navigate",phase:"error",data:{url:h,error:c instanceof Error?c.message:String(c)}});const S=new A(`Pre-navigation to ${h} failed: ${c instanceof Error?c.message:c}`,"Check that the site is reachable and the browser extension is running.");S.cause=c;if(a&&(l==="on"||l==="retain-on-failure")){a.record({stream:"error",message:S.message,stack:S.stack,code:S.code,hint:S.hint});await U(a,u).catch(()=>{});O(a,"failure",S,n.onTraceExport)}throw S}}const E=s!==null?s+ee:he,I=B(e,u,o,t);C=I;let T=!1;I.then(()=>{T=!0},()=>{T=!0});try{const c=await V(I,{timeout:E,label:w(e),hint:re(e,s)});a?.record({stream:"action",name:"command",phase:"end"});if(a&&l==="on"){await U(a,u).catch(()=>{});O(a,"success",void 0,n.onTraceExport)}if(!q)await u.closeWindow?.().catch(()=>{});return c}catch(c){if(!T){H=!0;Ue(c)}if(a){a.record({stream:"action",name:"command",phase:"error",data:{error:c instanceof Error?c.message:String(c)}});a.record({stream:"error",message:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0});if(l==="on"||l==="retain-on-failure"){await U(a,u).catch(()=>{});O(a,"failure",c,n.onTraceExport)}}if(!q)await u.closeWindow?.().catch(()=>{});throw c}},{session:R,cdpEndpoint:P,contextId:L,windowMode:x,surface:"adapter",siteSession:b,initScript:F,proxyAuth:W}),p?.name)}catch(u){z=u;throw u}finally{if(y)if(H&&C){const{runId:u,session:a}=y,h=(E)=>{be(u);if(!G(E))J({runId:u,session:a,surface:"adapter"})};C.then(()=>h(),(E)=>h(E))}else{Q(null);if(!G(z))await J({runId:y.runId,session:y.session,surface:"adapter"})}}}else if(s!==null){const i=s+ee;m=await V(B(e,null,o,t),{timeout:i,label:w(e),hint:re(e,s)})}else m=await B(e,null,o,t)}catch(i){f.error=i;f.finishedAt=Date.now();await D("onAfterExecute",f);throw i}f.finishedAt=Date.now();await D("onAfterExecute",f,m);return m}const Z=new WeakSet;function Ue(e){if(e!==null&&typeof e==="object")Z.add(e)}export function isAdapterStillRunning(e){return e!==null&&typeof e==="object"&&Z.has(e)}async function U(e,r){const t=r.getActivePage?.()??e.scope.target,[n,o,s,l,f]=await Promise.all([r.getCurrentUrl?.().catch(()=>null)??Promise.resolve(null),r.snapshot().catch(()=>{return}),r.readNetworkCapture?.().catch(()=>[])??Promise.resolve([]),r.consoleMessages("all").catch(()=>[]),r.screenshot({format:"png"}).catch(()=>{return})]);if(o!==void 0||n!==void 0)e.record({stream:"state",url:n,target:t,snapshot:o,label:"final"});for(const m of Array.isArray(s)?s:[]){const i=m;e.record({stream:"network",url:String(i.url??""),method:typeof i.method==="string"?i.method:void 0,status:typeof i.responseStatus==="number"?i.responseStatus:void 0,contentType:typeof i.responseContentType==="string"?i.responseContentType:void 0,size:typeof i.responseBodyFullSize==="number"?i.responseBodyFullSize:void 0,requestHeaders:i.requestHeaders,responseHeaders:i.responseHeaders,requestBody:i.requestBodyPreview,responseBody:i.responsePreview,ts:typeof i.timestamp==="number"?i.timestamp:void 0})}for(const m of Array.isArray(l)?l:[])if(m&&typeof m==="object"){const i=m;e.record({stream:"console",level:String(i.type??i.level??"log"),text:String(i.text??i.message??""),ts:typeof i.timestamp==="number"?i.timestamp:void 0})}else e.record({stream:"console",level:"log",text:String(m)});if(typeof f==="string"&&f)e.record({stream:"screenshot",format:"png",data:f,label:"final"})}function O(e,r,t,n){try{const o=Ie(e,{error:t,status:r});if(r==="failure"&&t!==void 0)le(t,o.receipt);else process.stderr.write(`ppcli trace artifact: ${o.dir}
2
- `);try{n?.(o)}catch(s){X.warn(`[trace] Trace export callback failed: ${s instanceof Error?s.message:String(s)}`)}return o}catch(o){X.warn(`[trace] Failed to export trace artifact: ${o instanceof Error?o.message:String(o)}`);return}}export function resolveFileBackedArg(e,r){const t=e.args.find((f)=>f.fromFile);if(!t)return;const n=typeof t.fromFile==="string"?t.fromFile:"file",o=t.positional?`<${t.name}>`:`--${t.name}`,s=r[n]==null?"":String(r[n]).trim(),l=r[t.name]==null?"":String(r[t.name]);if(s){if(l.trim())throw new d(`${o} 和 --${n} 只能二选一,不能同时给`);const f=N.resolve(s.startsWith("~/")?N.join(j.homedir(),s.slice(2)):s);let m;try{m=M.readFileSync(f,"utf-8")}catch(g){throw new d(`--${n} 指向的文件读不到: ${f}(${k(g)})`)}const i=m.trim();if(!i)throw new d(`--${n} 指向的文件内容为空: ${f}`);r[t.name]=i;Pe(N.dirname(f));return}if(!l.trim()&&t.requiredUnlessFile)throw new d(`缺少 ${t.name}:${o} 或 --${n} 给其一`)}export function prepareCommandArgs(e,r){const t=coerceAndValidateArgs(e.args,r);resolveFileBackedArg(e,t);e.validateArgs?.(t);return t}const ee=30;function Oe(e){if(e===void 0||e===null||e==="")return null;if(e==="ephemeral"||e==="persistent")return e;throw new d(`--site-session must be one of: ephemeral, persistent. Received: "${String(e)}"`)}function Fe(){const e=process.env.PUBLISHPORT_SITE_SESSION;if(e==="persistent"||e==="ephemeral")return e;return null}function We(e,r){return Oe(r)??Fe()??e.siteSession??"persistent"}function Le(e,r){const t=typeof e.sessionKey==="string"&&e.sessionKey.trim()?`:${e.sessionKey.trim()}`:"";if(r==="persistent")return`site:${e.site}${t}`;return`site:${e.site}${t}:${ae.randomUUID()}`}function qe(e,r){if(r===void 0||r==="")return null;if(r==="true")return!0;if(r==="false")return!1;throw new d(`${e} must be one of: true, false. Received: "${String(r)}"`)}function ze(e,r,t){return qe("--keep-tab",t)??(r==="persistent"&&e.siteSession==="persistent")}function te(e,r){if(r===void 0||r==="")return null;if(r==="foreground"||r==="background")return r;throw new d(`${e} must be one of: foreground, background. Received: "${String(r)}"`)}function He(e="background",r){if(pe())return"background";return te("--window",r)??te("OPENCLI_WINDOW",process.env.OPENCLI_WINDOW)??e}function re(e,r){const t=e.access==="write"?"⚠️ 这是写操作,超时不代表没写成功——请求可能已经到达平台。禁止直接重试:"+"先用该平台的列表/统计命令(stats / lists / articles 等)按标题回查,确认没写进去再重发。 ":"";if(r!==null)return`${t}Pass a higher --timeout value (currently ${r}s)`;if(e.args.some((n)=>n.name==="timeout"))return`${t}Try again, or pass a higher --timeout <seconds>`;return t+"This command has no --timeout option. Retry once; if it keeps timing out, "+"the page or browser bridge is likely stuck — have the user reopen the PublishPort client. "+"The global default can be raised with OPENCLI_BROWSER_COMMAND_TIMEOUT."}function je(e,r){if(!e.args.some((o)=>o.name==="timeout"))return null;const t=r.timeout;if(t===void 0||t===null||t==="")throw new d(`Argument "timeout" must be a positive integer. Received: "${String(t)}"`);const n=Number(t);if(!Number.isInteger(n)||n<=0)throw new d(`Argument "timeout" must be a positive integer. Received: "${String(t)}"`);return n}
1
+ import{getRegistry as se,fullName as w}from"./registry.js";import{pathToFileURL as ae}from"node:url";import*as ue from"node:crypto";import*as M from"node:fs";import*as j from"node:os";import*as D from"node:path";import{executePipeline as K}from"./pipeline/index.js";import{adapterLoadError as ce,ArgumentError as d,CommandExecutionError as x,SessionBusyError as le,attachTraceReceipt as fe,getErrorMessage as N}from"./errors.js";import{shouldUseBrowserSession as me}from"./capabilityRouting.js";import{getBrowserFactory as de,browserSession as pe,runWithTimeout as V,isRemoteExecution as he,DEFAULT_BROWSER_COMMAND_TIMEOUT as G}from"./runtime.js";import{withBrowserSessionLockIf as ge}from"./browser-session-lock.js";import{resolveProfile as we}from"./browser/profile.js";import{ensureManagedChrome as ye}from"./browser/managed-chrome.js";import{generateFingerprintJs as Se}from"./browser/fingerprint.js";import{CDPBridge as ve}from"./browser/index.js";import{clearDaemonRunContext as be,generateRunId as $e,isUnknownOutcomeError as J,releaseSiteSessionLease as Q,setDaemonCommandTimeoutSeconds as Ee,setDaemonRunContext as X}from"./browser/daemon-client.js";import{emitHook as _}from"./hooks.js";import{setContentBaseDir as Pe}from"./utils.js";import{log as Y}from"./logger.js";import{isElectronApp as xe}from"./electron-apps.js";import{probeCDP as Ae,resolveElectronEndpoint as Ce}from"./launcher.js";import{ObservationSession as Re,exportObservationSession as Te}from"./observation/index.js";import{resolveAdapterSourcePath as Ie}from"./adapter-source.js";const v=new Map,k=new Map,Me=`${j.homedir()}/.ppcli/clis/`;function De(e){if(e===void 0||e===null||e===""||e==="off")return"off";if(e==="on"||e==="retain-on-failure")return e;throw new d(`--trace must be one of: off, on, retain-on-failure. Received: "${String(e)}"`)}export function coerceAndValidateArgs(e,r){const t={...r};for(const n of e){const o=t[n.name];if(n.required&&(o===void 0||o===null||o===""))throw new d(`Argument "${n.name}" is required.`,n.help??`Provide a value for --${n.name}`);if(o!==void 0&&o!==null){if(n.type==="int"||n.type==="number"){const l=Number(o);if(!Number.isFinite(l))throw new d(`Argument "${n.name}" must be a valid number. Received: "${o}"`);if(n.type==="int"&&!Number.isInteger(l))throw new d(`Argument "${n.name}" must be a valid integer. Received: "${o}"`);t[n.name]=l}else if(n.type==="boolean"||n.type==="bool")if(typeof o==="string"){const l=o.toLowerCase();if(l==="true"||l==="1")t[n.name]=!0;else if(l==="false"||l==="0")t[n.name]=!1;else throw new d(`Argument "${n.name}" must be a boolean (true/false). Received: "${o}"`)}else t[n.name]=Boolean(o);const s=t[n.name];if(n.choices&&n.choices.length>0){if(!n.choices.map(String).includes(String(s)))throw new d(`Argument "${n.name}" must be one of: ${n.choices.join(", ")}. Received: "${s}"`)}}else if(n.default!==void 0)t[n.name]=n.default}return t}async function O(e,r,t,n){const o=e;if(o._lazy&&o._modulePath){const s=o._modulePath;if(s.startsWith(Me)&&v.has(s))try{const m=M.statSync(s),i=k.get(s);if(i!==void 0&&m.mtimeMs!==i)v.delete(s)}catch{}if(!v.has(s)){const m=ae(s).href,g=import(k.has(s)?`${m}?t=${Date.now()}`:m).then(()=>{try{k.set(s,M.statSync(s).mtimeMs)}catch{}},(p)=>{v.delete(s);throw ce(`Failed to load adapter module ${s}: ${N(p)}`,"Check that the adapter file exists and has no syntax errors.")});v.set(s,g)}await v.get(s);const f=se().get(w(e));if(f?.func)return Z(f,r,t,n);if(f?.pipeline)return K(r,f.pipeline,{args:t,debug:n})}if(e.func)return Z(e,r,t,n);if(e.pipeline)return K(r,e.pipeline,{args:t,debug:n});throw new x(`Command ${w(e)} has no func or pipeline`,"This is likely a bug in the adapter definition. Please report this issue.")}function Z(e,r,t,n){if(e.browser===!1)return e.func(t,n);if(!r)throw new x(`Command ${w(e)} requires a browser session but none was provided`);return e.func(r,t,n)}function Ne(e){if(e.navigateBefore===!1)return null;if(typeof e.navigateBefore==="string")return e.navigateBefore;return null}function _e(e,r){if(!e||!r)return!1;try{const t=new URL(e).hostname;return t===r||t.endsWith(`.${r}`)}catch{return!1}}function ke(e,r){if(!r)return!1;try{const t=new URL(e),n=t.hostname===r||t.hostname.endsWith(`.${r}`),o=t.pathname===""||t.pathname==="/";return n&&o&&t.search===""&&t.hash===""}catch{return!1}}async function Oe(e,r,t,n){if(t!=="persistent"||!e.domain)return!0;if(!ke(n,e.domain))return!0;const o=await r.getCurrentUrl?.().catch(()=>null);return!_e(o,e.domain)}export async function executeCommand(e,r,t=!1,n={}){let o;try{o=n.prepared?r:prepareCommandArgs(e,r)}catch(i){if(i instanceof d)throw i;throw new d(N(i))}const s=je(e,o);Ee(s);const l=De(n.trace),f={command:w(e),args:o,startedAt:Date.now()};await _("onBeforeExecute",f);let m;try{if(me(e)){const i=xe(e.site),g=we(n.profile),p=!i&&g.kind==="managed"?g:null;process.env.PPCLI_ACTIVE_PROFILE=p?p.name:"";let P;const A=He(e.defaultWindowMode??"background",n.windowMode);let F,W;if(p){P=await ye(p.name,p.entry,{windowMode:A});const u=p.entry.fingerprint;if(u?.enabled)F=Se(u);const a=p.entry.proxy;if(a?.username)W={username:a.username,password:a.password??""}}else if(i){const u=process.env.OPENCLI_CDP_ENDPOINT;if(u){const a=Number(new URL(u).port);if(!await Ae(a))throw new x(`CDP not reachable at ${u}`,"Check that the app is running with --remote-debugging-port and the endpoint is correct.");P=u}else P=await Ce(e.site)}const oe=p?ve:de(e.site),L=!p&&g.kind==="extension"?g.contextId:void 0,ie=e,b=We(e,n.siteSession),C=Le(e,b),q=ze(e,b,n.keepTab),y=b==="persistent"&&e.access==="write"?{runId:$e(),session:C}:null;if(y)X({runId:y.runId,command:w(e),access:"write"});let z,H=!1,R=null;try{m=await ge(A!=="foreground",()=>pe(oe,async(u)=>{const a=l==="off"?null:new Re({scope:{contextId:L??p?.name,session:C,target:u.getActivePage?.(),site:e.site,command:w(e),adapterSourcePath:Ie(ie)}});if(a){a.record({stream:"action",name:"command",phase:"start",data:{args:o}});await u.startNetworkCapture?.().catch(()=>!1)}const h=Ne(e);if(h&&await Oe(e,u,b,h)){a?.record({stream:"action",name:"pre_navigate",phase:"start",data:{url:h}});try{await u.goto(h);a?.record({stream:"action",name:"pre_navigate",phase:"end",data:{url:h}})}catch(c){if(c instanceof le)throw c;a?.record({stream:"action",name:"pre_navigate",phase:"error",data:{url:h,error:c instanceof Error?c.message:String(c)}});const S=new x(`Pre-navigation to ${h} failed: ${c instanceof Error?c.message:c}`,"Check that the site is reachable and the browser extension is running.");S.cause=c;if(a&&(l==="on"||l==="retain-on-failure")){a.record({stream:"error",message:S.message,stack:S.stack,code:S.code,hint:S.hint});await U(a,u).catch(()=>{});B(a,"failure",S,n.onTraceExport)}throw S}}const E=resolveBrowserCommandTimeout(e,s),T=O(e,u,o,t);R=T;let I=!1;T.then(()=>{I=!0},()=>{I=!0});try{const c=await V(T,{timeout:E,label:w(e),hint:ne(e,s)});a?.record({stream:"action",name:"command",phase:"end"});if(a&&l==="on"){await U(a,u).catch(()=>{});B(a,"success",void 0,n.onTraceExport)}if(!q)await u.closeWindow?.().catch(()=>{});return c}catch(c){if(!I){H=!0;Ue(c)}if(a){a.record({stream:"action",name:"command",phase:"error",data:{error:c instanceof Error?c.message:String(c)}});a.record({stream:"error",message:c instanceof Error?c.message:String(c),stack:c instanceof Error?c.stack:void 0});if(l==="on"||l==="retain-on-failure"){await U(a,u).catch(()=>{});B(a,"failure",c,n.onTraceExport)}}if(!q)await u.closeWindow?.().catch(()=>{});throw c}},{session:C,cdpEndpoint:P,contextId:L,windowMode:A,surface:"adapter",siteSession:b,initScript:F,proxyAuth:W}),p?.name)}catch(u){z=u;throw u}finally{if(y)if(H&&R){const{runId:u,session:a}=y,h=(E)=>{be(u);if(!J(E))Q({runId:u,session:a,surface:"adapter"})};R.then(()=>h(),(E)=>h(E))}else{X(null);if(!J(z))await Q({runId:y.runId,session:y.session,surface:"adapter"})}}}else if(s!==null){const i=s+te;m=await V(O(e,null,o,t),{timeout:i,label:w(e),hint:ne(e,s)})}else m=await O(e,null,o,t)}catch(i){f.error=i;f.finishedAt=Date.now();await _("onAfterExecute",f);throw i}f.finishedAt=Date.now();await _("onAfterExecute",f,m);return m}const ee=new WeakSet;function Ue(e){if(e!==null&&typeof e==="object")ee.add(e)}export function isAdapterStillRunning(e){return e!==null&&typeof e==="object"&&ee.has(e)}async function U(e,r){const t=r.getActivePage?.()??e.scope.target,[n,o,s,l,f]=await Promise.all([r.getCurrentUrl?.().catch(()=>null)??Promise.resolve(null),r.snapshot().catch(()=>{return}),r.readNetworkCapture?.().catch(()=>[])??Promise.resolve([]),r.consoleMessages("all").catch(()=>[]),r.screenshot({format:"png"}).catch(()=>{return})]);if(o!==void 0||n!==void 0)e.record({stream:"state",url:n,target:t,snapshot:o,label:"final"});for(const m of Array.isArray(s)?s:[]){const i=m;e.record({stream:"network",url:String(i.url??""),method:typeof i.method==="string"?i.method:void 0,status:typeof i.responseStatus==="number"?i.responseStatus:void 0,contentType:typeof i.responseContentType==="string"?i.responseContentType:void 0,size:typeof i.responseBodyFullSize==="number"?i.responseBodyFullSize:void 0,requestHeaders:i.requestHeaders,responseHeaders:i.responseHeaders,requestBody:i.requestBodyPreview,responseBody:i.responsePreview,ts:typeof i.timestamp==="number"?i.timestamp:void 0})}for(const m of Array.isArray(l)?l:[])if(m&&typeof m==="object"){const i=m;e.record({stream:"console",level:String(i.type??i.level??"log"),text:String(i.text??i.message??""),ts:typeof i.timestamp==="number"?i.timestamp:void 0})}else e.record({stream:"console",level:"log",text:String(m)});if(typeof f==="string"&&f)e.record({stream:"screenshot",format:"png",data:f,label:"final"})}function B(e,r,t,n){try{const o=Te(e,{error:t,status:r});if(r==="failure"&&t!==void 0)fe(t,o.receipt);else process.stderr.write(`ppcli trace artifact: ${o.dir}
2
+ `);try{n?.(o)}catch(s){Y.warn(`[trace] Trace export callback failed: ${s instanceof Error?s.message:String(s)}`)}return o}catch(o){Y.warn(`[trace] Failed to export trace artifact: ${o instanceof Error?o.message:String(o)}`);return}}export function resolveFileBackedArg(e,r){const t=e.args.find((f)=>f.fromFile);if(!t)return;const n=typeof t.fromFile==="string"?t.fromFile:"file",o=t.positional?`<${t.name}>`:`--${t.name}`,s=r[n]==null?"":String(r[n]).trim(),l=r[t.name]==null?"":String(r[t.name]);if(s){if(l.trim())throw new d(`${o} 和 --${n} 只能二选一,不能同时给`);const f=D.resolve(s.startsWith("~/")?D.join(j.homedir(),s.slice(2)):s);let m;try{m=M.readFileSync(f,"utf-8")}catch(g){throw new d(`--${n} 指向的文件读不到: ${f}(${N(g)})`)}const i=m.trim();if(!i)throw new d(`--${n} 指向的文件内容为空: ${f}`);r[t.name]=i;Pe(D.dirname(f));return}if(!l.trim()&&t.requiredUnlessFile)throw new d(`缺少 ${t.name}:${o} 或 --${n} 给其一`)}export function prepareCommandArgs(e,r){const t=coerceAndValidateArgs(e.args,r);resolveFileBackedArg(e,t);e.validateArgs?.(t);return t}const te=30;export const WRITE_COMMAND_DEFAULT_TIMEOUT_SECONDS=540;export function resolveBrowserCommandTimeout(e,r){if(r!==null)return r+te;if(e.access==="write")return Math.max(G,WRITE_COMMAND_DEFAULT_TIMEOUT_SECONDS);return G}function Be(e){if(e===void 0||e===null||e==="")return null;if(e==="ephemeral"||e==="persistent")return e;throw new d(`--site-session must be one of: ephemeral, persistent. Received: "${String(e)}"`)}function Fe(){const e=process.env.PUBLISHPORT_SITE_SESSION;if(e==="persistent"||e==="ephemeral")return e;return null}function We(e,r){return Be(r)??Fe()??e.siteSession??"persistent"}function Le(e,r){const t=typeof e.sessionKey==="string"&&e.sessionKey.trim()?`:${e.sessionKey.trim()}`:"";if(r==="persistent")return`site:${e.site}${t}`;return`site:${e.site}${t}:${ue.randomUUID()}`}function qe(e,r){if(r===void 0||r==="")return null;if(r==="true")return!0;if(r==="false")return!1;throw new d(`${e} must be one of: true, false. Received: "${String(r)}"`)}function ze(e,r,t){return qe("--keep-tab",t)??(r==="persistent"&&e.siteSession==="persistent")}function re(e,r){if(r===void 0||r==="")return null;if(r==="foreground"||r==="background")return r;throw new d(`${e} must be one of: foreground, background. Received: "${String(r)}"`)}function He(e="background",r){if(he())return"background";return re("--window",r)??re("OPENCLI_WINDOW",process.env.OPENCLI_WINDOW)??e}function ne(e,r){const t=e.access==="write"?"⚠️ 这是写操作,超时不代表没写成功——请求可能已经到达平台。禁止直接重试:"+"先用该平台的列表/统计命令(stats / lists / articles 等)按标题回查,确认没写进去再重发。 ":"";if(r!==null)return`${t}Pass a higher --timeout value (currently ${r}s)`;if(e.args.some((n)=>n.name==="timeout"))return`${t}Try again, or pass a higher --timeout <seconds>`;return t+"This command has no --timeout option. Retry once; if it keeps timing out, "+"the page or browser bridge is likely stuck — have the user reopen the PublishPort client. "+"The global default can be raised with OPENCLI_BROWSER_COMMAND_TIMEOUT."}function je(e,r){if(!e.args.some((o)=>o.name==="timeout"))return null;const t=r.timeout;if(t===void 0||t===null||t==="")throw new d(`Argument "timeout" must be a positive integer. Received: "${String(t)}"`);const n=Number(t);if(!Number.isInteger(n)||n<=0)throw new d(`Argument "timeout" must be a positive integer. Received: "${String(t)}"`);return n}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "publishport-opencli",
3
- "version": "1.0.55",
3
+ "version": "1.0.57",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "provenance": false