@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
package/src/i18n.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import type { EngineConfig } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* i18n 引擎(M3,总设计 §8 + PRD):
|
|
6
|
+
*
|
|
7
|
+
* locale 协商:URL /en 前缀 → cookie kit_lang → Accept-Language → baseLocale
|
|
8
|
+
* URL 策略:默认语言无前缀,其他语言 /<locale> 前缀(内容页语言由 URL 显式寻址,
|
|
9
|
+
* 与 SWR 缓存键天然兼容);cookie/Accept-Language 供 /lang 切换端点与非内容
|
|
10
|
+
* 场景消费,不参与内容页渲染决策(缓存安全)。
|
|
11
|
+
*
|
|
12
|
+
* paraglide v2 集成采用「显式传递」而非 AsyncLocalStorage〔implement.md:
|
|
13
|
+
* Workers 无 ALS 就显式〕:编译产物消息函数支持 options.locale 每次调用覆盖,
|
|
14
|
+
* tr(locale) 返回注入了 locale 的消息代理——零全局状态,Workers / Node 双端一致。
|
|
15
|
+
*
|
|
16
|
+
* M2.5 拆包后消息模块由站点注入(engine 是 npm 库,不能反向依赖站点层的
|
|
17
|
+
* paraglide 编译产物):站点在 site.config.ts 里
|
|
18
|
+
* import * as messages from './src/paraglide/messages.js';
|
|
19
|
+
* registerMessages(messages);
|
|
20
|
+
* 编译产物 src/paraglide/ 由站点 `npm run compile:i18n` 生成(gitignore 不入库),
|
|
21
|
+
* project.inlang/settings.json 的 modules 必须指向 ./node_modules 本地路径
|
|
22
|
+
* 〔sitengine memory:inlang CDN 被墙坑〕。
|
|
23
|
+
* 未注册/缺 key 时 tr 回退返回消息 key 本身(服务不 500,缺文案显性可见)。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/* ------------------------------------------------------------ locale 配置 */
|
|
27
|
+
|
|
28
|
+
export const LOCALE_COOKIE = 'kit_lang';
|
|
29
|
+
|
|
30
|
+
/** 站点 locale 全集([0] = baseLocale);未配置 = 单语言(i18n 关闭,零开销) */
|
|
31
|
+
export function siteLocales(config: EngineConfig): string[] {
|
|
32
|
+
const locales = config?.site?.locales;
|
|
33
|
+
const fallback = config?.site?.locale ?? 'zh-CN';
|
|
34
|
+
return locales && locales.length > 0 ? locales : [fallback];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** locale 数为 1(或缺省)时 i18n 整链关闭:不生成 /en 路由、head 无 hreflang */
|
|
38
|
+
export function i18nEnabled(locales: string[]): boolean {
|
|
39
|
+
return locales.length > 1;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function baseLocaleOf(locales: string[]): string {
|
|
43
|
+
return locales[0] ?? 'zh-CN';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 是否合法 locale 目录段/路由前缀(排除 base 与未知语言) */
|
|
47
|
+
export function isVariantLocale(locale: string, locales: string[]): boolean {
|
|
48
|
+
return i18nEnabled(locales) && locale !== baseLocaleOf(locales) && locales.includes(locale);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* ------------------------------------------------------------ URL 策略 */
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 路径首段是否为 variant locale 前缀:'/en/blog' → 'en'(base 无前缀返回 null)。
|
|
55
|
+
* 只认 locales 清单内的语言,'/android/app' 这类普通嵌套 slug 不受影响。
|
|
56
|
+
*/
|
|
57
|
+
export function pathLocale(path: string, locales: string[]): string | null {
|
|
58
|
+
const m = /^\/([^/]+)(?:\/|$)/.exec(path);
|
|
59
|
+
const first = m?.[1];
|
|
60
|
+
if (!first || !isVariantLocale(first, locales)) return null;
|
|
61
|
+
return first;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 剥离 locale 前缀:'/en/blog' → '/blog';无前缀原样 */
|
|
65
|
+
export function stripLocalePrefix(path: string, locales: string[]): string {
|
|
66
|
+
const locale = pathLocale(path, locales);
|
|
67
|
+
if (!locale) return path;
|
|
68
|
+
const rest = path.slice(`/${locale}`.length);
|
|
69
|
+
return rest === '' ? '/' : rest;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 注入 locale 前缀(base 无前缀):('/blog', 'en') → '/en/blog';('/', 'en') → '/en'。
|
|
74
|
+
* idempotent:已带该前缀的路径原样返回。
|
|
75
|
+
*/
|
|
76
|
+
export function localePath(path: string, locale: string, locales: string[]): string {
|
|
77
|
+
if (!isVariantLocale(locale, locales)) return path;
|
|
78
|
+
const bare = stripLocalePrefix(path, locales);
|
|
79
|
+
return bare === '/' ? `/${locale}` : `/${locale}${bare}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** variant locale 的 URL 前缀(base 返回 ''):'en' → '/en' */
|
|
83
|
+
export function localePrefix(locale: string, locales: string[]): string {
|
|
84
|
+
return isVariantLocale(locale, locales) ? `/${locale}` : '';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 全 locale 页面地址(origin + localePath) */
|
|
88
|
+
export function localeHref(origin: string, path: string, locale: string, locales: string[]): string {
|
|
89
|
+
return `${origin.replace(/\/+$/, '')}${localePath(path, locale, locales)}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/* ------------------------------------------------------------ locale 协商 */
|
|
93
|
+
|
|
94
|
+
export interface NegotiateInput {
|
|
95
|
+
/** 当前路径(URL 前缀优先级最高) */
|
|
96
|
+
path?: string;
|
|
97
|
+
/** cookie kit_lang 值 */
|
|
98
|
+
cookie?: string | null;
|
|
99
|
+
/** Accept-Language 头原文('en-US,en;q=0.9,zh-CN;q=0.8') */
|
|
100
|
+
acceptLanguage?: string | null;
|
|
101
|
+
locales: string[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Accept-Language 解析:按 q 值降序的语言标签列表(无 q = 1) */
|
|
105
|
+
export function parseAcceptLanguage(header: string): { tag: string; q: number }[] {
|
|
106
|
+
return header
|
|
107
|
+
.split(',')
|
|
108
|
+
.map((part) => {
|
|
109
|
+
const [tag, ...params] = part.trim().split(';');
|
|
110
|
+
let q = 1;
|
|
111
|
+
for (const p of params) {
|
|
112
|
+
const m = /q\s*=\s*([\d.]+)/.exec(p.trim());
|
|
113
|
+
if (m) q = Number.parseFloat(m[1] ?? '1');
|
|
114
|
+
}
|
|
115
|
+
return { tag: (tag ?? '').trim().toLowerCase(), q: Number.isFinite(q) ? q : 0 };
|
|
116
|
+
})
|
|
117
|
+
.filter((t) => t.tag.length > 0)
|
|
118
|
+
.sort((a, b) => b.q - a.q);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 完整协商链(PRD):URL 前缀 → cookie kit_lang → Accept-Language(精确 → 主子标签)
|
|
123
|
+
* → baseLocale。任何一步命中 locales 清单即返回。
|
|
124
|
+
*/
|
|
125
|
+
export function negotiateLocale(input: NegotiateInput): string {
|
|
126
|
+
const { locales } = input;
|
|
127
|
+
const base = baseLocaleOf(locales);
|
|
128
|
+
|
|
129
|
+
if (input.path) {
|
|
130
|
+
const fromPath = pathLocale(input.path, locales);
|
|
131
|
+
if (fromPath) return fromPath;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const cookie = (input.cookie ?? '').trim();
|
|
135
|
+
if (cookie && locales.includes(cookie)) return cookie;
|
|
136
|
+
|
|
137
|
+
if (input.acceptLanguage) {
|
|
138
|
+
const tags = parseAcceptLanguage(input.acceptLanguage);
|
|
139
|
+
for (const { tag } of tags) {
|
|
140
|
+
const exact = locales.find((l) => l.toLowerCase() === tag);
|
|
141
|
+
if (exact) return exact;
|
|
142
|
+
// 主子标签匹配:'en-us' → 'en';'zh' → 'zh-CN'
|
|
143
|
+
const primary = tag.split('-')[0] ?? '';
|
|
144
|
+
const partial = locales.find((l) => l.toLowerCase().split('-')[0] === primary);
|
|
145
|
+
if (partial) return partial;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return base;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 从 Hono 请求协商(内容页渲染语言以 URL 前缀为准;此助手供端点/扩展消费) */
|
|
153
|
+
export function negotiateFromContext(c: Context, locales: string[]): string {
|
|
154
|
+
return negotiateLocale({
|
|
155
|
+
path: c.req.path,
|
|
156
|
+
cookie: c.req.header('cookie') ? readCookie(c.req.header('cookie') ?? '', LOCALE_COOKIE) : null,
|
|
157
|
+
acceptLanguage: c.req.header('accept-language'),
|
|
158
|
+
locales,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 极简 cookie 读取(避免引依赖;只取第一个同名值) */
|
|
163
|
+
export function readCookie(cookieHeader: string, name: string): string | null {
|
|
164
|
+
for (const part of cookieHeader.split(';')) {
|
|
165
|
+
const idx = part.indexOf('=');
|
|
166
|
+
if (idx === -1) continue;
|
|
167
|
+
const k = part.slice(0, idx).trim();
|
|
168
|
+
if (k === name) return part.slice(idx + 1).trim();
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/* ------------------------------------------------------------ 消息代理(tr) */
|
|
174
|
+
|
|
175
|
+
/** 单条消息函数形状(paraglide 编译产物导出的函数同构;返回 string 供 JSX 直接消费) */
|
|
176
|
+
export type MessageFn = (inputs?: unknown, options?: { locale?: string }) => string;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 站点注入的消息模块契约:引擎自带视图/栏目消费的 key 逐个声明(点访问不受
|
|
180
|
+
* noUncheckedIndexedAccess 影响),站点扩展 key 走索引签名(索引访问按
|
|
181
|
+
* MessageFn | undefined 处理,调用前自行判空)。key 清单由 grep 引擎视图
|
|
182
|
+
* `t.<key>(` 生成,与 dogfood messages/*.json 一一对应;站点新增消息放
|
|
183
|
+
* 索引签名面,不进本契约。
|
|
184
|
+
*/
|
|
185
|
+
export interface Messages {
|
|
186
|
+
/* 布局(views/layout) */
|
|
187
|
+
nav_label: MessageFn;
|
|
188
|
+
nav_home: MessageFn;
|
|
189
|
+
nav_blog: MessageFn;
|
|
190
|
+
nav_docs: MessageFn;
|
|
191
|
+
nav_search: MessageFn;
|
|
192
|
+
lang_switch_title: MessageFn;
|
|
193
|
+
footer_note: MessageFn;
|
|
194
|
+
/* 首页 + 搜索页(sections/landing) */
|
|
195
|
+
search_kicker: MessageFn;
|
|
196
|
+
search_title: MessageFn;
|
|
197
|
+
search_description: MessageFn;
|
|
198
|
+
search_input_label: MessageFn;
|
|
199
|
+
search_input_placeholder: MessageFn;
|
|
200
|
+
search_submit: MessageFn;
|
|
201
|
+
search_empty_hint: MessageFn;
|
|
202
|
+
search_no_results: MessageFn;
|
|
203
|
+
search_results_for: MessageFn;
|
|
204
|
+
search_loading: MessageFn;
|
|
205
|
+
search_error: MessageFn;
|
|
206
|
+
search_powered: MessageFn;
|
|
207
|
+
search_results_count: MessageFn;
|
|
208
|
+
/* blog 列表(sections/blog) */
|
|
209
|
+
blog_list_title: MessageFn;
|
|
210
|
+
blog_list_desc: MessageFn;
|
|
211
|
+
more_posts: MessageFn;
|
|
212
|
+
prev_page: MessageFn;
|
|
213
|
+
next_page: MessageFn;
|
|
214
|
+
page_info: MessageFn;
|
|
215
|
+
/* docs(sections/docs) */
|
|
216
|
+
docs_list_desc: MessageFn;
|
|
217
|
+
docs_default_group: MessageFn;
|
|
218
|
+
/* 站点自定义扩展 key */
|
|
219
|
+
[key: string]: MessageFn;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let activeMessages: Messages | null = null;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 站点侧消息注入(site.config.ts 模块加载时调用一次)。
|
|
226
|
+
* engine 不持有 paraglide 依赖:消息的所有权在站点,注册后 tr() 全局生效。
|
|
227
|
+
*/
|
|
228
|
+
export function registerMessages(messages: Messages): void {
|
|
229
|
+
activeMessages = messages;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 当前已注册的消息模块(未注册返回 null;诊断用) */
|
|
233
|
+
export function registeredMessages(): Messages | null {
|
|
234
|
+
return activeMessages;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* tr(locale):注入 locale 的消息代理(显式传递,零全局状态)。
|
|
239
|
+
*
|
|
240
|
+
* tr('en').nav_blog() → 'Blog'
|
|
241
|
+
* tr('zh-CN').nav_blog() → '博客'
|
|
242
|
+
* tr(locale).search_no_results({ query: 'x' })
|
|
243
|
+
*
|
|
244
|
+
* 底层是 paraglide 编译产物的 options.locale 每次调用覆盖(无 ALS 依赖,
|
|
245
|
+
* Workers / Node 行为一致)。未注册消息模块或 key 缺失时回退返回 key 本身
|
|
246
|
+
* (渲染不 500,缺文案显性可见,便于发现漏跑 compile:i18n)。
|
|
247
|
+
*/
|
|
248
|
+
export function tr(locale: string): Messages {
|
|
249
|
+
const source = (activeMessages ?? {}) as Messages;
|
|
250
|
+
return new Proxy(source, {
|
|
251
|
+
get(_target, prop) {
|
|
252
|
+
const key = String(prop);
|
|
253
|
+
const value = source[key];
|
|
254
|
+
if (typeof value !== 'function') {
|
|
255
|
+
return (() => key) as MessageFn;
|
|
256
|
+
}
|
|
257
|
+
return (inputs?: unknown, options?: { locale?: string }) =>
|
|
258
|
+
value(inputs, { ...(options ?? {}), locale });
|
|
259
|
+
},
|
|
260
|
+
}) as unknown as Messages;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/* ------------------------------------------------------------ head alternates */
|
|
264
|
+
|
|
265
|
+
export interface HreflangAlternate {
|
|
266
|
+
hreflang: string;
|
|
267
|
+
href: string;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* x-default + 全 locale alternates(PRD:seo buildHead 单测覆盖)。
|
|
272
|
+
* x-default 指向 base 版本;单语言(i18n 关闭)返回 [] —— head 不输出 hreflang。
|
|
273
|
+
*/
|
|
274
|
+
export function hreflangAlternates(origin: string, path: string, locales: string[]): HreflangAlternate[] {
|
|
275
|
+
if (!i18nEnabled(locales)) return [];
|
|
276
|
+
const base = baseLocaleOf(locales);
|
|
277
|
+
return [
|
|
278
|
+
{ hreflang: 'x-default', href: localeHref(origin, path, base, locales) },
|
|
279
|
+
...locales.map((locale) => ({ hreflang: locale, href: localeHref(origin, path, locale, locales) })),
|
|
280
|
+
];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/* ------------------------------------------------------------ 布局语言切换器 */
|
|
284
|
+
|
|
285
|
+
export interface LocaleSwitchProps {
|
|
286
|
+
/** 全部 locale(含 base) */
|
|
287
|
+
locales: string[];
|
|
288
|
+
/** 当前渲染 locale */
|
|
289
|
+
current: string;
|
|
290
|
+
/** 切换后回到的站点路径(已剥前缀) */
|
|
291
|
+
nextPath: string;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 视图层语言切换器 props(Layout 消费;单语言返回 null 不渲染) */
|
|
295
|
+
export function localeSwitchProps(c: Context, config: EngineConfig, current: string): LocaleSwitchProps | null {
|
|
296
|
+
const locales = siteLocales(config);
|
|
297
|
+
if (!i18nEnabled(locales)) return null;
|
|
298
|
+
return { locales, current, nextPath: stripLocalePrefix(c.req.path, locales) };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 切换端点地址:/lang/:code?next=<站点路径> */
|
|
302
|
+
export function langSwitchHref(locale: string, nextPath: string): string {
|
|
303
|
+
return `/lang/${encodeURIComponent(locale)}?next=${encodeURIComponent(nextPath)}`;
|
|
304
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @horizonwing/engine 主出口(M2.5 拆包):
|
|
3
|
+
* 平台无关的核心面(类型 + 组装 + Section 协议 + SEO)。
|
|
4
|
+
* 细分能力按子路径导入(./md ./seo ./content ./i18n ./platform/* …),
|
|
5
|
+
* 完整清单见 package.json exports。
|
|
6
|
+
*/
|
|
7
|
+
export type {
|
|
8
|
+
Platform,
|
|
9
|
+
PlatformEnv,
|
|
10
|
+
StoragePut,
|
|
11
|
+
WorkersEnv,
|
|
12
|
+
ExecContext,
|
|
13
|
+
EngineConfig,
|
|
14
|
+
SiteMeta,
|
|
15
|
+
AuthOptions,
|
|
16
|
+
CacheOptions,
|
|
17
|
+
EngineContext,
|
|
18
|
+
} from './types';
|
|
19
|
+
export { createApp } from './server';
|
|
20
|
+
export { defineSection } from './section';
|
|
21
|
+
export type { Section, SeoDeclaration } from './section';
|
|
22
|
+
export { buildHead, articleJsonLd, breadcrumbJsonLd, collectionPageJsonLd, organizationJsonLd, personJsonLd, websiteWithSearchJsonLd } from './seo';
|
|
23
|
+
export { renderMarkdown, RENDERER_VERSION } from './md';
|
|
24
|
+
export { syncContent, frontmatterSchema } from './content';
|
|
25
|
+
export type { Frontmatter } from './content';
|
|
26
|
+
export { registerMessages, tr } from './i18n';
|
|
27
|
+
export type { Messages, MessageFn } from './i18n';
|
package/src/md.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { Marked } from 'marked';
|
|
2
|
+
import type { Tokens, MarkedExtension } from 'marked';
|
|
3
|
+
import sanitizeHtml from 'sanitize-html';
|
|
4
|
+
import { escapeHtml } from './html';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Markdown 渲染器(marked 内核 + sanitize-html 输出过滤)
|
|
8
|
+
*
|
|
9
|
+
* 移植自 bbs src/lib/markdown.ts;相对原版的差异:
|
|
10
|
+
* - 去掉 @提及(mentionify / extractMentions,社区功能,kit 不需要)
|
|
11
|
+
* - escapeHtml 改由 engine/html.ts 提供
|
|
12
|
+
*
|
|
13
|
+
* 支持:标题 / 加粗 / 斜体 / 删除线 / 行内代码 / 代码块 / 链接 / 图片 / 引用 /
|
|
14
|
+
* 有序无序列表 / 分割线 / 表格(GFM)/ 自动链接 / ```chart 图表块
|
|
15
|
+
*
|
|
16
|
+
* 安全模型:
|
|
17
|
+
* marked 官方声明不做 XSS 过滤,DOMPurify 又需要 DOM(Workers 无 DOM),
|
|
18
|
+
* 所以最终 HTML 必须过一遍 sanitize-html,白名单只放开本渲染器实际产出的标签。
|
|
19
|
+
*
|
|
20
|
+
* 版本号:
|
|
21
|
+
* RENDERER_VERSION 变更后,读路径发现存量 content_html 的版本不匹配就会重渲染并回写,
|
|
22
|
+
* 同时它也是 SWR 缓存键的一部分(engine/cache.ts versionedUrl),
|
|
23
|
+
* 因此「改渲染器」= 改常量 + 部署,不需要批量迁移脚本。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const RENDERER_VERSION = 'v-marked-1';
|
|
27
|
+
|
|
28
|
+
/** 正文长度上限(与 bbs 实现保持一致) */
|
|
29
|
+
const MAX_INPUT = 60000;
|
|
30
|
+
|
|
31
|
+
/* ------------------------------------------------------------------ 图表 */
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* ```chart 代码块:内容是声明式 JSON,服务端只做校验 + 生成占位,
|
|
35
|
+
* SVG 由 public/js/chart.js 在浏览器里绘制(零依赖,CSP script-src 'self' 下可用)。
|
|
36
|
+
*
|
|
37
|
+
* 为什么不在服务端画:content_html 会缓存,图表样式/算法会迭代,
|
|
38
|
+
* 固化后的 SVG 无法跟随;占位 + 客户端绘制则历史内容自动获得新样式。
|
|
39
|
+
* 校验不过时返回 null,调用方退回普通代码块 —— 用户至少能看到原文。
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
interface ChartSpec {
|
|
43
|
+
type: 'line' | 'bar';
|
|
44
|
+
title?: string;
|
|
45
|
+
x: string[];
|
|
46
|
+
series: { name: string; data: (number | null)[]; axis?: 'left' | 'right' }[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const CHART_TYPES = new Set(['line', 'bar']);
|
|
50
|
+
const MAX_CHART_BYTES = 20000;
|
|
51
|
+
const MAX_CHART_POINTS = 240;
|
|
52
|
+
const MAX_CHART_SERIES = 8;
|
|
53
|
+
|
|
54
|
+
function parseChartSpec(raw: string): ChartSpec | null {
|
|
55
|
+
if (!raw || raw.length > MAX_CHART_BYTES) return null;
|
|
56
|
+
let obj: unknown;
|
|
57
|
+
try {
|
|
58
|
+
obj = JSON.parse(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null;
|
|
63
|
+
const o = obj as Record<string, unknown>;
|
|
64
|
+
const type = typeof o.type === 'string' ? o.type.toLowerCase() : '';
|
|
65
|
+
if (!CHART_TYPES.has(type)) return null;
|
|
66
|
+
|
|
67
|
+
const x = o.x;
|
|
68
|
+
if (!Array.isArray(x) || !x.length || x.length > MAX_CHART_POINTS) return null;
|
|
69
|
+
const labels = x.map((v) => (typeof v === 'string' || typeof v === 'number' ? String(v) : null));
|
|
70
|
+
if (labels.some((v) => v === null)) return null;
|
|
71
|
+
|
|
72
|
+
const rawSeries = o.series;
|
|
73
|
+
if (!Array.isArray(rawSeries) || !rawSeries.length || rawSeries.length > MAX_CHART_SERIES) return null;
|
|
74
|
+
const series: ChartSpec['series'] = [];
|
|
75
|
+
for (const s of rawSeries) {
|
|
76
|
+
if (!s || typeof s !== 'object') return null;
|
|
77
|
+
const rec = s as Record<string, unknown>;
|
|
78
|
+
if (!Array.isArray(rec.data) || rec.data.length !== labels.length) return null;
|
|
79
|
+
const data = rec.data.map((v) => (typeof v === 'number' && Number.isFinite(v) ? v : null));
|
|
80
|
+
const name = typeof rec.name === 'string' ? rec.name.slice(0, 60) : '';
|
|
81
|
+
const axis = rec.axis === 'right' ? 'right' : undefined;
|
|
82
|
+
series.push({ name, data, axis });
|
|
83
|
+
}
|
|
84
|
+
// 至少要有可画的点,避免空图
|
|
85
|
+
if (!series.some((s) => s.data.some((v) => v !== null))) return null;
|
|
86
|
+
|
|
87
|
+
const title = typeof o.title === 'string' ? o.title.slice(0, 120) : '';
|
|
88
|
+
return { type: type as ChartSpec['type'], ...(title ? { title } : {}), x: labels as string[], series };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function renderChartBlock(lang: string, code: string): string | null {
|
|
92
|
+
if (lang !== 'chart') return null;
|
|
93
|
+
const spec = parseChartSpec(code);
|
|
94
|
+
if (!spec) return null;
|
|
95
|
+
const json = JSON.stringify(spec);
|
|
96
|
+
const label = spec.title || spec.series.map((s) => s.name).filter(Boolean).join(' / ') || 'chart';
|
|
97
|
+
return (
|
|
98
|
+
`<figure class="md-chart" data-chart="${escapeHtml(json)}">` +
|
|
99
|
+
(spec.title ? `<figcaption class="md-chart-title">${escapeHtml(spec.title)}</figcaption>` : '') +
|
|
100
|
+
`<div class="md-chart-canvas" role="img" aria-label="${escapeHtml(label)}"></div>` +
|
|
101
|
+
`<noscript><pre class="code-block" data-lang="chart"><code>${escapeHtml(json)}</code></pre></noscript>` +
|
|
102
|
+
`</figure>`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/* ------------------------------------------------------------------ 链接 */
|
|
107
|
+
|
|
108
|
+
function safeUrl(raw: string): string | null {
|
|
109
|
+
const url = String(raw || '').trim();
|
|
110
|
+
if (/^https?:\/\//i.test(url) || url.startsWith('/')) return url;
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const isExternal = (url: string): boolean => /^https?:\/\//i.test(url);
|
|
115
|
+
|
|
116
|
+
/* ------------------------------------------------------------------ 渲染 */
|
|
117
|
+
|
|
118
|
+
const marked = new Marked({ gfm: true, breaks: true });
|
|
119
|
+
|
|
120
|
+
// marked 只允许在模块顶层 use() 一次(官方警告:反复 use 会叠加扩展)
|
|
121
|
+
marked.use({
|
|
122
|
+
renderer: {
|
|
123
|
+
heading({ tokens, depth }: Tokens.Heading) {
|
|
124
|
+
// 页面自身已有 h1,正文从 h2 起;上限 h5 与既有 CSS 对齐,
|
|
125
|
+
// 不允许跳级由 normalizeHeadingLevels 兜底
|
|
126
|
+
const level = Math.min(5, depth + 1);
|
|
127
|
+
const inner = this.parser.parseInline(tokens);
|
|
128
|
+
return `<h${level}>${inner}</h${level}>\n`;
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
code({ text, lang }: Tokens.Code) {
|
|
132
|
+
const language = (lang || '').trim();
|
|
133
|
+
const chart = renderChartBlock(language.toLowerCase(), text);
|
|
134
|
+
if (chart) return chart + '\n';
|
|
135
|
+
return `<pre class="code-block" data-lang="${escapeHtml(language)}"><code>${escapeHtml(
|
|
136
|
+
text.replace(/\n$/, ''),
|
|
137
|
+
)}</code></pre>\n`;
|
|
138
|
+
},
|
|
139
|
+
|
|
140
|
+
codespan({ text }: Tokens.Codespan) {
|
|
141
|
+
return `<code class="inline-code">${escapeHtml(text)}</code>`;
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
table(token: Tokens.Table) {
|
|
145
|
+
let head = '<thead><tr>';
|
|
146
|
+
for (const cell of token.header) {
|
|
147
|
+
head += `<th${alignStyle(cell.align)}>${this.parser.parseInline(cell.tokens)}</th>`;
|
|
148
|
+
}
|
|
149
|
+
head += '</tr></thead>';
|
|
150
|
+
|
|
151
|
+
let body = '';
|
|
152
|
+
if (token.rows.length) {
|
|
153
|
+
body = '<tbody>';
|
|
154
|
+
for (const row of token.rows) {
|
|
155
|
+
body += '<tr>';
|
|
156
|
+
for (const cell of row) {
|
|
157
|
+
body += `<td${alignStyle(cell.align)}>${this.parser.parseInline(cell.tokens)}</td>`;
|
|
158
|
+
}
|
|
159
|
+
body += '</tr>';
|
|
160
|
+
}
|
|
161
|
+
body += '</tbody>';
|
|
162
|
+
}
|
|
163
|
+
// 窄屏靠 .table-wrap 横向滚动,避免表格撑破正文栏
|
|
164
|
+
return `<div class="table-wrap"><table class="md-table">${head}${body}</table></div>\n`;
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
link({ href, title, tokens }: Tokens.Link) {
|
|
168
|
+
const safe = safeUrl(href);
|
|
169
|
+
if (!safe) return this.parser.parseInline(tokens);
|
|
170
|
+
const label = this.parser.parseInline(tokens);
|
|
171
|
+
const ext = isExternal(safe) ? ' target="_blank" rel="nofollow noopener noreferrer"' : '';
|
|
172
|
+
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
|
|
173
|
+
return `<a href="${escapeHtml(safe)}"${titleAttr}${ext}>${label}</a>`;
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
image({ href, title, text }: Tokens.Image) {
|
|
177
|
+
const safe = safeUrl(href);
|
|
178
|
+
if (!safe) return escapeHtml(text || '');
|
|
179
|
+
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
|
|
180
|
+
return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text || '')}"${titleAttr} loading="lazy" decoding="async" />`;
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
text(token: Tokens.Escape | Tokens.Text) {
|
|
184
|
+
// Escape token:marked 已完成转义,原样透传
|
|
185
|
+
if (token.type === 'escape') return token.text;
|
|
186
|
+
if ('tokens' in token && token.tokens) return this.parser.parseInline(token.tokens);
|
|
187
|
+
const raw = 'escaped' in token && token.escaped ? token.text : escapeHtml(token.text);
|
|
188
|
+
return raw;
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
// 正文里的原始 HTML 一律按字面文本展示(先整体转义),
|
|
192
|
+
// 不把 <div>/<iframe> 原样透传后再指望 sanitize 兜底。
|
|
193
|
+
html({ text }: Tokens.HTML | Tokens.Tag) {
|
|
194
|
+
return escapeHtml(text);
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
function alignStyle(align: string | null | undefined): string {
|
|
200
|
+
return align === 'center' || align === 'right' || align === 'left' ? ` style="text-align:${align}"` : '';
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 供 section 注入自定义 marked 扩展(M2 sections 用)。
|
|
205
|
+
* 注意:marked 单例上反复 use 会叠加扩展,注入应只在模块加载期发生一次。
|
|
206
|
+
*/
|
|
207
|
+
export function registerMdExtension(ext: MarkedExtension): void {
|
|
208
|
+
marked.use(ext);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/* -------------------------------------------------------------- sanitize */
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 白名单只覆盖本渲染器实际产出的结构。
|
|
215
|
+
* 注意:sanitize-html 默认会把不在 allowedTags 里的标签连同内容一起删除,
|
|
216
|
+
* 因此 figure / noscript 这类图表占位必须显式放行。
|
|
217
|
+
*/
|
|
218
|
+
const SANITIZE_OPTIONS: sanitizeHtml.IOptions = {
|
|
219
|
+
allowedTags: [
|
|
220
|
+
'p', 'br', 'strong', 'em', 'del', 'code', 'pre', 'a', 'img',
|
|
221
|
+
'blockquote', 'ul', 'ol', 'li', 'hr',
|
|
222
|
+
'h2', 'h3', 'h4', 'h5', 'h6',
|
|
223
|
+
'table', 'thead', 'tbody', 'tr', 'th', 'td',
|
|
224
|
+
'div', 'span', 'figure', 'figcaption', 'noscript',
|
|
225
|
+
],
|
|
226
|
+
allowedAttributes: {
|
|
227
|
+
a: ['href', 'title', 'target', 'rel', 'class'],
|
|
228
|
+
img: ['src', 'alt', 'title', 'loading', 'decoding'],
|
|
229
|
+
code: ['class'],
|
|
230
|
+
pre: ['class', 'data-lang'],
|
|
231
|
+
table: ['class'],
|
|
232
|
+
div: ['class', 'role', 'aria-label'],
|
|
233
|
+
figure: ['class', 'data-chart'],
|
|
234
|
+
figcaption: ['class'],
|
|
235
|
+
th: ['style'],
|
|
236
|
+
td: ['style'],
|
|
237
|
+
span: ['class'],
|
|
238
|
+
},
|
|
239
|
+
allowedStyles: {
|
|
240
|
+
th: { 'text-align': [/^(left|center|right)$/] },
|
|
241
|
+
td: { 'text-align': [/^(left|center|right)$/] },
|
|
242
|
+
},
|
|
243
|
+
allowedSchemes: ['http', 'https'],
|
|
244
|
+
allowedSchemesAppliedToAttributes: ['href', 'src'],
|
|
245
|
+
allowProtocolRelative: false,
|
|
246
|
+
disallowedTagsMode: 'discard',
|
|
247
|
+
parser: {
|
|
248
|
+
lowerCaseTags: false,
|
|
249
|
+
lowerCaseAttributeNames: false,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
/* ------------------------------------------------------------------ 导出 */
|
|
254
|
+
|
|
255
|
+
export function renderMarkdown(input: string): string {
|
|
256
|
+
if (!input) return '';
|
|
257
|
+
const text = String(input).replace(/\r\n?/g, '\n').replace(/\u0000/g, '').slice(0, MAX_INPUT);
|
|
258
|
+
const html = marked.parse(text) as string;
|
|
259
|
+
return sanitizeHtml(html, SANITIZE_OPTIONS).trim();
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 把 HTML 的标题层级压平到从 h2 起、且不跳级。
|
|
264
|
+
*
|
|
265
|
+
* 两种情况会用到:
|
|
266
|
+
* 1. 历史渲染产物(h4/h5 直接落地);
|
|
267
|
+
* 2. 作者以 `###` 开头,marked 产出 h4 —— 首个标题会跳级。
|
|
268
|
+
* 只在渲染前做一次归一化,不回填历史数据。
|
|
269
|
+
*/
|
|
270
|
+
export function normalizeHeadingLevels(html: string): string {
|
|
271
|
+
if (!html || !/<h[2-6][\s>]/.test(html)) return html;
|
|
272
|
+
let prev = 1;
|
|
273
|
+
return html.replace(/<h([2-6])(\s[^>]*)?>([\s\S]*?)<\/h\1>/g, (_m, raw: string, attrs = '', inner: string) => {
|
|
274
|
+
const level = Math.min(Number(raw), prev + 1);
|
|
275
|
+
prev = level;
|
|
276
|
+
return `<h${level}${attrs}>${inner}</h${level}>`;
|
|
277
|
+
});
|
|
278
|
+
}
|
package/src/media.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Hono } from 'hono';
|
|
2
|
+
import type { EngineConfig } from './types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* /media/:key storage 代理(总设计 §1 engine/media.ts,M2):
|
|
6
|
+
*
|
|
7
|
+
* - 对象读取走 platform.storage(workers = R2 binding,node = fs public/media/),
|
|
8
|
+
* 不暴露 bucket 名与内部结构
|
|
9
|
+
* - 对象键带随机串即不可猜 URL:不要求登录,否则外链/客户端里打不开
|
|
10
|
+
* - 一年 + immutable(键随机生成,内容永不改写);nosniff + 只许按图片解析
|
|
11
|
+
* - 404 / 非法键 no-store(红线:非 2xx 一律不进任何缓存)
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** 允许的对象键:字母数字开头,/ . _ - 组合;拒绝 ..、空段与控制字符 */
|
|
15
|
+
export function isValidMediaKey(key: string): boolean {
|
|
16
|
+
if (!key || key.length > 512) return false;
|
|
17
|
+
if (key.includes('..')) return false;
|
|
18
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9/_.-]*$/.test(key)) return false;
|
|
19
|
+
if (key.endsWith('/')) return false;
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const MIME_BY_EXT: Record<string, string> = {
|
|
24
|
+
webp: 'image/webp',
|
|
25
|
+
png: 'image/png',
|
|
26
|
+
jpg: 'image/jpeg',
|
|
27
|
+
jpeg: 'image/jpeg',
|
|
28
|
+
gif: 'image/gif',
|
|
29
|
+
avif: 'image/avif',
|
|
30
|
+
svg: 'image/svg+xml',
|
|
31
|
+
ico: 'image/x-icon',
|
|
32
|
+
mp4: 'video/mp4',
|
|
33
|
+
webm: 'video/webm',
|
|
34
|
+
pdf: 'application/pdf',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function mimeForKey(key: string, stored: string | undefined): string {
|
|
38
|
+
if (stored && stored !== 'application/octet-stream') return stored;
|
|
39
|
+
const ext = key.slice(key.lastIndexOf('.') + 1).toLowerCase();
|
|
40
|
+
return MIME_BY_EXT[ext] ?? 'application/octet-stream';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function registerMediaRoute(app: Hono, config: EngineConfig): void {
|
|
44
|
+
app.get('/media/*', async (c) => {
|
|
45
|
+
const key = c.req.path.slice('/media/'.length);
|
|
46
|
+
if (!isValidMediaKey(key)) {
|
|
47
|
+
return new Response('Not Found', {
|
|
48
|
+
status: 404,
|
|
49
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const obj = await config.platform.storage.get(key);
|
|
54
|
+
if (!obj) {
|
|
55
|
+
return new Response('Not Found', {
|
|
56
|
+
status: 404,
|
|
57
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const headers = new Headers();
|
|
62
|
+
headers.set('content-type', mimeForKey(key, obj.contentType));
|
|
63
|
+
headers.set('cache-control', 'public, max-age=31536000, immutable');
|
|
64
|
+
// 用户上传内容只按声明的类型解析:nosniff + 正确 image/* 已足够阻止被当 HTML/脚本执行;
|
|
65
|
+
// 不加 CSP(图片查看器会因 default-src 'none' 报控制台错误)
|
|
66
|
+
headers.set('x-content-type-options', 'nosniff');
|
|
67
|
+
headers.set('content-disposition', 'inline');
|
|
68
|
+
return new Response(obj.body, { status: 200, headers });
|
|
69
|
+
});
|
|
70
|
+
}
|