@openyida/yidacli 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/env.js CHANGED
@@ -1 +1 @@
1
- let fs=require("fs"),path=require("path"),os=require("os"),{loadCookieData,resolveBaseUrl,extractInfoFromCookies}=require("./utils"),home=os.homedir();function detectActiveTool(){var o=process.env,e=process.cwd();return o.QODER_IDE||o.QODER_AGENT?{tool:"qoder",displayName:"Qoder",dirName:".qoder",workspaceRoot:path.join(e,"openyida")}:o.CLAUDE_CODE?{tool:"claude-code",displayName:"Claude Code",dirName:".claudecode",workspaceRoot:path.join(e,"openyida")}:o.OPENCODE?{tool:"opencode",displayName:"OpenCode",dirName:".opencode",workspaceRoot:path.join(e,"openyida")}:o.CURSOR_TRACE_ID||(o.VSCODE_GIT_ASKPASS_NODE||"").includes("Cursor")?{tool:"cursor",displayName:"Cursor",dirName:".cursor",workspaceRoot:path.join(e,"openyida")}:o.IFLOW_ACTIVE||o.IFLOW_IDE?{tool:"iflow",displayName:"iFlow",dirName:".iflow",workspaceRoot:path.join(e,"openyida")}:o.AGENT_WORK_ROOT&&o.AGENT_WORK_ROOT.includes(".real")?{tool:"wukong",displayName:"悟空(Wukong)",dirName:".real",workspaceRoot:path.join(home,".real","workspace","openyida")}:"vscode"===o.TERM_PROGRAM?{tool:"aone-copilot",displayName:"Aone Copilot",dirName:".aone_copilot",workspaceRoot:path.join(e,"openyida")}:null}function getInstalledTools(){return[{dirName:".real",displayName:"悟空(Wukong)"},{dirName:".opencode",displayName:"OpenCode"},{dirName:".claudecode",displayName:"Claude Code"},{dirName:".aone_copilot",displayName:"Aone Copilot"},{dirName:".cursor",displayName:"Cursor"},{dirName:".qoder",displayName:"Qoder"},{dirName:".iflow",displayName:"iFlow"}].filter(({dirName:o})=>fs.existsSync(path.join(home,o)))}function detectEnvironment(){let s=detectActiveTool();var o=getInstalledTools();let r=path.join(process.cwd(),"openyida");o=o.map(({dirName:o,displayName:e})=>{var l=".real"===o,a=s&&s.dirName===o,l=l?path.join(home,".real","workspace","openyida"):r;return{displayName:e,dirName:o,isActive:!!a,hasProject:fs.existsSync(l),workspaceRoot:l}});return{activeToolName:s?s.displayName:null,activeProjectRoot:s?s.workspaceRoot:null,results:o}}function detectLoginStatus(o){var e,l,a,o=loadCookieData(o);return o&&o.cookies?({csrfToken:e,corpId:l,userId:a}=extractInfoFromCookies(o.cookies),{loggedIn:!!e,csrfToken:e,corpId:l,userId:a,baseUrl:resolveBaseUrl(o)}):{loggedIn:!1,csrfToken:null,corpId:null,userId:null,baseUrl:null}}function run(){var o="=".repeat(55),{activeToolName:e,activeProjectRoot:l,results:a}=(console.log(o),console.log(" yidacli env - 环境检测"),console.log(o),console.log("\n📋 系统信息"),console.log(` 操作系统: ${process.platform} (${os.arch()})`),console.log(" Node.js: "+process.version),console.log(" 主目录: "+os.homedir()),console.log(" 工作目录: "+process.cwd()),console.log("\n🤖 AI 工具检测"),detectEnvironment());if(0===a.length)console.log(" ⚠️ 未检测到任何已知 AI 工具");else for(var{displayName:s,isActive:r,hasProject:n,workspaceRoot:i}of a){let o,e;e=r&&n?(o="✅","← 当前活跃,项目已就绪"):r&&!n?(o="🟡","← 当前活跃,但无 openyida 项目"):!r&&n?(o="⬜","(已安装,项目存在,但未活跃)"):(o="⬜","(已安装,未活跃)"),console.log(` ${o} ${s.padEnd(18)} `+e)}console.log("\n🎯 当前生效环境"),e&&l?(console.log(" AI 工具: "+e),console.log(" 项目根目录: "+l)):(0<(e=a.filter(o=>o.isActive)).length?console.log(` AI 工具: ${e.map(o=>o.displayName).join(", ")} (活跃,但无 openyida 项目)`):console.log(" AI 工具: 未检测到活跃工具"),console.log(` 项目根目录: ${process.cwd()} (fallback)`)),console.log("\n🔐 登录态检测");a=detectLoginStatus(l||process.cwd());a.loggedIn?(console.log(" 状态: ✅ 已登录"),console.log(" 域名: "+a.baseUrl),console.log(" 组织 ID: "+(a.corpId||"(未知)")),console.log(" 用户 ID: "+(a.userId||"(未知)")),console.log(` csrf_token: ${a.csrfToken.slice(0,16)}...`)):console.log(" 状态: ❌ 未登录(运行 yidacli login 进行登录)"),console.log("\n"+o)}module.exports={run:run,detectEnvironment:detectEnvironment,detectLoginStatus:detectLoginStatus};
1
+ let fs=require("fs"),path=require("path"),os=require("os"),{detectActiveTool,loadCookieData,resolveBaseUrl,extractInfoFromCookies}=require("./utils"),home=os.homedir();function getInstalledTools(){return[{dirName:".real",displayName:"悟空(Wukong)"},{dirName:".opencode",displayName:"OpenCode"},{dirName:".claudecode",displayName:"Claude Code"},{dirName:".aone_copilot",displayName:"Aone Copilot"},{dirName:".cursor",displayName:"Cursor"},{dirName:".qoder",displayName:"Qoder"},{dirName:".iflow",displayName:"iFlow"}].filter(({dirName:o})=>fs.existsSync(path.join(home,o)))}function detectEnvironment(){let n=detectActiveTool();var o=getInstalledTools();let r=path.join(process.cwd(),"openyida");o=o.map(({dirName:o,displayName:e})=>{var l=".real"===o,s=n&&n.dirName===o,l=l?path.join(home,".real","workspace","openyida"):r;return{displayName:e,dirName:o,isActive:!!s,hasProject:fs.existsSync(l),workspaceRoot:l}});return{activeToolName:n?n.displayName:null,activeProjectRoot:n?n.workspaceRoot:null,results:o}}function detectLoginStatus(o){var e,l,s,o=loadCookieData(o);return o&&o.cookies?({csrfToken:e,corpId:l,userId:s}=extractInfoFromCookies(o.cookies),{loggedIn:!!e,csrfToken:e,corpId:l,userId:s,baseUrl:resolveBaseUrl(o)}):{loggedIn:!1,csrfToken:null,corpId:null,userId:null,baseUrl:null}}function run(){var o="=".repeat(55),{activeToolName:e,activeProjectRoot:l,results:s}=(console.log(o),console.log(" yidacli env - 环境检测"),console.log(o),console.log("\n📋 系统信息"),console.log(` 操作系统: ${process.platform} (${os.arch()})`),console.log(" Node.js: "+process.version),console.log(" 主目录: "+os.homedir()),console.log(" 工作目录: "+process.cwd()),console.log("\n🤖 AI 工具检测"),detectEnvironment());if(0===s.length)console.log(" ⚠️ 未检测到任何已知 AI 工具");else for(var{displayName:n,isActive:r,hasProject:a,workspaceRoot:t}of s){let o,e;e=r&&a?(o="✅","← 当前活跃,项目已就绪"):r&&!a?(o="🟡","← 当前活跃,但无 openyida 项目"):!r&&a?(o="⬜","(已安装,项目存在,但未活跃)"):(o="⬜","(已安装,未活跃)"),console.log(` ${o} ${n.padEnd(18)} `+e)}console.log("\n🎯 当前生效环境"),e&&l?(console.log(" AI 工具: "+e),console.log(" 项目根目录: "+l)):(0<(e=s.filter(o=>o.isActive)).length?console.log(` AI 工具: ${e.map(o=>o.displayName).join(", ")} (活跃,但无 openyida 项目)`):console.log(" AI 工具: 未检测到活跃工具"),console.log(` 项目根目录: ${process.cwd()} (fallback)`)),console.log("\n🔐 登录态检测");s=detectLoginStatus(l||process.cwd());s.loggedIn?(console.log(" 状态: ✅ 已登录"),console.log(" 域名: "+s.baseUrl),console.log(" 组织 ID: "+(s.corpId||"(未知)")),console.log(" 用户 ID: "+(s.userId||"(未知)")),console.log(` csrf_token: ${s.csrfToken.slice(0,16)}...`)):console.log(" 状态: ❌ 未登录(运行 yidacli login 进行登录)"),console.log("\n"+o)}module.exports={run:run,detectEnvironment:detectEnvironment,detectLoginStatus:detectLoginStatus};
package/dist/login.js CHANGED
@@ -1,8 +1,9 @@
1
1
  let fs=require("fs"),path=require("path"),os=require("os"),execSync=require("child_process").execSync,{findProjectRoot,extractInfoFromCookies,loadCookieData,resolveBaseUrl}=require("./utils"),DEFAULT_BASE_URL="https://www.aliwork.com",DEFAULT_LOGIN_URL="https://www.aliwork.com/workPlatform";function loadConfig(){var o=findProjectRoot(),o=path.join(o,"config.json");if(fs.existsSync(o))try{return JSON.parse(fs.readFileSync(o,"utf-8"))}catch{}return{loginUrl:DEFAULT_LOGIN_URL,defaultBaseUrl:DEFAULT_BASE_URL}}function saveCookieCache(o,e){var r=findProjectRoot(),r=path.join(r,".cache"),s=path.join(r,"cookies.json");fs.mkdirSync(r,{recursive:!0}),fs.writeFileSync(s,JSON.stringify({cookies:o,base_url:e},null,2),"utf-8"),console.error(" Cookie 已保存到 "+s)}function checkLoginOnly(){var o,e,r,s=loadCookieData();return s&&s.cookies?({csrfToken:r,corpId:o,userId:e}=extractInfoFromCookies(s.cookies),r?{status:"ok",can_auto_use:!0,csrf_token:r,corp_id:o,user_id:e,base_url:r=resolveBaseUrl(s),cookies:s.cookies,message:`✅ 已有有效登录态,可直接使用
2
2
  组织: ${o}
3
3
  用户: ${e}
4
- 域名: `+r}:{status:"not_logged_in",can_auto_use:!1,message:"Cookie 中无 tianshu_csrf_token,需要重新登录"}):{status:"not_logged_in",can_auto_use:!1,message:"本地无 Cookie 缓存,需要扫码登录"}}function refreshCsrfFromCache(){var o=loadCookieData(),{csrfToken:e,corpId:r,userId:s}=(o&&o.cookies||(console.error(" ❌ 本地无有效 Cookie,无法刷新,需要重新登录。"),process.exit(1)),extractInfoFromCookies(o.cookies)),i=(e||(console.error(" ❌ Cookie 中无 tianshu_csrf_token,需要重新登录。"),process.exit(1)),resolveBaseUrl(o));return console.error(` ✅ csrf_token 提取成功: ${e.slice(0,16)}...`),{csrf_token:e,corp_id:r,user_id:s,base_url:i,cookies:o.cookies}}function ensureLogin(){var o=loadCookieData();if(o&&o.cookies){var{csrfToken:e,corpId:r,userId:s}=extractInfoFromCookies(o.cookies);if(e)return console.error("🔍 检测到本地 Cookie,直接使用..."),console.error(` ✅ csrf_token: ${e.slice(0,16)}...`),r&&console.error(" ✅ corpId: "+r),{csrf_token:e,corp_id:r,user_id:s,base_url:resolveBaseUrl(o),cookies:o.cookies}}return interactiveLogin()}function interactiveLogin(){var o=loadConfig().loginUrl||DEFAULT_LOGIN_URL,o=(console.error("\n🔐 正在打开浏览器,请扫码登录..."),console.error(" 登录地址: "+o),`
5
- const { chromium } = require('playwright');
4
+ 域名: `+r}:{status:"not_logged_in",can_auto_use:!1,message:"Cookie 中无 tianshu_csrf_token,需要重新登录"}):{status:"not_logged_in",can_auto_use:!1,message:"本地无 Cookie 缓存,需要扫码登录"}}function refreshCsrfFromCache(){var o=loadCookieData(),{csrfToken:e,corpId:r,userId:s}=(o&&o.cookies||(console.error(" ❌ 本地无有效 Cookie,无法刷新,需要重新登录。"),process.exit(1)),extractInfoFromCookies(o.cookies)),i=(e||(console.error(" ❌ Cookie 中无 tianshu_csrf_token,需要重新登录。"),process.exit(1)),resolveBaseUrl(o));return console.error(` ✅ csrf_token 提取成功: ${e.slice(0,16)}...`),{csrf_token:e,corp_id:r,user_id:s,base_url:i,cookies:o.cookies}}function ensureLogin(){var o=loadCookieData();if(o&&o.cookies){var{csrfToken:e,corpId:r,userId:s}=extractInfoFromCookies(o.cookies);if(e)return console.error("🔍 检测到本地 Cookie,直接使用..."),console.error(` ✅ csrf_token: ${e.slice(0,16)}...`),r&&console.error(" ✅ corpId: "+r),{csrf_token:e,corp_id:r,user_id:s,base_url:resolveBaseUrl(o),cookies:o.cookies}}return interactiveLogin()}function getPlaywrightPath(){try{return require.resolve("playwright")}catch{try{var o=require("child_process").execSync,e=o("npm root -g",{encoding:"utf-8"}).trim(),r=path.join(e,"playwright");if(fs.existsSync(r))return require.resolve(path.join(r,"index.js"))}catch{}}return null}function interactiveLogin(){var o=loadConfig().loginUrl||DEFAULT_LOGIN_URL,e=getPlaywrightPath(),e=(e||(console.error("\n❌ 未找到 playwright 模块,请先安装:"),console.error(" npm install -g playwright"),console.error(" npx playwright install chromium"),process.exit(1)),console.error("\n🔐 正在打开浏览器,请扫码登录..."),console.error(" 登录地址: "+o),`
5
+ const playwright = require(${JSON.stringify(e)});
6
+ const { chromium } = playwright;
6
7
  const { URL } = require('url');
7
8
 
8
9
  (async () => {
@@ -30,5 +31,5 @@ const { URL } = require('url');
30
31
 
31
32
  console.log(JSON.stringify({ cookies, base_url: baseUrl }));
32
33
  })();
33
- `),e=path.join(os.tmpdir(),`yidacli-login-${Date.now()}.js`);fs.writeFileSync(e,o,"utf-8");try{var r=execSync(`node "${e}"`,{encoding:"utf-8",stdio:["inherit","pipe","inherit"],timeout:66e4}).trim().split("\n"),s=r[r.length-1],i=JSON.parse(s),{csrfToken:t,corpId:c,userId:n}=extractInfoFromCookies(i.cookies);return t||(console.error(" ❌ 登录成功但 Cookie 中无 tianshu_csrf_token,请重试。"),process.exit(1)),saveCookieCache(i.cookies,i.base_url),console.error(` ✅ csrf_token: ${t.slice(0,16)}...`),c&&console.error(" ✅ corpId: "+c),{csrf_token:t,corp_id:c,user_id:n,base_url:i.base_url,cookies:i.cookies}}finally{try{fs.unlinkSync(e)}catch{}}}function logout(){console.error("=".repeat(50)),console.error(" yidacli logout - 宜搭退出登录工具"),console.error("=".repeat(50));var o=findProjectRoot(),o=path.join(o,".cache","cookies.json");console.error(`
34
+ `),o=path.join(os.tmpdir(),`yidacli-login-${Date.now()}.js`);fs.writeFileSync(o,e,"utf-8");try{var r=execSync(`node "${o}"`,{encoding:"utf-8",stdio:["inherit","pipe","inherit"],timeout:66e4}).trim().split("\n"),s=r[r.length-1],i=JSON.parse(s),{csrfToken:t,corpId:n,userId:c}=extractInfoFromCookies(i.cookies);return t||(console.error(" ❌ 登录成功但 Cookie 中无 tianshu_csrf_token,请重试。"),process.exit(1)),saveCookieCache(i.cookies,i.base_url),console.error(` ✅ csrf_token: ${t.slice(0,16)}...`),n&&console.error(" ✅ corpId: "+n),{csrf_token:t,corp_id:n,user_id:c,base_url:i.base_url,cookies:i.cookies}}finally{try{fs.unlinkSync(o)}catch{}}}function logout(){console.error("=".repeat(50)),console.error(" yidacli logout - 宜搭退出登录工具"),console.error("=".repeat(50));var o=findProjectRoot(),o=path.join(o,".cache","cookies.json");console.error(`
34
35
  Cookie 文件: `+o),fs.existsSync(o)?(fs.writeFileSync(o,"","utf-8"),console.error(" ✅ 已清空 Cookie,登录态已失效。"),console.error(" 下次调用 yidacli login 时将重新触发扫码登录。")):console.error(" ℹ️ Cookie 文件不存在,无需清空。"),console.error("=".repeat(50))}module.exports={ensureLogin:ensureLogin,checkLoginOnly:checkLoginOnly,refreshCsrfFromCache:refreshCsrfFromCache,interactiveLogin:interactiveLogin,logout:logout};
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- let fs=require("fs"),path=require("path"),os=require("os"),execSync=require("child_process").execSync;function isWukongActive(){var e=path.join(os.homedir(),".real");return fs.existsSync(path.join(e,"daemon.sock"))||fs.existsSync(path.join(e,".mcp"))||fs.existsSync(path.join(e,".skills"))}function findProjectRoot(){var e=os.homedir();if(isWukongActive()){e=path.join(e,".real","workspace","openyida");if(fs.existsSync(e))return e}e=path.join(process.cwd(),"openyida");return fs.existsSync(e)?e:process.cwd()}function extractInfoFromCookies(e){let r=null,o=null,t=null;for(var s of e){var n;"tianshu_csrf_token"===s.name?r=s.value:"tianshu_corp_user"===s.name&&0<(n=s.value.lastIndexOf("_"))&&(o=s.value.slice(0,n),t=s.value.slice(n+1))}return{csrfToken:r,corpId:o,userId:t}}function loadCookieData(r,o){r=r||findProjectRoot(),o=o||"https://www.aliwork.com",r=path.join(r,".cache","cookies.json");if(!fs.existsSync(r))return null;try{var t=fs.readFileSync(r,"utf-8").trim();if(!t)return null;var s,n,i,a=JSON.parse(t);let e;return(e=Array.isArray(a)?{cookies:a,base_url:o}:a).cookies&&0<e.cookies.length&&({csrfToken:s,corpId:n,userId:i}=extractInfoFromCookies(e.cookies),s&&(e.csrf_token=s),n&&(e.corp_id=n),i)&&(e.user_id=i),e}catch{return null}}function triggerLogin(){console.error("\n🔐 登录态失效,正在打开浏览器扫码登录...\n");var e=require("./login").ensureLogin;return e()}function refreshCsrfToken(){console.error("\n🔄 csrf_token 已过期,正在从 Cookie 重新提取...\n");var e=require("./login").refreshCsrfFromCache;return e()}function isLoginExpired(e){return e&&!1===e.success&&("307"===e.errorCode||"302"===e.errorCode)}function isCsrfTokenExpired(e){return e&&!1===e.success&&"TIANSHU_000030"===e.errorCode}function resolveBaseUrl(e,r){r=r||"https://www.aliwork.com";return(e&&e.base_url||r).replace(/\/+$/,"")}function httpPost(a,c,u,l){let f=require("https"),p=require("http");return new Promise((t,e)=>{var r=l.map(e=>e.name+"="+e.value).join("; "),o=new URL(a),s="https:"===o.protocol,n=s?f:p,o={hostname:o.hostname,port:o.port||(s?443:80),path:c,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(u),Origin:a,Referer:a+"/",Cookie:r},timeout:3e4};let i=n.request(o,r=>{let o="";r.on("data",e=>{o+=e}),r.on("end",()=>{console.error(" HTTP 状态码: "+r.statusCode);try{var e=JSON.parse(o);isLoginExpired(e)?t({__needLogin:!0}):isCsrfTokenExpired(e)?t({__csrfExpired:!0}):t(e)}catch{console.error(" 响应内容: "+o.substring(0,500)),t({success:!1,errorMsg:`HTTP ${r.statusCode}: 响应非 JSON`})}})});i.on("timeout",()=>{i.destroy(),e(new Error("请求超时"))}),i.on("error",e),i.write(u),i.end()})}function httpGet(c,u,l,f){let p=require("https"),d=require("http"),h=require("querystring");return new Promise((t,e)=>{var r=f.map(e=>e.name+"="+e.value).join("; "),o=new URL(c),s="https:"===o.protocol,n=s?p:d,i=l?u+"?"+h.stringify(l):u;let a=n.request({hostname:o.hostname,port:o.port||(s?443:80),path:i,method:"GET",headers:{Origin:c,Referer:c+"/",Cookie:r},timeout:3e4},r=>{let o="";r.on("data",e=>{o+=e}),r.on("end",()=>{console.error(" HTTP 状态码: "+r.statusCode);try{var e=JSON.parse(o);isLoginExpired(e)?t({__needLogin:!0}):isCsrfTokenExpired(e)?t({__csrfExpired:!0}):t(e)}catch{console.error(" 响应内容: "+o.substring(0,500)),t({success:!1,errorMsg:`HTTP ${r.statusCode}: 响应非 JSON`})}})});a.on("timeout",()=>{a.destroy(),e(new Error("请求超时"))}),a.on("error",e),a.end()})}async function requestWithAutoLogin(e,r){let o=await e(r);var t;return o&&o.__csrfExpired&&(t=refreshCsrfToken(),r.cookieData=t,r.csrfToken=t.csrf_token,r.cookies=t.cookies,r.baseUrl=resolveBaseUrl(t),console.error(" 🔄 csrf_token 已刷新,重试..."),o=await e(r)),o&&o.__needLogin&&(t=triggerLogin(),r.cookieData=t,r.csrfToken=t.csrf_token,r.cookies=t.cookies,r.baseUrl=resolveBaseUrl(t),console.error(" 🔄 重新登录后重试..."),o=await e(r)),o}module.exports={findProjectRoot:findProjectRoot,extractInfoFromCookies:extractInfoFromCookies,loadCookieData:loadCookieData,triggerLogin:triggerLogin,refreshCsrfToken:refreshCsrfToken,resolveBaseUrl:resolveBaseUrl,isLoginExpired:isLoginExpired,isCsrfTokenExpired:isCsrfTokenExpired,httpPost:httpPost,httpGet:httpGet,requestWithAutoLogin:requestWithAutoLogin};
1
+ let fs=require("fs"),path=require("path"),os=require("os"),execSync=require("child_process").execSync;function detectActiveTool(){var e=process.env,o=process.cwd(),r=os.homedir();return e.QODER_IDE||e.QODER_AGENT?{tool:"qoder",displayName:"Qoder",dirName:".qoder",workspaceRoot:path.join(o,"openyida")}:e.CLAUDE_CODE?{tool:"claude-code",displayName:"Claude Code",dirName:".claudecode",workspaceRoot:path.join(o,"openyida")}:e.OPENCODE?{tool:"opencode",displayName:"OpenCode",dirName:".opencode",workspaceRoot:path.join(o,"openyida")}:e.CURSOR_TRACE_ID||(e.VSCODE_GIT_ASKPASS_NODE||"").includes("Cursor")?{tool:"cursor",displayName:"Cursor",dirName:".cursor",workspaceRoot:path.join(o,"openyida")}:e.IFLOW_ACTIVE||e.IFLOW_IDE?{tool:"iflow",displayName:"iFlow",dirName:".iflow",workspaceRoot:path.join(o,"openyida")}:e.AGENT_WORK_ROOT&&e.AGENT_WORK_ROOT.includes(".real")?{tool:"wukong",displayName:"悟空(Wukong)",dirName:".real",workspaceRoot:path.join(r,".real","workspace","openyida")}:"vscode"===e.TERM_PROGRAM?{tool:"aone-copilot",displayName:"Aone Copilot",dirName:".aone_copilot",workspaceRoot:path.join(o,"openyida")}:null}function findProjectRoot(){var e=detectActiveTool();return e&&fs.existsSync(e.workspaceRoot)?e.workspaceRoot:process.cwd()}function extractInfoFromCookies(e){let o=null,r=null,t=null;for(var n of e){var s;"tianshu_csrf_token"===n.name?o=n.value:"tianshu_corp_user"===n.name&&0<(s=n.value.lastIndexOf("_"))&&(r=n.value.slice(0,s),t=n.value.slice(s+1))}return{csrfToken:o,corpId:r,userId:t}}function loadCookieData(o,r){o=o||findProjectRoot(),r=r||"https://www.aliwork.com",o=path.join(o,".cache","cookies.json");if(!fs.existsSync(o))return null;try{var t=fs.readFileSync(o,"utf-8").trim();if(!t)return null;var n,s,i,a=JSON.parse(t);let e;return(e=Array.isArray(a)?{cookies:a,base_url:r}:a).cookies&&0<e.cookies.length&&({csrfToken:n,corpId:s,userId:i}=extractInfoFromCookies(e.cookies),n&&(e.csrf_token=n),s&&(e.corp_id=s),i)&&(e.user_id=i),e}catch{return null}}function triggerLogin(){console.error("\n🔐 登录态失效,正在打开浏览器扫码登录...\n");var e=require("./login").ensureLogin;return e()}function refreshCsrfToken(){console.error("\n🔄 csrf_token 已过期,正在从 Cookie 重新提取...\n");var e=require("./login").refreshCsrfFromCache;return e()}function isLoginExpired(e){return e&&!1===e.success&&("307"===e.errorCode||"302"===e.errorCode)}function isCsrfTokenExpired(e){return e&&!1===e.success&&"TIANSHU_000030"===e.errorCode}function resolveBaseUrl(e,o){o=o||"https://www.aliwork.com";return(e&&e.base_url||o).replace(/\/+$/,"")}function httpPost(a,c,l,u){let d=require("https"),p=require("http");return new Promise((t,e)=>{var o=u.map(e=>e.name+"="+e.value).join("; "),r=new URL(a),n="https:"===r.protocol,s=n?d:p,r={hostname:r.hostname,port:r.port||(n?443:80),path:c,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l),Origin:a,Referer:a+"/",Cookie:o},timeout:3e4};let i=s.request(r,o=>{let r="";o.on("data",e=>{r+=e}),o.on("end",()=>{console.error(" HTTP 状态码: "+o.statusCode);try{var e=JSON.parse(r);isLoginExpired(e)?t({__needLogin:!0}):isCsrfTokenExpired(e)?t({__csrfExpired:!0}):t(e)}catch{console.error(" 响应内容: "+r.substring(0,500)),t({success:!1,errorMsg:`HTTP ${o.statusCode}: 响应非 JSON`})}})});i.on("timeout",()=>{i.destroy(),e(new Error("请求超时"))}),i.on("error",e),i.write(l),i.end()})}function httpGet(c,l,u,d){let p=require("https"),f=require("http"),h=require("querystring");return new Promise((t,e)=>{var o=d.map(e=>e.name+"="+e.value).join("; "),r=new URL(c),n="https:"===r.protocol,s=n?p:f,i=u?l+"?"+h.stringify(u):l;let a=s.request({hostname:r.hostname,port:r.port||(n?443:80),path:i,method:"GET",headers:{Origin:c,Referer:c+"/",Cookie:o},timeout:3e4},o=>{let r="";o.on("data",e=>{r+=e}),o.on("end",()=>{console.error(" HTTP 状态码: "+o.statusCode);try{var e=JSON.parse(r);isLoginExpired(e)?t({__needLogin:!0}):isCsrfTokenExpired(e)?t({__csrfExpired:!0}):t(e)}catch{console.error(" 响应内容: "+r.substring(0,500)),t({success:!1,errorMsg:`HTTP ${o.statusCode}: 响应非 JSON`})}})});a.on("timeout",()=>{a.destroy(),e(new Error("请求超时"))}),a.on("error",e),a.end()})}async function requestWithAutoLogin(e,o){let r=await e(o);var t;return r&&r.__csrfExpired&&(t=refreshCsrfToken(),o.cookieData=t,o.csrfToken=t.csrf_token,o.cookies=t.cookies,o.baseUrl=resolveBaseUrl(t),console.error(" 🔄 csrf_token 已刷新,重试..."),r=await e(o)),r&&r.__needLogin&&(t=triggerLogin(),o.cookieData=t,o.csrfToken=t.csrf_token,o.cookies=t.cookies,o.baseUrl=resolveBaseUrl(t),console.error(" 🔄 重新登录后重试..."),r=await e(o)),r}module.exports={detectActiveTool:detectActiveTool,findProjectRoot:findProjectRoot,extractInfoFromCookies:extractInfoFromCookies,loadCookieData:loadCookieData,triggerLogin:triggerLogin,refreshCsrfToken:refreshCsrfToken,resolveBaseUrl:resolveBaseUrl,isLoginExpired:isLoginExpired,isCsrfTokenExpired:isCsrfTokenExpired,httpPost:httpPost,httpGet:httpGet,requestWithAutoLogin:requestWithAutoLogin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openyida/yidacli",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "宜搭 CLI 工具 - 宜搭平台应用、页面、表单的命令行管理工具",
5
5
  "main": "bin/yidacli.js",
6
6
  "bin": {