@heybox/hb-sdk 0.10.0-alpha.2 → 0.10.0-alpha.4

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +13 -0
  3. package/dist/cli-chunks/{build-Be8QI9ma.cjs → build-wguxGJim.cjs} +8 -6
  4. package/dist/cli-chunks/{create-CaAGgJXF.cjs → create-mJhWyXDG.cjs} +2 -2
  5. package/dist/cli-chunks/{dev-BS8uwRH2.cjs → dev-CyfaFkKn.cjs} +19 -11
  6. package/dist/cli-chunks/{doctor-CgdrOrS5.cjs → doctor-De8pnp13.cjs} +1 -1
  7. package/dist/cli-chunks/{game-binding-guide-DX8uXx0V.cjs → game-binding-guide-C9ICs9zj.cjs} +3 -3
  8. package/dist/cli-chunks/{game-bindings-CjI0oA1t.cjs → game-bindings-Bg2xoKZY.cjs} +4 -4
  9. package/dist/cli-chunks/{games-C8A0PCo-.cjs → games-CAhkA4nh.cjs} +1 -1
  10. package/dist/cli-chunks/{index-BTOX41Vr.cjs → index-B8rzkV1n.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CMbVUUpA.cjs → index-pGP_FOkj.cjs} +24 -22
  12. package/dist/cli-chunks/{index.esm-D7A_j5MA.cjs → index.esm-B8H9EwB1.cjs} +67 -0
  13. package/dist/cli-chunks/{index.esm-CIBT3Na1.cjs → index.esm-BqyU_JCg.cjs} +9 -9
  14. package/dist/cli-chunks/{login-BWuLgJWT.cjs → login-BYLNpsQ1.cjs} +1 -1
  15. package/dist/cli-chunks/{project-vite-FWtHl3XL.cjs → project-vite-BRUA9Vng.cjs} +1 -1
  16. package/dist/cli-chunks/{remote-R1jgvh-Z.cjs → remote-BAf86E8n.cjs} +13 -9
  17. package/dist/cli-chunks/{runtime-permission-env-BuXOApO4.cjs → runtime-permission-env-XMA-YAuB.cjs} +392 -113
  18. package/dist/cli-chunks/{skill-EM-Uv3Rj.cjs → skill-D6kR1-g0.cjs} +2 -2
  19. package/dist/cli-chunks/{version-BXh-cltM.cjs → version-SUKtha-_.cjs} +1 -1
  20. package/dist/cli.cjs +1 -1
  21. package/dist/devtools/browser-dev-host/assets/browser-dev-host-C2-qtvqp.js +224 -0
  22. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BXVw6d6N.js → desktop-app-launch-DVnZ7dFB.js} +1 -1
  23. package/dist/devtools/browser-dev-host/assets/{index-CABlopeJ.js → index-DCPdAyuJ.js} +3 -3
  24. package/dist/devtools/browser-dev-host/index.html +2 -2
  25. package/dist/index.cjs.js +284 -1
  26. package/dist/index.esm.js +284 -1
  27. package/dist/miniapp-publish.cjs.js +215 -116
  28. package/dist/miniapp-publish.esm.js +214 -117
  29. package/dist/protocol.cjs.js +57 -0
  30. package/dist/protocol.esm.js +57 -0
  31. package/dist/vite.cjs.js +238 -96
  32. package/dist/vite.esm.js +238 -96
  33. package/package.json +6 -6
  34. package/skill/skill.json +4 -4
  35. package/types/index.d.ts +81 -6
  36. package/types/miniapp-publish/index.d.ts +30 -15
  37. package/types/vite/index.d.ts +7 -0
  38. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CpphzCg4.js +0 -224
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ var node_crypto = require('node:crypto');
3
4
  var fs = require('node:fs');
5
+ var fs$1 = require('node:fs/promises');
4
6
  var path = require('node:path');
5
- var version = require('./version-BXh-cltM.cjs');
7
+ var version = require('./version-SUKtha-_.cjs');
6
8
  var bindings = require('./bindings-B9HSKhmy.cjs');
7
- var fs$1 = require('node:fs/promises');
8
- var index_esm = require('./index.esm-D7A_j5MA.cjs');
9
- var index = require('./index-CMbVUUpA.cjs');
10
- var node_crypto = require('node:crypto');
9
+ var index = require('./index-pGP_FOkj.cjs');
10
+ var index_esm = require('./index.esm-B8H9EwB1.cjs');
11
11
  require('node:zlib');
12
12
  require('node:module');
13
13
  require('node:url');
@@ -18,111 +18,6 @@ var require$$0 = require('os');
18
18
  var require$$6 = require('inspector');
19
19
  var node_async_hooks = require('node:async_hooks');
20
20
 
21
- const BASIC_INFO_MAX_BYTES = 10 * 1024 * 1024;
22
- const BASIC_INFO_MAX_PIXELS = 40_000_000;
23
- /**
24
- * 规范化并校验小程序展示名称。
25
- *
26
- * @param raw - 原始名称,必须是字符串。
27
- * @returns NFKC 规范化、去除首尾 Unicode White_Space 后的名称;不折叠规范化后的内部空白。
28
- * @throws `Error` 输入不是字符串,或规范化后不是 1–40 个 Unicode code point、不含文字或数字,或包含控制字符、
29
- * 格式字符、行/段分隔符以及 HTML 特殊字符 `<`、`>`、`&`、双引号或单引号时抛出。
30
- * @since 0.8.2
31
- */
32
- function normalizeBasicInfoName(raw) {
33
- if (typeof raw !== 'string')
34
- throw new Error('heybox.name 必须是字符串');
35
- // 与 Go TrimSpace 一致(JS trim 额外移除 BOM,故使用 Unicode White_Space)。
36
- const name = raw.normalize('NFKC').replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
37
- if (Array.from(name).length < 1 || Array.from(name).length > 40 || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}<>&"']/u.test(name) || !/[\p{L}\p{N}]/u.test(name)) {
38
- throw new Error('名称须包含 1–40 个字符及文字或数字,不能包含控制字符或 HTML 特殊字符');
39
- }
40
- return name;
41
- }
42
- function validateBasicInfoPath(raw) {
43
- if (typeof raw !== 'string' || !raw || /[\\:%?#\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(raw))
44
- throw new Error('资料图片必须是项目内的规范相对路径');
45
- const forbidden = new Set(['', '.', '..', '.git', 'node_modules', 'dist', '.hb-sdk', '.vite', '.cache', '.tmp', 'tmp']);
46
- if (raw.split('/').some((part) => forbidden.has(part)))
47
- throw new Error('资料图片路径包含禁止的目录');
48
- if (!/\.(png|jpe?g|gif|webp)$/i.test(raw))
49
- throw new Error('资料图片仅支持 JPEG、PNG、GIF、WebP');
50
- return raw;
51
- }
52
- /**
53
- * 校验项目声明或 Manifest 中的小程序展示资料。
54
- *
55
- * @param value - `package.json#heybox` 或 Manifest 对象,读取 `name`、`icon`、`coverImages`。
56
- * @param sdkVersion - 产物 SDK 版本,默认 `0.8.2`;用于判断历史产物是否允许缺失全部资料。
57
- * @returns 名称规范化后的新资料对象;仅版本早于 `0.8.2` 且三项均无自有属性时返回 `undefined`。
58
- * @throws `Error` SDK 版本非法、资料字段不齐、名称/图片路径非法,或封面不是 1–5 个互不重复的路径时抛出。
59
- * @remarks
60
- * 图片路径必须使用 `/` 分隔的非空相对路径,扩展名为 JPEG、PNG、GIF 或 WebP;拒绝 URL、点段、
61
- * 控制字符和构建/缓存等保留目录。此函数只校验声明,不读取文件,也不验证图片字节、尺寸或存在性。
62
- * @since 0.8.2
63
- */
64
- function parseMiniappBasicInfo(value, sdkVersion = '0.8.2') {
65
- sdkVersion = sdkVersion.trim();
66
- if (!index.semverExports.valid(sdkVersion) || sdkVersion.startsWith('v') || sdkVersion.includes('+'))
67
- throw new Error('manifest.sdkVersion 必须是合法 SemVer');
68
- const fields = ['name', 'icon', 'coverImages'];
69
- const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(value, key));
70
- if (!present.length && index.semverExports.lt(sdkVersion, '0.8.2'))
71
- return undefined;
72
- if (present.length !== fields.length)
73
- throw new Error('请配置 heybox.name、heybox.icon、heybox.coverImages,或运行 remote bind/dev/remote deploy 迁移已发布资料');
74
- const name = normalizeBasicInfoName(value.name);
75
- const icon = validateBasicInfoPath(value.icon);
76
- if (!Array.isArray(value.coverImages) || value.coverImages.length < 1 || value.coverImages.length > 5)
77
- throw new Error('coverImages 必须包含 1–5 张图片');
78
- const coverImages = value.coverImages.map(validateBasicInfoPath);
79
- if (new Set(coverImages).size !== coverImages.length)
80
- throw new Error('封面路径不能重复');
81
- return { name, icon, coverImages };
82
- }
83
-
84
- /**
85
- * 校验项目配置或产物中的小程序类别。
86
- *
87
- * @param value - 待校验值,只接受 `tool`、`game`、`other` 或 `undefined`;不做 trim 或大小写转换。
88
- * @param sourceLabel - 错误消息中的字段来源,默认 `package.json#heybox.category`。
89
- * @returns 合法类别原值;输入 `undefined` 时返回 `undefined`,由发布流程另行检查是否必填。
90
- * @throws `Error` 输入为其他值(包括 null 或空字符串)时抛出带字段来源的错误。
91
- * @since 0.8.3
92
- */
93
- function parseMiniappCategory(value, sourceLabel = 'package.json#heybox.category') {
94
- if (value === undefined)
95
- return undefined;
96
- if (value === 'tool' || value === 'game' || value === 'other')
97
- return value;
98
- throw new Error(`${sourceLabel} 必须是 tool、game 或 other`);
99
- }
100
-
101
- /** 小程序简介最大长度(Unicode code point),与服务端截断口径一致。 */
102
- const MINIAPP_DESC_MAX_LENGTH = 200;
103
- /**
104
- * 校验并规范化 `package.json#heybox.desc` / `manifest.desc`。
105
- *
106
- * @param value - 原始声明;未声明时为 `undefined`。
107
- * @param sourceLabel - 错误消息中的字段来源,默认 `package.json#heybox.desc`。
108
- * @returns 去除首尾空白后的简介;未声明或为空串时返回 `undefined`。
109
- * @throws `Error` 非字符串、超过 200 个字符,或包含除换行外的控制字符时抛出。
110
- */
111
- function parseMiniappDesc(value, sourceLabel = 'package.json#heybox.desc') {
112
- if (value === undefined)
113
- return undefined;
114
- if (typeof value !== 'string')
115
- throw new Error(`${sourceLabel} 必须是字符串`);
116
- const desc = value.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
117
- if (!desc)
118
- return undefined;
119
- if (Array.from(desc).length > MINIAPP_DESC_MAX_LENGTH)
120
- throw new Error(`${sourceLabel} 不能超过 ${MINIAPP_DESC_MAX_LENGTH} 个字符`);
121
- if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(desc.replace(/\n/g, '')))
122
- throw new Error(`${sourceLabel} 不能包含控制字符`);
123
- return desc;
124
- }
125
-
126
21
  const MINIAPP_PERMISSION_KEYS = index_esm.MINI_PROGRAM_PERMISSION_KEYS;
127
22
  function parseMiniappPermissions(value, options) {
128
23
  const sourceLabel = options.sourceLabel ?? 'package.json#heybox.permissions';
@@ -132,7 +27,7 @@ function parseMiniappPermissions(value, options) {
132
27
  }
133
28
  return { declared: false };
134
29
  }
135
- if (!isRecord$3(value)) {
30
+ if (!isRecord$5(value)) {
136
31
  throw new Error(`${sourceLabel} 必须是 JSON 对象`);
137
32
  }
138
33
  const knownKeys = new Set(MINIAPP_PERMISSION_KEYS);
@@ -146,7 +41,7 @@ function parseMiniappPermissions(value, options) {
146
41
  continue;
147
42
  const declaration = value[key];
148
43
  const itemLabel = `${sourceLabel}.${key}`;
149
- if (!isRecord$3(declaration))
44
+ if (!isRecord$5(declaration))
150
45
  throw new Error(`${itemLabel} 必须是 JSON 对象`);
151
46
  const definition = index_esm.MINI_PROGRAM_PERMISSION_CATALOG.find((item) => item.key === key);
152
47
  if (!definition)
@@ -216,7 +111,7 @@ function composeMiniappRuntimePermissions(local, approvals,
216
111
  partyType) {
217
112
  const parsedApprovals = index_esm.parseMiniProgramRuntimePermissions(approvals);
218
113
  const firstParty = local.declared && parsedApprovals.valid && partyType === 'first_party';
219
- const approvalRevision = isRecord$3(approvals) && Number.isInteger(approvals.revision) ? approvals.revision : undefined;
114
+ const approvalRevision = isRecord$5(approvals) && Number.isInteger(approvals.revision) ? approvals.revision : undefined;
220
115
  const views = [];
221
116
  const entries = [];
222
117
  for (const definition of index_esm.MINI_PROGRAM_PERMISSION_CATALOG) {
@@ -288,9 +183,358 @@ partyType) {
288
183
  function normalizeUserGameDataResources(declaration) {
289
184
  return index_esm.parseUserGameDataResourceDeclarations(declaration?.resources ?? {});
290
185
  }
186
+ function isRecord$5(value) {
187
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
188
+ }
189
+ /** Whether this manifest opts into the reviewed cloud room capability. */
190
+ function declaresCloudRooms(manifest) {
191
+ const permissions = manifest.permissions;
192
+ return permissions?.cloud_rooms?.enabled === true;
193
+ }
194
+
195
+ const privateRelative = '.hb-sdk/rooms/private.json';
196
+ function canonical(value) {
197
+ if (Array.isArray(value))
198
+ return `[${value.map(canonical).join(',')}]`;
199
+ if (value !== null && typeof value === 'object') {
200
+ const object = value;
201
+ return `{${Object.keys(object)
202
+ .sort()
203
+ .map((key) => `${JSON.stringify(key)}:${canonical(object[key])}`)
204
+ .join(',')}}`;
205
+ }
206
+ if (typeof value === 'number' && !Number.isFinite(value))
207
+ throw new Error('Room 数字必须为有限值');
208
+ const result = JSON.stringify(value);
209
+ if (result === undefined)
210
+ throw new Error('规则不能包含 undefined');
211
+ return result;
212
+ }
213
+ const validName = (name) => typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,47}$/.test(name) && name !== 'constructor' && name !== 'prototype';
214
+ const inRange = (value, low, high) => Number.isInteger(value) && value >= low && value <= high;
215
+ const isRecord$4 = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
216
+ /** 本地检查生成类型所需的协议结构,完整的规则编译在工坊提审时执行。 */
217
+ function references(definitions) {
218
+ if (!isRecord$4(definitions) || Object.keys(definitions).length > 4)
219
+ throw new Error('Room 定义集合无效');
220
+ return Object.fromEntries(Object.entries(definitions).map(([name, def]) => {
221
+ if (!isRecord$4(def) || !validName(name) || def.name !== name || def.format !== 'hb-room-relay/1' ||
222
+ Object.keys(def).some((key) => !['name', 'format', 'version', 'maxMembers', 'actions'].includes(key)) ||
223
+ !inRange(def.version, 1, 2147483647) || !inRange(def.maxMembers, 2, 8) ||
224
+ !isRecord$4(def.actions) || !inRange(Object.keys(def.actions).length, 1, 32)) {
225
+ throw new Error(`Room JSON 协议校验失败:${name}`);
226
+ }
227
+ for (const [action, spec] of Object.entries(def.actions)) {
228
+ if (!validName(action) || !isRecord$4(spec) ||
229
+ Object.keys(spec).some((key) => !['params', 'access', 'delivery', 'routing', 'maxHz'].includes(key)) ||
230
+ !['member', 'owner'].includes(spec.access) || !inRange(spec.maxHz, 1, 20) ||
231
+ (spec.routing !== undefined && !['targeted', 'broadcast'].includes(spec.routing)) ||
232
+ (spec.delivery !== undefined && spec.delivery !== 'reliable') ||
233
+ spec.params?.type !== 'object' || spec.params.nullable) {
234
+ throw new Error(`Room 动作校验失败:${name}.${action}`);
235
+ }
236
+ }
237
+ return [name, { name, hash: node_crypto.createHash('sha256').update(canonical(def)).digest('hex') }];
238
+ }));
239
+ }
240
+ const numericFields = ['minimum', 'maximum', 'multipleOf'];
241
+ const schemaFields = {
242
+ integer: numericFields,
243
+ number: numericFields,
244
+ object: ['properties', 'required'],
245
+ string: ['enum'],
246
+ array: ['items', 'maxItems'],
247
+ boolean: [],
248
+ member: [],
249
+ };
250
+ function schemaType(s, depth = 0) {
251
+ if (!isRecord$4(s) || depth > 5)
252
+ throw new Error('Room 参数结构无效');
253
+ if (!Object.hasOwn(schemaFields, s.type) ||
254
+ Object.keys(s).some((key) => key !== 'type' && key !== 'nullable' && !schemaFields[s.type].includes(key)) ||
255
+ (s.nullable !== undefined && typeof s.nullable !== 'boolean'))
256
+ throw new Error('Room 参数字段无效');
257
+ let type;
258
+ switch (s.type) {
259
+ case 'string':
260
+ if (!Array.isArray(s.enum) || !inRange(s.enum.length, 1, 32) || new Set(s.enum).size !== s.enum.length || !s.enum.every(validName))
261
+ throw new Error('Room 字符串参数需要 1-32 个合法且不重复的枚举值');
262
+ type = s.enum.map((value) => JSON.stringify(value)).join(' | ');
263
+ break;
264
+ case 'integer':
265
+ case 'number': {
266
+ const { minimum, maximum, multipleOf } = s;
267
+ const validBound = (value) => typeof value === 'number' &&
268
+ Math.abs(value) <= Number.MAX_SAFE_INTEGER && (s.type !== 'integer' || Number.isInteger(value));
269
+ if (!validBound(minimum) || !validBound(maximum) || minimum > maximum)
270
+ throw new Error('Room 数值边界无效');
271
+ if ((s.type === 'number' || multipleOf !== undefined) && (!validBound(multipleOf) || multipleOf < 0.000001))
272
+ throw new Error('Room 数值步长无效');
273
+ type = 'number';
274
+ break;
275
+ }
276
+ case 'boolean':
277
+ type = 'boolean';
278
+ break;
279
+ case 'member':
280
+ type = 'string';
281
+ break;
282
+ case 'array':
283
+ if (!s.items || !inRange(s.maxItems ?? 0, 1, 16))
284
+ throw new Error('Room 数组需要 items 和 1-16 的 maxItems');
285
+ type = `Array<${schemaType(s.items, depth + 1)}>`;
286
+ break;
287
+ case 'object': {
288
+ if ((s.properties !== undefined && !isRecord$4(s.properties)) || (s.required !== undefined && !Array.isArray(s.required))) {
289
+ throw new Error('Room 对象参数结构无效');
290
+ }
291
+ const keys = Object.keys(s.properties ?? {});
292
+ const required = s.required ?? [];
293
+ if (keys.length > 32 || !keys.every(validName) || new Set(required).size !== required.length || !required.every((key) => keys.includes(key)))
294
+ throw new Error('Room 对象属性或必填字段无效');
295
+ type = `{ ${Object.entries(s.properties ?? {})
296
+ .map(([k, v]) => `${JSON.stringify(k)}${s.required?.includes(k) ? '' : '?'}: ${schemaType(v, depth + 1)}`)
297
+ .join('; ')} }`;
298
+ break;
299
+ }
300
+ default:
301
+ throw new Error('不支持的 Room 参数类型');
302
+ }
303
+ return s.nullable ? `(${type}) | null` : type;
304
+ }
305
+ const generatedHeader = "// 由 hb-sdk build 生成。\nimport type { RoomDefinition } from '@heybox/hb-sdk';\n";
306
+ async function replaceFile(file, content, mode) {
307
+ const temp = file + '.' + node_crypto.randomUUID() + '.tmp';
308
+ try {
309
+ await fs$1.writeFile(temp, content, { flag: 'wx', mode });
310
+ await fs$1.rename(temp, file);
311
+ }
312
+ finally {
313
+ await fs$1.rm(temp, { force: true });
314
+ }
315
+ }
316
+ function renderRoomContract(def, hash) {
317
+ const actions = `{ ${Object.entries(def.actions)
318
+ .map(([name, a]) => `${JSON.stringify(name)}: ${schemaType(a.params)}`)
319
+ .join('; ')} }`;
320
+ return `${generatedHeader}export type Actions = ${actions};\nconst definition: RoomDefinition<Actions> = ${JSON.stringify({ name: def.name, hash })};\nexport { definition as ${def.name} };\n`;
321
+ }
322
+ async function buildRoomDefinitions(root) {
323
+ const directory = path.join(root, 'rooms');
324
+ const files = fs.existsSync(directory) ? await fs$1.readdir(directory, { withFileTypes: true }) : [];
325
+ if (files.some((file) => file.isFile() && /\.room\.[cm]?ts$/i.test(file.name)))
326
+ throw new Error('Room 定义只支持 rooms/*.room.json');
327
+ const sources = files
328
+ .filter((file) => file.isFile() && file.name.endsWith('.room.json'))
329
+ .map((file) => file.name)
330
+ .sort();
331
+ const definitions = Object.create(null);
332
+ const names = new Map();
333
+ if (sources.length > 4)
334
+ throw new Error('最多声明四种 Room Definition');
335
+ for (const file of sources) {
336
+ const source = await fs$1.readFile(path.join(directory, file), 'utf8');
337
+ if (Buffer.byteLength(source) > 65536)
338
+ throw new Error('Room 定义文件超过 64 KiB');
339
+ const def = JSON.parse(source);
340
+ if (!def || typeof def.name !== 'string' || !validName(def.name))
341
+ throw new Error('Room Definition 名称无效');
342
+ const filenameKey = def.name.toLowerCase();
343
+ const previous = names.get(filenameKey);
344
+ if (previous)
345
+ throw new Error(`Room Definition 名称重复:${previous} 与 ${def.name} 的生成文件重名`);
346
+ names.set(filenameKey, def.name);
347
+ definitions[def.name] = def;
348
+ }
349
+ const refs = references(definitions);
350
+ const contracts = Object.entries(definitions).map(([name, definition]) => ({
351
+ name,
352
+ source: renderRoomContract(definition, refs[name].hash),
353
+ }));
354
+ const privateDir = path.join(root, '.hb-sdk/rooms');
355
+ const generated = path.join(root, 'generated/rooms');
356
+ const filename = (name) => name + '.contract.ts';
357
+ for (const { name } of contracts) {
358
+ const target = path.join(generated, filename(name));
359
+ const stat = await fs$1.lstat(target).catch((error) => {
360
+ if (error.code !== 'ENOENT')
361
+ throw error;
362
+ return undefined;
363
+ });
364
+ if (stat && (!stat.isFile() || !(await fs$1.readFile(target, 'utf8')).startsWith(generatedHeader))) {
365
+ throw new Error('Room 类型文件与项目文件重名:' + target);
366
+ }
367
+ }
368
+ const existing = fs.existsSync(generated) ? await fs$1.readdir(generated, { withFileTypes: true }) : [];
369
+ for (const entry of existing) {
370
+ if (!entry.isFile() || !entry.name.endsWith('.contract.ts'))
371
+ continue;
372
+ const name = entry.name.slice(0, -'.contract.ts'.length);
373
+ if (!validName(name) || Object.hasOwn(definitions, name))
374
+ continue;
375
+ const file = path.join(generated, entry.name);
376
+ if ((await fs$1.readFile(file, 'utf8')).startsWith(generatedHeader))
377
+ await fs$1.rm(file, { force: true });
378
+ }
379
+ const privateFile = path.join(root, privateRelative);
380
+ const refsFile = path.join(privateDir, 'references.json');
381
+ if (!sources.length) {
382
+ await fs$1.rm(refsFile, { force: true });
383
+ await fs$1.rm(privateFile, { force: true });
384
+ return false;
385
+ }
386
+ await fs$1.mkdir(privateDir, { recursive: true, mode: 0o700 });
387
+ await fs$1.mkdir(generated, { recursive: true });
388
+ for (const { name, source } of contracts) {
389
+ await replaceFile(path.join(generated, filename(name)), source);
390
+ }
391
+ await replaceFile(privateFile, canonical(definitions), 0o600);
392
+ await replaceFile(refsFile, JSON.stringify(refs));
393
+ return true;
394
+ }
395
+ function readPrivateRoomRules(root, manifest) {
396
+ if (!declaresCloudRooms(manifest))
397
+ return undefined;
398
+ const refs = manifest.roomDefinitions;
399
+ if (!refs || !Object.keys(refs).length)
400
+ return undefined;
401
+ const file = path.join(root, privateRelative);
402
+ if (!fs.existsSync(file))
403
+ throw new Error('私有 Room 定义不存在,请重新运行 hb-sdk build');
404
+ const raw = fs.readFileSync(file, 'utf8');
405
+ if (Buffer.byteLength(raw) > 262144)
406
+ throw new Error('私有 Room 定义过大');
407
+ const definitions = JSON.parse(raw);
408
+ const actual = references(definitions);
409
+ if (Object.keys(actual).length !== Object.keys(refs).length ||
410
+ Object.entries(actual).some(([name, ref]) => refs[name]?.name !== name || refs[name]?.hash !== ref.hash))
411
+ throw new Error('Room 产物不一致,请重新 build');
412
+ return definitions;
413
+ }
414
+
291
415
  function isRecord$3(value) {
292
416
  return typeof value === 'object' && value !== null && !Array.isArray(value);
293
417
  }
418
+ function assertRoomReferences(refs) {
419
+ if (!isRecord$3(refs) || Object.keys(refs).length > 4)
420
+ throw new Error('roomDefinitions 无效');
421
+ for (const [name, ref] of Object.entries(refs)) {
422
+ if (!/^[A-Za-z][A-Za-z0-9_]{0,47}$/.test(name) ||
423
+ ['constructor', 'prototype', '__proto__'].includes(name) ||
424
+ !isRecord$3(ref) ||
425
+ Object.keys(ref).some((key) => key !== 'name' && key !== 'hash') ||
426
+ ref.name !== name ||
427
+ typeof ref.hash !== 'string' ||
428
+ !/^[a-f0-9]{64}$/.test(ref.hash)) {
429
+ throw new Error('Room 公开引用无效');
430
+ }
431
+ }
432
+ }
433
+
434
+ const BASIC_INFO_MAX_BYTES = 10 * 1024 * 1024;
435
+ const BASIC_INFO_MAX_PIXELS = 40_000_000;
436
+ /**
437
+ * 规范化并校验小程序展示名称。
438
+ *
439
+ * @param raw - 原始名称,必须是字符串。
440
+ * @returns NFKC 规范化、去除首尾 Unicode White_Space 后的名称;不折叠规范化后的内部空白。
441
+ * @throws `Error` 输入不是字符串,或规范化后不是 1–40 个 Unicode code point、不含文字或数字,或包含控制字符、
442
+ * 格式字符、行/段分隔符以及 HTML 特殊字符 `<`、`>`、`&`、双引号或单引号时抛出。
443
+ * @since 0.8.2
444
+ */
445
+ function normalizeBasicInfoName(raw) {
446
+ if (typeof raw !== 'string')
447
+ throw new Error('heybox.name 必须是字符串');
448
+ // 与 Go TrimSpace 一致(JS trim 额外移除 BOM,故使用 Unicode White_Space)。
449
+ const name = raw.normalize('NFKC').replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
450
+ if (Array.from(name).length < 1 || Array.from(name).length > 40 || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}<>&"']/u.test(name) || !/[\p{L}\p{N}]/u.test(name)) {
451
+ throw new Error('名称须包含 1–40 个字符及文字或数字,不能包含控制字符或 HTML 特殊字符');
452
+ }
453
+ return name;
454
+ }
455
+ function validateBasicInfoPath(raw) {
456
+ if (typeof raw !== 'string' || !raw || /[\\:%?#\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(raw))
457
+ throw new Error('资料图片必须是项目内的规范相对路径');
458
+ const forbidden = new Set(['', '.', '..', '.git', 'node_modules', 'dist', '.hb-sdk', '.vite', '.cache', '.tmp', 'tmp']);
459
+ if (raw.split('/').some((part) => forbidden.has(part)))
460
+ throw new Error('资料图片路径包含禁止的目录');
461
+ if (!/\.(png|jpe?g|gif|webp)$/i.test(raw))
462
+ throw new Error('资料图片仅支持 JPEG、PNG、GIF、WebP');
463
+ return raw;
464
+ }
465
+ /**
466
+ * 校验项目声明或 Manifest 中的小程序展示资料。
467
+ *
468
+ * @param value - `package.json#heybox` 或 Manifest 对象,读取 `name`、`icon`、`coverImages`。
469
+ * @param sdkVersion - 产物 SDK 版本,默认 `0.8.2`;用于判断历史产物是否允许缺失全部资料。
470
+ * @returns 名称规范化后的新资料对象;仅版本早于 `0.8.2` 且三项均无自有属性时返回 `undefined`。
471
+ * @throws `Error` SDK 版本非法、资料字段不齐、名称/图片路径非法,或封面不是 1–5 个互不重复的路径时抛出。
472
+ * @remarks
473
+ * 图片路径必须使用 `/` 分隔的非空相对路径,扩展名为 JPEG、PNG、GIF 或 WebP;拒绝 URL、点段、
474
+ * 控制字符和构建/缓存等保留目录。此函数只校验声明,不读取文件,也不验证图片字节、尺寸或存在性。
475
+ * @since 0.8.2
476
+ */
477
+ function parseMiniappBasicInfo(value, sdkVersion = '0.8.2') {
478
+ sdkVersion = sdkVersion.trim();
479
+ if (!index.semverExports.valid(sdkVersion) || sdkVersion.startsWith('v') || sdkVersion.includes('+'))
480
+ throw new Error('manifest.sdkVersion 必须是合法 SemVer');
481
+ const fields = ['name', 'icon', 'coverImages'];
482
+ const present = fields.filter((key) => Object.prototype.hasOwnProperty.call(value, key));
483
+ if (!present.length && index.semverExports.lt(sdkVersion, '0.8.2'))
484
+ return undefined;
485
+ if (present.length !== fields.length)
486
+ throw new Error('请配置 heybox.name、heybox.icon、heybox.coverImages,或运行 remote bind/dev/remote deploy 迁移已发布资料');
487
+ const name = normalizeBasicInfoName(value.name);
488
+ const icon = validateBasicInfoPath(value.icon);
489
+ if (!Array.isArray(value.coverImages) || value.coverImages.length < 1 || value.coverImages.length > 5)
490
+ throw new Error('coverImages 必须包含 1–5 张图片');
491
+ const coverImages = value.coverImages.map(validateBasicInfoPath);
492
+ if (new Set(coverImages).size !== coverImages.length)
493
+ throw new Error('封面路径不能重复');
494
+ return { name, icon, coverImages };
495
+ }
496
+
497
+ /**
498
+ * 校验项目配置或产物中的小程序类别。
499
+ *
500
+ * @param value - 待校验值,只接受 `tool`、`game`、`other` 或 `undefined`;不做 trim 或大小写转换。
501
+ * @param sourceLabel - 错误消息中的字段来源,默认 `package.json#heybox.category`。
502
+ * @returns 合法类别原值;输入 `undefined` 时返回 `undefined`,由发布流程另行检查是否必填。
503
+ * @throws `Error` 输入为其他值(包括 null 或空字符串)时抛出带字段来源的错误。
504
+ * @since 0.8.3
505
+ */
506
+ function parseMiniappCategory(value, sourceLabel = 'package.json#heybox.category') {
507
+ if (value === undefined)
508
+ return undefined;
509
+ if (value === 'tool' || value === 'game' || value === 'other')
510
+ return value;
511
+ throw new Error(`${sourceLabel} 必须是 tool、game 或 other`);
512
+ }
513
+
514
+ /** 小程序简介最大长度(Unicode code point),与服务端截断口径一致。 */
515
+ const MINIAPP_DESC_MAX_LENGTH = 200;
516
+ /**
517
+ * 校验并规范化 `package.json#heybox.desc` / `manifest.desc`。
518
+ *
519
+ * @param value - 原始声明;未声明时为 `undefined`。
520
+ * @param sourceLabel - 错误消息中的字段来源,默认 `package.json#heybox.desc`。
521
+ * @returns 去除首尾空白后的简介;未声明或为空串时返回 `undefined`。
522
+ * @throws `Error` 非字符串、超过 200 个字符,或包含除换行外的控制字符时抛出。
523
+ */
524
+ function parseMiniappDesc(value, sourceLabel = 'package.json#heybox.desc') {
525
+ if (value === undefined)
526
+ return undefined;
527
+ if (typeof value !== 'string')
528
+ throw new Error(`${sourceLabel} 必须是字符串`);
529
+ const desc = value.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, '');
530
+ if (!desc)
531
+ return undefined;
532
+ if (Array.from(desc).length > MINIAPP_DESC_MAX_LENGTH)
533
+ throw new Error(`${sourceLabel} 不能超过 ${MINIAPP_DESC_MAX_LENGTH} 个字符`);
534
+ if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(desc.replace(/\n/g, '')))
535
+ throw new Error(`${sourceLabel} 不能包含控制字符`);
536
+ return desc;
537
+ }
294
538
 
295
539
  /**
296
540
  * `package.json#heybox.platforms` 接受的平台值,顺序同时是 Manifest 的规范化输出顺序。
@@ -399,6 +643,9 @@ function parseMiniappManifestJson(raw, sourceLabel = 'manifest.json') {
399
643
  * @since 0.8.2
400
644
  */
401
645
  function validateMiniappManifestForDeploy(manifest) {
646
+ const roomDefinitions = declaresCloudRooms(manifest) ? manifest.roomDefinitions : undefined;
647
+ if (roomDefinitions !== undefined)
648
+ assertRoomReferences(roomDefinitions);
402
649
  const version = validateMiniappManifestVersion(manifest.version, 'manifest.version');
403
650
  const sdkVersion = validateSdkVersion(manifest.sdkVersion, 'manifest.sdkVersion');
404
651
  const permissions = parseMiniappPermissions(manifest.permissions, {
@@ -423,6 +670,7 @@ function validateMiniappManifestForDeploy(manifest) {
423
670
  platforms: validateMiniappPlatforms(manifest.platforms, 'manifest.platforms'),
424
671
  ...(permissions.permissions === undefined ? {} : { permissions: permissions.permissions }),
425
672
  ...(companions === undefined ? {} : { companions }),
673
+ ...(roomDefinitions === undefined ? {} : { roomDefinitions }),
426
674
  ...(manifest.workspaceCards === undefined ? {} : { workspaceCards: manifest.workspaceCards }),
427
675
  ...(window === undefined ? {} : { window }),
428
676
  ...(bindAppIds.length === 0 ? {} : { bindAppIds }),
@@ -211225,6 +211473,9 @@ function prepareMiniappArtifactFiles(files) {
211225
211473
  const usedPaths = new Set();
211226
211474
  const prepared = files.map((file) => {
211227
211475
  const relativePath = normalizeMiniappArtifactRelativePath(file.relativePath);
211476
+ if (isPrivateRoomArtifactPath(relativePath)) {
211477
+ throw new Error(`Room 私有文件不能上传到 CDN:${relativePath}`);
211478
+ }
211228
211479
  if (usedPaths.has(relativePath)) {
211229
211480
  throw new Error(`构建产物包含重复文件路径:${relativePath}`);
211230
211481
  }
@@ -211234,6 +211485,11 @@ function prepareMiniappArtifactFiles(files) {
211234
211485
  });
211235
211486
  return prepared.sort((left, right) => compareBytes(textEncoder.encode(left.relativePath), textEncoder.encode(right.relativePath)));
211236
211487
  }
211488
+ /** 平台私有目录在所有产物中保留,房间定义源文件仅对启用该能力的产物保留。 */
211489
+ function isPrivateRoomArtifactPath(relativePath, checkRoomSources = false) {
211490
+ return /(?:^|\/)\.hb-sdk\/rooms(?:\/|$)/i.test(relativePath) ||
211491
+ (checkRoomSources && /\.room\.(?:json|[cm]?ts)$/i.test(relativePath));
211492
+ }
211237
211493
  /**
211238
211494
  * 按服务端 session key 前缀校验最终上传路径的 UTF-8 字节长度。
211239
211495
  *
@@ -211618,6 +211874,24 @@ async function inspectVersionArtifactFiles(distDir) {
211618
211874
  const sizeError = validateMiniappUploadSizeBudgets(uploadFiles);
211619
211875
  if (sizeError)
211620
211876
  throw new Error(sizeError);
211877
+ const manifestFile = files.find((file) => file.relativePath === 'manifest.json');
211878
+ const manifest = manifestFile
211879
+ ? parseMiniappManifestJson(await fs$1.readFile(manifestFile.absolutePath, 'utf8'), 'dist/manifest.json').manifest
211880
+ : {};
211881
+ for (const file of declaresCloudRooms(manifest) ? files : []) {
211882
+ if (isPrivateRoomArtifactPath(file.relativePath, true))
211883
+ throw new Error(`dist 包含私有 Room 文件:${file.relativePath}`);
211884
+ if (!/\.(?:[cm]?js|json|map|html|[cm]?ts)$/i.test(file.relativePath))
211885
+ continue;
211886
+ // 分块检查,也覆盖 public 复制文件和不会上传的 sourcemap;不把整个文件载入内存。
211887
+ let tail = '';
211888
+ for await (const chunk of fs.createReadStream(file.absolutePath, { encoding: 'utf8', highWaterMark: 65536 })) {
211889
+ const content = tail + chunk;
211890
+ if (content.includes('hb-room-relay/1'))
211891
+ throw new Error(`dist 包含私有 Room 规则:${file.relativePath}`);
211892
+ tail = content.slice(-32);
211893
+ }
211894
+ }
211621
211895
  return { files: uploadFiles, fileCount: uploadFiles.length, totalBytes: uploadFiles.reduce((total, file) => total + file.size, 0) };
211622
211896
  async function walk(directory, prefix) {
211623
211897
  for (const entry of await fs$1.readdir(directory, { withFileTypes: true })) {
@@ -211631,6 +211905,8 @@ async function inspectVersionArtifactFiles(distDir) {
211631
211905
  // 在进入目录前检查,因此空的禁用目录同样拒绝。
211632
211906
  if (relativePathContainsNodeModulesSegment(relativePath))
211633
211907
  throw new Error(`dist 目录含 node_modules:${relativePath}`);
211908
+ if (isPrivateRoomArtifactPath(relativePath))
211909
+ throw new Error(`dist 包含私有 Room 文件:${relativePath}`);
211634
211910
  if (info.isDirectory())
211635
211911
  await walk(absolutePath, relativePath);
211636
211912
  else if (info.isFile())
@@ -211796,10 +212072,12 @@ exports.USER_MINIPROGRAM_POST_PREVIEW_API_PATH = USER_MINIPROGRAM_POST_PREVIEW_A
211796
212072
  exports.USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH = USER_MINIPROGRAM_PREVIEW_ALLOWLIST_API_PATH;
211797
212073
  exports.USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH = USER_MINIPROGRAM_VERSION_PREVIEW_INFO_API_PATH;
211798
212074
  exports.WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH = WITHDRAW_USER_MINIPROGRAM_VERSION_API_PATH;
212075
+ exports.buildRoomDefinitions = buildRoomDefinitions;
211799
212076
  exports.composeMiniappRuntimePermissions = composeMiniappRuntimePermissions;
211800
212077
  exports.createMiniappArtifactFileHeader = createMiniappArtifactFileHeader;
211801
212078
  exports.createMiniappArtifactSignatureHeader = createMiniappArtifactSignatureHeader;
211802
212079
  exports.createMiniappPlatformCspEnv = createMiniappPlatformCspEnv;
212080
+ exports.declaresCloudRooms = declaresCloudRooms;
211803
212081
  exports.hasMiniappDesktopPlatform = hasMiniappDesktopPlatform;
211804
212082
  exports.inspectVersionArtifact = inspectVersionArtifact;
211805
212083
  exports.inspectVersionArtifactFiles = inspectVersionArtifactFiles;
@@ -211815,6 +212093,7 @@ exports.readMiniappPermissionsFromPackageJson = readMiniappPermissionsFromPackag
211815
212093
  exports.readMiniappPlatformsFromPackageJson = readMiniappPlatformsFromPackageJson;
211816
212094
  exports.readMiniappWindowFromPackageJson = readMiniappWindowFromPackageJson;
211817
212095
  exports.readMiniappWorkspaceCardsFromPackageJson = readMiniappWorkspaceCardsFromPackageJson;
212096
+ exports.readPrivateRoomRules = readPrivateRoomRules;
211818
212097
  exports.resolveMiniappSdkVersion = resolveMiniappSdkVersion;
211819
212098
  exports.resolveMiniappUploadSessionFiles = resolveMiniappUploadSessionFiles;
211820
212099
  exports.shouldSkipMiniappPlatformCspFromEnv = shouldSkipMiniappPlatformCspFromEnv;
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var version = require('./version-BXh-cltM.cjs');
3
+ var version = require('./version-SUKtha-_.cjs');
4
4
  var fs = require('node:fs/promises');
5
5
  var path = require('node:path');
6
6
  var childProcess = require('node:child_process');
7
- var index = require('./index-CMbVUUpA.cjs');
7
+ var index = require('./index-pGP_FOkj.cjs');
8
8
  require('node:module');
9
9
  require('readline');
10
10
  require('os');
@@ -3,6 +3,6 @@
3
3
  /** 构建时替换为当前发布包的实际版本。 */
4
4
  const HB_SDK_VERSION = typeof undefined === 'string'
5
5
  ? undefined
6
- : '0.10.0-alpha.2';
6
+ : '0.10.0-alpha.4';
7
7
 
8
8
  exports.HB_SDK_VERSION = HB_SDK_VERSION;
package/dist/cli.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./cli-chunks/index-CMbVUUpA.cjs');
3
+ var index = require('./cli-chunks/index-pGP_FOkj.cjs');
4
4
  require('node:module');
5
5
  require('readline');
6
6
  require('os');