跳到主要内容

腾讯文档

收藏0

腾讯文档(docs.qq.com)在线云文档操作:创建与编辑文档/表格/幻灯片/思维导图/流程图/智能表格/收集表,管理知识库空间与文件夹,读取搜索内容,文件导入导出与网页剪藏。灵栈搬运自 SkillHub tencent-docs v1.0.42。

让 AI 安装

Minsaroun最新版本 0.1.0更新于 2026-11-14下载 0 次

aipage_pack.js

19.0 KB
1#!/usr/bin/env node
2/* eslint-disable no-console */
3/**
4 * aipage_pack.js — 把一个本地 HTML 目录(或单文件)打包成符合 aicanvas
5 * McpImport 规范的 .aipage 压缩包,供 tencent-docs MCP 的导入流程使用。
6 *
7 * 设计原则:
8 * - tencent-docs skill 自持「打包 + 导入」全链路,
9 * 上游 skill(如 smart-page)只负责输出 HTML,不再关心 manifest/zip。
10 * - 跨平台:纯 Node.js(>= 14),零 npm 依赖。
11 * 手写 ZIP(store 模式,method=0),同时兼容 macOS / Linux / Windows
12 * 原生 cmd / PowerShell(无需 bash / Git Bash / WSL)。
13 *
14 * Usage:
15 * node aipage_pack.js --html <html_path> [--title <title>] [--output <out_path>]
16 * node aipage_pack.js --dir <html_dir> [--title <title>] [--output <out_path>]
17 *
18 * Behaviors:
19 * 1. 创建临时打包目录
20 * 2. 将入口 HTML 复制为 index.html(aipage 硬要求)
21 * 3. 复制同级 assets/ 目录(如存在),目录模式下复制整个目录的全部文件
22 * 4. 生成 manifest.json(标题安全转义;未传 --title 时自动从 <title> 提取,
23 * 再 fallback 用文件名/目录名)
24 * 5. 生成 janus.manifest.json(固定内容)
25 * 6. 扁平化 zip 打包(zip 内无顶层目录),后缀强制为 .aipage
26 * 7. 输出结构化结果(供 SKILL 内 agent 直接解析):
27 * AIPAGE_PATH=...
28 * AIPAGE_SIZE=...
29 * AIPAGE_MD5=...
30 * AIPAGE_TITLE=...
31 *
32 * Exit codes:
33 * 0 成功
34 * 1 参数错误
35 * 2 源 HTML / 目录不存在或不合法
36 * 3 打包失败 / 内部错误
37 */
38
39'use strict';
40
41const fs = require('fs');
42const path = require('path');
43const os = require('os');
44const crypto = require('crypto');
45const zlib = require('zlib');
46
47// ─────────────────────────────────────────────────────────────────────────────
48// 1. 参数解析
49// ─────────────────────────────────────────────────────────────────────────────
50
51function usage(exitCode) {
52 const msg = [
53 'Usage:',
54 ' node aipage_pack.js --html <html_path> [--title <title>] [--output <out_path>]',
55 ' node aipage_pack.js --dir <html_dir> [--title <title>] [--output <out_path>]',
56 '',
57 ' --html 单个 HTML 文件路径(推荐:smart-page 等上游产物)',
58 ' --dir 已组织好的 HTML 目录路径,目录中必须有且仅有一个 .html / .htm 入口',
59 ' --title 可选,文档标题;缺省时自动读 <title> 标签,再 fallback 用文件名/目录名',
60 ' --output 可选,输出 .aipage 路径;缺省为 <tmpdir>/<stem>.aipage',
61 '',
62 '示例:',
63 ' node aipage_pack.js --html "output/立项方案.html"',
64 ' node aipage_pack.js --html "output/邀请函.html" --title "邀请函" --output /tmp/x.aipage',
65 ' node aipage_pack.js --dir "output/site" --title "站点演示"',
66 '',
67 ].join('\n');
68 process.stderr.write(msg);
69 process.exit(typeof exitCode === 'number' ? exitCode : 1);
70}
71
72function parseArgs(argv) {
73 const opts = { html: '', dir: '', title: '', output: '' };
74 for (let i = 0; i < argv.length; i++) {
75 const a = argv[i];
76 switch (a) {
77 case '--html':
78 opts.html = argv[++i] || '';
79 break;
80 case '--dir':
81 opts.dir = argv[++i] || '';
82 break;
83 case '--title':
84 opts.title = argv[++i] || '';
85 break;
86 case '--output':
87 opts.output = argv[++i] || '';
88 break;
89 case '-h':
90 case '--help':
91 usage(0);
92 break;
93 default:
94 process.stderr.write(`aipage_pack.js: unknown argument: ${a}\n`);
95 usage(1);
96 }
97 }
98 return opts;
99}
100
101// ─────────────────────────────────────────────────────────────────────────────
102// 2. 工具函数
103// ─────────────────────────────────────────────────────────────────────────────
104
105function fail(code, msg) {
106 process.stderr.write(`aipage_pack.js: ${msg}\n`);
107 process.exit(code);
108}
109
110function md5OfFile(filePath) {
111 const h = crypto.createHash('md5');
112 h.update(fs.readFileSync(filePath));
113 return h.digest('hex');
114}
115
116function sizeOfFile(filePath) {
117 return fs.statSync(filePath).size;
118}
119
120function extractHtmlTitle(htmlPath) {
121 let html = '';
122 try {
123 html = fs.readFileSync(htmlPath, 'utf8');
124 } catch (_) {
125 return '';
126 }
127 const m = html.match(/<title>([\s\S]*?)<\/title>/i);
128 return m ? m[1].trim() : '';
129}
130
131function rmrf(p) {
132 if (!fs.existsSync(p)) return;
133 // Node 14.14+ 支持 rmSync({recursive:true}); 兼容更早版本回退到 rmdirSync
134 try {
135 fs.rmSync(p, { recursive: true, force: true });
136 } catch (_) {
137 fs.rmdirSync(p, { recursive: true });
138 }
139}
140
141function mkTempDir(prefix) {
142 return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
143}
144
145function copyFile(src, dst) {
146 fs.mkdirSync(path.dirname(dst), { recursive: true });
147 fs.copyFileSync(src, dst);
148}
149
150// 递归复制目录内容到 dstDir(不包含 dstDir 自身的创建)
151function copyDirContents(srcDir, dstDir) {
152 fs.mkdirSync(dstDir, { recursive: true });
153 const entries = fs.readdirSync(srcDir, { withFileTypes: true });
154 for (const ent of entries) {
155 const sp = path.join(srcDir, ent.name);
156 const dp = path.join(dstDir, ent.name);
157 if (ent.isDirectory()) {
158 copyDirContents(sp, dp);
159 } else if (ent.isFile()) {
160 fs.copyFileSync(sp, dp);
161 }
162 // 软链/特殊文件直接忽略,避免打入压缩包污染
163 }
164}
165
166// 递归收集打包目录下所有相对路径(POSIX 风格,给 zip 用)
167function listFilesRel(rootDir) {
168 const result = [];
169 function walk(absDir, relDir) {
170 const entries = fs.readdirSync(absDir, { withFileTypes: true });
171 for (const ent of entries) {
172 const abs = path.join(absDir, ent.name);
173 const rel = relDir ? `${relDir}/${ent.name}` : ent.name;
174 if (shouldExcludeName(ent.name)) continue;
175 if (ent.isDirectory()) {
176 walk(abs, rel);
177 } else if (ent.isFile()) {
178 result.push({ abs, rel });
179 }
180 }
181 }
182 walk(rootDir, '');
183 return result;
184}
185
186// 排除 macOS / Windows 副产物(与原 .sh 保持一致)
187function shouldExcludeName(name) {
188 if (name === '__MACOSX') return true;
189 if (name === '.DS_Store') return true;
190 if (name === 'Thumbs.db') return true;
191 if (name.startsWith('._')) return true;
192 return false;
193}
194
195// ─────────────────────────────────────────────────────────────────────────────
196// 3. 手写 ZIP(store 模式 + DEFLATE 模式自动选择,扁平、无目录条目、无外部依赖)
197// 采用 ZIP 标准(PKZIP appnote 6.3.x),仅使用 method=0/8、CRC32、本地头/中央目录头/EOCD。
198// 不支持 Zip64(aipage 单文件不会大到需要 Zip64)。
199// ─────────────────────────────────────────────────────────────────────────────
200
201// CRC32(标准多项式 0xEDB88320),构建查表,处理 Buffer
202const CRC_TABLE = (() => {
203 const t = new Uint32Array(256);
204 for (let n = 0; n < 256; n++) {
205 let c = n;
206 for (let k = 0; k < 8; k++) {
207 c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
208 }
209 t[n] = c >>> 0;
210 }
211 return t;
212})();
213
214function crc32(buf) {
215 let c = 0xffffffff;
216 for (let i = 0; i < buf.length; i++) {
217 c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
218 }
219 return (c ^ 0xffffffff) >>> 0;
220}
221
222// 把 JS Date 转为 DOS 时间/日期
223function toDosDateTime(date) {
224 const year = Math.max(1980, date.getFullYear());
225 const dosTime =
226 ((date.getHours() & 0x1f) << 11) |
227 ((date.getMinutes() & 0x3f) << 5) |
228 ((Math.floor(date.getSeconds() / 2)) & 0x1f);
229 const dosDate =
230 (((year - 1980) & 0x7f) << 9) |
231 (((date.getMonth() + 1) & 0x0f) << 5) |
232 (date.getDate() & 0x1f);
233 return { dosTime, dosDate };
234}
235
236/**
237 * 创建符合 aipage 要求的扁平 zip。
238 * @param {string} outPath 输出 .aipage 文件路径
239 * @param {{abs:string, rel:string}[]} files 待打包文件列表,rel 必须是 POSIX 风格相对路径
240 */
241function buildZip(outPath, files) {
242 const localChunks = [];
243 const centralChunks = [];
244 let offset = 0;
245 const now = new Date();
246 const { dosTime, dosDate } = toDosDateTime(now);
247
248 for (const f of files) {
249 const data = fs.readFileSync(f.abs);
250 const nameBuf = Buffer.from(f.rel, 'utf8');
251 const crc = crc32(data);
252 const uncompressedSize = data.length;
253
254 // 选择压缩算法:默认 DEFLATE(method=8),但若压缩反而变大则回退到 STORE(method=0)
255 let method = 8;
256 let compressed = zlib.deflateRawSync(data, { level: 9 });
257 if (compressed.length >= uncompressedSize) {
258 method = 0;
259 compressed = data;
260 }
261 const compressedSize = compressed.length;
262
263 // ── Local file header (30 bytes + name + extra(0))
264 const lfh = Buffer.alloc(30);
265 lfh.writeUInt32LE(0x04034b50, 0); // signature
266 lfh.writeUInt16LE(20, 4); // version needed
267 // bit 11: UTF-8 file name; 其它位为 0(无加密、无 data descriptor)
268 lfh.writeUInt16LE(0x0800, 6); // general purpose bit flag
269 lfh.writeUInt16LE(method, 8); // compression method
270 lfh.writeUInt16LE(dosTime, 10);
271 lfh.writeUInt16LE(dosDate, 12);
272 lfh.writeUInt32LE(crc, 14);
273 lfh.writeUInt32LE(compressedSize, 18);
274 lfh.writeUInt32LE(uncompressedSize, 22);
275 lfh.writeUInt16LE(nameBuf.length, 26);
276 lfh.writeUInt16LE(0, 28); // extra length
277
278 localChunks.push(lfh, nameBuf, compressed);
279
280 // ── Central directory header (46 bytes + name + extra(0) + comment(0))
281 const cdh = Buffer.alloc(46);
282 cdh.writeUInt32LE(0x02014b50, 0); // signature
283 cdh.writeUInt16LE(20, 4); // version made by
284 cdh.writeUInt16LE(20, 6); // version needed
285 cdh.writeUInt16LE(0x0800, 8); // general purpose bit flag
286 cdh.writeUInt16LE(method, 10); // compression method
287 cdh.writeUInt16LE(dosTime, 12);
288 cdh.writeUInt16LE(dosDate, 14);
289 cdh.writeUInt32LE(crc, 16);
290 cdh.writeUInt32LE(compressedSize, 20);
291 cdh.writeUInt32LE(uncompressedSize, 24);
292 cdh.writeUInt16LE(nameBuf.length, 28);
293 cdh.writeUInt16LE(0, 30); // extra length
294 cdh.writeUInt16LE(0, 32); // comment length
295 cdh.writeUInt16LE(0, 34); // disk number start
296 cdh.writeUInt16LE(0, 36); // internal file attrs
297 cdh.writeUInt32LE(0, 38); // external file attrs
298 cdh.writeUInt32LE(offset, 42); // relative offset of local header
299
300 centralChunks.push(cdh, nameBuf);
301
302 offset += lfh.length + nameBuf.length + compressed.length;
303 }
304
305 const centralStart = offset;
306 const centralBuf = Buffer.concat(centralChunks);
307 const centralSize = centralBuf.length;
308
309 // ── End of central directory record
310 const eocd = Buffer.alloc(22);
311 eocd.writeUInt32LE(0x06054b50, 0); // signature
312 eocd.writeUInt16LE(0, 4); // disk number
313 eocd.writeUInt16LE(0, 6); // disk with central dir
314 eocd.writeUInt16LE(files.length, 8); // entries on this disk
315 eocd.writeUInt16LE(files.length, 10); // total entries
316 eocd.writeUInt32LE(centralSize, 12); // central dir size
317 eocd.writeUInt32LE(centralStart, 16); // central dir offset
318 eocd.writeUInt16LE(0, 20); // comment length
319
320 const out = Buffer.concat([Buffer.concat(localChunks), centralBuf, eocd]);
321 fs.mkdirSync(path.dirname(outPath), { recursive: true });
322 fs.writeFileSync(outPath, out);
323}
324
325// ─────────────────────────────────────────────────────────────────────────────
326// 4. 主流程
327// ─────────────────────────────────────────────────────────────────────────────
328
329function main() {
330 const opts = parseArgs(process.argv.slice(2));
331
332 if (opts.html && opts.dir) {
333 process.stderr.write('aipage_pack.js: --html 与 --dir 二选一,不可同时使用\n');
334 usage(1);
335 }
336 if (!opts.html && !opts.dir) {
337 process.stderr.write('aipage_pack.js: 必须指定 --html 或 --dir\n');
338 usage(1);
339 }
340
341 // ── 创建临时打包目录 ────────────────────────────────────────────────
342 const packDir = mkTempDir('aipage_pack_');
343 let cleaned = false;
344 const cleanup = () => {
345 if (cleaned) return;
346 cleaned = true;
347 rmrf(packDir);
348 };
349 process.on('exit', cleanup);
350 process.on('SIGINT', () => { cleanup(); process.exit(130); });
351 process.on('SIGTERM', () => { cleanup(); process.exit(143); });
352
353 let stem = '';
354 let entryHtmlInPack = '';
355
356 try {
357 if (opts.html) {
358 if (!fs.existsSync(opts.html) || !fs.statSync(opts.html).isFile()) {
359 fail(2, `HTML 不存在: ${opts.html}`);
360 }
361 const htmlAbs = path.resolve(opts.html);
362 const htmlAbsDir = path.dirname(htmlAbs);
363 const base = path.basename(htmlAbs);
364 const ext = path.extname(base).toLowerCase();
365 stem = (ext === '.html' || ext === '.htm') ? base.slice(0, -ext.length) : base;
366
367 copyFile(htmlAbs, path.join(packDir, 'index.html'));
368 const assetsDir = path.join(htmlAbsDir, 'assets');
369 if (fs.existsSync(assetsDir) && fs.statSync(assetsDir).isDirectory()) {
370 copyDirContents(assetsDir, path.join(packDir, 'assets'));
371 }
372 entryHtmlInPack = path.join(packDir, 'index.html');
373 } else {
374 if (!fs.existsSync(opts.dir) || !fs.statSync(opts.dir).isDirectory()) {
375 fail(2, `目录不存在: ${opts.dir}`);
376 }
377 const htmlDirAbs = path.resolve(opts.dir);
378
379 // 找入口 HTML:优先 index.html / index.htm,其次唯一 *.html / *.htm
380 let entry = '';
381 if (fs.existsSync(path.join(htmlDirAbs, 'index.html'))) {
382 entry = path.join(htmlDirAbs, 'index.html');
383 } else if (fs.existsSync(path.join(htmlDirAbs, 'index.htm'))) {
384 entry = path.join(htmlDirAbs, 'index.htm');
385 } else {
386 const candidates = fs.readdirSync(htmlDirAbs)
387 .filter((n) => /\.html?$/i.test(n))
388 .map((n) => path.join(htmlDirAbs, n))
389 .filter((p) => fs.statSync(p).isFile());
390 if (candidates.length === 1) {
391 entry = candidates[0];
392 } else if (candidates.length === 0) {
393 fail(2, `目录下找不到 HTML 入口: ${htmlDirAbs}`);
394 } else {
395 fail(2, `目录下存在多个 HTML,请显式 --html 指定: ${candidates.join(' ')}`);
396 }
397 }
398 stem = path.basename(htmlDirAbs);
399 copyDirContents(htmlDirAbs, packDir);
400 const entryName = path.basename(entry);
401 if (entryName !== 'index.html') {
402 const src = path.join(packDir, entryName);
403 const dst = path.join(packDir, 'index.html');
404 // 入口归一化为 index.html;如果同名 index.html 与入口同名(理论不会到这里)则跳过
405 if (src !== dst) {
406 fs.renameSync(src, dst);
407 }
408 }
409 entryHtmlInPack = path.join(packDir, 'index.html');
410 }
411
412 // ── 推导 TITLE ──────────────────────────────────────────────────
413 let title = opts.title;
414 if (!title) {
415 title = extractHtmlTitle(entryHtmlInPack) || stem;
416 }
417
418 // ── 默认 OUT ───────────────────────────────────────────────────
419 let zipOut = opts.output;
420 if (!zipOut) {
421 zipOut = path.join(os.tmpdir(), `${stem}.aipage`);
422 }
423 // 后缀强制 .aipage
424 const lower = zipOut.toLowerCase();
425 if (lower.endsWith('.aipage')) {
426 // 保持原样
427 } else if (lower.endsWith('.page')) {
428 zipOut = zipOut.slice(0, -'.page'.length) + '.aipage';
429 } else if (lower.endsWith('.zip')) {
430 zipOut = zipOut.slice(0, -'.zip'.length) + '.aipage';
431 } else {
432 zipOut = zipOut + '.aipage';
433 }
434 fs.mkdirSync(path.dirname(zipOut), { recursive: true });
435 if (fs.existsSync(zipOut)) {
436 fs.unlinkSync(zipOut);
437 }
438
439 // ── 生成 manifest.json ────────────────────────────────────────
440 const manifest = { entry: 'index.html', title, version: '1.0' };
441 fs.writeFileSync(
442 path.join(packDir, 'manifest.json'),
443 JSON.stringify(manifest, null, 2),
444 'utf8',
445 );
446
447 // ── 生成 janus.manifest.json(固定内容)─────────────────────
448 fs.writeFileSync(
449 path.join(packDir, 'janus.manifest.json'),
450 '{"version":"1.0.0","render_engine":"native","scene":""}',
451 'utf8',
452 );
453
454 // ── 校验 ─────────────────────────────────────────────────────
455 if (!fs.existsSync(path.join(packDir, 'index.html'))) {
456 fail(3, 'missing index.html');
457 }
458 if (!fs.existsSync(path.join(packDir, 'manifest.json'))) {
459 fail(3, 'missing manifest.json');
460 }
461 try {
462 JSON.parse(fs.readFileSync(path.join(packDir, 'manifest.json'), 'utf8'));
463 } catch (_) {
464 fail(3, 'manifest.json 不是合法 JSON');
465 }
466
467 // ── 打包(扁平化)────────────────────────────────────────────
468 const files = listFilesRel(packDir);
469 if (files.length === 0) {
470 fail(3, '打包目录为空');
471 }
472 buildZip(zipOut, files);
473
474 if (!fs.existsSync(zipOut)) {
475 fail(3, `zip 没产出: ${zipOut}`);
476 }
477
478 const size = sizeOfFile(zipOut);
479 const md5 = md5OfFile(zipOut);
480
481 // ── 结构化输出(与 .sh 完全一致)────────────────────────────
482 process.stdout.write(`AIPAGE_PATH=${zipOut}\n`);
483 process.stdout.write(`AIPAGE_SIZE=${size}\n`);
484 process.stdout.write(`AIPAGE_MD5=${md5}\n`);
485 process.stdout.write(`AIPAGE_TITLE=${title}\n`);
486 } finally {
487 cleanup();
488 }
489}
490
491main();

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。