@wenyan-md/core 2.0.8 → 3.0.1

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/wechat.js CHANGED
@@ -1,10 +1,10 @@
1
1
  const tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
2
2
  const publishUrl = "https://api.weixin.qq.com/cgi-bin/draft/add";
3
3
  const uploadUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material";
4
- function createWechatClient(adapter) {
4
+ function createWechatClient(httpAdapter) {
5
5
  return {
6
6
  async fetchAccessToken(appId, appSecret) {
7
- const res = await adapter.fetch(
7
+ const res = await httpAdapter.fetch(
8
8
  `${tokenUrl}?grant_type=client_credential&appid=${appId}&secret=${appSecret}`
9
9
  );
10
10
  if (!res.ok) throw new Error(await res.text());
@@ -13,8 +13,8 @@ function createWechatClient(adapter) {
13
13
  return data;
14
14
  },
15
15
  async uploadMaterial(type, file, filename, accessToken) {
16
- const multipart = adapter.createMultipart("media", file, filename);
17
- const res = await adapter.fetch(`${uploadUrl}?access_token=${accessToken}&type=${type}`, {
16
+ const multipart = httpAdapter.createMultipart("media", file, filename);
17
+ const res = await httpAdapter.fetch(`${uploadUrl}?access_token=${accessToken}&type=${type}`, {
18
18
  ...multipart,
19
19
  method: "POST"
20
20
  });
@@ -27,7 +27,7 @@ function createWechatClient(adapter) {
27
27
  return data;
28
28
  },
29
29
  async publishArticle(accessToken, options) {
30
- const res = await adapter.fetch(`${publishUrl}?access_token=${accessToken}`, {
30
+ const res = await httpAdapter.fetch(`${publishUrl}?access_token=${accessToken}`, {
31
31
  method: "POST",
32
32
  body: JSON.stringify({
33
33
  articles: [options]
package/dist/wrapper.js CHANGED
@@ -3,9 +3,110 @@ import { Readable } from "node:stream";
3
3
  import { FormData, File } from "formdata-node";
4
4
  import { FormDataEncoder } from "form-data-encoder";
5
5
  import { JSDOM } from "jsdom";
6
- import { R as RuntimeEnv, r as readBinaryFile, g as getNormalizeFilePath, a as readFileContent, c as configStore, publishToWechatDraft } from "./publish.js";
7
- import { b, d, e, i, m, f, n, s, h, t, j, u } from "./publish.js";
6
+ import fs, { stat } from "node:fs/promises";
7
+ import crypto from "node:crypto";
8
+ import { fileFromPath } from "formdata-node/file-from-path";
9
+ import os from "node:os";
10
+ import { defaultTokenCache, WechatPublisher } from "./publish.js";
8
11
  import { createWenyanCore, getAllGzhThemes } from "./core.js";
12
+ async function readFileContent(filePath) {
13
+ return await fs.readFile(filePath, "utf-8");
14
+ }
15
+ async function readBinaryFile(filePath) {
16
+ return await fs.readFile(filePath);
17
+ }
18
+ async function safeReadJson(file, fallback) {
19
+ try {
20
+ const content = await fs.readFile(file, "utf-8");
21
+ return JSON.parse(content);
22
+ } catch {
23
+ return fallback;
24
+ }
25
+ }
26
+ async function safeWriteJson(file, data) {
27
+ const tmp = file + ".tmp";
28
+ await fs.writeFile(tmp, JSON.stringify(data ?? {}, null, 2), "utf-8");
29
+ await fs.rename(tmp, file);
30
+ }
31
+ async function ensureDir(dir) {
32
+ await fs.mkdir(dir, { recursive: true });
33
+ }
34
+ function md5FromBuffer(buf) {
35
+ return crypto.createHash("md5").update(buf).digest("hex");
36
+ }
37
+ async function md5FromFile(filePath) {
38
+ const buf = await fs.readFile(filePath);
39
+ return md5FromBuffer(buf);
40
+ }
41
+ function normalizePath(p) {
42
+ return p.replace(/\\/g, "/").replace(/\/+$/, "");
43
+ }
44
+ function isAbsolutePath(path2) {
45
+ if (!path2) return false;
46
+ const winAbsPattern = /^[a-zA-Z]:\//;
47
+ const linuxAbsPattern = /^\//;
48
+ return winAbsPattern.test(path2) || linuxAbsPattern.test(path2);
49
+ }
50
+ function getNormalizeFilePath(inputPath) {
51
+ const isContainer = !!process.env.CONTAINERIZED;
52
+ const hostFilePath = normalizePath(process.env.HOST_FILE_PATH || "");
53
+ if (isContainer && hostFilePath) {
54
+ const containerFilePath = normalizePath(process.env.CONTAINER_FILE_PATH || "/mnt/host-downloads");
55
+ let relativePart = normalizePath(inputPath);
56
+ if (relativePart.startsWith(hostFilePath)) {
57
+ relativePart = relativePart.slice(hostFilePath.length);
58
+ }
59
+ if (!relativePart.startsWith("/")) {
60
+ relativePart = "/" + relativePart;
61
+ }
62
+ return containerFilePath + relativePart;
63
+ } else {
64
+ return path.resolve(inputPath);
65
+ }
66
+ }
67
+ const RuntimeEnv = {
68
+ isContainer: !!process.env.CONTAINERIZED,
69
+ hostFilePath: normalizePath(process.env.HOST_FILE_PATH || ""),
70
+ containerFilePath: normalizePath(process.env.CONTAINER_FILE_PATH || "/mnt/host-downloads"),
71
+ resolveLocalPath(inputPath, relativeBase) {
72
+ if (!this.isContainer) {
73
+ if (relativeBase) {
74
+ return path.resolve(relativeBase, inputPath);
75
+ } else {
76
+ if (!path.isAbsolute(inputPath)) {
77
+ throw new Error(
78
+ `Invalid input: '${inputPath}'. InputPath must be an absolute path.`
79
+ );
80
+ }
81
+ return path.normalize(inputPath);
82
+ }
83
+ }
84
+ let normalizedInput = normalizePath(inputPath);
85
+ relativeBase = normalizePath(relativeBase || "");
86
+ if (relativeBase) {
87
+ if (!isAbsolutePath(normalizedInput)) {
88
+ normalizedInput = relativeBase + (normalizedInput.startsWith("/") ? "" : "/") + normalizedInput;
89
+ }
90
+ } else {
91
+ if (!isAbsolutePath(normalizedInput)) {
92
+ throw new Error(
93
+ `Invalid input: '${inputPath}'. InputPath must be an absolute path.`
94
+ );
95
+ }
96
+ }
97
+ if (this.hostFilePath && normalizedInput.startsWith(this.hostFilePath)) {
98
+ let relativePart = normalizedInput.slice(this.hostFilePath.length);
99
+ if (relativePart && !relativePart.startsWith("/")) {
100
+ return normalizedInput;
101
+ }
102
+ if (!relativePart.startsWith("/")) {
103
+ relativePart = "/" + relativePart;
104
+ }
105
+ return this.containerFilePath + relativePart;
106
+ }
107
+ return normalizedInput;
108
+ }
109
+ };
9
110
  function getServerUrl(options) {
10
111
  let serverUrl = options.server || "http://localhost:3000";
11
112
  serverUrl = serverUrl.replace(/\/$/, "");
@@ -168,6 +269,246 @@ async function uploadCover(serverUrl, headers, cover, relativePath) {
168
269
  }
169
270
  return cover;
170
271
  }
272
+ const nodeHttpAdapter = {
273
+ fetch,
274
+ createMultipart(field, file, filename) {
275
+ const form = new FormData();
276
+ form.append(field, file, filename);
277
+ const encoder = new FormDataEncoder(form);
278
+ return {
279
+ body: Readable.from(encoder),
280
+ headers: encoder.headers,
281
+ duplex: "half"
282
+ };
283
+ }
284
+ };
285
+ const defaultConfig = {};
286
+ const configDir = process.env.APPDATA ? path.join(process.env.APPDATA, "wenyan-md") : path.join(os.homedir(), ".config", "wenyan-md");
287
+ const configPath = path.join(configDir, "config.json");
288
+ class ConfigStore {
289
+ config = { ...defaultConfig };
290
+ initPromise;
291
+ constructor() {
292
+ this.initPromise = this.load();
293
+ }
294
+ async load() {
295
+ await ensureDir(configDir);
296
+ this.config = await safeReadJson(configPath, defaultConfig);
297
+ }
298
+ async save() {
299
+ try {
300
+ await ensureDir(configDir);
301
+ await safeWriteJson(configPath, this.config);
302
+ } catch (error) {
303
+ throw new Error(`无法保存配置文件: ${error instanceof Error ? error.message : String(error)}`);
304
+ }
305
+ }
306
+ async getConfig() {
307
+ await this.initPromise;
308
+ return this.config;
309
+ }
310
+ async getThemes() {
311
+ await this.initPromise;
312
+ return Object.values(this.config.themes ?? {});
313
+ }
314
+ async getThemeById(themeId) {
315
+ await this.initPromise;
316
+ const themeOption = this.config.themes?.[themeId];
317
+ if (!themeOption) return void 0;
318
+ const absoluteFilePath = path.join(configDir, themeOption.path);
319
+ try {
320
+ return await fs.readFile(absoluteFilePath, "utf-8");
321
+ } catch {
322
+ return void 0;
323
+ }
324
+ }
325
+ async addThemeToConfig(name, content) {
326
+ await this.initPromise;
327
+ const savedPath = await this.addThemeFile(name, content);
328
+ this.config.themes ??= {};
329
+ this.config.themes[name] = {
330
+ id: name,
331
+ name,
332
+ path: savedPath
333
+ };
334
+ await this.save();
335
+ }
336
+ async addThemeFile(themeId, themeContent) {
337
+ const filePath = `themes/${themeId}.css`;
338
+ const absoluteFilePath = path.join(configDir, filePath);
339
+ await ensureDir(path.dirname(absoluteFilePath));
340
+ await fs.writeFile(absoluteFilePath, themeContent, "utf-8");
341
+ return filePath;
342
+ }
343
+ async deleteThemeFromConfig(themeId) {
344
+ await this.initPromise;
345
+ const theme = this.config.themes?.[themeId];
346
+ if (!theme) return;
347
+ await this.deleteThemeFile(theme.path);
348
+ delete this.config.themes[themeId];
349
+ await this.save();
350
+ }
351
+ async deleteThemeFile(filePath) {
352
+ try {
353
+ await fs.unlink(path.join(configDir, filePath));
354
+ } catch {
355
+ }
356
+ }
357
+ }
358
+ const configStore = new ConfigStore();
359
+ const tokenPath = path.join(configDir, "token.json");
360
+ class NodeTokenStorageAdapter {
361
+ async loadToken() {
362
+ await ensureDir(configDir);
363
+ return await safeReadJson(tokenPath, defaultTokenCache);
364
+ }
365
+ async saveToken(cache) {
366
+ await ensureDir(configDir);
367
+ await safeWriteJson(tokenPath, cache);
368
+ }
369
+ async clearToken() {
370
+ try {
371
+ await fs.unlink(tokenPath);
372
+ } catch (error) {
373
+ if (error.code !== "ENOENT") {
374
+ throw error;
375
+ }
376
+ }
377
+ }
378
+ }
379
+ const cachePath = path.join(configDir, "upload-cache.json");
380
+ class NodeUploadCacheAdapter {
381
+ async loadCache() {
382
+ await ensureDir(configDir);
383
+ return await safeReadJson(cachePath, {});
384
+ }
385
+ async saveCache(cache) {
386
+ await ensureDir(configDir);
387
+ await safeWriteJson(cachePath, cache);
388
+ }
389
+ async clearCache() {
390
+ try {
391
+ await fs.unlink(cachePath);
392
+ } catch (error) {
393
+ if (error.code !== "ENOENT") {
394
+ throw error;
395
+ }
396
+ }
397
+ }
398
+ async calcHash(buffer) {
399
+ return crypto.createHash("md5").update(Buffer.from(buffer)).digest("hex");
400
+ }
401
+ }
402
+ const mediaIdMapping = /* @__PURE__ */ new Map();
403
+ const wechatPublisher = new WechatPublisher(nodeHttpAdapter, new NodeTokenStorageAdapter(), new NodeUploadCacheAdapter());
404
+ async function uploadImage(imageUrl, accessToken, fileName, relativePath) {
405
+ let fileData;
406
+ let finalName;
407
+ if (imageUrl.startsWith("http")) {
408
+ const response = await fetch(imageUrl);
409
+ if (!response.ok || !response.body) {
410
+ throw new Error(`下载图片失败 URL: ${imageUrl}`);
411
+ }
412
+ const arrayBuffer = await response.arrayBuffer();
413
+ if (arrayBuffer.byteLength === 0) {
414
+ throw new Error(`远程图片大小为0,无法上传: ${imageUrl}`);
415
+ }
416
+ const fileNameFromUrl = path.basename(imageUrl.split("?")[0]);
417
+ const ext = path.extname(fileNameFromUrl);
418
+ finalName = fileName ?? (ext === "" ? `${fileNameFromUrl}.jpg` : fileNameFromUrl);
419
+ const contentType = response.headers.get("content-type") || "image/jpeg";
420
+ fileData = new Blob([arrayBuffer], { type: contentType });
421
+ } else {
422
+ const resolvedPath = RuntimeEnv.resolveLocalPath(imageUrl, relativePath);
423
+ const stats = await stat(resolvedPath);
424
+ if (stats.size === 0) {
425
+ throw new Error(`本地图片大小为0,无法上传: ${resolvedPath}`);
426
+ }
427
+ const fileNameFromLocal = path.basename(resolvedPath);
428
+ const ext = path.extname(fileNameFromLocal);
429
+ finalName = fileName ?? (ext === "" ? `${fileNameFromLocal}.jpg` : fileNameFromLocal);
430
+ const fileFromPathResult = await fileFromPath(resolvedPath);
431
+ fileData = new Blob([await fileFromPathResult.arrayBuffer()], { type: fileFromPathResult.type });
432
+ }
433
+ const data = await wechatPublisher.uploadImage(fileData, finalName, accessToken);
434
+ mediaIdMapping.set(data.url, data.media_id);
435
+ return data;
436
+ }
437
+ async function uploadImages(content, accessToken, relativePath) {
438
+ if (!content.includes("<img")) {
439
+ return { html: content, firstImageId: "" };
440
+ }
441
+ const dom = new JSDOM(content);
442
+ const document = dom.window.document;
443
+ const images = Array.from(document.querySelectorAll("img"));
444
+ const uploadPromises = images.map(async (element) => {
445
+ const dataSrc = element.getAttribute("src");
446
+ if (dataSrc) {
447
+ if (!dataSrc.startsWith("https://mmbiz.qpic.cn")) {
448
+ const resp = await uploadImage(dataSrc, accessToken, void 0, relativePath);
449
+ element.setAttribute("src", resp.url);
450
+ return resp.media_id;
451
+ } else {
452
+ return dataSrc;
453
+ }
454
+ }
455
+ return null;
456
+ });
457
+ const mediaIds = (await Promise.all(uploadPromises)).filter(Boolean);
458
+ const firstImageId = mediaIds[0] || "";
459
+ const updatedHtml = dom.serialize();
460
+ return { html: updatedHtml, firstImageId };
461
+ }
462
+ async function publishToWechatDraft(articleOptions, publishOptions = {}) {
463
+ const { title, content, cover, author, source_url } = articleOptions;
464
+ const { appId, appSecret, relativePath } = publishOptions;
465
+ const appIdFinal = appId ?? process.env.WECHAT_APP_ID;
466
+ const appSecretFinal = appSecret ?? process.env.WECHAT_APP_SECRET;
467
+ if (!appIdFinal || !appSecretFinal) {
468
+ throw new Error("请通过参数或环境变量 WECHAT_APP_ID / WECHAT_APP_SECRET 提供公众号凭据");
469
+ }
470
+ const accessToken = await wechatPublisher.getAccessTokenWithCache(appIdFinal, appSecretFinal);
471
+ const { html, firstImageId } = await uploadImages(content, accessToken, relativePath);
472
+ let thumbMediaId = "";
473
+ if (cover) {
474
+ const cachedThumbMediaId = mediaIdMapping.get(cover);
475
+ if (cachedThumbMediaId) {
476
+ thumbMediaId = cachedThumbMediaId;
477
+ } else {
478
+ const resp = await uploadImage(cover, accessToken, "cover.jpg", relativePath);
479
+ thumbMediaId = resp.media_id;
480
+ }
481
+ } else {
482
+ if (firstImageId.startsWith("https://mmbiz.qpic.cn")) {
483
+ const cachedThumbMediaId = mediaIdMapping.get(firstImageId);
484
+ if (cachedThumbMediaId) {
485
+ thumbMediaId = cachedThumbMediaId;
486
+ } else {
487
+ const resp = await uploadImage(firstImageId, accessToken, "cover.jpg", relativePath);
488
+ thumbMediaId = resp.media_id;
489
+ }
490
+ } else {
491
+ thumbMediaId = firstImageId;
492
+ }
493
+ }
494
+ if (!thumbMediaId) {
495
+ throw new Error("你必须指定一张封面图或者在正文中至少出现一张图片。");
496
+ }
497
+ const data = await wechatPublisher.publishToDraft(accessToken, {
498
+ title,
499
+ content: html,
500
+ thumb_media_id: thumbMediaId,
501
+ author,
502
+ content_source_url: source_url
503
+ });
504
+ if (data.media_id) {
505
+ return data;
506
+ }
507
+ throw new Error(`上传到公众号草稿失败: ${JSON.stringify(data)}`);
508
+ }
509
+ async function publishToDraft(title, content, cover = "", options = {}) {
510
+ return publishToWechatDraft({ title, content, cover }, options);
511
+ }
171
512
  const wenyanCoreInstance = await createWenyanCore();
172
513
  async function renderWithTheme(markdownContent, options) {
173
514
  if (!markdownContent) {
@@ -176,8 +517,8 @@ async function renderWithTheme(markdownContent, options) {
176
517
  const { theme, customTheme, highlight, macStyle, footnote } = options;
177
518
  let handledCustomTheme = customTheme;
178
519
  if (customTheme) {
179
- const normalizePath = getNormalizeFilePath(customTheme);
180
- handledCustomTheme = await readFileContent(normalizePath);
520
+ const normalizePath2 = getNormalizeFilePath(customTheme);
521
+ handledCustomTheme = await readFileContent(normalizePath2);
181
522
  } else if (theme) {
182
523
  handledCustomTheme = await configStore.getThemeById(theme);
183
524
  }
@@ -252,8 +593,8 @@ async function addTheme(name, path2) {
252
593
  const content = await response.text();
253
594
  await configStore.addThemeToConfig(name, content);
254
595
  } else {
255
- const normalizePath = getNormalizeFilePath(path2);
256
- const content = await readFileContent(normalizePath);
596
+ const normalizePath2 = getNormalizeFilePath(path2);
597
+ const content = await readFileContent(normalizePath2);
257
598
  await configStore.addThemeToConfig(name, content);
258
599
  }
259
600
  }
@@ -318,18 +659,20 @@ async function renderAndPublishToServer(inputContent, options, getInputContent)
318
659
  }
319
660
  export {
320
661
  addTheme,
321
- b as configDir,
322
- d as configPath,
662
+ configDir,
663
+ configPath,
323
664
  configStore,
324
- e as ensureDir,
665
+ ensureDir,
325
666
  getGzhContent,
326
667
  getNormalizeFilePath,
327
- i as isAbsolutePath,
668
+ isAbsolutePath,
328
669
  listThemes,
329
- m as md5FromBuffer,
330
- f as md5FromFile,
331
- n as normalizePath,
670
+ md5FromBuffer,
671
+ md5FromFile,
672
+ normalizePath,
332
673
  prepareRenderContext,
674
+ publishToDraft,
675
+ publishToWechatDraft,
333
676
  readBinaryFile,
334
677
  readFileContent,
335
678
  removeTheme,
@@ -337,9 +680,6 @@ export {
337
680
  renderAndPublishToServer,
338
681
  renderStyledContent,
339
682
  renderWithTheme,
340
- s as safeReadJson,
341
- h as safeWriteJson,
342
- t as tokenPath,
343
- j as tokenStore,
344
- u as uploadCacheStore
683
+ safeReadJson,
684
+ safeWriteJson
345
685
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wenyan-md/core",
3
- "version": "2.0.8",
3
+ "version": "3.0.1",
4
4
  "description": "Core library for Wenyan markdown rendering & publishing",
5
5
  "author": "Lei <caol64@gmail.com> (https://github.com/caol64)",
6
6
  "license": "Apache-2.0",
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "./publish": {
34
34
  "import": "./dist/publish.js",
35
- "types": "./dist/types/node/publish.d.ts"
35
+ "types": "./dist/types/publish.d.ts"
36
36
  },
37
37
  "./wrapper": {
38
38
  "import": "./dist/wrapper.js",
@@ -43,6 +43,7 @@
43
43
  "types": "./dist/types/wechat.d.ts"
44
44
  },
45
45
  "./http": {
46
+ "import": "./dist/http.js",
46
47
  "types": "./dist/types/http.d.ts"
47
48
  }
48
49
  },
@@ -1,2 +0,0 @@
1
- import { HttpAdapter } from "../http.js";
2
- export declare const browserHttpAdapter: HttpAdapter;
@@ -1,16 +0,0 @@
1
- export interface MediaInfo {
2
- media_id: string;
3
- url: string;
4
- updated_at?: number;
5
- }
6
- declare class UploadCacheStore {
7
- private cache;
8
- private initPromise;
9
- constructor();
10
- private load;
11
- private save;
12
- get(md5: string): Promise<MediaInfo | undefined>;
13
- set(md5: string, mediaId: string, url: string): Promise<void>;
14
- }
15
- export declare const uploadCacheStore: UploadCacheStore;
16
- export {};