@heybox/hb-sdk 0.9.6-alpha.8 → 0.9.6

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 (50) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +8 -1
  3. package/THIRD_PARTY_NOTICES.md +472 -48
  4. package/dist/cli-chunks/{artifact-BKO6SUi7.cjs → artifact-D63EGQx9.cjs} +6 -5
  5. package/dist/cli-chunks/{build-Dfmx31Pu.cjs → build-fyHfi216.cjs} +6 -5
  6. package/dist/cli-chunks/{create-C9vj2WPs.cjs → create-B-EnCHjU.cjs} +322 -4
  7. package/dist/cli-chunks/{dev-CbvQhSfw.cjs → dev-Zb0pMdzr.cjs} +309 -39
  8. package/dist/cli-chunks/{dev-context-ohqz7YNY.cjs → dev-context-DYFBVQ_C.cjs} +22 -14
  9. package/dist/cli-chunks/{doctor-49h9U79a.cjs → doctor-DmkHu1Hk.cjs} +1 -1
  10. package/dist/cli-chunks/{games-CoT7KYEe.cjs → games-CeCLFeTt.cjs} +1 -1
  11. package/dist/cli-chunks/{index-Cy_IlqkS.cjs → index-C696i2DY.cjs} +1 -1
  12. package/dist/cli-chunks/{index-BCXuTxAO.cjs → index-It90_ScC.cjs} +210 -38
  13. package/dist/cli-chunks/index.esm-CvMA_ppV.cjs +7977 -0
  14. package/dist/cli-chunks/{index.esm-B9jI5p-8.cjs → index.esm-YDTVatz_.cjs} +7 -6
  15. package/dist/cli-chunks/{login-DzlRTbfT.cjs → login-BGJz7JZV.cjs} +1 -1
  16. package/dist/cli-chunks/{project-vite-Vibzv63j.cjs → project-vite-DybH-3Qp.cjs} +1 -1
  17. package/dist/cli-chunks/{remote-Cho-39Vd.cjs → remote-D9-2nonN.cjs} +13 -8
  18. package/dist/cli-chunks/{runtime-permission-env-BzP0KWpC.cjs → runtime-permission-env-BrSofQNz.cjs} +52 -6990
  19. package/dist/cli-chunks/{skill-XkW3Tj0X.cjs → skill-D6ebJn5J.cjs} +2 -2
  20. package/dist/cli-chunks/{version-DwTUFZwJ.cjs → version-CtGTgNGb.cjs} +1 -1
  21. package/dist/cli.cjs +1 -1
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DsmreI9p.js +228 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-CLikLiNS.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-1VVyBeMq.js +567 -0
  25. package/dist/devtools/browser-dev-host/assets/index-ophYZqpX.css +1 -0
  26. package/dist/devtools/browser-dev-host/assets/linux-DwJAcUeD.svg +1 -0
  27. package/dist/devtools/browser-dev-host/index.html +6 -4
  28. package/dist/index.cjs.js +1201 -156
  29. package/dist/index.esm.js +1201 -156
  30. package/dist/miniapp-publish.cjs.js +1072 -131
  31. package/dist/miniapp-publish.esm.js +1072 -131
  32. package/dist/protocol.cjs.js +732 -158
  33. package/dist/protocol.esm.js +716 -159
  34. package/dist/templates/vanilla-vite-js/README.md.ejs +27 -0
  35. package/dist/templates/vanilla-vite-js/package.json.ejs +1 -1
  36. package/dist/templates/vanilla-vite-js/src/user-game-data.js.ejs +1 -0
  37. package/dist/vite.cjs.js +1087 -150
  38. package/dist/vite.esm.js +1087 -150
  39. package/docs/appreciation-code.md +4 -8
  40. package/package.json +9 -10
  41. package/skill/SKILL.md +4 -0
  42. package/skill/skill.json +5 -5
  43. package/types/index.d.ts +492 -77
  44. package/types/miniapp-publish/index.d.ts +18 -2
  45. package/types/protocol.d.ts +1 -1
  46. package/types/vite/index.d.ts +10 -16
  47. package/dist/devtools/browser-dev-host/assets/browser-dev-host-YlT8qe4e.js +0 -100
  48. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-CIhnhlZj.js +0 -6
  49. package/dist/devtools/browser-dev-host/assets/index-BchRnwoE.js +0 -586
  50. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +0 -1
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-BCXuTxAO.cjs');
4
- var runtimePermissionEnv = require('./runtime-permission-env-BzP0KWpC.cjs');
3
+ var index = require('./index-It90_ScC.cjs');
4
+ var runtimePermissionEnv = require('./runtime-permission-env-BrSofQNz.cjs');
5
5
  var node_crypto = require('node:crypto');
6
6
  var fs = require('node:fs/promises');
7
7
  var path = require('node:path');
8
8
  var fs$1 = require('node:fs');
9
9
  var sharp = require('sharp');
10
+ var index_esm = require('./index.esm-CvMA_ppV.cjs');
10
11
 
11
12
  function createRemoteApiClient(options) {
12
13
  return {
@@ -544,7 +545,7 @@ async function compareBasicInfo(cwd, detail, fetchImpl = fetch) {
544
545
  function resolveBrowserFakeContext(context, now = Date.now()) {
545
546
  if (context.localDevGrant === undefined)
546
547
  return context;
547
- const parsed = runtimePermissionEnv.parseMiniProgramLocalDevGrant(context.localDevGrant);
548
+ const parsed = index_esm.parseMiniProgramLocalDevGrant(context.localDevGrant);
548
549
  if (!parsed.valid ||
549
550
  !context.devSessionId?.trim() ||
550
551
  !Number.isSafeInteger(context.contextRevision) ||
@@ -557,7 +558,7 @@ function resolveBrowserFakeContext(context, now = Date.now()) {
557
558
  return {
558
559
  ...context,
559
560
  ...(context.expiresAt <= now ? { source: 'anonymous', localDevLaunchToken: undefined, expiresAt: now + 30_000 } : {}),
560
- localDevGrant: runtimePermissionEnv.createMiniProgramLocalDevGrant({
561
+ localDevGrant: index_esm.createMiniProgramLocalDevGrant({
561
562
  declaredPermissions: context.declaredPermissions ?? {},
562
563
  runtimePermissions: context.runtimePermissions,
563
564
  revision: parsed.grant.revision,
@@ -577,8 +578,8 @@ const DEFAULT_PERMISSION_STATE = {
577
578
  },
578
579
  };
579
580
  function createBrowserDevPermissionState(context) {
580
- const parsed = runtimePermissionEnv.parseMiniProgramRuntimePermissions(context.localDevGrant
581
- ? runtimePermissionEnv.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
581
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(context.localDevGrant
582
+ ? index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions ?? {}, runtimePermissions: context.runtimePermissions,
582
583
  localDevGrant: context.localDevGrant }).runtimePermissions
583
584
  : context.runtimePermissions);
584
585
  const networkRequest = parsed.permissions.network;
@@ -601,7 +602,7 @@ function createMobileDevSessionRuntimePermissions(context) {
601
602
  const state = createBrowserDevPermissionState(context);
602
603
  return createDevRuntimePermissions(context.runtimePermissions, state, state.networkRequest.useOfficialDomain);
603
604
  }
604
- return runtimePermissionEnv.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
605
+ return index_esm.composeLocalDevRuntimePermissions({ declaredPermissions: context.declaredPermissions, runtimePermissions: context.runtimePermissions }).runtimePermissions;
605
606
  }
606
607
  function cloneDefaultPermissionState() {
607
608
  return {
@@ -609,12 +610,12 @@ function cloneDefaultPermissionState() {
609
610
  };
610
611
  }
611
612
  function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
612
- const parsed = runtimePermissionEnv.parseMiniProgramRuntimePermissions(snapshot);
613
+ const parsed = index_esm.parseMiniProgramRuntimePermissions(snapshot);
613
614
  if (!parsed.valid) {
614
615
  return { schema_version: 1, entries: [] };
615
616
  }
616
617
  const entries = [];
617
- for (const key of runtimePermissionEnv.MINI_PROGRAM_PERMISSION_KEYS) {
618
+ for (const key of index_esm.MINI_PROGRAM_PERMISSION_KEYS) {
618
619
  const entry = parsed.permissions[key];
619
620
  if (!entry)
620
621
  continue;
@@ -624,11 +625,18 @@ function createDevRuntimePermissions(snapshot, state, useOfficialDomain) {
624
625
  status: state.networkRequest.status,
625
626
  config: { useOfficialDomain },
626
627
  }
627
- : {
628
- key,
629
- status: entry.status,
630
- config: {},
631
- });
628
+ : key === 'user_game_data'
629
+ ? {
630
+ key,
631
+ status: entry.status,
632
+ // 精确资源清单是 snapshot 的合法必需项:浏览器模拟只调整开关,不能丢掉 Manifest 声明。
633
+ config: { resources: entry.config.resources },
634
+ }
635
+ : {
636
+ key,
637
+ status: entry.status,
638
+ config: {},
639
+ });
632
640
  }
633
641
  const revision = isPlainRecord(snapshot) && typeof snapshot.revision === 'number' && Number.isInteger(snapshot.revision) && snapshot.revision >= 0
634
642
  ? snapshot.revision
@@ -3,7 +3,7 @@
3
3
  var fs = require('node:fs/promises');
4
4
  var os = require('node:os');
5
5
  var path = require('node:path');
6
- var index = require('./index-BCXuTxAO.cjs');
6
+ var index = require('./index-It90_ScC.cjs');
7
7
  require('node:module');
8
8
  require('readline');
9
9
  require('os');
@@ -3,7 +3,7 @@
3
3
  var node_crypto = require('node:crypto');
4
4
  var fs = require('node:fs/promises');
5
5
  var path = require('node:path');
6
- var index = require('./index-BCXuTxAO.cjs');
6
+ var index = require('./index-It90_ScC.cjs');
7
7
  require('node:module');
8
8
  require('readline');
9
9
  require('os');
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index$2 = require('./index-BCXuTxAO.cjs');
3
+ var index$2 = require('./index-It90_ScC.cjs');
4
4
  var require$$0$3 = require('fs');
5
5
  var require$$0$2 = require('crypto');
6
6
  var require$$1$2 = require('path');
@@ -242,19 +242,19 @@ function requireArgument () {
242
242
 
243
243
  var command = {};
244
244
 
245
- const require$5 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-BCXuTxAO.cjs', document.baseURI).href)));
245
+ const require$5 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-It90_ScC.cjs', document.baseURI).href)));
246
246
  function __require$4() { return require$5("node:events"); }
247
247
 
248
- const require$4 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-BCXuTxAO.cjs', document.baseURI).href)));
248
+ const require$4 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-It90_ScC.cjs', document.baseURI).href)));
249
249
  function __require$3() { return require$4("node:child_process"); }
250
250
 
251
- const require$3 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-BCXuTxAO.cjs', document.baseURI).href)));
251
+ const require$3 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-It90_ScC.cjs', document.baseURI).href)));
252
252
  function __require$2() { return require$3("node:path"); }
253
253
 
254
- const require$2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-BCXuTxAO.cjs', document.baseURI).href)));
254
+ const require$2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-It90_ScC.cjs', document.baseURI).href)));
255
255
  function __require$1() { return require$2("node:fs"); }
256
256
 
257
- const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-BCXuTxAO.cjs', document.baseURI).href)));
257
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli-chunks/index-It90_ScC.cjs', document.baseURI).href)));
258
258
  function __require() { return require$1("node:process"); }
259
259
 
260
260
  var help = {};
@@ -17253,7 +17253,7 @@ async function inspectFeedbackLog(file, size) {
17253
17253
  return { mimeType: 'text/plain', width: 0, height: 0 };
17254
17254
  }
17255
17255
  async function createFeedbackCosClient(getToken) {
17256
- const { default: COS } = await Promise.resolve().then(function () { return require('./index-Cy_IlqkS.cjs'); }).then(function (n) { return n.index; });
17256
+ const { default: COS } = await Promise.resolve().then(function () { return require('./index-C696i2DY.cjs'); }).then(function (n) { return n.index; });
17257
17257
  const cos = new COS({
17258
17258
  getAuthorization(_options, callback) {
17259
17259
  void getToken().then((token) => callback({
@@ -20739,7 +20739,7 @@ function awaitWithSignal(work, signal) {
20739
20739
 
20740
20740
  /** 固定兼容版本;生产安装不声明 core 依赖,也不下载浏览器。 */
20741
20741
  const PREVIEW_PLAYWRIGHT_VERSION = '1.64.1';
20742
- const execFileAsync = node_util.promisify(childProcess.execFile);
20742
+ const execFileAsync$1 = node_util.promisify(childProcess.execFile);
20743
20743
  const pending = new Map();
20744
20744
  function previewDependencyDirectory(cacheRoot = process.env.HB_SDK_PREVIEW_CACHE_DIR ?? envPaths('hb-sdk', { suffix: '' }).cache) {
20745
20745
  return path.join(cacheRoot, 'preview', 'playwright-core', PREVIEW_PLAYWRIGHT_VERSION);
@@ -20884,7 +20884,7 @@ async function installPlaywright(directory) {
20884
20884
  ? path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js')
20885
20885
  : undefined;
20886
20886
  try {
20887
- await execFileAsync(npmCli ? process.execPath : 'npm', npmCli ? [npmCli, ...args] : args, {
20887
+ await execFileAsync$1(npmCli ? process.execPath : 'npm', npmCli ? [npmCli, ...args] : args, {
20888
20888
  cwd: directory,
20889
20889
  timeout: 120_000,
20890
20890
  maxBuffer: 1024 * 1024,
@@ -21935,7 +21935,7 @@ function installDevPreviewCommands(dev) {
21935
21935
  }
21936
21936
 
21937
21937
  const CLI_VERSION_PLACEHOLDER = ['__HB', 'SDK', 'CLI', 'VERSION__'].join('_');
21938
- const BUILT_CLI_VERSION = '0.9.6-alpha.8';
21938
+ const BUILT_CLI_VERSION = '0.9.6';
21939
21939
  const PACKAGE_JSON_CANDIDATES$1 = [
21940
21940
  path.resolve(__dirname, '..', '..', 'package.json'),
21941
21941
  path.resolve(__dirname, '..', 'package.json'),
@@ -21969,6 +21969,88 @@ function pathExists$1(filePath) {
21969
21969
  }
21970
21970
  }
21971
21971
 
21972
+ const execFileAsync = node_util.promisify(childProcess.execFile);
21973
+ let selfSnapshot;
21974
+ /** PID 可在退出或重启后复用;启动标识只用于比较,不保存进程命令行。 */
21975
+ async function readProcessIdentity(pid) {
21976
+ return (await readProcessSnapshot(pid))?.identity;
21977
+ }
21978
+ /** 查询失败时返回 unknown,由调用方保守保留登记,不能当作进程已退出。 */
21979
+ async function isProcessUsingProfile(pid, profile) {
21980
+ const snapshot = await readProcessSnapshot(pid);
21981
+ if (snapshot?.identity === null)
21982
+ return false;
21983
+ if (!snapshot?.command)
21984
+ return undefined;
21985
+ const argument = `--user-data-dir=${profile}`;
21986
+ const index = snapshot.command.indexOf(argument);
21987
+ // Linux 保留 argv 的 NUL 边界;ps/CIM 文本中的空格也可能是 profile 自身的一部分。
21988
+ const suffix = snapshot.command.slice(index + argument.length);
21989
+ return index >= 0 && (index === 0 || /[\s\0"']/.test(snapshot.command[index - 1])) &&
21990
+ /^(?:\0|$|["']$|["']?\s+(?:--|$))/.test(suffix);
21991
+ }
21992
+ function readProcessSnapshot(pid) {
21993
+ if (!Number.isSafeInteger(pid) || pid <= 0)
21994
+ return Promise.resolve(undefined);
21995
+ if (pid === process.pid)
21996
+ return selfSnapshot ??= queryProcessSnapshot(pid).then(snapshot => {
21997
+ if (!snapshot)
21998
+ selfSnapshot = undefined;
21999
+ return snapshot;
22000
+ });
22001
+ return queryProcessSnapshot(pid);
22002
+ }
22003
+ async function queryProcessSnapshot(pid) {
22004
+ try {
22005
+ let started;
22006
+ let command;
22007
+ if (process.platform === 'linux') {
22008
+ const [boot, status, args] = await Promise.all([
22009
+ fs$2.readFile('/proc/sys/kernel/random/boot_id', 'utf8'),
22010
+ fs$2.readFile(`/proc/${pid}/stat`, 'utf8'),
22011
+ fs$2.readFile(`/proc/${pid}/cmdline`, 'utf8'),
22012
+ ]);
22013
+ // comm 可包含空格或右括号;最后一个右括号之后从 state(第3字段)开始。
22014
+ const fields = status.slice(status.lastIndexOf(')') + 2).trim().split(/\s+/);
22015
+ if (fields[0] === 'Z' || fields[0] === 'X')
22016
+ return { identity: null };
22017
+ if (!/^\d+$/.test(fields[19] ?? ''))
22018
+ return undefined;
22019
+ started = `${boot.trim()}:${fields[19]}`;
22020
+ command = args;
22021
+ }
22022
+ else if (process.platform === 'win32') {
22023
+ // pid 已校验为正整数;不把 profile 或其它外部字符串拼入 PowerShell。
22024
+ const script = `[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); $p=Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if($p){[pscustomobject]@{started=$p.CreationDate.ToUniversalTime().ToString('o');command=$p.CommandLine}|ConvertTo-Json -Compress}`;
22025
+ const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
22026
+ timeout: 2500, maxBuffer: 64 * 1024, windowsHide: true, encoding: 'utf8',
22027
+ });
22028
+ const value = JSON.parse(stdout.replace(/^\uFEFF/, '').trim());
22029
+ if (!value || typeof value !== 'object' || !('started' in value) || typeof value.started !== 'string')
22030
+ return undefined;
22031
+ started = value.started;
22032
+ command = 'command' in value && typeof value.command === 'string' ? value.command : undefined;
22033
+ }
22034
+ else {
22035
+ const { stdout } = await execFileAsync('ps', ['-ww', '-p', String(pid), '-o', 'lstart=', '-o', 'command='], {
22036
+ timeout: 2500, maxBuffer: 64 * 1024, encoding: 'utf8', env: { ...process.env, LC_ALL: 'en_US.UTF-8' },
22037
+ });
22038
+ const match = /^(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+([\s\S]+)$/.exec(stdout.trim());
22039
+ if (!match)
22040
+ return undefined;
22041
+ started = match[1].replace(/\s+/g, ' ');
22042
+ command = match[2];
22043
+ }
22044
+ if (!started)
22045
+ return undefined;
22046
+ return { identity: node_crypto.createHash('sha256').update(started).digest('hex'), command };
22047
+ }
22048
+ catch {
22049
+ // 不把 ps / CIM 的原始命令行或 stderr 附到错误中,避免泄漏其他进程参数。
22050
+ return undefined;
22051
+ }
22052
+ }
22053
+
21972
22054
  const DEPLOY_LOCKED_MESSAGE = '当前设备已有同版本产物正在上传,请等待完成后重试';
21973
22055
  const DEPLOY_LOCK_DIRECTORY_NAME = 'deploy-locks';
21974
22056
  const DEPLOY_LOCK_OWNER_FILE = 'owner.json';
@@ -22009,6 +22091,7 @@ async function acquireLocalLock(lockDirectory, options) {
22009
22091
  version: 1,
22010
22092
  pid: options.pid ?? process.pid,
22011
22093
  token: options.token ?? node_crypto.randomBytes(16).toString('hex'),
22094
+ processIdentity: options.pid === undefined || options.pid === process.pid ? (await readProcessIdentity(process.pid)) ?? undefined : undefined,
22012
22095
  };
22013
22096
  await fs$2.mkdir(path.dirname(lockDirectory), { recursive: true, mode: 0o700 });
22014
22097
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -22027,10 +22110,12 @@ async function acquireLocalLock(lockDirectory, options) {
22027
22110
  if (!isNodeError(error) || error.code !== 'EEXIST') {
22028
22111
  throw error;
22029
22112
  }
22030
- if (!(await canReclaimDeployLock(lockDirectory, ownerFile, options))) {
22113
+ const generation = await reclaimableLockGeneration(lockDirectory, ownerFile, options);
22114
+ if (generation === undefined) {
22031
22115
  throw new DeployLockConflictError(DEPLOY_LOCKED_MESSAGE);
22032
22116
  }
22033
- await reclaimDeployLock(lockDirectory, owner.token);
22117
+ if (generation !== null)
22118
+ await reclaimDeployLock(lockDirectory, generation);
22034
22119
  }
22035
22120
  }
22036
22121
  throw new DeployLockConflictError(DEPLOY_LOCKED_MESSAGE);
@@ -22050,18 +22135,31 @@ function createDeployLock(lockDirectory, ownerFile, token) {
22050
22135
  },
22051
22136
  };
22052
22137
  }
22053
- async function canReclaimDeployLock(lockDirectory, ownerFile, options) {
22054
- const owner = await readDeployLockOwner(ownerFile);
22055
- if (owner) {
22056
- return !(options.isProcessRunning ?? isProcessRunning)(owner.pid);
22057
- }
22138
+ async function reclaimableLockGeneration(lockDirectory, ownerFile, options) {
22139
+ let info;
22058
22140
  try {
22059
- const lockStat = await fs$2.stat(lockDirectory);
22060
- return (options.now ?? Date.now)() - lockStat.mtimeMs >= INCOMPLETE_LOCK_GRACE_MS;
22141
+ info = await fs$2.stat(lockDirectory);
22061
22142
  }
22062
22143
  catch (error) {
22063
- return isNodeError(error) && error.code === 'ENOENT';
22144
+ if (isNodeError(error) && error.code === 'ENOENT')
22145
+ return null;
22146
+ throw error;
22064
22147
  }
22148
+ const owner = await readDeployLockOwner(ownerFile);
22149
+ if (owner) {
22150
+ if ((options.isProcessRunning ?? isProcessRunning)(owner.pid)) {
22151
+ if (options.isProcessRunning)
22152
+ return undefined;
22153
+ const identity = await readProcessIdentity(owner.pid);
22154
+ if (identity !== null && (!owner.processIdentity || identity === undefined || identity === owner.processIdentity))
22155
+ return undefined;
22156
+ }
22157
+ }
22158
+ else if ((options.now ?? Date.now)() - info.mtimeMs < INCOMPLETE_LOCK_GRACE_MS) {
22159
+ return undefined;
22160
+ }
22161
+ // 被回收目录会保留,因此其 inode 不会被下一代锁复用。
22162
+ return `${info.dev}:${info.ino}:${info.birthtimeMs}`;
22065
22163
  }
22066
22164
  async function removeOwnedLock(lockDirectory, ownerFile, token) {
22067
22165
  const owner = await readDeployLockOwner(ownerFile);
@@ -22069,17 +22167,31 @@ async function removeOwnedLock(lockDirectory, ownerFile, token) {
22069
22167
  await fs$2.rm(lockDirectory, { force: true, recursive: true });
22070
22168
  }
22071
22169
  }
22072
- async function reclaimDeployLock(lockDirectory, token) {
22073
- const reclaimDirectory = `${lockDirectory}.reclaim-${node_crypto.createHash('sha256').update(token).digest('hex')}`;
22170
+ async function reclaimDeployLock(lockDirectory, generation) {
22171
+ const reclaimDirectory = `${lockDirectory}.reclaim-${node_crypto.createHash('sha256').update(generation).digest('hex')}`;
22172
+ // 空的旧目录也须保持非空,避免 POSIX rename 覆盖空目标目录。
22173
+ try {
22174
+ await fs$2.writeFile(path.join(lockDirectory, '.reclaimed'), '1', { flag: 'wx', mode: 0o600 });
22175
+ }
22176
+ catch (error) {
22177
+ if (isNodeError(error) && error.code === 'ENOENT')
22178
+ return;
22179
+ if (!isNodeError(error) || error.code !== 'EEXIST')
22180
+ throw error;
22181
+ }
22074
22182
  try {
22075
22183
  await fs$2.rename(lockDirectory, reclaimDirectory);
22076
22184
  }
22077
22185
  catch (error) {
22078
22186
  if (isNodeError(error) && error.code === 'ENOENT')
22079
22187
  return;
22188
+ if (isNodeError(error) && ['EEXIST', 'ENOTEMPTY', 'EACCES', 'EPERM'].includes(error.code ?? '') &&
22189
+ await fs$2.stat(reclaimDirectory).then(info => info.isDirectory(), () => false))
22190
+ return;
22080
22191
  throw error;
22081
22192
  }
22082
- await fs$2.rm(reclaimDirectory, { force: true, recursive: true });
22193
+ // 同一旧代际共享固定、非空的目标,迟到的回收者无法把新锁移到这里。
22194
+ // 保留此目录作为回收凭证,不能在仍可能有迟到回收请求时删除。
22083
22195
  }
22084
22196
  async function readDeployLockOwner(ownerFile) {
22085
22197
  try {
@@ -22098,8 +22210,11 @@ function isDeployLockOwner(value) {
22098
22210
  return (typeof value === 'object' &&
22099
22211
  value !== null &&
22100
22212
  value.version === 1 &&
22101
- Number.isInteger(value.pid) &&
22102
- typeof value.token === 'string');
22213
+ Number.isSafeInteger(value.pid) &&
22214
+ Number(value.pid) > 0 &&
22215
+ typeof value.token === 'string' &&
22216
+ (value.processIdentity === undefined ||
22217
+ typeof value.processIdentity === 'string' && /^[a-f0-9]{64}$/.test(value.processIdentity)));
22103
22218
  }
22104
22219
  function isProcessRunning(pid) {
22105
22220
  try {
@@ -22898,21 +23013,38 @@ function createCliProgram(overrides = {}) {
22898
23013
  // 公告获取或展示失败不能阻断命令;交互环境判断由展示模块统一执行。
22899
23014
  }
22900
23015
  });
22901
- addVerboseOption(program.command('create').description('创建外部小程序项目开发模板').argument('<project-name>', '项目目录名,例如 my-miniapp')).action(withUpdateReminder(async (projectName, _options, command) => {
23016
+ addVerboseOption(program
23017
+ .command('create')
23018
+ .description('创建外部小程序项目开发模板')
23019
+ .argument('<project-name>', '项目目录名,例如 my-miniapp')
23020
+ .option('--game <game>', '声明游戏资料的游戏,可重复或逗号分隔:ark、black_myth_wukong、task_bar_hero、phantom_blade_zero', collectRepeatableOption, [])
23021
+ .option('--features <features>', '该游戏的功能,可重复或逗号分隔:profile、gacha、save_analysis、save_files', collectRepeatableOption, [])
23022
+ .option('--resources <resourceKey>', '精确资源 key,可重复或逗号分隔;不接受通配符或前缀', collectRepeatableOption, [])
23023
+ .option('--purpose <purpose>', '所选游戏资料的实际用途,必填 1~30 个 Unicode 码点')).action(withUpdateReminder(async (projectName, options, command) => {
22902
23024
  const logger = resolveLogger(command);
22903
- await handlers.runCreateCommand(projectName, { logger });
23025
+ await handlers.runCreateCommand(projectName, {
23026
+ features: readStringListOption(options.features),
23027
+ games: readStringListOption(options.game),
23028
+ logger,
23029
+ resources: readStringListOption(options.resources),
23030
+ purpose: options.purpose,
23031
+ });
22904
23032
  }, handlers.printUpdateReminder, resolveLogger));
22905
23033
  addVerboseOption(program
22906
23034
  .command('dev')
22907
23035
  .description('启动当前小程序项目的 Vite 开发服务器和浏览器调试页服务')
22908
23036
  .addOption(new Option('--browser <browser>', '预览使用的本机浏览器').choices(['chrome', 'edge']))
22909
- .addOption(new Option('--browser-mode <mode>', '默认 auto:优先请求日常浏览器授权后回退;isolated 直接使用临时独立环境').choices(['auto', 'isolated']))
23037
+ .addOption(new Option('--browser-mode <mode>', '默认 auto:复用项目独立浏览器,否则请求日常浏览器授权后回退;isolated 使用独立环境').choices(['auto', 'isolated']))
22910
23038
  .option('--port <port>', '小程序开发服务器端口', parsePositivePort)
22911
23039
  .option('--browser-dev-host-port <port>', '浏览器调试页服务端口', parsePositivePort)
22912
23040
  .option('--no-open', '不自动打开浏览器调试页')
22913
23041
  .option('--no-hmr', '关闭热更新,默认遵循项目的 Vite 配置')
23042
+ .option('--service-tag <tag>', '给 Heybox 后台请求附加 x-rylai-service-tag,默认读取 HB_SDK_SERVICE_TAG')
22914
23043
  .helpOption('-h, --help', '显示命令帮助')).action(withUpdateReminder(async (options, command) => {
22915
23044
  const logger = resolveLogger(command);
23045
+ // dev 需要与 remote 相同的小程序后台 tag 路由:读取远端权限、签发本地调试凭证都走
23046
+ // /mall/developer/user_miniprogram/ 前缀。没传时沿用 HB_SDK_SERVICE_TAG。
23047
+ applyDevServiceTag(options?.serviceTag);
22916
23048
  await handlers.runDevCommand(options, { logger });
22917
23049
  }, handlers.printUpdateReminder, resolveLogger));
22918
23050
  installDevToolCommands(program.commands.find(command => command.name() === 'dev'));
@@ -23035,7 +23167,7 @@ function installRemoteCommands(program, handlers, resolveLogger) {
23035
23167
  const permission = addRemotePublicOptions(remote.command('permission').description('申请平台权限并查看审核状态'));
23036
23168
  addRemotePublicOptions(permission.command('list').description('查看平台权限及最近申请状态')).action(createRemoteAction(handlers, resolveLogger, 'permission:list'));
23037
23169
  addRemotePublicOptions(permission.command('apply').description('提交平台权限申请')
23038
- .argument('<key>', 'network、companion 或 appProtocol')
23170
+ .argument('<key>', 'network、companion 或 appProtocol;user_game_data 是声明型权限,无需申请')
23039
23171
  .requiredOption('--reason <text>', '申请理由,不超过 500 字')
23040
23172
  .option('--domains <domains>', 'network 访问域名,多个用逗号分隔')).action(createRemoteAction(handlers, resolveLogger, 'permission:apply', (command, key) => {
23041
23173
  const options = readCommandOptionsWithAncestors(command);
@@ -23172,6 +23304,16 @@ function pickOptions(command, keys) {
23172
23304
  function readStringOption(value) {
23173
23305
  return typeof value === 'string' ? value : undefined;
23174
23306
  }
23307
+ /** 收集可重复选项;重复出现时按出现顺序累加,逗号拆分交给 create 的声明校验统一处理。 */
23308
+ function collectRepeatableOption(value, previous) {
23309
+ return [...previous, value];
23310
+ }
23311
+ function readStringListOption(value) {
23312
+ if (!Array.isArray(value))
23313
+ return undefined;
23314
+ const items = value.filter((item) => typeof item === 'string');
23315
+ return items.length > 0 ? items : undefined;
23316
+ }
23175
23317
  function readStringArgument(value, name) {
23176
23318
  if (typeof value !== 'string') {
23177
23319
  throw new Error(`无法解析 ${name} 参数`);
@@ -23204,39 +23346,39 @@ function createCommandLoggerResolver(options) {
23204
23346
  };
23205
23347
  }
23206
23348
  const defaultClearLoginStatus = async (...args) => {
23207
- const { clearLoginStatus } = await Promise.resolve().then(function () { return require('./login-DzlRTbfT.cjs'); });
23349
+ const { clearLoginStatus } = await Promise.resolve().then(function () { return require('./login-BGJz7JZV.cjs'); });
23208
23350
  return clearLoginStatus(...args);
23209
23351
  };
23210
23352
  const defaultLoginToHeybox = async (...args) => {
23211
- const { loginToHeybox } = await Promise.resolve().then(function () { return require('./login-DzlRTbfT.cjs'); });
23353
+ const { loginToHeybox } = await Promise.resolve().then(function () { return require('./login-BGJz7JZV.cjs'); });
23212
23354
  return loginToHeybox(...args);
23213
23355
  };
23214
23356
  const defaultPrintLoginStatus = async (...args) => {
23215
- const { printLoginStatus } = await Promise.resolve().then(function () { return require('./login-DzlRTbfT.cjs'); });
23357
+ const { printLoginStatus } = await Promise.resolve().then(function () { return require('./login-BGJz7JZV.cjs'); });
23216
23358
  return printLoginStatus(...args);
23217
23359
  };
23218
23360
  const defaultRunBuildCommand = async (...args) => {
23219
- const { runBuildCommand } = await Promise.resolve().then(function () { return require('./build-Dfmx31Pu.cjs'); });
23361
+ const { runBuildCommand } = await Promise.resolve().then(function () { return require('./build-fyHfi216.cjs'); });
23220
23362
  return runBuildCommand(...args);
23221
23363
  };
23222
23364
  const defaultRunCreateCommand = async (...args) => {
23223
- const { runCreateCommand } = await Promise.resolve().then(function () { return require('./create-C9vj2WPs.cjs'); });
23365
+ const { runCreateCommand } = await Promise.resolve().then(function () { return require('./create-B-EnCHjU.cjs'); });
23224
23366
  return runCreateCommand(...args);
23225
23367
  };
23226
23368
  const defaultRunDevCommand = async (...args) => {
23227
- const { runDevCommand } = await Promise.resolve().then(function () { return require('./dev-CbvQhSfw.cjs'); }).then(function (n) { return n.dev; });
23369
+ const { runDevCommand } = await Promise.resolve().then(function () { return require('./dev-Zb0pMdzr.cjs'); }).then(function (n) { return n.dev; });
23228
23370
  return runDevCommand(...args);
23229
23371
  };
23230
23372
  const defaultRunDoctorCommand = async (...args) => {
23231
- const { runDoctorCommand } = await Promise.resolve().then(function () { return require('./doctor-49h9U79a.cjs'); });
23373
+ const { runDoctorCommand } = await Promise.resolve().then(function () { return require('./doctor-DmkHu1Hk.cjs'); });
23232
23374
  return runDoctorCommand(...args);
23233
23375
  };
23234
23376
  const defaultRunSkillInstallCommand = async (...args) => {
23235
- const { runSkillInstallCommand } = await Promise.resolve().then(function () { return require('./skill-XkW3Tj0X.cjs'); });
23377
+ const { runSkillInstallCommand } = await Promise.resolve().then(function () { return require('./skill-D6ebJn5J.cjs'); });
23236
23378
  return runSkillInstallCommand(...args);
23237
23379
  };
23238
23380
  const defaultRunRemoteCommand = async (...args) => {
23239
- const { runRemoteCommand } = await Promise.resolve().then(function () { return require('./remote-Cho-39Vd.cjs'); });
23381
+ const { runRemoteCommand } = await Promise.resolve().then(function () { return require('./remote-D9-2nonN.cjs'); });
23240
23382
  return runRemoteCommand(...args);
23241
23383
  };
23242
23384
  function resolveStandaloneLogger(options, verbose) {
@@ -23309,6 +23451,9 @@ function readCommandFromActionArgs(args) {
23309
23451
  */
23310
23452
  function preloadCliEnvPreset(argv, options = {}) {
23311
23453
  const result = loadEnvPreset(argv);
23454
+ // HB_SDK_SERVICE_TAG 可能在 --env 预设之外单独设置;它必须对 dev/remote 等命令生效,
23455
+ // 因此先应用,再在缺少预设文件时提前返回。
23456
+ applyServiceTagIfNeeded(process.env.HB_SDK_SERVICE_TAG);
23312
23457
  if (!result.filePath) {
23313
23458
  return;
23314
23459
  }
@@ -23321,6 +23466,29 @@ function preloadCliEnvPreset(argv, options = {}) {
23321
23466
  }
23322
23467
  applyServiceTagIfNeeded(process.env.HB_SDK_SERVICE_TAG);
23323
23468
  }
23469
+ /**
23470
+ * `hb-sdk dev` 的 service tag 路由。
23471
+ *
23472
+ * @remarks
23473
+ * 小程序后台(`/mall/developer/user_miniprogram/`)使用 special_tag,仅对该前缀附加
23474
+ * `x-rylai-service-tag`;同时设置全局 default_tag,便于把公开接口也定向到同 tag 实例。
23475
+ * 未传 tag 时不改动已有配置(可能来自 `HB_SDK_SERVICE_TAG`)。
23476
+ */
23477
+ function applyDevServiceTag(tag) {
23478
+ if (typeof tag !== 'string' || !tag.trim())
23479
+ return;
23480
+ const normalized = tag.trim();
23481
+ if (/[\r\n]/.test(normalized))
23482
+ throw new Error('x-rylai-service-tag 不允许包含换行符');
23483
+ // 一次写入:两个 apply 辅助函数会互相覆盖(各自只设置自己的字段),dev 需要同时设置。
23484
+ configureHeyboxCliRequestConfig({
23485
+ default_tag: normalized,
23486
+ special_tag: {
23487
+ tag_name: normalized,
23488
+ path_prefix_list: ['/mall/developer/user_miniprogram/'],
23489
+ },
23490
+ });
23491
+ }
23324
23492
  function parsePositivePort(value) {
23325
23493
  const parsed = Number(value);
23326
23494
  if (!Number.isInteger(parsed) || parsed <= 0) {
@@ -23336,7 +23504,7 @@ function parseNonNegativeInteger(value) {
23336
23504
  return parsed;
23337
23505
  }
23338
23506
  const defaultRunGameSearchCommand = async (...args) => {
23339
- const { runGameSearchCommand } = await Promise.resolve().then(function () { return require('./games-CoT7KYEe.cjs'); });
23507
+ const { runGameSearchCommand } = await Promise.resolve().then(function () { return require('./games-CeCLFeTt.cjs'); });
23340
23508
  return runGameSearchCommand(...args);
23341
23509
  };
23342
23510
 
@@ -23349,10 +23517,12 @@ exports.DEV_DIAGNOSTICS_SCHEMA_VERSION = DEV_DIAGNOSTICS_SCHEMA_VERSION;
23349
23517
  exports.DEV_PRESENTATION_MAX_INTERACTIONS = DEV_PRESENTATION_MAX_INTERACTIONS;
23350
23518
  exports.DEV_RESOURCE_PATH = DEV_RESOURCE_PATH;
23351
23519
  exports.DEV_SANDBOX_READ_MAX_BYTES = DEV_SANDBOX_READ_MAX_BYTES;
23520
+ exports.DeployLockConflictError = DeployLockConflictError;
23352
23521
  exports.HB_SDK_PACKAGE_NAME = HB_SDK_PACKAGE_NAME;
23353
23522
  exports.HB_SDK_SKILL_NAME = HB_SDK_SKILL_NAME;
23354
23523
  exports.PREVIEW_SELECTORS = PREVIEW_SELECTORS;
23355
23524
  exports.acquireDeployLock = acquireDeployLock;
23525
+ exports.acquireLocalFileLock = acquireLocalFileLock;
23356
23526
  exports.acquirePreviewFocus = acquirePreviewFocus;
23357
23527
  exports.applyMiniProgramServiceTagIfNeeded = applyMiniProgramServiceTagIfNeeded;
23358
23528
  exports.awaitWithSignal = awaitWithSignal;
@@ -23375,6 +23545,7 @@ exports.getCDNUploadToken = getCDNUploadToken;
23375
23545
  exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
23376
23546
  exports.getPreviewPlaywrightStatus = getPreviewPlaywrightStatus;
23377
23547
  exports.isPreviewDocumentUrl = isPreviewDocumentUrl;
23548
+ exports.isProcessUsingProfile = isProcessUsingProfile;
23378
23549
  exports.isRecord = isRecord$1;
23379
23550
  exports.listPreviewSelections = listPreviewSelections;
23380
23551
  exports.loadPreviewPlaywright = loadPreviewPlaywright;
@@ -23384,6 +23555,7 @@ exports.readCliRateLimitState = readCliRateLimitState;
23384
23555
  exports.readErrorMessage = readErrorMessage;
23385
23556
  exports.readHeyboxApiEnvelope = readHeyboxApiEnvelope;
23386
23557
  exports.readHeyboxAuthSession = readHeyboxAuthSession;
23558
+ exports.readProcessIdentity = readProcessIdentity;
23387
23559
  exports.readRedactedErrorMessage = readRedactedErrorMessage;
23388
23560
  exports.readRedactedHeyboxAuthStatus = readRedactedHeyboxAuthStatus;
23389
23561
  exports.registerDevHost = registerDevHost;