yuque-dl 1.0.0

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/.editorconfig ADDED
@@ -0,0 +1,16 @@
1
+ # http://editorconfig.org
2
+
3
+ root = true
4
+
5
+ [*]
6
+ charset = utf-8
7
+ indent_style = space
8
+ indent_size = 2
9
+ end_of_line = lf
10
+ # 最后一行换行 取消掉
11
+ insert_final_newline = false
12
+ trim_trailing_whitespace = true
13
+
14
+ [*.md]
15
+ insert_final_newline = false
16
+ trim_trailing_whitespace = false
package/.eslintignore ADDED
@@ -0,0 +1,5 @@
1
+ dist
2
+ types
3
+ node_modules
4
+ bin
5
+ test
package/.eslintrc.js ADDED
@@ -0,0 +1,21 @@
1
+ module.exports = {
2
+ env: {
3
+ node: true,
4
+ },
5
+ parser: '@typescript-eslint/parser',
6
+ plugins: [
7
+ '@typescript-eslint',
8
+ ],
9
+ extends: [
10
+ 'eslint:recommended',
11
+ 'plugin:@typescript-eslint/recommended',
12
+ ],
13
+ rules: {
14
+ semi: ['error', 'never'],
15
+ 'no-console': 'off',
16
+ 'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
17
+ // TODO
18
+ '@typescript-eslint/no-explicit-any': 'off',
19
+ '@typescript-eslint/no-non-null-assertion': 'off'
20
+ },
21
+ }
package/.prettierrc.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ semi: false,
3
+ endOfLine: 'lf',
4
+ singleQuote: true,
5
+ tabWidth: 2,
6
+ useTabs: false,
7
+ }
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # yuque-dl
2
+
3
+ yuque 知识库下载
package/bin/index.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+
3
+ function run() {
4
+ return import('../dist/es/cli.js')
5
+ }
6
+ run()
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ var cac = require('cac');
4
+ var index = require('./index-0e9279f8.js');
5
+ require('node:fs/promises');
6
+ require('node:path');
7
+ require('axios');
8
+ require('log4js');
9
+ require('progress');
10
+ require('rand-user-agent');
11
+ require('pull-md-img');
12
+
13
+ var version = "1.0.0";
14
+
15
+ const cli = cac.cac('yuque-dl');
16
+ cli
17
+ .command('<url>', 'request url')
18
+ .option('-d, --distDir <dir>', '下载的目录 eg: -d download', {
19
+ default: 'download',
20
+ })
21
+ .action(async (url, options) => {
22
+ try {
23
+ await index.main(url, options);
24
+ }
25
+ catch (err) {
26
+ index.logger.error(err.message || 'unknown exception');
27
+ }
28
+ });
29
+ cli.help();
30
+ cli.version(version);
31
+ try {
32
+ cli.parse();
33
+ }
34
+ catch (err) {
35
+ index.logger.error(err.message || 'unknown exception');
36
+ process.exit(1);
37
+ }
38
+ // try {
39
+ // cli.parse(process.argv, { run: false })
40
+ // await cli.runMatchedCommand()
41
+ // } catch (error) {
42
+ // logger.error(error.message || 'unknown exception')
43
+ // process.exit(1)
44
+ // }
@@ -0,0 +1,405 @@
1
+ 'use strict';
2
+
3
+ var fs = require('node:fs/promises');
4
+ var path = require('node:path');
5
+ var axios = require('axios');
6
+ var log4js = require('log4js');
7
+ var progress = require('progress');
8
+ var randUserAgentLib = require('rand-user-agent');
9
+ var mdImg = require('pull-md-img');
10
+
11
+ var config = {
12
+ knowledgeBaseReg: /decodeURIComponent\(\"(.+)\"\)\);/m,
13
+ dist: './download'
14
+ };
15
+ // data = re.findall(r"decodeURIComponent\(\"(.+)\"\)\);", docsdata.content.decode('utf-8'))
16
+ // const config = {
17
+ // path: '',
18
+ // suffix: '',
19
+ // dist: './res/',
20
+ // imgDir:`./img/${Date.now()}`,
21
+ // // markdown img 正则 注意多行匹配
22
+ // mdImgReg: /!\[(.*?)\]\((.*?)\)/gm,
23
+ // isIgnoreConsole: false
24
+ // }
25
+
26
+ /**
27
+ * log 初始化
28
+ */
29
+ const getLogger = () => {
30
+ log4js.configure({
31
+ appenders: {
32
+ // cheeseLog: { type: 'file', filename: 'cheese.log' },
33
+ cheese: {
34
+ type: 'console',
35
+ layout: {
36
+ // type: 'messagePassThrough',
37
+ type: 'pattern',
38
+ // pattern: '%[%d{yyyy-MM-dd hh:mm:ss} [%p] %c -%] %m%n'
39
+ pattern: '%[%c [%p]:%] %m%n'
40
+ }
41
+ }
42
+ },
43
+ categories: { default: { appenders: ['cheese'], level: 'trace' } }
44
+ });
45
+ return log4js.getLogger('yuque-dl');
46
+ };
47
+ var logger = getLogger();
48
+
49
+ class Progress {
50
+ constructor(bookPath, total) {
51
+ this.bookPath = '';
52
+ this.processFilePath = '';
53
+ this.processInfo = [];
54
+ this.curr = 0;
55
+ this.total = 0;
56
+ this.isDownloadInterrupted = false;
57
+ this.bar = null;
58
+ this.completePromise = null;
59
+ this.bookPath = bookPath;
60
+ this.processFilePath = `${bookPath}/process.json`;
61
+ this.total = total;
62
+ }
63
+ async init() {
64
+ this.processInfo = await this.getProgress();
65
+ this.curr = this.processInfo.length;
66
+ let completeResolve;
67
+ this.completePromise = new Promise(resolve => {
68
+ completeResolve = resolve;
69
+ });
70
+ if (this.curr > 0 && this.curr !== this.total) {
71
+ this.isDownloadInterrupted = true;
72
+ logger.info('断点下载');
73
+ }
74
+ this.bar = new progress('[:bar] :rate/bps :percent :etas', {
75
+ // width: 20,
76
+ total: this.total,
77
+ curr: this.curr,
78
+ callback() {
79
+ completeResolve();
80
+ }
81
+ });
82
+ }
83
+ async getProgress() {
84
+ let processInfo = [];
85
+ try {
86
+ const processInfoStr = await fs.readFile(this.processFilePath, { encoding: 'utf8' });
87
+ processInfo = JSON.parse(processInfoStr);
88
+ }
89
+ catch (err) {
90
+ if (err && err.code === 'ENOENT') {
91
+ await fs.writeFile(this.processFilePath, JSON.stringify(processInfo), { encoding: 'utf8' });
92
+ }
93
+ }
94
+ return processInfo;
95
+ }
96
+ async updateProgress(progressItem) {
97
+ this.processInfo.push(progressItem);
98
+ await fs.writeFile(this.processFilePath, JSON.stringify(this.processInfo), { encoding: 'utf8' });
99
+ this.curr = this.curr + 1;
100
+ if (this.bar) {
101
+ this.bar?.tick();
102
+ }
103
+ }
104
+ }
105
+
106
+ function randUserAgent({ browser = 'chrome', os = 'mac os', device = 'desktop' }) {
107
+ device = device.toLowerCase();
108
+ browser = browser.toLowerCase();
109
+ os = os.toLowerCase();
110
+ let UA = randUserAgentLib(device, browser, os);
111
+ if (browser === 'chrome') {
112
+ while (UA.includes('Chrome-Lighthouse')
113
+ || UA.includes('Gener8')
114
+ || UA.includes('HeadlessChrome')
115
+ || UA.includes('SMTBot')) {
116
+ UA = randUserAgentLib(device, browser, os);
117
+ }
118
+ }
119
+ if (browser === 'safari') {
120
+ while (UA.includes('Applebot')) {
121
+ UA = randUserAgentLib(device, browser, os);
122
+ }
123
+ }
124
+ return UA;
125
+ }
126
+
127
+ // SUMMARY.md
128
+ function getKnowledgeBaseInfo(url) {
129
+ return axios.get(url, {
130
+ headers: {
131
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
132
+ }
133
+ }).then(({ data = '', status }) => {
134
+ if (status === 200)
135
+ return data;
136
+ return '';
137
+ }).then(html => {
138
+ const data = html.match(config.knowledgeBaseReg) || '';
139
+ if (!data[1])
140
+ return {};
141
+ const jsonData = JSON.parse(decodeURIComponent(data[1]));
142
+ const info = {
143
+ bookId: jsonData.book.id,
144
+ tocList: jsonData.book.toc || [],
145
+ bookName: jsonData.book.name || '',
146
+ bookDesc: jsonData.book.description || '',
147
+ };
148
+ return info;
149
+ });
150
+ }
151
+ async function main(url, options) {
152
+ const { bookId, tocList, bookName, bookDesc } = await getKnowledgeBaseInfo(url);
153
+ if (!bookId)
154
+ throw new Error('No found book id');
155
+ if (!tocList || tocList.length === 0)
156
+ throw new Error('No found toc list');
157
+ const bookPath = `${options.distDir}/${bookId}`;
158
+ await fs.mkdir(bookPath, { recursive: true });
159
+ const total = tocList.length;
160
+ const progress = new Progress(bookPath, total);
161
+ await progress.init();
162
+ if (progress.curr === total) {
163
+ logger.info('√ 已完成');
164
+ return;
165
+ }
166
+ const uuidMap = new Map();
167
+ // 下载中断 重新获取下载进度数据
168
+ if (progress.isDownloadInterrupted) {
169
+ progress.processInfo.forEach(item => {
170
+ uuidMap.set(item.toc.uuid, item);
171
+ });
172
+ }
173
+ const articleUrlPrefix = path.parse(url).dir;
174
+ // const url.split('/')
175
+ for (let i = 0; i < total; i++) {
176
+ const item = tocList[i];
177
+ if (typeof item.type !== 'string')
178
+ continue;
179
+ if (uuidMap.get(item.uuid))
180
+ continue;
181
+ console.log(item.uuid);
182
+ const itemType = item.type.toLocaleLowerCase();
183
+ const dirNameReg = /[\\\/:\*\?"<>\|\n\r]/g;
184
+ // 目录
185
+ if (itemType === 'title' || item['child_uuid'] !== '') {
186
+ let tempItem = item;
187
+ let pathTitleList = [];
188
+ let pathIdList = [];
189
+ while (tempItem) {
190
+ pathTitleList.unshift(tempItem.title.replace(dirNameReg, '_'));
191
+ pathIdList.unshift(tempItem.uuid);
192
+ if (uuidMap.get(tempItem['parent_uuid'])) {
193
+ tempItem = uuidMap.get(tempItem['parent_uuid']).toc;
194
+ }
195
+ else {
196
+ tempItem = undefined;
197
+ }
198
+ }
199
+ const progressItem = {
200
+ path: pathTitleList.join('/'),
201
+ pathTitleList,
202
+ pathIdList,
203
+ toc: item
204
+ };
205
+ await fs.mkdir(`${bookPath}/${pathTitleList.join('/')}`, { recursive: true });
206
+ uuidMap.set(item.uuid, progressItem);
207
+ progress.updateProgress(progressItem);
208
+ }
209
+ else if (item.url) {
210
+ let preItem = {
211
+ path: '',
212
+ pathTitleList: [],
213
+ pathIdList: []
214
+ };
215
+ if (uuidMap.get(item['parent_uuid'])) {
216
+ preItem = uuidMap.get(item['parent_uuid']);
217
+ }
218
+ const fileName = item.title.replace(dirNameReg, '_');
219
+ const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
220
+ const pathIdList = [...preItem.pathIdList, item.uuid];
221
+ const progressItem = {
222
+ path: pathTitleList.join('/'),
223
+ pathTitleList,
224
+ pathIdList,
225
+ toc: item
226
+ };
227
+ const isSuccess = await downloadArticle({
228
+ bookId,
229
+ itemUrl: item.url,
230
+ savePath: `${bookPath}/${preItem.path}`,
231
+ saveFilePath: `${bookPath}/${progressItem.path}`,
232
+ uuid: item.uuid,
233
+ articleUrl: `${articleUrlPrefix}/${item.url}`,
234
+ articleTitle: item.title
235
+ });
236
+ if (isSuccess) {
237
+ uuidMap.set(item.uuid, progressItem);
238
+ progress.updateProgress(progressItem);
239
+ }
240
+ }
241
+ console.log('完成', item.uuid);
242
+ }
243
+ await progress.completePromise;
244
+ logger.info('生成目录 SUMMARY.md');
245
+ await genSummaryFile({
246
+ bookPath,
247
+ bookName,
248
+ bookDesc,
249
+ uuidMap
250
+ });
251
+ if (progress.curr === total) {
252
+ logger.info('√ 已完成');
253
+ return;
254
+ }
255
+ }
256
+ async function downloadArticle(params) {
257
+ const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
258
+ const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
259
+ const response = await axios.get(apiUrl, {
260
+ headers: {
261
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
262
+ },
263
+ params: {
264
+ 'book_id': bookId,
265
+ 'merge_dynamic_data': false,
266
+ mode: 'markdown'
267
+ }
268
+ }).then(({ data, status }) => {
269
+ if (status === 200)
270
+ return data;
271
+ logger.error(`download article error: ${apiUrl} http status ${status}`);
272
+ return null;
273
+ });
274
+ if (!response || !response.data || !response.data.sourcecode)
275
+ return false;
276
+ let mdData = response.data.sourcecode;
277
+ try {
278
+ mdData = await mdImg.run(mdData, {
279
+ dist: savePath,
280
+ imgDir: `img/${uuid}`,
281
+ isIgnoreConsole: true
282
+ });
283
+ }
284
+ catch (err) {
285
+ logger.error(`download article img Error (api: ${apiUrl})`);
286
+ return false;
287
+ }
288
+ mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
289
+ if (articleTitle) {
290
+ mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
291
+ }
292
+ if (articleUrl) {
293
+ mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
294
+ }
295
+ try {
296
+ await fs.writeFile(saveFilePath, mdData);
297
+ return true;
298
+ }
299
+ catch (e) {
300
+ logger.error(`download article write file Error (api: ${apiUrl})`);
301
+ return false;
302
+ }
303
+ }
304
+ async function genSummaryFile(params) {
305
+ const { bookName, bookDesc, bookPath, uuidMap } = params;
306
+ const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
307
+ let mdContent = header;
308
+ const summary = [];
309
+ uuidMap.forEach(processItem => {
310
+ const toc = processItem.toc;
311
+ const parentId = toc['parent_uuid'];
312
+ const findRes = findTree(summary, parentId);
313
+ if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
314
+ if (typeof findRes !== 'boolean') {
315
+ if (!Array.isArray(findRes.children))
316
+ findRes.children = [];
317
+ findRes.children.push({
318
+ id: toc.uuid,
319
+ type: 'title',
320
+ level: findRes.level + 1,
321
+ text: toc.title
322
+ });
323
+ }
324
+ else {
325
+ summary.push({
326
+ id: toc.uuid,
327
+ type: 'title',
328
+ text: toc.title,
329
+ level: 1
330
+ });
331
+ }
332
+ }
333
+ else {
334
+ if (typeof findRes !== 'boolean') {
335
+ if (!Array.isArray(findRes.children))
336
+ findRes.children = [];
337
+ findRes.children.push({
338
+ id: toc.uuid,
339
+ type: 'link',
340
+ level: findRes.level + 1,
341
+ link: processItem.path,
342
+ text: toc.title
343
+ });
344
+ }
345
+ else {
346
+ summary.push({
347
+ id: toc.uuid,
348
+ type: 'link',
349
+ text: toc.title,
350
+ link: processItem.path,
351
+ level: 1
352
+ });
353
+ }
354
+ }
355
+ });
356
+ let summaryContent = genSummaryContent(summary, '');
357
+ mdContent += summaryContent;
358
+ try {
359
+ await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
360
+ }
361
+ catch (err) {
362
+ logger.error('Generate Summary Error');
363
+ }
364
+ }
365
+ function genSummaryContent(summary, summaryContent) {
366
+ for (let i = 0; i < summary.length; i++) {
367
+ const item = summary[i];
368
+ if (item.type === 'title') {
369
+ summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
370
+ }
371
+ else if (item.type === 'link') {
372
+ const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
373
+ summaryContent += `- [${item.text}](${link})\n`;
374
+ }
375
+ if (Array.isArray(item.children)) {
376
+ summaryContent += genSummaryContent(item.children, '');
377
+ }
378
+ }
379
+ return summaryContent;
380
+ }
381
+ function findIdItem(node, id) {
382
+ if (node.id === id) {
383
+ return node;
384
+ }
385
+ else if (node.children) {
386
+ const findRes = findTree(node.children, id);
387
+ if (findRes)
388
+ return findRes;
389
+ }
390
+ return false;
391
+ }
392
+ function findTree(tree, id) {
393
+ if (!id)
394
+ return false;
395
+ for (let i = 0; i < tree.length; i++) {
396
+ const findRes = findIdItem(tree[i], id);
397
+ if (findRes)
398
+ return findRes;
399
+ }
400
+ return false;
401
+ }
402
+
403
+ exports.getKnowledgeBaseInfo = getKnowledgeBaseInfo;
404
+ exports.logger = logger;
405
+ exports.main = main;
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ require('node:fs/promises');
4
+ require('node:path');
5
+ require('axios');
6
+ var index = require('./index-0e9279f8.js');
7
+ require('pull-md-img');
8
+ require('log4js');
9
+ require('progress');
10
+ require('rand-user-agent');
11
+
12
+
13
+
14
+ exports.getKnowledgeBaseInfo = index.getKnowledgeBaseInfo;
15
+ exports.main = index.main;
package/dist/es/cli.js ADDED
@@ -0,0 +1,42 @@
1
+ import { cac } from 'cac';
2
+ import { m as main, l as logger } from './index-be42878f.js';
3
+ import 'node:fs/promises';
4
+ import 'node:path';
5
+ import 'axios';
6
+ import 'log4js';
7
+ import 'progress';
8
+ import 'rand-user-agent';
9
+ import 'pull-md-img';
10
+
11
+ var version = "1.0.0";
12
+
13
+ const cli = cac('yuque-dl');
14
+ cli
15
+ .command('<url>', 'request url')
16
+ .option('-d, --distDir <dir>', '下载的目录 eg: -d download', {
17
+ default: 'download',
18
+ })
19
+ .action(async (url, options) => {
20
+ try {
21
+ await main(url, options);
22
+ }
23
+ catch (err) {
24
+ logger.error(err.message || 'unknown exception');
25
+ }
26
+ });
27
+ cli.help();
28
+ cli.version(version);
29
+ try {
30
+ cli.parse();
31
+ }
32
+ catch (err) {
33
+ logger.error(err.message || 'unknown exception');
34
+ process.exit(1);
35
+ }
36
+ // try {
37
+ // cli.parse(process.argv, { run: false })
38
+ // await cli.runMatchedCommand()
39
+ // } catch (error) {
40
+ // logger.error(error.message || 'unknown exception')
41
+ // process.exit(1)
42
+ // }
@@ -0,0 +1,401 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import axios from 'axios';
4
+ import log4js from 'log4js';
5
+ import progress from 'progress';
6
+ import randUserAgentLib from 'rand-user-agent';
7
+ import mdImg from 'pull-md-img';
8
+
9
+ var config = {
10
+ knowledgeBaseReg: /decodeURIComponent\(\"(.+)\"\)\);/m,
11
+ dist: './download'
12
+ };
13
+ // data = re.findall(r"decodeURIComponent\(\"(.+)\"\)\);", docsdata.content.decode('utf-8'))
14
+ // const config = {
15
+ // path: '',
16
+ // suffix: '',
17
+ // dist: './res/',
18
+ // imgDir:`./img/${Date.now()}`,
19
+ // // markdown img 正则 注意多行匹配
20
+ // mdImgReg: /!\[(.*?)\]\((.*?)\)/gm,
21
+ // isIgnoreConsole: false
22
+ // }
23
+
24
+ /**
25
+ * log 初始化
26
+ */
27
+ const getLogger = () => {
28
+ log4js.configure({
29
+ appenders: {
30
+ // cheeseLog: { type: 'file', filename: 'cheese.log' },
31
+ cheese: {
32
+ type: 'console',
33
+ layout: {
34
+ // type: 'messagePassThrough',
35
+ type: 'pattern',
36
+ // pattern: '%[%d{yyyy-MM-dd hh:mm:ss} [%p] %c -%] %m%n'
37
+ pattern: '%[%c [%p]:%] %m%n'
38
+ }
39
+ }
40
+ },
41
+ categories: { default: { appenders: ['cheese'], level: 'trace' } }
42
+ });
43
+ return log4js.getLogger('yuque-dl');
44
+ };
45
+ var logger = getLogger();
46
+
47
+ class Progress {
48
+ constructor(bookPath, total) {
49
+ this.bookPath = '';
50
+ this.processFilePath = '';
51
+ this.processInfo = [];
52
+ this.curr = 0;
53
+ this.total = 0;
54
+ this.isDownloadInterrupted = false;
55
+ this.bar = null;
56
+ this.completePromise = null;
57
+ this.bookPath = bookPath;
58
+ this.processFilePath = `${bookPath}/process.json`;
59
+ this.total = total;
60
+ }
61
+ async init() {
62
+ this.processInfo = await this.getProgress();
63
+ this.curr = this.processInfo.length;
64
+ let completeResolve;
65
+ this.completePromise = new Promise(resolve => {
66
+ completeResolve = resolve;
67
+ });
68
+ if (this.curr > 0 && this.curr !== this.total) {
69
+ this.isDownloadInterrupted = true;
70
+ logger.info('断点下载');
71
+ }
72
+ this.bar = new progress('[:bar] :rate/bps :percent :etas', {
73
+ // width: 20,
74
+ total: this.total,
75
+ curr: this.curr,
76
+ callback() {
77
+ completeResolve();
78
+ }
79
+ });
80
+ }
81
+ async getProgress() {
82
+ let processInfo = [];
83
+ try {
84
+ const processInfoStr = await fs.readFile(this.processFilePath, { encoding: 'utf8' });
85
+ processInfo = JSON.parse(processInfoStr);
86
+ }
87
+ catch (err) {
88
+ if (err && err.code === 'ENOENT') {
89
+ await fs.writeFile(this.processFilePath, JSON.stringify(processInfo), { encoding: 'utf8' });
90
+ }
91
+ }
92
+ return processInfo;
93
+ }
94
+ async updateProgress(progressItem) {
95
+ this.processInfo.push(progressItem);
96
+ await fs.writeFile(this.processFilePath, JSON.stringify(this.processInfo), { encoding: 'utf8' });
97
+ this.curr = this.curr + 1;
98
+ if (this.bar) {
99
+ this.bar?.tick();
100
+ }
101
+ }
102
+ }
103
+
104
+ function randUserAgent({ browser = 'chrome', os = 'mac os', device = 'desktop' }) {
105
+ device = device.toLowerCase();
106
+ browser = browser.toLowerCase();
107
+ os = os.toLowerCase();
108
+ let UA = randUserAgentLib(device, browser, os);
109
+ if (browser === 'chrome') {
110
+ while (UA.includes('Chrome-Lighthouse')
111
+ || UA.includes('Gener8')
112
+ || UA.includes('HeadlessChrome')
113
+ || UA.includes('SMTBot')) {
114
+ UA = randUserAgentLib(device, browser, os);
115
+ }
116
+ }
117
+ if (browser === 'safari') {
118
+ while (UA.includes('Applebot')) {
119
+ UA = randUserAgentLib(device, browser, os);
120
+ }
121
+ }
122
+ return UA;
123
+ }
124
+
125
+ // SUMMARY.md
126
+ function getKnowledgeBaseInfo(url) {
127
+ return axios.get(url, {
128
+ headers: {
129
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
130
+ }
131
+ }).then(({ data = '', status }) => {
132
+ if (status === 200)
133
+ return data;
134
+ return '';
135
+ }).then(html => {
136
+ const data = html.match(config.knowledgeBaseReg) || '';
137
+ if (!data[1])
138
+ return {};
139
+ const jsonData = JSON.parse(decodeURIComponent(data[1]));
140
+ const info = {
141
+ bookId: jsonData.book.id,
142
+ tocList: jsonData.book.toc || [],
143
+ bookName: jsonData.book.name || '',
144
+ bookDesc: jsonData.book.description || '',
145
+ };
146
+ return info;
147
+ });
148
+ }
149
+ async function main(url, options) {
150
+ const { bookId, tocList, bookName, bookDesc } = await getKnowledgeBaseInfo(url);
151
+ if (!bookId)
152
+ throw new Error('No found book id');
153
+ if (!tocList || tocList.length === 0)
154
+ throw new Error('No found toc list');
155
+ const bookPath = `${options.distDir}/${bookId}`;
156
+ await fs.mkdir(bookPath, { recursive: true });
157
+ const total = tocList.length;
158
+ const progress = new Progress(bookPath, total);
159
+ await progress.init();
160
+ if (progress.curr === total) {
161
+ logger.info('√ 已完成');
162
+ return;
163
+ }
164
+ const uuidMap = new Map();
165
+ // 下载中断 重新获取下载进度数据
166
+ if (progress.isDownloadInterrupted) {
167
+ progress.processInfo.forEach(item => {
168
+ uuidMap.set(item.toc.uuid, item);
169
+ });
170
+ }
171
+ const articleUrlPrefix = path.parse(url).dir;
172
+ // const url.split('/')
173
+ for (let i = 0; i < total; i++) {
174
+ const item = tocList[i];
175
+ if (typeof item.type !== 'string')
176
+ continue;
177
+ if (uuidMap.get(item.uuid))
178
+ continue;
179
+ console.log(item.uuid);
180
+ const itemType = item.type.toLocaleLowerCase();
181
+ const dirNameReg = /[\\\/:\*\?"<>\|\n\r]/g;
182
+ // 目录
183
+ if (itemType === 'title' || item['child_uuid'] !== '') {
184
+ let tempItem = item;
185
+ let pathTitleList = [];
186
+ let pathIdList = [];
187
+ while (tempItem) {
188
+ pathTitleList.unshift(tempItem.title.replace(dirNameReg, '_'));
189
+ pathIdList.unshift(tempItem.uuid);
190
+ if (uuidMap.get(tempItem['parent_uuid'])) {
191
+ tempItem = uuidMap.get(tempItem['parent_uuid']).toc;
192
+ }
193
+ else {
194
+ tempItem = undefined;
195
+ }
196
+ }
197
+ const progressItem = {
198
+ path: pathTitleList.join('/'),
199
+ pathTitleList,
200
+ pathIdList,
201
+ toc: item
202
+ };
203
+ await fs.mkdir(`${bookPath}/${pathTitleList.join('/')}`, { recursive: true });
204
+ uuidMap.set(item.uuid, progressItem);
205
+ progress.updateProgress(progressItem);
206
+ }
207
+ else if (item.url) {
208
+ let preItem = {
209
+ path: '',
210
+ pathTitleList: [],
211
+ pathIdList: []
212
+ };
213
+ if (uuidMap.get(item['parent_uuid'])) {
214
+ preItem = uuidMap.get(item['parent_uuid']);
215
+ }
216
+ const fileName = item.title.replace(dirNameReg, '_');
217
+ const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
218
+ const pathIdList = [...preItem.pathIdList, item.uuid];
219
+ const progressItem = {
220
+ path: pathTitleList.join('/'),
221
+ pathTitleList,
222
+ pathIdList,
223
+ toc: item
224
+ };
225
+ const isSuccess = await downloadArticle({
226
+ bookId,
227
+ itemUrl: item.url,
228
+ savePath: `${bookPath}/${preItem.path}`,
229
+ saveFilePath: `${bookPath}/${progressItem.path}`,
230
+ uuid: item.uuid,
231
+ articleUrl: `${articleUrlPrefix}/${item.url}`,
232
+ articleTitle: item.title
233
+ });
234
+ if (isSuccess) {
235
+ uuidMap.set(item.uuid, progressItem);
236
+ progress.updateProgress(progressItem);
237
+ }
238
+ }
239
+ console.log('完成', item.uuid);
240
+ }
241
+ await progress.completePromise;
242
+ logger.info('生成目录 SUMMARY.md');
243
+ await genSummaryFile({
244
+ bookPath,
245
+ bookName,
246
+ bookDesc,
247
+ uuidMap
248
+ });
249
+ if (progress.curr === total) {
250
+ logger.info('√ 已完成');
251
+ return;
252
+ }
253
+ }
254
+ async function downloadArticle(params) {
255
+ const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
256
+ const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
257
+ const response = await axios.get(apiUrl, {
258
+ headers: {
259
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
260
+ },
261
+ params: {
262
+ 'book_id': bookId,
263
+ 'merge_dynamic_data': false,
264
+ mode: 'markdown'
265
+ }
266
+ }).then(({ data, status }) => {
267
+ if (status === 200)
268
+ return data;
269
+ logger.error(`download article error: ${apiUrl} http status ${status}`);
270
+ return null;
271
+ });
272
+ if (!response || !response.data || !response.data.sourcecode)
273
+ return false;
274
+ let mdData = response.data.sourcecode;
275
+ try {
276
+ mdData = await mdImg.run(mdData, {
277
+ dist: savePath,
278
+ imgDir: `img/${uuid}`,
279
+ isIgnoreConsole: true
280
+ });
281
+ }
282
+ catch (err) {
283
+ logger.error(`download article img Error (api: ${apiUrl})`);
284
+ return false;
285
+ }
286
+ mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
287
+ if (articleTitle) {
288
+ mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
289
+ }
290
+ if (articleUrl) {
291
+ mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
292
+ }
293
+ try {
294
+ await fs.writeFile(saveFilePath, mdData);
295
+ return true;
296
+ }
297
+ catch (e) {
298
+ logger.error(`download article write file Error (api: ${apiUrl})`);
299
+ return false;
300
+ }
301
+ }
302
+ async function genSummaryFile(params) {
303
+ const { bookName, bookDesc, bookPath, uuidMap } = params;
304
+ const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
305
+ let mdContent = header;
306
+ const summary = [];
307
+ uuidMap.forEach(processItem => {
308
+ const toc = processItem.toc;
309
+ const parentId = toc['parent_uuid'];
310
+ const findRes = findTree(summary, parentId);
311
+ if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
312
+ if (typeof findRes !== 'boolean') {
313
+ if (!Array.isArray(findRes.children))
314
+ findRes.children = [];
315
+ findRes.children.push({
316
+ id: toc.uuid,
317
+ type: 'title',
318
+ level: findRes.level + 1,
319
+ text: toc.title
320
+ });
321
+ }
322
+ else {
323
+ summary.push({
324
+ id: toc.uuid,
325
+ type: 'title',
326
+ text: toc.title,
327
+ level: 1
328
+ });
329
+ }
330
+ }
331
+ else {
332
+ if (typeof findRes !== 'boolean') {
333
+ if (!Array.isArray(findRes.children))
334
+ findRes.children = [];
335
+ findRes.children.push({
336
+ id: toc.uuid,
337
+ type: 'link',
338
+ level: findRes.level + 1,
339
+ link: processItem.path,
340
+ text: toc.title
341
+ });
342
+ }
343
+ else {
344
+ summary.push({
345
+ id: toc.uuid,
346
+ type: 'link',
347
+ text: toc.title,
348
+ link: processItem.path,
349
+ level: 1
350
+ });
351
+ }
352
+ }
353
+ });
354
+ let summaryContent = genSummaryContent(summary, '');
355
+ mdContent += summaryContent;
356
+ try {
357
+ await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
358
+ }
359
+ catch (err) {
360
+ logger.error('Generate Summary Error');
361
+ }
362
+ }
363
+ function genSummaryContent(summary, summaryContent) {
364
+ for (let i = 0; i < summary.length; i++) {
365
+ const item = summary[i];
366
+ if (item.type === 'title') {
367
+ summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
368
+ }
369
+ else if (item.type === 'link') {
370
+ const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
371
+ summaryContent += `- [${item.text}](${link})\n`;
372
+ }
373
+ if (Array.isArray(item.children)) {
374
+ summaryContent += genSummaryContent(item.children, '');
375
+ }
376
+ }
377
+ return summaryContent;
378
+ }
379
+ function findIdItem(node, id) {
380
+ if (node.id === id) {
381
+ return node;
382
+ }
383
+ else if (node.children) {
384
+ const findRes = findTree(node.children, id);
385
+ if (findRes)
386
+ return findRes;
387
+ }
388
+ return false;
389
+ }
390
+ function findTree(tree, id) {
391
+ if (!id)
392
+ return false;
393
+ for (let i = 0; i < tree.length; i++) {
394
+ const findRes = findIdItem(tree[i], id);
395
+ if (findRes)
396
+ return findRes;
397
+ }
398
+ return false;
399
+ }
400
+
401
+ export { getKnowledgeBaseInfo as g, logger as l, main as m };
@@ -0,0 +1,8 @@
1
+ import 'node:fs/promises';
2
+ import 'node:path';
3
+ import 'axios';
4
+ export { g as getKnowledgeBaseInfo, m as main } from './index-be42878f.js';
5
+ import 'pull-md-img';
6
+ import 'log4js';
7
+ import 'progress';
8
+ import 'rand-user-agent';
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "yuque-dl",
3
+ "version": "1.0.0",
4
+ "description": "yuque 知识库下载",
5
+ "type": "module",
6
+ "bin": {
7
+ "yuque-dl": "bin/index.js"
8
+ },
9
+ "scripts": {
10
+ "dev": "pnpm run build:bundle -w",
11
+ "build": "run-s build:**",
12
+ "build:bundle": "rollup -c rollup.config.ts --configPlugin typescript",
13
+ "build:types": "tsc --emitDeclarationOnly --outDir types -p tsconfig.base.json",
14
+ "test": "echo \"Error: no test specified\" && exit 1"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/gxr404/yuque-dl.git"
19
+ },
20
+ "keywords": [],
21
+ "author": "",
22
+ "license": "ISC",
23
+ "bugs": {
24
+ "url": "https://github.com/gxr404/yuque-dl/issues"
25
+ },
26
+ "homepage": "https://github.com/gxr404/yuque-dl#readme",
27
+ "devDependencies": {
28
+ "@rollup/plugin-json": "^6.0.0",
29
+ "@rollup/plugin-typescript": "^11.1.2",
30
+ "@types/node": "^20.5.0",
31
+ "@types/progress": "^2.0.5",
32
+ "@typescript-eslint/eslint-plugin": "^6.3.0",
33
+ "@typescript-eslint/parser": "^6.3.0",
34
+ "cac": "^6.7.14",
35
+ "jest": "^29.6.2",
36
+ "npm-run-all": "^4.1.5",
37
+ "rollup": "^3.28.0",
38
+ "tslib": "^2.6.1"
39
+ },
40
+ "main": "dist/es/index.js",
41
+ "types": "types/index.d.ts",
42
+ "exports": {
43
+ ".": {
44
+ "types": "./types/index.d.ts",
45
+ "import": "./es/index.js",
46
+ "require": "./cjs/index.js"
47
+ }
48
+ },
49
+ "dependencies": {
50
+ "axios": "^1.4.0",
51
+ "log4js": "^6.9.1",
52
+ "progress": "^2.0.3",
53
+ "pull-md-img": "^0.0.18",
54
+ "rand-user-agent": "1.0.109"
55
+ },
56
+ "engines": {
57
+ "node": "^14.18.0 || >=16.0.0"
58
+ }
59
+ }
@@ -0,0 +1,26 @@
1
+ import { defineConfig } from 'rollup'
2
+ import typescript from '@rollup/plugin-typescript'
3
+ import json from '@rollup/plugin-json'
4
+
5
+ export default defineConfig({
6
+ input: {
7
+ index: 'src/index.ts',
8
+ cli: 'src/cli.ts'
9
+ },
10
+ output:[
11
+ {
12
+ format: "cjs",
13
+ dir: "dist/cjs"
14
+ },
15
+ {
16
+ format: "es",
17
+ dir: "dist/es",
18
+ },
19
+ ],
20
+ plugins: [
21
+ typescript(),
22
+ json()
23
+ ]
24
+ })
25
+
26
+
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "moduleResolution": "node",
6
+ "strict": true,
7
+ "declaration": true,
8
+ "noImplicitOverride": true,
9
+ "noUnusedLocals": true,
10
+ "esModuleInterop": true,
11
+ "useUnknownInCatchVariables": false,
12
+ "resolveJsonModule": true,
13
+ },
14
+ "include": [
15
+ "src/**/*"
16
+ ]
17
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "./tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "declaration": false
5
+ }
6
+ }