yuque-dl 1.0.35 → 1.0.39

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/cjs/cli.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("node:fs"),r=require("cac"),o=require("semver"),i=require("./index-327317a7.js");require("node:fs/promises"),require("pull-md-img"),require("ora"),require("markdown-toc"),require("cli-progress"),require("log4js"),require("axios"),require("rand-user-agent"),require("pako");var n="undefined"!=typeof document?document.currentScript:null;const s=r.cac("yuque-dl"),{version:t,engines:c}=JSON.parse(e.readFileSync(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:n&&n.src||new URL("cli.js",document.baseURI).href)).toString());!function(){const e=c.node;o.satisfies(process.version,e)||(i.logger.error(`✕ nodejs 版本需 ${e}, 当前版本为 ${process.version}`),process.exit(1))}(),s.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(e,r)=>{try{await i.main(e,r)}catch(e){i.logger.error(e.message||"unknown exception")}})),s.help(),s.version(t);try{s.parse()}catch(e){i.logger.error(e.message||"unknown exception"),process.exit(1)}
1
+ "use strict";var e=require("node:fs"),r=require("cac"),o=require("semver"),i=require("./index-93941526.js");require("node:fs/promises"),require("node:path"),require("pull-md-img"),require("ora"),require("markdown-toc"),require("cli-progress"),require("log4js"),require("axios"),require("rand-user-agent"),require("pako"),require("node:crypto");var n="undefined"!=typeof document?document.currentScript:null;const s=r.cac("yuque-dl"),{version:t,engines:u}=JSON.parse(e.readFileSync(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:n&&n.src||new URL("cli.js",document.baseURI).href)).toString());!function(){const e=u.node;o.satisfies(process.version,e)||(i.logger.error(`✕ nodejs 版本需 ${e}, 当前版本为 ${process.version}`),process.exit(1))}(),s.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(e,r)=>{try{await i.main(e,r)}catch(e){i.logger.error(e.message||"unknown exception")}})),s.help(),s.version(t);try{s.parse()}catch(e){i.logger.error(e.message||"unknown exception"),process.exit(1)}
@@ -0,0 +1 @@
1
+ "use strict";var e=require("node:fs/promises"),t=require("node:path"),r=require("pull-md-img"),o=require("ora"),s=require("markdown-toc"),i=require("cli-progress"),n=require("log4js"),a=require("axios"),c=require("rand-user-agent"),l=require("pako"),u=require("node:crypto");var h,p,d=(n.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),n.getLogger("yuque-dl"));class f{constructor(e,t){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=e,this.progressFilePath=`${e}/progress.json`,this.total=t}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,d.info("根据上次数据继续断点下载")),this.bar=new i.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},i.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let t=[];try{const r=await e.readFile(this.progressFilePath,{encoding:"utf8"});t=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await e.writeFile(this.progressFilePath,JSON.stringify(t),{encoding:"utf8"})}return t}async updateProgress(t,r){this.curr=this.curr+1,r&&(this.progressInfo.push(t),await e.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log("")))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(e){if(!(e<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let t=0;t<e;t++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}class g{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:r,bookPath:o,uuidMap:s}=this.summaryInfo;let i=`# ${t}\n\n`;r&&(i+=`> ${r}\n\n`);let n=i;const a=[];s.forEach((e=>{const t=e.toc,r=t.parent_uuid,o=this.findTree(a,r),s={text:t.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:t.uuid,level:1,type:""},i=t.type.toLocaleLowerCase();"title"===i||""!==t.child_uuid?(s.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s))):(s.type="link",s.link="link"===i?e.toc.url:e.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s)))}));n+=this.genSummaryContent(a,"");try{await e.writeFile(`${o}/SUMMARY.md`,n)}catch(e){d.error("Generate Summary Error")}}genSummaryContent(e,t){for(const r of e){if("title"===r.type)t+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if("link"===r.type){const e=r.link?r.link.replace(/\s/g,"%20"):r.link;t+=`- [${r.text}](${e})\n`}Array.isArray(r.children)&&(t+=this.genSummaryContent(r.children,""))}return t}findIdItem(e,t){if(e.id===t)return e;if(e.children){const r=this.findTree(e.children,t);if(r)return r}return!1}findTree(e,t){if(!t)return!1;for(const r of e){const e=this.findIdItem(r,t);if(e)return e}return!1}}!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(h||(h={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(p||(p={}));const m=new Map([[p.BOARD,"画板类型"],[p.TABLE,"数据表类型"],[p.SHEET,"表格类型"],[p.DOC,"文档类型"]]),w="_yuque_session",$="https://www.yuque.com",k="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD";function y({browser:e="chrome",os:t="mac os",device:r="desktop"}){r=r.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let o=c(r,e,t);if("chrome"===e)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=c(r,e,t);if("safari"===e)for(;o.includes("Applebot");)o=c(r,e,t);return o}function b(e){const{key:t=w,token:r}=e,o={"user-agent":y({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${t}=${r};`),o}function I(e){return{headers:b(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...b(e)}}}}const L=(e,t=!0)=>{const{articleUrl:r,bookId:o,token:s,key:i,host:n=$}=e;let c=`${n}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};t&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,a.get(c,I({token:s,key:i})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))},S=e=>{if(!e)return"";const t=JSON.parse(l.inflate(e,{to:"string"}));let r="";return t.forEach((e=>{const t=`## ${e.name}\n`,o=function(e){let t=Object.keys(e);t=t.filter((t=>Object.keys(e[t]).some((r=>e?.[t]?.[r]?.v))));let r=[];t.forEach((t=>{const o=e[t];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...t.map((e=>Number(e)))),s=Math.max(...r.map((e=>Number(e))));if(o<0||s<0)return"";let i="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(s+1).fill(" ").map(((e,t)=>{const r=t%n.length;return n[r]})).join(" | ");a=`| |${a}|`;let c=Array(s+2).fill("---").join(" |");c=`|${c}|`,i=`${a}\n${c}\n`;for(let t=0;t<o+1;t++){const r=[];for(let o=0;o<s+1;o++){const s=e?.[t]?.[o]?.v||null;s&&"string"==typeof s?r.push(s):s&&"object"==typeof s?"image"===s?.class&&s?.src?r.push(`![${s?.name}'](${s?.src})`):"checkbox"===s?.class?r.push(s?.value?"[x] ":"[ ] "):"link"===s?.class?r.push(`[${s?.text}](${s?.url})`):"select"===s?.class&&r.push(s?.value?.join(",")):r.push(null)}i=`${i}${`| ${t+1} | ${r.join(" | ")}|`}\n`}return i}(e.data);r=`${r}\n${t}\n${o}`})),r};function v(e,t=[]){if(!function(e,t){try{const{host:r,pathname:o}=new URL(e);return!t.includes(r)&&Boolean(o)}catch(e){return!1}}(e,t))return e;let r=e;try{const{origin:e,pathname:t}=new URL(r);r=`${e}${t}`}catch(t){return e}return`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(r)}&sign=${function(e){const t=u.createHash("sha256");return t.update(`${k}${e}`),t.digest("hex")}(r)}`}async function E(t){const{articleInfo:i,progressBar:n,options:a}=t,{token:c,key:l}=a,{bookId:u,itemUrl:h,savePath:d,saveFilePath:f,uuid:g,articleUrl:w,articleTitle:$,ignoreImg:k,host:y,imageServiceDomains:b}=i,{httpStatus:I,apiUrl:E,response:P}=await L({articleUrl:h,bookId:u,token:c,host:y,key:l}),T=P?.data?.type?.toLocaleLowerCase();let D="";if(T===p.SHEET){const{response:e}=await L({articleUrl:h,bookId:u,token:c,host:y,key:l},!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},o=r?.sheet;D=o?S(o):""}catch(e){const t=m.get(T);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([p.BOARD,p.TABLE].includes(T)){const e=m.get(T);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof P?.data?.sourcecode)throw new Error(`download article Error: ${E}, http status ${I}`);D=P.data.sourcecode}if(!k){n.pause(),console.log("");const t=o({text:`下载 "${$}" 的图片中...`});t.start();try{D=await r.run(D,{dist:d,imgDir:`./img/${g}`,isIgnoreConsole:!0,referer:w||"",transform:e=>v(e,b)})}catch(t){let r=`图片下载失败(md的图片按远程url保存): ${t.message}`;throw t.error&&t.url&&(r=`图片下载失败(md的图片按远程url保存) ${t.url}: ${t.error?.message}`),await e.writeFile(f,U(D)),new Error(r)}finally{t.stop(),n.continue()}}function U(e){let t=e;t=t.replace(/<br(\s?)\/>/gm,"\n"),t=t.replace(/<a.*?>(\s*?)<\/a>/gm,"");const r=$?`# ${$}\n\n`:"";let o=a.ignoreToc?"":s(t).content;o&&(o=`${o}\n\n---\n\n`);return t=`${r}${o}${t}${w?`\n\n> 原文: <${w}>`:""}`,t}try{return await e.writeFile(f,U(D)),!0}catch(e){throw new Error(`download article Error ${w}: ${e.message}`)}}function P(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}exports.downloadArticle=E,exports.logger=d,exports.main=async function(r,o){const{bookId:s,tocList:i,bookName:n,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:p}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return a.get(e,I(t)).then((({data:e="",status:t})=>200===t?e:"")).then((e=>{const t=r.exec(e)??"";if(!t[1])return{};const o=JSON.parse(decodeURIComponent(t[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||$,imageServiceDomains:o.imageServiceDomains||[]}:{}}))})(r,{token:o.token,key:o.key});if(!s)throw new Error("No found book id");if(!i||0===i.length)throw new Error("No found toc list");const m=t.resolve(o.distDir,n?P(n):String(s));await e.mkdir(m,{recursive:!0});const w=i.length,k=new f(m,w);if(await k.init(),k.curr===w)return k.bar&&k.bar.stop(),void d.info(`√ 已完成: ${m}`);const y=new Map;k.isDownloadInterrupted&&k.progressInfo.forEach((e=>{y.set(e.toc.uuid,e)}));const b=r.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(t){const{articleUrlPrefix:r,total:o,uuidMap:s,tocList:i,bookPath:n,bookId:a,progressBar:c,host:l,options:u,imageServiceDomains:p=[]}=t;let f=0,g=0,m=0;const w=[],$=[];for(let t=0;t<o;t++){const o=i[t];if("string"!=typeof o.type)continue;if(s.get(o.uuid))continue;const d=o.type.toLocaleLowerCase();if(d===h.TITLE||""!==o.child_uuid||d===h.LINK){let t=o;const r=[],i=[];for(;t;)r.unshift(P(t.title)),i.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const a={path:r.join("/"),pathTitleList:r,pathIdList:i,toc:o};d===h.LINK?(m+=1,$.push(a)):await e.mkdir(`${n}/${r.join("/")}`,{recursive:!0}),s.set(o.uuid,a),await c.updateProgress(a,d!==h.LINK)}else if(o.url){g+=1;let e={path:"",pathTitleList:[],pathIdList:[]};s.get(o.parent_uuid)&&(e=s.get(o.parent_uuid));const t=P(o.title),i=[...e.pathTitleList,`${t}.md`],h=[...e.pathIdList,o.uuid],d={path:i.join("/"),pathTitleList:i,pathIdList:h,toc:o};let m=!0;const $=`${r}/${o.url}`;try{const t={bookId:a,itemUrl:o.url,savePath:`${n}/${e.path}`,saveFilePath:`${n}/${d.path}`,uuid:o.uuid,articleUrl:$,articleTitle:o.title,ignoreImg:u.ignoreImg,host:l,imageServiceDomains:p};await E({articleInfo:t,progressBar:c,options:u})}catch(e){m=!1,f+=1,w.push({articleUrl:$,errItem:d,errMsg:e.message,err:e})}s.set(o.uuid,d),await c.updateProgress(d,m)}}if(m>0){d.warn("该知识库存在以下外链文章");for(const e of $)d.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(f>0){d.error(`本次执行总数${g}篇,✕ 失败${f}篇`);for(const e of w)d.error(`${e.errItem.path} ———— ${e.articleUrl}`),d.error(`———— ✕ ${e.errMsg}`);d.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:b,total:w,uuidMap:y,tocList:i,bookPath:m,bookId:s,progressBar:k,host:u,options:o,imageServiceDomains:p});const L=new g({bookPath:m,bookName:n,bookDesc:c,uuidMap:y});await L.genFile(),d.info(`√ 生成目录 ${m}/SUMMARY.md`),k.curr===w&&d.info(`√ 已完成: ${m}`),process.exit(0)};
package/dist/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";require("node:fs/promises"),require("pull-md-img"),require("ora"),require("markdown-toc");var r=require("./index-327317a7.js");require("cli-progress"),require("log4js"),require("axios"),require("rand-user-agent"),require("pako"),exports.downloadArticle=r.downloadArticle,exports.main=r.main;
1
+ "use strict";require("node:fs/promises"),require("node:path"),require("pull-md-img"),require("ora"),require("markdown-toc");var r=require("./index-93941526.js");require("cli-progress"),require("log4js"),require("axios"),require("rand-user-agent"),require("pako"),require("node:crypto"),exports.downloadArticle=r.downloadArticle,exports.main=r.main;
package/dist/es/cli.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as o}from"node:fs";import{cac as e}from"cac";import r from"semver";import{m as i,l as t}from"./index-6d8832a0.js";import"node:fs/promises";import"pull-md-img";import"ora";import"markdown-toc";import"cli-progress";import"log4js";import"axios";import"rand-user-agent";import"pako";const n=e("yuque-dl"),{version:s,engines:p}=JSON.parse(o(new URL("../../package.json",import.meta.url)).toString());!function(){const o=p.node;r.satisfies(process.version,o)||(t.error(`✕ nodejs 版本需 ${o}, 当前版本为 ${process.version}`),process.exit(1))}(),n.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(o,e)=>{try{await i(o,e)}catch(o){t.error(o.message||"unknown exception")}})),n.help(),n.version(s);try{n.parse()}catch(o){t.error(o.message||"unknown exception"),process.exit(1)}
1
+ import{readFileSync as o}from"node:fs";import{cac as e}from"cac";import r from"semver";import{m as t,l as i}from"./index-b284aad1.js";import"node:fs/promises";import"node:path";import"pull-md-img";import"ora";import"markdown-toc";import"cli-progress";import"log4js";import"axios";import"rand-user-agent";import"pako";import"node:crypto";const n=e("yuque-dl"),{version:s,engines:p}=JSON.parse(o(new URL("../../package.json",import.meta.url)).toString());!function(){const o=p.node;r.satisfies(process.version,o)||(i.error(`✕ nodejs 版本需 ${o}, 当前版本为 ${process.version}`),process.exit(1))}(),n.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(o,e)=>{try{await t(o,e)}catch(o){i.error(o.message||"unknown exception")}})),n.help(),n.version(s);try{n.parse()}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}
@@ -0,0 +1 @@
1
+ import t,{writeFile as e,mkdir as r}from"node:fs/promises";import o from"node:path";import s from"pull-md-img";import n from"ora";import i from"markdown-toc";import a from"cli-progress";import c from"log4js";import l from"axios";import u from"rand-user-agent";import h from"pako";import p from"node:crypto";var d,f,m=(c.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),c.getLogger("yuque-dl"));class g{constructor(t,e){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=t,this.progressFilePath=`${t}/progress.json`,this.total=e}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,m.info("根据上次数据继续断点下载")),this.bar=new a.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},a.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const r=await t.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await t.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,r){this.curr=this.curr+1,r&&(this.progressInfo.push(e),await t.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log("")))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(t){if(!(t<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let e=0;e<t;e++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}class ${constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:s}=this.summaryInfo;let n=`# ${e}\n\n`;r&&(n+=`> ${r}\n\n`);let i=n;const a=[];s.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(a,r),s={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:""},n=e.type.toLocaleLowerCase();"title"===n||""!==e.child_uuid?(s.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s))):(s.type="link",s.link="link"===n?t.toc.url:t.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s)))}));i+=this.genSummaryContent(a,"");try{await t.writeFile(`${o}/SUMMARY.md`,i)}catch(t){m.error("Generate Summary Error")}}genSummaryContent(t,e){for(const r of t){if("title"===r.type)e+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if("link"===r.type){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`- [${r.text}](${t})\n`}Array.isArray(r.children)&&(e+=this.genSummaryContent(r.children,""))}return e}findIdItem(t,e){if(t.id===e)return t;if(t.children){const r=this.findTree(t.children,e);if(r)return r}return!1}findTree(t,e){if(!e)return!1;for(const r of t){const t=this.findIdItem(r,e);if(t)return t}return!1}}!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(d||(d={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(f||(f={}));const w=new Map([[f.BOARD,"画板类型"],[f.TABLE,"数据表类型"],[f.SHEET,"表格类型"],[f.DOC,"文档类型"]]),k="_yuque_session",y="https://www.yuque.com",b="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD";function I({browser:t="chrome",os:e="mac os",device:r="desktop"}){r=r.toLowerCase(),t=t.toLowerCase(),e=e.toLowerCase();let o=u(r,t,e);if("chrome"===t)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=u(r,t,e);if("safari"===t)for(;o.includes("Applebot");)o=u(r,t,e);return o}function L(t){const{key:e=k,token:r}=t,o={"user-agent":I({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function S(t){return{headers:L(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...L(t)}}}}const v=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:s,key:n,host:i=y}=t;let a=`${i}/api/docs/${r}`;const c={book_id:String(o),merge_dynamic_data:String(!1)};e&&(c.mode="markdown");const u=new URLSearchParams(c).toString();return a=`${a}?${u}`,l.get(a,S({token:s,key:n})).then((({data:t,status:e})=>({apiUrl:a,httpStatus:e,response:t})))},E=t=>{if(!t)return"";const e=JSON.parse(h.inflate(t,{to:"string"}));let r="";return e.forEach((t=>{const e=`## ${t.name}\n`,o=function(t){let e=Object.keys(t);e=e.filter((e=>Object.keys(t[e]).some((r=>t?.[e]?.[r]?.v))));let r=[];e.forEach((e=>{const o=t[e];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...e.map((t=>Number(t)))),s=Math.max(...r.map((t=>Number(t))));if(o<0||s<0)return"";let n="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(s+1).fill(" ").map(((t,e)=>{const r=e%i.length;return i[r]})).join(" | ");a=`| |${a}|`;let c=Array(s+2).fill("---").join(" |");c=`|${c}|`,n=`${a}\n${c}\n`;for(let e=0;e<o+1;e++){const r=[];for(let o=0;o<s+1;o++){const s=t?.[e]?.[o]?.v||null;s&&"string"==typeof s?r.push(s):s&&"object"==typeof s?"image"===s?.class&&s?.src?r.push(`![${s?.name}'](${s?.src})`):"checkbox"===s?.class?r.push(s?.value?"[x] ":"[ ] "):"link"===s?.class?r.push(`[${s?.text}](${s?.url})`):"select"===s?.class&&r.push(s?.value?.join(",")):r.push(null)}n=`${n}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return n}(t.data);r=`${r}\n${e}\n${o}`})),r};function P(t,e=[]){if(!function(t,e){try{const{host:r,pathname:o}=new URL(t);return!e.includes(r)&&Boolean(o)}catch(t){return!1}}(t,e))return t;let r=t;try{const{origin:t,pathname:e}=new URL(r);r=`${t}${e}`}catch(e){return t}return`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(r)}&sign=${function(t){const e=p.createHash("sha256");return e.update(`${b}${t}`),e.digest("hex")}(r)}`}async function T(t){const{articleInfo:r,progressBar:o,options:a}=t,{token:c,key:l}=a,{bookId:u,itemUrl:h,savePath:p,saveFilePath:d,uuid:m,articleUrl:g,articleTitle:$,ignoreImg:k,host:y,imageServiceDomains:b}=r,{httpStatus:I,apiUrl:L,response:S}=await v({articleUrl:h,bookId:u,token:c,host:y,key:l}),T=S?.data?.type?.toLocaleLowerCase();let D="";if(T===f.SHEET){const{response:t}=await v({articleUrl:h,bookId:u,token:c,host:y,key:l},!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;D=o?E(o):""}catch(t){const e=w.get(T);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([f.BOARD,f.TABLE].includes(T)){const t=w.get(T);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof S?.data?.sourcecode)throw new Error(`download article Error: ${L}, http status ${I}`);D=S.data.sourcecode}if(!k){o.pause(),console.log("");const t=n({text:`下载 "${$}" 的图片中...`});t.start();try{D=await s.run(D,{dist:p,imgDir:`./img/${m}`,isIgnoreConsole:!0,referer:g||"",transform:t=>P(t,b)})}catch(t){let r=`图片下载失败(md的图片按远程url保存): ${t.message}`;throw t.error&&t.url&&(r=`图片下载失败(md的图片按远程url保存) ${t.url}: ${t.error?.message}`),await e(d,U(D)),new Error(r)}finally{t.stop(),o.continue()}}function U(t){let e=t;e=e.replace(/<br(\s?)\/>/gm,"\n"),e=e.replace(/<a.*?>(\s*?)<\/a>/gm,"");const r=$?`# ${$}\n\n`:"";let o=a.ignoreToc?"":i(e).content;o&&(o=`${o}\n\n---\n\n`);return e=`${r}${o}${e}${g?`\n\n> 原文: <${g}>`:""}`,e}try{return await e(d,U(D)),!0}catch(t){throw new Error(`download article Error ${g}: ${t.message}`)}}function D(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}async function U(t,e){const{bookId:s,tocList:n,bookName:i,bookDesc:a,bookSlug:c,host:u,imageServiceDomains:h}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return l.get(t,S(e)).then((({data:t="",status:e})=>200===e?t:"")).then((t=>{const e=r.exec(t)??"";if(!e[1])return{};const o=JSON.parse(decodeURIComponent(e[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||y,imageServiceDomains:o.imageServiceDomains||[]}:{}}))})(t,{token:e.token,key:e.key});if(!s)throw new Error("No found book id");if(!n||0===n.length)throw new Error("No found toc list");const p=o.resolve(e.distDir,i?D(i):String(s));await r(p,{recursive:!0});const f=n.length,w=new g(p,f);if(await w.init(),w.curr===f)return w.bar&&w.bar.stop(),void m.info(`√ 已完成: ${p}`);const k=new Map;w.isDownloadInterrupted&&w.progressInfo.forEach((t=>{k.set(t.toc.uuid,t)}));const b=t.replace(new RegExp(`(.*?/${c}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:o,uuidMap:s,tocList:n,bookPath:i,bookId:a,progressBar:c,host:l,options:u,imageServiceDomains:h=[]}=t;let p=0,f=0,g=0;const $=[],w=[];for(let t=0;t<o;t++){const o=n[t];if("string"!=typeof o.type)continue;if(s.get(o.uuid))continue;const m=o.type.toLocaleLowerCase();if(m===d.TITLE||""!==o.child_uuid||m===d.LINK){let t=o;const e=[],n=[];for(;t;)e.unshift(D(t.title)),n.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const a={path:e.join("/"),pathTitleList:e,pathIdList:n,toc:o};m===d.LINK?(g+=1,w.push(a)):await r(`${i}/${e.join("/")}`,{recursive:!0}),s.set(o.uuid,a),await c.updateProgress(a,m!==d.LINK)}else if(o.url){f+=1;let t={path:"",pathTitleList:[],pathIdList:[]};s.get(o.parent_uuid)&&(t=s.get(o.parent_uuid));const r=D(o.title),n=[...t.pathTitleList,`${r}.md`],d=[...t.pathIdList,o.uuid],m={path:n.join("/"),pathTitleList:n,pathIdList:d,toc:o};let g=!0;const w=`${e}/${o.url}`;try{const e={bookId:a,itemUrl:o.url,savePath:`${i}/${t.path}`,saveFilePath:`${i}/${m.path}`,uuid:o.uuid,articleUrl:w,articleTitle:o.title,ignoreImg:u.ignoreImg,host:l,imageServiceDomains:h};await T({articleInfo:e,progressBar:c,options:u})}catch(t){g=!1,p+=1,$.push({articleUrl:w,errItem:m,errMsg:t.message,err:t})}s.set(o.uuid,m),await c.updateProgress(m,g)}}if(g>0){m.warn("该知识库存在以下外链文章");for(const t of w)m.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(p>0){m.error(`本次执行总数${f}篇,✕ 失败${p}篇`);for(const t of $)m.error(`${t.errItem.path} ———— ${t.articleUrl}`),m.error(`———— ✕ ${t.errMsg}`);m.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:b,total:f,uuidMap:k,tocList:n,bookPath:p,bookId:s,progressBar:w,host:u,options:e,imageServiceDomains:h});const I=new $({bookPath:p,bookName:i,bookDesc:a,uuidMap:k});await I.genFile(),m.info(`√ 生成目录 ${p}/SUMMARY.md`),w.curr===f&&m.info(`√ 已完成: ${p}`),process.exit(0)}export{T as d,m as l,U as m};
package/dist/es/index.js CHANGED
@@ -1 +1 @@
1
- import"node:fs/promises";import"pull-md-img";import"ora";import"markdown-toc";export{d as downloadArticle,m as main}from"./index-6d8832a0.js";import"cli-progress";import"log4js";import"axios";import"rand-user-agent";import"pako";
1
+ import"node:fs/promises";import"node:path";import"pull-md-img";import"ora";import"markdown-toc";export{d as downloadArticle,m as main}from"./index-b284aad1.js";import"cli-progress";import"log4js";import"axios";import"rand-user-agent";import"pako";import"node:crypto";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yuque-dl",
3
- "version": "1.0.35",
3
+ "version": "1.0.39",
4
4
  "description": "yuque 知识库下载",
5
5
  "type": "module",
6
6
  "bin": {
@@ -64,7 +64,7 @@
64
64
  "markdown-toc": "^1.2.0",
65
65
  "ora": "^7.0.1",
66
66
  "pako": "1.0.11",
67
- "pull-md-img": "^0.0.41",
67
+ "pull-md-img": "^0.0.43",
68
68
  "rand-user-agent": "1.0.109",
69
69
  "semver": "^7.6.0"
70
70
  },
@@ -6,7 +6,7 @@ export interface IProgressItem {
6
6
  pathIdList: string[];
7
7
  pathTitleList: string[];
8
8
  }
9
- export declare type IProgress = IProgressItem[];
9
+ export type IProgress = IProgressItem[];
10
10
  export default class ProgressBar {
11
11
  bookPath: string;
12
12
  progressFilePath: string;
package/types/api.d.ts CHANGED
@@ -7,12 +7,13 @@ interface IKnowledgeBaseInfo {
7
7
  bookName?: string;
8
8
  bookDesc?: string;
9
9
  host?: string;
10
+ imageServiceDomains?: string[];
10
11
  }
11
12
  interface GetHeaderParams {
12
13
  key?: string;
13
14
  token?: string;
14
15
  }
15
- declare type TGetKnowledgeBaseInfo = (url: string, headerParams: GetHeaderParams) => Promise<IKnowledgeBaseInfo>;
16
+ type TGetKnowledgeBaseInfo = (url: string, headerParams: GetHeaderParams) => Promise<IKnowledgeBaseInfo>;
16
17
  /** 获取知识库数据信息 */
17
18
  export declare const getKnowledgeBaseInfo: TGetKnowledgeBaseInfo;
18
19
  interface GetMdDataParams {
@@ -27,6 +28,6 @@ interface IGetDocsMdDataRes {
27
28
  httpStatus: number;
28
29
  response?: ArticleResponse.RootObject;
29
30
  }
30
- declare type TGetMdData = (params: GetMdDataParams, isMd?: boolean) => Promise<IGetDocsMdDataRes>;
31
+ type TGetMdData = (params: GetMdDataParams, isMd?: boolean) => Promise<IGetDocsMdDataRes>;
31
32
  export declare const getDocsMdData: TGetMdData;
32
33
  export {};
@@ -20,4 +20,5 @@ declare const articleContentMap: Map<ARTICLE_CONTENT_TYPE, string>;
20
20
  declare const DEFAULT_COOKIE_KEY = "_yuque_session";
21
21
  /** 默认语雀域名 */
22
22
  declare const DEFAULT_DOMAIN = "https://www.yuque.com";
23
- export { ARTICLE_TOC_TYPE, ARTICLE_CONTENT_TYPE, articleContentMap, DEFAULT_COOKIE_KEY, DEFAULT_DOMAIN };
23
+ declare const IMAGE_SING_KEY = "UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD";
24
+ export { ARTICLE_TOC_TYPE, ARTICLE_CONTENT_TYPE, articleContentMap, DEFAULT_COOKIE_KEY, DEFAULT_DOMAIN, IMAGE_SING_KEY };
@@ -0,0 +1 @@
1
+ export declare function captureImageURL(url: string, imageServiceDomains?: string[]): string;
package/types/index.d.ts CHANGED
@@ -10,6 +10,7 @@ interface ArticleInfo {
10
10
  articleUrl: string;
11
11
  ignoreImg: boolean;
12
12
  host?: string;
13
+ imageServiceDomains: string[];
13
14
  }
14
15
  interface DownloadArticleParams {
15
16
  /** 文章信息 */
@@ -1 +0,0 @@
1
- "use strict";var t=require("node:fs/promises"),e=require("pull-md-img"),r=require("ora"),o=require("markdown-toc"),s=require("cli-progress"),i=require("log4js"),n=require("axios"),a=require("rand-user-agent"),c=require("pako");var l,u,h=(i.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),i.getLogger("yuque-dl"));class d{constructor(t,e){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=t,this.progressFilePath=`${t}/progress.json`,this.total=e}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,h.info("根据上次数据继续断点下载")),this.bar=new s.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},s.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const r=await t.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await t.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,r){this.curr=this.curr+1,r&&(this.progressInfo.push(e),await t.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log("")))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(t){if(!(t<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let e=0;e<t;e++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}class p{constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:s}=this.summaryInfo;let i=`# ${e}\n\n`;r&&(i+=`> ${r}\n\n`);let n=i;const a=[];s.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(a,r),s={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:""},i=e.type.toLocaleLowerCase();"title"===i||""!==e.child_uuid?(s.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s))):(s.type="link",s.link="link"===i?t.toc.url:t.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s)))}));n+=this.genSummaryContent(a,"");try{await t.writeFile(`${o}/SUMMARY.md`,n)}catch(t){h.error("Generate Summary Error")}}genSummaryContent(t,e){for(const r of t){if("title"===r.type)e+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if("link"===r.type){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`- [${r.text}](${t})\n`}Array.isArray(r.children)&&(e+=this.genSummaryContent(r.children,""))}return e}findIdItem(t,e){if(t.id===e)return t;if(t.children){const r=this.findTree(t.children,e);if(r)return r}return!1}findTree(t,e){if(!e)return!1;for(const r of t){const t=this.findIdItem(r,e);if(t)return t}return!1}}!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(l||(l={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(u||(u={}));const f=new Map([[u.BOARD,"画板类型"],[u.TABLE,"数据表类型"],[u.SHEET,"表格类型"],[u.DOC,"文档类型"]]),g="_yuque_session",m="https://www.yuque.com";function $({browser:t="chrome",os:e="mac os",device:r="desktop"}){r=r.toLowerCase(),t=t.toLowerCase(),e=e.toLowerCase();let o=a(r,t,e);if("chrome"===t)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=a(r,t,e);if("safari"===t)for(;o.includes("Applebot");)o=a(r,t,e);return o}function w(t){const{key:e=g,token:r}=t,o={"user-agent":$({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function k(t){return{headers:w(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...w(t)}}}}const y=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:s,key:i,host:a=m}=t;let c=`${a}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};e&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,n.get(c,k({token:s,key:i})).then((({data:t,status:e})=>({apiUrl:c,httpStatus:e,response:t})))},b=t=>{if(!t)return"";const e=JSON.parse(c.inflate(t,{to:"string"}));let r="";return e.forEach((t=>{const e=`## ${t.name}\n`,o=function(t){let e=Object.keys(t);e=e.filter((e=>Object.keys(t[e]).some((r=>t?.[e]?.[r]?.v))));let r=[];e.forEach((e=>{const o=t[e];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...e.map((t=>Number(t)))),s=Math.max(...r.map((t=>Number(t))));if(o<0||s<0)return"";let i="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(s+1).fill(" ").map(((t,e)=>{const r=e%n.length;return n[r]})).join(" | ");a=`| |${a}|`;let c=Array(s+2).fill("---").join(" |");c=`|${c}|`,i=`${a}\n${c}\n`;for(let e=0;e<o+1;e++){const r=[];for(let o=0;o<s+1;o++){const s=t?.[e]?.[o]?.v||null;s&&"string"==typeof s?r.push(s):s&&"object"==typeof s?"image"===s?.class&&s?.src?r.push(`![${s?.name}'](${s?.src})`):"checkbox"===s?.class?r.push(s?.value?"[x] ":"[ ] "):"link"===s?.class?r.push(`[${s?.text}](${s?.url})`):"select"===s?.class&&r.push(s?.value?.join(",")):r.push(null)}i=`${i}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return i}(t.data);r=`${r}\n${e}\n${o}`})),r};async function I(s){const{articleInfo:i,progressBar:n,options:a}=s,{token:c,key:l}=a,{bookId:h,itemUrl:d,savePath:p,saveFilePath:g,uuid:m,articleUrl:$,articleTitle:w,ignoreImg:k,host:I}=i,{httpStatus:L,apiUrl:E,response:S}=await y({articleUrl:d,bookId:h,token:c,host:I,key:l}),v=S?.data?.type?.toLocaleLowerCase();let P="";if(v===u.SHEET){const{response:t}=await y({articleUrl:d,bookId:h,token:c,host:I,key:l},!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;P=o?b(o):""}catch(t){const e=f.get(v);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([u.BOARD,u.TABLE].includes(v)){const t=f.get(v);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof S?.data?.sourcecode)throw new Error(`download article Error: ${E}, http status ${L}`);P=S.data.sourcecode}if(!k){n.pause(),console.log("");const t=r({text:`下载 "${w}" 的图片中...`});t.start();try{P=await e.run(P,{dist:p,imgDir:`./img/${m}`,isIgnoreConsole:!0,referer:d||""})}catch(t){let e=`download article image Error: ${t.message}`;throw t.error&&t.url&&(e=`download article image Error ${t.url}: ${t.error?.message}`),new Error(e)}finally{t.stop(),n.continue()}}P=P.replace(/<br(\s?)\/>/gm,"\n"),P=P.replace(/<a.*?>(\s*?)<\/a>/gm,"");const T=w?`# ${w}\n\n`:"";let N=a.ignoreToc?"":o(P).content;N&&(N=`${N}\n\n---\n\n`);P=`${T}${N}${P}${$?`\n\n> 原文: <${$}>`:""}`;try{return await t.writeFile(g,P),!0}catch(t){throw new Error(`download article Error ${$}: ${t.message}`)}}function L(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}exports.downloadArticle=I,exports.logger=h,exports.main=async function(e,r){const{bookId:o,tocList:s,bookName:i,bookDesc:a,bookSlug:c,host:u}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return n.get(t,k(e)).then((({data:t="",status:e})=>200===e?t:"")).then((t=>{const e=r.exec(t)??"";if(!e[1])return{};const o=JSON.parse(decodeURIComponent(e[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||m}:{}}))})(e,{token:r.token,key:r.key});if(!o)throw new Error("No found book id");if(!s||0===s.length)throw new Error("No found toc list");const f=`${r.distDir}/${i?L(i):o}`;await t.mkdir(f,{recursive:!0});const g=s.length,$=new d(f,g);if(await $.init(),$.curr===g)return $.bar&&$.bar.stop(),void h.info(`√ 已完成: ${process.cwd()}/${f}`);const w=new Map;$.isDownloadInterrupted&&$.progressInfo.forEach((t=>{w.set(t.toc.uuid,t)}));const y=e.replace(new RegExp(`(.*?/${c}).*`),"$1");await async function(e){const{articleUrlPrefix:r,total:o,uuidMap:s,tocList:i,bookPath:n,bookId:a,progressBar:c,host:u,options:d}=e;let p=0,f=0,g=0;const m=[],$=[];for(let e=0;e<o;e++){const o=i[e];if("string"!=typeof o.type)continue;if(s.get(o.uuid))continue;const h=o.type.toLocaleLowerCase();if(h===l.TITLE||""!==o.child_uuid||h===l.LINK){let e=o;const r=[],i=[];for(;e;)r.unshift(L(e.title)),i.unshift(e.uuid),e=s.get(e.parent_uuid)?s.get(e.parent_uuid).toc:void 0;const a={path:r.join("/"),pathTitleList:r,pathIdList:i,toc:o};h===l.LINK?(g+=1,$.push(a)):await t.mkdir(`${n}/${r.join("/")}`,{recursive:!0}),s.set(o.uuid,a),await c.updateProgress(a,h!==l.LINK)}else if(o.url){f+=1;let t={path:"",pathTitleList:[],pathIdList:[]};s.get(o.parent_uuid)&&(t=s.get(o.parent_uuid));const e=L(o.title),i=[...t.pathTitleList,`${e}.md`],l=[...t.pathIdList,o.uuid],h={path:i.join("/"),pathTitleList:i,pathIdList:l,toc:o};let g=!0;const $=`${r}/${o.url}`;try{const e={bookId:a,itemUrl:o.url,savePath:`${n}/${t.path}`,saveFilePath:`${n}/${h.path}`,uuid:o.uuid,articleUrl:$,articleTitle:o.title,ignoreImg:d.ignoreImg,host:u};await I({articleInfo:e,progressBar:c,options:d})}catch(t){g=!1,p+=1,m.push({articleUrl:$,errItem:h,errMsg:t.message,err:t})}s.set(o.uuid,h),await c.updateProgress(h,g)}}if(g>0){h.warn("该知识库存在以下外链文章");for(const t of $)h.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(p>0){h.error(`本次执行总数${f}篇,✕ 失败${p}篇`);for(const t of m)h.error(`${t.errItem.path} ———— ${t.articleUrl}`),h.error(`———— ✕ ${t.errMsg}`);h.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:y,total:g,uuidMap:w,tocList:s,bookPath:f,bookId:o,progressBar:$,host:u,options:r});const b=new p({bookPath:f,bookName:i,bookDesc:a,uuidMap:w});await b.genFile();const E=process.cwd();h.info(`√ 生成目录 ${E}/${f}/SUMMARY.md`),$.curr===g&&h.info(`√ 已完成: ${E}/${f}`),process.exit(0)};
@@ -1 +0,0 @@
1
- import t,{writeFile as e,mkdir as r}from"node:fs/promises";import o from"pull-md-img";import s from"ora";import i from"markdown-toc";import n from"cli-progress";import a from"log4js";import c from"axios";import l from"rand-user-agent";import u from"pako";var h,p,d=(a.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),a.getLogger("yuque-dl"));class f{constructor(t,e){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=t,this.progressFilePath=`${t}/progress.json`,this.total=e}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,d.info("根据上次数据继续断点下载")),this.bar=new n.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},n.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const r=await t.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await t.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,r){this.curr=this.curr+1,r&&(this.progressInfo.push(e),await t.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log("")))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(t){if(!(t<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let e=0;e<t;e++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}class g{constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:s}=this.summaryInfo;let i=`# ${e}\n\n`;r&&(i+=`> ${r}\n\n`);let n=i;const a=[];s.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(a,r),s={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:""},i=e.type.toLocaleLowerCase();"title"===i||""!==e.child_uuid?(s.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s))):(s.type="link",s.link="link"===i?t.toc.url:t.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),s.level=o.level+1,o.children.push(s)):(s.level=1,a.push(s)))}));n+=this.genSummaryContent(a,"");try{await t.writeFile(`${o}/SUMMARY.md`,n)}catch(t){d.error("Generate Summary Error")}}genSummaryContent(t,e){for(const r of t){if("title"===r.type)e+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if("link"===r.type){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`- [${r.text}](${t})\n`}Array.isArray(r.children)&&(e+=this.genSummaryContent(r.children,""))}return e}findIdItem(t,e){if(t.id===e)return t;if(t.children){const r=this.findTree(t.children,e);if(r)return r}return!1}findTree(t,e){if(!e)return!1;for(const r of t){const t=this.findIdItem(r,e);if(t)return t}return!1}}!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(h||(h={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(p||(p={}));const m=new Map([[p.BOARD,"画板类型"],[p.TABLE,"数据表类型"],[p.SHEET,"表格类型"],[p.DOC,"文档类型"]]),$="_yuque_session",w="https://www.yuque.com";function k({browser:t="chrome",os:e="mac os",device:r="desktop"}){r=r.toLowerCase(),t=t.toLowerCase(),e=e.toLowerCase();let o=l(r,t,e);if("chrome"===t)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=l(r,t,e);if("safari"===t)for(;o.includes("Applebot");)o=l(r,t,e);return o}function y(t){const{key:e=$,token:r}=t,o={"user-agent":k({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function b(t){return{headers:y(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...y(t)}}}}const I=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:s,key:i,host:n=w}=t;let a=`${n}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};e&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return a=`${a}?${u}`,c.get(a,b({token:s,key:i})).then((({data:t,status:e})=>({apiUrl:a,httpStatus:e,response:t})))},L=t=>{if(!t)return"";const e=JSON.parse(u.inflate(t,{to:"string"}));let r="";return e.forEach((t=>{const e=`## ${t.name}\n`,o=function(t){let e=Object.keys(t);e=e.filter((e=>Object.keys(t[e]).some((r=>t?.[e]?.[r]?.v))));let r=[];e.forEach((e=>{const o=t[e];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...e.map((t=>Number(t)))),s=Math.max(...r.map((t=>Number(t))));if(o<0||s<0)return"";let i="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(s+1).fill(" ").map(((t,e)=>{const r=e%n.length;return n[r]})).join(" | ");a=`| |${a}|`;let c=Array(s+2).fill("---").join(" |");c=`|${c}|`,i=`${a}\n${c}\n`;for(let e=0;e<o+1;e++){const r=[];for(let o=0;o<s+1;o++){const s=t?.[e]?.[o]?.v||null;s&&"string"==typeof s?r.push(s):s&&"object"==typeof s?"image"===s?.class&&s?.src?r.push(`![${s?.name}'](${s?.src})`):"checkbox"===s?.class?r.push(s?.value?"[x] ":"[ ] "):"link"===s?.class?r.push(`[${s?.text}](${s?.url})`):"select"===s?.class&&r.push(s?.value?.join(",")):r.push(null)}i=`${i}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return i}(t.data);r=`${r}\n${e}\n${o}`})),r};async function E(t){const{articleInfo:r,progressBar:n,options:a}=t,{token:c,key:l}=a,{bookId:u,itemUrl:h,savePath:d,saveFilePath:f,uuid:g,articleUrl:$,articleTitle:w,ignoreImg:k,host:y}=r,{httpStatus:b,apiUrl:E,response:S}=await I({articleUrl:h,bookId:u,token:c,host:y,key:l}),P=S?.data?.type?.toLocaleLowerCase();let v="";if(P===p.SHEET){const{response:t}=await I({articleUrl:h,bookId:u,token:c,host:y,key:l},!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;v=o?L(o):""}catch(t){const e=m.get(P);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([p.BOARD,p.TABLE].includes(P)){const t=m.get(P);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof S?.data?.sourcecode)throw new Error(`download article Error: ${E}, http status ${b}`);v=S.data.sourcecode}if(!k){n.pause(),console.log("");const t=s({text:`下载 "${w}" 的图片中...`});t.start();try{v=await o.run(v,{dist:d,imgDir:`./img/${g}`,isIgnoreConsole:!0,referer:h||""})}catch(t){let e=`download article image Error: ${t.message}`;throw t.error&&t.url&&(e=`download article image Error ${t.url}: ${t.error?.message}`),new Error(e)}finally{t.stop(),n.continue()}}v=v.replace(/<br(\s?)\/>/gm,"\n"),v=v.replace(/<a.*?>(\s*?)<\/a>/gm,"");const T=w?`# ${w}\n\n`:"";let N=a.ignoreToc?"":i(v).content;N&&(N=`${N}\n\n---\n\n`);v=`${T}${N}${v}${$?`\n\n> 原文: <${$}>`:""}`;try{return await e(f,v),!0}catch(t){throw new Error(`download article Error ${$}: ${t.message}`)}}function S(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}async function P(t,e){const{bookId:o,tocList:s,bookName:i,bookDesc:n,bookSlug:a,host:l}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return c.get(t,b(e)).then((({data:t="",status:e})=>200===e?t:"")).then((t=>{const e=r.exec(t)??"";if(!e[1])return{};const o=JSON.parse(decodeURIComponent(e[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||w}:{}}))})(t,{token:e.token,key:e.key});if(!o)throw new Error("No found book id");if(!s||0===s.length)throw new Error("No found toc list");const u=`${e.distDir}/${i?S(i):o}`;await r(u,{recursive:!0});const p=s.length,m=new f(u,p);if(await m.init(),m.curr===p)return m.bar&&m.bar.stop(),void d.info(`√ 已完成: ${process.cwd()}/${u}`);const $=new Map;m.isDownloadInterrupted&&m.progressInfo.forEach((t=>{$.set(t.toc.uuid,t)}));const k=t.replace(new RegExp(`(.*?/${a}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:o,uuidMap:s,tocList:i,bookPath:n,bookId:a,progressBar:c,host:l,options:u}=t;let p=0,f=0,g=0;const m=[],$=[];for(let t=0;t<o;t++){const o=i[t];if("string"!=typeof o.type)continue;if(s.get(o.uuid))continue;const d=o.type.toLocaleLowerCase();if(d===h.TITLE||""!==o.child_uuid||d===h.LINK){let t=o;const e=[],i=[];for(;t;)e.unshift(S(t.title)),i.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const a={path:e.join("/"),pathTitleList:e,pathIdList:i,toc:o};d===h.LINK?(g+=1,$.push(a)):await r(`${n}/${e.join("/")}`,{recursive:!0}),s.set(o.uuid,a),await c.updateProgress(a,d!==h.LINK)}else if(o.url){f+=1;let t={path:"",pathTitleList:[],pathIdList:[]};s.get(o.parent_uuid)&&(t=s.get(o.parent_uuid));const r=S(o.title),i=[...t.pathTitleList,`${r}.md`],h=[...t.pathIdList,o.uuid],d={path:i.join("/"),pathTitleList:i,pathIdList:h,toc:o};let g=!0;const $=`${e}/${o.url}`;try{const e={bookId:a,itemUrl:o.url,savePath:`${n}/${t.path}`,saveFilePath:`${n}/${d.path}`,uuid:o.uuid,articleUrl:$,articleTitle:o.title,ignoreImg:u.ignoreImg,host:l};await E({articleInfo:e,progressBar:c,options:u})}catch(t){g=!1,p+=1,m.push({articleUrl:$,errItem:d,errMsg:t.message,err:t})}s.set(o.uuid,d),await c.updateProgress(d,g)}}if(g>0){d.warn("该知识库存在以下外链文章");for(const t of $)d.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(p>0){d.error(`本次执行总数${f}篇,✕ 失败${p}篇`);for(const t of m)d.error(`${t.errItem.path} ———— ${t.articleUrl}`),d.error(`———— ✕ ${t.errMsg}`);d.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:k,total:p,uuidMap:$,tocList:s,bookPath:u,bookId:o,progressBar:m,host:l,options:e});const y=new g({bookPath:u,bookName:i,bookDesc:n,uuidMap:$});await y.genFile();const I=process.cwd();d.info(`√ 生成目录 ${I}/${u}/SUMMARY.md`),m.curr===p&&d.info(`√ 已完成: ${I}/${u}`),process.exit(0)}export{E as d,d as l,P as m};