@elonzh/fafa 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +55 -2
- package/dist/bin.js +8 -0
- package/dist/chunk-LKU762XJ.js +2807 -0
- package/dist/chunk-ZCVVJMRN.js +3311 -0
- package/dist/dist-G3FZO234.js +12 -0
- package/dist/index.js +9 -0
- package/package.json +65 -4
- package/themes/base.css +191 -0
- package/themes/default.css +32 -0
- package/themes/elegant.css +50 -0
- package/themes/green.css +47 -0
- package/themes/minimal.css +47 -0
- package/themes/official.css +74 -0
- package/themes/tech.css +47 -0
- package/themes/warm.css +48 -0
- package/web/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/web/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/web/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/web/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/web/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/web/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/web/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/web/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/web/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/web/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/web/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/web/assets/index-BT8QLdyk.css +1 -0
- package/web/assets/index-IRxKoB6K.js +25 -0
- package/web/icon.svg +6 -0
- package/web/index.html +31 -0
- package/web/manifest.webmanifest +17 -0
|
@@ -0,0 +1,3311 @@
|
|
|
1
|
+
// ../../packages/application/dist/index.js
|
|
2
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
4
|
+
import { dirname as dirname5, join as join6 } from "path";
|
|
5
|
+
|
|
6
|
+
// ../../packages/assets/dist/index.js
|
|
7
|
+
import { createHash } from "crypto";
|
|
8
|
+
import { lookup } from "dns/promises";
|
|
9
|
+
import { readFile } from "fs/promises";
|
|
10
|
+
import { isIP } from "net";
|
|
11
|
+
import { basename, extname } from "path";
|
|
12
|
+
|
|
13
|
+
// ../../packages/domain/dist/index.js
|
|
14
|
+
var IMAGE_CAPTION_MODES = [
|
|
15
|
+
"title-first",
|
|
16
|
+
"alt-first",
|
|
17
|
+
"title-only",
|
|
18
|
+
"alt-only",
|
|
19
|
+
"filename",
|
|
20
|
+
"none"
|
|
21
|
+
];
|
|
22
|
+
var FaFaError = class extends Error {
|
|
23
|
+
code;
|
|
24
|
+
details;
|
|
25
|
+
constructor(code, message, details) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "FaFaError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.details = details;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
function hasErrors(diagnostics) {
|
|
33
|
+
return diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ../../packages/assets/dist/index.js
|
|
37
|
+
import { fileTypeFromBuffer } from "file-type";
|
|
38
|
+
import sharp from "sharp";
|
|
39
|
+
var MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
|
|
40
|
+
var MAX_WECHAT_ARTICLE_IMAGE_BYTES = 1 * 1024 * 1024;
|
|
41
|
+
var MAX_WECHAT_PERMANENT_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
42
|
+
var ARTICLE_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set(["image/jpeg", "image/png"]);
|
|
43
|
+
var PERMANENT_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/gif"]);
|
|
44
|
+
function assetError(message, details) {
|
|
45
|
+
return new FaFaError("ASSET_INVALID", message, details);
|
|
46
|
+
}
|
|
47
|
+
function isPrivateIpv4(value) {
|
|
48
|
+
const parts = value.split(".").map(Number);
|
|
49
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return true;
|
|
50
|
+
const [a, b] = parts;
|
|
51
|
+
return a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
|
|
52
|
+
}
|
|
53
|
+
function isPrivateIp(value) {
|
|
54
|
+
if (isIP(value) === 4) return isPrivateIpv4(value);
|
|
55
|
+
if (isIP(value) === 6) {
|
|
56
|
+
const normalized = value.toLowerCase();
|
|
57
|
+
return normalized === "::1" || normalized === "::" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
|
|
58
|
+
}
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
async function assertSafeRemoteUrl(url) {
|
|
62
|
+
if (url.protocol !== "https:") throw assetError(`Remote assets must use HTTPS: ${url}`);
|
|
63
|
+
if (url.username || url.password) throw assetError(`Remote asset URLs cannot contain credentials: ${url}`);
|
|
64
|
+
if (url.hostname === "localhost" || url.hostname.endsWith(".localhost")) {
|
|
65
|
+
throw assetError(`Remote asset URL resolves to localhost: ${url}`);
|
|
66
|
+
}
|
|
67
|
+
const addresses = await lookup(url.hostname, { all: true, verbatim: true });
|
|
68
|
+
if (addresses.length === 0 || addresses.some((entry) => isPrivateIp(entry.address))) {
|
|
69
|
+
throw assetError(`Remote asset URL resolves to a private or invalid address: ${url}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function fetchRemoteImage(source, fetcher = fetch) {
|
|
73
|
+
let current = new URL(source);
|
|
74
|
+
for (let redirectCount = 0; redirectCount <= 5; redirectCount += 1) {
|
|
75
|
+
await assertSafeRemoteUrl(current);
|
|
76
|
+
const response = await fetcher(current, { redirect: "manual", signal: AbortSignal.timeout(15e3) });
|
|
77
|
+
if (response.status >= 300 && response.status < 400) {
|
|
78
|
+
const location2 = response.headers.get("location");
|
|
79
|
+
if (!location2) throw assetError(`Remote image redirect has no location: ${current}`);
|
|
80
|
+
current = new URL(location2, current);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!response.ok) throw assetError(`Remote image returned HTTP ${response.status}: ${current}`);
|
|
84
|
+
const declaredLength = Number(response.headers.get("content-length") ?? "0");
|
|
85
|
+
if (declaredLength > MAX_DOWNLOAD_BYTES) throw assetError(`Remote image is too large: ${current}`);
|
|
86
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
87
|
+
if (bytes.byteLength === 0) throw assetError(`Remote image is empty: ${current}`);
|
|
88
|
+
if (bytes.byteLength > MAX_DOWNLOAD_BYTES) throw assetError(`Remote image is too large: ${current}`);
|
|
89
|
+
return bytes;
|
|
90
|
+
}
|
|
91
|
+
throw assetError(`Remote image exceeded redirect limit: ${source}`);
|
|
92
|
+
}
|
|
93
|
+
function extensionMimeType(filename) {
|
|
94
|
+
switch (extname(filename).toLowerCase()) {
|
|
95
|
+
case ".svg":
|
|
96
|
+
return "image/svg+xml";
|
|
97
|
+
case ".webp":
|
|
98
|
+
return "image/webp";
|
|
99
|
+
case ".jpg":
|
|
100
|
+
case ".jpeg":
|
|
101
|
+
return "image/jpeg";
|
|
102
|
+
case ".png":
|
|
103
|
+
return "image/png";
|
|
104
|
+
case ".gif":
|
|
105
|
+
return "image/gif";
|
|
106
|
+
default:
|
|
107
|
+
return void 0;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function normalizeImage(input, mimeType, purpose) {
|
|
111
|
+
let bytes = input;
|
|
112
|
+
let outputMimeType = mimeType;
|
|
113
|
+
let extension = mimeType === "image/jpeg" ? ".jpg" : `.${mimeType.split("/")[1] ?? "bin"}`;
|
|
114
|
+
let transformKey = "original";
|
|
115
|
+
const supportedMimeTypes = purpose === "inline" ? ARTICLE_IMAGE_MIME_TYPES : PERMANENT_IMAGE_MIME_TYPES;
|
|
116
|
+
const maximumBytes = purpose === "inline" ? MAX_WECHAT_ARTICLE_IMAGE_BYTES : MAX_WECHAT_PERMANENT_IMAGE_BYTES;
|
|
117
|
+
if (!supportedMimeTypes.has(mimeType)) {
|
|
118
|
+
bytes = new Uint8Array(await sharp(input).png({ compressionLevel: 9 }).toBuffer());
|
|
119
|
+
outputMimeType = "image/png";
|
|
120
|
+
extension = ".png";
|
|
121
|
+
transformKey = `${mimeType}-to-png`;
|
|
122
|
+
}
|
|
123
|
+
if (bytes.byteLength > maximumBytes) {
|
|
124
|
+
if (outputMimeType === "image/gif") {
|
|
125
|
+
throw assetError("Animated GIF exceeds 10 MiB and cannot be compressed without losing animation");
|
|
126
|
+
}
|
|
127
|
+
for (const quality of [85, 75, 65, 55, 45, 35]) {
|
|
128
|
+
const candidate = new Uint8Array(
|
|
129
|
+
await sharp(bytes).flatten({ background: "#ffffff" }).jpeg({ quality, mozjpeg: true }).toBuffer()
|
|
130
|
+
);
|
|
131
|
+
bytes = candidate;
|
|
132
|
+
outputMimeType = "image/jpeg";
|
|
133
|
+
extension = ".jpg";
|
|
134
|
+
transformKey = `${transformKey}+jpeg-${quality}`;
|
|
135
|
+
if (bytes.byteLength <= maximumBytes) break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (bytes.byteLength > maximumBytes) {
|
|
139
|
+
throw assetError(
|
|
140
|
+
purpose === "inline" ? "Article image remains larger than 1 MiB after normalization" : "Permanent image remains larger than 10 MiB after normalization"
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
return { bytes, mimeType: outputMimeType, extension, transformKey };
|
|
144
|
+
}
|
|
145
|
+
async function resolveAsset(reference, options = {}) {
|
|
146
|
+
const originalFilename = reference.resolvedPath ? basename(reference.resolvedPath) : basename(new URL(reference.remoteUrl).pathname) || `${reference.id}.img`;
|
|
147
|
+
const input = reference.resolvedPath ? new Uint8Array(await readFile(reference.resolvedPath)) : await fetchRemoteImage(reference.remoteUrl, options.fetcher);
|
|
148
|
+
const detected = await fileTypeFromBuffer(input);
|
|
149
|
+
const mimeType = detected?.mime ?? extensionMimeType(originalFilename);
|
|
150
|
+
if (!mimeType?.startsWith("image/")) {
|
|
151
|
+
throw assetError(`Asset is not a recognized image: ${reference.source}`);
|
|
152
|
+
}
|
|
153
|
+
const normalized = await normalizeImage(input, mimeType, reference.purpose);
|
|
154
|
+
const hash = createHash("sha256").update(normalized.bytes).digest("hex");
|
|
155
|
+
const filenameBase = basename(originalFilename, extname(originalFilename)) || reference.id;
|
|
156
|
+
return {
|
|
157
|
+
...reference,
|
|
158
|
+
hash,
|
|
159
|
+
mimeType: normalized.mimeType,
|
|
160
|
+
bytes: normalized.bytes,
|
|
161
|
+
filename: `${filenameBase}${normalized.extension}`,
|
|
162
|
+
transformKey: normalized.transformKey
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function dataUrl(asset) {
|
|
166
|
+
return `data:${asset.mimeType};base64,${Buffer.from(asset.bytes).toString("base64")}`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ../../packages/config/dist/index.js
|
|
170
|
+
import { access as access2, mkdir as mkdir2, readdir, readFile as readFile3, rename as rename3, stat as stat2, writeFile as writeFile3 } from "fs/promises";
|
|
171
|
+
import { homedir } from "os";
|
|
172
|
+
import { basename as basename2, dirname, extname as extname2, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve3, sep } from "path";
|
|
173
|
+
import matter from "gray-matter";
|
|
174
|
+
import ignore from "ignore";
|
|
175
|
+
import { parse, stringify } from "yaml";
|
|
176
|
+
import { z as z2 } from "zod";
|
|
177
|
+
import { readFile as readFile2, realpath, rename, writeFile } from "fs/promises";
|
|
178
|
+
import { isAbsolute, relative, resolve } from "path";
|
|
179
|
+
import { createHash as createHash2 } from "crypto";
|
|
180
|
+
import { access, mkdir, readFile as readFile22, realpath as realpath2, rename as rename2, stat, writeFile as writeFile2 } from "fs/promises";
|
|
181
|
+
import { basename as basename3, join, resolve as resolve2 } from "path";
|
|
182
|
+
import { z } from "zod";
|
|
183
|
+
function locateFrontmatter(markdown) {
|
|
184
|
+
const opening = markdown.match(/^(?:\uFEFF)?---[ \t]*(?:\r?\n)/);
|
|
185
|
+
if (!opening) {
|
|
186
|
+
throw new FaFaError("CONFIG_INVALID", "Article is missing opening YAML front matter (---)");
|
|
187
|
+
}
|
|
188
|
+
const bodyStart = opening[0].length;
|
|
189
|
+
const closingPattern = /^---[ \t]*(?:\r?\n|$)/gm;
|
|
190
|
+
closingPattern.lastIndex = bodyStart;
|
|
191
|
+
const closing = closingPattern.exec(markdown);
|
|
192
|
+
if (!closing) {
|
|
193
|
+
throw new FaFaError("CONFIG_INVALID", "Article YAML front matter is missing closing delimiter (---)");
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
bodyStart,
|
|
197
|
+
closingIndex: closing.index,
|
|
198
|
+
eol: markdown.includes("\r\n") ? "\r\n" : "\n",
|
|
199
|
+
frontmatter: markdown.slice(bodyStart, closing.index)
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function setArticleFrontmatterField(markdown, field, value) {
|
|
203
|
+
const normalized = value.trim();
|
|
204
|
+
if (!normalized) {
|
|
205
|
+
throw new FaFaError("CONFIG_INVALID", `Front matter field "${field}" cannot be empty`);
|
|
206
|
+
}
|
|
207
|
+
const { bodyStart, closingIndex, eol, frontmatter } = locateFrontmatter(markdown);
|
|
208
|
+
const encoded = JSON.stringify(normalized);
|
|
209
|
+
const fieldLine = new RegExp(`^${field}[ \\t]*:[^\\r\\n]*(?:\\r?\\n|$)`, "m");
|
|
210
|
+
const updated = fieldLine.test(frontmatter) ? frontmatter.replace(fieldLine, (line) => `${field}: ${encoded}${line.endsWith(eol) ? eol : ""}`) : `${frontmatter}${frontmatter && !frontmatter.endsWith(eol) ? eol : ""}${field}: ${encoded}${eol}`;
|
|
211
|
+
return `${markdown.slice(0, bodyStart)}${updated}${markdown.slice(closingIndex)}`;
|
|
212
|
+
}
|
|
213
|
+
function clearArticleFrontmatterField(markdown, field) {
|
|
214
|
+
const { bodyStart, closingIndex, frontmatter } = locateFrontmatter(markdown);
|
|
215
|
+
const fieldLine = new RegExp(`^${field}[ \\t]*:[^\\r\\n]*(?:\\r?\\n|$)`, "gm");
|
|
216
|
+
if (!fieldLine.test(frontmatter)) return markdown;
|
|
217
|
+
const updated = frontmatter.replace(fieldLine, "");
|
|
218
|
+
return `${markdown.slice(0, bodyStart)}${updated}${markdown.slice(closingIndex)}`;
|
|
219
|
+
}
|
|
220
|
+
async function updateArticleFrontmatterFile(projectRoot, articlePath, field, value) {
|
|
221
|
+
const fullPath = resolveInsideProject(projectRoot, articlePath);
|
|
222
|
+
const [canonicalRoot, canonicalArticle] = await Promise.all([
|
|
223
|
+
realpath(resolve(projectRoot)),
|
|
224
|
+
realpath(fullPath)
|
|
225
|
+
]);
|
|
226
|
+
const rel = relative(canonicalRoot, canonicalArticle);
|
|
227
|
+
if (rel.startsWith("..") || isAbsolute(rel)) {
|
|
228
|
+
throw new FaFaError("CONFIG_INVALID", `Path escapes project root: ${articlePath}`);
|
|
229
|
+
}
|
|
230
|
+
const current = await readFile2(canonicalArticle, "utf8");
|
|
231
|
+
const updated = value === null ? clearArticleFrontmatterField(current, field) : setArticleFrontmatterField(current, field, value);
|
|
232
|
+
if (updated === current) {
|
|
233
|
+
return { fullPath: canonicalArticle, changed: false };
|
|
234
|
+
}
|
|
235
|
+
const tempPath = `${canonicalArticle}.${process.pid}.${Date.now()}.tmp`;
|
|
236
|
+
await writeFile(tempPath, updated, "utf8");
|
|
237
|
+
await rename(tempPath, canonicalArticle);
|
|
238
|
+
return { fullPath: canonicalArticle, changed: true };
|
|
239
|
+
}
|
|
240
|
+
var LIBRARIES_FILENAME = "libraries.json";
|
|
241
|
+
var libraryEntrySchema = z.object({
|
|
242
|
+
id: z.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/),
|
|
243
|
+
name: z.string().min(1),
|
|
244
|
+
root: z.string().min(1),
|
|
245
|
+
addedAt: z.string().min(1),
|
|
246
|
+
lastOpenedAt: z.string().min(1).optional()
|
|
247
|
+
});
|
|
248
|
+
var libraryRegistrySchema = z.object({
|
|
249
|
+
version: z.literal(1),
|
|
250
|
+
lastActiveLibraryId: z.string().min(1).optional(),
|
|
251
|
+
libraries: z.array(libraryEntrySchema).default([])
|
|
252
|
+
});
|
|
253
|
+
async function pathExists(path) {
|
|
254
|
+
try {
|
|
255
|
+
await access(path);
|
|
256
|
+
return true;
|
|
257
|
+
} catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async function isDirectory(path) {
|
|
262
|
+
try {
|
|
263
|
+
return (await stat(path)).isDirectory();
|
|
264
|
+
} catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function buildLibraryId(root) {
|
|
269
|
+
const hash = createHash2("sha256").update(root).digest("hex").slice(0, 8);
|
|
270
|
+
const rawSlug = basename3(root).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24);
|
|
271
|
+
return rawSlug ? `${rawSlug}-${hash}` : `lib-${hash}`;
|
|
272
|
+
}
|
|
273
|
+
async function summarizeLibrary(entry) {
|
|
274
|
+
const exists2 = await isDirectory(entry.root);
|
|
275
|
+
const hasConfig = exists2 && await pathExists(join(entry.root, CONFIG_FILENAME));
|
|
276
|
+
return { ...entry, exists: exists2, hasConfig };
|
|
277
|
+
}
|
|
278
|
+
async function loadLibraryRegistry(home = getFaFaHome()) {
|
|
279
|
+
const path = join(home, LIBRARIES_FILENAME);
|
|
280
|
+
if (!await pathExists(path)) return { version: 1, libraries: [] };
|
|
281
|
+
let parsedJson;
|
|
282
|
+
try {
|
|
283
|
+
parsedJson = JSON.parse(await readFile22(path, "utf8"));
|
|
284
|
+
} catch {
|
|
285
|
+
throw new FaFaError("CONFIG_INVALID", `Invalid library registry ${path}`);
|
|
286
|
+
}
|
|
287
|
+
const result2 = libraryRegistrySchema.safeParse(parsedJson);
|
|
288
|
+
if (!result2.success) {
|
|
289
|
+
throw new FaFaError("CONFIG_INVALID", `Invalid library registry ${path}`, {
|
|
290
|
+
issues: result2.error.issues
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
return result2.data;
|
|
294
|
+
}
|
|
295
|
+
async function saveLibraryRegistry(registry, home = getFaFaHome()) {
|
|
296
|
+
const parsed = libraryRegistrySchema.parse(registry);
|
|
297
|
+
await mkdir(home, { recursive: true, mode: 448 });
|
|
298
|
+
const path = join(home, LIBRARIES_FILENAME);
|
|
299
|
+
const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
300
|
+
await writeFile2(temporaryPath, `${JSON.stringify(parsed, null, 2)}
|
|
301
|
+
`, { mode: 384 });
|
|
302
|
+
await rename2(temporaryPath, path);
|
|
303
|
+
}
|
|
304
|
+
async function listRegisteredLibraries(home = getFaFaHome()) {
|
|
305
|
+
const registry = await loadLibraryRegistry(home);
|
|
306
|
+
const libraries = await Promise.all(registry.libraries.map((entry) => summarizeLibrary(entry)));
|
|
307
|
+
return {
|
|
308
|
+
...registry.lastActiveLibraryId ? { lastActiveLibraryId: registry.lastActiveLibraryId } : {},
|
|
309
|
+
libraries
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
async function registerLibrary(input, home = getFaFaHome()) {
|
|
313
|
+
const resolved = resolve2(input.root);
|
|
314
|
+
if (!await isDirectory(resolved)) {
|
|
315
|
+
throw new FaFaError("CONFIG_INVALID", `Library directory does not exist: ${input.root}`);
|
|
316
|
+
}
|
|
317
|
+
const canonicalRoot = await realpath2(resolved);
|
|
318
|
+
const configPath = join(canonicalRoot, CONFIG_FILENAME);
|
|
319
|
+
if (!await pathExists(configPath)) {
|
|
320
|
+
if (input.initialize) {
|
|
321
|
+
await createProject(canonicalRoot);
|
|
322
|
+
} else {
|
|
323
|
+
throw new FaFaError("PROJECT_NOT_FOUND", `No ${CONFIG_FILENAME} found in ${canonicalRoot}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
327
|
+
const registry = await loadLibraryRegistry(home);
|
|
328
|
+
const existing = registry.libraries.find((entry2) => entry2.root === canonicalRoot);
|
|
329
|
+
const displayName = input.name?.trim() || existing?.name || basename3(canonicalRoot) || canonicalRoot;
|
|
330
|
+
let entry;
|
|
331
|
+
let libraries;
|
|
332
|
+
if (existing) {
|
|
333
|
+
entry = {
|
|
334
|
+
...existing,
|
|
335
|
+
name: displayName,
|
|
336
|
+
lastOpenedAt: now
|
|
337
|
+
};
|
|
338
|
+
libraries = registry.libraries.map((item) => item.id === existing.id ? entry : item);
|
|
339
|
+
} else {
|
|
340
|
+
let id = buildLibraryId(canonicalRoot);
|
|
341
|
+
let suffix = 1;
|
|
342
|
+
while (registry.libraries.some((item) => item.id === id)) {
|
|
343
|
+
suffix += 1;
|
|
344
|
+
id = `${buildLibraryId(canonicalRoot)}-${suffix}`;
|
|
345
|
+
}
|
|
346
|
+
entry = {
|
|
347
|
+
id,
|
|
348
|
+
name: displayName,
|
|
349
|
+
root: canonicalRoot,
|
|
350
|
+
addedAt: now,
|
|
351
|
+
lastOpenedAt: now
|
|
352
|
+
};
|
|
353
|
+
libraries = [...registry.libraries, entry];
|
|
354
|
+
}
|
|
355
|
+
const updated = {
|
|
356
|
+
version: 1,
|
|
357
|
+
lastActiveLibraryId: entry.id,
|
|
358
|
+
libraries
|
|
359
|
+
};
|
|
360
|
+
await saveLibraryRegistry(updated, home);
|
|
361
|
+
return {
|
|
362
|
+
library: await summarizeLibrary(entry),
|
|
363
|
+
registry: updated
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
async function touchLibrary(libraryId, home = getFaFaHome()) {
|
|
367
|
+
const registry = await loadLibraryRegistry(home);
|
|
368
|
+
const exists2 = registry.libraries.some((entry) => entry.id === libraryId);
|
|
369
|
+
if (!exists2) {
|
|
370
|
+
throw new FaFaError("PROJECT_NOT_FOUND", `Library ${libraryId} is not registered`);
|
|
371
|
+
}
|
|
372
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
373
|
+
const updated = {
|
|
374
|
+
version: 1,
|
|
375
|
+
lastActiveLibraryId: libraryId,
|
|
376
|
+
libraries: registry.libraries.map(
|
|
377
|
+
(entry) => entry.id === libraryId ? { ...entry, lastOpenedAt: now } : entry
|
|
378
|
+
)
|
|
379
|
+
};
|
|
380
|
+
await saveLibraryRegistry(updated, home);
|
|
381
|
+
return updated;
|
|
382
|
+
}
|
|
383
|
+
async function removeRegisteredLibrary(libraryId, home = getFaFaHome()) {
|
|
384
|
+
const registry = await loadLibraryRegistry(home);
|
|
385
|
+
const libraries = registry.libraries.filter((entry) => entry.id !== libraryId);
|
|
386
|
+
const lastActiveLibraryId = registry.lastActiveLibraryId && registry.lastActiveLibraryId !== libraryId ? registry.lastActiveLibraryId : libraries[0]?.id;
|
|
387
|
+
const updated = {
|
|
388
|
+
version: 1,
|
|
389
|
+
...lastActiveLibraryId ? { lastActiveLibraryId } : {},
|
|
390
|
+
libraries
|
|
391
|
+
};
|
|
392
|
+
await saveLibraryRegistry(updated, home);
|
|
393
|
+
return updated;
|
|
394
|
+
}
|
|
395
|
+
var CONFIG_FILENAME = "fafa.config.yaml";
|
|
396
|
+
var IGNORED_CONTENT_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "dist", "out", "release", "coverage"]);
|
|
397
|
+
var projectConfigSchema = z2.object({
|
|
398
|
+
version: z2.literal(1),
|
|
399
|
+
contentDirs: z2.array(z2.string().min(1)).min(1).default(["."]),
|
|
400
|
+
defaults: z2.object({
|
|
401
|
+
theme: z2.string().min(1).default("default"),
|
|
402
|
+
codeTheme: z2.string().min(1).default("github-light"),
|
|
403
|
+
imageCaption: z2.enum(IMAGE_CAPTION_MODES).default("none"),
|
|
404
|
+
author: z2.string().min(1).optional()
|
|
405
|
+
}).default({ theme: "default", codeTheme: "github-light", imageCaption: "none" })
|
|
406
|
+
}).strict();
|
|
407
|
+
var articleMetadataSchema = z2.object({
|
|
408
|
+
title: z2.string().min(1).max(64),
|
|
409
|
+
author: z2.string().max(16).optional(),
|
|
410
|
+
cover: z2.string().min(1).optional(),
|
|
411
|
+
summary: z2.string().max(120).optional(),
|
|
412
|
+
sourceUrl: z2.url().optional(),
|
|
413
|
+
comments: z2.object({
|
|
414
|
+
open: z2.boolean().default(false),
|
|
415
|
+
fansOnly: z2.boolean().default(false)
|
|
416
|
+
}).default({ open: false, fansOnly: false }),
|
|
417
|
+
theme: z2.string().min(1).optional(),
|
|
418
|
+
codeTheme: z2.string().min(1).optional(),
|
|
419
|
+
imageCaption: z2.enum(IMAGE_CAPTION_MODES).optional()
|
|
420
|
+
});
|
|
421
|
+
var storedAccountSchema = z2.object({
|
|
422
|
+
id: z2.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/),
|
|
423
|
+
platform: z2.literal("wechat"),
|
|
424
|
+
name: z2.string().min(1),
|
|
425
|
+
appId: z2.string().min(1),
|
|
426
|
+
appSecret: z2.string().min(1),
|
|
427
|
+
test: z2.boolean().default(false)
|
|
428
|
+
});
|
|
429
|
+
var accountInputSchema = storedAccountSchema.extend({ appSecret: z2.string().min(1).optional() });
|
|
430
|
+
var userConfigSchema = z2.object({
|
|
431
|
+
version: z2.literal(1),
|
|
432
|
+
defaultAccount: z2.string().optional(),
|
|
433
|
+
accounts: z2.array(storedAccountSchema).default([])
|
|
434
|
+
});
|
|
435
|
+
async function pathExists2(path) {
|
|
436
|
+
try {
|
|
437
|
+
await access2(path);
|
|
438
|
+
return true;
|
|
439
|
+
} catch {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function configError(message, details) {
|
|
444
|
+
return new FaFaError("CONFIG_INVALID", message, details);
|
|
445
|
+
}
|
|
446
|
+
async function findProjectRoot(startPath = process.cwd()) {
|
|
447
|
+
let current = resolve3(startPath);
|
|
448
|
+
if (!await pathExists2(join2(current, CONFIG_FILENAME)) && basename2(current).includes(".")) {
|
|
449
|
+
current = dirname(current);
|
|
450
|
+
}
|
|
451
|
+
while (true) {
|
|
452
|
+
if (await pathExists2(join2(current, CONFIG_FILENAME))) return current;
|
|
453
|
+
const parent = dirname(current);
|
|
454
|
+
if (parent === current) {
|
|
455
|
+
throw new FaFaError(
|
|
456
|
+
"PROJECT_NOT_FOUND",
|
|
457
|
+
`No ${CONFIG_FILENAME} found above ${startPath}. Run fafa init first.`
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
current = parent;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
async function loadProject(startPath = process.cwd()) {
|
|
464
|
+
const root = await findProjectRoot(startPath);
|
|
465
|
+
const configPath = join2(root, CONFIG_FILENAME);
|
|
466
|
+
const raw = parse(await readFile3(configPath, "utf8"));
|
|
467
|
+
const result2 = projectConfigSchema.safeParse(raw);
|
|
468
|
+
if (!result2.success) {
|
|
469
|
+
throw configError(`Invalid ${CONFIG_FILENAME}`, { issues: result2.error.issues });
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
root,
|
|
473
|
+
configPath,
|
|
474
|
+
config: result2.data,
|
|
475
|
+
contentRoots: await resolveContentRoots(root, result2.data.contentDirs)
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
async function createProject(rootPath) {
|
|
479
|
+
const root = resolve3(rootPath);
|
|
480
|
+
const configPath = join2(root, CONFIG_FILENAME);
|
|
481
|
+
if (await pathExists2(configPath)) {
|
|
482
|
+
throw configError(`${CONFIG_FILENAME} already exists at ${configPath}`);
|
|
483
|
+
}
|
|
484
|
+
const config = projectConfigSchema.parse({ version: 1 });
|
|
485
|
+
await mkdir2(root, { recursive: true });
|
|
486
|
+
const { contentDirs: _contentDirs, ...storedConfig } = config;
|
|
487
|
+
await writeFile3(configPath, stringify(storedConfig), "utf8");
|
|
488
|
+
return { root, configPath, config, contentRoots: [root] };
|
|
489
|
+
}
|
|
490
|
+
async function setProjectDefaultTheme(startPath, theme) {
|
|
491
|
+
const project = await loadProject(startPath);
|
|
492
|
+
const config = projectConfigSchema.parse({
|
|
493
|
+
...project.config,
|
|
494
|
+
defaults: { ...project.config.defaults, theme }
|
|
495
|
+
});
|
|
496
|
+
const temporaryPath = `${project.configPath}.${process.pid}.tmp`;
|
|
497
|
+
await writeFile3(temporaryPath, stringify(config), "utf8");
|
|
498
|
+
await rename3(temporaryPath, project.configPath);
|
|
499
|
+
return { ...project, config };
|
|
500
|
+
}
|
|
501
|
+
async function setProjectDefaultCodeTheme(startPath, codeTheme) {
|
|
502
|
+
const project = await loadProject(startPath);
|
|
503
|
+
const config = projectConfigSchema.parse({
|
|
504
|
+
...project.config,
|
|
505
|
+
defaults: { ...project.config.defaults, codeTheme }
|
|
506
|
+
});
|
|
507
|
+
const temporaryPath = `${project.configPath}.${process.pid}.tmp`;
|
|
508
|
+
await writeFile3(temporaryPath, stringify(config), "utf8");
|
|
509
|
+
await rename3(temporaryPath, project.configPath);
|
|
510
|
+
return { ...project, config };
|
|
511
|
+
}
|
|
512
|
+
async function setProjectDefaultImageCaption(startPath, imageCaption2) {
|
|
513
|
+
const project = await loadProject(startPath);
|
|
514
|
+
const config = projectConfigSchema.parse({
|
|
515
|
+
...project.config,
|
|
516
|
+
defaults: { ...project.config.defaults, imageCaption: imageCaption2 }
|
|
517
|
+
});
|
|
518
|
+
const temporaryPath = `${project.configPath}.${process.pid}.tmp`;
|
|
519
|
+
await writeFile3(temporaryPath, stringify(config), "utf8");
|
|
520
|
+
await rename3(temporaryPath, project.configPath);
|
|
521
|
+
return { ...project, config };
|
|
522
|
+
}
|
|
523
|
+
function resolveInsideProject(projectRoot, candidate) {
|
|
524
|
+
const resolved = resolve3(projectRoot, candidate);
|
|
525
|
+
const normalizedRoot = `${resolve3(projectRoot)}${sep}`;
|
|
526
|
+
if (resolved !== resolve3(projectRoot) && !resolved.startsWith(normalizedRoot)) {
|
|
527
|
+
throw configError(`Path escapes project root: ${candidate}`);
|
|
528
|
+
}
|
|
529
|
+
return resolved;
|
|
530
|
+
}
|
|
531
|
+
function pathIsInside(root, candidate) {
|
|
532
|
+
const path = relative2(resolve3(root), resolve3(candidate));
|
|
533
|
+
return path === "" || !isAbsolute2(path) && path !== ".." && !path.startsWith(`..${sep}`);
|
|
534
|
+
}
|
|
535
|
+
async function resolveContentRoots(projectRoot, contentDirs) {
|
|
536
|
+
const contentRoots = contentDirs.map((contentDirectory) => {
|
|
537
|
+
if (isAbsolute2(contentDirectory)) {
|
|
538
|
+
throw configError(`Content directory must be relative to the project root: ${contentDirectory}`, {
|
|
539
|
+
contentDirectory
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
return resolveInsideProject(projectRoot, contentDirectory);
|
|
543
|
+
});
|
|
544
|
+
for (let leftIndex = 0; leftIndex < contentRoots.length; leftIndex += 1) {
|
|
545
|
+
for (let rightIndex = leftIndex + 1; rightIndex < contentRoots.length; rightIndex += 1) {
|
|
546
|
+
const left = contentRoots[leftIndex];
|
|
547
|
+
const right = contentRoots[rightIndex];
|
|
548
|
+
if (!left || !right) continue;
|
|
549
|
+
if (left === right) {
|
|
550
|
+
throw configError("Content directories must be unique", {
|
|
551
|
+
contentDirs: [contentDirs[leftIndex], contentDirs[rightIndex]]
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
if (pathIsInside(left, right) || pathIsInside(right, left)) {
|
|
555
|
+
throw configError("Content directories must not contain one another", {
|
|
556
|
+
contentDirs: [contentDirs[leftIndex], contentDirs[rightIndex]]
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
await Promise.all(
|
|
562
|
+
contentRoots.map(async (contentRoot, index) => {
|
|
563
|
+
try {
|
|
564
|
+
if (!(await stat2(contentRoot)).isDirectory()) {
|
|
565
|
+
throw configError(`Content directory is not a directory: ${contentDirs[index]}`, {
|
|
566
|
+
contentDirectory: contentDirs[index]
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
} catch (error) {
|
|
570
|
+
if (error instanceof FaFaError) throw error;
|
|
571
|
+
if (error.code === "ENOENT") {
|
|
572
|
+
throw configError(`Content directory does not exist: ${contentDirs[index]}`, {
|
|
573
|
+
contentDirectory: contentDirs[index]
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
throw error;
|
|
577
|
+
}
|
|
578
|
+
})
|
|
579
|
+
);
|
|
580
|
+
return contentRoots;
|
|
581
|
+
}
|
|
582
|
+
function isInsideContentDirectories(project, candidate) {
|
|
583
|
+
return project.contentRoots.some((contentRoot) => pathIsInside(contentRoot, candidate));
|
|
584
|
+
}
|
|
585
|
+
function portableProjectPath(inputPath) {
|
|
586
|
+
return inputPath.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
587
|
+
}
|
|
588
|
+
async function createContentDiscoveryFilter(projectRoot) {
|
|
589
|
+
let rules = "";
|
|
590
|
+
try {
|
|
591
|
+
rules = await readFile3(join2(projectRoot, ".gitignore"), "utf8");
|
|
592
|
+
} catch (error) {
|
|
593
|
+
if (error.code !== "ENOENT") throw error;
|
|
594
|
+
}
|
|
595
|
+
const matcher = ignore().add(rules);
|
|
596
|
+
return {
|
|
597
|
+
ignores(inputPath, directory = false) {
|
|
598
|
+
const portable = portableProjectPath(inputPath);
|
|
599
|
+
if (!portable) return false;
|
|
600
|
+
const segments = portable.split("/");
|
|
601
|
+
if (segments.some((segment) => segment.startsWith(".") || IGNORED_CONTENT_DIRECTORIES.has(segment))) {
|
|
602
|
+
return true;
|
|
603
|
+
}
|
|
604
|
+
return matcher.ignores(directory ? `${portable}/` : portable);
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
function articleSource(project, sourcePath) {
|
|
609
|
+
const relativeSource = relative2(project.root, sourcePath);
|
|
610
|
+
return {
|
|
611
|
+
articleDir: dirname(sourcePath),
|
|
612
|
+
sourcePath,
|
|
613
|
+
inputPath: relativeSource
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
async function discoverArticles(project) {
|
|
617
|
+
const found = [];
|
|
618
|
+
const filter = await createContentDiscoveryFilter(project.root);
|
|
619
|
+
async function walk3(directory) {
|
|
620
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
621
|
+
for (const entry of entries) {
|
|
622
|
+
if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name.startsWith(".")) continue;
|
|
623
|
+
const sourcePath = join2(directory, entry.name);
|
|
624
|
+
if (filter.ignores(relative2(project.root, sourcePath))) continue;
|
|
625
|
+
const frontmatter = matter(await readFile3(sourcePath, "utf8")).data;
|
|
626
|
+
if (typeof frontmatter.title === "string" && frontmatter.title.trim()) {
|
|
627
|
+
found.push(articleSource(project, sourcePath));
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
await Promise.all(
|
|
631
|
+
entries.filter(
|
|
632
|
+
(entry) => entry.isDirectory() && !entry.name.startsWith(".") && !filter.ignores(relative2(project.root, join2(directory, entry.name)), true)
|
|
633
|
+
).map((entry) => walk3(join2(directory, entry.name)))
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
await Promise.all(project.contentRoots.map((contentRoot) => walk3(contentRoot)));
|
|
637
|
+
return found.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath));
|
|
638
|
+
}
|
|
639
|
+
async function resolveArticleSource(project, input) {
|
|
640
|
+
const candidate = isAbsolute2(input) ? resolve3(input) : resolve3(project.root, input);
|
|
641
|
+
resolveInsideProject(project.root, candidate);
|
|
642
|
+
const sourcePath = candidate;
|
|
643
|
+
if (!isInsideContentDirectories(project, sourcePath)) {
|
|
644
|
+
throw configError(`Article is outside contentDirs: ${input}`);
|
|
645
|
+
}
|
|
646
|
+
if (!await pathExists2(sourcePath) || extname2(sourcePath).toLowerCase() !== ".md" || !(await stat2(sourcePath)).isFile()) {
|
|
647
|
+
throw new FaFaError("ARTICLE_NOT_FOUND", `No Markdown article found for ${input}`);
|
|
648
|
+
}
|
|
649
|
+
return articleSource(project, sourcePath);
|
|
650
|
+
}
|
|
651
|
+
function parseArticleMetadata(frontmatter, sourcePath) {
|
|
652
|
+
const accountFields = ["account", "accountId", "accounts"].filter((field) => field in frontmatter);
|
|
653
|
+
if (accountFields.length) {
|
|
654
|
+
throw configError(`Article metadata in ${sourcePath} must not depend on an account`, {
|
|
655
|
+
fields: accountFields
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
const result2 = articleMetadataSchema.safeParse(frontmatter);
|
|
659
|
+
if (!result2.success) {
|
|
660
|
+
throw configError(`Invalid article metadata in ${sourcePath}`, { issues: result2.error.issues });
|
|
661
|
+
}
|
|
662
|
+
return {
|
|
663
|
+
title: result2.data.title,
|
|
664
|
+
comments: result2.data.comments,
|
|
665
|
+
...result2.data.author ? { author: result2.data.author } : {},
|
|
666
|
+
...result2.data.cover ? { cover: result2.data.cover } : {},
|
|
667
|
+
...result2.data.summary ? { summary: result2.data.summary } : {},
|
|
668
|
+
...result2.data.sourceUrl ? { sourceUrl: result2.data.sourceUrl } : {},
|
|
669
|
+
...result2.data.theme ? { theme: result2.data.theme } : {},
|
|
670
|
+
...result2.data.codeTheme ? { codeTheme: result2.data.codeTheme } : {},
|
|
671
|
+
...result2.data.imageCaption ? { imageCaption: result2.data.imageCaption } : {}
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function getFaFaHome(environment = process.env) {
|
|
675
|
+
if (environment.FAFA_HOME) return resolve3(environment.FAFA_HOME);
|
|
676
|
+
if (process.platform === "darwin") return join2(homedir(), "Library", "Application Support", "fafa");
|
|
677
|
+
return join2(homedir(), ".config", "fafa");
|
|
678
|
+
}
|
|
679
|
+
async function loadUserConfig(home = getFaFaHome()) {
|
|
680
|
+
const path = join2(home, "config.json");
|
|
681
|
+
if (!await pathExists2(path)) return { version: 1, accounts: [] };
|
|
682
|
+
const result2 = userConfigSchema.safeParse(JSON.parse(await readFile3(path, "utf8")));
|
|
683
|
+
if (!result2.success) throw configError(`Invalid user config ${path}`, { issues: result2.error.issues });
|
|
684
|
+
return result2.data;
|
|
685
|
+
}
|
|
686
|
+
async function saveUserConfig(config, home = getFaFaHome()) {
|
|
687
|
+
const parsed = userConfigSchema.parse(config);
|
|
688
|
+
await mkdir2(home, { recursive: true, mode: 448 });
|
|
689
|
+
const path = join2(home, "config.json");
|
|
690
|
+
const temporaryPath = `${path}.${process.pid}.tmp`;
|
|
691
|
+
await writeFile3(temporaryPath, `${JSON.stringify(parsed, null, 2)}
|
|
692
|
+
`, { mode: 384 });
|
|
693
|
+
await rename3(temporaryPath, path);
|
|
694
|
+
}
|
|
695
|
+
async function upsertAccount(account, home = getFaFaHome()) {
|
|
696
|
+
const parsed = accountInputSchema.parse(account);
|
|
697
|
+
const config = await loadUserConfig(home);
|
|
698
|
+
const existing = config.accounts.find((candidate) => candidate.id === parsed.id);
|
|
699
|
+
const appSecret = parsed.appSecret ?? existing?.appSecret;
|
|
700
|
+
if (!appSecret) {
|
|
701
|
+
throw new FaFaError("CREDENTIAL_MISSING", `AppSecret is required for new account ${parsed.id}`);
|
|
702
|
+
}
|
|
703
|
+
const stored = storedAccountSchema.parse({ ...parsed, appSecret });
|
|
704
|
+
const accounts = config.accounts.filter((candidate) => candidate.id !== parsed.id);
|
|
705
|
+
accounts.push(stored);
|
|
706
|
+
const updated = {
|
|
707
|
+
...config,
|
|
708
|
+
accounts: accounts.sort((left, right) => left.id.localeCompare(right.id)),
|
|
709
|
+
...config.defaultAccount ? {} : { defaultAccount: parsed.id }
|
|
710
|
+
};
|
|
711
|
+
await saveUserConfig(updated, home);
|
|
712
|
+
return updated;
|
|
713
|
+
}
|
|
714
|
+
async function removeAccount(accountId, home = getFaFaHome()) {
|
|
715
|
+
const config = await loadUserConfig(home);
|
|
716
|
+
const updated = {
|
|
717
|
+
version: 1,
|
|
718
|
+
accounts: config.accounts.filter((account) => account.id !== accountId),
|
|
719
|
+
...config.defaultAccount && config.defaultAccount !== accountId ? { defaultAccount: config.defaultAccount } : {}
|
|
720
|
+
};
|
|
721
|
+
await saveUserConfig(updated, home);
|
|
722
|
+
return updated;
|
|
723
|
+
}
|
|
724
|
+
function toPublicUserConfig(config) {
|
|
725
|
+
return {
|
|
726
|
+
version: 1,
|
|
727
|
+
accounts: config.accounts.map(({ appSecret: _appSecret, ...account }) => ({
|
|
728
|
+
...account,
|
|
729
|
+
credentialConfigured: true
|
|
730
|
+
})),
|
|
731
|
+
...config.defaultAccount ? { defaultAccount: config.defaultAccount } : {}
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
async function resolveWechatCredential(accountId, home = getFaFaHome()) {
|
|
735
|
+
const config = await loadUserConfig(home);
|
|
736
|
+
const account = config.accounts.find((candidate) => candidate.id === accountId);
|
|
737
|
+
if (!account) throw new FaFaError("CREDENTIAL_MISSING", `Account ${accountId} is not configured`);
|
|
738
|
+
return { appId: account.appId, appSecret: account.appSecret };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// ../../packages/exporter/dist/index.js
|
|
742
|
+
import { execFile } from "child_process";
|
|
743
|
+
import { randomUUID } from "crypto";
|
|
744
|
+
import { constants } from "fs";
|
|
745
|
+
import { access as access3, mkdir as mkdir3, readFile as readFile4, rename as rename4, stat as stat3, writeFile as writeFile4 } from "fs/promises";
|
|
746
|
+
import { createRequire } from "module";
|
|
747
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
748
|
+
import { pathToFileURL } from "url";
|
|
749
|
+
import { promisify } from "util";
|
|
750
|
+
var require2 = createRequire(import.meta.url);
|
|
751
|
+
var execFileAsync = promisify(execFile);
|
|
752
|
+
function currentPlaywrightVersion() {
|
|
753
|
+
const packageJson = require2("playwright-core/package.json");
|
|
754
|
+
return packageJson.version;
|
|
755
|
+
}
|
|
756
|
+
function runtimeIdentity(options) {
|
|
757
|
+
return {
|
|
758
|
+
playwrightVersion: options.playwrightVersion ?? currentPlaywrightVersion(),
|
|
759
|
+
platform: options.platform ?? process.platform,
|
|
760
|
+
arch: options.arch ?? process.arch
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
async function isExecutable(path) {
|
|
764
|
+
try {
|
|
765
|
+
if (!(await stat3(path)).isFile()) return false;
|
|
766
|
+
if (process.platform !== "win32") await access3(path, constants.X_OK);
|
|
767
|
+
return true;
|
|
768
|
+
} catch {
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
function isManifest(value) {
|
|
773
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
774
|
+
const candidate = value;
|
|
775
|
+
return typeof candidate.playwrightVersion === "string" && typeof candidate.platform === "string" && typeof candidate.arch === "string" && typeof candidate.executablePath === "string";
|
|
776
|
+
}
|
|
777
|
+
async function readManagedRuntime(home, identity) {
|
|
778
|
+
try {
|
|
779
|
+
const value = JSON.parse(await readFile4(join3(home, "browsers", "manifest.json"), "utf8"));
|
|
780
|
+
if (!isManifest(value) || value.playwrightVersion !== identity.playwrightVersion || value.platform !== identity.platform || value.arch !== identity.arch || !await isExecutable(value.executablePath)) {
|
|
781
|
+
return void 0;
|
|
782
|
+
}
|
|
783
|
+
return {
|
|
784
|
+
status: "ready",
|
|
785
|
+
source: "managed",
|
|
786
|
+
executablePath: value.executablePath
|
|
787
|
+
};
|
|
788
|
+
} catch {
|
|
789
|
+
return void 0;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
async function defaultProbeChannel(channel) {
|
|
793
|
+
try {
|
|
794
|
+
const { chromium } = await import("playwright-core");
|
|
795
|
+
const browser = await chromium.launch({ channel, headless: true, chromiumSandbox: true });
|
|
796
|
+
await browser.close();
|
|
797
|
+
return true;
|
|
798
|
+
} catch {
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
async function inspectBrowserRuntime(options) {
|
|
803
|
+
if (options.browserPath && await isExecutable(options.browserPath)) {
|
|
804
|
+
return {
|
|
805
|
+
status: "ready",
|
|
806
|
+
source: "explicit",
|
|
807
|
+
executablePath: options.browserPath
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
const managed = await readManagedRuntime(options.home, runtimeIdentity(options));
|
|
811
|
+
if (managed) return managed;
|
|
812
|
+
const probeChannel = options.probeChannel ?? defaultProbeChannel;
|
|
813
|
+
for (const channel of ["chrome", "msedge"]) {
|
|
814
|
+
if (await probeChannel(channel)) {
|
|
815
|
+
return { status: "ready", source: channel, channel };
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return { status: "missing", source: "missing" };
|
|
819
|
+
}
|
|
820
|
+
async function defaultRunInstaller(request) {
|
|
821
|
+
await execFileAsync(process.execPath, [request.cliPath, "install", "chromium-headless-shell"], {
|
|
822
|
+
env: request.environment
|
|
823
|
+
});
|
|
824
|
+
return resolveHeadlessShellExecutable(request.browserDirectory, request.environment);
|
|
825
|
+
}
|
|
826
|
+
async function resolveHeadlessShellExecutable(browserDirectory, environment = {
|
|
827
|
+
...process.env,
|
|
828
|
+
PLAYWRIGHT_BROWSERS_PATH: browserDirectory
|
|
829
|
+
}) {
|
|
830
|
+
const coreBundleEntry = require2.resolve("playwright-core/lib/coreBundle");
|
|
831
|
+
const script = [
|
|
832
|
+
`const loaded = await import(${JSON.stringify(pathToFileURL(coreBundleEntry).href)});`,
|
|
833
|
+
"const coreBundle = loaded.default ?? loaded;",
|
|
834
|
+
"const executable = coreBundle.registry.registry.findExecutable('chromium-headless-shell');",
|
|
835
|
+
"process.stdout.write(executable.executablePath() ?? '');"
|
|
836
|
+
].join("\n");
|
|
837
|
+
const result2 = await execFileAsync(process.execPath, ["--input-type=module", "--eval", script], {
|
|
838
|
+
env: environment
|
|
839
|
+
});
|
|
840
|
+
const executablePath = result2.stdout.trim();
|
|
841
|
+
if (!await isExecutable(executablePath)) {
|
|
842
|
+
throw new Error(`Installed Chromium headless shell was not found: ${executablePath}`);
|
|
843
|
+
}
|
|
844
|
+
return executablePath;
|
|
845
|
+
}
|
|
846
|
+
async function writeManifestAtomically(path, manifest) {
|
|
847
|
+
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
848
|
+
await writeFile4(temporaryPath, `${JSON.stringify(manifest, null, 2)}
|
|
849
|
+
`, { mode: 384 });
|
|
850
|
+
await rename4(temporaryPath, path);
|
|
851
|
+
}
|
|
852
|
+
async function installBrowserRuntime(options) {
|
|
853
|
+
try {
|
|
854
|
+
const browserDirectory = join3(options.home, "browsers");
|
|
855
|
+
await mkdir3(browserDirectory, { recursive: true });
|
|
856
|
+
const environment = {
|
|
857
|
+
...process.env,
|
|
858
|
+
PLAYWRIGHT_BROWSERS_PATH: browserDirectory
|
|
859
|
+
};
|
|
860
|
+
const runInstaller = options.runInstaller ?? defaultRunInstaller;
|
|
861
|
+
const executablePath = await runInstaller({
|
|
862
|
+
browserDirectory,
|
|
863
|
+
cliPath: join3(dirname2(require2.resolve("playwright-core/package.json")), "cli.js"),
|
|
864
|
+
environment
|
|
865
|
+
});
|
|
866
|
+
if (!await isExecutable(executablePath)) {
|
|
867
|
+
throw new Error(`Installed browser executable was not found: ${executablePath}`);
|
|
868
|
+
}
|
|
869
|
+
await writeManifestAtomically(join3(browserDirectory, "manifest.json"), {
|
|
870
|
+
...runtimeIdentity(options),
|
|
871
|
+
executablePath
|
|
872
|
+
});
|
|
873
|
+
return {
|
|
874
|
+
status: "ready",
|
|
875
|
+
source: "managed",
|
|
876
|
+
executablePath
|
|
877
|
+
};
|
|
878
|
+
} catch (error) {
|
|
879
|
+
if (error instanceof FaFaError && error.code === "BROWSER_INSTALL_FAILED") throw error;
|
|
880
|
+
throw new FaFaError("BROWSER_INSTALL_FAILED", "Could not install the FaFa browser runtime", {
|
|
881
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
function escapeHtml(value) {
|
|
886
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
887
|
+
}
|
|
888
|
+
function removeSourceLocations(articleHtml) {
|
|
889
|
+
return articleHtml.replace(/\sdata-fafa-line=(?:"[^"]*"|'[^']*')/gu, "");
|
|
890
|
+
}
|
|
891
|
+
function createExportDocument(options) {
|
|
892
|
+
const articleHtml = removeSourceLocations(options.articleHtml);
|
|
893
|
+
const appearance = options.appearance ?? "day";
|
|
894
|
+
const night = appearance === "night";
|
|
895
|
+
const canvas = night ? "#111827" : "#fff";
|
|
896
|
+
const bodyPadding = night ? "24px 0" : "0";
|
|
897
|
+
const minHeight = night ? "calc(100vh - 48px)" : "100vh";
|
|
898
|
+
return `<!doctype html>
|
|
899
|
+
<html lang="zh-CN" data-fafa-appearance="${appearance}">
|
|
900
|
+
<head>
|
|
901
|
+
<meta charset="utf-8">
|
|
902
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
903
|
+
<title>${escapeHtml(options.title)}</title>
|
|
904
|
+
<style>
|
|
905
|
+
@page { size: A4; margin: 0; }
|
|
906
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
907
|
+
html, body { margin: 0; min-height: 100%; background: ${canvas}; }
|
|
908
|
+
body { padding: ${bodyPadding}; color: #000; color-scheme: light; }
|
|
909
|
+
main { display: flow-root; width: 100%; max-width: ${options.width}px; min-height: ${minHeight}; margin: 0 auto; background: #fff; }
|
|
910
|
+
</style>
|
|
911
|
+
</head>
|
|
912
|
+
<body>
|
|
913
|
+
<main>${articleHtml}</main>
|
|
914
|
+
</body>
|
|
915
|
+
</html>
|
|
916
|
+
`;
|
|
917
|
+
}
|
|
918
|
+
var EXPORT_FORMATS = ["html", "pdf", "png"];
|
|
919
|
+
var EXPORT_APPEARANCES = ["day", "night"];
|
|
920
|
+
function safeFilename(value) {
|
|
921
|
+
let stem = value.normalize("NFC").replaceAll(/[\p{Cc}<>:"/\\|?*]+/gu, "-").replace(/[. ]+$/gu, "");
|
|
922
|
+
if (!stem || stem === "." || stem === "..") stem = "article";
|
|
923
|
+
if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(stem)) stem = `_${stem}`;
|
|
924
|
+
return stem;
|
|
925
|
+
}
|
|
926
|
+
function exportFilename(articleId2, format, appearance = "day") {
|
|
927
|
+
const suffix = appearance === "night" ? "-night" : "";
|
|
928
|
+
return `${safeFilename(articleId2)}${suffix}.${format}`;
|
|
929
|
+
}
|
|
930
|
+
var DEFAULT_PNG_WIDTH = 390;
|
|
931
|
+
var DEFAULT_PNG_HEIGHT = 844;
|
|
932
|
+
var A4_VIEWPORT = { width: 794, height: 1123 };
|
|
933
|
+
var defaultBrowserAdapter = {
|
|
934
|
+
async launch(options) {
|
|
935
|
+
const { chromium } = await import("playwright-core");
|
|
936
|
+
const browser = await chromium.launch(options);
|
|
937
|
+
return {
|
|
938
|
+
async newContext(contextOptions) {
|
|
939
|
+
const context = await browser.newContext(contextOptions);
|
|
940
|
+
return {
|
|
941
|
+
async newPage() {
|
|
942
|
+
const page = await context.newPage();
|
|
943
|
+
return {
|
|
944
|
+
async route(matcher, handler) {
|
|
945
|
+
await page.route(matcher, async (route) => handler(route));
|
|
946
|
+
},
|
|
947
|
+
async setContent(html, pageOptions) {
|
|
948
|
+
await page.setContent(html, pageOptions);
|
|
949
|
+
},
|
|
950
|
+
async emulateMedia(mediaOptions) {
|
|
951
|
+
await page.emulateMedia(mediaOptions);
|
|
952
|
+
},
|
|
953
|
+
async pdf(pdfOptions) {
|
|
954
|
+
return page.pdf(pdfOptions);
|
|
955
|
+
},
|
|
956
|
+
async screenshot(screenshotOptions) {
|
|
957
|
+
return page.screenshot(screenshotOptions);
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
},
|
|
961
|
+
async close() {
|
|
962
|
+
await context.close();
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
},
|
|
966
|
+
async close() {
|
|
967
|
+
await browser.close();
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
function launchOptions(runtime) {
|
|
973
|
+
if (runtime.executablePath) {
|
|
974
|
+
return { executablePath: runtime.executablePath, chromiumSandbox: true };
|
|
975
|
+
}
|
|
976
|
+
if (runtime.channel) return { channel: runtime.channel, chromiumSandbox: true };
|
|
977
|
+
throw new FaFaError("BROWSER_NOT_FOUND", "The selected browser runtime cannot be launched");
|
|
978
|
+
}
|
|
979
|
+
function result(format, bytes, browserSource, appearance) {
|
|
980
|
+
const mimeTypes = {
|
|
981
|
+
html: "text/html; charset=utf-8",
|
|
982
|
+
pdf: "application/pdf",
|
|
983
|
+
png: "image/png"
|
|
984
|
+
};
|
|
985
|
+
return {
|
|
986
|
+
format,
|
|
987
|
+
bytes,
|
|
988
|
+
mimeType: mimeTypes[format],
|
|
989
|
+
extension: format,
|
|
990
|
+
browserSource,
|
|
991
|
+
appearance
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function exportError(format, error) {
|
|
995
|
+
if (error instanceof FaFaError) return error;
|
|
996
|
+
return new FaFaError("EXPORT_FAILED", `Could not export ${format.toUpperCase()} document`, {
|
|
997
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
async function exportDocument(options, dependencies = {}) {
|
|
1001
|
+
const width = options.format === "png" ? options.width ?? DEFAULT_PNG_WIDTH : A4_VIEWPORT.width;
|
|
1002
|
+
const appearance = options.appearance ?? "day";
|
|
1003
|
+
const html = createExportDocument({
|
|
1004
|
+
title: options.title,
|
|
1005
|
+
articleHtml: options.articleHtml,
|
|
1006
|
+
width,
|
|
1007
|
+
appearance
|
|
1008
|
+
});
|
|
1009
|
+
if (options.format === "html") {
|
|
1010
|
+
return result("html", new TextEncoder().encode(html), "none", appearance);
|
|
1011
|
+
}
|
|
1012
|
+
const inspectRuntime = dependencies.inspectRuntime ?? inspectBrowserRuntime;
|
|
1013
|
+
const runtime = await inspectRuntime({
|
|
1014
|
+
home: options.home,
|
|
1015
|
+
...options.browserPath ? { browserPath: options.browserPath } : {}
|
|
1016
|
+
});
|
|
1017
|
+
if (runtime.status === "missing") {
|
|
1018
|
+
throw new FaFaError(
|
|
1019
|
+
"BROWSER_NOT_FOUND",
|
|
1020
|
+
"No supported browser was found. Install the FaFa browser runtime or configure a browser path."
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
const browserAdapter = dependencies.browser ?? defaultBrowserAdapter;
|
|
1024
|
+
let browser;
|
|
1025
|
+
let context;
|
|
1026
|
+
let exportFailure;
|
|
1027
|
+
let exportResult;
|
|
1028
|
+
try {
|
|
1029
|
+
browser = await browserAdapter.launch(launchOptions(runtime));
|
|
1030
|
+
context = await browser.newContext(
|
|
1031
|
+
options.format === "png" ? {
|
|
1032
|
+
viewport: { width, height: DEFAULT_PNG_HEIGHT },
|
|
1033
|
+
deviceScaleFactor: 2
|
|
1034
|
+
} : {
|
|
1035
|
+
viewport: A4_VIEWPORT,
|
|
1036
|
+
deviceScaleFactor: 1
|
|
1037
|
+
}
|
|
1038
|
+
);
|
|
1039
|
+
const page = await context.newPage();
|
|
1040
|
+
await page.route(/^https?:\/\//iu, async (route) => route.abort());
|
|
1041
|
+
await page.setContent(html, { waitUntil: "load" });
|
|
1042
|
+
if (options.format === "pdf") {
|
|
1043
|
+
await page.emulateMedia({ media: "screen" });
|
|
1044
|
+
exportResult = result(
|
|
1045
|
+
"pdf",
|
|
1046
|
+
await page.pdf({ format: "A4", printBackground: true }),
|
|
1047
|
+
runtime.source,
|
|
1048
|
+
appearance
|
|
1049
|
+
);
|
|
1050
|
+
} else {
|
|
1051
|
+
exportResult = result(
|
|
1052
|
+
"png",
|
|
1053
|
+
await page.screenshot({ type: "png", fullPage: true }),
|
|
1054
|
+
runtime.source,
|
|
1055
|
+
appearance
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
exportFailure = error;
|
|
1060
|
+
}
|
|
1061
|
+
let cleanupFailure;
|
|
1062
|
+
try {
|
|
1063
|
+
await context?.close();
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
cleanupFailure = error;
|
|
1066
|
+
}
|
|
1067
|
+
try {
|
|
1068
|
+
await browser?.close();
|
|
1069
|
+
} catch (error) {
|
|
1070
|
+
cleanupFailure ??= error;
|
|
1071
|
+
}
|
|
1072
|
+
if (exportFailure) throw exportError(options.format, exportFailure);
|
|
1073
|
+
if (cleanupFailure) throw exportError(options.format, cleanupFailure);
|
|
1074
|
+
return exportResult;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// ../../packages/markdown/dist/index.js
|
|
1078
|
+
import { createHash as createHash3 } from "crypto";
|
|
1079
|
+
import { access as access4, readdir as readdir2, readFile as readFile5 } from "fs/promises";
|
|
1080
|
+
import { basename as basename4, dirname as dirname3, extname as extname3, join as join4, relative as relative3, resolve as resolve4, sep as sep2 } from "path";
|
|
1081
|
+
import matter2 from "gray-matter";
|
|
1082
|
+
import remarkGfm from "remark-gfm";
|
|
1083
|
+
import remarkMath from "remark-math";
|
|
1084
|
+
import remarkParse from "remark-parse";
|
|
1085
|
+
import { unified } from "unified";
|
|
1086
|
+
function sha256(value) {
|
|
1087
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
1088
|
+
}
|
|
1089
|
+
function articleId(projectRoot, sourcePath, frontmatter) {
|
|
1090
|
+
if (typeof frontmatter.id === "string" && frontmatter.id.trim()) return frontmatter.id.trim();
|
|
1091
|
+
return relative3(projectRoot, sourcePath).slice(0, -extname3(sourcePath).length).split(sep2).join("/");
|
|
1092
|
+
}
|
|
1093
|
+
function isInside(root, candidate) {
|
|
1094
|
+
const normalizedRoot = `${resolve4(root)}${sep2}`;
|
|
1095
|
+
const normalizedCandidate = resolve4(candidate);
|
|
1096
|
+
return normalizedCandidate === resolve4(root) || normalizedCandidate.startsWith(normalizedRoot);
|
|
1097
|
+
}
|
|
1098
|
+
async function exists(path) {
|
|
1099
|
+
try {
|
|
1100
|
+
await access4(path);
|
|
1101
|
+
return true;
|
|
1102
|
+
} catch {
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
function location(node, file) {
|
|
1107
|
+
const start = node.position?.start;
|
|
1108
|
+
return start ? { file, line: start.line, column: start.column } : { file };
|
|
1109
|
+
}
|
|
1110
|
+
function walk(node, visitor) {
|
|
1111
|
+
visitor(node);
|
|
1112
|
+
if ("children" in node && Array.isArray(node.children)) {
|
|
1113
|
+
for (const child of node.children) walk(child, visitor);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
var IGNORED_VAULT_DIRECTORIES = /* @__PURE__ */ new Set([".obsidian", ".fafa", ".git", "node_modules"]);
|
|
1117
|
+
function protectCode(context, markdown) {
|
|
1118
|
+
const protect = (value) => {
|
|
1119
|
+
const token = `FAFA_PROTECTED_CODE_${context.nextProtectedCode}`;
|
|
1120
|
+
context.nextProtectedCode += 1;
|
|
1121
|
+
context.protectedCode.set(token, value);
|
|
1122
|
+
return token;
|
|
1123
|
+
};
|
|
1124
|
+
return markdown.replace(/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[ \t]*$/gm, protect).replace(/(`+)([^`\n]*?)\1/g, protect);
|
|
1125
|
+
}
|
|
1126
|
+
function restoreCode(context, markdown) {
|
|
1127
|
+
let restored = markdown;
|
|
1128
|
+
for (const [token, code] of context.protectedCode) restored = restored.replaceAll(token, code);
|
|
1129
|
+
return restored;
|
|
1130
|
+
}
|
|
1131
|
+
function parseObsidianTarget(raw) {
|
|
1132
|
+
const [reference = "", alias] = raw.split("|", 2);
|
|
1133
|
+
const hashIndex = reference.indexOf("#");
|
|
1134
|
+
if (hashIndex < 0) return { path: reference.trim(), ...alias?.trim() ? { alias: alias.trim() } : {} };
|
|
1135
|
+
return {
|
|
1136
|
+
path: reference.slice(0, hashIndex).trim(),
|
|
1137
|
+
selector: reference.slice(hashIndex + 1).trim(),
|
|
1138
|
+
...alias?.trim() ? { alias: alias.trim() } : {}
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
async function listVaultFiles(root) {
|
|
1142
|
+
const files = [];
|
|
1143
|
+
async function visit(directory) {
|
|
1144
|
+
const entries = await readdir2(directory, { withFileTypes: true });
|
|
1145
|
+
await Promise.all(
|
|
1146
|
+
entries.map(async (entry) => {
|
|
1147
|
+
const path = join4(directory, entry.name);
|
|
1148
|
+
if (entry.isDirectory() && !IGNORED_VAULT_DIRECTORIES.has(entry.name)) await visit(path);
|
|
1149
|
+
else if (entry.isFile()) files.push(path);
|
|
1150
|
+
})
|
|
1151
|
+
);
|
|
1152
|
+
}
|
|
1153
|
+
await visit(root);
|
|
1154
|
+
return files;
|
|
1155
|
+
}
|
|
1156
|
+
async function resolveVaultFile(context, currentSource, target, defaultExtension = "") {
|
|
1157
|
+
const decoded = decodeURIComponent(target).replaceAll("\\", "/");
|
|
1158
|
+
const withExtension = extname3(decoded) || !defaultExtension ? decoded : `${decoded}${defaultExtension}`;
|
|
1159
|
+
const candidates = [
|
|
1160
|
+
resolve4(dirname3(currentSource), withExtension),
|
|
1161
|
+
resolve4(context.projectRoot, withExtension.replace(/^\/+/, ""))
|
|
1162
|
+
];
|
|
1163
|
+
for (const candidate of candidates) {
|
|
1164
|
+
if (isInside(context.projectRoot, candidate) && await exists(candidate)) return candidate;
|
|
1165
|
+
}
|
|
1166
|
+
context.files ??= listVaultFiles(context.projectRoot);
|
|
1167
|
+
const expectedName = basename4(withExtension).toLocaleLowerCase();
|
|
1168
|
+
const matches = (await context.files).filter(
|
|
1169
|
+
(candidate) => basename4(candidate).toLocaleLowerCase() === expectedName
|
|
1170
|
+
);
|
|
1171
|
+
if (matches.length === 1) return matches[0];
|
|
1172
|
+
if (matches.length > 1) {
|
|
1173
|
+
throw new FaFaError("CHECK_FAILED", `Obsidian link is ambiguous: ${target}`, { matches });
|
|
1174
|
+
}
|
|
1175
|
+
throw new FaFaError("CHECK_FAILED", `Obsidian link target does not exist: ${target}`, {
|
|
1176
|
+
source: currentSource
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
function extractHeading(markdown, heading) {
|
|
1180
|
+
const lines = markdown.split(/\r?\n/);
|
|
1181
|
+
const expected = heading.trim().toLocaleLowerCase();
|
|
1182
|
+
const start = lines.findIndex((line) => {
|
|
1183
|
+
const match = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
|
|
1184
|
+
return match?.[2]?.trim().toLocaleLowerCase() === expected;
|
|
1185
|
+
});
|
|
1186
|
+
if (start < 0) return void 0;
|
|
1187
|
+
const level = /^(#{1,6})/.exec(lines[start])?.[1]?.length ?? 6;
|
|
1188
|
+
let end = lines.length;
|
|
1189
|
+
for (let index = start + 1; index < lines.length; index += 1) {
|
|
1190
|
+
const nextLevel = /^(#{1,6})\s+/.exec(lines[index])?.[1]?.length;
|
|
1191
|
+
if (nextLevel && nextLevel <= level) {
|
|
1192
|
+
end = index;
|
|
1193
|
+
break;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
return lines.slice(start + 1, end).join("\n").trim();
|
|
1197
|
+
}
|
|
1198
|
+
function extractBlock(markdown, blockId) {
|
|
1199
|
+
const lines = markdown.split(/\r?\n/);
|
|
1200
|
+
const marker = `^${blockId}`;
|
|
1201
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
1202
|
+
const line = lines[index];
|
|
1203
|
+
if (line.trim() === marker) {
|
|
1204
|
+
let end = index - 1;
|
|
1205
|
+
while (end >= 0 && !lines[end].trim()) end -= 1;
|
|
1206
|
+
let start = end;
|
|
1207
|
+
while (start > 0 && lines[start - 1].trim() && !/^#{1,6}\s+/.test(lines[start - 1])) {
|
|
1208
|
+
start -= 1;
|
|
1209
|
+
}
|
|
1210
|
+
return lines.slice(start, end + 1).join("\n").trim();
|
|
1211
|
+
}
|
|
1212
|
+
if (line.trimEnd().endsWith(` ${marker}`)) {
|
|
1213
|
+
return line.slice(0, line.lastIndexOf(marker)).trimEnd();
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
return void 0;
|
|
1217
|
+
}
|
|
1218
|
+
function extractSelection(markdown, selector) {
|
|
1219
|
+
if (!selector) return markdown.trim();
|
|
1220
|
+
const selected = selector.startsWith("^") ? extractBlock(markdown, selector.slice(1)) : extractHeading(markdown, selector);
|
|
1221
|
+
if (selected === void 0) {
|
|
1222
|
+
throw new FaFaError("CHECK_FAILED", `Obsidian embed target was not found: #${selector}`);
|
|
1223
|
+
}
|
|
1224
|
+
return selected;
|
|
1225
|
+
}
|
|
1226
|
+
function relativeMarkdownPath(from, target) {
|
|
1227
|
+
const value = relative3(from, target).split(sep2).join("/");
|
|
1228
|
+
return encodeURI(value.startsWith(".") ? value : `./${value}`);
|
|
1229
|
+
}
|
|
1230
|
+
function rewriteRelativeImages(markdown, sourceDir, articleDir) {
|
|
1231
|
+
return markdown.replace(/(!\[[^\]]*\]\()([^\s)]+)(\))/g, (match, open, rawPath, close) => {
|
|
1232
|
+
if (/^(?:https?:|data:|asset:)/i.test(rawPath)) return match;
|
|
1233
|
+
const target = resolve4(sourceDir, decodeURIComponent(rawPath.split(/[?#]/, 1)[0] ?? rawPath));
|
|
1234
|
+
return `${open}${relativeMarkdownPath(articleDir, target)}${close}`;
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
async function expandObsidianEmbeds(context, currentSource, markdown, stack) {
|
|
1238
|
+
let content = protectCode(context, markdown);
|
|
1239
|
+
content = dirname3(currentSource) === context.articleDir ? content : rewriteRelativeImages(content, dirname3(currentSource), context.articleDir);
|
|
1240
|
+
const matches = [...content.matchAll(/!\[\[([^\]]+)\]\]/g)];
|
|
1241
|
+
for (const match of matches) {
|
|
1242
|
+
const raw = match[0];
|
|
1243
|
+
const target = parseObsidianTarget(match[1]);
|
|
1244
|
+
const targetExtension = extname3(target.path).toLocaleLowerCase();
|
|
1245
|
+
if (targetExtension && targetExtension !== ".md") {
|
|
1246
|
+
const assetPath = await resolveVaultFile(context, currentSource, target.path);
|
|
1247
|
+
const replacement2 = `})`;
|
|
1248
|
+
content = content.replace(raw, replacement2);
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
const targetSource = target.path ? await resolveVaultFile(context, currentSource, target.path, ".md") : currentSource;
|
|
1252
|
+
const stackKey = `${targetSource}#${target.selector ?? ""}`;
|
|
1253
|
+
if (stack.includes(stackKey) || stack.length >= 12) {
|
|
1254
|
+
throw new FaFaError("CHECK_FAILED", `Circular or too-deep Obsidian embed: ${raw}`, { stack });
|
|
1255
|
+
}
|
|
1256
|
+
const targetMarkdown = targetSource === currentSource && !target.path ? markdown : matter2(await readFile5(targetSource, "utf8")).content;
|
|
1257
|
+
const selected = extractSelection(targetMarkdown, target.selector);
|
|
1258
|
+
const replacement = await expandObsidianEmbeds(context, targetSource, selected, [...stack, stackKey]);
|
|
1259
|
+
content = content.replace(raw, replacement);
|
|
1260
|
+
}
|
|
1261
|
+
return content.replace(/(?<!!)\[\[([^\]]+)\]\]/g, (_match, rawTarget) => {
|
|
1262
|
+
const target = parseObsidianTarget(rawTarget);
|
|
1263
|
+
return target.alias ?? target.selector?.replace(/^\^/, "") ?? basename4(target.path, extname3(target.path));
|
|
1264
|
+
}).replace(/^[ \t]*\^[a-zA-Z0-9-]+[ \t]*$/gm, "").replace(/[ \t]+\^[a-zA-Z0-9-]+(?=[ \t]*$)/gm, "");
|
|
1265
|
+
}
|
|
1266
|
+
async function parseArticle(projectRoot, source) {
|
|
1267
|
+
if (extname3(source).toLocaleLowerCase() !== ".md") {
|
|
1268
|
+
throw new FaFaError("ARTICLE_NOT_FOUND", `Expected a Markdown note path: ${source}`);
|
|
1269
|
+
}
|
|
1270
|
+
const articleDir = dirname3(source);
|
|
1271
|
+
const raw = await readFile5(source, "utf8");
|
|
1272
|
+
return parseArticleContent(projectRoot, articleDir, raw, source);
|
|
1273
|
+
}
|
|
1274
|
+
async function parseArticleContent(projectRoot, articleDir, raw, sourcePath = join4(articleDir, "stdin.md")) {
|
|
1275
|
+
const parsedMatter = matter2(raw);
|
|
1276
|
+
const frontmatter = parsedMatter.data;
|
|
1277
|
+
const sourceLineOffset = (raw.slice(0, Math.max(0, raw.length - parsedMatter.content.length)).match(/\n/g) ?? []).length;
|
|
1278
|
+
const embedContext = {
|
|
1279
|
+
projectRoot,
|
|
1280
|
+
articleDir,
|
|
1281
|
+
protectedCode: /* @__PURE__ */ new Map(),
|
|
1282
|
+
nextProtectedCode: 0
|
|
1283
|
+
};
|
|
1284
|
+
const expanded = restoreCode(
|
|
1285
|
+
embedContext,
|
|
1286
|
+
await expandObsidianEmbeds(embedContext, sourcePath, parsedMatter.content, [`${sourcePath}#`])
|
|
1287
|
+
);
|
|
1288
|
+
const tree = unified().use(remarkParse).use(remarkGfm).use(remarkMath).parse(expanded);
|
|
1289
|
+
const diagnostics = [];
|
|
1290
|
+
const assets = [];
|
|
1291
|
+
let imageIndex = 0;
|
|
1292
|
+
walk(tree, (node) => {
|
|
1293
|
+
if (node.type === "html") {
|
|
1294
|
+
diagnostics.push({
|
|
1295
|
+
code: "RAW_HTML_NOT_ALLOWED",
|
|
1296
|
+
severity: "error",
|
|
1297
|
+
message: "Raw HTML is not allowed in source manuscripts.",
|
|
1298
|
+
location: location(node, sourcePath),
|
|
1299
|
+
hint: "Use Markdown constructs so the platform renderer can enforce compatibility."
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
});
|
|
1303
|
+
const images = [];
|
|
1304
|
+
walk(tree, (node) => {
|
|
1305
|
+
if (node.type === "image") images.push(node);
|
|
1306
|
+
});
|
|
1307
|
+
for (const image of images) {
|
|
1308
|
+
const source = image.url.trim();
|
|
1309
|
+
const id2 = `asset-${imageIndex}-${sha256(`${sourcePath}:${imageIndex}:${source}`).slice(0, 12)}`;
|
|
1310
|
+
imageIndex += 1;
|
|
1311
|
+
if (/^https:\/\//i.test(source)) {
|
|
1312
|
+
assets.push({
|
|
1313
|
+
id: id2,
|
|
1314
|
+
source,
|
|
1315
|
+
origin: "remote",
|
|
1316
|
+
purpose: "inline",
|
|
1317
|
+
remoteUrl: source,
|
|
1318
|
+
...image.alt ? { alt: image.alt } : {},
|
|
1319
|
+
...image.title ? { title: image.title } : {}
|
|
1320
|
+
});
|
|
1321
|
+
image.url = `asset://${id2}`;
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(source)) {
|
|
1325
|
+
diagnostics.push({
|
|
1326
|
+
code: "ASSET_SCHEME_NOT_ALLOWED",
|
|
1327
|
+
severity: "error",
|
|
1328
|
+
message: `Only project-local paths and HTTPS images are allowed: ${source}`,
|
|
1329
|
+
location: location(image, sourcePath)
|
|
1330
|
+
});
|
|
1331
|
+
continue;
|
|
1332
|
+
}
|
|
1333
|
+
const resolvedPath = resolve4(articleDir, decodeURIComponent(source.split(/[?#]/, 1)[0] ?? source));
|
|
1334
|
+
if (!isInside(projectRoot, resolvedPath)) {
|
|
1335
|
+
diagnostics.push({
|
|
1336
|
+
code: "ASSET_OUTSIDE_PROJECT",
|
|
1337
|
+
severity: "error",
|
|
1338
|
+
message: `Asset escapes project root: ${source}`,
|
|
1339
|
+
location: location(image, sourcePath)
|
|
1340
|
+
});
|
|
1341
|
+
continue;
|
|
1342
|
+
}
|
|
1343
|
+
if (!await exists(resolvedPath)) {
|
|
1344
|
+
diagnostics.push({
|
|
1345
|
+
code: "ASSET_NOT_FOUND",
|
|
1346
|
+
severity: "error",
|
|
1347
|
+
message: `Asset does not exist: ${source}`,
|
|
1348
|
+
location: location(image, sourcePath)
|
|
1349
|
+
});
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1352
|
+
assets.push({
|
|
1353
|
+
id: id2,
|
|
1354
|
+
source,
|
|
1355
|
+
origin: resolvedPath.startsWith(`${resolve4(articleDir)}${sep2}`) ? "article" : "shared",
|
|
1356
|
+
purpose: "inline",
|
|
1357
|
+
resolvedPath,
|
|
1358
|
+
...image.alt ? { alt: image.alt } : {},
|
|
1359
|
+
...image.title ? { title: image.title } : {}
|
|
1360
|
+
});
|
|
1361
|
+
image.url = `asset://${id2}`;
|
|
1362
|
+
}
|
|
1363
|
+
const id = articleId(projectRoot, sourcePath, frontmatter);
|
|
1364
|
+
if (!id) throw new FaFaError("CONFIG_INVALID", `Could not derive article id for ${sourcePath}`);
|
|
1365
|
+
return {
|
|
1366
|
+
manuscript: {
|
|
1367
|
+
id,
|
|
1368
|
+
projectRoot,
|
|
1369
|
+
articleDir,
|
|
1370
|
+
sourcePath,
|
|
1371
|
+
markdown: expanded,
|
|
1372
|
+
frontmatter
|
|
1373
|
+
},
|
|
1374
|
+
tree,
|
|
1375
|
+
assets,
|
|
1376
|
+
diagnostics,
|
|
1377
|
+
sourceLineOffset
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
function createCoverReference(projectRoot, articleDir, source) {
|
|
1381
|
+
const id = `cover-${sha256(`${articleDir}:${source}`).slice(0, 12)}`;
|
|
1382
|
+
if (/^https:\/\//i.test(source)) {
|
|
1383
|
+
return { id, source, origin: "remote", purpose: "cover", remoteUrl: source };
|
|
1384
|
+
}
|
|
1385
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(source)) {
|
|
1386
|
+
throw new FaFaError("ASSET_INVALID", `Only project-local paths and HTTPS covers are allowed: ${source}`);
|
|
1387
|
+
}
|
|
1388
|
+
const resolvedPath = resolve4(articleDir, decodeURIComponent(source.split(/[?#]/, 1)[0] ?? source));
|
|
1389
|
+
if (!isInside(projectRoot, resolvedPath)) {
|
|
1390
|
+
throw new FaFaError("ASSET_INVALID", `Cover escapes project root: ${source}`);
|
|
1391
|
+
}
|
|
1392
|
+
return {
|
|
1393
|
+
id,
|
|
1394
|
+
source,
|
|
1395
|
+
origin: resolvedPath.startsWith(`${resolve4(articleDir)}${sep2}`) ? "article" : "shared",
|
|
1396
|
+
purpose: "cover",
|
|
1397
|
+
resolvedPath
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
function manuscriptDisplayName(article) {
|
|
1401
|
+
return typeof article.manuscript.frontmatter.title === "string" ? article.manuscript.frontmatter.title : basename4(article.manuscript.sourcePath, extname3(article.manuscript.sourcePath));
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// ../../packages/renderer-wechat/dist/index.js
|
|
1405
|
+
import { createHash as createHash22 } from "crypto";
|
|
1406
|
+
|
|
1407
|
+
// ../../packages/i18n/dist/index.js
|
|
1408
|
+
function normalizeLocale(input, fallback = "zh-CN") {
|
|
1409
|
+
const normalized = input?.trim().replaceAll("_", "-").toLowerCase();
|
|
1410
|
+
if (!normalized) return fallback;
|
|
1411
|
+
return normalized === "zh" || normalized.startsWith("zh-") ? "zh-CN" : "en";
|
|
1412
|
+
}
|
|
1413
|
+
function localeFromEnvironment(environment, fallback = "zh-CN") {
|
|
1414
|
+
return normalizeLocale(
|
|
1415
|
+
environment.FAFA_LANGUAGE ?? environment.LC_ALL ?? environment.LC_MESSAGES ?? environment.LANG,
|
|
1416
|
+
fallback
|
|
1417
|
+
);
|
|
1418
|
+
}
|
|
1419
|
+
function formatMessage(template, values = {}) {
|
|
1420
|
+
return template.replaceAll(/\{([a-zA-Z0-9_]+)\}/g, (match, key) => {
|
|
1421
|
+
const value = values[key];
|
|
1422
|
+
return value === void 0 ? match : String(value);
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
function createTranslator(locale, catalog) {
|
|
1426
|
+
const messages = catalog[locale];
|
|
1427
|
+
return (key, values) => formatMessage(messages[key], values);
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// ../../packages/renderer-wechat/dist/index.js
|
|
1431
|
+
import { createHash as createHash4 } from "crypto";
|
|
1432
|
+
import { fromShikiTheme, renderMermaidSVG } from "beautiful-mermaid";
|
|
1433
|
+
import sharp2 from "sharp";
|
|
1434
|
+
import { createBundledHighlighter } from "shiki/core";
|
|
1435
|
+
import { createOnigurumaEngine } from "shiki/engine/oniguruma";
|
|
1436
|
+
import { bundledLanguages, bundledLanguagesAlias } from "shiki/langs";
|
|
1437
|
+
import { bundledThemes } from "shiki/themes";
|
|
1438
|
+
import MathJaxLoader from "mathjax";
|
|
1439
|
+
import sharp3 from "sharp";
|
|
1440
|
+
import { readFile as readFile6, stat as stat4 } from "fs/promises";
|
|
1441
|
+
import { basename as basename5, extname as extname4, isAbsolute as isAbsolute3, relative as relative4, resolve as resolve5, sep as sep3 } from "path";
|
|
1442
|
+
import { fileURLToPath } from "url";
|
|
1443
|
+
import juice from "juice";
|
|
1444
|
+
var mathJaxPackage = MathJaxLoader;
|
|
1445
|
+
var LOGICAL_EM_PIXELS = 16;
|
|
1446
|
+
var LOGICAL_EX_PIXELS = 8;
|
|
1447
|
+
var RASTER_SCALE = 2;
|
|
1448
|
+
var CONTAINER_WIDTH_PIXELS = 720;
|
|
1449
|
+
var MAX_RASTER_WIDTH = 4096;
|
|
1450
|
+
var MAX_RASTER_HEIGHT = 2048;
|
|
1451
|
+
var FORMULA_COLOR = "#24292f";
|
|
1452
|
+
var mathJaxPromise;
|
|
1453
|
+
var renderQueue = Promise.resolve();
|
|
1454
|
+
function getMathJax() {
|
|
1455
|
+
mathJaxPromise ??= mathJaxPackage.init({
|
|
1456
|
+
loader: {
|
|
1457
|
+
load: ["input/tex-base", "[tex]/ams", "[tex]/newcommand", "output/svg"]
|
|
1458
|
+
},
|
|
1459
|
+
tex: {
|
|
1460
|
+
packages: ["base", "ams", "newcommand"],
|
|
1461
|
+
maxBuffer: 1e4,
|
|
1462
|
+
maxTemplateSubtitutions: 1e3,
|
|
1463
|
+
processRefs: false,
|
|
1464
|
+
tags: "none",
|
|
1465
|
+
formatError(_jax, error) {
|
|
1466
|
+
throw error;
|
|
1467
|
+
}
|
|
1468
|
+
},
|
|
1469
|
+
svg: {
|
|
1470
|
+
fontCache: "none"
|
|
1471
|
+
},
|
|
1472
|
+
output: {
|
|
1473
|
+
linebreaks: {
|
|
1474
|
+
inline: false
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
});
|
|
1478
|
+
return mathJaxPromise;
|
|
1479
|
+
}
|
|
1480
|
+
function svgMetrics(svg) {
|
|
1481
|
+
const viewBox = /viewBox="(-?[\d.]+)\s+(-?[\d.]+)\s+([\d.]+)\s+([\d.]+)"/.exec(svg);
|
|
1482
|
+
const viewBoxWidth = viewBox?.[3] === void 0 ? void 0 : Number.parseFloat(viewBox[3]);
|
|
1483
|
+
const viewBoxHeight = viewBox?.[4] === void 0 ? void 0 : Number.parseFloat(viewBox[4]);
|
|
1484
|
+
if (viewBoxWidth === void 0 || viewBoxHeight === void 0 || !Number.isFinite(viewBoxWidth) || !Number.isFinite(viewBoxHeight) || viewBoxWidth <= 0 || viewBoxHeight <= 0) {
|
|
1485
|
+
throw new Error("MathJax returned an SVG without valid dimensions.");
|
|
1486
|
+
}
|
|
1487
|
+
const verticalAlignMatch = /vertical-align:\s*(-?[\d.]+)ex/.exec(svg);
|
|
1488
|
+
const verticalAlignEx = verticalAlignMatch?.[1] === void 0 ? void 0 : Number.parseFloat(verticalAlignMatch[1]);
|
|
1489
|
+
return {
|
|
1490
|
+
width: viewBoxWidth / 1e3 * LOGICAL_EM_PIXELS,
|
|
1491
|
+
height: viewBoxHeight / 1e3 * LOGICAL_EM_PIXELS,
|
|
1492
|
+
verticalAlign: (verticalAlignEx ?? 0) * (LOGICAL_EX_PIXELS / LOGICAL_EM_PIXELS)
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
function rasterDimensions(width, height) {
|
|
1496
|
+
const requestedWidth = Math.max(1, width * RASTER_SCALE);
|
|
1497
|
+
const requestedHeight = Math.max(1, height * RASTER_SCALE);
|
|
1498
|
+
const scale = Math.min(1, MAX_RASTER_WIDTH / requestedWidth, MAX_RASTER_HEIGHT / requestedHeight);
|
|
1499
|
+
return {
|
|
1500
|
+
width: Math.max(1, Math.round(requestedWidth * scale)),
|
|
1501
|
+
height: Math.max(1, Math.round(requestedHeight * scale))
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
function prepareSvg(svg, width, height) {
|
|
1505
|
+
return svg.replace(/\sdata-[A-Za-z0-9:_-]+="[^"]*"/g, "").replaceAll("currentColor", FORMULA_COLOR).replace(/\swidth="[^"]*"/, ` width="${width}"`).replace(/\sheight="[^"]*"/, ` height="${height}"`);
|
|
1506
|
+
}
|
|
1507
|
+
async function render(source, display) {
|
|
1508
|
+
const mathJax = await getMathJax();
|
|
1509
|
+
if (!mathJax) throw new Error("MathJax could not be initialized.");
|
|
1510
|
+
const container = await mathJax.tex2svgPromise(source, {
|
|
1511
|
+
display,
|
|
1512
|
+
em: LOGICAL_EM_PIXELS,
|
|
1513
|
+
ex: LOGICAL_EX_PIXELS,
|
|
1514
|
+
containerWidth: CONTAINER_WIDTH_PIXELS
|
|
1515
|
+
});
|
|
1516
|
+
const svgNode = mathJax.startup.adaptor.tags(container, "svg")[0];
|
|
1517
|
+
if (!svgNode) throw new Error("MathJax did not produce an SVG.");
|
|
1518
|
+
const svg = mathJax.startup.adaptor.serializeXML(svgNode);
|
|
1519
|
+
if (/<(?:script|image|foreignObject)\b|\b(?:href|xlink:href)=/i.test(svg)) {
|
|
1520
|
+
throw new Error("MathJax produced an SVG with unsupported external or interactive content.");
|
|
1521
|
+
}
|
|
1522
|
+
const metrics = svgMetrics(svg);
|
|
1523
|
+
const raster = rasterDimensions(metrics.width, metrics.height);
|
|
1524
|
+
const bytes = new Uint8Array(
|
|
1525
|
+
await sharp3(Buffer.from(prepareSvg(svg, raster.width, raster.height))).png({ compressionLevel: 9 }).toBuffer()
|
|
1526
|
+
);
|
|
1527
|
+
return {
|
|
1528
|
+
bytes,
|
|
1529
|
+
width: metrics.width,
|
|
1530
|
+
height: metrics.height,
|
|
1531
|
+
verticalAlign: metrics.verticalAlign,
|
|
1532
|
+
engineVersion: mathJax.version
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
function renderLatexPng(source, display) {
|
|
1536
|
+
const result2 = renderQueue.then(() => render(source, display));
|
|
1537
|
+
renderQueue = result2.then(
|
|
1538
|
+
() => void 0,
|
|
1539
|
+
() => void 0
|
|
1540
|
+
);
|
|
1541
|
+
return result2;
|
|
1542
|
+
}
|
|
1543
|
+
var MAX_HIGHLIGHTED_CODE_CHARS = 1e5;
|
|
1544
|
+
var MAX_MERMAID_CHARS = 5e4;
|
|
1545
|
+
var MAX_MERMAID_BLOCKS = 20;
|
|
1546
|
+
var MAX_LATEX_CHARS = 1e4;
|
|
1547
|
+
var MAX_LATEX_FORMULAS = 100;
|
|
1548
|
+
var codeThemeIds = [
|
|
1549
|
+
"github-light",
|
|
1550
|
+
"min-light",
|
|
1551
|
+
"light-plus",
|
|
1552
|
+
"rose-pine-dawn",
|
|
1553
|
+
"github-dark",
|
|
1554
|
+
"nord",
|
|
1555
|
+
"one-dark-pro",
|
|
1556
|
+
"dracula"
|
|
1557
|
+
];
|
|
1558
|
+
var codeThemeNames = {
|
|
1559
|
+
"github-light": "GitHub Light",
|
|
1560
|
+
"min-light": "Min Light",
|
|
1561
|
+
"light-plus": "Light Plus",
|
|
1562
|
+
"rose-pine-dawn": "Ros\xE9 Pine Dawn",
|
|
1563
|
+
"github-dark": "GitHub Dark",
|
|
1564
|
+
nord: "Nord",
|
|
1565
|
+
"one-dark-pro": "One Dark Pro",
|
|
1566
|
+
dracula: "Dracula"
|
|
1567
|
+
};
|
|
1568
|
+
var codeThemeMessages = {
|
|
1569
|
+
en: {
|
|
1570
|
+
"github-light": "A clear, neutral light code theme.",
|
|
1571
|
+
"min-light": "A minimal light theme with low visual noise.",
|
|
1572
|
+
"light-plus": "The classic light theme familiar from VS Code.",
|
|
1573
|
+
"rose-pine-dawn": "A soft, warm light code theme.",
|
|
1574
|
+
"github-dark": "A high-contrast dark code theme.",
|
|
1575
|
+
nord: "A calm blue-gray dark theme.",
|
|
1576
|
+
"one-dark-pro": "A classic dark theme for technical writing.",
|
|
1577
|
+
dracula: "A vivid, colorful dark theme."
|
|
1578
|
+
},
|
|
1579
|
+
"zh-CN": {
|
|
1580
|
+
"github-light": "\u6E05\u6670\u4E2D\u6027\u7684\u6D45\u8272\u4EE3\u7801\u4E3B\u9898\u3002",
|
|
1581
|
+
"min-light": "\u4F4E\u5E72\u6270\u7684\u6781\u7B80\u6D45\u8272\u4EE3\u7801\u4E3B\u9898\u3002",
|
|
1582
|
+
"light-plus": "\u63A5\u8FD1 VS Code \u7684\u7ECF\u5178\u6D45\u8272\u4E3B\u9898\u3002",
|
|
1583
|
+
"rose-pine-dawn": "\u67D4\u548C\u6E29\u6696\u7684\u6D45\u8272\u4EE3\u7801\u4E3B\u9898\u3002",
|
|
1584
|
+
"github-dark": "\u9AD8\u5BF9\u6BD4\u5EA6\u7684\u6DF1\u8272\u4EE3\u7801\u4E3B\u9898\u3002",
|
|
1585
|
+
nord: "\u51B7\u9759\u514B\u5236\u7684\u84DD\u7070\u6DF1\u8272\u4E3B\u9898\u3002",
|
|
1586
|
+
"one-dark-pro": "\u9002\u5408\u6280\u672F\u6587\u7AE0\u7684\u7ECF\u5178\u6DF1\u8272\u4E3B\u9898\u3002",
|
|
1587
|
+
dracula: "\u8272\u5F69\u9C9C\u660E\u7684\u6DF1\u8272\u4EE3\u7801\u4E3B\u9898\u3002"
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
var codeThemeIdSet = new Set(codeThemeIds);
|
|
1591
|
+
var createHighlighter = createBundledHighlighter({
|
|
1592
|
+
langs: bundledLanguages,
|
|
1593
|
+
themes: bundledThemes,
|
|
1594
|
+
engine: () => createOnigurumaEngine(import("shiki/wasm"))
|
|
1595
|
+
});
|
|
1596
|
+
var highlighterPromise = createHighlighter({
|
|
1597
|
+
langs: [],
|
|
1598
|
+
themes: [...codeThemeIds]
|
|
1599
|
+
});
|
|
1600
|
+
function sha2562(value) {
|
|
1601
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1602
|
+
}
|
|
1603
|
+
function walk2(node, visitor) {
|
|
1604
|
+
visitor(node);
|
|
1605
|
+
if ("children" in node && Array.isArray(node.children)) {
|
|
1606
|
+
for (const child of node.children) walk2(child, visitor);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
function diagnosticLocation(article, node) {
|
|
1610
|
+
const start = node.position?.start;
|
|
1611
|
+
return start ? {
|
|
1612
|
+
file: article.manuscript.sourcePath,
|
|
1613
|
+
line: start.line + article.sourceLineOffset,
|
|
1614
|
+
column: start.column
|
|
1615
|
+
} : { file: article.manuscript.sourcePath };
|
|
1616
|
+
}
|
|
1617
|
+
function plainCodeBlock(value, colors, language) {
|
|
1618
|
+
return {
|
|
1619
|
+
kind: "code",
|
|
1620
|
+
...language ? { language } : {},
|
|
1621
|
+
lines: value.split("\n").map((line) => [{ content: line || " ", color: colors.foreground }]),
|
|
1622
|
+
...colors
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
function knownLanguage(language) {
|
|
1626
|
+
return language in bundledLanguages || language in bundledLanguagesAlias;
|
|
1627
|
+
}
|
|
1628
|
+
function matchingParenthesis(value, openIndex) {
|
|
1629
|
+
let depth = 0;
|
|
1630
|
+
for (let index = openIndex; index < value.length; index += 1) {
|
|
1631
|
+
if (value[index] === "(") depth += 1;
|
|
1632
|
+
if (value[index] === ")") {
|
|
1633
|
+
depth -= 1;
|
|
1634
|
+
if (depth === 0) return index;
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
throw new Error("Unable to resolve an unterminated CSS function in the Mermaid SVG.");
|
|
1638
|
+
}
|
|
1639
|
+
function splitCssArguments(value) {
|
|
1640
|
+
const parts = [];
|
|
1641
|
+
let depth = 0;
|
|
1642
|
+
let start = 0;
|
|
1643
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1644
|
+
if (value[index] === "(") depth += 1;
|
|
1645
|
+
else if (value[index] === ")") depth -= 1;
|
|
1646
|
+
else if (value[index] === "," && depth === 0) {
|
|
1647
|
+
parts.push(value.slice(start, index).trim());
|
|
1648
|
+
start = index + 1;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
parts.push(value.slice(start).trim());
|
|
1652
|
+
return parts;
|
|
1653
|
+
}
|
|
1654
|
+
function replaceCssFunctions(value, name, resolve22) {
|
|
1655
|
+
let output = value;
|
|
1656
|
+
const marker = `${name}(`;
|
|
1657
|
+
for (let attempt = 0; attempt < 1e3; attempt += 1) {
|
|
1658
|
+
const start = output.lastIndexOf(marker);
|
|
1659
|
+
if (start < 0) return output;
|
|
1660
|
+
const open = start + name.length;
|
|
1661
|
+
const close = matchingParenthesis(output, open);
|
|
1662
|
+
output = `${output.slice(0, start)}${resolve22(output.slice(open + 1, close))}${output.slice(close + 1)}`;
|
|
1663
|
+
}
|
|
1664
|
+
throw new Error(`Unable to resolve all ${name}() functions in the Mermaid SVG.`);
|
|
1665
|
+
}
|
|
1666
|
+
function parseCssColor(value) {
|
|
1667
|
+
const normalized = value.trim().toLocaleLowerCase();
|
|
1668
|
+
if (normalized === "transparent") return { red: 0, green: 0, blue: 0, alpha: 0 };
|
|
1669
|
+
const match = /^#([\da-f]{3,8})$/i.exec(normalized);
|
|
1670
|
+
if (!match) throw new Error(`Unsupported Mermaid theme color: ${value}`);
|
|
1671
|
+
let hex = match[1] ?? "";
|
|
1672
|
+
if (hex.length === 3 || hex.length === 4) {
|
|
1673
|
+
hex = [...hex].map((character) => character.repeat(2)).join("");
|
|
1674
|
+
}
|
|
1675
|
+
if (hex.length !== 6 && hex.length !== 8) {
|
|
1676
|
+
throw new Error(`Unsupported Mermaid theme color: ${value}`);
|
|
1677
|
+
}
|
|
1678
|
+
return {
|
|
1679
|
+
red: Number.parseInt(hex.slice(0, 2), 16),
|
|
1680
|
+
green: Number.parseInt(hex.slice(2, 4), 16),
|
|
1681
|
+
blue: Number.parseInt(hex.slice(4, 6), 16),
|
|
1682
|
+
alpha: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
function colorByte(value) {
|
|
1686
|
+
return Math.round(Math.max(0, Math.min(255, value)));
|
|
1687
|
+
}
|
|
1688
|
+
function formatCssColor(color) {
|
|
1689
|
+
const hex = (value) => colorByte(value).toString(16).padStart(2, "0");
|
|
1690
|
+
const alpha = colorByte(color.alpha * 255);
|
|
1691
|
+
return `#${hex(color.red)}${hex(color.green)}${hex(color.blue)}${alpha === 255 ? "" : hex(alpha)}`;
|
|
1692
|
+
}
|
|
1693
|
+
function parseWeightedColor(value) {
|
|
1694
|
+
const match = /^(.*?)(?:\s+([\d.]+)%)?$/.exec(value.trim());
|
|
1695
|
+
if (!match?.[1]) throw new Error(`Invalid color-mix() entry in Mermaid SVG: ${value}`);
|
|
1696
|
+
return {
|
|
1697
|
+
color: parseCssColor(match[1]),
|
|
1698
|
+
...match[2] === void 0 ? {} : { weight: Number.parseFloat(match[2]) }
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
function mixCssColors(firstValue, secondValue) {
|
|
1702
|
+
const first = parseWeightedColor(firstValue);
|
|
1703
|
+
const second = parseWeightedColor(secondValue);
|
|
1704
|
+
const firstWeight = first.weight ?? (second.weight === void 0 ? 50 : 100 - second.weight);
|
|
1705
|
+
const secondWeight = second.weight ?? 100 - firstWeight;
|
|
1706
|
+
const totalWeight = firstWeight + secondWeight;
|
|
1707
|
+
if (!Number.isFinite(totalWeight) || totalWeight <= 0) {
|
|
1708
|
+
throw new Error("Invalid color-mix() weights in Mermaid SVG.");
|
|
1709
|
+
}
|
|
1710
|
+
const firstAlphaWeight = first.color.alpha * firstWeight;
|
|
1711
|
+
const secondAlphaWeight = second.color.alpha * secondWeight;
|
|
1712
|
+
const alphaWeight = firstAlphaWeight + secondAlphaWeight;
|
|
1713
|
+
const channel = (firstChannel, secondChannel) => alphaWeight === 0 ? 0 : (firstChannel * firstAlphaWeight + secondChannel * secondAlphaWeight) / alphaWeight;
|
|
1714
|
+
return formatCssColor({
|
|
1715
|
+
red: channel(first.color.red, second.color.red),
|
|
1716
|
+
green: channel(first.color.green, second.color.green),
|
|
1717
|
+
blue: channel(first.color.blue, second.color.blue),
|
|
1718
|
+
alpha: alphaWeight / totalWeight
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1721
|
+
function resolveCssValue(value, variables) {
|
|
1722
|
+
const withVariables = replaceCssFunctions(value, "var", (contents) => {
|
|
1723
|
+
const [name, fallback] = splitCssArguments(contents);
|
|
1724
|
+
if (!name?.startsWith("--")) throw new Error(`Invalid CSS variable in Mermaid SVG: ${contents}`);
|
|
1725
|
+
const resolved = variables.get(name);
|
|
1726
|
+
if (resolved !== void 0) return resolved;
|
|
1727
|
+
if (fallback !== void 0) return fallback;
|
|
1728
|
+
throw new Error(`Unresolved CSS variable in Mermaid SVG: ${name}`);
|
|
1729
|
+
});
|
|
1730
|
+
return replaceCssFunctions(withVariables, "color-mix", (contents) => {
|
|
1731
|
+
const [space, first, second] = splitCssArguments(contents);
|
|
1732
|
+
if (space?.toLocaleLowerCase() !== "in srgb" || !first || !second) {
|
|
1733
|
+
throw new Error(`Unsupported color-mix() expression in Mermaid SVG: ${contents}`);
|
|
1734
|
+
}
|
|
1735
|
+
return mixCssColors(first, second);
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
function materializeMermaidSvg(svg, colors) {
|
|
1739
|
+
const variables = /* @__PURE__ */ new Map([
|
|
1740
|
+
["--bg", colors.bg],
|
|
1741
|
+
["--fg", colors.fg]
|
|
1742
|
+
]);
|
|
1743
|
+
for (const [name, value] of [
|
|
1744
|
+
["--line", colors.line],
|
|
1745
|
+
["--accent", colors.accent],
|
|
1746
|
+
["--muted", colors.muted],
|
|
1747
|
+
["--surface", colors.surface],
|
|
1748
|
+
["--border", colors.border]
|
|
1749
|
+
]) {
|
|
1750
|
+
if (value) variables.set(name, value);
|
|
1751
|
+
}
|
|
1752
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1753
|
+
for (const match of svg.matchAll(/(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g)) {
|
|
1754
|
+
if (match[1] && match[2] && !variables.has(match[1])) definitions.set(match[1], match[2].trim());
|
|
1755
|
+
}
|
|
1756
|
+
for (let attempt = 0; definitions.size > 0 && attempt < 100; attempt += 1) {
|
|
1757
|
+
let progress = false;
|
|
1758
|
+
for (const [name, value] of definitions) {
|
|
1759
|
+
try {
|
|
1760
|
+
variables.set(name, resolveCssValue(value, variables));
|
|
1761
|
+
definitions.delete(name);
|
|
1762
|
+
progress = true;
|
|
1763
|
+
} catch {
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
if (!progress) break;
|
|
1767
|
+
}
|
|
1768
|
+
if (definitions.size > 0) {
|
|
1769
|
+
throw new Error(`Unable to resolve Mermaid SVG colors: ${[...definitions.keys()].join(", ")}`);
|
|
1770
|
+
}
|
|
1771
|
+
const materialized = resolveCssValue(svg, variables).replace(/\s*@import\s+url\([^)]*\);/g, "");
|
|
1772
|
+
if (materialized.includes("var(") || materialized.includes("color-mix(")) {
|
|
1773
|
+
throw new Error("Mermaid SVG still contains unresolved dynamic colors.");
|
|
1774
|
+
}
|
|
1775
|
+
return materialized.replace(
|
|
1776
|
+
/(<svg\b[^>]*>)/,
|
|
1777
|
+
`$1
|
|
1778
|
+
<rect x="0" y="0" width="100%" height="100%" fill="${colors.bg}" />`
|
|
1779
|
+
);
|
|
1780
|
+
}
|
|
1781
|
+
async function highlightCode(value, language, theme, diagnostics, article, node) {
|
|
1782
|
+
const highlighter = await highlighterPromise;
|
|
1783
|
+
const resolvedTheme = highlighter.getTheme(theme.id);
|
|
1784
|
+
const colors = {
|
|
1785
|
+
foreground: resolvedTheme.fg || "#24292f",
|
|
1786
|
+
background: resolvedTheme.bg || "#ffffff"
|
|
1787
|
+
};
|
|
1788
|
+
const normalizedLanguage = language?.trim().toLocaleLowerCase();
|
|
1789
|
+
if (!normalizedLanguage) return plainCodeBlock(value, colors);
|
|
1790
|
+
if (value.length > MAX_HIGHLIGHTED_CODE_CHARS) {
|
|
1791
|
+
diagnostics.push({
|
|
1792
|
+
code: "CODE_HIGHLIGHT_SKIPPED",
|
|
1793
|
+
severity: "warning",
|
|
1794
|
+
message: `Code block exceeds ${MAX_HIGHLIGHTED_CODE_CHARS} characters and was rendered without syntax highlighting.`,
|
|
1795
|
+
location: diagnosticLocation(article, node)
|
|
1796
|
+
});
|
|
1797
|
+
return plainCodeBlock(value, colors, normalizedLanguage);
|
|
1798
|
+
}
|
|
1799
|
+
if (!knownLanguage(normalizedLanguage)) {
|
|
1800
|
+
diagnostics.push({
|
|
1801
|
+
code: "CODE_LANGUAGE_UNSUPPORTED",
|
|
1802
|
+
severity: "warning",
|
|
1803
|
+
message: `Shiki does not recognize code language: ${normalizedLanguage}`,
|
|
1804
|
+
location: diagnosticLocation(article, node),
|
|
1805
|
+
hint: "Use a Shiki bundled language ID or omit the fenced code language."
|
|
1806
|
+
});
|
|
1807
|
+
return plainCodeBlock(value, colors, normalizedLanguage);
|
|
1808
|
+
}
|
|
1809
|
+
await highlighter.loadLanguage(normalizedLanguage);
|
|
1810
|
+
const result2 = highlighter.codeToTokens(value, {
|
|
1811
|
+
lang: normalizedLanguage,
|
|
1812
|
+
theme: theme.id,
|
|
1813
|
+
tokenizeMaxLineLength: 2e4,
|
|
1814
|
+
tokenizeTimeLimit: 500
|
|
1815
|
+
});
|
|
1816
|
+
return {
|
|
1817
|
+
kind: "code",
|
|
1818
|
+
language: normalizedLanguage,
|
|
1819
|
+
foreground: result2.fg || colors.foreground,
|
|
1820
|
+
background: result2.bg || colors.background,
|
|
1821
|
+
lines: result2.tokens.map(
|
|
1822
|
+
(line) => line.map((token) => ({
|
|
1823
|
+
content: token.content,
|
|
1824
|
+
...token.color ? { color: token.color } : {},
|
|
1825
|
+
...token.bgColor ? { backgroundColor: token.bgColor } : {},
|
|
1826
|
+
...token.fontStyle === void 0 ? {} : { fontStyle: token.fontStyle }
|
|
1827
|
+
}))
|
|
1828
|
+
)
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
async function renderMermaidAsset(article, node, index, theme) {
|
|
1832
|
+
const highlighter = await highlighterPromise;
|
|
1833
|
+
const colors = fromShikiTheme(highlighter.getTheme(theme.id));
|
|
1834
|
+
const svg = materializeMermaidSvg(
|
|
1835
|
+
renderMermaidSVG(node.value, {
|
|
1836
|
+
...colors,
|
|
1837
|
+
font: "Inter",
|
|
1838
|
+
padding: 36,
|
|
1839
|
+
transparent: true
|
|
1840
|
+
}),
|
|
1841
|
+
colors
|
|
1842
|
+
);
|
|
1843
|
+
const bytes = new Uint8Array(
|
|
1844
|
+
await sharp2(Buffer.from(svg), { density: 144 }).resize({ width: 1600, withoutEnlargement: true }).flatten({ background: colors.bg }).png({ compressionLevel: 9 }).toBuffer()
|
|
1845
|
+
);
|
|
1846
|
+
const sourceHash = sha2562(
|
|
1847
|
+
`${article.manuscript.sourcePath}:${node.position?.start.offset ?? index}:${node.value}`
|
|
1848
|
+
).slice(0, 12);
|
|
1849
|
+
const id = `diagram-${index}-${sourceHash}`;
|
|
1850
|
+
return {
|
|
1851
|
+
id,
|
|
1852
|
+
source: `mermaid:${index + 1}`,
|
|
1853
|
+
origin: "article",
|
|
1854
|
+
purpose: "inline",
|
|
1855
|
+
alt: node.meta?.trim().slice(0, 120) || "Mermaid \u56FE\u8868",
|
|
1856
|
+
hash: sha2562(bytes),
|
|
1857
|
+
mimeType: "image/png",
|
|
1858
|
+
bytes,
|
|
1859
|
+
filename: `${id}.png`,
|
|
1860
|
+
transformKey: `beautiful-mermaid-png-v2:${theme.id}`
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1863
|
+
async function renderLatexAsset(article, node, index) {
|
|
1864
|
+
const display = node.type === "math";
|
|
1865
|
+
const rendered = await renderLatexPng(node.value, display);
|
|
1866
|
+
const sourceHash = sha2562(
|
|
1867
|
+
`${article.manuscript.sourcePath}:${node.position?.start.offset ?? index}:${node.value}:${display}`
|
|
1868
|
+
).slice(0, 12);
|
|
1869
|
+
const id = `formula-${index}-${sourceHash}`;
|
|
1870
|
+
const bytes = rendered.bytes;
|
|
1871
|
+
const asset = {
|
|
1872
|
+
id,
|
|
1873
|
+
source: `latex:${display ? "block" : "inline"}:${index + 1}`,
|
|
1874
|
+
origin: "article",
|
|
1875
|
+
purpose: "inline",
|
|
1876
|
+
alt: `LaTeX: ${node.value.replaceAll(/\s+/g, " ").trim().slice(0, 500)}`,
|
|
1877
|
+
hash: sha2562(bytes),
|
|
1878
|
+
mimeType: "image/png",
|
|
1879
|
+
bytes,
|
|
1880
|
+
filename: `${id}.png`,
|
|
1881
|
+
transformKey: `mathjax-${rendered.engineVersion}-svg-png-v1`
|
|
1882
|
+
};
|
|
1883
|
+
return {
|
|
1884
|
+
kind: "math",
|
|
1885
|
+
asset,
|
|
1886
|
+
display,
|
|
1887
|
+
source: node.value,
|
|
1888
|
+
width: rendered.width,
|
|
1889
|
+
height: rendered.height,
|
|
1890
|
+
verticalAlign: rendered.verticalAlign
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
function listCodeHighlightThemes(locale = "zh-CN") {
|
|
1894
|
+
const t = createTranslator(locale, codeThemeMessages);
|
|
1895
|
+
return codeThemeIds.map((id) => ({
|
|
1896
|
+
id,
|
|
1897
|
+
name: codeThemeNames[id],
|
|
1898
|
+
description: t(id)
|
|
1899
|
+
}));
|
|
1900
|
+
}
|
|
1901
|
+
function resolveCodeHighlightTheme(reference, locale = "zh-CN") {
|
|
1902
|
+
const id = reference.trim();
|
|
1903
|
+
const theme = listCodeHighlightThemes(locale).find((candidate) => candidate.id === id);
|
|
1904
|
+
if (!theme || !codeThemeIdSet.has(id)) {
|
|
1905
|
+
throw new FaFaError("CONFIG_INVALID", `Unknown built-in Shiki code theme: ${reference}`);
|
|
1906
|
+
}
|
|
1907
|
+
return { ...theme };
|
|
1908
|
+
}
|
|
1909
|
+
async function prepareWechatRichContent(article, codeThemeReference = "github-light") {
|
|
1910
|
+
const codeTheme = resolveCodeHighlightTheme(codeThemeReference);
|
|
1911
|
+
const nodes = [];
|
|
1912
|
+
walk2(article.tree, (node) => {
|
|
1913
|
+
if (node.type === "code" || node.type === "math" || node.type === "inlineMath") {
|
|
1914
|
+
nodes.push(node);
|
|
1915
|
+
}
|
|
1916
|
+
});
|
|
1917
|
+
const blocks = /* @__PURE__ */ new Map();
|
|
1918
|
+
const assets = [];
|
|
1919
|
+
const diagnostics = [];
|
|
1920
|
+
let mermaidIndex = 0;
|
|
1921
|
+
let latexIndex = 0;
|
|
1922
|
+
for (const node of nodes) {
|
|
1923
|
+
if (node.type === "math" || node.type === "inlineMath") {
|
|
1924
|
+
if (latexIndex >= MAX_LATEX_FORMULAS || node.value.length > MAX_LATEX_CHARS) {
|
|
1925
|
+
diagnostics.push({
|
|
1926
|
+
code: "LATEX_LIMIT_EXCEEDED",
|
|
1927
|
+
severity: "error",
|
|
1928
|
+
message: latexIndex >= MAX_LATEX_FORMULAS ? `An article may contain at most ${MAX_LATEX_FORMULAS} LaTeX formulas.` : `LaTeX source exceeds ${MAX_LATEX_CHARS} characters.`,
|
|
1929
|
+
location: diagnosticLocation(article, node)
|
|
1930
|
+
});
|
|
1931
|
+
latexIndex += 1;
|
|
1932
|
+
continue;
|
|
1933
|
+
}
|
|
1934
|
+
try {
|
|
1935
|
+
const formula = await renderLatexAsset(article, node, latexIndex);
|
|
1936
|
+
assets.push(formula.asset);
|
|
1937
|
+
blocks.set(node, formula);
|
|
1938
|
+
} catch (error) {
|
|
1939
|
+
diagnostics.push({
|
|
1940
|
+
code: "LATEX_RENDER_FAILED",
|
|
1941
|
+
severity: "error",
|
|
1942
|
+
message: `Unable to render LaTeX formula: ${error instanceof Error ? error.message : String(error)}`,
|
|
1943
|
+
location: diagnosticLocation(article, node),
|
|
1944
|
+
hint: "Check the LaTeX math syntax and use MathJax base, AMS, or newcommand features."
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
latexIndex += 1;
|
|
1948
|
+
continue;
|
|
1949
|
+
}
|
|
1950
|
+
if (node.lang?.trim().toLocaleLowerCase() !== "mermaid") {
|
|
1951
|
+
blocks.set(
|
|
1952
|
+
node,
|
|
1953
|
+
await highlightCode(node.value, node.lang ?? void 0, codeTheme, diagnostics, article, node)
|
|
1954
|
+
);
|
|
1955
|
+
continue;
|
|
1956
|
+
}
|
|
1957
|
+
if (mermaidIndex >= MAX_MERMAID_BLOCKS || node.value.length > MAX_MERMAID_CHARS) {
|
|
1958
|
+
diagnostics.push({
|
|
1959
|
+
code: "MERMAID_LIMIT_EXCEEDED",
|
|
1960
|
+
severity: "error",
|
|
1961
|
+
message: mermaidIndex >= MAX_MERMAID_BLOCKS ? `An article may contain at most ${MAX_MERMAID_BLOCKS} Mermaid diagrams.` : `Mermaid source exceeds ${MAX_MERMAID_CHARS} characters.`,
|
|
1962
|
+
location: diagnosticLocation(article, node)
|
|
1963
|
+
});
|
|
1964
|
+
blocks.set(node, await highlightCode(node.value, "mermaid", codeTheme, diagnostics, article, node));
|
|
1965
|
+
mermaidIndex += 1;
|
|
1966
|
+
continue;
|
|
1967
|
+
}
|
|
1968
|
+
try {
|
|
1969
|
+
const asset = await renderMermaidAsset(article, node, mermaidIndex, codeTheme);
|
|
1970
|
+
assets.push(asset);
|
|
1971
|
+
blocks.set(node, {
|
|
1972
|
+
kind: "mermaid",
|
|
1973
|
+
asset,
|
|
1974
|
+
alt: asset.alt ?? "Mermaid \u56FE\u8868"
|
|
1975
|
+
});
|
|
1976
|
+
} catch (error) {
|
|
1977
|
+
diagnostics.push({
|
|
1978
|
+
code: "MERMAID_RENDER_FAILED",
|
|
1979
|
+
severity: "error",
|
|
1980
|
+
message: `Unable to render Mermaid diagram: ${error instanceof Error ? error.message : String(error)}`,
|
|
1981
|
+
location: diagnosticLocation(article, node),
|
|
1982
|
+
hint: "Check the Mermaid syntax and use a supported diagram type."
|
|
1983
|
+
});
|
|
1984
|
+
blocks.set(node, await highlightCode(node.value, "mermaid", codeTheme, diagnostics, article, node));
|
|
1985
|
+
}
|
|
1986
|
+
mermaidIndex += 1;
|
|
1987
|
+
}
|
|
1988
|
+
return { codeTheme, blocks, assets, diagnostics };
|
|
1989
|
+
}
|
|
1990
|
+
var MAX_THEME_CSS_BYTES = 256 * 1024;
|
|
1991
|
+
var presetIds = ["default", "minimal", "warm", "tech", "elegant", "green", "official"];
|
|
1992
|
+
var themeMessages = {
|
|
1993
|
+
en: {
|
|
1994
|
+
"default.name": "Classic Blue",
|
|
1995
|
+
"default.description": "Clear and composed, suited to general articles and long-form reading.",
|
|
1996
|
+
"minimal.name": "Minimal Monochrome",
|
|
1997
|
+
"minimal.description": "Restrained decoration for essays, opinions, and analytical writing.",
|
|
1998
|
+
"warm.name": "Warm Orange",
|
|
1999
|
+
"warm.description": "Warm and approachable for life, growth, and people stories.",
|
|
2000
|
+
"tech.name": "Tech Cyan",
|
|
2001
|
+
"tech.description": "High-contrast cyan and blue for technology and product analysis.",
|
|
2002
|
+
"elegant.name": "Elegant Gold",
|
|
2003
|
+
"elegant.description": "Refined and restrained for culture, books, and brand content.",
|
|
2004
|
+
"green.name": "Natural Green",
|
|
2005
|
+
"green.description": "Fresh and calm for health, nature, and sustainability.",
|
|
2006
|
+
"official.name": "Official Document",
|
|
2007
|
+
"official.description": "Formal and restrained for notices, reports, policies, and institutional writing.",
|
|
2008
|
+
"custom.description": "Project theme file {path}"
|
|
2009
|
+
},
|
|
2010
|
+
"zh-CN": {
|
|
2011
|
+
"default.name": "\u7ECF\u5178\u84DD",
|
|
2012
|
+
"default.description": "\u6E05\u6670\u7A33\u91CD\uFF0C\u9002\u5408\u901A\u7528\u6587\u7AE0\u548C\u957F\u6587\u9605\u8BFB\u3002",
|
|
2013
|
+
"minimal.name": "\u6781\u7B80\u9ED1\u767D",
|
|
2014
|
+
"minimal.description": "\u5F31\u5316\u88C5\u9970\uFF0C\u9002\u5408\u89C2\u70B9\u3001\u968F\u7B14\u548C\u8BCA\u65AD\u6392\u7248\u3002",
|
|
2015
|
+
"warm.name": "\u6696\u6A59\u4EBA\u6587",
|
|
2016
|
+
"warm.description": "\u6E29\u6696\u4EB2\u548C\uFF0C\u9002\u5408\u751F\u6D3B\u3001\u6210\u957F\u548C\u4EBA\u7269\u6545\u4E8B\u3002",
|
|
2017
|
+
"tech.name": "\u79D1\u6280\u9752",
|
|
2018
|
+
"tech.description": "\u9AD8\u5BF9\u6BD4\u7684\u9752\u84DD\u8272\u8C03\uFF0C\u9002\u5408\u6280\u672F\u6587\u7AE0\u548C\u4EA7\u54C1\u89E3\u6790\u3002",
|
|
2019
|
+
"elegant.name": "\u96C5\u81F4\u91D1\u68D5",
|
|
2020
|
+
"elegant.description": "\u514B\u5236\u5178\u96C5\uFF0C\u9002\u5408\u6587\u5316\u3001\u8BFB\u4E66\u548C\u54C1\u724C\u5185\u5BB9\u3002",
|
|
2021
|
+
"green.name": "\u81EA\u7136\u7EFF",
|
|
2022
|
+
"green.description": "\u6E05\u723D\u5E73\u548C\uFF0C\u9002\u5408\u5065\u5EB7\u3001\u81EA\u7136\u548C\u53EF\u6301\u7EED\u4E3B\u9898\u3002",
|
|
2023
|
+
"official.name": "\u516C\u6587\u7EA2",
|
|
2024
|
+
"official.description": "\u5E84\u91CD\u514B\u5236\uFF0C\u9002\u5408\u901A\u77E5\u3001\u62A5\u544A\u3001\u653F\u7B56\u89E3\u8BFB\u548C\u673A\u6784\u6587\u7AE0\u3002",
|
|
2025
|
+
"custom.description": "\u9879\u76EE\u4E3B\u9898\u6587\u4EF6 {path}"
|
|
2026
|
+
}
|
|
2027
|
+
};
|
|
2028
|
+
var presetIdSet = new Set(presetIds);
|
|
2029
|
+
var inlineOptions = {
|
|
2030
|
+
applyAttributesTableElements: false,
|
|
2031
|
+
applyHeightAttributes: false,
|
|
2032
|
+
applyStyleTags: false,
|
|
2033
|
+
applyWidthAttributes: false,
|
|
2034
|
+
preserveFontFaces: false,
|
|
2035
|
+
preserveImportant: false,
|
|
2036
|
+
preserveKeyFrames: false,
|
|
2037
|
+
preserveMediaQueries: false,
|
|
2038
|
+
preservePseudos: false,
|
|
2039
|
+
removeStyleTags: true,
|
|
2040
|
+
resolveCSSVariables: true,
|
|
2041
|
+
xmlMode: false
|
|
2042
|
+
};
|
|
2043
|
+
function themeError(message, details) {
|
|
2044
|
+
return new FaFaError("CONFIG_INVALID", message, details);
|
|
2045
|
+
}
|
|
2046
|
+
function themeAssetPath(filename) {
|
|
2047
|
+
const packagedThemesDirectory = process.env.FAFA_INTERNAL_THEMES_DIR;
|
|
2048
|
+
if (packagedThemesDirectory) {
|
|
2049
|
+
if (!isAbsolute3(packagedThemesDirectory)) {
|
|
2050
|
+
throw themeError("FAFA_INTERNAL_THEMES_DIR must be an absolute path");
|
|
2051
|
+
}
|
|
2052
|
+
return resolve5(packagedThemesDirectory, filename);
|
|
2053
|
+
}
|
|
2054
|
+
return fileURLToPath(new URL(`../themes/${filename}`, import.meta.url));
|
|
2055
|
+
}
|
|
2056
|
+
async function readCss(path, reference) {
|
|
2057
|
+
let css;
|
|
2058
|
+
try {
|
|
2059
|
+
if (!(await stat4(path)).isFile()) throw themeError(`Theme path is not a file: ${reference}`);
|
|
2060
|
+
css = await readFile6(path, "utf8");
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
if (error instanceof FaFaError) throw error;
|
|
2063
|
+
if (error.code === "ENOENT") {
|
|
2064
|
+
throw themeError(`Theme file does not exist: ${reference}`);
|
|
2065
|
+
}
|
|
2066
|
+
throw error;
|
|
2067
|
+
}
|
|
2068
|
+
if (Buffer.byteLength(css, "utf8") > MAX_THEME_CSS_BYTES) {
|
|
2069
|
+
throw themeError(`Theme file exceeds ${MAX_THEME_CSS_BYTES} bytes: ${reference}`);
|
|
2070
|
+
}
|
|
2071
|
+
return css;
|
|
2072
|
+
}
|
|
2073
|
+
function validateThemeCss(css, reference) {
|
|
2074
|
+
const forbidden = [
|
|
2075
|
+
[/@import\b/i, "@import is not allowed"],
|
|
2076
|
+
[/@(?:font-face|keyframes|media|supports|container|layer)\b/i, "CSS at-rules cannot be inlined"],
|
|
2077
|
+
[/url\s*\(/i, "url() is not allowed"],
|
|
2078
|
+
[/expression\s*\(/i, "CSS expressions are not allowed"],
|
|
2079
|
+
[/(?:javascript|data)\s*:/i, "executable or embedded URLs are not allowed"],
|
|
2080
|
+
[/(?:behavior|-moz-binding)\s*:/i, "browser behavior bindings are not allowed"],
|
|
2081
|
+
[/position\s*:\s*(?:fixed|absolute|sticky)/i, "unsupported positioning is not allowed"],
|
|
2082
|
+
[/display\s*:\s*grid/i, "CSS grid is not supported by the WeChat target"]
|
|
2083
|
+
];
|
|
2084
|
+
for (const [pattern, message] of forbidden) {
|
|
2085
|
+
if (pattern.test(css)) throw themeError(`Invalid theme CSS ${reference}: ${message}`);
|
|
2086
|
+
}
|
|
2087
|
+
try {
|
|
2088
|
+
juice.inlineContent(
|
|
2089
|
+
'<section class="fafa-article"><p class="fafa-paragraph"><span leaf="">test</span></p></section>',
|
|
2090
|
+
css,
|
|
2091
|
+
inlineOptions
|
|
2092
|
+
);
|
|
2093
|
+
} catch (error) {
|
|
2094
|
+
throw themeError(`Unable to parse theme CSS: ${reference}`, {
|
|
2095
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
async function baseCss() {
|
|
2100
|
+
return readCss(themeAssetPath("base.css"), "base.css");
|
|
2101
|
+
}
|
|
2102
|
+
function listWechatThemePresets(locale = "zh-CN") {
|
|
2103
|
+
const t = createTranslator(locale, themeMessages);
|
|
2104
|
+
return presetIds.map((id) => ({
|
|
2105
|
+
id,
|
|
2106
|
+
name: t(`${id}.name`),
|
|
2107
|
+
description: t(`${id}.description`)
|
|
2108
|
+
}));
|
|
2109
|
+
}
|
|
2110
|
+
async function resolveWechatTheme(projectRoot, reference, locale = "zh-CN") {
|
|
2111
|
+
const base = await baseCss();
|
|
2112
|
+
if (presetIdSet.has(reference)) {
|
|
2113
|
+
const metadata = listWechatThemePresets(locale).find(({ id }) => id === reference);
|
|
2114
|
+
if (!metadata) throw themeError(`Unknown built-in WeChat theme: ${reference}`);
|
|
2115
|
+
const preset = await readCss(themeAssetPath(`${reference}.css`), reference);
|
|
2116
|
+
const css = `${base}
|
|
2117
|
+
${preset}`;
|
|
2118
|
+
validateThemeCss(css, reference);
|
|
2119
|
+
return { ...metadata, source: "preset", reference, css };
|
|
2120
|
+
}
|
|
2121
|
+
const root = resolve5(projectRoot);
|
|
2122
|
+
const path = isAbsolute3(reference) ? resolve5(reference) : resolve5(root, reference);
|
|
2123
|
+
const normalizedRoot = `${root}${sep3}`;
|
|
2124
|
+
if (path !== root && !path.startsWith(normalizedRoot)) {
|
|
2125
|
+
throw themeError(`Theme file escapes project root: ${reference}`);
|
|
2126
|
+
}
|
|
2127
|
+
if (extname4(path).toLowerCase() !== ".css") {
|
|
2128
|
+
throw themeError(`Theme file must use .css: ${reference}`);
|
|
2129
|
+
}
|
|
2130
|
+
const custom = await readCss(path, reference);
|
|
2131
|
+
validateThemeCss(custom, reference);
|
|
2132
|
+
const relativePath = relative4(root, path).split(sep3).join("/");
|
|
2133
|
+
const t = createTranslator(locale, themeMessages);
|
|
2134
|
+
return {
|
|
2135
|
+
id: `file:${relativePath}`,
|
|
2136
|
+
name: basename5(relativePath, extname4(relativePath)),
|
|
2137
|
+
description: t("custom.description", { path: relativePath }),
|
|
2138
|
+
source: "file",
|
|
2139
|
+
reference: relativePath,
|
|
2140
|
+
css: `${base}
|
|
2141
|
+
${custom}`
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
function inlineWechatTheme(html, theme) {
|
|
2145
|
+
let inlined;
|
|
2146
|
+
try {
|
|
2147
|
+
inlined = juice.inlineContent(html, theme.css, inlineOptions);
|
|
2148
|
+
} catch (error) {
|
|
2149
|
+
throw themeError(`Unable to inline theme CSS: ${theme.reference}`, {
|
|
2150
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2151
|
+
});
|
|
2152
|
+
}
|
|
2153
|
+
return inlined.replaceAll(/\sclass=(?:"[^"]*"|'[^']*')/g, "").replaceAll(/<span\s+leaf(?=[\s>])/g, '<span leaf=""');
|
|
2154
|
+
}
|
|
2155
|
+
var RENDERER_VERSION = "wechat-v5";
|
|
2156
|
+
var imageCaptionMessages = {
|
|
2157
|
+
en: {
|
|
2158
|
+
"title-first.name": "title first",
|
|
2159
|
+
"title-first.description": "Use the image title, falling back to alt text.",
|
|
2160
|
+
"alt-first.name": "alt first",
|
|
2161
|
+
"alt-first.description": "Use the image alt text, falling back to the title.",
|
|
2162
|
+
"title-only.name": "title only",
|
|
2163
|
+
"title-only.description": "Show only the Markdown image title.",
|
|
2164
|
+
"alt-only.name": "alt only",
|
|
2165
|
+
"alt-only.description": "Show only the Markdown image alt text.",
|
|
2166
|
+
"filename.name": "Filename",
|
|
2167
|
+
"filename.description": "Show the filename from the image URL or local path.",
|
|
2168
|
+
"none.name": "Hidden",
|
|
2169
|
+
"none.description": "Do not generate image captions."
|
|
2170
|
+
},
|
|
2171
|
+
"zh-CN": {
|
|
2172
|
+
"title-first.name": "title \u4F18\u5148",
|
|
2173
|
+
"title-first.description": "\u4F18\u5148\u4F7F\u7528\u56FE\u7247 title\uFF0C\u7F3A\u5931\u65F6\u4F7F\u7528 alt\u3002",
|
|
2174
|
+
"alt-first.name": "alt \u4F18\u5148",
|
|
2175
|
+
"alt-first.description": "\u4F18\u5148\u4F7F\u7528\u56FE\u7247 alt\uFF0C\u7F3A\u5931\u65F6\u4F7F\u7528 title\u3002",
|
|
2176
|
+
"title-only.name": "\u4EC5 title",
|
|
2177
|
+
"title-only.description": "\u53EA\u663E\u793A Markdown \u56FE\u7247 title\u3002",
|
|
2178
|
+
"alt-only.name": "\u4EC5 alt",
|
|
2179
|
+
"alt-only.description": "\u53EA\u663E\u793A Markdown \u56FE\u7247 alt\u3002",
|
|
2180
|
+
"filename.name": "\u6587\u4EF6\u540D",
|
|
2181
|
+
"filename.description": "\u663E\u793A\u56FE\u7247 URL \u6216\u672C\u5730\u8DEF\u5F84\u4E2D\u7684\u6587\u4EF6\u540D\u3002",
|
|
2182
|
+
"none.name": "\u4E0D\u663E\u793A",
|
|
2183
|
+
"none.description": "\u4E0D\u751F\u6210\u56FE\u7247\u56FE\u6CE8\u3002"
|
|
2184
|
+
}
|
|
2185
|
+
};
|
|
2186
|
+
function escapeHtml2(value) {
|
|
2187
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
2188
|
+
}
|
|
2189
|
+
function leaf(value) {
|
|
2190
|
+
return `<span leaf="">${escapeHtml2(value)}</span>`;
|
|
2191
|
+
}
|
|
2192
|
+
function sourceLocation(node, context) {
|
|
2193
|
+
if (!context.includeSourceLocations) return "";
|
|
2194
|
+
const line = node.position?.start.line;
|
|
2195
|
+
return line ? ` data-fafa-line="${line + context.sourceLineOffset}"` : "";
|
|
2196
|
+
}
|
|
2197
|
+
function children(node, context) {
|
|
2198
|
+
if (!("children" in node)) return "";
|
|
2199
|
+
return node.children.map((child) => renderNode(child, context)).join("");
|
|
2200
|
+
}
|
|
2201
|
+
function safeLink(url) {
|
|
2202
|
+
try {
|
|
2203
|
+
const parsed = new URL(url);
|
|
2204
|
+
return parsed.protocol === "https:" ? parsed.toString() : void 0;
|
|
2205
|
+
} catch {
|
|
2206
|
+
return void 0;
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
function nonEmpty(value) {
|
|
2210
|
+
const normalized = value?.trim();
|
|
2211
|
+
return normalized || void 0;
|
|
2212
|
+
}
|
|
2213
|
+
function assetFilename(asset) {
|
|
2214
|
+
const source = asset?.source.startsWith("mermaid:") ? asset.filename : asset?.source;
|
|
2215
|
+
if (!source) return void 0;
|
|
2216
|
+
let path = source;
|
|
2217
|
+
try {
|
|
2218
|
+
if (/^https:\/\//i.test(source)) path = new URL(source).pathname;
|
|
2219
|
+
} catch {
|
|
2220
|
+
return void 0;
|
|
2221
|
+
}
|
|
2222
|
+
const clean = path.split(/[?#]/, 1)[0] ?? path;
|
|
2223
|
+
const name = clean.split(/[\\/]/).at(-1);
|
|
2224
|
+
if (!name) return void 0;
|
|
2225
|
+
try {
|
|
2226
|
+
return decodeURIComponent(name);
|
|
2227
|
+
} catch {
|
|
2228
|
+
return name;
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
function imageCaption(mode, title, alt, asset) {
|
|
2232
|
+
const normalizedTitle = nonEmpty(title);
|
|
2233
|
+
const normalizedAlt = nonEmpty(alt);
|
|
2234
|
+
if (mode === "title-first") return normalizedTitle ?? normalizedAlt;
|
|
2235
|
+
if (mode === "alt-first") return normalizedAlt ?? normalizedTitle;
|
|
2236
|
+
if (mode === "title-only") return normalizedTitle;
|
|
2237
|
+
if (mode === "alt-only") return normalizedAlt;
|
|
2238
|
+
if (mode === "filename") return assetFilename(asset);
|
|
2239
|
+
return void 0;
|
|
2240
|
+
}
|
|
2241
|
+
function renderImage(url, alt, title, asset, className, location2, context, allowCaption) {
|
|
2242
|
+
const normalizedTitle = nonEmpty(title);
|
|
2243
|
+
const titleAttribute = normalizedTitle ? ` title="${escapeHtml2(normalizedTitle)}"` : "";
|
|
2244
|
+
const caption = allowCaption ? imageCaption(context.imageCaption, title, alt, asset) : void 0;
|
|
2245
|
+
const image = `<img class="${className}"${caption ? "" : location2} src="${escapeHtml2(url)}" alt="${escapeHtml2(alt ?? "")}"${titleAttribute}>`;
|
|
2246
|
+
return caption ? `<section class="fafa-image-figure"${location2}>${image}<p class="fafa-image-caption">${leaf(caption)}</p></section>` : image;
|
|
2247
|
+
}
|
|
2248
|
+
function renderMarkdownImage(image, context, location2, allowCaption) {
|
|
2249
|
+
const id = image.url.startsWith("asset://") ? image.url.slice("asset://".length) : image.url;
|
|
2250
|
+
const url = context.assetUrls.get(id) ?? `asset://${id}`;
|
|
2251
|
+
return renderImage(
|
|
2252
|
+
url,
|
|
2253
|
+
image.alt,
|
|
2254
|
+
image.title,
|
|
2255
|
+
context.assets.get(id),
|
|
2256
|
+
"fafa-image",
|
|
2257
|
+
location2,
|
|
2258
|
+
context,
|
|
2259
|
+
allowCaption
|
|
2260
|
+
);
|
|
2261
|
+
}
|
|
2262
|
+
function tokenStyle(token) {
|
|
2263
|
+
const declarations = [];
|
|
2264
|
+
if (token.color) declarations.push(`color: ${token.color}`);
|
|
2265
|
+
if (token.backgroundColor) declarations.push(`background-color: ${token.backgroundColor}`);
|
|
2266
|
+
if (token.fontStyle !== void 0) {
|
|
2267
|
+
if (token.fontStyle & 1) declarations.push("font-style: italic");
|
|
2268
|
+
if (token.fontStyle & 2) declarations.push("font-weight: 700");
|
|
2269
|
+
const decorations = [
|
|
2270
|
+
...token.fontStyle & 4 ? ["underline"] : [],
|
|
2271
|
+
...token.fontStyle & 8 ? ["line-through"] : []
|
|
2272
|
+
];
|
|
2273
|
+
if (decorations.length) declarations.push(`text-decoration: ${decorations.join(" ")}`);
|
|
2274
|
+
}
|
|
2275
|
+
return declarations.length ? ` style="${escapeHtml2(declarations.join("; "))}"` : "";
|
|
2276
|
+
}
|
|
2277
|
+
function renderCodeBlock(block, location2) {
|
|
2278
|
+
const language = block.language ? `<p class="fafa-code-language">${leaf(block.language)}</p>` : "";
|
|
2279
|
+
const lines = block.lines.map((line) => {
|
|
2280
|
+
const content = line.map(
|
|
2281
|
+
(token) => `<span leaf=""${tokenStyle(token)}>${escapeHtml2(token.content)}</span>`
|
|
2282
|
+
);
|
|
2283
|
+
return `<p class="fafa-code-line">${content.join("") || leaf(" ")}</p>`;
|
|
2284
|
+
});
|
|
2285
|
+
const style = `background-color: ${block.background}; color: ${block.foreground}`;
|
|
2286
|
+
return `<section class="fafa-code-block"${location2} style="${escapeHtml2(style)}">${language}${lines.join("")}</section>`;
|
|
2287
|
+
}
|
|
2288
|
+
function formulaNumber(value) {
|
|
2289
|
+
return Number(value.toFixed(3)).toString();
|
|
2290
|
+
}
|
|
2291
|
+
function renderFormula(formula, location2, context) {
|
|
2292
|
+
const url = context.assetUrls.get(formula.asset.id) ?? `asset://${formula.asset.id}`;
|
|
2293
|
+
const size = `width: ${formulaNumber(Math.max(0, formula.width))}px; height: auto; max-width: 100%`;
|
|
2294
|
+
const style = formula.display ? `${size}; display: inline-block` : `${size}; display: inline-block; vertical-align: ${formulaNumber(formula.verticalAlign)}em`;
|
|
2295
|
+
const image = `<img class="fafa-math fafa-math-${formula.display ? "display" : "inline"}"${formula.display ? "" : location2} src="${escapeHtml2(url)}" alt="${escapeHtml2(formula.asset.alt ?? "LaTeX formula")}" style="${escapeHtml2(style)}">`;
|
|
2296
|
+
return formula.display ? `<section class="fafa-math-block"${location2}>${image}</section>` : image;
|
|
2297
|
+
}
|
|
2298
|
+
function renderNode(node, context) {
|
|
2299
|
+
const location2 = sourceLocation(node, context);
|
|
2300
|
+
switch (node.type) {
|
|
2301
|
+
case "root":
|
|
2302
|
+
return children(node, context);
|
|
2303
|
+
case "text":
|
|
2304
|
+
return leaf(node.value);
|
|
2305
|
+
case "paragraph":
|
|
2306
|
+
if (node.children.length === 1 && node.children[0]?.type === "image") {
|
|
2307
|
+
return renderMarkdownImage(node.children[0], context, location2, true);
|
|
2308
|
+
}
|
|
2309
|
+
return `<p class="fafa-paragraph"${location2}>${children(node, context)}</p>`;
|
|
2310
|
+
case "heading": {
|
|
2311
|
+
const depth = node.depth;
|
|
2312
|
+
return `<h${depth} class="fafa-heading fafa-heading-${depth}"${location2}>${children(node, context)}</h${depth}>`;
|
|
2313
|
+
}
|
|
2314
|
+
case "strong":
|
|
2315
|
+
return `<strong class="fafa-strong">${children(node, context)}</strong>`;
|
|
2316
|
+
case "emphasis":
|
|
2317
|
+
return `<em class="fafa-emphasis">${children(node, context)}</em>`;
|
|
2318
|
+
case "delete":
|
|
2319
|
+
return `<span class="fafa-delete">${children(node, context)}</span>`;
|
|
2320
|
+
case "inlineCode":
|
|
2321
|
+
return `<code class="fafa-inline-code">${leaf(node.value)}</code>`;
|
|
2322
|
+
case "inlineMath": {
|
|
2323
|
+
const prepared = context.preparation.blocks.get(node);
|
|
2324
|
+
return prepared?.kind === "math" ? renderFormula(prepared, location2, context) : `<code class="fafa-inline-code"${location2}>${leaf(`$${node.value}$`)}</code>`;
|
|
2325
|
+
}
|
|
2326
|
+
case "math": {
|
|
2327
|
+
const prepared = context.preparation.blocks.get(node);
|
|
2328
|
+
return prepared?.kind === "math" ? renderFormula(prepared, location2, context) : `<p class="fafa-paragraph"${location2}>${leaf(`$$${node.value}$$`)}</p>`;
|
|
2329
|
+
}
|
|
2330
|
+
case "code": {
|
|
2331
|
+
const prepared = context.preparation.blocks.get(node);
|
|
2332
|
+
if (prepared?.kind === "mermaid") {
|
|
2333
|
+
const url = context.assetUrls.get(prepared.asset.id) ?? `asset://${prepared.asset.id}`;
|
|
2334
|
+
return renderImage(
|
|
2335
|
+
url,
|
|
2336
|
+
prepared.alt,
|
|
2337
|
+
void 0,
|
|
2338
|
+
prepared.asset,
|
|
2339
|
+
"fafa-image fafa-diagram",
|
|
2340
|
+
location2,
|
|
2341
|
+
context,
|
|
2342
|
+
true
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
if (prepared?.kind === "code") return renderCodeBlock(prepared, location2);
|
|
2346
|
+
return renderCodeBlock(
|
|
2347
|
+
{
|
|
2348
|
+
kind: "code",
|
|
2349
|
+
...node.lang ? { language: node.lang } : {},
|
|
2350
|
+
lines: node.value.split("\n").map((line) => [{ content: line || " " }]),
|
|
2351
|
+
foreground: "#24292f",
|
|
2352
|
+
background: "#f6f8fa"
|
|
2353
|
+
},
|
|
2354
|
+
location2
|
|
2355
|
+
);
|
|
2356
|
+
}
|
|
2357
|
+
case "blockquote":
|
|
2358
|
+
return `<section class="fafa-quote"${location2}>${children(node, context)}</section>`;
|
|
2359
|
+
case "list": {
|
|
2360
|
+
const ordered = Boolean(node.ordered);
|
|
2361
|
+
const tag = ordered ? "ol" : "ul";
|
|
2362
|
+
return `<${tag} class="fafa-list"${location2}>${children(node, context)}</${tag}>`;
|
|
2363
|
+
}
|
|
2364
|
+
case "listItem":
|
|
2365
|
+
return `<li class="fafa-list-item"${location2}>${children(node, context)}</li>`;
|
|
2366
|
+
case "link": {
|
|
2367
|
+
const url = safeLink(node.url);
|
|
2368
|
+
return url ? `<a class="fafa-link" href="${escapeHtml2(url)}">${children(node, context)}</a>` : children(node, context);
|
|
2369
|
+
}
|
|
2370
|
+
case "image":
|
|
2371
|
+
return renderMarkdownImage(node, context, location2, false);
|
|
2372
|
+
case "thematicBreak":
|
|
2373
|
+
return `<hr class="fafa-divider"${location2}>`;
|
|
2374
|
+
case "break":
|
|
2375
|
+
return "<br>";
|
|
2376
|
+
case "table":
|
|
2377
|
+
return `<table class="fafa-table"${location2}><tbody>${children(node, context)}</tbody></table>`;
|
|
2378
|
+
case "tableRow":
|
|
2379
|
+
return `<tr${location2}>${children(node, context)}</tr>`;
|
|
2380
|
+
case "tableCell":
|
|
2381
|
+
return `<td class="fafa-table-cell"${location2}>${children(node, context)}</td>`;
|
|
2382
|
+
case "html":
|
|
2383
|
+
return leaf(node.value);
|
|
2384
|
+
default:
|
|
2385
|
+
return children(node, context);
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
function validateWechatHtml(html, final = false) {
|
|
2389
|
+
const diagnostics = [];
|
|
2390
|
+
const forbidden = [
|
|
2391
|
+
[/<style[\s>]/i, "WECHAT_STYLE_TAG", "<style> is not allowed; use inline styles."],
|
|
2392
|
+
[/<script[\s>]/i, "WECHAT_SCRIPT_TAG", "<script> is not allowed."],
|
|
2393
|
+
[/<\/?div[\s>]/i, "WECHAT_DIV_TAG", "<div> is not allowed; use semantic elements."],
|
|
2394
|
+
[/\sclass\s*=/i, "WECHAT_CLASS_ATTRIBUTE", "class attributes are not allowed."],
|
|
2395
|
+
[/\sid\s*=/i, "WECHAT_ID_ATTRIBUTE", "id attributes are not allowed."],
|
|
2396
|
+
[/position\s*:\s*(fixed|absolute|sticky)/i, "WECHAT_POSITION", "Unsupported position style."],
|
|
2397
|
+
[/display\s*:\s*grid/i, "WECHAT_GRID", "CSS grid is not supported."],
|
|
2398
|
+
[/var\s*\(\s*--/i, "WECHAT_CSS_VARIABLE", "CSS variables are not supported."]
|
|
2399
|
+
];
|
|
2400
|
+
for (const [pattern, code, message] of forbidden) {
|
|
2401
|
+
if (pattern.test(html)) diagnostics.push({ code, severity: "error", message });
|
|
2402
|
+
}
|
|
2403
|
+
if (!/<span\s+leaf="">/i.test(html)) {
|
|
2404
|
+
diagnostics.push({
|
|
2405
|
+
code: "WECHAT_LEAF_MISSING",
|
|
2406
|
+
severity: "error",
|
|
2407
|
+
message: 'Rendered text must be wrapped in <span leaf="">.'
|
|
2408
|
+
});
|
|
2409
|
+
}
|
|
2410
|
+
if (final && /(?:asset|file):\/\//i.test(html)) {
|
|
2411
|
+
diagnostics.push({
|
|
2412
|
+
code: "WECHAT_UNRESOLVED_ASSET",
|
|
2413
|
+
severity: "error",
|
|
2414
|
+
message: "Final HTML contains an unresolved local asset."
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
if (final && /src="data:/i.test(html)) {
|
|
2418
|
+
diagnostics.push({
|
|
2419
|
+
code: "WECHAT_DATA_URL",
|
|
2420
|
+
severity: "error",
|
|
2421
|
+
message: "Final HTML contains a preview-only data URL."
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
return diagnostics;
|
|
2425
|
+
}
|
|
2426
|
+
function stableHash(article, metadata, assets, theme, preparation, assetHashes) {
|
|
2427
|
+
return createHash22("sha256").update(
|
|
2428
|
+
JSON.stringify({
|
|
2429
|
+
renderer: RENDERER_VERSION,
|
|
2430
|
+
markdown: article.manuscript.markdown,
|
|
2431
|
+
frontmatter: article.manuscript.frontmatter,
|
|
2432
|
+
metadata,
|
|
2433
|
+
theme: { id: theme.id, css: theme.css },
|
|
2434
|
+
codeTheme: preparation.codeTheme.id,
|
|
2435
|
+
assets: assets.map((asset) => ({
|
|
2436
|
+
id: asset.id,
|
|
2437
|
+
source: asset.source,
|
|
2438
|
+
hash: assetHashes.get(asset.id)
|
|
2439
|
+
})),
|
|
2440
|
+
assetHashes: [...assetHashes.entries()].sort(([left], [right]) => left.localeCompare(right))
|
|
2441
|
+
})
|
|
2442
|
+
).digest("hex");
|
|
2443
|
+
}
|
|
2444
|
+
function listImageCaptionModes(locale = "zh-CN") {
|
|
2445
|
+
const t = createTranslator(locale, imageCaptionMessages);
|
|
2446
|
+
return IMAGE_CAPTION_MODES.map((id) => ({
|
|
2447
|
+
id,
|
|
2448
|
+
name: t(`${id}.name`),
|
|
2449
|
+
description: t(`${id}.description`)
|
|
2450
|
+
}));
|
|
2451
|
+
}
|
|
2452
|
+
function resolveImageCaptionMode(reference) {
|
|
2453
|
+
const id = reference.trim();
|
|
2454
|
+
if (!IMAGE_CAPTION_MODES.includes(id)) {
|
|
2455
|
+
throw new FaFaError("CONFIG_INVALID", `Unknown image caption mode: ${reference}`);
|
|
2456
|
+
}
|
|
2457
|
+
return id;
|
|
2458
|
+
}
|
|
2459
|
+
async function renderWechatArticle(article, metadata, options) {
|
|
2460
|
+
const {
|
|
2461
|
+
theme,
|
|
2462
|
+
assetUrls = /* @__PURE__ */ new Map(),
|
|
2463
|
+
final = false,
|
|
2464
|
+
assetHashes = /* @__PURE__ */ new Map(),
|
|
2465
|
+
includeSourceLocations = false
|
|
2466
|
+
} = options;
|
|
2467
|
+
const preparation = options.preparation ?? await prepareWechatRichContent(article, metadata.codeTheme ?? "github-light");
|
|
2468
|
+
const assets = options.assets ?? [...article.assets, ...preparation.assets];
|
|
2469
|
+
const imageCaptionMode = resolveImageCaptionMode(metadata.imageCaption ?? "none");
|
|
2470
|
+
const body = renderNode(article.tree, {
|
|
2471
|
+
assetUrls,
|
|
2472
|
+
assets: new Map(assets.map((asset) => [asset.id, asset])),
|
|
2473
|
+
imageCaption: imageCaptionMode,
|
|
2474
|
+
includeSourceLocations,
|
|
2475
|
+
sourceLineOffset: article.sourceLineOffset,
|
|
2476
|
+
preparation
|
|
2477
|
+
});
|
|
2478
|
+
const html = inlineWechatTheme(`<section class="fafa-article">${body}</section>`, theme);
|
|
2479
|
+
const diagnostics = [
|
|
2480
|
+
...article.diagnostics,
|
|
2481
|
+
...preparation.diagnostics,
|
|
2482
|
+
...validateWechatHtml(html, final)
|
|
2483
|
+
];
|
|
2484
|
+
for (const asset of assets) {
|
|
2485
|
+
if (asset.purpose !== "inline") continue;
|
|
2486
|
+
if (!assetUrls.has(asset.id)) {
|
|
2487
|
+
diagnostics.push({
|
|
2488
|
+
code: "ASSET_URL_MISSING",
|
|
2489
|
+
severity: final ? "error" : "warning",
|
|
2490
|
+
message: `No rendered URL was provided for ${asset.source}.`
|
|
2491
|
+
});
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
return {
|
|
2495
|
+
articleId: article.manuscript.id,
|
|
2496
|
+
platform: "wechat",
|
|
2497
|
+
html,
|
|
2498
|
+
buildHash: stableHash(article, metadata, assets, theme, preparation, assetHashes),
|
|
2499
|
+
assets,
|
|
2500
|
+
diagnostics,
|
|
2501
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
function wrapWechatPreview(title, body) {
|
|
2505
|
+
return `<!doctype html>
|
|
2506
|
+
<html lang="zh-CN">
|
|
2507
|
+
<head>
|
|
2508
|
+
<meta charset="utf-8">
|
|
2509
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2510
|
+
<title>${escapeHtml2(title)}</title>
|
|
2511
|
+
<style>body{margin:0;background:#f3f4f6;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.shell{max-width:430px;margin:24px auto;padding:24px;background:#fff;box-shadow:0 8px 32px rgba(0,0,0,.08)}@media(max-width:480px){.shell{margin:0;padding:20px;box-shadow:none}}</style>
|
|
2512
|
+
</head>
|
|
2513
|
+
<body><main class="shell">${body}</main></body>
|
|
2514
|
+
</html>`;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
// ../../packages/wechat-adapter/dist/index.js
|
|
2518
|
+
import { mkdir as mkdir4, readFile as readFile7, rename as rename5, writeFile as writeFile5 } from "fs/promises";
|
|
2519
|
+
import { dirname as dirname4, join as join5 } from "path";
|
|
2520
|
+
|
|
2521
|
+
// ../../packages/wechat-client/dist/index.js
|
|
2522
|
+
var WechatApiError = class extends Error {
|
|
2523
|
+
action;
|
|
2524
|
+
errcode;
|
|
2525
|
+
errmsg;
|
|
2526
|
+
status;
|
|
2527
|
+
constructor(message, details = {}) {
|
|
2528
|
+
super(message);
|
|
2529
|
+
this.name = "WechatApiError";
|
|
2530
|
+
this.action = details.action;
|
|
2531
|
+
this.errcode = details.errcode;
|
|
2532
|
+
this.errmsg = details.errmsg;
|
|
2533
|
+
this.status = details.status;
|
|
2534
|
+
}
|
|
2535
|
+
};
|
|
2536
|
+
var API_ORIGIN = "https://api.weixin.qq.com";
|
|
2537
|
+
var TOKEN_SAFETY_WINDOW_MS = 5 * 60 * 1e3;
|
|
2538
|
+
function apiError(action, response, status) {
|
|
2539
|
+
return new WechatApiError(
|
|
2540
|
+
`WeChat ${action} failed${response.errcode === void 0 ? "" : ` (${response.errcode})`}: ${response.errmsg ?? "unknown error"}`,
|
|
2541
|
+
{
|
|
2542
|
+
action,
|
|
2543
|
+
...response.errcode === void 0 ? {} : { errcode: response.errcode },
|
|
2544
|
+
...response.errmsg === void 0 ? {} : { errmsg: response.errmsg },
|
|
2545
|
+
...status === void 0 ? {} : { status }
|
|
2546
|
+
}
|
|
2547
|
+
);
|
|
2548
|
+
}
|
|
2549
|
+
function assertWechatSuccess(action, response) {
|
|
2550
|
+
if (response.errcode !== void 0 && response.errcode !== 0) throw apiError(action, response);
|
|
2551
|
+
}
|
|
2552
|
+
function normalizeWechatImageUrl(value) {
|
|
2553
|
+
let url;
|
|
2554
|
+
try {
|
|
2555
|
+
url = new URL(value);
|
|
2556
|
+
} catch {
|
|
2557
|
+
throw new WechatApiError("WeChat image upload returned an invalid URL", {
|
|
2558
|
+
action: "image upload"
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
if (url.protocol === "http:") url.protocol = "https:";
|
|
2562
|
+
if (url.protocol !== "https:") {
|
|
2563
|
+
throw new WechatApiError("WeChat image upload returned an unsafe URL", {
|
|
2564
|
+
action: "image upload"
|
|
2565
|
+
});
|
|
2566
|
+
}
|
|
2567
|
+
return url.toString();
|
|
2568
|
+
}
|
|
2569
|
+
async function readJson(response, action) {
|
|
2570
|
+
let result2;
|
|
2571
|
+
try {
|
|
2572
|
+
result2 = await response.json();
|
|
2573
|
+
} catch {
|
|
2574
|
+
throw new WechatApiError(`WeChat ${action} returned invalid JSON`, {
|
|
2575
|
+
action,
|
|
2576
|
+
status: response.status
|
|
2577
|
+
});
|
|
2578
|
+
}
|
|
2579
|
+
if (!response.ok) {
|
|
2580
|
+
throw apiError(action, result2, response.status);
|
|
2581
|
+
}
|
|
2582
|
+
return result2;
|
|
2583
|
+
}
|
|
2584
|
+
var WechatOfficialAccountClient = class {
|
|
2585
|
+
constructor(tokenStore, fetcher = fetch) {
|
|
2586
|
+
this.tokenStore = tokenStore;
|
|
2587
|
+
this.fetcher = fetcher;
|
|
2588
|
+
}
|
|
2589
|
+
tokenStore;
|
|
2590
|
+
fetcher;
|
|
2591
|
+
async token(credential) {
|
|
2592
|
+
const cached = await this.tokenStore.get(credential.appId);
|
|
2593
|
+
if (cached && cached.expiresAt - TOKEN_SAFETY_WINDOW_MS > Date.now()) return cached.accessToken;
|
|
2594
|
+
const url = new URL("/cgi-bin/token", API_ORIGIN);
|
|
2595
|
+
url.searchParams.set("grant_type", "client_credential");
|
|
2596
|
+
url.searchParams.set("appid", credential.appId);
|
|
2597
|
+
url.searchParams.set("secret", credential.appSecret);
|
|
2598
|
+
const result2 = await readJson(await this.fetcher(url), "access token");
|
|
2599
|
+
assertWechatSuccess("access token", result2);
|
|
2600
|
+
if (!result2.access_token || !result2.expires_in) {
|
|
2601
|
+
throw new WechatApiError("WeChat access token response is incomplete", {
|
|
2602
|
+
action: "access token"
|
|
2603
|
+
});
|
|
2604
|
+
}
|
|
2605
|
+
await this.tokenStore.set(credential.appId, {
|
|
2606
|
+
accessToken: result2.access_token,
|
|
2607
|
+
expiresAt: Date.now() + result2.expires_in * 1e3
|
|
2608
|
+
});
|
|
2609
|
+
return result2.access_token;
|
|
2610
|
+
}
|
|
2611
|
+
async endpoint(path, credential) {
|
|
2612
|
+
const url = new URL(path, API_ORIGIN);
|
|
2613
|
+
url.searchParams.set("access_token", await this.token(credential));
|
|
2614
|
+
return url;
|
|
2615
|
+
}
|
|
2616
|
+
async probeDraftCapability(credential) {
|
|
2617
|
+
const url = await this.endpoint("/cgi-bin/draft/batchget", credential);
|
|
2618
|
+
const response = await this.fetcher(url, {
|
|
2619
|
+
method: "POST",
|
|
2620
|
+
headers: { "content-type": "application/json" },
|
|
2621
|
+
body: JSON.stringify({ offset: 0, count: 1, no_content: 1 })
|
|
2622
|
+
});
|
|
2623
|
+
const result2 = await readJson(response, "draft capability probe");
|
|
2624
|
+
assertWechatSuccess("draft capability probe", result2);
|
|
2625
|
+
return { ok: true, draftApi: true, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2626
|
+
}
|
|
2627
|
+
async uploadArticleImage(credential, image) {
|
|
2628
|
+
const url = await this.endpoint("/cgi-bin/media/uploadimg", credential);
|
|
2629
|
+
const form = new FormData();
|
|
2630
|
+
const blobBytes = new Uint8Array(image.bytes.byteLength);
|
|
2631
|
+
blobBytes.set(image.bytes);
|
|
2632
|
+
form.set("media", new Blob([blobBytes.buffer], { type: image.mimeType }), image.filename);
|
|
2633
|
+
const response = await readJson(
|
|
2634
|
+
await this.fetcher(url, { method: "POST", body: form }),
|
|
2635
|
+
"article image upload"
|
|
2636
|
+
);
|
|
2637
|
+
assertWechatSuccess("article image upload", response);
|
|
2638
|
+
if (!response.url) {
|
|
2639
|
+
throw new WechatApiError("WeChat article image upload response has no URL", {
|
|
2640
|
+
action: "article image upload"
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
return { url: normalizeWechatImageUrl(response.url) };
|
|
2644
|
+
}
|
|
2645
|
+
async uploadPermanentImage(credential, image) {
|
|
2646
|
+
const url = await this.endpoint("/cgi-bin/material/add_material", credential);
|
|
2647
|
+
url.searchParams.set("type", "image");
|
|
2648
|
+
const form = new FormData();
|
|
2649
|
+
const blobBytes = new Uint8Array(image.bytes.byteLength);
|
|
2650
|
+
blobBytes.set(image.bytes);
|
|
2651
|
+
form.set("media", new Blob([blobBytes.buffer], { type: image.mimeType }), image.filename);
|
|
2652
|
+
const response = await readJson(
|
|
2653
|
+
await this.fetcher(url, { method: "POST", body: form }),
|
|
2654
|
+
"image upload"
|
|
2655
|
+
);
|
|
2656
|
+
if (!response) {
|
|
2657
|
+
throw new WechatApiError("WeChat image upload response is empty", {
|
|
2658
|
+
action: "image upload"
|
|
2659
|
+
});
|
|
2660
|
+
}
|
|
2661
|
+
assertWechatSuccess("image upload", response);
|
|
2662
|
+
if (!response.media_id || !response.url) {
|
|
2663
|
+
throw new WechatApiError("WeChat image upload response is incomplete", {
|
|
2664
|
+
action: "image upload"
|
|
2665
|
+
});
|
|
2666
|
+
}
|
|
2667
|
+
return { mediaId: response.media_id, url: normalizeWechatImageUrl(response.url) };
|
|
2668
|
+
}
|
|
2669
|
+
async createDraft(credential, article) {
|
|
2670
|
+
const url = await this.endpoint("/cgi-bin/draft/add", credential);
|
|
2671
|
+
const result2 = await readJson(
|
|
2672
|
+
await this.fetcher(url, {
|
|
2673
|
+
method: "POST",
|
|
2674
|
+
headers: { "content-type": "application/json" },
|
|
2675
|
+
body: JSON.stringify({ articles: [toWechatArticle(article)] })
|
|
2676
|
+
}),
|
|
2677
|
+
"draft create"
|
|
2678
|
+
);
|
|
2679
|
+
assertWechatSuccess("draft create", result2);
|
|
2680
|
+
if (!result2.media_id) {
|
|
2681
|
+
throw new WechatApiError("WeChat draft create response has no media_id", {
|
|
2682
|
+
action: "draft create"
|
|
2683
|
+
});
|
|
2684
|
+
}
|
|
2685
|
+
return result2.media_id;
|
|
2686
|
+
}
|
|
2687
|
+
async updateDraft(credential, mediaId, article) {
|
|
2688
|
+
const url = await this.endpoint("/cgi-bin/draft/update", credential);
|
|
2689
|
+
const result2 = await readJson(
|
|
2690
|
+
await this.fetcher(url, {
|
|
2691
|
+
method: "POST",
|
|
2692
|
+
headers: { "content-type": "application/json" },
|
|
2693
|
+
body: JSON.stringify({ media_id: mediaId, index: 0, articles: toWechatArticle(article) })
|
|
2694
|
+
}),
|
|
2695
|
+
"draft update"
|
|
2696
|
+
);
|
|
2697
|
+
assertWechatSuccess("draft update", result2);
|
|
2698
|
+
}
|
|
2699
|
+
async deleteDraft(credential, mediaId) {
|
|
2700
|
+
const url = await this.endpoint("/cgi-bin/draft/delete", credential);
|
|
2701
|
+
const result2 = await readJson(
|
|
2702
|
+
await this.fetcher(url, {
|
|
2703
|
+
method: "POST",
|
|
2704
|
+
headers: { "content-type": "application/json" },
|
|
2705
|
+
body: JSON.stringify({ media_id: mediaId })
|
|
2706
|
+
}),
|
|
2707
|
+
"draft delete"
|
|
2708
|
+
);
|
|
2709
|
+
assertWechatSuccess("draft delete", result2);
|
|
2710
|
+
}
|
|
2711
|
+
async deletePermanentMaterial(credential, mediaId) {
|
|
2712
|
+
const url = await this.endpoint("/cgi-bin/material/del_material", credential);
|
|
2713
|
+
const result2 = await readJson(
|
|
2714
|
+
await this.fetcher(url, {
|
|
2715
|
+
method: "POST",
|
|
2716
|
+
headers: { "content-type": "application/json" },
|
|
2717
|
+
body: JSON.stringify({ media_id: mediaId })
|
|
2718
|
+
}),
|
|
2719
|
+
"material delete"
|
|
2720
|
+
);
|
|
2721
|
+
assertWechatSuccess("material delete", result2);
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
function toWechatArticle(article) {
|
|
2725
|
+
return {
|
|
2726
|
+
title: article.title,
|
|
2727
|
+
content: article.content,
|
|
2728
|
+
thumb_media_id: article.thumbMediaId,
|
|
2729
|
+
need_open_comment: article.needOpenComment ? 1 : 0,
|
|
2730
|
+
only_fans_can_comment: article.onlyFansCanComment ? 1 : 0,
|
|
2731
|
+
...article.author ? { author: article.author } : {},
|
|
2732
|
+
...article.digest ? { digest: article.digest } : {},
|
|
2733
|
+
...article.contentSourceUrl ? { content_source_url: article.contentSourceUrl } : {}
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
// ../../packages/wechat-adapter/dist/index.js
|
|
2738
|
+
var JsonTokenStore = class {
|
|
2739
|
+
path;
|
|
2740
|
+
constructor(home) {
|
|
2741
|
+
this.path = join5(home, "tokens.json");
|
|
2742
|
+
}
|
|
2743
|
+
async read() {
|
|
2744
|
+
try {
|
|
2745
|
+
return JSON.parse(await readFile7(this.path, "utf8"));
|
|
2746
|
+
} catch (error) {
|
|
2747
|
+
if (error.code === "ENOENT") return {};
|
|
2748
|
+
throw error;
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
async write(tokens) {
|
|
2752
|
+
const directory = dirname4(this.path);
|
|
2753
|
+
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
2754
|
+
const temporary = `${this.path}.${process.pid}.tmp`;
|
|
2755
|
+
await writeFile5(temporary, `${JSON.stringify(tokens, null, 2)}
|
|
2756
|
+
`, { mode: 384 });
|
|
2757
|
+
await rename5(temporary, this.path);
|
|
2758
|
+
}
|
|
2759
|
+
async get(appId) {
|
|
2760
|
+
return (await this.read())[appId];
|
|
2761
|
+
}
|
|
2762
|
+
async set(appId, token) {
|
|
2763
|
+
await this.write({ ...await this.read(), [appId]: token });
|
|
2764
|
+
}
|
|
2765
|
+
async remove(appId) {
|
|
2766
|
+
const tokens = await this.read();
|
|
2767
|
+
delete tokens[appId];
|
|
2768
|
+
await this.write(tokens);
|
|
2769
|
+
}
|
|
2770
|
+
};
|
|
2771
|
+
var FaFaWechatClient = class {
|
|
2772
|
+
client;
|
|
2773
|
+
constructor(tokenStore, fetcher) {
|
|
2774
|
+
this.client = new WechatOfficialAccountClient(tokenStore, fetcher);
|
|
2775
|
+
}
|
|
2776
|
+
probeDraftCapability(credential) {
|
|
2777
|
+
return this.call(() => this.client.probeDraftCapability(credential));
|
|
2778
|
+
}
|
|
2779
|
+
uploadArticleImage(credential, image) {
|
|
2780
|
+
return this.call(() => this.client.uploadArticleImage(credential, image));
|
|
2781
|
+
}
|
|
2782
|
+
uploadPermanentImage(credential, image) {
|
|
2783
|
+
return this.call(() => this.client.uploadPermanentImage(credential, image));
|
|
2784
|
+
}
|
|
2785
|
+
createDraft(credential, article) {
|
|
2786
|
+
return this.call(() => this.client.createDraft(credential, article));
|
|
2787
|
+
}
|
|
2788
|
+
updateDraft(credential, mediaId, article) {
|
|
2789
|
+
return this.call(() => this.client.updateDraft(credential, mediaId, article));
|
|
2790
|
+
}
|
|
2791
|
+
async call(operation) {
|
|
2792
|
+
try {
|
|
2793
|
+
return await operation();
|
|
2794
|
+
} catch (error) {
|
|
2795
|
+
if (!(error instanceof WechatApiError)) throw error;
|
|
2796
|
+
throw new FaFaError("WECHAT_API_ERROR", error.message, {
|
|
2797
|
+
...error.action === void 0 ? {} : { action: error.action },
|
|
2798
|
+
...error.errcode === void 0 ? {} : { errcode: error.errcode },
|
|
2799
|
+
...error.errmsg === void 0 ? {} : { errmsg: error.errmsg },
|
|
2800
|
+
...error.status === void 0 ? {} : { status: error.status }
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
};
|
|
2805
|
+
function createDefaultWechatClient(home) {
|
|
2806
|
+
return new FaFaWechatClient(new JsonTokenStore(home));
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
// ../../packages/application/dist/index.js
|
|
2810
|
+
function emptyState() {
|
|
2811
|
+
return { version: 1, operations: [], draftDeliveries: [], assetUploads: [] };
|
|
2812
|
+
}
|
|
2813
|
+
function isRecord(value) {
|
|
2814
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
2815
|
+
}
|
|
2816
|
+
function isOptionalString(value) {
|
|
2817
|
+
return value === void 0 || typeof value === "string";
|
|
2818
|
+
}
|
|
2819
|
+
function isOperationRecord(value) {
|
|
2820
|
+
if (!isRecord(value)) return false;
|
|
2821
|
+
return typeof value.id === "string" && typeof value.type === "string" && (value.status === "running" || value.status === "succeeded" || value.status === "failed") && typeof value.startedAt === "string" && isOptionalString(value.articleId) && isOptionalString(value.accountId) && isOptionalString(value.finishedAt) && isOptionalString(value.errorCode) && isOptionalString(value.errorMessage);
|
|
2822
|
+
}
|
|
2823
|
+
function isStoredDraftDelivery(value) {
|
|
2824
|
+
if (!isRecord(value)) return false;
|
|
2825
|
+
return typeof value.articleId === "string" && value.platform === "wechat" && typeof value.accountId === "string" && typeof value.mediaId === "string" && typeof value.buildHash === "string" && typeof value.deliveredAt === "string";
|
|
2826
|
+
}
|
|
2827
|
+
function isAssetUploadRecord(value) {
|
|
2828
|
+
if (!isRecord(value)) return false;
|
|
2829
|
+
return typeof value.accountId === "string" && typeof value.hash === "string" && typeof value.purpose === "string" && typeof value.transformKey === "string" && isOptionalString(value.mediaId) && typeof value.url === "string" && typeof value.createdAt === "string";
|
|
2830
|
+
}
|
|
2831
|
+
function isStateDocument(value) {
|
|
2832
|
+
if (!value || typeof value !== "object") return false;
|
|
2833
|
+
const candidate = value;
|
|
2834
|
+
return candidate.version === 1 && Array.isArray(candidate.operations) && candidate.operations.every(isOperationRecord) && Array.isArray(candidate.draftDeliveries) && candidate.draftDeliveries.every(isStoredDraftDelivery) && Array.isArray(candidate.assetUploads) && candidate.assetUploads.every(isAssetUploadRecord);
|
|
2835
|
+
}
|
|
2836
|
+
var FaFaStateStore = class {
|
|
2837
|
+
path;
|
|
2838
|
+
memory;
|
|
2839
|
+
constructor(path) {
|
|
2840
|
+
this.path = path;
|
|
2841
|
+
if (path === ":memory:") this.memory = emptyState();
|
|
2842
|
+
else mkdirSync(dirname5(path), { recursive: true });
|
|
2843
|
+
}
|
|
2844
|
+
close() {
|
|
2845
|
+
}
|
|
2846
|
+
read() {
|
|
2847
|
+
if (this.memory) return structuredClone(this.memory);
|
|
2848
|
+
if (!existsSync(this.path)) return emptyState();
|
|
2849
|
+
let parsed;
|
|
2850
|
+
try {
|
|
2851
|
+
parsed = JSON.parse(readFileSync(this.path, "utf8"));
|
|
2852
|
+
} catch (error) {
|
|
2853
|
+
throw new FaFaError("CONFIG_INVALID", `Could not read state file ${this.path}`, {
|
|
2854
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
2855
|
+
});
|
|
2856
|
+
}
|
|
2857
|
+
if (!isStateDocument(parsed)) {
|
|
2858
|
+
throw new FaFaError("CONFIG_INVALID", `Invalid FaFa state file ${this.path}`);
|
|
2859
|
+
}
|
|
2860
|
+
return parsed;
|
|
2861
|
+
}
|
|
2862
|
+
write(state) {
|
|
2863
|
+
if (this.memory) {
|
|
2864
|
+
this.memory = structuredClone(state);
|
|
2865
|
+
return;
|
|
2866
|
+
}
|
|
2867
|
+
const temporary = `${this.path}.${process.pid}.tmp`;
|
|
2868
|
+
writeFileSync(temporary, `${JSON.stringify(state, null, 2)}
|
|
2869
|
+
`, { mode: 384 });
|
|
2870
|
+
renameSync(temporary, this.path);
|
|
2871
|
+
}
|
|
2872
|
+
startOperation(record) {
|
|
2873
|
+
const operation = {
|
|
2874
|
+
...record,
|
|
2875
|
+
status: "running",
|
|
2876
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2877
|
+
};
|
|
2878
|
+
const state = this.read();
|
|
2879
|
+
if (state.operations.some((candidate) => candidate.id === operation.id)) {
|
|
2880
|
+
throw new FaFaError("CONFIG_INVALID", `Duplicate operation id ${operation.id}`);
|
|
2881
|
+
}
|
|
2882
|
+
state.operations.push(operation);
|
|
2883
|
+
if (state.operations.length > 1e3) state.operations.splice(0, state.operations.length - 1e3);
|
|
2884
|
+
this.write(state);
|
|
2885
|
+
return operation;
|
|
2886
|
+
}
|
|
2887
|
+
finishOperation(id, error) {
|
|
2888
|
+
const state = this.read();
|
|
2889
|
+
const index = state.operations.findIndex((operation2) => operation2.id === id);
|
|
2890
|
+
if (index < 0) throw new FaFaError("CONFIG_INVALID", `Unknown operation id ${id}`);
|
|
2891
|
+
const operation = state.operations[index];
|
|
2892
|
+
state.operations[index] = {
|
|
2893
|
+
...operation,
|
|
2894
|
+
status: error ? "failed" : "succeeded",
|
|
2895
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2896
|
+
...error?.code ? { errorCode: error.code } : {},
|
|
2897
|
+
...error ? { errorMessage: error.message } : {}
|
|
2898
|
+
};
|
|
2899
|
+
this.write(state);
|
|
2900
|
+
}
|
|
2901
|
+
listOperations(limit = 50) {
|
|
2902
|
+
return this.read().operations.sort((left, right) => right.startedAt.localeCompare(left.startedAt)).slice(0, limit);
|
|
2903
|
+
}
|
|
2904
|
+
getDraftDelivery(articleId2, platform, accountId) {
|
|
2905
|
+
const stored = this.read().draftDeliveries.find(
|
|
2906
|
+
(candidate) => candidate.articleId === articleId2 && candidate.platform === platform && candidate.accountId === accountId
|
|
2907
|
+
);
|
|
2908
|
+
if (!stored) return void 0;
|
|
2909
|
+
return {
|
|
2910
|
+
...stored,
|
|
2911
|
+
operationId: "stored",
|
|
2912
|
+
action: "updated"
|
|
2913
|
+
};
|
|
2914
|
+
}
|
|
2915
|
+
saveDraftDelivery(receipt) {
|
|
2916
|
+
const state = this.read();
|
|
2917
|
+
const stored = {
|
|
2918
|
+
articleId: receipt.articleId,
|
|
2919
|
+
platform: receipt.platform,
|
|
2920
|
+
accountId: receipt.accountId,
|
|
2921
|
+
mediaId: receipt.mediaId,
|
|
2922
|
+
buildHash: receipt.buildHash,
|
|
2923
|
+
deliveredAt: receipt.deliveredAt
|
|
2924
|
+
};
|
|
2925
|
+
const index = state.draftDeliveries.findIndex(
|
|
2926
|
+
(candidate) => candidate.articleId === receipt.articleId && candidate.platform === receipt.platform && candidate.accountId === receipt.accountId
|
|
2927
|
+
);
|
|
2928
|
+
if (index < 0) state.draftDeliveries.push(stored);
|
|
2929
|
+
else state.draftDeliveries[index] = stored;
|
|
2930
|
+
this.write(state);
|
|
2931
|
+
}
|
|
2932
|
+
getAssetUpload(accountId, hash, purpose, transformKey) {
|
|
2933
|
+
return this.read().assetUploads.find(
|
|
2934
|
+
(candidate) => candidate.accountId === accountId && candidate.hash === hash && candidate.purpose === purpose && candidate.transformKey === transformKey && (purpose !== "cover" || typeof candidate.mediaId === "string")
|
|
2935
|
+
);
|
|
2936
|
+
}
|
|
2937
|
+
saveAssetUpload(record) {
|
|
2938
|
+
const state = this.read();
|
|
2939
|
+
const index = state.assetUploads.findIndex(
|
|
2940
|
+
(candidate) => candidate.accountId === record.accountId && candidate.hash === record.hash && candidate.purpose === record.purpose && candidate.transformKey === record.transformKey
|
|
2941
|
+
);
|
|
2942
|
+
if (index < 0) state.assetUploads.push(record);
|
|
2943
|
+
else state.assetUploads[index] = record;
|
|
2944
|
+
this.write(state);
|
|
2945
|
+
}
|
|
2946
|
+
};
|
|
2947
|
+
function inspectExportBrowser(home, options = {}) {
|
|
2948
|
+
return inspectBrowserRuntime({ home, ...options });
|
|
2949
|
+
}
|
|
2950
|
+
function installExportBrowser(home, options = {}) {
|
|
2951
|
+
return installBrowserRuntime({ home, ...options });
|
|
2952
|
+
}
|
|
2953
|
+
var FaFaService = class _FaFaService {
|
|
2954
|
+
project;
|
|
2955
|
+
state;
|
|
2956
|
+
home;
|
|
2957
|
+
wechat;
|
|
2958
|
+
assetFetcher;
|
|
2959
|
+
exporter;
|
|
2960
|
+
constructor(project, state, options) {
|
|
2961
|
+
this.project = project;
|
|
2962
|
+
this.state = state;
|
|
2963
|
+
this.home = options.home ?? getFaFaHome(options.environment);
|
|
2964
|
+
this.wechat = options.wechat ?? createDefaultWechatClient(this.home);
|
|
2965
|
+
this.assetFetcher = options.assetFetcher;
|
|
2966
|
+
this.exporter = options.exporter ?? {};
|
|
2967
|
+
}
|
|
2968
|
+
static async open(startPath = process.cwd(), options = {}) {
|
|
2969
|
+
const project = await loadProject(startPath);
|
|
2970
|
+
const statePath = join6(project.root, ".fafa", "state.json");
|
|
2971
|
+
return new _FaFaService(project, new FaFaStateStore(statePath), options);
|
|
2972
|
+
}
|
|
2973
|
+
close() {
|
|
2974
|
+
this.state.close();
|
|
2975
|
+
}
|
|
2976
|
+
async listArticles() {
|
|
2977
|
+
const sources = await discoverArticles(this.project);
|
|
2978
|
+
return Promise.all(
|
|
2979
|
+
sources.map(async (source) => {
|
|
2980
|
+
const parsed = await parseArticle(this.project.root, source.sourcePath);
|
|
2981
|
+
return {
|
|
2982
|
+
id: parsed.manuscript.id,
|
|
2983
|
+
name: manuscriptDisplayName(parsed),
|
|
2984
|
+
path: source.inputPath
|
|
2985
|
+
};
|
|
2986
|
+
})
|
|
2987
|
+
);
|
|
2988
|
+
}
|
|
2989
|
+
async build(articleInput) {
|
|
2990
|
+
const source = await resolveArticleSource(this.project, articleInput);
|
|
2991
|
+
const parsed = await parseArticle(this.project.root, source.sourcePath);
|
|
2992
|
+
return this.buildParsed(source.articleDir, parsed);
|
|
2993
|
+
}
|
|
2994
|
+
async buildSource(markdown, sourceInput) {
|
|
2995
|
+
const source = await resolveArticleSource(this.project, sourceInput);
|
|
2996
|
+
const parsed = await parseArticleContent(
|
|
2997
|
+
this.project.root,
|
|
2998
|
+
source.articleDir,
|
|
2999
|
+
markdown,
|
|
3000
|
+
source.sourcePath
|
|
3001
|
+
);
|
|
3002
|
+
return this.buildParsed(source.articleDir, parsed);
|
|
3003
|
+
}
|
|
3004
|
+
async exportArticle(articleInput, options) {
|
|
3005
|
+
const build = await this.build(articleInput);
|
|
3006
|
+
return this.exportBuild(build, options);
|
|
3007
|
+
}
|
|
3008
|
+
async exportSource(markdown, sourceInput, options) {
|
|
3009
|
+
const build = await this.buildSource(markdown, sourceInput);
|
|
3010
|
+
return this.exportBuild(build, options);
|
|
3011
|
+
}
|
|
3012
|
+
async exportBuild(build, options) {
|
|
3013
|
+
if (hasErrors(build.artifact.diagnostics)) {
|
|
3014
|
+
throw new FaFaError("CHECK_FAILED", "Article failed validation", {
|
|
3015
|
+
diagnostics: build.artifact.diagnostics
|
|
3016
|
+
});
|
|
3017
|
+
}
|
|
3018
|
+
const exported = await exportDocument(
|
|
3019
|
+
{
|
|
3020
|
+
format: options.format,
|
|
3021
|
+
title: build.metadata.title,
|
|
3022
|
+
articleHtml: build.artifact.html,
|
|
3023
|
+
home: this.home,
|
|
3024
|
+
...options.appearance ? { appearance: options.appearance } : {},
|
|
3025
|
+
...options.width === void 0 ? {} : { width: options.width },
|
|
3026
|
+
...options.browserPath ? { browserPath: options.browserPath } : {}
|
|
3027
|
+
},
|
|
3028
|
+
this.exporter
|
|
3029
|
+
);
|
|
3030
|
+
return {
|
|
3031
|
+
...exported,
|
|
3032
|
+
articleId: build.artifact.articleId,
|
|
3033
|
+
buildHash: build.artifact.buildHash
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
inspectExportBrowser(options = {}) {
|
|
3037
|
+
return inspectExportBrowser(this.home, options);
|
|
3038
|
+
}
|
|
3039
|
+
installExportBrowser(options = {}) {
|
|
3040
|
+
return installExportBrowser(this.home, options);
|
|
3041
|
+
}
|
|
3042
|
+
async buildParsed(articleDir, parsed) {
|
|
3043
|
+
const loadedMetadata = parseArticleMetadata(parsed.manuscript.frontmatter, parsed.manuscript.sourcePath);
|
|
3044
|
+
const metadata = {
|
|
3045
|
+
...loadedMetadata,
|
|
3046
|
+
theme: loadedMetadata.theme ?? this.project.config.defaults.theme,
|
|
3047
|
+
codeTheme: loadedMetadata.codeTheme ?? this.project.config.defaults.codeTheme,
|
|
3048
|
+
imageCaption: loadedMetadata.imageCaption ?? this.project.config.defaults.imageCaption,
|
|
3049
|
+
...loadedMetadata.author ? {} : this.project.config.defaults.author ? { author: this.project.config.defaults.author } : {}
|
|
3050
|
+
};
|
|
3051
|
+
const [resolvedArticleAssets, theme, renderPreparation] = await Promise.all([
|
|
3052
|
+
Promise.all(
|
|
3053
|
+
parsed.assets.map(
|
|
3054
|
+
(reference) => resolveAsset(reference, this.assetFetcher ? { fetcher: this.assetFetcher } : {})
|
|
3055
|
+
)
|
|
3056
|
+
),
|
|
3057
|
+
resolveWechatTheme(this.project.root, metadata.theme ?? "default"),
|
|
3058
|
+
prepareWechatRichContent(parsed, metadata.codeTheme ?? "github-light")
|
|
3059
|
+
]);
|
|
3060
|
+
const inlineAssets = [...resolvedArticleAssets, ...renderPreparation.assets];
|
|
3061
|
+
const firstInline = inlineAssets[0];
|
|
3062
|
+
if (!metadata.cover && !firstInline) {
|
|
3063
|
+
throw new FaFaError(
|
|
3064
|
+
"CHECK_FAILED",
|
|
3065
|
+
`Article ${parsed.manuscript.id} has no explicit cover or inline image`
|
|
3066
|
+
);
|
|
3067
|
+
}
|
|
3068
|
+
const cover = metadata.cover ? await resolveAsset(
|
|
3069
|
+
createCoverReference(this.project.root, articleDir, metadata.cover),
|
|
3070
|
+
this.assetFetcher ? { fetcher: this.assetFetcher } : {}
|
|
3071
|
+
) : {
|
|
3072
|
+
...firstInline,
|
|
3073
|
+
id: `cover-fallback-${firstInline?.id}`,
|
|
3074
|
+
purpose: "cover"
|
|
3075
|
+
};
|
|
3076
|
+
const assets = [...inlineAssets, cover];
|
|
3077
|
+
const hashes = new Map(assets.map((asset) => [asset.id, asset.hash]));
|
|
3078
|
+
const previewUrls = new Map(
|
|
3079
|
+
assets.filter((asset) => asset.purpose === "inline").map((asset) => [asset.id, dataUrl(asset)])
|
|
3080
|
+
);
|
|
3081
|
+
const [artifact, previewArtifact] = await Promise.all([
|
|
3082
|
+
renderWechatArticle(parsed, metadata, {
|
|
3083
|
+
theme,
|
|
3084
|
+
preparation: renderPreparation,
|
|
3085
|
+
assets,
|
|
3086
|
+
assetUrls: previewUrls,
|
|
3087
|
+
assetHashes: hashes
|
|
3088
|
+
}),
|
|
3089
|
+
renderWechatArticle(parsed, metadata, {
|
|
3090
|
+
theme,
|
|
3091
|
+
preparation: renderPreparation,
|
|
3092
|
+
assets,
|
|
3093
|
+
assetUrls: previewUrls,
|
|
3094
|
+
assetHashes: hashes,
|
|
3095
|
+
includeSourceLocations: true
|
|
3096
|
+
})
|
|
3097
|
+
]);
|
|
3098
|
+
return {
|
|
3099
|
+
project: this.project,
|
|
3100
|
+
articleDir,
|
|
3101
|
+
parsed,
|
|
3102
|
+
metadata,
|
|
3103
|
+
theme,
|
|
3104
|
+
codeTheme: renderPreparation.codeTheme,
|
|
3105
|
+
renderPreparation,
|
|
3106
|
+
assets,
|
|
3107
|
+
cover,
|
|
3108
|
+
artifact,
|
|
3109
|
+
previewHtml: wrapWechatPreview(metadata.title, previewArtifact.html)
|
|
3110
|
+
};
|
|
3111
|
+
}
|
|
3112
|
+
async resolveDeliveryAccountId(accountId) {
|
|
3113
|
+
const config = await loadUserConfig(this.home);
|
|
3114
|
+
const resolved = accountId ?? config.defaultAccount;
|
|
3115
|
+
if (!resolved) {
|
|
3116
|
+
throw new FaFaError(
|
|
3117
|
+
"CREDENTIAL_MISSING",
|
|
3118
|
+
"No WeChat account selected and no default account is configured"
|
|
3119
|
+
);
|
|
3120
|
+
}
|
|
3121
|
+
return resolved;
|
|
3122
|
+
}
|
|
3123
|
+
async planDraftPush(articleInput, accountId) {
|
|
3124
|
+
const [build, targetAccountId] = await Promise.all([
|
|
3125
|
+
this.build(articleInput),
|
|
3126
|
+
this.resolveDeliveryAccountId(accountId)
|
|
3127
|
+
]);
|
|
3128
|
+
const previous = this.state.getDraftDelivery(build.parsed.manuscript.id, "wechat", targetAccountId);
|
|
3129
|
+
let uploads = 0;
|
|
3130
|
+
let reusedUploads = 0;
|
|
3131
|
+
for (const asset of build.assets) {
|
|
3132
|
+
const cached = this.state.getAssetUpload(
|
|
3133
|
+
targetAccountId,
|
|
3134
|
+
asset.hash,
|
|
3135
|
+
asset.purpose,
|
|
3136
|
+
asset.transformKey
|
|
3137
|
+
);
|
|
3138
|
+
if (cached) reusedUploads += 1;
|
|
3139
|
+
else uploads += 1;
|
|
3140
|
+
}
|
|
3141
|
+
return {
|
|
3142
|
+
articleId: build.parsed.manuscript.id,
|
|
3143
|
+
accountId: targetAccountId,
|
|
3144
|
+
buildHash: build.artifact.buildHash,
|
|
3145
|
+
action: previous ? "update" : "create",
|
|
3146
|
+
uploads,
|
|
3147
|
+
reusedUploads,
|
|
3148
|
+
diagnostics: build.artifact.diagnostics
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
async probeAccount(accountId) {
|
|
3152
|
+
const credential = await resolveWechatCredential(accountId, this.home);
|
|
3153
|
+
return this.wechat.probeDraftCapability(credential);
|
|
3154
|
+
}
|
|
3155
|
+
async pushDraft(articleInput, accountId) {
|
|
3156
|
+
const [build, targetAccountId] = await Promise.all([
|
|
3157
|
+
this.build(articleInput),
|
|
3158
|
+
this.resolveDeliveryAccountId(accountId)
|
|
3159
|
+
]);
|
|
3160
|
+
if (hasErrors(build.artifact.diagnostics)) {
|
|
3161
|
+
throw new FaFaError("CHECK_FAILED", "Article failed validation", {
|
|
3162
|
+
diagnostics: build.artifact.diagnostics
|
|
3163
|
+
});
|
|
3164
|
+
}
|
|
3165
|
+
const operationId = randomUUID2();
|
|
3166
|
+
this.state.startOperation({
|
|
3167
|
+
id: operationId,
|
|
3168
|
+
type: "wechat.draft.push",
|
|
3169
|
+
articleId: build.parsed.manuscript.id,
|
|
3170
|
+
accountId: targetAccountId
|
|
3171
|
+
});
|
|
3172
|
+
try {
|
|
3173
|
+
const credential = await resolveWechatCredential(targetAccountId, this.home);
|
|
3174
|
+
const inlineUrls = /* @__PURE__ */ new Map();
|
|
3175
|
+
let coverMediaId;
|
|
3176
|
+
for (const asset of build.assets) {
|
|
3177
|
+
const cached = this.state.getAssetUpload(
|
|
3178
|
+
targetAccountId,
|
|
3179
|
+
asset.hash,
|
|
3180
|
+
asset.purpose,
|
|
3181
|
+
asset.transformKey
|
|
3182
|
+
);
|
|
3183
|
+
const upload = cached ?? (asset.purpose === "inline" ? await this.wechat.uploadArticleImage(credential, {
|
|
3184
|
+
bytes: asset.bytes,
|
|
3185
|
+
filename: asset.filename,
|
|
3186
|
+
mimeType: asset.mimeType
|
|
3187
|
+
}) : await this.wechat.uploadPermanentImage(credential, {
|
|
3188
|
+
bytes: asset.bytes,
|
|
3189
|
+
filename: asset.filename,
|
|
3190
|
+
mimeType: asset.mimeType
|
|
3191
|
+
}));
|
|
3192
|
+
const mediaId2 = "mediaId" in upload && typeof upload.mediaId === "string" ? upload.mediaId : void 0;
|
|
3193
|
+
if (!cached) {
|
|
3194
|
+
this.state.saveAssetUpload({
|
|
3195
|
+
accountId: targetAccountId,
|
|
3196
|
+
hash: asset.hash,
|
|
3197
|
+
purpose: asset.purpose,
|
|
3198
|
+
transformKey: asset.transformKey,
|
|
3199
|
+
...mediaId2 ? { mediaId: mediaId2 } : {},
|
|
3200
|
+
url: upload.url,
|
|
3201
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
if (asset.purpose === "inline") inlineUrls.set(asset.id, upload.url);
|
|
3205
|
+
if (asset.id === build.cover.id) coverMediaId = mediaId2;
|
|
3206
|
+
}
|
|
3207
|
+
if (!coverMediaId) throw new FaFaError("DELIVERY_FAILED", "Cover upload produced no media_id");
|
|
3208
|
+
const hashes = new Map(build.assets.map((asset) => [asset.id, asset.hash]));
|
|
3209
|
+
const finalArtifact = await renderWechatArticle(build.parsed, build.metadata, {
|
|
3210
|
+
theme: build.theme,
|
|
3211
|
+
preparation: build.renderPreparation,
|
|
3212
|
+
assets: build.assets,
|
|
3213
|
+
assetUrls: inlineUrls,
|
|
3214
|
+
final: true,
|
|
3215
|
+
assetHashes: hashes
|
|
3216
|
+
});
|
|
3217
|
+
if (hasErrors(finalArtifact.diagnostics)) {
|
|
3218
|
+
throw new FaFaError("CHECK_FAILED", "Final WeChat HTML failed validation", {
|
|
3219
|
+
diagnostics: finalArtifact.diagnostics
|
|
3220
|
+
});
|
|
3221
|
+
}
|
|
3222
|
+
const current = await this.build(articleInput);
|
|
3223
|
+
if (current.artifact.buildHash !== build.artifact.buildHash) {
|
|
3224
|
+
throw new FaFaError("STALE_BUILD", "Source content or assets changed while the draft was uploading");
|
|
3225
|
+
}
|
|
3226
|
+
const previous = this.state.getDraftDelivery(build.parsed.manuscript.id, "wechat", targetAccountId);
|
|
3227
|
+
const article = {
|
|
3228
|
+
title: build.metadata.title,
|
|
3229
|
+
content: finalArtifact.html,
|
|
3230
|
+
thumbMediaId: coverMediaId,
|
|
3231
|
+
needOpenComment: build.metadata.comments.open,
|
|
3232
|
+
onlyFansCanComment: build.metadata.comments.fansOnly,
|
|
3233
|
+
...build.metadata.author ? { author: build.metadata.author } : {},
|
|
3234
|
+
...build.metadata.summary ? { digest: build.metadata.summary } : {},
|
|
3235
|
+
...build.metadata.sourceUrl ? { contentSourceUrl: build.metadata.sourceUrl } : {}
|
|
3236
|
+
};
|
|
3237
|
+
let mediaId;
|
|
3238
|
+
let action;
|
|
3239
|
+
if (previous) {
|
|
3240
|
+
await this.wechat.updateDraft(credential, previous.mediaId, article);
|
|
3241
|
+
mediaId = previous.mediaId;
|
|
3242
|
+
action = "updated";
|
|
3243
|
+
} else {
|
|
3244
|
+
mediaId = await this.wechat.createDraft(credential, article);
|
|
3245
|
+
action = "created";
|
|
3246
|
+
}
|
|
3247
|
+
const receipt = {
|
|
3248
|
+
operationId,
|
|
3249
|
+
articleId: build.parsed.manuscript.id,
|
|
3250
|
+
accountId: targetAccountId,
|
|
3251
|
+
platform: "wechat",
|
|
3252
|
+
mediaId,
|
|
3253
|
+
buildHash: finalArtifact.buildHash,
|
|
3254
|
+
action,
|
|
3255
|
+
deliveredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3256
|
+
};
|
|
3257
|
+
this.state.saveDraftDelivery(receipt);
|
|
3258
|
+
this.state.finishOperation(operationId);
|
|
3259
|
+
return receipt;
|
|
3260
|
+
} catch (error) {
|
|
3261
|
+
this.state.finishOperation(operationId, {
|
|
3262
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3263
|
+
...error instanceof FaFaError ? { code: error.code } : {}
|
|
3264
|
+
});
|
|
3265
|
+
throw error;
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
};
|
|
3269
|
+
|
|
3270
|
+
export {
|
|
3271
|
+
normalizeLocale,
|
|
3272
|
+
localeFromEnvironment,
|
|
3273
|
+
createTranslator,
|
|
3274
|
+
FaFaError,
|
|
3275
|
+
hasErrors,
|
|
3276
|
+
updateArticleFrontmatterFile,
|
|
3277
|
+
loadLibraryRegistry,
|
|
3278
|
+
listRegisteredLibraries,
|
|
3279
|
+
registerLibrary,
|
|
3280
|
+
touchLibrary,
|
|
3281
|
+
removeRegisteredLibrary,
|
|
3282
|
+
CONFIG_FILENAME,
|
|
3283
|
+
loadProject,
|
|
3284
|
+
createProject,
|
|
3285
|
+
setProjectDefaultTheme,
|
|
3286
|
+
setProjectDefaultCodeTheme,
|
|
3287
|
+
setProjectDefaultImageCaption,
|
|
3288
|
+
resolveInsideProject,
|
|
3289
|
+
createContentDiscoveryFilter,
|
|
3290
|
+
getFaFaHome,
|
|
3291
|
+
loadUserConfig,
|
|
3292
|
+
upsertAccount,
|
|
3293
|
+
removeAccount,
|
|
3294
|
+
toPublicUserConfig,
|
|
3295
|
+
resolveWechatCredential,
|
|
3296
|
+
createDefaultWechatClient,
|
|
3297
|
+
EXPORT_FORMATS,
|
|
3298
|
+
EXPORT_APPEARANCES,
|
|
3299
|
+
safeFilename,
|
|
3300
|
+
exportFilename,
|
|
3301
|
+
listCodeHighlightThemes,
|
|
3302
|
+
resolveCodeHighlightTheme,
|
|
3303
|
+
listWechatThemePresets,
|
|
3304
|
+
resolveWechatTheme,
|
|
3305
|
+
listImageCaptionModes,
|
|
3306
|
+
resolveImageCaptionMode,
|
|
3307
|
+
FaFaStateStore,
|
|
3308
|
+
inspectExportBrowser,
|
|
3309
|
+
installExportBrowser,
|
|
3310
|
+
FaFaService
|
|
3311
|
+
};
|