@capyclaw/scrapling 1.0.2 → 1.1.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.
@@ -0,0 +1,264 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-scrapling 爬虫工作台独立服务入口(broker 清单 / 手动调试用)。
4
+ *
5
+ * node server/server.mjs [--port 39640] [--host 127.0.0.1]
6
+ *
7
+ * 只绑 127.0.0.1;/healthz 报标准服务信息,`/` 是爬虫工作台界面,
8
+ * /demo/* 是内置离线演示页(不依赖外网即可完整体验爬取流程)。
9
+ * lib/host.mjs 在被 insert 时会以同一装配拉起本服务并返回 disposer。
10
+ */
11
+ import { readFile } from 'node:fs/promises'
12
+ import path from 'node:path'
13
+ import { createServer } from 'node:http'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { isMain, parseArgs } from '@capyclaw/plugin-kit'
16
+
17
+ import { createCrawler } from '../lib/crawler.mjs'
18
+
19
+ export const DEFAULT_PORT = 39640
20
+ export const CONTRACT_VERSION = '1'
21
+
22
+ const MIME = {
23
+ '.html': 'text/html; charset=utf-8',
24
+ '.js': 'text/javascript; charset=utf-8',
25
+ '.css': 'text/css; charset=utf-8',
26
+ '.json': 'application/json; charset=utf-8',
27
+ '.svg': 'image/svg+xml',
28
+ '.png': 'image/png',
29
+ }
30
+
31
+ /** 静态文件白名单(路径 → 磁盘相对路径),杜绝路径穿越。 */
32
+ function staticFiles(uiDir, demoDir) {
33
+ return new Map([
34
+ ['/', path.join(uiDir, 'index.html')],
35
+ ['/index.html', path.join(uiDir, 'index.html')],
36
+ ['/app.js', path.join(uiDir, 'app.js')],
37
+ ['/style.css', path.join(uiDir, 'style.css')],
38
+ ['/demo/quotes.html', path.join(demoDir, 'quotes.html')],
39
+ ['/demo/products.html', path.join(demoDir, 'products.html')],
40
+ ['/demo/news.html', path.join(demoDir, 'news.html')],
41
+ ])
42
+ }
43
+
44
+ function sendJson(res, status, payload) {
45
+ const body = JSON.stringify(payload)
46
+ res.writeHead(status, {
47
+ 'content-type': 'application/json; charset=utf-8',
48
+ 'cache-control': 'no-store',
49
+ })
50
+ res.end(body)
51
+ }
52
+
53
+ function sendError(res, status, { code, message, hint }) {
54
+ sendJson(res, status, { ok: false, error: { code, message, hint } })
55
+ }
56
+
57
+ async function readJsonBody(req, { limitBytes = 1024 * 1024 } = {}) {
58
+ const chunks = []
59
+ let size = 0
60
+ for await (const chunk of req) {
61
+ size += chunk.length
62
+ if (size > limitBytes) throw Object.assign(new Error('请求体过大'), { code: 'BODY_TOO_LARGE' })
63
+ chunks.push(chunk)
64
+ }
65
+ if (!chunks.length) return {}
66
+ const text = Buffer.concat(chunks).toString('utf8')
67
+ if (!text.trim()) return {}
68
+ try {
69
+ return JSON.parse(text)
70
+ } catch {
71
+ throw Object.assign(new Error('请求体不是合法 JSON'), { code: 'BODY_INVALID' })
72
+ }
73
+ }
74
+
75
+ /** 校验 /api/crawl 与 /api/extract 的 selectors 入参形状。 */
76
+ function normalizeSelectors(raw) {
77
+ if (raw === undefined || raw === null) return []
78
+ if (!Array.isArray(raw)) throw Object.assign(new Error('selectors 需要是数组'), { code: 'SELECTORS_INVALID' })
79
+ return raw.slice(0, 20).map((item, index) => {
80
+ if (typeof item === 'string') return { key: `s${index + 1}`, selector: item }
81
+ if (!item || typeof item.selector !== 'string') {
82
+ throw Object.assign(new Error(`selectors[${index}] 缺少 selector 字段`), { code: 'SELECTORS_INVALID' })
83
+ }
84
+ return { key: String(item.key || `s${index + 1}`).slice(0, 60), selector: item.selector.slice(0, 500) }
85
+ })
86
+ }
87
+
88
+ /**
89
+ * 拉起工作台服务。
90
+ *
91
+ * @param {object} [options]
92
+ * @param {number} [options.port=39640]
93
+ * @param {string} [options.host='127.0.0.1']
94
+ * @param {string} [options.packageDir] 插件根目录(默认取本文件上两级)
95
+ * @param {object} [options.crawler] 注入的爬取器(默认新建)
96
+ * @param {string} [options.version] healthz 里的版本号
97
+ */
98
+ export async function startWorkbenchServer(options = {}) {
99
+ const packageDir = options.packageDir
100
+ || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
101
+ const port = Number(options.port) || DEFAULT_PORT
102
+ const host = options.host || '127.0.0.1'
103
+ const crawler = options.crawler || createCrawler()
104
+ const version = options.version || '1.1.0'
105
+ const uiDir = path.join(packageDir, 'ui')
106
+ const demoDir = path.join(packageDir, 'demo')
107
+ const files = staticFiles(uiDir, demoDir)
108
+ const startedAt = Date.now()
109
+
110
+ const server = createServer(async (req, res) => {
111
+ const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${port}`}`)
112
+ try {
113
+ /* ---- 健康检查 / 指标(服务契约) ---- */
114
+ if (url.pathname === '/healthz' && req.method === 'GET') {
115
+ return sendJson(res, 200, {
116
+ ok: true,
117
+ name: 'scrapling-workbench',
118
+ version,
119
+ contractVersion: CONTRACT_VERSION,
120
+ uptimeSec: Math.round((Date.now() - startedAt) / 1000),
121
+ port,
122
+ pid: process.pid,
123
+ crawls: crawler.counters.total,
124
+ capabilities: { http: true, browser: false, selectors: true },
125
+ })
126
+ }
127
+ if (url.pathname === '/metrics' && req.method === 'GET') {
128
+ const body = [
129
+ '# HELP scrapling_up 服务存活状态',
130
+ '# TYPE scrapling_up gauge',
131
+ 'scrapling_up 1',
132
+ '# HELP scrapling_uptime_seconds 服务运行秒数',
133
+ '# TYPE scrapling_uptime_seconds counter',
134
+ `scrapling_uptime_seconds ${Math.round((Date.now() - startedAt) / 1000)}`,
135
+ '# HELP scrapling_crawls_total 累计爬取次数',
136
+ '# TYPE scrapling_crawls_total counter',
137
+ `scrapling_crawls_total ${crawler.counters.total}`,
138
+ '# HELP scrapling_crawl_errors_total 累计失败次数',
139
+ '# TYPE scrapling_crawl_errors_total counter',
140
+ `scrapling_crawl_errors_total ${crawler.counters.errors}`,
141
+ '',
142
+ ].join('\n')
143
+ res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4; charset=utf-8', 'cache-control': 'no-store' })
144
+ return res.end(body)
145
+ }
146
+
147
+ /* ---- API ---- */
148
+ if (url.pathname === '/api/crawl' && req.method === 'POST') {
149
+ const body = await readJsonBody(req)
150
+ if (!body.url || typeof body.url !== 'string') {
151
+ return sendError(res, 400, { code: 'URL_REQUIRED', message: '缺少 url 字段', hint: '请在请求体里提供要抓取的网址,如 { "url": "http://127.0.0.1:39640/demo/quotes.html" }' })
152
+ }
153
+ if (body.mode && body.mode !== 'http') {
154
+ return sendError(res, 400, {
155
+ code: 'NOT_IMPLEMENTED',
156
+ message: `浏览器渲染模式(${body.mode})未实现:依赖外部 Python scrapling 运行时`,
157
+ hint: '请使用 HTTP 模式(mode 缺省即为 HTTP)。',
158
+ })
159
+ }
160
+ const selectors = normalizeSelectors(body.selectors)
161
+ const record = await crawler.crawl({
162
+ url: body.url,
163
+ mode: 'http',
164
+ timeoutMs: Number(body.timeoutMs) || undefined,
165
+ userAgent: body.userAgent,
166
+ selectors,
167
+ })
168
+ /* 历史里保留 root 供二次提取;对外响应剔除 root/html 大字段 */
169
+ const { root, html, ...payload } = record
170
+ return sendJson(res, 200, { ok: !record.error, crawl: { ...payload, htmlPreview: typeof html === 'string' ? html.slice(0, 40000) : undefined } })
171
+ }
172
+
173
+ if (url.pathname === '/api/extract' && req.method === 'POST') {
174
+ const body = await readJsonBody(req)
175
+ if (!body.crawlId || typeof body.crawlId !== 'string') {
176
+ return sendError(res, 400, { code: 'CRAWL_ID_REQUIRED', message: '缺少 crawlId', hint: '先执行一次 /api/crawl,再用返回的 crawl.id 做二次提取。' })
177
+ }
178
+ const selectors = normalizeSelectors(body.selectors)
179
+ if (!selectors.length) {
180
+ return sendError(res, 400, { code: 'SELECTORS_REQUIRED', message: '缺少 selectors', hint: '提供 [{ "key": "标题", "selector": "h1::text" }] 形式的选择器列表。' })
181
+ }
182
+ const result = crawler.reExtract(body.crawlId, selectors)
183
+ if (!result) {
184
+ return sendError(res, 404, { code: 'CRAWL_NOT_FOUND', message: `找不到爬取记录 ${body.crawlId}`, hint: '记录可能已过期(仅保留最近 20 条),请重新爬取一次。' })
185
+ }
186
+ return sendJson(res, 200, { ok: true, ...result })
187
+ }
188
+
189
+ if (url.pathname === '/api/crawls' && req.method === 'GET') {
190
+ return sendJson(res, 200, { ok: true, crawls: crawler.list() })
191
+ }
192
+
193
+ const crawlMatch = /^\/api\/crawls\/([\w-]+)$/.exec(url.pathname)
194
+ if (crawlMatch) {
195
+ if (req.method !== 'GET') return sendError(res, 405, { code: 'METHOD', message: '只支持 GET', hint: '' })
196
+ const record = crawler.get(crawlMatch[1])
197
+ if (!record) return sendError(res, 404, { code: 'CRAWL_NOT_FOUND', message: `找不到爬取记录 ${crawlMatch[1]}`, hint: '记录可能已过期,请重新爬取。' })
198
+ return sendJson(res, 200, { ok: true, crawl: record })
199
+ }
200
+
201
+ if (url.pathname.startsWith('/api/')) {
202
+ return sendError(res, 404, { code: 'NOT_FOUND', message: `未知接口 ${url.pathname}`, hint: '可用接口:POST /api/crawl、POST /api/extract、GET /api/crawls、GET /api/crawls/:id' })
203
+ }
204
+
205
+ /* ---- 静态资源(白名单) ---- */
206
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
207
+ return sendError(res, 405, { code: 'METHOD', message: `不支持 ${req.method}`, hint: '' })
208
+ }
209
+ const file = files.get(url.pathname)
210
+ if (!file) {
211
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
212
+ return res.end('Not found')
213
+ }
214
+ const content = await readFile(file)
215
+ res.writeHead(200, {
216
+ 'content-type': MIME[path.extname(file)] || 'application/octet-stream',
217
+ 'cache-control': 'no-store',
218
+ 'x-content-type-options': 'nosniff',
219
+ })
220
+ return res.end(req.method === 'HEAD' ? undefined : content)
221
+ } catch (error) {
222
+ if (error.code === 'BODY_TOO_LARGE' || error.code === 'BODY_INVALID' || error.code === 'SELECTORS_INVALID') {
223
+ return sendError(res, 400, { code: error.code, message: error.message, hint: '请检查请求体格式。' })
224
+ }
225
+ return sendError(res, 500, { code: 'INTERNAL', message: error.message || '服务内部错误', hint: '请重试;若持续失败请查看服务日志。' })
226
+ }
227
+ })
228
+
229
+ await new Promise((resolve, reject) => {
230
+ server.once('error', reject)
231
+ server.listen(port, host, () => resolve())
232
+ })
233
+
234
+ return {
235
+ port,
236
+ host,
237
+ url: `http://${host === '127.0.0.1' ? '127.0.0.1' : host}:${port}`,
238
+ crawler,
239
+ close: () => new Promise((resolve) => server.close(() => resolve())),
240
+ }
241
+ }
242
+
243
+ async function main() {
244
+ const { flags } = parseArgs(process.argv.slice(2))
245
+ if (flags.help) {
246
+ console.log('dsh-scrapling 工作台服务\n\n用法: node server/server.mjs [--port 39640] [--host 127.0.0.1]')
247
+ return
248
+ }
249
+ const port = flags.port === undefined ? DEFAULT_PORT : Number(flags.port)
250
+ const instance = await startWorkbenchServer({ port, host: flags.host })
251
+ console.log(`[dsh-scrapling] 工作台已就绪: ${instance.url}/ (浏览器打开即用)`)
252
+ const shutdown = () => {
253
+ instance.close().then(() => process.exit(0))
254
+ }
255
+ process.on('SIGINT', shutdown)
256
+ process.on('SIGTERM', shutdown)
257
+ }
258
+
259
+ if (isMain(import.meta.url)) {
260
+ main().catch((error) => {
261
+ console.error(`✗ ${error.message}`)
262
+ process.exit(1)
263
+ })
264
+ }