@wkgeo/cli 1.1.0 → 1.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.
@@ -0,0 +1,206 @@
1
+ /**
2
+ * `wkgeo template pack` —— 把模板打成可直接分发的 zip。
3
+ *
4
+ * ## 为什么自己写 ZIP
5
+ * 派单的红线是「不 npm install」,`archiver` / `jszip` 都不能用;Node 内置没有 zip 写入器。
6
+ * 所以这里用 `zlib.deflateRawSync` + 自算 CRC32 写一个**最小但合规**的 zip(deflate 压缩、
7
+ * UTF-8 文件名标志位 0x0800、中央目录齐全),解压工具(PowerShell Expand-Archive / 7-Zip)都认。
8
+ *
9
+ * ## 打包前
10
+ * 1. 把 `templates/_base/assets/**` **逐字节**同步进 `<模板>/assets/base/`(§3 基础库同步规则);
11
+ * 2. 跑 9 关校验(`template-validate.mjs`),**不合格不出包**(exit 1)。
12
+ *
13
+ * 包内结构:`template.json`、`pages/`、`partials/`、`assets/`(含 `assets/base/`)、`design/`。
14
+ */
15
+
16
+ import fs from 'node:fs';
17
+ import fsp from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import zlib from 'node:zlib';
20
+
21
+ import { CliError, EXIT } from './errors.mjs';
22
+ import { assertValid, validateTemplate } from './template-validate.mjs';
23
+ import { resolveBaseDir, syncBaseAssets } from './template-gen.mjs';
24
+
25
+ // ---------------------------------------------------------------- CRC32 / ZIP
26
+
27
+ const CRC_TABLE = (() => {
28
+ const t = new Int32Array(256);
29
+ for (let n = 0; n < 256; n++) {
30
+ let c = n;
31
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
32
+ t[n] = c;
33
+ }
34
+ return t;
35
+ })();
36
+
37
+ export function crc32(buf) {
38
+ let c = 0 ^ -1;
39
+ for (let i = 0; i < buf.length; i++) c = (c >>> 8) ^ CRC_TABLE[(c ^ buf[i]) & 0xff];
40
+ return (c ^ -1) >>> 0;
41
+ }
42
+
43
+ function dosDateTime(date = new Date()) {
44
+ const time = ((date.getHours() & 0x1f) << 11) | ((date.getMinutes() & 0x3f) << 5) | ((Math.floor(date.getSeconds() / 2)) & 0x1f);
45
+ const day = (((date.getFullYear() - 1980) & 0x7f) << 9) | (((date.getMonth() + 1) & 0xf) << 5) | (date.getDate() & 0x1f);
46
+ return { time, day };
47
+ }
48
+
49
+ /**
50
+ * 组 zip(entries: [{name, data:Buffer, date?}],name 用 / 分隔、不带前导斜杠)。
51
+ * @returns {Buffer}
52
+ */
53
+ export function buildZip(entries) {
54
+ const locals = [];
55
+ const centrals = [];
56
+ let offset = 0;
57
+ for (const e of entries) {
58
+ const name = Buffer.from(String(e.name).replace(/\\/g, '/'), 'utf8');
59
+ const raw = e.data;
60
+ const comp = zlib.deflateRawSync(raw, { level: 9 });
61
+ const crc = crc32(raw);
62
+ const { time, day } = dosDateTime(e.date || new Date());
63
+ const flags = 0x0800; // UTF-8
64
+
65
+ const local = Buffer.alloc(30);
66
+ local.writeUInt32LE(0x04034b50, 0);
67
+ local.writeUInt16LE(20, 4); // version needed
68
+ local.writeUInt16LE(flags, 6);
69
+ local.writeUInt16LE(8, 8); // deflate
70
+ local.writeUInt16LE(time, 10);
71
+ local.writeUInt16LE(day, 12);
72
+ local.writeUInt32LE(crc, 14);
73
+ local.writeUInt32LE(comp.length, 18);
74
+ local.writeUInt32LE(raw.length, 22);
75
+ local.writeUInt16LE(name.length, 26);
76
+ local.writeUInt16LE(0, 28);
77
+ locals.push(local, name, comp);
78
+
79
+ const central = Buffer.alloc(46);
80
+ central.writeUInt32LE(0x02014b50, 0);
81
+ central.writeUInt16LE(20, 4); // version made by
82
+ central.writeUInt16LE(20, 6); // version needed
83
+ central.writeUInt16LE(flags, 8);
84
+ central.writeUInt16LE(8, 10);
85
+ central.writeUInt16LE(time, 12);
86
+ central.writeUInt16LE(day, 14);
87
+ central.writeUInt32LE(crc, 16);
88
+ central.writeUInt32LE(comp.length, 20);
89
+ central.writeUInt32LE(raw.length, 24);
90
+ central.writeUInt16LE(name.length, 28);
91
+ central.writeUInt16LE(0, 30); // extra
92
+ central.writeUInt16LE(0, 32); // comment
93
+ central.writeUInt16LE(0, 34); // disk
94
+ central.writeUInt16LE(0, 36); // internal attr
95
+ central.writeUInt32LE(0, 38); // external attr
96
+ central.writeUInt32LE(offset, 42);
97
+ centrals.push(central, name);
98
+
99
+ offset += local.length + name.length + comp.length;
100
+ }
101
+ const centralBuf = Buffer.concat(centrals);
102
+ const eocd = Buffer.alloc(22);
103
+ eocd.writeUInt32LE(0x06054b50, 0);
104
+ eocd.writeUInt16LE(0, 4);
105
+ eocd.writeUInt16LE(0, 6);
106
+ eocd.writeUInt16LE(entries.length, 8);
107
+ eocd.writeUInt16LE(entries.length, 10);
108
+ eocd.writeUInt32LE(centralBuf.length, 12);
109
+ eocd.writeUInt32LE(offset, 16);
110
+ eocd.writeUInt16LE(0, 20);
111
+ return Buffer.concat([...locals, centralBuf, eocd]);
112
+ }
113
+
114
+ /** 校验 zip 自身结构(EOCD 文件数 / 中央目录条目),用于"打完自检" */
115
+ export function inspectZip(buf) {
116
+ const eocdAt = buf.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
117
+ if (eocdAt < 0) return { ok: false, reason: '找不到 EOCD(不是合法 zip)' };
118
+ const count = buf.readUInt16LE(eocdAt + 10);
119
+ const cdSize = buf.readUInt32LE(eocdAt + 12);
120
+ const cdOff = buf.readUInt32LE(eocdAt + 16);
121
+ if (cdOff + cdSize > buf.length) return { ok: false, reason: '中央目录越界' };
122
+ const names = [];
123
+ let p = cdOff;
124
+ for (let i = 0; i < count; i++) {
125
+ if (buf.readUInt32LE(p) !== 0x02014b50) return { ok: false, reason: `第 ${i} 条中央目录签名不对` };
126
+ const nlen = buf.readUInt16LE(p + 28);
127
+ const elen = buf.readUInt16LE(p + 30);
128
+ const clen = buf.readUInt16LE(p + 32);
129
+ names.push(buf.toString('utf8', p + 46, p + 46 + nlen));
130
+ p += 46 + nlen + elen + clen;
131
+ }
132
+ return { ok: true, count, names, bytes: buf.length };
133
+ }
134
+
135
+ async function walk(root, out = [], skip = new Set(['node_modules', '.git'])) {
136
+ const entries = await fsp.readdir(root, { withFileTypes: true });
137
+ for (const e of entries) {
138
+ if (skip.has(e.name)) continue;
139
+ const full = path.join(root, e.name);
140
+ if (e.isDirectory()) await walk(full, out, skip);
141
+ else if (e.isFile()) out.push(full);
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * 打包。
148
+ * @returns {Promise<{zip:string,bytes:number,files:string[],validate:object,baseSync:object}>}
149
+ */
150
+ export async function packTemplate({ dir, out = null, base = null, cwd = process.cwd(), onProgress = null } = {}) {
151
+ const say = (s) => onProgress && onProgress(s);
152
+ const root = path.resolve(cwd, dir || '.');
153
+ if (!fs.existsSync(path.join(root, 'template.json'))) {
154
+ throw new CliError(`不是模板目录(没有 template.json):${root}`, { kind: 'pack', code: 'ENOTEMPLATE', exitCode: EXIT.ERROR });
155
+ }
156
+ const template = JSON.parse(fs.readFileSync(path.join(root, 'template.json'), 'utf8'));
157
+ const key = template.key || path.basename(root);
158
+ const version = template.version || '0.0.1';
159
+ const zipPath = path.resolve(cwd, out || `${key}-${version}.zip`);
160
+
161
+ // 1) 基础库逐字节同步
162
+ const baseDir = resolveBaseDir(base, { cwd });
163
+ const baseSync = await syncBaseAssets(root, baseDir);
164
+ if (!baseSync.copied) say(`! 没找到 templates/_base:${baseSync.reason}`);
165
+
166
+ // 2) 9 关校验(不合格不出包)
167
+ say('跑 9 关校验…');
168
+ const validate = await validateTemplate({ dir: root, base: baseDir, cwd });
169
+ assertValid(validate, { action: 'pack' });
170
+ say(`校验通过(9/9),开始打包 → ${zipPath}`);
171
+
172
+ // 3) 收集文件(排除目标 zip 自身)
173
+ const all = await walk(root);
174
+ const rels = all
175
+ .map((f) => path.relative(root, f).replace(/\\/g, '/'))
176
+ .filter((r) => path.resolve(root, r) !== path.resolve(zipPath))
177
+ .sort();
178
+ const entries = [];
179
+ for (const rel of rels) {
180
+ entries.push({ name: rel, data: await fsp.readFile(path.join(root, rel)) });
181
+ }
182
+ const buf = buildZip(entries);
183
+ await fsp.mkdir(path.dirname(zipPath), { recursive: true });
184
+ await fsp.writeFile(zipPath, buf);
185
+
186
+ const info = inspectZip(buf);
187
+ if (!info.ok || info.count !== entries.length) {
188
+ throw new CliError(`打包产物自检失败:${info.reason || `条目数 ${info.count} ≠ ${entries.length}`}`, {
189
+ kind: 'pack',
190
+ code: 'EZIP',
191
+ exitCode: EXIT.ERROR,
192
+ });
193
+ }
194
+ const required = ['template.json', 'pages/index.html', 'assets/base/base.css'];
195
+ const missing = required.filter((r) => !info.names.includes(r));
196
+ const hasDesign = info.names.some((n) => /^design\/.*\.png$/.test(n));
197
+ if (missing.length || !hasDesign) {
198
+ throw new CliError(`zip 内容不全:缺 ${missing.concat(hasDesign ? [] : ['design/*.png']).join(', ')}`, {
199
+ kind: 'pack',
200
+ code: 'EZIPCONTENT',
201
+ exitCode: EXIT.ERROR,
202
+ });
203
+ }
204
+ say(`完成:${entries.length} 个文件 / ${info.bytes}B → ${zipPath}`);
205
+ return { zip: zipPath, bytes: info.bytes, files: info.names, count: entries.length, validate, baseSync };
206
+ }