@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.
@@ -0,0 +1,2807 @@
1
+ import {
2
+ CONFIG_FILENAME,
3
+ EXPORT_APPEARANCES,
4
+ EXPORT_FORMATS,
5
+ FaFaError,
6
+ FaFaService,
7
+ createContentDiscoveryFilter,
8
+ createDefaultWechatClient,
9
+ createProject,
10
+ createTranslator,
11
+ exportFilename,
12
+ getFaFaHome,
13
+ hasErrors,
14
+ inspectExportBrowser,
15
+ installExportBrowser,
16
+ listCodeHighlightThemes,
17
+ listImageCaptionModes,
18
+ listRegisteredLibraries,
19
+ listWechatThemePresets,
20
+ loadLibraryRegistry,
21
+ loadProject,
22
+ loadUserConfig,
23
+ localeFromEnvironment,
24
+ normalizeLocale,
25
+ registerLibrary,
26
+ removeAccount,
27
+ removeRegisteredLibrary,
28
+ resolveCodeHighlightTheme,
29
+ resolveImageCaptionMode,
30
+ resolveInsideProject,
31
+ resolveWechatCredential,
32
+ resolveWechatTheme,
33
+ safeFilename,
34
+ setProjectDefaultCodeTheme,
35
+ setProjectDefaultImageCaption,
36
+ setProjectDefaultTheme,
37
+ toPublicUserConfig,
38
+ touchLibrary,
39
+ updateArticleFrontmatterFile,
40
+ upsertAccount
41
+ } from "./chunk-ZCVVJMRN.js";
42
+
43
+ // src/i18n.ts
44
+ var englishMessages = {
45
+ "app.description": "FaFa local-first content rendering and platform draft delivery",
46
+ "option.json": "write a stable JSON result to stdout",
47
+ "option.project": "project path (defaults to the current directory)",
48
+ "option.home": "user configuration directory (or use FAFA_HOME)",
49
+ "option.language": "interface language: en or zh-CN (or use FAFA_LANGUAGE)",
50
+ "init.description": "create a FaFa project",
51
+ "init.success": "Created {root}",
52
+ "articles.description": "list local source articles",
53
+ "articles.count": "{count} article(s)",
54
+ "theme.description": "manage WeChat CSS themes",
55
+ "theme.list.description": "list built-in themes",
56
+ "theme.list.count": "{count} built-in theme(s)",
57
+ "theme.set.description": "set the project default theme",
58
+ "theme.set.preset": "built-in theme id",
59
+ "theme.set.file": "project-local CSS theme file",
60
+ "theme.set.choice": "Specify exactly one of --preset or --file",
61
+ "theme.set.unknown": "Unknown built-in WeChat theme: {id}",
62
+ "theme.set.success": "Set project theme to {reference}",
63
+ "codeTheme.description": "manage Shiki code themes",
64
+ "codeTheme.list.description": "list built-in Shiki code themes",
65
+ "codeTheme.list.count": "{count} Shiki code theme(s)",
66
+ "codeTheme.set.description": "set the project default Shiki code theme",
67
+ "codeTheme.set.preset": "built-in Shiki code theme id",
68
+ "codeTheme.set.success": "Set project code theme to {reference}",
69
+ "caption.description": "manage image caption modes",
70
+ "caption.list.description": "list supported image caption modes",
71
+ "caption.list.count": "{count} image caption mode(s)",
72
+ "caption.set.description": "set the project default image caption mode",
73
+ "caption.set.mode": "image caption mode id",
74
+ "caption.set.success": "Set project image caption mode to {reference}",
75
+ "stdin.sourcePath": "Reading Markdown from stdin requires --source-path",
76
+ "check.failed": "Article failed validation",
77
+ "check.description": "validate an article without network access",
78
+ "sourcePath.description": "existing note identity and asset base for stdin",
79
+ "check.success": "Check passed: {articleId}",
80
+ "render.description": "render an offline WeChat preview",
81
+ "render.output": "preview output path",
82
+ "render.success": "Rendered {output}",
83
+ "export.description": "export an article as HTML, PDF, or PNG",
84
+ "export.format": "output format: html, pdf, or png",
85
+ "export.appearance": "export appearance: day or night",
86
+ "export.output": "export output path",
87
+ "export.width": "PNG width in CSS pixels (240-2000)",
88
+ "export.browserPath": "explicit Chrome or Edge executable path",
89
+ "export.formatError": "Unsupported export format: {format}. Use html, pdf, or png.",
90
+ "export.appearanceError": "Unsupported export appearance: {appearance}. Use day or night.",
91
+ "export.widthError": "--width must be an integer from 240 to 2000",
92
+ "export.widthFormatError": "--width can only be used with PNG export",
93
+ "export.success": "Exported {format} to {output}",
94
+ "browser.description": "manage the export browser runtime",
95
+ "browser.status.description": "inspect the available export browser",
96
+ "browser.status.ready": "Export browser is ready: {source}",
97
+ "browser.status.missing": "No export browser was found",
98
+ "browser.install.description": "install the managed export browser",
99
+ "browser.install.success": "Installed export browser: {source}",
100
+ "draft.description": "manage platform drafts",
101
+ "draft.push.description": "create or update a WeChat draft",
102
+ "draft.account": "target WeChat account",
103
+ "draft.dryRun": "plan without remote calls",
104
+ "draft.planFailed": "Draft plan failed validation",
105
+ "draft.planSuccess": "Dry run: {action} draft, upload {uploads}, reuse {reused}",
106
+ "draft.pushSuccess": "{action} WeChat draft {mediaId}",
107
+ "draft.created": "Created",
108
+ "draft.updated": "Updated",
109
+ "operations.description": "list recent local operations",
110
+ "operations.limit": "maximum records",
111
+ "operations.limitError": "--limit must be an integer from 1 to 500",
112
+ "operations.count": "{count} operation(s)",
113
+ "account.description": "manage WeChat accounts and credentials",
114
+ "account.add.description": "add or update an account",
115
+ "account.id": "stable local account id",
116
+ "account.name": "display name",
117
+ "account.appId": "WeChat AppID",
118
+ "account.test": "mark as a test account",
119
+ "account.secretEnv": "read AppSecret from this environment variable and store it in config",
120
+ "account.emptyEnv": "Environment variable {name} is empty",
121
+ "account.saved": "Saved account {id}",
122
+ "account.list.description": "list configured accounts (never prints secrets)",
123
+ "account.count": "{count} account(s)",
124
+ "account.remove.description": "remove an account and its stored credential",
125
+ "account.removed": "Removed account {id}",
126
+ "account.probe.description": "verify token and draft API capability without changing drafts",
127
+ "account.available": "Account {id} draft API is available",
128
+ "ui.description": "open or start the local FaFa Web Workbench",
129
+ "ui.port": "loopback port (default: 47890)",
130
+ "ui.portError": "--port must be an integer between 0 and 65535",
131
+ "ui.noOpen": "do not open a browser automatically",
132
+ "ui.foreground": "run the web server in the foreground instead of reusing a running daemon",
133
+ "ui.init": "initialize fafa.config.yaml if the target directory is not yet a library",
134
+ "ui.reused": "Opened running FaFa Web Workbench: {url}",
135
+ "ui.started": "FaFa Web Workbench listening on {url}",
136
+ "ui.launchHint": "Open with browser authorization: {url}",
137
+ "service.description": "manage the background auto-start FaFa Web Workbench service",
138
+ "service.install.description": "install and start the user-level background service",
139
+ "service.install.success": "Installed FaFa background service ({url})",
140
+ "service.uninstall.description": "stop and remove the background service",
141
+ "service.uninstall.success": "Uninstalled FaFa background service",
142
+ "service.status.description": "inspect background service status and local URL",
143
+ "service.status.running": "FaFa background service is running at {url} (PID {pid})",
144
+ "service.status.stopped": "FaFa background service is stopped ({url})",
145
+ "service.status.notInstalled": "FaFa background service is not installed",
146
+ "service.start.description": "start the installed background service",
147
+ "service.start.success": "Started FaFa background service ({url})",
148
+ "service.stop.description": "stop the running background service",
149
+ "service.stop.success": "Stopped FaFa background service",
150
+ "service.restart.description": "restart the installed background service",
151
+ "service.restart.success": "Restarted FaFa background service ({url})",
152
+ "service.logs.description": "print recent background service log lines",
153
+ "service.logs.lines": "maximum number of log lines",
154
+ "service.logs.empty": "No background service logs yet ({path})",
155
+ "language.unsupported": "Unsupported language: {language}. Use en or zh-CN."
156
+ };
157
+ var chineseMessages = {
158
+ "app.description": "FaFa \u672C\u5730\u4F18\u5148\u5185\u5BB9\u6E32\u67D3\u4E0E\u5E73\u53F0\u8349\u7A3F\u6295\u9012\u5DE5\u5177",
159
+ "option.json": "\u5C06\u7A33\u5B9A\u7684 JSON \u7ED3\u679C\u5199\u5165\u6807\u51C6\u8F93\u51FA",
160
+ "option.project": "\u9879\u76EE\u8DEF\u5F84\uFF08\u9ED8\u8BA4\u4F7F\u7528\u5F53\u524D\u76EE\u5F55\uFF09",
161
+ "option.home": "\u7528\u6237\u914D\u7F6E\u76EE\u5F55\uFF08\u4E5F\u53EF\u4F7F\u7528 FAFA_HOME\uFF09",
162
+ "option.language": "\u754C\u9762\u8BED\u8A00\uFF1Aen \u6216 zh-CN\uFF08\u4E5F\u53EF\u4F7F\u7528 FAFA_LANGUAGE\uFF09",
163
+ "init.description": "\u521B\u5EFA FaFa \u9879\u76EE",
164
+ "init.success": "\u5DF2\u521B\u5EFA {root}",
165
+ "articles.description": "\u5217\u51FA\u672C\u5730\u6E90\u6587\u7A3F",
166
+ "articles.count": "\u5171 {count} \u7BC7\u6E90\u6587\u7A3F",
167
+ "theme.description": "\u7BA1\u7406\u5FAE\u4FE1\u516C\u4F17\u53F7 CSS \u4E3B\u9898",
168
+ "theme.list.description": "\u5217\u51FA\u5185\u7F6E\u4E3B\u9898",
169
+ "theme.list.count": "\u5171 {count} \u4E2A\u5185\u7F6E\u4E3B\u9898",
170
+ "theme.set.description": "\u8BBE\u7F6E\u9879\u76EE\u9ED8\u8BA4\u4E3B\u9898",
171
+ "theme.set.preset": "\u5185\u7F6E\u4E3B\u9898 ID",
172
+ "theme.set.file": "\u9879\u76EE\u5185 CSS \u4E3B\u9898\u6587\u4EF6",
173
+ "theme.set.choice": "--preset \u4E0E --file \u5FC5\u987B\u4E14\u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A",
174
+ "theme.set.unknown": "\u672A\u77E5\u7684\u5185\u7F6E\u5FAE\u4FE1\u4E3B\u9898\uFF1A{id}",
175
+ "theme.set.success": "\u9879\u76EE\u4E3B\u9898\u5DF2\u8BBE\u4E3A {reference}",
176
+ "codeTheme.description": "\u7BA1\u7406 Shiki \u4EE3\u7801\u4E3B\u9898",
177
+ "codeTheme.list.description": "\u5217\u51FA\u5185\u7F6E Shiki \u4EE3\u7801\u4E3B\u9898",
178
+ "codeTheme.list.count": "\u5171 {count} \u4E2A\u5185\u7F6E Shiki \u4EE3\u7801\u4E3B\u9898",
179
+ "codeTheme.set.description": "\u8BBE\u7F6E\u9879\u76EE\u9ED8\u8BA4 Shiki \u4EE3\u7801\u4E3B\u9898",
180
+ "codeTheme.set.preset": "\u5185\u7F6E Shiki \u4EE3\u7801\u4E3B\u9898 ID",
181
+ "codeTheme.set.success": "\u9879\u76EE\u4EE3\u7801\u4E3B\u9898\u5DF2\u8BBE\u4E3A {reference}",
182
+ "caption.description": "\u7BA1\u7406\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F",
183
+ "caption.list.description": "\u5217\u51FA\u652F\u6301\u7684\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F",
184
+ "caption.list.count": "\u5171 {count} \u4E2A\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F",
185
+ "caption.set.description": "\u8BBE\u7F6E\u9879\u76EE\u9ED8\u8BA4\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F",
186
+ "caption.set.mode": "\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F ID",
187
+ "caption.set.success": "\u9879\u76EE\u56FE\u7247\u56FE\u6CE8\u6A21\u5F0F\u5DF2\u8BBE\u4E3A {reference}",
188
+ "stdin.sourcePath": "\u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6 Markdown \u65F6\u5FC5\u987B\u63D0\u4F9B --source-path",
189
+ "check.failed": "\u6E90\u6587\u7A3F\u6821\u9A8C\u672A\u901A\u8FC7",
190
+ "check.description": "\u79BB\u7EBF\u6821\u9A8C\u6E90\u6587\u7A3F",
191
+ "sourcePath.description": "\u6807\u51C6\u8F93\u5165\u5BF9\u5E94\u7684\u73B0\u6709\u7B14\u8BB0\u8EAB\u4EFD\u4E0E\u7D20\u6750\u57FA\u51C6\u8DEF\u5F84",
192
+ "check.success": "\u6821\u9A8C\u901A\u8FC7\uFF1A{articleId}",
193
+ "render.description": "\u751F\u6210\u79BB\u7EBF\u5FAE\u4FE1\u9884\u89C8",
194
+ "render.output": "\u9884\u89C8\u8F93\u51FA\u8DEF\u5F84",
195
+ "render.success": "\u5DF2\u6E32\u67D3 {output}",
196
+ "export.description": "\u5C06\u6587\u7AE0\u5BFC\u51FA\u4E3A HTML\u3001PDF \u6216 PNG",
197
+ "export.format": "\u8F93\u51FA\u683C\u5F0F\uFF1Ahtml\u3001pdf \u6216 png",
198
+ "export.appearance": "\u5BFC\u51FA\u663E\u793A\u6A21\u5F0F\uFF1Aday \u6216 night",
199
+ "export.output": "\u5BFC\u51FA\u6587\u4EF6\u8DEF\u5F84",
200
+ "export.width": "PNG \u7684 CSS \u50CF\u7D20\u5BBD\u5EA6\uFF08240-2000\uFF09",
201
+ "export.browserPath": "\u663E\u5F0F\u6307\u5B9A Chrome \u6216 Edge \u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84",
202
+ "export.formatError": "\u4E0D\u652F\u6301\u5BFC\u51FA\u683C\u5F0F {format}\uFF0C\u8BF7\u4F7F\u7528 html\u3001pdf \u6216 png\u3002",
203
+ "export.appearanceError": "\u4E0D\u652F\u6301\u5BFC\u51FA\u663E\u793A\u6A21\u5F0F {appearance}\uFF0C\u8BF7\u4F7F\u7528 day \u6216 night\u3002",
204
+ "export.widthError": "--width \u5FC5\u987B\u662F 240 \u5230 2000 \u4E4B\u95F4\u7684\u6574\u6570",
205
+ "export.widthFormatError": "--width \u53EA\u80FD\u7528\u4E8E PNG \u5BFC\u51FA",
206
+ "export.success": "\u5DF2\u5C06 {format} \u5BFC\u51FA\u5230 {output}",
207
+ "browser.description": "\u7BA1\u7406\u5BFC\u51FA\u6D4F\u89C8\u5668\u8FD0\u884C\u65F6",
208
+ "browser.status.description": "\u68C0\u67E5\u53EF\u7528\u7684\u5BFC\u51FA\u6D4F\u89C8\u5668",
209
+ "browser.status.ready": "\u5BFC\u51FA\u6D4F\u89C8\u5668\u5DF2\u5C31\u7EEA\uFF1A{source}",
210
+ "browser.status.missing": "\u672A\u627E\u5230\u5BFC\u51FA\u6D4F\u89C8\u5668",
211
+ "browser.install.description": "\u5B89\u88C5\u53D7\u7BA1\u7406\u7684\u5BFC\u51FA\u6D4F\u89C8\u5668",
212
+ "browser.install.success": "\u5DF2\u5B89\u88C5\u5BFC\u51FA\u6D4F\u89C8\u5668\uFF1A{source}",
213
+ "draft.description": "\u7BA1\u7406\u5E73\u53F0\u8349\u7A3F",
214
+ "draft.push.description": "\u521B\u5EFA\u6216\u66F4\u65B0\u5FAE\u4FE1\u516C\u4F17\u53F7\u8349\u7A3F",
215
+ "draft.account": "\u76EE\u6807\u5FAE\u4FE1\u516C\u4F17\u53F7\u8D26\u53F7",
216
+ "draft.dryRun": "\u53EA\u751F\u6210\u8BA1\u5212\uFF0C\u4E0D\u8C03\u7528\u8FDC\u7AEF\u63A5\u53E3",
217
+ "draft.planFailed": "\u8349\u7A3F\u6295\u9012\u9884\u68C0\u672A\u901A\u8FC7",
218
+ "draft.planSuccess": "\u9884\u68C0\uFF1A{action}\u8349\u7A3F\uFF0C\u4E0A\u4F20 {uploads} \u4E2A\u7D20\u6750\uFF0C\u590D\u7528 {reused} \u4E2A\u7D20\u6750",
219
+ "draft.pushSuccess": "{action}\u5FAE\u4FE1\u516C\u4F17\u53F7\u8349\u7A3F {mediaId}",
220
+ "draft.created": "\u5DF2\u521B\u5EFA",
221
+ "draft.updated": "\u5DF2\u66F4\u65B0",
222
+ "operations.description": "\u5217\u51FA\u6700\u8FD1\u7684\u672C\u5730\u64CD\u4F5C",
223
+ "operations.limit": "\u6700\u5927\u8BB0\u5F55\u6570",
224
+ "operations.limitError": "--limit \u5FC5\u987B\u662F 1 \u5230 500 \u4E4B\u95F4\u7684\u6574\u6570",
225
+ "operations.count": "\u5171 {count} \u6761\u64CD\u4F5C",
226
+ "account.description": "\u7BA1\u7406\u5FAE\u4FE1\u516C\u4F17\u53F7\u8D26\u53F7\u4E0E\u51ED\u636E",
227
+ "account.add.description": "\u6DFB\u52A0\u6216\u66F4\u65B0\u8D26\u53F7",
228
+ "account.id": "\u7A33\u5B9A\u7684\u672C\u5730\u8D26\u53F7 ID",
229
+ "account.name": "\u663E\u793A\u540D\u79F0",
230
+ "account.appId": "\u5FAE\u4FE1\u516C\u4F17\u53F7 AppID",
231
+ "account.test": "\u6807\u8BB0\u4E3A\u6D4B\u8BD5\u8D26\u53F7",
232
+ "account.secretEnv": "\u4ECE\u6B64\u73AF\u5883\u53D8\u91CF\u8BFB\u53D6 AppSecret \u5E76\u4FDD\u5B58\u5230\u914D\u7F6E",
233
+ "account.emptyEnv": "\u73AF\u5883\u53D8\u91CF {name} \u4E3A\u7A7A",
234
+ "account.saved": "\u5DF2\u4FDD\u5B58\u8D26\u53F7 {id}",
235
+ "account.list.description": "\u5217\u51FA\u5DF2\u914D\u7F6E\u8D26\u53F7\uFF08\u7EDD\u4E0D\u8F93\u51FA\u51ED\u636E\uFF09",
236
+ "account.count": "\u5171 {count} \u4E2A\u8D26\u53F7",
237
+ "account.remove.description": "\u79FB\u9664\u8D26\u53F7\u53CA\u5176\u5DF2\u4FDD\u5B58\u51ED\u636E",
238
+ "account.removed": "\u5DF2\u79FB\u9664\u8D26\u53F7 {id}",
239
+ "account.probe.description": "\u5728\u4E0D\u4FEE\u6539\u8349\u7A3F\u7684\u524D\u63D0\u4E0B\u9A8C\u8BC1 Token \u4E0E\u8349\u7A3F\u63A5\u53E3\u80FD\u529B",
240
+ "account.available": "\u8D26\u53F7 {id} \u7684\u8349\u7A3F\u63A5\u53E3\u53EF\u7528",
241
+ "ui.description": "\u6253\u5F00\u6216\u542F\u52A8\u672C\u5730\u53D1\u53D1 FaFa Web \u5DE5\u4F5C\u53F0",
242
+ "ui.port": "\u672C\u5730\u56DE\u73AF\u7AEF\u53E3\uFF08\u9ED8\u8BA4 47890\uFF09",
243
+ "ui.portError": "--port \u5FC5\u987B\u662F 0 \u5230 65535 \u4E4B\u95F4\u7684\u6574\u6570",
244
+ "ui.noOpen": "\u542F\u52A8\u540E\u4E0D\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668",
245
+ "ui.foreground": "\u5728\u524D\u53F0\u8FD0\u884C\u672C\u5730 Web \u670D\u52A1\uFF0C\u4E0D\u590D\u7528\u5DF2\u8FD0\u884C\u7684\u5E38\u9A7B\u670D\u52A1",
246
+ "ui.init": "\u82E5\u76EE\u6807\u76EE\u5F55\u5C1A\u672A\u521D\u59CB\u5316\u5185\u5BB9\u5E93\uFF0C\u81EA\u52A8\u521B\u5EFA fafa.config.yaml",
247
+ "ui.reused": "\u5DF2\u590D\u7528\u8FD0\u884C\u4E2D\u7684\u53D1\u53D1 Web \u5DE5\u4F5C\u53F0\uFF1A{url}",
248
+ "ui.started": "\u53D1\u53D1 Web \u5DE5\u4F5C\u53F0\u5DF2\u76D1\u542C\uFF1A{url}",
249
+ "ui.launchHint": "\u9996\u6B21\u6D4F\u89C8\u5668\u6388\u6743\u76F4\u8FBE\u94FE\u63A5\uFF1A{url}",
250
+ "service.description": "\u7BA1\u7406\u7528\u6237\u7EA7\u5F00\u673A\u81EA\u542F\u7684\u53D1\u53D1 Web \u5DE5\u4F5C\u53F0\u5E38\u9A7B\u670D\u52A1",
251
+ "service.install.description": "\u5B89\u88C5\u5E76\u542F\u52A8\u5F00\u673A\u81EA\u542F\u7684\u672C\u5730\u5E38\u9A7B\u670D\u52A1",
252
+ "service.install.success": "\u5DF2\u5B89\u88C5\u5E76\u542F\u52A8\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\uFF08{url}\uFF09",
253
+ "service.uninstall.description": "\u505C\u6B62\u5E76\u5378\u8F7D\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
254
+ "service.uninstall.success": "\u5DF2\u5378\u8F7D\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
255
+ "service.status.description": "\u67E5\u770B\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\u72B6\u6001\u4E0E\u672C\u5730\u8BBF\u95EE\u5730\u5740",
256
+ "service.status.running": "\u53D1\u53D1\u540E\u53F0\u670D\u52A1\u8FD0\u884C\u4E2D\uFF1A{url}\uFF08PID {pid}\uFF09",
257
+ "service.status.stopped": "\u53D1\u53D1\u540E\u53F0\u670D\u52A1\u5DF2\u5B89\u88C5\u4F46\u672A\u8FD0\u884C\uFF08{url}\uFF09",
258
+ "service.status.notInstalled": "\u5C1A\u672A\u5B89\u88C5\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\uFF08\u53EF\u8FD0\u884C fafa service install\uFF09",
259
+ "service.start.description": "\u542F\u52A8\u5DF2\u5B89\u88C5\u7684\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
260
+ "service.start.success": "\u5DF2\u542F\u52A8\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\uFF08{url}\uFF09",
261
+ "service.stop.description": "\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
262
+ "service.stop.success": "\u5DF2\u505C\u6B62\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
263
+ "service.restart.description": "\u91CD\u542F\u540E\u53F0\u5E38\u9A7B\u670D\u52A1",
264
+ "service.restart.success": "\u5DF2\u91CD\u542F\u53D1\u53D1\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\uFF08{url}\uFF09",
265
+ "service.logs.description": "\u67E5\u770B\u540E\u53F0\u5E38\u9A7B\u670D\u52A1\u65E5\u5FD7",
266
+ "service.logs.lines": "\u6700\u591A\u663E\u793A\u7684\u65E5\u5FD7\u884C\u6570",
267
+ "service.logs.empty": "\u6682\u65E0\u540E\u53F0\u670D\u52A1\u65E5\u5FD7\uFF08{path}\uFF09",
268
+ "language.unsupported": "\u4E0D\u652F\u6301\u8BED\u8A00 {language}\uFF0C\u8BF7\u4F7F\u7528 en \u6216 zh-CN\u3002"
269
+ };
270
+ var cliMessages = {
271
+ en: englishMessages,
272
+ "zh-CN": chineseMessages
273
+ };
274
+ function createCliTranslator(locale) {
275
+ return createTranslator(locale, cliMessages);
276
+ }
277
+ function resolveCliLocale(value, fallback) {
278
+ if (!value) return fallback;
279
+ if (!/^(?:en|en[-_].*|zh|zh[-_].*)$/i.test(value.trim())) {
280
+ throw new FaFaError(
281
+ "CONFIG_INVALID",
282
+ createCliTranslator(fallback)("language.unsupported", { language: value })
283
+ );
284
+ }
285
+ return normalizeLocale(value, fallback);
286
+ }
287
+ function languageFromArgv(argv) {
288
+ const index = argv.findIndex((argument) => argument === "--language");
289
+ if (index >= 0) return argv[index + 1];
290
+ return argv.find((argument) => argument.startsWith("--language="))?.slice("--language=".length);
291
+ }
292
+
293
+ // src/io.ts
294
+ import { CommanderError } from "commander";
295
+ var defaultIo = {
296
+ stdout: (message) => process.stdout.write(message),
297
+ stderr: (message) => process.stderr.write(message),
298
+ readStdin: async () => {
299
+ const chunks = [];
300
+ for await (const chunk of process.stdin) {
301
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
302
+ }
303
+ return Buffer.concat(chunks).toString("utf8");
304
+ }
305
+ };
306
+ function line(value) {
307
+ return value.endsWith("\n") ? value : `${value}
308
+ `;
309
+ }
310
+ function isDisplayExit(error) {
311
+ return error.code === "commander.helpDisplayed" || error.code === "commander.version";
312
+ }
313
+ function exitCode(error) {
314
+ if (error instanceof CommanderError) return isDisplayExit(error) ? 0 : 2;
315
+ if (!(error instanceof FaFaError)) return 1;
316
+ if (error.code === "CHECK_FAILED" || error.code === "ASSET_INVALID" || error.code === "STALE_BUILD") {
317
+ return 3;
318
+ }
319
+ if (error.code === "CREDENTIAL_MISSING") return 4;
320
+ if (error.code === "WECHAT_API_ERROR" || error.code === "DELIVERY_FAILED") return 5;
321
+ if (error.code === "BROWSER_INSTALL_FAILED" || error.code === "EXPORT_FAILED") return 1;
322
+ return 2;
323
+ }
324
+ function errorCode(error) {
325
+ if (error instanceof FaFaError) return error.code;
326
+ if (error instanceof CommanderError) return "CLI_USAGE";
327
+ return "INTERNAL_ERROR";
328
+ }
329
+ function emitDiagnostics(io, diagnostics) {
330
+ for (const diagnostic of diagnostics) {
331
+ const position = diagnostic.location ? ` ${diagnostic.location.file}${diagnostic.location.line ? `:${diagnostic.location.line}` : ""}` : "";
332
+ io.stderr(
333
+ line(`${diagnostic.severity.toUpperCase()} ${diagnostic.code}${position}: ${diagnostic.message}`)
334
+ );
335
+ }
336
+ }
337
+ function success(io, json, command, data, human) {
338
+ io.stdout(json ? line(JSON.stringify({ ok: true, command, data })) : line(human));
339
+ }
340
+ function failure(io, json, error, code) {
341
+ const message = error instanceof Error ? error.message : String(error);
342
+ if (json) {
343
+ io.stdout(
344
+ line(
345
+ JSON.stringify({
346
+ ok: false,
347
+ error: {
348
+ code: errorCode(error),
349
+ message,
350
+ exitCode: code,
351
+ ...error instanceof FaFaError && error.details ? { details: error.details } : {}
352
+ }
353
+ })
354
+ )
355
+ );
356
+ }
357
+ if (!(error instanceof CommanderError && isDisplayExit(error))) {
358
+ io.stderr(line(`${errorCode(error)}: ${message}`));
359
+ }
360
+ }
361
+
362
+ // src/program.ts
363
+ import { Command } from "commander";
364
+
365
+ // package.json
366
+ var package_default = { name: "@elonzh/fafa", version: "0.2.1" };
367
+
368
+ // src/commands/account.ts
369
+ function registerAccountCommands(program, context) {
370
+ const t = context.translate();
371
+ const account = program.command("account").description(t("account.description"));
372
+ const accountAdd = account.command("add").description(t("account.add.description"));
373
+ accountAdd.requiredOption("--id <id>", t("account.id")).requiredOption("--name <name>", t("account.name")).requiredOption("--app-id <id>", t("account.appId")).option("--test", t("account.test")).option("--app-secret-env <name>", t("account.secretEnv"));
374
+ accountAdd.action(async () => {
375
+ const options = accountAdd.opts();
376
+ const secret = options.appSecretEnv ? process.env[options.appSecretEnv] : void 0;
377
+ if (options.appSecretEnv && !secret) {
378
+ throw new FaFaError(
379
+ "CREDENTIAL_MISSING",
380
+ context.translate()("account.emptyEnv", { name: options.appSecretEnv })
381
+ );
382
+ }
383
+ const config = await upsertAccount(
384
+ {
385
+ id: options.id,
386
+ platform: "wechat",
387
+ name: options.name,
388
+ appId: options.appId,
389
+ ...secret ? { appSecret: secret } : {},
390
+ test: Boolean(options.test)
391
+ },
392
+ context.home()
393
+ );
394
+ const publicConfig = toPublicUserConfig(config);
395
+ success(
396
+ context.io,
397
+ context.json(),
398
+ "account.add",
399
+ { account: publicConfig.accounts.find((candidate) => candidate.id === options.id) },
400
+ context.translate()("account.saved", { id: options.id })
401
+ );
402
+ });
403
+ account.command("list").description(t("account.list.description")).action(async () => {
404
+ const config = await loadUserConfig(context.home());
405
+ const publicConfig = toPublicUserConfig(config);
406
+ success(
407
+ context.io,
408
+ context.json(),
409
+ "account.list",
410
+ publicConfig,
411
+ context.translate()("account.count", { count: publicConfig.accounts.length })
412
+ );
413
+ if (!context.json()) {
414
+ for (const item of publicConfig.accounts) {
415
+ context.io.stdout(line(`- ${item.id} ${item.name} ${item.appId}`));
416
+ }
417
+ }
418
+ });
419
+ account.command("remove <id>").description(t("account.remove.description")).action(async (id) => {
420
+ await removeAccount(id, context.home());
421
+ success(
422
+ context.io,
423
+ context.json(),
424
+ "account.remove",
425
+ { id },
426
+ context.translate()("account.removed", { id })
427
+ );
428
+ });
429
+ account.command("probe <id>").description(t("account.probe.description")).action(async (id) => {
430
+ const credential = await resolveWechatCredential(id, context.home());
431
+ const result = await createDefaultWechatClient(context.home()).probeDraftCapability(credential);
432
+ success(
433
+ context.io,
434
+ context.json(),
435
+ "account.probe",
436
+ { accountId: id, ...result },
437
+ context.translate()("account.available", { id })
438
+ );
439
+ });
440
+ }
441
+
442
+ // src/commands/article.ts
443
+ import { mkdir, writeFile } from "fs/promises";
444
+ import { dirname, join, resolve } from "path";
445
+
446
+ // src/article.ts
447
+ async function buildInput(service, article, sourcePath, io, locale) {
448
+ if (article !== "-") return service.build(article);
449
+ const source = await readStdinSource(sourcePath, io, locale);
450
+ return service.buildSource(source.markdown, source.sourcePath);
451
+ }
452
+ async function readStdinSource(sourcePath, io, locale) {
453
+ if (!sourcePath) {
454
+ throw new FaFaError("CONFIG_INVALID", createCliTranslator(locale)("stdin.sourcePath"));
455
+ }
456
+ return { markdown: await io.readStdin(), sourcePath };
457
+ }
458
+ function assertValid(build, locale) {
459
+ if (hasErrors(build.artifact.diagnostics)) {
460
+ throw new FaFaError("CHECK_FAILED", createCliTranslator(locale)("check.failed"), {
461
+ diagnostics: build.artifact.diagnostics
462
+ });
463
+ }
464
+ }
465
+
466
+ // src/context.ts
467
+ function createCliContext(program, io, initialLocale) {
468
+ const globals = () => program.opts();
469
+ const locale = () => resolveCliLocale(globals().language, initialLocale);
470
+ return {
471
+ io,
472
+ globals,
473
+ locale,
474
+ translate: () => createCliTranslator(locale()),
475
+ json: () => Boolean(globals().json),
476
+ home: () => globals().home ?? getFaFaHome(),
477
+ serviceStart: (input) => globals().project ?? input ?? process.cwd()
478
+ };
479
+ }
480
+ async function withService(startPath, home, callback) {
481
+ const { FaFaService: FaFaService2 } = await import("./dist-G3FZO234.js");
482
+ const service = await FaFaService2.open(startPath, home ? { home } : {});
483
+ try {
484
+ return await callback(service);
485
+ } finally {
486
+ service.close();
487
+ }
488
+ }
489
+
490
+ // src/commands/article.ts
491
+ function registerArticleCommands(program, context) {
492
+ const t = context.translate();
493
+ const check = program.command("check <article>").description(t("check.description"));
494
+ check.option("--source-path <path>", t("sourcePath.description"));
495
+ check.action(async (article) => {
496
+ const options = check.opts();
497
+ const start = context.serviceStart(article === "-" ? options.sourcePath : article);
498
+ await withService(start, context.globals().home, async (service) => {
499
+ const build = await buildInput(service, article, options.sourcePath, context.io, context.locale());
500
+ emitDiagnostics(context.io, build.artifact.diagnostics);
501
+ assertValid(build, context.locale());
502
+ success(
503
+ context.io,
504
+ context.json(),
505
+ "check",
506
+ {
507
+ articleId: build.artifact.articleId,
508
+ buildHash: build.artifact.buildHash,
509
+ diagnostics: build.artifact.diagnostics
510
+ },
511
+ context.translate()("check.success", { articleId: build.artifact.articleId })
512
+ );
513
+ });
514
+ });
515
+ const render = program.command("render <article>").description(t("render.description"));
516
+ render.option("--source-path <path>", t("sourcePath.description")).option("--out <path>", t("render.output"));
517
+ render.action(async (article) => {
518
+ const options = render.opts();
519
+ const start = context.serviceStart(article === "-" ? options.sourcePath : article);
520
+ await withService(start, context.globals().home, async (service) => {
521
+ const build = await buildInput(service, article, options.sourcePath, context.io, context.locale());
522
+ emitDiagnostics(context.io, build.artifact.diagnostics);
523
+ assertValid(build, context.locale());
524
+ const output = options.out ? resolve(options.out) : join(build.project.root, ".fafa", "previews", `${safeFilename(build.artifact.articleId)}.html`);
525
+ await mkdir(dirname(output), { recursive: true });
526
+ await writeFile(output, build.previewHtml, "utf8");
527
+ success(
528
+ context.io,
529
+ context.json(),
530
+ "render",
531
+ {
532
+ articleId: build.artifact.articleId,
533
+ buildHash: build.artifact.buildHash,
534
+ output,
535
+ diagnostics: build.artifact.diagnostics
536
+ },
537
+ context.translate()("render.success", { output })
538
+ );
539
+ });
540
+ });
541
+ }
542
+
543
+ // src/commands/browser.ts
544
+ function registerBrowserCommands(program, context, dependencies = {}) {
545
+ const t = context.translate();
546
+ const browser = program.command("browser").description(t("browser.description"));
547
+ const status = browser.command("status").description(t("browser.status.description"));
548
+ status.option("--browser-path <path>", t("export.browserPath"));
549
+ status.action(async () => {
550
+ const options = status.opts();
551
+ const inspect = dependencies.inspectExportBrowser ?? inspectExportBrowser;
552
+ const result = await inspect(
553
+ context.home(),
554
+ options.browserPath ? { browserPath: options.browserPath } : {}
555
+ );
556
+ success(
557
+ context.io,
558
+ context.json(),
559
+ "browser.status",
560
+ result,
561
+ result.status === "ready" ? context.translate()("browser.status.ready", { source: result.source }) : context.translate()("browser.status.missing")
562
+ );
563
+ });
564
+ const install = browser.command("install").description(t("browser.install.description"));
565
+ install.action(async () => {
566
+ const installBrowser = dependencies.installExportBrowser ?? installExportBrowser;
567
+ const result = await installBrowser(context.home());
568
+ success(
569
+ context.io,
570
+ context.json(),
571
+ "browser.install",
572
+ result,
573
+ context.translate()("browser.install.success", { source: result.source })
574
+ );
575
+ });
576
+ }
577
+
578
+ // src/commands/draft.ts
579
+ function registerDraftCommands(program, context) {
580
+ const t = context.translate();
581
+ const draft = program.command("draft").description(t("draft.description"));
582
+ const push = draft.command("push <article>").description(t("draft.push.description"));
583
+ push.option("--account <id>", t("draft.account")).option("--dry-run", t("draft.dryRun"));
584
+ push.action(async (article) => {
585
+ const options = push.opts();
586
+ await withService(context.serviceStart(article), context.globals().home, async (service) => {
587
+ if (options.dryRun) {
588
+ const plan = await service.planDraftPush(article, options.account);
589
+ emitDiagnostics(context.io, plan.diagnostics);
590
+ if (hasErrors(plan.diagnostics)) {
591
+ throw new FaFaError("CHECK_FAILED", context.translate()("draft.planFailed"), {
592
+ diagnostics: plan.diagnostics
593
+ });
594
+ }
595
+ success(
596
+ context.io,
597
+ context.json(),
598
+ "draft.push.dry-run",
599
+ plan,
600
+ context.translate()("draft.planSuccess", {
601
+ action: plan.action,
602
+ uploads: plan.uploads,
603
+ reused: plan.reusedUploads
604
+ })
605
+ );
606
+ return;
607
+ }
608
+ const receipt = await service.pushDraft(article, options.account);
609
+ success(
610
+ context.io,
611
+ context.json(),
612
+ "draft.push",
613
+ receipt,
614
+ context.translate()("draft.pushSuccess", {
615
+ action: receipt.action === "created" ? context.translate()("draft.created") : context.translate()("draft.updated"),
616
+ mediaId: receipt.mediaId
617
+ })
618
+ );
619
+ });
620
+ });
621
+ }
622
+
623
+ // src/commands/export.ts
624
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
625
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
626
+ function parseAppearance(value, context) {
627
+ if (EXPORT_APPEARANCES.includes(value)) {
628
+ return value;
629
+ }
630
+ throw new FaFaError("CONFIG_INVALID", context.translate()("export.appearanceError", { appearance: value }));
631
+ }
632
+ function parseFormat(value, context) {
633
+ if (EXPORT_FORMATS.includes(value)) return value;
634
+ throw new FaFaError("CONFIG_INVALID", context.translate()("export.formatError", { format: value }));
635
+ }
636
+ function parseWidth(value, format, context) {
637
+ if (value === void 0) return void 0;
638
+ if (format !== "png") {
639
+ throw new FaFaError("CONFIG_INVALID", context.translate()("export.widthFormatError"));
640
+ }
641
+ const width = Number(value);
642
+ if (!Number.isInteger(width) || width < 240 || width > 2e3) {
643
+ throw new FaFaError("CONFIG_INVALID", context.translate()("export.widthError"));
644
+ }
645
+ return width;
646
+ }
647
+ function defaultOutput(root, articleId, format, appearance) {
648
+ return join2(root, ".fafa", "exports", exportFilename(articleId, format, appearance));
649
+ }
650
+ function registerExportCommand(program, context, dependencies = {}) {
651
+ const t = context.translate();
652
+ const command = program.command("export <article>").description(t("export.description"));
653
+ command.option("--format <format>", t("export.format"), "html").option("--appearance <appearance>", t("export.appearance"), "day").option("--out <path>", t("export.output")).option("--width <pixels>", t("export.width")).option("--browser-path <path>", t("export.browserPath")).option("--source-path <path>", t("sourcePath.description"));
654
+ command.action(async (article) => {
655
+ const options = command.opts();
656
+ const format = parseFormat(options.format, context);
657
+ const appearance = parseAppearance(options.appearance, context);
658
+ const width = parseWidth(options.width, format, context);
659
+ const exportArticle = dependencies.exportArticle ?? ((service, articleInput, exportOptions2) => service.exportArticle(articleInput, exportOptions2));
660
+ const exportOptions = {
661
+ format,
662
+ appearance,
663
+ ...width === void 0 ? {} : { width },
664
+ ...options.browserPath ? { browserPath: options.browserPath } : {}
665
+ };
666
+ const start = context.serviceStart(article === "-" ? options.sourcePath : article);
667
+ await withService(start, context.globals().home, async (service) => {
668
+ const exported = article === "-" ? await readStdinSource(options.sourcePath, context.io, context.locale()).then(
669
+ (source) => service.exportSource(source.markdown, source.sourcePath, exportOptions)
670
+ ) : await exportArticle(service, article, exportOptions);
671
+ const output = options.out ? resolve2(options.out) : defaultOutput(service.project.root, exported.articleId, format, appearance);
672
+ await mkdir2(dirname2(output), { recursive: true });
673
+ await writeFile2(output, exported.bytes);
674
+ success(
675
+ context.io,
676
+ context.json(),
677
+ "export",
678
+ {
679
+ format: exported.format,
680
+ appearance: exported.appearance,
681
+ output,
682
+ buildHash: exported.buildHash,
683
+ browserSource: exported.browserSource
684
+ },
685
+ context.translate()("export.success", { format: exported.format.toUpperCase(), output })
686
+ );
687
+ });
688
+ });
689
+ }
690
+
691
+ // src/commands/operations.ts
692
+ function registerOperationsCommand(program, context) {
693
+ const t = context.translate();
694
+ const operations = program.command("operations").description(t("operations.description"));
695
+ operations.option("--limit <number>", t("operations.limit"), "50");
696
+ operations.action(async () => {
697
+ const options = operations.opts();
698
+ const limit = Number.parseInt(options.limit, 10);
699
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) {
700
+ throw new FaFaError("CONFIG_INVALID", context.translate()("operations.limitError"));
701
+ }
702
+ const records = await withService(
703
+ context.serviceStart(),
704
+ context.globals().home,
705
+ async (service) => service.state.listOperations(limit)
706
+ );
707
+ success(
708
+ context.io,
709
+ context.json(),
710
+ "operations",
711
+ { operations: records },
712
+ context.translate()("operations.count", { count: records.length })
713
+ );
714
+ if (!context.json()) {
715
+ for (const record of records) {
716
+ context.io.stdout(line(`- ${record.status} ${record.type} ${record.id}`));
717
+ }
718
+ }
719
+ });
720
+ }
721
+
722
+ // src/commands/project.ts
723
+ import { resolve as resolve3 } from "path";
724
+ function registerProjectCommands(program, context) {
725
+ const t = context.translate();
726
+ program.command("init [directory]").description(t("init.description")).action(async (directory = ".") => {
727
+ const project = await createProject(resolve3(directory));
728
+ success(
729
+ context.io,
730
+ context.json(),
731
+ "init",
732
+ { root: project.root, configPath: project.configPath },
733
+ context.translate()("init.success", { root: project.root })
734
+ );
735
+ });
736
+ program.command("articles").description(t("articles.description")).action(async () => {
737
+ const articles = await withService(
738
+ context.serviceStart(),
739
+ context.globals().home,
740
+ (service) => service.listArticles()
741
+ );
742
+ success(
743
+ context.io,
744
+ context.json(),
745
+ "articles",
746
+ { articles },
747
+ context.translate()("articles.count", { count: articles.length })
748
+ );
749
+ if (!context.json()) {
750
+ for (const article of articles) context.io.stdout(line(`- ${article.id} ${article.path}`));
751
+ }
752
+ });
753
+ }
754
+
755
+ // src/commands/style.ts
756
+ function registerStyleCommands(program, context) {
757
+ const t = context.translate();
758
+ const theme = program.command("theme").description(t("theme.description"));
759
+ theme.command("list").description(t("theme.list.description")).action(() => {
760
+ const presets = listWechatThemePresets(context.locale());
761
+ success(
762
+ context.io,
763
+ context.json(),
764
+ "theme.list",
765
+ { presets },
766
+ context.translate()("theme.list.count", { count: presets.length })
767
+ );
768
+ if (!context.json()) {
769
+ for (const preset of presets) {
770
+ context.io.stdout(line(`- ${preset.id} ${preset.name} ${preset.description}`));
771
+ }
772
+ }
773
+ });
774
+ const themeSet = theme.command("set").description(t("theme.set.description"));
775
+ themeSet.option("--preset <id>", t("theme.set.preset")).option("--file <path>", t("theme.set.file"));
776
+ themeSet.action(async () => {
777
+ const options = themeSet.opts();
778
+ if (Boolean(options.preset) === Boolean(options.file)) {
779
+ throw new FaFaError("CONFIG_INVALID", context.translate()("theme.set.choice"));
780
+ }
781
+ const project = await loadProject(context.serviceStart());
782
+ if (options.preset && !listWechatThemePresets(context.locale()).some(({ id }) => id === options.preset)) {
783
+ throw new FaFaError("CONFIG_INVALID", context.translate()("theme.set.unknown", { id: options.preset }));
784
+ }
785
+ const selected = await resolveWechatTheme(
786
+ project.root,
787
+ options.preset ?? options.file,
788
+ context.locale()
789
+ );
790
+ const updated = await setProjectDefaultTheme(project.root, selected.reference);
791
+ success(
792
+ context.io,
793
+ context.json(),
794
+ "theme.set",
795
+ {
796
+ reference: selected.reference,
797
+ source: selected.source,
798
+ name: selected.name,
799
+ configPath: updated.configPath
800
+ },
801
+ context.translate()("theme.set.success", { reference: selected.reference })
802
+ );
803
+ });
804
+ const codeTheme = program.command("code-theme").description(t("codeTheme.description"));
805
+ codeTheme.command("list").description(t("codeTheme.list.description")).action(() => {
806
+ const presets = listCodeHighlightThemes(context.locale());
807
+ success(
808
+ context.io,
809
+ context.json(),
810
+ "code-theme.list",
811
+ { presets },
812
+ context.translate()("codeTheme.list.count", { count: presets.length })
813
+ );
814
+ if (!context.json()) {
815
+ for (const preset of presets) {
816
+ context.io.stdout(line(`- ${preset.id} ${preset.name} ${preset.description}`));
817
+ }
818
+ }
819
+ });
820
+ const codeThemeSet = codeTheme.command("set").description(t("codeTheme.set.description")).requiredOption("--preset <id>", t("codeTheme.set.preset"));
821
+ codeThemeSet.action(async () => {
822
+ const { preset } = codeThemeSet.opts();
823
+ const selected = resolveCodeHighlightTheme(preset, context.locale());
824
+ const project = await loadProject(context.serviceStart());
825
+ const updated = await setProjectDefaultCodeTheme(project.root, selected.id);
826
+ success(
827
+ context.io,
828
+ context.json(),
829
+ "code-theme.set",
830
+ {
831
+ reference: selected.id,
832
+ name: selected.name,
833
+ configPath: updated.configPath
834
+ },
835
+ context.translate()("codeTheme.set.success", { reference: selected.id })
836
+ );
837
+ });
838
+ const imageCaption = program.command("image-caption").description(t("caption.description"));
839
+ imageCaption.command("list").description(t("caption.list.description")).action(() => {
840
+ const modes = listImageCaptionModes(context.locale());
841
+ success(
842
+ context.io,
843
+ context.json(),
844
+ "image-caption.list",
845
+ { modes },
846
+ context.translate()("caption.list.count", { count: modes.length })
847
+ );
848
+ if (!context.json()) {
849
+ for (const mode of modes) {
850
+ context.io.stdout(line(`- ${mode.id} ${mode.name} ${mode.description}`));
851
+ }
852
+ }
853
+ });
854
+ const imageCaptionSet = imageCaption.command("set").description(t("caption.set.description")).requiredOption("--mode <id>", t("caption.set.mode"));
855
+ imageCaptionSet.action(async () => {
856
+ const { mode } = imageCaptionSet.opts();
857
+ const selected = resolveImageCaptionMode(mode);
858
+ const project = await loadProject(context.serviceStart());
859
+ const updated = await setProjectDefaultImageCaption(project.root, selected);
860
+ const summary = listImageCaptionModes(context.locale()).find(({ id }) => id === selected);
861
+ success(
862
+ context.io,
863
+ context.json(),
864
+ "image-caption.set",
865
+ {
866
+ reference: selected,
867
+ name: summary?.name ?? selected,
868
+ configPath: updated.configPath
869
+ },
870
+ context.translate()("caption.set.success", { reference: selected })
871
+ );
872
+ });
873
+ }
874
+
875
+ // src/commands/workbench.ts
876
+ import { execFile as execFile2 } from "child_process";
877
+ import { access as access6 } from "fs/promises";
878
+ import { dirname as dirname4, join as join6, resolve as resolve5 } from "path";
879
+ import { fileURLToPath } from "url";
880
+ import { promisify as promisify2 } from "util";
881
+
882
+ // ../../packages/web-server/dist/index.js
883
+ import { access, mkdir as mkdir3, readFile, rename, rm, writeFile as writeFile3 } from "fs/promises";
884
+ import { join as join3 } from "path";
885
+ import { access as access2, readdir, realpath, stat } from "fs/promises";
886
+ import { homedir } from "os";
887
+ import { dirname as dirname3, join as join22, resolve as resolve4 } from "path";
888
+ import { watch } from "fs";
889
+ import { access as access3, mkdir as mkdir22, readdir as readdir2, stat as stat2, writeFile as writeFile22 } from "fs/promises";
890
+ import { dirname as dirname22, extname, join as join32, relative, resolve as resolve22 } from "path";
891
+ import { access as access4, readFile as readFile2, stat as stat3 } from "fs/promises";
892
+ import { createServer } from "http";
893
+ import { extname as extname2, join as join4, normalize, relative as relative2, resolve as resolve32 } from "path";
894
+ import { execFile } from "child_process";
895
+ import { access as access5, mkdir as mkdir32, readFile as readFile3, rm as rm2, writeFile as writeFile32 } from "fs/promises";
896
+ import { homedir as homedir2 } from "os";
897
+ import { dirname as dirname32, join as join5, resolve as resolve42 } from "path";
898
+ import { promisify } from "util";
899
+ var DEFAULT_WEB_HOST = "127.0.0.1";
900
+ var DEFAULT_WEB_PORT = 47890;
901
+ var CSRF_HEADER_NAME = "x-fafa-requested-with";
902
+ var CSRF_HEADER_VALUE = "web";
903
+ var DAEMON_STATE_FILENAME = "daemon.json";
904
+ var WATCH_DEBOUNCE_MS = 150;
905
+ var PREVIEW_CACHE_LIMIT = 20;
906
+ async function fileExists(path) {
907
+ try {
908
+ await access(path);
909
+ return true;
910
+ } catch {
911
+ return false;
912
+ }
913
+ }
914
+ function daemonStatePath(home = getFaFaHome()) {
915
+ return join3(home, DAEMON_STATE_FILENAME);
916
+ }
917
+ async function writeDaemonState(record, home = getFaFaHome()) {
918
+ await mkdir3(home, { recursive: true, mode: 448 });
919
+ const target = daemonStatePath(home);
920
+ const tempPath = `${target}.${process.pid}.${Date.now()}.tmp`;
921
+ await writeFile3(tempPath, `${JSON.stringify(record, null, 2)}
922
+ `, { mode: 384 });
923
+ await rename(tempPath, target);
924
+ }
925
+ async function readDaemonState(home = getFaFaHome()) {
926
+ const target = daemonStatePath(home);
927
+ if (!await fileExists(target)) return null;
928
+ try {
929
+ const parsed = JSON.parse(await readFile(target, "utf8"));
930
+ if (parsed.version !== 1 || typeof parsed.pid !== "number" || typeof parsed.host !== "string" || typeof parsed.port !== "number") {
931
+ return null;
932
+ }
933
+ return parsed;
934
+ } catch {
935
+ return null;
936
+ }
937
+ }
938
+ async function clearDaemonState(expectedPid, home = getFaFaHome()) {
939
+ const existing = await readDaemonState(home);
940
+ if (expectedPid !== void 0 && existing && existing.pid !== expectedPid) {
941
+ return;
942
+ }
943
+ await rm(daemonStatePath(home), { force: true }).catch(() => {
944
+ });
945
+ }
946
+ function isProcessRunning(pid) {
947
+ if (!Number.isInteger(pid) || pid <= 0) return false;
948
+ try {
949
+ process.kill(pid, 0);
950
+ return true;
951
+ } catch (error) {
952
+ return error.code === "EPERM";
953
+ }
954
+ }
955
+ async function probeRunningDaemon(home = getFaFaHome()) {
956
+ const state = await readDaemonState(home);
957
+ if (!state) return { running: false, state: null };
958
+ if (!isProcessRunning(state.pid)) {
959
+ return { running: false, state };
960
+ }
961
+ const url = `http://${state.host}:${state.port}`;
962
+ try {
963
+ const response = await fetch(`${url}/api/health`, {
964
+ signal: AbortSignal.timeout(1500)
965
+ });
966
+ if (!response.ok) return { running: false, state };
967
+ const body = await response.json();
968
+ if (body.ok && body.data?.pid === state.pid) {
969
+ return { running: true, state, url };
970
+ }
971
+ return { running: false, state };
972
+ } catch {
973
+ return { running: false, state };
974
+ }
975
+ }
976
+ async function pathExists(path) {
977
+ try {
978
+ await access2(path);
979
+ return true;
980
+ } catch {
981
+ return false;
982
+ }
983
+ }
984
+ async function browseLocalDirectories(requestedPath, options = {}) {
985
+ const homePath = await realpath(homedir()).catch(() => resolve4(homedir()));
986
+ const target = requestedPath?.trim() ? resolve4(requestedPath.trim()) : homePath;
987
+ let canonical;
988
+ try {
989
+ const stats = await stat(target);
990
+ if (!stats.isDirectory()) {
991
+ throw new FaFaError("CONFIG_INVALID", `Not a directory: ${target}`);
992
+ }
993
+ canonical = await realpath(target);
994
+ } catch (error) {
995
+ if (error instanceof FaFaError) throw error;
996
+ throw new FaFaError("CONFIG_INVALID", `Directory not accessible: ${target}`);
997
+ }
998
+ const parentCandidate = dirname3(canonical);
999
+ const parentPath = parentCandidate !== canonical ? parentCandidate : null;
1000
+ const hasConfig = await pathExists(join22(canonical, CONFIG_FILENAME));
1001
+ const dirents = await readdir(canonical, { withFileTypes: true }).catch(() => []);
1002
+ const subdirs = dirents.filter((entry) => entry.isDirectory()).filter((entry) => options.includeHidden || !entry.name.startsWith(".")).sort((left, right) => left.name.localeCompare(right.name));
1003
+ const entries = await Promise.all(
1004
+ subdirs.map(async (entry) => {
1005
+ const fullPath = join22(canonical, entry.name);
1006
+ return {
1007
+ name: entry.name,
1008
+ path: fullPath,
1009
+ hasConfig: await pathExists(join22(fullPath, CONFIG_FILENAME))
1010
+ };
1011
+ })
1012
+ );
1013
+ return {
1014
+ currentPath: canonical,
1015
+ parentPath,
1016
+ homePath,
1017
+ hasConfig,
1018
+ entries
1019
+ };
1020
+ }
1021
+ function normalizeDiagnostics(diagnostics) {
1022
+ return diagnostics.map((item) => ({
1023
+ code: item.code,
1024
+ severity: item.severity,
1025
+ message: item.message,
1026
+ ...item.location?.line !== void 0 ? { line: item.location.line } : {}
1027
+ }));
1028
+ }
1029
+ function mimeTypeForFormat(format) {
1030
+ if (format === "html") return "text/html; charset=utf-8";
1031
+ if (format === "pdf") return "application/pdf";
1032
+ return "image/png";
1033
+ }
1034
+ async function fileSignature(path) {
1035
+ try {
1036
+ const info = await stat2(path);
1037
+ return `${info.mtimeMs}:${info.size}`;
1038
+ } catch {
1039
+ return "missing";
1040
+ }
1041
+ }
1042
+ async function pathExists2(path) {
1043
+ try {
1044
+ await access3(path);
1045
+ return true;
1046
+ } catch {
1047
+ return false;
1048
+ }
1049
+ }
1050
+ async function collectDirectoriesForFallbackWatch(root, baseDir, filter, out) {
1051
+ out.push(baseDir);
1052
+ const entries = await readdir2(baseDir, { withFileTypes: true }).catch(() => []);
1053
+ for (const entry of entries) {
1054
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
1055
+ const child = join32(baseDir, entry.name);
1056
+ if (filter.ignores(relative(root, child), true)) continue;
1057
+ await collectDirectoriesForFallbackWatch(root, child, filter, out);
1058
+ }
1059
+ }
1060
+ var LibraryRuntime = class {
1061
+ constructor(entry, home, dependencies = {}) {
1062
+ this.entry = entry;
1063
+ this.home = home;
1064
+ this.dependencies = dependencies;
1065
+ }
1066
+ entry;
1067
+ home;
1068
+ dependencies;
1069
+ service = null;
1070
+ openingPromise = null;
1071
+ articlesCache = null;
1072
+ previewCache = /* @__PURE__ */ new Map();
1073
+ listeners = /* @__PURE__ */ new Set();
1074
+ watchers = [];
1075
+ watchFilter = null;
1076
+ debounceTimer = null;
1077
+ pendingChangedPaths = /* @__PURE__ */ new Set();
1078
+ pendingConfigChanged = false;
1079
+ watching = false;
1080
+ createWechat() {
1081
+ return this.dependencies.createWechatClient ? this.dependencies.createWechatClient(this.home) : createDefaultWechatClient(this.home);
1082
+ }
1083
+ async ensureService() {
1084
+ if (this.service) return this.service;
1085
+ if (!this.openingPromise) {
1086
+ this.openingPromise = (async () => {
1087
+ const options = {
1088
+ home: this.home,
1089
+ wechat: this.createWechat()
1090
+ };
1091
+ const opened = this.dependencies.openService ? await this.dependencies.openService(this.entry.root, options) : await FaFaService.open(this.entry.root, options);
1092
+ this.service = opened;
1093
+ return opened;
1094
+ })().finally(() => {
1095
+ this.openingPromise = null;
1096
+ });
1097
+ }
1098
+ return this.openingPromise;
1099
+ }
1100
+ invalidateAllCaches() {
1101
+ this.articlesCache = null;
1102
+ this.previewCache.clear();
1103
+ }
1104
+ invalidateService() {
1105
+ this.invalidateAllCaches();
1106
+ if (this.service) {
1107
+ this.service.close();
1108
+ this.service = null;
1109
+ }
1110
+ }
1111
+ subscribe(listener) {
1112
+ this.listeners.add(listener);
1113
+ if (!this.watching) {
1114
+ void this.ensureWatching();
1115
+ }
1116
+ return () => {
1117
+ this.listeners.delete(listener);
1118
+ if (this.listeners.size === 0) {
1119
+ this.stopWatching();
1120
+ }
1121
+ };
1122
+ }
1123
+ emit(event) {
1124
+ for (const listener of this.listeners) {
1125
+ listener(event);
1126
+ }
1127
+ }
1128
+ async ensureWatching() {
1129
+ if (this.watching) return;
1130
+ this.watching = true;
1131
+ try {
1132
+ const service = await this.ensureService();
1133
+ this.watchFilter = await createContentDiscoveryFilter(this.entry.root);
1134
+ const rootsToWatch = /* @__PURE__ */ new Set([this.entry.root, ...service.project.contentRoots]);
1135
+ const supportsRecursive = process.platform === "darwin" || process.platform === "win32";
1136
+ for (const watchRoot of rootsToWatch) {
1137
+ if (supportsRecursive) {
1138
+ try {
1139
+ const watcher = watch(watchRoot, { recursive: true }, (_eventType, filename) => {
1140
+ this.handleRawWatchEvent(watchRoot, filename);
1141
+ });
1142
+ watcher.on("error", () => {
1143
+ });
1144
+ this.watchers.push(watcher);
1145
+ continue;
1146
+ } catch {
1147
+ }
1148
+ }
1149
+ const dirs = [];
1150
+ await collectDirectoriesForFallbackWatch(this.entry.root, watchRoot, this.watchFilter, dirs);
1151
+ for (const dir of dirs) {
1152
+ try {
1153
+ const watcher = watch(dir, (_eventType, filename) => {
1154
+ this.handleRawWatchEvent(dir, filename);
1155
+ });
1156
+ watcher.on("error", () => {
1157
+ });
1158
+ this.watchers.push(watcher);
1159
+ } catch {
1160
+ }
1161
+ }
1162
+ }
1163
+ } catch {
1164
+ this.watching = false;
1165
+ }
1166
+ }
1167
+ handleRawWatchEvent(baseDir, filename) {
1168
+ const rawName = typeof filename === "string" ? filename : filename?.toString("utf8");
1169
+ const fullPath = rawName ? resolve22(baseDir, rawName) : baseDir;
1170
+ const relPath = relative(this.entry.root, fullPath).replaceAll("\\", "/");
1171
+ if (!relPath || relPath.startsWith("..")) return;
1172
+ if (relPath === CONFIG_FILENAME || relPath === ".gitignore") {
1173
+ this.pendingConfigChanged = true;
1174
+ this.scheduleWatchFlush();
1175
+ return;
1176
+ }
1177
+ if (this.watchFilter?.ignores(relPath, false)) {
1178
+ return;
1179
+ }
1180
+ const segments = relPath.split("/");
1181
+ if (segments.some((segment) => segment.startsWith("."))) {
1182
+ return;
1183
+ }
1184
+ this.pendingChangedPaths.add(relPath);
1185
+ this.scheduleWatchFlush();
1186
+ }
1187
+ scheduleWatchFlush() {
1188
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
1189
+ this.debounceTimer = setTimeout(() => {
1190
+ this.debounceTimer = null;
1191
+ this.flushWatchEvents();
1192
+ }, WATCH_DEBOUNCE_MS);
1193
+ }
1194
+ flushWatchEvents() {
1195
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1196
+ const configChanged = this.pendingConfigChanged;
1197
+ const paths = [...this.pendingChangedPaths];
1198
+ this.pendingConfigChanged = false;
1199
+ this.pendingChangedPaths.clear();
1200
+ if (configChanged) {
1201
+ this.invalidateService();
1202
+ this.stopWatching();
1203
+ if (this.listeners.size > 0) {
1204
+ void this.ensureWatching();
1205
+ }
1206
+ this.emit({
1207
+ type: "config.changed",
1208
+ libraryId: this.entry.id,
1209
+ timestamp
1210
+ });
1211
+ return;
1212
+ }
1213
+ if (paths.length === 0) return;
1214
+ const hasMarkdown = paths.some((item) => extname(item).toLowerCase() === ".md");
1215
+ const hasNonArticleAssetOrCss = paths.some((item) => extname(item).toLowerCase() !== ".md");
1216
+ const knownArticlePaths = new Set((this.articlesCache ?? []).map((article) => article.path));
1217
+ const hasSharedMarkdownChange = hasMarkdown && paths.some((item) => extname(item).toLowerCase() === ".md" && !knownArticlePaths.has(item));
1218
+ if (hasMarkdown) {
1219
+ this.articlesCache = null;
1220
+ }
1221
+ const invalidateAll = hasNonArticleAssetOrCss || hasSharedMarkdownChange;
1222
+ if (invalidateAll) {
1223
+ this.previewCache.clear();
1224
+ } else {
1225
+ for (const changedPath of paths) {
1226
+ this.previewCache.delete(changedPath);
1227
+ }
1228
+ }
1229
+ if (hasMarkdown) {
1230
+ this.emit({
1231
+ type: "articles.changed",
1232
+ libraryId: this.entry.id,
1233
+ paths,
1234
+ timestamp
1235
+ });
1236
+ }
1237
+ this.emit({
1238
+ type: "article.updated",
1239
+ libraryId: this.entry.id,
1240
+ paths,
1241
+ invalidateAll,
1242
+ timestamp
1243
+ });
1244
+ }
1245
+ stopWatching() {
1246
+ this.watching = false;
1247
+ if (this.debounceTimer) {
1248
+ clearTimeout(this.debounceTimer);
1249
+ this.debounceTimer = null;
1250
+ }
1251
+ for (const watcher of this.watchers) {
1252
+ watcher.close();
1253
+ }
1254
+ this.watchers = [];
1255
+ this.pendingChangedPaths.clear();
1256
+ this.pendingConfigChanged = false;
1257
+ }
1258
+ close() {
1259
+ this.stopWatching();
1260
+ this.listeners.clear();
1261
+ this.invalidateService();
1262
+ }
1263
+ async getSnapshot() {
1264
+ const service = await this.ensureService();
1265
+ if (!this.articlesCache) {
1266
+ this.articlesCache = await service.listArticles();
1267
+ }
1268
+ const librarySummary = {
1269
+ ...this.entry,
1270
+ exists: true,
1271
+ hasConfig: await pathExists2(join32(this.entry.root, CONFIG_FILENAME))
1272
+ };
1273
+ return {
1274
+ library: librarySummary,
1275
+ project: {
1276
+ contentDirs: service.project.config.contentDirs,
1277
+ theme: service.project.config.defaults.theme,
1278
+ codeTheme: service.project.config.defaults.codeTheme,
1279
+ imageCaption: service.project.config.defaults.imageCaption,
1280
+ ...service.project.config.defaults.author ? { author: service.project.config.defaults.author } : {}
1281
+ },
1282
+ articles: this.articlesCache
1283
+ };
1284
+ }
1285
+ async computePreviewSignature(articlePath, locale) {
1286
+ const fullArticlePath = resolveInsideProject(this.entry.root, articlePath);
1287
+ const [articleSig, configSig] = await Promise.all([
1288
+ fileSignature(fullArticlePath),
1289
+ fileSignature(join32(this.entry.root, CONFIG_FILENAME))
1290
+ ]);
1291
+ return `${locale}|${articleSig}|${configSig}`;
1292
+ }
1293
+ async buildPreview(articlePath, locale, options = {}) {
1294
+ const signature = await this.computePreviewSignature(articlePath, locale);
1295
+ if (!options.bypassCache) {
1296
+ const cached = this.previewCache.get(articlePath);
1297
+ if (cached && cached.signature === signature && cached.locale === locale) {
1298
+ return { ...cached.payload, cached: true };
1299
+ }
1300
+ }
1301
+ const service = await this.ensureService();
1302
+ const build = await service.build(articlePath);
1303
+ const presetName = listWechatThemePresets(locale).find(
1304
+ (preset) => preset.id === build.theme.reference
1305
+ )?.name;
1306
+ const rawFrontmatter = build.parsed.manuscript.frontmatter;
1307
+ const overrides = {
1308
+ ...typeof rawFrontmatter.theme === "string" && rawFrontmatter.theme.trim() ? { theme: rawFrontmatter.theme.trim() } : {},
1309
+ ...typeof rawFrontmatter.codeTheme === "string" && rawFrontmatter.codeTheme.trim() ? { codeTheme: rawFrontmatter.codeTheme.trim() } : {},
1310
+ ...typeof rawFrontmatter.imageCaption === "string" && rawFrontmatter.imageCaption.trim() ? { imageCaption: rawFrontmatter.imageCaption.trim() } : {}
1311
+ };
1312
+ const payload = {
1313
+ libraryId: this.entry.id,
1314
+ articlePath,
1315
+ articleId: build.parsed.manuscript.id,
1316
+ title: build.metadata.title,
1317
+ ...build.metadata.author ? { author: build.metadata.author } : {},
1318
+ ...build.metadata.summary ? { summary: build.metadata.summary } : {},
1319
+ buildHash: build.artifact.buildHash,
1320
+ theme: {
1321
+ reference: build.theme.reference,
1322
+ name: presetName ?? build.theme.name,
1323
+ description: build.theme.description
1324
+ },
1325
+ codeTheme: {
1326
+ id: build.codeTheme.id,
1327
+ name: build.codeTheme.name
1328
+ },
1329
+ imageCaption: build.metadata.imageCaption ?? service.project.config.defaults.imageCaption,
1330
+ overrides,
1331
+ diagnostics: normalizeDiagnostics(build.artifact.diagnostics),
1332
+ previewHtml: build.previewHtml,
1333
+ wechatHtml: build.artifact.html,
1334
+ renderedAt: (/* @__PURE__ */ new Date()).toISOString(),
1335
+ cached: false
1336
+ };
1337
+ this.previewCache.delete(articlePath);
1338
+ this.previewCache.set(articlePath, { signature, locale, payload });
1339
+ while (this.previewCache.size > PREVIEW_CACHE_LIMIT) {
1340
+ const oldestKey = this.previewCache.keys().next().value;
1341
+ if (oldestKey) this.previewCache.delete(oldestKey);
1342
+ }
1343
+ return payload;
1344
+ }
1345
+ async checkArticle(articlePath) {
1346
+ const service = await this.ensureService();
1347
+ const build = await service.build(articlePath);
1348
+ const diagnostics = normalizeDiagnostics(build.artifact.diagnostics);
1349
+ return {
1350
+ libraryId: this.entry.id,
1351
+ articlePath,
1352
+ articleId: build.parsed.manuscript.id,
1353
+ title: build.metadata.title,
1354
+ buildHash: build.artifact.buildHash,
1355
+ ok: !hasErrors(build.artifact.diagnostics),
1356
+ errorCount: diagnostics.filter((item) => item.severity === "error").length,
1357
+ warningCount: diagnostics.filter((item) => item.severity === "warning").length,
1358
+ diagnostics
1359
+ };
1360
+ }
1361
+ async setProjectDefaults(input) {
1362
+ if (input.theme !== void 0) {
1363
+ const resolved = await resolveWechatTheme(this.entry.root, input.theme, input.locale);
1364
+ await setProjectDefaultTheme(this.entry.root, resolved.reference);
1365
+ }
1366
+ if (input.codeTheme !== void 0) {
1367
+ const resolved = resolveCodeHighlightTheme(input.codeTheme, input.locale);
1368
+ await setProjectDefaultCodeTheme(this.entry.root, resolved.id);
1369
+ }
1370
+ if (input.imageCaption !== void 0) {
1371
+ const resolved = resolveImageCaptionMode(input.imageCaption);
1372
+ await setProjectDefaultImageCaption(this.entry.root, resolved);
1373
+ }
1374
+ this.invalidateService();
1375
+ this.emit({
1376
+ type: "config.changed",
1377
+ libraryId: this.entry.id,
1378
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1379
+ });
1380
+ return this.getSnapshot();
1381
+ }
1382
+ async setArticleOption(input) {
1383
+ let normalizedValue = null;
1384
+ if (input.value !== null) {
1385
+ if (input.field === "theme") {
1386
+ normalizedValue = (await resolveWechatTheme(this.entry.root, input.value, input.locale)).reference;
1387
+ } else if (input.field === "codeTheme") {
1388
+ normalizedValue = resolveCodeHighlightTheme(input.value, input.locale).id;
1389
+ } else {
1390
+ normalizedValue = resolveImageCaptionMode(input.value);
1391
+ }
1392
+ }
1393
+ await updateArticleFrontmatterFile(this.entry.root, input.articlePath, input.field, normalizedValue);
1394
+ this.previewCache.delete(input.articlePath);
1395
+ const preview = await this.buildPreview(input.articlePath, input.locale, { bypassCache: true });
1396
+ this.emit({
1397
+ type: "article.updated",
1398
+ libraryId: this.entry.id,
1399
+ paths: [input.articlePath],
1400
+ invalidateAll: false,
1401
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1402
+ });
1403
+ return preview;
1404
+ }
1405
+ async exportArticle(input) {
1406
+ const service = await this.ensureService();
1407
+ try {
1408
+ const exported = await service.exportArticle(input.articlePath, {
1409
+ format: input.format,
1410
+ appearance: input.appearance,
1411
+ ...input.browserPath ? { browserPath: input.browserPath } : {}
1412
+ });
1413
+ const filename = exportFilename(exported.articleId, input.format, input.appearance);
1414
+ const mimeType = mimeTypeForFormat(input.format);
1415
+ let outputPath;
1416
+ if (input.saveToDisk) {
1417
+ const resolvedArticle = resolveInsideProject(this.entry.root, input.articlePath);
1418
+ outputPath = join32(dirname22(resolvedArticle), filename);
1419
+ await mkdir22(dirname22(outputPath), { recursive: true });
1420
+ await writeFile22(outputPath, exported.bytes);
1421
+ }
1422
+ return {
1423
+ status: "exported",
1424
+ format: input.format,
1425
+ appearance: input.appearance,
1426
+ filename,
1427
+ ...outputPath ? { outputPath } : {},
1428
+ mimeType,
1429
+ bytesLength: exported.bytes.byteLength,
1430
+ buildHash: exported.buildHash,
1431
+ contentBase64: Buffer.from(exported.bytes).toString("base64")
1432
+ };
1433
+ } catch (error) {
1434
+ if (error instanceof FaFaError && error.code === "BROWSER_NOT_FOUND") {
1435
+ return {
1436
+ status: "missingBrowser",
1437
+ format: input.format,
1438
+ appearance: input.appearance,
1439
+ errorCode: error.code,
1440
+ errorMessage: error.message
1441
+ };
1442
+ }
1443
+ throw error;
1444
+ }
1445
+ }
1446
+ async planDraft(input) {
1447
+ const service = await this.ensureService();
1448
+ const [plan, userConfig] = await Promise.all([
1449
+ service.planDraftPush(input.articlePath, input.accountId),
1450
+ loadUserConfig(this.home)
1451
+ ]);
1452
+ const accountName = userConfig.accounts.find((account) => account.id === plan.accountId)?.name ?? plan.accountId;
1453
+ return {
1454
+ libraryId: this.entry.id,
1455
+ articlePath: input.articlePath,
1456
+ articleId: plan.articleId,
1457
+ accountId: plan.accountId,
1458
+ accountName,
1459
+ buildHash: plan.buildHash,
1460
+ action: plan.action,
1461
+ uploads: plan.uploads,
1462
+ reusedUploads: plan.reusedUploads,
1463
+ diagnostics: normalizeDiagnostics(plan.diagnostics)
1464
+ };
1465
+ }
1466
+ async pushDraft(input) {
1467
+ if (!input.confirmed || !input.expectedBuildHash.trim()) {
1468
+ throw new FaFaError(
1469
+ "CHECK_FAILED",
1470
+ "Explicit confirmation and expectedBuildHash are required before pushing a WeChat draft."
1471
+ );
1472
+ }
1473
+ const service = await this.ensureService();
1474
+ const freshPlan = await service.planDraftPush(input.articlePath, input.accountId);
1475
+ if (freshPlan.buildHash !== input.expectedBuildHash) {
1476
+ throw new FaFaError(
1477
+ "STALE_BUILD",
1478
+ "Source content or assets changed after preflight. Run preflight again before pushing."
1479
+ );
1480
+ }
1481
+ const receipt = await service.pushDraft(input.articlePath, freshPlan.accountId);
1482
+ return {
1483
+ operationId: receipt.operationId,
1484
+ articleId: receipt.articleId,
1485
+ accountId: receipt.accountId,
1486
+ mediaId: receipt.mediaId,
1487
+ buildHash: receipt.buildHash,
1488
+ action: receipt.action,
1489
+ deliveredAt: receipt.deliveredAt
1490
+ };
1491
+ }
1492
+ async listOperations(limit = 50) {
1493
+ const service = await this.ensureService();
1494
+ return service.state.listOperations(Math.min(500, Math.max(1, Math.trunc(limit))));
1495
+ }
1496
+ };
1497
+ async function inspectBrowserForWeb(home, dependencies, browserPath) {
1498
+ return dependencies.inspectBrowser ? dependencies.inspectBrowser(home, browserPath) : inspectExportBrowser(home, browserPath ? { browserPath } : {});
1499
+ }
1500
+ async function installBrowserForWeb(home, dependencies) {
1501
+ return dependencies.installBrowser ? dependencies.installBrowser(home) : installExportBrowser(home);
1502
+ }
1503
+ function isValidHostHeader(hostHeader, port) {
1504
+ if (!hostHeader) return false;
1505
+ const normalized = hostHeader.trim().toLowerCase();
1506
+ const allowed = /* @__PURE__ */ new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
1507
+ if (port === 80) {
1508
+ allowed.add("127.0.0.1");
1509
+ allowed.add("localhost");
1510
+ }
1511
+ return allowed.has(normalized);
1512
+ }
1513
+ function isValidOriginHeader(originHeader, port) {
1514
+ if (!originHeader) return true;
1515
+ const normalized = originHeader.trim().toLowerCase();
1516
+ const allowed = /* @__PURE__ */ new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]);
1517
+ if (port === 80) {
1518
+ allowed.add("http://127.0.0.1");
1519
+ allowed.add("http://localhost");
1520
+ }
1521
+ return allowed.has(normalized);
1522
+ }
1523
+ function isValidSameSiteHeaders(request, port) {
1524
+ const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
1525
+ if (!isValidOriginHeader(origin, port)) return false;
1526
+ const secFetchSite = typeof request.headers["sec-fetch-site"] === "string" ? request.headers["sec-fetch-site"].trim().toLowerCase() : void 0;
1527
+ if (secFetchSite && secFetchSite !== "same-origin" && secFetchSite !== "none") {
1528
+ return false;
1529
+ }
1530
+ return true;
1531
+ }
1532
+ function isValidWriteSecurityHeaders(request, port) {
1533
+ if (!isValidSameSiteHeaders(request, port)) return false;
1534
+ const csrfHeader = request.headers[CSRF_HEADER_NAME];
1535
+ return typeof csrfHeader === "string" && csrfHeader.trim().toLowerCase() === CSRF_HEADER_VALUE;
1536
+ }
1537
+ var MAX_JSON_BODY_BYTES = 2 * 1024 * 1024;
1538
+ var STATIC_MIME_TYPES = {
1539
+ ".html": "text/html; charset=utf-8",
1540
+ ".js": "application/javascript; charset=utf-8",
1541
+ ".mjs": "application/javascript; charset=utf-8",
1542
+ ".css": "text/css; charset=utf-8",
1543
+ ".json": "application/json; charset=utf-8",
1544
+ ".webmanifest": "application/manifest+json; charset=utf-8",
1545
+ ".svg": "image/svg+xml",
1546
+ ".png": "image/png",
1547
+ ".jpg": "image/jpeg",
1548
+ ".jpeg": "image/jpeg",
1549
+ ".webp": "image/webp",
1550
+ ".ico": "image/x-icon",
1551
+ ".woff2": "font/woff2"
1552
+ };
1553
+ function isWriteMethod(method) {
1554
+ return method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";
1555
+ }
1556
+ function sendJson(response, statusCode, body, extraHeaders = {}) {
1557
+ const payload = JSON.stringify(body);
1558
+ response.writeHead(statusCode, {
1559
+ "content-type": "application/json; charset=utf-8",
1560
+ "cache-control": "no-store",
1561
+ "x-content-type-options": "nosniff",
1562
+ ...extraHeaders
1563
+ });
1564
+ response.end(payload);
1565
+ }
1566
+ function sendError(response, error) {
1567
+ if (error instanceof FaFaError) {
1568
+ const status = error.code === "PROJECT_NOT_FOUND" || error.code === "ARTICLE_NOT_FOUND" ? 404 : error.code === "STALE_BUILD" ? 409 : error.code === "CONFIG_INVALID" || error.code === "CHECK_FAILED" ? 400 : error.code === "CREDENTIAL_MISSING" ? 400 : 500;
1569
+ sendJson(response, status, {
1570
+ ok: false,
1571
+ error: {
1572
+ code: error.code,
1573
+ message: error.message,
1574
+ ...error.details ? { details: error.details } : {}
1575
+ }
1576
+ });
1577
+ return;
1578
+ }
1579
+ const message = error instanceof Error ? error.message : String(error);
1580
+ sendJson(response, 500, {
1581
+ ok: false,
1582
+ error: {
1583
+ code: "INTERNAL_ERROR",
1584
+ message
1585
+ }
1586
+ });
1587
+ }
1588
+ async function readJsonBody(request) {
1589
+ const chunks = [];
1590
+ let total = 0;
1591
+ for await (const chunk of request) {
1592
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
1593
+ total += buf.byteLength;
1594
+ if (total > MAX_JSON_BODY_BYTES) {
1595
+ throw new FaFaError("CONFIG_INVALID", "Request body exceeds maximum allowed size");
1596
+ }
1597
+ chunks.push(buf);
1598
+ }
1599
+ if (chunks.length === 0) return {};
1600
+ const text = Buffer.concat(chunks).toString("utf8").trim();
1601
+ if (!text) return {};
1602
+ let parsed;
1603
+ try {
1604
+ parsed = JSON.parse(text);
1605
+ } catch {
1606
+ throw new FaFaError("CONFIG_INVALID", "Request body is not valid JSON");
1607
+ }
1608
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1609
+ throw new FaFaError("CONFIG_INVALID", "Request body must be a JSON object");
1610
+ }
1611
+ return parsed;
1612
+ }
1613
+ function listPresetsForLocale(locale) {
1614
+ return {
1615
+ themes: listWechatThemePresets(locale).map((theme) => ({
1616
+ id: theme.id,
1617
+ name: theme.name,
1618
+ description: theme.description
1619
+ })),
1620
+ codeThemes: listCodeHighlightThemes(locale).map((theme) => ({
1621
+ id: theme.id,
1622
+ name: theme.name
1623
+ })),
1624
+ imageCaptions: listImageCaptionModes(locale).map((mode) => ({
1625
+ id: mode.id,
1626
+ name: mode.name,
1627
+ description: mode.description
1628
+ }))
1629
+ };
1630
+ }
1631
+ function formatBrowserStatus(status) {
1632
+ if (status.status !== "ready") {
1633
+ return { available: false, source: status.source };
1634
+ }
1635
+ return {
1636
+ available: true,
1637
+ source: status.source,
1638
+ ...status.executablePath ? { executablePath: status.executablePath } : {},
1639
+ ...status.channel ? { channel: status.channel } : {}
1640
+ };
1641
+ }
1642
+ async function fileExists2(path) {
1643
+ try {
1644
+ await access4(path);
1645
+ return true;
1646
+ } catch {
1647
+ return false;
1648
+ }
1649
+ }
1650
+ function resolveLocaleParam(url, body) {
1651
+ const fromBody = typeof body?.locale === "string" ? body.locale : void 0;
1652
+ const fromQuery = url.searchParams.get("locale") ?? void 0;
1653
+ return normalizeLocale(fromBody ?? fromQuery, "zh-CN");
1654
+ }
1655
+ function fallbackHtmlPage(appVersion) {
1656
+ return `<!doctype html>
1657
+ <html lang="zh-CN">
1658
+ <head>
1659
+ <meta charset="utf-8" />
1660
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1661
+ <title>\u53D1\u53D1 FaFa</title>
1662
+ </head>
1663
+ <body>
1664
+ <main style="font-family:system-ui,sans-serif;max-width:560px;margin:64px auto;padding:0 20px;line-height:1.6;">
1665
+ <h1>\u53D1\u53D1 FaFa \u672C\u5730\u5DE5\u4F5C\u53F0</h1>
1666
+ <p>Web \u524D\u7AEF\u9759\u6001\u8D44\u6E90\u5C1A\u672A\u6784\u5EFA\uFF08\u7248\u672C ${appVersion}\uFF09\u3002\u8BF7\u8FD0\u884C <code>pnpm --filter @fafa/web build</code> \u540E\u5237\u65B0\u9875\u9762\u3002</p>
1667
+ </main>
1668
+ </body>
1669
+ </html>`;
1670
+ }
1671
+ async function startWebWorkbenchServer(options = {}) {
1672
+ const home = options.home ? resolve32(options.home) : getFaFaHome();
1673
+ const host = options.host ?? DEFAULT_WEB_HOST;
1674
+ if (host !== "127.0.0.1" && host !== "localhost") {
1675
+ throw new FaFaError(
1676
+ "CONFIG_INVALID",
1677
+ `Local web workbench must bind only to loopback (127.0.0.1 or localhost), received: ${host}`
1678
+ );
1679
+ }
1680
+ const requestedPort = options.port ?? DEFAULT_WEB_PORT;
1681
+ const appVersion = options.appVersion ?? "0.2.1";
1682
+ const dependencies = options.dependencies ?? {};
1683
+ const webDistDir = options.webDistDir ? resolve32(options.webDistDir) : void 0;
1684
+ const runtimes = /* @__PURE__ */ new Map();
1685
+ const activeSseResponses = /* @__PURE__ */ new Set();
1686
+ let boundPort = requestedPort;
1687
+ async function resolveRuntime(libraryId) {
1688
+ const registry = await loadLibraryRegistry(home);
1689
+ const entry = registry.libraries.find((item) => item.id === libraryId);
1690
+ if (!entry) {
1691
+ throw new FaFaError("PROJECT_NOT_FOUND", `Library "${libraryId}" is not registered`);
1692
+ }
1693
+ const existing = runtimes.get(libraryId);
1694
+ if (existing) {
1695
+ existing.entry = entry;
1696
+ return existing;
1697
+ }
1698
+ const runtime = new LibraryRuntime(entry, home, dependencies);
1699
+ runtimes.set(libraryId, runtime);
1700
+ return runtime;
1701
+ }
1702
+ async function serveStatic(requestPath, response) {
1703
+ if (!webDistDir || !await fileExists2(join4(webDistDir, "index.html"))) {
1704
+ response.writeHead(200, {
1705
+ "content-type": "text/html; charset=utf-8",
1706
+ "cache-control": "no-store"
1707
+ });
1708
+ response.end(fallbackHtmlPage(appVersion));
1709
+ return;
1710
+ }
1711
+ const cleanPath = decodeURIComponent(requestPath).replace(/^\/+/, "");
1712
+ const candidate = normalize(join4(webDistDir, cleanPath || "index.html"));
1713
+ const rel = relative2(webDistDir, candidate);
1714
+ const safeCandidate = rel && !rel.startsWith("..") && !rel.startsWith("/") ? candidate : join4(webDistDir, "index.html");
1715
+ let targetFile = safeCandidate;
1716
+ try {
1717
+ const info = await stat3(targetFile);
1718
+ if (info.isDirectory()) {
1719
+ targetFile = join4(webDistDir, "index.html");
1720
+ }
1721
+ } catch {
1722
+ targetFile = join4(webDistDir, "index.html");
1723
+ }
1724
+ const ext = extname2(targetFile).toLowerCase();
1725
+ const contentType = STATIC_MIME_TYPES[ext] ?? "application/octet-stream";
1726
+ const isHashedAsset = targetFile.includes(`${join4(webDistDir, "assets")}`);
1727
+ const bytes = await readFile2(targetFile);
1728
+ response.writeHead(200, {
1729
+ "content-type": contentType,
1730
+ "cache-control": isHashedAsset ? "public, max-age=31536000, immutable" : "no-store",
1731
+ "x-content-type-options": "nosniff"
1732
+ });
1733
+ response.end(bytes);
1734
+ }
1735
+ async function handleRequest(request, response) {
1736
+ const method = (request.method ?? "GET").toUpperCase();
1737
+ if (!isValidHostHeader(request.headers.host, boundPort)) {
1738
+ sendJson(response, 403, {
1739
+ ok: false,
1740
+ error: { code: "FORBIDDEN_HOST", message: "Rejected request with untrusted Host header" }
1741
+ });
1742
+ return;
1743
+ }
1744
+ const url2 = new URL(request.url ?? "/", `http://${host}:${boundPort}`);
1745
+ const pathname = url2.pathname;
1746
+ if (method === "GET" && pathname === "/api/health") {
1747
+ sendJson(response, 200, {
1748
+ ok: true,
1749
+ data: {
1750
+ status: "ok",
1751
+ version: appVersion,
1752
+ pid: process.pid,
1753
+ host,
1754
+ port: boundPort
1755
+ }
1756
+ });
1757
+ return;
1758
+ }
1759
+ if (pathname.startsWith("/api/")) {
1760
+ if (isWriteMethod(method)) {
1761
+ if (!isValidWriteSecurityHeaders(request, boundPort)) {
1762
+ sendJson(response, 403, {
1763
+ ok: false,
1764
+ error: { code: "FORBIDDEN_ORIGIN", message: "Cross-origin or missing CSRF header rejected" }
1765
+ });
1766
+ return;
1767
+ }
1768
+ } else if (!isValidSameSiteHeaders(request, boundPort)) {
1769
+ sendJson(response, 403, {
1770
+ ok: false,
1771
+ error: { code: "FORBIDDEN_ORIGIN", message: "Cross-origin API request rejected" }
1772
+ });
1773
+ return;
1774
+ }
1775
+ if (method === "GET" && pathname === "/api/bootstrap") {
1776
+ const locale = resolveLocaleParam(url2);
1777
+ const [libraries, userConfig] = await Promise.all([
1778
+ listRegisteredLibraries(home),
1779
+ loadUserConfig(home)
1780
+ ]);
1781
+ const publicConfig = toPublicUserConfig(userConfig);
1782
+ sendJson(response, 200, {
1783
+ ok: true,
1784
+ data: {
1785
+ version: appVersion,
1786
+ locale,
1787
+ home,
1788
+ lastActiveLibraryId: libraries.lastActiveLibraryId ?? null,
1789
+ libraries: libraries.libraries,
1790
+ accounts: {
1791
+ defaultAccount: publicConfig.defaultAccount ?? null,
1792
+ items: publicConfig.accounts
1793
+ },
1794
+ presets: listPresetsForLocale(locale)
1795
+ }
1796
+ });
1797
+ return;
1798
+ }
1799
+ if (method === "GET" && pathname === "/api/fs/browse") {
1800
+ const targetPath = url2.searchParams.get("path") ?? void 0;
1801
+ const includeHidden = url2.searchParams.get("includeHidden") === "true";
1802
+ const result = await browseLocalDirectories(targetPath, { includeHidden });
1803
+ sendJson(response, 200, { ok: true, data: result });
1804
+ return;
1805
+ }
1806
+ if (method === "GET" && pathname === "/api/libraries") {
1807
+ const result = await listRegisteredLibraries(home);
1808
+ sendJson(response, 200, { ok: true, data: result });
1809
+ return;
1810
+ }
1811
+ if (method === "POST" && pathname === "/api/libraries") {
1812
+ const body = await readJsonBody(request);
1813
+ const root = typeof body.root === "string" ? body.root.trim() : "";
1814
+ if (!root) {
1815
+ throw new FaFaError("CONFIG_INVALID", "Library root path is required");
1816
+ }
1817
+ const registered = await registerLibrary(
1818
+ {
1819
+ root,
1820
+ ...typeof body.name === "string" && body.name.trim() ? { name: body.name.trim() } : {},
1821
+ initialize: Boolean(body.initialize)
1822
+ },
1823
+ home
1824
+ );
1825
+ sendJson(response, 200, {
1826
+ ok: true,
1827
+ data: {
1828
+ library: registered.library,
1829
+ lastActiveLibraryId: registered.registry.lastActiveLibraryId ?? null
1830
+ }
1831
+ });
1832
+ return;
1833
+ }
1834
+ if (method === "GET" && pathname === "/api/events") {
1835
+ const libraryId = url2.searchParams.get("libraryId")?.trim() ?? "";
1836
+ if (!libraryId) {
1837
+ throw new FaFaError("CONFIG_INVALID", "Query parameter libraryId is required for SSE stream");
1838
+ }
1839
+ const runtime = await resolveRuntime(libraryId);
1840
+ response.writeHead(200, {
1841
+ "content-type": "text/event-stream; charset=utf-8",
1842
+ "cache-control": "no-cache, no-transform",
1843
+ connection: "keep-alive",
1844
+ "x-accel-buffering": "no"
1845
+ });
1846
+ activeSseResponses.add(response);
1847
+ const writeEvent = (eventPayload) => {
1848
+ if (response.writableEnded) return;
1849
+ response.write(`data: ${JSON.stringify(eventPayload)}
1850
+
1851
+ `);
1852
+ };
1853
+ const unsubscribe = runtime.subscribe((event) => {
1854
+ writeEvent(event);
1855
+ });
1856
+ await runtime.ensureWatching();
1857
+ writeEvent({
1858
+ type: "connected",
1859
+ libraryId,
1860
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1861
+ });
1862
+ const heartbeat = setInterval(() => {
1863
+ if (!response.writableEnded) response.write(": heartbeat\n\n");
1864
+ }, 25e3);
1865
+ request.on("close", () => {
1866
+ clearInterval(heartbeat);
1867
+ unsubscribe();
1868
+ activeSseResponses.delete(response);
1869
+ });
1870
+ return;
1871
+ }
1872
+ const libraryMatch = pathname.match(/^\/api\/libraries\/([^/]+)(?:\/(.*))?$/);
1873
+ if (libraryMatch) {
1874
+ const libraryId = decodeURIComponent(libraryMatch[1] ?? "");
1875
+ const subroute = libraryMatch[2] ?? "";
1876
+ if (method === "DELETE" && subroute === "") {
1877
+ const runtime = runtimes.get(libraryId);
1878
+ if (runtime) {
1879
+ runtime.emit({
1880
+ type: "library.removed",
1881
+ libraryId,
1882
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1883
+ });
1884
+ runtime.close();
1885
+ runtimes.delete(libraryId);
1886
+ }
1887
+ const updated = await removeRegisteredLibrary(libraryId, home);
1888
+ sendJson(response, 200, {
1889
+ ok: true,
1890
+ data: {
1891
+ removedId: libraryId,
1892
+ lastActiveLibraryId: updated.lastActiveLibraryId ?? null
1893
+ }
1894
+ });
1895
+ return;
1896
+ }
1897
+ if (method === "GET" && (subroute === "" || subroute === "articles")) {
1898
+ const runtime = await resolveRuntime(libraryId);
1899
+ await touchLibrary(libraryId, home);
1900
+ const snapshot = await runtime.getSnapshot();
1901
+ sendJson(response, 200, { ok: true, data: snapshot });
1902
+ return;
1903
+ }
1904
+ if (method === "POST" && subroute === "refresh") {
1905
+ const runtime = await resolveRuntime(libraryId);
1906
+ runtime.invalidateService();
1907
+ const snapshot = await runtime.getSnapshot();
1908
+ sendJson(response, 200, { ok: true, data: snapshot });
1909
+ return;
1910
+ }
1911
+ if (method === "GET" && subroute === "preview") {
1912
+ const articlePath = url2.searchParams.get("path")?.trim() ?? "";
1913
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "Query parameter path is required");
1914
+ const bypassCache = url2.searchParams.get("fresh") === "1";
1915
+ const locale = resolveLocaleParam(url2);
1916
+ const runtime = await resolveRuntime(libraryId);
1917
+ const preview = await runtime.buildPreview(articlePath, locale, { bypassCache });
1918
+ sendJson(response, 200, { ok: true, data: preview });
1919
+ return;
1920
+ }
1921
+ if (method === "POST" && subroute === "check") {
1922
+ const body = await readJsonBody(request);
1923
+ const articlePath = typeof body.articlePath === "string" ? body.articlePath.trim() : "";
1924
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "articlePath is required");
1925
+ const runtime = await resolveRuntime(libraryId);
1926
+ const result = await runtime.checkArticle(articlePath);
1927
+ sendJson(response, 200, { ok: true, data: result });
1928
+ return;
1929
+ }
1930
+ if (method === "PATCH" && subroute === "defaults") {
1931
+ const body = await readJsonBody(request);
1932
+ const locale = resolveLocaleParam(url2, body);
1933
+ const runtime = await resolveRuntime(libraryId);
1934
+ const snapshot = await runtime.setProjectDefaults({
1935
+ ...typeof body.theme === "string" ? { theme: body.theme } : {},
1936
+ ...typeof body.codeTheme === "string" ? { codeTheme: body.codeTheme } : {},
1937
+ ...typeof body.imageCaption === "string" ? { imageCaption: body.imageCaption } : {},
1938
+ locale
1939
+ });
1940
+ sendJson(response, 200, { ok: true, data: snapshot });
1941
+ return;
1942
+ }
1943
+ if (method === "PATCH" && subroute === "article-options") {
1944
+ const body = await readJsonBody(request);
1945
+ const articlePath = typeof body.articlePath === "string" ? body.articlePath.trim() : "";
1946
+ const field = body.field;
1947
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "articlePath is required");
1948
+ if (field !== "theme" && field !== "codeTheme" && field !== "imageCaption") {
1949
+ throw new FaFaError("CONFIG_INVALID", "field must be theme, codeTheme, or imageCaption");
1950
+ }
1951
+ const value = body.value === null ? null : typeof body.value === "string" ? body.value : void 0;
1952
+ if (value === void 0) {
1953
+ throw new FaFaError("CONFIG_INVALID", "value must be a string or null");
1954
+ }
1955
+ const locale = resolveLocaleParam(url2, body);
1956
+ const runtime = await resolveRuntime(libraryId);
1957
+ const preview = await runtime.setArticleOption({
1958
+ articlePath,
1959
+ field,
1960
+ value,
1961
+ locale
1962
+ });
1963
+ sendJson(response, 200, { ok: true, data: preview });
1964
+ return;
1965
+ }
1966
+ if (method === "POST" && subroute === "export") {
1967
+ const body = await readJsonBody(request);
1968
+ const articlePath = typeof body.articlePath === "string" ? body.articlePath.trim() : "";
1969
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "articlePath is required");
1970
+ const format = body.format === "pdf" || body.format === "png" ? body.format : "html";
1971
+ const appearance = body.appearance === "night" ? "night" : "day";
1972
+ const browserPath = typeof body.browserPath === "string" && body.browserPath.trim() ? body.browserPath.trim() : void 0;
1973
+ const saveToDisk = Boolean(body.saveToDisk);
1974
+ const runtime = await resolveRuntime(libraryId);
1975
+ const exported = await runtime.exportArticle({
1976
+ articlePath,
1977
+ format,
1978
+ appearance,
1979
+ ...browserPath ? { browserPath } : {},
1980
+ saveToDisk
1981
+ });
1982
+ sendJson(response, 200, { ok: true, data: exported });
1983
+ return;
1984
+ }
1985
+ if (method === "POST" && subroute === "draft/plan") {
1986
+ const body = await readJsonBody(request);
1987
+ const articlePath = typeof body.articlePath === "string" ? body.articlePath.trim() : "";
1988
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "articlePath is required");
1989
+ const accountId = typeof body.accountId === "string" && body.accountId.trim() ? body.accountId.trim() : void 0;
1990
+ const runtime = await resolveRuntime(libraryId);
1991
+ const plan = await runtime.planDraft({
1992
+ articlePath,
1993
+ ...accountId ? { accountId } : {}
1994
+ });
1995
+ sendJson(response, 200, { ok: true, data: plan });
1996
+ return;
1997
+ }
1998
+ if (method === "POST" && subroute === "draft/push") {
1999
+ const body = await readJsonBody(request);
2000
+ const articlePath = typeof body.articlePath === "string" ? body.articlePath.trim() : "";
2001
+ if (!articlePath) throw new FaFaError("ARTICLE_NOT_FOUND", "articlePath is required");
2002
+ const accountId = typeof body.accountId === "string" && body.accountId.trim() ? body.accountId.trim() : void 0;
2003
+ const expectedBuildHash = typeof body.expectedBuildHash === "string" ? body.expectedBuildHash.trim() : "";
2004
+ const confirmed = body.confirmed === true;
2005
+ const runtime = await resolveRuntime(libraryId);
2006
+ const receipt = await runtime.pushDraft({
2007
+ articlePath,
2008
+ ...accountId ? { accountId } : {},
2009
+ expectedBuildHash,
2010
+ confirmed
2011
+ });
2012
+ sendJson(response, 200, { ok: true, data: receipt });
2013
+ return;
2014
+ }
2015
+ if (method === "GET" && subroute === "operations") {
2016
+ const limitRaw = Number(url2.searchParams.get("limit") ?? "50");
2017
+ const limit = Number.isFinite(limitRaw) ? limitRaw : 50;
2018
+ const runtime = await resolveRuntime(libraryId);
2019
+ const operations = await runtime.listOperations(limit);
2020
+ sendJson(response, 200, { ok: true, data: { operations } });
2021
+ return;
2022
+ }
2023
+ }
2024
+ if (method === "GET" && pathname === "/api/browser/status") {
2025
+ const browserPath = url2.searchParams.get("browserPath")?.trim() || void 0;
2026
+ const status = await inspectBrowserForWeb(home, dependencies, browserPath);
2027
+ sendJson(response, 200, { ok: true, data: formatBrowserStatus(status) });
2028
+ return;
2029
+ }
2030
+ if (method === "POST" && pathname === "/api/browser/install") {
2031
+ const status = await installBrowserForWeb(home, dependencies);
2032
+ sendJson(response, 200, {
2033
+ ok: true,
2034
+ data: {
2035
+ status: "installed",
2036
+ browser: formatBrowserStatus(status)
2037
+ }
2038
+ });
2039
+ return;
2040
+ }
2041
+ if (method === "GET" && pathname === "/api/accounts") {
2042
+ const publicConfig = toPublicUserConfig(await loadUserConfig(home));
2043
+ sendJson(response, 200, {
2044
+ ok: true,
2045
+ data: {
2046
+ defaultAccount: publicConfig.defaultAccount ?? null,
2047
+ items: publicConfig.accounts
2048
+ }
2049
+ });
2050
+ return;
2051
+ }
2052
+ if (method === "POST" && pathname === "/api/accounts") {
2053
+ const body = await readJsonBody(request);
2054
+ const id = typeof body.id === "string" ? body.id.trim() : "";
2055
+ const name = typeof body.name === "string" ? body.name.trim() : "";
2056
+ const appId = typeof body.appId === "string" ? body.appId.trim() : "";
2057
+ const appSecret = typeof body.appSecret === "string" && body.appSecret.trim() ? body.appSecret.trim() : void 0;
2058
+ if (!id || !name || !appId) {
2059
+ throw new FaFaError("CONFIG_INVALID", "Account id, name, and appId are required");
2060
+ }
2061
+ const updated = await upsertAccount(
2062
+ {
2063
+ id,
2064
+ name,
2065
+ appId,
2066
+ platform: "wechat",
2067
+ test: Boolean(body.test),
2068
+ ...appSecret ? { appSecret } : {}
2069
+ },
2070
+ home
2071
+ );
2072
+ const publicConfig = toPublicUserConfig(updated);
2073
+ sendJson(response, 200, {
2074
+ ok: true,
2075
+ data: {
2076
+ defaultAccount: publicConfig.defaultAccount ?? null,
2077
+ items: publicConfig.accounts
2078
+ }
2079
+ });
2080
+ return;
2081
+ }
2082
+ const accountMatch = pathname.match(/^\/api\/accounts\/([^/]+)(?:\/(.*))?$/);
2083
+ if (accountMatch) {
2084
+ const accountId = decodeURIComponent(accountMatch[1] ?? "");
2085
+ const subroute = accountMatch[2] ?? "";
2086
+ if (method === "DELETE" && subroute === "") {
2087
+ const updated = await removeAccount(accountId, home);
2088
+ const publicConfig = toPublicUserConfig(updated);
2089
+ sendJson(response, 200, {
2090
+ ok: true,
2091
+ data: {
2092
+ defaultAccount: publicConfig.defaultAccount ?? null,
2093
+ items: publicConfig.accounts
2094
+ }
2095
+ });
2096
+ return;
2097
+ }
2098
+ if (method === "POST" && subroute === "probe") {
2099
+ const [config, credential] = await Promise.all([
2100
+ loadUserConfig(home),
2101
+ resolveWechatCredential(accountId, home)
2102
+ ]);
2103
+ const account = config.accounts.find((item) => item.id === accountId);
2104
+ const client = dependencies.createWechatClient ? dependencies.createWechatClient(home) : createDefaultWechatClient(home);
2105
+ const probe = await client.probeDraftCapability(credential);
2106
+ const payload = {
2107
+ accountId,
2108
+ name: account?.name ?? accountId,
2109
+ checkedAt: probe.checkedAt,
2110
+ ok: probe.ok
2111
+ };
2112
+ sendJson(response, 200, { ok: true, data: payload });
2113
+ return;
2114
+ }
2115
+ }
2116
+ sendJson(response, 404, {
2117
+ ok: false,
2118
+ error: { code: "NOT_FOUND", message: `Unknown API endpoint: ${method} ${pathname}` }
2119
+ });
2120
+ return;
2121
+ }
2122
+ if (method !== "GET" && method !== "HEAD") {
2123
+ sendJson(response, 405, {
2124
+ ok: false,
2125
+ error: { code: "METHOD_NOT_ALLOWED", message: `Method ${method} not allowed` }
2126
+ });
2127
+ return;
2128
+ }
2129
+ await serveStatic(pathname, response);
2130
+ }
2131
+ const server = createServer((request, response) => {
2132
+ void handleRequest(request, response).catch((error) => {
2133
+ if (!response.headersSent) {
2134
+ sendError(response, error);
2135
+ } else {
2136
+ response.end();
2137
+ }
2138
+ });
2139
+ });
2140
+ await new Promise((resolveListen, rejectListen) => {
2141
+ const onError = (error) => {
2142
+ server.off("listening", onListening);
2143
+ rejectListen(error);
2144
+ };
2145
+ const onListening = () => {
2146
+ server.off("error", onError);
2147
+ resolveListen();
2148
+ };
2149
+ server.once("error", onError);
2150
+ server.once("listening", onListening);
2151
+ server.listen(requestedPort, host);
2152
+ });
2153
+ const address = server.address();
2154
+ boundPort = address?.port ?? requestedPort;
2155
+ const url = `http://${host}:${boundPort}`;
2156
+ if (options.writeDaemonState) {
2157
+ await writeDaemonState(
2158
+ {
2159
+ version: 1,
2160
+ pid: process.pid,
2161
+ host,
2162
+ port: boundPort,
2163
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2164
+ appVersion
2165
+ },
2166
+ home
2167
+ );
2168
+ }
2169
+ return {
2170
+ host,
2171
+ port: boundPort,
2172
+ url,
2173
+ home,
2174
+ issueLaunchUrl: (libraryId) => {
2175
+ const next = libraryId ? `/libraries/${encodeURIComponent(libraryId)}` : "/";
2176
+ return `${url}${next}`;
2177
+ },
2178
+ close: async () => {
2179
+ for (const sse of activeSseResponses) {
2180
+ sse.end();
2181
+ }
2182
+ activeSseResponses.clear();
2183
+ for (const runtime of runtimes.values()) {
2184
+ runtime.close();
2185
+ }
2186
+ runtimes.clear();
2187
+ await new Promise((resolveClose) => {
2188
+ server.close(() => resolveClose());
2189
+ });
2190
+ if (options.writeDaemonState) {
2191
+ await clearDaemonState(process.pid, home);
2192
+ }
2193
+ }
2194
+ };
2195
+ }
2196
+ var execFileAsync = promisify(execFile);
2197
+ var MACOS_LAUNCHD_LABEL = "io.elonzh.fafa";
2198
+ var LINUX_SYSTEMD_UNIT = "fafa.service";
2199
+ var WINDOWS_TASK_NAME = "FaFaWorkbench";
2200
+ var defaultRunner = async (command, args) => {
2201
+ try {
2202
+ const result = await execFileAsync(command, args, { encoding: "utf8" });
2203
+ return { stdout: result.stdout ?? "", stderr: result.stderr ?? "", exitCode: 0 };
2204
+ } catch (error) {
2205
+ const execErr = error;
2206
+ return {
2207
+ stdout: execErr.stdout ?? "",
2208
+ stderr: execErr.stderr ?? (error instanceof Error ? error.message : String(error)),
2209
+ exitCode: typeof execErr.code === "number" ? execErr.code : 1
2210
+ };
2211
+ }
2212
+ };
2213
+ function xmlEscape(value) {
2214
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
2215
+ }
2216
+ async function fileExists3(path) {
2217
+ try {
2218
+ await access5(path);
2219
+ return true;
2220
+ } catch {
2221
+ return false;
2222
+ }
2223
+ }
2224
+ function defaultServiceLogPath(home = getFaFaHome(), platform = process.platform, userHome = homedir2()) {
2225
+ if (platform === "darwin") {
2226
+ return join5(userHome, "Library", "Logs", "fafa", "daemon.log");
2227
+ }
2228
+ return join5(home, "logs", "daemon.log");
2229
+ }
2230
+ function serviceDefinitionPath(home = getFaFaHome(), platform = process.platform, userHome = homedir2()) {
2231
+ if (platform === "darwin") {
2232
+ return join5(userHome, "Library", "LaunchAgents", `${MACOS_LAUNCHD_LABEL}.plist`);
2233
+ }
2234
+ if (platform === "linux") {
2235
+ return join5(userHome, ".config", "systemd", "user", LINUX_SYSTEMD_UNIT);
2236
+ }
2237
+ return join5(home, "service", "fafa-workbench.cmd");
2238
+ }
2239
+ function renderLaunchdPlist(input) {
2240
+ const label = input.label ?? MACOS_LAUNCHD_LABEL;
2241
+ const args = [
2242
+ input.nodePath,
2243
+ input.cliScript,
2244
+ "ui",
2245
+ "--foreground",
2246
+ "--no-open",
2247
+ "--port",
2248
+ String(input.port),
2249
+ "--home",
2250
+ input.home
2251
+ ];
2252
+ const argsXml = args.map((arg) => ` <string>${xmlEscape(arg)}</string>`).join("\n");
2253
+ return `<?xml version="1.0" encoding="UTF-8"?>
2254
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2255
+ <plist version="1.0">
2256
+ <dict>
2257
+ <key>Label</key>
2258
+ <string>${xmlEscape(label)}</string>
2259
+ <key>ProgramArguments</key>
2260
+ <array>
2261
+ ${argsXml}
2262
+ </array>
2263
+ <key>EnvironmentVariables</key>
2264
+ <dict>
2265
+ <key>PATH</key>
2266
+ <string>${xmlEscape(input.pathEnv)}</string>
2267
+ <key>FAFA_HOME</key>
2268
+ <string>${xmlEscape(input.home)}</string>
2269
+ </dict>
2270
+ <key>RunAtLoad</key>
2271
+ <true/>
2272
+ <key>KeepAlive</key>
2273
+ <true/>
2274
+ <key>StandardOutPath</key>
2275
+ <string>${xmlEscape(input.logPath)}</string>
2276
+ <key>StandardErrorPath</key>
2277
+ <string>${xmlEscape(input.logPath)}</string>
2278
+ </dict>
2279
+ </plist>
2280
+ `;
2281
+ }
2282
+ function quoteSystemdArg(value) {
2283
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
2284
+ }
2285
+ function renderSystemdUnit(input) {
2286
+ const execStart = [
2287
+ quoteSystemdArg(input.nodePath),
2288
+ quoteSystemdArg(input.cliScript),
2289
+ "ui",
2290
+ "--foreground",
2291
+ "--no-open",
2292
+ "--port",
2293
+ String(input.port),
2294
+ "--home",
2295
+ quoteSystemdArg(input.home)
2296
+ ].join(" ");
2297
+ return `[Unit]
2298
+ Description=FaFa Local Web Workbench
2299
+ After=network.target
2300
+
2301
+ [Service]
2302
+ Type=simple
2303
+ ExecStart=${execStart}
2304
+ Environment=FAFA_HOME=${quoteSystemdArg(input.home)}
2305
+ Restart=on-failure
2306
+ RestartSec=3
2307
+ StandardOutput=append:${input.logPath}
2308
+ StandardError=append:${input.logPath}
2309
+
2310
+ [Install]
2311
+ WantedBy=default.target
2312
+ `;
2313
+ }
2314
+ function renderWindowsServiceScript(input) {
2315
+ return `@echo off
2316
+ set "FAFA_HOME=${input.home}"
2317
+ "${input.nodePath}" "${input.cliScript}" ui --foreground --no-open --port ${input.port} --home "${input.home}" >> "${input.logPath}" 2>&1
2318
+ `;
2319
+ }
2320
+ async function waitForDaemonReady(home, timeoutMs = 4500) {
2321
+ const deadline = Date.now() + timeoutMs;
2322
+ while (Date.now() < deadline) {
2323
+ const probed = await probeRunningDaemon(home);
2324
+ if (probed.running) return true;
2325
+ await new Promise((r) => setTimeout(r, 150));
2326
+ }
2327
+ return false;
2328
+ }
2329
+ function resolveServiceContext(options) {
2330
+ const platform = options.platform ?? process.platform;
2331
+ const userHome = options.userHome ?? homedir2();
2332
+ const home = options.home ? resolve42(options.home) : getFaFaHome();
2333
+ const port = options.port ?? DEFAULT_WEB_PORT;
2334
+ const nodePath = options.nodePath ?? process.execPath;
2335
+ const cliScript = options.cliScript ? resolve42(options.cliScript) : resolve42(process.argv[1] ?? "");
2336
+ const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
2337
+ const pathEnv = options.pathEnv ?? process.env.PATH ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
2338
+ const runner = options.runner ?? defaultRunner;
2339
+ const serviceFile = serviceDefinitionPath(home, platform, userHome);
2340
+ const logPath = defaultServiceLogPath(home, platform, userHome);
2341
+ return { platform, userHome, home, port, nodePath, cliScript, uid, pathEnv, runner, serviceFile, logPath };
2342
+ }
2343
+ async function getUserServiceStatus(options = {}) {
2344
+ const ctx = resolveServiceContext(options);
2345
+ const [installed, probed] = await Promise.all([fileExists3(ctx.serviceFile), probeRunningDaemon(ctx.home)]);
2346
+ const state = probed.state ?? await readDaemonState(ctx.home);
2347
+ const port = state?.port ?? ctx.port;
2348
+ const host = state?.host ?? DEFAULT_WEB_HOST;
2349
+ return {
2350
+ platform: ctx.platform,
2351
+ installed,
2352
+ running: probed.running,
2353
+ serviceFile: ctx.serviceFile,
2354
+ logPath: ctx.logPath,
2355
+ host,
2356
+ port,
2357
+ url: `http://${host}:${port}`,
2358
+ pid: probed.running ? state?.pid ?? null : null,
2359
+ startedAt: probed.running ? state?.startedAt ?? null : null,
2360
+ state
2361
+ };
2362
+ }
2363
+ async function installUserService(options = {}) {
2364
+ const ctx = resolveServiceContext(options);
2365
+ if (!ctx.cliScript) {
2366
+ throw new FaFaError("CONFIG_INVALID", "Unable to determine FaFa CLI entry script path");
2367
+ }
2368
+ await mkdir32(dirname32(ctx.serviceFile), { recursive: true });
2369
+ await mkdir32(dirname32(ctx.logPath), { recursive: true });
2370
+ await mkdir32(ctx.home, { recursive: true, mode: 448 });
2371
+ if (ctx.platform === "darwin") {
2372
+ const plist = renderLaunchdPlist({
2373
+ nodePath: ctx.nodePath,
2374
+ cliScript: ctx.cliScript,
2375
+ home: ctx.home,
2376
+ port: ctx.port,
2377
+ logPath: ctx.logPath,
2378
+ pathEnv: ctx.pathEnv
2379
+ });
2380
+ await writeFile32(ctx.serviceFile, plist, "utf8");
2381
+ await ctx.runner("launchctl", ["bootout", `gui/${ctx.uid}/${MACOS_LAUNCHD_LABEL}`]);
2382
+ const boot = await ctx.runner("launchctl", ["bootstrap", `gui/${ctx.uid}`, ctx.serviceFile]);
2383
+ if (boot.exitCode !== 0) {
2384
+ throw new FaFaError(
2385
+ "CONFIG_INVALID",
2386
+ `Failed to load macOS LaunchAgent (${boot.stderr.trim() || `exit ${boot.exitCode}`})`
2387
+ );
2388
+ }
2389
+ await ctx.runner("launchctl", ["kickstart", "-k", `gui/${ctx.uid}/${MACOS_LAUNCHD_LABEL}`]);
2390
+ } else if (ctx.platform === "linux") {
2391
+ const unit = renderSystemdUnit({
2392
+ nodePath: ctx.nodePath,
2393
+ cliScript: ctx.cliScript,
2394
+ home: ctx.home,
2395
+ port: ctx.port,
2396
+ logPath: ctx.logPath
2397
+ });
2398
+ await writeFile32(ctx.serviceFile, unit, "utf8");
2399
+ const reload = await ctx.runner("systemctl", ["--user", "daemon-reload"]);
2400
+ if (reload.exitCode !== 0) {
2401
+ throw new FaFaError(
2402
+ "CONFIG_INVALID",
2403
+ `Failed to reload systemd user daemon (${reload.stderr.trim() || `exit ${reload.exitCode}`})`
2404
+ );
2405
+ }
2406
+ const enable = await ctx.runner("systemctl", ["--user", "enable", "--now", LINUX_SYSTEMD_UNIT]);
2407
+ if (enable.exitCode !== 0) {
2408
+ throw new FaFaError(
2409
+ "CONFIG_INVALID",
2410
+ `Failed to enable systemd service (${enable.stderr.trim() || `exit ${enable.exitCode}`})`
2411
+ );
2412
+ }
2413
+ } else if (ctx.platform === "win32") {
2414
+ const script = renderWindowsServiceScript({
2415
+ nodePath: ctx.nodePath,
2416
+ cliScript: ctx.cliScript,
2417
+ home: ctx.home,
2418
+ port: ctx.port,
2419
+ logPath: ctx.logPath
2420
+ });
2421
+ await writeFile32(ctx.serviceFile, script, "utf8");
2422
+ const create = await ctx.runner("schtasks", [
2423
+ "/Create",
2424
+ "/TN",
2425
+ WINDOWS_TASK_NAME,
2426
+ "/SC",
2427
+ "ONLOGON",
2428
+ "/TR",
2429
+ `"${ctx.serviceFile}"`,
2430
+ "/F"
2431
+ ]);
2432
+ if (create.exitCode !== 0) {
2433
+ throw new FaFaError(
2434
+ "CONFIG_INVALID",
2435
+ `Failed to register Windows scheduled task (${create.stderr.trim() || `exit ${create.exitCode}`})`
2436
+ );
2437
+ }
2438
+ await ctx.runner("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME]);
2439
+ } else {
2440
+ throw new FaFaError("CONFIG_INVALID", `Unsupported platform for background service: ${ctx.platform}`);
2441
+ }
2442
+ if (!options.runner) {
2443
+ await waitForDaemonReady(ctx.home);
2444
+ }
2445
+ return getUserServiceStatus(options);
2446
+ }
2447
+ async function uninstallUserService(options = {}) {
2448
+ const ctx = resolveServiceContext(options);
2449
+ if (ctx.platform === "darwin") {
2450
+ await ctx.runner("launchctl", ["bootout", `gui/${ctx.uid}/${MACOS_LAUNCHD_LABEL}`]);
2451
+ } else if (ctx.platform === "linux") {
2452
+ await ctx.runner("systemctl", ["--user", "disable", "--now", LINUX_SYSTEMD_UNIT]);
2453
+ } else if (ctx.platform === "win32") {
2454
+ await ctx.runner("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME]);
2455
+ await ctx.runner("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"]);
2456
+ }
2457
+ await rm2(ctx.serviceFile, { force: true }).catch(() => {
2458
+ });
2459
+ const state = await readDaemonState(ctx.home);
2460
+ if (state && !options.runner) {
2461
+ try {
2462
+ process.kill(state.pid, "SIGTERM");
2463
+ } catch {
2464
+ }
2465
+ await clearDaemonState(state.pid, ctx.home);
2466
+ }
2467
+ return getUserServiceStatus(options);
2468
+ }
2469
+ async function startUserService(options = {}) {
2470
+ const ctx = resolveServiceContext(options);
2471
+ if (!await fileExists3(ctx.serviceFile)) {
2472
+ throw new FaFaError(
2473
+ "CONFIG_INVALID",
2474
+ "FaFa background service is not installed. Run `fafa service install` first."
2475
+ );
2476
+ }
2477
+ if (ctx.platform === "darwin") {
2478
+ await ctx.runner("launchctl", ["bootstrap", `gui/${ctx.uid}`, ctx.serviceFile]);
2479
+ await ctx.runner("launchctl", ["kickstart", "-k", `gui/${ctx.uid}/${MACOS_LAUNCHD_LABEL}`]);
2480
+ } else if (ctx.platform === "linux") {
2481
+ await ctx.runner("systemctl", ["--user", "start", LINUX_SYSTEMD_UNIT]);
2482
+ } else if (ctx.platform === "win32") {
2483
+ await ctx.runner("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME]);
2484
+ }
2485
+ if (!options.runner) {
2486
+ await waitForDaemonReady(ctx.home);
2487
+ }
2488
+ return getUserServiceStatus(options);
2489
+ }
2490
+ async function stopUserService(options = {}) {
2491
+ const ctx = resolveServiceContext(options);
2492
+ if (ctx.platform === "darwin") {
2493
+ await ctx.runner("launchctl", ["bootout", `gui/${ctx.uid}/${MACOS_LAUNCHD_LABEL}`]);
2494
+ } else if (ctx.platform === "linux") {
2495
+ await ctx.runner("systemctl", ["--user", "stop", LINUX_SYSTEMD_UNIT]);
2496
+ } else if (ctx.platform === "win32") {
2497
+ await ctx.runner("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME]);
2498
+ }
2499
+ const state = await readDaemonState(ctx.home);
2500
+ if (state && !options.runner) {
2501
+ try {
2502
+ process.kill(state.pid, "SIGTERM");
2503
+ } catch {
2504
+ }
2505
+ await clearDaemonState(state.pid, ctx.home);
2506
+ }
2507
+ return getUserServiceStatus(options);
2508
+ }
2509
+ async function restartUserService(options = {}) {
2510
+ await stopUserService(options);
2511
+ return startUserService(options);
2512
+ }
2513
+ async function readServiceLogs(options = {}) {
2514
+ const ctx = resolveServiceContext(options);
2515
+ const limit = Math.min(2e3, Math.max(1, Math.trunc(options.lines ?? 80)));
2516
+ if (!await fileExists3(ctx.logPath)) {
2517
+ return { logPath: ctx.logPath, lines: [] };
2518
+ }
2519
+ const content = await readFile3(ctx.logPath, "utf8");
2520
+ const allLines = content.split(/\r?\n/).filter((line2, idx, arr) => idx < arr.length - 1 || line2.length > 0);
2521
+ return {
2522
+ logPath: ctx.logPath,
2523
+ lines: allLines.slice(-limit)
2524
+ };
2525
+ }
2526
+
2527
+ // src/commands/workbench.ts
2528
+ var execFileAsync2 = promisify2(execFile2);
2529
+ async function fileExists4(path) {
2530
+ try {
2531
+ await access6(path);
2532
+ return true;
2533
+ } catch {
2534
+ return false;
2535
+ }
2536
+ }
2537
+ async function isBuiltWebDistDir(candidate) {
2538
+ return await fileExists4(join6(candidate, "index.html")) && await fileExists4(join6(candidate, "assets"));
2539
+ }
2540
+ async function resolveWebDistDir(explicit) {
2541
+ if (explicit) {
2542
+ const resolved = resolve5(explicit);
2543
+ if (await fileExists4(join6(resolved, "index.html"))) return resolved;
2544
+ }
2545
+ const moduleDir = dirname4(fileURLToPath(import.meta.url));
2546
+ const candidates = [
2547
+ resolve5(moduleDir, "../web"),
2548
+ resolve5(moduleDir, "../../web/dist"),
2549
+ resolve5(moduleDir, "../../../web/dist")
2550
+ ];
2551
+ for (const candidate of candidates) {
2552
+ if (await isBuiltWebDistDir(candidate)) {
2553
+ return candidate;
2554
+ }
2555
+ }
2556
+ return void 0;
2557
+ }
2558
+ async function defaultOpenBrowser(url) {
2559
+ try {
2560
+ if (process.platform === "darwin") {
2561
+ await execFileAsync2("open", [url]);
2562
+ return;
2563
+ }
2564
+ if (process.platform === "win32") {
2565
+ await execFileAsync2("cmd", ["/c", "start", "", url]);
2566
+ return;
2567
+ }
2568
+ await execFileAsync2("xdg-open", [url]);
2569
+ } catch {
2570
+ }
2571
+ }
2572
+ function parsePortOption(raw, errorMessage) {
2573
+ if (raw === void 0) return DEFAULT_WEB_PORT;
2574
+ const parsed = Number(raw);
2575
+ if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
2576
+ throw new FaFaError("CONFIG_INVALID", errorMessage);
2577
+ }
2578
+ return parsed;
2579
+ }
2580
+ async function resolveOptionalLibraryId(directory, projectFlag, initialize, home) {
2581
+ const candidate = directory ?? projectFlag;
2582
+ if (!candidate) return void 0;
2583
+ const target = resolve5(candidate);
2584
+ const hasConfig = await fileExists4(join6(target, CONFIG_FILENAME));
2585
+ if (!hasConfig && !initialize) {
2586
+ throw new FaFaError(
2587
+ "PROJECT_NOT_FOUND",
2588
+ `No ${CONFIG_FILENAME} found in ${target}. Pass --init or initialize inside the Web Workbench.`
2589
+ );
2590
+ }
2591
+ const registered = await registerLibrary({ root: target, initialize }, home);
2592
+ return registered.library.id;
2593
+ }
2594
+ function registerWorkbenchCommands(program, context, dependencies = {}) {
2595
+ const t = context.translate();
2596
+ const openBrowser = dependencies.openBrowser ?? defaultOpenBrowser;
2597
+ program.command("ui [directory]").alias("serve").description(t("ui.description")).option("--port <number>", t("ui.port")).option("--no-open", t("ui.noOpen")).option("--foreground", t("ui.foreground")).option("--init", t("ui.init")).action(
2598
+ async (directory, options) => {
2599
+ const currentT = context.translate();
2600
+ const home = context.home();
2601
+ const port = parsePortOption(options.port, currentT("ui.portError"));
2602
+ const shouldOpen = options.open !== false;
2603
+ const libraryId = await resolveOptionalLibraryId(
2604
+ directory,
2605
+ context.globals().project,
2606
+ Boolean(options.init),
2607
+ home
2608
+ );
2609
+ const libraryRoute = libraryId ? `/libraries/${encodeURIComponent(libraryId)}` : "/";
2610
+ if (!options.foreground) {
2611
+ const running = await probeRunningDaemon(home);
2612
+ if (running.running && running.url && running.state) {
2613
+ const launchUrl2 = `${running.url}${libraryRoute}`;
2614
+ if (shouldOpen) {
2615
+ await openBrowser(launchUrl2);
2616
+ }
2617
+ success(
2618
+ context.io,
2619
+ context.json(),
2620
+ "ui",
2621
+ {
2622
+ mode: "reused",
2623
+ url: running.url,
2624
+ launchUrl: launchUrl2,
2625
+ port: running.state.port,
2626
+ pid: running.state.pid,
2627
+ ...libraryId ? { libraryId } : {}
2628
+ },
2629
+ currentT("ui.reused", { url: launchUrl2 })
2630
+ );
2631
+ return;
2632
+ }
2633
+ }
2634
+ const webDistDir = await resolveWebDistDir(dependencies.webDistDir);
2635
+ const server = await startWebWorkbenchServer({
2636
+ home,
2637
+ port,
2638
+ ...webDistDir ? { webDistDir } : {},
2639
+ appVersion: package_default.version,
2640
+ writeDaemonState: true
2641
+ });
2642
+ const launchUrl = server.issueLaunchUrl(libraryId);
2643
+ success(
2644
+ context.io,
2645
+ context.json(),
2646
+ "ui",
2647
+ {
2648
+ mode: "foreground",
2649
+ url: server.url,
2650
+ launchUrl,
2651
+ port: server.port,
2652
+ pid: process.pid,
2653
+ ...libraryId ? { libraryId } : {}
2654
+ },
2655
+ currentT("ui.started", { url: server.url })
2656
+ );
2657
+ if (!context.json()) {
2658
+ context.io.stdout(line(currentT("ui.launchHint", { url: launchUrl })));
2659
+ }
2660
+ if (shouldOpen) {
2661
+ await openBrowser(launchUrl);
2662
+ }
2663
+ await new Promise((resolveStop) => {
2664
+ const shutdown = () => {
2665
+ process.off("SIGINT", shutdown);
2666
+ process.off("SIGTERM", shutdown);
2667
+ void server.close().finally(() => resolveStop());
2668
+ };
2669
+ process.on("SIGINT", shutdown);
2670
+ process.on("SIGTERM", shutdown);
2671
+ });
2672
+ }
2673
+ );
2674
+ const serviceCmd = program.command("service").description(t("service.description"));
2675
+ serviceCmd.command("install").description(t("service.install.description")).option("--port <number>", t("ui.port")).action(async (options) => {
2676
+ const currentT = context.translate();
2677
+ const home = context.home();
2678
+ const port = parsePortOption(options.port, currentT("ui.portError"));
2679
+ const status = await installUserService({
2680
+ home,
2681
+ port,
2682
+ ...dependencies.serviceRunner ? { runner: dependencies.serviceRunner } : {}
2683
+ });
2684
+ success(
2685
+ context.io,
2686
+ context.json(),
2687
+ "service install",
2688
+ status,
2689
+ currentT("service.install.success", { url: status.url })
2690
+ );
2691
+ });
2692
+ serviceCmd.command("uninstall").description(t("service.uninstall.description")).action(async () => {
2693
+ const currentT = context.translate();
2694
+ const status = await uninstallUserService({
2695
+ home: context.home(),
2696
+ ...dependencies.serviceRunner ? { runner: dependencies.serviceRunner } : {}
2697
+ });
2698
+ success(context.io, context.json(), "service uninstall", status, currentT("service.uninstall.success"));
2699
+ });
2700
+ serviceCmd.command("status").description(t("service.status.description")).action(async () => {
2701
+ const currentT = context.translate();
2702
+ const home = context.home();
2703
+ const status = await getUserServiceStatus({ home });
2704
+ const summary = status.running ? currentT("service.status.running", { url: status.url, pid: status.pid ?? 0 }) : status.installed ? currentT("service.status.stopped", { url: status.url }) : currentT("service.status.notInstalled");
2705
+ success(context.io, context.json(), "service status", status, summary);
2706
+ if (!context.json()) {
2707
+ context.io.stdout(line(` service: ${status.serviceFile}`));
2708
+ context.io.stdout(line(` log: ${status.logPath}`));
2709
+ }
2710
+ });
2711
+ serviceCmd.command("start").description(t("service.start.description")).action(async () => {
2712
+ const currentT = context.translate();
2713
+ const status = await startUserService({
2714
+ home: context.home(),
2715
+ ...dependencies.serviceRunner ? { runner: dependencies.serviceRunner } : {}
2716
+ });
2717
+ success(
2718
+ context.io,
2719
+ context.json(),
2720
+ "service start",
2721
+ status,
2722
+ currentT("service.start.success", { url: status.url })
2723
+ );
2724
+ });
2725
+ serviceCmd.command("stop").description(t("service.stop.description")).action(async () => {
2726
+ const currentT = context.translate();
2727
+ const status = await stopUserService({
2728
+ home: context.home(),
2729
+ ...dependencies.serviceRunner ? { runner: dependencies.serviceRunner } : {}
2730
+ });
2731
+ success(context.io, context.json(), "service stop", status, currentT("service.stop.success"));
2732
+ });
2733
+ serviceCmd.command("restart").description(t("service.restart.description")).action(async () => {
2734
+ const currentT = context.translate();
2735
+ const status = await restartUserService({
2736
+ home: context.home(),
2737
+ ...dependencies.serviceRunner ? { runner: dependencies.serviceRunner } : {}
2738
+ });
2739
+ success(
2740
+ context.io,
2741
+ context.json(),
2742
+ "service restart",
2743
+ status,
2744
+ currentT("service.restart.success", { url: status.url })
2745
+ );
2746
+ });
2747
+ serviceCmd.command("logs").description(t("service.logs.description")).option("--lines <number>", t("service.logs.lines"), "80").action(async (options) => {
2748
+ const currentT = context.translate();
2749
+ const linesCount = Number(options.lines ?? "80");
2750
+ const result = await readServiceLogs({
2751
+ home: context.home(),
2752
+ lines: Number.isFinite(linesCount) ? linesCount : 80
2753
+ });
2754
+ if (context.json()) {
2755
+ success(context.io, true, "service logs", result, "");
2756
+ return;
2757
+ }
2758
+ if (result.lines.length === 0) {
2759
+ context.io.stdout(line(currentT("service.logs.empty", { path: result.logPath })));
2760
+ return;
2761
+ }
2762
+ for (const entry of result.lines) {
2763
+ context.io.stdout(line(entry));
2764
+ }
2765
+ });
2766
+ }
2767
+
2768
+ // src/program.ts
2769
+ function createCli(io = defaultIo, initialLocale = localeFromEnvironment(process.env), dependencies = {}) {
2770
+ const t = createCliTranslator(initialLocale);
2771
+ const program = new Command();
2772
+ program.name("fafa").description(t("app.description")).version(package_default.version).option("--json", t("option.json")).option("--project <path>", t("option.project")).option("--home <path>", t("option.home")).option("--language <locale>", t("option.language")).showHelpAfterError().exitOverride().configureOutput({
2773
+ writeOut: (message) => io.stdout(message),
2774
+ writeErr: (message) => io.stderr(message)
2775
+ });
2776
+ const context = createCliContext(program, io, initialLocale);
2777
+ registerProjectCommands(program, context);
2778
+ registerStyleCommands(program, context);
2779
+ registerArticleCommands(program, context);
2780
+ registerExportCommand(program, context, dependencies);
2781
+ registerBrowserCommands(program, context, dependencies);
2782
+ registerDraftCommands(program, context);
2783
+ registerOperationsCommand(program, context);
2784
+ registerAccountCommands(program, context);
2785
+ registerWorkbenchCommands(program, context, dependencies);
2786
+ return program;
2787
+ }
2788
+
2789
+ // src/index.ts
2790
+ async function runCli(argv = process.argv, io = defaultIo, dependencies = {}) {
2791
+ const json = argv.includes("--json");
2792
+ const environmentLocale = localeFromEnvironment(process.env);
2793
+ try {
2794
+ const locale = resolveCliLocale(languageFromArgv(argv), environmentLocale);
2795
+ await createCli(io, locale, dependencies).parseAsync(argv, { from: "node" });
2796
+ return 0;
2797
+ } catch (error) {
2798
+ const code = exitCode(error);
2799
+ failure(io, json, error, code);
2800
+ return code;
2801
+ }
2802
+ }
2803
+
2804
+ export {
2805
+ createCli,
2806
+ runCli
2807
+ };