yukari-dsh-plugin 0.0.0-stage → 0.7.2

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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/client.js +8340 -0
  4. package/cordis.patch.yml +95 -0
  5. package/host/browser/index.js +397 -0
  6. package/host/browser/lib/browser.js +885 -0
  7. package/host/browser/lib/cdp.js +302 -0
  8. package/host/browser/lib/libraries.js +309 -0
  9. package/host/browser/lib/page-scripts.js +243 -0
  10. package/host/browser/lib/runtime.js +351 -0
  11. package/host/browser/lib/url-guard.js +122 -0
  12. package/host/browser/locale/en.json +6 -0
  13. package/host/browser/locale/zh.json +6 -0
  14. package/host/chats/index.js +254 -0
  15. package/host/chats/lib/admin.js +893 -0
  16. package/host/chats/lib/cleanup.js +272 -0
  17. package/host/chats/lib/paths.js +108 -0
  18. package/host/chats/lib/preview.js +74 -0
  19. package/host/chats/locale/en.json +6 -0
  20. package/host/chats/locale/zh.json +6 -0
  21. package/host/files/index.js +403 -0
  22. package/host/files/locale/en.json +6 -0
  23. package/host/files/locale/zh.json +6 -0
  24. package/host/github/index.js +121 -0
  25. package/host/github/lib/api.js +310 -0
  26. package/host/github/lib/atomic.js +42 -0
  27. package/host/github/lib/controller.js +450 -0
  28. package/host/github/lib/git.js +389 -0
  29. package/host/github/lib/redact.js +22 -0
  30. package/host/github/lib/signing.js +124 -0
  31. package/host/github/lib/store.js +181 -0
  32. package/host/github/locale/en.json +6 -0
  33. package/host/github/locale/zh.json +6 -0
  34. package/host/presets/index.js +450 -0
  35. package/host/presets/lib/definition.js +267 -0
  36. package/host/presets/lib/sources.js +278 -0
  37. package/host/presets/lib/store.js +136 -0
  38. package/host/presets/locale/en.json +6 -0
  39. package/host/presets/locale/zh.json +6 -0
  40. package/host/proxy/index.js +236 -0
  41. package/host/proxy/lib/controller.js +1151 -0
  42. package/host/proxy/lib/egress.js +120 -0
  43. package/host/proxy/lib/local-proxy.js +422 -0
  44. package/host/proxy/lib/shadowsocks.js +335 -0
  45. package/host/proxy/lib/ss-uri.js +501 -0
  46. package/host/proxy/lib/subscriptions.js +140 -0
  47. package/host/proxy/locale/en.json +6 -0
  48. package/host/proxy/locale/zh.json +6 -0
  49. package/host/purge/index.js +538 -0
  50. package/host/purge/lib/preset.js +140 -0
  51. package/host/purge/lib/prompts.js +95 -0
  52. package/host/purge/lib/retry-gate.js +97 -0
  53. package/host/purge/lib/rewriter.js +322 -0
  54. package/host/purge/lib/settings.js +54 -0
  55. package/host/purge/lib/stream-retry.js +255 -0
  56. package/host/purge/locale/en.json +6 -0
  57. package/host/purge/locale/zh.json +6 -0
  58. package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
  59. package/host/purge/presets/unrestricted/preset.json +75 -0
  60. package/host/purge/presets/unrestricted/preset.yml +3 -0
  61. package/host/rewind/index.js +127 -0
  62. package/host/rewind/lib/controller.js +449 -0
  63. package/host/rewind/lib/marker.js +53 -0
  64. package/host/rewind/lib/safe-path.js +47 -0
  65. package/host/rewind/lib/store.js +585 -0
  66. package/host/rewind/lib/surface.js +108 -0
  67. package/host/rewind/locale/en.json +6 -0
  68. package/host/rewind/locale/zh.json +6 -0
  69. package/host/rules/index.js +624 -0
  70. package/host/rules/lib/paths.js +87 -0
  71. package/host/rules/lib/render.js +92 -0
  72. package/host/rules/lib/scope.js +146 -0
  73. package/host/rules/lib/settings.js +55 -0
  74. package/host/rules/lib/store.js +222 -0
  75. package/host/rules/locale/en.json +6 -0
  76. package/host/rules/locale/zh.json +6 -0
  77. package/host/runtime/index.js +577 -0
  78. package/host/runtime/lib/npm.js +293 -0
  79. package/host/runtime/lib/restart.js +105 -0
  80. package/host/runtime/lib/update-guard.js +70 -0
  81. package/host/runtime/lib/versions.js +188 -0
  82. package/host/runtime/locale/en.json +6 -0
  83. package/host/runtime/locale/zh.json +6 -0
  84. package/host/shared/busy.js +40 -0
  85. package/host/shared/home.js +27 -0
  86. package/host/shared/http.js +159 -0
  87. package/host/shared/migrate.js +60 -0
  88. package/host/shared/mounted.js +54 -0
  89. package/host/shared/zip-writer.js +319 -0
  90. package/host/shared/zip.js +180 -0
  91. package/host/sites/index.js +258 -0
  92. package/host/sites/lib/sites.js +630 -0
  93. package/host/sites/locale/en.json +6 -0
  94. package/host/sites/locale/zh.json +6 -0
  95. package/host/skills/index.js +176 -0
  96. package/host/skills/lib/frontmatter.js +149 -0
  97. package/host/skills/lib/library.js +408 -0
  98. package/host/skills/lib/upload.js +115 -0
  99. package/host/skills/locale/en.json +6 -0
  100. package/host/skills/locale/zh.json +6 -0
  101. package/icon.png +0 -0
  102. package/index.js +702 -0
  103. package/locale/en.json +5 -0
  104. package/locale/zh.json +5 -0
  105. package/package.json +113 -4
@@ -0,0 +1,630 @@
1
+ /**
2
+ * Filesystem side of static-site publishing.
3
+ *
4
+ * The publish root is the directory the web server exposes at `/p/`, so
5
+ * everything inside it is public. Manifests, staging and trash therefore live
6
+ * outside the root, under the state directory, and never reach the Web.
7
+ * @module @local/publish-sites/lib/sites
8
+ */
9
+ import { chmod, cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
10
+ import { isIP } from 'node:net'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+
14
+ /** Allowed URL segment. */
15
+ const SLUG = /^[a-z0-9][a-z0-9._-]{0,40}$/
16
+
17
+ /** Bound recursive copies as well as total bytes. */
18
+ const DEFAULT_MAX_FILES = 10000
19
+
20
+ /** Directory under the user's home used when the row names no publish root. */
21
+ const DEFAULT_ROOT_NAME = 'publish'
22
+
23
+ /**
24
+ * Publish roots that earlier versions of this component shipped as their default.
25
+ *
26
+ * 默认根改成 `~/publish` 之后,升级上来的安装会对着一个空目录:站点还在旧目录里,
27
+ * 面板却列不出来。启动时按这份名单接管旧目录,不搬、不删。这是迁移名单,不是配置项。
28
+ */
29
+ const LEGACY_DEFAULT_ROOTS = ['/workspace/publish']
30
+
31
+ /**
32
+ * Prefix assumed when the row names none.
33
+ *
34
+ * 相对路径,由面板拼上当前来源:换个部署、换个端口都不用改配置。
35
+ */
36
+ const DEFAULT_PUBLIC_BASE = '/p'
37
+
38
+ /** An asset reference that resolves against the origin root instead of the site. */
39
+ const ROOT_LINK = /(?:src|href)\s*=\s*["']\/[^/"']/i
40
+
41
+ /** Skip absurdly large HTML files when scanning for root links. */
42
+ const MAX_HTML_SCAN_BYTES = 4 * 1024 * 1024
43
+
44
+ /** Read one positive number from config. */
45
+ function positive(value, fallback) {
46
+ return Number.isFinite(value) && value > 0 ? Number(value) : fallback
47
+ }
48
+
49
+ /** Human-readable byte count. */
50
+ function formatBytes(bytes) {
51
+ const value = Number(bytes) || 0
52
+ if (value < 1024) return `${value} B`
53
+ if (value < 1048576) return `${(value / 1024).toFixed(1)} KB`
54
+ return `${(value / 1048576).toFixed(1)} MB`
55
+ }
56
+
57
+ /** Recursive walk yielding regular files and rejecting every symbolic link. */
58
+ async function* walk(directory, sourceRoot = directory) {
59
+ const entries = await readdir(directory, { withFileTypes: true })
60
+ for (const entry of entries) {
61
+ const file = path.join(directory, entry.name)
62
+ if (entry.isSymbolicLink()) {
63
+ throw new Error(`不允许符号链接:${path.relative(sourceRoot, file) || file}`)
64
+ }
65
+ if (entry.isDirectory()) {
66
+ yield* walk(file, sourceRoot)
67
+ } else if (entry.isFile()) {
68
+ yield { file, size: (await stat(file)).size }
69
+ }
70
+ }
71
+ }
72
+
73
+ /** First path in `directory` derived from `base` that does not exist yet. */
74
+ async function uniquePath(directory, base) {
75
+ let candidate = path.join(directory, base)
76
+ let counter = 2
77
+ for (;;) {
78
+ try {
79
+ await lstat(candidate)
80
+ candidate = path.join(directory, `${base}-${counter}`)
81
+ counter += 1
82
+ } catch {
83
+ return candidate
84
+ }
85
+ }
86
+ }
87
+
88
+ /** A local timestamp usable in a directory name, unique within one run. */
89
+ function stamp() {
90
+ const now = new Date()
91
+ const pad = (value) => String(value).padStart(2, '0')
92
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
93
+ }
94
+
95
+ /**
96
+ * Validate one public URL prefix. A bare host gets `https://`; a trailing
97
+ * slash, query or fragment is dropped.
98
+ * @param value - user input.
99
+ * @returns the normalized prefix without a trailing slash.
100
+ */
101
+ export function normalizePublicBase(value) {
102
+ let text = String(value ?? '').trim()
103
+ if (text === '') throw new Error('访问前缀不能为空')
104
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) text = `https://${text}`
105
+ let url
106
+ try {
107
+ url = new URL(text)
108
+ } catch {
109
+ throw new Error(`不是有效的网址:${value}`)
110
+ }
111
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('访问前缀只支持 http:// 或 https://')
112
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, '')
113
+ }
114
+
115
+ /**
116
+ * Why a host cannot carry published pages, or null when it can.
117
+ *
118
+ * Loopback, unspecified and link-local addresses point back at this machine —
119
+ * either at the panel itself or at the cloud metadata endpoint — so a prefix
120
+ * naming one of them turns every publish probe into a request from the Host.
121
+ * Private RFC1918 ranges stay allowed: publishing to the LAN is a real use.
122
+ * @param hostname - parsed hostname, IPv6 brackets included or not.
123
+ */
124
+ function forbiddenHostReason(hostname) {
125
+ const host = String(hostname).trim().toLowerCase().replace(/^\[|\]$/g, '')
126
+ if (host === 'localhost' || host.endsWith('.localhost')) return '本机回环地址'
127
+ const version = isIP(host)
128
+ if (version === 4) {
129
+ const octets = host.split('.').map(Number)
130
+ if (octets[0] === 127 || octets[0] === 0) return '本机回环地址'
131
+ if (octets[0] === 169 && octets[1] === 254) return '链路本地地址'
132
+ }
133
+ if (version === 6) {
134
+ if (host === '::1' || host === '::') return '本机回环地址'
135
+ if (/^fe[89ab]/.test(host)) return '链路本地地址'
136
+ if (/^f[cd]/.test(host)) return '唯一本地地址'
137
+ }
138
+ return null
139
+ }
140
+
141
+ /**
142
+ * Why a prefix cannot be used, or null when it can.
143
+ * @param value - prefix text from the panel or the row config.
144
+ * @param panelHost - `Host` header of the panel request; a prefix on it would
145
+ * share the panel's origin and therefore its session.
146
+ */
147
+ export function publicBaseRejection(value, panelHost = '') {
148
+ const text = String(value ?? '').trim()
149
+ if (text === '') return null
150
+ let url
151
+ try {
152
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`)
153
+ } catch {
154
+ return '不是合法的网址'
155
+ }
156
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return '只支持 http 与 https'
157
+ const forbidden = forbiddenHostReason(url.hostname)
158
+ if (forbidden !== null) return forbidden
159
+ const panel = String(panelHost ?? '').trim().toLowerCase()
160
+ if (panel !== '' && url.host.toLowerCase() === panel) {
161
+ return '与面板同源,页面里的脚本会带着面板的登录态访问接口'
162
+ }
163
+ return null
164
+ }
165
+
166
+ /** Names that must never be served from the publish root. */
167
+ const NEVER_PUBLISH = /(^|\/)(\.git|\.env[^/]*|node_modules)(\/|$)|(^|\/)[^/]+\.(pem|key|p12|pfx)$/
168
+
169
+ export class SiteStore {
170
+ /**
171
+ * @param config - root, stateRoot, publicBase, maxMb, keep, legacyRoots.
172
+ */
173
+ constructor(config = {}) {
174
+ // 空字符串是「没配」,不是「当前目录」:path.resolve('') 会落到 cwd。
175
+ const configuredRoot = String(config.root ?? '').trim()
176
+ /** 用户显式配了目录时一律照用,不猜测旧位置。 */
177
+ this.explicitRoot = configuredRoot !== ''
178
+ this.explicitStateRoot = String(config.stateRoot ?? '').trim() !== ''
179
+ const root = path.resolve(configuredRoot === '' ? path.join(os.homedir(), DEFAULT_ROOT_NAME) : configuredRoot)
180
+ this.root = root
181
+ this.stateRoot = path.resolve(String(config.stateRoot ?? path.join(path.dirname(root), '.publish-state')))
182
+ /** 接管来的旧发布目录;面板据此说明为什么路径与默认值不同。 */
183
+ this.adoptedFrom = null
184
+ this.legacyRoots = Array.isArray(config.legacyRoots) && config.legacyRoots.length > 0
185
+ ? config.legacyRoots.map((value) => path.resolve(String(value)))
186
+ : LEGACY_DEFAULT_ROOTS.map((value) => path.resolve(value))
187
+ this.defaultPublicBase = typeof config.publicBase === 'string' && config.publicBase.trim() !== ''
188
+ ? config.publicBase.trim().replace(/\/+$/, '')
189
+ : DEFAULT_PUBLIC_BASE
190
+ /** Prefix saved from the panel; overrides the row config when set. */
191
+ this.customPublicBase = null
192
+ this.maxMb = positive(config.maxMb, 200)
193
+ this.maxFiles = positive(config.maxFiles, DEFAULT_MAX_FILES)
194
+ this.keep = positive(config.keep, 5)
195
+ this.ready = null
196
+ /** Mutations run one at a time: staging, trash and manifests are shared. */
197
+ this.queue = Promise.resolve()
198
+ }
199
+
200
+ /** URL prefix every site link starts with. */
201
+ get publicBase() {
202
+ return this.customPublicBase ?? this.defaultPublicBase
203
+ }
204
+
205
+ /** Panel settings, kept out of the public root. */
206
+ get settingsFile() {
207
+ return path.join(this.stateRoot, 'settings.json')
208
+ }
209
+
210
+ /** Manifests of published sites, kept out of the public root. */
211
+ get sitesDir() {
212
+ return path.join(this.stateRoot, 'sites')
213
+ }
214
+
215
+ /** Partially copied sites, kept out of the public root. */
216
+ get stagingDir() {
217
+ return path.join(this.stateRoot, 'staging')
218
+ }
219
+
220
+ /** Previous generations, kept out of the public root. */
221
+ get trashDir() {
222
+ return path.join(this.stateRoot, 'trash')
223
+ }
224
+
225
+ /**
226
+ * Keep using the directory an older default pointed at.
227
+ *
228
+ * 只在新目录里一张站点清单都没有、且用户没显式配 root 时接管:文件原地不动,
229
+ * 旧目录继续对外提供,不需要重新发布。
230
+ * @returns the adopted root, or null.
231
+ */
232
+ async #adoptLegacyRoot() {
233
+ if (this.explicitRoot) return null
234
+ if (await this.#hasManifests(this.stateRoot)) return null
235
+ for (const candidate of this.legacyRoots) {
236
+ if (candidate === this.root) continue
237
+ const stateRoot = path.join(path.dirname(candidate), '.publish-state')
238
+ if (!(await this.#hasManifests(stateRoot))) continue
239
+ this.root = candidate
240
+ if (!this.explicitStateRoot) this.stateRoot = stateRoot
241
+ this.adoptedFrom = candidate
242
+ return candidate
243
+ }
244
+ return null
245
+ }
246
+
247
+ /** Whether one state directory already holds site manifests. */
248
+ async #hasManifests(stateRoot) {
249
+ try {
250
+ const entries = await readdir(path.join(stateRoot, 'sites'))
251
+ return entries.some((name) => name.endsWith('.json'))
252
+ } catch {
253
+ return false
254
+ }
255
+ }
256
+
257
+ /** Create every directory once and load the saved prefix. */
258
+ async init() {
259
+ if (this.ready === null) {
260
+ this.ready = (async () => {
261
+ await this.#adoptLegacyRoot()
262
+ await mkdir(this.root, { recursive: true })
263
+ await mkdir(this.sitesDir, { recursive: true })
264
+ await mkdir(this.stagingDir, { recursive: true })
265
+ await mkdir(this.trashDir, { recursive: true })
266
+ try {
267
+ const saved = JSON.parse(await readFile(this.settingsFile, 'utf8'))
268
+ if (typeof saved?.publicBase === 'string' && saved.publicBase !== '') {
269
+ this.customPublicBase = normalizePublicBase(saved.publicBase)
270
+ }
271
+ } catch {
272
+ // No saved prefix yet, or an unreadable one: keep the row config.
273
+ }
274
+ })().catch((error) => {
275
+ // A failed first init must be retryable; a cached rejected promise
276
+ // would keep every later request failing with the same error.
277
+ this.ready = null
278
+ throw error
279
+ })
280
+ }
281
+ return await this.ready
282
+ }
283
+
284
+ /**
285
+ * Save the URL prefix site links use; an empty value restores the row config.
286
+ * @param value - e.g. `https://pages.example.com` or `https://dsh.example.com/p`.
287
+ * @returns the prefix now in effect.
288
+ */
289
+ async setPublicBase(value, options = {}) {
290
+ await this.init()
291
+ const text = String(value ?? '').trim()
292
+ const rejection = publicBaseRejection(text, options.panelHost)
293
+ if (rejection !== null) {
294
+ const error = new Error(`该前缀不能使用:${rejection}。请填写站点实际的对外地址。`)
295
+ error.appCode = 'base-forbidden'
296
+ throw error
297
+ }
298
+ this.customPublicBase = text === '' ? null : normalizePublicBase(text)
299
+ const staging = `${this.settingsFile}.${process.pid}.tmp`
300
+ await writeFile(staging, `${JSON.stringify({ publicBase: this.customPublicBase ?? '' }, null, 2)}\n`)
301
+ await rename(staging, this.settingsFile)
302
+ return this.publicBase
303
+ }
304
+
305
+ /** Run one mutating operation after the previous one has finished. */
306
+ serialized(work) {
307
+ const next = this.queue.then(work, work)
308
+ this.queue = next.then(() => {}, () => {})
309
+ return next
310
+ }
311
+
312
+ /** Public URL of one site. */
313
+ urlOf(slug) {
314
+ return `${this.publicBase}/${slug}/`
315
+ }
316
+
317
+ /** Reject a slug that could escape the publish root. */
318
+ assertSlug(slug) {
319
+ if (!SLUG.test(slug)) {
320
+ throw new Error(`无效的 slug「${slug}」:只能用小写字母、数字、点、短横线和下划线(1-41 字符)`)
321
+ }
322
+ const target = path.resolve(this.root, slug)
323
+ if (path.dirname(target) !== this.root) throw new Error(`无效的 slug「${slug}」`)
324
+ return target
325
+ }
326
+
327
+ /** Read every manifest, and adopt directories that have none. */
328
+ async list() {
329
+ await this.init()
330
+ const records = new Map()
331
+ let names = []
332
+ try {
333
+ names = await readdir(this.sitesDir)
334
+ } catch {
335
+ names = []
336
+ }
337
+ for (const name of names) {
338
+ if (!name.endsWith('.json')) continue
339
+ try {
340
+ const record = JSON.parse(await readFile(path.join(this.sitesDir, name), 'utf8'))
341
+ if (record && typeof record.slug === 'string') records.set(record.slug, record)
342
+ } catch {
343
+ // A damaged manifest must not hide the site itself.
344
+ }
345
+ }
346
+ let directories = []
347
+ try {
348
+ directories = await readdir(this.root, { withFileTypes: true })
349
+ } catch {
350
+ directories = []
351
+ }
352
+ for (const entry of directories) {
353
+ if (!entry.isDirectory() || entry.name.startsWith('.') || !SLUG.test(entry.name)) continue
354
+ if (records.has(entry.name)) continue
355
+ records.set(entry.name, { slug: entry.name, title: entry.name, version: 1 })
356
+ }
357
+ const sites = []
358
+ for (const record of records.values()) {
359
+ const directory = path.join(this.root, record.slug)
360
+ let info = null
361
+ try {
362
+ info = await stat(directory)
363
+ } catch {
364
+ info = null
365
+ }
366
+ if (info === null || !info.isDirectory()) continue
367
+ sites.push({
368
+ slug: record.slug,
369
+ title: record.title || record.slug,
370
+ url: this.urlOf(record.slug),
371
+ bytes: Number(record.bytes) || 0,
372
+ files: Number(record.files) || 0,
373
+ version: Number(record.version) || 1,
374
+ publishedAt: record.publishedAt || info.mtime.toISOString(),
375
+ })
376
+ }
377
+ sites.sort((a, b) => String(b.publishedAt).localeCompare(String(a.publishedAt)))
378
+ return sites
379
+ }
380
+
381
+ /**
382
+ * Copy one built site into the publish root and swap it in.
383
+ * @param request - source directory, optional slug and title.
384
+ * @returns the stored record.
385
+ */
386
+ publish(input) {
387
+ return this.serialized(() => this.publishNow(input))
388
+ }
389
+
390
+ /** Body of {@link publish}; callers go through the queue. */
391
+ async publishNow({ source, slug, title }) {
392
+ await this.init()
393
+ if (typeof source !== 'string' || source.trim() === '') throw new Error('必须指定源目录')
394
+ const from = path.resolve(source.trim())
395
+ let sourceInfo
396
+ try {
397
+ sourceInfo = await lstat(from)
398
+ } catch {
399
+ throw new Error(`源目录不存在:${from}`)
400
+ }
401
+ if (sourceInfo.isSymbolicLink()) throw new Error(`源目录不能是符号链接:${from}`)
402
+ if (!sourceInfo.isDirectory()) throw new Error(`源路径不是目录:${from}`)
403
+
404
+ const [realSource, realRoot, realState] = await Promise.all([
405
+ realpath(from),
406
+ realpath(this.root),
407
+ realpath(this.stateRoot),
408
+ ])
409
+ const protectedPath = (parent, child) => child === parent || child.startsWith(`${parent}${path.sep}`)
410
+ if (protectedPath(realRoot, realSource) || protectedPath(realState, realSource)
411
+ || protectedPath(realSource, realRoot) || protectedPath(realSource, realState)) {
412
+ throw new Error('源目录不能与发布目录或状态目录互相包含')
413
+ }
414
+
415
+ let files = 0
416
+ let bytes = 0
417
+ for await (const entry of walk(realSource)) {
418
+ files += 1
419
+ bytes += entry.size
420
+ if (files > this.maxFiles) throw new Error(`站点文件数超过 ${this.maxFiles} 个`)
421
+ }
422
+ if (bytes > this.maxMb * 1048576) {
423
+ throw new Error(`站点体积 ${formatBytes(bytes)},超过 ${this.maxMb} MB 上限`)
424
+ }
425
+ const index = await lstat(path.join(realSource, 'index.html')).catch(() => null)
426
+ if (!index?.isFile()) throw new Error(`源目录顶层缺少 index.html:${from}`)
427
+
428
+ const resolvedSlug = this.normalizeSlug(slug ?? path.basename(from))
429
+ const target = this.assertSlug(resolvedSlug)
430
+ // mkdtemp is atomic in the kernel: two publishes of one slug can never pick
431
+ // the same staging directory, which `lstat`-then-create could not promise.
432
+ const stage = await mkdtemp(path.join(this.stagingDir, `${resolvedSlug}-`))
433
+ let staged = false
434
+ let activated = false
435
+ let retired = null
436
+
437
+ try {
438
+ let skipped = 0
439
+ await cp(realSource, stage, {
440
+ recursive: true,
441
+ force: true,
442
+ dereference: false,
443
+ filter: async (file) => {
444
+ const relative = path.relative(realSource, file)
445
+ if (relative !== '' && NEVER_PUBLISH.test(relative)) {
446
+ skipped += 1
447
+ return false
448
+ }
449
+ return !(await lstat(file)).isSymbolicLink()
450
+ },
451
+ })
452
+ staged = true
453
+ await this.relax(stage)
454
+ await this.sanitize(stage)
455
+
456
+ // The pre-copy walk enforces the limits on the source; what actually ships
457
+ // is the staged copy after sanitize drops source maps, so measure that.
458
+ let servedFiles = 0
459
+ let servedBytes = 0
460
+ for await (const entry of walk(stage)) {
461
+ servedFiles += 1
462
+ servedBytes += entry.size
463
+ }
464
+ // The source can grow between the pre-copy walk and this one (a build
465
+ // still running). What ships is the staged copy, so the limit is applied
466
+ // there too — before anything is swapped in.
467
+ if (servedFiles > this.maxFiles) throw new Error(`站点文件数超过 ${this.maxFiles} 个`)
468
+ if (servedBytes > this.maxMb * 1048576) {
469
+ throw new Error(`站点体积 ${formatBytes(servedBytes)},超过 ${this.maxMb} MB 上限`)
470
+ }
471
+
472
+ const previous = await this.readManifest(resolvedSlug)
473
+ const nextTitle = (title && title.trim()) || (await this.titleOf(stage)) || resolvedSlug
474
+ const existing = await lstat(target).catch(() => null)
475
+ if (existing !== null) {
476
+ if (!existing.isDirectory() || existing.isSymbolicLink()) {
477
+ throw new Error(`发布目标不是普通目录:${target}`)
478
+ }
479
+ retired = await uniquePath(this.trashDir, `${resolvedSlug}@${stamp()}`)
480
+ await rename(target, retired)
481
+ }
482
+
483
+ const record = {
484
+ slug: resolvedSlug,
485
+ title: nextTitle,
486
+ url: this.urlOf(resolvedSlug),
487
+ bytes: servedBytes,
488
+ files: servedFiles,
489
+ version: (Number(previous?.version) || 0) + 1,
490
+ publishedAt: new Date().toISOString(),
491
+ source: from,
492
+ skipped,
493
+ }
494
+ try {
495
+ await rename(stage, target)
496
+ staged = false
497
+ activated = true
498
+ await this.writeManifest(record)
499
+ } catch (error) {
500
+ // Best-effort restoration: retain both the old directory and its manifest.
501
+ if (activated) {
502
+ await rename(target, stage).then(() => { staged = true }).catch(() => {})
503
+ }
504
+ if (retired !== null) await rename(retired, target).catch(() => {})
505
+ throw error
506
+ }
507
+ if (retired !== null) await this.rotate(resolvedSlug)
508
+ return record
509
+ } finally {
510
+ if (staged) await rm(stage, { recursive: true, force: true }).catch(() => {})
511
+ }
512
+ }
513
+
514
+ /** Move one site out of the publish root. */
515
+ remove(slug) {
516
+ return this.serialized(() => this.removeNow(slug))
517
+ }
518
+
519
+ /** Body of {@link remove}; callers go through the queue. */
520
+ async removeNow(slug) {
521
+ await this.init()
522
+ const resolved = this.normalizeSlug(slug)
523
+ const target = this.assertSlug(resolved)
524
+ let info = null
525
+ try {
526
+ info = await stat(target)
527
+ } catch {
528
+ info = null
529
+ }
530
+ if (info === null || !info.isDirectory()) return { slug: resolved, deleted: false }
531
+ await rename(target, await uniquePath(this.trashDir, `${resolved}@${stamp()}`))
532
+ await rm(path.join(this.sitesDir, `${resolved}.json`), { force: true })
533
+ // Publish rotates the trash; without the same call here, publishing and
534
+ // deleting the same site over and over grows full copies forever.
535
+ await this.rotate(resolved)
536
+ return { slug: resolved, deleted: true }
537
+ }
538
+
539
+ /** Normalize a user-supplied segment. */
540
+ normalizeSlug(value) {
541
+ const slug = String(value ?? '')
542
+ .trim()
543
+ .toLowerCase()
544
+ .replace(/\s+/g, '-')
545
+ if (slug === '') throw new Error('必须填写 slug')
546
+ return slug
547
+ }
548
+
549
+ /** Make the copy world-readable: the file service may not run as this user. */
550
+ async relax(directory) {
551
+ await chmod(directory, 0o755)
552
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
553
+ const file = path.join(directory, entry.name)
554
+ if (entry.isDirectory()) {
555
+ await this.relax(file)
556
+ } else if (entry.isFile()) {
557
+ await chmod(file, 0o644)
558
+ }
559
+ }
560
+ }
561
+
562
+ /** Drop source maps and refuse root-absolute asset links. */
563
+ async sanitize(directory) {
564
+ const offenders = []
565
+ for await (const entry of walk(directory)) {
566
+ if (/\.(?:js|css)\.map$/.test(entry.file)) {
567
+ await rm(entry.file, { force: true })
568
+ continue
569
+ }
570
+ if (!entry.file.endsWith('.html') || entry.size > MAX_HTML_SCAN_BYTES) continue
571
+ const text = await readFile(entry.file, 'utf8').catch(() => '')
572
+ if (ROOT_LINK.test(text)) offenders.push(path.relative(directory, entry.file))
573
+ }
574
+ if (offenders.length > 0) {
575
+ await rm(directory, { recursive: true, force: true })
576
+ throw new Error(
577
+ `发现根路径资源引用:${offenders.slice(0, 5).join(', ')};站点挂在 ${this.publicBase}/ 下,构建时请用相对路径(Vite 的 base: './')`,
578
+ )
579
+ }
580
+ }
581
+
582
+ /** Read the page title. */
583
+ async titleOf(directory) {
584
+ try {
585
+ const html = await readFile(path.join(directory, 'index.html'), 'utf8')
586
+ const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)
587
+ return match ? match[1].replace(/\s+/g, ' ').trim().slice(0, 80) : ''
588
+ } catch {
589
+ return ''
590
+ }
591
+ }
592
+
593
+ /** Read one manifest. */
594
+ async readManifest(slug) {
595
+ try {
596
+ return JSON.parse(await readFile(path.join(this.sitesDir, `${slug}.json`), 'utf8'))
597
+ } catch {
598
+ return null
599
+ }
600
+ }
601
+
602
+ /** Write one manifest atomically. */
603
+ async writeManifest(record) {
604
+ const file = path.join(this.sitesDir, `${record.slug}.json`)
605
+ const temporary = `${file}.tmp`
606
+ try {
607
+ await writeFile(temporary, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
608
+ await rename(temporary, file)
609
+ } finally {
610
+ await rm(temporary, { force: true }).catch(() => {})
611
+ }
612
+ }
613
+
614
+ /** Keep only the newest generations of one slug in the trash. */
615
+ async rotate(slug) {
616
+ let names = []
617
+ try {
618
+ names = await readdir(this.trashDir)
619
+ } catch {
620
+ return
621
+ }
622
+ const mine = names
623
+ .filter((name) => name.startsWith(`${slug}@`))
624
+ .sort()
625
+ .reverse()
626
+ for (const name of mine.slice(this.keep)) {
627
+ await rm(path.join(this.trashDir, name), { recursive: true, force: true })
628
+ }
629
+ }
630
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Sites",
4
+ "description": "Publish and unpublish static sites"
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "站点",
4
+ "description": "静态站点发布与下线"
5
+ }
6
+ }