mirror of
https://github.com/JimLiu/baoyu-skills.git
synced 2026-07-15 15:09:48 +08:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 28a7db6129 | |||
| 7c5e81fd15 | |||
| 058d25d02c | |||
| fe09ec546f | |||
| cf611a4514 |
@@ -6,7 +6,7 @@
|
|||||||
},
|
},
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"description": "Skills shared by Baoyu for improving daily work efficiency",
|
"description": "Skills shared by Baoyu for improving daily work efficiency",
|
||||||
"version": "1.25.1"
|
"version": "1.25.4"
|
||||||
},
|
},
|
||||||
"plugins": [
|
"plugins": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,24 @@
|
|||||||
|
|
||||||
English | [中文](./CHANGELOG.zh.md)
|
English | [中文](./CHANGELOG.zh.md)
|
||||||
|
|
||||||
|
## 1.25.4 - 2026-01-29
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- `baoyu-markdown-to-html`: generate proper `<img>` tags with `data-local-path` attribute instead of text placeholders.
|
||||||
|
- `baoyu-post-to-wechat`: fix API publishing to read image paths from `data-local-path` attribute; fix title/cover extraction from corresponding `.md` frontmatter when publishing HTML files.
|
||||||
|
- `baoyu-post-to-wechat`: fix CLI argument parsing to handle unknown parameters gracefully; add `--summary` parameter support.
|
||||||
|
- `baoyu-post-to-wechat`: fix browser publishing to convert `<img>` tags back to text placeholders before paste.
|
||||||
|
|
||||||
|
## 1.25.3 - 2026-01-28
|
||||||
|
|
||||||
|
### Features
|
||||||
|
- `baoyu-format-markdown`: add content type detection with user confirmation for markdown files; add CJK punctuation handling to move paired punctuation outside emphasis markers.
|
||||||
|
|
||||||
|
## 1.25.2 - 2026-01-28
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- `baoyu-post-to-wechat`: add WeChat API credentials configuration guide to README.
|
||||||
|
|
||||||
## 1.25.1 - 2026-01-28
|
## 1.25.1 - 2026-01-28
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
@@ -2,6 +2,24 @@
|
|||||||
|
|
||||||
[English](./CHANGELOG.md) | 中文
|
[English](./CHANGELOG.md) | 中文
|
||||||
|
|
||||||
|
## 1.25.4 - 2026-01-29
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
- `baoyu-markdown-to-html`:生成带 `data-local-path` 属性的 `<img>` 标签,而非纯文本占位符。
|
||||||
|
- `baoyu-post-to-wechat`:修复 API 发布时从 `data-local-path` 属性读取图片路径;修复发布 HTML 文件时从对应 `.md` 的 frontmatter 提取标题和封面图。
|
||||||
|
- `baoyu-post-to-wechat`:修复命令行参数解析,正确跳过未知参数;新增 `--summary` 参数支持。
|
||||||
|
- `baoyu-post-to-wechat`:修复浏览器发布模式,粘贴前将 `<img>` 标签转换回文本占位符。
|
||||||
|
|
||||||
|
## 1.25.3 - 2026-01-28
|
||||||
|
|
||||||
|
### 新功能
|
||||||
|
- `baoyu-format-markdown`:新增内容类型检测,对已有 markdown 格式的文件提供用户确认选项;新增 CJK 配对标点处理,将括号、引号等标点移出加粗标记外。
|
||||||
|
|
||||||
|
## 1.25.2 - 2026-01-28
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
- `baoyu-post-to-wechat`:README 新增微信公众号 API 凭证配置说明。
|
||||||
|
|
||||||
## 1.25.1 - 2026-01-28
|
## 1.25.1 - 2026-01-28
|
||||||
|
|
||||||
### 新功能
|
### 新功能
|
||||||
|
|||||||
@@ -535,7 +535,28 @@ Post content to WeChat Official Account (微信公众号). Two modes available:
|
|||||||
/baoyu-post-to-wechat 文章 --html article.html
|
/baoyu-post-to-wechat 文章 --html article.html
|
||||||
```
|
```
|
||||||
|
|
||||||
Prerequisites: Google Chrome installed. First run requires QR code login (session preserved).
|
**Publishing Methods**:
|
||||||
|
|
||||||
|
| Method | Speed | Requirements |
|
||||||
|
|--------|-------|--------------|
|
||||||
|
| API (Recommended) | Fast | API credentials |
|
||||||
|
| Browser | Slow | Chrome, login session |
|
||||||
|
|
||||||
|
**API Configuration** (for faster publishing):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add to .baoyu-skills/.env (project-level) or ~/.baoyu-skills/.env (user-level)
|
||||||
|
WECHAT_APP_ID=your_app_id
|
||||||
|
WECHAT_APP_SECRET=your_app_secret
|
||||||
|
```
|
||||||
|
|
||||||
|
To obtain credentials:
|
||||||
|
1. Visit https://developers.weixin.qq.com/platform/
|
||||||
|
2. Go to: 我的业务 → 公众号 → 开发密钥
|
||||||
|
3. Create development key and copy AppID/AppSecret
|
||||||
|
4. Add your machine's IP to the whitelist
|
||||||
|
|
||||||
|
**Browser Method** (no API setup needed): Requires Google Chrome. First run opens browser for QR code login (session preserved).
|
||||||
|
|
||||||
### AI Generation Skills
|
### AI Generation Skills
|
||||||
|
|
||||||
|
|||||||
+22
-1
@@ -535,7 +535,28 @@ npx skills add jimliu/baoyu-skills
|
|||||||
/baoyu-post-to-wechat 文章 --html article.html
|
/baoyu-post-to-wechat 文章 --html article.html
|
||||||
```
|
```
|
||||||
|
|
||||||
前置要求:已安装 Google Chrome,首次运行需扫码登录(登录状态会保存)
|
**发布方式**:
|
||||||
|
|
||||||
|
| 方式 | 速度 | 要求 |
|
||||||
|
|------|------|------|
|
||||||
|
| API(推荐) | 快 | API 凭证 |
|
||||||
|
| 浏览器 | 慢 | Chrome,登录会话 |
|
||||||
|
|
||||||
|
**API 配置**(更快的发布方式):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 添加到 .baoyu-skills/.env(项目级)或 ~/.baoyu-skills/.env(用户级)
|
||||||
|
WECHAT_APP_ID=你的AppID
|
||||||
|
WECHAT_APP_SECRET=你的AppSecret
|
||||||
|
```
|
||||||
|
|
||||||
|
获取凭证方法:
|
||||||
|
1. 访问 https://developers.weixin.qq.com/platform/
|
||||||
|
2. 进入:我的业务 → 公众号 → 开发密钥
|
||||||
|
3. 添加开发密钥,复制 AppID 和 AppSecret
|
||||||
|
4. 将你操作的机器 IP 加入白名单
|
||||||
|
|
||||||
|
**浏览器方式**(无需 API 配置):需已安装 Google Chrome,首次运行需扫码登录(登录状态会保存)
|
||||||
|
|
||||||
### AI 生成技能 (AI Generation Skills)
|
### AI 生成技能 (AI Generation Skills)
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,55 @@ Claude performs content analysis and formatting (Steps 1-6), then runs the scrip
|
|||||||
|
|
||||||
Read the user-specified markdown or plain text file.
|
Read the user-specified markdown or plain text file.
|
||||||
|
|
||||||
|
### Step 1.5: Detect Content Type & Confirm
|
||||||
|
|
||||||
|
**Content Type Detection:**
|
||||||
|
|
||||||
|
| Indicator | Classification |
|
||||||
|
|-----------|----------------|
|
||||||
|
| Has `---` YAML frontmatter | Markdown |
|
||||||
|
| Has `#`, `##`, `###` headings | Markdown |
|
||||||
|
| Has `**bold**`, `*italic*` | Markdown |
|
||||||
|
| Has `- ` or `1. ` lists | Markdown |
|
||||||
|
| Has ``` code blocks | Markdown |
|
||||||
|
| Has `> ` blockquotes | Markdown |
|
||||||
|
| None of above | Plain text |
|
||||||
|
|
||||||
|
**Decision Flow:**
|
||||||
|
|
||||||
|
┌─────────────────┬────────────────────────────────────────────────┐
|
||||||
|
│ Content Type │ Action │
|
||||||
|
├─────────────────┼────────────────────────────────────────────────┤
|
||||||
|
│ Plain text │ Proceed to Step 2 (format to markdown) │
|
||||||
|
├─────────────────┼────────────────────────────────────────────────┤
|
||||||
|
│ Markdown │ Use AskUserQuestion to confirm optimization │
|
||||||
|
└─────────────────┴────────────────────────────────────────────────┘
|
||||||
|
|
||||||
|
**If Markdown detected, ask user:**
|
||||||
|
|
||||||
|
```
|
||||||
|
Detected existing markdown formatting. What would you like to do?
|
||||||
|
|
||||||
|
1. Optimize formatting (Recommended)
|
||||||
|
- Add/improve frontmatter, headings, bold, lists
|
||||||
|
- Run typography script (spacing, emphasis fixes)
|
||||||
|
- Output: {filename}-formatted.md
|
||||||
|
|
||||||
|
2. Keep original formatting
|
||||||
|
- Preserve existing markdown structure
|
||||||
|
- Run typography script (spacing, emphasis fixes)
|
||||||
|
- Output: {filename}-formatted.md
|
||||||
|
|
||||||
|
3. Typography fixes only
|
||||||
|
- Run typography script on original file in-place
|
||||||
|
- No copy created, modifies original file directly
|
||||||
|
```
|
||||||
|
|
||||||
|
**Based on user choice:**
|
||||||
|
- **Optimize**: Continue to Step 2-8 (full workflow)
|
||||||
|
- **Keep original**: Skip Steps 2-5, copy file → Step 6-8 (run script on copy)
|
||||||
|
- **Typography only**: Skip Steps 2-6, run Step 7 on original file directly
|
||||||
|
|
||||||
### Step 2: Analyze Content Structure
|
### Step 2: Analyze Content Structure
|
||||||
|
|
||||||
Identify:
|
Identify:
|
||||||
@@ -138,6 +187,10 @@ Examples:
|
|||||||
- `final.md` → `final-formatted.md`
|
- `final.md` → `final-formatted.md`
|
||||||
- `draft-v1.md` → `draft-v1-formatted.md`
|
- `draft-v1.md` → `draft-v1-formatted.md`
|
||||||
|
|
||||||
|
**If user chose "Keep original formatting" (from Step 1.5):**
|
||||||
|
- Copy original file to `{filename}-formatted.md` without modifications
|
||||||
|
- Proceed to Step 7 for typography fixes only
|
||||||
|
|
||||||
**Backup existing file:**
|
**Backup existing file:**
|
||||||
|
|
||||||
If `{filename}-formatted.md` already exists, backup before overwriting:
|
If `{filename}-formatted.md` already exists, backup before overwriting:
|
||||||
|
|||||||
@@ -11,6 +11,21 @@ export const CJK_CHAR_RE = new RegExp(`[${CJK_SCRIPTS}]`, "u");
|
|||||||
const PUNCT_OR_SYMBOL_RE = /[\p{P}\p{S}]/u;
|
const PUNCT_OR_SYMBOL_RE = /[\p{P}\p{S}]/u;
|
||||||
const WORD_CHAR_RE = /[\p{L}\p{N}]/u;
|
const WORD_CHAR_RE = /[\p{L}\p{N}]/u;
|
||||||
|
|
||||||
|
const CJK_PUNCT_PAIRS: Record<string, string> = {
|
||||||
|
"“": "”",
|
||||||
|
"‘": "’",
|
||||||
|
"(": ")",
|
||||||
|
"〔": "〕",
|
||||||
|
"〖": "〗",
|
||||||
|
"〘": "〙",
|
||||||
|
"〚": "〛",
|
||||||
|
"「": "」",
|
||||||
|
"『": "』",
|
||||||
|
"〈": "〉",
|
||||||
|
"《": "》",
|
||||||
|
"【": "】",
|
||||||
|
};
|
||||||
|
|
||||||
function findInlineCodeRanges(text: string): Array<[number, number]> {
|
function findInlineCodeRanges(text: string): Array<[number, number]> {
|
||||||
const ranges: Array<[number, number]> = [];
|
const ranges: Array<[number, number]> = [];
|
||||||
let i = 0;
|
let i = 0;
|
||||||
@@ -69,8 +84,120 @@ function isPunctuationOrSymbol(ch: string | undefined): boolean {
|
|||||||
return !!ch && PUNCT_OR_SYMBOL_RE.test(ch);
|
return !!ch && PUNCT_OR_SYMBOL_RE.test(ch);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fixCjkEmphasisSpacingInBlock(block: string): string {
|
function isMatchingCjkPunct(open: string, close: string): boolean {
|
||||||
|
return CJK_PUNCT_PAIRS[open] === close;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapNonCodeSegments(
|
||||||
|
block: string,
|
||||||
|
mapper: (segment: string) => string
|
||||||
|
): string {
|
||||||
const codeRanges = findInlineCodeRanges(block);
|
const codeRanges = findInlineCodeRanges(block);
|
||||||
|
if (codeRanges.length === 0) {
|
||||||
|
return mapper(block);
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = "";
|
||||||
|
let lastIndex = 0;
|
||||||
|
for (const [start, end] of codeRanges) {
|
||||||
|
if (start > lastIndex) {
|
||||||
|
result += mapper(block.slice(lastIndex, start));
|
||||||
|
}
|
||||||
|
result += block.slice(start, end + 1);
|
||||||
|
lastIndex = end + 1;
|
||||||
|
}
|
||||||
|
if (lastIndex < block.length) {
|
||||||
|
result += mapper(block.slice(lastIndex));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveCjkPunctuationOutsideEmphasis(block: string): string {
|
||||||
|
return mapNonCodeSegments(block, (segment) => {
|
||||||
|
const delimiterPositions: number[] = [];
|
||||||
|
let cursor = 0;
|
||||||
|
while (cursor < segment.length - 1) {
|
||||||
|
if (
|
||||||
|
segment[cursor] === "*" &&
|
||||||
|
segment[cursor + 1] === "*" &&
|
||||||
|
segment[cursor - 1] !== "*" &&
|
||||||
|
segment[cursor + 2] !== "*" &&
|
||||||
|
!isEscaped(segment, cursor)
|
||||||
|
) {
|
||||||
|
delimiterPositions.push(cursor);
|
||||||
|
cursor += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cursor += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delimiterPositions.length < 2) return segment;
|
||||||
|
|
||||||
|
const stack: number[] = [];
|
||||||
|
const pairs: Array<{ open: number; close: number }> = [];
|
||||||
|
for (const pos of delimiterPositions) {
|
||||||
|
if (stack.length === 0) {
|
||||||
|
stack.push(pos);
|
||||||
|
} else {
|
||||||
|
const open = stack.pop() as number;
|
||||||
|
pairs.push({ open, close: pos });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const skip = new Set<number>();
|
||||||
|
const insertBefore = new Map<number, string>();
|
||||||
|
|
||||||
|
for (const pair of pairs) {
|
||||||
|
const openPunctPos = pair.open + 2;
|
||||||
|
const closePunctPos = pair.close - 1;
|
||||||
|
if (openPunctPos >= closePunctPos) continue;
|
||||||
|
|
||||||
|
const openPunct = segment[openPunctPos];
|
||||||
|
const closePunct = segment[closePunctPos];
|
||||||
|
if (!openPunct || !closePunct) continue;
|
||||||
|
if (!CJK_OPENING_PUNCT_RE.test(openPunct)) continue;
|
||||||
|
if (!CJK_CLOSING_PUNCT_RE.test(closePunct)) continue;
|
||||||
|
if (!isMatchingCjkPunct(openPunct, closePunct)) continue;
|
||||||
|
if (openPunctPos + 1 >= closePunctPos) continue;
|
||||||
|
|
||||||
|
const inner = segment.slice(openPunctPos + 1, closePunctPos);
|
||||||
|
if (inner.length === 0) continue;
|
||||||
|
|
||||||
|
skip.add(openPunctPos);
|
||||||
|
skip.add(closePunctPos);
|
||||||
|
|
||||||
|
insertBefore.set(pair.open, (insertBefore.get(pair.open) ?? "") + openPunct);
|
||||||
|
const afterClose = pair.close + 2;
|
||||||
|
insertBefore.set(
|
||||||
|
afterClose,
|
||||||
|
(insertBefore.get(afterClose) ?? "") + closePunct
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skip.size === 0) return segment;
|
||||||
|
|
||||||
|
let result = "";
|
||||||
|
for (let idx = 0; idx < segment.length; idx += 1) {
|
||||||
|
const insert = insertBefore.get(idx);
|
||||||
|
if (insert) {
|
||||||
|
result += insert;
|
||||||
|
}
|
||||||
|
if (skip.has(idx)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result += segment[idx];
|
||||||
|
}
|
||||||
|
const tailInsert = insertBefore.get(segment.length);
|
||||||
|
if (tailInsert) {
|
||||||
|
result += tailInsert;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixCjkEmphasisSpacingInBlock(block: string): string {
|
||||||
|
const normalized = moveCjkPunctuationOutsideEmphasis(block);
|
||||||
|
const codeRanges = findInlineCodeRanges(normalized);
|
||||||
let rangeIndex = 0;
|
let rangeIndex = 0;
|
||||||
|
|
||||||
const delimiters: Array<{
|
const delimiters: Array<{
|
||||||
@@ -79,7 +206,7 @@ function fixCjkEmphasisSpacingInBlock(block: string): string {
|
|||||||
canClose: boolean;
|
canClose: boolean;
|
||||||
}> = [];
|
}> = [];
|
||||||
let cursor = 0;
|
let cursor = 0;
|
||||||
while (cursor < block.length - 1) {
|
while (cursor < normalized.length - 1) {
|
||||||
if (rangeIndex < codeRanges.length && cursor >= codeRanges[rangeIndex][0]) {
|
if (rangeIndex < codeRanges.length && cursor >= codeRanges[rangeIndex][0]) {
|
||||||
if (cursor <= codeRanges[rangeIndex][1]) {
|
if (cursor <= codeRanges[rangeIndex][1]) {
|
||||||
cursor = codeRanges[rangeIndex][1] + 1;
|
cursor = codeRanges[rangeIndex][1] + 1;
|
||||||
@@ -90,14 +217,14 @@ function fixCjkEmphasisSpacingInBlock(block: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
block[cursor] === "*" &&
|
normalized[cursor] === "*" &&
|
||||||
block[cursor + 1] === "*" &&
|
normalized[cursor + 1] === "*" &&
|
||||||
block[cursor - 1] !== "*" &&
|
normalized[cursor - 1] !== "*" &&
|
||||||
block[cursor + 2] !== "*" &&
|
normalized[cursor + 2] !== "*" &&
|
||||||
!isEscaped(block, cursor)
|
!isEscaped(normalized, cursor)
|
||||||
) {
|
) {
|
||||||
const before = block[cursor - 1];
|
const before = normalized[cursor - 1];
|
||||||
const after = block[cursor + 2];
|
const after = normalized[cursor + 2];
|
||||||
const beforeIsSpace = isWhitespaceChar(before);
|
const beforeIsSpace = isWhitespaceChar(before);
|
||||||
const afterIsSpace = isWhitespaceChar(after);
|
const afterIsSpace = isWhitespaceChar(after);
|
||||||
const beforeIsPunct = isPunctuationOrSymbol(before);
|
const beforeIsPunct = isPunctuationOrSymbol(before);
|
||||||
@@ -140,12 +267,12 @@ function fixCjkEmphasisSpacingInBlock(block: string): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pairs.length === 0) return block;
|
if (pairs.length === 0) return normalized;
|
||||||
|
|
||||||
const insertPositions = new Set<number>();
|
const insertPositions = new Set<number>();
|
||||||
for (const pair of pairs) {
|
for (const pair of pairs) {
|
||||||
const insideLast = block[pair.close - 1];
|
const insideLast = normalized[pair.close - 1];
|
||||||
const afterClose = block[pair.close + 2];
|
const afterClose = normalized[pair.close + 2];
|
||||||
if (!afterClose) continue;
|
if (!afterClose) continue;
|
||||||
if (
|
if (
|
||||||
CJK_CLOSING_PUNCT_RE.test(insideLast) &&
|
CJK_CLOSING_PUNCT_RE.test(insideLast) &&
|
||||||
@@ -155,16 +282,16 @@ function fixCjkEmphasisSpacingInBlock(block: string): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (insertPositions.size === 0) return block;
|
if (insertPositions.size === 0) return normalized;
|
||||||
|
|
||||||
let result = "";
|
let result = "";
|
||||||
for (let idx = 0; idx < block.length; idx += 1) {
|
for (let idx = 0; idx < normalized.length; idx += 1) {
|
||||||
if (insertPositions.has(idx)) {
|
if (insertPositions.has(idx)) {
|
||||||
result += " ";
|
result += " ";
|
||||||
}
|
}
|
||||||
result += block[idx];
|
result += normalized[idx];
|
||||||
}
|
}
|
||||||
if (insertPositions.has(block.length)) {
|
if (insertPositions.has(normalized.length)) {
|
||||||
result += " ";
|
result += " ";
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -214,7 +214,6 @@ export async function convertMarkdown(markdownPath: string, options?: { title?:
|
|||||||
}
|
}
|
||||||
|
|
||||||
fs.copyFileSync(tempHtmlPath, finalHtmlPath);
|
fs.copyFileSync(tempHtmlPath, finalHtmlPath);
|
||||||
console.error(`[markdown-to-html] HTML saved to: ${finalHtmlPath}`);
|
|
||||||
|
|
||||||
const contentImages: ImageInfo[] = [];
|
const contentImages: ImageInfo[] = [];
|
||||||
for (const img of images) {
|
for (const img of images) {
|
||||||
@@ -226,6 +225,15 @@ export async function convertMarkdown(markdownPath: string, options?: { title?:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let htmlContent = fs.readFileSync(finalHtmlPath, 'utf-8');
|
||||||
|
for (const img of contentImages) {
|
||||||
|
const imgTag = `<img src="${img.placeholder}" data-local-path="${img.localPath}" style="display: block; width: 100%; margin: 1.5em auto;">`;
|
||||||
|
htmlContent = htmlContent.replace(img.placeholder, imgTag);
|
||||||
|
}
|
||||||
|
fs.writeFileSync(finalHtmlPath, htmlContent, 'utf-8');
|
||||||
|
|
||||||
|
console.error(`[markdown-to-html] HTML saved to: ${finalHtmlPath}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title,
|
title,
|
||||||
author,
|
author,
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ async function uploadImagesInHtml(
|
|||||||
accessToken: string,
|
accessToken: string,
|
||||||
baseDir: string
|
baseDir: string
|
||||||
): Promise<{ html: string; firstMediaId: string }> {
|
): Promise<{ html: string; firstMediaId: string }> {
|
||||||
const imgRegex = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
|
const imgRegex = /<img[^>]*\ssrc=["']([^"']+)["'][^>]*>/gi;
|
||||||
const matches = [...html.matchAll(imgRegex)];
|
const matches = [...html.matchAll(imgRegex)];
|
||||||
|
|
||||||
if (matches.length === 0) {
|
if (matches.length === 0) {
|
||||||
@@ -188,7 +188,7 @@ async function uploadImagesInHtml(
|
|||||||
let updatedHtml = html;
|
let updatedHtml = html;
|
||||||
|
|
||||||
for (const match of matches) {
|
for (const match of matches) {
|
||||||
const [, src] = match;
|
const [fullTag, src] = match;
|
||||||
if (!src) continue;
|
if (!src) continue;
|
||||||
|
|
||||||
if (src.startsWith("https://mmbiz.qpic.cn")) {
|
if (src.startsWith("https://mmbiz.qpic.cn")) {
|
||||||
@@ -198,15 +198,21 @@ async function uploadImagesInHtml(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(`[wechat-api] Uploading image: ${src}`);
|
const localPathMatch = fullTag.match(/data-local-path=["']([^"']+)["']/);
|
||||||
|
const imagePath = localPathMatch ? localPathMatch[1]! : src;
|
||||||
|
|
||||||
|
console.error(`[wechat-api] Uploading image: ${imagePath}`);
|
||||||
try {
|
try {
|
||||||
const resp = await uploadImage(src, accessToken, baseDir);
|
const resp = await uploadImage(imagePath, accessToken, baseDir);
|
||||||
updatedHtml = updatedHtml.replace(src, resp.url);
|
const newTag = fullTag
|
||||||
|
.replace(/\ssrc=["'][^"']+["']/, ` src="${resp.url}"`)
|
||||||
|
.replace(/\sdata-local-path=["'][^"']+["']/, "");
|
||||||
|
updatedHtml = updatedHtml.replace(fullTag, newTag);
|
||||||
if (!firstMediaId) {
|
if (!firstMediaId) {
|
||||||
firstMediaId = resp.media_id;
|
firstMediaId = resp.media_id;
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`[wechat-api] Failed to upload ${src}:`, err);
|
console.error(`[wechat-api] Failed to upload ${imagePath}:`, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,6 +316,7 @@ Arguments:
|
|||||||
|
|
||||||
Options:
|
Options:
|
||||||
--title <title> Override title
|
--title <title> Override title
|
||||||
|
--summary <text> Article summary (for future use)
|
||||||
--theme <name> Theme name for markdown (default, grace, simple). Default: default
|
--theme <name> Theme name for markdown (default, grace, simple). Default: default
|
||||||
--cover <path> Cover image path (local or URL)
|
--cover <path> Cover image path (local or URL)
|
||||||
--dry-run Parse and render only, don't publish
|
--dry-run Parse and render only, don't publish
|
||||||
@@ -337,6 +344,7 @@ interface CliArgs {
|
|||||||
filePath: string;
|
filePath: string;
|
||||||
isHtml: boolean;
|
isHtml: boolean;
|
||||||
title?: string;
|
title?: string;
|
||||||
|
summary?: string;
|
||||||
theme: string;
|
theme: string;
|
||||||
cover?: string;
|
cover?: string;
|
||||||
dryRun: boolean;
|
dryRun: boolean;
|
||||||
@@ -358,12 +366,16 @@ function parseArgs(argv: string[]): CliArgs {
|
|||||||
const arg = argv[i]!;
|
const arg = argv[i]!;
|
||||||
if (arg === "--title" && argv[i + 1]) {
|
if (arg === "--title" && argv[i + 1]) {
|
||||||
args.title = argv[++i];
|
args.title = argv[++i];
|
||||||
|
} else if (arg === "--summary" && argv[i + 1]) {
|
||||||
|
args.summary = argv[++i];
|
||||||
} else if (arg === "--theme" && argv[i + 1]) {
|
} else if (arg === "--theme" && argv[i + 1]) {
|
||||||
args.theme = argv[++i]!;
|
args.theme = argv[++i]!;
|
||||||
} else if (arg === "--cover" && argv[i + 1]) {
|
} else if (arg === "--cover" && argv[i + 1]) {
|
||||||
args.cover = argv[++i];
|
args.cover = argv[++i];
|
||||||
} else if (arg === "--dry-run") {
|
} else if (arg === "--dry-run") {
|
||||||
args.dryRun = true;
|
args.dryRun = true;
|
||||||
|
} else if (arg.startsWith("--") && argv[i + 1] && !argv[i + 1]!.startsWith("-")) {
|
||||||
|
i++;
|
||||||
} else if (!arg.startsWith("-")) {
|
} else if (!arg.startsWith("-")) {
|
||||||
args.filePath = arg;
|
args.filePath = arg;
|
||||||
}
|
}
|
||||||
@@ -405,6 +417,15 @@ async function main(): Promise<void> {
|
|||||||
if (args.isHtml) {
|
if (args.isHtml) {
|
||||||
htmlPath = filePath;
|
htmlPath = filePath;
|
||||||
htmlContent = extractHtmlContent(htmlPath);
|
htmlContent = extractHtmlContent(htmlPath);
|
||||||
|
const mdPath = filePath.replace(/\.html$/i, ".md");
|
||||||
|
if (fs.existsSync(mdPath)) {
|
||||||
|
const mdContent = fs.readFileSync(mdPath, "utf-8");
|
||||||
|
const parsed = parseFrontmatter(mdContent);
|
||||||
|
frontmatter = parsed.frontmatter;
|
||||||
|
if (!title && frontmatter.title) {
|
||||||
|
title = frontmatter.title;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!title) {
|
if (!title) {
|
||||||
title = extractHtmlTitle(fs.readFileSync(htmlPath, "utf-8"));
|
title = extractHtmlTitle(fs.readFileSync(htmlPath, "utf-8"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ async function sendPaste(cdp?: CdpConnection, sessionId?: string): Promise<void>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function copyHtmlFromBrowser(cdp: CdpConnection, htmlFilePath: string): Promise<void> {
|
async function copyHtmlFromBrowser(cdp: CdpConnection, htmlFilePath: string, contentImages: ImageInfo[] = []): Promise<void> {
|
||||||
const absolutePath = path.isAbsolute(htmlFilePath) ? htmlFilePath : path.resolve(process.cwd(), htmlFilePath);
|
const absolutePath = path.isAbsolute(htmlFilePath) ? htmlFilePath : path.resolve(process.cwd(), htmlFilePath);
|
||||||
const fileUrl = `file://${absolutePath}`;
|
const fileUrl = `file://${absolutePath}`;
|
||||||
|
|
||||||
@@ -128,6 +128,28 @@ async function copyHtmlFromBrowser(cdp: CdpConnection, htmlFilePath: string): Pr
|
|||||||
await cdp.send('Runtime.enable', {}, { sessionId });
|
await cdp.send('Runtime.enable', {}, { sessionId });
|
||||||
await sleep(2000);
|
await sleep(2000);
|
||||||
|
|
||||||
|
if (contentImages.length > 0) {
|
||||||
|
console.log('[wechat] Replacing img tags with placeholders for browser paste...');
|
||||||
|
const replacements = contentImages.map(img => ({ placeholder: img.placeholder, localPath: img.localPath }));
|
||||||
|
await cdp.send<{ result: { value: unknown } }>('Runtime.evaluate', {
|
||||||
|
expression: `
|
||||||
|
(function() {
|
||||||
|
const replacements = ${JSON.stringify(replacements)};
|
||||||
|
for (const r of replacements) {
|
||||||
|
const imgs = document.querySelectorAll('img[src="' + r.placeholder + '"], img[data-local-path="' + r.localPath + '"]');
|
||||||
|
for (const img of imgs) {
|
||||||
|
const text = document.createTextNode(r.placeholder);
|
||||||
|
img.parentNode.replaceChild(text, img);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
})()
|
||||||
|
`,
|
||||||
|
returnByValue: true,
|
||||||
|
}, { sessionId });
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
|
||||||
console.log('[wechat] Selecting #output content...');
|
console.log('[wechat] Selecting #output content...');
|
||||||
await cdp.send<{ result: { value: unknown } }>('Runtime.evaluate', {
|
await cdp.send<{ result: { value: unknown } }>('Runtime.evaluate', {
|
||||||
expression: `
|
expression: `
|
||||||
@@ -176,7 +198,7 @@ async function parseMarkdownWithPlaceholders(markdownPath: string, theme?: strin
|
|||||||
return JSON.parse(output);
|
return JSON.parse(output);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseHtmlMeta(htmlPath: string): { title: string; author: string; summary: string } {
|
function parseHtmlMeta(htmlPath: string): { title: string; author: string; summary: string; contentImages: ImageInfo[] } {
|
||||||
const content = fs.readFileSync(htmlPath, 'utf-8');
|
const content = fs.readFileSync(htmlPath, 'utf-8');
|
||||||
|
|
||||||
let title = '';
|
let title = '';
|
||||||
@@ -203,7 +225,45 @@ function parseHtmlMeta(htmlPath: string): { title: string; author: string; summa
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { title, author, summary };
|
const mdPath = htmlPath.replace(/\.html$/i, '.md');
|
||||||
|
if (fs.existsSync(mdPath)) {
|
||||||
|
const mdContent = fs.readFileSync(mdPath, 'utf-8');
|
||||||
|
const fmMatch = mdContent.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||||||
|
if (fmMatch) {
|
||||||
|
const lines = fmMatch[1]!.split('\n');
|
||||||
|
for (const line of lines) {
|
||||||
|
const colonIdx = line.indexOf(':');
|
||||||
|
if (colonIdx > 0) {
|
||||||
|
const key = line.slice(0, colonIdx).trim();
|
||||||
|
let value = line.slice(colonIdx + 1).trim();
|
||||||
|
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
if (key === 'title' && !title) title = value;
|
||||||
|
if (key === 'author' && !author) author = value;
|
||||||
|
if ((key === 'description' || key === 'summary') && !summary) summary = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentImages: ImageInfo[] = [];
|
||||||
|
const imgRegex = /<img[^>]*\ssrc=["']([^"']+)["'][^>]*>/gi;
|
||||||
|
const matches = [...content.matchAll(imgRegex)];
|
||||||
|
for (const match of matches) {
|
||||||
|
const [fullTag, src] = match;
|
||||||
|
if (!src || src.startsWith('http')) continue;
|
||||||
|
const localPathMatch = fullTag.match(/data-local-path=["']([^"']+)["']/);
|
||||||
|
if (localPathMatch) {
|
||||||
|
contentImages.push({
|
||||||
|
placeholder: src,
|
||||||
|
localPath: localPathMatch[1]!,
|
||||||
|
originalPath: src,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { title, author, summary, contentImages };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function selectAndReplacePlaceholder(session: ChromeSession, placeholder: string): Promise<boolean> {
|
async function selectAndReplacePlaceholder(session: ChromeSession, placeholder: string): Promise<boolean> {
|
||||||
@@ -273,9 +333,13 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
|
|||||||
effectiveAuthor = effectiveAuthor || meta.author;
|
effectiveAuthor = effectiveAuthor || meta.author;
|
||||||
effectiveSummary = effectiveSummary || meta.summary;
|
effectiveSummary = effectiveSummary || meta.summary;
|
||||||
effectiveHtmlFile = htmlFile;
|
effectiveHtmlFile = htmlFile;
|
||||||
|
if (meta.contentImages.length > 0) {
|
||||||
|
contentImages = meta.contentImages;
|
||||||
|
}
|
||||||
console.log(`[wechat] Title: ${effectiveTitle || '(empty)'}`);
|
console.log(`[wechat] Title: ${effectiveTitle || '(empty)'}`);
|
||||||
console.log(`[wechat] Author: ${effectiveAuthor || '(empty)'}`);
|
console.log(`[wechat] Author: ${effectiveAuthor || '(empty)'}`);
|
||||||
console.log(`[wechat] Summary: ${effectiveSummary || '(empty)'}`);
|
console.log(`[wechat] Summary: ${effectiveSummary || '(empty)'}`);
|
||||||
|
console.log(`[wechat] Found ${contentImages.length} images to insert`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (effectiveTitle && effectiveTitle.length > 64) throw new Error(`Title too long: ${effectiveTitle.length} chars (max 64)`);
|
if (effectiveTitle && effectiveTitle.length > 64) throw new Error(`Title too long: ${effectiveTitle.length} chars (max 64)`);
|
||||||
@@ -416,7 +480,7 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
|
|||||||
|
|
||||||
if (effectiveHtmlFile && fs.existsSync(effectiveHtmlFile)) {
|
if (effectiveHtmlFile && fs.existsSync(effectiveHtmlFile)) {
|
||||||
console.log(`[wechat] Copying HTML content from: ${effectiveHtmlFile}`);
|
console.log(`[wechat] Copying HTML content from: ${effectiveHtmlFile}`);
|
||||||
await copyHtmlFromBrowser(cdp, effectiveHtmlFile);
|
await copyHtmlFromBrowser(cdp, effectiveHtmlFile, contentImages);
|
||||||
await sleep(500);
|
await sleep(500);
|
||||||
console.log('[wechat] Pasting into editor...');
|
console.log('[wechat] Pasting into editor...');
|
||||||
await pasteFromClipboardInEditor(session);
|
await pasteFromClipboardInEditor(session);
|
||||||
|
|||||||
Reference in New Issue
Block a user