@horizonwing/engine 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/drizzle/pg/schema.ts +100 -0
- package/drizzle/postgres/0000_smooth_princess_powerful.sql +34 -0
- package/drizzle/postgres/0001_colossal_morbius.sql +50 -0
- package/drizzle/postgres/README.md +23 -0
- package/drizzle/postgres/meta/0000_snapshot.json +244 -0
- package/drizzle/postgres/meta/0001_snapshot.json +545 -0
- package/drizzle/postgres/meta/_journal.json +20 -0
- package/drizzle/schema.ts +128 -0
- package/drizzle/sqlite/0000_cooing_jackpot.sql +34 -0
- package/drizzle/sqlite/0001_living_ben_urich.sql +49 -0
- package/drizzle/sqlite/meta/0000_snapshot.json +231 -0
- package/drizzle/sqlite/meta/0001_snapshot.json +554 -0
- package/drizzle/sqlite/meta/_journal.json +20 -0
- package/package.json +80 -4
- package/src/account-pages.tsx +152 -0
- package/src/auth.tsx +265 -0
- package/src/cache.ts +199 -0
- package/src/content.ts +448 -0
- package/src/db.ts +107 -0
- package/src/feeds.ts +376 -0
- package/src/guard.ts +126 -0
- package/src/html.ts +20 -0
- package/src/i18n.ts +304 -0
- package/src/index.ts +27 -0
- package/src/md.ts +278 -0
- package/src/media.ts +70 -0
- package/src/password.ts +59 -0
- package/src/platform.node.ts +98 -0
- package/src/platform.postgres.ts +61 -0
- package/src/platform.shared.ts +114 -0
- package/src/platform.ts +24 -0
- package/src/platform.workers.ts +94 -0
- package/src/ratelimit.ts +144 -0
- package/src/section.ts +123 -0
- package/src/sections/blog/index.tsx +93 -0
- package/src/sections/blog/schema.ts +12 -0
- package/src/sections/blog/views/pages.tsx +167 -0
- package/src/sections/docs/index.tsx +67 -0
- package/src/sections/docs/schema.ts +16 -0
- package/src/sections/docs/views/pages.tsx +181 -0
- package/src/sections/landing/index.tsx +42 -0
- package/src/sections/landing/views/pages.tsx +218 -0
- package/src/seo.ts +193 -0
- package/src/server.ts +122 -0
- package/src/services/content.ts +342 -0
- package/src/turnstile.ts +62 -0
- package/src/types.ts +192 -0
- package/src/views/error.tsx +36 -0
- package/src/views/index.tsx +13 -0
- package/src/views/layout.tsx +89 -0
- package/themes/warm/tokens.css +119 -0
- package/tsconfig.json +32 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { and, count, desc, eq, inArray, sql } from 'drizzle-orm';
|
|
2
|
+
import { RENDERER_VERSION, normalizeHeadingLevels, renderMarkdown } from '../md';
|
|
3
|
+
import { runAtomic } from '../db';
|
|
4
|
+
import type { AppDatabase } from '../db';
|
|
5
|
+
import { content, redirects } from '../../drizzle/schema';
|
|
6
|
+
import type { ContentArticle, ContentItemWithMeta, ContentListItem, PagedList } from '../types';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 内容 service 层(总设计 §2/§4/§10):运行时唯一的 content/redirects 数据出入口。
|
|
10
|
+
*
|
|
11
|
+
* 写路径纪律(总设计 §10):
|
|
12
|
+
* - 内容同步的 upsert 走 ON CONFLICT 受控路径(本文件 upsertContentRows / upsertRedirects);
|
|
13
|
+
* - 删除一律带 (section, locale, slug) / 主键 WHERE 守卫;
|
|
14
|
+
* - `sql\`\`` 只用于 json_each 标签查询这一处逃生舱(D1 与 better-sqlite3 的
|
|
15
|
+
* SQLite JSON1 扩展都支持,跨方言可用)。
|
|
16
|
+
*
|
|
17
|
+
* 结构守卫(tests/guard-sql.spec.ts)允许本文件对 content/redirects/kv 的受控写入。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export type ContentRow = typeof content.$inferSelect;
|
|
21
|
+
export type RedirectRow = typeof redirects.$inferSelect;
|
|
22
|
+
|
|
23
|
+
/* ------------------------------------------------------------------ 同步期写路径 */
|
|
24
|
+
|
|
25
|
+
export interface ContentUpsert {
|
|
26
|
+
section: string;
|
|
27
|
+
slug: string;
|
|
28
|
+
locale: string;
|
|
29
|
+
title: string;
|
|
30
|
+
description: string;
|
|
31
|
+
publishedAt: Date;
|
|
32
|
+
updatedAt: Date;
|
|
33
|
+
tags: string[];
|
|
34
|
+
meta: Record<string, unknown>;
|
|
35
|
+
bodyMd: string;
|
|
36
|
+
bodyHtml: string;
|
|
37
|
+
rendererVersion: string;
|
|
38
|
+
checksum: string;
|
|
39
|
+
draft: boolean;
|
|
40
|
+
author: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** D1 单批语句上限的保守分片 */
|
|
44
|
+
const BATCH_CHUNK = 40;
|
|
45
|
+
|
|
46
|
+
function chunk<T>(items: T[], size: number): T[][] {
|
|
47
|
+
const out: T[][] = [];
|
|
48
|
+
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 同步期内容 upsert:UNIQUE(section, locale, slug) 冲突时整行受控覆盖。
|
|
54
|
+
* 渲染失败的内容绝不允许进库(bodyHtml 必须已由调用方渲染成功)。
|
|
55
|
+
*/
|
|
56
|
+
export async function upsertContentRows(db: AppDatabase, rows: ContentUpsert[]): Promise<void> {
|
|
57
|
+
for (const part of chunk(rows, BATCH_CHUNK)) {
|
|
58
|
+
// 原子组:D1 走 batch,同步驱动走事务(runAtomic 方言感知;每行一个语句工厂)
|
|
59
|
+
await runAtomic(db, part.map(
|
|
60
|
+
(r) => (d: AppDatabase) =>
|
|
61
|
+
d
|
|
62
|
+
.insert(content)
|
|
63
|
+
.values({
|
|
64
|
+
section: r.section,
|
|
65
|
+
slug: r.slug,
|
|
66
|
+
locale: r.locale,
|
|
67
|
+
title: r.title,
|
|
68
|
+
description: r.description,
|
|
69
|
+
publishedAt: r.publishedAt,
|
|
70
|
+
updatedAt: r.updatedAt,
|
|
71
|
+
tags: r.tags,
|
|
72
|
+
meta: r.meta,
|
|
73
|
+
bodyMd: r.bodyMd,
|
|
74
|
+
bodyHtml: r.bodyHtml,
|
|
75
|
+
rendererVersion: r.rendererVersion,
|
|
76
|
+
checksum: r.checksum,
|
|
77
|
+
draft: r.draft,
|
|
78
|
+
author: r.author,
|
|
79
|
+
})
|
|
80
|
+
.onConflictDoUpdate({
|
|
81
|
+
target: [content.section, content.locale, content.slug],
|
|
82
|
+
set: {
|
|
83
|
+
title: r.title,
|
|
84
|
+
description: r.description,
|
|
85
|
+
publishedAt: r.publishedAt,
|
|
86
|
+
updatedAt: r.updatedAt,
|
|
87
|
+
tags: r.tags,
|
|
88
|
+
meta: r.meta,
|
|
89
|
+
bodyMd: r.bodyMd,
|
|
90
|
+
bodyHtml: r.bodyHtml,
|
|
91
|
+
rendererVersion: r.rendererVersion,
|
|
92
|
+
checksum: r.checksum,
|
|
93
|
+
draft: r.draft,
|
|
94
|
+
author: r.author,
|
|
95
|
+
},
|
|
96
|
+
}),
|
|
97
|
+
),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 同步期删除:repo 里已消失的 slug(带 section/locale 守卫) */
|
|
103
|
+
export async function removeContentSlugs(db: AppDatabase, section: string, locale: string, slugs: string[]): Promise<void> {
|
|
104
|
+
if (!slugs.length) return;
|
|
105
|
+
for (const part of chunk(slugs, BATCH_CHUNK)) {
|
|
106
|
+
await db
|
|
107
|
+
.delete(content)
|
|
108
|
+
.where(and(eq(content.section, section), eq(content.locale, locale), inArray(content.slug, part)));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface RedirectUpsert {
|
|
113
|
+
fromPath: string;
|
|
114
|
+
toPath: string;
|
|
115
|
+
createdAt: Date;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 同步期重定向 upsert(from_path UNIQUE 冲突时只更新 to_path) */
|
|
119
|
+
export async function upsertRedirects(db: AppDatabase, rows: RedirectUpsert[]): Promise<void> {
|
|
120
|
+
if (!rows.length) return;
|
|
121
|
+
for (const part of chunk(rows, BATCH_CHUNK)) {
|
|
122
|
+
await runAtomic(db, part.map(
|
|
123
|
+
(r) => (d: AppDatabase) =>
|
|
124
|
+
d
|
|
125
|
+
.insert(redirects)
|
|
126
|
+
.values({ fromPath: r.fromPath, toPath: r.toPath, createdAt: r.createdAt })
|
|
127
|
+
.onConflictDoUpdate({ target: redirects.fromPath, set: { toPath: r.toPath } }),
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 同步期重定向收敛:redirects 表是 repo 派生表(git 唯一事实源),
|
|
135
|
+
* 每次全量同步后不在 repo 集合里的行删除。手工加的运行时重定向(M2+)
|
|
136
|
+
* 需要另行处理,M1 阶段 redirects 只来自 frontmatter redirect_from。
|
|
137
|
+
* 返回删除行数(同步报告用)。
|
|
138
|
+
*/
|
|
139
|
+
export async function removeRedirectsNotIn(db: AppDatabase, keepFromPaths: string[]): Promise<number> {
|
|
140
|
+
const existing = await db.select({ fromPath: redirects.fromPath }).from(redirects);
|
|
141
|
+
const keep = new Set(keepFromPaths);
|
|
142
|
+
const stale = existing.map((r) => r.fromPath).filter((p) => !keep.has(p));
|
|
143
|
+
if (!stale.length) return 0;
|
|
144
|
+
for (const part of chunk(stale, BATCH_CHUNK)) {
|
|
145
|
+
await db.delete(redirects).where(inArray(redirects.fromPath, part));
|
|
146
|
+
}
|
|
147
|
+
return stale.length;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 同步 diff 用:栏目内 (slug, checksum) 轻量投影 */
|
|
151
|
+
export async function listSectionChecksums(db: AppDatabase, section: string, locale = 'zh-CN'): Promise<{ slug: string; checksum: string }[]> {
|
|
152
|
+
const rows = await db
|
|
153
|
+
.select({ slug: content.slug, checksum: content.checksum })
|
|
154
|
+
.from(content)
|
|
155
|
+
.where(and(eq(content.section, section), eq(content.locale, locale)));
|
|
156
|
+
return rows;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/* ------------------------------------------------------------------ 运行时读路径 */
|
|
160
|
+
|
|
161
|
+
/** 列表条目投影(不含正文,列表页/feed/sitemap 共用) */
|
|
162
|
+
const LIST_COLUMNS = {
|
|
163
|
+
section: content.section,
|
|
164
|
+
slug: content.slug,
|
|
165
|
+
title: content.title,
|
|
166
|
+
description: content.description,
|
|
167
|
+
publishedAt: content.publishedAt,
|
|
168
|
+
updatedAt: content.updatedAt,
|
|
169
|
+
tags: content.tags,
|
|
170
|
+
author: content.author,
|
|
171
|
+
} as const;
|
|
172
|
+
|
|
173
|
+
type ListRow = {
|
|
174
|
+
section: string;
|
|
175
|
+
slug: string;
|
|
176
|
+
title: string;
|
|
177
|
+
description: string;
|
|
178
|
+
publishedAt: Date;
|
|
179
|
+
updatedAt: Date;
|
|
180
|
+
tags: unknown;
|
|
181
|
+
author: string | null;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
function toListItem(row: ListRow): ContentListItem {
|
|
185
|
+
return {
|
|
186
|
+
section: row.section,
|
|
187
|
+
slug: row.slug,
|
|
188
|
+
title: row.title,
|
|
189
|
+
description: row.description,
|
|
190
|
+
publishedAt: row.publishedAt,
|
|
191
|
+
updatedAt: row.updatedAt,
|
|
192
|
+
tags: Array.isArray(row.tags) ? (row.tags as string[]) : [],
|
|
193
|
+
author: row.author,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export interface ListOptions {
|
|
198
|
+
page?: number;
|
|
199
|
+
perPage?: number;
|
|
200
|
+
locale?: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const DEFAULT_PER_PAGE = 12;
|
|
204
|
+
|
|
205
|
+
/** 栏目列表(草稿一律不出现在运行时读路径) */
|
|
206
|
+
export async function listPublished(db: AppDatabase, section: string, options: ListOptions = {}): Promise<PagedList<ContentListItem>> {
|
|
207
|
+
const page = Math.max(1, Math.floor(options.page ?? 1));
|
|
208
|
+
const perPage = Math.max(1, Math.floor(options.perPage ?? DEFAULT_PER_PAGE));
|
|
209
|
+
const locale = options.locale ?? 'zh-CN';
|
|
210
|
+
const where = and(eq(content.section, section), eq(content.locale, locale), eq(content.draft, false));
|
|
211
|
+
|
|
212
|
+
const totalRows = await db.select({ n: count() }).from(content).where(where);
|
|
213
|
+
const total = totalRows[0]?.n ?? 0;
|
|
214
|
+
const pages = Math.max(1, Math.ceil(total / perPage));
|
|
215
|
+
|
|
216
|
+
const rows = await db
|
|
217
|
+
.select(LIST_COLUMNS)
|
|
218
|
+
.from(content)
|
|
219
|
+
.where(where)
|
|
220
|
+
.orderBy(desc(content.publishedAt), content.slug)
|
|
221
|
+
.limit(perPage)
|
|
222
|
+
.offset((page - 1) * perPage);
|
|
223
|
+
|
|
224
|
+
return { items: rows.map(toListItem), page, perPage, total, pages };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 全站已发布内容(feed/sitemap/llms.txt 用,按发布时间倒序) */
|
|
228
|
+
export async function listPublishedAll(db: AppDatabase, options: { locale?: string; limit?: number } = {}): Promise<ContentListItem[]> {
|
|
229
|
+
const locale = options.locale ?? 'zh-CN';
|
|
230
|
+
const rows = await db
|
|
231
|
+
.select(LIST_COLUMNS)
|
|
232
|
+
.from(content)
|
|
233
|
+
.where(and(eq(content.locale, locale), eq(content.draft, false)))
|
|
234
|
+
.orderBy(desc(content.publishedAt))
|
|
235
|
+
.limit(Math.min(1000, Math.max(1, options.limit ?? 200)));
|
|
236
|
+
return rows.map(toListItem);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 标签过滤(json_each 逃生舱:跨 D1/better-sqlite3 的 JSON1 能力) */
|
|
240
|
+
export async function listByTag(db: AppDatabase, section: string, tag: string, options: ListOptions = {}): Promise<PagedList<ContentListItem>> {
|
|
241
|
+
const page = Math.max(1, Math.floor(options.page ?? 1));
|
|
242
|
+
const perPage = Math.max(1, Math.floor(options.perPage ?? DEFAULT_PER_PAGE));
|
|
243
|
+
const locale = options.locale ?? 'zh-CN';
|
|
244
|
+
const where = and(
|
|
245
|
+
eq(content.section, section),
|
|
246
|
+
eq(content.locale, locale),
|
|
247
|
+
eq(content.draft, false),
|
|
248
|
+
sql`EXISTS (SELECT 1 FROM json_each(${content.tags}) WHERE json_each.value = ${tag})`,
|
|
249
|
+
);
|
|
250
|
+
|
|
251
|
+
const totalRows = await db.select({ n: count() }).from(content).where(where);
|
|
252
|
+
const total = totalRows[0]?.n ?? 0;
|
|
253
|
+
const pages = Math.max(1, Math.ceil(total / perPage));
|
|
254
|
+
|
|
255
|
+
const rows = await db
|
|
256
|
+
.select(LIST_COLUMNS)
|
|
257
|
+
.from(content)
|
|
258
|
+
.where(where)
|
|
259
|
+
.orderBy(desc(content.publishedAt))
|
|
260
|
+
.limit(perPage)
|
|
261
|
+
.offset((page - 1) * perPage);
|
|
262
|
+
|
|
263
|
+
return { items: rows.map(toListItem), page, perPage, total, pages };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 栏目内全部已发布条目(docs 这类「一屏列表」栏目用) */
|
|
267
|
+
export async function listSectionFlat(db: AppDatabase, section: string, options: { locale?: string; limit?: number } = {}): Promise<ContentListItem[]> {
|
|
268
|
+
const locale = options.locale ?? 'zh-CN';
|
|
269
|
+
const rows = await db
|
|
270
|
+
.select(LIST_COLUMNS)
|
|
271
|
+
.from(content)
|
|
272
|
+
.where(and(eq(content.section, section), eq(content.locale, locale), eq(content.draft, false)))
|
|
273
|
+
.orderBy(content.slug)
|
|
274
|
+
.limit(Math.min(500, Math.max(1, options.limit ?? 200)));
|
|
275
|
+
return rows.map(toListItem);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 栏目内全部已发布条目 + frontmatter 剩余 meta(docs 树导航的 order/group 字段)。
|
|
280
|
+
* 返回原 repo 顺序由调用方按栏目语义排序(docs:meta.order 升序,缺省排最后)。
|
|
281
|
+
*/
|
|
282
|
+
export async function listSectionWithMeta(db: AppDatabase, section: string, options: { locale?: string; limit?: number } = {}): Promise<ContentItemWithMeta[]> {
|
|
283
|
+
const locale = options.locale ?? 'zh-CN';
|
|
284
|
+
const rows = await db
|
|
285
|
+
.select({ ...LIST_COLUMNS, meta: content.meta })
|
|
286
|
+
.from(content)
|
|
287
|
+
.where(and(eq(content.section, section), eq(content.locale, locale), eq(content.draft, false)))
|
|
288
|
+
.limit(Math.min(500, Math.max(1, options.limit ?? 200)));
|
|
289
|
+
return rows.map((row) => ({
|
|
290
|
+
...toListItem(row),
|
|
291
|
+
meta: row.meta && typeof row.meta === 'object' ? (row.meta as Record<string, unknown>) : {},
|
|
292
|
+
}));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 详情(未命中返回 null;draft 不出) */
|
|
296
|
+
export async function getPublished(db: AppDatabase, section: string, slug: string, locale = 'zh-CN'): Promise<ContentRow | null> {
|
|
297
|
+
const rows = await db
|
|
298
|
+
.select()
|
|
299
|
+
.from(content)
|
|
300
|
+
.where(and(eq(content.section, section), eq(content.locale, locale), eq(content.slug, slug), eq(content.draft, false)))
|
|
301
|
+
.limit(1);
|
|
302
|
+
return rows[0] ?? null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** 301 解析:命中返回目标路径 */
|
|
306
|
+
export async function resolveRedirect(db: AppDatabase, fromPath: string): Promise<string | null> {
|
|
307
|
+
const rows = await db.select({ toPath: redirects.toPath }).from(redirects).where(eq(redirects.fromPath, fromPath)).limit(1);
|
|
308
|
+
return rows[0]?.toPath ?? null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/* ------------------------------------------------------------------ 渲染自愈 */
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 正文 HTML 读时自愈(bbs render-cache 思路,kit 版不回写库):
|
|
315
|
+
* renderer_version 命中 → 直用存量 HTML(热数据零成本);
|
|
316
|
+
* 版本未命中(渲染器升级后的历史行)→ 现算一次,下次同步自然回填,
|
|
317
|
+
* 失败时退回存量 HTML(渲染失败绝不能出空白)。
|
|
318
|
+
*/
|
|
319
|
+
export function renderContentHtml(row: { bodyMd: string; bodyHtml: string; rendererVersion: string }): string {
|
|
320
|
+
if (row.rendererVersion === RENDERER_VERSION) return normalizeHeadingLevels(row.bodyHtml);
|
|
321
|
+
try {
|
|
322
|
+
return normalizeHeadingLevels(renderMarkdown(row.bodyMd));
|
|
323
|
+
} catch {
|
|
324
|
+
return normalizeHeadingLevels(row.bodyHtml);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 详情行 → ContentArticle(含自愈 HTML) */
|
|
329
|
+
export function toArticle(row: ContentRow, locale?: string): ContentArticle {
|
|
330
|
+
return {
|
|
331
|
+
section: row.section,
|
|
332
|
+
slug: row.slug,
|
|
333
|
+
title: row.title,
|
|
334
|
+
description: row.description,
|
|
335
|
+
publishedAt: row.publishedAt,
|
|
336
|
+
updatedAt: row.updatedAt,
|
|
337
|
+
tags: Array.isArray(row.tags) ? (row.tags as string[]) : [],
|
|
338
|
+
author: row.author,
|
|
339
|
+
html: renderContentHtml(row),
|
|
340
|
+
locale: locale ?? row.locale,
|
|
341
|
+
};
|
|
342
|
+
}
|
package/src/turnstile.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Platform, TurnstileOptions } from './types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cloudflare Turnstile(M2):只挂写路径(注册 / 登录),读路径保持匿名可抓。
|
|
5
|
+
* 移植自 research/bbs/turnstile.ts(bbs 已验证实现)。
|
|
6
|
+
*
|
|
7
|
+
* site.config / 环境无密钥时整条链路自动关闭(本地开发、fork 自部署不需要先
|
|
8
|
+
* 申请密钥);Cloudflare 官方测试钥匙(1x000…/2x000…/3x000…AA 模式)走同一
|
|
9
|
+
* siteverify 通道,配到配置里即可用,无需特判。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const SITEVERIFY = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
|
|
13
|
+
|
|
14
|
+
/** widget 脚本的源;启用时需追加进 CSP(engine/guard.ts 安全头扩展位) */
|
|
15
|
+
export const TURNSTILE_SCRIPT_ORIGIN = 'https://challenges.cloudflare.com';
|
|
16
|
+
|
|
17
|
+
export interface Turnstile {
|
|
18
|
+
enabled: boolean;
|
|
19
|
+
siteKey?: string;
|
|
20
|
+
verify(token: string | null | undefined, ip?: string | null): Promise<boolean>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createTurnstile(config: TurnstileOptions | undefined, platform: Platform): Turnstile {
|
|
24
|
+
const siteKey = config?.siteKey || (platform.env['TURNSTILE_SITE_KEY'] as string | undefined);
|
|
25
|
+
const secretKey = config?.secretKey || (platform.env['TURNSTILE_SECRET_KEY'] as string | undefined);
|
|
26
|
+
const enabled = !!(siteKey && secretKey);
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
enabled,
|
|
30
|
+
siteKey,
|
|
31
|
+
/**
|
|
32
|
+
* 服务端校验 token。未启用 → 恒过;网络失败按「未通过」处理(fail-closed),
|
|
33
|
+
* 但打日志避免 Cloudflare 侧故障时完全无法注册/登录却查不到原因。
|
|
34
|
+
*/
|
|
35
|
+
async verify(token, ip): Promise<boolean> {
|
|
36
|
+
if (!enabled) return true;
|
|
37
|
+
if (!token) return false;
|
|
38
|
+
|
|
39
|
+
const body = new FormData();
|
|
40
|
+
body.append('secret', secretKey!);
|
|
41
|
+
body.append('response', token);
|
|
42
|
+
if (ip) body.append('remoteip', ip);
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
const res = await fetch(SITEVERIFY, { method: 'POST', body });
|
|
46
|
+
if (!res.ok) {
|
|
47
|
+
console.error('turnstile_http_error', res.status);
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
const data = (await res.json()) as { success?: boolean; 'error-codes'?: string[] };
|
|
51
|
+
if (!data.success) {
|
|
52
|
+
console.warn('turnstile_rejected', (data['error-codes'] ?? []).join(','));
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
} catch (err) {
|
|
57
|
+
console.error('turnstile_verify_failed', err);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { AppDatabase } from './db';
|
|
3
|
+
import type { Section } from './section';
|
|
4
|
+
|
|
5
|
+
/* ------------------------------------------------------------ 平台抽象 */
|
|
6
|
+
|
|
7
|
+
export interface PlatformEnv {
|
|
8
|
+
[k: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface StoragePut {
|
|
12
|
+
key: string;
|
|
13
|
+
value: ArrayBuffer | ReadableStream;
|
|
14
|
+
contentType?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Workers 原生 Rate Limiting binding 的最小接口(避免依赖 workers-types 版本) */
|
|
18
|
+
export interface RateLimitBinding {
|
|
19
|
+
limit(options: { key: string }): Promise<{ success: boolean }>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Platform {
|
|
23
|
+
/** drizzle 实例(方言异构,service 层统一 API,形态见 engine/db.ts AppDatabase) */
|
|
24
|
+
db: AppDatabase;
|
|
25
|
+
dbKind: 'd1' | 'sqlite' | 'postgres';
|
|
26
|
+
/** 渲染缓存(按 URL):workers = Cache API,node = 内存 Map(带 TTL) */
|
|
27
|
+
cache: {
|
|
28
|
+
match(url: URL): Promise<Response | undefined>;
|
|
29
|
+
put(url: URL, res: Response, ttl: number): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
kv: {
|
|
32
|
+
get(key: string): Promise<string | null>;
|
|
33
|
+
put(key: string, value: string, ttl?: number): Promise<void>;
|
|
34
|
+
delete?(key: string): Promise<void>;
|
|
35
|
+
};
|
|
36
|
+
storage: {
|
|
37
|
+
get(key: string): Promise<{ body: ArrayBuffer; contentType: string } | null>;
|
|
38
|
+
put(p: StoragePut): Promise<void>;
|
|
39
|
+
};
|
|
40
|
+
waitUntil(p: Promise<unknown>): void;
|
|
41
|
+
env: PlatformEnv;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** R2 binding 最小接口(避免依赖 workers-types 版本;M2 media) */
|
|
45
|
+
export interface StorageBinding {
|
|
46
|
+
get(key: string): Promise<{ arrayBuffer(): Promise<ArrayBuffer>; httpMetadata?: { contentType?: string } } | null>;
|
|
47
|
+
put(key: string, value: ArrayBuffer | ReadableStream, options?: { httpMetadata?: { contentType?: string } }): Promise<unknown>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/* ------------------------------------------------------------ Workers env */
|
|
51
|
+
|
|
52
|
+
export interface WorkersEnv {
|
|
53
|
+
/** D1 binding(M1 接线) */
|
|
54
|
+
DB?: unknown;
|
|
55
|
+
/** Workers Assets binding(wrangler.jsonc assets) */
|
|
56
|
+
ASSETS?: { fetch(req: Request): Promise<Response> };
|
|
57
|
+
/** R2 binding(M2 media) */
|
|
58
|
+
R2?: StorageBinding;
|
|
59
|
+
/** 原生限流 binding(wrangler [[ratelimits]]),本地未配置时回退 Cache API / 内存 */
|
|
60
|
+
RL_PAGE?: RateLimitBinding;
|
|
61
|
+
RL_API?: RateLimitBinding;
|
|
62
|
+
SITE_NAME?: string;
|
|
63
|
+
SITE_URL?: string;
|
|
64
|
+
CONTENT_VERSION?: string;
|
|
65
|
+
/** better-auth 签名密钥(M2;生产必须注入,本地有开发占位) */
|
|
66
|
+
BETTER_AUTH_SECRET?: string;
|
|
67
|
+
/** Turnstile(M2 写路径人机校验;无密钥自动关闭) */
|
|
68
|
+
TURNSTILE_SITE_KEY?: string;
|
|
69
|
+
TURNSTILE_SECRET_KEY?: string;
|
|
70
|
+
/** PBKDF2 迭代数(M2;缺省 100000,范围 10000-300000) */
|
|
71
|
+
PASSWORD_ITERATIONS?: string;
|
|
72
|
+
[key: string]: unknown;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** ExecutionContext 最小形状(避免全局依赖 workers-types) */
|
|
76
|
+
export interface ExecContext {
|
|
77
|
+
waitUntil(p: Promise<unknown>): void;
|
|
78
|
+
passThroughOnException(): void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/* ------------------------------------------------------------ 内容引擎(M1/M2) */
|
|
82
|
+
|
|
83
|
+
/** 列表页条目(content 表投影,运行时只暴露已发布内容) */
|
|
84
|
+
export interface ContentListItem {
|
|
85
|
+
section: string;
|
|
86
|
+
slug: string;
|
|
87
|
+
title: string;
|
|
88
|
+
description: string;
|
|
89
|
+
publishedAt: Date;
|
|
90
|
+
updatedAt: Date;
|
|
91
|
+
tags: string[];
|
|
92
|
+
author: string | null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 文章页条目:列表字段 + 自愈后的正文 HTML */
|
|
96
|
+
export interface ContentArticle extends ContentListItem {
|
|
97
|
+
html: string;
|
|
98
|
+
locale: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 分页结果 */
|
|
102
|
+
export interface PagedList<T> {
|
|
103
|
+
items: T[];
|
|
104
|
+
page: number;
|
|
105
|
+
perPage: number;
|
|
106
|
+
total: number;
|
|
107
|
+
pages: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 列表条目 + frontmatter 剩余 meta(docs 的 order/group 等栏目扩展字段从这里取) */
|
|
111
|
+
export interface ContentItemWithMeta extends ContentListItem {
|
|
112
|
+
meta: Record<string, unknown>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/* ------------------------------------------------------------ 引擎配置 */
|
|
116
|
+
|
|
117
|
+
export interface SiteMeta {
|
|
118
|
+
name: string;
|
|
119
|
+
url: string;
|
|
120
|
+
locale: string;
|
|
121
|
+
/**
|
|
122
|
+
* 全部 locale(M3,[0] = baseLocale,如 ['zh-CN', 'en'])。
|
|
123
|
+
* 缺省 / 长度 ≤1 = i18n 关闭:不生成 <locale> 前缀路由、head 不输出 hreflang。
|
|
124
|
+
*/
|
|
125
|
+
locales?: string[];
|
|
126
|
+
tagline?: string;
|
|
127
|
+
description?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface CacheOptions {
|
|
131
|
+
/** fresh 窗口(秒),默认 60 */
|
|
132
|
+
sMaxAge?: number;
|
|
133
|
+
/** stale 可服务窗口(秒),默认 86400 */
|
|
134
|
+
staleWhileRevalidate?: number;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Turnstile 配置(M2):site.config / 环境无密钥时自动关闭 */
|
|
138
|
+
export interface TurnstileOptions {
|
|
139
|
+
siteKey?: string;
|
|
140
|
+
secretKey?: string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** better-auth 配置(M2):secret 缺省走开发占位(仅本地;部署必须注入) */
|
|
144
|
+
export interface AuthOptions {
|
|
145
|
+
secret?: string;
|
|
146
|
+
baseURL?: string;
|
|
147
|
+
turnstile?: TurnstileOptions;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface EngineConfig {
|
|
151
|
+
platform: Platform;
|
|
152
|
+
site: SiteMeta;
|
|
153
|
+
/** 内容同步时间戳/校验和:注入缓存键,bump 即整体翻新渲染缓存 */
|
|
154
|
+
contentVersion: string;
|
|
155
|
+
cache?: CacheOptions;
|
|
156
|
+
/**
|
|
157
|
+
* Section 列表(M2 协议):createApp 经 registerSections 挂载全部栏目路由;
|
|
158
|
+
* 引擎自身不再保留内置内容路由。
|
|
159
|
+
*/
|
|
160
|
+
sections?: Section[];
|
|
161
|
+
/** better-auth 账户体系(M2):提供 secret 即启用 /api/auth/* 与账户页 */
|
|
162
|
+
auth?: AuthOptions;
|
|
163
|
+
/** 兜底首页渲染器:无 section 认领 '/' 时使用;缺省用引擎内置占位页 */
|
|
164
|
+
renderHome?: (c: Context) => Response | Promise<Response>;
|
|
165
|
+
/** 错误页渲染器(404/429/500);缺省用引擎内置占位页 */
|
|
166
|
+
renderError?: (c: Context, status: number, message?: string) => Response | Promise<Response>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 路由/section 上下文(总设计 §6,M2 sections 接线时扩展;M3 加 locale 变体挂载) */
|
|
170
|
+
export interface EngineContext {
|
|
171
|
+
platform: Platform;
|
|
172
|
+
config: EngineConfig;
|
|
173
|
+
/**
|
|
174
|
+
* locale 变体挂载时的渲染语言(M3):'/en/**' 子应用传入 'en';
|
|
175
|
+
* 根应用缺省 = baseLocale。section 路由/视图据此查询对应 locale 的内容。
|
|
176
|
+
*/
|
|
177
|
+
locale?: string;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/* ------------------------------------------------------------ 错误模型 */
|
|
181
|
+
|
|
182
|
+
export class ApiError extends Error {
|
|
183
|
+
status: number;
|
|
184
|
+
code: string;
|
|
185
|
+
|
|
186
|
+
constructor(status: number, code: string, message?: string) {
|
|
187
|
+
super(message ?? code);
|
|
188
|
+
this.status = status;
|
|
189
|
+
this.code = code;
|
|
190
|
+
this.name = 'ApiError';
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** @jsxImportSource hono/jsx */
|
|
2
|
+
import { buildHead } from '../seo';
|
|
3
|
+
import type { EngineConfig } from '../types';
|
|
4
|
+
import { Layout } from './layout';
|
|
5
|
+
|
|
6
|
+
const STATUS_TITLES: Record<number, string> = {
|
|
7
|
+
404: '页面不存在',
|
|
8
|
+
429: '请求过于频繁',
|
|
9
|
+
500: '服务暂时不可用',
|
|
10
|
+
503: '服务维护中',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function ErrorPage(props: { config: EngineConfig; status: number; message?: string }) {
|
|
14
|
+
const { site } = props.config;
|
|
15
|
+
const title = STATUS_TITLES[props.status] ?? `错误 ${props.status}`;
|
|
16
|
+
const head = buildHead({
|
|
17
|
+
title: `${props.status} ${title} - ${site.name}`,
|
|
18
|
+
description: props.message ?? '请稍后重试,或返回首页继续浏览。',
|
|
19
|
+
noindex: true,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
return (
|
|
23
|
+
<Layout head={head} jsonld={[]} brand={site.name} footerNote={`${site.name} · M0 脚手架`}>
|
|
24
|
+
<section class="error-page">
|
|
25
|
+
<div class="container">
|
|
26
|
+
<p class="error-status">{props.status}</p>
|
|
27
|
+
<h1 class="error-title">{title}</h1>
|
|
28
|
+
<p class="error-message">{props.message ?? '请稍后重试,或返回首页继续浏览。'}</p>
|
|
29
|
+
<p>
|
|
30
|
+
<a class="button button-primary" href="/">返回首页</a>
|
|
31
|
+
</p>
|
|
32
|
+
</div>
|
|
33
|
+
</section>
|
|
34
|
+
</Layout>
|
|
35
|
+
);
|
|
36
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** @jsxImportSource hono/jsx */
|
|
2
|
+
import type { Context } from 'hono';
|
|
3
|
+
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
|
4
|
+
import type { EngineConfig } from '../types';
|
|
5
|
+
import { ErrorPage } from './error';
|
|
6
|
+
|
|
7
|
+
/** 站点视图入口:错误页注入 engine 配置(engine 不反向依赖站点层)。
|
|
8
|
+
* 首页与内容页 M2 起由 sections/(landing/blog/docs)持有,站点层只留布局与错误页。 */
|
|
9
|
+
|
|
10
|
+
export function renderErrorPage(c: Context, config: EngineConfig, status: number, message?: string): Response | Promise<Response> {
|
|
11
|
+
c.status(status as ContentfulStatusCode);
|
|
12
|
+
return c.html(<ErrorPage config={config} status={status} message={message} />);
|
|
13
|
+
}
|