koishi-plugin-clocktower 0.0.0-stage → 1.0.0
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/lib/crawler.d.ts +80 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +586 -0
- package/package.json +23 -3
- package/readme.md +68 -0
- package/README.md +0 -3
package/lib/crawler.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export declare const RULE_PAGES: readonly ["规则概要", "重要细节", "术语汇总", "给说书人的建议", "规则解释", "相克规则", "哪些是“可以但不建议”", "夜晚行动顺序一览", "钟楼谜团隐性规则汇总", "规则调整提前公示"];
|
|
2
|
+
type PageKind = 'rule' | 'index' | 'role';
|
|
3
|
+
interface ParseLink {
|
|
4
|
+
ns: number;
|
|
5
|
+
title: string;
|
|
6
|
+
exists?: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface WikiSection {
|
|
9
|
+
line: string;
|
|
10
|
+
level?: string;
|
|
11
|
+
index?: string;
|
|
12
|
+
anchor?: string;
|
|
13
|
+
[key: string]: unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface WikiImage {
|
|
16
|
+
url: string;
|
|
17
|
+
alt: string;
|
|
18
|
+
localPath?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface WikiPage {
|
|
21
|
+
kind: PageKind;
|
|
22
|
+
requestedTitle: string;
|
|
23
|
+
title: string;
|
|
24
|
+
pageId: number;
|
|
25
|
+
revisionId?: number;
|
|
26
|
+
displayTitle?: string;
|
|
27
|
+
sourceUrl: string;
|
|
28
|
+
fetchedAt: string;
|
|
29
|
+
sourceIndexes: string[];
|
|
30
|
+
html: string;
|
|
31
|
+
text: string;
|
|
32
|
+
wikitext: string;
|
|
33
|
+
images: WikiImage[];
|
|
34
|
+
imageFiles: string[];
|
|
35
|
+
links: ParseLink[];
|
|
36
|
+
externalLinks: string[];
|
|
37
|
+
sections: WikiSection[];
|
|
38
|
+
categories: unknown[];
|
|
39
|
+
properties: unknown[];
|
|
40
|
+
}
|
|
41
|
+
export interface PageResult {
|
|
42
|
+
page: WikiPage;
|
|
43
|
+
offline: boolean;
|
|
44
|
+
}
|
|
45
|
+
export type LookupResult = {
|
|
46
|
+
status: 'ok';
|
|
47
|
+
result: PageResult;
|
|
48
|
+
} | {
|
|
49
|
+
status: 'candidates';
|
|
50
|
+
titles: string[];
|
|
51
|
+
} | {
|
|
52
|
+
status: 'not-found';
|
|
53
|
+
};
|
|
54
|
+
export interface WikiOptions {
|
|
55
|
+
outputDir: string;
|
|
56
|
+
pageCacheHours: number;
|
|
57
|
+
indexCacheHours: number;
|
|
58
|
+
logger?: (message: string) => void;
|
|
59
|
+
}
|
|
60
|
+
export declare class ClocktowerWiki {
|
|
61
|
+
private options;
|
|
62
|
+
private catalogs;
|
|
63
|
+
private cacheCatalogs;
|
|
64
|
+
private catalogTask?;
|
|
65
|
+
private saveQueue;
|
|
66
|
+
private pending;
|
|
67
|
+
private logger;
|
|
68
|
+
constructor(options: WikiOptions);
|
|
69
|
+
private cachePath;
|
|
70
|
+
private addSummary;
|
|
71
|
+
private ensureCatalog;
|
|
72
|
+
private loadCatalog;
|
|
73
|
+
private findSummary;
|
|
74
|
+
private savePage;
|
|
75
|
+
getPage(title: string, kind: PageKind, refresh?: boolean): Promise<PageResult>;
|
|
76
|
+
private search;
|
|
77
|
+
findRole(query: string, refresh?: boolean): Promise<LookupResult>;
|
|
78
|
+
findRule(query: string, refresh?: boolean): Promise<LookupResult>;
|
|
79
|
+
}
|
|
80
|
+
export {};
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Context, Schema } from 'koishi';
|
|
2
|
+
export declare const name = "clocktower";
|
|
3
|
+
export interface Config {
|
|
4
|
+
pageCacheHours: number;
|
|
5
|
+
indexCacheHours: number;
|
|
6
|
+
}
|
|
7
|
+
export declare const Config: Schema<Config>;
|
|
8
|
+
export declare function apply(ctx: Context, config: Config): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name2 in all)
|
|
10
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
Config: () => Config,
|
|
34
|
+
apply: () => apply,
|
|
35
|
+
name: () => name
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(src_exports);
|
|
38
|
+
var import_koishi = require("koishi");
|
|
39
|
+
var import_node_path2 = require("node:path");
|
|
40
|
+
|
|
41
|
+
// src/crawler.ts
|
|
42
|
+
var import_node_crypto = require("node:crypto");
|
|
43
|
+
var import_promises = require("node:fs/promises");
|
|
44
|
+
var import_node_path = require("node:path");
|
|
45
|
+
var cheerio = __toESM(require("cheerio"));
|
|
46
|
+
var BASE_URL = "https://clocktower-wiki.gstonegames.com";
|
|
47
|
+
var API_URL = `${BASE_URL}/api.php`;
|
|
48
|
+
var REQUEST_INTERVAL = 120;
|
|
49
|
+
var REQUEST_TIMEOUT = 3e4;
|
|
50
|
+
var MAX_ATTEMPTS = 3;
|
|
51
|
+
var RULE_PAGES = [
|
|
52
|
+
"规则概要",
|
|
53
|
+
"重要细节",
|
|
54
|
+
"术语汇总",
|
|
55
|
+
"给说书人的建议",
|
|
56
|
+
"规则解释",
|
|
57
|
+
"相克规则",
|
|
58
|
+
"哪些是“可以但不建议”",
|
|
59
|
+
"夜晚行动顺序一览",
|
|
60
|
+
"钟楼谜团隐性规则汇总",
|
|
61
|
+
"规则调整提前公示"
|
|
62
|
+
];
|
|
63
|
+
var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)), "sleep");
|
|
64
|
+
var lastRequestAt = 0;
|
|
65
|
+
async function request(url) {
|
|
66
|
+
let lastError;
|
|
67
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
68
|
+
const wait = lastRequestAt + REQUEST_INTERVAL - Date.now();
|
|
69
|
+
if (wait > 0) await sleep(wait);
|
|
70
|
+
lastRequestAt = Date.now();
|
|
71
|
+
try {
|
|
72
|
+
const response = await fetch(url, {
|
|
73
|
+
headers: { "user-agent": "KoishiClocktower/0.2" },
|
|
74
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT)
|
|
75
|
+
});
|
|
76
|
+
if (response.ok) return response;
|
|
77
|
+
const error = new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
78
|
+
if (response.status < 500 && response.status !== 429) throw error;
|
|
79
|
+
lastError = error;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof Error && /^HTTP 4\d\d/.test(error.message) && !error.message.startsWith("HTTP 429")) {
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
85
|
+
}
|
|
86
|
+
if (attempt < MAX_ATTEMPTS) await sleep(attempt * 1e3);
|
|
87
|
+
}
|
|
88
|
+
throw lastError ?? new Error("请求失败");
|
|
89
|
+
}
|
|
90
|
+
__name(request, "request");
|
|
91
|
+
function pageUrl(title) {
|
|
92
|
+
return `${BASE_URL}/index.php?title=${encodeURIComponent(title)}`;
|
|
93
|
+
}
|
|
94
|
+
__name(pageUrl, "pageUrl");
|
|
95
|
+
async function fetchParse(title) {
|
|
96
|
+
const params = new URLSearchParams({
|
|
97
|
+
action: "parse",
|
|
98
|
+
page: title,
|
|
99
|
+
redirects: "1",
|
|
100
|
+
format: "json",
|
|
101
|
+
formatversion: "2",
|
|
102
|
+
prop: "text|links|images|sections|categories|properties|displaytitle|wikitext|revid|externallinks"
|
|
103
|
+
});
|
|
104
|
+
const response = await request(`${API_URL}?${params}`);
|
|
105
|
+
const data = await response.json();
|
|
106
|
+
if (data.error) throw new Error(`${title}:${data.error.code} ${data.error.info}`);
|
|
107
|
+
if (!data.parse) throw new Error(`${title}:接口未返回正文`);
|
|
108
|
+
return data.parse;
|
|
109
|
+
}
|
|
110
|
+
__name(fetchParse, "fetchParse");
|
|
111
|
+
function absoluteUrl(value, base) {
|
|
112
|
+
try {
|
|
113
|
+
return new URL(value, base).href;
|
|
114
|
+
} catch {
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
__name(absoluteUrl, "absoluteUrl");
|
|
119
|
+
function normalizeHtml(html, base) {
|
|
120
|
+
const $ = cheerio.load(html);
|
|
121
|
+
$("[href]").each((_, element) => {
|
|
122
|
+
const href = $(element).attr("href");
|
|
123
|
+
if (href) $(element).attr("href", absoluteUrl(href, base));
|
|
124
|
+
});
|
|
125
|
+
$("[src]").each((_, element) => {
|
|
126
|
+
const src = $(element).attr("src");
|
|
127
|
+
if (src) $(element).attr("src", absoluteUrl(src, base));
|
|
128
|
+
});
|
|
129
|
+
$("[srcset]").each((_, element) => {
|
|
130
|
+
const srcset = $(element).attr("srcset");
|
|
131
|
+
if (!srcset) return;
|
|
132
|
+
const normalized = srcset.split(",").map((part) => {
|
|
133
|
+
const [url, ...descriptor] = part.trim().split(/\s+/);
|
|
134
|
+
return [absoluteUrl(url, base), ...descriptor].join(" ");
|
|
135
|
+
}).join(", ");
|
|
136
|
+
$(element).attr("srcset", normalized);
|
|
137
|
+
});
|
|
138
|
+
return $.root().html() ?? html;
|
|
139
|
+
}
|
|
140
|
+
__name(normalizeHtml, "normalizeHtml");
|
|
141
|
+
function extractText(html) {
|
|
142
|
+
const $ = cheerio.load(html);
|
|
143
|
+
$("script, style, .mw-editsection, #toc").remove();
|
|
144
|
+
$("br").replaceWith("\n");
|
|
145
|
+
$("td, th").each((_, element) => {
|
|
146
|
+
$(element).append(" ");
|
|
147
|
+
});
|
|
148
|
+
$("h1, h2, h3, h4, h5, h6, p, li, pre, tr, blockquote, .gallerybox").each((_, element) => {
|
|
149
|
+
$(element).append("\n");
|
|
150
|
+
});
|
|
151
|
+
return $.root().text().replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n[ \t]+/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
152
|
+
}
|
|
153
|
+
__name(extractText, "extractText");
|
|
154
|
+
function extractImages(html) {
|
|
155
|
+
const $ = cheerio.load(html);
|
|
156
|
+
const seen = /* @__PURE__ */ new Set();
|
|
157
|
+
const images = [];
|
|
158
|
+
$("img[src]").each((_, element) => {
|
|
159
|
+
const url = $(element).attr("src");
|
|
160
|
+
if (!url || url.startsWith("data:") || seen.has(url)) return;
|
|
161
|
+
seen.add(url);
|
|
162
|
+
images.push({ url, alt: $(element).attr("alt") ?? "" });
|
|
163
|
+
});
|
|
164
|
+
return images;
|
|
165
|
+
}
|
|
166
|
+
__name(extractImages, "extractImages");
|
|
167
|
+
function isRolePage(page) {
|
|
168
|
+
return page.sections.some((section) => section.line === "角色能力");
|
|
169
|
+
}
|
|
170
|
+
__name(isRolePage, "isRolePage");
|
|
171
|
+
function fileStem(title) {
|
|
172
|
+
const safeTitle = title.replace(/[<>:"/\\|?*\x00-\x1F]/g, "_").replace(/[. ]+$/g, "");
|
|
173
|
+
const hash = (0, import_node_crypto.createHash)("sha1").update(title).digest("hex").slice(0, 8);
|
|
174
|
+
return `${safeTitle || "page"}-${hash}`;
|
|
175
|
+
}
|
|
176
|
+
__name(fileStem, "fileStem");
|
|
177
|
+
function normalizeTitle(title) {
|
|
178
|
+
return title.trim().replace(/\s+/g, "").toLocaleLowerCase();
|
|
179
|
+
}
|
|
180
|
+
__name(normalizeTitle, "normalizeTitle");
|
|
181
|
+
function rankTitles(titles, query) {
|
|
182
|
+
const normalizedQuery = normalizeTitle(query);
|
|
183
|
+
const candidates = [...new Map(titles.map((title) => [normalizeTitle(title), title])).values()];
|
|
184
|
+
const exact = candidates.filter((title) => normalizeTitle(title) === normalizedQuery);
|
|
185
|
+
if (exact.length) return exact;
|
|
186
|
+
const ranked = candidates.flatMap((title) => {
|
|
187
|
+
const normalized = normalizeTitle(title);
|
|
188
|
+
if (normalized.startsWith(normalizedQuery)) return [{ title, score: 1 }];
|
|
189
|
+
if (normalized.includes(normalizedQuery)) return [{ title, score: 2 }];
|
|
190
|
+
return [];
|
|
191
|
+
});
|
|
192
|
+
if (!ranked.length) return [];
|
|
193
|
+
const bestScore = Math.min(...ranked.map((item) => item.score));
|
|
194
|
+
return ranked.filter((item) => item.score === bestScore).map((item) => item.title);
|
|
195
|
+
}
|
|
196
|
+
__name(rankTitles, "rankTitles");
|
|
197
|
+
async function readJson(path) {
|
|
198
|
+
try {
|
|
199
|
+
return JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
__name(readJson, "readJson");
|
|
205
|
+
async function readPage(path) {
|
|
206
|
+
const page = await readJson(path);
|
|
207
|
+
if (!page || typeof page.title !== "string" || typeof page.text !== "string" || !Array.isArray(page.sections)) return null;
|
|
208
|
+
return page;
|
|
209
|
+
}
|
|
210
|
+
__name(readPage, "readPage");
|
|
211
|
+
async function writeJson(path, value) {
|
|
212
|
+
await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
|
|
213
|
+
const temporaryPath = `${path}.tmp`;
|
|
214
|
+
await (0, import_promises.writeFile)(temporaryPath, `${JSON.stringify(value, null, 2)}
|
|
215
|
+
`, "utf8");
|
|
216
|
+
await (0, import_promises.rename)(temporaryPath, path);
|
|
217
|
+
}
|
|
218
|
+
__name(writeJson, "writeJson");
|
|
219
|
+
function isFresh(fetchedAt, maxAge) {
|
|
220
|
+
const timestamp = Date.parse(fetchedAt);
|
|
221
|
+
return Number.isFinite(timestamp) && Date.now() - timestamp <= maxAge;
|
|
222
|
+
}
|
|
223
|
+
__name(isFresh, "isFresh");
|
|
224
|
+
async function crawlPage(title, kind, sourceIndexes = []) {
|
|
225
|
+
const result = await fetchParse(title);
|
|
226
|
+
const sourceUrl = pageUrl(result.title);
|
|
227
|
+
const html = normalizeHtml(result.text, sourceUrl);
|
|
228
|
+
return {
|
|
229
|
+
kind,
|
|
230
|
+
requestedTitle: title,
|
|
231
|
+
title: result.title,
|
|
232
|
+
pageId: result.pageid,
|
|
233
|
+
revisionId: result.revid,
|
|
234
|
+
displayTitle: result.displaytitle,
|
|
235
|
+
sourceUrl,
|
|
236
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
237
|
+
sourceIndexes,
|
|
238
|
+
html,
|
|
239
|
+
text: extractText(html),
|
|
240
|
+
wikitext: result.wikitext ?? "",
|
|
241
|
+
images: extractImages(html),
|
|
242
|
+
imageFiles: result.images ?? [],
|
|
243
|
+
links: result.links ?? [],
|
|
244
|
+
externalLinks: result.externallinks ?? [],
|
|
245
|
+
sections: result.sections ?? [],
|
|
246
|
+
categories: result.categories ?? [],
|
|
247
|
+
properties: result.properties ?? []
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
__name(crawlPage, "crawlPage");
|
|
251
|
+
var ClocktowerWiki = class {
|
|
252
|
+
constructor(options) {
|
|
253
|
+
this.options = options;
|
|
254
|
+
this.logger = options.logger ?? (() => {
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
static {
|
|
258
|
+
__name(this, "ClocktowerWiki");
|
|
259
|
+
}
|
|
260
|
+
catalogs = {
|
|
261
|
+
rule: /* @__PURE__ */ new Map(),
|
|
262
|
+
index: /* @__PURE__ */ new Map(),
|
|
263
|
+
role: /* @__PURE__ */ new Map()
|
|
264
|
+
};
|
|
265
|
+
cacheCatalogs = {
|
|
266
|
+
rule: /* @__PURE__ */ new Map(),
|
|
267
|
+
index: /* @__PURE__ */ new Map(),
|
|
268
|
+
role: /* @__PURE__ */ new Map()
|
|
269
|
+
};
|
|
270
|
+
catalogTask;
|
|
271
|
+
saveQueue = Promise.resolve();
|
|
272
|
+
pending = /* @__PURE__ */ new Map();
|
|
273
|
+
logger;
|
|
274
|
+
cachePath(title, kind) {
|
|
275
|
+
return (0, import_node_path.join)(this.options.outputDir, "cache/pages", kind, `${fileStem(title)}.json`);
|
|
276
|
+
}
|
|
277
|
+
addSummary(catalog, summary) {
|
|
278
|
+
catalog.set(normalizeTitle(summary.requestedTitle), summary);
|
|
279
|
+
}
|
|
280
|
+
async ensureCatalog() {
|
|
281
|
+
if (!this.catalogTask) this.catalogTask = this.loadCatalog();
|
|
282
|
+
await this.catalogTask;
|
|
283
|
+
}
|
|
284
|
+
async loadCatalog() {
|
|
285
|
+
const manifest = await readJson((0, import_node_path.join)(this.options.outputDir, "manifest.json"));
|
|
286
|
+
const cacheManifest = await readJson((0, import_node_path.join)(this.options.outputDir, "cache/catalog.json"));
|
|
287
|
+
for (const kind of ["rule", "index", "role"]) {
|
|
288
|
+
const key = kind === "rule" ? "rules" : kind === "index" ? "indexes" : "roles";
|
|
289
|
+
for (const summary of manifest?.[key] ?? []) this.addSummary(this.catalogs[kind], summary);
|
|
290
|
+
for (const summary of cacheManifest?.[key] ?? []) {
|
|
291
|
+
this.addSummary(this.catalogs[kind], summary);
|
|
292
|
+
this.addSummary(this.cacheCatalogs[kind], summary);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
findSummary(title, kind) {
|
|
297
|
+
const normalized = normalizeTitle(title);
|
|
298
|
+
return [...this.catalogs[kind].values()].find(
|
|
299
|
+
(summary) => normalizeTitle(summary.requestedTitle) === normalized || normalizeTitle(summary.title) === normalized
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
async savePage(page, path) {
|
|
303
|
+
const relativePath = path.slice(this.options.outputDir.length + 1).replace(/\\/g, "/");
|
|
304
|
+
const summary = {
|
|
305
|
+
title: page.title,
|
|
306
|
+
requestedTitle: page.requestedTitle,
|
|
307
|
+
sourceUrl: page.sourceUrl,
|
|
308
|
+
revisionId: page.revisionId,
|
|
309
|
+
path: relativePath,
|
|
310
|
+
sourceIndexes: page.sourceIndexes
|
|
311
|
+
};
|
|
312
|
+
this.addSummary(this.catalogs[page.kind], summary);
|
|
313
|
+
this.addSummary(this.cacheCatalogs[page.kind], summary);
|
|
314
|
+
this.saveQueue = this.saveQueue.catch(() => {
|
|
315
|
+
}).then(async () => {
|
|
316
|
+
await writeJson((0, import_node_path.join)(this.options.outputDir, "cache/catalog.json"), {
|
|
317
|
+
schemaVersion: 2,
|
|
318
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
319
|
+
rules: [...this.cacheCatalogs.rule.values()],
|
|
320
|
+
indexes: [...this.cacheCatalogs.index.values()],
|
|
321
|
+
roles: [...this.cacheCatalogs.role.values()]
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
await this.saveQueue;
|
|
325
|
+
}
|
|
326
|
+
async getPage(title, kind, refresh = false) {
|
|
327
|
+
await this.ensureCatalog();
|
|
328
|
+
const cachePath = this.cachePath(title, kind);
|
|
329
|
+
const cached = await readPage(cachePath);
|
|
330
|
+
const summary = this.findSummary(title, kind);
|
|
331
|
+
const snapshot = summary && (0, import_node_path.join)(this.options.outputDir, summary.path) !== cachePath ? await readPage((0, import_node_path.join)(this.options.outputDir, summary.path)) : null;
|
|
332
|
+
const local = [cached, snapshot].filter((page) => !!page).sort((a, b) => Date.parse(b.fetchedAt) - Date.parse(a.fetchedAt))[0];
|
|
333
|
+
const maxAge = (kind === "index" ? this.options.indexCacheHours : this.options.pageCacheHours) * 36e5;
|
|
334
|
+
if (!refresh && local && isFresh(local.fetchedAt, maxAge)) return { page: local, offline: false };
|
|
335
|
+
const key = `${kind}:${normalizeTitle(title)}`;
|
|
336
|
+
const pending = this.pending.get(key);
|
|
337
|
+
if (pending) return pending;
|
|
338
|
+
const task = (async () => {
|
|
339
|
+
try {
|
|
340
|
+
const page = await crawlPage(title, kind, local?.sourceIndexes ?? []);
|
|
341
|
+
try {
|
|
342
|
+
await writeJson(cachePath, page);
|
|
343
|
+
await this.savePage(page, cachePath);
|
|
344
|
+
} catch (error) {
|
|
345
|
+
this.logger(`缓存 ${title} 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
346
|
+
}
|
|
347
|
+
return { page, offline: false };
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (local) {
|
|
350
|
+
this.logger(`更新 ${title} 失败,使用离线缓存:${error instanceof Error ? error.message : String(error)}`);
|
|
351
|
+
return { page: local, offline: true };
|
|
352
|
+
}
|
|
353
|
+
throw error;
|
|
354
|
+
} finally {
|
|
355
|
+
this.pending.delete(key);
|
|
356
|
+
}
|
|
357
|
+
})();
|
|
358
|
+
this.pending.set(key, task);
|
|
359
|
+
return task;
|
|
360
|
+
}
|
|
361
|
+
async search(query, refresh = false) {
|
|
362
|
+
const normalized = normalizeTitle(query);
|
|
363
|
+
const path = (0, import_node_path.join)(this.options.outputDir, "cache/search", `${fileStem(normalized)}.json`);
|
|
364
|
+
const cached = await readJson(path);
|
|
365
|
+
const maxAge = this.options.indexCacheHours * 36e5;
|
|
366
|
+
if (!refresh && cached && isFresh(cached.fetchedAt, maxAge)) return cached.titles;
|
|
367
|
+
try {
|
|
368
|
+
const params = new URLSearchParams({
|
|
369
|
+
action: "opensearch",
|
|
370
|
+
search: query,
|
|
371
|
+
limit: "10",
|
|
372
|
+
namespace: "0",
|
|
373
|
+
redirects: "resolve",
|
|
374
|
+
format: "json",
|
|
375
|
+
formatversion: "2"
|
|
376
|
+
});
|
|
377
|
+
const response = await request(`${API_URL}?${params}`);
|
|
378
|
+
const data = await response.json();
|
|
379
|
+
if (!Array.isArray(data[1])) throw new Error("搜索接口返回格式不正确");
|
|
380
|
+
const titles = data[1];
|
|
381
|
+
try {
|
|
382
|
+
await writeJson(path, { query, fetchedAt: (/* @__PURE__ */ new Date()).toISOString(), titles });
|
|
383
|
+
} catch (error) {
|
|
384
|
+
this.logger(`缓存搜索“${query}”失败:${error instanceof Error ? error.message : String(error)}`);
|
|
385
|
+
}
|
|
386
|
+
return titles;
|
|
387
|
+
} catch (error) {
|
|
388
|
+
if (cached) return cached.titles;
|
|
389
|
+
throw error;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async findRole(query, refresh = false) {
|
|
393
|
+
await this.ensureCatalog();
|
|
394
|
+
const summaries = [...this.catalogs.role.values()];
|
|
395
|
+
const exact = summaries.find(
|
|
396
|
+
(summary) => normalizeTitle(summary.requestedTitle) === normalizeTitle(query) || normalizeTitle(summary.title) === normalizeTitle(query)
|
|
397
|
+
);
|
|
398
|
+
const localTitles = exact ? [exact.requestedTitle] : rankTitles(summaries.map((summary) => summary.title), query);
|
|
399
|
+
if (localTitles.length === 1) {
|
|
400
|
+
return { status: "ok", result: await this.getPage(localTitles[0], "role", refresh) };
|
|
401
|
+
}
|
|
402
|
+
if (localTitles.length > 1) return { status: "candidates", titles: localTitles.slice(0, 10) };
|
|
403
|
+
const remoteTitles = await this.search(query, refresh);
|
|
404
|
+
if (!remoteTitles.length) return { status: "not-found" };
|
|
405
|
+
const exactRemote = remoteTitles.find((title) => normalizeTitle(title) === normalizeTitle(query));
|
|
406
|
+
const ranked = exactRemote ? [exactRemote] : rankTitles(remoteTitles, query);
|
|
407
|
+
const candidates = ranked.length ? ranked : remoteTitles;
|
|
408
|
+
if (candidates.length > 1) return { status: "candidates", titles: candidates.slice(0, 10) };
|
|
409
|
+
const result = await this.getPage(candidates[0], "role", refresh);
|
|
410
|
+
if (!isRolePage(result.page)) return { status: "not-found" };
|
|
411
|
+
return { status: "ok", result };
|
|
412
|
+
}
|
|
413
|
+
async findRule(query, refresh = false) {
|
|
414
|
+
const titles = rankTitles([...RULE_PAGES], query);
|
|
415
|
+
if (!titles.length) return { status: "not-found" };
|
|
416
|
+
if (titles.length > 1) return { status: "candidates", titles };
|
|
417
|
+
return { status: "ok", result: await this.getPage(titles[0], "rule", refresh) };
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// src/index.ts
|
|
422
|
+
var name = "clocktower";
|
|
423
|
+
var Config = import_koishi.Schema.object({
|
|
424
|
+
pageCacheHours: import_koishi.Schema.number().description("角色与规则页面的缓存时长(小时),过期后仅在查询时更新。").min(1).default(168),
|
|
425
|
+
indexCacheHours: import_koishi.Schema.number().description("角色搜索索引的缓存时长(小时)。").min(1).default(24)
|
|
426
|
+
}).description("血染钟楼");
|
|
427
|
+
function escapeRegExp(value) {
|
|
428
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
429
|
+
}
|
|
430
|
+
__name(escapeRegExp, "escapeRegExp");
|
|
431
|
+
function splitSections(page) {
|
|
432
|
+
const positions = [];
|
|
433
|
+
let cursor = 0;
|
|
434
|
+
for (const section of page.sections) {
|
|
435
|
+
const pattern = new RegExp(`^${escapeRegExp(section.line)}[ \\t]*$`, "gm");
|
|
436
|
+
pattern.lastIndex = cursor;
|
|
437
|
+
const match = pattern.exec(page.text);
|
|
438
|
+
if (!match) continue;
|
|
439
|
+
positions.push({
|
|
440
|
+
line: section.line,
|
|
441
|
+
index: section.index,
|
|
442
|
+
level: Number(section.level) || 2,
|
|
443
|
+
start: match.index,
|
|
444
|
+
contentStart: match.index + match[0].length
|
|
445
|
+
});
|
|
446
|
+
cursor = match.index + match[0].length;
|
|
447
|
+
}
|
|
448
|
+
return positions.map((position, index) => {
|
|
449
|
+
let end = page.text.length;
|
|
450
|
+
for (let next = index + 1; next < positions.length; next++) {
|
|
451
|
+
if (positions[next].level <= position.level) {
|
|
452
|
+
end = positions[next].start;
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return { ...position, text: page.text.slice(position.contentStart, end).trim() };
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
__name(splitSections, "splitSections");
|
|
460
|
+
function normalize(value) {
|
|
461
|
+
return value.trim().replace(/\s+/g, "").toLocaleLowerCase();
|
|
462
|
+
}
|
|
463
|
+
__name(normalize, "normalize");
|
|
464
|
+
function selectSection(sections, query) {
|
|
465
|
+
if (/^\d+$/.test(query)) {
|
|
466
|
+
const byIndex = sections.filter((section) => section.index === query);
|
|
467
|
+
if (byIndex.length === 1) return byIndex[0];
|
|
468
|
+
}
|
|
469
|
+
const normalized = normalize(query);
|
|
470
|
+
const exact = sections.filter((section) => normalize(section.line) === normalized);
|
|
471
|
+
if (exact.length === 1) return exact[0];
|
|
472
|
+
if (exact.length > 1) return null;
|
|
473
|
+
const prefixed = sections.filter((section) => normalize(section.line).startsWith(normalized));
|
|
474
|
+
if (prefixed.length === 1) return prefixed[0];
|
|
475
|
+
if (prefixed.length > 1) return null;
|
|
476
|
+
const included = sections.filter((section) => normalize(section.line).includes(normalized));
|
|
477
|
+
return included.length === 1 ? included[0] : null;
|
|
478
|
+
}
|
|
479
|
+
__name(selectSection, "selectSection");
|
|
480
|
+
function sectionList(sections) {
|
|
481
|
+
return sections.map((section) => `${section.index ? `${section.index}. ` : ""}${section.line}`).join("\n");
|
|
482
|
+
}
|
|
483
|
+
__name(sectionList, "sectionList");
|
|
484
|
+
function truncate(text, maxLength = 2400) {
|
|
485
|
+
if (text.length <= maxLength) return text;
|
|
486
|
+
const paragraphEnd = text.lastIndexOf("\n", maxLength);
|
|
487
|
+
const end = paragraphEnd > maxLength * 0.8 ? paragraphEnd : maxLength;
|
|
488
|
+
return `${text.slice(0, end).trim()}
|
|
489
|
+
……本节较长,完整内容请查看来源页面。`;
|
|
490
|
+
}
|
|
491
|
+
__name(truncate, "truncate");
|
|
492
|
+
function offlineNotice(result) {
|
|
493
|
+
if (!result.offline) return "";
|
|
494
|
+
return `
|
|
495
|
+
【离线缓存】百科暂时不可用,内容更新于 ${result.page.fetchedAt.slice(0, 10)}。`;
|
|
496
|
+
}
|
|
497
|
+
__name(offlineNotice, "offlineNotice");
|
|
498
|
+
function formatPage(result, sectionQuery) {
|
|
499
|
+
const { page } = result;
|
|
500
|
+
const sections = splitSections(page);
|
|
501
|
+
const command = page.kind === "role" ? "clocktower/角色" : "clocktower/规则";
|
|
502
|
+
if (page.kind === "rule" && !sectionQuery) {
|
|
503
|
+
return `【${page.title}】
|
|
504
|
+
请选择章节:
|
|
505
|
+
${sectionList(sections)}
|
|
506
|
+
|
|
507
|
+
用法:${command} ${page.title} <章节名或编号>${offlineNotice(result)}
|
|
508
|
+
来源:${page.sourceUrl}`;
|
|
509
|
+
}
|
|
510
|
+
if (!sections.length) return `【${page.title}】
|
|
511
|
+
${truncate(page.text)}${offlineNotice(result)}
|
|
512
|
+
来源:${page.sourceUrl}`;
|
|
513
|
+
const query = sectionQuery ?? "角色能力";
|
|
514
|
+
const section = selectSection(sections, query);
|
|
515
|
+
if (!section) {
|
|
516
|
+
return `未在《${page.title}》中找到唯一匹配的“${query}”章节。
|
|
517
|
+
可选章节:
|
|
518
|
+
${sectionList(sections)}`;
|
|
519
|
+
}
|
|
520
|
+
return `【${page.title} · ${section.line}】
|
|
521
|
+
${truncate(section.text || "本章节暂无文字内容。")}${offlineNotice(result)}
|
|
522
|
+
|
|
523
|
+
其他章节:${sections.map((item) => item.line).join("、")}
|
|
524
|
+
用法:${command} ${page.title} <章节名或编号>
|
|
525
|
+
来源:${page.sourceUrl}`;
|
|
526
|
+
}
|
|
527
|
+
__name(formatPage, "formatPage");
|
|
528
|
+
function formatLookup(lookup, section) {
|
|
529
|
+
if (lookup.status === "ok") return formatPage(lookup.result, section);
|
|
530
|
+
if (lookup.status === "candidates") return `找到多个匹配页面:
|
|
531
|
+
${lookup.titles.join("\n")}
|
|
532
|
+
请输入更完整的名称。`;
|
|
533
|
+
return "没有找到匹配页面,请检查名称或更换关键词。";
|
|
534
|
+
}
|
|
535
|
+
__name(formatLookup, "formatLookup");
|
|
536
|
+
function apply(ctx, config) {
|
|
537
|
+
const logger = ctx.logger(name);
|
|
538
|
+
const wiki = new ClocktowerWiki({
|
|
539
|
+
outputDir: (0, import_node_path2.resolve)(ctx.baseDir, "data/clocktower"),
|
|
540
|
+
pageCacheHours: config.pageCacheHours,
|
|
541
|
+
indexCacheHours: config.indexCacheHours,
|
|
542
|
+
logger: /* @__PURE__ */ __name((message) => logger.warn(message), "logger")
|
|
543
|
+
});
|
|
544
|
+
ctx.command("clocktower/角色 [name] [section]", "查询血染钟楼角色资料").action(async (_, roleName, section) => {
|
|
545
|
+
if (!roleName) return "用法:clocktower/角色 <角色名> [章节名或编号]\n例如:clocktower/角色 洗衣妇\n默认显示“角色能力”,可指定“范例”“提示与技巧”等章节。";
|
|
546
|
+
try {
|
|
547
|
+
return formatLookup(await wiki.findRole(roleName), section);
|
|
548
|
+
} catch (error) {
|
|
549
|
+
logger.warn("角色查询失败:%s", error);
|
|
550
|
+
return `角色查询失败:${error instanceof Error ? error.message : String(error)}`;
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
ctx.command("clocktower/规则 [name] [section]", "查询血染钟楼规则").action(async (_, ruleName, section) => {
|
|
554
|
+
if (!ruleName) return `用法:clocktower/规则 <规则页名> [章节名或编号]
|
|
555
|
+
可用规则页:
|
|
556
|
+
${RULE_PAGES.join("\n")}`;
|
|
557
|
+
try {
|
|
558
|
+
return formatLookup(await wiki.findRule(ruleName), section);
|
|
559
|
+
} catch (error) {
|
|
560
|
+
logger.warn("规则查询失败:%s", error);
|
|
561
|
+
return `规则查询失败:${error instanceof Error ? error.message : String(error)}`;
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
ctx.command("clocktower/刷新 <name>", "刷新单个角色或规则页面", { authority: 3 }).action(async (_, pageName) => {
|
|
565
|
+
try {
|
|
566
|
+
const rule = await wiki.findRule(pageName, true);
|
|
567
|
+
if (rule.status !== "not-found") {
|
|
568
|
+
if (rule.status === "candidates") return formatLookup(rule);
|
|
569
|
+
return rule.result.offline ? `百科连接失败,仍使用《${rule.result.page.title}》的离线缓存。` : `已刷新规则页《${rule.result.page.title}》。`;
|
|
570
|
+
}
|
|
571
|
+
const role = await wiki.findRole(pageName, true);
|
|
572
|
+
if (role.status !== "ok") return formatLookup(role);
|
|
573
|
+
return role.result.offline ? `百科连接失败,仍使用《${role.result.page.title}》的离线缓存。` : `已刷新角色《${role.result.page.title}》。`;
|
|
574
|
+
} catch (error) {
|
|
575
|
+
logger.warn("单页刷新失败:%s", error);
|
|
576
|
+
return `刷新失败:${error instanceof Error ? error.message : String(error)}`;
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
__name(apply, "apply");
|
|
581
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
582
|
+
0 && (module.exports = {
|
|
583
|
+
Config,
|
|
584
|
+
apply,
|
|
585
|
+
name
|
|
586
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "koishi-plugin-clocktower",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "血染钟楼:钟楼百科角色资料与规则按需查询",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"typings": "lib/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"lib",
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"chatbot",
|
|
14
|
+
"koishi",
|
|
15
|
+
"plugin",
|
|
16
|
+
"clocktower",
|
|
17
|
+
"blood-on-the-clocktower",
|
|
18
|
+
"血染钟楼"
|
|
19
|
+
],
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"cheerio": "^1.0.0"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"koishi": "^4.18.7"
|
|
25
|
+
}
|
|
6
26
|
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# koishi-plugin-clocktower
|
|
2
|
+
|
|
3
|
+
血染钟楼插件。提供钟楼百科角色资料与规则的按需查询、本地缓存和离线兜底,不会在启动时同步整个百科,也不会预下载图片。
|
|
4
|
+
|
|
5
|
+
## 配置项
|
|
6
|
+
|
|
7
|
+
| 配置项 | 类型 | 默认值 | 说明 |
|
|
8
|
+
| --- | --- | --- | --- |
|
|
9
|
+
| `pageCacheHours` | `number` | `168` | 角色与规则页面缓存时长,默认 7 天 |
|
|
10
|
+
| `indexCacheHours` | `number` | `24` | 角色搜索索引缓存时长,默认 1 天 |
|
|
11
|
+
|
|
12
|
+
## 指令
|
|
13
|
+
|
|
14
|
+
| 指令 | 权限 | 说明 |
|
|
15
|
+
| --- | --- | --- |
|
|
16
|
+
| `clocktower/角色 <角色名> [章节名或编号]` | 1 | 模糊查询角色,默认显示“角色能力”,也可查询“范例”“提示与技巧”等章节 |
|
|
17
|
+
| `clocktower/规则 <规则页名> [章节名或编号]` | 1 | 查询规则页;不指定章节时列出可选章节 |
|
|
18
|
+
| `clocktower/刷新 <角色名或规则页名>` | 3 | 强制刷新单个页面,不再提供全量同步 |
|
|
19
|
+
|
|
20
|
+
示例:
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
clocktower/角色 洗衣妇
|
|
24
|
+
clocktower/角色 洗衣妇 提示与技巧
|
|
25
|
+
clocktower/角色 洗衣妇 8
|
|
26
|
+
clocktower/规则 规则概要
|
|
27
|
+
clocktower/规则 规则概要 二、夜晚阶段
|
|
28
|
+
clocktower/刷新 洗衣妇
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
角色名支持精确匹配、前缀和包含匹配;本地没有结果时使用 MediaWiki `opensearch` 搜索。存在多个同等级匹配项时返回候选名称,不会随意选择页面。
|
|
32
|
+
|
|
33
|
+
## 查询与缓存
|
|
34
|
+
|
|
35
|
+
- 页面通过 MediaWiki `action=parse` 按需获取,只有被查询或手动刷新的页面才会请求更新。
|
|
36
|
+
- 新鲜缓存直接返回;缓存过期后尝试联网更新,网络失败时继续使用旧缓存,并在消息中标注“离线缓存”。
|
|
37
|
+
- 已有 `manifest.json` 和 `pages/` 中的完整抓取数据会作为离线快照保留,不会删除。
|
|
38
|
+
- 新获取的页面写入 `data/clocktower/cache/pages/`,页面目录写入 `cache/catalog.json`,搜索索引写入 `cache/search/`。
|
|
39
|
+
- 正文图片仍保留原始 URL 和已有本地文件信息,但查询消息仅发送文字,不预下载图片。
|
|
40
|
+
- 单个章节最长显示约 2400 字,超出时提供来源链接,避免长文刷屏。
|
|
41
|
+
|
|
42
|
+
每个页面 JSON 包含原始标题、实际标题、页面 ID、修订 ID、来源 URL、抓取时间、完整 HTML、纯文本、维基源码、图片及本地路径、站内链接、站外链接、目录、分类和页面属性。角色另含 `sourceIndexes`,记录其出现的角色类型或剧本索引。
|
|
43
|
+
|
|
44
|
+
## 数据库表
|
|
45
|
+
|
|
46
|
+
无。
|
|
47
|
+
|
|
48
|
+
## 更新日志
|
|
49
|
+
|
|
50
|
+
### v1.0.0
|
|
51
|
+
|
|
52
|
+
- 发布首个 npm 正式版本。
|
|
53
|
+
- 提供角色与规则按需查询、章节输出、本地缓存和离线兜底。
|
|
54
|
+
|
|
55
|
+
### v0.2.0
|
|
56
|
+
|
|
57
|
+
- 改为角色与规则按需查询,移除启动全量同步、图片预下载和全量同步指令。
|
|
58
|
+
- 新增 `clocktower/角色`、`clocktower/规则` 和管理员单页刷新指令 `clocktower/刷新`。
|
|
59
|
+
- 支持角色模糊搜索、候选列表、章节查询和长文截断。
|
|
60
|
+
- 新增 7 天页面缓存、1 天搜索索引缓存及网络失败时的旧缓存兜底。
|
|
61
|
+
- 保留已有完整抓取数据作为离线快照,新数据独立写入缓存目录。
|
|
62
|
+
|
|
63
|
+
### v0.1.0
|
|
64
|
+
|
|
65
|
+
- 创建血染钟楼插件。
|
|
66
|
+
- 支持同步 10 个规则页面和 9 个角色索引。
|
|
67
|
+
- 支持抓取索引内全部角色详情并按来源分类。
|
|
68
|
+
- 保存 HTML、纯文本、维基源码、元数据和正文图片。
|
package/README.md
DELETED