@ttmg/cli 0.4.6-vibe-beta.23 → 0.4.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 (73) hide show
  1. package/CHANGELOG.md +57 -1
  2. package/README.md +56 -19
  3. package/dist/index.js +819 -220
  4. package/dist/index.js.map +1 -1
  5. package/dist/package.json +8 -4
  6. package/dist/public/assets/{Card-CN2lxY0Y.js → Card-D4FjfZC9.js} +1 -1
  7. package/dist/public/assets/{Detail-CELZZ-4h.js → Detail-m3nH8XXe.js} +1 -1
  8. package/dist/public/assets/Detail-m3nH8XXe.js.br +0 -0
  9. package/dist/public/assets/{MonetizationMode-C7DNqium.js → MonetizationMode-1rShmN0o.js} +1 -1
  10. package/dist/public/assets/{MonetizationModeSummary-DYE7XUq1.js → MonetizationModeSummary-CVfWOth1.js} +1 -1
  11. package/dist/public/assets/{SectionHeader-BKc3BWXP.js → SectionHeader-CAuUcT9Q.js} +1 -1
  12. package/dist/public/assets/{baseForm-I9suIiQn.js → baseForm-C3PqJ30b.js} +1 -1
  13. package/dist/public/assets/baseForm-C3PqJ30b.js.br +0 -0
  14. package/dist/public/assets/{col-w9Q-2mgM.js → col-CcZ10DdH.js} +1 -1
  15. package/dist/public/assets/{compass-D6waJ52O.js → compass-H7uPUHxP.js} +1 -1
  16. package/dist/public/assets/{index-mjEeEQcC.js → index-B0xVTiB7.js} +1 -1
  17. package/dist/public/assets/index-B0xVTiB7.js.br +0 -0
  18. package/dist/public/assets/{index-CgXOkYrX.js → index-BAbIp3cP.js} +1 -1
  19. package/dist/public/assets/index-BAbIp3cP.js.br +0 -0
  20. package/dist/public/assets/{index-DDecPuod.js → index-BESASZaa.js} +1 -1
  21. package/dist/public/assets/{index-YVB9ZW00.js → index-BIZgIFOe.js} +1 -1
  22. package/dist/public/assets/{index-BIrFkB6r.js → index-BX17swkm.js} +1 -1
  23. package/dist/public/assets/index-BX17swkm.js.br +0 -0
  24. package/dist/public/assets/{index-BqwflQml.js → index-Bbsc4UYr.js} +1 -1
  25. package/dist/public/assets/{index-B6hY5GdS.js → index-BhswTE7o.js} +1 -1
  26. package/dist/public/assets/{index-DGkgqtgJ.js → index-BntW17GH.js} +1 -1
  27. package/dist/public/assets/{index-BY3eQmfP.js → index-BswJGTPK.js} +1 -1
  28. package/dist/public/assets/index-BswJGTPK.js.br +0 -0
  29. package/dist/public/assets/{index-BvPolBSn.js → index-CCX74BCm.js} +1 -1
  30. package/dist/public/assets/{index-Q0GC8Irj.js → index-CQ3yj6IA.js} +1 -1
  31. package/dist/public/assets/index-CQ3yj6IA.js.br +0 -0
  32. package/dist/public/assets/{index-Csmg5oyu.js → index-CRqInRg3.js} +1 -1
  33. package/dist/public/assets/{index-BegU9LBT.js → index-C_G_C9eS.js} +10 -10
  34. package/dist/public/assets/index-C_G_C9eS.js.br +0 -0
  35. package/dist/public/assets/{index-rLkONFpx.js → index-CqDAcAbN.js} +1 -1
  36. package/dist/public/assets/{index-Cb4Ja0tZ.js → index-CrRxN4us.js} +1 -1
  37. package/dist/public/assets/{index-CcUgN29Y.js → index-CyDpw03-.js} +1 -1
  38. package/dist/public/assets/{index-BrOFdVbv.js → index-D8BnlF58.js} +1 -1
  39. package/dist/public/assets/{index-DDy4PkWT.js → index-DAY6FKtH.js} +1 -1
  40. package/dist/public/assets/{index-CsiIrLKY.js → index-DKcAZ6VY.js} +1 -1
  41. package/dist/public/assets/{index-M8jf-YAZ.js → index-DS5Uafh7.js} +1 -1
  42. package/dist/public/assets/{index-FVHabbDB.js → index-DdxoW9oQ.js} +1 -1
  43. package/dist/public/assets/{index-CLKKui8G.js → index-O0yoYI51.js} +1 -1
  44. package/dist/public/assets/{index-DEQ2hVPA.js → index-aQ98LrVv.js} +1 -1
  45. package/dist/public/assets/index-aQ98LrVv.js.br +0 -0
  46. package/dist/public/assets/{index-8sDAOAcS.js → index-ivwHgxUB.js} +1 -1
  47. package/dist/public/assets/index-ivwHgxUB.js.br +0 -0
  48. package/dist/public/assets/{index-BwrZjkCc.js → index-sIdIkg5O.js} +1 -1
  49. package/dist/public/assets/{index-BLWgpW64.js → index-wTaBRIal.js} +1 -1
  50. package/dist/public/assets/{layers-Dbwq9AyL.js → layers-Bw-W5e-K.js} +1 -1
  51. package/dist/public/assets/{list-checks-og1usOZf.js → list-checks-ClFMgLBy.js} +1 -1
  52. package/dist/public/assets/{sparkles-p-dZbjGb.js → sparkles-JXa7CZhS.js} +1 -1
  53. package/dist/public/assets/{triangle-alert-BZVAEUiL.js → triangle-alert--wDqk97a.js} +1 -1
  54. package/dist/public/assets/{zap-BAhZUPPa.js → zap-D27jUGUv.js} +1 -1
  55. package/dist/public/index.html +1 -1
  56. package/dist/scripts/dev-remote-resources-smoke.js +80 -0
  57. package/dist/scripts/remoteResources.js +54 -0
  58. package/dist/scripts/verify-agent-contract.js +28 -0
  59. package/dist/scripts/vibe-upload-smoke.js +19 -3
  60. package/dist/scripts/wasm-collect-smoke.js +8 -2
  61. package/dist/scripts/worker.js +5 -1
  62. package/package.json +8 -4
  63. package/vibe-upload.md +26 -15
  64. package/dist/public/assets/Detail-CELZZ-4h.js.br +0 -0
  65. package/dist/public/assets/baseForm-I9suIiQn.js.br +0 -0
  66. package/dist/public/assets/index-8sDAOAcS.js.br +0 -0
  67. package/dist/public/assets/index-BIrFkB6r.js.br +0 -0
  68. package/dist/public/assets/index-BY3eQmfP.js.br +0 -0
  69. package/dist/public/assets/index-BegU9LBT.js.br +0 -0
  70. package/dist/public/assets/index-CgXOkYrX.js.br +0 -0
  71. package/dist/public/assets/index-DEQ2hVPA.js.br +0 -0
  72. package/dist/public/assets/index-Q0GC8Irj.js.br +0 -0
  73. package/dist/public/assets/index-mjEeEQcC.js.br +0 -0
package/dist/index.js CHANGED
@@ -44,8 +44,8 @@ var got = require('got');
44
44
  var ttmgPack = require('ttmg-pack');
45
45
  var expressStaticGzip = require('express-static-gzip');
46
46
  var fileUpload = require('express-fileupload');
47
- var crypto$1 = require('node:crypto');
48
47
  var fs$1 = require('node:fs');
48
+ var crypto$1 = require('node:crypto');
49
49
  var zlib = require('zlib');
50
50
  var promises$1 = require('fs/promises');
51
51
  var os$1 = require('node:os');
@@ -6621,20 +6621,17 @@ function verboseWarn(...args) {
6621
6621
  console.warn(...args);
6622
6622
  }
6623
6623
 
6624
- /**
6625
- * PPE / 测试环境开关。
6626
- *
6627
- * 除登录和本地客户端请求外,CLI 后端接口(`stark_wasm/v4/*`,
6628
- * `wasm-collect/v1/*`, portal 业务接口等)都共用本文件的 `request()`,
6629
- * 所以在这里统一注入 PPE header 就能覆盖主要平台请求。
6630
- * 不在 `DEV_HEADERS` 里改是因为那份常量只被 `remotePipeline.ts` 里的老
6631
- * 远程分包接口 spread 用;新加的 `startSession.ts` / `finishSession.ts` /
6632
- * `getCollectedFuncIds.ts` 都没 spread,漏一处就会绕开 PPE。
6633
- *
6634
- * 要切回线上环境,直接把 `CLI_PPE_ENV` 设成空串即可(下方条件 spread 会
6635
- * 自动不带这两个 header)。
6636
- */
6637
- const CLI_PPE_ENV = 'ppe_role_perm'; // 走权限体系 PPE 环境
6624
+ // Ordinary platform requests use production unless a developer explicitly
6625
+ // selects a PPE lane. Vibe's opt-in trial supplies its own per-request headers.
6626
+ function getPlatformEnvironmentHeaders() {
6627
+ const lane = process.env.TTMG_PPE_ENV?.trim();
6628
+ if (!lane)
6629
+ return {};
6630
+ if (!/^ppe_[a-zA-Z0-9_-]{1,64}$/.test(lane)) {
6631
+ throw new Error('TTMG_PPE_ENV must be a PPE lane such as ppe_example');
6632
+ }
6633
+ return { 'x-use-ppe': '1', 'x-tt-env': lane };
6634
+ }
6638
6635
  const NETWORK_PROXY_ERROR_CODE = -1001;
6639
6636
  function getAxiosProxyConfig() {
6640
6637
  const config = getTTMGRC();
@@ -6781,6 +6778,7 @@ function printApiResponseLog(title, result) {
6781
6778
  ]);
6782
6779
  }
6783
6780
  async function request({ url, method, data, headers, params, logRequestBody = true, logApiCalls = true, signal, }) {
6781
+ const environmentHeaders = getPlatformEnvironmentHeaders();
6784
6782
  const config = getTTMGRC();
6785
6783
  const cookie = sanitizeCookieHeader(config?.cookie);
6786
6784
  const proxyConfig = getAxiosProxyConfig();
@@ -6802,11 +6800,7 @@ async function request({ url, method, data, headers, params, logRequestBody = tr
6802
6800
  signal,
6803
6801
  headers: {
6804
6802
  Cookie: cookie,
6805
- // 注入 PPE header — 放在 caller headers 之前,允许单个调用点通过
6806
- // 显式传 `x-tt-env` 来覆盖本次请求(例如某个接口还没在 PPE 上发布)。
6807
- ...(CLI_PPE_ENV
6808
- ? { 'x-use-ppe': '1', 'x-tt-env': CLI_PPE_ENV }
6809
- : {}),
6803
+ ...environmentHeaders,
6810
6804
  ...(headers || {}),
6811
6805
  },
6812
6806
  ...proxyConfig,
@@ -7248,6 +7242,7 @@ const messages = {
7248
7242
  'cli.command.game.categories.category': 'Filter by an exact category value, e.g. Puzzle',
7249
7243
  'cli.command.game.categories.unknown': 'Unknown category. Run ttmg game categories --format json for valid values.',
7250
7244
  'cli.command.game.categories.invalidFormat': 'Use text, json, or ndjson output.',
7245
+ 'cli.command.upload.minisType': 'MINI_GAME (default) or MINI_TOOL (local PPE trial; Native ZIP, Efficiency & Office)',
7251
7246
  'cli.command.upload.vibeCategory': 'Optional game category; provide with --subcategory (--vibe). Query ttmg game categories --format json',
7252
7247
  'cli.command.upload.vibeDescription': 'Optional game description (--vibe); default: Discover the fun of TikTok Mini Games.',
7253
7248
  'cli.command.upload.vibeSubcategory': 'Optional subcategory belonging to --category; omit both to keep Other/Other (--vibe)',
@@ -7263,8 +7258,9 @@ Vibe QR upload (real PPE trial):
7263
7258
  Keep this process running. At waiting_authorization, scan the QR on pageUrl with TikTok on your phone.
7264
7259
  pageUrl is the local QR/progress page on the CLI computer. Reopen it with authorizationOpenCommand.
7265
7260
  The CLI polls and uploads avatar, app_info and package automatically after authorization. Do not start a second upload.
7266
- After upload, waiting_preview keeps polling the same task until previewUrl is available; pageUrl then shows the game preview QR.
7267
- Preview ready: previewReady=true and qrPurpose=game_preview. A preview timeout preserves uploaded=true; check the task, do not reupload.
7261
+ After upload, waiting_preview keeps polling the same task until previewUrl is available, including status 9 (waiting for review submission).
7262
+ When previewReady=true, pageUrl keeps the original QR on the left for checking progress and shows the preview QR on the right. qrPurpose is game_preview or tool_preview. A preview timeout preserves uploaded=true; do not reupload.
7263
+ The operation timeout defaults to 1800 seconds (maximum 3600). The page stays available during the operation and for 30 minutes after the CLI finishes.
7268
7264
  Real success: terminal=true, status=uploaded, uploaded=true, simulation=false. On failure, read errorCode and nextAction.
7269
7265
  The local QR page opens for every output format; --no-open disables automatic opening.
7270
7266
  The page displays the submitted title, icon, description, category and subcategory.
@@ -7483,7 +7479,7 @@ Vibe QR upload (real PPE trial):
7483
7479
  'cli.command.upload.vibeApi': 'Minis Import API origin on a loopback IP only (--vibe)',
7484
7480
  'cli.command.upload.vibeAuthorizeUrl': 'Obsolete: remove this option; task creation returns landing_url (--vibe)',
7485
7481
  'cli.command.upload.vibePollInterval': 'Override task polling interval; otherwise use poll_interval_seconds (--vibe)',
7486
- 'cli.command.upload.vibeTimeout': 'Operation timeout in seconds (--vibe; default 300)',
7482
+ 'cli.command.upload.vibeTimeout': 'Operation timeout in seconds (--vibe; default 1800, maximum 3600)',
7487
7483
  'cli.command.upload.vibeRequired': 'These options require --vibe; the existing platform upload has not been executed.',
7488
7484
  'cli.command.testAccount.desc': 'Manage Mini Game test-account access',
7489
7485
  'cli.command.testAccount.add.desc': 'Generate the authorization entry for adding a TikTok test account',
@@ -7698,6 +7694,7 @@ Vibe QR upload (real PPE trial):
7698
7694
  'cli.command.game.categories.category': '按类型的精确值筛选,例如 Puzzle',
7699
7695
  'cli.command.game.categories.unknown': '类型不存在。使用 ttmg game categories --format json 查询有效值。',
7700
7696
  'cli.command.game.categories.invalidFormat': '输出格式请使用 text、json 或 ndjson。',
7697
+ 'cli.command.upload.minisType': 'MINI_GAME(默认)或 MINI_TOOL(本地 PPE 试用;Native ZIP、效率办公类)',
7701
7698
  'cli.command.upload.vibeCategory': '可选游戏类型,须与 --subcategory 同传(--vibe);用 ttmg game categories --format json 查询',
7702
7699
  'cli.command.upload.vibeDescription': '可选游戏描述(--vibe);默认值:Discover the fun of TikTok Mini Games.',
7703
7700
  'cli.command.upload.vibeSubcategory': '所属类型的可选子类型;两者均不传保留 Other/Other(--vibe)',
@@ -7713,8 +7710,9 @@ Vibe 扫码上传(真实 PPE 试用):
7713
7710
  保持原进程运行。在 waiting_authorization 阶段,使用手机 TikTok 扫描 pageUrl 页面中的二维码。
7714
7711
  pageUrl 是 CLI 所在电脑的二维码/进度页;重新打开时,执行返回的 authorizationOpenCommand。
7715
7712
  CLI 负责轮询,授权后自动上传 avatar、app_info、package,不再启动第二次上传。
7716
- 上传后进入 waiting_preview,继续查询同一任务;拿到 previewUrl 后,原 pageUrl 页面展示游戏预览二维码。
7717
- previewReady=true 且 qrPurpose=game_preview 表示可扫码预览;等待超时仍保留 uploaded=true,请核对任务,不要重传。
7713
+ 上传成功后 waiting_preview 继续查询同一任务直到取得 previewUrl,包括状态 9(等待提交代码审核)。
7714
+ previewReady=true 时,pageUrl 左侧保留原码用于查看进度,右侧显示预览码;qrPurpose 为 game_preview 或 tool_preview。等待超时仍保留 uploaded=true,请核对任务,不要重传。
7715
+ 整体超时默认 1800 秒,最大 3600 秒;页面在任务进行中保持可用,CLI 结束后再保留 30 分钟。
7718
7716
  真实成功:terminal=true、status=uploaded、uploaded=true、simulation=false。失败时读取 errorCode 和 nextAction。
7719
7717
  所有输出格式都会打开本地二维码页;--no-open 可关闭自动打开。
7720
7718
  页面展示本次提交的标题、头像、描述、类型和子类型。
@@ -7933,7 +7931,7 @@ Vibe 扫码上传(真实 PPE 试用):
7933
7931
  'cli.command.upload.vibeApi': 'Minis Import 接口地址,仅接受回环 IP(--vibe)',
7934
7932
  'cli.command.upload.vibeAuthorizeUrl': '已废弃,请移除此参数;授权地址由创建任务返回(--vibe)',
7935
7933
  'cli.command.upload.vibePollInterval': '覆盖 task 轮询间隔;默认使用接口 poll_interval_seconds(--vibe)',
7936
- 'cli.command.upload.vibeTimeout': '操作超时秒数(--vibe,默认 300)',
7934
+ 'cli.command.upload.vibeTimeout': '操作超时秒数(--vibe,默认 1800,最大 3600)',
7937
7935
  'cli.command.upload.vibeRequired': '这些参数需要 --vibe;没有执行原有平台上传。',
7938
7936
  'cli.command.testAccount.desc': '管理小游戏测试账号访问',
7939
7937
  'cli.command.testAccount.add.desc': '生成添加 TikTok 测试账号的授权入口',
@@ -16382,7 +16380,7 @@ async function authStatus(options = {}) {
16382
16380
  return result;
16383
16381
  }
16384
16382
 
16385
- var version = "0.4.6-vibe-beta.23";
16383
+ var version = "0.4.6";
16386
16384
  var engines = {
16387
16385
  node: ">=20.19.1 <21 || >=22"
16388
16386
  };
@@ -16405,6 +16403,23 @@ const VIBE_INPUT_REQUIREMENTS = {
16405
16403
  categoryPairRequiredWhenProvided: true,
16406
16404
  defaultCategory: { category: 'Other', subcategory: 'Other' },
16407
16405
  };
16406
+ const VIBE_TOOL_INPUT_REQUIREMENTS = {
16407
+ ...VIBE_INPUT_REQUIREMENTS,
16408
+ defaultMetadataProfile: 'ppe-tool-trial',
16409
+ optionalSkillInputs: ['description', 'minisType'],
16410
+ defaultDescription: 'A simple productivity tool for everyday tasks.',
16411
+ categoryQuery: undefined,
16412
+ categoryPairRequiredWhenProvided: false,
16413
+ defaultCategory: { category: 'EFFICIENCY_AND_OFFICE', subcategory: '' },
16414
+ region: 'US', minSDKVersion: '1.0.0',
16415
+ };
16416
+ function resolveMinisType(value) {
16417
+ if (value === undefined)
16418
+ return 'MINI_GAME';
16419
+ if (value !== 'MINI_GAME' && value !== 'MINI_TOOL')
16420
+ throw new VibeError('VIBE_INVALID_MINIS_TYPE');
16421
+ return value;
16422
+ }
16408
16423
  class VibeError extends Error {
16409
16424
  constructor(code) {
16410
16425
  super(code);
@@ -17142,6 +17157,10 @@ function getCapabilities() {
17142
17157
  networkRequired: false,
17143
17158
  },
17144
17159
  vibeUpload: {
17160
+ minisType: {
17161
+ option: '--minis-type', default: 'MINI_GAME', values: ['MINI_GAME', 'MINI_TOOL'],
17162
+ tool: { readiness: 'local-ppe-trial', deviceVerified: false, category: 'EFFICIENCY_AND_OFFICE', region: 'US', minSDKVersion: '1.0.0', assetType: 'NativeRuntime', metadataOverrides: false },
17163
+ },
17145
17164
  command: 'ttmg upload --vibe --dir <gameDir> --title <title> --icon <iconPath> --format ndjson',
17146
17165
  mockCommand: 'ttmg upload --vibe --mock --dir <gameDir> --title <title> --icon <iconPath> --format ndjson',
17147
17166
  guide: 'vibe-upload.md',
@@ -17275,6 +17294,9 @@ function getCapabilities() {
17275
17294
  resultFields: ['previewUrl', 'previewReady', 'clientKey', 'appId', 'codeAssetId', 'minisCenterHistoryId'],
17276
17295
  readiness: 'nonempty-valid-preview-url',
17277
17296
  qrPurpose: 'game_preview',
17297
+ toolQrPurpose: 'tool_preview',
17298
+ pageQrSource: 'preview-url',
17299
+ retainsBindingQr: true,
17278
17300
  sameTask: true,
17279
17301
  timeout: 'shared-operation-timeout',
17280
17302
  failurePreservesUploaded: true,
@@ -18038,6 +18060,7 @@ withVerboseOption(program
18038
18060
  .option('--serve-preview-page', t('cli.command.upload.servePreviewPage'))
18039
18061
  .option('--no-open', t('cli.command.upload.noOpen'))
18040
18062
  .option('--vibe', t('cli.command.upload.vibe'))
18063
+ .option('--minis-type <type>', t('cli.command.upload.minisType'))
18041
18064
  .addOption(new commander.Option('--web', t('cli.command.upload.vibeWeb')).hideHelp())
18042
18065
  // Vibe v2 backend selection (including opt-in ppe-mock) stays outside the Skill workflow.
18043
18066
  .option('--title <title>', t('cli.command.upload.vibeTitle'))
@@ -18064,6 +18087,7 @@ withVerboseOption(program
18064
18087
  }
18065
18088
  if ([
18066
18089
  cmd.title,
18090
+ cmd.minisType,
18067
18091
  cmd.description,
18068
18092
  cmd.icon,
18069
18093
  cmd.appInfo,
@@ -18708,7 +18732,10 @@ function taskId(value) {
18708
18732
  return value;
18709
18733
  }
18710
18734
  function status(value) {
18711
- if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 8)
18735
+ // IDL status 9 waits for code review submission; preview may already be ready.
18736
+ // Keep polling it just like other non-failure states and use preview_url to
18737
+ // determine preview readiness, rather than treating review as a prerequisite.
18738
+ if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 9)
18712
18739
  throw new VibeError('VIBE_INVALID_RESPONSE');
18713
18740
  return Number(value);
18714
18741
  }
@@ -18770,6 +18797,7 @@ function createBackend(mode, transport) {
18770
18797
  signal,
18771
18798
  });
18772
18799
  if (!nonempty(data.import_token) ||
18800
+ !nonempty(data.landing_url) ||
18773
18801
  !Number.isFinite(data.poll_interval_seconds) ||
18774
18802
  data.poll_interval_seconds <= 0 ||
18775
18803
  data.poll_interval_seconds > 3600)
@@ -18777,7 +18805,7 @@ function createBackend(mode, transport) {
18777
18805
  return {
18778
18806
  taskId: taskId(data.task_id),
18779
18807
  importToken: data.import_token,
18780
- landingUrl: safeWebUrl(data.landing_url),
18808
+ landingUrl: data.landing_url,
18781
18809
  pollIntervalSeconds: data.poll_interval_seconds,
18782
18810
  };
18783
18811
  },
@@ -18819,7 +18847,7 @@ function createBackend(mode, transport) {
18819
18847
  path: MINIS_IMPORT_PATHS.info,
18820
18848
  data: {
18821
18849
  ...credentials(task),
18822
- app_info: { ...(appInfo || VIBE_PPE_DEFAULT_APP_INFO), app_name: title, icon_uri: iconUri },
18850
+ app_info: { ...Object.fromEntries(Object.entries(appInfo || VIBE_PPE_DEFAULT_APP_INFO).filter(([, value]) => value !== '')), app_name: title, icon_uri: iconUri },
18823
18851
  },
18824
18852
  signal,
18825
18853
  });
@@ -19039,7 +19067,7 @@ function createMockBackend(scenario = 'success') {
19039
19067
  if (path === MINIS_IMPORT_PATHS.create) {
19040
19068
  if (created ||
19041
19069
  data.source_type !== 1 ||
19042
- data.minis_type !== 'MINI_GAME' ||
19070
+ !['MINI_GAME', 'MINI_TOOL'].includes(data.minis_type) ||
19043
19071
  !nonempty(data.source_project_id) ||
19044
19072
  !nonempty(data.task_idempotency_id))
19045
19073
  throw new VibeError('VIBE_INVALID_RESPONSE');
@@ -19108,7 +19136,7 @@ function createMockBackend(scenario = 'success') {
19108
19136
  function createAuthorizationScheme(landingUrl) {
19109
19137
  // QR and browser authorization use the same backend-provided landing URL.
19110
19138
  // Preserve its query exactly; do not wrap it in an app scheme or re-encode it.
19111
- return safeWebUrl(landingUrl);
19139
+ return landingUrl;
19112
19140
  }
19113
19141
 
19114
19142
  const DEV_PORT = 3000;
@@ -19343,9 +19371,19 @@ function readFile(file, limit, code) {
19343
19371
  }
19344
19372
  async function prepareVibeInput(options, onPackaging, signal, deps = { check: executeCheck, zip: zipCwdToBuffer }) {
19345
19373
  const title = options.title?.trim();
19374
+ const minisType = resolveMinisType(options.minisType);
19346
19375
  if (!title)
19347
19376
  throw new VibeError('VIBE_TITLE_REQUIRED');
19348
- const appInfo = applyVibeCategory(options, applyVibeDescription(options.description, readVibeAppInfo(options.appInfo)));
19377
+ if (minisType === 'MINI_TOOL' && (options.appInfo || options.category || options.subcategory))
19378
+ throw new VibeError('VIBE_TOOL_TRIAL_METADATA');
19379
+ const appInfo = minisType === 'MINI_TOOL'
19380
+ ? applyVibeDescription(options.description, {
19381
+ description: 'A simple productivity tool for everyday tasks.',
19382
+ category: 'EFFICIENCY_AND_OFFICE', subcategory: '',
19383
+ terms_of_service: 'https://www.tiktok.com', privacy_policy: 'https://www.tiktok.com',
19384
+ copyright_confirmation: true, region: 'US', min_sdk_version: '1.0.0',
19385
+ })
19386
+ : applyVibeCategory(options, applyVibeDescription(options.description, readVibeAppInfo(options.appInfo)));
19349
19387
  if (options.package && options.dir)
19350
19388
  throw new VibeError('VIBE_INPUT_CONFLICT');
19351
19389
  const image = readFile(options.icon, VIBE_ICON_LIMIT, 'VIBE_INVALID_ICON');
@@ -19379,6 +19417,7 @@ async function prepareVibeInput(options, onPackaging, signal, deps = { check: ex
19379
19417
  if (signal.aborted)
19380
19418
  throw new VibeError('VIBE_CANCELLED');
19381
19419
  const input = {
19420
+ minisType,
19382
19421
  title,
19383
19422
  ...(appInfo ? { appInfo } : {}),
19384
19423
  icon: {
@@ -19398,33 +19437,294 @@ const vibePageStyles = `
19398
19437
  :root{font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#24282f;background:#fff;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased}
19399
19438
  *{box-sizing:border-box}
19400
19439
  body{margin:0;min-height:100vh;min-height:100svh;display:flex;align-items:center;justify-content:center;padding:64px 24px;font-size:14px;line-height:1.5}
19401
- .shell{position:relative;width:100%;max-width:400px}
19402
- .steps{display:flex;align-items:center;justify-content:center;gap:10px;margin:0 0 24px;padding:0;list-style:none}
19440
+ .shell{position:relative;width:480px;max-width:100%}
19441
+ .steps{display:flex;align-items:center;justify-content:center;gap:10px;margin:24px 0 20px;padding:0;list-style:none}
19403
19442
  .step{display:flex;align-items:center;gap:6px;font-size:11px;color:#9298a2;white-space:nowrap}
19404
19443
  .step:after{content:"";height:1px;width:25px;margin-left:4px;background:#e9ebef}.step:last-child:after{display:none}
19405
19444
  .step-number{height:18px;min-width:18px;border-radius:50%;border:1px solid #e2e5e9;display:grid;place-items:center;font-size:10px}
19406
- .step.active{color:#272c34;font-weight:600}.step.active .step-number{background:#272c34;color:#fff;border-color:#272c34}
19407
- .step.done{color:#537565}.step.done .step-number{background:#edf6f0;color:#287c54;border-color:#edf6f0}
19408
- .heading{text-align:center}h1{font-size:26px;font-weight:650;line-height:1.35;letter-spacing:-.6px;margin:0 0 10px}
19409
- .subtitle{color:#7a818c;font-size:12px;line-height:1.7;margin:0;overflow-wrap:anywhere}
19410
- .game{margin:24px 0 0;padding-top:20px;border-top:1px solid #eceef1;text-align:center}
19411
- .game-summary{display:flex;align-items:center;justify-content:center;gap:12px}.game-title{max-width:100%;margin:0;font-size:15px;font-weight:600;overflow-wrap:anywhere;min-width:0}
19445
+ .step.active{color:#272c34;font-weight:600}.step.active .step-number{background:none;color:#272c34;border-color:transparent}
19446
+ .step.done{color:#7a818c}.step.done .step-number{background:#a3e635;color:#24282f;border-color:#a3e635}
19447
+ .swirl{display:block;width:18px;height:18px;border-radius:50%;background:conic-gradient(transparent 0 .1turn,currentColor 1turn);-webkit-mask:radial-gradient(farthest-side,#0000 calc(100% - 2.5px),#000 0);mask:radial-gradient(farthest-side,#0000 calc(100% - 2.5px),#000 0);animation:swirl-spin .9s linear infinite}
19448
+ @keyframes swirl-spin{to{transform:rotate(1turn)}}
19449
+ .heading{text-align:center}h1{font-size:20px;font-weight:600;line-height:1.6;letter-spacing:-.3px;margin:0 0 12px}
19450
+ .subtitle{color:#7a818c;font-size:14px;line-height:1.6;margin:0;min-height:22px;overflow-wrap:anywhere}
19451
+ .preview-loading{width:min(240px,100%);height:4px;margin:18px auto 0;border-radius:4px;overflow:hidden;background:#eceef1}
19452
+ .preview-loading span{display:block;width:40%;height:100%;border-radius:inherit;background:#858c96;animation:preview-loading-slide 1.8s ease-in-out infinite}
19453
+ @keyframes preview-loading-slide{from{transform:translateX(-100%)}to{transform:translateX(250%)}}
19454
+ @media(prefers-reduced-motion:reduce){.preview-loading span{animation:none;transform:translateX(75%)}}
19455
+ .game{display:grid;grid-template-columns:44px minmax(0,1fr);column-gap:14px;align-items:start;margin:24px 22px 0;padding:16px 18px;border-radius:16px;background:#f7f8fa;text-align:left}
19456
+ .game-summary{display:contents}.game-title{grid-column:2;max-width:100%;margin:0;font-size:15px;font-weight:600;overflow-wrap:anywhere;min-width:0}
19412
19457
  .game-icon,.game-avatar{width:44px;height:44px;border-radius:10px;flex-shrink:0;background:#f0f2f5}.game-avatar{object-fit:cover}.game-icon{display:grid;place-items:center;color:#707b8b}
19413
- .game-details{margin:16px 0 0;font-size:13px}.game-details>div:first-child,.game-categories>div{display:flex;align-items:baseline;justify-content:center;gap:8px}.game-details dt{flex-shrink:0;font-size:11px;color:#9298a2;margin:0}.game-details dd{min-width:0;margin:0;text-align:left;overflow-wrap:anywhere}
19414
- .game-description{white-space:pre-wrap;line-height:1.65}.game-categories{display:grid;grid-template-columns:1fr;gap:16px;margin-top:16px}
19415
- .scan-action{text-align:center;font-size:13px;font-weight:500;margin:26px 0 10px}.qr-area{display:flex;justify-content:center}.qr-frame{padding:8px;width:208px;height:208px}.qr-frame img{display:block;width:192px;height:192px;max-width:100%}
19458
+ .game-icon,.game-avatar{grid-column:1;grid-row:1 / 3;align-self:center}
19459
+ .game-details{grid-column:2;margin:4px 0 0;font-size:12px;color:#7a818c}.game-details>div:first-child,.game-categories>div{display:flex;align-items:baseline;gap:6px}.game-details dt{flex-shrink:0;font-size:11px;color:#9298a2;margin:0}.game-details dd{min-width:0;margin:0;text-align:left;overflow-wrap:anywhere}
19460
+ .game-description{white-space:pre-wrap;line-height:1.65}.game-categories{display:flex;flex-wrap:wrap;gap:6px 16px;margin-top:6px}
19461
+ /* 32px preserves at least four quiet modules even for a 21-module QR at 160px. */
19462
+ .scan-action{text-align:center;font-size:13px;font-weight:500;margin:26px 0 10px}.qr-area{display:flex;justify-content:center}.qr-frame{padding:32px;width:224px;height:224px;background:#fff}.qr-frame img{display:block;width:160px;height:160px;max-width:100%}
19463
+ .game+.qr-area{margin-top:20px}.scan-hint{text-align:center;font-size:11px;color:#7a818c;line-height:1.7;margin:8px 0 0;min-height:19px}
19464
+ .qr-area{flex-wrap:wrap;gap:20px;min-height:288px;align-content:flex-start}.qr-code{margin:0;width:224px;text-align:center}.qr-code figcaption{font-size:13px;font-weight:600;margin-top:4px;min-height:60px}.qr-code figcaption span{display:block;font-size:11px;font-weight:400;color:#7a818c;margin-top:4px;min-height:35px}
19465
+ .snake{display:grid;grid-template-columns:repeat(var(--cells),var(--module));color:#24282f;width:160px;height:160px}
19466
+ .snake i{width:var(--module);height:var(--module)}.snake i.lit,.snake i.on{background:currentColor}.snake i.fresh{animation:snake-settle .5s ease-out}.snake i.apple{background:#a3e635;animation:snake-apple 1.2s ease-in-out infinite}
19467
+ @keyframes snake-settle{from{background:#a3e635}to{background:currentColor}}@keyframes snake-apple{50%{opacity:.4}}
19468
+ @media(prefers-reduced-motion:reduce){.swirl,.snake i.fresh,.snake i.apple{animation:none}}
19416
19469
  .upload-area{display:flex;align-items:center;flex-direction:column;gap:16px;padding-top:26px}.percentage{font-size:34px;line-height:1;font-variant-numeric:tabular-nums;font-weight:550}.percentage span{font-size:16px;color:#858e9d;padding-left:3px}
19417
19470
  .progress-wrap{width:100%}progress{display:block;width:100%;height:4px;border:none;border-radius:20px;overflow:hidden;background:#edf0f4;accent-color:#4c6378}progress::-webkit-progress-bar{background:#edf0f4;border-radius:20px}progress::-webkit-progress-value{background:#4c6378;border-radius:20px}progress::-moz-progress-bar{background:#4c6378;border-radius:20px}.transfer-label{text-align:center;font-size:11px;color:#8b939f;margin:8px 0 0}
19418
19471
  .footer{text-align:center;font-size:10px;line-height:1.7;color:#a0a5ae;margin:24px 0 0}.footer .dot{display:inline-block;height:5px;width:5px;border-radius:50%;background:#c1995e;vertical-align:middle;margin-right:5px}.mock-badge{width:fit-content;margin:0 0 10px auto;font-size:10px;padding:2px 7px;border:1px solid #dfe2e7;border-radius:5px;color:#707783}
19419
- @media(max-width:380px){body{padding-left:20px;padding-right:20px}.steps{gap:7px}.step:after{width:16px;margin-left:1px}h1{font-size:24px}}
19472
+ @media(max-width:380px){body{padding-left:20px;padding-right:20px}.steps{gap:7px}.step:after{width:16px;margin-left:1px}}
19473
+ @media(max-width:520px){.game{margin-left:0;margin-right:0}.scan-hint{min-height:38px}}
19420
19474
  `;
19421
19475
 
19476
+ // Adapted from tiktok-minis-skills publish_tool.js at 132cd91.
19477
+ // Decorative waiting animation only; real preview QRs always use previewUrl.
19478
+ const qrPreviewLoader = `(() => {
19479
+ const neighbours = (p, w) => {
19480
+ const row = (p / w) | 0, col = p % w, out = [];
19481
+ if (row > 0) out.push(p - w);
19482
+ if (row < w - 1) out.push(p + w);
19483
+ if (col > 0) out.push(p - 1);
19484
+ if (col < w - 1) out.push(p + 1);
19485
+ return out;
19486
+ };
19487
+
19488
+ /** First step of a shortest path from 'from' to 'to', body cells excluded. */
19489
+ function stepToward(from, to, blocked, w) {
19490
+ if (from === to) return from;
19491
+ const prev = new Map([[from, from]]);
19492
+ let front = [from];
19493
+ while (front.length) {
19494
+ const next = [];
19495
+ for (const cell of front)
19496
+ for (const nb of neighbours(cell, w)) {
19497
+ if (prev.has(nb) || (blocked.has(nb) && nb !== to)) continue;
19498
+ prev.set(nb, cell);
19499
+ if (nb === to) {
19500
+ let node = nb;
19501
+ while (prev.get(node) !== from) node = prev.get(node);
19502
+ return node;
19503
+ }
19504
+ next.push(nb);
19505
+ }
19506
+ front = next;
19507
+ }
19508
+ return -1;
19509
+ }
19510
+
19511
+ /** Nearest still-unlit module, by plain grid distance from the head. */
19512
+ function nearestTarget(head, pending, w) {
19513
+ const hr = (head / w) | 0, hc = head % w;
19514
+ let best = -1, bestD = Infinity;
19515
+ for (const cell of pending) {
19516
+ const d = Math.abs(((cell / w) | 0) - hr) + Math.abs((cell % w) - hc);
19517
+ if (d < bestD) { bestD = d; best = cell; }
19518
+ }
19519
+ return best;
19520
+ }
19521
+
19522
+ function play(matrix, w, maxLength) {
19523
+ const pending = new Set();
19524
+ for (let i = 0; i < w * w; i++) if (matrix[i]) pending.add(i);
19525
+
19526
+ // The snake starts on a dark module, and only moving lights one, so the
19527
+ // starting square has to be lit here or the finished code is a module
19528
+ // short -- a hole the error correction hides rather than a code that is
19529
+ // actually right.
19530
+ const start = [...pending][0];
19531
+ pending.delete(start);
19532
+ const snake = [start];
19533
+ const body = new Set(snake);
19534
+ const lit = new Set([start]);
19535
+ const frames = [];
19536
+ let budget = w * w * 6;
19537
+
19538
+ while (pending.size && --budget > 0) {
19539
+ const head = snake[snake.length - 1];
19540
+ const target = nearestTarget(head, pending, w);
19541
+ if (target < 0) break;
19542
+ const move = stepToward(head, target, body, w);
19543
+ if (move < 0) break;
19544
+
19545
+ snake.push(move);
19546
+ body.add(move);
19547
+ while (snake.length > maxLength) body.delete(snake.shift());
19548
+ if (matrix[move]) { lit.add(move); pending.delete(move); }
19549
+
19550
+ frames.push({ snake: [...snake], lit: [...lit], apple: target });
19551
+ }
19552
+ return frames;
19553
+ }
19554
+
19555
+ function mount(host) {
19556
+ if (host.dataset.mounted) return;
19557
+ host.dataset.mounted = '1';
19558
+ const matrix = JSON.parse(host.dataset.matrix);
19559
+ const w = Number(host.dataset.size);
19560
+ const SPEED = Number(host.dataset.speed) || 20; // ms a step
19561
+ host.style.setProperty('--cells', w);
19562
+ host.replaceChildren(...Array.from({ length: w * w }, () => document.createElement('i')));
19563
+ const dots = Array.from(host.children);
19564
+
19565
+ const frames = play(matrix, w, 14);
19566
+ const last = frames.length - 1;
19567
+ if (last < 1) return;
19568
+ const all = frames[last].lit;
19569
+
19570
+ // A lap stops short of the last modules and fades, rather than holding a
19571
+ // finished code that would read as the preview having arrived.
19572
+ const DRAW = Math.round(0.95 * last);
19573
+ const FADE = 20;
19574
+ const lap = DRAW + FADE;
19575
+ // Below this a lap is too unfinished for a sprint to be worth watching.
19576
+ const SPRINTABLE = 0.6;
19577
+
19578
+ // One clock for the whole wait. <main> is replaced as the upload advances,
19579
+ // so a board may be a later stand-in for an earlier one; it has to carry
19580
+ // on from where that one stopped instead of starting the code over.
19581
+ window.__snakeStart = window.__snakeStart || Date.now();
19582
+
19583
+ let sprint = null;
19584
+
19585
+ /**
19586
+ * Only the cells that changed. Repainting all 841 every frame meant ~2500
19587
+ * class writes 50 times a second to move a 14-cell snake; this touches
19588
+ * about 30. The lit list only ever grows within a pass, so the new
19589
+ * modules are its tail, and the body and the apple are small.
19590
+ *
19591
+ * The settle flag is off while the snake is only wandering: the flash
19592
+ * means a module was just revealed, and nothing is revealed then.
19593
+ */
19594
+ const litSet = new Set();
19595
+ let litCount = 0;
19596
+ let prevBody = [];
19597
+ let prevApple = -1;
19598
+
19599
+ const cell = (k, className, opacity) => {
19600
+ const dot = dots[k];
19601
+ if (dot.className !== className) dot.className = className;
19602
+ if (dot.style.opacity !== opacity) dot.style.opacity = opacity;
19603
+ };
19604
+ const restingClass = (k) => (litSet.has(k) ? 'lit' : '');
19605
+
19606
+ const paint = ({ snake, lit, apple }, settle = true) => {
19607
+ if (lit.length < litCount) { // a fresh pass: start from an empty board
19608
+ litSet.clear(); litCount = 0; prevBody = []; prevApple = -1;
19609
+ for (const dot of dots) { dot.className = ''; dot.style.opacity = ''; }
19610
+ }
19611
+ // Paint every new module here rather than relying on the body to
19612
+ // uncover it: frames are skipped whenever the board moves faster than
19613
+ // one step a tick -- the sprint skips dozens -- and a module the body
19614
+ // never sat on would otherwise stay dark in a finished code.
19615
+ for (let i = litCount; i < lit.length; i++) { litSet.add(lit[i]); cell(lit[i], 'lit', ''); }
19616
+ litCount = lit.length;
19617
+
19618
+ // The module the snake lit is under its head; it shows when the tail
19619
+ // clears it, so the flash belongs to the cell the body just left.
19620
+ for (const k of prevBody)
19621
+ if (!snake.includes(k))
19622
+ cell(k, litSet.has(k) && settle ? 'lit fresh' : restingClass(k), '');
19623
+
19624
+ const length = snake.length;
19625
+ snake.forEach((k, i) => cell(k, 'on', String(0.2 + 0.55 * ((i + 1) / length))));
19626
+ prevBody = snake;
19627
+
19628
+ if (prevApple !== apple) {
19629
+ if (prevApple >= 0 && !snake.includes(prevApple))
19630
+ cell(prevApple, restingClass(prevApple), '');
19631
+ if (apple >= 0) cell(apple, 'apple', '');
19632
+ prevApple = apple;
19633
+ }
19634
+ };
19635
+
19636
+ const step = () => Math.floor((Date.now() - window.__snakeStart) / SPEED) % lap;
19637
+ /** How far into its draw this lap is, 0 to 1. */
19638
+ const lapProgress = () => Math.min(1, step() / DRAW);
19639
+
19640
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
19641
+ paint(frames[Math.floor(DRAW / 3)], false);
19642
+ host.finish = () => Promise.resolve();
19643
+ return;
19644
+ }
19645
+
19646
+ const timer = setInterval(() => {
19647
+ // The page swaps <main> as the upload advances; stop with the old board.
19648
+ if (!host.isConnected) { clearInterval(timer); return; }
19649
+ if (sprint) {
19650
+ const k = Math.min(1, (Date.now() - sprint.at) / sprint.ms);
19651
+ const p = sprint.from + (1 - sprint.from) * k;
19652
+ if (p >= 1) {
19653
+ paint({ snake: [], lit: all, apple: -1 });
19654
+ clearInterval(timer);
19655
+ sprint.done();
19656
+ return;
19657
+ }
19658
+ paint(frames[Math.round(p * last)]);
19659
+ return;
19660
+ }
19661
+ const at = step();
19662
+ if (at > DRAW) { // fading out before the next lap
19663
+ host.style.opacity = String(1 - (at - DRAW) / FADE);
19664
+ return;
19665
+ }
19666
+ if (host.style.opacity) host.style.opacity = '';
19667
+ paint(frames[at]);
19668
+ }, SPEED);
19669
+
19670
+ host.finish = () => {
19671
+ if (sprint) return Promise.resolve();
19672
+ const from = lapProgress();
19673
+ if (from < SPRINTABLE) return Promise.resolve();
19674
+ host.style.opacity = '';
19675
+ sprint = { from, at: Date.now(), ms: 300 + 500 * (1 - from), done: () => {} };
19676
+ return new Promise((resolve) => { sprint.done = resolve; });
19677
+ };
19678
+ }
19679
+
19680
+ const boards = () => [...document.querySelectorAll('.snake')];
19681
+ const start = () => boards().forEach(mount);
19682
+ window.__mountSnakes = start;
19683
+ window.__snakeFinish = () => Promise.all(boards().map((b) => b.finish?.()));
19684
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
19685
+ else start();
19686
+ })();`;
19687
+
19422
19688
  const VIBE_PAGE_WORKER = '__vibe-page-server';
19423
19689
  // Includes the base64 form of the locally validated image (up to 10 MiB).
19424
19690
  const VIBE_PAGE_HTML_LIMIT = 16 * 1024 * 1024;
19425
19691
  const pageUpdates = `(() => {
19426
19692
  let etag;
19427
19693
  const terminal = () => ['complete', 'preview', 'failed'].includes(document.querySelector('main')?.dataset.phase);
19694
+ const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
19695
+ async function replace(current, updated) {
19696
+ const animate = current.dataset.phase !== updated.dataset.phase && current.animate &&
19697
+ !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
19698
+ const height = current.getBoundingClientRect().height;
19699
+ if (animate) await current.animate([{opacity: 1}, {opacity: 0}], {duration: 140, fill: 'forwards'}).finished.catch(() => {});
19700
+ current.replaceWith(updated);
19701
+ window.__mountSnakes?.();
19702
+ if (animate) await updated.animate([
19703
+ {opacity: 0, height: height + 'px', overflow: 'hidden'},
19704
+ {opacity: 1, height: updated.getBoundingClientRect().height + 'px', overflow: 'hidden'}
19705
+ ], {duration: 280, easing: 'ease-out'}).finished.catch(() => {});
19706
+ }
19707
+ async function show(updated) {
19708
+ let current = document.querySelector('main');
19709
+ if (!current || current.dataset.rev === updated.dataset.rev) return;
19710
+ if (updated.dataset.phase === 'preview' && current.querySelector('.snake'))
19711
+ await window.__snakeFinish?.();
19712
+ if (updated.dataset.uploaded === 'true' && current.dataset.uploaded !== 'true') {
19713
+ // Show the upload receipt before either the binding or ready preview QR,
19714
+ // even when polling skips intermediate upload states.
19715
+ const success = updated.cloneNode(true);
19716
+ success.dataset.phase = 'upload_success';
19717
+ delete success.dataset.uploaded;
19718
+ const heading = success.querySelector('.heading');
19719
+ success.querySelector('h1').textContent = heading.dataset.uploadTitle;
19720
+ success.querySelector('.subtitle').textContent = heading.dataset.uploadSubtitle;
19721
+ success.querySelectorAll('.qr-area, .scan-action, .scan-hint, .preview-loading').forEach(node => node.remove());
19722
+ await replace(current, success);
19723
+ current = success;
19724
+ await delay(1200);
19725
+ }
19726
+ await replace(current, updated);
19727
+ }
19428
19728
  async function refresh() {
19429
19729
  if (terminal()) return;
19430
19730
  try {
@@ -19432,9 +19732,10 @@ const pageUpdates = `(() => {
19432
19732
  if (response.ok) {
19433
19733
  etag = response.headers.get('etag');
19434
19734
  const next = new DOMParser().parseFromString(await response.text(), 'text/html');
19435
- const current = document.querySelector('main'), updated = next.querySelector('main');
19436
- if (current && updated && current.outerHTML !== updated.outerHTML) current.replaceWith(updated);
19735
+ const updated = next.querySelector('main');
19736
+ if (updated) await show(updated);
19437
19737
  document.title = next.title;
19738
+ document.documentElement.lang = next.documentElement.lang;
19438
19739
  }
19439
19740
  } catch { /* Keep the current page readable during a temporary connection failure. */ }
19440
19741
  if (!terminal()) setTimeout(refresh, 2000);
@@ -19444,12 +19745,20 @@ const pageUpdates = `(() => {
19444
19745
  const escape = (s) => s.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
19445
19746
  async function renderVibePage(input) {
19446
19747
  const zh = input.language !== 'en-US';
19748
+ const message = input.localizedMessages?.[zh ? 'zh-CN' : 'en-US'] ?? input.message;
19749
+ const tool = input.minisType === 'MINI_TOOL';
19447
19750
  const phase = input.phase ||
19448
19751
  (input.purpose === 'authorization_binding' ? 'binding' : 'uploading');
19752
+ const uploadedBinding = !input.simulation && input.purpose === 'authorization_binding' &&
19753
+ (phase === 'waiting_preview' || phase === 'preview' || phase === 'complete');
19754
+ const preview = !input.simulation && phase === 'preview' &&
19755
+ (input.purpose === 'game_preview' || input.purpose === 'tool_preview');
19756
+ const uploaded = uploadedBinding || preview;
19449
19757
  const copy = zh
19450
19758
  ? {
19451
- steps: ['扫码授权', '上传游戏', '完成'],
19759
+ steps: ['扫码授权', '上传游戏', '预览'],
19452
19760
  mock: input.hybrid ? 'PPE + Mock' : '模拟',
19761
+ game: '当前游戏',
19453
19762
  gameIcon: '游戏头像',
19454
19763
  bindingTitle: '上传到 TikTok',
19455
19764
  bindingAction: input.hybrid ? '真实授权二维码 · 混合联调' : '使用 TikTok 扫描二维码',
@@ -19462,6 +19771,7 @@ async function renderVibePage(input) {
19462
19771
  uploadingTitle: '正在上传小游戏',
19463
19772
  uploadingSubtitle: input.simulation ? '正在模拟授权后的上传流程,不会上传游戏内容。' : '授权已完成,正在上传本次游戏内容。',
19464
19773
  uploadLabel: input.simulation ? '模拟上传进度' : '上传进度',
19774
+ uploadStatus: '正在上传游戏,请稍候',
19465
19775
  completeTitle: input.simulation ? '模拟上传完成' : '上传完成',
19466
19776
  completeSubtitle: input.simulation
19467
19777
  ? '绑定和上传流程模拟完成,未向 TikTok 上传游戏。'
@@ -19470,11 +19780,11 @@ async function renderVibePage(input) {
19470
19780
  bindingCode: '授权绑定二维码',
19471
19781
  accepted: input.simulation ? '模拟完成' : '已上传',
19472
19782
  mockNote: input.hybrid ? '真实创建 / 查询任务 · 授权 / 上传为模拟 · 不改变真实任务状态' : '模拟运行 · 无需扫码,不会真实上传',
19473
- footer: '临时页面 · 15 分钟后关闭',
19474
19783
  }
19475
19784
  : {
19476
- steps: ['Authorize', 'Upload', 'Done'],
19785
+ steps: ['Scan', 'Upload', 'Preview'],
19477
19786
  mock: input.hybrid ? 'PPE + Mock' : 'MOCK',
19787
+ game: 'YOUR GAME',
19478
19788
  gameIcon: 'Game icon',
19479
19789
  bindingTitle: 'Upload to TikTok',
19480
19790
  bindingAction: input.hybrid ? 'Real authorization QR · integration demo' : 'Scan the QR code with TikTok',
@@ -19491,6 +19801,7 @@ async function renderVibePage(input) {
19491
19801
  uploadLabel: input.simulation
19492
19802
  ? 'Simulated upload progress'
19493
19803
  : 'Upload progress',
19804
+ uploadStatus: 'Uploading your game. Please wait.',
19494
19805
  completeTitle: input.simulation ? 'Simulated upload complete' : 'Upload complete',
19495
19806
  completeSubtitle: input.simulation
19496
19807
  ? 'Binding and upload simulation complete. Nothing was uploaded to TikTok.'
@@ -19499,8 +19810,17 @@ async function renderVibePage(input) {
19499
19810
  bindingCode: 'Authorization QR',
19500
19811
  accepted: input.simulation ? 'Simulation complete' : 'Uploaded',
19501
19812
  mockNote: input.hybrid ? 'Real task creation / polling · Mock authorization / upload · Real task status unchanged' : 'Mock only · no scan needed, nothing is uploaded',
19502
- footer: 'Temporary page · closes after 15 minutes',
19503
19813
  };
19814
+ if (tool) {
19815
+ for (const key of Object.keys(copy)) {
19816
+ const value = copy[key];
19817
+ if (typeof value === 'string')
19818
+ copy[key] = value.replace(/小游戏|游戏/g, '工具').replace(/game/gi, 'tool');
19819
+ }
19820
+ copy.steps[1] = zh ? '上传工具' : 'Upload';
19821
+ }
19822
+ if (input.simulation)
19823
+ copy.steps[2] = zh ? '完成' : 'Done';
19504
19824
  if (input.web) {
19505
19825
  copy.steps[0] = zh ? '网页授权' : 'Web authorization';
19506
19826
  copy.bindingAction = zh ? '在浏览器完成授权绑定' : 'Authorize in your browser';
@@ -19509,70 +19829,106 @@ async function renderVibePage(input) {
19509
19829
  : (zh ? '请在已打开的 TikTok 页面确认授权,当前命令会继续查询绑定状态。' : 'Confirm authorization on the opened TikTok page. The command continues polling.');
19510
19830
  copy.bindingStatus = input.simulation ? (zh ? '模拟等待授权' : 'Simulating authorization') : (zh ? '等待网页授权' : 'Waiting for browser authorization');
19511
19831
  }
19512
- const step = phase === 'binding' ? 0 : phase === 'uploading' ? 1 : 2;
19832
+ const step = phase === 'binding' ? 0 : phase === 'uploading' ? 1 : phase === 'preview' ? 3 : 2;
19513
19833
  // Only embed the chosen raster image; never fetch a URL or expose its local path.
19514
19834
  const icon = input.iconDataUrl &&
19515
19835
  input.iconDataUrl.length <= 14 * 1024 * 1024 &&
19516
19836
  /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+=*$/.test(input.iconDataUrl)
19517
19837
  ? `<img class="game-avatar" width="44" height="44" alt="${copy.gameIcon}" src="${input.iconDataUrl}">`
19518
19838
  : '<span class="game-icon" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M7 7h10c2 0 3 2 3 4l1 5c.4 2-1 3-2.5 2l-3-2h-7l-3 2C4 19 2.6 18 3 16l1-5c0-2 1-4 3-4Z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><path d="M8 10v4m-2-2h4m6-1h.01M18 13h.01" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg></span>';
19519
- const game = `<div class="game"><div class="game-summary">${icon}<p class="game-title">${escape(input.title)}</p></div><dl class="game-details"><div><dt>${zh ? '描述' : 'Description'}</dt><dd class="game-description">${escape(input.description ?? VIBE_PPE_DEFAULT_APP_INFO.description)}</dd></div><div class="game-categories"><div><dt>${zh ? '类型' : 'Category'}</dt><dd>${escape(input.category ?? VIBE_PPE_DEFAULT_APP_INFO.category)}</dd></div><div><dt>${zh ? '子类型' : 'Subcategory'}</dt><dd>${escape(input.subcategory ?? VIBE_PPE_DEFAULT_APP_INFO.subcategory)}</dd></div></div></dl></div>`;
19839
+ const game = `<div class="game"><div class="game-summary">${icon}<p class="game-title">${escape(input.title)}</p></div><dl class="game-details"><div><dt>${zh ? '描述' : 'Description'}</dt><dd class="game-description">${escape(input.description ?? VIBE_PPE_DEFAULT_APP_INFO.description)}</dd></div><div class="game-categories"><div><dt>${zh ? '类型' : 'Category'}</dt><dd>${escape(tool && input.category === 'EFFICIENCY_AND_OFFICE' ? (zh ? '效率办公' : 'Efficiency & Office') : input.category ?? VIBE_PPE_DEFAULT_APP_INFO.category)}</dd></div>${tool ? '' : `<div><dt>${zh ? '子类型' : 'Subcategory'}</dt><dd>${escape(input.subcategory ?? VIBE_PPE_DEFAULT_APP_INFO.subcategory)}</dd></div>`}</div></dl></div>`;
19520
19840
  const checkIcon = '<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="m3 8 3 3 7-7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
19521
- const title = phase === 'waiting_preview' ? (zh ? '正在准备预览' : 'Preparing preview')
19522
- : phase === 'preview' ? (zh ? '扫码预览游戏' : 'Scan to preview')
19523
- : phase === 'binding'
19524
- ? copy.bindingTitle
19525
- : phase === 'uploading'
19526
- ? copy.uploadingTitle
19527
- : phase === 'failed'
19528
- ? copy.failedTitle
19529
- : copy.completeTitle;
19530
- const subtitle = phase === 'waiting_preview' ? (zh ? '游戏内容已上传,预览就绪后会自动显示二维码。' : 'Game content uploaded. The preview QR will appear when ready.')
19531
- : phase === 'preview' ? (zh ? '上传完成,使用手机 TikTok 扫描下方二维码。' : 'Upload complete. Scan the QR below with TikTok on your phone.')
19532
- : phase === 'complete' && !input.simulation ? escape(input.message)
19841
+ const uploadSuccessTitle = zh ? '上传成功' : 'Upload complete';
19842
+ const uploadSuccessSubtitle = zh
19843
+ ? `${tool ? '工具' : '游戏'}内容已上传,正在返回扫码页面。`
19844
+ : `Your ${tool ? 'tool' : 'game'} has been uploaded. Returning to the scan page.`;
19845
+ const title = uploadedBinding ? (phase === 'waiting_preview' ? (zh ? '正在生成预览' : 'Preparing preview') : zh ? '扫码查看进度' : 'Scan to check progress')
19846
+ : phase === 'waiting_preview' ? (zh ? '正在准备预览' : 'Preparing preview')
19847
+ : phase === 'preview' ? (zh ? `扫码预览${tool ? '工具' : '游戏'}` : 'Scan to preview')
19533
19848
  : phase === 'binding'
19534
- ? copy.bindingSubtitle
19849
+ ? copy.bindingTitle
19535
19850
  : phase === 'uploading'
19536
- ? copy.uploadingSubtitle
19851
+ ? copy.uploadingTitle
19537
19852
  : phase === 'failed'
19538
- ? escape(input.message)
19539
- : copy.completeSubtitle;
19540
- const qr = (phase === 'binding' || phase === 'preview') && !input.web && input.qrUrl
19853
+ ? copy.failedTitle
19854
+ : copy.completeTitle;
19855
+ const subtitle = uploadedBinding ? (phase === 'complete' ? escape(message) : phase === 'waiting_preview'
19856
+ ? (zh ? '代码包已上传,正在生成预览。准备好后会自动显示预览二维码。' : 'Package uploaded. Your preview is being prepared; its QR will appear when ready.') : zh
19857
+ ? `本次${tool ? '工具' : '游戏'}代码包已上传完成,再次扫码即可查看预览版本并提交审核。`
19858
+ : `Your ${tool ? 'tool' : 'game'} package has been uploaded. Scan again to view the preview version and submit it for review.`)
19859
+ : phase === 'waiting_preview' ? (zh ? '内容已上传,预览就绪后会自动显示二维码。' : 'Content uploaded. The preview QR will appear when ready.')
19860
+ : phase === 'preview' ? ''
19861
+ : phase === 'complete' && !input.simulation ? escape(message)
19862
+ : phase === 'binding'
19863
+ ? copy.bindingSubtitle
19864
+ : phase === 'uploading'
19865
+ ? copy.uploadingSubtitle
19866
+ : phase === 'failed'
19867
+ ? escape(message)
19868
+ : copy.completeSubtitle;
19869
+ const qr = (phase === 'binding' || phase === 'uploading' || phase === 'preview' || uploadedBinding) && !input.web && input.qrUrl
19541
19870
  ? await QRCode.toDataURL(input.qrUrl, {
19542
19871
  width: 384,
19543
- margin: 4,
19872
+ // Fixed CSS quiet zones keep different QR versions visually equal.
19873
+ margin: 0,
19544
19874
  errorCorrectionLevel: 'M',
19545
19875
  })
19546
19876
  : '';
19547
- const purpose = phase === 'preview' ? (zh ? '游戏预览二维码' : 'Game preview QR') : copy.bindingCode;
19548
- const done = phase === 'complete' || phase === 'preview';
19877
+ const progressCode = zh ? '查看进度二维码' : 'Progress QR';
19878
+ const purpose = preview ? (zh ? `${tool ? '工具' : '游戏'}预览二维码` : `${tool ? 'Tool' : 'Game'} preview QR`) : uploadedBinding || phase === 'uploading' ? (zh ? '应用页面二维码' : 'App page QR') : copy.bindingCode;
19879
+ const bindingQr = preview && !input.web && input.bindingQrUrl && input.bindingQrUrl !== input.qrUrl
19880
+ ? await QRCode.toDataURL(input.bindingQrUrl, { width: 384, margin: 0, errorCorrectionLevel: 'M' }) : '';
19881
+ const done = phase === 'preview' || phase === 'complete' && input.simulation;
19882
+ const active = phase === 'binding' || phase === 'uploading' || phase === 'waiting_preview';
19883
+ const waiting = phase === 'waiting_preview';
19884
+ const matrix = waiting ? QRCode.create('https://www.tiktok.com/minis/').modules : undefined;
19885
+ const pendingQr = matrix ? `<figure class="qr-code qr-pending"><div class="qr-frame" role="img" aria-label="${zh ? '预览正在生成' : 'Preview is being prepared'}"><div class="snake" aria-hidden="true" data-size="${matrix.size}" data-speed="20" data-matrix='${JSON.stringify(Array.from(matrix.data))}' style="--module:${160 / matrix.size}px"></div></div><figcaption>${zh ? '正在生成预览' : 'Preparing preview'}</figcaption></figure>` : '';
19549
19886
  const progress = typeof input.progressPercent === 'number' &&
19550
19887
  Number.isFinite(input.progressPercent)
19551
19888
  ? Math.max(0, Math.min(100, Math.round(input.progressPercent)))
19552
19889
  : undefined;
19890
+ const progressQr = bindingQr ? `<figure class="qr-code"><div class="qr-frame"><img width="160" height="160" alt="${progressCode}" src="${bindingQr}"></div><figcaption>${zh ? '查看进度' : 'Check progress'}<span>${zh ? '查看应用信息并提交审核' : 'View app details and submit for review'}</span></figcaption></figure>` : '';
19891
+ // Keep the original scan entry on the left while the right side becomes a preview.
19553
19892
  const content = qr
19554
- ? `<div class="qr-area"><div class="qr-frame"><img width="192" height="192" alt="${purpose}" src="${qr}"></div></div>`
19893
+ ? `<div class="qr-area">${progressQr}<figure class="qr-code"><div class="qr-frame"><img width="160" height="160" alt="${purpose}" src="${qr}"></div>${preview ? `<figcaption>${zh ? '扫码预览' : 'Preview'}<span>${zh ? '打开本次上传的预览版本' : 'Open the preview of this upload'}</span></figcaption>` : phase === 'binding' ? `<figcaption>${zh ? '扫码授权' : 'Authorize upload'}</figcaption>` : `<figcaption>${zh ? '查看进度' : 'Check progress'}<span>${zh ? '扫码查看应用信息' : 'Scan to view app details'}</span></figcaption>`}</figure>${pendingQr}</div>`
19555
19894
  : phase === 'uploading' && progress !== undefined
19556
19895
  ? `<div class="upload-area"><div class="percentage">${progress}<span>%</span></div><div class="progress-wrap"><progress aria-label="${copy.uploadLabel}" max="100" value="${progress}"></progress><p class="transfer-label">${copy.uploadLabel}</p></div></div>`
19557
19896
  : '';
19897
+ const previewLoading = phase === 'waiting_preview'
19898
+ ? `<div class="preview-loading" role="progressbar" aria-label="${zh ? '正在生成预览' : 'Preparing preview'}"><span aria-hidden="true"></span></div>`
19899
+ : '';
19900
+ const revision = crypto.createHash('sha256').update(JSON.stringify(input)).digest('hex');
19901
+ const steps = phase === 'failed' ? '' : `<ol class="steps" aria-label="${zh ? '上传步骤' : 'Upload steps'}">${copy.steps.map((label, i) => `<li class="step ${done || i < step ? 'done' : active && i === step ? 'active' : ''}"${!done && active && i === step ? ' aria-current="step"' : ''}><span class="step-number">${done || i < step ? checkIcon : active && i === step ? '<span class="swirl" aria-hidden="true"></span>' : i + 1}</span>${label}</li>`).join('')}</ol>`;
19558
19902
  return `<!doctype html><html lang="${zh ? 'zh-CN' : 'en'}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)} · ${escape(input.title)}</title><style>${vibePageStyles}</style><script src="?updates" defer></script></head>
19559
- <body><main class="shell" data-phase="${phase}">${input.simulation ? `<p class="mock-badge">${copy.mock}</p>` : ''}
19560
- <section class="card" aria-labelledby="page-title">${phase === 'failed' ? '' : `<ol class="steps" aria-label="${zh ? '上传步骤' : 'Upload steps'}">${copy.steps.map((label, i) => `<li class="step ${done || i < step ? 'done' : i === step ? 'active' : ''}"${!done && i === step ? ' aria-current="step"' : ''}><span class="step-number">${done || i < step ? checkIcon : i + 1}</span>${label}</li>`).join('')}</ol>`}
19561
- <div class="heading"><h1 id="page-title">${title}</h1><p class="subtitle" role="status">${subtitle}</p></div>${game}${phase === 'binding' ? `<p class="scan-action">${copy.bindingAction}</p>` : ''}${content}
19903
+ <body><main class="shell${bindingQr || pendingQr ? ' dual-qr' : ''}" data-phase="${phase}" data-rev="${revision}"${uploaded ? ' data-uploaded="true"' : ''}>${input.simulation ? `<p class="mock-badge">${copy.mock}</p>` : ''}
19904
+ <section class="card" aria-labelledby="page-title">
19905
+ <div class="heading"${uploaded ? ` data-upload-title="${escape(uploadSuccessTitle)}" data-upload-subtitle="${escape(uploadSuccessSubtitle)}"` : ''}><h1 id="page-title">${title}</h1><p class="subtitle" role="status">${subtitle}</p>${previewLoading}</div>${game}${steps}${phase === 'binding' && (input.web || input.hybrid) ? `<p class="scan-action">${copy.bindingAction}</p>` : ''}${content}<p class="scan-hint">${uploadedBinding ? (zh ? '可扫码查看进度信息,无需重复上传。' : 'Scan to view app details. No need to upload again.') : ''}</p>
19562
19906
  </section>
19563
- <p class="footer">${input.simulation ? `<span class="dot" aria-hidden="true"></span>${copy.mockNote}` : copy.footer}</p></main></body></html>`;
19907
+ ${input.simulation ? `<p class="footer"><span class="dot" aria-hidden="true"></span>${copy.mockNote}</p>` : ''}</main></body></html>`;
19908
+ }
19909
+ // Follow the reader's preferred browser language, as in the Tool skill.
19910
+ function browserPageLanguage(header) {
19911
+ const preferred = (header || '').split(',').map(part => {
19912
+ const [tag, ...parameters] = part.trim().split(';');
19913
+ const quality = parameters.find(value => /^\s*q=/i.test(value));
19914
+ const q = quality ? Number(quality.split('=')[1]) : 1;
19915
+ return { tag: tag.toLowerCase(), q };
19916
+ }).filter(item => item.tag && Number.isFinite(item.q) && item.q > 0 && item.q <= 1)
19917
+ .sort((a, b) => b.q - a.q)[0];
19918
+ return preferred?.tag.split('-')[0] === 'zh' ? 'zh-CN' : 'en-US';
19564
19919
  }
19565
19920
  async function createVibePageServer() {
19566
19921
  const route = `/${crypto.randomBytes(24).toString('hex')}`;
19567
19922
  let html = 'Starting…';
19568
19923
  let etag = '';
19924
+ let variants = {};
19569
19925
  let landingUrl;
19570
19926
  const server = http.createServer((req, res) => {
19571
19927
  const address = server.address();
19572
19928
  const host = address && typeof address !== 'string' ? `127.0.0.1:${address.port}` : '';
19573
19929
  if (req.method === 'GET' && req.url === `${route}?updates` && req.headers.host === host) {
19574
19930
  res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
19575
- res.end(pageUpdates);
19931
+ res.end(qrPreviewLoader + '\n' + pageUpdates);
19576
19932
  return;
19577
19933
  }
19578
19934
  if (req.url === `${route}/authorize` && req.headers.host === host &&
@@ -19595,19 +19951,23 @@ async function createVibePageServer() {
19595
19951
  res.writeHead(404).end();
19596
19952
  return;
19597
19953
  }
19598
- if (etag && req.headers['if-none-match'] === etag) {
19599
- res.writeHead(304, { 'ETag': etag, 'Cache-Control': 'no-store' }).end();
19954
+ const localized = variants[browserPageLanguage(req.headers['accept-language'])];
19955
+ const responseHtml = localized?.html ?? html;
19956
+ const responseEtag = localized?.etag ?? etag;
19957
+ if (responseEtag && req.headers['if-none-match'] === responseEtag) {
19958
+ res.writeHead(304, { 'ETag': responseEtag, 'Cache-Control': 'no-store', 'Vary': 'Accept-Language' }).end();
19600
19959
  return;
19601
19960
  }
19602
19961
  res.writeHead(200, {
19603
- 'ETag': etag,
19962
+ 'ETag': responseEtag,
19963
+ 'Vary': 'Accept-Language',
19604
19964
  'Content-Type': 'text/html; charset=utf-8',
19605
19965
  'Cache-Control': 'no-store',
19606
19966
  'Referrer-Policy': 'no-referrer',
19607
19967
  'X-Content-Type-Options': 'nosniff',
19608
19968
  'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'",
19609
19969
  });
19610
- res.end(html);
19970
+ res.end(responseHtml);
19611
19971
  });
19612
19972
  await new Promise((resolve, reject) => {
19613
19973
  server.once('error', reject);
@@ -19616,9 +19976,15 @@ async function createVibePageServer() {
19616
19976
  const address = server.address();
19617
19977
  return {
19618
19978
  url: `http://127.0.0.1:${address.port}${route}`,
19619
- update: (value, authorization) => {
19979
+ update: (value, authorization, localizedHtml) => {
19620
19980
  html = value;
19621
19981
  etag = '"' + crypto.createHash('sha256').update(value).digest('hex') + '"';
19982
+ variants = {};
19983
+ for (const language of ['zh-CN', 'en-US']) {
19984
+ const localized = localizedHtml?.[language];
19985
+ if (typeof localized === 'string' && localized.length < VIBE_PAGE_HTML_LIMIT)
19986
+ variants[language] = { html: localized, etag: '"' + crypto.createHash('sha256').update(localized).digest('hex') + '"' };
19987
+ }
19622
19988
  landingUrl = browserLandingUrl(authorization);
19623
19989
  },
19624
19990
  close: () => server.close(),
@@ -19631,24 +19997,34 @@ async function runVibePageWorker() {
19631
19997
  }
19632
19998
  const server = await createVibePageServer();
19633
19999
  const requestedTtl = Number(process.env.TTMG_VIBE_PAGE_TTL_MS);
19634
- const ttl = requestedTtl > 0 && requestedTtl <= 900000 ? requestedTtl : 900000;
19635
- const timer = setTimeout(() => {
20000
+ const ttl = requestedTtl > 0 && requestedTtl <= 1800000 ? requestedTtl : 1800000;
20001
+ let timer;
20002
+ let closing = false;
20003
+ const close = () => {
20004
+ closing = true;
20005
+ clearTimeout(timer);
19636
20006
  server.close();
19637
20007
  if (process.connected)
19638
20008
  process.disconnect();
19639
- }, ttl);
20009
+ };
20010
+ // The parent owns the operation deadline. Keep the page alive during polling,
20011
+ // then start its retention window when the parent detaches (or exits).
20012
+ const retain = () => {
20013
+ if (!closing && !timer)
20014
+ timer = setTimeout(close, ttl);
20015
+ };
20016
+ process.once('disconnect', retain);
20017
+ if (!process.connected)
20018
+ retain();
19640
20019
  process.on('message', (message) => {
19641
20020
  if (message?.type === 'render' &&
19642
20021
  typeof message.html === 'string' &&
19643
20022
  message.html.length < VIBE_PAGE_HTML_LIMIT) {
19644
- server.update(message.html, message.browserLandingUrl);
20023
+ server.update(message.html, message.browserLandingUrl, message.localizedHtml);
19645
20024
  process.send?.({ type: 'rendered', id: message.id });
19646
20025
  }
19647
20026
  if (message?.type === 'close') {
19648
- clearTimeout(timer);
19649
- server.close();
19650
- if (process.connected)
19651
- process.disconnect();
20027
+ close();
19652
20028
  }
19653
20029
  });
19654
20030
  process.send({ type: 'ready', url: server.url });
@@ -19686,11 +20062,15 @@ async function startVibePage() {
19686
20062
  return {
19687
20063
  url: ready.url,
19688
20064
  async update(input) {
19689
- const html = await renderVibePage(input);
20065
+ const [zh, en] = await Promise.all([
20066
+ renderVibePage({ ...input, language: 'zh-CN' }),
20067
+ renderVibePage({ ...input, language: 'en-US' }),
20068
+ ]);
20069
+ const html = input.language === 'en-US' ? en : zh;
19690
20070
  const current = ++id;
19691
20071
  const ack = receive(m => m?.type === 'rendered' && m.id === current);
19692
20072
  const landingUrl = input.phase === 'binding' ? browserLandingUrl(input.browserLandingUrl) : undefined;
19693
- child.send({ type: 'render', id: current, html, browserLandingUrl: landingUrl }, error => {
20073
+ child.send({ type: 'render', id: current, html, localizedHtml: { 'zh-CN': zh, 'en-US': en }, browserLandingUrl: landingUrl }, error => {
19694
20074
  if (error)
19695
20075
  child.emit('error', error);
19696
20076
  });
@@ -19714,6 +20094,7 @@ async function startVibePage() {
19714
20094
 
19715
20095
  // Source identity is project metadata, not a Skill input or a credential.
19716
20096
  function getVibeProjectId(options) {
20097
+ const minisType = resolveMinisType(options.minisType);
19717
20098
  const root = path.resolve(options.package ? path.dirname(options.package) : options.dir || '.');
19718
20099
  const dir = path.join(root, '.ttmg');
19719
20100
  const file = path.join(dir, 'vibe-project.json');
@@ -19721,7 +20102,7 @@ function getVibeProjectId(options) {
19721
20102
  fs.mkdirSync(dir, { recursive: true });
19722
20103
  const id = crypto.randomUUID();
19723
20104
  try {
19724
- fs.writeFileSync(file, JSON.stringify({ schemaVersion: '1', sourceProjectId: id }) + '\n', { flag: 'wx', mode: 0o600 });
20105
+ fs.writeFileSync(file, JSON.stringify({ schemaVersion: '1', sourceProjectId: id, minisType }) + '\n', { flag: 'wx', mode: 0o600 });
19725
20106
  }
19726
20107
  catch (error) {
19727
20108
  if (error.code !== 'EEXIST')
@@ -19732,9 +20113,13 @@ function getVibeProjectId(options) {
19732
20113
  typeof saved.sourceProjectId !== 'string' ||
19733
20114
  !/^[a-zA-Z0-9_-]{1,100}$/.test(saved.sourceProjectId))
19734
20115
  throw new Error();
20116
+ if ((saved.minisType || 'MINI_GAME') !== minisType)
20117
+ throw new VibeError('VIBE_PROJECT_TYPE_CONFLICT');
19735
20118
  return saved.sourceProjectId;
19736
20119
  }
19737
- catch {
20120
+ catch (error) {
20121
+ if (error instanceof VibeError)
20122
+ throw error;
19738
20123
  throw new VibeError('VIBE_PROJECT_STATE_FAILED');
19739
20124
  }
19740
20125
  }
@@ -19822,6 +20207,7 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19822
20207
  let page;
19823
20208
  let backend = deps.backend;
19824
20209
  let task;
20210
+ let authorizationUrl;
19825
20211
  let detached = false;
19826
20212
  let progressUpdates = Promise.resolve();
19827
20213
  let ppeLane;
@@ -19875,6 +20261,10 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19875
20261
  try {
19876
20262
  if (options.web)
19877
20263
  throw new VibeError('VIBE_WEB_DISABLED');
20264
+ const minisType = resolveMinisType(options.minisType);
20265
+ result.minisType = minisType;
20266
+ if (minisType === 'MINI_TOOL')
20267
+ result.inputRequirements = VIBE_TOOL_INPUT_REQUIREMENTS;
19878
20268
  // Real QR uploads use the release-owned PPE route.
19879
20269
  // Explicit test backends remain opt-in; real failures never fall back to them.
19880
20270
  if (!options.mock && !options.vibeApi && process.env.TTMG_VIBE_BACKEND) {
@@ -19915,7 +20305,7 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19915
20305
  throw new VibeError('VIBE_BACKEND_OPTION_CONFLICT');
19916
20306
  if (options.pollInterval !== undefined)
19917
20307
  seconds(options.pollInterval, 1);
19918
- const timeoutMs = seconds(options.timeout, 300);
20308
+ const timeoutMs = seconds(options.timeout, 1800);
19919
20309
  timeout = setTimeout(() => {
19920
20310
  timedOut = true;
19921
20311
  controller.abort();
@@ -19950,7 +20340,7 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19950
20340
  category: (input.appInfo || VIBE_PPE_DEFAULT_APP_INFO).category,
19951
20341
  subcategory: (input.appInfo || VIBE_PPE_DEFAULT_APP_INFO).subcategory,
19952
20342
  source: options.category !== undefined ? 'arguments' : options.appInfo !== undefined ? 'app-info' : 'defaults',
19953
- catalogVersion: GAME_CATEGORY_CATALOG_VERSION,
20343
+ catalogVersion: minisType === 'MINI_TOOL' ? 'mini-tool-ppe-trial-2026-09-19' : GAME_CATEGORY_CATALOG_VERSION,
19954
20344
  },
19955
20345
  iconSizeBytes: input.icon.bytes.length,
19956
20346
  packageSizeBytes: input.code.bytes.length,
@@ -19962,6 +20352,7 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19962
20352
  return result;
19963
20353
  const submittedInfo = input.appInfo || VIBE_PPE_DEFAULT_APP_INFO;
19964
20354
  pageMetadata = {
20355
+ minisType,
19965
20356
  iconDataUrl: `data:${input.icon.contentType};base64,${input.icon.bytes.toString('base64')}`,
19966
20357
  description: submittedInfo.description,
19967
20358
  category: submittedInfo.category,
@@ -19982,10 +20373,10 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
19982
20373
  source_type: 1,
19983
20374
  source_project_id: sourceProjectId,
19984
20375
  task_idempotency_id: taskIdempotencyId,
19985
- minis_type: 'MINI_GAME',
20376
+ minis_type: minisType,
19986
20377
  }, controller.signal);
19987
20378
  ensureActive();
19988
- const authorizationUrl = createAuthorizationScheme(task.landingUrl);
20379
+ authorizationUrl = createAuthorizationScheme(task.landingUrl);
19989
20380
  const pollMs = seconds(options.pollInterval, task.pollIntervalSeconds);
19990
20381
  result = {
19991
20382
  ...result,
@@ -20064,6 +20455,8 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20064
20455
  ...pageGame,
20065
20456
  language: getCurrentLanguage(),
20066
20457
  phase: 'uploading',
20458
+ qrUrl: result.simulation ? undefined : authorizationUrl,
20459
+ purpose: result.simulation ? undefined : 'authorization_binding',
20067
20460
  simulation: result.simulation,
20068
20461
  message: text('uploading', result.simulation),
20069
20462
  });
@@ -20102,6 +20495,8 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20102
20495
  ...pageGame,
20103
20496
  language: getCurrentLanguage(),
20104
20497
  phase: 'uploading',
20498
+ qrUrl: result.simulation ? undefined : authorizationUrl,
20499
+ purpose: result.simulation ? undefined : 'authorization_binding',
20105
20500
  simulation: result.simulation,
20106
20501
  message: text('uploading', result.simulation),
20107
20502
  progressPercent: percent(loaded, validTotal),
@@ -20123,8 +20518,9 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20123
20518
  throw progressPageError;
20124
20519
  if (!result.simulation) {
20125
20520
  emit('waiting_preview', { previewReady: false, terminal: false, nextAction: 'wait',
20126
- qrPurpose: undefined, authorizationOpenCommand: undefined });
20521
+ qrPurpose: 'authorization_binding', authorizationOpenCommand: undefined });
20127
20522
  await page.update({ ...pageGame, language: getCurrentLanguage(), phase: 'waiting_preview',
20523
+ qrUrl: authorizationUrl, purpose: 'authorization_binding',
20128
20524
  simulation: false, message: text('waiting_preview') });
20129
20525
  while (true) {
20130
20526
  ensureActive();
@@ -20148,17 +20544,20 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20148
20544
  ...pageGame,
20149
20545
  language: getCurrentLanguage(),
20150
20546
  phase: result.previewReady ? 'preview' : 'complete',
20151
- qrUrl: result.previewUrl,
20152
- purpose: result.previewReady ? 'game_preview' : undefined,
20547
+ qrUrl: result.simulation ? undefined : result.previewUrl || authorizationUrl,
20548
+ bindingQrUrl: result.previewReady ? authorizationUrl : undefined,
20549
+ purpose: result.simulation ? undefined : result.previewReady
20550
+ ? result.minisType === 'MINI_TOOL' ? 'tool_preview' : 'game_preview'
20551
+ : 'authorization_binding',
20153
20552
  simulation: result.simulation,
20154
20553
  message: text('uploaded', result.simulation),
20155
20554
  });
20156
20555
  page.detach();
20157
20556
  detached = true;
20158
20557
  return emit('uploaded', { terminal: true, nextAction: result.previewReady ? 'scan_qr' : 'none',
20159
- qrPurpose: result.previewReady ? 'game_preview' : undefined,
20558
+ qrPurpose: result.previewReady ? result.minisType === 'MINI_TOOL' ? 'tool_preview' : 'game_preview' : undefined,
20160
20559
  ...(result.previewReady ? { message: getCurrentLanguage() === 'zh-CN'
20161
- ? '上传完成,请使用 TikTok 扫码预览游戏。' : 'Upload complete. Scan with TikTok to preview your game.' } : {}) });
20560
+ ? '预览已就绪,请使用 TikTok 扫描预览二维码;也可扫描“查看进度”二维码查看应用信息并提交审核。' : 'Preview ready. Scan the preview QR with TikTok, or scan the progress QR to view app details and submit for review.' } : {}) });
20162
20561
  }
20163
20562
  catch (error) {
20164
20563
  const code = timedOut
@@ -20176,6 +20575,9 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20176
20575
  const messages = {
20177
20576
  VIBE_CATEGORY_PAIR_REQUIRED: ['--category 和 --subcategory 必须同时提供;均不传时保留默认分类。使用 ttmg game categories --format json 查询。', 'Provide --category and --subcategory together, or omit both to keep the default. Query ttmg game categories --format json.'],
20178
20577
  VIBE_INVALID_CATEGORY: ['类型或子类型无效,或两者不匹配。使用 ttmg game categories --format json 查询有效组合。', 'Invalid category/subcategory pair. Query valid values with ttmg game categories --format json.'],
20578
+ VIBE_INVALID_MINIS_TYPE: ['应用类型须为 MINI_GAME 或 MINI_TOOL。', 'Minis type must be MINI_GAME or MINI_TOOL.'],
20579
+ VIBE_TOOL_TRIAL_METADATA: ['本地 Tool 试用固定使用效率办公类、US 和 SDK 1.0.0;暂不接受分类或 app-info 覆盖。', 'The local Tool trial uses Efficiency & Office, US and SDK 1.0.0; category and app-info overrides are not supported yet.'],
20580
+ VIBE_PROJECT_TYPE_CONFLICT: ['该工程已使用其他应用类型,请为新的 Tool 使用独立工程目录。', 'This project has a different Minis type. Use a separate project directory for a new Tool.'],
20179
20581
  VIBE_INVALID_DESCRIPTION: ['描述必须是非空的有效 Unicode 文本;省略 --description 可使用默认描述。', 'Description must be non-empty valid Unicode text; omit --description to use the default.'],
20180
20582
  VIBE_AUTH_DENIED: [
20181
20583
  '已取消授权,本次未上传。',
@@ -20257,7 +20659,7 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20257
20659
  text(status);
20258
20660
  controller.abort();
20259
20661
  await progressUpdates;
20260
- // Remove the binding QR on failure too. Keep a readable terminal result page.
20662
+ // After upload, preserve the original code for checking progress even if preview lookup stops.
20261
20663
  if (page && (code !== 'VIBE_CANCELLED' || result.uploaded)) {
20262
20664
  try {
20263
20665
  await page.update({
@@ -20267,7 +20669,20 @@ async function executeVibeUpload(options, onEvent = () => { }, dependencies = {}
20267
20669
  simulation: result.simulation,
20268
20670
  hybrid: result.backend === 'ppe-mock',
20269
20671
  phase: result.uploaded ? 'complete' : 'failed',
20270
- message,
20672
+ qrUrl: result.uploaded && !result.simulation ? authorizationUrl : undefined,
20673
+ purpose: result.uploaded && !result.simulation ? 'authorization_binding' : undefined,
20674
+ localizedMessages: result.uploaded && !result.simulation ? {
20675
+ 'zh-CN': '代码包已上传,本页已停止等待预览。可扫码查看进度,无需重复上传。',
20676
+ 'en-US': 'Package uploaded. This page has stopped waiting for the preview. Scan to check progress; no need to upload again.',
20677
+ } : {
20678
+ 'zh-CN': messages[code]?.[0] || '本次操作未完成,请检查 CLI 输出。',
20679
+ 'en-US': messages[code]?.[1] || 'This operation did not complete. Check the CLI output.',
20680
+ },
20681
+ message: result.uploaded && !result.simulation
20682
+ ? getCurrentLanguage() === 'zh-CN'
20683
+ ? '代码包已上传,本页已停止等待预览。可扫码查看进度,无需重复上传。'
20684
+ : 'Package uploaded. This page has stopped waiting for the preview. Scan to check progress; no need to upload again.'
20685
+ : message,
20271
20686
  });
20272
20687
  page.detach();
20273
20688
  detached = true;
@@ -20474,6 +20889,9 @@ const store = Store.getInstance({
20474
20889
  nodeHttpPort: DEV_PORT,
20475
20890
  nodeWsPort: DEV_WS_PORT,
20476
20891
  packages: {},
20892
+ remoteCdnResources: undefined,
20893
+ nodeResourceHost: '',
20894
+ previewRemoteResources: undefined,
20477
20895
  isUnderCompiling: false,
20478
20896
  isUnderUploading: false,
20479
20897
  isWaitingForUpload: false,
@@ -20623,6 +21041,139 @@ function formatHostForUrl(host) {
20623
21041
  return net$1.isIPv6(host) ? `[${host}]` : host;
20624
21042
  }
20625
21043
 
21044
+ const DEV_REMOTE_RESOURCE_PATH = '/game/remote-resources';
21045
+ const DEV_REMOTE_RESOURCE_CACHE = '__TTMG_TEMP__/remote-cdn';
21046
+ function isRelativeDirectory(value) {
21047
+ return typeof value === 'string' && value.length > 0 &&
21048
+ !/[\\:\x00-\x1f]/.test(value) &&
21049
+ value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
21050
+ }
21051
+ function readDevRemoteCdnResources(value) {
21052
+ if (value == null)
21053
+ return undefined;
21054
+ const config = value;
21055
+ const source = new URL(config.base_url);
21056
+ if (!['http:', 'https:'].includes(source.protocol) || source.username ||
21057
+ source.password || source.search || source.hash ||
21058
+ !Array.isArray(config.resources) || config.resources.length === 0 ||
21059
+ !config.resources.every(item => item && isRelativeDirectory(item.root) &&
21060
+ isRelativeDirectory(item.output))) {
21061
+ throw new Error('Invalid compiled remote CDN resource declaration.');
21062
+ }
21063
+ return {
21064
+ base_url: config.base_url,
21065
+ resources: config.resources.map(({ root, output }) => ({ root, output })),
21066
+ };
21067
+ }
21068
+ function buildDevRemoteCdnResources(value, localBaseUrl) {
21069
+ const config = readDevRemoteCdnResources(value);
21070
+ if (!config)
21071
+ return undefined;
21072
+ const target = new URL(localBaseUrl || '');
21073
+ if (!['http:', 'https:'].includes(target.protocol) || target.username ||
21074
+ target.password || target.search || target.hash) {
21075
+ throw new Error('Invalid local remote resource service URL.');
21076
+ }
21077
+ return { ...config, platform_cdn_base_url: target.href.replace(/\/+$/, '') + '/' };
21078
+ }
21079
+
21080
+ const VIRTUAL_INTERFACE_PREFIX = /^(lo\d*|utun\d*|tun\d*|tap\d*|ppp\d*|ipsec\d*|wg\d*|tailscale\d*|zerotier\d*|veth|docker|br-|bridge|vmnet|vbox|anpi|awdl|llw|npf)/i;
21081
+ const VIRTUAL_INTERFACE_KEYWORDS = [
21082
+ 'vmware',
21083
+ 'virtual',
21084
+ 'hyper-v',
21085
+ 'vethernet',
21086
+ 'anyconnect',
21087
+ 'teleport',
21088
+ 'npcap',
21089
+ 'hamachi',
21090
+ ];
21091
+ const WIRELESS_INTERFACE = /^(wl|wlan|wlp|wifi|wi-fi|airport)|无线|无线网络连接/i;
21092
+ const WIRED_INTERFACE = /^(en\d+|enp\w+|eno\w+|ens\w+|eth\w+)$|ethernet|\blan\b|以太网|本地连接/i;
21093
+ function isVirtualInterface(name) {
21094
+ const lowerName = name.toLowerCase();
21095
+ return (VIRTUAL_INTERFACE_PREFIX.test(lowerName) ||
21096
+ VIRTUAL_INTERFACE_KEYWORDS.some(keyword => lowerName.includes(keyword)));
21097
+ }
21098
+ function getInterfaceRank(name) {
21099
+ if (WIRELESS_INTERFACE.test(name))
21100
+ return 0;
21101
+ if (WIRED_INTERFACE.test(name))
21102
+ return 1;
21103
+ return 2;
21104
+ }
21105
+ function isPhysicalInterface(name) {
21106
+ return getInterfaceRank(name) < 2;
21107
+ }
21108
+ function isPrivateIPv4(ip) {
21109
+ return (ip.startsWith('10.') ||
21110
+ ip.startsWith('192.168.') ||
21111
+ /^172\.(1[6-9]|2\d|3[01])\./.test(ip));
21112
+ }
21113
+ function isUsableFallbackIPv4(ip) {
21114
+ const parts = ip.split('.').map(Number);
21115
+ if (parts.length !== 4 ||
21116
+ parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {
21117
+ return false;
21118
+ }
21119
+ const [first, second] = parts;
21120
+ return (first !== 0 &&
21121
+ first !== 127 &&
21122
+ first < 224 &&
21123
+ !(first === 169 && second === 254));
21124
+ }
21125
+ function isIPv4Family(family) {
21126
+ return family === 4 || family === 'IPv4';
21127
+ }
21128
+ function selectLocalIPs(nets) {
21129
+ const privateResults = [];
21130
+ const physicalFallbacks = [];
21131
+ for (const [name, addrs] of Object.entries(nets)) {
21132
+ if (!addrs || isVirtualInterface(name) || !isPhysicalInterface(name)) {
21133
+ continue;
21134
+ }
21135
+ for (const net of addrs) {
21136
+ if (!isIPv4Family(net.family) ||
21137
+ net.internal ||
21138
+ !net.address) {
21139
+ continue;
21140
+ }
21141
+ const target = isPrivateIPv4(net.address)
21142
+ ? privateResults
21143
+ : physicalFallbacks;
21144
+ if (isPrivateIPv4(net.address) ||
21145
+ isUsableFallbackIPv4(net.address)) {
21146
+ target.push({ name, address: net.address });
21147
+ }
21148
+ }
21149
+ }
21150
+ const candidates = privateResults.length > 0 ? privateResults : physicalFallbacks;
21151
+ const seen = new Set();
21152
+ return candidates
21153
+ .sort((a, b) => {
21154
+ const rankDiff = getInterfaceRank(a.name) - getInterfaceRank(b.name);
21155
+ return (rankDiff ||
21156
+ a.name.localeCompare(b.name, undefined, { numeric: true }));
21157
+ })
21158
+ .filter(item => {
21159
+ if (seen.has(item.address))
21160
+ return false;
21161
+ seen.add(item.address);
21162
+ return true;
21163
+ })
21164
+ .map(item => item.address);
21165
+ }
21166
+ function getLocalIPs() {
21167
+ return selectLocalIPs(os.networkInterfaces());
21168
+ }
21169
+
21170
+ function getRemoteResourceBaseUrl() {
21171
+ const { nodeResourceHost, nodeHttpPort } = store.getState();
21172
+ const host = nodeResourceHost || getLocalIPs()[0] || '127.0.0.1';
21173
+ const formattedHost = host.includes(':') ? `[${host}]` : host;
21174
+ return `http://${formattedHost}:${nodeHttpPort}${DEV_REMOTE_RESOURCE_PATH}/`;
21175
+ }
21176
+
20626
21177
  function normalizeRuntimeDiscoveryMessage(message, peerAddress) {
20627
21178
  if (!message || typeof message !== 'object')
20628
21179
  return null;
@@ -20785,6 +21336,7 @@ class WsServer {
20785
21336
  }
20786
21337
  if (isSuccess) {
20787
21338
  store.setState({
21339
+ nodeResourceHost: (request.socket.localAddress || '').replace(/^::ffff:/, ''),
20788
21340
  clientHttpPort: port,
20789
21341
  clientHost: host,
20790
21342
  clientWsPort: wsPort,
@@ -20826,6 +21378,7 @@ class WsServer {
20826
21378
  const payload = clientMessage.payload || {};
20827
21379
  const { host, port, wsPort } = payload;
20828
21380
  store.setState({
21381
+ nodeResourceHost: (request.socket.localAddress || '').replace(/^::ffff:/, ''),
20829
21382
  clientHttpPort: port,
20830
21383
  clientHost: host,
20831
21384
  clientWsPort: wsPort,
@@ -20902,10 +21455,15 @@ class WsServer {
20902
21455
  });
20903
21456
  }
20904
21457
  sendUploadStatus(status, payload) {
21458
+ const { remoteCdnResources } = store.getState();
20905
21459
  this.send({
20906
21460
  method: 'uploadStatus',
20907
21461
  status,
20908
- payload,
21462
+ payload: status === 'success' ? {
21463
+ ...payload,
21464
+ remoteCdnResources: remoteCdnResources || null,
21465
+ remoteResourceBaseUrl: remoteCdnResources ? getRemoteResourceBaseUrl() : null,
21466
+ } : payload,
20909
21467
  });
20910
21468
  }
20911
21469
  }
@@ -21006,6 +21564,7 @@ async function compile(context) {
21006
21564
  store.setState({
21007
21565
  isUnderCompiling: false,
21008
21566
  packages,
21567
+ remoteCdnResources: msg.remoteCdnResources,
21009
21568
  });
21010
21569
  /**
21011
21570
  * 编译成功后,需要触发上传
@@ -21482,96 +22041,6 @@ function listen$1() {
21482
22041
  });
21483
22042
  }
21484
22043
 
21485
- const VIRTUAL_INTERFACE_PREFIX = /^(lo\d*|utun\d*|tun\d*|tap\d*|ppp\d*|ipsec\d*|wg\d*|tailscale\d*|zerotier\d*|veth|docker|br-|bridge|vmnet|vbox|anpi|awdl|llw|npf)/i;
21486
- const VIRTUAL_INTERFACE_KEYWORDS = [
21487
- 'vmware',
21488
- 'virtual',
21489
- 'hyper-v',
21490
- 'vethernet',
21491
- 'anyconnect',
21492
- 'teleport',
21493
- 'npcap',
21494
- 'hamachi',
21495
- ];
21496
- const WIRELESS_INTERFACE = /^(wl|wlan|wlp|wifi|wi-fi|airport)|无线|无线网络连接/i;
21497
- const WIRED_INTERFACE = /^(en\d+|enp\w+|eno\w+|ens\w+|eth\w+)$|ethernet|\blan\b|以太网|本地连接/i;
21498
- function isVirtualInterface(name) {
21499
- const lowerName = name.toLowerCase();
21500
- return (VIRTUAL_INTERFACE_PREFIX.test(lowerName) ||
21501
- VIRTUAL_INTERFACE_KEYWORDS.some(keyword => lowerName.includes(keyword)));
21502
- }
21503
- function getInterfaceRank(name) {
21504
- if (WIRELESS_INTERFACE.test(name))
21505
- return 0;
21506
- if (WIRED_INTERFACE.test(name))
21507
- return 1;
21508
- return 2;
21509
- }
21510
- function isPhysicalInterface(name) {
21511
- return getInterfaceRank(name) < 2;
21512
- }
21513
- function isPrivateIPv4(ip) {
21514
- return (ip.startsWith('10.') ||
21515
- ip.startsWith('192.168.') ||
21516
- /^172\.(1[6-9]|2\d|3[01])\./.test(ip));
21517
- }
21518
- function isUsableFallbackIPv4(ip) {
21519
- const parts = ip.split('.').map(Number);
21520
- if (parts.length !== 4 ||
21521
- parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {
21522
- return false;
21523
- }
21524
- const [first, second] = parts;
21525
- return (first !== 0 &&
21526
- first !== 127 &&
21527
- first < 224 &&
21528
- !(first === 169 && second === 254));
21529
- }
21530
- function isIPv4Family(family) {
21531
- return family === 4 || family === 'IPv4';
21532
- }
21533
- function selectLocalIPs(nets) {
21534
- const privateResults = [];
21535
- const physicalFallbacks = [];
21536
- for (const [name, addrs] of Object.entries(nets)) {
21537
- if (!addrs || isVirtualInterface(name) || !isPhysicalInterface(name)) {
21538
- continue;
21539
- }
21540
- for (const net of addrs) {
21541
- if (!isIPv4Family(net.family) ||
21542
- net.internal ||
21543
- !net.address) {
21544
- continue;
21545
- }
21546
- const target = isPrivateIPv4(net.address)
21547
- ? privateResults
21548
- : physicalFallbacks;
21549
- if (isPrivateIPv4(net.address) ||
21550
- isUsableFallbackIPv4(net.address)) {
21551
- target.push({ name, address: net.address });
21552
- }
21553
- }
21554
- }
21555
- const candidates = privateResults.length > 0 ? privateResults : physicalFallbacks;
21556
- const seen = new Set();
21557
- return candidates
21558
- .sort((a, b) => {
21559
- const rankDiff = getInterfaceRank(a.name) - getInterfaceRank(b.name);
21560
- return (rankDiff ||
21561
- a.name.localeCompare(b.name, undefined, { numeric: true }));
21562
- })
21563
- .filter(item => {
21564
- if (seen.has(item.address))
21565
- return false;
21566
- seen.add(item.address);
21567
- return true;
21568
- })
21569
- .map(item => item.address);
21570
- }
21571
- function getLocalIPs() {
21572
- return selectLocalIPs(os.networkInterfaces());
21573
- }
21574
-
21575
22044
  async function init(options = {}) {
21576
22045
  const providedClientKey = options.clientKey?.trim();
21577
22046
  if (providedClientKey) {
@@ -21824,10 +22293,58 @@ async function listen(app, options) {
21824
22293
  }
21825
22294
  // @ts-ignore
21826
22295
  const port = server.address().port;
22296
+ store.setState({ nodeHttpPort: port });
21827
22297
  const url = `http://localhost:${port}?v=${encodeURIComponent(version)}`;
21828
22298
  return { server, port, url, version };
21829
22299
  }
21830
22300
 
22301
+ function isInside(root, target) {
22302
+ const relative = path$1.relative(root, target);
22303
+ return relative !== '' && relative !== '..' &&
22304
+ !relative.startsWith(`..${path$1.sep}`) && !path$1.isAbsolute(relative);
22305
+ }
22306
+ function remoteResourceMiddleware(getResources) {
22307
+ return (req, res) => {
22308
+ res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
22309
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Range');
22310
+ if (req.method === 'OPTIONS') {
22311
+ res.sendStatus(204);
22312
+ return;
22313
+ }
22314
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
22315
+ res.setHeader('Allow', 'GET, HEAD, OPTIONS');
22316
+ res.sendStatus(405);
22317
+ return;
22318
+ }
22319
+ try {
22320
+ const { directory, declaration } = getResources();
22321
+ const relative = decodeURIComponent(req.path).replace(/^\//, '');
22322
+ const parts = relative.split('/');
22323
+ if (!declaration || /[\\\x00-\x1f]/.test(relative) ||
22324
+ parts.some(part => !part || part === '.' || part === '..' || part.startsWith('.')) ||
22325
+ !declaration.resources.some(({ root }) => relative.startsWith(`${root}/`))) {
22326
+ res.sendStatus(404);
22327
+ return;
22328
+ }
22329
+ const base = fs$1.realpathSync(directory);
22330
+ const file = path$1.resolve(base, ...parts);
22331
+ const realFile = fs$1.realpathSync(file);
22332
+ // Do not follow links added after compilation, including directory links.
22333
+ if (!isInside(base, realFile) || realFile !== file || !fs$1.statSync(realFile).isFile()) {
22334
+ res.sendStatus(404);
22335
+ return;
22336
+ }
22337
+ res.sendFile(realFile, { cacheControl: false, dotfiles: 'deny' }, error => {
22338
+ if (error && !res.headersSent)
22339
+ res.sendStatus(error.statusCode || 404);
22340
+ });
22341
+ }
22342
+ catch {
22343
+ res.sendStatus(404);
22344
+ }
22345
+ };
22346
+ }
22347
+
21831
22348
  function setupMiddlewares(app, options) {
21832
22349
  const { publicPath, outputDir } = options;
21833
22350
  app.use(fileUpload());
@@ -21846,6 +22363,13 @@ function setupMiddlewares(app, options) {
21846
22363
  });
21847
22364
  app.use(express.json());
21848
22365
  app.use(express.urlencoded({ extended: true }));
22366
+ app.use(DEV_REMOTE_RESOURCE_PATH, remoteResourceMiddleware(() => {
22367
+ const state = store.getState();
22368
+ return state.previewRemoteResources || {
22369
+ directory: path$1.join(outputDir, DEV_REMOTE_RESOURCE_CACHE),
22370
+ declaration: state.remoteCdnResources,
22371
+ };
22372
+ }));
21849
22373
  app.use('/game/files', express.static(outputDir));
21850
22374
  }
21851
22375
 
@@ -22024,7 +22548,6 @@ function buildCheckPkgsOptions(outputDir) {
22024
22548
  };
22025
22549
  }
22026
22550
 
22027
- const outputDir$2 = getOutputDir();
22028
22551
  const devToolVersion = getDevToolVersion();
22029
22552
  const gameConfigRoute = {
22030
22553
  method: 'get',
@@ -22032,7 +22555,7 @@ const gameConfigRoute = {
22032
22555
  handler: async (req, res) => {
22033
22556
  const [basic, checkResult] = await Promise.all([
22034
22557
  ttmgPack.getPkgs({ entryDir: process.cwd() }),
22035
- ttmgPack.checkPkgs(buildCheckPkgsOptions(store.getState().previewOutputDirectory || outputDir$2), {
22558
+ ttmgPack.checkPkgs(buildCheckPkgsOptions(getOutputDir()), {
22036
22559
  lang: getCurrentLanguage(),
22037
22560
  }),
22038
22561
  ]);
@@ -22055,6 +22578,8 @@ const gameConfigRoute = {
22055
22578
  checkResult,
22056
22579
  lang: localLang,
22057
22580
  nodeStaticBaseUrl: `http://localhost:${store.getState().nodeHttpPort}/game/files`,
22581
+ remoteCdnResources: store.getState().remoteCdnResources || null,
22582
+ remoteResourceBaseUrl: store.getState().remoteCdnResources ? getRemoteResourceBaseUrl() : null,
22058
22583
  },
22059
22584
  });
22060
22585
  },
@@ -22098,12 +22623,12 @@ const gameConfigFillbackRoute = {
22098
22623
  },
22099
22624
  };
22100
22625
 
22101
- const outputDir$1 = getOutputDir();
22626
+ const outputDir = getOutputDir();
22102
22627
  const gameCheckRoute = {
22103
22628
  method: 'get',
22104
22629
  path: '/game/check',
22105
22630
  handler: async (req, res) => {
22106
- const checkResult = await ttmgPack.checkPkgs(buildCheckPkgsOptions(store.getState().previewOutputDirectory || outputDir$1), {
22631
+ const checkResult = await ttmgPack.checkPkgs(buildCheckPkgsOptions(store.getState().previewOutputDirectory || outputDir), {
22107
22632
  lang: getCurrentLanguage(),
22108
22633
  });
22109
22634
  res.send({ code: successCode, data: checkResult });
@@ -22111,6 +22636,51 @@ const gameCheckRoute = {
22111
22636
  };
22112
22637
 
22113
22638
  const changelog = [
22639
+ {
22640
+ title: '0.4.6',
22641
+ target: { iOS: '>=46.0', Android: '>=45.9' },
22642
+ changes: {
22643
+ bugfix: [
22644
+ {
22645
+ desc: {
22646
+ 'zh-CN': '修复已声明 CDN 托管的远程资源仍被计入主包和代码包总大小的问题。',
22647
+ 'en-US': 'Fix declared CDN-hosted resources being counted toward main-package and total code-package size.',
22648
+ },
22649
+ module: 'check',
22650
+ },
22651
+ {
22652
+ desc: {
22653
+ 'zh-CN': '修复调试日志、截图和历史构建被带入代码打包、上传或包体检查的问题。',
22654
+ 'en-US': 'Fix debug logs, screenshots and previous build outputs being included in code packaging, upload or package-size checks.',
22655
+ },
22656
+ module: 'upload',
22657
+ },
22658
+ {
22659
+ desc: {
22660
+ 'zh-CN': '修复缺少 Wasm 分包组件时 CLI 无法启动的问题,项目检查等普通命令不再依赖该组件。',
22661
+ 'en-US': 'Fix CLI startup failing when the Wasm splitting component is unavailable. Ordinary commands such as project checks no longer require it.',
22662
+ },
22663
+ module: 'new',
22664
+ },
22665
+ ],
22666
+ feature: [
22667
+ {
22668
+ desc: {
22669
+ 'zh-CN': '新增项目检查、本地构建、环境诊断和登录态查询的 JSON 输出,便于 AI 工具和自动化脚本调用。',
22670
+ 'en-US': 'Add JSON output for project checks, local builds, environment diagnostics and authentication status for AI tools and automation scripts.',
22671
+ },
22672
+ module: 'new',
22673
+ },
22674
+ {
22675
+ desc: {
22676
+ 'zh-CN': '新增上传预览选项,可在上传后等待平台处理结果,并通过本地预览页扫码打开游戏。',
22677
+ 'en-US': 'Add an upload-preview option to wait for platform processing and open the game by scanning a QR code on the local preview page.',
22678
+ },
22679
+ module: 'upload',
22680
+ },
22681
+ ],
22682
+ },
22683
+ },
22114
22684
  {
22115
22685
  title: '0.4.5',
22116
22686
  target: {
@@ -23270,17 +23840,11 @@ const gameUploadRoute = {
23270
23840
  },
23271
23841
  };
23272
23842
 
23273
- // 历史遗留:`remotePipeline.ts` 里的老远程分包接口 spread 了 `DEV_HEADERS`。
23274
- // 目前全局 PPE 走的是 `libs/api/request.ts` 里的 `CLI_PPE_ENV`,这里保持
23275
- // 相同的值是为了:一旦以后需要按接口粒度覆盖 PPE(例如远程走 PPE、本地
23276
- // 走线上),只需在这里填回 header、两处值天然一致。
23277
23843
  const BASE_URL = 'https://developers.tiktok.com';
23278
23844
  const WASM_COLLECT_BASE_URL = `${BASE_URL}/api/wasm-collect/v1`;
23279
- const DEV_HEADERS = {
23280
- // 'x-use-ppe': '1',
23281
- // 'x-tt-env': UNITY_PPE_ENV,
23282
- // 'x-tt-target-idc': 'sg',
23283
- };
23845
+ // Legacy remote-split calls retain this extension point. Shared request()
23846
+ // handles the explicit TTMG_PPE_ENV setting for all platform APIs.
23847
+ const DEV_HEADERS = {};
23284
23848
  const TTMG_TEMP_DIR = '__TTMG_TEMP__';
23285
23849
  const WASM_SPLIT_CACHE_DIR = `${TTMG_TEMP_DIR}/wasmcode/`;
23286
23850
  const WASM_SYMBOL_FILE_NAME = 'webgl.symbols.json';
@@ -26268,15 +26832,16 @@ function registerRoutes(app, options) {
26268
26832
  }
26269
26833
  }
26270
26834
 
26271
- const outputDir = getOutputDir();
26272
26835
  const publicPath = path.join(__dirname, 'public');
26273
26836
  async function start(options = {}) {
26274
26837
  const startTime = Date.now();
26838
+ // Resolve after init has selected the current Client Key, not at module load.
26839
+ const outputDir = options.outputDirectory || getOutputDir();
26275
26840
  const app = express();
26276
26841
  // Before the IDE fallback and permissive game-resource CORS middleware.
26277
26842
  if (options.scanPageHandler)
26278
26843
  app.use(options.scanPageHandler);
26279
- setupMiddlewares(app, { publicPath, outputDir: options.outputDirectory || outputDir });
26844
+ setupMiddlewares(app, { publicPath, outputDir });
26280
26845
  registerRoutes(app, { publicPath });
26281
26846
  const result = await listen(app, {
26282
26847
  maxRetries: 20,
@@ -27404,6 +27969,7 @@ function assertDevRuntimePackages(value) {
27404
27969
  }
27405
27970
  function buildDevMeta(options) {
27406
27971
  assertDevRuntimePackages(options.packages);
27972
+ const remoteResources = buildDevRemoteCdnResources(options.remoteCdnResources, options.remoteResourceBaseUrl);
27407
27973
  const { scopes, update_time, display_icon_url, request_allowed_domains, name, terms_of_service_link, privacy_policy_link, description, } = options.gameDetail || DEBUG_META_DATA;
27408
27974
  return {
27409
27975
  ...DEBUG_META_DATA,
@@ -27414,8 +27980,13 @@ function buildDevMeta(options) {
27414
27980
  icon_big_url: display_icon_url || DEBUG_META_DATA.icon_url,
27415
27981
  client_key: options.clientKey,
27416
27982
  minis_url: `https://minis-${options.clientKey}-vdebug-minigame.tiktok-minis.us/`,
27417
- package_config: JSON.stringify({ packages: options.packages }),
27418
- allowed_domains: request_allowed_domains || [],
27983
+ package_config: JSON.stringify({
27984
+ packages: options.packages,
27985
+ ...(remoteResources ? { remote_cdn_resources: remoteResources } : {}),
27986
+ }),
27987
+ allowed_domains: remoteResources
27988
+ ? [...new Set([...(request_allowed_domains || []), new URL(remoteResources.platform_cdn_base_url).origin])]
27989
+ : request_allowed_domains || [],
27419
27990
  status_code: 0,
27420
27991
  status_msg: '',
27421
27992
  update_time,
@@ -27454,7 +28025,11 @@ function capturePreviewBuild(sourceDirectory = getOutputDir(), packages = store.
27454
28025
  recursive: true,
27455
28026
  dereference: true,
27456
28027
  });
27457
- return { directory, packages: metadata, dispose };
28028
+ const configPath = path$1.join(directory, 'packageConfig.json');
28029
+ const remoteCdnResources = fs$1.existsSync(configPath)
28030
+ ? readDevRemoteCdnResources(JSON.parse(fs$1.readFileSync(configPath, 'utf8')).remote_cdn_resources)
28031
+ : undefined;
28032
+ return { directory, packages: metadata, remoteCdnResources, dispose };
27458
28033
  }
27459
28034
  catch {
27460
28035
  dispose();
@@ -27497,6 +28072,7 @@ class ClientPreviewOrchestrator {
27497
28072
  this.settingsDelivery = 'pending';
27498
28073
  this.settingsRevision = 0;
27499
28074
  this.latestBuild = null;
28075
+ this.resourceBuild = null;
27500
28076
  this.activeDeployment = null;
27501
28077
  this.pendingDeployment = null;
27502
28078
  this.deployment = null;
@@ -27597,7 +28173,7 @@ class ClientPreviewOrchestrator {
27597
28173
  this.deploymentFailure = null;
27598
28174
  const previous = this.latestBuild;
27599
28175
  this.latestBuild = build;
27600
- if (previous && previous !== this.activeDeployment?.build)
28176
+ if (previous && previous !== this.activeDeployment?.build && previous !== this.resourceBuild)
27601
28177
  previous.dispose();
27602
28178
  // Retain successful compiles before scan and during connection setup too.
27603
28179
  if (!this.initialized)
@@ -27690,7 +28266,7 @@ class ClientPreviewOrchestrator {
27690
28266
  }
27691
28267
  finally {
27692
28268
  clearTimeout(deadline);
27693
- if (request.build !== this.latestBuild)
28269
+ if (request.build !== this.latestBuild && request.build !== this.resourceBuild)
27694
28270
  request.build.dispose();
27695
28271
  this.activeDeployment = null;
27696
28272
  }
@@ -27743,6 +28319,8 @@ class ClientPreviewOrchestrator {
27743
28319
  clientKey: this.options.clientKey,
27744
28320
  packages: build.packages,
27745
28321
  gameDetail: gameInfo,
28322
+ remoteCdnResources: build.remoteCdnResources,
28323
+ remoteResourceBaseUrl: build.remoteCdnResources ? getRemoteResourceBaseUrl() : undefined,
27746
28324
  });
27747
28325
  }
27748
28326
  catch (error) {
@@ -27751,7 +28329,23 @@ class ClientPreviewOrchestrator {
27751
28329
  : 'Compiled package metadata is invalid.');
27752
28330
  }
27753
28331
  store.setState({ appId: gameInfo?.app_id });
27754
- await this.runtime.post('/game/meta', meta, 30000, signal);
28332
+ const previousResources = this.resourceBuild;
28333
+ this.resourceBuild = build.remoteCdnResources ? build : null;
28334
+ store.setState({
28335
+ previewRemoteResources: build.remoteCdnResources ? {
28336
+ directory: path$1.join(build.directory, DEV_REMOTE_RESOURCE_CACHE),
28337
+ declaration: build.remoteCdnResources,
28338
+ } : undefined,
28339
+ });
28340
+ try {
28341
+ await this.runtime.post('/game/meta', meta, 30000, signal);
28342
+ }
28343
+ finally {
28344
+ if (previousResources && previousResources !== build &&
28345
+ previousResources !== this.latestBuild && previousResources !== this.activeDeployment?.build) {
28346
+ previousResources.dispose();
28347
+ }
28348
+ }
27755
28349
  }
27756
28350
  async logsSnapshot(options) {
27757
28351
  return this.runtime.snapshot(options);
@@ -27815,10 +28409,15 @@ class ClientPreviewOrchestrator {
27815
28409
  this.deployment = null;
27816
28410
  this.initialized = false;
27817
28411
  this.cancelPending();
27818
- if (this.latestBuild && this.latestBuild !== this.activeDeployment?.build) {
28412
+ if (this.latestBuild && this.latestBuild !== this.activeDeployment?.build &&
28413
+ this.latestBuild !== this.resourceBuild) {
27819
28414
  this.latestBuild.dispose();
27820
28415
  }
27821
28416
  this.latestBuild = null;
28417
+ if (this.resourceBuild && this.resourceBuild !== this.activeDeployment?.build)
28418
+ this.resourceBuild.dispose();
28419
+ this.resourceBuild = null;
28420
+ store.setState({ previewRemoteResources: undefined });
27822
28421
  this.runtime.close();
27823
28422
  }
27824
28423
  }